@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/dist/setup.js ADDED
@@ -0,0 +1,121 @@
1
+ import { which } from "./claude.js";
2
+ import { readConfig } from "./config.js";
3
+ import { asUser } from "./service.js";
4
+ import { chmodSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { spawnSync } from "node:child_process";
6
+ import { homedir } from "node:os";
7
+ import { delimiter, join } from "node:path";
8
+ import { createInterface } from "node:readline/promises";
9
+ // src/setup.ts
10
+ /** Anthropic's installer for Claude Code. */
11
+ const INSTALLER = "curl -fsSL https://claude.ai/install.sh | bash";
12
+ const ttyTerminal = () => {
13
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return void 0;
14
+ const line = async (question) => {
15
+ const lines = createInterface({
16
+ input: process.stdin,
17
+ output: process.stdout
18
+ });
19
+ try {
20
+ return (await lines.question(question)).trim();
21
+ } finally {
22
+ lines.close();
23
+ }
24
+ };
25
+ return {
26
+ line,
27
+ confirm: async (question) => /^y(es)?$/i.test(await line(`${question} [y/n] `))
28
+ };
29
+ };
30
+ const as = (user) => user && process.getuid?.() === 0 ? {
31
+ uid: user.uid,
32
+ gid: user.gid
33
+ } : {};
34
+ /** The `claude` on the PATH or where Anthropic's installer puts it; none: installs it with `install`, or after a yes on the terminal. */
35
+ const ensureClaude = async (o) => {
36
+ const find = () => {
37
+ try {
38
+ return which("claude", `${process.env.PATH ?? "/usr/bin:/bin"}${delimiter}${join(homedir(), ".local", "bin")}`);
39
+ } catch {
40
+ return;
41
+ }
42
+ };
43
+ const found = find();
44
+ if (found) return found;
45
+ if (!o.install && !await o.terminal?.confirm(`Claude Code isn't installed. Install it now with Anthropic's installer (curl -fsSL https://claude.ai/install.sh | bash)?`)) throw new Error(`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.`);
46
+ const installed = spawnSync("/bin/bash", ["-c", "curl -fsSL https://claude.ai/install.sh | bash"], {
47
+ stdio: "inherit",
48
+ ...as(o.user)
49
+ }).status === 0 ? find() : void 0;
50
+ if (!installed) throw new Error("The installer left no claude command on the PATH or in ~/.local/bin. Install Claude Code yourself, then run harnessd service install again.");
51
+ return installed;
52
+ };
53
+ /**
54
+ * Checks that Claude Code is signed in the way the service can use, and offers the sign-in on the terminal: Claude
55
+ * Code's own for a login item, a `claude setup-token` token for a boot service and for Linux without a desktop.
56
+ * Without a sign-in it throws what to run; with `skip` it asks nothing and resolves to that instead. Resolves to
57
+ * nothing when Claude Code is signed in, or when a prestart command may sign it in.
58
+ */
59
+ const ensureSignedIn = async (o) => {
60
+ const platform = o.platform ?? process.platform;
61
+ const { accounts, prestart } = readConfig(o.paths);
62
+ if (prestart !== void 0) return void 0;
63
+ const [account] = Object.keys(accounts);
64
+ const env = () => {
65
+ const config = readConfig(o.paths);
66
+ return {
67
+ HOME: homedir(),
68
+ ...o.env,
69
+ ...config.env,
70
+ ...account !== void 0 && config.accounts[account].env
71
+ };
72
+ };
73
+ const signedIn = () => {
74
+ const status = spawnSync(o.claude, [
75
+ "auth",
76
+ "status",
77
+ "--json"
78
+ ], {
79
+ encoding: "utf8",
80
+ env: env(),
81
+ timeout: 3e4,
82
+ ...as(o.user)
83
+ });
84
+ let auth = {};
85
+ try {
86
+ auth = JSON.parse(status.stdout);
87
+ } catch {}
88
+ const keychainOnly = o.user !== void 0 && platform === "darwin" && auth.authMethod === "claude.ai";
89
+ return auth.loggedIn === true && !keychainOnly;
90
+ };
91
+ if (signedIn()) return void 0;
92
+ const token = o.user !== void 0 || platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY;
93
+ const again = "then run harnessd service install again";
94
+ const how = account !== void 0 ? `Claude Code isn't signed in on account ${account}: set its env in ${o.paths.config}, ${again}.` : token ? `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}.` : `Claude Code isn't signed in. Run claude auth login, ${again}.`;
95
+ if (o.skip) return account === void 0 && !token ? `${how.slice(0, -1)}; or sign in inside harnessd attach.` : how;
96
+ const stop = /* @__PURE__ */ new Error(`${how}\nTo install without a sign-in, add --skip-sign-in.`);
97
+ if (account !== void 0 || !await o.terminal?.confirm(token ? "Claude Code isn't signed in. Make a sign-in token now (claude setup-token)?" : "Claude Code isn't signed in. Sign in now (claude auth login)?")) throw stop;
98
+ spawnSync(o.claude, token ? ["setup-token"] : ["auth", "login"], {
99
+ stdio: "inherit",
100
+ env: env(),
101
+ ...as(o.user)
102
+ });
103
+ if (token) {
104
+ const pasted = (await o.terminal.line("Paste the token claude setup-token printed: ")).replace(/\s+/g, "");
105
+ if (pasted) asUser(o.user, () => {
106
+ const raw = JSON.parse(readFileSync(o.paths.config, "utf8"));
107
+ writeFileSync(o.paths.config, `${JSON.stringify({
108
+ ...raw,
109
+ env: {
110
+ ...raw.env,
111
+ CLAUDE_CODE_OAUTH_TOKEN: pasted
112
+ }
113
+ }, null, 2)}\n`);
114
+ chmodSync(o.paths.config, 384);
115
+ });
116
+ }
117
+ if (!signedIn()) throw stop;
118
+ };
119
+ export { INSTALLER, ensureClaude, ensureSignedIn, ttyTerminal };
120
+
121
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.js","names":[],"sources":["../src/setup.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport { chmodSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport { createInterface } from \"node:readline/promises\";\nimport { which } from \"./claude\";\nimport { readConfig, type Harnessd } from \"./config\";\nimport { asUser, type Service } from \"./service\";\n\nexport namespace Setup {\n /** The person at `harnessd service install`; none when it runs from a script. */\n export type Terminal = {\n readonly confirm: (question: string) => Promise<boolean>;\n readonly line: (question: string) => Promise<string>;\n };\n}\n\n/** Anthropic's installer for Claude Code. */\nexport const INSTALLER = \"curl -fsSL https://claude.ai/install.sh | bash\";\n\nexport const ttyTerminal = (): Setup.Terminal | undefined => {\n if (!process.stdin.isTTY || !process.stdout.isTTY) return undefined;\n const line = async (question: string) => {\n const lines = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n try {\n return (await lines.question(question)).trim();\n } finally {\n lines.close();\n }\n };\n return {\n line,\n confirm: async (question) =>\n /^y(es)?$/i.test(await line(`${question} [y/n] `)),\n };\n};\n\n// under sudo, Claude Code's own commands run as the user the service is for\nconst as = (user: Service.User | undefined) =>\n user && process.getuid?.() === 0 ? { uid: user.uid, gid: user.gid } : {};\n\n/** The `claude` on the PATH or where Anthropic's installer puts it; none: installs it with `install`, or after a yes on the terminal. */\nexport const ensureClaude = async (o: {\n terminal: Setup.Terminal | undefined;\n user: Service.User | undefined;\n /** `--install-claude`: runs the installer without asking. */\n install?: boolean | undefined;\n}) => {\n const find = () => {\n try {\n return which(\n \"claude\",\n `${process.env.PATH ?? \"/usr/bin:/bin\"}${delimiter}${join(homedir(), \".local\", \"bin\")}`,\n );\n } catch {\n return undefined;\n }\n };\n const found = find();\n if (found) return found;\n if (\n !o.install &&\n !(await o.terminal?.confirm(\n `Claude Code isn't installed. Install it now with Anthropic's installer (${INSTALLER})?`,\n ))\n )\n throw new Error(\n `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.`,\n );\n const ran = spawnSync(\"/bin/bash\", [\"-c\", INSTALLER], {\n stdio: \"inherit\",\n ...as(o.user),\n });\n const installed = ran.status === 0 ? find() : undefined;\n if (!installed)\n throw new Error(\n \"The installer left no claude command on the PATH or in ~/.local/bin. Install Claude Code yourself, then run harnessd service install again.\",\n );\n return installed;\n};\n\n/**\n * Checks that Claude Code is signed in the way the service can use, and offers the sign-in on the terminal: Claude\n * Code's own for a login item, a `claude setup-token` token for a boot service and for Linux without a desktop.\n * Without a sign-in it throws what to run; with `skip` it asks nothing and resolves to that instead. Resolves to\n * nothing when Claude Code is signed in, or when a prestart command may sign it in.\n */\nexport const ensureSignedIn = async (o: {\n claude: string;\n paths: Harnessd.Paths;\n /** The environment the service starts harnessd with. */\n env: Readonly<Record<string, string>>;\n user: Service.User | undefined;\n terminal: Setup.Terminal | undefined;\n /** `--skip-sign-in`: the install goes on without a sign-in. */\n skip?: boolean | undefined;\n platform?: string;\n}): Promise<string | undefined> => {\n const platform = o.platform ?? process.platform;\n const { accounts, prestart } = readConfig(o.paths);\n // a prestart command may fetch the sign-in at each start: what it prints then isn't known now\n if (prestart !== undefined) return undefined;\n const [account] = Object.keys(accounts);\n const env = () => {\n const config = readConfig(o.paths);\n return {\n HOME: homedir(),\n ...o.env,\n ...config.env,\n ...(account !== undefined && config.accounts[account]!.env),\n };\n };\n const signedIn = () => {\n const status = spawnSync(o.claude, [\"auth\", \"status\", \"--json\"], {\n encoding: \"utf8\",\n env: env(),\n timeout: 30_000,\n ...as(o.user),\n });\n let auth: { loggedIn?: boolean; authMethod?: string } = {};\n try {\n auth = JSON.parse(status.stdout);\n } catch {}\n // a Mac's boot service starts outside any login, where the keychain's sign-in can't be read\n const keychainOnly =\n o.user !== undefined &&\n platform === \"darwin\" &&\n auth.authMethod === \"claude.ai\";\n return auth.loggedIn === true && !keychainOnly;\n };\n if (signedIn()) return undefined;\n\n const token =\n o.user !== undefined ||\n (platform === \"linux\" &&\n !process.env.DISPLAY &&\n !process.env.WAYLAND_DISPLAY);\n const again = \"then run harnessd service install again\";\n const how =\n account !== undefined\n ? `Claude Code isn't signed in on account ${account}: set its env in ${o.paths.config}, ${again}.`\n : token\n ? `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}.`\n : `Claude Code isn't signed in. Run claude auth login, ${again}.`;\n // once the service runs, Claude Code's own sign-in screen is another way\n if (o.skip)\n return account === undefined && !token\n ? `${how.slice(0, -1)}; or sign in inside harnessd attach.`\n : how;\n const stop = new Error(\n `${how}\\nTo install without a sign-in, add --skip-sign-in.`,\n );\n if (\n account !== undefined ||\n !(await o.terminal?.confirm(\n token\n ? \"Claude Code isn't signed in. Make a sign-in token now (claude setup-token)?\"\n : \"Claude Code isn't signed in. Sign in now (claude auth login)?\",\n ))\n )\n throw stop;\n spawnSync(o.claude, token ? [\"setup-token\"] : [\"auth\", \"login\"], {\n stdio: \"inherit\",\n env: env(),\n ...as(o.user),\n });\n if (token) {\n const pasted = (\n await o.terminal!.line(\"Paste the token claude setup-token printed: \")\n ).replace(/\\s+/g, \"\");\n if (pasted)\n asUser(o.user, () => {\n const raw = JSON.parse(readFileSync(o.paths.config, \"utf8\")) as {\n env?: Record<string, string>;\n };\n writeFileSync(\n o.paths.config,\n `${JSON.stringify({ ...raw, env: { ...raw.env, CLAUDE_CODE_OAUTH_TOKEN: pasted } }, null, 2)}\\n`,\n );\n chmodSync(o.paths.config, 0o600);\n });\n }\n if (!signedIn()) throw stop;\n return undefined;\n};\n"],"mappings":";;;;;;;;;;AAkBA,MAAa,YAAY;AAEzB,MAAa,oBAAgD;CAC3D,IAAI,CAAC,QAAQ,MAAM,SAAS,CAAC,QAAQ,OAAO,OAAO,OAAO,KAAA;CAC1D,MAAM,OAAO,OAAO,aAAqB;EACvC,MAAM,QAAQ,gBAAgB;GAC5B,OAAO,QAAQ;GACf,QAAQ,QAAQ;EAClB,CAAC;EACD,IAAI;GACF,QAAQ,MAAM,MAAM,SAAS,QAAQ,EAAA,CAAG,KAAK;EAC/C,UAAU;GACR,MAAM,MAAM;EACd;CACF;CACA,OAAO;EACL;EACA,SAAS,OAAO,aACd,YAAY,KAAK,MAAM,KAAK,GAAG,SAAS,QAAQ,CAAC;CACrD;AACF;AAGA,MAAM,MAAM,SACV,QAAQ,QAAQ,SAAS,MAAM,IAAI;CAAE,KAAK,KAAK;CAAK,KAAK,KAAK;AAAI,IAAI,CAAC;;AAGzE,MAAa,eAAe,OAAO,MAK7B;CACJ,MAAM,aAAa;EACjB,IAAI;GACF,OAAO,MACL,UACA,GAAG,QAAQ,IAAI,QAAQ,kBAAkB,YAAY,KAAK,QAAQ,GAAG,UAAU,KAAK,GACtF;EACF,QAAQ;GACN;EACF;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,IAAI,OAAO,OAAO;CAClB,IACE,CAAC,EAAE,WACH,CAAE,MAAM,EAAE,UAAU,QAClB,0HACF,GAEA,MAAM,IAAI,MACR,+FAA+F,UAAU,kEAC3G;CAKF,MAAM,YAJM,UAAU,aAAa,CAAC,MAAA,gDAAe,GAAG;EACpD,OAAO;EACP,GAAG,GAAG,EAAE,IAAI;CACd,CACoB,CAAC,CAAC,WAAW,IAAI,KAAK,IAAI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AE,EAAE,wCACpB;CACN,MAAM,uBAAO,IAAI,MACf,GAAG,IAAI,oDACT;CACA,IACE,YAAY,KAAA,KACZ,CAAE,MAAM,EAAE,UAAU,QAClB,QACI,gFACA,+DACN,GAEA,MAAM;CACR,UAAU,EAAE,QAAQ,QAAQ,CAAC,aAAa,IAAI,CAAC,QAAQ,OAAO,GAAG;EAC/D,OAAO;EACP,KAAK,IAAI;EACT,GAAG,GAAG,EAAE,IAAI;CACd,CAAC;CACD,IAAI,OAAO;EACT,MAAM,UACJ,MAAM,EAAE,SAAU,KAAK,8CAA8C,EAAA,CACrE,QAAQ,QAAQ,EAAE;EACpB,IAAI,QACF,OAAO,EAAE,YAAY;GACnB,MAAM,MAAM,KAAK,MAAM,aAAa,EAAE,MAAM,QAAQ,MAAM,CAAC;GAG3D,cACE,EAAE,MAAM,QACR,GAAG,KAAK,UAAU;IAAE,GAAG;IAAK,KAAK;KAAE,GAAG,IAAI;KAAK,yBAAyB;IAAO;GAAE,GAAG,MAAM,CAAC,EAAE,GAC/F;GACA,UAAU,EAAE,MAAM,QAAQ,GAAK;EACjC,CAAC;CACL;CACA,IAAI,CAAC,SAAS,GAAG,MAAM;AAEzB"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Runs one of the system's own commands (launchctl, systemctl, id), found in the system's folders only: under sudo the
3
+ * PATH is the caller's, and what runs as root must not come from it.
4
+ */
5
+ export declare const system: (file: string, args: readonly string[]) => import("node:child_process").SpawnSyncReturns<string>;
6
+ //# sourceMappingURL=system.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"system.d.ts","sourceRoot":"","sources":["../src/system.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,eAAO,MAAM,MAAM,GAAI,MAAM,MAAM,EAAE,MAAM,SAAS,MAAM,EAAE,0DAIxD,CAAC"}
package/dist/system.js ADDED
@@ -0,0 +1,16 @@
1
+ import { spawnSync } from "node:child_process";
2
+ // src/system.ts
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
+ const system = (file, args) => spawnSync(file, args, {
8
+ encoding: "utf8",
9
+ env: {
10
+ ...process.env,
11
+ PATH: "/usr/sbin:/usr/bin:/sbin:/bin"
12
+ }
13
+ });
14
+ export { system };
15
+
16
+ //# sourceMappingURL=system.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"system.js","names":[],"sources":["../src/system.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\n\n/**\n * Runs one of the system's own commands (launchctl, systemctl, id), found in the system's folders only: under sudo the\n * PATH is the caller's, and what runs as root must not come from it.\n */\nexport const system = (file: string, args: readonly string[]) =>\n spawnSync(file, args, {\n encoding: \"utf8\",\n env: { ...process.env, PATH: \"/usr/sbin:/usr/bin:/sbin:/bin\" },\n });\n"],"mappings":";;;;;;AAMA,MAAa,UAAU,MAAc,SACnC,UAAU,MAAM,MAAM;CACpB,UAAU;CACV,KAAK;EAAE,GAAG,QAAQ;EAAK,MAAM;CAAgC;AAC/D,CAAC"}
@@ -0,0 +1,14 @@
1
+ import type { Service } from "./service.js";
2
+ /** The unit's line that names harnessd's state folder: what tells one harnessd's unit from another's. */
3
+ export declare const unitFolder: (home: string) => string;
4
+ /** The unit's name: `harnessd.service`, or `harnessd-<id>.service` for a state folder of its own. */
5
+ export declare const unitName: (label: string) => string;
6
+ /** A user unit in the user's own folder, or for a boot service a system unit. */
7
+ export declare const unitPath: (label: string, boot?: boolean) => string;
8
+ /** The systemd unit: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
9
+ export declare const unitOf: (o: Service.Spec) => string;
10
+ /** Writes the unit, enables it and (re)starts it, which starts harnessd. */
11
+ export declare const enable: (label: string, unit: string, boot: boolean) => void;
12
+ /** Stops harnessd (it stops Claude Code first) and removes the unit. */
13
+ export declare const disable: (label: string, boot: boolean) => boolean;
14
+ //# sourceMappingURL=systemd.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"systemd.d.ts","sourceRoot":"","sources":["../src/systemd.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,qBAAkB;AASzC,yGAAyG;AACzG,eAAO,MAAM,UAAU,GAAI,MAAM,MAAM,WAAsC,CAAC;AAE9E,qGAAqG;AACrG,eAAO,MAAM,QAAQ,GAAI,OAAO,MAAM,WACwB,CAAC;AAE/D,iFAAiF;AACjF,eAAO,MAAM,QAAQ,GAAI,OAAO,MAAM,EAAE,cAAY,WAGgB,CAAC;AAErE,2GAA2G;AAC3G,eAAO,MAAM,MAAM,GAAI,GAAG,OAAO,CAAC,IAAI,WAmBrC,CAAC;AAaF,4EAA4E;AAC5E,eAAO,MAAM,MAAM,GAAI,OAAO,MAAM,EAAE,MAAM,MAAM,EAAE,MAAM,OAAO,SAQhE,CAAC;AAEF,wEAAwE;AACxE,eAAO,MAAM,OAAO,GAAI,OAAO,MAAM,EAAE,MAAM,OAAO,YAOnD,CAAC"}
@@ -0,0 +1,62 @@
1
+ import { system } from "./system.js";
2
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+ // src/systemd.ts
6
+ const quoted = (value) => `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/%/g, "%%")}"`;
7
+ const plain = (path) => path.replace(/%/g, "%%");
8
+ /** The unit's line that names harnessd's state folder: what tells one harnessd's unit from another's. */
9
+ const unitFolder = (home) => `WorkingDirectory=${plain(home)}`;
10
+ /** The unit's name: `harnessd.service`, or `harnessd-<id>.service` for a state folder of its own. */
11
+ const unitName = (label) => `${label.replace(/^dev\./, "").replace(/\./g, "-")}.service`;
12
+ /** A user unit in the user's own folder, or for a boot service a system unit. */
13
+ const unitPath = (label, boot = false) => boot ? `/etc/systemd/system/${unitName(label)}` : join(homedir(), ".config", "systemd", "user", unitName(label));
14
+ /** The systemd unit: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
15
+ const unitOf = (o) => `[Unit]
16
+ Description=harnessd keeps Claude Code running
17
+ StartLimitIntervalSec=0
18
+ ${o.user === void 0 ? "" : "After=network-online.target\nWants=network-online.target\n"}
19
+ [Service]
20
+ ${o.user === void 0 ? "" : `User=${o.user}\n`}ExecStart=${[
21
+ o.node,
22
+ o.bin,
23
+ "run"
24
+ ].map((arg) => quoted(arg).replace(/\$/g, "$$$$")).join(" ")}
25
+ ${unitFolder(o.paths.home)}
26
+ ${Object.entries(o.env).map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`).join("\n")}
27
+ Restart=always
28
+ RestartSec=5
29
+ KillMode=mixed
30
+ TimeoutStopSec=30
31
+ StandardOutput=append:${plain(o.paths.serviceLog)}
32
+ StandardError=append:${plain(o.paths.serviceLog)}
33
+
34
+ [Install]
35
+ WantedBy=${o.user === void 0 ? "default.target" : "multi-user.target"}
36
+ `;
37
+ const systemctl = (boot, ...args) => {
38
+ const result = system("systemctl", [...boot ? [] : ["--user"], ...args]);
39
+ if (result.status === 0) return;
40
+ const said = (result.stderr || result.stdout || String(result.error)).trim();
41
+ throw new Error(/connect to bus|No medium found/.test(said) ? `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.` : `systemctl ${args.join(" ")} failed: ${said}`);
42
+ };
43
+ /** Writes the unit, enables it and (re)starts it, which starts harnessd. */
44
+ const enable = (label, unit, boot) => {
45
+ systemctl(boot, "show-environment");
46
+ mkdirSync(dirname(unitPath(label, boot)), { recursive: true });
47
+ writeFileSync(unitPath(label, boot), unit, { mode: 420 });
48
+ systemctl(boot, "daemon-reload");
49
+ systemctl(boot, "enable", unitName(label));
50
+ systemctl(boot, "restart", unitName(label));
51
+ };
52
+ /** Stops harnessd (it stops Claude Code first) and removes the unit. */
53
+ const disable = (label, boot) => {
54
+ if (!existsSync(unitPath(label, boot))) return false;
55
+ systemctl(boot, "disable", "--now", unitName(label));
56
+ rmSync(unitPath(label, boot), { force: true });
57
+ systemctl(boot, "daemon-reload");
58
+ return true;
59
+ };
60
+ export { disable, enable, unitFolder, unitName, unitOf, unitPath };
61
+
62
+ //# sourceMappingURL=systemd.js.map
@@ -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), { force: true });\n systemctl(boot, \"daemon-reload\");\n return true;\n};\n"],"mappings":";;;;;AAOA,MAAM,UAAU,UACd,IAAI,MAAM,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAK,CAAC,CAAC,QAAQ,MAAM,IAAI,EAAE;AAE5E,MAAM,SAAS,SAAiB,KAAK,QAAQ,MAAM,IAAI;;AAGvD,MAAa,cAAc,SAAiB,oBAAoB,MAAM,IAAI;;AAG1E,MAAa,YAAY,UACvB,GAAG,MAAM,QAAQ,UAAU,EAAE,CAAC,CAAC,QAAQ,OAAO,GA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,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"}
@@ -0,0 +1,11 @@
1
+ /** The terminal's size while nobody is attached. */
2
+ export declare const IDLE_SIZE: {
3
+ cols: number;
4
+ rows: number;
5
+ };
6
+ /** The terminal's last ~2 MB of output, so an attach replays the screen before following it live. */
7
+ export declare const scrollback: (max?: number) => {
8
+ push: (chunk: string) => void;
9
+ read: () => string;
10
+ };
11
+ //# sourceMappingURL=terminal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal.d.ts","sourceRoot":"","sources":["../src/terminal.ts"],"names":[],"mappings":"AAAA,oDAAoD;AACpD,eAAO,MAAM,SAAS;;;CAA0B,CAAC;AAIjD,qGAAqG;AACrG,eAAO,MAAM,UAAU,GAAI,YAAsB;kBAI/B,MAAM;;CAsBvB,CAAC"}
@@ -0,0 +1,36 @@
1
+ // src/terminal.ts
2
+ /** The terminal's size while nobody is attached. */
3
+ const IDLE_SIZE = {
4
+ cols: 160,
5
+ rows: 50
6
+ };
7
+ const SCROLLBACK_CHARS = 2097152;
8
+ /** The terminal's last ~2 MB of output, so an attach replays the screen before following it live. */
9
+ const scrollback = (max = SCROLLBACK_CHARS) => {
10
+ let chunks = [];
11
+ let size = 0;
12
+ return {
13
+ push: (chunk) => {
14
+ if (!chunk) return;
15
+ chunks.push(chunk);
16
+ size += chunk.length;
17
+ while (chunks.length > 1 && size - chunks[0].length >= max) size -= chunks.shift().length;
18
+ if (size > max) {
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
+ };
34
+ export { IDLE_SIZE, scrollback };
35
+
36
+ //# sourceMappingURL=terminal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"terminal.js","names":[],"sources":["../src/terminal.ts"],"sourcesContent":["/** The terminal's size while nobody is attached. */\nexport const IDLE_SIZE = { cols: 160, rows: 50 };\n\nconst SCROLLBACK_CHARS = 2 * 1024 * 1024;\n\n/** The terminal's last ~2 MB of output, so an attach replays the screen before following it live. */\nexport const scrollback = (max = SCROLLBACK_CHARS) => {\n let chunks: string[] = [];\n let size = 0;\n return {\n push: (chunk: string) => {\n if (!chunk) return;\n chunks.push(chunk);\n size += chunk.length;\n while (chunks.length > 1 && size - chunks[0]!.length >= max)\n size -= chunks.shift()!.length;\n if (size > max) {\n // cut at a line start, so the replay doesn't open inside an escape sequence\n const first = chunks[0]!;\n let from = first.length - (max - (size - first.length));\n const newline = first.indexOf(\"\\n\", from);\n if (newline !== -1) from = newline + 1;\n chunks[0] = first.slice(from);\n size -= from;\n }\n },\n read: () => {\n if (!size) return \"\";\n chunks = [chunks.join(\"\")];\n return `\\x1b[0m${chunks[0]}`;\n },\n };\n};\n"],"mappings":";;AACA,MAAa,YAAY;CAAE,MAAM;CAAK,MAAM;AAAG;AAE/C,MAAM,mBAAmB;;AAGzB,MAAa,cAAc,MAAM,qBAAqB;CACpD,IAAI,SAAmB,CAAC;CACxB,IAAI,OAAO;CACX,OAAO;EACL,OAAO,UAAkB;GACvB,IAAI,CAAC,OAAO;GACZ,OAAO,KAAK,KAAK;GACjB,QAAQ,MAAM;GACd,OAAO,OAAO,SAAS,KAAK,OAAO,OAAO,EAAE,CAAE,UAAU,KACtD,QAAQ,OAAO,MAAM,CAAC,CAAE;GAC1B,IAAI,OAAO,KAAK;IAEd,MAAM,QAAQ,OAAO;IACrB,IAAI,OAAO,MAAM,UAAU,OAAO,OAAO,MAAM;IAC/C,MAAM,UAAU,MAAM,QAAQ,MAAM,IAAI;IACxC,IAAI,YAAY,IAAI,OAAO,UAAU;IACrC,OAAO,KAAK,MAAM,MAAM,IAAI;IAC5B,QAAQ;GACV;EACF;EACA,YAAY;GACV,IAAI,CAAC,MAAM,OAAO;GAClB,SAAS,CAAC,OAAO,KAAK,EAAE,CAAC;GACzB,OAAO,UAAU,OAAO;EAC1B;CACF;AACF"}
@@ -0,0 +1,83 @@
1
+ export declare namespace Watchdog {
2
+ /** What harnessd keeps across its own restarts. */
3
+ type State = {
4
+ /** The conversation Claude Code is in, and the next start resumes. */
5
+ readonly sessionId?: string;
6
+ /** Stopped with `harnessd stop`: nothing starts until `harnessd start`. */
7
+ readonly stopped?: boolean;
8
+ /** The account Claude Code last ran on, of the config's accounts. */
9
+ readonly account?: string;
10
+ };
11
+ /** One start of Claude Code: a new conversation with this id, or a resume of it. */
12
+ type Start = {
13
+ readonly sessionId: string;
14
+ readonly resume: boolean;
15
+ /** The first message of a resumed conversation: why it restarted. */
16
+ readonly prompt?: string;
17
+ };
18
+ type Run = {
19
+ readonly pid?: number;
20
+ /** Resolves with the exit code (128 + signal for a signal). */
21
+ readonly exited: Promise<number>;
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;
25
+ };
26
+ type Timing = {
27
+ readonly minBackoffMs: number;
28
+ readonly maxBackoffMs: number;
29
+ /** A run this long resets the backoff. */
30
+ readonly healthyMs: number;
31
+ /** A resumed run that exits sooner failed to resume: the next start is a new conversation. */
32
+ readonly resumeFailedMs: number;
33
+ /** Alive this long: running. */
34
+ readonly runningAfterMs: number;
35
+ /** How long a stop waits after SIGTERM before SIGKILL. */
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;
39
+ };
40
+ type Options = {
41
+ /** Starts Claude Code; a throw (a failed prestart command, say) is a failed start that keeps the conversation. */
42
+ readonly launch: (start: Start) => Promise<Run>;
43
+ readonly state: {
44
+ read(): State;
45
+ write(state: State): void;
46
+ };
47
+ /** Whether Claude Code still has this conversation's transcript. */
48
+ readonly hasTranscript: (sessionId: string) => boolean;
49
+ readonly log: (line: string) => void;
50
+ readonly timing?: Partial<Timing>;
51
+ readonly now?: () => number;
52
+ readonly newId?: () => string;
53
+ };
54
+ type Status = {
55
+ readonly state: "starting" | "running" | "waiting" | "stopped";
56
+ readonly pid?: number | undefined;
57
+ readonly sessionId?: string | undefined;
58
+ readonly startedAt?: string | undefined;
59
+ readonly restarts: number;
60
+ readonly lastExit?: {
61
+ readonly code: number;
62
+ readonly at: string;
63
+ } | undefined;
64
+ readonly nextStartAt?: string | undefined;
65
+ };
66
+ type Watchdog = {
67
+ /** Runs until `shutdown`. */
68
+ readonly run: () => Promise<void>;
69
+ readonly status: () => Status;
70
+ readonly stop: () => Promise<string>;
71
+ readonly start: () => 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>;
76
+ /** Stops Claude Code and ends `run`, keeping the conversation for the next harnessd. */
77
+ readonly shutdown: () => Promise<void>;
78
+ };
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.";
82
+ export declare const watchdog: (options: Watchd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,CAAC;QACd,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;KAC3C,CAAC;IAEF,KAAY,QAAQ,GAAG;QACrB,6BAA6B;QAC7B,QAAQ,CAAC,GAAG,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;QAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,MAAM,CAAC;QAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;QACrC,QAAQ,CAAC,KAAK,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;QACtC,4FAA4F;QAC5F,QAAQ,CAAC,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;QAC7C,mKAAmK;QACnK,QAAQ,CAAC,OAAO,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC;QACpE,wFAAwF;QACxF,QAAQ,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;KACxC,CAAC;CACH;AAYD,qEAAqE;AACrE,eAAO,MAAM,WAAW,qEAC4C,CAAC;AAErE,eAAO,MAAM,QAAQ,GAAI,SAAS,QAAQ,CAAC,OAAO,KAAG,QAAQ,CAAC,QA2N7D,CAAC"}
@@ -0,0 +1,236 @@
1
+ import { randomUUID } from "node:crypto";
2
+ // src/watchdog.ts
3
+ const DEFAULT_TIMING = {
4
+ minBackoffMs: 5e3,
5
+ maxBackoffMs: 3e5,
6
+ healthyMs: 6e5,
7
+ resumeFailedMs: 3e4,
8
+ runningAfterMs: 3e3,
9
+ killAfterMs: 1e4,
10
+ spawnWaitMs: 75e3
11
+ };
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.";
14
+ const watchdog = (options) => {
15
+ const timing = {
16
+ ...DEFAULT_TIMING,
17
+ ...options.timing
18
+ };
19
+ const now = options.now ?? Date.now;
20
+ const newId = options.newId ?? randomUUID;
21
+ const iso = (ms) => new Date(ms).toISOString();
22
+ let status = {
23
+ state: "starting",
24
+ restarts: 0
25
+ };
26
+ let current;
27
+ let launching = Promise.resolve();
28
+ let shuttingDown = false;
29
+ let restartNow = false;
30
+ let fresh = false;
31
+ let reason = "harnessd started (a login, a reboot or an update)";
32
+ let wakeUp = () => {};
33
+ let finished;
34
+ const spawnWaiters = /* @__PURE__ */ new Set();
35
+ let queue = Promise.resolve();
36
+ const set = (patch) => {
37
+ status = {
38
+ ...status,
39
+ ...patch
40
+ };
41
+ };
42
+ const sleep = (ms) => new Promise((resolve) => {
43
+ const timer = setTimeout(done, ms);
44
+ function done() {
45
+ clearTimeout(timer);
46
+ resolve();
47
+ }
48
+ wakeUp = done;
49
+ });
50
+ const nextSpawn = () => new Promise((resolve) => {
51
+ const done = () => {
52
+ clearTimeout(timer);
53
+ resolve(true);
54
+ };
55
+ const timer = setTimeout(() => {
56
+ spawnWaiters.delete(done);
57
+ resolve(false);
58
+ }, timing.killAfterMs + timing.spawnWaitMs);
59
+ spawnWaiters.add(done);
60
+ });
61
+ const kill = async (run) => {
62
+ run.kill("SIGTERM");
63
+ let timer;
64
+ const exited = await Promise.race([run.exited.then(() => true), new Promise((resolve) => timer = setTimeout(() => resolve(false), timing.killAfterMs))]);
65
+ clearTimeout(timer);
66
+ if (exited) return;
67
+ options.log("Claude Code didn't exit after SIGTERM; sending SIGKILL");
68
+ run.kill("SIGKILL");
69
+ await run.exited;
70
+ };
71
+ const next = () => {
72
+ const { sessionId } = options.state.read();
73
+ if (!fresh && sessionId && options.hasTranscript(sessionId)) return {
74
+ sessionId,
75
+ resume: true,
76
+ prompt: `harnessd restarted Claude Code: ${reason}. This is the same conversation.`
77
+ };
78
+ return {
79
+ sessionId: newId(),
80
+ resume: false
81
+ };
82
+ };
83
+ const loop = async () => {
84
+ let backoff = timing.minBackoffMs;
85
+ let runs = 0;
86
+ while (!shuttingDown) {
87
+ if (options.state.read().stopped) {
88
+ set({
89
+ state: "stopped",
90
+ nextStartAt: void 0
91
+ });
92
+ await sleep(2 ** 31 - 1);
93
+ continue;
94
+ }
95
+ const start = next();
96
+ options.state.write({
97
+ ...options.state.read(),
98
+ sessionId: start.sessionId
99
+ });
100
+ if (runs++ > 0) set({ restarts: status.restarts + 1 });
101
+ const startedAt = now();
102
+ set({
103
+ state: "starting",
104
+ sessionId: start.sessionId,
105
+ startedAt: iso(startedAt),
106
+ nextStartAt: void 0
107
+ });
108
+ options.log(`starting Claude Code: ${start.resume ? `resuming conversation ${start.sessionId}` : `new conversation ${start.sessionId}`} (${reason})`);
109
+ let run;
110
+ try {
111
+ const launch = options.launch(start).then((started) => current = started);
112
+ launching = launch.catch(() => {});
113
+ run = await launch;
114
+ } catch (error) {
115
+ options.log(`couldn't start Claude Code: ${error instanceof Error ? error.message : String(error)}`);
116
+ reason = "the start before this one failed";
117
+ }
118
+ if (run) {
119
+ if (!start.resume) fresh = false;
120
+ const spawnedAt = now();
121
+ set({ pid: run.pid });
122
+ for (const waiter of spawnWaiters) waiter();
123
+ spawnWaiters.clear();
124
+ const running = setTimeout(() => current === run && set({ state: "running" }), timing.runningAfterMs);
125
+ const code = await run.exited;
126
+ clearTimeout(running);
127
+ current = void 0;
128
+ const ran = now() - spawnedAt;
129
+ set({
130
+ pid: void 0,
131
+ lastExit: {
132
+ code,
133
+ at: iso(now())
134
+ }
135
+ });
136
+ options.log(`Claude Code exited with code ${code} after ${Math.round(ran / 1e3)}s`);
137
+ if (shuttingDown) break;
138
+ if (restartNow) {
139
+ restartNow = false;
140
+ backoff = timing.minBackoffMs;
141
+ continue;
142
+ }
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
+ }
150
+ if (start.resume && ran < timing.resumeFailedMs) {
151
+ fresh = true;
152
+ reason = `resuming conversation ${start.sessionId} failed (exit code ${code})`;
153
+ options.log(`${reason}; the next start is a new conversation`);
154
+ } else reason = `it exited with code ${code} after ${Math.round(ran / 1e3)}s`;
155
+ if (ran >= timing.healthyMs) backoff = timing.minBackoffMs;
156
+ }
157
+ if (shuttingDown) break;
158
+ set({
159
+ state: "waiting",
160
+ nextStartAt: iso(now() + backoff)
161
+ });
162
+ options.log(`starting again in ${Math.round(backoff / 1e3)}s`);
163
+ await sleep(backoff);
164
+ backoff = Math.min(backoff * 2, timing.maxBackoffMs);
165
+ }
166
+ set({
167
+ state: "stopped",
168
+ nextStartAt: void 0
169
+ });
170
+ };
171
+ const serial = (command) => {
172
+ const result = queue.catch(() => {}).then(command);
173
+ queue = result;
174
+ return result;
175
+ };
176
+ return {
177
+ run: () => finished ??= loop(),
178
+ status: () => status,
179
+ stop: () => serial(async () => {
180
+ await launching;
181
+ const stopped = options.state.read().stopped;
182
+ options.state.write({
183
+ ...options.state.read(),
184
+ stopped: true
185
+ });
186
+ const run = current;
187
+ if (run) await kill(run);
188
+ wakeUp();
189
+ options.log("stopped with harnessd stop");
190
+ return run ? "Stopped Claude Code." : stopped ? "Claude Code was already stopped." : "Stopped (Claude Code was waiting to start).";
191
+ }),
192
+ start: () => serial(async () => {
193
+ await launching;
194
+ if (current) return "Claude Code is already running.";
195
+ options.state.write({
196
+ ...options.state.read(),
197
+ stopped: false
198
+ });
199
+ reason = "started with harnessd start";
200
+ const spawned = nextSpawn();
201
+ wakeUp();
202
+ return await spawned ? "Started Claude Code." : NOT_STARTED;
203
+ }),
204
+ follow: (sessionId) => {
205
+ if (sessionId === options.state.read().sessionId) return;
206
+ options.state.write({
207
+ ...options.state.read(),
208
+ sessionId
209
+ });
210
+ set({ sessionId });
211
+ options.log(`Claude Code moved to conversation ${sessionId}`);
212
+ },
213
+ restart: (why, pid) => serial(async () => {
214
+ await launching;
215
+ const run = current;
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;
223
+ }),
224
+ shutdown: async () => {
225
+ shuttingDown = true;
226
+ wakeUp();
227
+ await launching;
228
+ const run = current;
229
+ if (run) await kill(run);
230
+ await finished;
231
+ }
232
+ };
233
+ };
234
+ export { NOT_STARTED, watchdog };
235
+
236
+ //# sourceMappingURL=watchdog.js.map