From 32f067f5bb625d2f0e9e146e993dfc40a2dc9f1c Mon Sep 17 00:00:00 2001 From: hinotoi-agent Date: Mon, 25 May 2026 19:51:54 +0800 Subject: [PATCH 01/11] fix(cli): preserve caller context after approval --- src/cli/dispatch.test.ts | 76 ++++++++++++++++++++++++++++++++++++++-- src/cli/dispatch.ts | 40 ++++++++++++++++++--- 2 files changed, 109 insertions(+), 7 deletions(-) diff --git a/src/cli/dispatch.test.ts b/src/cli/dispatch.test.ts index 20ff18707..6a9c58506 100644 --- a/src/cli/dispatch.test.ts +++ b/src/cli/dispatch.test.ts @@ -2,6 +2,32 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; // --- Mocks --- +const approvalState = vi.hoisted(() => ({ + requestApproval: vi.fn(), + approvalHandler: null as + | null + | ((args: { + session: unknown; + payload: Record; + userId: string; + notify: (text: string) => void; + }) => Promise), + registerApprovalHandler: vi.fn( + ( + action: string, + handler: (args: { + session: unknown; + payload: Record; + userId: string; + notify: (text: string) => void; + }) => Promise, + ) => { + if (action === 'cli_command') approvalState.approvalHandler = handler; + }, + ), + observedContexts: [] as CallerContext[], +})); + vi.mock('../log.js', () => ({ log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, })); @@ -29,8 +55,8 @@ vi.mock('./crud.js', () => ({ })); vi.mock('../modules/approvals/index.js', () => ({ - registerApprovalHandler: vi.fn(), - requestApproval: vi.fn(), + registerApprovalHandler: approvalState.registerApprovalHandler, + requestApproval: approvalState.requestApproval, })); // Register a test command so dispatch has something to find @@ -98,6 +124,18 @@ register({ handler: async (args) => ({ echo: args }), }); +register({ + name: 'approval-context-command', + description: 'approval command that records caller context', + resource: 'groups', + access: 'approval', + parseArgs: (raw) => raw, + handler: async (_args, ctx) => { + approvalState.observedContexts.push(ctx); + return { caller: ctx.caller }; + }, +}); + // Commands that return data shaped like real resources (for post-handler filtering tests) register({ name: 'groups-list-data', @@ -152,6 +190,7 @@ import type { CallerContext } from './frame.js'; beforeEach(() => { vi.clearAllMocks(); + approvalState.observedContexts.length = 0; // Default: the four CLI-whitelisted resources with their real scopeFields. const scopeFields: Record = { groups: 'id', @@ -391,6 +430,39 @@ describe('CLI scope enforcement', () => { expect(mockGetContainerConfig).not.toHaveBeenCalled(); }); + it('approval replay preserves the original agent caller context', async () => { + mockGetContainerConfig.mockReturnValue({ cli_scope: 'group' }); + mockGetSession.mockReturnValue({ id: 's1', agent_group_id: 'g1', messaging_group_id: 'mg1' }); + mockGetAgentGroup.mockReturnValue({ id: 'g1', name: 'Group One' }); + + const ctx = agentCtx(); + const resp = await dispatch({ id: '1', command: 'approval-context-command', args: {} }, ctx); + + expect(resp.ok).toBe(false); + expect(approvalState.requestApproval).toHaveBeenCalledTimes(1); + + const approval = approvalState.requestApproval.mock.calls[0][0] as { payload: Record }; + expect(approval.payload).toEqual({ + frame: { + id: '1', + command: 'approval-context-command', + args: { agent_group_id: 'g1', group: 'g1', id: 'g1' }, + }, + callerContext: ctx, + }); + + expect(approvalState.approvalHandler).toBeTypeOf('function'); + await approvalState.approvalHandler!({ + session: { id: 's1', agent_group_id: 'g1', messaging_group_id: 'mg1' }, + payload: approval.payload, + userId: 'telegram:admin', + notify: vi.fn(), + }); + + expect(approvalState.observedContexts).toEqual([ctx]); + expect(approvalState.requestApproval).toHaveBeenCalledTimes(1); + }); + // --- Post-handler filtering --- it('group: groups list filters out other groups', async () => { diff --git a/src/cli/dispatch.ts b/src/cli/dispatch.ts index 7878a9b57..c35365272 100644 --- a/src/cli/dispatch.ts +++ b/src/cli/dispatch.ts @@ -14,7 +14,16 @@ import type { CallerContext, ErrorCode, RequestFrame, ResponseFrame } from './fr import { getResource } from './crud.js'; import { lookup } from './registry.js'; -export async function dispatch(req: RequestFrame, ctx: CallerContext): Promise { +type DispatchOptions = { + /** True when a command is being replayed after approval. */ + approved?: boolean; +}; + +export async function dispatch( + req: RequestFrame, + ctx: CallerContext, + opts: DispatchOptions = {}, +): Promise { let cmd = lookup(req.command); // Fallback: if the full command isn't registered, trim the last @@ -101,7 +110,7 @@ export async function dispatch(req: RequestFrame, ctx: CallerContext): Promise { +registerApprovalHandler('cli_command', async ({ payload, notify }) => { const frame = payload.frame as RequestFrame; - const response = await dispatch(frame, { caller: 'host' }); + const callerContext = parseCallerContext(payload.callerContext) ?? { caller: 'host' }; + const response = await dispatch(frame, callerContext, { approved: true }); if (response.ok) { const data = typeof response.data === 'string' ? response.data : JSON.stringify(response.data, null, 2); @@ -190,6 +200,26 @@ registerApprovalHandler('cli_command', async ({ session, payload, userId, notify } }); +function parseCallerContext(value: unknown): CallerContext | undefined { + if (!value || typeof value !== 'object') return undefined; + const record = value as Record; + if (record.caller === 'host') return { caller: 'host' }; + if ( + record.caller === 'agent' && + typeof record.sessionId === 'string' && + typeof record.agentGroupId === 'string' && + typeof record.messagingGroupId === 'string' + ) { + return { + caller: 'agent', + sessionId: record.sessionId, + agentGroupId: record.agentGroupId, + messagingGroupId: record.messagingGroupId, + }; + } + return undefined; +} + function err(id: string, code: ErrorCode, message: string): ResponseFrame { return { id, ok: false, error: { code, message } }; } From a00a5610bd69747363df067b9d7d695a38775da8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 4 Jul 2026 08:08:50 +0000 Subject: [PATCH 02/11] chore: bump version to 2.1.25 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ce57347d6..6d2212918 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nanoclaw", - "version": "2.1.24", + "version": "2.1.25", "description": "Personal Claude assistant. Lightweight, secure, customizable.", "type": "module", "packageManager": "pnpm@10.33.0", From b28c917997b2d8b9ff32b00060490acb02560e07 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 4 Jul 2026 08:08:52 +0000 Subject: [PATCH 03/11] =?UTF-8?q?docs:=20update=20token=20count=20to=20207?= =?UTF-8?q?k=20tokens=20=C2=B7=20104%=20of=20context=20window?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- repo-tokens/badge.svg | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/repo-tokens/badge.svg b/repo-tokens/badge.svg index 24e2f6d4e..408a4a09a 100644 --- a/repo-tokens/badge.svg +++ b/repo-tokens/badge.svg @@ -1,5 +1,5 @@ - - 204k tokens, 102% of context window + + 207k tokens, 104% of context window @@ -15,8 +15,8 @@ tokens - - 204k + + 207k From 3731e2676968eb4eed3af0e953631ee51927ba7a Mon Sep 17 00:00:00 2001 From: gavrielc Date: Sat, 4 Jul 2026 16:04:08 +0300 Subject: [PATCH 04/11] feat(approvals): render OneCLI approval requests from the gateway's structured summary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The hosted OneCLI gateway (api.onecli.sh) sends a structured summary field on ApprovalRequest — { action, details: [{label, value}] } — that the SDK's TypeScript type doesn't declare yet. When present, render it as the approval card body (*Action:* plus labeled fields, fencing multi-line values) instead of the raw METHOD host/path + bodyPreview, so approvers see what the agent is doing (e.g. To / Subject / Body of an email send) rather than an HTTP trace. Rendering is defensive: non-string values are coerced via JSON.stringify (a render throw would turn into a deny via handleRequest's catch), each value is capped at 900 chars, and a 2600-char running budget keeps the card under Slack's 3000-char section block limit — overflow is reported with an explicit "…N field(s) omitted for length" line instead of a failed delivery. Without a summary, the old bodyPreview fallback remains, now capped and with the method/host/path as a footnote. Co-Authored-By: Claude Fable 5 --- src/modules/approvals/onecli-approvals.ts | 48 ++++++++++++++++++----- 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/src/modules/approvals/onecli-approvals.ts b/src/modules/approvals/onecli-approvals.ts index eec05c0b4..3ee357a05 100644 --- a/src/modules/approvals/onecli-approvals.ts +++ b/src/modules/approvals/onecli-approvals.ts @@ -254,16 +254,46 @@ async function sweepStaleApprovals(): Promise { } } +/** The hosted gateway's structured request summary — not yet in the SDK's + * ApprovalRequest type (observed on api.onecli.sh, 2026-07): the action being + * performed plus labeled fields (To / Subject / Body for email sends). */ +interface ApprovalSummary { + action?: string; + details?: { label: string; value: string }[]; +} + +const SUMMARY_VALUE_EXCERPT_CHARS = 900; + function buildQuestion(request: ApprovalRequest, agentName: string): string { - const lines = [ - 'Credential access request', - `Agent: ${agentName}`, - '```', - `${request.method} ${request.host}${request.path}`, - '```', - ]; - if (request.bodyPreview) { - lines.push('Body:', '```', request.bodyPreview, '```'); + const lines = [`*Agent:* ${agentName}`]; + + const summary = (request as ApprovalRequest & { summary?: ApprovalSummary }).summary; + if (summary?.details?.length) { + if (summary.action) lines.push(`*Action:* ${summary.action}`); + // A render bug here must never decide the request: handleRequest's catch + // returns 'deny', so stay defensive — coerce non-string values instead of + // assuming the gateway's shape, and keep the card under Slack's 3000-char + // section limit or delivery itself fails. + let budget = 2600; + for (const { label, value } of summary.details) { + const raw = typeof value === 'string' ? value : (JSON.stringify(value) ?? String(value)); + const cap = Math.min(SUMMARY_VALUE_EXCERPT_CHARS, Math.max(0, budget)); + if (cap === 0) { + lines.push(`_…${summary.details.length} field(s) omitted for length — see the audit payload._`); + break; + } + const v = raw.length > cap ? `${raw.slice(0, cap)}…` : raw; + budget -= v.length + String(label).length + 8; + // Multi-line values (message bodies) read better fenced; short labeled + // fields (To, Subject) inline. + if (v.includes('\n')) lines.push(`*${label}:*`, '```', v, '```'); + else lines.push(`*${label}:* ${v}`); + } + } else if (request.bodyPreview) { + lines.push('```', request.bodyPreview.slice(0, SUMMARY_VALUE_EXCERPT_CHARS * 2), '```'); + lines.push(`_${request.method} ${request.host}${request.path}_`); + } else { + lines.push(`_${request.method} ${request.host}${request.path}_`); } return lines.join('\n'); } From c9aa69dea9d54bbb55ac71548415854ea796bf42 Mon Sep 17 00:00:00 2001 From: gavrielc Date: Sat, 4 Jul 2026 16:04:09 +0300 Subject: [PATCH 05/11] Unregister the mock provider from the production container barrel The container self-registration barrel imported mock.js, so every container registered a 'mock' provider returning canned text. A typo'd --provider mock would silently 'work' instead of failing loudly. Drop the import (mock.ts stays for direct test use) and tidy the now-stale host comments and docs. Co-Authored-By: Claude Opus 4.8 --- container/agent-runner/src/providers/index.ts | 1 - docs/architecture-diagram.md | 2 +- src/providers/index.ts | 2 +- src/providers/provider-container-registry.ts | 2 +- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/container/agent-runner/src/providers/index.ts b/container/agent-runner/src/providers/index.ts index 70497cf32..ec47b3d40 100644 --- a/container/agent-runner/src/providers/index.ts +++ b/container/agent-runner/src/providers/index.ts @@ -3,4 +3,3 @@ // level. Skills add a new provider by appending one import line below. import './claude.js'; -import './mock.js'; diff --git a/docs/architecture-diagram.md b/docs/architecture-diagram.md index 4d8671cc2..f3d36df61 100644 --- a/docs/architecture-diagram.md +++ b/docs/architecture-diagram.md @@ -31,7 +31,7 @@ flowchart TB subgraph Session["Per-Session Container (Docker / Apple Container)"] direction TB PollLoop["Poll Loop
(container/agent-runner)"] - Provider["Agent providers
(claude, opencode, mock; todo: codex)"] + Provider["Agent providers
(claude, opencode; todo: codex)"] MCP["MCP Tools
send_message, send_file, edit_message,
add_reaction, send_card, ask_user_question,
schedule_task, create_agent,
install_packages, add_mcp_server"] Skills["Container Skills
(container/skills/)"] InDB[("inbound.db
host writes
even seq
messages_in
destinations
processing_ack")] diff --git a/src/providers/index.ts b/src/providers/index.ts index 3ec95126b..9060a6b48 100644 --- a/src/providers/index.ts +++ b/src/providers/index.ts @@ -1,6 +1,6 @@ // Host-side provider container-config barrel. // Providers that need host-side container setup (extra mounts, env passthrough, // per-session directories) self-register on import. Providers with no host -// needs (claude, mock) don't appear here. +// needs (claude) don't appear here. // // Skills add a new provider by appending one import line below. diff --git a/src/providers/provider-container-registry.ts b/src/providers/provider-container-registry.ts index 9ff661ca2..b82ae3c8c 100644 --- a/src/providers/provider-container-registry.ts +++ b/src/providers/provider-container-registry.ts @@ -7,7 +7,7 @@ * the registered config fn, and merges the returned mounts/env into the spawn * args. * - * Providers without host-side needs (e.g. `claude`, `mock`) don't appear in + * Providers without host-side needs (e.g. `claude`) don't appear in * this registry at all — the lookup returns `undefined` and the spawn path * proceeds with only the default mounts and env. * From f4be00e6ed6f6cbc154a5a50dbfff552999b7d8c Mon Sep 17 00:00:00 2001 From: gavrielc Date: Sat, 4 Jul 2026 16:04:14 +0300 Subject: [PATCH 06/11] Remove dead /workspace/global mount and untrack v1 group seed files Co-Authored-By: Claude Opus 4.8 --- groups/global/CLAUDE.md | 166 --------------------- groups/main/CLAUDE.md | 312 ---------------------------------------- src/container-runner.ts | 6 - 3 files changed, 484 deletions(-) delete mode 100644 groups/global/CLAUDE.md delete mode 100644 groups/main/CLAUDE.md diff --git a/groups/global/CLAUDE.md b/groups/global/CLAUDE.md deleted file mode 100644 index c4428fff4..000000000 --- a/groups/global/CLAUDE.md +++ /dev/null @@ -1,166 +0,0 @@ -# Main - -You are Main, a personal assistant. You help with tasks, answer questions, and can schedule reminders. - -## What You Can Do - -- Answer questions and have conversations -- Search the web and fetch content from URLs -- **Browse the web** with `agent-browser` — open pages, click, fill forms, take screenshots, extract data (run `agent-browser open ` to start, then `agent-browser snapshot -i` to see interactive elements) -- Read and write files in your workspace -- Run bash commands in your sandbox -- Schedule tasks to run later or on a recurring basis -- Send messages back to the chat - -## Communication - -Be concise — every message costs the reader's attention. - -### Destinations - -Each turn, your system prompt lists the destinations available to you. If you only have one destination, just write your response directly — it goes there automatically. If you have multiple, wrap each message in a `...` block: - -``` -On my way home, 15 minutes -kick off the pipeline -``` - -Inbound messages are labeled with `from="name"` so you can tell which destination they came from and reply using that same name. - -### Mid-turn updates - -Use the `mcp__nanoclaw__send_message` tool to send a message mid-work (before your final output). If you have one destination, `to` is optional; with multiple, specify it. Pace your updates to the length of the work: - -- **Short work (a few seconds, ≤2 quick tool calls):** Don't narrate. Just do it and put the result in your final response. -- **Longer work (many tool calls, web searches, installs, sub-agents):** Send a short acknowledgment right away ("On it — checking the logs now") so the user knows you got the message. -- **Long-running work (many minutes, multi-step tasks):** Send periodic updates at natural milestones, and especially **before** slow operations like spinning up an explore sub-agent, downloading large files, or installing packages. - -**Never narrate micro-steps.** "I'm going to read the file now… okay, I'm reading it… now I'm parsing it…" is noise. Updates should mark meaningful transitions, not every tool call. - -**Outcomes, not play-by-play.** When the work is done, the final message should be about the result, not a transcript of what you did. - -### Internal thoughts - -Wrap reasoning in `...` tags to mark it as scratchpad — logged but not sent. With multiple destinations, any text outside of `` blocks is also treated as scratchpad. With a single destination, only explicit `` tags are scratchpad; the rest of your response is sent. - -``` -Compiled all three reports, ready to summarize. - -Here are the key findings from the research… -``` - -### Sub-agents and teammates - -When working as a sub-agent or teammate, only use `send_message` if instructed to by the main agent. - -## Your Workspace - -Files you create are saved in `/workspace/group/`. Use this for notes, research, or anything that should persist. - -## Memory - -The `conversations/` folder contains searchable history of past conversations. Use this to recall context from previous sessions. - -When you learn something important: -- Create files for structured data (e.g., `customers.md`, `preferences.md`) -- Split files larger than 500 lines into folders -- Keep an index in your memory for the files you create - -## Message Formatting - -Format messages based on the channel you're responding to. Check your group folder name: - -### Slack channels (folder starts with `slack_`) - -Use Slack mrkdwn syntax. Run `/slack-formatting` for the full reference. Key rules: -- `*bold*` (single asterisks) -- `_italic_` (underscores) -- `` for links (NOT `[text](url)`) -- `•` bullets (no numbered lists) -- `:emoji:` shortcodes -- `>` for block quotes -- No `##` headings — use `*Bold text*` instead - -### WhatsApp/Telegram channels (folder starts with `whatsapp_` or `telegram_`) - -- `*bold*` (single asterisks, NEVER **double**) -- `_italic_` (underscores) -- `•` bullet points -- ` ``` ` code blocks - -No `##` headings. No `[links](url)`. No `**double stars**`. - -### Discord channels (folder starts with `discord_`) - -Standard Markdown works: `**bold**`, `*italic*`, `[links](url)`, `# headings`. - ---- - -## Installing Packages & Tools - -Your container is ephemeral — anything installed via `apt-get` or `pnpm install -g` is lost on restart. To install packages that persist, use the self-modification tools: - -1. **`install_packages`** — request system (apt) or global npm packages. Requires admin approval. -2. **`request_rebuild`** — rebuild your container image so approved packages are baked in. Always call this after `install_packages` to apply the changes. - -Example flow: -``` -install_packages({ apt: ["ffmpeg"], npm: ["@xenova/transformers"], reason: "Audio transcription" }) -# → Admin gets an approval card → approves -request_rebuild({ reason: "Apply ffmpeg + transformers" }) -# → Admin approves → image rebuilt with the packages -``` - -**When to use this vs workspace pnpm install:** -- `pnpm install` in `/workspace/agent/` persists on disk (it's mounted) but isn't on the global PATH — use it for project-level dependencies -- `install_packages` is for system tools (ffmpeg, imagemagick) and global npm packages that need to be on PATH - -### MCP Servers - -Use **`add_mcp_server`** to add an MCP server to your configuration, then **`request_rebuild`** to apply. Browse available servers at https://mcp.so — it's a curated directory of high-quality MCP servers. Most Node.js servers run via `pnpm dlx`, e.g.: - -``` -add_mcp_server({ name: "memory", command: "pnpm", args: ["dlx", "@modelcontextprotocol/server-memory"] }) -request_rebuild({ reason: "Add memory MCP server" }) -``` - -## Task Scripts - -For any recurring task, use `schedule_task`. This is the scheduling path — tasks persist across sessions and restarts, and support the pre-task `script` hook described below. Other scheduling tools you might discover (e.g. `CronCreate`, `ScheduleWakeup`) are session-scoped SDK builtins and won't behave the way NanoClaw users expect, so stick with `schedule_task`. - -To inspect or change existing tasks, use `list_tasks` (returns one row per series with the stable id) and `update_task` / `cancel_task` / `pause_task` / `resume_task`. Prefer `update_task` over cancel + reschedule — it preserves the series id the user already knows. - -Frequent agent invocations — especially multiple times a day — consume API credits and can risk account restrictions. If a simple check can determine whether action is needed, add a `script` — it runs first, and the agent is only called when the check passes. This keeps invocations to a minimum. - -### How it works - -1. You provide a bash `script` alongside the `prompt` when scheduling -2. When the task fires, the script runs first (30-second timeout) -3. Script prints JSON to stdout: `{ "wakeAgent": true/false, "data": {...} }` -4. If `wakeAgent: false` — nothing happens, task waits for next run -5. If `wakeAgent: true` — you wake up and receive the script's data + prompt - -### Always test your script first - -Before scheduling, run the script in your sandbox to verify it works: - -```bash -bash -c 'node --input-type=module -e " - const r = await fetch(\"https://api.github.com/repos/owner/repo/pulls?state=open\"); - const prs = await r.json(); - console.log(JSON.stringify({ wakeAgent: prs.length > 0, data: prs.slice(0, 5) })); -"' -``` - -### When NOT to use scripts - -If a task requires your judgment every time (daily briefings, reminders, reports), skip the script — just use a regular prompt. - -### Frequent task guidance - -If a user wants tasks running more than ~2x daily and a script can't reduce agent wake-ups: - -- Explain that each wake-up uses API credits and risks rate limits -- Suggest restructuring with a script that checks the condition first -- If the user needs an LLM to evaluate data, suggest using an API key with direct Anthropic API calls inside the script -- Help the user find the minimum viable frequency diff --git a/groups/main/CLAUDE.md b/groups/main/CLAUDE.md deleted file mode 100644 index 011a906aa..000000000 --- a/groups/main/CLAUDE.md +++ /dev/null @@ -1,312 +0,0 @@ -@./.claude-global.md -# Main - -You are Main, a personal assistant. You help with tasks, answer questions, and can schedule reminders. - -## What You Can Do - -- Answer questions and have conversations -- Search the web and fetch content from URLs -- **Browse the web** with `agent-browser` — open pages, click, fill forms, take screenshots, extract data (run `agent-browser open ` to start, then `agent-browser snapshot -i` to see interactive elements) -- Read and write files in your workspace -- Run bash commands in your sandbox -- Schedule tasks to run later or on a recurring basis -- Send messages back to the chat - -## Communication - -Your output is sent to the user or group. - -You also have `mcp__nanoclaw__send_message` which sends a message immediately while you're still working. This is useful when you want to acknowledge a request before starting longer work. - -### Internal thoughts - -If part of your output is internal reasoning rather than something for the user, wrap it in `` tags: - -``` -Compiled all three reports, ready to summarize. - -Here are the key findings from the research... -``` - -Text inside `` tags is logged but not sent to the user. If you've already sent the key information via `send_message`, you can wrap the recap in `` to avoid sending it again. - -### Sub-agents and teammates - -When working as a sub-agent or teammate, only use `send_message` if instructed to by the main agent. - -## Memory - -The `conversations/` folder contains searchable history of past conversations. Use this to recall context from previous sessions. - -When you learn something important: -- Create files for structured data (e.g., `customers.md`, `preferences.md`) -- Split files larger than 500 lines into folders -- Keep an index in your memory for the files you create - -## Message Formatting - -Format messages based on the channel. Check the group folder name prefix: - -### Slack channels (folder starts with `slack_`) - -Use Slack mrkdwn syntax. Run `/slack-formatting` for the full reference. Key rules: -- `*bold*` (single asterisks) -- `_italic_` (underscores) -- `` for links (NOT `[text](url)`) -- `•` bullets (no numbered lists) -- `:emoji:` shortcodes like `:white_check_mark:`, `:rocket:` -- `>` for block quotes -- No `##` headings — use `*Bold text*` instead - -### WhatsApp/Telegram (folder starts with `whatsapp_` or `telegram_`) - -- `*bold*` (single asterisks, NEVER **double**) -- `_italic_` (underscores) -- `•` bullet points -- ` ``` ` code blocks - -No `##` headings. No `[links](url)`. No `**double stars**`. - -### Discord (folder starts with `discord_`) - -Standard Markdown: `**bold**`, `*italic*`, `[links](url)`, `# headings`. - ---- - -## Admin Context - -This is the **main channel**, which has elevated privileges. - -## Authentication - -Anthropic credentials must be either an API key from console.anthropic.com (`ANTHROPIC_API_KEY`) or a long-lived OAuth token from `claude setup-token` (`CLAUDE_CODE_OAUTH_TOKEN`). Short-lived tokens from the system keychain or `~/.claude/.credentials.json` expire within hours and can cause recurring container 401s. The `/setup` skill walks through this. OneCLI manages credentials (including Anthropic auth) — run `onecli --help`. - -## Container Mounts - -Main has read-only access to the project, read-write access to the store (SQLite DB), and read-write access to its group folder: - -| Container Path | Host Path | Access | -|----------------|-----------|--------| -| `/workspace/project` | Project root | read-only | -| `/workspace/project/store` | `store/` | read-write | -| `/workspace/group` | `groups/main/` | read-write | - -Key paths inside the container: -- `/workspace/project/store/messages.db` - SQLite database (read-write) -- `/workspace/project/store/messages.db` (registered_groups table) - Group config -- `/workspace/project/groups/` - All group folders - ---- - -## Managing Groups - -### Finding Available Groups - -Available groups are provided in `/workspace/ipc/available_groups.json`: - -```json -{ - "groups": [ - { - "jid": "120363336345536173@g.us", - "name": "Family Chat", - "lastActivity": "2026-01-31T12:00:00.000Z", - "isRegistered": false - } - ], - "lastSync": "2026-01-31T12:00:00.000Z" -} -``` - -Groups are ordered by most recent activity. The list is synced from WhatsApp daily. - -If a group the user mentions isn't in the list, request a fresh sync: - -```bash -echo '{"type": "refresh_groups"}' > /workspace/ipc/tasks/refresh_$(date +%s).json -``` - -Then wait a moment and re-read `available_groups.json`. - -**Fallback**: Query the SQLite database directly: - -```bash -sqlite3 /workspace/project/store/messages.db " - SELECT jid, name, last_message_time - FROM chats - WHERE jid LIKE '%@g.us' AND jid != '__group_sync__' - ORDER BY last_message_time DESC - LIMIT 10; -" -``` - -### Registered Groups Config - -Groups are registered in the SQLite `registered_groups` table: - -```json -{ - "1234567890-1234567890@g.us": { - "name": "Family Chat", - "folder": "whatsapp_family-chat", - "trigger": "@Andy", - "added_at": "2024-01-31T12:00:00.000Z" - } -} -``` - -Fields: -- **Key**: The chat JID (unique identifier — WhatsApp, Telegram, Slack, Discord, etc.) -- **name**: Display name for the group -- **folder**: Channel-prefixed folder name under `groups/` for this group's files and memory -- **trigger**: The trigger word (usually same as global, but could differ) -- **requiresTrigger**: Whether `@trigger` prefix is needed (default: `true`). Set to `false` for solo/personal chats where all messages should be processed -- **isMain**: Whether this is the main control group (elevated privileges, no trigger required) -- **added_at**: ISO timestamp when registered - -### Trigger Behavior - -- **Main group** (`isMain: true`): No trigger needed — all messages are processed automatically -- **Groups with `requiresTrigger: false`**: No trigger needed — all messages processed (use for 1-on-1 or solo chats) -- **Other groups** (default): Messages must start with `@AssistantName` to be processed - -### Adding a Group - -1. Query the database to find the group's JID -2. Ask the user whether the group should require a trigger word before registering -3. Use the `register_group` MCP tool with the JID, name, folder, trigger, and the chosen `requiresTrigger` setting -4. Optionally include `containerConfig` for additional mounts -5. The group folder is created automatically: `/workspace/project/groups/{folder-name}/` -6. Optionally create an initial `CLAUDE.md` for the group - -Folder naming convention — channel prefix with underscore separator: -- WhatsApp "Family Chat" → `whatsapp_family-chat` -- Telegram "Dev Team" → `telegram_dev-team` -- Discord "General" → `discord_general` -- Slack "Engineering" → `slack_engineering` -- Use lowercase, hyphens for the group name part - -#### Adding Additional Directories for a Group - -Groups can have extra directories mounted. Add `containerConfig` to their entry: - -```json -{ - "1234567890@g.us": { - "name": "Dev Team", - "folder": "dev-team", - "trigger": "@Andy", - "added_at": "2026-01-31T12:00:00Z", - "containerConfig": { - "additionalMounts": [ - { - "hostPath": "~/projects/webapp", - "containerPath": "webapp", - "readonly": false - } - ] - } - } -} -``` - -The directory will appear at `/workspace/extra/webapp` in that group's container. - -#### Sender Allowlist - -After registering a group, explain the sender allowlist feature to the user: - -> This group can be configured with a sender allowlist to control who can interact with me. There are two modes: -> -> - **Trigger mode** (default): Everyone's messages are stored for context, but only allowed senders can trigger me with @{AssistantName}. -> - **Drop mode**: Messages from non-allowed senders are not stored at all. -> -> For closed groups with trusted members, I recommend setting up an allow-only list so only specific people can trigger me. Want me to configure that? - -If the user wants to set up an allowlist, edit `~/.config/nanoclaw/sender-allowlist.json` on the host: - -```json -{ - "default": { "allow": "*", "mode": "trigger" }, - "chats": { - "": { - "allow": ["sender-id-1", "sender-id-2"], - "mode": "trigger" - } - }, - "logDenied": true -} -``` - -Notes: -- Your own messages (`is_from_me`) explicitly bypass the allowlist in trigger checks. Bot messages are filtered out by the database query before trigger evaluation, so they never reach the allowlist. -- If the config file doesn't exist or is invalid, all senders are allowed (fail-open) -- The config file is on the host at `~/.config/nanoclaw/sender-allowlist.json`, not inside the container - -### Removing a Group - -1. Read `/workspace/project/data/registered_groups.json` -2. Remove the entry for that group -3. Write the updated JSON back -4. The group folder and its files remain (don't delete them) - -### Listing Groups - -Read `/workspace/project/data/registered_groups.json` and format it nicely. - ---- - -## Global Memory - -You can read and write to `/workspace/global/CLAUDE.md` for facts that should apply to all groups. Only update global memory when explicitly asked to "remember this globally" or similar. - ---- - -## Scheduling for Other Groups - -When scheduling tasks for other groups, use the `target_group_jid` parameter with the group's JID from `registered_groups.json`: -- `schedule_task(prompt: "...", schedule_type: "cron", schedule_value: "0 9 * * 1", target_group_jid: "120363336345536173@g.us")` - -The task will run in that group's context with access to their files and memory. - ---- - -## Task Scripts - -For any recurring task, use `schedule_task`. Frequent agent invocations — especially multiple times a day — consume API credits and can risk account restrictions. If a simple check can determine whether action is needed, add a `script` — it runs first, and the agent is only called when the check passes. This keeps invocations to a minimum. - -Use `list_tasks` to see existing tasks (one row per series with the stable id), and `update_task` / `cancel_task` / `pause_task` / `resume_task` to modify them. Prefer `update_task` over cancel + reschedule when adjusting an existing task. - -### How it works - -1. You provide a bash `script` alongside the `prompt` when scheduling -2. When the task fires, the script runs first (30-second timeout) -3. Script prints JSON to stdout: `{ "wakeAgent": true/false, "data": {...} }` -4. If `wakeAgent: false` — nothing happens, task waits for next run -5. If `wakeAgent: true` — you wake up and receive the script's data + prompt - -### Always test your script first - -Before scheduling, run the script in your sandbox to verify it works: - -```bash -bash -c 'node --input-type=module -e " - const r = await fetch(\"https://api.github.com/repos/owner/repo/pulls?state=open\"); - const prs = await r.json(); - console.log(JSON.stringify({ wakeAgent: prs.length > 0, data: prs.slice(0, 5) })); -"' -``` - -### When NOT to use scripts - -If a task requires your judgment every time (daily briefings, reminders, reports), skip the script — just use a regular prompt. - -### Frequent task guidance - -If a user wants tasks running more than ~2x daily and a script can't reduce agent wake-ups: - -- Explain that each wake-up uses API credits and risks rate limits -- Suggest restructuring with a script that checks the condition first -- If the user needs an LLM to evaluate data, suggest using an API key with direct Anthropic API calls inside the script -- Help the user find the minimum viable frequency diff --git a/src/container-runner.ts b/src/container-runner.ts index c5abbdba3..be1f2abe2 100644 --- a/src/container-runner.ts +++ b/src/container-runner.ts @@ -320,12 +320,6 @@ export function buildMounts( mounts.push({ hostPath: fragmentsDir, containerPath: '/workspace/agent/.claude-fragments', readonly: true }); } - // Global memory directory — always read-only. - const globalDir = path.join(GROUPS_DIR, 'global'); - if (fs.existsSync(globalDir)) { - mounts.push({ hostPath: globalDir, containerPath: '/workspace/global', readonly: true }); - } - // Shared CLAUDE.md — read-only, imported by the composed entry point via // the `.claude-shared.md` symlink inside the group dir. const sharedClaudeMd = path.join(process.cwd(), 'container', 'CLAUDE.md'); From fcee39ea142eb1514452d2ba4a4a8a5d52544d38 Mon Sep 17 00:00:00 2001 From: gavrielc Date: Sat, 4 Jul 2026 16:04:58 +0300 Subject: [PATCH 07/11] command-gate: restore the /start filter and remove the fail-open admin check Add '/start' back to the host FILTERED set (a Telegram fix from 866b791 was silently undone when host gating was added) so it is dropped instead of reaching the agent as a normal message. Replace the inline isAdmin query and its hasTable('user_roles') fail-open guard with a call to hasAdminPrivilege; user_roles always exists (core migration 001-initial), so the guard only ever masked a missing check. Add a focused command-gate test covering both. Co-Authored-By: Claude Opus 4.8 --- src/command-gate.test.ts | 83 ++++++++++++++++++++++++++++++++++++++++ src/command-gate.ts | 17 ++------ 2 files changed, 86 insertions(+), 14 deletions(-) create mode 100644 src/command-gate.test.ts diff --git a/src/command-gate.test.ts b/src/command-gate.test.ts new file mode 100644 index 000000000..503034d57 --- /dev/null +++ b/src/command-gate.test.ts @@ -0,0 +1,83 @@ +/** + * Tests for the host-side command gate — filtered commands are dropped + * before reaching the container, and admin commands are gated against + * the user_roles table. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { gateCommand } from './command-gate.js'; +import { closeDb, createAgentGroup, initTestDb, runMigrations } from './db/index.js'; +import { createUser } from './modules/permissions/db/users.js'; +import { grantRole } from './modules/permissions/db/user-roles.js'; + +function now(): string { + return new Date().toISOString(); +} + +function seedAgentGroup(id: string): void { + createAgentGroup({ id, name: id.toUpperCase(), folder: id, agent_provider: null, created_at: now() }); +} + +function seedUser(id: string): void { + createUser({ id, kind: 'telegram', display_name: null, created_at: now() }); +} + +beforeEach(() => { + const db = initTestDb(); + runMigrations(db); + seedAgentGroup('ag-1'); + seedAgentGroup('ag-2'); +}); + +afterEach(() => { + closeDb(); +}); + +describe('filtered commands', () => { + it('drops /start before it reaches the container', () => { + expect(gateCommand('/start', 'telegram:1', 'ag-1')).toEqual({ action: 'filter' }); + }); + + it('drops /start regardless of sender', () => { + expect(gateCommand('/start', null, 'ag-1')).toEqual({ action: 'filter' }); + }); +}); + +describe('admin gating goes through roles', () => { + it('denies an admin command from a non-admin user', () => { + expect(gateCommand('/clear', 'telegram:nobody', 'ag-1')).toEqual({ action: 'deny', command: '/clear' }); + }); + + it('denies an admin command with no sender', () => { + expect(gateCommand('/clear', null, 'ag-1')).toEqual({ action: 'deny', command: '/clear' }); + }); + + it('allows an admin command from an owner', () => { + seedUser('telegram:owner'); + grantRole({ user_id: 'telegram:owner', role: 'owner', agent_group_id: null, granted_by: null, granted_at: now() }); + expect(gateCommand('/clear', 'telegram:owner', 'ag-1')).toEqual({ action: 'pass' }); + }); + + it('allows an admin command from a scoped admin of the group', () => { + seedUser('telegram:admin'); + grantRole({ + user_id: 'telegram:admin', + role: 'admin', + agent_group_id: 'ag-1', + granted_by: null, + granted_at: now(), + }); + expect(gateCommand('/clear', 'telegram:admin', 'ag-1')).toEqual({ action: 'pass' }); + expect(gateCommand('/clear', 'telegram:admin', 'ag-2')).toEqual({ action: 'deny', command: '/clear' }); + }); +}); + +describe('normal messages pass through', () => { + it('passes a plain message', () => { + expect(gateCommand('hello there', 'telegram:1', 'ag-1')).toEqual({ action: 'pass' }); + }); + + it('passes an unknown slash command', () => { + expect(gateCommand('/whatever', 'telegram:1', 'ag-1')).toEqual({ action: 'pass' }); + }); +}); diff --git a/src/command-gate.ts b/src/command-gate.ts index 4f600eb12..933c39277 100644 --- a/src/command-gate.ts +++ b/src/command-gate.ts @@ -7,11 +7,11 @@ * "Permission denied" response written directly to messages_out * - Normal messages: pass through unchanged */ -import { getDb, hasTable } from './db/connection.js'; +import { hasAdminPrivilege } from './modules/permissions/db/user-roles.js'; export type GateResult = { action: 'pass' } | { action: 'filter' } | { action: 'deny'; command: string }; -const FILTERED_COMMANDS = new Set(['/help', '/login', '/logout', '/doctor', '/config', '/remote-control']); +const FILTERED_COMMANDS = new Set(['/start', '/help', '/login', '/logout', '/doctor', '/config', '/remote-control']); const ADMIN_COMMANDS = new Set(['/clear', '/compact', '/context', '/cost', '/files', '/upload-trace']); /** @@ -48,16 +48,5 @@ export function gateCommand(content: string, userId: string | null, agentGroupId function isAdmin(userId: string | null, agentGroupId: string): boolean { if (!userId) return false; - if (!hasTable(getDb(), 'user_roles')) return true; // no permissions module = allow all - const db = getDb(); - const row = db - .prepare( - `SELECT 1 FROM user_roles - WHERE user_id = ? - AND (role = 'owner' OR role = 'admin') - AND (agent_group_id IS NULL OR agent_group_id = ?) - LIMIT 1`, - ) - .get(userId, agentGroupId); - return row != null; + return hasAdminPrivilege(userId, agentGroupId); } From 455014e7b9ddee4ecc86a4aba37e418cb1ca17b0 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 4 Jul 2026 13:25:56 +0000 Subject: [PATCH 08/11] chore: bump version to 2.1.26 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 6d2212918..ff3abb3b5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nanoclaw", - "version": "2.1.25", + "version": "2.1.26", "description": "Personal Claude assistant. Lightweight, secure, customizable.", "type": "module", "packageManager": "pnpm@10.33.0", From 687d7d13acef473119fe6a6807a48bb4a598ebbe Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 4 Jul 2026 13:26:56 +0000 Subject: [PATCH 09/11] chore: bump version to 2.1.27 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index ff3abb3b5..f9c8b48b3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nanoclaw", - "version": "2.1.26", + "version": "2.1.27", "description": "Personal Claude assistant. Lightweight, secure, customizable.", "type": "module", "packageManager": "pnpm@10.33.0", From 10d400ec643ff783dd037ead004385d43b075907 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 4 Jul 2026 13:29:49 +0000 Subject: [PATCH 10/11] chore: bump version to 2.1.28 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index f9c8b48b3..225087a08 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nanoclaw", - "version": "2.1.27", + "version": "2.1.28", "description": "Personal Claude assistant. Lightweight, secure, customizable.", "type": "module", "packageManager": "pnpm@10.33.0", From bf0a3d2612d1e744854aa3858e67c27c32b09557 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Sat, 4 Jul 2026 13:31:46 +0000 Subject: [PATCH 11/11] chore: bump version to 2.1.29 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 225087a08..8518f28f6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nanoclaw", - "version": "2.1.28", + "version": "2.1.29", "description": "Personal Claude assistant. Lightweight, secure, customizable.", "type": "module", "packageManager": "pnpm@10.33.0",