@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.
package/dist/src/mcp.js CHANGED
@@ -6,7 +6,7 @@ import { FACT_RULE, refOf, taskUrl } from './prompts.js';
6
6
  import { VERSION } from './version.js';
7
7
  import { resolveAttachments, taskFiles } from './attachments.js';
8
8
  import { isAbsolute, join, relative } from 'node:path';
9
- import { AttentionNotifier, ChangeFeed, codexQueue, defaultExec, fetchAttention } from './attention.js';
9
+ import { AttentionNotifier, ChangeFeed, codexQueue, defaultExec, fetchAttention, wakesAttention } from './attention.js';
10
10
  import { isZh } from './client.js';
11
11
  import { startStaleNotice } from './selfupdate.js';
12
12
  import { decisionTo, explainToUser, mentionNames, unknownMentions } from './names.js';
@@ -540,7 +540,8 @@ export function startSessionNotices(server, client, o = {}) {
540
540
  gapMs: o.gapMs,
541
541
  log: o.log,
542
542
  });
543
- const feed = new ChangeFeed({ socket: () => client.eventsSocket(), onChange: () => notifier.check(), log: o.log, ...o.feed });
543
+ // (only what is addressed to this person: counting again for every event of the team made this the hub's most asked question)
544
+ const feed = new ChangeFeed({ socket: () => client.eventsSocket(), onChange: () => notifier.check(), relevant: wakesAttention, log: o.log, ...o.feed });
544
545
  const done = feed.run();
545
546
  // a session cannot be restarted from outside: when the hub names a newer ach, say so once (see selfupdate.ts)
546
547
  const stale = startStaleNotice({
@@ -577,4 +578,29 @@ export async function startMcp(client, where = { cwd: process.cwd() }) {
577
578
  };
578
579
  server.server.onclose = () => notices?.stop();
579
580
  await server.connect(new StdioServerTransport());
581
+ moveOffNpxLater(where.cwd);
582
+ }
583
+ /**
584
+ * Started from npx (`npx -y <spec> mcp`): some time after start, copy this release into the install in the AgentChannel home and point
585
+ * the npx `ach` entries at it (mcpmove.ts), so the next session starts without npm. A runner service does the same on Mac and Linux;
586
+ * this reaches the machines without one (Windows, a join whose service did not install). This session goes on as it is.
587
+ */
588
+ function moveOffNpxLater(cwd, delayMs = 30_000) {
589
+ const timer = setTimeout(() => {
590
+ void (async () => {
591
+ const { adoptFromNpx, npxModulesOf } = await import('./appinstall.js');
592
+ const { thisCliPath } = await import('./invite.js');
593
+ const self = thisCliPath();
594
+ if (!npxModulesOf(self))
595
+ return;
596
+ const log = (s) => process.stderr.write(`[ach mcp] ${s}\n`);
597
+ if (!adoptFromNpx({ self, env: process.env, log }))
598
+ return;
599
+ const { moveNpxMcpEntriesHere } = await import('./mcpmove.js');
600
+ const moved = await moveNpxMcpEntriesHere({ env: process.env, dir: cwd, log });
601
+ if (moved.length)
602
+ log(`the \`ach\` MCP entry (${moved.join(', ')}) starts the install in the AgentChannel home from the next session`);
603
+ })().catch(() => { });
604
+ }, delayMs);
605
+ timer.unref?.();
580
606
  }
@@ -0,0 +1,37 @@
1
+ import { type ExecLike } from './doctor.js';
2
+ import { type Argv } from './onboard.js';
3
+ /** An entry that starts this package through npx, directly or through `cmd /c` (Claude Code on Windows). */
4
+ export declare function isNpxEntry(e: {
5
+ command?: string;
6
+ args: string[];
7
+ }): boolean;
8
+ /**
9
+ * The user's `claude` / `codex`. On Windows the extension-less file npm puts beside `claude.cmd` is a shell script nothing can start:
10
+ * the .exe (native installer) or .cmd (npm) is what runs.
11
+ */
12
+ export declare function toolBin(name: 'claude' | 'codex', env: NodeJS.ProcessEnv, platform?: string): string | undefined;
13
+ /** Runs a tool in `cwd`; a .cmd/.bat goes through the shell with its arguments quoted. Never throws. */
14
+ export declare function execIn(cwd: string): ExecLike;
15
+ /**
16
+ * Points the npx `ach` entries at `achCmd`, keeping their scope and AGENTCHANNEL_HOME. `exec` runs in the project dir, where Claude Code
17
+ * keeps a local-scope entry; `userExec` in a dir with no entries of its own, where `claude mcp get` shows the user-scope one (a local
18
+ * entry hides it). A project-scope entry (.mcp.json, in the repository) is left alone. Returns what was moved, as `<tool> <scope>`.
19
+ */
20
+ export declare function moveNpxMcpEntries(o: {
21
+ env: NodeJS.ProcessEnv;
22
+ exec: ExecLike;
23
+ userExec?: ExecLike;
24
+ achCmd: Argv;
25
+ findBin?: (kind: 'claude' | 'codex') => string | undefined;
26
+ log?: (s: string) => void;
27
+ }): Promise<string[]>;
28
+ /**
29
+ * moveNpxMcpEntries for the project in `dir`, one process at a time on the machine: the runners restart together after a release, and
30
+ * several sessions start their MCP at once, while each `claude mcp add` rewrites ~/.claude.json. Waits up to three minutes for the lock.
31
+ */
32
+ export declare function moveNpxMcpEntriesHere(o: {
33
+ env: NodeJS.ProcessEnv;
34
+ dir: string;
35
+ log?: (s: string) => void;
36
+ waitMs?: number;
37
+ }): Promise<string[]>;
@@ -0,0 +1,134 @@
1
+ // Moving the `ach` MCP entries that start npx (`npx -y @koalaauto/agentchannel@3 mcp`, on Windows also `cmd /c npx ...`) to the install
2
+ // in the AgentChannel home (appinstall.ts). npx re-resolves the spec at every session start and fails while npm catches up with a
3
+ // release ("Reconnect ach"). Two callers: a runner of the install (its service was just moved there), and `ach mcp` started from npx
4
+ // (machines without a runner service: Windows, or a join whose service did not install). Both copy the release first, then this.
5
+ import { execFile } from 'node:child_process';
6
+ import { accessSync, closeSync, constants, mkdirSync, openSync, statSync, unlinkSync } from 'node:fs';
7
+ import { delimiter, join } from 'node:path';
8
+ import { appAch, appDir } from './appinstall.js';
9
+ import { parseMcpEntry } from './doctor.js';
10
+ import { isBundledBin, MCP_SERVER_NAME, userBin } from './invite.js';
11
+ import { mcpAddArgv, mcpRemoveArgv } from './onboard.js';
12
+ import { PKG_NAME } from './version.js';
13
+ /** An entry that starts this package through npx, directly or through `cmd /c` (Claude Code on Windows). */
14
+ export function isNpxEntry(e) {
15
+ if (!e.command || e.args.at(-1) !== 'mcp')
16
+ return false;
17
+ const npx = (x) => !!x && /(^|[\\/])npx(\.cmd)?$/i.test(x);
18
+ const viaCmd = /(^|[\\/])cmd(\.exe)?$/i.test(e.command) && /^\/c$/i.test(e.args[0] ?? '') && npx(e.args[1]);
19
+ return (npx(e.command) || viaCmd) && e.args.some((a) => a === PKG_NAME || a.startsWith(`${PKG_NAME}@`));
20
+ }
21
+ /**
22
+ * The user's `claude` / `codex`. On Windows the extension-less file npm puts beside `claude.cmd` is a shell script nothing can start:
23
+ * the .exe (native installer) or .cmd (npm) is what runs.
24
+ */
25
+ export function toolBin(name, env, platform = process.platform) {
26
+ if (platform !== 'win32')
27
+ return userBin(name, env);
28
+ for (const d of (env.PATH ?? env.Path ?? '').split(delimiter)) {
29
+ if (!d || isBundledBin(join(d, 'x')))
30
+ continue;
31
+ for (const ext of ['.exe', '.cmd']) {
32
+ try {
33
+ accessSync(join(d, name + ext), constants.F_OK);
34
+ return join(d, name + ext);
35
+ }
36
+ catch {
37
+ /* next */
38
+ }
39
+ }
40
+ }
41
+ return undefined;
42
+ }
43
+ /** cmd.exe quoting for one argument (a .cmd file runs through the shell, which would split a path with a space). */
44
+ const cmdQuote = (s) => (/^[A-Za-z0-9_./:=@\\-]+$/.test(s) ? s : `"${s.replace(/"/g, '""')}"`);
45
+ /** Runs a tool in `cwd`; a .cmd/.bat goes through the shell with its arguments quoted. Never throws. */
46
+ export function execIn(cwd) {
47
+ return (file, args, env) => new Promise((res) => {
48
+ const shell = /\.(cmd|bat)$/i.test(file);
49
+ const [f, a] = shell ? [cmdQuote(file), args.map(cmdQuote)] : [file, args];
50
+ execFile(f, a, { cwd, env, timeout: 30_000, encoding: 'utf8', shell, windowsHide: true }, (err, stdout, stderr) => res({ code: err ? (typeof err.code === 'number' ? err.code : 1) : 0, stdout: String(stdout ?? ''), stderr: String(stderr ?? '') }));
51
+ });
52
+ }
53
+ /**
54
+ * Points the npx `ach` entries at `achCmd`, keeping their scope and AGENTCHANNEL_HOME. `exec` runs in the project dir, where Claude Code
55
+ * keeps a local-scope entry; `userExec` in a dir with no entries of its own, where `claude mcp get` shows the user-scope one (a local
56
+ * entry hides it). A project-scope entry (.mcp.json, in the repository) is left alone. Returns what was moved, as `<tool> <scope>`.
57
+ */
58
+ export async function moveNpxMcpEntries(o) {
59
+ const moved = [];
60
+ const find = o.findBin ?? ((k) => toolBin(k, o.env));
61
+ const looks = [
62
+ { kind: 'claude', exec: o.exec },
63
+ ...(o.userExec ? [{ kind: 'claude', exec: o.userExec }] : []),
64
+ { kind: 'codex', exec: o.exec },
65
+ ];
66
+ for (const { kind, exec } of looks) {
67
+ const bin = find(kind);
68
+ if (!bin)
69
+ continue;
70
+ const got = await exec(bin, ['mcp', 'get', MCP_SERVER_NAME], o.env);
71
+ if (got.code !== 0)
72
+ continue;
73
+ const e = parseMcpEntry(got.stdout, MCP_SERVER_NAME);
74
+ if (!isNpxEntry(e))
75
+ continue;
76
+ const scope = kind === 'codex' ? 'user' : /^\s*Scope:\s*Local/im.test(got.stdout) ? 'local' : /^\s*Scope:\s*User/im.test(got.stdout) ? 'user' : undefined;
77
+ if (!scope || moved.includes(`${kind} ${scope}`))
78
+ continue;
79
+ const local = scope === 'local';
80
+ const rm = await exec(bin, mcpRemoveArgv(kind, bin, MCP_SERVER_NAME, local).slice(1), o.env);
81
+ if (rm.code !== 0) {
82
+ o.log?.(`could not remove the npx \`ach\` entry of ${kind} (exit ${rm.code}): ${rm.stderr.trim().split('\n')[0] ?? ''}`);
83
+ continue;
84
+ }
85
+ const add = await exec(bin, mcpAddArgv(kind, bin, o.achCmd, e.home, local).slice(1), o.env);
86
+ if (add.code !== 0) {
87
+ // the entry is gone now: put the npx one back rather than leave the tool without AgentChannel
88
+ await exec(bin, mcpAddArgv(kind, bin, [e.command, ...e.args.slice(0, -1)], e.home, local).slice(1), o.env);
89
+ o.log?.(`could not point the \`ach\` entry of ${kind} at ${o.achCmd.join(' ')} (exit ${add.code}): kept npx`);
90
+ continue;
91
+ }
92
+ moved.push(`${kind} ${scope}`);
93
+ }
94
+ return moved;
95
+ }
96
+ /**
97
+ * moveNpxMcpEntries for the project in `dir`, one process at a time on the machine: the runners restart together after a release, and
98
+ * several sessions start their MCP at once, while each `claude mcp add` rewrites ~/.claude.json. Waits up to three minutes for the lock.
99
+ */
100
+ export async function moveNpxMcpEntriesHere(o) {
101
+ const app = appDir(o.env);
102
+ const empty = join(app, 'mcp-cwd'); // the user-scope entry is seen from a dir with no local entry: an empty one of ours
103
+ mkdirSync(empty, { recursive: true });
104
+ const lock = join(app, 'mcp-move.lock');
105
+ for (let waited = 0;; waited += 2000) {
106
+ try {
107
+ closeSync(openSync(lock, 'wx'));
108
+ break;
109
+ }
110
+ catch {
111
+ try {
112
+ if (Date.now() - statSync(lock).mtimeMs > 120_000)
113
+ unlinkSync(lock); // left by a process that died holding it
114
+ }
115
+ catch {
116
+ /* gone already */
117
+ }
118
+ if (waited >= (o.waitMs ?? 180_000))
119
+ return [];
120
+ await new Promise((r) => setTimeout(r, 2000));
121
+ }
122
+ }
123
+ try {
124
+ return await moveNpxMcpEntries({ env: o.env, exec: execIn(o.dir), userExec: execIn(empty), achCmd: appAch(o.env), log: o.log });
125
+ }
126
+ finally {
127
+ try {
128
+ unlinkSync(lock);
129
+ }
130
+ catch {
131
+ /* gone already */
132
+ }
133
+ }
134
+ }
@@ -1,4 +1,4 @@
1
- import { type ExecLike } from './doctor.js';
1
+ import type { ExecLike } from './doctor.js';
2
2
  import { type SandboxStatus, type SandboxTool } from './sandboxcheck.js';
3
3
  /**
4
4
  * One-line onboarding: what `ach join` sets up after the key is stored.
@@ -117,22 +117,3 @@ export interface SetupResult {
117
117
  export declare function runSetup(io: SetupIo, o: SetupOptions): Promise<SetupResult>;
118
118
  /** The Linux command that lets a user's services outlive their logins. */
119
119
  export declare const LINGER_CMD = "sudo loginctl enable-linger \"$USER\"";
120
- /** An entry that starts this package through npx (`npx -y @koalaauto/agentchannel@3 mcp`). */
121
- export declare function isNpxEntry(e: {
122
- command?: string;
123
- args: string[];
124
- }): boolean;
125
- /**
126
- * The `ach` MCP entries of Claude Code and Codex that join wrote as `npx -y <spec> mcp` are pointed at the install in the AgentChannel
127
- * home (`achCmd`), keeping their scope and AGENTCHANNEL_HOME: npx re-resolves the spec at every session start and fails while npm catches
128
- * up with a release. `exec` runs in the runner's project dir, where Claude Code keeps a local-scope entry; `userExec` in a dir with no
129
- * entries of its own, where `claude mcp get` shows the user-scope one (a local entry hides it). A project-scope entry (.mcp.json, in the
130
- * repository) is left alone. Returns what was moved, as `<tool> <scope>`.
131
- */
132
- export declare function moveNpxMcpEntries(o: {
133
- env: NodeJS.ProcessEnv;
134
- exec: ExecLike;
135
- userExec?: ExecLike;
136
- achCmd: Argv;
137
- log?: (s: string) => void;
138
- }): Promise<string[]>;
@@ -1,10 +1,8 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
- import { parseMcpEntry } from './doctor.js';
4
3
  import { probeSandbox } from './sandboxcheck.js';
5
4
  import { adoptFromNpx, appAch } from './appinstall.js';
6
5
  import { identifyAch, isOurs, MCP_SERVER_NAME, npxAch, thisCliPath, userBin, whichAll } from './invite.js';
7
- import { PKG_NAME } from './version.js';
8
6
  /** The closing line: which tool to open and what to say to it. */
9
7
  export function doneLine(tools, zh) {
10
8
  const names = [...new Set(tools)].map((k) => (k === 'claude' ? 'Claude Code' : 'Codex'));
@@ -320,51 +318,3 @@ function printOnly(io, d, plan, o) {
320
318
  out.push('', `${zh ? '随时检查配置:' : 'Check the setup any time with: '}${shellLine([...(d.npx ? d.achCmd : ['ach']), 'doctor'])}`);
321
319
  io.out(out.join('\n'));
322
320
  }
323
- /** An entry that starts this package through npx (`npx -y @koalaauto/agentchannel@3 mcp`). */
324
- export function isNpxEntry(e) {
325
- return !!e.command && /(^|[\\/])npx(\.cmd)?$/.test(e.command) && e.args.at(-1) === 'mcp' && e.args.some((a) => a === PKG_NAME || a.startsWith(`${PKG_NAME}@`));
326
- }
327
- /**
328
- * The `ach` MCP entries of Claude Code and Codex that join wrote as `npx -y <spec> mcp` are pointed at the install in the AgentChannel
329
- * home (`achCmd`), keeping their scope and AGENTCHANNEL_HOME: npx re-resolves the spec at every session start and fails while npm catches
330
- * up with a release. `exec` runs in the runner's project dir, where Claude Code keeps a local-scope entry; `userExec` in a dir with no
331
- * entries of its own, where `claude mcp get` shows the user-scope one (a local entry hides it). A project-scope entry (.mcp.json, in the
332
- * repository) is left alone. Returns what was moved, as `<tool> <scope>`.
333
- */
334
- export async function moveNpxMcpEntries(o) {
335
- const moved = [];
336
- const looks = [
337
- { kind: 'claude', exec: o.exec },
338
- ...(o.userExec ? [{ kind: 'claude', exec: o.userExec }] : []),
339
- { kind: 'codex', exec: o.exec },
340
- ];
341
- for (const { kind, exec } of looks) {
342
- const bin = userBin(kind, o.env);
343
- if (!bin)
344
- continue;
345
- const got = await exec(bin, ['mcp', 'get', MCP_SERVER_NAME], o.env);
346
- if (got.code !== 0)
347
- continue;
348
- const e = parseMcpEntry(got.stdout, MCP_SERVER_NAME);
349
- if (!isNpxEntry(e))
350
- continue;
351
- const scope = kind === 'codex' ? 'user' : /^\s*Scope:\s*Local/im.test(got.stdout) ? 'local' : /^\s*Scope:\s*User/im.test(got.stdout) ? 'user' : undefined;
352
- if (!scope || moved.includes(`${kind} ${scope}`))
353
- continue;
354
- const local = scope === 'local';
355
- const rm = await exec(bin, mcpRemoveArgv(kind, bin, MCP_SERVER_NAME, local).slice(1), o.env);
356
- if (rm.code !== 0) {
357
- o.log?.(`could not remove the npx \`ach\` entry of ${kind} (exit ${rm.code}): ${rm.stderr.trim().split('\n')[0] ?? ''}`);
358
- continue;
359
- }
360
- const add = await exec(bin, mcpAddArgv(kind, bin, o.achCmd, e.home, local).slice(1), o.env);
361
- if (add.code !== 0) {
362
- // the entry is gone now: put the npx one back rather than leave the tool without AgentChannel
363
- await exec(bin, mcpAddArgv(kind, bin, [e.command, ...e.args.slice(0, -1)], e.home, local).slice(1), o.env);
364
- o.log?.(`could not point the \`ach\` entry of ${kind} at ${o.achCmd.join(' ')} (exit ${add.code}): kept npx`);
365
- continue;
366
- }
367
- moved.push(`${kind} ${scope}`);
368
- }
369
- return moved;
370
- }
@@ -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`.');
@@ -19,6 +19,13 @@ export interface RunnerOptions {
19
19
  max?: number;
20
20
  perm?: Perm;
21
21
  intervalMs?: number;
22
+ /**
23
+ * Opens the hub's change stream (Client.eventsSocket). With it, an idle runner asks for its inbox when an event concerns its
24
+ * agent and every `quietMs` anyway, instead of every `intervalMs`; without it, or while the stream is down, it polls as before.
25
+ */
26
+ socket?: () => import('../attention.js').FeedSocket | null;
27
+ /** How often an idle runner asks anyway while the stream is up (work the stream did not announce: a private channel, a task another one was waiting for). */
28
+ quietMs?: number;
22
29
  /** How long to wait before trying to describe the agent again after a failure (default 5 minutes; 3 tries per start). */
23
30
  describeRetryMs?: number;
24
31
  /** The hub answered 426 client_too_old: this release is below its floor (the updater checks at once). */
@@ -173,6 +180,9 @@ export declare class Runner {
173
180
  /** B7: set when the hub answered 401 (key rotated, agent or owner deactivated): the runner stops. */
174
181
  fatal?: 'unauthorized';
175
182
  private wake?;
183
+ /** The hub's change stream, when the runner follows it, and whether it said something since the last poll. */
184
+ private feed?;
185
+ private nudged;
176
186
  /** decisions §27: the last sandbox probe, when it ran, and what the hub was last told (a JSON key). */
177
187
  sandbox?: {
178
188
  st: SandboxStatus;
@@ -18,6 +18,7 @@ import { unlinkWindowsSandbox } from '../codexhome.js';
18
18
  import { effectivePerm } from '../perm.js';
19
19
  import { ANSWER_SCHEMA, MENTION_SCHEMA, buildAnswerPrompt, buildMentionPrompt, buildPreparePrompt, buildResumePrompt, buildTaskPrompt, postUrl, refOf, REMOTE_FAILED_PREFIX, taskUrl } from '../prompts.js';
20
20
  import { RunnerState } from './state.js';
21
+ import { ChangeFeed, wakesRunner } from '../attention.js';
21
22
  import { isGitRepo } from './workspace.js';
22
23
  import { accountProblem, effortRejected, looksLikeLoginError, modelRejected, programMissing, summarizeRuntimeError } from '../envcheck.js';
23
24
  import { redact } from '../redact.js';
@@ -196,6 +197,9 @@ export class Runner {
196
197
  /** B7: set when the hub answered 401 (key rotated, agent or owner deactivated): the runner stops. */
197
198
  fatal;
198
199
  wake;
200
+ /** The hub's change stream, when the runner follows it, and whether it said something since the last poll. */
201
+ feed;
202
+ nudged = false;
199
203
  /** decisions §27: the last sandbox probe, when it ran, and what the hub was last told (a JSON key). */
200
204
  sandbox;
201
205
  setupReported;
@@ -1038,6 +1042,7 @@ export class Runner {
1038
1042
  judgment: claim.judgment,
1039
1043
  remote: !!this.cloud,
1040
1044
  report: !this.o.adapter.spec.ach,
1045
+ achTool: this.o.adapter.spec.achBy === 'tool',
1041
1046
  ...this.runContext(workdir),
1042
1047
  });
1043
1048
  this.reportPromptSize(taskId, rec.runId, prompt);
@@ -1123,6 +1128,7 @@ export class Runner {
1123
1128
  nudge,
1124
1129
  remote: !!this.cloud,
1125
1130
  report: !this.o.adapter.spec.ach,
1131
+ achTool: this.o.adapter.spec.achBy === 'tool',
1126
1132
  })
1127
1133
  : buildTaskPrompt({
1128
1134
  agentName: me.name,
@@ -1141,6 +1147,7 @@ export class Runner {
1141
1147
  judgment: bundle.judgment,
1142
1148
  remote: !!this.cloud,
1143
1149
  report: !this.o.adapter.spec.ach,
1150
+ achTool: this.o.adapter.spec.achBy === 'tool',
1144
1151
  ...this.runContext(rec.workdir),
1145
1152
  });
1146
1153
  if (!resume)
@@ -1869,6 +1876,21 @@ export class Runner {
1869
1876
  async start() {
1870
1877
  this.recover();
1871
1878
  this.pump();
1879
+ if (this.o.socket) {
1880
+ // its own polling is only for finding the stream again; what it reports is a nudge to the loop below
1881
+ this.feed = new ChangeFeed({
1882
+ socket: this.o.socket,
1883
+ relevant: (ev) => wakesRunner(ev, this.me?.id),
1884
+ onChange: () => {
1885
+ this.nudged = true;
1886
+ this.wake?.();
1887
+ },
1888
+ pollMs: 60_000,
1889
+ wsRetryPolls: 5,
1890
+ log: (s) => this.log(s),
1891
+ });
1892
+ void this.feed.run();
1893
+ }
1872
1894
  while (!this.stopped) {
1873
1895
  let wait = this.o.intervalMs;
1874
1896
  try {
@@ -1894,6 +1916,12 @@ export class Runner {
1894
1916
  }
1895
1917
  if (this.stopped)
1896
1918
  break;
1919
+ // nothing in hand and the stream is up: the hub says when there is something (asked at once, a second apart at most),
1920
+ // and the runner asks anyway every quietMs. With a run going, parked or queued, or without the stream: as ever.
1921
+ const idle = this.active.size === 0 && this.queue.length === 0 && Object.keys(this.state.runs.runs).length === 0;
1922
+ if (this.feed?.mode === 'ws' && idle && wait === this.o.intervalMs)
1923
+ wait = this.nudged ? Math.min(1000, wait) : (this.o.quietMs ?? 20_000);
1924
+ this.nudged = false;
1897
1925
  await new Promise((r) => {
1898
1926
  const t = setTimeout(r, wait);
1899
1927
  this.wake = () => {
@@ -1911,6 +1939,7 @@ export class Runner {
1911
1939
  /** Stop polling; abort running jobs without failing their tasks (they resume on restart). */
1912
1940
  async stop() {
1913
1941
  this.stopped = true;
1942
+ this.feed?.stop();
1914
1943
  this.wake?.(); // start() is asleep between polls: let it end now (a slow poll after a 426 would hold the exit)
1915
1944
  for (const a of this.active.values()) {
1916
1945
  a.reason = a.reason ?? 'stop';
@@ -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
+ }
@@ -29,12 +29,29 @@ export interface Migration {
29
29
  start: string[];
30
30
  }
31
31
  /**
32
- * This agent's own service, when it starts through the npx cache (`npx -y <spec>`, or node on a file in the cache): rewritten to start
33
- * `command`, the install in the AgentChannel home. Null when there is none, or it is already fine. Writing only; the caller decides when
34
- * to reload (that ends this very process).
32
+ * This agent's own service: in its home, named after the agent or one of its former names (a renamed agent keeps the service file of
33
+ * its old name: `agentchannel-runner-spark-bot` runs `bot-spark`), else the one in its home that runs in `runDir`.
34
+ */
35
+ export declare function ownService(o: {
36
+ agentName: string;
37
+ formerNames?: string[];
38
+ runDir?: string;
39
+ platform: ServiceSpec['platform'];
40
+ dir?: string;
41
+ env: NodeJS.ProcessEnv;
42
+ home: string;
43
+ }): FoundService | undefined;
44
+ /** Does this service start through the npx cache (`npx -y <spec>`, or node on a cached file)? */
45
+ export declare const startsThroughNpx: (s: FoundService) => boolean;
46
+ /**
47
+ * This agent's own service (ownService), when it starts through the npx cache: rewritten to start `command`, the install in the
48
+ * AgentChannel home. Null when there is none, or it is already fine. Writing only; the caller decides when to reload (that ends this
49
+ * very process).
35
50
  */
36
51
  export declare function migrateOldService(o: {
37
52
  agentName: string;
53
+ formerNames?: string[];
54
+ runDir?: string;
38
55
  platform: ServiceSpec['platform'];
39
56
  dir?: string;
40
57
  env: NodeJS.ProcessEnv;
@@ -60,15 +60,33 @@ export function startedByService(agentName, platform, env) {
60
60
  return false;
61
61
  }
62
62
  /**
63
- * This agent's own service, when it starts through the npx cache (`npx -y <spec>`, or node on a file in the cache): rewritten to start
64
- * `command`, the install in the AgentChannel home. Null when there is none, or it is already fine. Writing only; the caller decides when
65
- * to reload (that ends this very process).
63
+ * This agent's own service: in its home, named after the agent or one of its former names (a renamed agent keeps the service file of
64
+ * its old name: `agentchannel-runner-spark-bot` runs `bot-spark`), else the one in its home that runs in `runDir`.
65
+ */
66
+ export function ownService(o) {
67
+ const inHome = listServices(o.platform, o.dir, o.env).filter((s) => homeOfService(s, o.env) === o.home);
68
+ const names = [o.agentName, ...(o.formerNames ?? [])].map(labelName);
69
+ for (const n of names) {
70
+ const s = inHome.find((x) => x.agentName === n);
71
+ if (s)
72
+ return s;
73
+ }
74
+ const dirOf = (s) => s.args[s.args.indexOf('--dir') + 1];
75
+ const byDir = o.runDir ? inHome.filter((s) => s.args.includes('--dir') && dirOf(s) === o.runDir) : [];
76
+ return byDir.length === 1 ? byDir[0] : undefined;
77
+ }
78
+ /** Does this service start through the npx cache (`npx -y <spec>`, or node on a cached file)? */
79
+ export const startsThroughNpx = (s) => s.format === 'npx' || s.format === 'node-cache';
80
+ /**
81
+ * This agent's own service (ownService), when it starts through the npx cache: rewritten to start `command`, the install in the
82
+ * AgentChannel home. Null when there is none, or it is already fine. Writing only; the caller decides when to reload (that ends this
83
+ * very process).
66
84
  */
67
85
  export function migrateOldService(o) {
68
- const name = o.agentName.replace(/[^A-Za-z0-9-]/g, '-');
69
- const own = listServices(o.platform, o.dir, o.env).find((s) => s.agentName === name && homeOfService(s, o.env) === o.home);
70
- if (!own || (own.format !== 'npx' && own.format !== 'node-cache'))
86
+ const own = ownService(o);
87
+ if (!own || !startsThroughNpx(own))
71
88
  return null;
89
+ // specOf keeps the name the file has (a renamed agent's file keeps its old name), so it is written at its own path
72
90
  const f = serviceFile(specOf(own, o.platform, o.command), o.dir, o.env);
73
91
  writeServiceFile(f);
74
92
  return { path: f.path, start: f.start };
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.55.1";
1
+ export declare const VERSION = "3.57.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.1';
1
+ export const VERSION = '3.57.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.1",
3
+ "version": "3.57.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",