Compare commits

..

39 Commits

Author SHA1 Message Date
Gabi Simons 68ebc02114 Update CONTRIBUTING.md 2026-07-08 14:48:25 +03:00
Gabi Simons d4e73c5523 Merge branch 'main' into feat/core-team-pr-label 2026-07-08 14:35:23 +03:00
github-actions[bot] 9a103f4f93 docs: update token count to 213k tokens · 106% of context window 2026-07-08 11:29:45 +00:00
github-actions[bot] a8554c6248 chore: bump version to 2.1.40 2026-07-08 11:29:40 +00:00
gavrielc 2480ae7cb8 Merge pull request #2980 from nanocoai/tasks/01-cli-verb-args-human-view
ncl CLI: verb-level args, deep help, server-rendered human view
2026-07-08 14:29:24 +03:00
Omri Maya 763a3f757b feat(cli): verb-level args, deep help, server-rendered human view
Every ncl verb now declares its args: strict validation with fix-carrying
error messages, generated per-verb --help, and multi-word custom-op key
resolution (spaces vs dashes). Longest-prefix command fallback keeps dashed
positional ids intact.

Responses gain a server-rendered 'human' frame field (formatHuman hook): the
host renders tables once and every client prints them verbatim — container
agents cannot import host formatters, so this is how they get aligned output
instead of a raw column dump. --help responses carry 'human' for clean
multi-line rendering.

Robustness fixes riding along:
- generic list returns newest rows first, so the LIMIT no longer hides
  recent rows
- stdout flushed before exit — >64KB responses were silently truncated

Additive only: new response-frame fields, no schema changes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 12:39:10 +03:00
Gabi Simons 8943c1cbf4 ci: auto-label PRs from core team members
Extends the existing label-pr workflow with an author allowlist that
applies a core-team label. The label is auto-provisioned on first use
so no manual repo setup is needed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 10:11:43 +03:00
github-actions[bot] 559bb5ca1a chore: bump version to 2.1.39 2026-07-07 20:00:50 +00:00
gavrielc 04b364e828 Merge pull request #2965 from nanocoai/fix/rate-limit-event-shape
fix(agent-runner): match rate_limit_event as a top-level SDK message type
2026-07-07 23:00:36 +03:00
gavrielc 627ab23bad Merge branch 'main' into fix/rate-limit-event-shape 2026-07-07 23:00:24 +03:00
gavrielc 8986fef586 Apply suggestion from @gavrielc 2026-07-07 23:00:07 +03:00
gavrielc 7f49450c0c Merge pull request #2964 from nanocoai/docs-sdk-deep-dive
docs: update SDK deep-dive from 0.2.x to 0.3.197
2026-07-07 22:58:40 +03:00
gavrielc cdc519e1f4 Merge pull request #2963 from nanocoai/docs-rewrite-core
docs: rewrite architecture.md and agent-runner-details.md to match current code
2026-07-07 22:56:12 +03:00
gavrielc 1276645c3b Merge pull request #2962 from nanocoai/docs-fix-schema
docs: sync DB schema and entity docs with migrations 010-018
2026-07-07 22:55:40 +03:00
github-actions[bot] d3499b7d70 docs: update token count to 209k tokens · 104% of context window 2026-07-07 19:55:04 +00:00
gavrielc c2cf19ec28 Merge pull request #2961 from nanocoai/docs-fix-mechanical
docs: fix stale claims across README, CONTRIBUTING, CLAUDE.md and operational docs
2026-07-07 22:54:48 +03:00
glifocat 44f351349a docs: Output Delivery — messages_out comes from <message> envelope parsing, not raw results
The section still described the pre-envelope model where every provider
result was written to messages_out verbatim. Since the envelope parser
landed, the agent-runner parses the final text for <message to="name">
blocks (dispatchResultText, poll-loop.ts): one messages_out row per
block, bare/<internal> text is scratchpad (logged, never sent), unknown
destinations are dropped, unwrapped output gets a one-time re-wrap
nudge, and non-retryable error results are delivered as error notices
instead of being dropped.
2026-07-07 00:26:12 +00:00
glifocat e8a32207d8 fix(agent-runner): match rate_limit_event as a top-level SDK message type
The claude provider mapped rate-limit events with
`message.type === 'system' && subtype === 'rate_limit_event'`, but
`@anthropic-ai/claude-agent-sdk` 0.3.x ships rate limits as a top-level
`SDKRateLimitEvent` (`{ type: 'rate_limit_event', ... }`) with no `system`
subtype. The old condition never matched, so the quota-classified error
event was never emitted and rate-limit signals were silently dropped.

Match the top-level `type` instead.
2026-07-06 15:05:01 +00:00
glifocat 1dda751a48 docs: update SDK deep-dive from 0.2.x to 0.3.x 2026-07-06 14:52:03 +00:00
glifocat 4f1b17c737 docs: sync DB schema + entity docs with migrations 010-018 2026-07-06 13:04:14 +00:00
glifocat 967aee2c27 docs: fix stale claims vs v2.1.38 (skills lists, runtime claims, file refs) 2026-07-06 13:04:14 +00:00
glifocat 5aac750aa5 docs: rewrite architecture + agent-runner internals to match current code 2026-07-06 13:04:14 +00:00
glifocat b6cb53e21c Merge pull request #2953 from nanocoai/docs-staleness-fixes
docs: correct stale mount topology row + removed env var
2026-07-04 23:06:27 +02:00
gavrielc 5a7e75f854 Apply suggestion from @gavrielc 2026-07-04 23:36:05 +03:00
glifocat d770e56596 docs: correct stale mount topology + removed env var vs code 2026-07-04 19:39:13 +00:00
github-actions[bot] 08a1ac9753 chore: bump version to 2.1.38 2026-07-04 16:58:45 +00:00
gavrielc 273489badf Merge pull request #2931 from nanocoai/cleanup/async-image-build
Build agent images asynchronously instead of blocking the host
2026-07-04 19:58:34 +03:00
gavrielc 504651633f Merge branch 'main' into cleanup/async-image-build 2026-07-04 19:58:25 +03:00
github-actions[bot] 694ab74aa1 chore: bump version to 2.1.37 2026-07-04 16:55:14 +00:00
gavrielc aae81321e9 Merge pull request #2948 from nanocoai/cleanup/arch-scheduling-provider-docs
Fix stale architecture, scheduling, provider-config, and overlay docs
2026-07-04 19:55:02 +03:00
gavrielc 6c46b1e43d Merge branch 'main' into cleanup/arch-scheduling-provider-docs 2026-07-04 19:54:49 +03:00
gavrielc 71453707ba Apply suggestion from @gavrielc 2026-07-04 19:54:15 +03:00
gavrielc 0aa9e668f6 Apply suggestion from @gavrielc 2026-07-04 19:53:24 +03:00
gavrielc 023128def5 Merge pull request #2946 from nanocoai/cleanup/remove-env-secrets-mirror
Remove the dead data/env/env secrets mirror
2026-07-04 19:52:00 +03:00
gavrielc c4a1679666 Merge branch 'main' into cleanup/remove-env-secrets-mirror 2026-07-04 19:51:30 +03:00
gavrielc 2e40e17155 Merge pull request #2945 from nanocoai/cleanup/security-docs-v2
Rewrite the security docs to match the v2 perimeter
2026-07-04 19:51:10 +03:00
gavrielc 0835089a51 Fix stale architecture, scheduling, provider-config, and overlay docs
Correct docs (and one code comment) that describe systems that no longer
exist in v2: mark docs/SPEC.md as the historical v1 spec; replace the
impossible "write messages_in (to self)" / stale list_tasks scheduling
model with the real messages_out system-action path in
agent-runner-details.md and architecture.md; drop the false
MAX_CONCURRENT_CONTAINERS cap claim; remove the per-group agent-runner-src
overlay from the live DB map (source is a shared read-only mount) and fix
the insertTask attribution to src/modules/scheduling/db.ts; correct the
container-skills count to 8; repoint the deleted-doc comment in
src/claude-md-compose.ts; and replace the AGENT_PROVIDER / hand-edit
container.json provider-config instructions in add-opencode and add-mnemon
with the real `ncl groups config update --provider` flow.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 16:18:08 +03:00
gavrielc c82f062d57 Remove the dead data/env/env secrets mirror from setup
Nothing has read data/env/env since commit 1a07869 removed the container
mount, yet setup still wrote the full .env (live tokens included) there.
Drop every writer and correct the stale comments/docs that described it.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 16:11:09 +03:00
gavrielc e3b2ffce36 Build agent images asynchronously instead of blocking the host
Replace the execSync docker build in buildAgentGroupImage with an awaited
promisified exec so the single-threaded host stays responsive during the
image build (up to 15 minutes) that a package-install approval or
`ncl groups restart --rebuild` triggers. Timeout, buffered stdio, and
non-zero-exit error propagation are preserved; both callers already await.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 16:04:56 +03:00
53 changed files with 2106 additions and 954 deletions
+3 -3
View File
@@ -9,13 +9,13 @@ Installs [mnemon](https://github.com/mnemon-dev/mnemon) in the agent container i
## Provider Compatibility
mnemon hooks fire only under `--target claude-code`. Use this skill on agent groups that run the default Claude provider (`AGENT_PROVIDER=claude`). Confirm the provider before applying:
mnemon hooks fire only under `--target claude-code`. Use this skill on agent groups that run the default Claude provider. The provider is the materialized `provider` key in each group's `container.json` (absent or `claude` = default Claude provider). Confirm it before applying:
```bash
grep AGENT_PROVIDER .env groups/*/container.json 2>/dev/null
grep -H '"provider"' groups/*/container.json 2>/dev/null # no match, or "provider": "claude" = Claude
```
If a group uses a different provider (e.g. `AGENT_PROVIDER=opencode`), it spawns its own process and never invokes the `claude` CLI, so the hooks registered by `mnemon setup` do not run for that group.
If a group sets a different provider (e.g. `"provider": "opencode"`), it spawns its own process and never invokes the `claude` CLI, so the hooks registered by `mnemon setup` do not run for that group.
## Phase 1: Pre-flight
+14 -7
View File
@@ -1,11 +1,11 @@
---
name: add-opencode
description: Use OpenCode as an agent provider (AGENT_PROVIDER=opencode). OpenRouter, OpenAI, Google, DeepSeek, etc. via OpenCode config — not the Anthropic Agent SDK. Per-session and per-group via agent_provider; host passes OPENCODE_* and XDG mount when spawning containers.
description: Use OpenCode as an agent provider. OpenRouter, OpenAI, Google, DeepSeek, etc. via OpenCode config — not the Anthropic Agent SDK. Per group via `ncl groups config update --provider opencode`; host passes OPENCODE_* and XDG mount when spawning containers.
---
# OpenCode agent provider
NanoClaw runs agents in a long-lived **poll loop** inside the container. The backend is selected with **`AGENT_PROVIDER`** (`claude` | `opencode` | `mock`).
NanoClaw runs agents in a long-lived **poll loop** inside the container. The backend is selected per agent group by the **`provider`** key in that group's `container.json` (materialized from the `container_configs` table) — set it with `ncl groups config update --provider opencode`. Default is `claude`.
Trunk ships with only the `claude` provider baked in. This skill copies the OpenCode provider files in from the `providers` branch, wires them into the host and container barrels, installs dependencies, and rebuilds the image.
@@ -148,7 +148,7 @@ done
Set model/provider strings in the form OpenCode expects (often `provider/model-id`). **Put comments on their own lines** — a `#` inside a value is kept verbatim and breaks model IDs.
These variables are read **on the host** and passed into the container only when the effective provider is `opencode`. They do not switch the provider by themselves; the DB still needs `agent_provider` set (below).
These variables are read **on the host** and passed into the container only when the effective provider is `opencode`. They do not switch the provider by themselves; the group still needs `provider` set to `opencode` (see [Select the provider](#select-the-provider) below).
- `OPENCODE_PROVIDER` — OpenCode provider id, e.g. `openrouter`, `anthropic`, `deepseek`.
- `OPENCODE_MODEL` — full model id in `provider/model` form, e.g. `deepseek/deepseek-chat`.
@@ -215,7 +215,7 @@ OPENCODE_SMALL_MODEL=anthropic/claude-haiku-4-5-20251001
Zen's HTTP API (e.g. `POST …/zen/v1/messages`) expects the key in the **`x-api-key`** header. If OneCLI injects **`Authorization: Bearer …`** only, Zen often returns **401 / "Missing API key"** even though the gateway is working.
**Naming:** NanoClaw **`AGENT_PROVIDER=opencode`** (DB `agent_provider`) means "run the **OpenCode agent provider**." Separately, **`OPENCODE_PROVIDER=opencode`** in `.env` is OpenCode's **Zen provider id** inside the OpenCode config (see [Zen docs](https://opencode.ai/docs/zen/)).
**Naming:** NanoClaw's **`provider: opencode`** (the `container.json` key, set via `ncl groups config update --provider opencode`) means "run the **OpenCode agent provider**." Separately, **`OPENCODE_PROVIDER=opencode`** in `.env` is OpenCode's **Zen provider id** inside the OpenCode config (see [Zen docs](https://opencode.ai/docs/zen/)).
**Host `.env` (typical Zen shape):**
@@ -236,9 +236,16 @@ onecli secrets create --name "OpenCode Zen" --type generic \
--header-name "x-api-key" --value-format "{value}"
```
### Per group / per session
### Select the provider
Set `"provider": "opencode"` in the group's **`container.json`** (`groups/<folder>/container.json`) — the in-container runner reads `provider` from there, not from the DB. The DB columns **`agent_groups.agent_provider`** and **`sessions.agent_provider`** (session overrides group) only drive host-side provider contribution — per-session XDG mount, `OPENCODE_*` env passthrough — and do not propagate into `container.json` at spawn time. Set both, or just edit `container.json`; if they disagree, the runner uses `container.json` and the host-side resolver falls back through session → group → `container.json``'claude'`.
Per group, from the host:
```bash
ncl groups config update --id <group-id> --provider opencode
ncl groups restart --id <group-id>
```
`ncl groups config update --provider` writes the `provider` value into the `container_configs` table; the host materializes it into `groups/<folder>/container.json` at spawn time and the in-container runner reads `provider` from there (defaulting to `claude`). The restart picks up the change. Switching is an operator action — run it from the host. Memory does NOT carry over automatically between providers — run `/migrate-memory` to carry it across.
Extra MCP servers still come from **`NANOCLAW_MCP_SERVERS`** / `container_config.mcpServers` on the host; the runner merges them into the same `mcpServers` object passed to **both** Claude and OpenCode providers.
@@ -250,6 +257,6 @@ Extra MCP servers still come from **`NANOCLAW_MCP_SERVERS`** / `container_config
## Next Steps
The registration and Dockerfile guards in step 7 verify the wiring. To confirm an end-to-end round-trip, set `agent_provider = 'opencode'` (or `"provider": "opencode"` in the group's `container.json`) on a test group, register the matching provider key in OneCLI, and send a message. A clean exchange returns the model's reply with no `Unknown provider: opencode` error and no UUID/session warnings in the logs.
The registration and Dockerfile guards in step 7 verify the wiring. To confirm an end-to-end round-trip, switch a test group with `ncl groups config update --id <group-id> --provider opencode && ncl groups restart --id <group-id>`, register the matching provider key in OneCLI, and send a message. A clean exchange returns the model's reply with no `Unknown provider: opencode` error and no UUID/session warnings in the logs.
To remove this provider, see [REMOVE.md](REMOVE.md).
+19
View File
@@ -14,6 +14,7 @@ jobs:
runs-on: ubuntu-latest
permissions:
pull-requests: write
issues: write # createLabel — auto-provisions the core-team label
steps:
- uses: actions/github-script@v7
with:
@@ -30,6 +31,24 @@ jobs:
if (body.includes('contributing-guide: v1')) labels.push('follows-guidelines');
// Lowercase GitHub logins; keep in sync with the core team roster.
const CORE_TEAM = ['gavrielc', 'koshkoshinsk', 'glifocat', 'gabi-simons', 'omri-maya', 'amit-shafnir', 'moshe-nanoco'];
const author = context.payload.pull_request.user.login.toLowerCase();
if (CORE_TEAM.includes(author)) {
labels.push('core-team');
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: 'core-team',
color: '1D76DB',
description: 'PR opened by a core team member',
});
} catch (e) {
if (e.status !== 422) throw e; // 422: label already exists
}
}
if (labels.length > 0) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
+14 -14
View File
@@ -15,11 +15,11 @@ If you are a fresh install (you ran `git clone`, not `git pull`) and there are n
# NanoClaw
Personal Claude assistant. See [README.md](README.md) for philosophy and setup. Architecture lives in `docs/`.
Personal AI assistant. See [README.md](README.md) for philosophy and setup. Architecture lives in `docs/`.
## Quick Context
The host is a single Node process that orchestrates per-session agent containers. Platform messages land via channel adapters, route through an entity model (users → messaging groups → agent groups → sessions), get written into the session's inbound DB, and wake a container. The agent-runner inside the container polls the DB, calls Claude, and writes back to the outbound DB. The host polls the outbound DB and delivers through the same adapter.
The host is a single Node process that orchestrates per-session agent containers. Platform messages land via channel adapters, route through an entity model (users → messaging groups → agent groups → sessions), get written into the session's inbound DB, and wake a container. The agent-runner inside the container polls the DB, calls the agent, and writes back to the outbound DB. The host polls the outbound DB and delivers through the same adapter.
**Everything is a message.** There is no IPC, no file watcher, no stdin piping between host and container. The two session DBs are the sole IO surface.
@@ -32,7 +32,7 @@ agent_group_members (user_id, agent_group_id) — unprivileged access gate
user_dms (user_id, channel_type, messaging_group_id) — cold-DM cache
agent_groups (workspace, memory, CLAUDE.md, personality, container config)
↕ many-to-many via messaging_group_agents (session_mode, trigger_rules, priority)
↕ many-to-many via messaging_group_agents (session_mode, engage_mode/engage_pattern, sender_scope, priority)
messaging_groups (one chat/channel on one platform; instance = adapter-instance name, defaults to channel_type; unknown_sender_policy)
sessions (agent_group_id + messaging_group_id + thread_id → per-session container)
@@ -44,8 +44,8 @@ Privilege is user-level (owner/admin), not agent-group-level. See [docs/isolatio
Each session has **two** SQLite files under `data/v2-sessions/<session_id>/`:
- `inbound.db` — host writes, container reads. `messages_in`, routing, destinations, pending_questions, processing_ack.
- `outbound.db` — container writes, host reads. `messages_out`, session_state.
- `inbound.db` — host writes, container reads. `messages_in`, delivered, destinations, session_routing.
- `outbound.db` — container writes, host reads. `messages_out`, processing_ack, session_state, container_state.
Exactly one writer per file — no cross-mount lock contention. Heartbeat is a file touch at `/workspace/.heartbeat`, not a DB update. Host uses even `seq` numbers, container uses odd.
@@ -65,13 +65,13 @@ For ad-hoc queries from skills or scripts, use the in-tree wrapper rather than t
| `src/host-sweep.ts` | 60s sweep: `processing_ack` sync, stale detection, due-message wake, recurrence |
| `src/session-manager.ts` | Resolves sessions; opens `inbound.db` / `outbound.db`; manages heartbeat path |
| `src/container-runner.ts` | Spawns per-agent-group Docker containers with session DB + outbox mounts, OneCLI `ensureAgent` |
| `src/container-runtime.ts` | Runtime selection (Docker vs Apple containers), orphan cleanup |
| `src/container-runtime.ts` | Docker CLI wrapper (runtime binary, host-gateway args, mount args), orphan cleanup |
| `src/modules/permissions/access.ts` | `canAccessAgentGroup` — owner / global admin / scoped admin / member resolution against `user_roles` + `agent_group_members` |
| `src/modules/approvals/primitive.ts` | `pickApprover`, `pickApprovalDelivery`, `requestApproval`, approval-handler registry |
| `src/command-gate.ts` | Router-side admin command gate — queries `user_roles` directly (no env var, no container-side check) |
| `src/modules/approvals/onecli-approvals.ts` | OneCLI credentialed-action approval bridge |
| `src/modules/permissions/user-dm.ts` | Cold-DM resolution + `user_dms` cache |
| `src/group-init.ts` | Per-agent-group filesystem scaffold (CLAUDE.md, skills, agent-runner-src overlay) |
| `src/group-init.ts` | Per-agent-group filesystem scaffold (CLAUDE.md, skills) — agent-runner source is a shared read-only mount, not copied per group |
| `src/db/container-configs.ts` | CRUD for `container_configs` table (per-group container runtime config) |
| `src/backfill-container-configs.ts` | Migrates legacy `container.json` files into the DB on startup |
| `src/container-restart.ts` | Kill + on-wake respawn for agent group containers |
@@ -79,8 +79,8 @@ For ad-hoc queries from skills or scripts, use the in-tree wrapper rather than t
| `src/channels/` | Channel adapter infra (registry, Chat SDK bridge); specific channel adapters are skill-installed from the `channels` branch |
| `src/providers/` | Host-side provider container-config (`claude` baked in; `opencode` etc. installed from the `providers` branch) |
| `container/agent-runner/src/` | Agent-runner: poll loop, formatter, provider abstraction, MCP tools, destinations |
| `container/skills/` | Container skills mounted into every agent session (`onecli-gateway`, `welcome`, `self-customize`, `agent-browser`, `slack-formatting`) |
| `groups/<folder>/` | Per-agent-group filesystem (CLAUDE.md, skills, per-group `agent-runner-src/` overlay) |
| `container/skills/` | Container skills mounted into every agent session (`agent-browser`, `frontend-engineer`, `onecli-gateway`, `self-customize`, `slack-formatting`, `vercel-cli`, `welcome`, `whatsapp-formatting`) |
| `groups/<folder>/` | Per-agent-group filesystem (CLAUDE.md, skills) — agent-runner source is a shared read-only mount, not copied per group |
| `scripts/init-first-agent.ts` | Bootstrap the first DM-wired agent (used by `/init-first-agent` skill) |
| `migrate-v2.sh` + `setup/migrate-v2/` | v1→v2 migration. Standalone script: `bash migrate-v2.sh`. Seeds DB, copies groups/sessions, installs channels, builds container, offers service switchover, then hands off to `/migrate-from-v1` skill for owner setup and CLAUDE.md cleanup. See [docs/migration-dev.md](docs/migration-dev.md). |
| `nanoclaw.sh --uninstall` + `setup/uninstall/` | Uninstall this copy only (slug-scoped): service, containers + image, `data/`, `logs/`, `groups/`, this copy's OneCLI agents. Confirms per group; `--dry-run` previews, `--yes` skips prompts. Other copies and the shared OneCLI app are untouched. Bypasses bootstrap entirely; `uninstall.sh` is a pointer that execs it. |
@@ -115,7 +115,7 @@ Key files: `src/cli/dispatch.ts` (dispatcher + approval handler), `src/cli/crud.
Trunk does not ship any specific channel adapter or non-default agent provider. The codebase is the registry/infra; the actual adapters and providers live on long-lived sibling branches and get copied in by skills:
- **`channels` branch** — Discord, Slack, Telegram, WhatsApp, Teams, Linear, GitHub, iMessage, Webex, Resend, Matrix, Google Chat, WhatsApp Cloud (+ helpers, tests, channel-specific setup steps). Installed via `/add-<channel>` skills.
- **`channels` branch** — Discord, Slack, Telegram, WhatsApp, Teams, Linear, GitHub, iMessage, Webex, Resend, Matrix, Google Chat, WhatsApp Cloud, Signal, WeChat, DeltaChat, Emacs (+ helpers, tests, channel-specific setup steps). Installed via `/add-<channel>` skills.
- **`providers` branch** — OpenCode (and any future non-default agent providers). Installed via `/add-opencode`.
Each `/add-<name>` skill is idempotent: `git fetch origin <branch>` → copy module(s) into the standard paths → append a self-registration import to the relevant barrel → `pnpm install <pkg>@<pinned-version>` → build.
@@ -170,7 +170,7 @@ No container restart needed — the gateway looks up secrets per request.
Approval-gating credentialed actions is a **two-sided** flow:
- **Server-side** (OneCLI gateway): decides *when* to hold a request and emit a pending approval. As of `onecli@1.3.0`, the CLI does **not** expose this — `rules create --action` only accepts `block` or `rate_limit`, and `secrets create` has no approval flag. Approval policies must be configured via the OneCLI web UI at `http://127.0.0.1:10254`. If/when the CLI grows an `approve` action, this section needs updating.
- **Server-side** (OneCLI gateway): decides *when* to hold a request and emit a pending approval. As of `onecli@2.2.5`, the CLI does **not** expose this — `rules create --action` only accepts `block` or `rate_limit`, and `secrets create` has no approval flag. Approval policies must be configured via the OneCLI web UI at `http://127.0.0.1:10254`. If/when the CLI grows an `approve` action, this section needs updating.
- **Host-side** (nanoclaw): receives pending approvals and routes them to a human. `src/modules/approvals/onecli-approvals.ts` registers a callback via `onecli.configureManualApproval(cb)` (long-polls `GET /api/approvals/pending`). The callback uses `pickApprover` + `pickApprovalDelivery` from `src/modules/approvals/primitive.ts` to DM an approver. Approvers are resolved from the `user_roles` table — preference order: scoped admins for the agent group → global admins → owners. There is no env var like `NANOCLAW_ADMIN_USER_IDS`; roles are persisted in the central DB only.
If approvals are configured server-side but the host callback isn't running (or throws), every credentialed call hangs until the gateway times out. Conversely, if the gateway has no rule asking for approval, the host callback never fires regardless of how it's wired.
@@ -182,7 +182,7 @@ Four types of skills. See [CONTRIBUTING.md](CONTRIBUTING.md) for the full taxono
- **Channel/provider install skills** — copy the relevant module(s) in from the `channels` or `providers` branch, wire imports, install pinned deps (e.g. `/add-discord`, `/add-slack`, `/add-whatsapp`, `/add-opencode`).
- **Utility skills** — ship code files alongside `SKILL.md` (e.g. a `scripts/` CLI or helper).
- **Operational skills** — instruction-only workflows (`/setup`, `/debug`, `/customize`, `/init-first-agent`, `/manage-channels`, `/init-onecli`, `/update-nanoclaw`).
- **Container skills** — loaded inside agent containers at runtime (`container/skills/`: `onecli-gateway`, `welcome`, `self-customize`, `agent-browser`, `slack-formatting`).
- **Container skills** — loaded inside agent containers at runtime (`container/skills/`: `agent-browser`, `frontend-engineer`, `onecli-gateway`, `self-customize`, `slack-formatting`, `vercel-cli`, `welcome`, `whatsapp-formatting`).
| Skill | When to Use |
|-------|-------------|
@@ -216,7 +216,7 @@ Run commands directly — don't tell the user to run them.
```bash
# Host (Node + pnpm)
pnpm run dev # Host with hot reload
pnpm run dev # Host via tsx (no watch)
pnpm run build # Compile host TypeScript (src/)
./container/build.sh # Rebuild agent container image (nanoclaw-agent:latest)
pnpm test # Host tests (vitest)
@@ -297,7 +297,7 @@ The agent container runs on **Bun**; the host runs on **Node** (pnpm). They comm
- **Writing a new named-param SQL insert/update in the container** → use `$name` in both SQL and JS keys: `.run({ $id: msg.id })`. `bun:sqlite` does not auto-strip the prefix the way `better-sqlite3` does on the host. Positional `?` params work normally.
- **Adding a test in `container/agent-runner/src/`** → import from `bun:test`, not `vitest`. Vitest runs on Node and can't load `bun:sqlite`. `vitest.config.ts` excludes this tree.
- **Adding a Node CLI the agent invokes at runtime** (like `agent-browser`, `claude-code`, `vercel`) → put it in the Dockerfile's pnpm global-install block, pinned to an exact version via a new `ARG`. Don't use `bun install -g` — that bypasses the pnpm supply-chain policy.
- **Changing the Dockerfile entrypoint or the dynamic-spawn command** (`src/container-runner.ts` line ~301) → keep `exec bun ...` so signals forward cleanly. The image has no `/app/dist`; don't reintroduce a tsc build step.
- **Changing the Dockerfile entrypoint or the dynamic-spawn command** (`src/container-runner.ts` line ~503) → keep `exec bun ...` so signals forward cleanly. The image has no `/app/dist`; don't reintroduce a tsc build step.
- **Changing session-DB pragmas** (`container/agent-runner/src/db/connection.ts`) → `journal_mode=DELETE` is load-bearing for cross-mount visibility. Read the comment block at the top of the file first.
## CJK font support
+4 -4
View File
@@ -75,7 +75,7 @@ Standalone tools that ship code files alongside the SKILL.md. The SKILL.md tells
#### 3. Operational skills (instruction-only)
Workflows and guides with no code changes. The SKILL.md is the entire skill — Claude follows the instructions to perform a task.
Workflows and guides with no code changes. The SKILL.md is the entire skill — the coding agent follows the instructions to perform a task.
**Location:** `.claude/skills/` on `main`
@@ -88,13 +88,13 @@ Workflows and guides with no code changes. The SKILL.md is the entire skill —
#### 4. Container skills (agent runtime)
Skills that run inside the agent container, not on the host. These teach the container agent how to use tools, format output, or perform tasks. They are synced into each group's `.claude/skills/` directory when a container starts.
Skills that run inside the agent container, not on the host. These teach the NanoClaw agent how to use tools, format output, or perform tasks. They are synced into each group's `.claude/skills/` directory when a container starts.
**Location:** `container/skills/<name>/`
**Examples:** `agent-browser` (web browsing), `capabilities` (/capabilities command), `status` (/status command), `slack-formatting` (Slack mrkdwn syntax)
**Examples:** `agent-browser` (web browsing), `frontend-engineer`, `onecli-gateway` (OneCLI proxy usage), `self-customize`, `slack-formatting` (Slack mrkdwn syntax), `vercel-cli`, `welcome`, `whatsapp-formatting`
**Key difference:** These are NOT invoked by the user on the host. They're loaded by Claude Code inside the container and influence how the agent behaves.
**Key difference:** You never invoke these from a coding-agent session on the host, the way you run `/setup` or `/update-nanoclaw` in Claude Code/Codex/OpenCode. They're mounted into the sandbox and loaded by the NanoClaw agent itself, shaping how it behaves when you chat with it.
**Guidelines:**
- Follow the same SKILL.md + frontmatter format
+8 -11
View File
@@ -22,7 +22,7 @@
[OpenClaw](https://github.com/openclaw/openclaw) is an impressive project, but I wouldn't have been able to sleep if I had given complex software I didn't understand full access to my life. OpenClaw has nearly half a million lines of code, 53 config files, and 70+ dependencies. Its security is at the application level (allowlists, pairing codes) rather than true OS-level isolation. Everything runs in one Node process with shared memory.
NanoClaw provides that same core functionality, but in a codebase small enough to understand: one process and a handful of files. Claude agents run in their own Linux containers with filesystem isolation, not merely behind permission checks.
NanoClaw provides that same core functionality, but in a codebase small enough to understand: one process and a handful of files. Agents run in their own Linux containers with filesystem isolation, not merely behind permission checks.
## Quick Start
@@ -49,7 +49,7 @@ bash migrate-v2.sh
Run the script directly, not from inside a Claude session — the deterministic side needs interactive prompts and real shell I/O for Node/pnpm bootstrap, Docker, OneCLI, and the container build.
**What it does:** merges `.env`, seeds the v2 DB from `registered_groups`, copies group folders + session data + scheduled tasks, installs the channel adapters you select, copies channel auth state (including Baileys keystore + LID mappings for WhatsApp), builds the agent container.
**What it does:** merges `.env`, seeds the v2 DB from `registered_groups`, copies group folders + session data + scheduled tasks, installs the channel adapters you select, copies channel auth state (including the Baileys keystore for WhatsApp — LID mapping is now resolved per-message by the Baileys v7 adapter, not migrated), builds the agent container.
**What it doesn't:** flip the system service. Pick *"switch to v2"* at the prompt, or do it manually after testing — your v1 install is left untouched.
@@ -78,11 +78,11 @@ See [docs/v1-to-v2-changes.md](docs/v1-to-v2-changes.md) for what's different an
- **Multi-channel messaging** — WhatsApp, Telegram, Discord, Slack, Microsoft Teams, iMessage, Matrix, Google Chat, Webex, Linear, GitHub, WeChat, and email via Resend. Installed on demand with `/add-<channel>` skills. Run one or many at the same time.
- **Flexible isolation** — connect each channel to its own agent for full privacy, share one agent across many channels for unified memory with separate conversations, or fold multiple channels into a single shared session so one conversation spans many surfaces. Pick per channel via `/manage-channels`. See [docs/isolation-model.md](docs/isolation-model.md).
- **Per-agent workspace** — each agent group has its own `CLAUDE.md`, its own memory, its own container, and only the mounts you allow. Nothing crosses the boundary unless you wire it to.
- **Scheduled tasks** — recurring jobs that run Claude and can message you back
- **Scheduled tasks** — recurring jobs executed by the agent, which can message you the results
- **Web access** — search and fetch content from the web
- **Container isolation** — agents are sandboxed in Docker (macOS/Linux/WSL2), with optional Docker Sandboxes micro-VM isolation
- **Container isolation** — agents are sandboxed in Docker containers (macOS/Linux/WSL2)
- **Credential security** — agents never hold raw API keys. Outbound requests route through [OneCLI's Agent Vault](https://github.com/onecli/onecli), which injects credentials at request time and enforces per-agent policies and rate limits.
- **Agent templates**: stamp a ready-to-run agent (instructions + MCP tools + skills, no secrets) from a reusable bundle, via the setup wizard or `ncl groups create --template <ref>`. Load from the [public library](https://github.com/nanocoai/nanoclaw-templates), a local folder, or any git repo. See [docs/templates.md](docs/templates.md).
- **Agent templates**: stamp a ready-to-run agent (instructions + MCP tools + skills, no secrets) from a reusable bundle via `ncl groups create --template <ref>`. Templates load from the local `templates/` folder; populate it by hand or by copying from the [public library](https://github.com/nanocoai/nanoclaw-templates). See [docs/templates.md](docs/templates.md).
## Usage
@@ -124,10 +124,7 @@ This keeps trunk as pure registry and infra, and every fork stays lean — users
### RFS (Request for Skills)
Skills we'd like to see:
**Communication Channels**
- `/add-signal` — Add Signal as a channel
No channel or provider skills are currently requested — propose one via an issue.
## Requirements
@@ -142,7 +139,7 @@ Skills we'd like to see:
messaging apps → host process (router) → inbound.db → container (Bun, Claude Agent SDK) → outbound.db → host process (delivery) → messaging apps
```
A single Node host orchestrates per-session agent containers. When a message arrives, the host routes it via the entity model (user → messaging group → agent group → session), writes it to the session's `inbound.db`, and wakes the container. The agent-runner inside the container polls `inbound.db`, runs Claude, and writes responses to `outbound.db`. The host polls `outbound.db` and delivers back through the channel adapter.
A single Node host orchestrates per-session agent containers. When a message arrives, the host routes it via the entity model (user → messaging group → agent group → session), writes it to the session's `inbound.db`, and wakes the container. The agent-runner inside the container polls `inbound.db`, runs the agent, and writes responses to `outbound.db`. The host polls `outbound.db` and delivers back through the channel adapter.
Two SQLite files per session, each with exactly one writer — no cross-mount contention, no IPC, no stdin piping. Channels and alternative providers self-register at startup; trunk ships the registry and the Chat SDK bridge, while the adapters themselves are skill-installed per fork.
@@ -165,7 +162,7 @@ Key files:
**Why Docker?**
Docker provides cross-platform support (macOS, Linux and Windows via WSL2) and a mature ecosystem. For additional isolation, Docker Sandboxes run each container inside a micro VM.
Docker provides cross-platform support (macOS, Linux and Windows via WSL2) and a mature ecosystem.
**Can I run this on Linux or Windows?**
+6 -1
View File
@@ -22,7 +22,9 @@ type RequestFrame = {
};
type ResponseFrame =
| { id: string; ok: true; data: unknown }
// `human` mirrors src/cli/frame.ts: an optional server-rendered string we
// print verbatim instead of running our own (drift-prone) formatter.
| { id: string; ok: true; data: unknown; human?: string }
| { id: string; ok: false; error: { code: string; message: string } };
// ---------------------------------------------------------------------------
@@ -244,6 +246,9 @@ if (!resp) {
if (json) {
process.stdout.write(JSON.stringify(resp, null, 2) + '\n');
} else if (resp.ok && resp.human !== undefined) {
// Server-rendered view — print verbatim.
process.stdout.write(resp.human + '\n');
} else {
const output = formatHuman(resp);
if (!resp.ok) {
@@ -449,7 +449,7 @@ export class ClaudeProvider implements AgentProvider {
yield { type: 'result', text, isError: m.is_error === true };
} else if (message.type === 'system' && (message as { subtype?: string }).subtype === 'api_retry') {
yield { type: 'error', message: 'API retry', retryable: true };
} else if (message.type === 'system' && (message as { subtype?: string }).subtype === 'rate_limit_event') {
} else if (message.type === 'rate_limit_event') {
yield { type: 'error', message: 'Rate limit', retryable: false, classification: 'quota' };
} else if (message.type === 'system' && (message as { subtype?: string }).subtype === 'compact_boundary') {
const meta = (message as { compact_metadata?: { pre_tokens?: number } }).compact_metadata;
-1
View File
@@ -6,6 +6,5 @@ The files in this directory are original design documents and developer referenc
| This directory | Documentation site |
|---|---|
| [SPEC.md](SPEC.md) | [Architecture](https://docs.nanoclaw.dev/concepts/architecture) |
| [SECURITY.md](SECURITY.md) | [Security model](https://docs.nanoclaw.dev/concepts/security) |
| [REQUIREMENTS.md](REQUIREMENTS.md) | [Introduction](https://docs.nanoclaw.dev/introduction) |
+9 -9
View File
@@ -20,7 +20,7 @@ The entire codebase should be something you can read and understand. One Node.js
### Security Through True Isolation
Instead of application-level permission systems trying to prevent agents from accessing things, agents run in actual Linux containers. The isolation is at the OS level. Agents can only see what's explicitly mounted. Bash access is safe because commands run inside the container, not on your Mac.
Instead of application-level permission systems trying to prevent agents from accessing things, agents run in actual Linux containers. The isolation is at the OS level. Agents can only see what's explicitly mounted. Bash access is safe because commands run inside the container, not on your host.
### Built for the Individual User
@@ -47,23 +47,23 @@ When people contribute, they shouldn't add "Telegram support alongside WhatsApp.
Skills we'd like to see contributed:
### Communication Channels
- `/add-signal` - Add Signal as a channel
- `/add-matrix` - Add Matrix integration
> **Note:** Telegram, Slack, Discord, Gmail, and Apple Container skills already exist. See the [skills documentation](https://docs.nanoclaw.dev/integrations/skills-system) for the full list.
None currently — Signal and Matrix have since shipped as skills.
> **Note:** Telegram, Slack, Discord, Gmail, Signal, and Matrix skills already exist. See the [skills documentation](https://docs.nanoclaw.dev/integrations/skills-system) for the full list.
---
## Vision
A personal Claude assistant accessible via messaging, with minimal custom code.
A personal AI assistant accessible via messaging, with minimal custom code.
**Core components:**
- **Claude Agent SDK** as the core agent
- **Containers** for isolated agent execution (Linux VMs)
- **Containers** for isolated agent execution (Docker)
- **Multi-channel messaging** (WhatsApp, Telegram, Discord, Slack, Gmail) — add exactly the channels you need
- **Persistent memory** per conversation and globally
- **Scheduled tasks** that run Claude and can message back
- **Scheduled tasks** executed by the agent, which can message back
- **Web access** for search and browsing
- **Browser automation** via agent-browser
@@ -93,14 +93,14 @@ A personal Claude assistant accessible via messaging, with minimal custom code.
- Sessions auto-compact when context gets too long, preserving critical information
### Container Isolation
- All agents run inside containers (lightweight Linux VMs)
- All agents run inside Docker containers
- Each agent invocation spawns a container with mounted directories
- Containers provide filesystem isolation - agents can only see mounted paths
- Bash access is safe because commands run inside the container, not on the host
- Browser automation via agent-browser with Chromium in the container
### Scheduled Tasks
- Users can ask Claude to schedule recurring or one-time tasks from any group
- Users can ask the agent to schedule recurring or one-time tasks from any group
- Tasks run as full agents in the context of the group that created them
- Tasks have access to all tools including Bash (safe in container)
- Tasks can optionally send messages to their group via `send_message` tool, or complete silently
+471 -434
View File
File diff suppressed because it is too large Load Diff
+5 -1
View File
@@ -1,5 +1,10 @@
# NanoClaw Security Model
> The canonical, continuously-verified version of this model lives at
> [docs.nanoclaw.dev/concepts/security](https://docs.nanoclaw.dev/concepts/security).
> This in-repo copy can drift; if the two disagree, verify against
> `src/container-runner.ts` (`buildMounts`).
## Trust Model
Privilege is **user-level**, persisted in the `user_roles` table (owner /
@@ -39,7 +44,6 @@ spawn. For the default (Claude) provider these are:
| `/workspace/agent/container.json` | group `container.json` | RO | Container config — readable, not writable |
| `/workspace/agent/CLAUDE.md` | composed `CLAUDE.md` | RO | Regenerated every spawn; agent edits would be clobbered |
| `/workspace/agent/.claude-fragments` | group `.claude-fragments/` | RO | Composer skill/MCP fragments |
| `/workspace/global` | `groups/global/` | RO | Shared global memory |
| `/app/CLAUDE.md` | `container/CLAUDE.md` | RO | Shared base doc imported by the composed entry point |
| `/home/node/.claude` | `data/v2-sessions/<group>/.claude-shared/` | RW | Claude state, settings, skill symlinks |
| `/app/src` | `container/agent-runner/src/` | RO | Shared agent-runner source (same for all groups) |
+2
View File
@@ -1,5 +1,7 @@
# NanoClaw Specification
> **⚠️ Historical v1 spec.** This document describes the original NanoClaw v1 architecture — the single `store/messages.db`, the file-based IPC watcher, the `task-scheduler.ts` loop, the `MAX_CONCURRENT_CONTAINERS` cap, and the `groups/{channel}_{name}/` folder convention. **None of these exist in v2.** v2 replaced them with the two-DB session split (`inbound.db`/`outbound.db`), the entity model (users → messaging groups → agent groups → sessions), and the system-action delivery path. Kept for reference only. For the current architecture start at [architecture.md](architecture.md) and the root [CLAUDE.md](../CLAUDE.md); the v1→v2 diff is in [v1-to-v2-changes.md](v1-to-v2-changes.md).
A personal Claude assistant with multi-channel support, persistent memory per conversation, scheduled tasks, and container-isolated agent execution.
---
+246 -167
View File
@@ -14,37 +14,62 @@ The boundary: the agent-runner decides **what** to send and **what to do** with
## AgentProvider Interface
Provider-wide settings (MCP servers, env, additional directories, model, effort,
assistant name) are passed to the provider **constructor** via `ProviderOptions`, not
per query. `QueryInput` carries only what changes turn to turn: the prompt, the
continuation token to resume, the working directory, and system context to inject.
```typescript
interface AgentProvider {
/** True if the SDK handles slash commands natively and wants them passed
* through raw. When false, the poll-loop formats them like any chat message. */
readonly supportsNativeSlashCommands: boolean;
/** Opt-in: scaffold a persistent memory/ tree at boot. Providers with native
* memory (Claude's CLAUDE.local.md) omit it. Never gated on a provider name. */
readonly usesMemoryScaffold?: boolean;
/** Optional. Called after each completed exchange so providers whose harness
* keeps no on-disk transcript can persist it themselves. Claude (the SDK
* writes its own .jsonl) omits this. */
onExchangeComplete?(exchange: ProviderExchange): void;
/** Start a new query. Returns a handle for streaming input and output. */
query(input: QueryInput): AgentQuery;
/** True if the error means the stored continuation is invalid (missing
* transcript, unknown session) and should be cleared. */
isSessionInvalid(err: unknown): boolean;
/** Optional pre-resume maintenance: given the stored continuation, return a
* reason string to drop it and start fresh (e.g. transcript too large/old to
* cold-resume before the host idle ceiling), or null to keep resuming. */
maybeRotateContinuation?(continuation: string, cwd: string): string | null;
}
interface ProviderOptions {
assistantName?: string;
mcpServers?: Record<string, McpServerConfig>;
env?: Record<string, string | undefined>;
additionalDirectories?: string[];
model?: string; // alias (sonnet/opus/haiku) or full model ID
effort?: string; // low | medium | high | xhigh | max
}
interface QueryInput {
/** Initial prompt (already formatted by agent-runner).
* String for text-only. ContentBlock[] for multimodal (images, PDFs, audio). */
prompt: string | ContentBlock[];
/** Initial prompt, already formatted by the agent-runner into a string. */
prompt: string;
/** Session ID to resume, if any */
sessionId?: string;
/** Opaque continuation token from a previous query. The provider decides
* what it means (session ID, thread ID, or nothing). */
continuation?: string;
/** Resume from a specific point in the session (provider-specific, may be ignored) */
resumeAt?: string;
/** Working directory inside the container */
/** Working directory inside the container. */
cwd: string;
/** MCP server configurations (normalized format — provider translates) */
mcpServers: Record<string, McpServerConfig>;
/** System prompt / developer instructions */
systemPrompt?: string;
/** Environment variables for the SDK process */
env: Record<string, string | undefined>;
/** Additional directories the agent can access */
additionalDirectories?: string[];
/** System context to inject; the provider translates it into whatever its
* SDK expects (preset append, full system prompt, per-turn injection). */
systemContext?: { instructions?: string };
}
interface McpServerConfig {
@@ -54,40 +79,42 @@ interface McpServerConfig {
}
interface AgentQuery {
/** Push a follow-up message into the active query */
/** Push a follow-up message into the active query. */
push(message: string): void;
/** Signal that no more input will be sent */
/** Signal that no more input will be sent. */
end(): void;
/** Output event stream */
/** Output event stream. */
events: AsyncIterable<ProviderEvent>;
/** Force-stop the query (e.g., container shutting down) */
/** Force-stop the query (e.g., container shutting down). */
abort(): void;
}
type ProviderEvent =
| { type: 'init'; sessionId: string }
| { type: 'result'; text: string | null }
| { type: 'init'; continuation: string }
| { type: 'result'; text: string | null; isError?: boolean }
| { type: 'error'; message: string; retryable: boolean; classification?: string }
| { type: 'progress'; message: string };
| { type: 'progress'; message: string }
| { type: 'activity' };
```
### What the interface does NOT include
- **Message formatting** — the agent-runner formats messages before passing to the provider. The provider receives a ready-to-send prompt string.
- **Hooks** — Claude-specific. The Claude provider registers hooks internally (PreCompact, PreToolUse, etc.). Other providers don't need them.
- **Tool allowlists** — Claude uses `allowedTools`. Codex uses `approvalPolicy`. OpenCode uses `permission`. Each provider configures this internally based on the same intent: "allow everything, no prompting."
- **Session persistence**Claude persists sessions to disk automatically. Codex and OpenCode manage their own session state. The agent-runner doesn't control this — it just passes `sessionId` and `resumeAt`.
- **Hooks** — Claude-specific. The Claude provider registers hooks internally (PreToolUse, PostToolUse, PreCompact). Other providers don't need them.
- **Tool allowlists** — Claude uses `allowedTools` + `disallowedTools`. Other SDKs use their own equivalents. Each provider configures this internally.
- **Session persistence**the agent-runner stores one opaque `continuation` token per provider (see [Session Resume](#session-resume)) and passes it back as `QueryInput.continuation`. What it means is provider-private; Claude persists its own `.jsonl` transcript on disk keyed by the continuation (session ID).
- **Sandbox configuration** — provider-specific. Each provider configures its own sandbox internally.
### Provider event semantics
- **`init`** — emitted once per query when the provider establishes or resumes a session. The agent-runner captures `sessionId` for future resume.
- **`result`** — emitted when the agent produces a complete response. May be emitted multiple times per query (e.g., Claude's multi-turn with subagents). The agent-runner writes each result to messages_out.
- **`error`** — emitted on failure. `retryable` indicates whether the agent-runner should retry. `classification` is optional detail (e.g., 'quota', 'auth', 'transport').
- **`init`** — emitted once per query when the provider establishes or resumes a session. The agent-runner captures `continuation` and persists it for future resume.
- **`result`** — emitted when the agent produces a complete response. May be emitted multiple times per query (e.g., Claude's multi-turn with subagents). `isError` is set when the SDK flagged the turn as an error (e.g. a non-retryable billing error) so the poll-loop still surfaces the text instead of dropping it. The agent-runner writes each result to messages_out.
- **`error`** — emitted on failure. `retryable` indicates whether the agent-runner should retry. `classification` is optional detail (e.g., 'quota').
- **`progress`** — optional, for logging. The agent-runner logs these but doesn't act on them.
- **`activity`** — a liveness signal. Providers MUST yield it on every underlying SDK event (tool call, thinking, partial message) so the poll-loop's idle timer stays honest during long tool runs.
## Provider Implementations
@@ -97,58 +124,82 @@ Only the `claude` provider ships in trunk. The Codex and OpenCode sections below
Wraps `@anthropic-ai/claude-agent-sdk`'s `query()`.
The provider takes its settings (`mcpServers`, `env`, `additionalDirectories`,
`model`, `effort`, `assistantName`) in its constructor via `ProviderOptions`; `query()`
only reads the per-turn `QueryInput`.
```typescript
class ClaudeProvider implements AgentProvider {
readonly supportsNativeSlashCommands = true;
// ...constructor stores options.mcpServers, .env, .additionalDirectories,
// .model, .effort, .assistantName...
query(input: QueryInput): AgentQuery {
const stream = new MessageStream(); // AsyncIterable<SDKUserMessage>
stream.push(input.prompt);
const sdkQuery = query({
const sdkResult = sdkQuery({
prompt: stream,
options: {
cwd: input.cwd,
resume: input.sessionId,
resumeSessionAt: input.resumeAt,
systemPrompt: input.systemPrompt
? { type: 'preset', preset: 'claude_code', append: input.systemPrompt }
additionalDirectories: this.additionalDirectories,
resume: input.continuation,
pathToClaudeCodeExecutable: '/pnpm/claude',
systemPrompt: input.systemContext?.instructions
? { type: 'preset', preset: 'claude_code', append: input.systemContext.instructions }
: undefined,
mcpServers: input.mcpServers, // already the right shape
additionalDirectories: input.additionalDirectories,
env: input.env,
allowedTools: NANOCLAW_TOOL_ALLOWLIST,
// Base tools plus one `mcp__<server>__*` pattern per registered MCP
// server — without the explicit MCP patterns the SDK's allowedTools
// filter silently drops every MCP namespace.
allowedTools: [...TOOL_ALLOWLIST, ...Object.keys(this.mcpServers).map(mcpAllowPattern)],
disallowedTools: SDK_DISALLOWED_TOOLS,
env: this.env,
model: this.model,
effort: this.effort,
permissionMode: 'bypassPermissions',
allowDangerouslySkipPermissions: true,
settingSources: ['project', 'user', 'local'],
mcpServers: this.mcpServers,
hooks: {
PreCompact: [{ hooks: [preCompactHook] }],
PreToolUse: [{ matcher: 'Bash', hooks: [sanitizeBashHook] }],
PreToolUse: [{ hooks: [preToolUseHook] }],
PostToolUse: [{ hooks: [postToolUseHook] }],
PostToolUseFailure: [{ hooks: [postToolUseHook] }],
PreCompact: [{ hooks: [createPreCompactHook(this.assistantName)] }],
},
},
});
let aborted = false;
return {
push: (msg) => stream.push(msg),
end: () => stream.end(),
abort: () => sdkQuery.close(),
events: translateClaudeEvents(sdkQuery),
// Abort doesn't call into the SDK — it flips a flag the event generator
// checks and ends the input stream so the query drains and stops.
abort: () => { aborted = true; stream.end(); },
events: translateEvents(sdkResult, () => aborted),
};
}
}
```
`translateClaudeEvents` is an async generator that maps SDK messages to `ProviderEvent`:
- `message.type === 'system' && message.subtype === 'init'``{ type: 'init', sessionId }`
- `message.type === 'result'``{ type: 'result', text }`
- `message.type === 'system' && message.subtype === 'api_retry'``{ type: 'error', retryable: true }`
- `message.type === 'system' && message.subtype === 'rate_limit_event'``{ type: 'error', retryable: false, classification: 'quota' }`
- `message.type === 'system' && message.subtype === 'task_notification'``{ type: 'progress', message }`
- Everything else → logged, not emitted
`translateEvents` is an async generator that yields `{ type: 'activity' }` for **every**
SDK message (so the idle timer stays honest) and maps recognized messages to `ProviderEvent`:
- `system`/`init``{ type: 'init', continuation: session_id }`
- `result``{ type: 'result', text, isError }``text` is `result.result`, or the joined `result.errors[]` on error subtypes (billing/quota), so the notice still reaches the user
- `system`/`api_retry``{ type: 'error', retryable: true }`
- `system`/`rate_limit_event``{ type: 'error', retryable: false, classification: 'quota' }`
- `system`/`compact_boundary``{ type: 'result', text: 'Context compacted…' }`
- `system`/`task_notification``{ type: 'progress', message }`
- when the `aborted` flag is set → the generator returns immediately
**Claude-specific features preserved inside the provider:**
- `MessageStream` for async iterable input (push-based)
- `resumeSessionAt` for resume at specific message UUID
- PreCompact hook for transcript archiving
- PreToolUse hook for sanitizing bash env vars
- Full tool allowlist
**Claude-specific behavior inside the provider:**
- `MessageStream` for async iterable input (push-based follow-ups)
- Resume via the SDK `resume` option keyed on the stored `continuation` (the SDK session ID) — no separate resume-at cursor
- `TOOL_ALLOWLIST` (Bash, Read, Write, Edit, Glob, Grep, WebSearch, WebFetch, Task, Skill, …) extended at the call site with a `mcp__<server>__*` pattern per registered MCP server; `SDK_DISALLOWED_TOOLS` blocks SDK builtins that collide with NanoClaw's own scheduling/interaction model (CronCreate/Delete/List, ScheduleWakeup, AskUserQuestion, Enter/ExitPlanMode, Enter/ExitWorktree)
- **PreToolUse hook** records the current tool + its declared timeout to `container_state` (so the host sweep widens its stuck tolerance while a long Bash runs) and, as defense-in-depth, blocks any `SDK_DISALLOWED_TOOLS` call that slips through. It does **not** sanitize bash env vars — there is no such hook.
- **PostToolUse / PostToolUseFailure** hooks clear the in-flight tool
- **PreCompact** hook archives the transcript to `conversations/` before compaction
- `maybeRotateContinuation` drops an oversized/aged transcript (default caps 12 MB / 14 days, both operator-overridable) so a cold container isn't killed reloading days of `.jsonl` before the host idle ceiling; `isSessionInvalid` clears a continuation whose transcript is gone
- `additionalDirectories` for multi-directory access
### Codex Provider
@@ -159,8 +210,8 @@ Wraps `@openai/codex-sdk`.
class CodexProvider implements AgentProvider {
query(input: QueryInput): AgentQuery {
const codex = new Codex(this.buildOptions(input));
const thread = input.sessionId
? codex.resumeThread(input.sessionId, this.threadOptions(input))
const thread = input.continuation
? codex.resumeThread(input.continuation, this.threadOptions(input))
: codex.startThread(this.threadOptions(input));
const abortController = new AbortController();
@@ -188,13 +239,13 @@ class CodexProvider implements AgentProvider {
signal: abortController.signal,
});
let sessionId: string | undefined;
let continuation: string | undefined;
let resultText = '';
for await (const event of streamed.events) {
if (event.type === 'thread.started') {
sessionId = event.thread_id;
yield { type: 'init', sessionId };
continuation = event.thread_id;
yield { type: 'init', continuation };
}
if (event.type === 'item.completed' && event.item.type === 'agent_message') {
resultText = event.item.text || resultText;
@@ -264,7 +315,7 @@ class OpenCodeProvider implements AgentProvider {
private async *run(client, server, stream, input, getPendingFollowUp): AsyncIterable<ProviderEvent> {
const session = await client.session.create();
yield { type: 'init', sessionId: session.data.id };
yield { type: 'init', continuation: session.data.id };
await client.session.promptAsync({
path: { id: session.data.id },
@@ -356,62 +407,58 @@ The agent-runner transforms messages_in rows into a prompt string. The provider
**Routing field stripping:** `platform_id`, `channel_type`, `thread_id` are never included in the prompt. They're stored as context for writing messages_out.
**Single message formatting by kind:**
Every kind renders to a single self-contained XML element. The `id` attribute is the
message's `seq` (the agent-facing message ID it passes to `edit_message` / `add_reaction`).
The `from` attribute is the origin destination name (resolved from the routing fields via
the destination map), so the agent always knows where a message came from — routing fields
themselves are never shown.
- **`chat`** — format into message XML:
- **`chat`** — one `<message>` per row:
```xml
<message sender="John" time="2024-01-01 10:00">
Check this PR
</message>
<message id="5" from="family" sender="John" time="Jan 1, 10:00 AM">Check this PR</message>
```
A reply carries a `reply_to` attribute and an inline `<quoted_message from="…">…</quoted_message>`.
- **`chat-sdk`** — extract fields from serialized Chat SDK message:
- **`chat-sdk`** — same `<message>` shape, fields extracted from the serialized Chat SDK
message. Attachments are appended inline: `[image: screenshot.png — saved to /workspace/…]`
or `[image: screenshot.png (https://signed-url…)]`. Images/PDFs that Claude handles
natively are also passed as content blocks (see Media Handling below).
- **`task`** — a `<task>` element, script output first when present:
```xml
<message sender="John (john@slack)" time="2024-01-01 10:00">
Check this PR
[image: screenshot.png — https://signed-url...]
</message>
```
Attachments are listed inline. Images/PDFs that Claude handles natively are passed as content blocks (see Media Handling below).
- **`task`** — task prompt, optionally with script output:
```
[SCHEDULED TASK]
Script output:
{"data": ...}
<task from="scheduler" time="Jan 1, 9:00 AM">Script output:
{"data": …}
Instructions:
Review open PRs
Review open PRs</task>
```
- **`webhook`** — webhook payload:
```
[WEBHOOK: github/pull_request]
{"action": "opened", "pull_request": {...}}
- **`webhook`** — a `<webhook>` element wrapping the JSON payload:
```xml
<webhook from="github" source="github" event="pull_request">{"action": "opened", …}</webhook>
```
- **`system`** — host action result (response to an earlier system request):
```
[SYSTEM RESPONSE]
Action: register_agent_group
Status: success
Result: {"agent_group_id": "ag-456"}
- **`system`** — host action result, rendered as `<system_response>`:
```xml
<system_response from="host" action="create_agent" status="success">{"agent_group_id": "ag-456"}</system_response>
```
**Batch formatting:** Multiple pending messages are combined into one prompt:
**Batch formatting:** All pending messages are combined into one prompt. The prompt opens
with a self-closing `<context timezone="<IANA>" />` header (so the agent interprets every
timestamp — and every time it schedules — in the user's zone), then the chat messages
concatenated as consecutive `<message>` blocks, then any task/webhook/system elements,
joined by blank lines:
```xml
<context timezone="America/Los_Angeles">
<messages>
<message sender="John" time="10:00">Check this PR</message>
<message sender="Jane" time="10:01">Already on it</message>
</messages>
<context timezone="America/Los_Angeles" />
<message id="2" from="family" sender="John" time="10:00">Check this PR</message>
<message id="4" from="family" sender="Jane" time="10:01">Already on it</message>
```
Mixed kinds (e.g., a chat message + a system response) are combined with clear delimiters. Each section is labeled by kind.
There is **no** outer `<messages>` envelope — an earlier revision wrapped multi-message
batches that way, but the Claude Agent SDK answered the wrapped shape with a synthetic
"No response requested." stub instead of calling the API (#2555). Dropping the wrapper made
the single-message path just the N=1 case of the same concatenation.
**Command detection:** Messages starting with `/` are checked against a command list. Recognized commands bypass formatting and are passed raw to the provider (for Claude's slash command handling) or intercepted by the agent-runner (for NanoClaw-level commands like session reset).
@@ -430,54 +477,70 @@ interface RoutingContext {
When writing messages_out (either from provider results or MCP tool calls), the agent-runner copies this routing context by default. The agent never sees routing fields — it just produces text. The routing is implicit: "respond to whoever sent the message."
MCP tools that target a different destination (e.g., `send_to_agent`, `send_message` with explicit channel) override the routing context for that specific messages_out row.
MCP tools that target a named destination (`send_message` / `send_file` with a `to`
argument) resolve routing through the session's destination map instead of the default
reply context — including agent-to-agent sends, which are just a `to` pointing at an
`agent`-type destination.
### Status Management
The agent-runner manages the `status` and `status_changed` fields on messages_in:
`inbound.db` is a read-only mount inside the container, so the agent-runner never writes
`messages_in`. It tracks processing status in the `processing_ack` table in the
container-owned `outbound.db`; the host reads `processing_ack` and mirrors completion
back onto `messages_in.status`.
```
pending → processing → completed
→ failed (if provider returns error and max retries exhausted)
processing_ack: (no row) → processing → completed
```
- **Pick up:** `UPDATE messages_in SET status = 'processing', status_changed = now(), tries = tries + 1 WHERE id IN (...)`
- **Complete:** `UPDATE messages_in SET status = 'completed', status_changed = now() WHERE id IN (...)`
- **Error:** Agent-runner does NOT set `failed` — it leaves the message as `processing`. The host detects stale processing via `status_changed` and handles retry logic (reset to pending with backoff). This keeps retry policy on the host side.
- **Pick up:** `INSERT OR REPLACE INTO processing_ack (message_id, status, status_changed) VALUES (?, 'processing', now())` for each claimed row (`markProcessing`). Pending queries skip any row already present in `processing_ack`.
- **Complete:** same upsert with `status = 'completed'` (`markCompleted`). Every consumed batch ends here — error outcomes included. On a provider error the poll-loop writes an error **chat message** to `messages_out` (so the user sees it), then still acks the batch completed; errors surface as messages, not as an ack status. (A `markFailed` helper exists in `messages-in.ts` but currently has no callers.)
- The host's `syncProcessingAcks` mirrors acked ids onto `messages_in.status = 'completed'`. Its stale/retry policy is driven off the `.heartbeat` file mtime and the `processing_ack` claim timestamps. On startup the agent-runner clears leftover `processing` acks (crash recovery) so orphaned claims re-process.
### MCP Tools
The agent-runner runs an MCP server that exposes NanoClaw tools to the agent. All tools write to the session DB.
**DB path:** The MCP server receives the session DB path via environment variable. It opens a second connection to the same SQLite file (WAL mode allows concurrent access).
The agent-runner runs an MCP server (stdio) that exposes NanoClaw tools to the agent. The
tool modules use the same two-DB connection layer as the rest of the runner
(`container/agent-runner/src/db/connection.ts`): they read the host-written `inbound.db`
at `/workspace/inbound.db` **read-only** (destinations, session routing, question
responses, task lists) and write to the container-owned `outbound.db` at
`/workspace/outbound.db`. There is no shared single-file connection and no WAL — both files
are `journal_mode=DELETE` because WAL's memory-mapped `-shm` file does not stay coherent
across the VirtioFS host↔container mount.
#### send_message
Send a chat message to the current conversation (or a specified destination).
Send a chat message to a named destination. Agents address destinations by name, never by
raw platform/channel/thread IDs — the destination map (`destinations` table in `inbound.db`,
written by the host) resolves the name to routing fields.
```typescript
{
name: 'send_message',
params: {
text: string, // message content
channel?: string, // optional: target channel type (default: reply to origin)
platformId?: string, // optional: target platform ID
threadId?: string, // optional: target thread ID
text: string, // message content (required)
to?: string, // destination name (e.g. "family", "worker-1").
// Optional when the agent has exactly one destination.
}
}
```
Implementation: write a `messages_out` row with `kind: 'chat'`. If channel/platformId/threadId are provided, use those as routing. Otherwise, copy from the current routing context.
Implementation: `resolveRouting(to)` looks up the destination. With no `to`, it defaults to
the session's own reply routing (`session_routing`); if the destination resolves to the same
channel the session is bound to, the session's `thread_id` is preserved so the reply lands
in-thread, otherwise `thread_id` is null. The tool then writes a `messages_out` row with
`kind: 'chat'` and content `{ text }`, and returns the new `seq` as the message id.
#### send_file
Send a file to the current conversation.
Send a file to a named destination (same destination model as `send_message`).
```typescript
{
name: 'send_file',
params: {
path: string, // file path (relative to /workspace/agent/ or absolute)
path: string, // file path (relative to /workspace/agent/ or absolute) (required)
to?: string, // destination name; optional if the agent has one destination
text?: string, // optional accompanying message
filename?: string, // display name (default: basename of path)
}
@@ -485,10 +548,10 @@ Send a file to the current conversation.
```
Implementation:
1. Generate a message ID
2. Create `outbox/{messageId}/` directory
3. Copy the file into the outbox directory
4. Write a `messages_out` row with `files: [filename]` in the content
1. Resolve routing via `resolveRouting(to)` (as `send_message`)
2. Generate a message ID and create `/workspace/outbox/{messageId}/`
3. Copy the file into that outbox directory
4. Write a `messages_out` row (`kind: 'chat'`) with content `{ text, files: [filename] }`
#### send_card
@@ -523,11 +586,11 @@ Send an interactive question and wait for the user's response. This is a **block
```
Implementation:
1. Generate a `questionId`
2. Write a `messages_out` row with `operation: 'ask_question'`, the question, options, and questionId
3. Poll `messages_in` for a row with matching `questionId` in content
4. When found, return the `selectedOption` as the tool result
5. If timeout expires, return a timeout error as the tool result
1. Generate a `questionId` and normalize each option to `{ label, selectedLabel, value }`
2. Write a `messages_out` row with `kind: 'chat-sdk'` and content `{ type: 'ask_question', questionId, title, question, options }`
3. Poll `inbound.db` (read-only) for a pending `messages_in` row whose content carries the matching `questionId` (`findQuestionResponse`), skipping any already in `processing_ack`
4. When found, `markCompleted` the response row (a `processing_ack` write in `outbound.db`) and return its `selectedOption` as the tool result
5. If the deadline passes, return a timeout error as the tool result
The agent's execution is paused at this tool call. The provider's query keeps running (Claude holds the tool call open). The agent-runner polls for the response in a separate loop.
@@ -563,22 +626,13 @@ Add an emoji reaction to a message.
Implementation: write a `messages_out` row with `operation: 'reaction'`.
#### send_to_agent
#### Agent-to-agent sends (no dedicated tool)
Send a message to another agent group.
```typescript
{
name: 'send_to_agent',
params: {
agentGroupId: string, // target agent group
text: string, // message content
sessionId?: string, // optional: target specific session
}
}
```
Implementation: write a `messages_out` row with `channel_type: 'agent'`, `platform_id: agentGroupId`, `thread_id: sessionId`.
There is no `send_to_agent` tool. Agents and channels share one destination namespace, so
messaging another agent is just `send_message(to="<agent-name>")` where the named
destination is of type `agent`. `resolveRouting` maps it to a `messages_out` row with
`channel_type: 'agent'` and `platform_id` set to the target agent group id; the host
validates the send and routes it into the target session's `inbound.db`.
#### schedule_task
@@ -596,7 +650,7 @@ Schedule a one-shot or recurring task.
}
```
Implementation: write a `messages_in` row (to self) with `kind: 'task'`, `process_after`, and optionally `recurrence`. The host sweep picks it up when due.
Implementation: the container can't write host-owned `inbound.db`, so this writes a `messages_out` row with `kind: 'system'` and `action: 'schedule_task'` (`container/agent-runner/src/mcp-tools/scheduling.ts`). During delivery the host's action handler (`src/modules/scheduling/actions.ts``insertTask()` in `src/modules/scheduling/db.ts`) inserts the `kind: 'task'` row into `inbound.db` with `process_after` and optionally `recurrence`. The host sweep picks it up when due.
#### list_tasks
@@ -609,7 +663,7 @@ List active scheduled/recurring tasks.
}
```
Implementation: query `messages_in WHERE recurrence IS NOT NULL AND status != 'failed'`.
Implementation: a read, not a write — the container may read the read-only `inbound.db` mount directly. Returns one row per series (the live pending/paused occurrence): `SELECT series_id AS id, ... FROM messages_in WHERE kind = 'task' AND status IN ('pending','paused') GROUP BY series_id`. See `container/agent-runner/src/mcp-tools/scheduling.ts`.
#### cancel_task / pause_task / resume_task / update_task
@@ -625,27 +679,44 @@ Modify a scheduled task.
// update_task: merge { prompt?, recurrence?, processAfter?, script? } into the live row
```
Implementation: cancel/pause/resume update the live row(s) directly. update_task is sent as a system action — the host reads current content, merges supplied fields, and writes back. All four match by `(id = ? OR series_id = ?) AND kind='task' AND status IN ('pending','paused')`, so they reach the live next occurrence of a recurring task even when the agent passes the original (now-completed) id.
Implementation: all four are sent as system actions (`messages_out`, `kind: 'system'`, `action: 'cancel_task' | 'pause_task' | 'resume_task' | 'update_task'`) — the container never writes `inbound.db`. The host's handlers in `src/modules/scheduling/actions.ts` apply the change against `inbound.db` via `src/modules/scheduling/db.ts`: cancel/pause/resume flip status on the live row(s); update_task reads current content, merges supplied fields, and writes back. All four match by `(id = ? OR series_id = ?) AND kind='task' AND status IN ('pending','paused')`, so they reach the live next occurrence of a recurring task even when the agent passes the original (now-completed) id.
#### register_agent_group
#### create_agent
Register a new agent group (admin only).
Create a long-lived companion sub-agent. The `name` becomes a destination the creating
agent can address. (There is no `register_agent_group` tool — this replaced it.)
```typescript
{
name: 'register_agent_group',
name: 'create_agent',
params: {
name: string,
folder: string,
platformId: string, // messaging group to wire to
channelType: string,
triggerRules?: object,
sessionMode?: 'shared' | 'per-thread',
name: string, // human-readable name; also the destination name (required)
instructions?: string, // CLAUDE.md content for the new agent (role, personality)
}
}
```
Implementation: write a `messages_out` row with `kind: 'system'`, `action: 'register_agent_group'`. The host reads, validates admin permission, creates the entity rows in the central DB, and writes a `system` messages_in response.
Implementation: fire-and-forget. Writes a `messages_out` row with `kind: 'system'`,
`action: 'create_agent'`, `requestId`, `name`, and `instructions`. The container is
untrusted and does not gate itself; the host authorizes by CLI scope — trusted owner groups
(scope `global`) create directly, confined groups require admin approval
(`src/modules/agent-to-agent/create-agent.ts`) — then creates the entity rows and notifies
the agent via a chat message when the agent is ready.
#### Self-modification: install_packages, add_mcp_server
Two fire-and-forget system-action tools let an agent extend its own runtime (both require
admin approval, applied host-side):
- **`install_packages`** — `{ apt?: string[], npm?: string[], reason?: string }`. Package
names are validated at the tool boundary and re-validated on the host. On approval the
host rebuilds the per-agent image and restarts the container.
- **`add_mcp_server`** — `{ name, command, args?, env? }`. Wires an existing third-party MCP
server into the agent's `container.json`; on approval the host updates the config and
restarts (no rebuild — Bun runs the TS directly).
Both write a `messages_out` row with `kind: 'system'` and the matching `action`, then return
immediately; the host notifies the agent when approval resolves.
### Media Handling
@@ -701,20 +772,28 @@ Archive location: `/workspace/agent/conversations/{date}-{summary}.md`
### Session Resume
The agent-runner tracks `sessionId` and `resumeAt` across queries:
The agent-runner tracks a single opaque `continuation` token per provider:
- `sessionId` — captured from `ProviderEvent { type: 'init' }`. Passed back to `QueryInput.sessionId` on the next query.
- `resumeAt` — Claude-specific (last assistant message UUID). Stored by the agent-runner, passed to `QueryInput.resumeAt`. Providers that don't support this ignore it.
- Captured from `ProviderEvent { type: 'init', continuation }` and persisted to the
`session_state` table in `outbound.db` under the key `continuation:<provider>` (keyed per
provider because a continuation is provider-private — a Claude session id is meaningless to
another provider).
- Passed back as `QueryInput.continuation` on the next query. For Claude that becomes the
SDK `resume` option; the SDK reloads its on-disk `.jsonl` transcript for that session id.
These are ephemeral to the container's lifetime. When the container is killed and restarted, the host passes the stored `sessionId` from the central DB's sessions table. `resumeAt` is lost on container restart (the provider resumes from the end of the session).
Because it lives in the session folder's `outbound.db`, the continuation survives container
teardown and restart — a fresh container reads it back and resumes. `/clear` deletes the row
to start a clean session. Before resuming, `maybeRotateContinuation` may archive and drop an
oversized/aged transcript (so a cold container isn't killed reloading it), and
`isSessionInvalid` clears a continuation whose backing transcript has gone missing.
### Container Startup
The agent-runner receives configuration via:
- **Environment variables:** `AGENT_PROVIDER` (claude/codex/opencode), `NANOCLAW_ADMIN_USER_ID`, provider-specific vars (API keys, model overrides), `TZ`
- **Fixed mount paths:** Session DB at `/workspace/session.db`. Agent group folder at `/workspace/agent/`. System prompt from `/workspace/agent/CLAUDE.md` and `/workspace/global/CLAUDE.md`.
- **Optional startup config:** Some config may be passed as a JSON file at a fixed path (e.g., `/workspace/config.json`) for things like the session ID to resume, assistant name, and admin user ID. This avoids overloading environment variables.
- **`container.json`:** The provider name, model, assistant name, MCP servers, and other NanoClaw config are read from `/workspace/agent/container.json` (materialized by the host from the `container_configs` table), not from environment variables. See `container/agent-runner/src/config.ts`.
- **Environment variables:** provider-specific vars only (API keys, model overrides), `TZ`.
- **Fixed mount paths:** Host-written `inbound.db` (read-only) at `/workspace/inbound.db` and container-owned `outbound.db` at `/workspace/outbound.db`. Agent group folder at `/workspace/agent/`. System prompt from `/workspace/agent/CLAUDE.md` and `/workspace/global/CLAUDE.md`.
The agent-runner reads config, creates the provider, and enters the poll loop. No stdin, no initial prompt — messages are already in the session DB.
@@ -731,7 +810,7 @@ function createProvider(name: ProviderName, config: ProviderConfig): AgentProvid
}
```
The provider name comes from the container's environment (`AGENT_PROVIDER` env var), set by the host based on `agent_groups.agent_provider` or `sessions.agent_provider`.
The provider name comes from the `provider` key in `/workspace/agent/container.json` (defaulting to `'claude'`), which the host materializes from the `container_configs` table — set it with `ncl groups config update --provider`. It is not an environment variable.
`ProviderConfig` contains provider-specific settings (API keys, model overrides, etc.) passed via environment variables — not via the interface. Each provider reads what it needs from `env`.
+4 -2
View File
@@ -13,6 +13,8 @@ interface ChannelSetup {
// Host callbacks
onInbound(platformId: string, threadId: string | null, message: InboundMessage): void;
// Admin-transport adapters (e.g. CLI) route to an arbitrary channel via this instead of onInbound
onInboundEvent(event: InboundEvent): void;
onMetadata(platformId: string, name?: string, isGroup?: boolean): void;
}
@@ -34,7 +36,7 @@ interface ChannelAdapter {
isConnected(): boolean;
// Outbound delivery
deliver(platformId: string, threadId: string | null, message: OutboundMessage): Promise<void>;
deliver(platformId: string, threadId: string | null, message: OutboundMessage): Promise<string | undefined>;
// Optional
setTyping?(platformId: string, threadId: string | null): Promise<void>;
@@ -307,7 +309,7 @@ function createWhatsAppChannel(): ChannelAdapter {
**Ask user question:**
```json
{
"operation": "ask_question",
"type": "ask_question",
"questionId": "q-123",
"title": "Failing Test",
"question": "How should we handle the failing test?",
+4 -4
View File
@@ -311,7 +311,6 @@ erDiagram
string name
string folder
string agent_provider
json container_config
}
messaging_groups {
int id
@@ -344,14 +343,15 @@ erDiagram
int messaging_group_id
int agent_group_id
string session_mode
json trigger_rules
string engage_mode "pattern | mention | mention-sticky"
string sender_scope "all | known"
int priority
}
sessions {
int id
int agent_group_id
int messaging_group_id
string sdk_session_id
string thread_id
string status
}
</pre>
@@ -391,7 +391,7 @@ flowchart LR
Container -->|writes · odd seq| Out
Container -->|touch every poll| HB
HostSweep[Host sweep] -->|stat mtime| HB
HostSweep -->|reads processing_ack| In
HostSweep -->|reads processing_ack| Out
</pre>
</div>
</section>
+9 -9
View File
@@ -28,18 +28,18 @@ flowchart TB
Approvals["configureManualApproval<br/>-> pending_approvals"]
end
subgraph Session["Per-Session Container (Docker / Apple Container)"]
subgraph Session["Per-Session Container (Docker)"]
direction TB
PollLoop["Poll Loop<br/>(container/agent-runner)"]
Provider["Agent providers<br/>(claude, opencode; todo: codex)"]
Provider["Agent providers<br/>(claude — the only one registered in trunk;<br/>opencode ships via the /add-opencode skill)"]
MCP["MCP Tools<br/>send_message, send_file, edit_message,<br/>add_reaction, send_card, ask_user_question,<br/>schedule_task, create_agent,<br/>install_packages, add_mcp_server"]
Skills["Container Skills<br/>(container/skills/)"]
InDB[("inbound.db<br/>host writes<br/>even seq<br/>messages_in<br/>destinations<br/>processing_ack")]
OutDB[("outbound.db<br/>container writes<br/>odd seq<br/>messages_out<br/>heartbeat file")]
InDB[("inbound.db<br/>host writes<br/>even seq<br/>messages_in<br/>delivered<br/>destinations<br/>session_routing")]
OutDB[("outbound.db<br/>container writes<br/>odd seq<br/>messages_out<br/>processing_ack<br/>session_state<br/>container_state<br/>heartbeat file")]
end
subgraph Groups["Agent Group Filesystem (groups/*)"]
Folder["CLAUDE.md<br/>memory<br/>per-group skills<br/>container_config"]
Folder["CLAUDE.md<br/>memory<br/>per-group skills<br/>container.json (materialized from container_configs)"]
end
P1 & P2 & P3 & P4 & P5 --> Bridge
@@ -140,7 +140,6 @@ erDiagram
string name
string folder
string agent_provider
json container_config
}
messaging_groups {
int id
@@ -173,14 +172,15 @@ erDiagram
int messaging_group_id
int agent_group_id
string session_mode "agent-shared | shared | per-thread"
json trigger_rules
string engage_mode "pattern | mention | mention-sticky"
string sender_scope "all | known"
int priority
}
sessions {
int id
int agent_group_id
int messaging_group_id
string sdk_session_id
string thread_id
string status
}
```
@@ -209,7 +209,7 @@ flowchart LR
Container -->|"writes only<br/>(odd seq)"| Out
Container -->|touch every poll| HB
HostSweep[Host sweep] -->|stat mtime| HB
HostSweep -->|reads processing_ack| In
HostSweep -->|reads processing_ack| Out
note1["Each file has exactly ONE writer.<br/>Eliminates SQLite cross-process write contention.<br/>Collision-free seq numbering."]
```
+171 -103
View File
@@ -1,8 +1,20 @@
# NanoClaw Architecture (Draft)
> **Draft — design intent, not a line-by-line spec.** Some passages predate the current implementation and can drift from it. The root [CLAUDE.md](../CLAUDE.md) and the cited source files (`src/`, `container/agent-runner/src/`) are the source of truth; when this doc and the code disagree, trust the code. Notably, scheduling MCP tools do **not** write `inbound.db` directly — they emit `messages_out` system actions that the host applies (see [agent-runner-details.md](agent-runner-details.md) and `src/modules/scheduling/`).
## Core Idea
Each agent session has a mounted SQLite DB. The DB is the one and only IO mechanism between host and container. No IPC files, no stdin piping. Two tables: messages_in (host → agent-runner) and messages_out (agent-runner → host). Everything is a message.
Each agent session has a **pair** of mounted SQLite DBs. They are the one and only IO
mechanism between host and container. No IPC files, no stdin piping. `inbound.db` carries
host → agent-runner messages (`messages_in`); `outbound.db` carries agent-runner → host
messages (`messages_out`) plus the container's processing acks. Everything is a message.
The split exists so each file has exactly one writer: the host writes `inbound.db` (the
container opens it read-only) and the container writes `outbound.db` (the host opens it
read-only). One writer per file means no cross-process lock contention over the
host↔container mount. Both files run `journal_mode=DELETE`, **not** WAL: WAL's memory-mapped
`-shm` coherency does not propagate across VirtioFS, so a WAL reader in the guest would
freeze on an early snapshot and never see new host writes.
## Two-Level DB
@@ -11,15 +23,18 @@ Each agent session has a mounted SQLite DB. The DB is the one and only IO mechan
- Maps platform IDs → agent groups → sessions
- Channel adapters don't touch this directly — the host does the lookup
**Per-session DB (mounted into container):**
- messages_in (written by host, read by agent-runner)
- messages_out (written by agent-runner, read by host)
- Everything is a message: chat, tasks, webhooks, system actions, agent-to-agent — all use these two tables
- One DB per session, not per agent group
**Per-session DBs (mounted into container):**
- `inbound.db``messages_in` (written by host, read-only in container) plus host-written
lookup tables the container reads live: `destinations`, `session_routing`, `delivered`
- `outbound.db``messages_out` (written by agent-runner, read by host) plus
`processing_ack`, `session_state`, and `container_state` (all container-owned)
- Everything is a message: chat, tasks, webhooks, system actions, agent-to-agent — all use
`messages_in` / `messages_out`
- One pair per session, not per agent group
## Agent Groups vs Sessions
An agent group has its own filesystem — folder, CLAUDE.md, skills, container config. Multiple sessions can share the same agent group (same filesystem, same skills) but each session gets its own DB mounted at a known path. Each session = a separate container with the same agent group's filesystem but a different session DB.
An agent group has its own filesystem — folder, CLAUDE.md, skills, container config. Multiple sessions can share the same agent group (same filesystem, same skills) but each session gets its own `inbound.db`/`outbound.db` pair mounted at known paths. Each session = a separate container with the same agent group's filesystem but a different DB pair.
## Message Flow
@@ -28,13 +43,13 @@ Platform event
→ Channel adapter (trigger check, ID extraction)
→ Returns: { platformChannelId, platformThreadId, triggered }
→ Host maps platformChannelId + platformThreadId → agent group + session
→ Host writes message to session's DB
→ Host writes messages_in row to the session's inbound.db
→ Host calls wakeUpAgent(session)
→ Container spins up (or is already running)
→ Agent-runner polls its session DB, finds new messages
→ Agent-runner processes with Claude
→ Agent-runner writes response to session DB
→ Host polls active session DBs for responses
→ Agent-runner polls inbound.db (read-only), finds new messages
→ Agent-runner processes with the configured provider
→ Agent-runner writes response to messages_out in outbound.db
→ Host polls active sessions' outbound.db for responses
→ Host reads response, looks up conversation, delivers through channel adapter
```
@@ -128,9 +143,8 @@ Non-Chat-SDK channels (WhatsApp via Baileys, Gmail, custom integrations) impleme
The host is an orchestrator:
1. **Spawn** — when wakeUpAgent is called and no container exists for the session
2. **Idle kill** — when a container has no unprocessed messages for some timeout period
3. **Limits** — MAX_CONCURRENT_CONTAINERS caps active containers
When a container spins up, the agent-runner immediately starts polling its session DB. Messages are already there waiting.
When a container spins up, the agent-runner immediately starts polling `inbound.db`. Messages are already there waiting.
## Media Handling
@@ -184,50 +198,66 @@ Dedup is the channel adapter's responsibility. Chat SDK handles this internally.
## Session DB Schema
Two tables. JSON blobs for content — schema-free, format varies by `kind`.
Split across the two files. JSON blobs for content — schema-free, format varies by `kind`.
`seq` is a global ordering counter with a **disjoint parity**: the host writes even seqs to
`messages_in`, the container writes odd seqs to `messages_out`. Each side reads the other's
MAX(seq) to pick its next value, so seq is a single monotonic message id across both tables —
which is why the agent-facing message id it returns from `send_message` (and accepts in
`edit_message` / `add_reaction`) is unambiguous.
```sql
-- Host writes, agent-runner reads
-- inbound.db — host writes, container opens read-only
CREATE TABLE messages_in (
id TEXT PRIMARY KEY,
seq INTEGER UNIQUE, -- even (host-assigned)
kind TEXT NOT NULL, -- 'chat' | 'chat-sdk' | 'task' | 'webhook' | 'system'
timestamp TEXT NOT NULL,
status TEXT DEFAULT 'pending', -- 'pending' | 'processing' | 'completed' | 'failed'
status_changed TEXT, -- ISO timestamp of last status change
status TEXT DEFAULT 'pending', -- host-owned; the host mirrors the container's
-- processing_ack terminal states onto this column
process_after TEXT, -- ISO timestamp. NULL = process immediately.
recurrence TEXT, -- cron expression. NULL = one-shot.
series_id TEXT, -- groups a recurring task's occurrences
tries INTEGER DEFAULT 0, -- number of processing attempts
-- routing (agent-runner copies to messages_out; agent never sees these)
platform_id TEXT,
trigger INTEGER NOT NULL DEFAULT 1, -- 0 = accumulated context (don't wake), 1 = wake
platform_id TEXT, -- routing (stripped before the agent sees content)
channel_type TEXT,
thread_id TEXT,
-- payload (structure depends on kind)
content TEXT NOT NULL -- JSON blob
content TEXT NOT NULL, -- JSON blob (structure depends on kind)
source_session_id TEXT, -- a2a return path: source session that emitted the trigger
on_wake INTEGER NOT NULL DEFAULT 0 -- 1 = only deliver on a container's first poll
);
-- Agent-runner writes, host reads
-- outbound.db — container writes, host opens read-only
CREATE TABLE messages_out (
id TEXT PRIMARY KEY,
in_reply_to TEXT, -- references messages_in.id (optional)
seq INTEGER UNIQUE, -- odd (container-assigned)
in_reply_to TEXT, -- references messages_in.id (optional)
timestamp TEXT NOT NULL,
delivered INTEGER DEFAULT 0,
deliver_after TEXT, -- ISO timestamp. NULL = deliver immediately.
recurrence TEXT, -- cron expression. NULL = one-shot.
-- routing (default: copied from messages_in by agent-runner)
kind TEXT NOT NULL, -- 'chat' | 'chat-sdk' | 'task' | 'webhook' | 'system'
platform_id TEXT,
deliver_after TEXT, -- ISO timestamp. NULL = deliver immediately.
recurrence TEXT, -- cron expression. NULL = one-shot.
kind TEXT NOT NULL, -- copied from messages_in by default
platform_id TEXT, -- routing (default: copied from messages_in)
channel_type TEXT,
thread_id TEXT,
-- payload (format matches kind)
content TEXT NOT NULL -- JSON blob
content TEXT NOT NULL -- JSON blob (format matches kind)
);
-- outbound.db — container's processing status (it can't write inbound.db).
-- Host reads this to drive the message lifecycle; stale 'processing' rows are
-- cleared on container startup (crash recovery).
CREATE TABLE processing_ack (
message_id TEXT PRIMARY KEY, -- references messages_in.id
status TEXT NOT NULL, -- 'processing' | 'completed' | 'failed'
status_changed TEXT NOT NULL
);
```
Delivery is tracked host-side in a `delivered` table in `inbound.db` (not a column on
`messages_out`, which the host can't write). `inbound.db` also holds the host-written
`destinations` and `session_routing` tables the container reads live; `outbound.db` also
holds `session_state` (the resume continuation, per provider) and `container_state`
(current tool in flight).
### Scheduling
One-shot and recurring tasks use the same tables — no separate scheduler.
@@ -236,15 +266,15 @@ One-shot and recurring tasks use the same tables — no separate scheduler.
**Recurring:** Same, plus a `recurrence` cron expression. After the host marks a row as handled/delivered, if `recurrence` is set, it inserts a new row with `process_after`/`deliver_after` advanced to the next cron occurrence. Next time is computed from the scheduled time (not wall clock) to prevent drift.
**Host sweep** (every ~60s across all session DBs):
- `messages_in WHERE status = 'pending' AND (process_after IS NULL OR process_after <= now())` → wake agent
- `messages_in WHERE status = 'processing' AND status_changed < (now - stale_threshold)` → stale detection, increment tries, reset to pending with backoff
- `messages_out WHERE delivered = 0 AND (deliver_after IS NULL OR deliver_after <= now())` → deliver
**Host sweep** (every ~60s across all sessions):
- `inbound.db``messages_in WHERE status = 'pending' AND (process_after IS NULL OR process_after <= now())` → wake agent
- A `processing_ack` (in `outbound.db`) whose claim, or the `.heartbeat` mtime, is older than the stale threshold → stale detection, increment tries, reschedule `process_after` with backoff
- `outbound.db` → due `messages_out` rows not yet in the host's `delivered` table (in `inbound.db`) → deliver
- After completing/delivering a row with `recurrence`, insert next occurrence
**Active container poll** (~1s) checks the same conditions but only for sessions with running containers.
**Agent-runner creates schedules** by writing messages_in (to itself) or messages_out (reminders/notifications) with `process_after` and optionally `recurrence`.
**Agent-runner creates schedules** by emitting a `messages_out` row with `kind: 'system'` and an `action` (`schedule_task`, `cancel_task`, …) — it cannot write host-owned `inbound.db` directly. The host applies the action during delivery (`src/modules/scheduling/actions.ts`), inserting/updating the `kind: 'task'` `messages_in` row with `process_after` and optionally `recurrence`.
### messages_in content by kind
@@ -331,7 +361,7 @@ Two patterns, both handled at the host level:
In both cases, the approval and action execution happen on the host side, not the agent side.
**Approval routing:** Privilege is a user-level concept. `user_roles` records `owner` (global only — first user to pair becomes owner) and `admin` (global or scoped to a specific `agent_group_id`). When an action requires approval, `pickApprover(agentGroupId)` returns candidates in order: scoped admins for that agent group → global admins → owners (deduplicated). `pickApprovalDelivery` then takes the first candidate reachable via `ensureUserDm` (with a same-channel-kind tie-break so a Discord approval request prefers a Discord-using approver). The approval card lands in the approver's DM messaging group, not the origin chat. Delivery is resolved through the Chat SDK's `openDM` for resolution-required channels (Discord/Slack/…) or the user's handle directly for direct-addressable channels (Telegram/WhatsApp/…), and the mapping is cached in `user_dms` for subsequent requests. See `src/access.ts`, `src/user-dm.ts`.
**Approval routing:** Privilege is a user-level concept. `user_roles` records `owner` (global only — first user to pair becomes owner) and `admin` (global or scoped to a specific `agent_group_id`). When an action requires approval, `pickApprover(agentGroupId)` returns candidates in order: scoped admins for that agent group → global admins → owners (deduplicated). `pickApprovalDelivery` then takes the first candidate reachable via `ensureUserDm` (with a same-channel-kind tie-break so a Discord approval request prefers a Discord-using approver). The approval card lands in the approver's DM messaging group, not the origin chat. Delivery is resolved through the Chat SDK's `openDM` for resolution-required channels (Discord/Slack/…) or the user's handle directly for direct-addressable channels (Telegram/WhatsApp/…), and the mapping is cached in `user_dms` for subsequent requests. See `src/modules/permissions/access.ts` and `src/modules/permissions/user-dm.ts` (`ensureUserDm`); the approver-picking primitives live in `src/modules/approvals/primitive.ts`.
**Editing a sent message:**
@@ -408,14 +438,16 @@ This is documented as a pattern, not a built-in feature.
## Design Decisions
**Session DB location:** Not in the agent group folder. Separate directory (e.g., `sessions/{session_id}/`). Each session gets its own folder containing `session.db` and the Claude SDK's `.claude/` directory. The session identity IS the folder — no need to track Claude SDK session IDs.
**Session DB location:** Not in the agent group folder. Separate directory (e.g., `sessions/{session_id}/`). Each session gets its own folder containing `inbound.db`, `outbound.db`, and — when using the claude provider — the SDK's `.claude/` directory. The session identity IS the folder. The SDK's resume token (session id) is persisted in `outbound.db`'s `session_state` table, so a fresh container picks the conversation back up without the host tracking it centrally.
**Container mount structure:**
```
/workspace/ ← mount: session folder (read-write)
.claude/ ← Claude SDK session data (auto-created)
session.db ← session SQLite DB
.claude/ ← Claude SDK session data / transcripts (auto-created)
inbound.db ← host writes, container reads (opened read-only)
outbound.db ← container writes, host reads (opened read-only)
.heartbeat ← container touches this; host watches its mtime
outbox/ ← agent-runner writes outbound files here
agent/ ← mount: agent group folder (nested, read-write)
CLAUDE.md ← agent instructions
@@ -423,11 +455,17 @@ This is documented as a pattern, not a built-in feature.
... working files
```
Two directory mounts: session folder at `/workspace`, agent group folder at `/workspace/agent/`. The agent-runner CDs into `/workspace/agent/` to run the agent. Claude SDK writes `.claude/` at `/workspace/.claude/` (root of the workspace). The session DB is at `/workspace/session.db`.
Two directory mounts: session folder at `/workspace`, agent group folder at `/workspace/agent/`. The agent-runner CDs into `/workspace/agent/` to run the agent. Claude SDK writes `.claude/` at `/workspace/.claude/` (root of the workspace).
This works on both Docker (nested bind mounts) and Apple Container (directory mounts only — no file-level mounts, but nested directory mounts are supported).
The runtime is Docker (`src/container-runtime.ts` hardcodes the `docker` binary); nested bind mounts make this layout straightforward. The layout deliberately sticks to directory mounts (no file-level mounts) so it stays portable to runtimes that only support directory mounts.
**Session DB concurrent access:** The host writes messages_in, the agent-runner writes messages_out. Both access the same SQLite file simultaneously. WAL mode handles this — SQLite allows concurrent readers, and the two sides write to different tables so writer contention is minimal. The host enables WAL mode when creating the session DB.
**Cross-mount DB access:** The two files exist precisely so each has a single writer — the
host writes `inbound.db`, the container writes `outbound.db` — which removes writer
contention across the mount. Both files use `journal_mode=DELETE`, **not** WAL: WAL keeps its
index in a memory-mapped `-shm` file, and VirtioFS does not propagate that mmap coherency
from host to guest, so a WAL reader in the container would freeze on an early snapshot and
silently never see new host writes. Readers that must see fresh host writes promptly (the
`messages_in` poll) open `inbound.db` with `mmap_size = 0` to bypass SQLite's page cache.
**Session management:** Host-managed. The host creates session folders and mounts them. The container only sees its own session folder.
@@ -438,7 +476,7 @@ This works on both Docker (nested bind mounts) and Apple Container (directory mo
3. More messages arrive before container starts → host finds the existing session, writes to the same session DB
4. Container starts, mounts the folder, agent-runner finds messages waiting
The central DB session row creation is the serialization point. No Claude SDK session ID to coordinate — the SDK discovers its own session data in `.claude/` when the agent runs.
The central DB session row creation is the serialization point. No provider session ID to coordinate — the SDK discovers its own session data in `.claude/` when the agent runs.
**System actions:** The agent uses MCP tools (register group, reset session, schedule task, etc.). The agent-runner handles these tool calls and writes a structured, deterministic messages_out row with `kind: 'system'`. This is not natural language — it's a programmatic, structured payload that the host processes deterministically. Host validates permissions, executes, and writes the result back as a `system` messages_in row.
@@ -448,7 +486,9 @@ The central DB session row creation is the serialization point. No Claude SDK se
### Output Delivery
NanoClaw does not stream tokens to users. The Claude Agent SDK's `query()` yields complete results. The agent-runner writes one complete message to messages_out per result. The host delivers complete messages to channels.
NanoClaw does not stream tokens to users. The provider's query interface yields complete results, but a result's text is not delivered as-is: the agent-runner parses it for `<message to="name">...</message>` blocks (`dispatchResultText` in poll-loop.ts) and writes one messages_out row per block, addressed to that destination with its thread context resolved per destination. Everything outside a block — including `<internal>...</internal>` — is scratchpad: logged, never sent. A block naming an unknown destination is dropped into the scratchpad log.
If a result produced text but no valid block, the agent-runner pushes a one-time `<system>` nudge into the live turn asking the agent to re-wrap its response. The exception is a non-retryable error result (e.g. a billing error) with no envelope, which is delivered as an error notice instead of being dropped as scratchpad. Mid-turn interim updates go out through the `send_message` MCP tool; the final-text envelope parsing is how a turn's reply reaches the user. The host delivers complete messages_out rows to channels.
Message editing is supported as an explicit operation (agent calls an `edit_message` tool), not as a streaming mechanism.
@@ -456,21 +496,30 @@ Typing indicators: host sets typing when a container is active for a session, cl
### Message Batching
When multiple messages arrive while the container is down, they accumulate as `handled = 0` rows in messages_in. When the container wakes up, the agent-runner queries all unhandled messages and processes them as a batch — multiple messages are formatted into a single `<messages>` XML block.
When multiple messages arrive while the container is down, they accumulate as `status = 'pending'` rows in `messages_in`. When the container wakes up, the agent-runner reads all pending messages (those not yet in `processing_ack`) and processes them as a batch — formatted as a `<context timezone="…" />` header followed by the messages concatenated as consecutive `<message>` blocks. (There is no `<messages>` wrapper element; see [agent-runner-details.md](agent-runner-details.md#message-formatting).)
### Message Lifecycle
```
pending → processing → completed
→ failed (after max retries)
messages_in.status: pending ──────────► completed (mirrored from ack)
└─────────► failed (host-set, retries exhausted)
processing_ack.status: processing → completed
```
- **pending**: Written by host. Ready to be picked up (if `process_after` is null or past).
- **processing**: Agent-runner sets this when it picks up the message. `status_changed` is set to now. Prevents other polls from re-picking the same message.
- **completed**: Agent-runner sets this after successful processing.
- **failed**: Set after max retries exhausted.
Because `inbound.db` is read-only in the container, the agent-runner never mutates
`messages_in.status`. It records lifecycle in `processing_ack` (in `outbound.db`); the host
reads that and mirrors completion back.
**Stale detection**: If a message is `processing` but `status_changed` is too old (e.g., >10 minutes), the host assumes the container crashed. It resets the message to `pending`, increments `tries`, and sets `process_after` with exponential backoff.
- **pending**: Host writes the `messages_in` row. Ready to be picked up (if `process_after` is null or past).
- **processing**: Agent-runner upserts a `processing_ack` row (`status = 'processing'`) when it claims the message. Subsequent polls skip any id already in `processing_ack`, so it isn't re-picked.
- **completed**: Agent-runner sets `processing_ack.status = 'completed'` for **every** consumed batch, error outcomes included — a provider error is surfaced to the user as an error chat message in `messages_out`, then the batch is still acked completed. The host's `syncProcessingAcks` copies it onto `messages_in.status`.
- **failed**: Set by the **host** (sweep's `markMessageFailed`) when retries are exhausted — never by the container.
**Liveness / stale detection**: The container touches a `/workspace/.heartbeat` file rather
than writing the DB. The host sweep watches that mtime (widening its tolerance when
`container_state` shows a long-declared Bash running) to decide a container has crashed, then
increments `tries` and reschedules `process_after` with exponential backoff. On the next
container startup, leftover `processing` acks are cleared so orphaned claims re-process.
### Error Handling and Retries
@@ -555,7 +604,7 @@ const DISCORD_TOKEN = process.env.DISCORD_BOT_TOKEN;
const GMAIL_CREDS = process.env.GMAIL_CREDENTIALS_PATH;
```
Shared config (DATA_DIR, TIMEZONE, MAX_CONCURRENT_CONTAINERS) stays in `config.ts`. Channel/skill-specific config stays in the module that uses it.
Shared config (DATA_DIR, TIMEZONE) stays in `config.ts`. Channel/skill-specific config stays in the module that uses it.
### Code Style
@@ -594,13 +643,15 @@ src/db/
- **No inline ALTER TABLE.** A migration runner with a `schema_version` table replaces `try { ALTER TABLE } catch { /* exists */ }` blocks. On startup, it checks the current version and applies pending migrations in order. Each migration is a function: `(db: Database) => void`.
- **Skills add migrations.** A skill that needs a new column adds a new numbered migration file. No conflicts with other skills' migrations as long as numbers don't collide (use timestamps or high-enough numbers for skill branches).
**Agent-runner session DB** uses the same pattern but lighter — no migrations needed since session DBs are created fresh by the host:
**Agent-runner session DBs** use the same pattern but lighter — no migrations needed since the DB files are created fresh by the host:
```
container/agent-runner/src/db/
connection.ts ← open session.db at fixed path, WAL mode
messages-in.ts ← read pending, update status
messages-out.ts ← write results, outbox queries
connection.ts ← open inbound.db (read-only) + outbound.db (DELETE mode) at fixed paths
messages-in.ts ← read pending from inbound.db, ack via processing_ack in outbound.db
messages-out.ts ← write results/outbox rows to outbound.db (odd seq)
session-state.ts ← resume continuation, keyed per provider
session-routing.ts ← read the host-written default reply routing
index.ts ← barrel
```
@@ -663,9 +714,13 @@ CREATE TABLE agent_groups (
name TEXT NOT NULL,
folder TEXT NOT NULL UNIQUE,
agent_provider TEXT, -- default for sessions (null = system default)
container_config TEXT, -- JSON: { additionalMounts, timeout }
created_at TEXT NOT NULL
);
-- Container config is NOT a column here — it lives in a separate container_configs
-- table (migration 014), keyed by agent_group_id, with columns: provider, model,
-- effort, image_tag, assistant_name, max_messages_per_prompt, cli_scope, and JSON
-- columns skills / mcp_servers / packages_apt / packages_npm / additional_mounts.
-- The host materializes it into /workspace/agent/container.json for the container.
-- Platform groups/channels (WhatsApp group, Slack channel, Discord channel, email thread, etc.)
-- One row per chat PER ADAPTER INSTANCE. instance defaults to channel_type
@@ -720,16 +775,21 @@ CREATE TABLE user_dms (
PRIMARY KEY (user_id, channel_type)
);
-- Which agent groups handle which messaging groups, with what rules
-- Which agent groups handle which messaging groups, with what rules.
-- The opaque trigger_rules JSON + response_scope enum were replaced (migration
-- 010) by four orthogonal axes:
CREATE TABLE messaging_group_agents (
id TEXT PRIMARY KEY,
messaging_group_id TEXT NOT NULL REFERENCES messaging_groups(id),
agent_group_id TEXT NOT NULL REFERENCES agent_groups(id),
trigger_rules TEXT, -- JSON: { pattern, mentionOnly, excludeSenders, includeSenders }
response_scope TEXT DEFAULT 'all', -- 'all' | 'triggered' | 'allowlisted'
session_mode TEXT DEFAULT 'shared', -- 'shared' | 'per-thread'
priority INTEGER DEFAULT 0, -- higher = checked first when multiple agents match
created_at TEXT NOT NULL,
id TEXT PRIMARY KEY,
messaging_group_id TEXT NOT NULL REFERENCES messaging_groups(id),
agent_group_id TEXT NOT NULL REFERENCES agent_groups(id),
engage_mode TEXT NOT NULL DEFAULT 'mention', -- 'pattern' | 'mention' | 'mention-sticky'
engage_pattern TEXT, -- regex; required for engage_mode='pattern'
-- ('.' = match every message, the "always" flavor)
sender_scope TEXT NOT NULL DEFAULT 'all', -- 'all' | 'known'
ignored_message_policy TEXT NOT NULL DEFAULT 'drop', -- 'drop' | 'accumulate'
session_mode TEXT DEFAULT 'shared', -- 'shared' | 'per-thread'
priority INTEGER DEFAULT 0, -- higher = checked first when multiple agents match
created_at TEXT NOT NULL,
UNIQUE(messaging_group_id, agent_group_id)
);
@@ -794,7 +854,7 @@ stopped → running → idle → stopped
## Agent-Runner Architecture
The agent-runner is the process inside the container. It mediates between the session DB and the Claude SDK — polling for work, formatting messages for the agent, translating tool calls into DB rows, and managing the agent lifecycle.
The agent-runner is the process inside the container. It mediates between the session DB and the agent provider — polling for work, formatting messages for the agent, translating tool calls into DB rows, and managing the agent lifecycle.
### IO Model
@@ -807,50 +867,58 @@ All IO goes through the session DB. No stdin, no stdout markers, no IPC files.
### Poll Loop
1. Query `messages_in WHERE status = 'pending' AND (process_after IS NULL OR process_after <= now())`
2. If rows found: set `status = 'processing'`, `status_changed = now()` on each
1. Query `inbound.db` (read-only) for `messages_in WHERE status = 'pending' AND (process_after IS NULL OR process_after <= now())`, skipping any id already in `processing_ack`
2. If rows found: upsert `processing_ack` rows with `status = 'processing'` in `outbound.db` (the container can't write `messages_in`)
3. Batch messages into a single prompt (strip routing fields, format by kind)
4. Push into Claude SDK's MessageStream
4. Push into the provider's input stream
5. Process agent output → write `messages_out` rows
6. Set processed messages to `status = 'completed'`
6. Set the processed ids' `processing_ack.status = 'completed'` (the host mirrors that onto `messages_in.status`)
7. Back to step 1. If no messages found, sleep briefly and re-poll (container stays warm for idle timeout)
### Message Formatting by Kind
Agent-runner strips routing fields (`platform_id`, `channel_type`, `thread_id`) before formatting. The agent never sees routing info — it only sees content.
- **`chat`** — format into `<messages>` XML block
- **`chat-sdk`** — extract text, author, attachments from serialized message; format into `<messages>` XML
- **`task`** — format as `[SCHEDULED TASK]` prefix + prompt. Run pre-script if present.
- **`webhook`** — format as `[WEBHOOK: source/event]` + JSON payload
- **`system`** — host action results (e.g., "register_group succeeded"). Format as system context, not chat.
- **`chat`** — format into a `<message id="…" from="…" sender="…" time="…">` element
- **`chat-sdk`** — extract text, author, attachments from serialized message; same `<message>` element
- **`task`** — format as a `<task from="…" time="…">` element (script output first if present). Run pre-script if present.
- **`webhook`** — format as a `<webhook source="…" event="…">` element wrapping the JSON payload
- **`system`** — host action results, formatted as `<system_response action="…" status="…">`, not chat
Mixed batches (e.g., a chat message + a system result both pending) are combined into one prompt with clear delimiters.
### MCP Tools
MCP tools write directly to the session DB.
MCP tools write to the container's own `outbound.db`. Anything that needs a change in host-owned `inbound.db` (schedule/cancel/pause/resume/update a task, create an agent, self-modify) is emitted as a `kind: 'system'` `messages_out` action that the host applies during delivery — the container never writes `inbound.db`.
**Core tools:**
**Messaging & interaction:**
| Tool | What it does |
|------|-------------|
| `send_message` | Write `messages_out` row, `kind: 'chat'` |
| `send_file` | Move file to `outbox/{msg_id}/`, write `messages_out` with filenames |
| `schedule_task` | Write `messages_in` row (to self) with `process_after` + `recurrence`. Or `messages_out` with `deliver_after` for outbound reminders. |
| `list_tasks` | Query `messages_in WHERE recurrence IS NOT NULL` |
| `pause_task` / `resume_task` / `cancel_task` | Modify `messages_in` rows (update status, clear/set recurrence) |
| `register_agent_group` | Write `messages_out`, `kind: 'system'`, `action: 'register_agent_group'` |
**New tools:**
| Tool | What it does |
|------|-------------|
| `ask_user_question` | Write `messages_out` with question card. Hold tool call open, poll `messages_in` for response matching `questionId`. Return selection as tool result. |
| `edit_message` | Write `messages_out` with `operation: 'edit'` |
| `send_message` | Resolve `to` (destination name) → routing, write `messages_out` row, `kind: 'chat'`. Omit `to` to reply in place. Also the agent-to-agent path: a `to` naming an `agent`-type destination. |
| `send_file` | Copy file to `outbox/{msg_id}/`, write `messages_out` (`kind: 'chat'`) with filenames, same `to` resolution |
| `send_card` | Write `messages_out`, `kind: 'chat-sdk'`, content `{ type: 'card', … }` |
| `ask_user_question` | Write `messages_out` (`kind: 'chat-sdk'`, `type: 'ask_question'`). Hold tool call open, poll `inbound.db` for the response matching `questionId`. Return selection as tool result. |
| `edit_message` | Write `messages_out` with `operation: 'edit'` (targets the original message's destination) |
| `add_reaction` | Write `messages_out` with `operation: 'reaction'` |
| `send_to_agent` | Write `messages_out` with `channel_type: 'agent'`, `platform_id: '{target}'` |
| `send_card` | Write `messages_out` with card structure |
(There is no `send_to_agent` tool — agent-to-agent is `send_message` to an `agent` destination.)
**Scheduling** (all emit `kind: 'system'` actions except the read-only `list_tasks`):
| Tool | What it does |
|------|-------------|
| `schedule_task` | `action: 'schedule_task'`; host inserts the `kind: 'task'` `messages_in` row with `process_after` + optional `recurrence` |
| `list_tasks` | Read `inbound.db` (read-only) — one row per series: `kind = 'task' AND status IN ('pending','paused') GROUP BY series_id` |
| `pause_task` / `resume_task` / `cancel_task` / `update_task` | matching `action`; host updates the live `messages_in` row(s) |
**Central-DB / self-modification** (`kind: 'system'` actions; host authorizes, often via admin approval):
| Tool | What it does |
|------|-------------|
| `create_agent` | `action: 'create_agent'` (name + instructions); host creates the agent group (replaces the old `register_agent_group`) |
| `install_packages` | `action: 'install_packages'`; on approval host rebuilds the per-agent image and restarts |
| `add_mcp_server` | `action: 'add_mcp_server'`; on approval host updates `container.json` and restarts |
See [agent-runner-details.md](agent-runner-details.md) for full MCP tool parameter definitions.
@@ -886,11 +954,11 @@ The command lists are hardcoded in the agent-runner. Admin verification happens
The agent-runner processes recurring task messages like any other messages_in row. After the agent-runner marks a recurring message as `completed`, the **host** handles inserting the next occurrence (new messages_in row with `process_after` advanced to next cron time). The agent-runner doesn't manage recurrence — it just processes what it finds.
Pre-scripts: if a task message has a `script` field, run it first. If `wakeAgent = false`, mark completed without invoking Claude.
Pre-scripts: if a task message has a `script` field, run it first. If `wakeAgent = false`, mark completed without invoking the provider.
### Agent-to-Agent Messaging
**Outbound:** Agent calls `send_to_agent` tool → agent-runner writes messages_out with `channel_type: 'agent'`, `platform_id` = target agent group ID. Host validates permissions and writes to target session's messages_in.
**Outbound:** Agent calls `send_message(to="<agent-name>")` where the named destination is of type `agent` → agent-runner writes messages_out with `channel_type: 'agent'`, `platform_id` = target agent group ID. Host validates permissions and writes to the target session's `inbound.db` (recording `source_session_id` so the reply routes back to this exact session).
**Inbound:** Messages from other agents arrive as normal `chat` messages_in rows. The content includes `sender` and `senderId` (e.g., `"senderId": "agent:pr-admin"`). No special formatting — the agent sees it as a chat message.
@@ -906,7 +974,7 @@ Pre-scripts: if a task message has a `script` field, run it first. If `wakeAgent
- **Approval routing** — how does the host find the admin's DM conversation? What if no DM channel exists? Is the approval list configurable per agent group or global?
- **MCP server lifecycle** — does the MCP server process persist across multiple queries in the same container, or restart each time?
- **Container startup config** — what config (if any) is passed to the container at launch beyond env vars? The session DB is at a fixed mount path. System prompt comes from CLAUDE.md. Provider name comes from env. What else?
- **Container startup config** — what config (if any) is passed to the container at launch beyond env vars? The DB files are at fixed mount paths. System prompt comes from CLAUDE.md. Provider name comes from `container.json` (materialized from the `container_configs` table), not env. What else?
- **Idle detection with pending questions** — when `ask_user_question` is waiting for a response, the container should not be considered idle. Also need to detect when the agent is still working (active tool calls, subagents) and avoid killing the container even if no messages_out have been written recently.
## Related Documents
+3 -3
View File
@@ -33,13 +33,13 @@ Both are committed. CI and the Dockerfile run `--frozen-lockfile` variants — a
## Supply chain
- **Host + global CLIs** (pnpm): `minimumReleaseAge: 4320` (3-day hold on new versions), `onlyBuiltDependencies` allowlist for postinstall scripts. See `pnpm-workspace.yaml` and `docs/SECURITY.md`.
- **Agent-runner** (Bun): no release-age policy — Bun doesn't have an equivalent today. The defenses are `bun.lock` pinning plus version-pinned CLIs/Bun itself via Dockerfile ARGs. When bumping `@anthropic-ai/claude-agent-sdk` or any runtime dep, review the release date on npm and bump deliberately, not via `bun update`.
- **Agent-runner** (Bun): no release-age policy — Bun doesn't have an equivalent today. The defenses are `bun.lock` pinning plus a version-pinned Bun itself via a Dockerfile ARG (global CLIs are pinned separately in `container/cli-tools.json`). When bumping `@anthropic-ai/claude-agent-sdk` or any runtime dep, review the release date on npm and bump deliberately, not via `bun update`.
## Image build surface
`container/Dockerfile` is a single-stage build on `node:22-slim`:
- **Pinned ARGs**`BUN_VERSION`, `CLAUDE_CODE_VERSION`, `AGENT_BROWSER_VERSION`, `VERCEL_VERSION`. Bump deliberately in PRs.
- **Pinned ARGs**`BUN_VERSION`, `PNPM_VERSION`, `INSTALL_CJK_FONTS`. Bump deliberately in PRs. Global CLI versions (`@anthropic-ai/claude-code`, `agent-browser`, `vercel`) are pinned separately in `container/cli-tools.json`, not as ARGs.
- **CJK fonts**`ARG INSTALL_CJK_FONTS=false`. `container/build.sh` reads `INSTALL_CJK_FONTS` from `.env` and passes it through. Default build saves ~200MB; opt in when the user works with Chinese/Japanese/Korean content.
- **BuildKit cache mounts**`/var/cache/apt`, `/var/lib/apt`, `/root/.bun/install/cache`, `/root/.cache/pnpm`. Rebuilds where `package.json`/`bun.lock` haven't changed are fast. Requires BuildKit (default on Docker 23+, Apple Container-compat).
- **`tini` as init** — reaps Chromium zombies, forwards signals so in-flight `outbound.db` writes finalize on SIGTERM.
@@ -49,7 +49,7 @@ Both are committed. CI and the Dockerfile run `--frozen-lockfile` variants — a
## Session wake (two paths)
1. **Base image ENTRYPOINT** — used for stdin-piped test invocations like the sample in `container/build.sh`: `tini --> entrypoint.sh` captures stdin to `/tmp/input.json`, then `exec bun run src/index.ts`.
2. **Host-spawned session**`src/container-runner.ts` at line ~301 uses `--entrypoint bash` with `-c 'exec bun run /app/src/index.ts'`. Bypasses tini (Docker's default PID 1 handling applies). Stdin is unused; all IO flows through the mounted session DBs.
2. **Host-spawned session**`src/container-runner.ts` at line ~503 uses `--entrypoint bash` with `-c 'exec bun run /app/src/index.ts'`. Bypasses tini (Docker's default PID 1 handling applies). Stdin is unused; all IO flows through the mounted session DBs.
Both paths end with Bun running the same source file from `/app/src/index.ts`.
+105 -24
View File
@@ -2,7 +2,7 @@
Complete reference for `data/v2.db`, the host-owned admin-plane database. Start with [db.md](db.md) for the three-DB overview, the map, and the cross-mount rules.
Access layer: `src/db/`. Authoritative schema reference: `src/db/schema.ts` (comments only — actual creation runs via migrations in `src/db/migrations/`).
Access layer: `src/db/`. `src/db/schema.ts`'s `SCHEMA` constant is a *reference copy* of the core tables for orientation — it is not exhaustive: several tables (`agent_destinations`, `pending_approvals`, `container_configs`, `agent_message_policies`, `pending_channel_approvals`, and others) exist only in their migration files under `src/db/migrations/`, which remain the actual source of truth for what's created at runtime.
---
@@ -55,20 +55,24 @@ Wiring: which agent group handles which messaging group. Many-to-many — the sa
```sql
CREATE TABLE messaging_group_agents (
id TEXT PRIMARY KEY,
messaging_group_id TEXT NOT NULL REFERENCES messaging_groups(id),
agent_group_id TEXT NOT NULL REFERENCES agent_groups(id),
trigger_rules TEXT,
response_scope TEXT DEFAULT 'all',
session_mode TEXT DEFAULT 'shared',
priority INTEGER DEFAULT 0,
created_at TEXT NOT NULL,
id TEXT PRIMARY KEY,
messaging_group_id TEXT NOT NULL REFERENCES messaging_groups(id),
agent_group_id TEXT NOT NULL REFERENCES agent_groups(id),
engage_mode TEXT NOT NULL DEFAULT 'mention',
-- 'pattern' | 'mention' | 'mention-sticky'
engage_pattern TEXT, -- regex; required when engage_mode='pattern';
-- '.' means "match every message"
sender_scope TEXT NOT NULL DEFAULT 'all', -- 'all' | 'known'
ignored_message_policy TEXT NOT NULL DEFAULT 'drop', -- 'drop' | 'accumulate'
session_mode TEXT DEFAULT 'shared',
priority INTEGER DEFAULT 0,
created_at TEXT NOT NULL,
UNIQUE(messaging_group_id, agent_group_id)
);
```
- `session_mode`: `shared` (one session per channel), `per-thread` (one per thread), `agent-shared` (one per agent group across all channels).
- `trigger_rules`: JSON; e.g. regex for native channels.
- `engage_mode` / `engage_pattern` / `sender_scope` / `ignored_message_policy`: four orthogonal axes (migration 010) that replaced v1's opaque `trigger_rules` JSON + `response_scope` enum. `engage_mode='pattern'` requires `engage_pattern` (`'.'` matches every message — the "always respond" flavor); `sender_scope='known'` restricts engagement to group members; `ignored_message_policy='accumulate'` keeps ignored messages as context instead of dropping them.
- **Side effect:** creating a wiring must also populate `agent_destinations` — don't mutate one without the other (see §1.10).
### 1.4 `users`
@@ -323,6 +327,71 @@ CREATE TABLE container_configs (
- **Readers:** `src/container-config.ts`, `src/container-runner.ts`, `src/cli/dispatch.ts` (scope enforcement), `src/claude-md-compose.ts`
- **Writers:** `src/db/container-configs.ts`, `src/modules/self-mod/apply.ts`, `src/backfill-container-configs.ts`
### 1.16 `pending_sender_approvals`
In-flight state for the `unknown_sender_policy = 'request_approval'` flow. A row exists while an admin-approval card is outstanding for a first-time sender in a wired messaging group; `UNIQUE(messaging_group_id, sender_identity)` dedups concurrent attempts from the same sender instead of spamming the admin with repeat cards.
```sql
CREATE TABLE pending_sender_approvals (
id TEXT PRIMARY KEY,
messaging_group_id TEXT NOT NULL REFERENCES messaging_groups(id),
agent_group_id TEXT NOT NULL REFERENCES agent_groups(id),
sender_identity TEXT NOT NULL, -- namespaced user id (channel_type:handle)
sender_name TEXT,
original_message TEXT NOT NULL, -- JSON of the original InboundEvent
approver_user_id TEXT NOT NULL,
created_at TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '', -- added by migration 013
options_json TEXT NOT NULL DEFAULT '[]', -- added by migration 013
UNIQUE(messaging_group_id, sender_identity)
);
```
Deleted on admin approve (after adding the sender as a member) or deny.
- Access layer: `src/modules/permissions/db/pending-sender-approvals.ts`
- **Readers/writers:** `src/modules/permissions/sender-approval.ts`, `src/modules/permissions/index.ts`, `src/db/sessions.ts` (`getAskQuestionRender`), `src/cli/resources/groups.ts`
### 1.17 `pending_channel_approvals`
In-flight state for the unknown-channel registration flow. When a channel with no `messaging_group_agents` wiring receives a mention or DM, the router escalates to the owner; `PRIMARY KEY(messaging_group_id)` gives free in-flight dedup via `INSERT OR IGNORE` — a second mention while a card is pending drops silently.
```sql
CREATE TABLE pending_channel_approvals (
messaging_group_id TEXT PRIMARY KEY REFERENCES messaging_groups(id),
agent_group_id TEXT NOT NULL REFERENCES agent_groups(id),
-- agent the approved wiring will target (earliest
-- agent_group by created_at, picked at request time)
original_message TEXT NOT NULL, -- JSON of the original InboundEvent
approver_user_id TEXT NOT NULL,
created_at TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '', -- added by migration 013
options_json TEXT NOT NULL DEFAULT '[]' -- added by migration 013
);
```
Approve creates the `messaging_group_agents` wiring and replays the triggering event; deny sets `messaging_groups.denied_at` so future messages on that channel drop without re-prompting. Either way, this row is deleted.
- Access layer: `src/modules/permissions/db/pending-channel-approvals.ts`
- **Readers/writers:** `src/modules/permissions/channel-approval.ts`, `src/modules/permissions/index.ts`, `src/router.ts`, `src/db/sessions.ts` (`getAskQuestionRender`), `src/cli/resources/groups.ts`
### 1.18 `agent_message_policies`
Per-message approval gate on an agent-to-agent connection between two agent groups. No row for a `(from, to)` pair means free flow (no approval required); a row names the `approver` who must sign off on each message.
```sql
CREATE TABLE agent_message_policies (
from_agent_group_id TEXT NOT NULL REFERENCES agent_groups(id),
to_agent_group_id TEXT NOT NULL REFERENCES agent_groups(id),
approver TEXT NOT NULL,
created_at TEXT NOT NULL,
PRIMARY KEY (from_agent_group_id, to_agent_group_id)
);
```
- Access layer: `src/modules/agent-to-agent/db/agent-message-policies.ts`
- **Readers/writers:** `src/cli/resources/policies.ts`; approved messages create a row in `pending_approvals` (see §1.11) via the a2a send path.
---
## 2. Migration system
@@ -330,21 +399,33 @@ CREATE TABLE container_configs (
Migrations live in `src/db/migrations/`, one file per migration. Runner: `runMigrations()` in `src/db/migrations/index.ts`. It:
1. Creates `schema_version` if absent.
2. Reads `MAX(version)` — call it `current`.
3. For each migration with `version > current`, executes `up(db)` inside a transaction and appends a `schema_version` row.
2. Reads every already-applied `name` from `schema_version` into a `Set` and filters the `migrations` barrel array down to the ones whose `name` isn't in that set — dedup is by **name**, not by the numeric `version` field.
3. Runs each pending migration's `up(db)` inside a transaction, in the barrel array's literal order (which is *not* sorted by `version`), then inserts a `schema_version` row.
4. The `version` column stored in `schema_version` is **not** the migration's own `version` field — it's `COALESCE(MAX(version), 0) + 1`, i.e. an auto-assigned applied-order number computed at insert time. The `version` field on the `Migration` object is just an ordering hint for humans reading the barrel file; it lets module migrations (installed later by skills) pick arbitrary numbers without coordinating with trunk.
| # | File | Introduces |
|---|------|------------|
| 001 | `001-initial.ts` | Core tables: `agent_groups`, `messaging_groups`, `messaging_group_agents`, `users`, `user_roles`, `agent_group_members`, `user_dms`, `sessions`, `pending_questions` |
| 002 | `002-chat-sdk-state.ts` | `chat_sdk_kv`, `chat_sdk_subscriptions`, `chat_sdk_locks`, `chat_sdk_lists` |
| 003 | `003-pending-approvals.ts` | `pending_approvals` (session-bound + OneCLI fields) |
| 004 | `004-agent-destinations.ts` | `agent_destinations` + backfill from existing `messaging_group_agents` wirings |
| 007 | `007-pending-approvals-title-options.ts` | `ALTER TABLE pending_approvals` add `title`, `options_json` (retrofits DBs created between 003 and 007) |
| 008 | `008-dropped-messages.ts` | `unregistered_senders` |
| 009 | `009-drop-pending-credentials.ts` | Drop the defunct `pending_credentials` table |
| 014 | `014-container-configs.ts` | `container_configs` — per-agent-group container runtime config |
| 015 | `015-cli-scope.ts` | `ALTER TABLE container_configs ADD COLUMN cli_scope` |
A few migrations also set `disableForeignKeys: true` (needed for table recreates — SQLite can't relax a table-level `UNIQUE` without DROP+RENAME, which fails FK integrity checks with live child rows). The runner toggles `PRAGMA foreign_keys` around the transaction and runs `PRAGMA foreign_key_check` inside it, snapshotting pre-existing violations so it only fails on violations the migration itself introduced.
Numbers 005 and 006 are intentionally absent — migrations were renumbered during early development.
Several early migrations were later renamed/retired and replaced by "module" files (their original `name` is retained on the new file so already-migrated DBs don't re-run them):
| Ver. | Name (stored in `schema_version`) | File | Introduces |
|---|---|------|------------|
| 1 | `initial-v2-schema` | `001-initial.ts` | Core tables: `agent_groups`, `messaging_groups`, `messaging_group_agents` (with the original `trigger_rules`/`response_scope` columns — see v10), `users`, `user_roles`, `agent_group_members`, `user_dms`, `sessions`, `pending_questions` |
| 2 | `chat-sdk-state` | `002-chat-sdk-state.ts` | `chat_sdk_kv`, `chat_sdk_subscriptions`, `chat_sdk_locks`, `chat_sdk_lists` |
| 3 | `pending-approvals` | `module-approvals-pending-approvals.ts` | `pending_approvals` (session-bound + OneCLI fields) |
| 4 | `agent-destinations` | `module-agent-to-agent-destinations.ts` | `agent_destinations` + backfill from existing `messaging_group_agents` wirings |
| 7 | `pending-approvals-title-options` | `module-approvals-title-options.ts` | Retroactive `ALTER TABLE pending_approvals` add `title`, `options_json` for DBs that ran migration 3 before its `CREATE TABLE` was edited to include those columns |
| 8 | `dropped-messages` | `008-dropped-messages.ts` | `unregistered_senders` |
| 9 | `drop-pending-credentials` | `009-drop-pending-credentials.ts` | Drop the defunct `pending_credentials` table |
| 10 | `engage-modes` | `010-engage-modes.ts` | `messaging_group_agents`: add `engage_mode`, `engage_pattern`, `sender_scope`, `ignored_message_policy`; backfill from `trigger_rules`/`response_scope`; drop those two legacy columns (see §1.3) |
| 11 | `pending-sender-approvals` | `011-pending-sender-approvals.ts` | `pending_sender_approvals` (see §1.16) |
| 12 | `channel-registration` | `012-channel-registration.ts` | `messaging_groups.denied_at` + `pending_channel_approvals` (see §1.17) |
| 13 | `approval-render-metadata` | `013-approval-render-metadata.ts` | `title`, `options_json` columns on `pending_channel_approvals` and `pending_sender_approvals` |
| 14 | `container-configs` | `014-container-configs.ts` | `container_configs` — per-agent-group container runtime config |
| 15 | `cli-scope` | `015-cli-scope.ts` | `ALTER TABLE container_configs ADD COLUMN cli_scope` |
| 16 | `messaging-group-instance` | `016-messaging-group-instance.ts` | `messaging_groups` gets an `instance` column (adapter-instance dimension); table recreate (`disableForeignKeys: true`) backfills `instance = channel_type` on every existing row and relaxes the `UNIQUE` to `(channel_type, platform_id, instance)` |
| 17 | `agent-message-policies` | `017-agent-message-policies.ts` | `agent_message_policies` (see §1.18) |
| 18 | `approvals-approver-user-id` | `018-approvals-approver-user-id.ts` | `pending_approvals.approver_user_id` — names a single required approver for a2a message-gate policies |
Numbers 5 and 6 are intentionally absent — migrations were renumbered during early development.
Session DB schemas (`INBOUND_SCHEMA`, `OUTBOUND_SCHEMA`) are **not** versioned here. They're `CREATE TABLE IF NOT EXISTS` so new columns land via the session-DB lazy migration helpers (`migrateDeliveredTable()` etc.) when a session file from an older build is reopened. See [db-session.md](db-session.md).
+23 -3
View File
@@ -10,14 +10,16 @@ Schemas live in `src/db/schema.ts` as the `INBOUND_SCHEMA` and `OUTBOUND_SCHEMA`
```
data/v2-sessions/<agent_group_id>/<session_id>/
inbound.db ← host writes, container reads (read-only mount)
inbound.db ← host writes, container reads (read-only open)
outbound.db ← container writes, host reads (read-only open)
.heartbeat ← mtime touched by container (not a DB write)
inbox/<message_id>/ ← user attachments, decoded from inbound message content
outbox/<message_id>/ ← attachments the agent produced
```
One session = one folder = one pair of DBs. The `agent_group_id` parent directory also holds per-group state (`.claude-shared/`, `agent-runner-src/`) that is shared across every session of that agent group.
The session directory itself is mounted read-write into the container (`src/container-runner.ts`) — read-only is *not* a mount property. The container opens `inbound.db` with `{ readonly: true }` at the SQLite connection layer (`container/agent-runner/src/db/connection.ts`), so the container could technically write to the underlying file via another path, but every code path that touches `inbound.db` from inside the container goes through that read-only handle.
One session = one folder = one pair of DBs. The `agent_group_id` parent directory also holds per-group state (`.claude-shared/`) that is shared across every session of that agent group. (The agent-runner source is not copied per group — it's a shared read-only mount from `container/agent-runner/src` into every container; see `src/container-runner.ts`.)
Path helpers in `src/session-manager.ts`: `sessionDir()`, `inboundDbPath()`, `outboundDbPath()`, `heartbeatPath()`.
@@ -55,7 +57,7 @@ CREATE INDEX idx_messages_in_series ON messages_in(series_id);
Content shapes: see [api-details.md §Session DB Schema Details](api-details.md#session-db-schema-details).
**Writers (host):** `insertMessage()`, `insertTask()`, `insertRecurrence()` — all in `src/db/session-db.ts`. Each calls `nextEvenSeq()`.
**Writers (host):** `insertMessage()` (and `nextEvenSeq()`) in `src/db/session-db.ts`; `insertTask()` and `insertRecurrence()` in `src/modules/scheduling/db.ts`. Each calls `nextEvenSeq()`.
**Reader (container):** `container/agent-runner/src/db/messages-in.ts` — polls `status='pending' AND (process_after IS NULL OR process_after <= now)`.
### 2.2 `delivered`
@@ -177,6 +179,24 @@ CREATE TABLE session_state (
Access: `container/agent-runner/src/db/session-state.ts`.
### 4.4 `container_state`
Single-row (`id=1`) tool-in-flight tracker. The container records the currently-running tool on `PreToolUse` and clears it on `PostToolUse`/`PostToolUseFailure`; the host reads it during the stale-container sweep to widen its stuck-tolerance window when `Bash` is running with a user-declared `timeout` over the normal threshold, so long-running scripts aren't killed as "stuck".
```sql
CREATE TABLE container_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
current_tool TEXT,
tool_declared_timeout_ms INTEGER,
tool_started_at TEXT,
updated_at TEXT NOT NULL
);
```
- **Writer (container):** `setContainerToolInFlight()` / `clearContainerToolInFlight()` in `container/agent-runner/src/db/connection.ts`, called from the `preToolUseHook` / `postToolUseHook` in `container/agent-runner/src/providers/claude.ts`.
- **Reader (host):** `getContainerState()` in `src/db/session-db.ts`; consumed by the sweep's `bashTimeoutMs()` helper in `src/host-sweep.ts`.
- `CREATE TABLE IF NOT EXISTS` — forward-compatible with `outbound.db` files created before this table existed; `getContainerState()` returns `null` if the table or row is absent.
---
## 5. Schema evolution
-1
View File
@@ -35,7 +35,6 @@ data/
v2-sessions/
<agent_group_id>/
.claude-shared/ ← shared Claude state for the agent group
agent-runner-src/ ← per-group agent-runner overlay
<session_id>/
inbound.db ← host writes, container reads
outbound.db ← container writes, host reads
+1 -1
View File
@@ -80,7 +80,7 @@ agent_groups (workspace, memory, CLAUDE.md, personality)
↕ many-to-many
messaging_groups (a specific channel/chat/group on a platform)
via
messaging_group_agents (session_mode, trigger_rules, priority)
messaging_group_agents (session_mode, engage_mode, engage_pattern, sender_scope, ignored_message_policy, priority)
```
- **Shared session:** multiple messaging_groups → same agent_group, `session_mode = 'agent-shared'`
+2 -2
View File
@@ -10,11 +10,11 @@ Find out what is running and what is required:
```bash
cat versions.json # the sanctioned pin
curl -s http://127.0.0.1:10254/api/health # reports the running gateway version
curl -s http://127.0.0.1:10254/api/health # liveness check; `version` field is typically "unknown", not the gateway version
curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:10254/v1/health
```
If the last command prints `404`, the server predates the `/v1` API that `@onecli-sh/sdk` 2.x requires — every SDK call will fail with 404s that look transient but are permanent. If your gateway is remote, substitute its host for `127.0.0.1` (it's in `.env` as `ONECLI_URL` / `NANOCLAW_ONECLI_API_HOST`).
If the last command prints `404`, the server predates the `/v1` API that `@onecli-sh/sdk` 2.x requires — every SDK call will fail with 404s that look transient but are permanent. If your gateway is remote, substitute its host for `127.0.0.1` (it's `ONECLI_URL` in `.env`; `NANOCLAW_ONECLI_API_HOST` is a setup-time override only, not persisted to `.env`).
Why gateways fall behind: the OneCLI installer's docker-compose tracks the `latest` image tag, but Docker never re-pulls a tag — the server freezes at whatever `latest` meant on install day.
+2 -2
View File
@@ -179,7 +179,7 @@ So during this step:
marker.
The level-2 log still gets an entry (`auth [interactive] → success`
with the method — subscription / oauth-token / api-key). Level-3 captures
with the method — subscription / oauth / api). Level-3 captures
are optional here; mirroring `script -q` output is tricky and the risk of
leaking the token to disk outweighs the debugging value.
@@ -190,7 +190,7 @@ leaking the token to disk outweighs the debugging value.
| `nanoclaw.sh` | Top-level wrapper. Phase 1 (bootstrap) and phase 2 (setup:auto) orchestration. Writes bootstrap's raw log + progression entry. `--uninstall` bypasses bootstrap entirely — it execs setup:auto directly (the flow lives in `setup/uninstall/`), or prints manual-cleanup guidance and exits 1 when the TS toolchain is missing. |
| `setup.sh` | Phase 1 bootstrap: Node, pnpm, native-module verify. Emits its own `BOOTSTRAP` status block (historically printed to stdout; now goes to the bootstrap raw log). |
| `setup/auto.ts` | Phase 2 driver. Orchestrates the clack UI, step execution, user prompts, and writes to all three log levels for every step it spawns. |
| `setup/logs.ts` | The logging primitives (`logStep`, `logUserInput`, `logComplete`, `stepRawLog`, `initSetupLog`). Single source of truth for level 2/3 formatting and file paths. |
| `setup/logs.ts` | The logging primitives (`step`, `userInput`, `complete`, `stepRawLog`, `reset`). Single source of truth for level 2/3 formatting and file paths. |
| `setup/<step>.ts` | Individual step implementations. Must emit one terminal status block; must not write directly to the terminal. |
| `setup/register-claude-token.sh` | The Anthropic exception. Inherits stdio, prints its own UI, returns a status to the driver. |
| `setup/add-telegram.sh` | Non-interactive adapter installer. Reads `TELEGRAM_BOT_TOKEN` from env; never prompts. User-facing bits live in `auto.ts`. |
+5 -5
View File
@@ -14,7 +14,7 @@ Last updated: 2026-04-09
- Container clears stale `processing_ack` entries on startup (crash recovery)
- Files: `src/db/schema.ts` (INBOUND_SCHEMA + OUTBOUND_SCHEMA), `src/session-manager.ts`, `src/delivery.ts`, `src/host-sweep.ts`, `container/agent-runner/src/db/connection.ts`, `messages-in.ts`, `messages-out.ts`, `poll-loop.ts`, `mcp-tools/scheduling.ts`, `mcp-tools/interactive.ts`
- Container image rebuilt with tsconfig (`container/agent-runner/tsconfig.json`)
- E2E verified: host → Docker container → Claude responds → "E2E works!" ✓
- E2E verified: host → Docker container → agent responds → "E2E works!" ✓
### OneCLI Integration
- `ensureAgent()` call added before `applyContainerConfig()` in `src/container-runner.ts`
@@ -65,11 +65,11 @@ Added `session_mode: 'agent-shared'` for cross-channel shared sessions (e.g. Git
### Entity Model
```
agent_groups (id, name, folder, agent_provider, container_config)
↕ many-to-many
messaging_groups (id, channel_type, platform_id, name, is_group, unknown_sender_policy)
agent_groups (id, name, folder, agent_provider)
↕ many-to-many (container runtime config lives in the separate container_configs table)
messaging_groups (id, channel_type, platform_id, instance, name, is_group, unknown_sender_policy, denied_at)
via
messaging_group_agents (messaging_group_id, agent_group_id, trigger_rules, session_mode, priority)
messaging_group_agents (messaging_group_id, agent_group_id, engage_mode, engage_pattern, sender_scope, ignored_message_policy, session_mode, priority)
users (id, kind, display_name) -- namespaced as "<channel>:<handle>"
user_roles (user_id, role, agent_group_id) -- owner / admin (global or scoped)
+9 -15
View File
@@ -2,27 +2,21 @@
A **template** is a reusable folder you stamp into a working agent group: it
carries the agent's standing instructions, its MCP tool servers, and its skills,
but **no secrets and no provider**. Point `ncl` (or the setup wizard) at one and
but **no secrets and no provider**. Point `ncl` at one and
you get a configured agent in seconds; you choose the runtime/provider
separately.
Templates are purely additive: no DB migration, no new dependency. **At runtime,
templates are resolved only from a local directory**: `templates/` at the
Templates are purely additive: no DB migration, no new dependency. **Templates
are resolved only from a local directory**: `templates/` at the
project root by default (committed but shipped empty), or whatever
`NANOCLAW_TEMPLATES_DIR` points at (a local path only). The setup wizard can also
discover templates from the public registry
`NANOCLAW_TEMPLATES_DIR` points at (a local path only). The public registry
([`nanocoai/nanoclaw-templates`](https://github.com/nanocoai/nanoclaw-templates))
and copy a chosen one into your local `templates/` before stamping.
is a manual copy source — clone or download it yourself and copy the chosen
template into your local `templates/` before stamping.
## Using a template
**During install.** `bash nanoclaw.sh` opens the setup wizard. Choose **Template
setup**, then either **NanoClaw template library** (clones the public registry,
copies the template you pick into your local `templates/`) or **Local templates**
(lists what's already in `templates/`). The normal auth step then picks the
runtime, and the wizard stamps and wires your first agent.
**Anytime, via the CLI:**
**Via the CLI:**
```bash
ncl groups create --template sales/sdr --name "SDR Agent"
@@ -40,8 +34,8 @@ e.g. `sales/sdr` → `templates/sales/sdr`.
For safety the ref must stay inside the templates directory: absolute paths, a
leading `~`, and `../` escapes are rejected. There is no `--source`, no git URL,
and no remote fetch at `ncl` time. Populate `templates/` first (by hand, or via
the setup wizard's library option), then stamp.
and no remote fetch at `ncl` time. Populate `templates/` first (by hand, e.g.
copying from the public registry), then stamp.
`NANOCLAW_TEMPLATES_DIR` may point the library at another **local** directory; it
is never a URL and never changes at runtime.
+1 -1
View File
@@ -80,7 +80,7 @@ Tasks can exist before a session is awake — the host sweep creates/wakes the c
**v2:** OneCLI Agent Vault. A separate local service at `http://127.0.0.1:10254` holds secrets. Agents are *scoped* to specific secrets and the vault injects them into approved API requests as they leave the container. The container never sees the raw secret value.
Gotcha: auto-created agents default to `selective` secret mode — no secrets attached, even if matching secrets exist in the vault. See the "auto-created agents start in selective secret mode" section of the root CLAUDE.md for the fix (`onecli agents set-secret-mode --mode all`).
Note: auto-created agents default to `all` secret mode — every vault secret whose host pattern matches is injected automatically. See the "Secret modes" section of the root CLAUDE.md if you want per-agent control (`onecli agents set-secret-mode --mode selective`).
**What the automated migration does:** copies every v1 `.env` key verbatim into v2 `.env`, never overwriting existing v2 keys. The OneCLI vault migration is a separate step owned by the `/init-onecli` skill, which knows how to pull from `.env`.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "nanoclaw",
"version": "2.1.36",
"version": "2.1.40",
"description": "Personal Claude assistant. Lightweight, secure, customizable.",
"type": "module",
"packageManager": "pnpm@10.33.0",
+4 -4
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="20" role="img" aria-label="208k tokens, 104% of context window">
<title>208k tokens, 104% of context window</title>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="90" height="20" role="img" aria-label="213k tokens, 106% of context window">
<title>213k tokens, 106% of context window</title>
<linearGradient id="s" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
@@ -15,8 +15,8 @@
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">
<text aria-hidden="true" x="26" y="15" fill="#010101" fill-opacity=".3">tokens</text>
<text x="26" y="14">tokens</text>
<text aria-hidden="true" x="71" y="15" fill="#010101" fill-opacity=".3">208k</text>
<text x="71" y="14">208k</text>
<text aria-hidden="true" x="71" y="15" fill="#010101" fill-opacity=".3">213k</text>
<text x="71" y="14">213k</text>
</g>
</g>
</a>

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

+1 -5
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
#
# Install the Discord adapter, persist DISCORD_BOT_TOKEN / APPLICATION_ID /
# PUBLIC_KEY to .env + data/env/env, and restart the service. Non-interactive —
# PUBLIC_KEY to .env, and restart the service. Non-interactive —
# the operator-facing "Create a bot" walkthrough, owner confirmation, and
# server-invite step live in setup/channels/discord.ts. Credentials come in via
# env vars: DISCORD_BOT_TOKEN, DISCORD_APPLICATION_ID, DISCORD_PUBLIC_KEY.
@@ -105,10 +105,6 @@ upsert_env DISCORD_BOT_TOKEN "$DISCORD_BOT_TOKEN"
upsert_env DISCORD_APPLICATION_ID "$DISCORD_APPLICATION_ID"
upsert_env DISCORD_PUBLIC_KEY "$DISCORD_PUBLIC_KEY"
# Container reads from data/env/env (the host mounts it).
mkdir -p data/env
cp .env data/env/env
log "Restarting service so the new adapter picks up the credentials…"
# shellcheck source=setup/lib/install-slug.sh
source "$PROJECT_ROOT/setup/lib/install-slug.sh"
+1 -5
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
#
# Install the iMessage adapter, persist mode/creds to .env + data/env/env,
# Install the iMessage adapter, persist mode/creds to .env,
# and restart the service. Non-interactive — the Full Disk Access walkthrough
# (local mode) and Photon URL/key prompts (remote mode) live in
# setup/channels/imessage.ts. Creds come in via env vars:
@@ -135,10 +135,6 @@ else
remove_env IMESSAGE_ENABLED
fi
# Container reads from data/env/env (the host mounts it).
mkdir -p data/env
cp .env data/env/env
log "Restarting service so the new adapter picks up the creds…"
# shellcheck source=setup/lib/install-slug.sh
source "$PROJECT_ROOT/setup/lib/install-slug.sh"
+1 -5
View File
@@ -2,7 +2,7 @@
#
# Install the Slack adapter, persist SLACK_BOT_TOKEN plus the mode-specific
# secret (SLACK_APP_TOKEN for Socket Mode, SLACK_SIGNING_SECRET for webhook) to
# .env + data/env/env, and restart the service. Non-interactive — the
# .env, and restart the service. Non-interactive — the
# operator-facing app creation walkthrough + credential paste live in
# setup/channels/slack.ts. Credentials come in via env vars:
# SLACK_BOT_TOKEN, and SLACK_APP_TOKEN and/or SLACK_SIGNING_SECRET.
@@ -108,10 +108,6 @@ if [ -n "${SLACK_SIGNING_SECRET:-}" ]; then
upsert_env SLACK_SIGNING_SECRET "$SLACK_SIGNING_SECRET"
fi
# Container reads from data/env/env (the host mounts it).
mkdir -p data/env
cp .env data/env/env
log "Restarting service so the new adapter picks up the credentials…"
# shellcheck source=setup/lib/install-slug.sh
source "$PROJECT_ROOT/setup/lib/install-slug.sh"
+1 -5
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
#
# Install the Teams adapter, persist TEAMS_APP_ID / _PASSWORD / _TENANT_ID /
# _TYPE to .env + data/env/env, and restart the service. Non-interactive —
# _TYPE to .env, and restart the service. Non-interactive —
# the operator-facing Azure portal walkthroughs live in
# setup/channels/teams.ts. Credentials come in via env vars:
# TEAMS_APP_ID (required)
@@ -114,10 +114,6 @@ if [ -n "${TEAMS_APP_TENANT_ID:-}" ]; then
upsert_env TEAMS_APP_TENANT_ID "$TEAMS_APP_TENANT_ID"
fi
# Container reads from data/env/env (the host mounts it).
mkdir -p data/env
cp .env data/env/env
log "Restarting service so the new adapter picks up the credentials…"
# shellcheck source=setup/lib/install-slug.sh
source "$PROJECT_ROOT/setup/lib/install-slug.sh"
+1 -5
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
#
# Install the Telegram adapter, persist the bot token to .env + data/env/env,
# Install the Telegram adapter, persist the bot token to .env,
# restart the service, and open the bot's chat page in the local Telegram
# client. Non-interactive — the operator-facing "Create a bot" instructions
# and token paste live in setup/auto.ts. The token comes in via the
@@ -134,10 +134,6 @@ if echo "$INFO" | grep -q '"ok":true'; then
BOT_USERNAME=$(echo "$INFO" | sed -nE 's/.*"username":"([^"]+)".*/\1/p')
fi
# Container reads from data/env/env (the host mounts it).
mkdir -p data/env
cp .env data/env/env
# Browser/app deep-link is done by the parent driver (setup/channels/telegram.ts)
# BEFORE this script runs — gated on a clack confirm so focus-stealing doesn't
# surprise the user. Keeping it out of here means this script stays pure
+2 -6
View File
@@ -10,7 +10,7 @@
* 2. Install the adapter + qrcode via setup/add-signal.sh (idempotent).
* 3. Run the signal-auth step, rendering each SIGNAL_AUTH_QR block as
* a terminal QR the operator scans from Signal Linked Devices.
* 4. Persist SIGNAL_ACCOUNT to .env (+ data/env/env).
* 4. Persist SIGNAL_ACCOUNT to .env.
* 5. Kick the service so the adapter picks up the new credentials.
* 6. Ask operator role + agent name.
* 7. Wire the agent via scripts/init-first-agent.ts; the existing welcome
@@ -333,7 +333,7 @@ async function renderQr(url: string): Promise<string[]> {
}
}
/** Persist SIGNAL_ACCOUNT to .env and mirror to data/env/env for the container. */
/** Persist SIGNAL_ACCOUNT to .env. */
function writeSignalAccount(account: string): void {
const envPath = path.join(process.cwd(), '.env');
let contents = '';
@@ -353,10 +353,6 @@ function writeSignalAccount(account: string): void {
}
fs.writeFileSync(envPath, contents);
const containerEnvDir = path.join(process.cwd(), 'data', 'env');
fs.mkdirSync(containerEnvDir, { recursive: true });
fs.copyFileSync(envPath, path.join(containerEnvDir, 'env'));
setupLog.userInput('signal_account', account);
}
+1 -6
View File
@@ -433,7 +433,7 @@ async function askChatPhone(authedPhone: string): Promise<string> {
return phone;
}
/** Persist ASSISTANT_HAS_OWN_NUMBER=true to .env and data/env/env. */
/** Persist ASSISTANT_HAS_OWN_NUMBER=true to .env. */
function writeAssistantHasOwnNumber(): void {
const envPath = path.join(process.cwd(), '.env');
let contents = '';
@@ -452,11 +452,6 @@ function writeAssistantHasOwnNumber(): void {
contents += 'ASSISTANT_HAS_OWN_NUMBER=true\n';
}
fs.writeFileSync(envPath, contents);
// Container reads from data/env/env.
const containerEnvDir = path.join(process.cwd(), 'data', 'env');
fs.mkdirSync(containerEnvDir, { recursive: true });
fs.copyFileSync(envPath, path.join(containerEnvDir, 'env'));
}
async function resolveAgentName(): Promise<string> {
-9
View File
@@ -116,15 +116,6 @@ function main(): void {
channelsProcessed++;
}
// Sync to data/env/env
if (fs.existsSync(v2EnvPath)) {
const containerEnvDir = path.join(process.cwd(), 'data', 'env');
try {
fs.mkdirSync(containerEnvDir, { recursive: true });
fs.copyFileSync(v2EnvPath, path.join(containerEnvDir, 'env'));
} catch { /* non-fatal */ }
}
console.log(`OK:channels=${channelsProcessed},env_keys=${envKeysCopied},files=${filesCopied}`);
if (missing.length > 0) {
console.log(`MISSING:${missing.join(',')}`);
-9
View File
@@ -65,15 +65,6 @@ function main(): void {
fs.writeFileSync(v2EnvPath, result);
}
// Sync to data/env/env (container reads from here)
const containerEnvDir = path.join(process.cwd(), 'data', 'env');
try {
fs.mkdirSync(containerEnvDir, { recursive: true });
fs.copyFileSync(v2EnvPath, path.join(containerEnvDir, 'env'));
} catch {
// Non-fatal
}
console.log(`OK:copied=${copied.length},skipped=${skipped.length}`);
if (copied.length > 0) console.log(`COPIED:${copied.join(',')}`);
}
+2 -14
View File
@@ -1,10 +1,9 @@
/**
* Step: set-env Write or update a KEY=VALUE in .env, with optional sync to
* data/env/env (the container-mounted copy).
* Step: set-env Write or update a KEY=VALUE in .env.
*
* Usage:
* pnpm exec tsx setup/index.ts --step set-env -- \
* --key TELEGRAM_BOT_TOKEN --value "<token>" [--sync-container]
* --key TELEGRAM_BOT_TOKEN --value "<token>"
*
* Exists so channel-install flows don't have to invent grep/sed/rm pipelines
* (which can't be allowlisted tightly sed can read any file, and each
@@ -21,7 +20,6 @@ import { emitStatus } from './status.js';
export async function run(args: string[]): Promise<void> {
const keyIdx = args.indexOf('--key');
const valueIdx = args.indexOf('--value');
const syncContainer = args.includes('--sync-container');
if (keyIdx === -1 || !args[keyIdx + 1]) {
throw new Error('--key <KEY> is required');
@@ -59,19 +57,9 @@ export async function run(args: string[]): Promise<void> {
fs.writeFileSync(envFile, content);
log.info('Updated .env', { key, existed });
let synced = false;
if (syncContainer) {
const dataEnvDir = path.join(projectRoot, 'data', 'env');
fs.mkdirSync(dataEnvDir, { recursive: true });
fs.copyFileSync(envFile, path.join(dataEnvDir, 'env'));
synced = true;
log.info('Synced .env to container mount', { path: 'data/env/env' });
}
emitStatus('SET_ENV', {
KEY: key,
EXISTED: existed,
SYNCED_TO_CONTAINER: synced,
STATUS: 'success',
});
}
+1 -2
View File
@@ -11,8 +11,7 @@
*
* Runs on every spawn from `container-runner.buildMounts()`. Deterministic
* same inputs produce the same CLAUDE.md, and stale fragments are pruned.
*
* See `docs/claude-md-composition.md` for the full design.
* The composition order and fragment sources are documented inline above.
*/
import fs from 'fs';
import path from 'path';
+8 -2
View File
@@ -43,8 +43,14 @@ async function main(): Promise<void> {
process.exit(2);
}
process.stdout.write(formatResponse(res, json ? 'json' : 'human'));
process.exit(res.ok ? 0 : 1);
const output =
!json && res.ok && res.human !== undefined
? res.human + '\n' // server-rendered view — print verbatim
: formatResponse(res, json ? 'json' : 'human');
// Exit only after stdout drains: process.exit() discards buffered pipe
// writes, silently truncating any response past the 64KB pipe buffer
// (bit `ncl sessions list --json` at scale).
process.stdout.write(output, () => process.exit(res.ok ? 0 : 1));
}
function pickTransport(): Transport {
+32 -14
View File
@@ -5,11 +5,10 @@
* ncl groups help show group resource details (verbs, columns, enums)
*/
import { getContainerConfig } from '../../db/container-configs.js';
import { getResource, getResources } from '../crud.js';
import { getResources } from '../crud.js';
import { renderVerbHelp, summaryLine } from '../help-render.js';
import type { CallerContext } from '../frame.js';
import { listCommands, register } from '../registry.js';
const GROUP_SCOPE_RESOURCES = new Set(['groups', 'sessions', 'destinations', 'members']);
import { GROUP_SCOPE_RESOURCES, listCommands, register } from '../registry.js';
function getCliScope(ctx: CallerContext): string | undefined {
if (ctx.caller !== 'agent') return undefined;
@@ -76,13 +75,28 @@ export function registerResourceHelpCommands(): void {
try {
register({
name: `${res.plural}-help`,
description: `Show ${res.name} resource details.`,
description: `Show ${res.name} resource details; \`${res.plural} help <verb>\` for one verb in depth.`,
access: 'open',
resource: res.plural,
parseArgs: () => ({}),
handler: async (_args, ctx) => {
parseArgs: (raw) => raw,
handler: async (args, ctx) => {
const cliScope = getCliScope(ctx);
const lines: string[] = [];
// `ncl <resource> help <verb>` arrives via the dispatcher's
// longest-prefix fallback (`groups-help-create` → `groups-help` +
// id=`create`) and renders that verb's deep help — full description,
// flags, examples. No new routing. Group-scope auto-fill also puts
// the caller's agent group ID into `id` on groups/destinations —
// that's not a verb request, so ignore it.
const autoFilled = ctx.caller === 'agent' && args.id === ctx.agentGroupId;
const verbArg = !autoFilled && typeof args.id === 'string' ? args.id : null;
if (verbArg) {
const deep = renderVerbHelp(res, verbArg);
if (!deep) throw new Error(`no verb "${verbArg}" on ${res.plural} — run \`ncl ${res.plural} help\``);
return deep;
}
lines.push(`${res.plural}: ${res.description}`);
if (cliScope === 'group' && GROUP_SCOPE_RESOURCES.has(res.plural)) {
@@ -92,23 +106,27 @@ export function registerResourceHelpCommands(): void {
lines.push('');
// Verbs
// Verbs — one summary line each; deep help is a verb away. Only the
// exceptional access levels are tagged: `open` is the unmarked default.
const idAutoFilled = cliScope === 'group' && (res.plural === 'groups' || res.plural === 'destinations');
const idHint = idAutoFilled ? '' : ' <id>';
const tag = (access: string | undefined) => (!access || access === 'open' ? '' : ` [${access}]`);
const verbs: string[] = [];
if (res.operations.list) verbs.push(`list [open]`);
if (res.operations.get) verbs.push(`get${idHint} [open]`);
if (res.operations.create) verbs.push(`create [approval]`);
if (res.operations.update) verbs.push(`update${idHint} [approval]`);
if (res.operations.delete) verbs.push(`delete${idHint} [approval]`);
if (res.operations.list) verbs.push(`list${tag(res.operations.list)}`);
if (res.operations.get) verbs.push(`get${idHint}${tag(res.operations.get)}`);
if (res.operations.create) verbs.push(`create${tag(res.operations.create)}`);
if (res.operations.update) verbs.push(`update${idHint}${tag(res.operations.update)}`);
if (res.operations.delete) verbs.push(`delete${idHint}${tag(res.operations.delete)}`);
if (res.customOperations) {
for (const [verb, op] of Object.entries(res.customOperations)) {
verbs.push(`${verb} [${op.access}]${op.description}`);
verbs.push(`${verb}${tag(op.access)}${summaryLine(op.description)}`);
}
}
lines.push('Verbs:');
for (const v of verbs) lines.push(` ${v}`);
lines.push('');
lines.push(`Run \`ncl ${res.plural} help <verb>\` (or add --help to any command) for flags and examples.`);
lines.push('');
// Columns
const autoFilledFields =
+173
View File
@@ -0,0 +1,173 @@
import { describe, it, expect, vi } from 'vitest';
vi.mock('../db/connection.js', () => ({ getDb: vi.fn() }));
vi.mock('../db/container-configs.js', () => ({
getContainerConfig: vi.fn(() => ({ cli_scope: 'group' })),
}));
import { registerResource, validateArgs } from './crud.js';
import { registerResourceHelpCommands } from './commands/help.js';
import { lookup } from './registry.js';
import type { CallerContext } from './frame.js';
// --- validateArgs unit ---
describe('validateArgs', () => {
const defs = [
{ name: 'target', type: 'string' as const, description: 'Target.', required: true },
{ name: 'count', type: 'number' as const, description: 'Count.', default: 1 },
{ name: 'force', type: 'boolean' as const, description: 'Force.' },
{ name: 'meta', type: 'json' as const, description: 'Meta.' },
{ name: 'size', type: 'string' as const, description: 'Size.', enum: ['s', 'm', 'l'] },
];
it('coerces types per declaration', () => {
const out = validateArgs(defs, { target: 'x', count: '5', force: 'true', meta: '{"a":1}' });
expect(out).toMatchObject({ target: 'x', count: 5, force: true, meta: { a: 1 } });
});
it('applies defaults for absent optional flags', () => {
expect(validateArgs(defs, { target: 'x' }).count).toBe(1);
});
it('rejects a missing required flag', () => {
expect(() => validateArgs(defs, {})).toThrow('--target is required');
});
it('rejects unknown flags', () => {
expect(() => validateArgs(defs, { target: 'x', bogus: '1' })).toThrow('unknown flag --bogus');
});
it('tolerates dispatch-injected keys without declaration', () => {
const out = validateArgs(defs, { target: 'x', id: 'ag-1', agent_group_id: 'ag-1', group: 'ag-1' });
expect(out.id).toBe('ag-1');
});
it('rejects enum violations', () => {
expect(() => validateArgs(defs, { target: 'x', size: 'xl' })).toThrow('--size must be one of: s, m, l');
});
it('rejects non-numeric values for number flags', () => {
expect(() => validateArgs(defs, { target: 'x', count: 'many' })).toThrow('--count must be a number');
});
it('rejects a value-less flag on a non-boolean (client sends true)', () => {
expect(() => validateArgs(defs, { target: true })).toThrow('--target requires a value');
});
it('accepts a value-less boolean flag', () => {
expect(validateArgs(defs, { target: 'x', force: true }).force).toBe(true);
});
it('rejects invalid JSON', () => {
expect(() => validateArgs(defs, { target: 'x', meta: '{nope' })).toThrow('--meta must be valid JSON');
});
});
// --- registerResource wiring: strict where declared, lenient otherwise ---
registerResource({
name: 'widget',
plural: 'widgets',
table: 'widgets',
description: 'Test widgets.',
idColumn: 'id',
columns: [
{ name: 'id', type: 'string', description: 'UUID.', generated: true },
{ name: 'name', type: 'string', description: 'Display name.', required: true, updatable: true },
],
operations: {},
customOperations: {
ping: {
access: 'open',
description: 'Ping a widget.',
args: [{ name: 'target', type: 'string', description: 'Where to ping.', required: true }],
examples: ['ncl widgets ping --target prod'],
handler: async (args) => ({ echo: args }),
},
legacy: {
access: 'open',
description: 'Legacy op without declared args.',
handler: async (args) => ({ echo: args }),
},
},
});
registerResourceHelpCommands();
describe('strict validation wiring (declared args)', () => {
const parse = lookup('widgets-ping')!.parseArgs;
it('passes and coerces valid args', () => {
expect(parse({ target: 'prod' })).toMatchObject({ target: 'prod' });
});
it('failure carries the verb usage block (error + fix in one round-trip)', () => {
let message = '';
try {
parse({});
} catch (e) {
message = (e as Error).message;
}
expect(message).toContain('--target is required');
expect(message).toContain('ncl widgets ping'); // usage line
expect(message).toContain('Flags:');
expect(message).toContain('Examples:');
});
it('rejects unknown flags with the usage block', () => {
expect(() => parse({ target: 'prod', bogus: '1' })).toThrow(/unknown flag --bogus[\s\S]*Flags:/);
});
it('normalizes dashed flags before validating', () => {
// --target arrives as raw key "target"; a dashed alias like "tar-get" would
// normalize to underscores — prove normalize runs before validate.
expect(() => parse({ 'bogus-flag': '1', target: 'x' })).toThrow('unknown flag --bogus-flag');
});
});
describe('lenient ops (no declared args) keep legacy behavior', () => {
it('passes stray flags through untouched', () => {
const parse = lookup('widgets-legacy')!.parseArgs;
expect(parse({ anything: 'goes', 'dash-key': '1' })).toMatchObject({ anything: 'goes', dash_key: '1' });
});
});
// --- resource help: deep verb view + group-scope auto-fill guard ---
describe('resource help command', () => {
const helpCmd = lookup('widgets-help')!;
const host: CallerContext = { caller: 'host' };
const agent: CallerContext = {
caller: 'agent',
sessionId: 'sess-1',
agentGroupId: 'ag-1',
messagingGroupId: 'mg-1',
};
it('renders the resource overview with verb summaries', async () => {
const out = (await helpCmd.handler(helpCmd.parseArgs({}), host)) as string;
expect(out).toContain('widgets: Test widgets.');
expect(out).toContain('ping — Ping a widget.');
expect(out).toContain('help <verb>');
});
it('renders deep help for `help <verb>` (id from prefix fallback)', async () => {
const out = (await helpCmd.handler(helpCmd.parseArgs({ id: 'ping' }), host)) as string;
expect(out).toContain('ncl widgets ping');
expect(out).toContain('--target');
expect(out).toContain('Examples:');
});
it('errors on an unknown verb', async () => {
await expect(helpCmd.handler(helpCmd.parseArgs({ id: 'bogus' }), host)).rejects.toThrow(
'no verb "bogus" on widgets',
);
});
it('treats an auto-filled agent group id as no verb (scoped agent, plain help)', async () => {
// dispatch auto-fills id=ctx.agentGroupId on groups/destinations; the
// handler must show the overview, not "no verb <uuid>".
const out = (await helpCmd.handler(helpCmd.parseArgs({ id: 'ag-1' }), agent)) as string;
expect(out).toContain('widgets: Test widgets.');
});
});
+112 -3
View File
@@ -9,6 +9,7 @@
import { randomUUID } from 'crypto';
import { getDb } from '../db/connection.js';
import { renderVerbHelp } from './help-render.js';
import { register } from './registry.js';
import type { Access } from './registry.js';
import type { CallerContext } from './frame.js';
@@ -37,9 +38,21 @@ export interface ColumnDef {
export interface CustomOperation {
access: Access;
/** First line = one-line summary (resource help). Full text renders in the
* per-verb deep help (`ncl <resource> help <verb>` / `--help`). */
description: string;
/**
* Declaring args opts this verb into strict validation: required/enum/type
* checks plus unknown-flag rejection, with the verb's generated usage block
* appended to every failure. Omit to keep the legacy lenient behavior
* (handler validates by hand, stray flags ignored).
*/
args?: ColumnDef[];
/** Ready-to-paste invocations, rendered under EXAMPLES in deep help. */
examples?: string[];
handler: (args: Record<string, unknown>, ctx: CallerContext) => Promise<unknown>;
/** Presentational renderer for human mode — see CommandDef.formatHuman. */
formatHuman?: (data: unknown) => string;
}
export interface ResourceDef {
@@ -110,8 +123,11 @@ function genericList(def: ResourceDef) {
}
const where = filters.length > 0 ? ` WHERE ${filters.join(' AND ')}` : '';
params.push(limit);
// Newest first: without an ORDER BY the LIMIT silently hides the most
// recently inserted rows once a table outgrows it (bit `sessions list`
// past 200 sessions — a just-created session was invisible).
return getDb()
.prepare(`SELECT ${cols} FROM ${def.table}${where} LIMIT ?`)
.prepare(`SELECT ${cols} FROM ${def.table}${where} ORDER BY rowid DESC LIMIT ?`)
.all(...params);
};
}
@@ -222,6 +238,85 @@ function normalizeArgs(raw: Record<string, unknown>): Record<string, unknown> {
return out;
}
// ---------------------------------------------------------------------------
// Strict arg validation (opt-in via CustomOperation.args)
// ---------------------------------------------------------------------------
/**
* Keys the dispatcher may inject into `req.args` before parseArgs runs
* (group-scope auto-fill). Strict validation must tolerate them even when a
* verb doesn't declare them, or every scoped agent call breaks.
*/
const DISPATCH_INJECTED_KEYS = ['id', 'agent_group_id', 'group'] as const;
/**
* Validate `args` (already underscore-normalized) against a ColumnDef list:
* unknown-flag rejection, required, enum, and type coercion per the declared
* type. Returns a coerced copy; throws with a focused message on the first
* problem. Works from any ColumnDef list so generic CRUD resources can opt
* into the same strictness later without a second validator.
*/
export function validateArgs(
defs: ColumnDef[],
args: Record<string, unknown>,
opts: { allowExtra?: readonly string[] } = {},
): Record<string, unknown> {
const declared = new Map(defs.map((d) => [d.name, d]));
const allowed = new Set<string>([...declared.keys(), ...(opts.allowExtra ?? DISPATCH_INJECTED_KEYS)]);
for (const key of Object.keys(args)) {
if (!allowed.has(key)) {
throw new Error(`unknown flag --${key.replace(/_/g, '-')}`);
}
}
const out: Record<string, unknown> = { ...args };
for (const def of defs) {
const flag = `--${def.name.replace(/_/g, '-')}`;
const v = args[def.name];
if (v === undefined) {
if (def.required) throw new Error(`${flag} is required`);
if (def.default !== undefined) out[def.name] = def.default;
continue;
}
// The client parses a value-less `--flag` as boolean true.
if (v === true && def.type !== 'boolean') {
throw new Error(`${flag} requires a value`);
}
switch (def.type) {
case 'number': {
const n = Number(v);
if (Number.isNaN(n)) throw new Error(`${flag} must be a number, got "${v}"`);
out[def.name] = n;
break;
}
case 'boolean': {
if (v === true || v === 'true' || v === '1') out[def.name] = true;
else if (v === false || v === 'false' || v === '0') out[def.name] = false;
else throw new Error(`${flag} must be true or false, got "${v}"`);
break;
}
case 'json': {
if (typeof v === 'string') {
try {
out[def.name] = JSON.parse(v);
} catch {
throw new Error(`${flag} must be valid JSON`);
}
}
break;
}
case 'string':
out[def.name] = String(v);
break;
}
if (def.enum && !def.enum.includes(String(out[def.name]))) {
throw new Error(`${flag} must be one of: ${def.enum.join(', ')}`);
}
}
return out;
}
// ---------------------------------------------------------------------------
// registerResource
// ---------------------------------------------------------------------------
@@ -286,16 +381,30 @@ export function registerResource(def: ResourceDef): void {
});
}
// Custom operations
// Custom operations. Declaring `args` opts the verb into strict validation;
// every failure carries the verb's usage block so a caller (human or agent)
// can fix the invocation without a second help round-trip.
if (def.customOperations) {
for (const [verb, op] of Object.entries(def.customOperations)) {
const declared = op.args;
register({
name: `${def.plural}-${verb.replace(/ /g, '-')}`,
description: op.description,
access: op.access,
resource: def.plural,
parseArgs: (raw) => normalizeArgs(raw),
parseArgs: declared
? (raw) => {
try {
return validateArgs(declared, normalizeArgs(raw));
} catch (e) {
const usage = renderVerbHelp(def, verb);
const msg = e instanceof Error ? e.message : String(e);
throw new Error(usage ? `${msg}\n\n${usage}` : msg);
}
}
: (raw) => normalizeArgs(raw),
handler: async (args, ctx) => op.handler(args as Record<string, unknown>, ctx),
formatHuman: op.formatHuman,
});
}
}
+260 -7
View File
@@ -174,6 +174,17 @@ register({
handler: async () => ({ agent_group_id: 'g1', model: 'opus' }),
});
// A dash-joined command whose custom-operation key contains spaces
// ('config update') — used by the --help space/dash bridging test.
register({
name: 'groups-config-update',
description: 'bare registry description (should not be the help answer)',
resource: 'groups',
access: 'open',
parseArgs: (raw) => raw,
handler: async (args) => ({ echo: args }),
});
// The real `sessions-get` name — triggers the pre-handler ownership check.
register({
name: 'sessions-get',
@@ -595,18 +606,260 @@ describe('CLI scope enforcement', () => {
});
});
// --- Dash-joined positional id resolution (generated ids contain dashes) ---
// Multi-segment command, to prove the longest-prefix match (verb itself has dashes).
register({
name: 'groups-cfg-get',
description: 'test multi-segment command',
resource: 'groups',
access: 'open',
parseArgs: (raw) => raw,
handler: async (args) => ({ echo: args }),
});
describe('dash-joined positional id resolution', () => {
it('resolves `groups-get-<uuid-with-dashes>` to (groups get, id=<uuid>)', async () => {
const uuid = '550e8400-e29b-41d4-a716-446655440000';
describe('positional dashed-id resolution', () => {
const host = { caller: 'host' as const };
const resp = await dispatch({ id: '1', command: `groups-get-${uuid}`, args: {} }, { caller: 'host' });
it('resolves a long dashed id to command + intact id (no shredding)', async () => {
const id = 'task-374f0630-d3e0-4965-81da-fe4bf7a6a442';
const resp = await dispatch({ id: '1', command: `groups-test-${id}`, args: {} }, host);
expect(resp.ok).toBe(true);
if (resp.ok) expect(resp.data).toEqual({ echo: { id } });
});
it('matches the LONGEST command prefix when the verb itself has dashes', async () => {
const resp = await dispatch({ id: '2', command: 'groups-cfg-get-abc-123', args: {} }, host);
expect(resp.ok).toBe(true);
if (resp.ok) expect(resp.data).toEqual({ echo: { id: 'abc-123' } });
});
it('leaves a registered no-id command alone', async () => {
const resp = await dispatch({ id: '3', command: 'groups-test', args: {} }, host);
expect(resp.ok).toBe(true);
if (resp.ok) expect(resp.data).toEqual({ echo: {} });
});
it('does not override an explicit --id', async () => {
const resp = await dispatch({ id: '4', command: 'groups-test-tail', args: { id: 'explicit' } }, host);
expect(resp.ok).toBe(true);
if (resp.ok) expect(resp.data).toEqual({ echo: { id: 'explicit' } });
});
});
// --- `--help` interception: answer with generated help, execute nothing ---
describe('--help interception', () => {
it('returns command help instead of executing (open command)', async () => {
const resp = await dispatch({ id: '1', command: 'test-cmd', args: { help: true } }, { caller: 'host' });
expect(resp.ok).toBe(true);
if (resp.ok) {
const data = resp.data as { echo: Record<string, unknown> };
expect(data.echo.id).toBe(uuid);
// No deep resource def for 'test' → falls back to the description.
expect(resp.data).toBe('test command (non-group resource)');
}
});
it('carries the help text in `human` so clients print it verbatim', async () => {
const resp = await dispatch({ id: '1', command: 'test-cmd', args: { help: true } }, { caller: 'host' });
expect(resp.ok).toBe(true);
if (resp.ok) {
expect(typeof resp.data).toBe('string');
expect(resp.human).toBe(resp.data);
}
});
it('never mints an approval card for --help on an approval-gated command', async () => {
mockGetContainerConfig.mockReturnValue({ cli_scope: 'group' });
mockGetSession.mockReturnValue({ id: 's1', agent_group_id: 'g1', messaging_group_id: 'mg1' });
const resp = await dispatch({ id: '1', command: 'approval-context-command', args: { help: true } }, agentCtx());
expect(resp.ok).toBe(true);
expect(approvalState.requestApproval).not.toHaveBeenCalled();
expect(approvalState.observedContexts).toHaveLength(0); // handler never ran
});
it('renders deep verb help when the resource def is available', async () => {
mockGetResource.mockImplementation((plural: string) =>
plural === 'groups'
? {
name: 'group',
plural: 'groups',
table: 'agent_groups',
description: 'Agent groups.',
idColumn: 'id',
scopeField: 'id',
columns: [],
operations: {},
customOperations: {
test: {
access: 'open',
description: 'Deep test op.',
args: [{ name: 'foo', type: 'string', description: 'A foo.', required: true }],
handler: async () => ({}),
},
},
}
: undefined,
);
const resp = await dispatch({ id: '1', command: 'groups-test', args: { help: true } }, { caller: 'host' });
expect(resp.ok).toBe(true);
if (resp.ok) {
expect(resp.data).toContain('ncl groups test');
expect(resp.data).toContain('--foo');
expect(resp.data).toContain('(required)');
}
});
it('renders deep verb help for a multi-word custom-operation key (spaces vs dashes)', async () => {
// registerResource stores the op under 'config update' but registers the
// command as 'groups-config-update'; help must bridge the two.
mockGetResource.mockImplementation((plural: string) =>
plural === 'groups'
? {
name: 'group',
plural: 'groups',
table: 'agent_groups',
description: 'Agent groups.',
idColumn: 'id',
scopeField: 'id',
columns: [],
operations: {},
customOperations: {
'config update': {
access: 'open',
description: 'Update container config.',
args: [{ name: 'model', type: 'string', description: 'Model override.' }],
handler: async () => ({}),
},
},
}
: undefined,
);
const resp = await dispatch({ id: '1', command: 'groups-config-update', args: { help: true } }, { caller: 'host' });
expect(resp.ok).toBe(true);
if (resp.ok) {
expect(resp.data).toContain('ncl groups config update');
expect(resp.data).toContain('--model');
// Not the bare registry description fallback:
expect(resp.data).not.toBe('bare registry description (should not be the help answer)');
}
});
it('still enforces group scope before answering --help', async () => {
mockGetContainerConfig.mockReturnValue({ cli_scope: 'group' });
const resp = await dispatch({ id: '1', command: 'wirings-list', args: { help: true } }, agentCtx());
expect(resp.ok).toBe(false);
if (!resp.ok) expect(resp.error.code).toBe('forbidden');
});
});
// --- Unknown-command errors carry their fix ---
describe('unknown-command errors', () => {
it('lists the resource verbs when the command names a known resource', async () => {
mockGetResource.mockImplementation((plural: string) =>
plural === 'groups'
? {
name: 'group',
plural: 'groups',
table: 'agent_groups',
description: 'Agent groups.',
idColumn: 'id',
columns: [],
operations: { list: 'open', get: 'open' },
customOperations: {
restart: { access: 'approval', description: 'Restart.', handler: async () => ({}) },
},
}
: undefined,
);
const resp = await dispatch({ id: '1', command: 'groups-restrat', args: {} }, { caller: 'host' });
expect(resp.ok).toBe(false);
if (!resp.ok) {
expect(resp.error.code).toBe('unknown-command');
expect(resp.error.message).toContain('verbs for groups: list, get, restart');
expect(resp.error.message).toContain('ncl groups help');
}
});
it('suggests the closest command name for near-miss typos', async () => {
const resp = await dispatch({ id: '1', command: 'test-cm', args: {} }, { caller: 'host' });
expect(resp.ok).toBe(false);
if (!resp.ok) {
expect(resp.error.code).toBe('unknown-command');
expect(resp.error.message).toContain('did you mean "test-cmd"?');
}
});
it('falls back to a plain pointer when nothing is close', async () => {
const resp = await dispatch({ id: '1', command: 'zzz-qqq-vvv', args: {} }, { caller: 'host' });
expect(resp.ok).toBe(false);
if (!resp.ok) {
expect(resp.error.message).toContain('no command "zzz-qqq-vvv"');
expect(resp.error.message).toContain('ncl help');
expect(resp.error.message).not.toContain('did you mean');
}
});
});
// --- formatHuman hook: server-rendered human view on the frame ---
describe('formatHuman hook', () => {
register({
name: 'render-cmd',
description: 'command with a human renderer',
access: 'open',
parseArgs: (raw) => raw,
handler: async () => [{ id: 'x1', status: 'live' }],
formatHuman: (rows) => `TABLE(${(rows as { id: string }[]).map((r) => r.id).join(',')})`,
});
register({
name: 'render-throws',
description: 'command whose renderer throws',
access: 'open',
parseArgs: (raw) => raw,
handler: async () => ({ fine: true }),
formatHuman: () => {
throw new Error('renderer bug');
},
});
it('attaches human alongside data', async () => {
const resp = await dispatch({ id: '1', command: 'render-cmd', args: {} }, { caller: 'host' });
expect(resp.ok).toBe(true);
if (resp.ok) {
expect(resp.human).toBe('TABLE(x1)');
expect(resp.data).toEqual([{ id: 'x1', status: 'live' }]); // machine contract intact
}
});
it('a throwing renderer degrades to a plain frame, never an error', async () => {
const resp = await dispatch({ id: '1', command: 'render-throws', args: {} }, { caller: 'host' });
expect(resp.ok).toBe(true);
if (resp.ok) {
expect(resp.human).toBeUndefined();
expect(resp.data).toEqual({ fine: true });
}
});
it('commands without a renderer stay human-less', async () => {
const resp = await dispatch({ id: '1', command: 'test-cmd', args: {} }, { caller: 'host' });
expect(resp.ok).toBe(true);
if (resp.ok) expect(resp.human).toBeUndefined();
});
});
+116 -16
View File
@@ -12,7 +12,8 @@ import { getSession } from '../db/sessions.js';
import { registerApprovalHandler, requestApproval } from '../modules/approvals/index.js';
import type { CallerContext, ErrorCode, RequestFrame, ResponseFrame } from './frame.js';
import { getResource } from './crud.js';
import { lookup } from './registry.js';
import { listVerbs, renderVerbHelp } from './help-render.js';
import { GROUP_SCOPE_RESOURCES, listCommands, lookup } from './registry.js';
type DispatchOptions = {
/** True when a command is being replayed after approval. */
@@ -26,21 +27,22 @@ export async function dispatch(
): Promise<ResponseFrame> {
let cmd = lookup(req.command);
// Fallback: if the full command isn't registered, split the dash-joined
// command and treat the longest registered prefix as the command, with the
// re-joined remainder as the target ID. Clients join all positional args
// with dashes (e.g. `ncl groups get abc123` → command "groups-get-abc123"),
// and generated ids (UUIDs, `sess-…`, `appr-…`) themselves contain dashes,
// so trimming a single trailing segment isn't enough — walk prefixes from
// longest to shortest so `groups-get-<uuid-with-dashes>` still resolves to
// "groups-get" + id "<uuid-with-dashes>".
// Fallback: if the full command isn't registered, find the LONGEST registered
// command that is a dash-prefix of req.command; the remainder is the target ID,
// kept intact (dashes and all). This lets clients join all positional args with
// dashes e.g. `ncl groups get abc123` → "groups-get-abc123" → "groups-get" +
// id "abc123", and crucially `ncl tasks cancel task-374f-...-442` →
// "tasks-cancel" + id "task-374f-...-442" (a dashed id is no longer shredded).
// Trimming from the end (longestshortest) means a multi-segment verb like
// "groups-config-add-mcp-server" still matches before any shorter prefix.
if (!cmd) {
const parts = req.command.split('-');
for (let i = parts.length - 1; i > 0; i--) {
const shortened = parts.slice(0, i).join('-');
let shortened = req.command;
let idx: number;
while ((idx = shortened.lastIndexOf('-')) > 0) {
shortened = shortened.slice(0, idx);
const fallback = lookup(shortened);
if (fallback) {
const tail = parts.slice(i).join('-');
const tail = req.command.slice(shortened.length + 1); // full remainder = id, dashes intact
cmd = fallback;
req = { ...req, command: shortened, args: { ...req.args, id: req.args.id ?? tail } };
break;
@@ -49,7 +51,7 @@ export async function dispatch(
}
if (!cmd) {
return err(req.id, 'unknown-command', `no command "${req.command}"`);
return err(req.id, 'unknown-command', unknownCommandMessage(req.command));
}
// CLI scope enforcement for agent callers
@@ -62,9 +64,8 @@ export async function dispatch(
}
if (cliScope === 'group') {
const allowed = new Set(['groups', 'sessions', 'destinations', 'members']);
// Only allow whitelisted resources and general commands (no resource, like help)
if (cmd.resource && !allowed.has(cmd.resource)) {
if (cmd.resource && !GROUP_SCOPE_RESOURCES.has(cmd.resource)) {
return err(req.id, 'forbidden', `CLI access is scoped to this agent group. Cannot access "${cmd.resource}".`);
}
@@ -115,6 +116,17 @@ export async function dispatch(
}
}
// `--help` interception: answer with the command's generated help instead of
// executing. Placed after scope enforcement (a group-scoped agent can't probe
// forbidden resources) and BEFORE approval gating — asking for help on an
// approval-gated verb must never mint an approval card.
if (req.args.help === true) {
// Carry the help text in `human` too, so both clients print it verbatim
// as clean multi-line text instead of a JSON-stringified blob.
const helpText = commandHelp(cmd.name, cmd.resource, cmd.description);
return { id: req.id, ok: true, data: helpText, human: helpText };
}
if (ctx.caller !== 'host' && cmd.access === 'approval' && !opts.approved) {
const session = getSession(ctx.sessionId);
if (!session) {
@@ -186,6 +198,17 @@ export async function dispatch(
}
}
// Server-render the human view once, so every transport — host CLI and
// the Bun container client (which can't import host formatters) — prints
// one canonical rendering. Runs after scope filtering; a throwing
// formatter degrades to plain `data`, never fails the response.
if (cmd.formatHuman) {
try {
return { id: req.id, ok: true, data, human: cmd.formatHuman(data) };
} catch {
// fall through to the plain frame
}
}
return { id: req.id, ok: true, data };
} catch (e) {
return err(req.id, 'handler-error', errMsg(e));
@@ -225,6 +248,83 @@ function parseCallerContext(value: unknown): CallerContext | undefined {
return undefined;
}
/** Help text for a resolved command: deep verb help when derivable, else description. */
function commandHelp(name: string, resource: string | undefined, description: string): string {
if (resource && name.startsWith(`${resource}-`)) {
const res = getResource(resource);
const verb = name.slice(resource.length + 1);
const deep = res && renderVerbHelp(res, verb);
if (deep) return deep;
// Custom-operation KEYS may contain spaces ('config update') while command
// names are dash-joined ('groups-config-update'). Resolve by matching keys
// normalized the same way registerResource builds command names.
if (res?.customOperations) {
const spaced = Object.keys(res.customOperations).find((k) => k.replace(/ /g, '-') === verb);
const deepSpaced = spaced && renderVerbHelp(res, spaced);
if (deepSpaced) return deepSpaced;
}
}
return description;
}
/**
* Unknown-command error that carries its fix: if the command names a known
* resource, list that resource's verbs; otherwise suggest the closest
* registered command. Resource detection walks dash-prefixes longest-first,
* same as the ID fallback above, so multi-word plurals (messaging-groups,
* user-dms) resolve.
*/
function unknownCommandMessage(command: string): string {
const parts = command.split('-');
for (let i = parts.length; i > 0; i--) {
const prefix = parts.slice(0, i).join('-');
const res = getResource(prefix);
if (res) {
return (
`no command "${command}" — verbs for ${res.plural}: ${listVerbs(res).join(', ')}. ` +
`Run \`ncl ${res.plural} help <verb>\` for flags and examples.`
);
}
}
const names = listCommands()
.filter((c) => c.access !== 'hidden')
.map((c) => c.name);
const closest = closestName(command, names);
return `no command "${command}"${closest ? ` — did you mean "${closest}"?` : ''} Run \`ncl help\`.`;
}
/** Closest name by edit distance, only when convincingly close (≤2 edits). */
function closestName(input: string, names: string[]): string | undefined {
let best: string | undefined;
let bestDist = 3;
for (const name of names) {
if (Math.abs(name.length - input.length) >= bestDist) continue;
const d = editDistance(input, name, bestDist);
if (d < bestDist) {
bestDist = d;
best = name;
}
}
return best;
}
function editDistance(a: string, b: string, cap: number): number {
const prev = new Array(b.length + 1).fill(0).map((_, i) => i);
for (let i = 1; i <= a.length; i++) {
let diag = prev[0];
prev[0] = i;
let rowMin = prev[0];
for (let j = 1; j <= b.length; j++) {
const tmp = prev[j];
prev[j] = Math.min(prev[j] + 1, prev[j - 1] + 1, diag + (a[i - 1] === b[j - 1] ? 0 : 1));
diag = tmp;
rowMin = Math.min(rowMin, prev[j]);
}
if (rowMin >= cap) return cap;
}
return prev[b.length];
}
function err(id: string, code: ErrorCode, message: string): ResponseFrame {
return { id, ok: false, error: { code, message } };
}
+8 -1
View File
@@ -18,7 +18,14 @@ export type RequestFrame = {
};
export type ResponseFrame =
| { id: string; ok: true; data: unknown }
// `human` is an optional server-rendered presentational string. It lets
// every transport — host CLI and the Bun container client — print one
// canonical rendering without importing host-only formatters (the two
// runtimes share no modules, so client-side formatters drift). `data`
// stays the machine contract; --json callers ignore `human`. Additive:
// old clients that don't know the field just fall back to their own
// rendering of `data`.
| { id: string; ok: true; data: unknown; human?: string }
| { id: string; ok: false; error: { code: ErrorCode; message: string } };
export type ErrorCode =
+95
View File
@@ -0,0 +1,95 @@
import { describe, it, expect } from 'vitest';
import type { ResourceDef } from './crud.js';
import { listVerbs, renderVerbHelp, summaryLine } from './help-render.js';
const res: ResourceDef = {
name: 'widget',
plural: 'widgets',
table: 'widgets',
description: 'Test widgets.',
idColumn: 'id',
columns: [
{ name: 'id', type: 'string', description: 'UUID.', generated: true },
{ name: 'name', type: 'string', description: 'Display name.', required: true, updatable: true },
{ name: 'size', type: 'string', description: 'Widget size.', enum: ['s', 'm', 'l'], default: 'm' },
],
operations: { list: 'open', get: 'open', create: 'approval', update: 'approval' },
customOperations: {
ping: {
access: 'open',
description: 'Ping a widget.\nLonger prose that only deep help shows.',
args: [
{ name: 'target', type: 'string', description: 'Where to ping.', required: true },
{ name: 'count', type: 'number', description: 'How many times.', default: 1 },
],
examples: ['ncl widgets ping --target prod --count 3'],
handler: async () => ({}),
},
},
};
describe('listVerbs', () => {
it('lists enabled generics then custom verbs', () => {
expect(listVerbs(res)).toEqual(['list', 'get', 'create', 'update', 'ping']);
});
});
describe('renderVerbHelp — custom operation', () => {
it('renders usage, full description, flags with tags, and examples', () => {
const out = renderVerbHelp(res, 'ping')!;
expect(out).toContain('ncl widgets ping');
expect(out).toContain('Longer prose that only deep help shows.');
expect(out).toContain('--target');
expect(out).toContain('(required)');
expect(out).toContain('--count');
expect(out).toContain('default: 1');
expect(out).toContain('Examples:');
expect(out).toContain('ncl widgets ping --target prod --count 3');
});
it('tags non-open access on the usage line', () => {
const gated: ResourceDef = {
...res,
customOperations: { ping: { ...res.customOperations!.ping, access: 'approval' } },
};
expect(renderVerbHelp(gated, 'ping')).toContain('ncl widgets ping [approval]');
});
});
describe('renderVerbHelp — generic verbs', () => {
it('create renders non-generated columns as flags', () => {
const out = renderVerbHelp(res, 'create')!;
expect(out).toContain('ncl widgets create [approval]');
expect(out).toContain('--name');
expect(out).toContain('(required)');
expect(out).toContain('--size');
expect(out).toContain('values: s | m | l');
expect(out).not.toContain('--id'); // generated
});
it('update renders only updatable columns and takes <id>', () => {
const out = renderVerbHelp(res, 'update')!;
expect(out).toContain('ncl widgets update <id> [approval]');
expect(out).toContain('--name');
expect(out).not.toContain('--size');
});
it('list renders filter flags plus --limit, never marked required', () => {
const out = renderVerbHelp(res, 'list')!;
expect(out).toContain('--limit');
expect(out).toContain('--name');
expect(out).not.toContain('(required)');
});
it('returns undefined for verbs the resource does not have', () => {
expect(renderVerbHelp(res, 'delete')).toBeUndefined(); // not in operations
expect(renderVerbHelp(res, 'bogus')).toBeUndefined();
});
});
describe('summaryLine', () => {
it('returns only the first line', () => {
expect(summaryLine('Ping a widget.\nLonger prose.')).toBe('Ping a widget.');
});
});
+115
View File
@@ -0,0 +1,115 @@
/**
* Pure renderers for command help. Single source for three surfaces that must
* never disagree:
* - `ncl <resource> help [<verb>]` (commands/help.ts)
* - `--help` on any command (dispatch interception)
* - the usage block appended to invalid-args errors (crud.ts validation)
*
* Imports only types from crud.ts, so crud.ts can import these functions at
* runtime without a cycle.
*/
import type { ColumnDef, CustomOperation, ResourceDef } from './crud.js';
const GENERIC_VERBS = ['list', 'get', 'create', 'update', 'delete'] as const;
type GenericVerb = (typeof GENERIC_VERBS)[number];
export function flagName(col: Pick<ColumnDef, 'name'>): string {
return `--${col.name.replace(/_/g, '-')}`;
}
/** First line of a possibly multi-paragraph description. */
export function summaryLine(description: string): string {
return description.split('\n', 1)[0];
}
/** Indent every non-empty line of a block by `pad`. */
export function indent(text: string, pad: string): string {
return text
.split('\n')
.map((l) => (l ? pad + l : l))
.join('\n');
}
function flagLine(col: ColumnDef, extraTags: string[] = []): string {
const tags: string[] = [...extraTags];
if (col.required) tags.push('required');
if (col.default !== undefined && col.default !== null) tags.push(`default: ${col.default}`);
if (col.enum) tags.push(`values: ${col.enum.join(' | ')}`);
const tagStr = tags.length > 0 ? ` (${tags.join(', ')})` : '';
return ` ${flagName(col).padEnd(28)} ${summaryLine(col.description)}${tagStr}`;
}
/** All verbs a resource exposes, generics first, in help order. */
export function listVerbs(res: ResourceDef): string[] {
const verbs: string[] = GENERIC_VERBS.filter((v) => res.operations[v]);
if (res.customOperations) verbs.push(...Object.keys(res.customOperations));
return verbs;
}
/** Flags a generic verb accepts, derived from the resource's columns. */
function genericFlags(res: ResourceDef, verb: GenericVerb): ColumnDef[] {
switch (verb) {
case 'create':
return res.columns.filter((c) => !c.generated);
case 'update':
return res.columns.filter((c) => c.updatable);
case 'list':
// Non-generated columns double as equality filters.
return [
...res.columns.filter((c) => !c.generated).map((c) => ({ ...c, required: false })),
{ name: 'limit', type: 'number', description: 'Max rows returned.', default: 200 } as ColumnDef,
];
case 'get':
case 'delete':
return [];
}
}
function genericSummary(res: ResourceDef, verb: GenericVerb): string {
switch (verb) {
case 'list':
return `List ${res.plural}. Flags below act as equality filters.`;
case 'get':
return `Get a ${res.name} by ID.`;
case 'create':
return `Create a new ${res.name}.`;
case 'update':
return `Update a ${res.name} by ID. Provide at least one updatable flag.`;
case 'delete':
return `Delete a ${res.name} by ID.`;
}
}
/**
* Deep help for one verb: usage line, full description, flags, examples.
* `verb` is a custom-operation key or a generic CRUD verb. Returns undefined
* for a verb the resource doesn't have.
*/
export function renderVerbHelp(res: ResourceDef, verb: string): string | undefined {
const op: CustomOperation | undefined = res.customOperations?.[verb];
const generic = !op && (GENERIC_VERBS as readonly string[]).includes(verb) ? (verb as GenericVerb) : undefined;
if (!op && !generic) return undefined;
if (generic && !res.operations[generic]) return undefined;
const access = op ? op.access : res.operations[generic!];
const accessTag = access && access !== 'open' ? ` [${access}]` : '';
const needsId = generic === 'get' || generic === 'update' || generic === 'delete';
const lines: string[] = [];
lines.push(`ncl ${res.plural} ${verb}${needsId ? ' <id>' : ''}${accessTag}`);
lines.push('');
lines.push(op ? op.description : genericSummary(res, generic!));
const flags = op ? (op.args ?? []) : genericFlags(res, generic!);
if (flags.length > 0) {
lines.push('');
lines.push('Flags:');
for (const f of flags) lines.push(flagLine(f));
}
if (op?.examples?.length) {
lines.push('');
lines.push('Examples:');
for (const ex of op.examples) lines.push(indent(ex, ' '));
}
return lines.join('\n');
}
+16 -1
View File
@@ -10,7 +10,14 @@
*/
import type { CallerContext } from './frame.js';
export type Access = 'open' | 'approval';
/**
* Resources an agent under `cli_scope=group` may touch. Single source
* consumed by both dispatch enforcement and `ncl help` filtering, so the
* agent is never shown a resource the gate would reject (or vice versa).
*/
export const GROUP_SCOPE_RESOURCES = new Set(['groups', 'sessions', 'destinations', 'members']);
export type Access = 'open' | 'approval' | 'hidden';
export type CommandDef<TArgs = unknown, TData = unknown> = {
name: string;
@@ -34,6 +41,14 @@ export type CommandDef<TArgs = unknown, TData = unknown> = {
/** Validates `frame.args` and produces the typed handler input. Throws on invalid. */
parseArgs: (raw: Record<string, unknown>) => TArgs;
handler: (args: TArgs, ctx: CallerContext) => Promise<TData>;
/**
* Optional presentational renderer. When set, dispatch attaches its output
* as the response frame's `human` field (server-rendered once, printed
* verbatim by every client in human mode). Runs after post-handler scope
* filtering, so it only ever sees data the caller is allowed to see. A
* throwing formatter is ignored clients fall back to rendering `data`.
*/
formatHuman?: (data: TData) => string;
};
const registry = new Map<string, CommandDef>();
+9 -3
View File
@@ -3,9 +3,10 @@
* Spawns agent containers with session folder + agent group folder mounts.
* The container runs the v2 agent-runner which polls the session DB.
*/
import { ChildProcess, execSync, spawn } from 'child_process';
import { ChildProcess, exec, spawn } from 'child_process';
import fs from 'fs';
import path from 'path';
import { promisify } from 'util';
import { OneCLI } from '@onecli-sh/sdk';
@@ -504,6 +505,8 @@ async function buildContainerArgs(
return args;
}
const execAsync = promisify(exec);
/** Build a per-agent-group Docker image with custom packages. */
export async function buildAgentGroupImage(agentGroupId: string): Promise<void> {
const agentGroup = getAgentGroup(agentGroupId);
@@ -539,9 +542,12 @@ export async function buildAgentGroupImage(agentGroupId: string): Promise<void>
const tmpDockerfile = path.join(DATA_DIR, `Dockerfile.${agentGroupId}`);
fs.writeFileSync(tmpDockerfile, dockerfile);
try {
execSync(`${CONTAINER_RUNTIME_BIN} build -t ${imageTag} -f ${tmpDockerfile} .`, {
// Awaited async exec so the single-threaded host stays responsive during
// the build (can take minutes) instead of blocking on execSync. exec buffers
// stdout/stderr (matching the old stdio: 'pipe') and rejects on a non-zero
// exit, so error propagation is unchanged.
await execAsync(`${CONTAINER_RUNTIME_BIN} build -t ${imageTag} -f ${tmpDockerfile} .`, {
cwd: DATA_DIR,
stdio: 'pipe',
timeout: 900_000,
});
} finally {
+5 -3
View File
@@ -12,9 +12,11 @@ must stay inside this directory — absolute paths, `~`, and `../` escapes are
rejected. Override the location with `NANOCLAW_TEMPLATES_DIR=/another/local/path`
(a local path only — never a URL).
The setup wizard's **Template setup → NanoClaw template library** option clones
the public registry and copies your chosen template *into this folder*, after
which it stamps from the local copy. **Local templates** lists whatever is here.
To use a template from the public registry
([`nanocoai/nanoclaw-templates`](https://github.com/nanocoai/nanoclaw-templates)),
clone or download it yourself and copy the chosen template *into this folder*,
then stamp from the local copy. There is no remote fetch — templates are only
ever resolved from here.
## Anatomy of a template