@koalaauto/agentchannel 3.97.2 → 3.97.4

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.
@@ -11,7 +11,7 @@ import { Client, clientFromConfig, HubError, isZh } from './client.js';
11
11
  import { achHome, defaultHome, loadConfig, readFileConfig, resolveClaimDelay, writeFileConfig } from './config.js';
12
12
  import { isPerm } from './perm.js';
13
13
  import { isRuntime, runtimePerm } from './adapters/spec.js';
14
- import { bootGuard, loadUpdateState, markHealthy, restartFromNpx, SelfUpdater, superviseSelf, UPDATE_EXIT_CODE, UPDATE_HANDOFF_EXIT_CODE, waitForWindowsUpdate } from './selfupdate.js';
14
+ import { bootGuard, loadUpdateState, markHealthy, restartFromNpx, SelfUpdater, superviseSelf, UPDATE_EXIT_CODE, waitForWindowsUpdate } from './selfupdate.js';
15
15
  import { inheritedEnv } from './env.js';
16
16
  import { clearStopped, markStopped } from './watchdog.js';
17
17
  import { parseNum, splitList, str } from './cli-shared.js';
@@ -135,7 +135,7 @@ async function runOnce(p, io) {
135
135
  const env = io.env;
136
136
  if (env.ACH_RUN_TOKEN)
137
137
  throw new UsageError('run: refusing to start a runner inside a spawned agent (ACH_RUN_TOKEN is set)');
138
- // Windows: a release being installed by the helper of the runner before this one (a Startup script restarted it in between).
138
+ // Windows: a release being installed by the helper of an older runner before this one (a Startup script restarted it in between).
139
139
  // Wait before the key is read (that loads a native module, whose file the install replaces), then start the new release.
140
140
  if (process.platform === 'win32' && (await waitForWindowsUpdate(achHome(env), { log: io.err }))) {
141
141
  return env.ACH_SUPERVISED === '1' ? UPDATE_EXIT_CODE : superviseSelf({ log: io.err });
@@ -350,10 +350,6 @@ async function runOnce(p, io) {
350
350
  unhook();
351
351
  return new KeyRefused(`ach run: the hub refuses the key: ${runner.fatalReason ?? 'unauthorized'}`);
352
352
  }
353
- if (updater.restarting && updater.installed === 'handoff') {
354
- io.err(`ach run: exiting for the update; the installer starts the runner again when it is done`);
355
- return UPDATE_HANDOFF_EXIT_CODE;
356
- }
357
353
  if (updater.restarting) {
358
354
  const byHand = process.env.ACH_SUPERVISED !== '1' && !(await import('./servicefix.js')).startedByService(me.name, process.platform, process.env);
359
355
  // started by hand through npx: npx would start the old release again, so the new one goes into the home install and runs from there
package/dist/src/mcp.js CHANGED
@@ -314,7 +314,7 @@ export function buildMcpServer(client, o = {}) {
314
314
  inputSchema: { channel: z.string(), text: z.string().describe('The post, Markdown') },
315
315
  }, async (a) => sent('post', { channel: a.channel, body: a.text }));
316
316
  server.registerTool('reply', {
317
- description: `Reply in a post's thread, as your user, exactly as you write it, at once (a reply to a reply goes to the same thread). Only when your user asked for this reply. An @agent in it wakes that agent for a read-only reply: when your user says go ahead on work that changes something, send_task it. ${LINKS_HELP}`,
317
+ description: `Reply in a post's thread, as your user, exactly as you write it, at once (a reply to a reply goes to the same thread). post_id may be a task (TASK-128): the reply goes to that task's own thread, which is where a word to a person about a task belongs (with their @name), not a new post. Only when your user asked for this reply. An @agent in it wakes that agent for a read-only reply: when your user says go ahead on work that changes something, send_task it. ${LINKS_HELP}`,
318
318
  inputSchema: { post_id: z.string(), text: z.string().describe('The reply, Markdown') },
319
319
  }, async (a) => sent('reply', { post: a.post_id, body: a.text }));
320
320
  }
@@ -1,7 +1,5 @@
1
1
  /** A restart-worthy exit: not 0 (systemd on-failure and launchd restart only a failure). */
2
2
  export declare const UPDATE_EXIT_CODE = 75;
3
- /** Windows: the runner exited so that a helper can install the release (windowsHandoff); the process tree ends, nothing restarts here. */
4
- export declare const UPDATE_HANDOFF_EXIT_CODE = 76;
5
3
  export interface HubVersions {
6
4
  latest_client?: string;
7
5
  min_client_proto?: number;
@@ -108,8 +106,6 @@ export interface SelfUpdaterOptions {
108
106
  platform?: NodeJS.Platform;
109
107
  /** The install in the AgentChannel home (default appDir()); tests point it elsewhere. */
110
108
  app?: string;
111
- /** Windows: starts the helper that installs after this runner exited (default startWindowsUpdate). */
112
- handoff?: (target: string, dir: string) => boolean;
113
109
  runner: Quiescable;
114
110
  home: string;
115
111
  env?: NodeJS.ProcessEnv;
@@ -127,8 +123,8 @@ export declare class SelfUpdater {
127
123
  private o;
128
124
  /** True once the install is done and the runner is stopping: the process should exit UPDATE_EXIT_CODE. */
129
125
  restarting: boolean;
130
- /** How the release that was just installed got here (set with `restarting`); 'handoff': a helper installs it after this exits. */
131
- installed?: InstallKind['kind'] | 'handoff';
126
+ /** How the release that was just installed got here (set with `restarting`). */
127
+ installed?: InstallKind['kind'];
132
128
  private timer?;
133
129
  private stopped;
134
130
  private lastNudge;
@@ -154,47 +150,8 @@ export declare class SelfUpdater {
154
150
  check(): Promise<CheckResult>;
155
151
  }
156
152
  /**
157
- * The helper (CommonJS, run by the same node, from the AgentChannel home: never from the package it replaces). It waits for the
158
- * runner's processes to exit, runs `npm install -g` (up to three tries), reads the version back, removes the update lock, and
159
- * starts the runner again with the same command line unless something else already did (a Startup script that restarts it
160
- * holds the runner lock by then). It writes what it did to logs/update.log. The plan holds no secrets: the environment is
161
- * inherited, not written down.
162
- */
163
- export declare const WINDOWS_UPDATER_SCRIPT = "// written by agentchannel (ach): installs a release once the runner has exited (Windows keeps a running program's files)\n'use strict';\nconst { spawn, spawnSync } = require('child_process');\nconst fs = require('fs');\nconst plan = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));\nconst log = (s) => { try { fs.appendFileSync(plan.log, new Date().toISOString() + ' [ach update] ' + s + '\\n'); } catch (e) {} };\nconst alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };\nconst sleep = (ms) => new Promise((r) => setTimeout(r, ms));\n(async () => {\n for (let i = 0; i < 240 && plan.pids.some(alive); i++) await sleep(500);\n await sleep(plan.settleMs);\n let ok = false;\n for (let attempt = 1; attempt <= 3 && !ok; attempt++) {\n const r = spawnSync(plan.npm.file, plan.npm.pre.concat(plan.args), { shell: plan.npm.shell, windowsHide: true, encoding: 'utf8', timeout: 300000 });\n let got = '';\n try { got = JSON.parse(fs.readFileSync(plan.pkgJson, 'utf8')).version; } catch (e) {}\n ok = r.status === 0 && got === plan.target;\n if (ok) log('installed ' + plan.target);\n else { log('npm install -g failed (try ' + attempt + ', exit ' + r.status + ', installed ' + (got || 'nothing') + '): ' + String(r.stderr || r.stdout || r.error || '').trim().split('\\n').slice(-3).join(' | ')); await sleep(5000); }\n }\n try { fs.unlinkSync(plan.lock); } catch (e) {}\n await sleep(plan.settleMs * 10);\n let held = 0;\n try { held = Number(String(fs.readFileSync(plan.runnerLock, 'utf8')).split('@')[0]); } catch (e) {}\n if (held && alive(held)) { log('the runner is running again (pid ' + held + ')'); return; }\n const out = fs.openSync(plan.log, 'a');\n const c = spawn(plan.relaunch.file, plan.relaunch.args, { cwd: plan.relaunch.cwd, detached: true, stdio: ['ignore', out, out], windowsHide: true });\n c.unref();\n log('started the runner again (pid ' + c.pid + ')');\n})();\n";
164
- export declare const windowsUpdateFiles: (home: string) => {
165
- script: string;
166
- plan: string;
167
- lock: string;
168
- log: string;
169
- runnerLock: string;
170
- };
171
- /**
172
- * Start the Windows install helper (WINDOWS_UPDATER_SCRIPT), detached, for `target` into the global package at `dir`. It waits for
173
- * this process (and its supervisor, ACH_SUPERVISED) to exit. The update lock holds its pid from the start, so a runner a Startup
174
- * script restarts in between waits for it (waitForWindowsUpdate) instead of taking the files again. False when it did not start.
175
- */
176
- export declare function startWindowsUpdate(o: {
177
- home: string;
178
- target: string;
179
- dir: string;
180
- log?: (s: string) => void;
181
- pids?: number[];
182
- relaunch?: {
183
- file: string;
184
- args: string[];
185
- cwd: string;
186
- };
187
- npm?: {
188
- file: string;
189
- pre: string[];
190
- shell: boolean;
191
- };
192
- settleMs?: number;
193
- spawnHelper?: (script: string, plan: string) => number | undefined;
194
- }): boolean;
195
- /**
196
- * Called first thing by `ach run` on Windows, before anything loads a native module: while an install helper is working, wait
197
- * for it (at most 15 minutes). True when it waited: this process holds the old release's code, so the caller starts the new one.
153
+ * Called first thing by `ach run` on Windows, before anything loads a native module: while the install helper of an older release
154
+ * is working (it replaces the global files this process would load), wait for it (at most 15 minutes). True when it waited: this process holds the old release's code, so the caller starts the new one.
198
155
  */
199
156
  export declare function waitForWindowsUpdate(home: string, o?: {
200
157
  log?: (s: string) => void;
@@ -9,9 +9,10 @@
9
9
  // - an MCP session (`ach mcp`, started by Claude Code or Codex): it cannot be restarted from outside, so startStaleNotice
10
10
  // pushes one line into the session saying it is behind.
11
11
  //
12
- // - Windows: a running program's files cannot be replaced (npm EBUSY on the keyring native module, and the install left half
13
- // done), so the runner starts a helper (WINDOWS_UPDATER_SCRIPT) and exits; the helper installs once the runner's processes
14
- // are gone and starts the runner again, unless a Startup script already did (that runner waits for the helper first).
12
+ // - Windows: a running program's files cannot be replaced, and a global install is held by every runner and MCP session of the
13
+ // machine at once (npm EBUSY on the keyring native module; zip's three runners stayed on 3.68 for days). So a global install
14
+ // there is never updated in place: the release goes into the install in the AgentChannel home, a dir per release that nothing
15
+ // holds, and the runner starts it through that install's launcher; later updates happen there.
15
16
  //
16
17
  // What it never does: move across a major release by itself (the protocol may have changed: a person decides), move a stable
17
18
  // install onto a prerelease, touch a CLI it cannot tell how it was installed, or retry a failed update more than once a day.
@@ -24,8 +25,6 @@ import { thisCliPath } from './invite.js';
24
25
  import { CLIENT_PROTO, newerVersion, PKG_NAME, VERSION } from './version.js';
25
26
  /** A restart-worthy exit: not 0 (systemd on-failure and launchd restart only a failure). */
26
27
  export const UPDATE_EXIT_CODE = 75;
27
- /** Windows: the runner exited so that a helper can install the release (windowsHandoff); the process tree ends, nothing restarts here. */
28
- export const UPDATE_HANDOFF_EXIT_CODE = 76;
29
28
  const DAY_MS = 24 * 3600_000;
30
29
  /** npm's answer when the version is not (yet) served where it asked: E404, ETARGET / No matching version. */
31
30
  const NOT_ON_NPM = /\bE404\b|\b404 Not Found\b|npm error 404|\bETARGET\b|No matching version found/i;
@@ -174,7 +173,7 @@ export class SelfUpdater {
174
173
  o;
175
174
  /** True once the install is done and the runner is stopping: the process should exit UPDATE_EXIT_CODE. */
176
175
  restarting = false;
177
- /** How the release that was just installed got here (set with `restarting`); 'handoff': a helper installs it after this exits. */
176
+ /** How the release that was just installed got here (set with `restarting`). */
178
177
  installed;
179
178
  timer;
180
179
  stopped = false;
@@ -278,7 +277,19 @@ export class SelfUpdater {
278
277
  this.once(`backoff:${v.target}`, `ach ${v.target} is out but the last try ${new Date(last.at).toISOString()} did not end on it; trying again after a day`);
279
278
  return 'backoff';
280
279
  }
281
- const kind = await detectInstall({ self: this.o.self, exec: this.o.exec, version, app: this.o.app });
280
+ let kind = await detectInstall({ self: this.o.self, exec: this.o.exec, version, app: this.o.app });
281
+ if ((this.o.platform ?? process.platform) === 'win32' && kind.kind === 'global') {
282
+ // the global files are held by every runner and MCP session here (EBUSY): the release goes into the home install instead
283
+ const app = this.o.app ?? appDir();
284
+ try {
285
+ mkdirSync(app, { recursive: true, mode: 0o700 });
286
+ }
287
+ catch {
288
+ /* preflight says it cannot be written */
289
+ }
290
+ this.once(`win-app:${v.target}`, `Windows: ${kind.dir} is not replaced while it runs; ${v.target} goes into ${app}`);
291
+ kind = { kind: 'app', dir: app };
292
+ }
282
293
  if (kind.kind === 'other') {
283
294
  this.once(`other:${v.target}`, `ach ${v.target} is out (this is ${version}) and cannot be installed by itself: ${kind.why}`);
284
295
  return 'manual';
@@ -294,21 +305,6 @@ export class SelfUpdater {
294
305
  await this.o.runner.quiesce();
295
306
  const before = loadUpdateState(this.o.home);
296
307
  saveUpdateState(this.o.home, { target: v.target, at: now, attempts: (last?.attempts ?? 0) + 1, previous: version });
297
- if ((this.o.platform ?? process.platform) === 'win32' && kind.kind === 'global') {
298
- // Windows will not replace files a running process holds (its native modules: npm EBUSY, and the install left half
299
- // done): a helper installs once this runner, and its supervisor, have exited, then starts it again (windowsHandoff)
300
- const started = (this.o.handoff ?? ((t, d) => startWindowsUpdate({ home: this.o.home, target: t, dir: d, log: (x) => this.log(x) })))(v.target, kind.dir);
301
- if (!started) {
302
- this.log(`update to ${v.target}: the installer could not be started; staying on ${version}`);
303
- this.o.runner.unquiesce();
304
- return 'failed';
305
- }
306
- this.log(`exiting so that ${v.target} can be installed (Windows keeps a running program's files); it starts again after`);
307
- this.restarting = true;
308
- this.installed = 'handoff';
309
- await this.o.runner.stop();
310
- return 'restarting';
311
- }
312
308
  const r = await installRelease(kind, v.target, this.o.exec);
313
309
  if (!r.ok) {
314
310
  // npm said "no such version" although its view had just named it: the release is still spreading over npm's servers
@@ -332,52 +328,9 @@ export class SelfUpdater {
332
328
  }
333
329
  }
334
330
  }
335
- // ---- Windows: install after the runner exited ----------------------------------------------------------------------------------
336
- /**
337
- * The helper (CommonJS, run by the same node, from the AgentChannel home: never from the package it replaces). It waits for the
338
- * runner's processes to exit, runs `npm install -g` (up to three tries), reads the version back, removes the update lock, and
339
- * starts the runner again with the same command line unless something else already did (a Startup script that restarts it
340
- * holds the runner lock by then). It writes what it did to logs/update.log. The plan holds no secrets: the environment is
341
- * inherited, not written down.
342
- */
343
- export const WINDOWS_UPDATER_SCRIPT = `// written by agentchannel (ach): installs a release once the runner has exited (Windows keeps a running program's files)
344
- 'use strict';
345
- const { spawn, spawnSync } = require('child_process');
346
- const fs = require('fs');
347
- const plan = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
348
- const log = (s) => { try { fs.appendFileSync(plan.log, new Date().toISOString() + ' [ach update] ' + s + '\\n'); } catch (e) {} };
349
- const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
350
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
351
- (async () => {
352
- for (let i = 0; i < 240 && plan.pids.some(alive); i++) await sleep(500);
353
- await sleep(plan.settleMs);
354
- let ok = false;
355
- for (let attempt = 1; attempt <= 3 && !ok; attempt++) {
356
- const r = spawnSync(plan.npm.file, plan.npm.pre.concat(plan.args), { shell: plan.npm.shell, windowsHide: true, encoding: 'utf8', timeout: 300000 });
357
- let got = '';
358
- try { got = JSON.parse(fs.readFileSync(plan.pkgJson, 'utf8')).version; } catch (e) {}
359
- ok = r.status === 0 && got === plan.target;
360
- if (ok) log('installed ' + plan.target);
361
- else { log('npm install -g failed (try ' + attempt + ', exit ' + r.status + ', installed ' + (got || 'nothing') + '): ' + String(r.stderr || r.stdout || r.error || '').trim().split('\\n').slice(-3).join(' | ')); await sleep(5000); }
362
- }
363
- try { fs.unlinkSync(plan.lock); } catch (e) {}
364
- await sleep(plan.settleMs * 10);
365
- let held = 0;
366
- try { held = Number(String(fs.readFileSync(plan.runnerLock, 'utf8')).split('@')[0]); } catch (e) {}
367
- if (held && alive(held)) { log('the runner is running again (pid ' + held + ')'); return; }
368
- const out = fs.openSync(plan.log, 'a');
369
- const c = spawn(plan.relaunch.file, plan.relaunch.args, { cwd: plan.relaunch.cwd, detached: true, stdio: ['ignore', out, out], windowsHide: true });
370
- c.unref();
371
- log('started the runner again (pid ' + c.pid + ')');
372
- })();
373
- `;
374
- export const windowsUpdateFiles = (home) => ({
375
- script: join(home, 'ach-update.cjs'),
376
- plan: join(home, 'update-plan.json'),
377
- lock: join(home, 'update.lock'),
378
- log: join(home, 'logs', 'update.log'),
379
- runnerLock: join(home, 'runner.lock'),
380
- });
331
+ // ---- Windows: older releases installed with a helper after their runner exited ---------------------------------------------------
332
+ /** The lock that helper held while it installed (its pid). */
333
+ const windowsUpdateLock = (home) => join(home, 'update.lock');
381
334
  const pidAlive = (pid) => {
382
335
  try {
383
336
  process.kill(pid, 0);
@@ -388,53 +341,11 @@ const pidAlive = (pid) => {
388
341
  }
389
342
  };
390
343
  /**
391
- * Start the Windows install helper (WINDOWS_UPDATER_SCRIPT), detached, for `target` into the global package at `dir`. It waits for
392
- * this process (and its supervisor, ACH_SUPERVISED) to exit. The update lock holds its pid from the start, so a runner a Startup
393
- * script restarts in between waits for it (waitForWindowsUpdate) instead of taking the files again. False when it did not start.
394
- */
395
- export function startWindowsUpdate(o) {
396
- const f = windowsUpdateFiles(o.home);
397
- try {
398
- mkdirSync(dirname(f.log), { recursive: true, mode: 0o700 });
399
- writeFileSync(f.script, WINDOWS_UPDATER_SCRIPT, { mode: 0o600 });
400
- writeFileSync(f.plan, JSON.stringify({
401
- target: o.target,
402
- pids: o.pids ?? [process.pid, ...(process.env.ACH_SUPERVISED === '1' ? [process.ppid] : [])],
403
- npm: o.npm ?? npmCommand(),
404
- args: ['install', '-g', '--ignore-scripts', '--no-audit', '--no-fund', `${PKG_NAME}@${o.target}`],
405
- pkgJson: join(o.dir, 'package.json'),
406
- lock: f.lock,
407
- log: f.log,
408
- runnerLock: f.runnerLock,
409
- settleMs: o.settleMs ?? 2000,
410
- relaunch: o.relaunch ?? { file: process.execPath, args: [...process.execArgv, ...process.argv.slice(1)], cwd: process.cwd() },
411
- }), { mode: 0o600 });
412
- const spawnHelper = o.spawnHelper ??
413
- ((script, plan) => {
414
- // the helper inherits this environment, without the supervisor mark: the runner it starts is a first one
415
- const { ACH_SUPERVISED: _, ...env } = process.env;
416
- const c = spawn(process.execPath, [script, plan], { detached: true, stdio: 'ignore', windowsHide: true, env });
417
- c.unref();
418
- return c.pid;
419
- });
420
- const pid = spawnHelper(f.script, f.plan);
421
- if (!pid)
422
- return false;
423
- writeFileSync(f.lock, String(pid), { mode: 0o600 });
424
- o.log?.(`installer started (pid ${pid}); it logs to ${f.log}`);
425
- return true;
426
- }
427
- catch (e) {
428
- o.log?.(`installer not started: ${e?.message ?? e}`);
429
- return false;
430
- }
431
- }
432
- /**
433
- * Called first thing by `ach run` on Windows, before anything loads a native module: while an install helper is working, wait
434
- * for it (at most 15 minutes). True when it waited: this process holds the old release's code, so the caller starts the new one.
344
+ * Called first thing by `ach run` on Windows, before anything loads a native module: while the install helper of an older release
345
+ * is working (it replaces the global files this process would load), wait for it (at most 15 minutes). True when it waited: this process holds the old release's code, so the caller starts the new one.
435
346
  */
436
347
  export async function waitForWindowsUpdate(home, o = {}) {
437
- const { lock } = windowsUpdateFiles(home);
348
+ const lock = windowsUpdateLock(home);
438
349
  let pid = 0;
439
350
  try {
440
351
  pid = Number(readFileSync(lock, 'utf8').trim());
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.97.2";
1
+ export declare const VERSION = "3.97.4";
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.97.2';
1
+ export const VERSION = '3.97.4';
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.97.2",
3
+ "version": "3.97.4",
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",