@harness-sdk/harnessd 0.0.0 → 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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -2
  3. package/dist/accounts.d.ts +66 -0
  4. package/dist/accounts.d.ts.map +1 -0
  5. package/dist/accounts.js +166 -0
  6. package/dist/accounts.js.map +1 -0
  7. package/dist/bin.d.ts +3 -0
  8. package/dist/bin.d.ts.map +1 -0
  9. package/dist/bin.js +19 -0
  10. package/dist/bin.js.map +1 -0
  11. package/dist/channel.d.ts +56 -0
  12. package/dist/channel.d.ts.map +1 -0
  13. package/dist/channel.js +356 -0
  14. package/dist/channel.js.map +1 -0
  15. package/dist/claude.d.ts +41 -0
  16. package/dist/claude.d.ts.map +1 -0
  17. package/dist/claude.js +152 -0
  18. package/dist/claude.js.map +1 -0
  19. package/dist/cli.d.ts +13 -0
  20. package/dist/cli.d.ts.map +1 -0
  21. package/dist/cli.js +413 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/config.d.ts +56 -0
  24. package/dist/config.d.ts.map +1 -0
  25. package/dist/config.js +161 -0
  26. package/dist/config.js.map +1 -0
  27. package/dist/daemon.d.ts +37 -0
  28. package/dist/daemon.d.ts.map +1 -0
  29. package/dist/daemon.js +300 -0
  30. package/dist/daemon.js.map +1 -0
  31. package/dist/launchd.d.ts +18 -0
  32. package/dist/launchd.d.ts.map +1 -0
  33. package/dist/launchd.js +91 -0
  34. package/dist/launchd.js.map +1 -0
  35. package/dist/log.d.ts +3 -0
  36. package/dist/log.d.ts.map +1 -0
  37. package/dist/log.js +17 -0
  38. package/dist/log.js.map +1 -0
  39. package/dist/prompts.d.ts +53 -0
  40. package/dist/prompts.d.ts.map +1 -0
  41. package/dist/prompts.js +171 -0
  42. package/dist/prompts.js.map +1 -0
  43. package/dist/service.d.ts +37 -0
  44. package/dist/service.d.ts.map +1 -0
  45. package/dist/service.js +71 -0
  46. package/dist/service.js.map +1 -0
  47. package/dist/setup.d.ts +37 -0
  48. package/dist/setup.d.ts.map +1 -0
  49. package/dist/setup.js +121 -0
  50. package/dist/setup.js.map +1 -0
  51. package/dist/system.d.ts +6 -0
  52. package/dist/system.d.ts.map +1 -0
  53. package/dist/system.js +16 -0
  54. package/dist/system.js.map +1 -0
  55. package/dist/systemd.d.ts +14 -0
  56. package/dist/systemd.d.ts.map +1 -0
  57. package/dist/systemd.js +62 -0
  58. package/dist/systemd.js.map +1 -0
  59. package/dist/terminal.d.ts +11 -0
  60. package/dist/terminal.d.ts.map +1 -0
  61. package/dist/terminal.js +36 -0
  62. package/dist/terminal.js.map +1 -0
  63. package/dist/watchdog.d.ts +83 -0
  64. package/dist/watchdog.d.ts.map +1 -0
  65. package/dist/watchdog.js +236 -0
  66. package/dist/watchdog.js.map +1 -0
  67. package/package.json +55 -6
  68. package/src/accounts.ts +242 -0
  69. package/src/bin.ts +24 -0
  70. package/src/channel.ts +461 -0
  71. package/src/claude.ts +249 -0
  72. package/src/cli.ts +633 -0
  73. package/src/config.ts +281 -0
  74. package/src/daemon.ts +379 -0
  75. package/src/launchd.ts +131 -0
  76. package/src/log.ts +17 -0
  77. package/src/prompts.ts +255 -0
  78. package/src/service.ts +145 -0
  79. package/src/setup.ts +188 -0
  80. package/src/system.ts +11 -0
  81. package/src/systemd.ts +78 -0
  82. package/src/terminal.ts +33 -0
  83. package/src/watchdog.ts +318 -0
package/src/setup.ts ADDED
@@ -0,0 +1,188 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { chmodSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, join } from "node:path";
5
+ import { createInterface } from "node:readline/promises";
6
+ import { which } from "./claude";
7
+ import { readConfig, type Harnessd } from "./config";
8
+ import { asUser, type Service } from "./service";
9
+
10
+ export namespace Setup {
11
+ /** The person at `harnessd service install`; none when it runs from a script. */
12
+ export type Terminal = {
13
+ readonly confirm: (question: string) => Promise<boolean>;
14
+ readonly line: (question: string) => Promise<string>;
15
+ };
16
+ }
17
+
18
+ /** Anthropic's installer for Claude Code. */
19
+ export const INSTALLER = "curl -fsSL https://claude.ai/install.sh | bash";
20
+
21
+ export const ttyTerminal = (): Setup.Terminal | undefined => {
22
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return undefined;
23
+ const line = async (question: string) => {
24
+ const lines = createInterface({
25
+ input: process.stdin,
26
+ output: process.stdout,
27
+ });
28
+ try {
29
+ return (await lines.question(question)).trim();
30
+ } finally {
31
+ lines.close();
32
+ }
33
+ };
34
+ return {
35
+ line,
36
+ confirm: async (question) =>
37
+ /^y(es)?$/i.test(await line(`${question} [y/n] `)),
38
+ };
39
+ };
40
+
41
+ // under sudo, Claude Code's own commands run as the user the service is for
42
+ const as = (user: Service.User | undefined) =>
43
+ user && process.getuid?.() === 0 ? { uid: user.uid, gid: user.gid } : {};
44
+
45
+ /** The `claude` on the PATH or where Anthropic's installer puts it; none: installs it with `install`, or after a yes on the terminal. */
46
+ export const ensureClaude = async (o: {
47
+ terminal: Setup.Terminal | undefined;
48
+ user: Service.User | undefined;
49
+ /** `--install-claude`: runs the installer without asking. */
50
+ install?: boolean | undefined;
51
+ }) => {
52
+ const find = () => {
53
+ try {
54
+ return which(
55
+ "claude",
56
+ `${process.env.PATH ?? "/usr/bin:/bin"}${delimiter}${join(homedir(), ".local", "bin")}`,
57
+ );
58
+ } catch {
59
+ return undefined;
60
+ }
61
+ };
62
+ const found = find();
63
+ if (found) return found;
64
+ if (
65
+ !o.install &&
66
+ !(await o.terminal?.confirm(
67
+ `Claude Code isn't installed. Install it now with Anthropic's installer (${INSTALLER})?`,
68
+ ))
69
+ )
70
+ throw new Error(
71
+ `Claude Code isn't installed. Add --install-claude to install it with Anthropic's installer (${INSTALLER}), or install it yourself and run harnessd service install again.`,
72
+ );
73
+ const ran = spawnSync("/bin/bash", ["-c", INSTALLER], {
74
+ stdio: "inherit",
75
+ ...as(o.user),
76
+ });
77
+ const installed = ran.status === 0 ? find() : undefined;
78
+ if (!installed)
79
+ throw new Error(
80
+ "The installer left no claude command on the PATH or in ~/.local/bin. Install Claude Code yourself, then run harnessd service install again.",
81
+ );
82
+ return installed;
83
+ };
84
+
85
+ /**
86
+ * Checks that Claude Code is signed in the way the service can use, and offers the sign-in on the terminal: Claude
87
+ * Code's own for a login item, a `claude setup-token` token for a boot service and for Linux without a desktop.
88
+ * Without a sign-in it throws what to run; with `skip` it asks nothing and resolves to that instead. Resolves to
89
+ * nothing when Claude Code is signed in, or when a prestart command may sign it in.
90
+ */
91
+ export const ensureSignedIn = async (o: {
92
+ claude: string;
93
+ paths: Harnessd.Paths;
94
+ /** The environment the service starts harnessd with. */
95
+ env: Readonly<Record<string, string>>;
96
+ user: Service.User | undefined;
97
+ terminal: Setup.Terminal | undefined;
98
+ /** `--skip-sign-in`: the install goes on without a sign-in. */
99
+ skip?: boolean | undefined;
100
+ platform?: string;
101
+ }): Promise<string | undefined> => {
102
+ const platform = o.platform ?? process.platform;
103
+ const { accounts, prestart } = readConfig(o.paths);
104
+ // a prestart command may fetch the sign-in at each start: what it prints then isn't known now
105
+ if (prestart !== undefined) return undefined;
106
+ const [account] = Object.keys(accounts);
107
+ const env = () => {
108
+ const config = readConfig(o.paths);
109
+ return {
110
+ HOME: homedir(),
111
+ ...o.env,
112
+ ...config.env,
113
+ ...(account !== undefined && config.accounts[account]!.env),
114
+ };
115
+ };
116
+ const signedIn = () => {
117
+ const status = spawnSync(o.claude, ["auth", "status", "--json"], {
118
+ encoding: "utf8",
119
+ env: env(),
120
+ timeout: 30_000,
121
+ ...as(o.user),
122
+ });
123
+ let auth: { loggedIn?: boolean; authMethod?: string } = {};
124
+ try {
125
+ auth = JSON.parse(status.stdout);
126
+ } catch {}
127
+ // a Mac's boot service starts outside any login, where the keychain's sign-in can't be read
128
+ const keychainOnly =
129
+ o.user !== undefined &&
130
+ platform === "darwin" &&
131
+ auth.authMethod === "claude.ai";
132
+ return auth.loggedIn === true && !keychainOnly;
133
+ };
134
+ if (signedIn()) return undefined;
135
+
136
+ const token =
137
+ o.user !== undefined ||
138
+ (platform === "linux" &&
139
+ !process.env.DISPLAY &&
140
+ !process.env.WAYLAND_DISPLAY);
141
+ const again = "then run harnessd service install again";
142
+ const how =
143
+ account !== undefined
144
+ ? `Claude Code isn't signed in on account ${account}: set its env in ${o.paths.config}, ${again}.`
145
+ : token
146
+ ? `Claude Code isn't signed in. Run claude setup-token, put its token in ${o.paths.config} as "env": { "CLAUDE_CODE_OAUTH_TOKEN": "<token>" }, ${again}.`
147
+ : `Claude Code isn't signed in. Run claude auth login, ${again}.`;
148
+ // once the service runs, Claude Code's own sign-in screen is another way
149
+ if (o.skip)
150
+ return account === undefined && !token
151
+ ? `${how.slice(0, -1)}; or sign in inside harnessd attach.`
152
+ : how;
153
+ const stop = new Error(
154
+ `${how}\nTo install without a sign-in, add --skip-sign-in.`,
155
+ );
156
+ if (
157
+ account !== undefined ||
158
+ !(await o.terminal?.confirm(
159
+ token
160
+ ? "Claude Code isn't signed in. Make a sign-in token now (claude setup-token)?"
161
+ : "Claude Code isn't signed in. Sign in now (claude auth login)?",
162
+ ))
163
+ )
164
+ throw stop;
165
+ spawnSync(o.claude, token ? ["setup-token"] : ["auth", "login"], {
166
+ stdio: "inherit",
167
+ env: env(),
168
+ ...as(o.user),
169
+ });
170
+ if (token) {
171
+ const pasted = (
172
+ await o.terminal!.line("Paste the token claude setup-token printed: ")
173
+ ).replace(/\s+/g, "");
174
+ if (pasted)
175
+ asUser(o.user, () => {
176
+ const raw = JSON.parse(readFileSync(o.paths.config, "utf8")) as {
177
+ env?: Record<string, string>;
178
+ };
179
+ writeFileSync(
180
+ o.paths.config,
181
+ `${JSON.stringify({ ...raw, env: { ...raw.env, CLAUDE_CODE_OAUTH_TOKEN: pasted } }, null, 2)}\n`,
182
+ );
183
+ chmodSync(o.paths.config, 0o600);
184
+ });
185
+ }
186
+ if (!signedIn()) throw stop;
187
+ return undefined;
188
+ };
package/src/system.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ /**
4
+ * Runs one of the system's own commands (launchctl, systemctl, id), found in the system's folders only: under sudo the
5
+ * PATH is the caller's, and what runs as root must not come from it.
6
+ */
7
+ export const system = (file: string, args: readonly string[]) =>
8
+ spawnSync(file, args, {
9
+ encoding: "utf8",
10
+ env: { ...process.env, PATH: "/usr/sbin:/usr/bin:/sbin:/bin" },
11
+ });
package/src/systemd.ts ADDED
@@ -0,0 +1,78 @@
1
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import type { Service } from "./service";
5
+ import { system } from "./system";
6
+
7
+ // systemd reads `%` as a specifier everywhere, and `$` as a variable in a command line
8
+ const quoted = (value: string) =>
9
+ `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
10
+
11
+ const plain = (path: string) => path.replace(/%/g, "%%");
12
+
13
+ /** The unit's line that names harnessd's state folder: what tells one harnessd's unit from another's. */
14
+ export const unitFolder = (home: string) => `WorkingDirectory=${plain(home)}`;
15
+
16
+ /** The unit's name: `harnessd.service`, or `harnessd-<id>.service` for a state folder of its own. */
17
+ export const unitName = (label: string) =>
18
+ `${label.replace(/^dev\./, "").replace(/\./g, "-")}.service`;
19
+
20
+ /** A user unit in the user's own folder, or for a boot service a system unit. */
21
+ export const unitPath = (label: string, boot = false) =>
22
+ boot
23
+ ? `/etc/systemd/system/${unitName(label)}`
24
+ : join(homedir(), ".config", "systemd", "user", unitName(label));
25
+
26
+ /** The systemd unit: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
27
+ export const unitOf = (o: Service.Spec) => `[Unit]
28
+ Description=harnessd keeps Claude Code running
29
+ StartLimitIntervalSec=0
30
+ ${o.user === undefined ? "" : "After=network-online.target\nWants=network-online.target\n"}
31
+ [Service]
32
+ ${o.user === undefined ? "" : `User=${o.user}\n`}ExecStart=${[o.node, o.bin, "run"].map((arg) => quoted(arg).replace(/\$/g, "$$$$")).join(" ")}
33
+ ${unitFolder(o.paths.home)}
34
+ ${Object.entries(o.env)
35
+ .map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`)
36
+ .join("\n")}
37
+ Restart=always
38
+ RestartSec=5
39
+ KillMode=mixed
40
+ TimeoutStopSec=30
41
+ StandardOutput=append:${plain(o.paths.serviceLog)}
42
+ StandardError=append:${plain(o.paths.serviceLog)}
43
+
44
+ [Install]
45
+ WantedBy=${o.user === undefined ? "default.target" : "multi-user.target"}
46
+ `;
47
+
48
+ const systemctl = (boot: boolean, ...args: string[]) => {
49
+ const result = system("systemctl", [...(boot ? [] : ["--user"]), ...args]);
50
+ if (result.status === 0) return;
51
+ const said = (result.stderr || result.stdout || String(result.error)).trim();
52
+ throw new Error(
53
+ /connect to bus|No medium found/.test(said)
54
+ ? `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.`
55
+ : `systemctl ${args.join(" ")} failed: ${said}`,
56
+ );
57
+ };
58
+
59
+ /** Writes the unit, enables it and (re)starts it, which starts harnessd. */
60
+ export const enable = (label: string, unit: string, boot: boolean) => {
61
+ // before the unit is written: without systemd to reach, no file is left behind
62
+ systemctl(boot, "show-environment");
63
+ mkdirSync(dirname(unitPath(label, boot)), { recursive: true });
64
+ writeFileSync(unitPath(label, boot), unit, { mode: 0o644 });
65
+ systemctl(boot, "daemon-reload");
66
+ systemctl(boot, "enable", unitName(label));
67
+ systemctl(boot, "restart", unitName(label));
68
+ };
69
+
70
+ /** Stops harnessd (it stops Claude Code first) and removes the unit. */
71
+ export const disable = (label: string, boot: boolean) => {
72
+ const had = existsSync(unitPath(label, boot));
73
+ if (!had) return false;
74
+ systemctl(boot, "disable", "--now", unitName(label));
75
+ rmSync(unitPath(label, boot), { force: true });
76
+ systemctl(boot, "daemon-reload");
77
+ return true;
78
+ };
@@ -0,0 +1,33 @@
1
+ /** The terminal's size while nobody is attached. */
2
+ export const IDLE_SIZE = { cols: 160, rows: 50 };
3
+
4
+ const SCROLLBACK_CHARS = 2 * 1024 * 1024;
5
+
6
+ /** The terminal's last ~2 MB of output, so an attach replays the screen before following it live. */
7
+ export const scrollback = (max = SCROLLBACK_CHARS) => {
8
+ let chunks: string[] = [];
9
+ let size = 0;
10
+ return {
11
+ push: (chunk: string) => {
12
+ if (!chunk) return;
13
+ chunks.push(chunk);
14
+ size += chunk.length;
15
+ while (chunks.length > 1 && size - chunks[0]!.length >= max)
16
+ size -= chunks.shift()!.length;
17
+ if (size > max) {
18
+ // cut at a line start, so the replay doesn't open inside an escape sequence
19
+ const first = chunks[0]!;
20
+ let from = first.length - (max - (size - first.length));
21
+ const newline = first.indexOf("\n", from);
22
+ if (newline !== -1) from = newline + 1;
23
+ chunks[0] = first.slice(from);
24
+ size -= from;
25
+ }
26
+ },
27
+ read: () => {
28
+ if (!size) return "";
29
+ chunks = [chunks.join("")];
30
+ return `\x1b[0m${chunks[0]}`;
31
+ },
32
+ };
33
+ };
@@ -0,0 +1,318 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ export namespace Watchdog {
4
+ /** What harnessd keeps across its own restarts. */
5
+ export type State = {
6
+ /** The conversation Claude Code is in, and the next start resumes. */
7
+ readonly sessionId?: string;
8
+ /** Stopped with `harnessd stop`: nothing starts until `harnessd start`. */
9
+ readonly stopped?: boolean;
10
+ /** The account Claude Code last ran on, of the config's accounts. */
11
+ readonly account?: string;
12
+ };
13
+
14
+ /** One start of Claude Code: a new conversation with this id, or a resume of it. */
15
+ export type Start = {
16
+ readonly sessionId: string;
17
+ readonly resume: boolean;
18
+ /** The first message of a resumed conversation: why it restarted. */
19
+ readonly prompt?: string;
20
+ };
21
+
22
+ export type Run = {
23
+ readonly pid?: number;
24
+ /** Resolves with the exit code (128 + signal for a signal). */
25
+ readonly exited: Promise<number>;
26
+ readonly kill: (signal: NodeJS.Signals) => void;
27
+ /** After the exit: why it ended, when the launcher knows and the next start can go on in the same conversation at once. */
28
+ readonly ended?: () => string | undefined;
29
+ };
30
+
31
+ export type Timing = {
32
+ readonly minBackoffMs: number;
33
+ readonly maxBackoffMs: number;
34
+ /** A run this long resets the backoff. */
35
+ readonly healthyMs: number;
36
+ /** A resumed run that exits sooner failed to resume: the next start is a new conversation. */
37
+ readonly resumeFailedMs: number;
38
+ /** Alive this long: running. */
39
+ readonly runningAfterMs: number;
40
+ /** How long a stop waits after SIGTERM before SIGKILL. */
41
+ readonly killAfterMs: number;
42
+ /** How long start and a restart wait for Claude Code to start: longer than a prestart command may take (60 s). */
43
+ readonly spawnWaitMs: number;
44
+ };
45
+
46
+ export type Options = {
47
+ /** Starts Claude Code; a throw (a failed prestart command, say) is a failed start that keeps the conversation. */
48
+ readonly launch: (start: Start) => Promise<Run>;
49
+ readonly state: { read(): State; write(state: State): void };
50
+ /** Whether Claude Code still has this conversation's transcript. */
51
+ readonly hasTranscript: (sessionId: string) => boolean;
52
+ readonly log: (line: string) => void;
53
+ readonly timing?: Partial<Timing>;
54
+ readonly now?: () => number;
55
+ readonly newId?: () => string;
56
+ };
57
+
58
+ export type Status = {
59
+ readonly state: "starting" | "running" | "waiting" | "stopped";
60
+ readonly pid?: number | undefined;
61
+ readonly sessionId?: string | undefined;
62
+ readonly startedAt?: string | undefined;
63
+ readonly restarts: number;
64
+ readonly lastExit?:
65
+ | { readonly code: number; readonly at: string }
66
+ | undefined;
67
+ readonly nextStartAt?: string | undefined;
68
+ };
69
+
70
+ export type Watchdog = {
71
+ /** Runs until `shutdown`. */
72
+ readonly run: () => Promise<void>;
73
+ readonly status: () => Status;
74
+ readonly stop: () => Promise<string>;
75
+ readonly start: () => Promise<string>;
76
+ /** Claude Code moved to this conversation (a /clear, a /resume): later starts resume it. */
77
+ readonly follow: (sessionId: string) => void;
78
+ /** 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. */
79
+ readonly restart: (reason: string, pid?: number) => Promise<string>;
80
+ /** Stops Claude Code and ends `run`, keeping the conversation for the next harnessd. */
81
+ readonly shutdown: () => Promise<void>;
82
+ };
83
+ }
84
+
85
+ const DEFAULT_TIMING: Watchdog.Timing = {
86
+ minBackoffMs: 5_000,
87
+ maxBackoffMs: 5 * 60_000,
88
+ healthyMs: 10 * 60_000,
89
+ resumeFailedMs: 30_000,
90
+ runningAfterMs: 3_000,
91
+ killAfterMs: 10_000,
92
+ spawnWaitMs: 75_000,
93
+ };
94
+
95
+ /** What start and a restart answer when Claude Code didn't start. */
96
+ export const NOT_STARTED =
97
+ "Claude Code didn't start in time; harnessd status shows the log.";
98
+
99
+ export const watchdog = (options: Watchdog.Options): Watchdog.Watchdog => {
100
+ const timing = { ...DEFAULT_TIMING, ...options.timing };
101
+ const now = options.now ?? Date.now;
102
+ const newId = options.newId ?? randomUUID;
103
+ const iso = (ms: number) => new Date(ms).toISOString();
104
+
105
+ let status: Watchdog.Status = { state: "starting", restarts: 0 };
106
+ let current: Watchdog.Run | undefined;
107
+ // a start in progress (its prestart can take a minute): commands wait for it, then act on what it started
108
+ let launching: Promise<unknown> = Promise.resolve();
109
+ let shuttingDown = false;
110
+ let restartNow = false;
111
+ let fresh = false;
112
+ let reason = "harnessd started (a login, a reboot or an update)";
113
+ let wakeUp = () => {};
114
+ let finished: Promise<void> | undefined;
115
+ const spawnWaiters = new Set<() => void>();
116
+ let queue: Promise<unknown> = Promise.resolve();
117
+
118
+ const set = (patch: Partial<Watchdog.Status>) => {
119
+ status = { ...status, ...patch };
120
+ };
121
+ const sleep = (ms: number) =>
122
+ new Promise<void>((resolve) => {
123
+ const timer = setTimeout(done, ms);
124
+ function done() {
125
+ clearTimeout(timer);
126
+ resolve();
127
+ }
128
+ wakeUp = done;
129
+ });
130
+ const nextSpawn = () =>
131
+ new Promise<boolean>((resolve) => {
132
+ const done = () => {
133
+ clearTimeout(timer);
134
+ resolve(true);
135
+ };
136
+ const timer = setTimeout(() => {
137
+ spawnWaiters.delete(done);
138
+ resolve(false);
139
+ }, timing.killAfterMs + timing.spawnWaitMs);
140
+ spawnWaiters.add(done);
141
+ });
142
+ const kill = async (run: Watchdog.Run) => {
143
+ run.kill("SIGTERM");
144
+ let timer: ReturnType<typeof setTimeout> | undefined;
145
+ const exited = await Promise.race([
146
+ run.exited.then(() => true),
147
+ new Promise<false>(
148
+ (resolve) =>
149
+ (timer = setTimeout(() => resolve(false), timing.killAfterMs)),
150
+ ),
151
+ ]);
152
+ clearTimeout(timer);
153
+ if (exited) return;
154
+ options.log("Claude Code didn't exit after SIGTERM; sending SIGKILL");
155
+ run.kill("SIGKILL");
156
+ await run.exited;
157
+ };
158
+
159
+ const next = (): Watchdog.Start => {
160
+ const { sessionId } = options.state.read();
161
+ if (!fresh && sessionId && options.hasTranscript(sessionId))
162
+ return {
163
+ sessionId,
164
+ resume: true,
165
+ prompt: `harnessd restarted Claude Code: ${reason}. This is the same conversation.`,
166
+ };
167
+ return { sessionId: newId(), resume: false };
168
+ };
169
+
170
+ const loop = async () => {
171
+ let backoff = timing.minBackoffMs;
172
+ let runs = 0;
173
+ while (!shuttingDown) {
174
+ if (options.state.read().stopped) {
175
+ set({ state: "stopped", nextStartAt: undefined });
176
+ await sleep(2 ** 31 - 1);
177
+ continue;
178
+ }
179
+ const start = next();
180
+ options.state.write({
181
+ ...options.state.read(),
182
+ sessionId: start.sessionId,
183
+ });
184
+ if (runs++ > 0) set({ restarts: status.restarts + 1 });
185
+ const startedAt = now();
186
+ set({
187
+ state: "starting",
188
+ sessionId: start.sessionId,
189
+ startedAt: iso(startedAt),
190
+ nextStartAt: undefined,
191
+ });
192
+ options.log(
193
+ `starting Claude Code: ${start.resume ? `resuming conversation ${start.sessionId}` : `new conversation ${start.sessionId}`} (${reason})`,
194
+ );
195
+ let run: Watchdog.Run | undefined;
196
+ try {
197
+ const launch = options
198
+ .launch(start)
199
+ .then((started) => (current = started));
200
+ launching = launch.catch(() => {});
201
+ run = await launch;
202
+ } catch (error) {
203
+ options.log(
204
+ `couldn't start Claude Code: ${error instanceof Error ? error.message : String(error)}`,
205
+ );
206
+ reason = "the start before this one failed";
207
+ }
208
+ if (run) {
209
+ if (!start.resume) fresh = false;
210
+ const spawnedAt = now();
211
+ set({ pid: run.pid });
212
+ for (const waiter of spawnWaiters) waiter();
213
+ spawnWaiters.clear();
214
+ const running = setTimeout(
215
+ () => current === run && set({ state: "running" }),
216
+ timing.runningAfterMs,
217
+ );
218
+ const code = await run.exited;
219
+ clearTimeout(running);
220
+ current = undefined;
221
+ const ran = now() - spawnedAt;
222
+ set({ pid: undefined, lastExit: { code, at: iso(now()) } });
223
+ options.log(
224
+ `Claude Code exited with code ${code} after ${Math.round(ran / 1000)}s`,
225
+ );
226
+ if (shuttingDown) break;
227
+ if (restartNow) {
228
+ restartNow = false;
229
+ backoff = timing.minBackoffMs;
230
+ continue;
231
+ }
232
+ if (options.state.read().stopped) continue;
233
+ const ended = run.ended?.();
234
+ if (ended !== undefined) {
235
+ reason = ended;
236
+ backoff = timing.minBackoffMs;
237
+ continue;
238
+ }
239
+ if (start.resume && ran < timing.resumeFailedMs) {
240
+ fresh = true;
241
+ reason = `resuming conversation ${start.sessionId} failed (exit code ${code})`;
242
+ options.log(`${reason}; the next start is a new conversation`);
243
+ } else
244
+ reason = `it exited with code ${code} after ${Math.round(ran / 1000)}s`;
245
+ if (ran >= timing.healthyMs) backoff = timing.minBackoffMs;
246
+ }
247
+ if (shuttingDown) break;
248
+ set({ state: "waiting", nextStartAt: iso(now() + backoff) });
249
+ options.log(`starting again in ${Math.round(backoff / 1000)}s`);
250
+ await sleep(backoff);
251
+ backoff = Math.min(backoff * 2, timing.maxBackoffMs);
252
+ }
253
+ set({ state: "stopped", nextStartAt: undefined });
254
+ };
255
+
256
+ const serial = (command: () => Promise<string>) => {
257
+ const result = queue.catch(() => {}).then(command);
258
+ queue = result;
259
+ return result;
260
+ };
261
+
262
+ return {
263
+ run: () => (finished ??= loop()),
264
+ status: () => status,
265
+ stop: () =>
266
+ serial(async () => {
267
+ await launching;
268
+ const stopped = options.state.read().stopped;
269
+ options.state.write({ ...options.state.read(), stopped: true });
270
+ const run = current;
271
+ if (run) await kill(run);
272
+ wakeUp();
273
+ options.log("stopped with harnessd stop");
274
+ return run
275
+ ? "Stopped Claude Code."
276
+ : stopped
277
+ ? "Claude Code was already stopped."
278
+ : "Stopped (Claude Code was waiting to start).";
279
+ }),
280
+ start: () =>
281
+ serial(async () => {
282
+ await launching;
283
+ if (current) return "Claude Code is already running.";
284
+ options.state.write({ ...options.state.read(), stopped: false });
285
+ reason = "started with harnessd start";
286
+ const spawned = nextSpawn();
287
+ wakeUp();
288
+ return (await spawned) ? "Started Claude Code." : NOT_STARTED;
289
+ }),
290
+ follow: (sessionId) => {
291
+ if (sessionId === options.state.read().sessionId) return;
292
+ options.state.write({ ...options.state.read(), sessionId });
293
+ set({ sessionId });
294
+ options.log(`Claude Code moved to conversation ${sessionId}`);
295
+ },
296
+ restart: (why, pid) =>
297
+ serial(async () => {
298
+ await launching;
299
+ const run = current;
300
+ if (!run) return "Claude Code isn't running.";
301
+ if (pid !== undefined && run.pid !== pid)
302
+ return "That start of Claude Code is over.";
303
+ reason = why;
304
+ const spawned = nextSpawn();
305
+ restartNow = true;
306
+ await kill(run);
307
+ return (await spawned) ? "Restarted Claude Code." : NOT_STARTED;
308
+ }),
309
+ shutdown: async () => {
310
+ shuttingDown = true;
311
+ wakeUp();
312
+ await launching;
313
+ const run = current;
314
+ if (run) await kill(run);
315
+ await finished;
316
+ },
317
+ };
318
+ };