@koalaauto/agentchannel 3.55.1 → 3.57.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,
@@ -154,6 +154,7 @@ export declare class ClaudeAdapter implements RuntimeAdapter {
154
154
  readonly label: "Claude Code";
155
155
  readonly where: "local";
156
156
  readonly ach: true;
157
+ readonly achBy: "command";
157
158
  readonly structuredAnswers: false;
158
159
  readonly perms: readonly Perm[];
159
160
  readonly limits: {
@@ -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 },
@@ -135,6 +135,7 @@ export function adoptFromNpx(o) {
135
135
  const cur = currentVersion(app);
136
136
  if (!cur || cur === version || newerVersion(version, cur))
137
137
  setCurrent(app, version);
138
+ pruneApp(app);
138
139
  return appAch(env, app);
139
140
  }
140
141
  catch (e) {
@@ -199,6 +200,16 @@ export function pruneApp(app, now = Date.now(), keep = 3, minAgeMs = 3 * 24 * 36
199
200
  }
200
201
  const newest = [...names].sort((a, b) => (newerVersion(a, b) ? -1 : newerVersion(b, a) ? 1 : 0)).slice(0, keep);
201
202
  const out = [];
203
+ // half-made copies of a process that ended mid-way (`.<version>.<pid>.tmp`)
204
+ try {
205
+ for (const t of readdirSync(app).filter((n) => /^\..+\.tmp$/.test(n))) {
206
+ if (now - statSync(join(app, t)).mtimeMs > 24 * 3600_000)
207
+ rmSync(join(app, t), { recursive: true, force: true });
208
+ }
209
+ }
210
+ catch {
211
+ /* left for the next prune */
212
+ }
202
213
  for (const v of names) {
203
214
  if (v === cur || newest.includes(v))
204
215
  continue;
@@ -53,6 +53,8 @@ export interface FeedSocket {
53
53
  }
54
54
  export interface ChangeFeedOptions {
55
55
  onChange: () => unknown;
56
+ /** Is this event (the hub's `{kind, id, channel, thread, to, from}`) one to act on? Absent: every event is. A message that is not JSON counts. */
57
+ relevant?: (event: Record<string, unknown>) => boolean;
56
58
  /** Opens the hub's change stream (GET /api/ach/events; Client.eventsSocket). Absent or null: polling only. */
57
59
  socket?: () => FeedSocket | null;
58
60
  /** How long a socket may take to open before polling takes over. */
@@ -105,3 +107,12 @@ export declare const defaultExec: Exec;
105
107
  export declare function codexThreadId(env: NodeJS.ProcessEnv): string | undefined;
106
108
  /** `codex queue --thread <id> --message <notice>`: the notice as a queued message in that session. */
107
109
  export declare function codexQueue(text: string, env: NodeJS.ProcessEnv, exec?: Exec): Promise<boolean>;
110
+ /**
111
+ * Does this event mean a runner should look at its agent's inbox now? A task event that names the two agents it is between
112
+ * concerns only them; a post or a reply may mention anyone; what is addressed to a person (`notification`) or is about the
113
+ * channel list is not a runner's. An event that does not say (an older hub, a kind this release does not know) counts: asking
114
+ * once too often is harmless, missing work is not. `me` unknown yet: every event counts.
115
+ */
116
+ export declare function wakesRunner(ev: Record<string, unknown>, me: string | undefined): boolean;
117
+ /** What needs a person arrives as a `notification` event addressed to them; the rest of the team's traffic is not a reason to count again (the periodic check still runs). */
118
+ export declare const wakesAttention: (ev: Record<string, unknown>) => boolean;
@@ -279,9 +279,21 @@ export class ChangeFeed {
279
279
  check = setInterval(() => void this.fire(), this.o.wsCheckMs ?? 5 * 60_000);
280
280
  check.unref?.();
281
281
  });
282
- sock.addEventListener('message', () => {
283
- if (!done && !this.stopped)
284
- void this.fire();
282
+ sock.addEventListener('message', (m) => {
283
+ if (done || this.stopped)
284
+ return;
285
+ if (this.o.relevant) {
286
+ let ev;
287
+ try {
288
+ ev = JSON.parse(String(m?.data));
289
+ }
290
+ catch {
291
+ ev = undefined;
292
+ }
293
+ if (ev && typeof ev === 'object' && !this.o.relevant(ev))
294
+ return;
295
+ }
296
+ void this.fire();
285
297
  });
286
298
  sock.addEventListener('close', finish);
287
299
  sock.addEventListener('error', () => {
@@ -360,3 +372,20 @@ export async function codexQueue(text, env, exec = defaultExec) {
360
372
  const r = await exec(env.ACH_CODEX_BIN || 'codex', ['queue', '--thread', thread, '--message', text]);
361
373
  return r.code === 0;
362
374
  }
375
+ /**
376
+ * Does this event mean a runner should look at its agent's inbox now? A task event that names the two agents it is between
377
+ * concerns only them; a post or a reply may mention anyone; what is addressed to a person (`notification`) or is about the
378
+ * channel list is not a runner's. An event that does not say (an older hub, a kind this release does not know) counts: asking
379
+ * once too often is harmless, missing work is not. `me` unknown yet: every event counts.
380
+ */
381
+ export function wakesRunner(ev, me) {
382
+ if (ev.kind === 'notification' || ev.kind === 'channels')
383
+ return false;
384
+ if (ev.kind !== 'task' || !me)
385
+ return true;
386
+ if (typeof ev.to !== 'string' && typeof ev.from !== 'string')
387
+ return true;
388
+ return ev.to === me || ev.from === me;
389
+ }
390
+ /** What needs a person arrives as a `notification` event addressed to them; the rest of the team's traffic is not a reason to count again (the periodic check still runs). */
391
+ export const wakesAttention = (ev) => typeof ev.kind !== 'string' || ev.kind === 'notification';
@@ -111,7 +111,7 @@ export async function runCommand(p, io) {
111
111
  if (v['install-service'])
112
112
  return installService(p, io, { agentName: me.name, formerNames: me.former_names ?? [], dir, repos: repoFlags, home });
113
113
  // started by a service that starts through the npx cache: make it start the install in the AgentChannel home
114
- const moved = await moveOldService(io, me.name, home);
114
+ const moved = await moveOldService(io, { agentName: me.name, formerNames: me.former_names ?? [], runDir: dir }, home);
115
115
  if (moved)
116
116
  return UPDATE_EXIT_CODE;
117
117
  void moveMcpEntries(io, dir).catch(() => { });
@@ -155,6 +155,8 @@ export async function runCommand(p, io) {
155
155
  max: str(v.max) ? Math.max(1, Math.floor(parseNum(str(v.max), 'max'))) : 2,
156
156
  perm,
157
157
  intervalMs: (str(v.interval) ? parseNum(str(v.interval), 'interval') : 3) * 1000,
158
+ // the hub's change stream: an idle runner is told when there is work instead of asking every interval (ACH_RUN_STREAM=0: poll only)
159
+ ...(env.ACH_RUN_STREAM === '0' ? {} : { socket: () => c.eventsSocket() }),
158
160
  claimDelayMs: claimDelay * 1000,
159
161
  readAhead: true,
160
162
  noTrace: !!v['no-trace'] || env.ACH_NO_TRACE === '1',
@@ -414,17 +416,17 @@ function lingers(env) {
414
416
  * the AgentChannel home, the service rewritten to start that, the supervisor has it reloaded, and this one stops (the reload starts the
415
417
  * new one).
416
418
  */
417
- async function moveOldService(io, agentName, home) {
419
+ async function moveOldService(io, who, home) {
418
420
  const env = io.env;
419
421
  const platform = (env.ACH_SERVICE_PLATFORM || process.platform);
420
422
  if (platform !== 'darwin' && platform !== 'linux')
421
423
  return false;
422
- const { migrateOldService, reloadDetached, startedByService } = await import('./servicefix.js');
423
- if (!env.ACH_SERVICE_DIR && !startedByService(agentName, platform, env))
424
+ const { migrateOldService, ownService, reloadDetached, startedByService, startsThroughNpx } = await import('./servicefix.js');
425
+ const own = ownService({ ...who, platform, dir: env.ACH_SERVICE_DIR || undefined, env, home });
426
+ if (!own || !startsThroughNpx(own))
424
427
  return false;
425
- const { listServices } = await import('./service.js');
426
- const own = listServices(platform, env.ACH_SERVICE_DIR || undefined, env).find((s) => s.agentName === agentName.replace(/[^A-Za-z0-9-]/g, '-'));
427
- if (!own || (own.format !== 'npx' && own.format !== 'node-cache'))
428
+ // launchd names the service by its file's label: a renamed agent's service still has the old name
429
+ if (!env.ACH_SERVICE_DIR && !startedByService(own.agentName, platform, env))
428
430
  return false;
429
431
  const { adoptFromNpx, appAch, appDir, currentVersion } = await import('./appinstall.js');
430
432
  const { thisCliPath } = await import('./invite.js');
@@ -434,7 +436,7 @@ async function moveOldService(io, agentName, home) {
434
436
  return false;
435
437
  let m;
436
438
  try {
437
- m = migrateOldService({ agentName, platform, dir: env.ACH_SERVICE_DIR || undefined, env, home, command });
439
+ m = migrateOldService({ ...who, platform, dir: env.ACH_SERVICE_DIR || undefined, env, home, command });
438
440
  }
439
441
  catch (e) {
440
442
  io.err(`[ach run] could not rewrite the service file: ${e?.message ?? e}`);
@@ -447,50 +449,14 @@ async function moveOldService(io, agentName, home) {
447
449
  reloadDetached(m.start, env);
448
450
  return true;
449
451
  }
450
- /** A runner of the install in the AgentChannel home points the `ach` MCP entries that still start npx at it (onboard moveNpxMcpEntries). */
452
+ /** A runner of the install in the AgentChannel home points the `ach` MCP entries that still start npx at it (mcpmove.ts). */
451
453
  async function moveMcpEntries(io, dir) {
452
454
  const { appAch, appDir, inApp } = await import('./appinstall.js');
453
455
  const { thisCliPath } = await import('./invite.js');
454
456
  if (io.env.ACH_SERVICE_DIR || !inApp(thisCliPath(), appDir(io.env)))
455
457
  return; // tests, and runs of other installs
456
- const { moveNpxMcpEntries } = await import('./onboard.js');
457
- const { execFile } = await import('node:child_process');
458
- const execIn = (cwd) => (file, args, env) => new Promise((res) => execFile(file, args, { cwd, env, timeout: 30_000, encoding: 'utf8' }, (err, stdout, stderr) => res({ code: err ? (typeof err.code === 'number' ? err.code : 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })));
459
- // the user-scope entry is seen from a dir with no local entry: an empty one of ours
460
- const empty = join(appDir(io.env), 'mcp-cwd');
461
- (await import('node:fs')).mkdirSync(empty, { recursive: true });
462
- // the runners of one machine restart together after a release: one at a time, since each `claude mcp add` rewrites ~/.claude.json
463
- const { openSync, closeSync, statSync, unlinkSync } = await import('node:fs');
464
- const lock = join(appDir(io.env), 'mcp-move.lock');
465
- for (let i = 0;; i++) {
466
- try {
467
- closeSync(openSync(lock, 'wx'));
468
- break;
469
- }
470
- catch {
471
- try {
472
- if (Date.now() - statSync(lock).mtimeMs > 120_000)
473
- unlinkSync(lock); // left by a runner that died holding it
474
- }
475
- catch {
476
- /* gone already */
477
- }
478
- if (i >= 90)
479
- return;
480
- await new Promise((r) => setTimeout(r, 2000));
481
- }
482
- }
483
- try {
484
- const moved = await moveNpxMcpEntries({ env: io.env, exec: execIn(dir), userExec: execIn(empty), achCmd: appAch(io.env), log: (s) => io.err(`[ach run] ${s}`) });
485
- if (moved.length)
486
- io.err(`[ach run] the \`ach\` MCP entry (${moved.join(', ')}) started npx: it starts ${appAch(io.env).join(' ')} now (new sessions)`);
487
- }
488
- finally {
489
- try {
490
- unlinkSync(lock);
491
- }
492
- catch {
493
- /* gone already */
494
- }
495
- }
458
+ const { moveNpxMcpEntriesHere } = await import('./mcpmove.js');
459
+ const moved = await moveNpxMcpEntriesHere({ env: io.env, dir, log: (s) => io.err(`[ach run] ${s}`) });
460
+ if (moved.length)
461
+ io.err(`[ach run] the \`ach\` MCP entry (${moved.join(', ')}) started npx: it starts ${appAch(io.env).join(' ')} now (new sessions)`);
496
462
  }
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);