@harness-sdk/harnessd 0.0.1 → 0.0.2

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.
Files changed (66) hide show
  1. package/README.md +14 -13
  2. package/dist/accounts.d.ts +66 -0
  3. package/dist/accounts.d.ts.map +1 -0
  4. package/dist/accounts.js +166 -0
  5. package/dist/accounts.js.map +1 -0
  6. package/dist/bin.js +4 -0
  7. package/dist/bin.js.map +1 -1
  8. package/dist/channel.js +1 -1
  9. package/dist/claude.d.ts +12 -13
  10. package/dist/claude.d.ts.map +1 -1
  11. package/dist/claude.js +45 -59
  12. package/dist/claude.js.map +1 -1
  13. package/dist/cli.d.ts +5 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +269 -114
  16. package/dist/cli.js.map +1 -1
  17. package/dist/config.d.ts +14 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +53 -13
  20. package/dist/config.js.map +1 -1
  21. package/dist/daemon.d.ts +17 -4
  22. package/dist/daemon.d.ts.map +1 -1
  23. package/dist/daemon.js +112 -51
  24. package/dist/daemon.js.map +1 -1
  25. package/dist/launchd.d.ts +12 -16
  26. package/dist/launchd.d.ts.map +1 -1
  27. package/dist/launchd.js +28 -25
  28. package/dist/launchd.js.map +1 -1
  29. package/dist/prompts.d.ts +53 -0
  30. package/dist/prompts.d.ts.map +1 -0
  31. package/dist/prompts.js +171 -0
  32. package/dist/prompts.js.map +1 -0
  33. package/dist/service.d.ts +37 -0
  34. package/dist/service.d.ts.map +1 -0
  35. package/dist/service.js +71 -0
  36. package/dist/service.js.map +1 -0
  37. package/dist/setup.d.ts +37 -0
  38. package/dist/setup.d.ts.map +1 -0
  39. package/dist/setup.js +121 -0
  40. package/dist/setup.js.map +1 -0
  41. package/dist/system.d.ts +6 -0
  42. package/dist/system.d.ts.map +1 -0
  43. package/dist/system.js +16 -0
  44. package/dist/system.js.map +1 -0
  45. package/dist/systemd.d.ts +14 -0
  46. package/dist/systemd.d.ts.map +1 -0
  47. package/dist/systemd.js +62 -0
  48. package/dist/systemd.js.map +1 -0
  49. package/dist/watchdog.d.ts +14 -4
  50. package/dist/watchdog.d.ts.map +1 -1
  51. package/dist/watchdog.js +30 -24
  52. package/dist/watchdog.js.map +1 -1
  53. package/package.json +5 -3
  54. package/src/accounts.ts +242 -0
  55. package/src/bin.ts +6 -0
  56. package/src/claude.ts +65 -90
  57. package/src/cli.ts +413 -152
  58. package/src/config.ts +92 -14
  59. package/src/daemon.ts +131 -64
  60. package/src/launchd.ts +40 -35
  61. package/src/prompts.ts +255 -0
  62. package/src/service.ts +145 -0
  63. package/src/setup.ts +188 -0
  64. package/src/system.ts +11 -0
  65. package/src/systemd.ts +78 -0
  66. package/src/watchdog.ts +41 -33
@@ -0,0 +1 @@
1
+ {"version":3,"file":"systemd.js","names":[],"sources":["../src/systemd.ts"],"sourcesContent":["import { existsSync, mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type { Service } from \"./service\";\nimport { system } from \"./system\";\n\n// systemd reads `%` as a specifier everywhere, and `$` as a variable in a command line\nconst quoted = (value: string) =>\n `\"${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"').replace(/%/g, \"%%\")}\"`;\n\nconst plain = (path: string) => path.replace(/%/g, \"%%\");\n\n/** The unit's line that names harnessd's state folder: what tells one harnessd's unit from another's. */\nexport const unitFolder = (home: string) => `WorkingDirectory=${plain(home)}`;\n\n/** The unit's name: `harnessd.service`, or `harnessd-<id>.service` for a state folder of its own. */\nexport const unitName = (label: string) =>\n `${label.replace(/^dev\\./, \"\").replace(/\\./g, \"-\")}.service`;\n\n/** A user unit in the user's own folder, or for a boot service a system unit. */\nexport const unitPath = (label: string, boot = false) =>\n boot\n ? `/etc/systemd/system/${unitName(label)}`\n : join(homedir(), \".config\", \"systemd\", \"user\", unitName(label));\n\n/** The systemd unit: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */\nexport const unitOf = (o: Service.Spec) => `[Unit]\nDescription=harnessd keeps Claude Code running\nStartLimitIntervalSec=0\n${o.user === undefined ? \"\" : \"After=network-online.target\\nWants=network-online.target\\n\"}\n[Service]\n${o.user === undefined ? \"\" : `User=${o.user}\\n`}ExecStart=${[o.node, o.bin, \"run\"].map((arg) => quoted(arg).replace(/\\$/g, \"$$$$\")).join(\" \")}\n${unitFolder(o.paths.home)}\n${Object.entries(o.env)\n .map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`)\n .join(\"\\n\")}\nRestart=always\nRestartSec=5\nKillMode=mixed\nTimeoutStopSec=30\nStandardOutput=append:${plain(o.paths.serviceLog)}\nStandardError=append:${plain(o.paths.serviceLog)}\n\n[Install]\nWantedBy=${o.user === undefined ? \"default.target\" : \"multi-user.target\"}\n`;\n\nconst systemctl = (boot: boolean, ...args: string[]) => {\n const result = system(\"systemctl\", [...(boot ? [] : [\"--user\"]), ...args]);\n if (result.status === 0) return;\n const said = (result.stderr || result.stdout || String(result.error)).trim();\n throw new Error(\n /connect to bus|No medium found/.test(said)\n ? `systemd has no session for this user (${said}). Sign in at the machine or over SSH, not through su or sudo -u, and run it again.`\n : `systemctl ${args.join(\" \")} failed: ${said}`,\n );\n};\n\n/** Writes the unit, enables it and (re)starts it, which starts harnessd. */\nexport const enable = (label: string, unit: string, boot: boolean) => {\n // before the unit is written: without systemd to reach, no file is left behind\n systemctl(boot, \"show-environment\");\n mkdirSync(dirname(unitPath(label, boot)), { recursive: true });\n writeFileSync(unitPath(label, boot), unit, { mode: 0o644 });\n systemctl(boot, \"daemon-reload\");\n systemctl(boot, \"enable\", unitName(label));\n systemctl(boot, \"restart\", unitName(label));\n};\n\n/** Stops harnessd (it stops Claude Code first) and removes the unit. */\nexport const disable = (label: string, boot: boolean) => {\n const had = existsSync(unitPath(label, boot));\n if (!had) return false;\n systemctl(boot, \"disable\", \"--now\", unitName(label));\n rmSync(unitPath(label, boot),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;CACzE,IAAI,OAAO,WAAW,GAAG;CACzB,MAAM,QAAQ,OAAO,UAAU,OAAO,UAAU,OAAO,OAAO,KAAK,EAAA,CAAG,KAAK;CAC3E,MAAM,IAAI,MACR,iCAAiC,KAAK,IAAI,IACtC,yCAAyC,KAAK,uFAC9C,aAAa,KAAK,KAAK,GAAG,EAAE,WAAW,MAC7C;AACF;;AAGA,MAAa,UAAU,OAAe,MAAc,SAAkB;CAEpE,UAAU,MAAM,kBAAkB;CAClC,UAAU,QAAQ,SAAS,OAAO,IAAI,CAAC,GAAG,EAAE,WAAW,KAAK,CAAC;CAC7D,cAAc,SAAS,OAAO,IAAI,GAAG,MAAM,EAAE,MAAM,IAAM,CAAC;CAC1D,UAAU,MAAM,eAAe;CAC/B,UAAU,MAAM,UAAU,SAAS,KAAK,CAAC;CACzC,UAAU,MAAM,WAAW,SAAS,KAAK,CAAC;AAC5C;;AAGA,MAAa,WAAW,OAAe,SAAkB;CAEvD,IAAI,CADQ,WAAW,SAAS,OAAO,IAAI,CACpC,GAAG,OAAO;CACjB,UAAU,MAAM,WAAW,SAAS,SAAS,KAAK,CAAC;CACnD,OAAO,SAAS,OAAO,IAAI,GAAG,EAAE,OAAO,KAAK,CAAC;CAC7C,UAAU,MAAM,eAAe;CAC/B,OAAO;AACT"}
@@ -1,16 +1,18 @@
1
1
  export declare namespace Watchdog {
2
2
  /** What harnessd keeps across its own restarts. */
3
3
  type State = {
4
- /** The conversation the next start resumes. */
4
+ /** The conversation Claude Code is in, and the next start resumes. */
5
5
  readonly sessionId?: string;
6
6
  /** Stopped with `harnessd stop`: nothing starts until `harnessd start`. */
7
7
  readonly stopped?: boolean;
8
+ /** The account Claude Code last ran on, of the config's accounts. */
9
+ readonly account?: string;
8
10
  };
9
11
  /** One start of Claude Code: a new conversation with this id, or a resume of it. */
10
12
  type Start = {
11
13
  readonly sessionId: string;
12
14
  readonly resume: boolean;
13
- /** The first message: the one `harnessd new` gave, or why a resumed conversation restarted. */
15
+ /** The first message of a resumed conversation: why it restarted. */
14
16
  readonly prompt?: string;
15
17
  };
16
18
  type Run = {
@@ -18,6 +20,8 @@ export declare namespace Watchdog {
18
20
  /** Resolves with the exit code (128 + signal for a signal). */
19
21
  readonly exited: Promise<number>;
20
22
  readonly kill: (signal: NodeJS.Signals) => void;
23
+ /** After the exit: why it ended, when the launcher knows and the next start can go on in the same conversation at once. */
24
+ readonly ended?: () => string | undefined;
21
25
  };
22
26
  type Timing = {
23
27
  readonly minBackoffMs: number;
@@ -30,6 +34,8 @@ export declare namespace Watchdog {
30
34
  readonly runningAfterMs: number;
31
35
  /** How long a stop waits after SIGTERM before SIGKILL. */
32
36
  readonly killAfterMs: number;
37
+ /** How long start and a restart wait for Claude Code to start: longer than a prestart command may take (60 s). */
38
+ readonly spawnWaitMs: number;
33
39
  };
34
40
  type Options = {
35
41
  /** Starts Claude Code; a throw (a failed prestart command, say) is a failed start that keeps the conversation. */
@@ -63,11 +69,15 @@ export declare namespace Watchdog {
63
69
  readonly status: () => Status;
64
70
  readonly stop: () => Promise<string>;
65
71
  readonly start: () => Promise<string>;
66
- /** Starts a new conversation, with `message` as its first message. */
67
- readonly fresh: (message?: string) => Promise<string>;
72
+ /** Claude Code moved to this conversation (a /clear, a /resume): later starts resume it. */
73
+ readonly follow: (sessionId: string) => void;
74
+ /** Stops the Claude Code that runs and starts it again at once, in the same conversation, which is told `reason`. With `pid`, only while that start still runs. */
75
+ readonly restart: (reason: string, pid?: number) => Promise<string>;
68
76
  /** Stops Claude Code and ends `run`, keeping the conversation for the next harnessd. */
69
77
  readonly shutdown: () => Promise<void>;
70
78
  };
71
79
  }
80
+ /** What start and a restart answer when Claude Code didn't start. */
81
+ export declare const NOT_STARTED = "Claude Code didn't start in time; harnessd status shows the log.";
72
82
  export declare const watchdog: (options: Watchdog.Options) => Watchdog.Watchdog;
73
83
  //# sourceMappingURL=watchdog.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"watchdog.d.ts","sourceRoot":"","sources":["../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
8
  runningAfterMs: 3e3,
9
- killAfterMs: 1e4
9
+ killAfterMs: 1e4,
10
+ spawnWaitMs: 75e3
10
11
  };
11
- const SPAWN_WAIT_MS = 3e4;
12
+ /** What start and a restart answer when Claude Code didn't start. */
13
+ const NOT_STARTED = "Claude Code didn't start in time; harnessd status shows the log.";
12
14
  const watchdog = (options) => {
13
15
  const timing = {
14
16
  ...DEFAULT_TIMING,
@@ -26,7 +28,6 @@ const watchdog = (options) => {
26
28
  let shuttingDown = false;
27
29
  let restartNow = false;
28
30
  let fresh = false;
29
- let firstMessage;
30
31
  let reason = "harnessd started (a login, a reboot or an update)";
31
32
  let wakeUp = () => {};
32
33
  let finished;
@@ -54,7 +55,7 @@ const watchdog = (options) => {
54
55
  const timer = setTimeout(() => {
55
56
  spawnWaiters.delete(done);
56
57
  resolve(false);
57
- }, timing.killAfterMs + SPAWN_WAIT_MS);
58
+ }, timing.killAfterMs + timing.spawnWaitMs);
58
59
  spawnWaiters.add(done);
59
60
  });
60
61
  const kill = async (run) => {
@@ -76,8 +77,7 @@ const watchdog = (options) => {
76
77
  };
77
78
  return {
78
79
  sessionId: newId(),
79
- resume: false,
80
- ...firstMessage !== void 0 && { prompt: firstMessage }
80
+ resume: false
81
81
  };
82
82
  };
83
83
  const loop = async () => {
@@ -116,10 +116,7 @@ const watchdog = (options) => {
116
116
  reason = "the start before this one failed";
117
117
  }
118
118
  if (run) {
119
- if (!start.resume) {
120
- fresh = false;
121
- firstMessage = void 0;
122
- }
119
+ if (!start.resume) fresh = false;
123
120
  const spawnedAt = now();
124
121
  set({ pid: run.pid });
125
122
  for (const waiter of spawnWaiters) waiter();
@@ -144,6 +141,12 @@ const watchdog = (options) => {
144
141
  continue;
145
142
  }
146
143
  if (options.state.read().stopped) continue;
144
+ const ended = run.ended?.();
145
+ if (ended !== void 0) {
146
+ reason = ended;
147
+ backoff = timing.minBackoffMs;
148
+ continue;
149
+ }
147
150
  if (start.resume && ran < timing.resumeFailedMs) {
148
151
  fresh = true;
149
152
  reason = `resuming conversation ${start.sessionId} failed (exit code ${code})`;
@@ -196,24 +199,27 @@ const watchdog = (options) => {
196
199
  reason = "started with harnessd start";
197
200
  const spawned = nextSpawn();
198
201
  wakeUp();
199
- return await spawned ? "Started Claude Code." : "Claude Code didn't start in time; see harnessd logs.";
202
+ return await spawned ? "Started Claude Code." : NOT_STARTED;
200
203
  }),
201
- fresh: (message) => serial(async () => {
202
- await launching;
204
+ follow: (sessionId) => {
205
+ if (sessionId === options.state.read().sessionId) return;
203
206
  options.state.write({
204
207
  ...options.state.read(),
205
- stopped: false
208
+ sessionId
206
209
  });
207
- fresh = true;
208
- firstMessage = message;
209
- reason = "a new conversation was asked for";
210
- const spawned = nextSpawn();
210
+ set({ sessionId });
211
+ options.log(`Claude Code moved to conversation ${sessionId}`);
212
+ },
213
+ restart: (why, pid) => serial(async () => {
214
+ await launching;
211
215
  const run = current;
212
- if (run) {
213
- restartNow = true;
214
- await kill(run);
215
- } else wakeUp();
216
- return await spawned ? `Started a new conversation (${status.sessionId}).` : "Claude Code didn't start in time; see harnessd logs.";
216
+ if (!run) return "Claude Code isn't running.";
217
+ if (pid !== void 0 && run.pid !== pid) return "That start of Claude Code is over.";
218
+ reason = why;
219
+ const spawned = nextSpawn();
220
+ restartNow = true;
221
+ await kill(run);
222
+ return await spawned ? "Restarted Claude Code." : NOT_STARTED;
217
223
  }),
218
224
  shutdown: async () => {
219
225
  shuttingDown = true;
@@ -225,6 +231,6 @@ const watchdog = (options) => {
225
231
  }
226
232
  };
227
233
  };
228
- export { watchdog };
234
+ export { NOT_STARTED, watchdog };
229
235
 
230
236
  //# sourceMappingURL=watchdog.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"watchdog.js","names":[],"sources":["../src/watchdog.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nexport namespace Watchdog {\n /** What harnessd keeps across its own restarts. */\n export type State = {\n /** The conversation the next start resumes. */\n readonly sessionId?: string;\n /** Stopped with `harnessd stop`: nothing starts until `harnessd start`. */\n readonly stopped?: boolean;\n };\n\n /** One start of Claude Code: a new conversation with this id, or a resume of it. */\n export type Start = {\n readonly sessionId: string;\n readonly resume: boolean;\n /** The first message: the one `harnessd new` gave, or why a resumed conversation restarted. */\n readonly prompt?: string;\n };\n\n export type Run = {\n readonly pid?: number;\n /** Resolves with the exit code (128 + signal for a signal). */\n readonly exited: Promise<number>;\n readonly kill: (signal: NodeJS.Signals) => void;\n };\n\n export type Timing = {\n readonly minBackoffMs: number;\n readonly maxBackoffMs: number;\n /** A run this long resets the backoff. */\n readonly healthyMs: number;\n /** A resumed run that exits sooner failed to resume: the next start is a new conversation. */\n readonly resumeFailedMs: number;\n /** Alive this long: running. */\n readonly runningAfterMs: number;\n /** How long a stop waits after SIGTERM before SIGKILL. */\n readonly killAfterMs: number;\n };\n\n export type Options = {\n /** Starts Claude Code; a throw (a failed prestart command, say) is a failed start that keeps the conversation. */\n readonly launch: (start: Start) => Promise<Run>;\n readonly state: { read(): State; write(state: State): void };\n /** Whether Claude Code still has this conversation's transcript. */\n readonly hasTranscript: (sessionId: string) => boolean;\n readonly log: (line: string) => void;\n readonly timing?: Partial<Timing>;\n readonly now?: () => number;\n readonly newId?: () => string;\n };\n\n export type Status = {\n readonly state: \"starting\" | \"running\" | \"waiting\" | \"stopped\";\n readonly pid?: number | undefined;\n readonly sessionId?: string | undefined;\n readonly startedAt?: string | undefined;\n readonly restarts: number;\n readonly lastExit?:\n | { readonly code: number; readonly at: string }\n | undefined;\n readonly nextStartAt?: string | undefined;\n };\n\n export type Watchdog = {\n /** Runs until `shutdown`. */\n readonly run: () => Promise<void>;\n readonly status: () => Status;\n readonly stop: () => Promise<string>;\n readonly start: () => Promise<string>;\n /** Starts a new conversation, with `message` as its first message. */\n readonly fresh: (message?: string) => Promise<string>;\n /** Stops Claude Code and ends `run`, keeping the conversation for the next harnessd. */\n readonly shutdown: () => Promise<void>;\n };\n}\n\nconst DEFAULT_TIMING: Watchdog.Timing = {\n minBackoffMs: 5_000,\n maxBackoffMs: 5 * 60_000,\n healthyMs: 10 * 60_000,\n resumeFailedMs: 30_000,\n runningAfterMs: 3_000,\n killAfterMs: 10_000,\n};\n\nconst SPAWN_WAIT_MS = 30_000;\n\nexport const watchdog = (options: Watchdog.Options): Watchdog.Watchdog => {\n const timing = { ...DEFAULT_TIMING, ...options.timing };\n const now = options.now ?? Date.now;\n const newId = options.newId ?? randomUUID;\n const iso = (ms: number) => new Date(ms).toISOString();\n\n let status: Watchdog.Status = { state: \"starting\", restarts: 0 };\n let current: Watchdog.Run | undefined;\n // a start in progress (its prestart can take a minute): commands wait for it, then act on what it started\n let launching: Promise<unknown> = Promise.resolve();\n let shuttingDown = false;\n let restartNow = false;\n let fresh = false;\n let firstMessage: string | undefined;\n let reason = \"harnessd started (a login, a reboot or an update)\";\n let wakeUp = () => {};\n let finished: Promise<void> | undefined;\n const spawnWaiters = new Set<() => void>();\n let queue: Promise<unknown> = Promise.resolve();\n\n const set = (patch: Partial<Watchdog.Status>) => {\n status = { ...status, ...patch };\n };\n const sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n const timer = setTimeout(done, ms);\n function done() {\n clearTimeout(timer);\n resolve();\n }\n wakeUp = done;\n });\n const nextSpawn = () =>\n new Promise<boolean>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n resolve(true);\n };\n const timer = setTimeout(() => {\n spawnWaiters.delete(done);\n resolve(false);\n }, timing.killAfterMs + SPAWN_WAIT_MS);\n spawnWaiters.add(done);\n });\n const kill = async (run: Watchdog.Run) => {\n run.kill(\"SIGTERM\");\n let timer: ReturnType<typeof setTimeout> | undefined;\n const exited = await Promise.race([\n run.exited.then(() => true),\n new Promise<false>(\n (resolve) =>\n (timer = setTimeout(() => resolve(false), timing.killAfterMs)),\n ),\n ]);\n clearTimeout(timer);\n if (exited) return;\n options.log(\"Claude Code didn't exit after SIGTERM; sending SIGKILL\");\n run.kill(\"SIGKILL\");\n await run.exited;\n };\n\n const next = (): Watchdog.Start => {\n const { sessionId } = options.state.read();\n if (!fresh && sessionId && options.hasTranscript(sessionId))\n return {\n sessionId,\n resume: true,\n prompt: `harnessd restarted Claude Code: ${reason}. This is the same conversation.`,\n };\n // a new conversation asked for stays asked for, with its first message, until a start of it succeeds\n return {\n sessionId: newId(),\n resume: false,\n ...(firstMessage !== undefined && { prompt: firstMessage }),\n };\n };\n\n const loop = async () => {\n let backoff = timing.minBackoffMs;\n let runs = 0;\n while (!shuttingDown) {\n if (options.state.read().stopped) {\n set({ state: \"stopped\", nextStartAt: undefined });\n await sleep(2 ** 31 - 1);\n continue;\n }\n const start = next();\n options.state.write({\n ...options.state.read(),\n sessionId: start.sessionId,\n });\n if (runs++ > 0) set({ restarts: status.restarts + 1 });\n const startedAt = now();\n set({\n state: \"starting\",\n sessionId: start.sessionId,\n startedAt: iso(startedAt),\n nextStartAt: undefined,\n });\n options.log(\n `starting Claude Code: ${start.resume ? `resuming conversation ${start.sessionId}` : `new conversation ${start.sessionId}`} (${reason})`,\n );\n let run: Watchdog.Run | undefined;\n try {\n const launch = options\n .launch(start)\n .then((started) => (current = started));\n launching = launch.catch(() => {});\n run = await launch;\n } catch (error) {\n options.log(\n `couldn't start Claude Code: ${error instanceof Error ? error.message : String(error)}`,\n );\n reason = \"the start before this one failed\";\n }\n if (run) {\n if (!start.resume) {\n fresh = false;\n firstMessage = undefined;\n }\n const spawnedAt = now();\n set({ pid: run.pid });\n for (const waiter of spawnWaiters) waiter();\n spawnWaiters.clear();\n const running = setTimeout(\n () => current === run && set({ state: \"running\" }),\n timing.runningAfterMs,\n );\n const code = await run.exited;\n clearTimeout(running);\n current = undefined;\n const ran = now() - spawnedAt;\n set({ pid: undefined, lastExit: { code, at: iso(now()) } });\n options.log(\n `Claude Code exited with code ${code} after ${Math.round(ran / 1000)}s`,\n );\n if (shuttingDown) break;\n if (restartNow) {\n restartNow = false;\n backoff = timing.minBackoffMs;\n continue;\n }\n if (options.state.read().stopped) continue;\n if (start.resume && ran < timing.resumeFailedMs) {\n fresh = true;\n reason = `resuming conversation ${start.sessionId} failed (exit code ${code})`;\n options.log(`${reason}; the next start is a new conversation`);\n } else\n reason = `it exited with code ${code} after ${Math.round(ran / 1000)}s`;\n if (ran >= timing.healthyMs) backoff = timing.minBackoffMs;\n }\n if (shuttingDown) break;\n set({ state: \"waiting\", nextStartAt: iso(now() + backoff) });\n options.log(`starting again in ${Math.round(backoff / 1000)}s`);\n await sleep(backoff);\n backoff = Math.min(backoff * 2, timing.maxBackoffMs);\n }\n set({ state: \"stopped\", nextStartAt: undefined });\n };\n\n const serial = (command: () => Promise<string>) => {\n const result = queue.catch(() => {}).then(command);\n queue = result;\n return result;\n };\n\n return {\n run: () => (finished ??= loop()),\n status: () => status,\n stop: () =>\n serial(async () => {\n await launching;\n const stopped = options.state.read().stopped;\n options.state.write({ ...options.state.read(), stopped: true });\n const run = current;\n if (run) await kill(run);\n wakeUp();\n options.log(\"stopped with harnessd stop\");\n return run\n ? \"Stopped Claude Code.\"\n : stopped\n ? \"Claude Code was already stopped.\"\n : \"Stopped (Claude Code was waiting to start).\";\n }),\n start: () =>\n serial(async () => {\n await launching;\n if (current) return \"Claude Code is already running.\";\n options.state.write({ ...options.state.read(), stopped: false });\n reason = \"started with harnessd start\";\n const spawned = nextSpawn();\n wakeUp();\n return (await spawned)\n ? \"Started Claude Code.\"\n : \"Claude Code didn't start in time; see harnessd logs.\";\n }),\n fresh: (message) =>\n serial(async () => {\n await launching;\n options.state.write({ ...options.state.read(), stopped: false });\n fresh = true;\n firstMessage = message;\n reason = \"a new conversation was asked for\";\n const spawned = nextSpawn();\n const run = current;\n if (run) {\n restartNow = true;\n await kill(run);\n } else wakeUp();\n return (await spawned)\n ? `Started a new conversation (${status.sessionId}).`\n : \"Claude Code didn't start in time; see harnessd logs.\";\n }),\n shutdown: async () => {\n shuttingDown = true;\n wakeUp();\n await launching;\n const run = current;\n if (run) await kill(run);\n await finished;\n },\n };\n};\n"],"mappings":";;AA4EA,MAAM,iBA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ACF;AACF"}
1
+ {"version":3,"file":"watchdog.js","names":[],"sources":["../src/watchdog.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\n\nexport namespace Watchdog {\n /** What harnessd keeps across its own restarts. */\n export type State = {\n /** The conversation Claude Code is in, and the next start resumes. */\n readonly sessionId?: string;\n /** Stopped with `harnessd stop`: nothing starts until `harnessd start`. */\n readonly stopped?: boolean;\n /** The account Claude Code last ran on, of the config's accounts. */\n readonly account?: string;\n };\n\n /** One start of Claude Code: a new conversation with this id, or a resume of it. */\n export type Start = {\n readonly sessionId: string;\n readonly resume: boolean;\n /** The first message of a resumed conversation: why it restarted. */\n readonly prompt?: string;\n };\n\n export type Run = {\n readonly pid?: number;\n /** Resolves with the exit code (128 + signal for a signal). */\n readonly exited: Promise<number>;\n readonly kill: (signal: NodeJS.Signals) => void;\n /** After the exit: why it ended, when the launcher knows and the next start can go on in the same conversation at once. */\n readonly ended?: () => string | undefined;\n };\n\n export type Timing = {\n readonly minBackoffMs: number;\n readonly maxBackoffMs: number;\n /** A run this long resets the backoff. */\n readonly healthyMs: number;\n /** A resumed run that exits sooner failed to resume: the next start is a new conversation. */\n readonly resumeFailedMs: number;\n /** Alive this long: running. */\n readonly runningAfterMs: number;\n /** How long a stop waits after SIGTERM before SIGKILL. */\n readonly killAfterMs: number;\n /** How long start and a restart wait for Claude Code to start: longer than a prestart command may take (60 s). */\n readonly spawnWaitMs: number;\n };\n\n export type Options = {\n /** Starts Claude Code; a throw (a failed prestart command, say) is a failed start that keeps the conversation. */\n readonly launch: (start: Start) => Promise<Run>;\n readonly state: { read(): State; write(state: State): void };\n /** Whether Claude Code still has this conversation's transcript. */\n readonly hasTranscript: (sessionId: string) => boolean;\n readonly log: (line: string) => void;\n readonly timing?: Partial<Timing>;\n readonly now?: () => number;\n readonly newId?: () => string;\n };\n\n export type Status = {\n readonly state: \"starting\" | \"running\" | \"waiting\" | \"stopped\";\n readonly pid?: number | undefined;\n readonly sessionId?: string | undefined;\n readonly startedAt?: string | undefined;\n readonly restarts: number;\n readonly lastExit?:\n | { readonly code: number; readonly at: string }\n | undefined;\n readonly nextStartAt?: string | undefined;\n };\n\n export type Watchdog = {\n /** Runs until `shutdown`. */\n readonly run: () => Promise<void>;\n readonly status: () => Status;\n readonly stop: () => Promise<string>;\n readonly start: () => Promise<string>;\n /** Claude Code moved to this conversation (a /clear, a /resume): later starts resume it. */\n readonly follow: (sessionId: string) => void;\n /** Stops the Claude Code that runs and starts it again at once, in the same conversation, which is told `reason`. With `pid`, only while that start still runs. */\n readonly restart: (reason: string, pid?: number) => Promise<string>;\n /** Stops Claude Code and ends `run`, keeping the conversation for the next harnessd. */\n readonly shutdown: () => Promise<void>;\n };\n}\n\nconst DEFAULT_TIMING: Watchdog.Timing = {\n minBackoffMs: 5_000,\n maxBackoffMs: 5 * 60_000,\n healthyMs: 10 * 60_000,\n resumeFailedMs: 30_000,\n runningAfterMs: 3_000,\n killAfterMs: 10_000,\n spawnWaitMs: 75_000,\n};\n\n/** What start and a restart answer when Claude Code didn't start. */\nexport const NOT_STARTED =\n \"Claude Code didn't start in time; harnessd status shows the log.\";\n\nexport const watchdog = (options: Watchdog.Options): Watchdog.Watchdog => {\n const timing = { ...DEFAULT_TIMING, ...options.timing };\n const now = options.now ?? Date.now;\n const newId = options.newId ?? randomUUID;\n const iso = (ms: number) => new Date(ms).toISOString();\n\n let status: Watchdog.Status = { state: \"starting\", restarts: 0 };\n let current: Watchdog.Run | undefined;\n // a start in progress (its prestart can take a minute): commands wait for it, then act on what it started\n let launching: Promise<unknown> = Promise.resolve();\n let shuttingDown = false;\n let restartNow = false;\n let fresh = false;\n let reason = \"harnessd started (a login, a reboot or an update)\";\n let wakeUp = () => {};\n let finished: Promise<void> | undefined;\n const spawnWaiters = new Set<() => void>();\n let queue: Promise<unknown> = Promise.resolve();\n\n const set = (patch: Partial<Watchdog.Status>) => {\n status = { ...status, ...patch };\n };\n const sleep = (ms: number) =>\n new Promise<void>((resolve) => {\n const timer = setTimeout(done, ms);\n function done() {\n clearTimeout(timer);\n resolve();\n }\n wakeUp = done;\n });\n const nextSpawn = () =>\n new Promise<boolean>((resolve) => {\n const done = () => {\n clearTimeout(timer);\n resolve(true);\n };\n const timer = setTimeout(() => {\n spawnWaiters.delete(done);\n resolve(false);\n }, timing.killAfterMs + timing.spawnWaitMs);\n spawnWaiters.add(done);\n });\n const kill = async (run: Watchdog.Run) => {\n run.kill(\"SIGTERM\");\n let timer: ReturnType<typeof setTimeout> | undefined;\n const exited = await Promise.race([\n run.exited.then(() => true),\n new Promise<false>(\n (resolve) =>\n (timer = setTimeout(() => resolve(false), timing.killAfterMs)),\n ),\n ]);\n clearTimeout(timer);\n if (exited) return;\n options.log(\"Claude Code didn't exit after SIGTERM; sending SIGKILL\");\n run.kill(\"SIGKILL\");\n await run.exited;\n };\n\n const next = (): Watchdog.Start => {\n const { sessionId } = options.state.read();\n if (!fresh && sessionId && options.hasTranscript(sessionId))\n return {\n sessionId,\n resume: true,\n prompt: `harnessd restarted Claude Code: ${reason}. This is the same conversation.`,\n };\n return { sessionId: newId(), resume: false };\n };\n\n const loop = async () => {\n let backoff = timing.minBackoffMs;\n let runs = 0;\n while (!shuttingDown) {\n if (options.state.read().stopped) {\n set({ state: \"stopped\", nextStartAt: undefined });\n await sleep(2 ** 31 - 1);\n continue;\n }\n const start = next();\n options.state.write({\n ...options.state.read(),\n sessionId: start.sessionId,\n });\n if (runs++ > 0) set({ restarts: status.restarts + 1 });\n const startedAt = now();\n set({\n state: \"starting\",\n sessionId: start.sessionId,\n startedAt: iso(startedAt),\n nextStartAt: undefined,\n });\n options.log(\n `starting Claude Code: ${start.resume ? `resuming conversation ${start.sessionId}` : `new conversation ${start.sessionId}`} (${reason})`,\n );\n let run: Watchdog.Run | undefined;\n try {\n const launch = options\n .launch(start)\n .then((started) => (current = started));\n launching = launch.catch(() => {});\n run = await launch;\n } catch (error) {\n options.log(\n `couldn't start Claude Code: ${error instanceof Error ? error.message : String(error)}`,\n );\n reason = \"the start before this one failed\";\n }\n if (run) {\n if (!start.resume) fresh = false;\n const spawnedAt = now();\n set({ pid: run.pid });\n for (const waiter of spawnWaiters) waiter();\n spawnWaiters.clear();\n const running = setTimeout(\n () => current === run && set({ state: \"running\" }),\n timing.runningAfterMs,\n );\n const code = await run.exited;\n clearTimeout(running);\n current = undefined;\n const ran = now() - spawnedAt;\n set({ pid: undefined, lastExit: { code, at: iso(now()) } });\n options.log(\n `Claude Code exited with code ${code} after ${Math.round(ran / 1000)}s`,\n );\n if (shuttingDown) break;\n if (restartNow) {\n restartNow = false;\n backoff = timing.minBackoffMs;\n continue;\n }\n if (options.state.read().stopped) continue;\n const ended = run.ended?.();\n if (ended !== undefined) {\n reason = ended;\n backoff = timing.minBackoffMs;\n continue;\n }\n if (start.resume && ran < timing.resumeFailedMs) {\n fresh = true;\n reason = `resuming conversation ${start.sessionId} failed (exit code ${code})`;\n options.log(`${reason}; the next start is a new conversation`);\n } else\n reason = `it exited with code ${code} after ${Math.round(ran / 1000)}s`;\n if (ran >= timing.healthyMs) backoff = timing.minBackoffMs;\n }\n if (shuttingDown) break;\n set({ state: \"waiting\", nextStartAt: iso(now() + backoff) });\n options.log(`starting again in ${Math.round(backoff / 1000)}s`);\n await sleep(backoff);\n backoff = Math.min(backoff * 2, timing.maxBackoffMs);\n }\n set({ state: \"stopped\", nextStartAt: undefined });\n };\n\n const serial = (command: () => Promise<string>) => {\n const result = queue.catch(() => {}).then(command);\n queue = result;\n return result;\n };\n\n return {\n run: () => (finished ??= loop()),\n status: () => status,\n stop: () =>\n serial(async () => {\n await launching;\n const stopped = options.state.read().stopped;\n options.state.write({ ...options.state.read(), stopped: true });\n const run = current;\n if (run) await kill(run);\n wakeUp();\n options.log(\"stopped with harnessd stop\");\n return run\n ? \"Stopped Claude Code.\"\n : stopped\n ? \"Claude Code was already stopped.\"\n : \"Stopped (Claude Code was waiting to start).\";\n }),\n start: () =>\n serial(async () => {\n await launching;\n if (current) return \"Claude Code is already running.\";\n options.state.write({ ...options.state.read(), stopped: false });\n reason = \"started with harnessd start\";\n const spawned = nextSpawn();\n wakeUp();\n return (await spawned) ? \"Started Claude Code.\" : NOT_STARTED;\n }),\n follow: (sessionId) => {\n if (sessionId === options.state.read().sessionId) return;\n options.state.write({ ...options.state.read(), sessionId });\n set({ sessionId });\n options.log(`Claude Code moved to conversation ${sessionId}`);\n },\n restart: (why, pid) =>\n serial(async () => {\n await launching;\n const run = current;\n if (!run) return \"Claude Code isn't running.\";\n if (pid !== undefined && run.pid !== pid)\n return \"That start of Claude Code is over.\";\n reason = why;\n const spawned = nextSpawn();\n restartNow = true;\n await kill(run);\n return (await spawned) ? \"Restarted Claude Code.\" : NOT_STARTED;\n }),\n shutdown: async () => {\n shuttingDown = true;\n wakeUp();\n await launching;\n const run = current;\n if (run) await kill(run);\n await finished;\n },\n };\n};\n"],"mappings":";;AAoFA,MAAM,iBAAkC;CACtC,cAAc;CACd,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,gBAAgB;CAChB,aAAa;CACb,aAAa;AACf;;AAGA,MAAa,cACX;AAEF,MAAa,YAAY,YAAiD;CACxE,MAAM,SAAS;EAAE,GAAG;EAAgB,GAAG,QAAQ;CAAO;CACtD,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,OAAO,OAAe,IAAI,KAAK,EAAE,CAAC,CAAC,YAAY;CAErD,IAAI,SAA0B;EAAE,OAAO;EAAY,UAAU;CAAE;CAC/D,IAAI;CAEJ,IAAI,YAA8B,QAAQ,QAAQ;CAClD,IAAI,eAAe;CACnB,IAAI,aAAa;CACjB,IAAI,QAAQ;CACZ,IAAI,SAAS;CACb,IAAI,eAAe,CAAC;CACpB,IAAI;CACJ,MAAM,+BAAe,IAAI,IAAgB;CACzC,IAAI,QAA0B,QAAQ,QAAQ;CAE9C,MAAM,OAAO,UAAoC;EAC/C,SAAS;GAAE,GAAG;GAAQ,GAAG;EAAM;CACjC;C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AG,QAAQ,MAAM,KAAK;IAAG,SAAS;GAAM,CAAC;GAC/D,SAAS;GACT,MAAM,UAAU,UAAU;GAC1B,OAAO;GACP,OAAQ,MAAM,UAAW,yBAAyB;EACpD,CAAC;EACH,SAAS,cAAc;GACrB,IAAI,cAAc,QAAQ,MAAM,KAAK,CAAC,CAAC,WAAW;GAClD,QAAQ,MAAM,MAAM;IAAE,GAAG,QAAQ,MAAM,KAAK;IAAG;GAAU,CAAC;GAC1D,IAAI,EAAE,UAAU,CAAC;GACjB,QAAQ,IAAI,qCAAqC,WAAW;EAC9D;EACA,UAAU,KAAK,QACb,OAAO,YAAY;GACjB,MAAM;GACN,MAAM,MAAM;GACZ,IAAI,CAAC,KAAK,OAAO;GACjB,IAAI,QAAQ,KAAA,KAAa,IAAI,QAAQ,KACnC,OAAO;GACT,SAAS;GACT,MAAM,UAAU,UAAU;GAC1B,aAAa;GACb,MAAM,KAAK,GAAG;GACd,OAAQ,MAAM,UAAW,2BAA2B;EACtD,CAAC;EACH,UAAU,YAAY;GACpB,eAAe;GACf,OAAO;GACP,MAAM;GACN,MAAM,MAAM;GACZ,IAAI,KAAK,MAAM,KAAK,GAAG;GACvB,MAAM;EACR;CACF;AACF"}
package/package.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "@harness-sdk/harnessd",
3
- "version": "0.0.1",
4
- "description": "Keeps Claude Code running on your Mac, day and night, connected to the events of your agentic apps",
3
+ "version": "0.0.2",
4
+ "description": "Keeps Claude Code running on your Mac or Linux machine, day and night, connected to the events of your agentic apps",
5
5
  "keywords": [
6
6
  "claude-code",
7
7
  "agent",
8
8
  "daemon",
9
9
  "launchd",
10
+ "systemd",
10
11
  "mcp",
11
12
  "channels"
12
13
  ],
@@ -33,7 +34,8 @@
33
34
  "test": "vitest run"
34
35
  },
35
36
  "dependencies": {
36
- "node-pty": "1.1.0",
37
+ "@xterm/headless": "6.0.0",
38
+ "@lydell/node-pty": "1.1.0",
37
39
  "toolport": "^0.2.0"
38
40
  },
39
41
  "devDependencies": {
@@ -0,0 +1,242 @@
1
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
2
+
3
+ export namespace Accounts {
4
+ /** Why Claude Code can't go on with the account it runs on. */
5
+ export type Stop = {
6
+ readonly why: "its usage limit" | "a failed sign-in";
7
+ /** When the account is worth another try (epoch ms). */
8
+ readonly until: number;
9
+ };
10
+
11
+ /** An account harnessd passes over, for now. */
12
+ export type Mark = Stop & {
13
+ /** The account's environment when it stopped: a changed one (a new token) is tried again. */
14
+ readonly env: string;
15
+ };
16
+
17
+ export type Options = {
18
+ /** The config's accounts, in its order. */
19
+ readonly accounts: () => Readonly<
20
+ Record<string, Readonly<Record<string, string>>>
21
+ >;
22
+ readonly now?: () => number;
23
+ };
24
+
25
+ export type Rotation = {
26
+ /** The account the next start runs on: `current` while it can go on, else the first that can. All stopped: `current`. */
27
+ readonly pick: (current: string | undefined) => string | undefined;
28
+ readonly mark: (name: string, stop: Stop) => void;
29
+ /** The accounts passed over now. */
30
+ readonly marks: () => Readonly<Record<string, Stop>>;
31
+ };
32
+ }
33
+
34
+ const LIMIT_MS = 5 * 60 * 60_000;
35
+ const SIGN_IN_MS = 24 * 60 * 60_000;
36
+
37
+ /** Whether a line of Claude Code's transcript says the account can't go on: a usage limit, or a sign-in the API refused. */
38
+ export const accountStop = (
39
+ entry: unknown,
40
+ now = Date.now(),
41
+ ): Accounts.Stop | undefined => {
42
+ if (typeof entry !== "object" || entry === null) return undefined;
43
+ const e = entry as {
44
+ type?: unknown;
45
+ isApiErrorMessage?: unknown;
46
+ error?: unknown;
47
+ apiErrorStatus?: unknown;
48
+ apiErrorIsTransient?: unknown;
49
+ quotaLimits?: { resetsAt?: unknown };
50
+ };
51
+ if (e.type !== "assistant" || e.isApiErrorMessage !== true) return undefined;
52
+ if (e.error === "authentication_failed")
53
+ return { why: "a failed sign-in", until: now + SIGN_IN_MS };
54
+ if (
55
+ e.error !== "rate_limit" ||
56
+ e.apiErrorStatus !== 429 ||
57
+ e.apiErrorIsTransient === true
58
+ )
59
+ return undefined;
60
+ const resetsAt = e.quotaLimits?.resetsAt;
61
+ return {
62
+ why: "its usage limit",
63
+ until:
64
+ typeof resetsAt === "number" && resetsAt * 1000 > now
65
+ ? resetsAt * 1000
66
+ : now + LIMIT_MS,
67
+ };
68
+ };
69
+
70
+ /** Which of the config's accounts Claude Code runs on, and which it passes over until they can go on again. */
71
+ export const rotation = (options: Accounts.Options): Accounts.Rotation => {
72
+ const now = options.now ?? Date.now;
73
+ const marked = new Map<string, Accounts.Mark>();
74
+ const stopped = (name: string, env: Readonly<Record<string, string>>) => {
75
+ const mark = marked.get(name);
76
+ if (!mark) return false;
77
+ if (mark.until > now() && mark.env === JSON.stringify(env)) return true;
78
+ marked.delete(name);
79
+ return false;
80
+ };
81
+ const open = () =>
82
+ Object.entries(options.accounts())
83
+ .filter(([name, env]) => !stopped(name, env))
84
+ .map(([name]) => name);
85
+ return {
86
+ pick: (current) => {
87
+ const accounts = options.accounts();
88
+ const names = Object.keys(accounts);
89
+ const free = open();
90
+ if (current !== undefined && free.includes(current)) return current;
91
+ return (
92
+ free[0] ??
93
+ (current !== undefined && current in accounts ? current : names[0])
94
+ );
95
+ },
96
+ mark: (name, stop) => {
97
+ const env = options.accounts()[name];
98
+ if (env) marked.set(name, { ...stop, env: JSON.stringify(env) });
99
+ },
100
+ marks: () => {
101
+ const accounts = options.accounts();
102
+ for (const name of marked.keys())
103
+ if (!(name in accounts)) marked.delete(name);
104
+ const free = new Set(open());
105
+ return Object.fromEntries(
106
+ [...marked]
107
+ .filter(([name]) => !free.has(name))
108
+ .map(([name, { why, until }]) => [name, { why, until }]),
109
+ );
110
+ },
111
+ };
112
+ };
113
+
114
+ /**
115
+ * Calls `onEntry` with each line the conversation's transcript gains from now on; `file` says where it is once Claude
116
+ * Code has written it. When Claude Code moves to another conversation, its transcript is followed from then on.
117
+ */
118
+ export const followTranscript = (o: {
119
+ sessionId: () => string;
120
+ file: (sessionId: string) => string | undefined;
121
+ onEntry: (entry: unknown) => void;
122
+ /** After each look at the transcript, whether it gained lines or not. */
123
+ onRead?: () => void;
124
+ everyMs?: number;
125
+ }) => {
126
+ let sessionId: string | undefined;
127
+ let path: string | undefined;
128
+ let offset: number | undefined;
129
+ let rest = "";
130
+ const read = () => {
131
+ if (o.sessionId() !== sessionId) {
132
+ sessionId = o.sessionId();
133
+ path = undefined;
134
+ offset = undefined;
135
+ rest = "";
136
+ }
137
+ path ??= o.file(sessionId);
138
+ if (path === undefined) {
139
+ // a transcript that appears after the start, or after a move to another conversation, is read from its first line
140
+ offset = 0;
141
+ return;
142
+ }
143
+ let fd: number;
144
+ try {
145
+ fd = openSync(path, "r");
146
+ } catch {
147
+ return;
148
+ }
149
+ try {
150
+ const { size } = fstatSync(fd);
151
+ offset ??= size;
152
+ if (size <= offset) return;
153
+ const chunk = Buffer.alloc(size - offset);
154
+ readSync(fd, chunk, 0, chunk.length, offset);
155
+ offset = size;
156
+ const lines = (rest + chunk.toString("utf8")).split("\n");
157
+ rest = lines.pop() ?? "";
158
+ for (const line of lines) {
159
+ if (!line.trim()) continue;
160
+ let entry: unknown;
161
+ try {
162
+ entry = JSON.parse(line);
163
+ } catch {
164
+ continue;
165
+ }
166
+ o.onEntry(entry);
167
+ }
168
+ } finally {
169
+ closeSync(fd);
170
+ }
171
+ };
172
+ const look = () => {
173
+ read();
174
+ o.onRead?.();
175
+ };
176
+ look();
177
+ const timer = setInterval(look, o.everyMs ?? 10_000);
178
+ return {
179
+ /** Reads what the transcript gained since the last look, then stops looking. */
180
+ finish: () => {
181
+ clearInterval(timer);
182
+ read();
183
+ },
184
+ };
185
+ };
186
+
187
+ /**
188
+ * One start of Claude Code on `account`, watched from before the start to after the exit: when the account stops and
189
+ * another can go on, Claude Code hands over to it in the same conversation.
190
+ */
191
+ export const accountRun = (o: {
192
+ account: string;
193
+ rotation: Accounts.Rotation;
194
+ /** The conversation Claude Code is in. */
195
+ sessionId: () => string;
196
+ /** Where a conversation's transcript is, once Claude Code has written it. */
197
+ file: (sessionId: string) => string | undefined;
198
+ /** Restarts the start with this pid, telling the conversation why. */
199
+ restart: (reason: string, pid: number) => void;
200
+ log: (line: string) => void;
201
+ everyMs?: number;
202
+ }) => {
203
+ let pid: number | undefined;
204
+ let handed = false;
205
+ const handover = () => {
206
+ const why = o.rotation.marks()[o.account]?.why;
207
+ const next = o.rotation.pick(o.account);
208
+ if (handed || !why || next === undefined || next === o.account)
209
+ return undefined;
210
+ handed = true;
211
+ o.log(`switching from account ${o.account} to ${next}`);
212
+ return `account ${o.account} stopped at ${why}, so Claude Code now runs on account ${next}`;
213
+ };
214
+ const follow = followTranscript({
215
+ sessionId: o.sessionId,
216
+ file: o.file,
217
+ onEntry: (entry) => {
218
+ const stop = accountStop(entry);
219
+ if (!stop) return;
220
+ if (!(o.account in o.rotation.marks()))
221
+ o.log(`account ${o.account} stopped at ${stop.why}`);
222
+ o.rotation.mark(o.account, stop);
223
+ },
224
+ // after each look: a stopped account hands over as soon as another can go on, now or once that one's limit resets
225
+ onRead: () => {
226
+ if (pid === undefined) return;
227
+ const reason = handover();
228
+ if (reason !== undefined) o.restart(reason, pid);
229
+ },
230
+ ...(o.everyMs !== undefined && { everyMs: o.everyMs }),
231
+ });
232
+ return {
233
+ /** Claude Code runs. */
234
+ started: (startedPid: number) => void (pid = startedPid),
235
+ /** Claude Code exited, or never started: reads the transcript's last lines. A reason: the next start goes on with another account, and is told this. */
236
+ exited: () => {
237
+ pid = undefined;
238
+ follow.finish();
239
+ return handover();
240
+ },
241
+ };
242
+ };
package/src/bin.ts CHANGED
@@ -7,6 +7,12 @@ console.log = console.error.bind(console);
7
7
  console.info = console.error.bind(console);
8
8
  console.debug = console.error.bind(console);
9
9
 
10
+ // a reader that closes early (harnessd status | head) ends the command quietly
11
+ process.stdout.on("error", (error: NodeJS.ErrnoException) => {
12
+ if (error.code !== "EPIPE") throw error;
13
+ process.exit(0);
14
+ });
15
+
10
16
  try {
11
17
  process.exitCode = await runHarnessd(
12
18
  process.argv.slice(2),