@koalaauto/agentchannel 3.55.0 → 3.56.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.
@@ -5,14 +5,18 @@ import type { Perm } from '../perm.js';
5
5
  * Antigravity runtime: each run is one headless `agy -p <prompt> --output-format stream-json` on this machine, logged in
6
6
  * with the owner's Google account (the login is a file under the real ~/.gemini, so the run keeps the real HOME).
7
7
  *
8
- * The run gets no `ach` and no hub credentials: a sandboxed command has no network, so it could not reach the hub anyway.
9
- * The runner completes or fails the task and posts answers from the run's final text.
8
+ * A sandboxed command has no network, so `ach` is not a command here: a work run gets it as a tool, the "ach" MCP server
9
+ * (runtool.ts), which agy starts outside its sandbox with the run's environment. agy takes MCP servers from a file only:
10
+ * `<work dir>/.agents/mcp_config.json`, written for the run and put back as it was afterwards (it holds no secret: the
11
+ * run token is in the environment, as for every runtime). The owner's host capabilities are a second server there.
12
+ * Answer, mention and read-ahead runs get no tool: they return JSON and the runner posts it.
10
13
  *
11
14
  * Permission levels, as tried by hand with agy 1.5.13 on Linux (2026-11-20; recordings in test/fixtures/antigravity):
12
15
  * - read: no commands at all (one allowed command reads any file), no writes, no URL tools, no MCP; file reads only.
13
16
  * - workdir: `--sandbox`, commands run inside agy's own sandbox without asking: they write the work dir and /tmp, have no
14
17
  * network, and see a filtered HOME (no runner config, no tokens). The file tools run outside it, held by deny rules.
15
18
  * - full: `--dangerously-skip-permissions`.
19
+ * Files outside the work dir are readable without `--add-dir`, which is never passed: it would make them writable too.
16
20
  * What it does not hold: files outside HOME are readable (other checkouts on the machine, /tmp), and its web search tool
17
21
  * cannot be turned off by any rule (spec: `reads: 'machine'`, `limits.net: false`).
18
22
  *
@@ -29,7 +33,23 @@ export declare function agyExposed(paths: string[], realHome?: string): string[]
29
33
  export declare function agySettings(o: {
30
34
  perm: Perm;
31
35
  denyReadPaths?: string[];
36
+ readRoots?: string[];
37
+ mcp?: string[];
32
38
  }): Record<string, unknown> | undefined;
39
+ export interface AgyMcpServer {
40
+ command: string;
41
+ args: string[];
42
+ }
43
+ /** The MCP servers of a work run: `ach` as a tool, and the owner's host capabilities when declared. Other runs get none. */
44
+ export declare function agyServers(o: {
45
+ mode?: AdapterRunOptions['mode'];
46
+ cli: string;
47
+ caps?: AgyMcpServer;
48
+ }): Record<string, AgyMcpServer>;
49
+ /** `.agents/mcp_config.json` of the work dir with the run's servers added to what the project has there. Pure. */
50
+ export declare function agyMcpConfig(existing: string | undefined, servers: Record<string, AgyMcpServer>): string;
51
+ /** Writes the run's MCP file; the returned function puts back what was there (the runner commits the work dir after the run). */
52
+ export declare function agyInstallMcp(cwd: string, servers: Record<string, AgyMcpServer>): () => void;
33
53
  /** The level a run really gets: only a work run writes; every other run (answer, mention, read-ahead) reads. */
34
54
  export declare function agyPerm(perm: Perm, mode: AdapterRunOptions['mode']): Perm;
35
55
  export declare function agyArgs(o: {
@@ -41,10 +61,15 @@ export declare function agyArgs(o: {
41
61
  denyReadPaths?: string[];
42
62
  readRoots?: string[];
43
63
  outputSchema?: unknown;
64
+ mcp?: string[];
44
65
  }): string[];
45
- /** The environment agy runs with: the agent env without the hub's run variables, and the runner's real HOME (its login is there). */
66
+ /**
67
+ * The environment agy runs with: the runner's real HOME (its login is there), and the hub's run variables only when the run
68
+ * has the `ach` tool (the MCP server inherits them); any other run gets none.
69
+ */
46
70
  export declare function agyEnv(agentEnv: Record<string, string>, o: {
47
71
  realHome?: string;
72
+ tool?: boolean;
48
73
  }): Record<string, string>;
49
74
  /** agy as the runner starts it: ACH_ANTIGRAVITY_BIN, else `agy` (on PATH, or where its installer puts it). */
50
75
  export declare function agyBin(env: Record<string, string | undefined>): string;
@@ -113,6 +138,8 @@ export interface AntigravityAdapterOptions {
113
138
  env?: Record<string, string | undefined>;
114
139
  /** Tests: the program to start instead of agy. */
115
140
  bin?: string;
141
+ /** Tests: the CLI the `ach` tool runs (default: this package's). */
142
+ cli?: string;
116
143
  }
117
144
  export declare class AntigravityAdapter implements RuntimeAdapter {
118
145
  private o;
@@ -121,7 +148,8 @@ export declare class AntigravityAdapter implements RuntimeAdapter {
121
148
  readonly name: "antigravity";
122
149
  readonly label: "Antigravity";
123
150
  readonly where: "local";
124
- readonly ach: false;
151
+ readonly ach: true;
152
+ readonly achBy: "tool";
125
153
  readonly structuredAnswers: true;
126
154
  readonly perms: readonly Perm[];
127
155
  readonly limits: {
@@ -150,5 +178,6 @@ export declare class AntigravityAdapter implements RuntimeAdapter {
150
178
  * stays refused; a run that still ends without an answer fails.
151
179
  */
152
180
  run(opts: AdapterRunOptions): Promise<AdapterResult>;
181
+ private attempts;
153
182
  private once;
154
183
  }
@@ -1,5 +1,9 @@
1
1
  import { execFile } from 'node:child_process';
2
- import { join, relative, isAbsolute } from 'node:path';
2
+ import { existsSync, mkdirSync, readFileSync, rmdirSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, relative, isAbsolute } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { CAPS_SERVER } from '../caps.js';
6
+ import { RUN_TOOL_SERVER } from '../runtool.js';
3
7
  import { RUNTIME_SPECS } from './spec.js';
4
8
  import { spawnGroup } from './procgroup.js';
5
9
  import { modelId } from './types.js';
@@ -7,14 +11,18 @@ import { modelId } from './types.js';
7
11
  * Antigravity runtime: each run is one headless `agy -p <prompt> --output-format stream-json` on this machine, logged in
8
12
  * with the owner's Google account (the login is a file under the real ~/.gemini, so the run keeps the real HOME).
9
13
  *
10
- * The run gets no `ach` and no hub credentials: a sandboxed command has no network, so it could not reach the hub anyway.
11
- * The runner completes or fails the task and posts answers from the run's final text.
14
+ * A sandboxed command has no network, so `ach` is not a command here: a work run gets it as a tool, the "ach" MCP server
15
+ * (runtool.ts), which agy starts outside its sandbox with the run's environment. agy takes MCP servers from a file only:
16
+ * `<work dir>/.agents/mcp_config.json`, written for the run and put back as it was afterwards (it holds no secret: the
17
+ * run token is in the environment, as for every runtime). The owner's host capabilities are a second server there.
18
+ * Answer, mention and read-ahead runs get no tool: they return JSON and the runner posts it.
12
19
  *
13
20
  * Permission levels, as tried by hand with agy 1.5.13 on Linux (2026-11-20; recordings in test/fixtures/antigravity):
14
21
  * - read: no commands at all (one allowed command reads any file), no writes, no URL tools, no MCP; file reads only.
15
22
  * - workdir: `--sandbox`, commands run inside agy's own sandbox without asking: they write the work dir and /tmp, have no
16
23
  * network, and see a filtered HOME (no runner config, no tokens). The file tools run outside it, held by deny rules.
17
24
  * - full: `--dangerously-skip-permissions`.
25
+ * Files outside the work dir are readable without `--add-dir`, which is never passed: it would make them writable too.
18
26
  * What it does not hold: files outside HOME are readable (other checkouts on the machine, /tmp), and its web search tool
19
27
  * cannot be turned off by any rule (spec: `reads: 'machine'`, `limits.net: false`).
20
28
  *
@@ -41,11 +49,70 @@ export function agyExposed(paths, realHome) {
41
49
  export function agySettings(o) {
42
50
  if (o.perm === 'full')
43
51
  return undefined;
44
- const secrets = (o.denyReadPaths ?? []).flatMap((p) => [`read_file(${p})`, `write_file(${p})`]);
45
- const net = ['read_url(*)', 'execute_url(*)', 'download_url(*)', 'mcp(*)'];
52
+ // the read roots (other checkouts, attachments, the runner's `ach` shim): its file tools may read them and may not write
53
+ // them, both by rule. They are never given as `--add-dir`: agy makes an added directory part of the workspace (its file
54
+ // tools then write there: a result file landed in the runner's bin directory) and starts commands in whichever workspace
55
+ // directory sorts first, not in the task's (both seen 2026-11-20). A sandboxed command does not see a root under HOME.
56
+ const roots = o.readRoots ?? [];
57
+ const secrets = [...(o.denyReadPaths ?? []).flatMap((p) => [`read_file(${p})`, `write_file(${p})`]), ...roots.map((p) => `write_file(${p})`)];
58
+ // a deny rule wins over an allow rule, so MCP is denied as a whole only when the run has no server of its own
59
+ const servers = o.mcp ?? [];
60
+ const net = ['read_url(*)', 'execute_url(*)', 'download_url(*)', ...(servers.length ? [] : ['mcp(*)'])];
61
+ const allowed = [...servers.map((n) => `mcp(${n}/*)`), ...roots.map((p) => `read_file(${p})`)];
62
+ const allow = allowed.length ? { allow: allowed } : {};
46
63
  if (o.perm === 'read')
47
- return { permissions: { deny: ['command(*)', 'unsandboxed(*)', 'write_file(*)', ...net, ...secrets] } };
48
- return { toolPermission: 'proceed-in-sandbox', enableTerminalSandbox: true, permissions: { deny: ['unsandboxed(*)', ...net, ...secrets] } };
64
+ return { permissions: { ...allow, deny: ['command(*)', 'unsandboxed(*)', 'write_file(*)', ...net, ...secrets] } };
65
+ return { toolPermission: 'proceed-in-sandbox', enableTerminalSandbox: true, permissions: { ...allow, deny: ['unsandboxed(*)', ...net, ...secrets] } };
66
+ }
67
+ /** The MCP servers of a work run: `ach` as a tool, and the owner's host capabilities when declared. Other runs get none. */
68
+ export function agyServers(o) {
69
+ if (o.mode && o.mode !== 'work')
70
+ return {};
71
+ return { [RUN_TOOL_SERVER]: { command: process.execPath, args: [o.cli, 'run-tool-serve'] }, ...(o.caps ? { [CAPS_SERVER]: { command: o.caps.command, args: o.caps.args } } : {}) };
72
+ }
73
+ /** `.agents/mcp_config.json` of the work dir with the run's servers added to what the project has there. Pure. */
74
+ export function agyMcpConfig(existing, servers) {
75
+ let doc = {};
76
+ try {
77
+ const d = existing ? JSON.parse(existing) : {};
78
+ if (d && typeof d === 'object' && !Array.isArray(d))
79
+ doc = d;
80
+ }
81
+ catch {
82
+ /* not JSON: the run's servers alone */
83
+ }
84
+ const mine = Object.fromEntries(Object.entries(servers).map(([n, v]) => [n, { command: v.command, args: v.args }]));
85
+ return JSON.stringify({ ...doc, mcpServers: { ...(doc.mcpServers && typeof doc.mcpServers === 'object' ? doc.mcpServers : {}), ...mine } }, null, 2) + '\n';
86
+ }
87
+ /** Writes the run's MCP file; the returned function puts back what was there (the runner commits the work dir after the run). */
88
+ export function agyInstallMcp(cwd, servers) {
89
+ if (!Object.keys(servers).length)
90
+ return () => { };
91
+ const file = join(cwd, '.agents', 'mcp_config.json');
92
+ const hadDir = existsSync(dirname(file));
93
+ let before;
94
+ try {
95
+ before = readFileSync(file, 'utf8');
96
+ }
97
+ catch {
98
+ before = undefined;
99
+ }
100
+ mkdirSync(dirname(file), { recursive: true });
101
+ writeFileSync(file, agyMcpConfig(before, servers));
102
+ return () => {
103
+ try {
104
+ if (before !== undefined)
105
+ writeFileSync(file, before);
106
+ else {
107
+ rmSync(file, { force: true });
108
+ if (!hadDir)
109
+ rmdirSync(dirname(file));
110
+ }
111
+ }
112
+ catch {
113
+ /* a directory the agent filled stays */
114
+ }
115
+ };
49
116
  }
50
117
  /** The level a run really gets: only a work run writes; every other run (answer, mention, read-ahead) reads. */
51
118
  export function agyPerm(perm, mode) {
@@ -64,15 +131,17 @@ export function agyArgs(o) {
64
131
  ...(o.perm === 'full' ? ['--dangerously-skip-permissions'] : []),
65
132
  ...(o.perm === 'workdir' ? ['--sandbox'] : []),
66
133
  ...(settings ? ['--settings', JSON.stringify(settings)] : []),
67
- ...(o.readRoots ?? []).flatMap((d) => ['--add-dir', d]),
68
134
  ...(o.outputSchema ? ['--json-schema', JSON.stringify(o.outputSchema)] : []),
69
135
  ];
70
136
  }
71
- /** The environment agy runs with: the agent env without the hub's run variables, and the runner's real HOME (its login is there). */
137
+ /**
138
+ * The environment agy runs with: the runner's real HOME (its login is there), and the hub's run variables only when the run
139
+ * has the `ach` tool (the MCP server inherits them); any other run gets none.
140
+ */
72
141
  export function agyEnv(agentEnv, o) {
73
142
  const env = {};
74
143
  for (const [k, v] of Object.entries(agentEnv))
75
- if (!/^ACH_/.test(k))
144
+ if (o.tool || !/^ACH_/.test(k))
76
145
  env[k] = v;
77
146
  if (o.realHome)
78
147
  env.HOME = o.realHome;
@@ -289,10 +358,30 @@ export class AntigravityAdapter {
289
358
  opts.onEvent({ type: 'error', data: error });
290
359
  return { finalText: '', ok: false, error };
291
360
  }
361
+ const servers = agyServers({ mode: opts.mode, cli: this.o.cli ?? fileURLToPath(new URL('../cli.js', import.meta.url)), caps: opts.caps });
362
+ const mcp = Object.keys(servers);
363
+ let restore = () => { };
364
+ try {
365
+ restore = agyInstallMcp(opts.cwd, servers);
366
+ }
367
+ catch (e) {
368
+ const error = `not run: could not write the run's MCP servers into ${opts.cwd}/.agents: ${e?.message ?? e}`;
369
+ opts.onEvent({ type: 'error', data: error });
370
+ return { finalText: '', ok: false, error };
371
+ }
372
+ try {
373
+ return await this.attempts(opts, { perm, model, mcp });
374
+ }
375
+ finally {
376
+ restore();
377
+ }
378
+ }
379
+ async attempts(opts, o) {
380
+ const { perm, model, mcp } = o;
292
381
  let prompt = opts.prompt;
293
382
  let resume = opts.resume;
294
383
  for (let attempt = 0;; attempt++) {
295
- const r = await this.once(opts, { prompt, resume, perm, model });
384
+ const r = await this.once(opts, { prompt, resume, perm, model, mcp });
296
385
  const finalText = r.out.finalText();
297
386
  const { ok, error } = agyOutcome({ code: r.code, out: r.out, finalText, stderr: r.stderr, aborted: opts.signal.aborted, spawnError: r.spawnError });
298
387
  const used = r.out.model ?? (modelId(model) ? model : undefined);
@@ -309,7 +398,7 @@ export class AntigravityAdapter {
309
398
  const out = new AgyOutput(opts.onEvent);
310
399
  let stderr = '';
311
400
  return new Promise((resolve) => {
312
- const env = agyEnv(opts.env, { realHome: opts.realHome });
401
+ const env = agyEnv(opts.env, { realHome: opts.realHome, tool: o.mcp.length > 0 });
313
402
  env.PATH = agyPath(env, opts.realHome);
314
403
  let done = false;
315
404
  const finish = (code, spawnError) => {
@@ -321,7 +410,7 @@ export class AntigravityAdapter {
321
410
  };
322
411
  let child;
323
412
  try {
324
- child = spawnGroup(this.bin(), agyArgs({ prompt: o.prompt, perm: o.perm, model: o.model, effort: opts.effort, resume: o.resume, denyReadPaths: opts.denyReadPaths, readRoots: opts.readRoots, outputSchema: opts.outputSchema }), {
413
+ child = spawnGroup(this.bin(), agyArgs({ prompt: o.prompt, perm: o.perm, model: o.model, effort: opts.effort, resume: o.resume, denyReadPaths: opts.denyReadPaths, readRoots: opts.readRoots, outputSchema: opts.outputSchema, mcp: o.mcp }), {
325
414
  cwd: opts.cwd,
326
415
  env,
327
416
  signal: opts.signal,
@@ -14,15 +14,21 @@ export declare const MENTION_ACH_TOOLS: string[];
14
14
  /**
15
15
  * Mention runs may also read the repository's history: who changed what and when is what people ask in a thread. The sandbox
16
16
  * does not make these read-only by itself (the run's directory stays writable to a sandboxed command; live-tested:
17
- * `git log --output=<file>` wrote the file), so mentionGitDenied() checks every git command of a mention run before it starts.
17
+ * `git log --output=<file>` wrote the file), so mentionCommandDenied() checks every git command of a mention run before it starts.
18
18
  */
19
19
  export declare const MENTION_GIT_TOOLS: string[];
20
20
  /**
21
- * Why a mention run may not run this git command (undefined: it may). One plain command of the five: nothing a shell would
22
- * expand, chain or redirect, no option that writes a file (`--output`, in any abbreviation git accepts) or names a program to
23
- * run (`--ext-diff`, `-c`, `--exec`), and nothing before `git` (an environment variable can name a program too).
21
+ * And read GitHub through `gh`, with the run's read-only token (GH_TOKEN, scoped by the hub): a thread about a pull request needs
22
+ * its diff, and a branch nobody fetched is not in the local history (2026-11-20: four runs answered a thread about PR #12 without
23
+ * ever seeing it, each saying it could not read GitHub). Only the commands below; mentionCommandDenied() checks their options.
24
24
  */
25
- export declare function mentionGitDenied(command: string): string | undefined;
25
+ export declare const MENTION_GH_TOOLS: string[];
26
+ /**
27
+ * Why a mention run may not run this git or gh command (undefined: it may). One plain command of the allowed ones: nothing a shell
28
+ * would expand, chain or redirect, no option that writes a file (`--output`, in any abbreviation git accepts) or names a program to
29
+ * run (`--ext-diff`, `-c`, `--exec`), and nothing before `git` or `gh` (an environment variable can name a program too).
30
+ */
31
+ export declare function mentionCommandDenied(command: string): string | undefined;
26
32
  /**
27
33
  * Whether a command is one plain `ach <sub> ...` call of an allowed subcommand: literal words only. Claude Code's own rule
28
34
  * (`Bash(ach reply:*)`) gives up on a long quoted argument with `;` or a line break in it and asks, which a run that cannot ask
@@ -37,8 +43,8 @@ export declare function plainAchCommand(command: string, subs: string[]): boolea
37
43
  export declare const achSubcommands: (tools: string[]) => string[];
38
44
  /** PreToolUse for Bash: a plain call of one of the run's `ach` commands is allowed outright (see plainAchCommand). */
39
45
  export declare function achCommandHook(tools: string[]): HookCallbackMatcher;
40
- /** PreToolUse for a mention run's Bash: the git rules above (a hook runs for pre-approved commands too). */
41
- export declare function mentionGitHook(): HookCallbackMatcher;
46
+ /** PreToolUse for a mention run's Bash: the git and gh rules above (a hook runs for pre-approved commands too). */
47
+ export declare function mentionReadHook(): HookCallbackMatcher;
42
48
  /** canUseTool for workdir: path policy (reads under $HOME, writes outside cwd) plus the Bash deny list. */
43
49
  export declare function workdirCanUseTool(pol: PathPolicy): CanUseTool;
44
50
  /**
@@ -148,6 +154,7 @@ export declare class ClaudeAdapter implements RuntimeAdapter {
148
154
  readonly label: "Claude Code";
149
155
  readonly where: "local";
150
156
  readonly ach: true;
157
+ readonly achBy: "command";
151
158
  readonly structuredAnswers: false;
152
159
  readonly perms: readonly Perm[];
153
160
  readonly limits: {
@@ -44,16 +44,33 @@ export const MENTION_ACH_TOOLS = ['Bash(ach reply:*)', 'Bash(ach thread:*)', 'Ba
44
44
  /**
45
45
  * Mention runs may also read the repository's history: who changed what and when is what people ask in a thread. The sandbox
46
46
  * does not make these read-only by itself (the run's directory stays writable to a sandboxed command; live-tested:
47
- * `git log --output=<file>` wrote the file), so mentionGitDenied() checks every git command of a mention run before it starts.
47
+ * `git log --output=<file>` wrote the file), so mentionCommandDenied() checks every git command of a mention run before it starts.
48
48
  */
49
49
  export const MENTION_GIT_TOOLS = ['Bash(git log:*)', 'Bash(git show:*)', 'Bash(git diff:*)', 'Bash(git blame:*)', 'Bash(git status:*)'];
50
50
  /**
51
- * Why a mention run may not run this git command (undefined: it may). One plain command of the five: nothing a shell would
52
- * expand, chain or redirect, no option that writes a file (`--output`, in any abbreviation git accepts) or names a program to
53
- * run (`--ext-diff`, `-c`, `--exec`), and nothing before `git` (an environment variable can name a program too).
51
+ * And read GitHub through `gh`, with the run's read-only token (GH_TOKEN, scoped by the hub): a thread about a pull request needs
52
+ * its diff, and a branch nobody fetched is not in the local history (2026-11-20: four runs answered a thread about PR #12 without
53
+ * ever seeing it, each saying it could not read GitHub). Only the commands below; mentionCommandDenied() checks their options.
54
54
  */
55
- export function mentionGitDenied(command) {
55
+ export const MENTION_GH_TOOLS = ['Bash(gh pr view:*)', 'Bash(gh pr diff:*)', 'Bash(gh pr checks:*)', 'Bash(gh pr list:*)', 'Bash(gh issue view:*)', 'Bash(gh issue list:*)', 'Bash(gh run view:*)', 'Bash(gh run list:*)'];
56
+ const MENTION_GH = new Set(MENTION_GH_TOOLS.map((t) => /^Bash\(gh ([a-z]+ [a-z]+):\*\)$/.exec(t)[1]));
57
+ /**
58
+ * Why a mention run may not run this git or gh command (undefined: it may). One plain command of the allowed ones: nothing a shell
59
+ * would expand, chain or redirect, no option that writes a file (`--output`, in any abbreviation git accepts) or names a program to
60
+ * run (`--ext-diff`, `-c`, `--exec`), and nothing before `git` or `gh` (an environment variable can name a program too).
61
+ */
62
+ export function mentionCommandDenied(command) {
56
63
  const cmd = command.trim();
64
+ if (/^gh(\s|$)/.test(cmd)) {
65
+ if (/[;&|<>$`\\(){}\n\r]/.test(cmd))
66
+ return 'gh runs here as one plain command: no pipes, redirects, `&&`, `$(...)` or line breaks';
67
+ const args = cmd.replace(/["']/g, '').split(/\s+/).slice(1);
68
+ if (!MENTION_GH.has(args.slice(0, 2).join(' ')))
69
+ return `only ${[...MENTION_GH].map((c) => `gh ${c}`).join(', ')} run here`;
70
+ if (args.some((a) => /^(-w|--web)$/.test(a)))
71
+ return 'this run reads in the terminal: no --web';
72
+ return undefined;
73
+ }
57
74
  if (!/^git(\s|$)/.test(cmd))
58
75
  return undefined;
59
76
  if (/[;&|<>$`\\(){}\n\r]/.test(cmd))
@@ -136,14 +153,14 @@ export function achCommandHook(tools) {
136
153
  ],
137
154
  };
138
155
  }
139
- /** PreToolUse for a mention run's Bash: the git rules above (a hook runs for pre-approved commands too). */
140
- export function mentionGitHook() {
156
+ /** PreToolUse for a mention run's Bash: the git and gh rules above (a hook runs for pre-approved commands too). */
157
+ export function mentionReadHook() {
141
158
  return {
142
159
  hooks: [
143
160
  async (input) => {
144
161
  if (input.hook_event_name !== 'PreToolUse' || input.tool_name !== 'Bash')
145
162
  return {};
146
- const why = mentionGitDenied(String((input.tool_input ?? {}).command ?? ''));
163
+ const why = mentionCommandDenied(String((input.tool_input ?? {}).command ?? ''));
147
164
  if (!why)
148
165
  return {};
149
166
  return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: why } };
@@ -274,9 +291,9 @@ export function claudePermOptions(perm, o) {
274
291
  ...base,
275
292
  // pre-approved at every level: without that, Claude Code does not offer Glob and Grep to the model at workdir (live
276
293
  // test). The PreToolUse hook checks them; the SDK's notice that canUseTool is shadowed for them is expected.
277
- allowedTools: ['Read', 'Glob', 'Grep', ...achTools, ...(o.mode === 'mention' ? MENTION_GIT_TOOLS : [])],
294
+ allowedTools: ['Read', 'Glob', 'Grep', ...achTools, ...(o.mode === 'mention' ? [...MENTION_GIT_TOOLS, ...MENTION_GH_TOOLS] : [])],
278
295
  sandbox,
279
- hooks: { PreToolUse: [pathPolicyHook(pol), achCommandHook(achTools), ...(o.mode === 'mention' ? [mentionGitHook()] : [])] },
296
+ hooks: { PreToolUse: [pathPolicyHook(pol), achCommandHook(achTools), ...(o.mode === 'mention' ? [mentionReadHook()] : [])] },
280
297
  };
281
298
  if (perm === 'read')
282
299
  return { ...common, permissionMode: 'dontAsk' };
@@ -123,6 +123,7 @@ export declare class CodexAdapter implements RuntimeAdapter {
123
123
  readonly label: "Codex";
124
124
  readonly where: "local";
125
125
  readonly ach: true;
126
+ readonly achBy: "command";
126
127
  readonly structuredAnswers: true;
127
128
  readonly perms: readonly Perm[];
128
129
  readonly limits: {
@@ -41,6 +41,7 @@ export class FakeAdapter {
41
41
  label: 'Fake',
42
42
  where: o.remote ? 'cloud' : 'local',
43
43
  ach: !o.remote,
44
+ achBy: 'command',
44
45
  structuredAnswers: !!o.structuredAnswers || !!o.remote,
45
46
  perms: PERMS,
46
47
  limits: { net: true, denyRead: true },
@@ -88,6 +88,7 @@ export declare class KiroAdapter implements RuntimeAdapter {
88
88
  readonly label: "Kiro";
89
89
  readonly where: "cloud";
90
90
  readonly ach: false;
91
+ readonly achBy: "command";
91
92
  readonly structuredAnswers: true;
92
93
  readonly perms: readonly import("../perm.js").Perm[];
93
94
  readonly limits: {
@@ -13,6 +13,11 @@ export interface RuntimeSpec {
13
13
  where: 'local' | 'cloud';
14
14
  /** The run can call `ach` itself. false: it gets no hub credentials; the runner reports the task from the run's final text. */
15
15
  ach: boolean;
16
+ /**
17
+ * How a run with `ach` reaches it. command: the `ach` CLI in its shell. tool: an MCP tool that takes the same arguments
18
+ * (its commands have no network); the prompt says so.
19
+ */
20
+ achBy: 'command' | 'tool';
16
21
  /** Short runs (answer, mention, description) return JSON by a schema and the runner posts it. Implied by `ach: false`. */
17
22
  structuredAnswers: boolean;
18
23
  /** The permission levels the tool can enforce. */
@@ -55,6 +60,7 @@ export declare const RUNTIME_SPECS: {
55
60
  readonly label: "Claude Code";
56
61
  readonly where: "local";
57
62
  readonly ach: true;
63
+ readonly achBy: "command";
58
64
  readonly structuredAnswers: false;
59
65
  readonly perms: readonly Perm[];
60
66
  readonly limits: {
@@ -79,6 +85,7 @@ export declare const RUNTIME_SPECS: {
79
85
  readonly label: "Codex";
80
86
  readonly where: "local";
81
87
  readonly ach: true;
88
+ readonly achBy: "command";
82
89
  readonly structuredAnswers: true;
83
90
  readonly perms: readonly Perm[];
84
91
  readonly limits: {
@@ -103,6 +110,7 @@ export declare const RUNTIME_SPECS: {
103
110
  readonly label: "Kiro";
104
111
  readonly where: "cloud";
105
112
  readonly ach: false;
113
+ readonly achBy: "command";
106
114
  readonly structuredAnswers: true;
107
115
  readonly perms: readonly Perm[];
108
116
  readonly limits: {
@@ -122,7 +130,8 @@ export declare const RUNTIME_SPECS: {
122
130
  readonly name: "antigravity";
123
131
  readonly label: "Antigravity";
124
132
  readonly where: "local";
125
- readonly ach: false;
133
+ readonly ach: true;
134
+ readonly achBy: "tool";
126
135
  readonly structuredAnswers: true;
127
136
  readonly perms: readonly Perm[];
128
137
  readonly limits: {
@@ -6,6 +6,7 @@ export const RUNTIME_SPECS = {
6
6
  label: 'Claude Code',
7
7
  where: 'local',
8
8
  ach: true,
9
+ achBy: 'command',
9
10
  structuredAnswers: false,
10
11
  perms: ALL,
11
12
  limits: { net: true, denyRead: true },
@@ -22,6 +23,7 @@ export const RUNTIME_SPECS = {
22
23
  label: 'Codex',
23
24
  where: 'local',
24
25
  ach: true,
26
+ achBy: 'command',
25
27
  structuredAnswers: true,
26
28
  perms: ALL,
27
29
  limits: { net: true, denyRead: true },
@@ -39,6 +41,7 @@ export const RUNTIME_SPECS = {
39
41
  label: 'Kiro',
40
42
  where: 'cloud',
41
43
  ach: false,
44
+ achBy: 'command',
42
45
  structuredAnswers: true,
43
46
  perms: ALL,
44
47
  limits: { net: false, denyRead: false },
@@ -49,13 +52,14 @@ export const RUNTIME_SPECS = {
49
52
  login: { key: 'KIRO_API_KEY' },
50
53
  check: 'tool',
51
54
  },
52
- // one headless `agy` per run on this machine, with its own sandbox (adapters/antigravity.ts says what was tried by hand): no
53
- // `ach` in the run (a sandboxed command has no network), its web search cannot be turned off, and it reads outside HOME
55
+ // one headless `agy` per run on this machine, with its own sandbox (adapters/antigravity.ts says what was tried by hand): a
56
+ // sandboxed command has no network, so `ach` is a tool; its web search cannot be turned off, and it reads outside HOME
54
57
  antigravity: {
55
58
  name: 'antigravity',
56
59
  label: 'Antigravity',
57
60
  where: 'local',
58
- ach: false,
61
+ ach: true,
62
+ achBy: 'tool',
59
63
  structuredAnswers: true,
60
64
  perms: ALL,
61
65
  limits: { net: false, denyRead: true },
package/dist/src/cli.js CHANGED
@@ -144,6 +144,17 @@ export async function main(argv, io = defaultIo()) {
144
144
  await (await import('./caps.js')).serveCaps(argv.slice(1));
145
145
  return await new Promise(() => { });
146
146
  }
147
+ // `ach` as a tool of a run whose commands cannot reach the hub (runtool.ts): each call is this CLI again, with the run's limits
148
+ if (argv[0] === 'run-tool-serve') {
149
+ const { serveRunTool } = await import('./runtool.js');
150
+ await serveRunTool(async (args) => {
151
+ let stdout = '';
152
+ let stderr = '';
153
+ const code = await main(args, { ...io, out: (t) => (stdout += t + '\n'), err: (t) => (stderr += t + '\n') });
154
+ return { code, stdout, stderr };
155
+ });
156
+ return await new Promise(() => { });
157
+ }
147
158
  let p;
148
159
  try {
149
160
  p = parseCli(argv);
@@ -400,6 +400,8 @@ export declare class NetworkError extends Error {
400
400
  * (ENOTFOUND, ECONNREFUSED) or a hub that took the request and did not answer in time.
401
401
  */
402
402
  export declare function retryable(method: string, e: any): boolean;
403
+ /** The status a proxy answered a CONNECT with, when that is why the fetch failed (undici: "Proxy response (502) !== 200 when HTTP Tunneling", a few causes down). */
404
+ export declare function proxyTunnelStatus(e: any): number | undefined;
403
405
  export declare class HubError extends Error {
404
406
  status: number;
405
407
  code?: string | undefined;
@@ -46,8 +46,22 @@ export function retryable(method, e) {
46
46
  const code = String(e?.cause?.code ?? e?.code ?? '');
47
47
  if (CONNECT_FAULTS.has(code))
48
48
  return true;
49
+ // the proxy could not open its tunnel to the hub (a sandbox's proxy answers 502 when its own connect fails): nothing was sent.
50
+ // 2026-11-20: ~20% of connects from one runner machine to the hub's Cloudflare address stalled, and every one surfaced as a
51
+ // failed `ach` call in a run ("cannot reach ... (0)"); a 403 is the proxy refusing the host, which another try does not change.
52
+ if ([502, 503, 504].includes(proxyTunnelStatus(e) ?? 0))
53
+ return true;
49
54
  return (method === 'GET' || method === 'HEAD') && SOCKET_FAULTS.has(code);
50
55
  }
56
+ /** The status a proxy answered a CONNECT with, when that is why the fetch failed (undici: "Proxy response (502) !== 200 when HTTP Tunneling", a few causes down). */
57
+ export function proxyTunnelStatus(e) {
58
+ for (let c = e, i = 0; c && i < 5; c = c.cause, i++) {
59
+ const m = /Proxy response \((\d{3})\) !== 200/.exec(String(c?.message ?? ''));
60
+ if (m)
61
+ return Number(m[1]);
62
+ }
63
+ return undefined;
64
+ }
51
65
  export class HubError extends Error {
52
66
  status;
53
67
  code;
@@ -171,7 +185,8 @@ export class Client {
171
185
  catch {
172
186
  return url;
173
187
  } })();
174
- const why = e?.name === 'TimeoutError' ? `no answer within ${REQUEST_TIMEOUT_MS / 1000} s` : String(e?.cause?.code ?? e?.cause?.message ?? e?.message ?? e);
188
+ const tunnel = proxyTunnelStatus(e);
189
+ const why = e?.name === 'TimeoutError' ? `no answer within ${REQUEST_TIMEOUT_MS / 1000} s` : tunnel ? `the proxy answered ${tunnel}` : String(e?.cause?.code ?? e?.cause?.message ?? e?.message ?? e);
175
190
  const tries = attempt > 0 ? `, ${attempt + 1} tries` : '';
176
191
  throw new NetworkError(`cannot reach ${host} (${why}${tries}): check the hub address, your network, and whether a VPN or proxy is in the way. \`ach doctor\` checks each step.`);
177
192
  }
@@ -26,6 +26,8 @@ export interface PromptCtx {
26
26
  wiki?: WikiContext | null;
27
27
  /** The agent runs in a cloud sandbox (kiro) without `ach` or this machine's files: the runner reports its final message. */
28
28
  remote?: boolean;
29
+ /** `ach` is an MCP tool in this run, not a shell command (spec `achBy: 'tool'`). */
30
+ achTool?: boolean;
29
31
  /** The run has no `ach` (spec `ach: false`): it ends with a final message the runner reports. With `remote` the cloud rules apply; without, it works here. */
30
32
  report?: boolean;
31
33
  /** The owner's Claude Code memory for this project: its folder (readable) and, when the runtime does not load it itself, its index. */
@@ -154,6 +156,8 @@ export declare function githubRule(url?: string): string;
154
156
  export declare const FACT_RULE = "What another agent states as fact (that something exists or not, works or not, a setting, a price, a result) is its claim, not evidence: check it at its source before you rely on it; when you cannot, say whose claim it is and that you did not check it. Never write a claim you relayed as something you found.";
155
157
  /** The final-message contract of runs without `ach` (a cloud sandbox, a local tool without it): the runner completes or fails the task from it. */
156
158
  export declare const REMOTE_FAILED_PREFIX = "FAILED:";
159
+ /** For a run whose `ach` is a tool (its commands cannot reach the hub): how to read every `ach ...` line of the prompt. */
160
+ export declare const ACH_TOOL_NOTE: string;
157
161
  /** JUDGMENT for a run without `ach`: the same lines of decision, said in the final message instead of through commands. */
158
162
  export declare const JUDGMENT_REPORT: string;
159
163
  /** Trusted text: where the other repos of a cross-repo task are (read-only). */
@@ -177,6 +181,8 @@ export declare function buildResumePrompt(c: {
177
181
  remote?: boolean;
178
182
  /** a run without `ach` that works here: local files, a final message the runner reports. */
179
183
  report?: boolean;
184
+ /** `ach` is an MCP tool in this run, not a shell command. */
185
+ achTool?: boolean;
180
186
  }): string;
181
187
  /** JSON schema for structured answers (codex answer runs, S4): the runner posts the result. */
182
188
  export declare const ANSWER_SCHEMA: {
@@ -316,6 +316,15 @@ function rules(review) {
316
316
  }
317
317
  /** The final-message contract of runs without `ach` (a cloud sandbox, a local tool without it): the runner completes or fails the task from it. */
318
318
  export const REMOTE_FAILED_PREFIX = 'FAILED:';
319
+ /** For a run whose `ach` is a tool (its commands cannot reach the hub): how to read every `ach ...` line of the prompt. */
320
+ export const ACH_TOOL_NOTE = [
321
+ 'How to call `ach` in this run:',
322
+ '- `ach` is NOT a shell command here (commands in this run have no network; `ach` in a shell fails). It is the tool `ach` of the "ach" MCP server.',
323
+ '- Wherever these instructions write `ach <command> ...`, call that tool with the arguments as a list, without the leading "ach": `ach progress "half done"` is args ["progress", "half done"]; `ach complete --result-file .ach/result.md` is args ["complete", "--result-file", ".ach/result.md"]; `ach ask-human "<q>" --option "A|..|.." --option "B|..|.."` is args ["ask-human", "<q>", "--option", "A|..|..", "--option", "B|..|.."].',
324
+ '- Files named in the arguments (--result-file, --attach) must be inside the current directory.',
325
+ '- After `ach ask` or `ach ask-human`, stop and end your turn: you are resumed with the answer.',
326
+ '',
327
+ ].join('\n');
319
328
  /** JUDGMENT for a run without `ach`: the same lines of decision, said in the final message instead of through commands. */
320
329
  export const JUDGMENT_REPORT = [
321
330
  'How to decide (AgentChannel\'s default for every agent):',
@@ -387,6 +396,7 @@ export function buildTaskPrompt(c) {
387
396
  'Task data:',
388
397
  untrustedBlock(data),
389
398
  '',
399
+ ...(c.achTool && !c.remote && !c.report ? [ACH_TOOL_NOTE] : []),
390
400
  c.remote ? REMOTE_RULES : c.report ? LOCAL_REPORT_RULES : rules(!!c.task.review),
391
401
  githubRule(c.taskUrl),
392
402
  '',
@@ -418,6 +428,8 @@ export function buildResumePrompt(c) {
418
428
  if (c.handoffChanged !== undefined) {
419
429
  lines.push(`- The sender updated the task (now handoff v${c.handoffVersion}): follow the new handoff and header (priority, purpose, money, key question) above.`);
420
430
  }
431
+ if (c.achTool && !c.remote && !c.report)
432
+ lines.push('- As before, `ach` is the tool `ach` of the "ach" MCP server (arguments as a list), not a shell command.');
421
433
  lines.push(c.remote || c.report
422
434
  ? `Continue the task. End with your final message (start it with "${REMOTE_FAILED_PREFIX}" if it cannot be done).`
423
435
  : 'Continue the task. Use `ach ask` / `ach ask-human` again if needed. Finish by calling `ach complete`.');
@@ -547,7 +559,8 @@ export function buildMentionPrompt(c) {
547
559
  ownerAskedRule(c.ownerName, false),
548
560
  "- Flag values go in single quotes, with no backtick or `$` in them; the heredoc's last line is `EOF` alone.",
549
561
  '- `ach thread` shows the whole thread; `ach channel` the channel. Reply once, then stop.',
550
- '- Besides these three `ach` commands only `git log`, `git show`, `git diff`, `git blame` and `git status` run here, each as one plain command (no pipes, no `cd`); any other command is refused (that does not mean `ach reply` is). Read files with Read, Glob and Grep.',
562
+ '- Besides these three `ach` commands only `git log`, `git show`, `git diff`, `git blame` and `git status` run here, and for GitHub `gh pr view|diff|checks|list`, `gh issue view|list` and `gh run view|list` (a pull request\'s branch is usually not in the local history: read it with `gh pr view <n>` and `gh pr diff <n>`), each as one plain command (no pipes, no `cd`); any other command is refused (that does not mean `ach reply` is). Read files with Read, Glob and Grep.',
563
+ '- Say you cannot read something only after the command for it failed, and quote its error in the evidence.',
551
564
  '- If `ach reply` itself is refused or fails, end with the reply as your last message, written to the people in the thread: it is posted there as your reply.',
552
565
  '- Mention other agents (@name) only when you really need them; every agent-to-agent mention counts against the thread\'s hop limit.',
553
566
  ];
@@ -1038,6 +1038,7 @@ export class Runner {
1038
1038
  judgment: claim.judgment,
1039
1039
  remote: !!this.cloud,
1040
1040
  report: !this.o.adapter.spec.ach,
1041
+ achTool: this.o.adapter.spec.achBy === 'tool',
1041
1042
  ...this.runContext(workdir),
1042
1043
  });
1043
1044
  this.reportPromptSize(taskId, rec.runId, prompt);
@@ -1123,6 +1124,7 @@ export class Runner {
1123
1124
  nudge,
1124
1125
  remote: !!this.cloud,
1125
1126
  report: !this.o.adapter.spec.ach,
1127
+ achTool: this.o.adapter.spec.achBy === 'tool',
1126
1128
  })
1127
1129
  : buildTaskPrompt({
1128
1130
  agentName: me.name,
@@ -1141,6 +1143,7 @@ export class Runner {
1141
1143
  judgment: bundle.judgment,
1142
1144
  remote: !!this.cloud,
1143
1145
  report: !this.o.adapter.spec.ach,
1146
+ achTool: this.o.adapter.spec.achBy === 'tool',
1144
1147
  ...this.runContext(rec.workdir),
1145
1148
  });
1146
1149
  if (!resume)
@@ -0,0 +1,18 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ /**
3
+ * `ach` as a tool, for a run whose commands cannot reach the hub (a sandbox without network: antigravity). The runtime starts
4
+ * this stdio MCP server outside its sandbox with the run's environment (the run token, the task id); its one tool runs an
5
+ * `ach` command of the task, given as a list of arguments. No shell is involved, and the command is the same CLI with the same
6
+ * limits a run token has (its own task only; files named in arguments must be inside the working directory).
7
+ */
8
+ export declare const RUN_TOOL_SERVER = "ach";
9
+ export declare const RUN_TOOL = "ach";
10
+ export interface RunToolResult {
11
+ code: number;
12
+ stdout: string;
13
+ stderr: string;
14
+ }
15
+ /** What the model reads back: the output as the command printed it, and the exit code when it failed. Pure. */
16
+ export declare function runToolText(r: RunToolResult): string;
17
+ export declare function buildRunToolServer(run: (args: string[]) => Promise<RunToolResult>): McpServer;
18
+ export declare function serveRunTool(run: (args: string[]) => Promise<RunToolResult>): Promise<void>;
@@ -0,0 +1,35 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { z } from 'zod';
4
+ import { VERSION } from './version.js';
5
+ /**
6
+ * `ach` as a tool, for a run whose commands cannot reach the hub (a sandbox without network: antigravity). The runtime starts
7
+ * this stdio MCP server outside its sandbox with the run's environment (the run token, the task id); its one tool runs an
8
+ * `ach` command of the task, given as a list of arguments. No shell is involved, and the command is the same CLI with the same
9
+ * limits a run token has (its own task only; files named in arguments must be inside the working directory).
10
+ */
11
+ export const RUN_TOOL_SERVER = 'ach';
12
+ export const RUN_TOOL = 'ach';
13
+ /** Commands that make no sense from inside the tool (servers, nested runners): refused before the CLI sees them. */
14
+ const NESTED = new Set(['run-tool-serve', 'caps-serve', 'mcp', 'run']);
15
+ /** What the model reads back: the output as the command printed it, and the exit code when it failed. Pure. */
16
+ export function runToolText(r) {
17
+ const out = [r.stdout.trim(), r.stderr.trim()].filter(Boolean).join('\n');
18
+ return r.code === 0 ? out || 'ok' : `exit ${r.code}\n${out}`.trim();
19
+ }
20
+ export function buildRunToolServer(run) {
21
+ const server = new McpServer({ name: RUN_TOOL_SERVER, version: VERSION });
22
+ server.registerTool(RUN_TOOL, {
23
+ description: 'Run an `ach` command of this task (AgentChannel: progress, ask, ask-human, complete, fail, reply, channel, recall, memory read ...). ' +
24
+ 'Give the arguments as a list, without the leading "ach": `ach progress "half done"` is ["progress", "half done"]; ' +
25
+ '`ach complete --result-file .ach/result.md` is ["complete", "--result-file", ".ach/result.md"]. Returns what the command printed.',
26
+ inputSchema: { args: z.array(z.string()).min(1).max(60).describe('The command and its arguments, one list item each') },
27
+ }, async ({ args }) => {
28
+ const r = NESTED.has(args[0]) ? { code: 2, stdout: '', stderr: `ach ${args[0]} is not available in a run` } : await run(args).catch((e) => ({ code: 1, stdout: '', stderr: String(e?.message ?? e) }));
29
+ return { content: [{ type: 'text', text: runToolText(r).slice(0, 60_000) }], ...(r.code === 0 ? {} : { isError: true }) };
30
+ });
31
+ return server;
32
+ }
33
+ export async function serveRunTool(run) {
34
+ await buildRunToolServer(run).connect(new StdioServerTransport());
35
+ }
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.55.0";
1
+ export declare const VERSION = "3.56.0";
2
2
  /** The npm package (scripts/release.mjs keeps it and VERSION in step with package.json). */
3
3
  export declare const PKG_NAME = "@koalaauto/agentchannel";
4
4
  /**
@@ -1,4 +1,4 @@
1
- export const VERSION = '3.55.0';
1
+ export const VERSION = '3.56.0';
2
2
  /** The npm package (scripts/release.mjs keeps it and VERSION in step with package.json). */
3
3
  export const PKG_NAME = '@koalaauto/agentchannel';
4
4
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koalaauto/agentchannel",
3
- "version": "3.55.0",
3
+ "version": "3.56.0",
4
4
  "description": "Hand work between your team's agents (Claude Code, Codex) and follow it in one panel: the ach CLI, MCP server and runner for AgentChannel v2",
5
5
  "keywords": [
6
6
  "agentchannel",