@koalaauto/agentchannel 3.81.0 → 3.82.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.
@@ -13,6 +13,7 @@ import { isPerm } from './perm.js';
13
13
  import { isRuntime, runtimePerm } from './adapters/spec.js';
14
14
  import { bootGuard, markHealthy, SelfUpdater, superviseSelf, UPDATE_EXIT_CODE, UPDATE_HANDOFF_EXIT_CODE, waitForWindowsUpdate } from './selfupdate.js';
15
15
  import { inheritedEnv } from './env.js';
16
+ import { clearStopped, markStopped } from './watchdog.js';
16
17
  import { parseNum, splitList, str } from './cli-shared.js';
17
18
  import { fileURLToPath as toPath } from 'node:url';
18
19
  import { dirname as dirOf, join as joinPath } from 'node:path';
@@ -59,11 +60,14 @@ export async function runCommand(p, io) {
59
60
  io.err(r.message);
60
61
  return 1;
61
62
  }
62
- if (!(await waitForKey(io, r.message)))
63
+ if (!(await waitForKey(io, r.message))) {
64
+ markStopped(achHome(env0(io))); // stopped by a person while it waited: the watchdog leaves it stopped
63
65
  return 0;
66
+ }
64
67
  io.err('ach run: the hub accepts the key; starting again');
65
68
  }
66
69
  }
70
+ const env0 = (io) => io.env;
67
71
  /** Why runOnce stopped: no key here, or the hub refused it (401). */
68
72
  class KeyRefused {
69
73
  message;
@@ -301,6 +305,8 @@ async function runOnce(p, io) {
301
305
  updater.start();
302
306
  const shutdown = () => {
303
307
  io.err('stopping runner...');
308
+ // a person stopped it (Ctrl+C, `systemctl stop`): the watchdog of their sessions leaves it stopped (watchdog.ts)
309
+ markStopped(home);
304
310
  updater?.stop();
305
311
  desk?.stop();
306
312
  runner.stop().then(() => process.exit(0));
@@ -322,6 +328,7 @@ async function runOnce(p, io) {
322
328
  throw e;
323
329
  }
324
330
  process.once('exit', () => release()); // the shutdown path ends with process.exit, which skips the finally below
331
+ clearStopped(home); // started again: a watchdog may bring it back if it stops without being told to
325
332
  // the brake (counted only for the runner that holds the lock, not for a second `ach run` the lock turns away): a release this
326
333
  // runner updated itself to that keeps failing to start goes back to the one before
327
334
  if ((await bootGuard(home, { log: io.err })) === 'rolledback') {
package/dist/src/mcp.js CHANGED
@@ -11,6 +11,7 @@ import { isAbsolute, join, relative } from 'node:path';
11
11
  import { AttentionNotifier, ChangeFeed, codexQueue, defaultExec, fetchAttention, wakesAttention } from './attention.js';
12
12
  import { isZh } from './client.js';
13
13
  import { startStaleNotice } from './selfupdate.js';
14
+ import { startRunnerWatchdog } from './watchdog.js';
14
15
  import { decisionTo, explainToUser, unreachedLines } from './names.js';
15
16
  import { HubError, lintProblemLines } from './client.js';
16
17
  import { branchName } from './runner/workspace.js';
@@ -682,7 +683,12 @@ export async function startMcp(client, where = { cwd: process.cwd() }) {
682
683
  if (!notices)
683
684
  notices = startSessionNotices(server, client, { log: process.env.ACH_DEBUG ? (s) => process.stderr.write(`[ach mcp] ${s}\n`) : undefined });
684
685
  };
685
- server.server.onclose = () => notices?.stop();
686
+ // this machine's runner, when it stopped and should not have (watchdog.ts): started again from here
687
+ const watchdog = startRunnerWatchdog({ me: () => client.me(), log: (s) => process.stderr.write(`[ach mcp] ${s}\n`) });
688
+ server.server.onclose = () => {
689
+ notices?.stop();
690
+ watchdog.stop();
691
+ };
686
692
  await server.connect(new StdioServerTransport());
687
693
  moveOffNpxLater(where.cwd);
688
694
  }
@@ -1,4 +1,4 @@
1
- export declare const VERSION = "3.81.0";
1
+ export declare const VERSION = "3.82.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.81.0';
1
+ export const VERSION = '3.82.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
  /**
@@ -0,0 +1,56 @@
1
+ /** How the runner was started, as it told the hub (runner_report.start, 3.29+), and the flags it ran with. */
2
+ export interface RunnerStart {
3
+ dir: string;
4
+ home?: string;
5
+ repos?: Record<string, string>;
6
+ interactive_first?: boolean;
7
+ service?: string;
8
+ }
9
+ export interface WatchedAgent {
10
+ name: string;
11
+ runtime?: string;
12
+ pool?: string;
13
+ runner_at?: string;
14
+ runner?: {
15
+ perm?: string;
16
+ pass_env?: string[];
17
+ start?: RunnerStart;
18
+ } | null;
19
+ }
20
+ /** Silent for this long: the panel calls such a runner stopped (avatar.tsx runnerDown). */
21
+ export declare const DOWN_AFTER_MS: number;
22
+ /** A runner silent for longer than this was not running here lately: left alone (someone moved it, or gave it up). */
23
+ export declare const GIVEN_UP_AFTER_MS: number;
24
+ /** At most one try per home in this long, whatever the number of sessions open. */
25
+ export declare const TRY_EVERY_MS: number;
26
+ /** Written by `ach run` when a person stops it (SIGINT, SIGTERM, `systemctl stop`): the watchdog leaves it stopped. */
27
+ export declare const STOPPED_FILE = "runner-stopped";
28
+ export declare function markStopped(home: string): void;
29
+ export declare function clearStopped(home: string): void;
30
+ /** Why the runner of this home is left as it is, or null when it should be started. Pure apart from the files it reads. */
31
+ export declare function whyNotRestart(me: WatchedAgent, home: string, now: number, o?: {
32
+ lockHolder?: (home: string) => number | undefined;
33
+ env?: NodeJS.ProcessEnv;
34
+ }): string | null;
35
+ /** The `ach run` arguments that start it as it ran (web/src/lib/cli.ts restartLine, without npx: this very CLI). */
36
+ export declare function restartArgs(me: WatchedAgent): string[];
37
+ export type Starter = (args: string[], env: NodeJS.ProcessEnv, cwd: string) => Promise<{
38
+ code: number;
39
+ output: string;
40
+ }>;
41
+ /** One look: start the runner of this home when it should be running and is not. Returns what it did, for the log. */
42
+ export declare function checkRunner(o: {
43
+ me: () => Promise<WatchedAgent | null>;
44
+ env?: NodeJS.ProcessEnv;
45
+ now?: number;
46
+ start?: Starter;
47
+ lockHolder?: (home: string) => number | undefined;
48
+ }): Promise<string>;
49
+ /** Look now (a little after the session starts) and every ten minutes while the session is open. */
50
+ export declare function startRunnerWatchdog(o: Parameters<typeof checkRunner>[0] & {
51
+ firstMs?: number;
52
+ everyMs?: number;
53
+ log?: (s: string) => void;
54
+ }): {
55
+ stop(): void;
56
+ };
@@ -0,0 +1,156 @@
1
+ // The runner watchdog: an MCP session (Claude Code, Codex) brings this machine's stopped runner back by itself.
2
+ //
3
+ // 2026-11-24: the ids cutover stopped the runners of most of the team (a 401 for 3 minutes made old runners exit for good, and a
4
+ // runner that exits has nothing on its machine to start it again unless it was installed as a service that restarts it). The
5
+ // people did nothing wrong, and asking each of them to restart it by hand is the hub's mistake paid by them. What does still run
6
+ // on their machines, many times a day, is this MCP server (every Claude Code or Codex session starts it, through the install that
7
+ // follows updates). So it looks: this agent had a runner here in the last days, the hub has not heard from it for a while, no
8
+ // runner holds this home's lock, and it was not stopped on purpose. Then it runs the line the panel shows for a stopped runner
9
+ // (`ach run --install-service` with the directory, home and flags it ran with), which also leaves it installed as a service, so it
10
+ // does not stay down again.
11
+ import { spawn } from 'node:child_process';
12
+ import { existsSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
13
+ import { join } from 'node:path';
14
+ import { fileURLToPath } from 'node:url';
15
+ import { isRuntime } from './adapters/spec.js';
16
+ import { achHome, defaultHome } from './config.js';
17
+ import { runnerLockHolder } from './runner/lock.js';
18
+ /** The hub's time format ("2026-11-24 07:21:15.379Z"). */
19
+ const parseTime = (s) => Date.parse(String(s).replace(' ', 'T'));
20
+ /** Silent for this long: the panel calls such a runner stopped (avatar.tsx runnerDown). */
21
+ export const DOWN_AFTER_MS = 10 * 60_000;
22
+ /** A runner silent for longer than this was not running here lately: left alone (someone moved it, or gave it up). */
23
+ export const GIVEN_UP_AFTER_MS = 7 * 24 * 3600_000;
24
+ /** At most one try per home in this long, whatever the number of sessions open. */
25
+ export const TRY_EVERY_MS = 15 * 60_000;
26
+ /** Written by `ach run` when a person stops it (SIGINT, SIGTERM, `systemctl stop`): the watchdog leaves it stopped. */
27
+ export const STOPPED_FILE = 'runner-stopped';
28
+ const triedFile = (home) => join(home, 'watchdog-tried');
29
+ export function markStopped(home) {
30
+ try {
31
+ writeFileSync(join(home, STOPPED_FILE), new Date().toISOString() + '\n', { mode: 0o600 });
32
+ }
33
+ catch {
34
+ /* a read-only home: the watchdog may start it again, which is what it would have been anyway */
35
+ }
36
+ }
37
+ export function clearStopped(home) {
38
+ try {
39
+ unlinkSync(join(home, STOPPED_FILE));
40
+ }
41
+ catch {
42
+ /* not there */
43
+ }
44
+ }
45
+ /** Why the runner of this home is left as it is, or null when it should be started. Pure apart from the files it reads. */
46
+ export function whyNotRestart(me, home, now, o = {}) {
47
+ const env = o.env ?? process.env;
48
+ if (!isRuntime(String(me.runtime ?? '')))
49
+ return 'its runtime has no runner';
50
+ if (me.pool)
51
+ return 'a cloud workspace: the pool keeps it going';
52
+ const start = me.runner?.start;
53
+ if (!start?.dir)
54
+ return 'its runner never said how it was started';
55
+ if (!me.runner_at)
56
+ return 'it never had a runner';
57
+ const silent = now - parseTime(me.runner_at);
58
+ if (!(silent > DOWN_AFTER_MS))
59
+ return 'its runner is running';
60
+ if (silent > GIVEN_UP_AFTER_MS)
61
+ return 'its runner has not run for a week';
62
+ // this home, on this machine: the home the runner used is the one this session uses, and its directory is here
63
+ if ((start.home || defaultHome(env)) !== home)
64
+ return 'its runner used another home';
65
+ if (!existsSync(start.dir))
66
+ return 'its directory is not on this machine';
67
+ if ((o.lockHolder ?? runnerLockHolder)(home))
68
+ return 'a runner holds this home';
69
+ if (existsSync(join(home, STOPPED_FILE)))
70
+ return 'it was stopped on purpose';
71
+ try {
72
+ if (now - statSync(triedFile(home)).mtimeMs < TRY_EVERY_MS)
73
+ return 'tried a moment ago';
74
+ }
75
+ catch {
76
+ /* never tried */
77
+ }
78
+ return null;
79
+ }
80
+ /** The `ach run` arguments that start it as it ran (web/src/lib/cli.ts restartLine, without npx: this very CLI). */
81
+ export function restartArgs(me) {
82
+ const s = me.runner.start;
83
+ const a = ['run', '--install-service', '--dir', s.dir];
84
+ for (const [name, path] of Object.entries(s.repos ?? {}))
85
+ a.push('--repo', `${name}=${path}`);
86
+ const perm = me.runner?.perm;
87
+ if (perm && perm !== 'workdir')
88
+ a.push('--perm', perm);
89
+ for (const n of me.runner?.pass_env ?? [])
90
+ a.push('--pass-env', n);
91
+ if (s.interactive_first)
92
+ a.push('--interactive-first');
93
+ return a;
94
+ }
95
+ const CLI_JS = join(fileURLToPath(new URL('.', import.meta.url)), 'cli.js');
96
+ const defaultStarter = (args, env, cwd) => new Promise((resolve) => {
97
+ const c = spawn(process.execPath, [CLI_JS, ...args], { cwd, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
98
+ let output = '';
99
+ c.stdout?.on('data', (d) => (output += d));
100
+ c.stderr?.on('data', (d) => (output += d));
101
+ c.on('error', (e) => resolve({ code: -1, output: output + String(e) }));
102
+ c.on('exit', (code) => resolve({ code: code ?? -1, output }));
103
+ });
104
+ /** One look: start the runner of this home when it should be running and is not. Returns what it did, for the log. */
105
+ export async function checkRunner(o) {
106
+ const env = o.env ?? process.env;
107
+ if (env.ACH_RUNNER_WATCHDOG === '0')
108
+ return 'off';
109
+ const me = await o.me().catch(() => null);
110
+ if (!me)
111
+ return 'no agent';
112
+ const home = achHome(env);
113
+ const why = whyNotRestart(me, home, o.now ?? Date.now(), { lockHolder: o.lockHolder, env });
114
+ if (why)
115
+ return why;
116
+ try {
117
+ writeFileSync(triedFile(home), '', { mode: 0o600 });
118
+ }
119
+ catch {
120
+ return 'cannot write its home';
121
+ }
122
+ const start = me.runner.start;
123
+ const r = await (o.start ?? defaultStarter)(restartArgs(me), { ...env, ...(start.home ? { AGENTCHANNEL_HOME: start.home } : {}) }, start.dir);
124
+ const tail = r.output.trim().split('\n').slice(-3).join(' | ');
125
+ try {
126
+ writeFileSync(join(home, 'logs', 'watchdog.log'), `${new Date().toISOString()} started the runner of ${me.name} (exit ${r.code}): ${tail}\n`, { flag: 'a', mode: 0o600 });
127
+ }
128
+ catch {
129
+ /* no logs dir yet: the runner makes it */
130
+ }
131
+ return r.code === 0 ? `started the runner of ${me.name}` : `could not start the runner of ${me.name} (exit ${r.code}): ${tail}`;
132
+ }
133
+ /** Look now (a little after the session starts) and every ten minutes while the session is open. */
134
+ export function startRunnerWatchdog(o) {
135
+ let stopped = false;
136
+ let timer;
137
+ const tick = async () => {
138
+ if (stopped)
139
+ return;
140
+ const what = await checkRunner(o).catch((e) => `failed: ${e?.message ?? e}`);
141
+ if (/^(started|could not)/.test(what))
142
+ o.log?.(what);
143
+ if (!stopped)
144
+ timer = setTimeout(tick, o.everyMs ?? 10 * 60_000);
145
+ timer?.unref?.();
146
+ };
147
+ timer = setTimeout(tick, o.firstMs ?? 20_000);
148
+ timer.unref?.();
149
+ return {
150
+ stop() {
151
+ stopped = true;
152
+ if (timer)
153
+ clearTimeout(timer);
154
+ },
155
+ };
156
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koalaauto/agentchannel",
3
- "version": "3.81.0",
3
+ "version": "3.82.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",