@koalaauto/agentchannel 3.56.0 → 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.
@@ -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/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
- }
@@ -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;
@@ -1872,6 +1876,21 @@ export class Runner {
1872
1876
  async start() {
1873
1877
  this.recover();
1874
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
+ }
1875
1894
  while (!this.stopped) {
1876
1895
  let wait = this.o.intervalMs;
1877
1896
  try {
@@ -1897,6 +1916,12 @@ export class Runner {
1897
1916
  }
1898
1917
  if (this.stopped)
1899
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;
1900
1925
  await new Promise((r) => {
1901
1926
  const t = setTimeout(r, wait);
1902
1927
  this.wake = () => {
@@ -1914,6 +1939,7 @@ export class Runner {
1914
1939
  /** Stop polling; abort running jobs without failing their tasks (they resume on restart). */
1915
1940
  async stop() {
1916
1941
  this.stopped = true;
1942
+ this.feed?.stop();
1917
1943
  this.wake?.(); // start() is asleep between polls: let it end now (a slow poll after a 426 would hold the exit)
1918
1944
  for (const a of this.active.values()) {
1919
1945
  a.reason = a.reason ?? 'stop';
@@ -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.56.0";
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.56.0';
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.56.0",
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",