@koalaauto/agentchannel 3.45.2 → 3.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/src/adapters/codex.js +4 -0
  2. package/dist/src/args.d.ts +1 -1
  3. package/dist/src/args.js +16 -62
  4. package/dist/src/caps.d.ts +25 -2
  5. package/dist/src/caps.js +75 -11
  6. package/dist/src/cli-admin.d.ts +3 -0
  7. package/dist/src/cli-admin.js +307 -0
  8. package/dist/src/cli-memory.d.ts +3 -0
  9. package/dist/src/cli-memory.js +138 -0
  10. package/dist/src/cli-run.d.ts +28 -0
  11. package/dist/src/cli-run.js +429 -0
  12. package/dist/src/cli-shared.d.ts +73 -0
  13. package/dist/src/cli-shared.js +159 -0
  14. package/dist/src/cli.d.ts +9 -38
  15. package/dist/src/cli.js +64 -1181
  16. package/dist/src/client.d.ts +31 -22
  17. package/dist/src/client.js +16 -29
  18. package/dist/src/codexdaemon.d.ts +22 -0
  19. package/dist/src/codexdaemon.js +68 -0
  20. package/dist/src/invite_people.d.ts +31 -0
  21. package/dist/src/invite_people.js +238 -0
  22. package/dist/src/invite_person.d.ts +1 -1
  23. package/dist/src/invite_person.js +1 -1
  24. package/dist/src/mcp.d.ts +1 -1
  25. package/dist/src/mcp.js +14 -47
  26. package/dist/src/prompts.d.ts +2 -2
  27. package/dist/src/prompts.js +6 -17
  28. package/dist/src/runner/home.d.ts +45 -0
  29. package/dist/src/runner/home.js +150 -0
  30. package/dist/src/runner/runner.d.ts +3 -76
  31. package/dist/src/runner/runner.js +25 -327
  32. package/dist/src/runner/structured.d.ts +20 -0
  33. package/dist/src/runner/structured.js +64 -0
  34. package/dist/src/runner/traces.d.ts +29 -0
  35. package/dist/src/runner/traces.js +119 -0
  36. package/dist/src/sandboxcheck.d.ts +3 -0
  37. package/dist/src/sandboxcheck.js +16 -1
  38. package/dist/src/version.d.ts +1 -1
  39. package/dist/src/version.js +1 -1
  40. package/package.json +1 -1
  41. package/dist/src/import.d.ts +0 -244
  42. package/dist/src/import.js +0 -998
@@ -3,6 +3,7 @@ import { closeSync, existsSync, openSync, readdirSync, readSync, statSync } from
3
3
  import { join } from 'node:path';
4
4
  import { readable, systemPaths } from './scope.js';
5
5
  import { KILL_GRACE_MS } from './procgroup.js';
6
+ import { ensureCodexDaemonDir } from '../codexdaemon.js';
6
7
  import { CAPS_SERVER } from '../caps.js';
7
8
  import { modelId } from './types.js';
8
9
  export const DEFAULT_CODEX_PRICE = { input: 1.25, cached_input: 0.125, output: 10 };
@@ -329,6 +330,9 @@ export class CodexAdapter {
329
330
  denyRead: [...(opts.denyReadPaths ?? []), ...(opts.env.CODEX_HOME ? [opts.env.CODEX_HOME] : [])],
330
331
  realHome: opts.realHome,
331
332
  });
333
+ // Codex will not start its sandbox over a wrong socket folder: put it right (a problem left shows in Codex's own error)
334
+ if (sandbox.length && process.platform !== 'win32')
335
+ ensureCodexDaemonDir();
332
336
  const codex = new Codex(codexClientOptions(opts.env, [...sandbox, ...codexCapsOverrides(opts.caps)]));
333
337
  const thread = opts.resume ? codex.resumeThread(opts.resume, to) : codex.startThread(to);
334
338
  const price = this.o.price ?? priceFromEnv(opts.env);
@@ -16,5 +16,5 @@ export declare function parseCli(argv: string[]): Parsed;
16
16
  * runs over the more indented lines under it.
17
17
  */
18
18
  export declare function helpFor(words: string[]): string;
19
- export declare const HELP = "ach - AgentChannel CLI\n\nSetup: npx -y @koalaauto/agentchannel@3 join <ach2.invite> [--name <n>] [--service] [--yes] [--dry-run] (run it in the\n project directory: a line from the panel's \"Connect an agent\" creates the agent there, named\n \"<your name>-<directory>\" (lowercase) unless --name says otherwise; a line from the panel or\n `ach admin invite <agent>`: stores the agent's key and adds the `ach` MCP server to the agent's own tool\n (Claude Code or Codex). In a terminal it shows the hub and every command first and asks once; --yes skips\n that; run by an agent (no terminal) it just does it. --service also installs the background helper\n (notifications only where there is a desktop). --dry-run prints the plan and uses nothing)\n ach login --hub <url> --key <ach_sk_...> | ach me | ach agents\n ach owners [<repo>] (the team's projects and who answers for each: agents, people, an admin's note)\n ach doctor (hub, front door, key; then this machine: which `ach` runs, claude/codex login and MCP entry)\n ach doctor --codex-sandbox-setup (Windows, Codex agents: sets up Codex's elevated sandbox once; run it in a terminal opened as administrator)\n ach notify --test (shows a test desktop notification: checks the background helper can reach you)\nTasks: ach send --to <agent> --title <t> --priority P0..P3 --purpose <p> --key-question <q> --money <m> --handoff-file <f>\n [--depends <id> ...] (not handed out until those tasks complete) [--base <branch|commit>] [--repo <name>] [--read-repo <name>[@base] ...] [--attach <file> ...]\n [--review] (the task waits for acceptance when its worker is done: ach accept or ach request-changes)\n ach accept <task> [<note>] | ach request-changes <task> \"<what to change>\" (the sender's side judges work sent with --review)\n ach handoff <taskId> --note <change note> [--file <f>] [--priority P0..P3] [--purpose p] [--money m] [--key-question q] [--attach <file> ...]\n [--channel <name>] (default: the channel named like --repo, else #general)\n ach task <id|TASK-128> (lists attachments with download URLs) | ach inbox [--owner]\n Every task argument also takes the TASK-<seq> number shown in the panel (TASK-128; T-128 still works).\n ach download <taskId> [--out <dir>] (fetches every attachment; default ./ach-files-<taskId>)\nRecurring: ach schedule add --to <agent> --title <t> --money <m> --handoff-file <f> --every day|weekday|week|month --at HH:MM\n [--weekday 1..7] [--day 1..28] [--tz +08:00] [--purpose p] [--priority P0..P3] [--channel <name>]\n (a proposal: it runs only after your owner replies \"approve\"; {date} in the title/handoff becomes the run's date;\n a run is skipped while the previous one is still open)\n ach schedule add ... --on task_completed|task_failed|figure|post --match '<json>' (an event rule instead of a time:\n task: {\"to\":\"puller\",\"title\":\"pull\"} (its own tasks only); figure: {\"topic\":\"ads\",\"metric\":\"Meta daily spend\",\"op\":\">\",\"value\":5000};\n post: {\"channel\":\"ci\",\"contains\":\"failed\"}. {ref} {title} {link} {metric} {value} {unit} {text} fill the title/handoff)\n ach schedules | ach schedule pause <id> | ach schedule resume <id> | ach schedule rm <id> (resume: your owner, in the panel or with a person's session)\nMessages: ach ask [--task <id>] [--to <agent>] \"<question>\"\n ach answer [--task <id>] --reply-to <msgId> --evidence \"<files/commands>\" \"<answer>\"\n ach decide [--task <id>] <requestId> \"<reply>\" (interactive sessions only, with your agent key: your owner's reply, marked \"via <agent>\")\n ach decide [--task <id>] <requestId> --grant <id> --option <n> (a runner, within an authorization grant)\nAuthorization: ach grant (--agent <name> | --person <who>) (--task <TASK-n> | --channel <name>) --cap <usd> [--until YYYY-MM-DD]\n [--note \"<guidance>\"] [--requester <agent|person>] (your agent key: you, present, grant it; never a run token)\n ach grants | ach revoke <grantId>\n ach ask-human [--task <id>] [--to both|<person name|email>] \"<one question>\" --option \"A|detail|$450\" --option \"B|detail|$0\" [--recommend 0]\n (2\u20133 options, recommended first, money/impact on each; the person replies by picking one or typing;\n `decide-request` is the older name)\n ach progress [--task <id>] \"<text>\" | ach note [--task <id>] \"<text>\"\n Each takes --attach <file> (repeatable; png, jpg, webp, gif, mp4, webm, mov; text/code up to 2 MB:\n txt md json ts js py go sh diff patch log csv yaml sql; .html reports; inside a spawned\n agent the file must be inside the working directory).\nChannels: ach channels [--all] | ach channel [<#name>] [--since <iso>] [--before <iso>] [--limit n]\n ach post <#name|name|title> \"<text>\" [--attach <file> ...] [--announce] (@agent mentions wake that agent for a read-only reply;\n an @name that matches nobody is warned about, with the closest name;\n --announce: \"shipped\" / \"data published\": an announcement every channel reader is notified of)\n ach reply [<postId>] \"<text>\" [--evidence \"<files/commands>\"] [--escalate [--to owner|asker] [--ask \"<one line to decide>\"] | --as-owner] [--attach <file> ...]\n (postId defaults to $ACH_THREAD_ID in a mention run)\n ach thread <postId> | ach search \"<query>\" [--channel <name>] [--author <agent|person>] [--limit n]\n Inside a spawned agent: no new top-level posts; replies only in the task's own thread.\nMemory: ach recall \"<query>\" [--limit 5] (one line + link per hit: what the team already knows)\n ach remember [--channel <name>] [--topic <slug>] --source <link> \"<one fact or lesson>\" (source: hub permalink or GitHub URL)\n ach remember --to-team --source <link> \"<one fact>\" (members of a private channel: make one statement team-visible;\n its source stays private: others see \"source: private channel\")\n ach decide-draft [--by <person>] --source <link> [--task <id>] [--topic <slug>] [--scope task|channel] \"<the decision>\"\n (asks that person; their reply records it. Task-only unless it says \"from now on\"/\"always\"/\"\u4EE5\u540E\u90FD\")\n ach memory search \"<query>\" [--limit n] | ach memory read <slug>\n ach memory pull <dir> [--channel <name>] | ach memory push <dir> --note \"<what changed>\" (maintainers; Markdown + YAML\n front matter; per-page note: in front matter; every problem line is listed with its reason)\n ach memory seed --from-imports (maintainers: one upkeep task per channel over its imported GitHub issues/PRs)\n ach memory hook [--channel <name> | --task <id>] (a bounded Memory summary for a Claude Code SessionStart hook;\n default: --channel, $ACH_TASK_ID, a .ach-channel file in this or a parent directory, else your main channel)\n ach memory lang [en|zh] (admins: the language pages are written in)\nWorking: ach claim <task> (take a task sent to your agent and work it yourself, interactively; no runner starts)\nFinishing: ach complete [--task <id>] [--run-id <r>] [--result-file <f> | \"<text>\"] [--attach <file> ...]\n ach fail [--task <id>] [--run-id <r>] [--cause <c> --needs <what>] \"<reason>\" | ach cancel <id> [--reason <r>]\n With your agent key and no --run-id: an unclaimed task sent to your agent is claimed interactively\n first (complete), or declined (fail); a task you claimed with `ach claim` uses that claim.\nCapabilities: ach caps (lists the host capabilities in <agent home>/capabilities.json: commands your runner's agents may run\n outside their sandbox, with no approval, for anyone who sends them a task or mentions them)\n ach caps run <name> [arg=value ...] (runs one here, as a run would: to check a declaration)\nRunner: ach run --dir <path> [--repo name=path ...] [--runtime claude|codex|kiro] [--interval 3] [--max 2]\n [--perm read|workdir|full] [--model m] [--pass-env NAME ...]\n [--claim-delay <sec> | --interactive-first] (default 0; --interactive-first = 60 s for you to claim first)\n [--no-trace] (keep execution traces on this machine; ACH_NO_TRACE=1 too)\n [--notify] (desktop notifications for what needs your owner, the same items as their browser\n notifications; off by default; macOS needs terminal-notifier)\n ach run --install-service [same flags] (installs and starts a launchd/systemd user unit; runs at login)\n ach run --gc [--dir <path>] [--days 7]\nMCP: ach mcp (stdio server; your interactive agent can also claim and work tasks)\nPanel: ach open [--print] (opens the panel in your browser, logged in as this agent's owner; 60 s single-use link)\nAdmin: ach admin login --link <login link>\n ach admin users | ach admin create-user --name <n> [--email <e>] [--admin] (prints a 24 h one-time join link)\n ach admin login-link <email|userId> (a new one-time login link for a new device)\n ach admin user <email|userId> [--deactivate [--reassign-to <user>] | --reactivate] [--admin true|false] [--confirm-name <name>] [--name n] [--email e]\n ach admin create-agent --name <slug> [--owner <email|userId>] --runtime claude|codex|kiro|other --description <d>\n [--perm read|workdir|full] [--budget <usd>] [--net-allow a.com,b.com] [--invite] [--cf-token]\n ach admin invite <agent> [--line] [--lang zh|en] [--cf-token] (rotates the key; prints a paragraph to paste into the engineer's\n Claude/Codex: join, background helper + notifications, a test notification, the inbox. --line: only\n the join line npx -y @koalaauto/agentchannel@3 join <blob>. Language: --lang, else the hub's (Memory) language.\n --cf-token: also put the hub's shared front-door (Cloudflare Access) token in the line; off by default)\n ach admin invite <person> [--feishu] (prints a one-time login link; --feishu sends it on Feishu)\nOnboarding: ach admin import github --org <org> [--since 60d] --dry-run [--out plan.json] (reads GitHub with your gh login; writes a plan)\n ach admin import github --org <org> --link <one-time admin link> [--yes] (the line from the panel's Settings -> Import:\n logs in with the 15-minute link for this import only, shows the dry run, then imports on a yes / --yes)\n ach admin import github --org <org> [--plan plan.json] (channels, people, issues/PRs; idempotent, re-run updates)\n Two ranges: posted to channels = open items + items closed/merged in the last N days\n [--post-closed-days N (alias --closed-days), default 7 | --all]; used to seed Memory (links only) = closed\n items of the last M months [--seed-months M, default 6 | --seed-all]. The hub keeps both for sync.\n [--exclude security,secret,... | --no-exclude] (default exclusion:\n security, \u5B89\u5168, \u6F0F\u6D1E, secret, \u5BC6\u94A5 in labels or title: never sent, not even an excerpt)\n Plan: \"visibility\": \"private\" on a channel + people \"channels\" = members-only (the hub otherwise\n widens access: everyone on the hub reads team channels, even repos they cannot see on GitHub).\n ach admin sync github [--org <org>] [same range and --exclude flags] (issues/PRs updated since the last\n import/sync; items that closed since then still update their posts; releases too; cron-friendly)\n [--every 5m [--runs N]] (keep syncing in a loop; or cron: */5 * * * * ach admin sync github)\n ach admin invite --feishu [--people a,b] [--map login=ou_xxx ...] [--yes] (Feishu DMs via lark-cli; preview without --yes)\n ach admin invite --people a,b --yes (prints one-time login links to send yourself)\n ach admin rotate-key <name|id> | ach admin set <agentId> [--active true|false] [--perm p] [--budget usd]\n [--description d] [--accept-from a,b] [--net-allow a.com,b.com]\n ach admin profile [--notify-webhook <url>] [--name <n>] (your own account)\n ach admin decide --task <id> --message <msgId> \"<decision>\" [--attach <file> ...]\n ach admin note --task <id> \"<text>\" [--attach <file> ...] (a human note to the agents on a task)\n ach admin channels [list | create [--name path] [--folder f] [--title t] | archive <#name> | unarchive <#name>]\n ach admin channels move <#old> <#new-path> (a channel is a path like reela/onair, at most 3 levels; the old path keeps working)\n ach admin channels private|team <#name> [--cascade] (private: members and admins only; never wider than the channel above)\n ach admin channels members <#name> [--add a,b] [--remove c] (people by email or GitHub login)\n ach admin embeds [--set host1,host2] (embed allowlist; public suffixes are refused)\n ach admin wiki-lang [en|zh] (= ach memory lang: the language Memory pages are written in; default ACH_DEFAULT_LANG)\n ach admin memory-maintainers [<agent> ...] (who keeps Memory current; no name: show it. Default: the admin agent with no setup problem seen most recently)\n ach admin memory-upkeep [<#channel>] (queue Memory upkeep now; also restarts one paused after repeated failures)\n\n--task defaults to $ACH_TASK_ID. Links use ACH_PUBLIC_URL when set (else the hub URL). Env: ACH_HUB, ACH_KEY, ACH_RUN_TOKEN, ACH_CF_ID, ACH_CF_SECRET, AGENTCHANNEL_HOME,\nACH_KEYSTORE=file (store the agent key in a 0600 file instead of the OS keychain; Linux always uses the file).\nHome: ~/.config/agentchannel ($XDG_CONFIG_HOME/agentchannel; AGENTCHANNEL_HOME overrides).\nInside a spawned agent (ACH_RUN_TOKEN set) login, join, open, admin, run, mcp, send, handoff, cancel, doctor, post and search are refused.\n";
19
+ export declare const HELP = "ach - AgentChannel CLI\n\nSetup: npx -y @koalaauto/agentchannel@3 join <ach2.invite> [--name <n>] [--service] [--yes] [--dry-run] (run it in the\n project directory: a line from the panel's \"Connect an agent\" creates the agent there, named\n \"<your name>-<directory>\" (lowercase) unless --name says otherwise; a line from the panel or\n `ach admin invite <agent>`: stores the agent's key and adds the `ach` MCP server to the agent's own tool\n (Claude Code or Codex). In a terminal it shows the hub and every command first and asks once; --yes skips\n that; run by an agent (no terminal) it just does it. --service also installs the background helper\n (notifications only where there is a desktop). --dry-run prints the plan and uses nothing)\n ach login --hub <url> --key <ach_sk_...> | ach me | ach agents\n ach owners [<repo>] (the team's projects and who answers for each: agents, people, an admin's note)\n ach doctor (hub, front door, key; then this machine: which `ach` runs, claude/codex login and MCP entry)\n ach doctor --codex-sandbox-setup (Windows, Codex agents: sets up Codex's elevated sandbox once; run it in a terminal opened as administrator)\n ach notify --test (shows a test desktop notification: checks the background helper can reach you)\nTasks: ach send --to <agent> --title <t> --priority P0..P3 --purpose <p> --key-question <q> --money <m> --handoff-file <f>\n [--depends <id> ...] (not handed out until those tasks complete) [--base <branch|commit>] [--repo <name>] [--read-repo <name>[@base] ...] [--attach <file> ...]\n [--review] (the task waits for acceptance when its worker is done: ach accept or ach request-changes)\n ach accept <task> [<note>] | ach request-changes <task> \"<what to change>\" (the sender's side judges work sent with --review)\n ach handoff <taskId> --note <change note> [--file <f>] [--priority P0..P3] [--purpose p] [--money m] [--key-question q] [--attach <file> ...]\n [--channel <name>] (default: the channel named like --repo, else #general)\n ach task <id|TASK-128> (lists attachments with download URLs) | ach inbox [--owner]\n Every task argument also takes the TASK-<seq> number shown in the panel (TASK-128; T-128 still works).\n ach download <taskId> [--out <dir>] (fetches every attachment; default ./ach-files-<taskId>)\nMessages: ach ask [--task <id>] [--to <agent>] \"<question>\"\n ach answer [--task <id>] --reply-to <msgId> --evidence \"<files/commands>\" \"<answer>\"\n ach decide [--task <id>] <requestId> \"<reply>\" (interactive sessions only, with your agent key: your owner's reply, marked \"via <agent>\")\n ach ask-human [--task <id>] [--to both|<person name|email>] \"<one question>\" --option \"A|detail|$450\" --option \"B|detail|$0\" [--recommend 0]\n (2\u20133 options, recommended first, money/impact on each; the person replies by picking one or typing;\n `decide-request` is the older name)\n ach ask-human [--task <id>] \"<one question>\" --action <capability> [--arg k=v ...] [--money \"$86\"]\n (a capability your owner declared confirm: true: the person who asked for the work confirms that exact call;\n then call the capability with the same arguments, once)\n ach about [--task <id>] <source:id> (what this task is about in another system, e.g. batch:20261118_003; set once)\n ach related <source:id> (the tasks and outside events about it)\n ach progress [--task <id>] \"<text>\" | ach note [--task <id>] \"<text>\"\n Each takes --attach <file> (repeatable; png, jpg, webp, gif, mp4, webm, mov; text/code up to 2 MB:\n txt md json ts js py go sh diff patch log csv yaml sql; .html reports; inside a spawned\n agent the file must be inside the working directory).\nChannels: ach channels [--all] | ach channel [<#name>] [--since <iso>] [--before <iso>] [--limit n]\n ach post <#name|name|title> \"<text>\" [--attach <file> ...] [--announce] (@agent mentions wake that agent for a read-only reply;\n an @name that matches nobody is warned about, with the closest name;\n --announce: \"shipped\" / \"data published\": an announcement every channel reader is notified of)\n ach reply [<postId>] \"<text>\" [--evidence \"<files/commands>\"] [--escalate [--to owner|asker] [--ask \"<one line to decide>\"] | --as-owner] [--attach <file> ...]\n (postId defaults to $ACH_THREAD_ID in a mention run)\n ach thread <postId> | ach search \"<query>\" [--channel <name>] [--author <agent|person>] [--limit n]\n Inside a spawned agent: no new top-level posts; replies only in the task's own thread.\nMemory: ach recall \"<query>\" [--limit 5] (one line + link per hit: what the team already knows)\n ach remember [--channel <name>] [--topic <slug>] --source <link> \"<one fact or lesson>\" (source: hub permalink or GitHub URL)\n ach remember --to-team --source <link> \"<one fact>\" (members of a private channel: make one statement team-visible;\n its source stays private: others see \"source: private channel\")\n ach decide-draft [--by <person>] --source <link> [--task <id>] [--topic <slug>] [--scope task|channel] \"<the decision>\"\n (asks that person; their reply records it. Task-only unless it says \"from now on\"/\"always\"/\"\u4EE5\u540E\u90FD\")\n ach memory search \"<query>\" [--limit n] | ach memory read <slug>\n ach memory pull <dir> [--channel <name>] | ach memory push <dir> --note \"<what changed>\" (maintainers; Markdown + YAML\n front matter; per-page note: in front matter; every problem line is listed with its reason)\n ach memory hook [--channel <name> | --task <id>] (a bounded Memory summary for a Claude Code SessionStart hook;\n default: --channel, $ACH_TASK_ID, a .ach-channel file in this or a parent directory, else your main channel)\n ach memory lang [en|zh] (admins: the language pages are written in)\nWorking: ach claim <task> (take a task sent to your agent and work it yourself, interactively; no runner starts)\nFinishing: ach complete [--task <id>] [--run-id <r>] [--result-file <f> | \"<text>\"] [--attach <file> ...]\n ach fail [--task <id>] [--run-id <r>] [--cause <c> --needs <what>] \"<reason>\" | ach cancel <id> [--reason <r>]\n With your agent key and no --run-id: an unclaimed task sent to your agent is claimed interactively\n first (complete), or declined (fail); a task you claimed with `ach claim` uses that claim.\nCapabilities: ach caps (lists the host capabilities in <agent home>/capabilities.json: commands your runner's agents may run\n outside their sandbox, with no approval, for anyone who sends them a task or mentions them)\n ach caps run <name> [arg=value ...] (runs one here, as a run would: to check a declaration)\nRunner: ach run --dir <path> [--repo name=path ...] [--runtime claude|codex|kiro] [--interval 3] [--max 2]\n [--perm read|workdir|full] [--model m] [--pass-env NAME ...]\n [--claim-delay <sec> | --interactive-first] (default 0; --interactive-first = 60 s for you to claim first)\n [--no-trace] (keep execution traces on this machine; ACH_NO_TRACE=1 too)\n [--notify] (desktop notifications for what needs your owner, the same items as their browser\n notifications; off by default; macOS needs terminal-notifier)\n ach run --install-service [same flags] (installs and starts a launchd/systemd user unit; runs at login)\n ach run --gc [--dir <path>] [--days 7]\nMCP: ach mcp (stdio server; your interactive agent can also claim and work tasks)\nPanel: ach open [--print] (opens the panel in your browser, logged in as this agent's owner; 60 s single-use link)\nAdmin: ach admin login --link <login link>\n ach admin users | ach admin create-user --name <n> [--email <e>] [--admin] (prints a 24 h one-time join link)\n ach admin login-link <email|userId> (a new one-time login link for a new device)\n ach admin user <email|userId> [--deactivate [--reassign-to <user>] | --reactivate] [--admin true|false] [--confirm-name <name>] [--name n] [--email e]\n ach admin create-agent --name <slug> [--owner <email|userId>] --runtime claude|codex|kiro|other --description <d>\n [--perm read|workdir|full] [--budget <usd>] [--net-allow a.com,b.com] [--invite] [--cf-token]\n ach admin invite <agent> [--line] [--lang zh|en] [--cf-token] (rotates the key; prints a paragraph to paste into the engineer's\n Claude/Codex: join, background helper + notifications, a test notification, the inbox. --line: only\n the join line npx -y @koalaauto/agentchannel@3 join <blob>. Language: --lang, else the hub's (Memory) language.\n --cf-token: also put the hub's shared front-door (Cloudflare Access) token in the line; off by default)\n ach admin invite <person> [--feishu] (prints a one-time login link; --feishu sends it on Feishu)\nOnboarding: ach admin invite --feishu [--people a,b] [--map login=ou_xxx ...] [--yes] (Feishu DMs via lark-cli; preview without --yes)\n ach admin invite --people a,b --yes (prints one-time login links to send yourself)\n ach admin rotate-key <name|id> | ach admin set <agentId> [--active true|false] [--perm p] [--budget usd]\n [--description d] [--accept-from a,b] [--net-allow a.com,b.com]\n ach admin profile [--notify-webhook <url>] [--name <n>] (your own account)\n ach admin decide --task <id> --message <msgId> \"<decision>\" [--attach <file> ...]\n ach admin note --task <id> \"<text>\" [--attach <file> ...] (a human note to the agents on a task)\n ach admin channels [list | create [--name path] [--folder f] [--title t] | archive <#name> | unarchive <#name>]\n ach admin channels move <#old> <#new-path> (a channel is a path like reela/onair, at most 3 levels; the old path keeps working)\n ach admin channels private|team <#name> [--cascade] (private: members and admins only; never wider than the channel above)\n ach admin channels members <#name> [--add a,b] [--remove c] (people by email or GitHub login)\n ach admin wiki-lang [en|zh] (= ach memory lang: the language Memory pages are written in; default ACH_DEFAULT_LANG)\n ach admin memory-upkeep [<#channel>] (queue Memory upkeep now; also restarts one paused after repeated failures)\n\n--task defaults to $ACH_TASK_ID. Links use ACH_PUBLIC_URL when set (else the hub URL). Env: ACH_HUB, ACH_KEY, ACH_RUN_TOKEN, ACH_CF_ID, ACH_CF_SECRET, AGENTCHANNEL_HOME,\nACH_KEYSTORE=file (store the agent key in a 0600 file instead of the OS keychain; Linux always uses the file).\nHome: ~/.config/agentchannel ($XDG_CONFIG_HOME/agentchannel; AGENTCHANNEL_HOME overrides).\nInside a spawned agent (ACH_RUN_TOKEN set) login, join, open, admin, run, mcp, send, handoff, cancel, doctor, post and search are refused.\n";
20
20
  export {};
package/dist/src/args.js CHANGED
@@ -20,14 +20,6 @@ export const COMMANDS = {
20
20
  'request-changes': { task: s, ...json },
21
21
  handoff: { file: s, note: s, priority: s, purpose: s, money: s, 'key-question': s, attach: sm, 'attach-url': sm, ...json },
22
22
  task: { ...json },
23
- 'schedule add': {
24
- channel: s, to: s, title: s, priority: s, purpose: s, money: s, 'handoff-file': s, handoff: s,
25
- every: s, at: s, weekday: s, day: s, tz: s, on: s, match: s, ...json,
26
- },
27
- 'schedule list': { ...json },
28
- 'schedule pause': { ...json },
29
- 'schedule resume': { ...json },
30
- 'schedule rm': { ...json },
31
23
  download: { out: s, ...json },
32
24
  inbox: { owner: b, ...json },
33
25
  channels: { all: b, ...json },
@@ -38,12 +30,11 @@ export const COMMANDS = {
38
30
  search: { channel: s, author: s, limit: s, ...json },
39
31
  ask: { task: s, to: s, attach: sm, 'attach-url': sm, ...json },
40
32
  answer: { task: s, 'reply-to': s, evidence: s, attach: sm, 'attach-url': sm, ...json },
41
- 'ask-human': { task: s, to: s, attach: sm, 'attach-url': sm, option: sm, recommend: s, ...json },
42
- decide: { task: s, option: s, grant: s, ...json },
43
- grant: { agent: s, person: s, task: s, channel: s, cap: s, until: s, note: s, requester: s, ...json },
44
- grants: { ...json },
45
- revoke: { ...json },
46
- 'decide-request': { task: s, to: s, attach: sm, 'attach-url': sm, option: sm, recommend: s, ...json },
33
+ 'ask-human': { task: s, to: s, attach: sm, 'attach-url': sm, option: sm, recommend: s, action: s, arg: sm, money: s, ...json },
34
+ related: { ...json },
35
+ about: { task: s, ...json },
36
+ decide: { task: s, ...json },
37
+ 'decide-request': { task: s, to: s, attach: sm, 'attach-url': sm, option: sm, recommend: s, action: s, arg: sm, money: s, ...json },
47
38
  progress: { task: s, attach: sm, 'attach-url': sm, ...json },
48
39
  note: { task: s, attach: sm, 'attach-url': sm, ...json },
49
40
  complete: { task: s, 'result-file': s, cost: s, 'run-id': s, 'owner-action': s, attach: sm, 'attach-url': sm, ...json },
@@ -64,23 +55,18 @@ export const COMMANDS = {
64
55
  'admin user': { deactivate: b, reactivate: b, 'reassign-to': s, 'confirm-name': s, admin: s, name: s, email: s, ...json },
65
56
  'admin create-agent': { name: s, owner: s, runtime: s, description: s, perm: s, budget: s, 'accept-from': s, 'net-allow': s, invite: b, 'cf-token': b, ...json },
66
57
  'admin invite': { 'cf-id': s, 'cf-secret': s, 'cf-token': b, line: b, lang: s, feishu: b, people: s, map: sm, yes: b, ...json },
67
- 'admin import': { link: s, hub: s, yes: b, org: s, since: s, plan: s, out: s, 'dry-run': b, 'closed-days': s, 'post-closed-days': s, all: b, 'seed-months': s, 'seed-all': b, exclude: s, 'no-exclude': b, ...json },
68
- 'admin sync': { org: s, every: s, runs: s, since: s, 'closed-days': s, 'post-closed-days': s, all: b, 'seed-months': s, 'seed-all': b, exclude: s, 'no-exclude': b, ...json },
69
58
  'admin profile': { 'notify-webhook': s, name: s, ...json },
70
59
  'admin rotate-key': { 'cf-token': b, yes: b, ...json },
71
60
  'admin set': { active: s, perm: s, budget: s, description: s, 'accept-from': s, 'net-allow': s, ...json },
72
61
  'admin decide': { task: s, message: s, attach: sm, 'attach-url': sm, ...json },
73
62
  'admin channels': { name: s, folder: s, title: s, description: s, add: s, remove: s, cascade: b, ...json },
74
- 'admin embeds': { set: s, ...json },
75
63
  'admin memory-upkeep': { ...json },
76
- 'admin memory-maintainers': { ...json },
77
64
  'admin note': { task: s, attach: sm, 'attach-url': sm, ...json },
78
65
  remember: { source: s, channel: s, topic: s, 'to-team': b, ...json },
79
66
  'decide-draft': { source: s, by: s, channel: s, topic: s, task: s, scope: s, ...json },
80
67
  recall: { limit: s, ...json },
81
68
  'memory pull': { channel: s, ...json },
82
69
  'memory push': { note: s, ...json },
83
- 'memory seed': { 'from-imports': b, ...json },
84
70
  'memory search': { limit: s, ...json },
85
71
  'memory read': { ...json },
86
72
  'memory lang': { ...json },
@@ -98,13 +84,13 @@ export function parseCli(argv) {
98
84
  if (first === '--version' || first === '-v')
99
85
  return { cmd: 'version', values: {}, positionals: [] };
100
86
  let cmd = first;
101
- // `ach admin --help`, `ach memory -h`, `ach schedule --help`: the group's help, before a subcommand is expected
102
- if (['admin', 'memory', 'wiki', 'schedule'].includes(first) && (rest[0] === '--help' || rest[0] === '-h'))
87
+ // `ach admin --help`, `ach memory -h`: the group's help, before a subcommand is expected
88
+ if (['admin', 'memory', 'wiki'].includes(first) && (rest[0] === '--help' || rest[0] === '-h'))
103
89
  return { cmd: 'help', values: {}, positionals: [first === 'wiki' ? 'memory' : first] };
104
90
  if (first === 'admin') {
105
91
  const sub = rest[0];
106
92
  if (!sub)
107
- throw new UsageError('admin needs a subcommand: login, users, create-user, login-link, user, create-agent, invite, import, sync, rotate-key, set, profile, decide, note, channels, embeds, storage, wiki-lang');
93
+ throw new UsageError('admin needs a subcommand: login, users, create-user, login-link, user, create-agent, invite, rotate-key, set, profile, decide, note, channels, storage, wiki-lang');
108
94
  cmd = `admin ${sub}`;
109
95
  rest = rest.slice(1);
110
96
  }
@@ -112,18 +98,10 @@ export function parseCli(argv) {
112
98
  if (first === 'memory' || first === 'wiki') {
113
99
  const sub = rest[0];
114
100
  if (!sub)
115
- throw new UsageError('memory needs a subcommand: pull, push, seed, search, read, lang, hook');
101
+ throw new UsageError('memory needs a subcommand: pull, push, search, read, lang, hook');
116
102
  cmd = `memory ${sub}`;
117
103
  rest = rest.slice(1);
118
104
  }
119
- if (first === 'schedule' || first === 'schedules') {
120
- const sub = first === 'schedules' ? 'list' : rest[0];
121
- if (!sub)
122
- throw new UsageError('schedule needs a subcommand: add, list, pause, resume, rm');
123
- cmd = `schedule ${sub}`;
124
- if (first === 'schedule')
125
- rest = rest.slice(1);
126
- }
127
105
  const options = COMMANDS[cmd];
128
106
  if (!options)
129
107
  throw new UsageError(`Unknown command "${cmd}". Run \`ach help\`.`);
@@ -146,7 +124,7 @@ export function parseCli(argv) {
146
124
  export function helpFor(words) {
147
125
  const cmd = words.join(' ');
148
126
  const known = Object.keys(COMMANDS).filter((k) => k !== 'help' && k !== 'version');
149
- const key = known.includes(cmd) ? cmd : known.includes(words.slice(0, 2).join(' ')) ? words.slice(0, 2).join(' ') : words[0] === 'schedules' ? 'schedule list' : words[0] ?? '';
127
+ const key = known.includes(cmd) ? cmd : known.includes(words.slice(0, 2).join(' ')) ? words.slice(0, 2).join(' ') : words[0] ?? '';
150
128
  const lines = HELP.split('\n');
151
129
  const entries = [];
152
130
  for (const line of lines) {
@@ -193,24 +171,17 @@ Tasks: ach send --to <agent> --title <t> --priority P0..P3 --purpose <p> --
193
171
  ach task <id|TASK-128> (lists attachments with download URLs) | ach inbox [--owner]
194
172
  Every task argument also takes the TASK-<seq> number shown in the panel (TASK-128; T-128 still works).
195
173
  ach download <taskId> [--out <dir>] (fetches every attachment; default ./ach-files-<taskId>)
196
- Recurring: ach schedule add --to <agent> --title <t> --money <m> --handoff-file <f> --every day|weekday|week|month --at HH:MM
197
- [--weekday 1..7] [--day 1..28] [--tz +08:00] [--purpose p] [--priority P0..P3] [--channel <name>]
198
- (a proposal: it runs only after your owner replies "approve"; {date} in the title/handoff becomes the run's date;
199
- a run is skipped while the previous one is still open)
200
- ach schedule add ... --on task_completed|task_failed|figure|post --match '<json>' (an event rule instead of a time:
201
- task: {"to":"puller","title":"pull"} (its own tasks only); figure: {"topic":"ads","metric":"Meta daily spend","op":">","value":5000};
202
- post: {"channel":"ci","contains":"failed"}. {ref} {title} {link} {metric} {value} {unit} {text} fill the title/handoff)
203
- ach schedules | ach schedule pause <id> | ach schedule resume <id> | ach schedule rm <id> (resume: your owner, in the panel or with a person's session)
204
174
  Messages: ach ask [--task <id>] [--to <agent>] "<question>"
205
175
  ach answer [--task <id>] --reply-to <msgId> --evidence "<files/commands>" "<answer>"
206
176
  ach decide [--task <id>] <requestId> "<reply>" (interactive sessions only, with your agent key: your owner's reply, marked "via <agent>")
207
- ach decide [--task <id>] <requestId> --grant <id> --option <n> (a runner, within an authorization grant)
208
- Authorization: ach grant (--agent <name> | --person <who>) (--task <TASK-n> | --channel <name>) --cap <usd> [--until YYYY-MM-DD]
209
- [--note "<guidance>"] [--requester <agent|person>] (your agent key: you, present, grant it; never a run token)
210
- ach grants | ach revoke <grantId>
211
177
  ach ask-human [--task <id>] [--to both|<person name|email>] "<one question>" --option "A|detail|$450" --option "B|detail|$0" [--recommend 0]
212
178
  (2–3 options, recommended first, money/impact on each; the person replies by picking one or typing;
213
179
  \`decide-request\` is the older name)
180
+ ach ask-human [--task <id>] "<one question>" --action <capability> [--arg k=v ...] [--money "$86"]
181
+ (a capability your owner declared confirm: true: the person who asked for the work confirms that exact call;
182
+ then call the capability with the same arguments, once)
183
+ ach about [--task <id>] <source:id> (what this task is about in another system, e.g. batch:20261118_003; set once)
184
+ ach related <source:id> (the tasks and outside events about it)
214
185
  ach progress [--task <id>] "<text>" | ach note [--task <id>] "<text>"
215
186
  Each takes --attach <file> (repeatable; png, jpg, webp, gif, mp4, webm, mov; text/code up to 2 MB:
216
187
  txt md json ts js py go sh diff patch log csv yaml sql; .html reports; inside a spawned
@@ -232,7 +203,6 @@ Memory: ach recall "<query>" [--limit 5] (one line + link per hit: what th
232
203
  ach memory search "<query>" [--limit n] | ach memory read <slug>
233
204
  ach memory pull <dir> [--channel <name>] | ach memory push <dir> --note "<what changed>" (maintainers; Markdown + YAML
234
205
  front matter; per-page note: in front matter; every problem line is listed with its reason)
235
- ach memory seed --from-imports (maintainers: one upkeep task per channel over its imported GitHub issues/PRs)
236
206
  ach memory hook [--channel <name> | --task <id>] (a bounded Memory summary for a Claude Code SessionStart hook;
237
207
  default: --channel, $ACH_TASK_ID, a .ach-channel file in this or a parent directory, else your main channel)
238
208
  ach memory lang [en|zh] (admins: the language pages are written in)
@@ -265,21 +235,7 @@ Admin: ach admin login --link <login link>
265
235
  the join line npx -y @koalaauto/agentchannel@3 join <blob>. Language: --lang, else the hub's (Memory) language.
266
236
  --cf-token: also put the hub's shared front-door (Cloudflare Access) token in the line; off by default)
267
237
  ach admin invite <person> [--feishu] (prints a one-time login link; --feishu sends it on Feishu)
268
- Onboarding: ach admin import github --org <org> [--since 60d] --dry-run [--out plan.json] (reads GitHub with your gh login; writes a plan)
269
- ach admin import github --org <org> --link <one-time admin link> [--yes] (the line from the panel's Settings -> Import:
270
- logs in with the 15-minute link for this import only, shows the dry run, then imports on a yes / --yes)
271
- ach admin import github --org <org> [--plan plan.json] (channels, people, issues/PRs; idempotent, re-run updates)
272
- Two ranges: posted to channels = open items + items closed/merged in the last N days
273
- [--post-closed-days N (alias --closed-days), default 7 | --all]; used to seed Memory (links only) = closed
274
- items of the last M months [--seed-months M, default 6 | --seed-all]. The hub keeps both for sync.
275
- [--exclude security,secret,... | --no-exclude] (default exclusion:
276
- security, 安全, 漏洞, secret, 密钥 in labels or title: never sent, not even an excerpt)
277
- Plan: "visibility": "private" on a channel + people "channels" = members-only (the hub otherwise
278
- widens access: everyone on the hub reads team channels, even repos they cannot see on GitHub).
279
- ach admin sync github [--org <org>] [same range and --exclude flags] (issues/PRs updated since the last
280
- import/sync; items that closed since then still update their posts; releases too; cron-friendly)
281
- [--every 5m [--runs N]] (keep syncing in a loop; or cron: */5 * * * * ach admin sync github)
282
- ach admin invite --feishu [--people a,b] [--map login=ou_xxx ...] [--yes] (Feishu DMs via lark-cli; preview without --yes)
238
+ Onboarding: ach admin invite --feishu [--people a,b] [--map login=ou_xxx ...] [--yes] (Feishu DMs via lark-cli; preview without --yes)
283
239
  ach admin invite --people a,b --yes (prints one-time login links to send yourself)
284
240
  ach admin rotate-key <name|id> | ach admin set <agentId> [--active true|false] [--perm p] [--budget usd]
285
241
  [--description d] [--accept-from a,b] [--net-allow a.com,b.com]
@@ -290,9 +246,7 @@ Onboarding: ach admin import github --org <org> [--since 60d] --dry-run [--out p
290
246
  ach admin channels move <#old> <#new-path> (a channel is a path like reela/onair, at most 3 levels; the old path keeps working)
291
247
  ach admin channels private|team <#name> [--cascade] (private: members and admins only; never wider than the channel above)
292
248
  ach admin channels members <#name> [--add a,b] [--remove c] (people by email or GitHub login)
293
- ach admin embeds [--set host1,host2] (embed allowlist; public suffixes are refused)
294
249
  ach admin wiki-lang [en|zh] (= ach memory lang: the language Memory pages are written in; default ACH_DEFAULT_LANG)
295
- ach admin memory-maintainers [<agent> ...] (who keeps Memory current; no name: show it. Default: the admin agent with no setup problem seen most recently)
296
250
  ach admin memory-upkeep [<#channel>] (queue Memory upkeep now; also restarts one paused after repeated failures)
297
251
 
298
252
  --task defaults to $ACH_TASK_ID. Links use ACH_PUBLIC_URL when set (else the hub URL). Env: ACH_HUB, ACH_KEY, ACH_RUN_TOKEN, ACH_CF_ID, ACH_CF_SECRET, AGENTCHANNEL_HOME,
@@ -44,11 +44,21 @@ export interface Capability {
44
44
  timeout?: number;
45
45
  /** bytes returned inline (default 60000); the full output beyond that goes to a file */
46
46
  max_output?: number;
47
+ /**
48
+ * The agent may run it only after the person who asked for the work confirmed this call, arguments and all (docs/specs/
49
+ * bot-batch.md §5.1): the server redeems that confirmation on the hub first, once per confirmation. For commands that spend
50
+ * money or change what other people see. Its command may use {confirm.request}, {confirm.person}, {confirm.at}.
51
+ */
52
+ confirm?: boolean;
47
53
  }
48
54
  export interface CapsLoad {
49
55
  caps: Capability[];
50
56
  problems: string[];
51
57
  }
58
+ /** Values the server fills, never the agent: the run's task and who asked for it. */
59
+ export declare const RUN_VARS: string[];
60
+ /** Filled from the person's confirmation, for a `confirm: true` capability. */
61
+ export declare const CONFIRM_VARS: string[];
52
62
  export declare function capsPath(home: string): string;
53
63
  /** One declaration checked; a problem string, or undefined when it is usable. Pure. */
54
64
  export declare function capProblem(c: any): string | undefined;
@@ -58,8 +68,8 @@ export interface CapCall {
58
68
  argv: string[];
59
69
  stdin?: string;
60
70
  }
61
- /** The argv (and stdin) of one call, or an error the agent can act on. Pure. */
62
- export declare function buildCall(cap: Capability, input: Record<string, unknown>): CapCall | {
71
+ /** The argv (and stdin) of one call, or an error the agent can act on. `sys`: the values the server fills ({run.task}…). Pure. */
72
+ export declare function buildCall(cap: Capability, input: Record<string, unknown>, sys?: Record<string, string>): CapCall | {
63
73
  error: string;
64
74
  };
65
75
  /** The environment of a capability's command: no run token, no hub credentials, the real HOME. Pure. */
@@ -78,6 +88,8 @@ export interface CapRunOptions {
78
88
  baseEnv?: Record<string, string | undefined>;
79
89
  signal?: AbortSignal;
80
90
  now?: () => number;
91
+ /** the values the server fills ({run.task}, {confirm.person}…) */
92
+ sys?: Record<string, string>;
81
93
  }
82
94
  export interface CapResult {
83
95
  ok: boolean;
@@ -94,12 +106,14 @@ export interface CapsServerSpec {
94
106
  tools: {
95
107
  name: string;
96
108
  description: string;
109
+ confirm?: boolean;
97
110
  }[];
98
111
  }
99
112
  /** Trusted prompt text about the run's capabilities. Pure. */
100
113
  export declare function capsPromptText(tools: {
101
114
  name: string;
102
115
  description: string;
116
+ confirm?: boolean;
103
117
  }[]): string;
104
118
  /** argv of `ach caps-serve` for one run. Pure. */
105
119
  export declare function capsServeArgs(o: {
@@ -112,3 +126,12 @@ export declare function capsServeArgs(o: {
112
126
  }): string[];
113
127
  /** The stdio MCP server of `ach caps-serve`: one tool per declared capability. */
114
128
  export declare function serveCaps(argv: string[]): Promise<void>;
129
+ /**
130
+ * The values the server fills for one call: the run's task, who asked for it, and for a `confirm: true` capability the person's
131
+ * confirmation, redeemed on the hub now (after the arguments were checked, so a bad call never spends one).
132
+ */
133
+ export declare function sysValues(cap: Capability, input: Record<string, unknown>, task: string, hub: () => Promise<import('./client.js').Client>): Promise<{
134
+ values: Record<string, string>;
135
+ } | {
136
+ error: string;
137
+ }>;
package/dist/src/caps.js CHANGED
@@ -23,7 +23,11 @@ export const CAPS_FILE = 'capabilities.json';
23
23
  export const CAPS_SERVER = 'caps';
24
24
  const NAME = /^[a-z][a-z0-9_]{0,47}$/;
25
25
  const ARG = /^[a-z][a-z0-9_]{0,31}$/;
26
- const PLACEHOLDER = /\{([a-z][a-z0-9_]{0,31})\}/g;
26
+ const PLACEHOLDER = /\{([a-z][a-z0-9_]{0,31}(?:\.[a-z][a-z0-9_]{0,31})?)\}/g;
27
+ /** Values the server fills, never the agent: the run's task and who asked for it. */
28
+ export const RUN_VARS = ['run.task', 'run.requester'];
29
+ /** Filled from the person's confirmation, for a `confirm: true` capability. */
30
+ export const CONFIRM_VARS = ['confirm.request', 'confirm.person', 'confirm.at'];
27
31
  const DEFAULT_TIMEOUT = 120;
28
32
  const DEFAULT_MAX_OUTPUT = 60_000;
29
33
  /** what is kept in memory of one call's stdout before it is cut */
@@ -74,10 +78,15 @@ export function capProblem(c) {
74
78
  if (a.max !== undefined && !(Number.isInteger(a.max) && a.max > 0))
75
79
  return `${at} ${k}.max must be a positive integer`;
76
80
  }
81
+ if (c.confirm !== undefined && typeof c.confirm !== 'boolean')
82
+ return `${at} confirm must be true or false`;
77
83
  const used = [...c.command.flatMap((t) => placeholders(t)), ...(c.stdin ? placeholders(c.stdin) : [])];
78
- for (const u of used)
79
- if (!(u in args))
84
+ for (const u of used) {
85
+ if (CONFIRM_VARS.includes(u) && c.confirm !== true)
86
+ return `${at} {${u}} is only for a capability with confirm: true`;
87
+ if (u.includes('.') ? ![...RUN_VARS, ...CONFIRM_VARS].includes(u) : !(u in args))
80
88
  return `${at} {${u}} is not a declared argument`;
89
+ }
81
90
  for (const k of Object.keys(args))
82
91
  if (!used.includes(k))
83
92
  return `${at} argument ${k} is never used`;
@@ -118,8 +127,8 @@ export function loadCaps(file) {
118
127
  }
119
128
  return { caps, problems };
120
129
  }
121
- /** The argv (and stdin) of one call, or an error the agent can act on. Pure. */
122
- export function buildCall(cap, input) {
130
+ /** The argv (and stdin) of one call, or an error the agent can act on. `sys`: the values the server fills ({run.task}…). Pure. */
131
+ export function buildCall(cap, input, sys = {}) {
123
132
  const args = cap.args ?? {};
124
133
  for (const k of Object.keys(input ?? {}))
125
134
  if (!(k in args))
@@ -145,19 +154,24 @@ export function buildCall(cap, input) {
145
154
  return { error: `argument ${k} does not match ${a.pattern}` };
146
155
  vals[k] = v;
147
156
  }
157
+ for (const n of [...cap.command.flatMap(placeholders), ...(cap.stdin ? placeholders(cap.stdin) : [])]) {
158
+ if (n.includes('.') && sys[n] === undefined)
159
+ return { error: `{${n}} has no value in this run` };
160
+ }
161
+ const all = { ...sys, ...vals };
148
162
  const argv = [];
149
163
  for (const t of cap.command) {
150
164
  const names = placeholders(t);
151
- if (names.some((n) => !(n in vals)))
165
+ if (names.some((n) => !(n in all)))
152
166
  continue; // an optional argument that was not given: its token goes too
153
- const filled = t.replace(PLACEHOLDER, (_, n) => vals[n]);
167
+ const filled = t.replace(PLACEHOLDER, (_, n) => all[n]);
154
168
  // a value standing alone as an argument cannot become an option of the program
155
169
  if (names.length && t === `{${names[0]}}` && filled.startsWith('-') && !args[names[0]]?.enum?.includes(filled)) {
156
170
  return { error: `argument ${names[0]} cannot start with "-"` };
157
171
  }
158
172
  argv.push(filled);
159
173
  }
160
- return { argv, ...(cap.stdin !== undefined ? { stdin: cap.stdin.replace(PLACEHOLDER, (_, n) => vals[n] ?? '') } : {}) };
174
+ return { argv, ...(cap.stdin !== undefined ? { stdin: cap.stdin.replace(PLACEHOLDER, (_, n) => all[n] ?? '') } : {}) };
161
175
  }
162
176
  /** The environment of a capability's command: no run token, no hub credentials, the real HOME. Pure. */
163
177
  export function capEnv(base, home, extra = {}) {
@@ -190,14 +204,15 @@ function headText(b, max) {
190
204
  export async function runCap(cap, input, o) {
191
205
  const now = o.now ?? Date.now;
192
206
  const started = now();
193
- const call = buildCall(cap, input);
207
+ const call = buildCall(cap, input, o.sys);
194
208
  const log = (entry) => {
195
209
  if (!o.log)
196
210
  return;
197
211
  try {
198
212
  mkdirSync(dirname(o.log), { recursive: true });
199
213
  const args = Object.fromEntries(Object.entries(input ?? {}).map(([k, v]) => [k, String(v).slice(0, 500)]));
200
- appendFileSync(o.log, `${JSON.stringify({ at: new Date(started).toISOString(), cap: cap.name, args, ...(o.context ?? {}), ...entry })}\n`, { mode: 0o600 });
214
+ const confirmed = o.sys?.['confirm.request'] ? { confirm: o.sys['confirm.request'], confirmed_by: o.sys['confirm.person'] } : {};
215
+ appendFileSync(o.log, `${JSON.stringify({ at: new Date(started).toISOString(), cap: cap.name, args, ...(o.context ?? {}), ...confirmed, ...entry })}\n`, { mode: 0o600 });
201
216
  }
202
217
  catch {
203
218
  /* the log never stops a call */
@@ -292,9 +307,11 @@ export async function runCap(cap, input, o) {
292
307
  export function capsPromptText(tools) {
293
308
  if (!tools.length)
294
309
  return '';
310
+ const confirmed = tools.filter((t) => t.confirm).map((t) => t.name);
295
311
  return [
296
312
  `Host capabilities: your owner set these up on this machine as tools of the "${CAPS_SERVER}" MCP server. They run outside your sandbox with your owner's access and need no approval:`,
297
313
  ...tools.map((t) => `- ${t.name}: ${t.description.split('\n')[0]}`),
314
+ ...(confirmed.length ? [`These run only once the person who asked for the work confirmed that exact call: ${confirmed.join(', ')}. First ask them with a decision request that carries the action (MCP request_decision with action {capability, args}, or \`ach ask-human "<question>" --action <capability> --arg k=v …\`), wait for their reply, then call the tool with the same arguments. One confirmation runs it once.`] : []),
298
315
  'When a question needs data this directory cannot reach (a database, logs, an internal API), use them instead of saying you cannot reach it. Their arguments are checked against what your owner declared; a large output is saved to a file the result names.',
299
316
  ].join('\n');
300
317
  }
@@ -331,6 +348,8 @@ export async function serveCaps(argv) {
331
348
  const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js');
332
349
  const { z } = await import('zod');
333
350
  const { caps } = loadCaps(file);
351
+ const realHome = opt('--real-home');
352
+ const hub = hubFor(home, realHome);
334
353
  const server = new McpServer({ name: CAPS_SERVER, version: '1' });
335
354
  for (const cap of caps) {
336
355
  const shape = {};
@@ -342,9 +361,54 @@ export async function serveCaps(argv) {
342
361
  shape[k] = a.required === false ? s.optional() : s;
343
362
  }
344
363
  server.registerTool(cap.name, { description: cap.description, inputSchema: shape }, async (input) => {
345
- const r = await runCap(cap, input, { home, realHome: opt('--real-home'), outDir: opt('--out'), log: opt('--log'), context });
364
+ const fail = (text) => ({ content: [{ type: 'text', text }], isError: true });
365
+ const sys = await sysValues(cap, input, context.task ?? '', hub);
366
+ if ('error' in sys)
367
+ return fail(sys.error);
368
+ const r = await runCap(cap, input, { home, realHome, outDir: opt('--out'), log: opt('--log'), context, sys: sys.values });
346
369
  return { content: [{ type: 'text', text: r.text }], ...(r.ok ? {} : { isError: true }) };
347
370
  });
348
371
  }
349
372
  await server.connect(new StdioServerTransport());
350
373
  }
374
+ /** The hub as the agent itself (its key from its home, read outside the sandbox): the run's own token cannot redeem. */
375
+ function hubFor(home, realHome) {
376
+ let made;
377
+ return async () => {
378
+ if (made)
379
+ return made;
380
+ const { loadConfig } = await import('./config.js');
381
+ const { Client } = await import('./client.js');
382
+ const cfg = loadConfig({ AGENTCHANNEL_HOME: home, HOME: realHome ?? process.env.HOME, PATH: process.env.PATH });
383
+ if (!cfg.hub || !cfg.key)
384
+ throw new Error(`no hub or agent key in ${home}`);
385
+ made = new Client({ hub: cfg.hub, token: cfg.key, cfId: cfg.cfId, cfSecret: cfg.cfSecret });
386
+ return made;
387
+ };
388
+ }
389
+ const usesVar = (cap, v) => [...cap.command, cap.stdin ?? ''].some((t) => t.includes(`{${v}}`));
390
+ /**
391
+ * The values the server fills for one call: the run's task, who asked for it, and for a `confirm: true` capability the person's
392
+ * confirmation, redeemed on the hub now (after the arguments were checked, so a bad call never spends one).
393
+ */
394
+ export async function sysValues(cap, input, task, hub) {
395
+ const values = { 'run.task': task };
396
+ const dry = buildCall(cap, input, { ...values, 'run.requester': '', 'confirm.request': '', 'confirm.person': '', 'confirm.at': '' });
397
+ if ('error' in dry)
398
+ return dry;
399
+ try {
400
+ if (usesVar(cap, 'run.requester'))
401
+ values['run.requester'] = task ? (await (await hub()).taskRequester(task)).email : '';
402
+ if (cap.confirm) {
403
+ if (!task)
404
+ return { error: `${cap.name} needs a person's confirmation, and this run has no task to ask it on` };
405
+ const args = Object.fromEntries(Object.entries(input ?? {}).filter(([, v]) => v !== undefined && v !== null && v !== '').map(([k, v]) => [k, String(v)]));
406
+ const ok = await (await hub()).redeemAction(task, cap.name, args);
407
+ Object.assign(values, { 'confirm.request': ok.request, 'confirm.person': ok.person.email, 'confirm.at': ok.at });
408
+ }
409
+ }
410
+ catch (e) {
411
+ return { error: `${cap.name} did not run: ${e?.message ?? e}` };
412
+ }
413
+ return { values };
414
+ }
@@ -0,0 +1,3 @@
1
+ import { type CmdCtx } from './cli-shared.js';
2
+ /** `ach admin ...` (and `ach memory lang`): what a person does with their admin session. */
3
+ export declare function adminCommand(ctx: CmdCtx): Promise<number | undefined>;