@harness-sdk/harnessd 0.0.0 → 0.0.1

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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +15 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/channel.d.ts +56 -0
  8. package/dist/channel.d.ts.map +1 -0
  9. package/dist/channel.js +356 -0
  10. package/dist/channel.js.map +1 -0
  11. package/dist/claude.d.ts +42 -0
  12. package/dist/claude.d.ts.map +1 -0
  13. package/dist/claude.js +166 -0
  14. package/dist/claude.js.map +1 -0
  15. package/dist/cli.d.ts +8 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +258 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/config.d.ts +43 -0
  20. package/dist/config.d.ts.map +1 -0
  21. package/dist/config.js +121 -0
  22. package/dist/config.js.map +1 -0
  23. package/dist/daemon.d.ts +24 -0
  24. package/dist/daemon.d.ts.map +1 -0
  25. package/dist/daemon.js +239 -0
  26. package/dist/daemon.js.map +1 -0
  27. package/dist/launchd.d.ts +22 -0
  28. package/dist/launchd.d.ts.map +1 -0
  29. package/dist/launchd.js +88 -0
  30. package/dist/launchd.js.map +1 -0
  31. package/dist/log.d.ts +3 -0
  32. package/dist/log.d.ts.map +1 -0
  33. package/dist/log.js +17 -0
  34. package/dist/log.js.map +1 -0
  35. package/dist/terminal.d.ts +11 -0
  36. package/dist/terminal.d.ts.map +1 -0
  37. package/dist/terminal.js +36 -0
  38. package/dist/terminal.js.map +1 -0
  39. package/dist/watchdog.d.ts +73 -0
  40. package/dist/watchdog.d.ts.map +1 -0
  41. package/dist/watchdog.js +230 -0
  42. package/dist/watchdog.js.map +1 -0
  43. package/package.json +53 -6
  44. package/src/bin.ts +18 -0
  45. package/src/channel.ts +461 -0
  46. package/src/claude.ts +274 -0
  47. package/src/cli.ts +372 -0
  48. package/src/config.ts +203 -0
  49. package/src/daemon.ts +312 -0
  50. package/src/launchd.ts +126 -0
  51. package/src/log.ts +17 -0
  52. package/src/terminal.ts +33 -0
  53. package/src/watchdog.ts +310 -0
package/dist/config.js ADDED
@@ -0,0 +1,121 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ // src/config.ts
6
+ const DEFAULT_HOME = join(homedir(), ".harnessd");
7
+ const LOOPBACK = /* @__PURE__ */ new Set([
8
+ "localhost",
9
+ "127.0.0.1",
10
+ "[::1]"
11
+ ]);
12
+ const NAME = /^[a-z][a-z0-9-]{0,31}$/;
13
+ const RESERVED = /* @__PURE__ */ new Set([
14
+ "stream",
15
+ "login",
16
+ "help"
17
+ ]);
18
+ const SOCKET_MAX = 103;
19
+ const pathsOf = (env = process.env) => {
20
+ const home = resolve(env.HARNESSD_HOME || DEFAULT_HOME);
21
+ const socket = join(home, "harnessd.sock");
22
+ if (Buffer.byteLength(socket) > SOCKET_MAX) throw new Error(`HARNESSD_HOME is too long for a socket (${socket})`);
23
+ return {
24
+ home,
25
+ config: join(home, "config.json"),
26
+ state: join(home, "state.json"),
27
+ log: join(home, "harnessd.log"),
28
+ socket,
29
+ plugin: join(home, "plugin"),
30
+ channels: join(home, "channels"),
31
+ label: home === DEFAULT_HOME ? "dev.harnessd" : `dev.harnessd.${createHash("sha256").update(home).digest("hex").slice(0, 8)}`
32
+ };
33
+ };
34
+ const DEFAULT_CONFIG = {
35
+ folder: "~/agent",
36
+ channels: {}
37
+ };
38
+ const fail = (message) => {
39
+ throw new Error(`config.json: ${message}`);
40
+ };
41
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
42
+ const strings = (value, what) => {
43
+ if (value === void 0) return {};
44
+ if (!isRecord(value) || Object.values(value).some((v) => typeof v !== "string")) fail(`${what} must map names to strings`);
45
+ return value;
46
+ };
47
+ const only = (value, keys, what) => {
48
+ const unknown = Object.keys(value).find((key) => !keys.includes(key));
49
+ if (unknown !== void 0) fail(`${what} has no "${unknown}"; it takes ${keys.join(", ")}`);
50
+ };
51
+ const expandHome = (path) => path === "~" ? homedir() : path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
52
+ const parseConfig = (raw) => {
53
+ if (!isRecord(raw)) fail("must be a JSON object");
54
+ const value = raw;
55
+ only(value, [
56
+ "folder",
57
+ "args",
58
+ "env",
59
+ "prestart",
60
+ "channels"
61
+ ], "it");
62
+ if (typeof value.folder !== "string" || value.folder === "") fail("folder must be a path");
63
+ const args = value.args ?? [];
64
+ if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string")) fail("args must be a list of strings");
65
+ if (value.prestart !== void 0 && (typeof value.prestart !== "string" || value.prestart === "")) fail("prestart must be a shell command");
66
+ const channels = {};
67
+ const listed = value.channels ?? {};
68
+ if (!isRecord(listed)) fail("channels must map names to { url, headers, arguments }");
69
+ for (const [name, channel] of Object.entries(listed)) {
70
+ if (!NAME.test(name) || RESERVED.has(name)) fail(`channel "${name}" needs a name of lowercase letters, digits and dashes, other than ${[...RESERVED].join(", ")}`);
71
+ if (!isRecord(channel)) fail(`channels.${name} must be { url, headers, arguments }`);
72
+ const entry = channel;
73
+ only(entry, [
74
+ "url",
75
+ "headers",
76
+ "arguments"
77
+ ], `channels.${name}`);
78
+ let url;
79
+ try {
80
+ url = new URL(String(entry.url));
81
+ } catch {}
82
+ if (!url || url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.has(url.hostname))) fail(`channels.${name}.url must be an https URL (http only on this Mac: localhost, 127.0.0.1, [::1])`);
83
+ const args = entry.arguments ?? {};
84
+ if (!isRecord(args) || Object.values(args).some((v) => ![
85
+ "string",
86
+ "number",
87
+ "boolean"
88
+ ].includes(typeof v))) fail(`channels.${name}.arguments must map names to strings, numbers or booleans`);
89
+ channels[name] = {
90
+ url: url.href,
91
+ headers: strings(entry.headers, `channels.${name}.headers`),
92
+ arguments: args
93
+ };
94
+ }
95
+ return {
96
+ folder: resolve(expandHome(value.folder)),
97
+ args,
98
+ env: strings(value.env, "env"),
99
+ ...value.prestart !== void 0 && { prestart: value.prestart },
100
+ channels
101
+ };
102
+ };
103
+ const readConfig = (paths) => {
104
+ if (!existsSync(paths.config)) throw new Error(`No ${paths.config}: run harnessd install`);
105
+ let raw;
106
+ try {
107
+ raw = JSON.parse(readFileSync(paths.config, "utf8"));
108
+ } catch (error) {
109
+ throw new Error(`config.json isn't JSON: ${error instanceof Error ? error.message : String(error)}`);
110
+ }
111
+ return parseConfig(raw);
112
+ };
113
+ /** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
114
+ const headersOf = (channel, env) => Object.fromEntries(Object.entries(channel.headers).map(([key, value]) => [key, value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
115
+ const found = env[name];
116
+ if (found === void 0) throw new Error(`header ${key} needs $${name}, which isn't set`);
117
+ return found;
118
+ })]));
119
+ export { DEFAULT_CONFIG, headersOf, parseConfig, pathsOf, readConfig };
120
+
121
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nexport namespace Harnessd {\n /** `config.json` in harnessd's home, read at every start of Claude Code. */\n export type Config = {\n /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */\n readonly folder: string;\n /** More arguments for `claude`. */\n readonly args: readonly string[];\n /** More environment for `claude`. */\n readonly env: Readonly<Record<string, string>>;\n /** A shell command run before each start; its stdout is JSON `{ env?, args? }` for that start. */\n readonly prestart?: string;\n /** MCP servers whose events reach the agent, by name. */\n readonly channels: Readonly<Record<string, Channel>>;\n };\n\n /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */\n export type Channel = {\n readonly url: string;\n readonly headers: Readonly<Record<string, string>>;\n /** Subscription arguments for its events, such as the board to follow; each event type takes the ones it declares. */\n readonly arguments: Readonly<Record<string, string | number | boolean>>;\n };\n\n /** Where one harnessd keeps its files. */\n export type Paths = {\n readonly home: string;\n readonly config: string;\n readonly state: string;\n readonly log: string;\n readonly socket: string;\n readonly plugin: string;\n readonly channels: string;\n readonly label: string;\n };\n}\n\nconst DEFAULT_HOME = join(homedir(), \".harnessd\");\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\nconst NAME = /^[a-z][a-z0-9-]{0,31}$/;\n// toolport's CLI keeps these words for itself\nconst RESERVED = new Set([\"stream\", \"login\", \"help\"]);\n// macOS caps a socket path at 104 bytes\nconst SOCKET_MAX = 103;\n\nexport const pathsOf = (\n env: NodeJS.ProcessEnv = process.env,\n): Harnessd.Paths => {\n const home = resolve(env.HARNESSD_HOME || DEFAULT_HOME);\n const socket = join(home, \"harnessd.sock\");\n if (Buffer.byteLength(socket) > SOCKET_MAX)\n throw new Error(`HARNESSD_HOME is too long for a socket (${socket})`);\n return {\n home,\n config: join(home, \"config.json\"),\n state: join(home, \"state.json\"),\n log: join(home, \"harnessd.log\"),\n socket,\n plugin: join(home, \"plugin\"),\n channels: join(home, \"channels\"),\n label:\n home === DEFAULT_HOME\n ? \"dev.harnessd\"\n : `dev.harnessd.${createHash(\"sha256\").update(home).digest(\"hex\").slice(0, 8)}`,\n };\n};\n\nexport const DEFAULT_CONFIG = { folder: \"~/agent\", channels: {} };\n\nconst fail = (message: string): never => {\n throw new Error(`config.json: ${message}`);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst strings = (value: unknown, what: string): Record<string, string> => {\n if (value === undefined) return {};\n if (\n !isRecord(value) ||\n Object.values(value).some((v) => typeof v !== \"string\")\n )\n fail(`${what} must map names to strings`);\n return value as Record<string, string>;\n};\n\nconst only = (\n value: Record<string, unknown>,\n keys: readonly string[],\n what: string,\n) => {\n const unknown = Object.keys(value).find((key) => !keys.includes(key));\n if (unknown !== undefined)\n fail(`${what} has no \"${unknown}\"; it takes ${keys.join(\", \")}`);\n};\n\nconst expandHome = (path: string) =>\n path === \"~\"\n ? homedir()\n : path.startsWith(\"~/\")\n ? join(homedir(), path.slice(2))\n : path;\n\nexport const parseConfig = (raw: unknown): Harnessd.Config => {\n if (!isRecord(raw)) fail(\"must be a JSON object\");\n const value = raw as Record<string, unknown>;\n only(value, [\"folder\", \"args\", \"env\", \"prestart\", \"channels\"], \"it\");\n if (typeof value.folder !== \"string\" || value.folder === \"\")\n fail(\"folder must be a path\");\n const args = value.args ?? [];\n if (!Array.isArray(args) || args.some((arg) => typeof arg !== \"string\"))\n fail(\"args must be a list of strings\");\n if (\n value.prestart !== undefined &&\n (typeof value.prestart !== \"string\" || value.prestart === \"\")\n )\n fail(\"prestart must be a shell command\");\n const channels: Record<string, Harnessd.Channel> = {};\n const listed = value.channels ?? {};\n if (!isRecord(listed))\n fail(\"channels must map names to { url, headers, arguments }\");\n for (const [name, channel] of Object.entries(\n listed as Record<string, unknown>,\n )) {\n if (!NAME.test(name) || RESERVED.has(name))\n fail(\n `channel \"${name}\" needs a name of lowercase letters, digits and dashes, other than ${[...RESERVED].join(\", \")}`,\n );\n if (!isRecord(channel))\n fail(`channels.${name} must be { url, headers, arguments }`);\n const entry = channel as Record<string, unknown>;\n only(entry, [\"url\", \"headers\", \"arguments\"], `channels.${name}`);\n let url: URL | undefined;\n try {\n url = new URL(String(entry.url));\n } catch {}\n if (\n !url ||\n (url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && LOOPBACK.has(url.hostname)))\n )\n fail(\n `channels.${name}.url must be an https URL (http only on this Mac: localhost, 127.0.0.1, [::1])`,\n );\n const args = entry.arguments ?? {};\n if (\n !isRecord(args) ||\n Object.values(args).some(\n (v) => ![\"string\", \"number\", \"boolean\"].includes(typeof v),\n )\n )\n fail(\n `channels.${name}.arguments must map names to strings, numbers or booleans`,\n );\n channels[name] = {\n url: url!.href,\n headers: strings(entry.headers, `channels.${name}.headers`),\n arguments: args as Record<string, string | number | boolean>,\n };\n }\n return {\n folder: resolve(expandHome(value.folder as string)),\n args: args as string[],\n env: strings(value.env, \"env\"),\n ...(value.prestart !== undefined && { prestart: value.prestart as string }),\n channels,\n };\n};\n\nexport const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {\n if (!existsSync(paths.config))\n throw new Error(`No ${paths.config}: run harnessd install`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(paths.config, \"utf8\"));\n } catch (error) {\n throw new Error(\n `config.json isn't JSON: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return parseConfig(raw);\n};\n\n/** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */\nexport const headersOf = (\n channel: Harnessd.Channel,\n env: NodeJS.ProcessEnv,\n): Record<string, string> =>\n Object.fromEntries(\n Object.entries(channel.headers).map(([key, value]) => [\n key,\n value.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_, name: string) => {\n const found = env[name];\n if (found === undefined)\n throw new Error(`header ${key} needs $${name}, which isn't set`);\n return found;\n }),\n ]),\n );\n"],"mappings":";;;;;AAyCA,MAAM,eAAe,KAAK,QAAQ,GAAG,WAAW;AAChD,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAC5D,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAU;CAAS;AAAM,CAAC;AAEpD,MAAM,aAAa;AAEnB,MAAa,WACX,MAAyB,QAAQ,QACd;CACnB,MAAM,OAAO,QAAQ,IAAI,iBAAiB,YAAY;CACtD,MAAM,SAAS,KAAK,MAAM,eAAe;CACzC,IAAI,OAAO,WAAW,MAAM,IAAI,YAC9B,MAAM,IAAI,MAAM,2CAA2C,OAAO,EAAE;CACtE,OAAO;E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AQ,MAAM,SAAS,YAAY,KAAK,SAAS;GAC1D,WAAW;EACb;CACF;CACA,OAAO;EACL,QAAQ,QAAQ,WAAW,MAAM,MAAgB,CAAC;EAC5C;EACN,KAAK,QAAQ,MAAM,KAAK,KAAK;EAC7B,GAAI,MAAM,aAAa,KAAA,KAAa,EAAE,UAAU,MAAM,SAAmB;EACzE;CACF;AACF;AAEA,MAAa,cAAc,UAA2C;CACpE,IAAI,CAAC,WAAW,MAAM,MAAM,GAC1B,MAAM,IAAI,MAAM,MAAM,MAAM,OAAO,uBAAuB;CAC5D,IAAI;CACJ,IAAI;EACF,MAAM,KAAK,MAAM,aAAa,MAAM,QAAQ,MAAM,CAAC;CACrD,SAAS,OAAO;EACd,MAAM,IAAI,MACR,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAClF;CACF;CACA,OAAO,YAAY,GAAG;AACxB;;AAGA,MAAa,aACX,SACA,QAEA,OAAO,YACL,OAAO,QAAQ,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CACpD,KACA,MAAM,QAAQ,oCAAoC,GAAG,SAAiB;CACpE,MAAM,QAAQ,IAAI;CAClB,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,UAAU,IAAI,UAAU,KAAK,kBAAkB;CACjE,OAAO;AACT,CAAC,CACH,CAAC,CACH"}
@@ -0,0 +1,24 @@
1
+ import { type Harnessd } from "./config.js";
2
+ import { type Watchdog } from "./watchdog.js";
3
+ export declare namespace Daemon {
4
+ /** A request on harnessd's socket: one line of JSON. An attach then streams `{ output }` lines and takes `{ input }` and `{ resize }`. */
5
+ type Request = {
6
+ readonly command: "status" | "stop" | "start";
7
+ } | {
8
+ readonly command: "new";
9
+ readonly message?: string;
10
+ } | {
11
+ readonly command: "attach";
12
+ readonly cols: number;
13
+ readonly rows: number;
14
+ };
15
+ type Status = Watchdog.Status & {
16
+ readonly daemonPid: number;
17
+ readonly folder?: string;
18
+ };
19
+ }
20
+ /** Sends one request to a running harnessd; undefined when none answers. */
21
+ export declare const ask: (socket: string, request: Daemon.Request) => Promise<Record<string, unknown> | undefined>;
22
+ /** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
23
+ export declare const runDaemon: (paths: Harnessd.Paths, bin: string) => Promise<void>;
24
+ //# sourceMappingURL=daemon.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"daemon.d.ts","sourceRoot":"","sources":["../src/daemon.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAc,KAAK,QAAQ,EAAE,oBAAiB;AAGrD,OAAO,EAAY,KAAK,QAAQ,EAAE,sBAAmB;AAErD,yBAAiB,MAAM,CAAC;IACtB,0IAA0I;IAC1I,KAAY,OAAO,GACf;QAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAA;KAAE,GACjD;QAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;QAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,GACtD;QACE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;QAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;KACvB,CAAC;IAEN,KAAY,MAAM,GAAG,QAAQ,CAAC,MAAM,GAAG;QACrC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;QAC3B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;KAC1B,CAAC;CACH;AA0BD,4EAA4E;AAC5E,eAAO,MAAM,GAAG,GAAI,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,OAAO,iDAkBvD,CAAC;AAEL,wHAAwH;AACxH,eAAO,MAAM,SAAS,GAAU,OAAO,QAAQ,CAAC,KAAK,EAAE,KAAK,MAAM,kBA4NjE,CAAC"}
package/dist/daemon.js ADDED
@@ -0,0 +1,239 @@
1
+ import { channelBlockers, claudeArgs, findTranscript, prestart, trustFolder, which, writePlugin } from "./claude.js";
2
+ import { readConfig } from "./config.js";
3
+ import { logTo } from "./log.js";
4
+ import { IDLE_SIZE, scrollback } from "./terminal.js";
5
+ import { watchdog } from "./watchdog.js";
6
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import { createConnection, createServer } from "node:net";
8
+ import { createInterface } from "node:readline";
9
+ import { dirname, join } from "node:path";
10
+ import { createRequire } from "node:module";
11
+ // src/daemon.ts
12
+ const OWN_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(ENTRYPOINT|SSE_PORT|CHILD_SESSION|SESSION_ID|HOST_SESSION_ID|MESSAGING_SOCKET|MESSAGING_TOKEN|EXECPATH))$/;
13
+ const VIEWER_BUFFER = 8388608;
14
+ const clamp = (value, min, max, fallback) => typeof value === "number" && Number.isFinite(value) ? Math.max(min, Math.min(max, Math.floor(value))) : fallback;
15
+ const loadPty = async () => {
16
+ const helper = join(dirname(createRequire(import.meta.url).resolve("node-pty/package.json")), "prebuilds", `${process.platform}-${process.arch}`, "spawn-helper");
17
+ if (existsSync(helper) && (statSync(helper).mode & 73) === 0) chmodSync(helper, 493);
18
+ return import("node-pty");
19
+ };
20
+ /** Sends one request to a running harnessd; undefined when none answers. */
21
+ const ask = (socket, request) => new Promise((resolve) => {
22
+ if (!existsSync(socket)) return resolve(void 0);
23
+ const connection = createConnection(socket);
24
+ connection.once("error", () => resolve(void 0));
25
+ connection.once("connect", () => connection.write(`${JSON.stringify(request)}\n`));
26
+ const lines = createInterface({ input: connection });
27
+ lines.once("line", (line) => {
28
+ connection.end();
29
+ try {
30
+ resolve(JSON.parse(line));
31
+ } catch {
32
+ resolve(void 0);
33
+ }
34
+ });
35
+ lines.once("close", () => resolve(void 0));
36
+ });
37
+ /** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
38
+ const runDaemon = async (paths, bin) => {
39
+ mkdirSync(paths.home, { recursive: true });
40
+ const log = logTo(paths.log);
41
+ if (await ask(paths.socket, { command: "status" })) throw new Error(`Another harnessd already runs in ${paths.home}`);
42
+ rmSync(paths.socket, { force: true });
43
+ const term = scrollback();
44
+ const viewers = /* @__PURE__ */ new Set();
45
+ let size = IDLE_SIZE;
46
+ let pty;
47
+ let folder;
48
+ const show = (data) => {
49
+ term.push(data);
50
+ const line = `${JSON.stringify({ output: data })}\n`;
51
+ for (const viewer of viewers) if (viewer.writableLength > VIEWER_BUFFER) viewer.destroy();
52
+ else viewer.write(line);
53
+ };
54
+ const state = {
55
+ read: () => {
56
+ try {
57
+ return JSON.parse(readFileSync(paths.state, "utf8"));
58
+ } catch {
59
+ return {};
60
+ }
61
+ },
62
+ write: (value) => writeFileSync(paths.state, `${JSON.stringify(value)}\n`)
63
+ };
64
+ let claudeEnv;
65
+ const transcriptEnv = () => {
66
+ if (claudeEnv) return claudeEnv;
67
+ try {
68
+ return {
69
+ ...process.env,
70
+ ...readConfig(paths).env
71
+ };
72
+ } catch {
73
+ return process.env;
74
+ }
75
+ };
76
+ const launch = async (start) => {
77
+ const config = readConfig(paths);
78
+ folder = config.folder;
79
+ mkdirSync(config.folder, { recursive: true });
80
+ const base = {
81
+ ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !OWN_ENV.test(key))),
82
+ ...config.env,
83
+ HARNESSD_HOME: paths.home
84
+ };
85
+ const hook = config.prestart ? await prestart(config.prestart, config.folder, base, log) : {
86
+ env: {},
87
+ args: []
88
+ };
89
+ const env = {
90
+ ...base,
91
+ ...hook.env
92
+ };
93
+ claudeEnv = env;
94
+ if (!trustFolder(config.folder, env)) log("Claude Code has no settings yet: harnessd attach, then sign in and trust the folder");
95
+ const plugin = writePlugin(paths, config, bin) ? paths.plugin : void 0;
96
+ const blockers = plugin ? channelBlockers() : [];
97
+ if (blockers.length > 0) log(`Claude Code won't let the channels in: ${blockers.join("; ")} (harnessd install lets them in)`);
98
+ const file = which("claude", env.PATH);
99
+ const { spawn } = await loadPty();
100
+ const p = spawn(file, claudeArgs({
101
+ start,
102
+ plugin,
103
+ allowed: blockers.length === 0,
104
+ config,
105
+ extra: hook.args
106
+ }), {
107
+ name: "xterm-256color",
108
+ cols: size.cols,
109
+ rows: size.rows,
110
+ cwd: config.folder,
111
+ env
112
+ });
113
+ pty = p;
114
+ show(`\r\n\x1b[2m── harnessd started Claude Code ${(/* @__PURE__ */ new Date()).toLocaleString()} ──\x1b[0m\r\n`);
115
+ p.onData(show);
116
+ const exited = new Promise((resolve) => p.onExit(({ exitCode, signal }) => {
117
+ if (pty === p) pty = void 0;
118
+ resolve(signal ? 128 + signal : exitCode);
119
+ }));
120
+ return {
121
+ pid: p.pid,
122
+ exited,
123
+ kill: (signal) => {
124
+ try {
125
+ p.kill(signal);
126
+ } catch {}
127
+ }
128
+ };
129
+ };
130
+ const resize = (cols, rows) => {
131
+ if (cols === size.cols && rows === size.rows) return;
132
+ size = {
133
+ cols,
134
+ rows
135
+ };
136
+ try {
137
+ pty?.resize(cols, rows);
138
+ } catch {}
139
+ };
140
+ const dog = watchdog({
141
+ launch,
142
+ state,
143
+ hasTranscript: (id) => findTranscript(id, transcriptEnv()) !== void 0,
144
+ log
145
+ });
146
+ const status = () => ({
147
+ ...dog.status(),
148
+ daemonPid: process.pid,
149
+ ...folder && { folder }
150
+ });
151
+ const serve = (connection) => {
152
+ const reply = (value) => connection.end(`${JSON.stringify(value)}\n`);
153
+ const lines = createInterface({ input: connection });
154
+ let attached = false;
155
+ connection.on("error", () => {});
156
+ lines.on("line", async (line) => {
157
+ let message;
158
+ try {
159
+ message = JSON.parse(line);
160
+ } catch {
161
+ reply({
162
+ ok: false,
163
+ message: "Not JSON."
164
+ });
165
+ return;
166
+ }
167
+ if (attached) {
168
+ if (typeof message.input === "string") pty?.write(message.input);
169
+ const asked = message.resize;
170
+ if (asked) resize(clamp(asked.cols, 20, 500, size.cols), clamp(asked.rows, 5, 300, size.rows));
171
+ return;
172
+ }
173
+ const request = message;
174
+ if (request.command === "status") return void reply({
175
+ ok: true,
176
+ status: status()
177
+ });
178
+ if (request.command === "stop") return void reply({
179
+ ok: true,
180
+ message: await dog.stop()
181
+ });
182
+ if (request.command === "start") return void reply({
183
+ ok: true,
184
+ message: await dog.start()
185
+ });
186
+ if (request.command === "new") {
187
+ if (request.message !== void 0 && typeof request.message !== "string") return void reply({
188
+ ok: false,
189
+ message: "message must be text."
190
+ });
191
+ reply({
192
+ ok: true,
193
+ message: await dog.fresh(request.message)
194
+ });
195
+ return;
196
+ }
197
+ if (request.command === "attach") {
198
+ attached = true;
199
+ viewers.add(connection);
200
+ resize(clamp(request.cols, 20, 500, IDLE_SIZE.cols), clamp(request.rows, 5, 300, IDLE_SIZE.rows));
201
+ connection.write(`${JSON.stringify({ output: term.read() })}\n`);
202
+ connection.on("close", () => {
203
+ viewers.delete(connection);
204
+ if (viewers.size === 0) resize(IDLE_SIZE.cols, IDLE_SIZE.rows);
205
+ });
206
+ return;
207
+ }
208
+ reply({
209
+ ok: false,
210
+ message: `Unknown command ${String(request.command)}.`
211
+ });
212
+ });
213
+ };
214
+ const server = createServer(serve);
215
+ await new Promise((resolve, reject) => {
216
+ server.once("error", reject);
217
+ server.listen(paths.socket, resolve);
218
+ });
219
+ log(`harnessd ${process.pid} started`);
220
+ let stopping = false;
221
+ const shutdown = async (signal) => {
222
+ if (stopping) return;
223
+ stopping = true;
224
+ log(`harnessd got ${signal}; stopping Claude Code`);
225
+ await dog.shutdown();
226
+ for (const viewer of viewers) viewer.end();
227
+ server.close();
228
+ rmSync(paths.socket, { force: true });
229
+ log(`harnessd ${process.pid} stopped`);
230
+ process.exit(0);
231
+ };
232
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));
233
+ process.on("SIGINT", () => void shutdown("SIGINT"));
234
+ process.on("SIGHUP", () => void shutdown("SIGHUP"));
235
+ await dog.run();
236
+ };
237
+ export { ask, runDaemon };
238
+
239
+ //# sourceMappingURL=daemon.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"daemon.js","names":[],"sources":["../src/daemon.ts"],"sourcesContent":["import {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { createConnection, createServer, type Socket } from \"node:net\";\nimport { dirname, join } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { IPty } from \"node-pty\";\nimport {\n channelBlockers,\n claudeArgs,\n findTranscript,\n prestart,\n trustFolder,\n which,\n writePlugin,\n} from \"./claude\";\nimport { readConfig, type Harnessd } from \"./config\";\nimport { logTo } from \"./log\";\nimport { IDLE_SIZE, scrollback } from \"./terminal\";\nimport { watchdog, type Watchdog } from \"./watchdog\";\n\nexport namespace Daemon {\n /** A request on harnessd's socket: one line of JSON. An attach then streams `{ output }` lines and takes `{ input }` and `{ resize }`. */\n export type Request =\n | { readonly command: \"status\" | \"stop\" | \"start\" }\n | { readonly command: \"new\"; readonly message?: string }\n | {\n readonly command: \"attach\";\n readonly cols: number;\n readonly rows: number;\n };\n\n export type Status = Watchdog.Status & {\n readonly daemonPid: number;\n readonly folder?: string;\n };\n}\n\n// a Claude Code session's own markers, which the agent's session must not inherit\nconst OWN_ENV =\n /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(ENTRYPOINT|SSE_PORT|CHILD_SESSION|SESSION_ID|HOST_SESSION_ID|MESSAGING_SOCKET|MESSAGING_TOKEN|EXECPATH))$/;\n\nconst VIEWER_BUFFER = 8 * 1024 * 1024;\n\nconst clamp = (value: unknown, min: number, max: number, fallback: number) =>\n typeof value === \"number\" && Number.isFinite(value)\n ? Math.max(min, Math.min(max, Math.floor(value)))\n : fallback;\n\n// node-pty's prebuilt spawn-helper ships without its executable bit; its install script, which pnpm skips, sets it\nconst loadPty = async () => {\n const helper = join(\n dirname(createRequire(import.meta.url).resolve(\"node-pty/package.json\")),\n \"prebuilds\",\n `${process.platform}-${process.arch}`,\n \"spawn-helper\",\n );\n if (existsSync(helper) && (statSync(helper).mode & 0o111) === 0)\n chmodSync(helper, 0o755);\n return import(\"node-pty\");\n};\n\n/** Sends one request to a running harnessd; undefined when none answers. */\nexport const ask = (socket: string, request: Daemon.Request) =>\n new Promise<Record<string, unknown> | undefined>((resolve) => {\n if (!existsSync(socket)) return resolve(undefined);\n const connection = createConnection(socket);\n connection.once(\"error\", () => resolve(undefined));\n connection.once(\"connect\", () =>\n connection.write(`${JSON.stringify(request)}\\n`),\n );\n const lines = createInterface({ input: connection });\n lines.once(\"line\", (line) => {\n connection.end();\n try {\n resolve(JSON.parse(line));\n } catch {\n resolve(undefined);\n }\n });\n lines.once(\"close\", () => resolve(undefined));\n });\n\n/** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */\nexport const runDaemon = async (paths: Harnessd.Paths, bin: string) => {\n mkdirSync(paths.home, { recursive: true });\n const log = logTo(paths.log);\n if (await ask(paths.socket, { command: \"status\" }))\n throw new Error(`Another harnessd already runs in ${paths.home}`);\n rmSync(paths.socket, { force: true });\n\n const term = scrollback();\n const viewers = new Set<Socket>();\n let size = IDLE_SIZE;\n let pty: IPty | undefined;\n let folder: string | undefined;\n const show = (data: string) => {\n term.push(data);\n const line = `${JSON.stringify({ output: data })}\\n`;\n for (const viewer of viewers) {\n // a viewer that stops reading is let go rather than buffered without end\n if (viewer.writableLength > VIEWER_BUFFER) viewer.destroy();\n else viewer.write(line);\n }\n };\n\n const state = {\n read: (): Watchdog.State => {\n try {\n return JSON.parse(readFileSync(paths.state, \"utf8\")) as Watchdog.State;\n } catch {\n return {};\n }\n },\n write: (value: Watchdog.State) =>\n writeFileSync(paths.state, `${JSON.stringify(value)}\\n`),\n };\n\n // what Claude Code last ran with (before its first start: the config's env): its CLAUDE_CONFIG_DIR says where its transcripts are\n let claudeEnv: NodeJS.ProcessEnv | undefined;\n const transcriptEnv = (): NodeJS.ProcessEnv => {\n if (claudeEnv) return claudeEnv;\n try {\n return { ...process.env, ...readConfig(paths).env };\n } catch {\n return process.env;\n }\n };\n const launch = async (start: Watchdog.Start): Promise<Watchdog.Run> => {\n const config = readConfig(paths);\n folder = config.folder;\n mkdirSync(config.folder, { recursive: true });\n const inherited = Object.fromEntries(\n Object.entries(process.env).filter(([key]) => !OWN_ENV.test(key)),\n ) as Record<string, string>;\n const base: Record<string, string> = {\n ...inherited,\n ...config.env,\n HARNESSD_HOME: paths.home,\n };\n const hook = config.prestart\n ? await prestart(config.prestart, config.folder, base, log)\n : { env: {}, args: [] };\n const env = { ...base, ...hook.env };\n claudeEnv = env;\n if (!trustFolder(config.folder, env))\n log(\n \"Claude Code has no settings yet: harnessd attach, then sign in and trust the folder\",\n );\n const plugin = writePlugin(paths, config, bin) ? paths.plugin : undefined;\n const blockers = plugin ? channelBlockers() : [];\n if (blockers.length > 0)\n log(\n `Claude Code won't let the channels in: ${blockers.join(\"; \")} (harnessd install lets them in)`,\n );\n const file = which(\"claude\", env.PATH);\n const { spawn } = await loadPty();\n const p = spawn(\n file,\n claudeArgs({\n start,\n plugin,\n allowed: blockers.length === 0,\n config,\n extra: hook.args,\n }),\n {\n name: \"xterm-256color\",\n cols: size.cols,\n rows: size.rows,\n cwd: config.folder,\n env,\n },\n );\n pty = p;\n show(\n `\\r\\n\\x1b[2m── harnessd started Claude Code ${new Date().toLocaleString()} ──\\x1b[0m\\r\\n`,\n );\n p.onData(show);\n const exited = new Promise<number>((resolve) =>\n p.onExit(({ exitCode, signal }) => {\n if (pty === p) pty = undefined;\n resolve(signal ? 128 + signal : exitCode);\n }),\n );\n return {\n pid: p.pid,\n exited,\n kill: (signal) => {\n try {\n p.kill(signal);\n } catch {}\n },\n };\n };\n\n const resize = (cols: number, rows: number) => {\n if (cols === size.cols && rows === size.rows) return;\n size = { cols, rows };\n try {\n pty?.resize(cols, rows);\n } catch {}\n };\n\n const dog = watchdog({\n launch,\n state,\n hasTranscript: (id) => findTranscript(id, transcriptEnv()) !== undefined,\n log,\n });\n\n const status = (): Daemon.Status => ({\n ...dog.status(),\n daemonPid: process.pid,\n ...(folder && { folder }),\n });\n\n const serve = (connection: Socket) => {\n const reply = (value: unknown) =>\n connection.end(`${JSON.stringify(value)}\\n`);\n const lines = createInterface({ input: connection });\n let attached = false;\n connection.on(\"error\", () => {});\n lines.on(\"line\", async (line): Promise<void> => {\n let message: Record<string, unknown>;\n try {\n message = JSON.parse(line);\n } catch {\n return void reply({ ok: false, message: \"Not JSON.\" });\n }\n if (attached) {\n if (typeof message.input === \"string\") pty?.write(message.input);\n const asked = message.resize as\n | { cols?: unknown; rows?: unknown }\n | undefined;\n if (asked)\n resize(\n clamp(asked.cols, 20, 500, size.cols),\n clamp(asked.rows, 5, 300, size.rows),\n );\n return;\n }\n const request = message as Daemon.Request;\n if (request.command === \"status\")\n return void reply({ ok: true, status: status() });\n if (request.command === \"stop\")\n return void reply({ ok: true, message: await dog.stop() });\n if (request.command === \"start\")\n return void reply({ ok: true, message: await dog.start() });\n if (request.command === \"new\") {\n if (\n request.message !== undefined &&\n typeof request.message !== \"string\"\n )\n return void reply({ ok: false, message: \"message must be text.\" });\n return void reply({\n ok: true,\n message: await dog.fresh(request.message),\n });\n }\n if (request.command === \"attach\") {\n attached = true;\n viewers.add(connection);\n resize(\n clamp(request.cols, 20, 500, IDLE_SIZE.cols),\n clamp(request.rows, 5, 300, IDLE_SIZE.rows),\n );\n connection.write(`${JSON.stringify({ output: term.read() })}\\n`);\n connection.on(\"close\", () => {\n viewers.delete(connection);\n if (viewers.size === 0) resize(IDLE_SIZE.cols, IDLE_SIZE.rows);\n });\n return;\n }\n reply({\n ok: false,\n message: `Unknown command ${String((request as { command?: unknown }).command)}.`,\n });\n });\n };\n\n const server = createServer(serve);\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(paths.socket, resolve);\n });\n log(`harnessd ${process.pid} started`);\n\n let stopping = false;\n const shutdown = async (signal: string) => {\n if (stopping) return;\n stopping = true;\n log(`harnessd got ${signal}; stopping Claude Code`);\n await dog.shutdown();\n for (const viewer of viewers) viewer.end();\n server.close();\n rmSync(paths.socket, { force: true });\n log(`harnessd ${process.pid} stopped`);\n process.exit(0);\n };\n process.on(\"SIGTERM\", () => void shutdown(\"SIGTERM\"));\n process.on(\"SIGINT\", () => void shutdown(\"SIGINT\"));\n process.on(\"SIGHUP\", () => void shutdown(\"SIGHUP\"));\n await dog.run();\n};\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,UACJ;AAEF,MAAM,gBAAgB;AAEtB,MAAM,SAAS,OAAgB,KAAa,KAAa,aACvD,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAC9C,KAAK,IAAI,KAAK,KAAK,IAAI,KAAK,KAAK,MAAM,KAAK,CAAC,CAAC,IAC9C;AAGN,MAAM,UAAU,YAAY;CAC1B,MAAM,SAAS,KACb,QAAQ,cAAc,YAAY,GAAG,CAAC,CAAC,QAAQ,uBAAuB,CAAC,GACvE,aACA,GAAG,QAAQ,SAAS,GAAG,QAAQ,QAC/B,cACF;CACA,IAAI,WAAW,MAAM,MAAM,SAAS,MAAM,CAAC,CAAC,OAAO,QAAW,GAC5D,UAAU,QAAQ,GAAK;CACzB,OAAO,OAAO;AAChB;;AAGA,MAAa,OAAO,QAAgB,YAClC,IAAI,SAA8C,YAAY;CAC5D,IAAI,CAAC,WAAW,MAAM,GAAG,OAAO,QAAQ,KAAA,CAAS;CACjD,MAAM,aAAa,iBAAiB,MAAM;CAC1C,WAAW,KAAK,eAAe,QAAQ,KAAA,CAAS,CAAC;CACjD,WAAW,KAAK,iBACd,WAAW,MAAM,GAAG,KAAK,UAAU,OAAO,EAAE,GAAG,CACjD;CACA,MAAM,QAAQ,gBAAgB,EAAE,OAAO,WAAW,CAAC;CACnD,MAAM,KAAK,SAAS,SAAS;EAC3B,WAAW,IAAI;EACf,IAAI;GACF,QAAQ,KAAK,MAAM,IAAI,CAAC;EAC1B,QAAQ;GACN,QAAQ,KAAA,CAAS;EACnB;CACF,CAAC;CACD,MAAM,K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Q,IAAI,SAAS;EACrC,QAAQ,KAAK,CAAC;CAChB;CACA,QAAQ,GAAG,iBAAiB,KAAK,SAAS,SAAS,CAAC;CACpD,QAAQ,GAAG,gBAAgB,KAAK,SAAS,QAAQ,CAAC;CAClD,QAAQ,GAAG,gBAAgB,KAAK,SAAS,QAAQ,CAAC;CAClD,MAAM,IAAI,IAAI;AAChB"}
@@ -0,0 +1,22 @@
1
+ import type { Harnessd } from "./config.js";
2
+ /**
3
+ * The node the LaunchAgent starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
4
+ * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
5
+ * harnessd unable to start. None that is this one: `process.execPath`.
6
+ */
7
+ export declare const stableNode: (execPath?: string, path?: string) => string;
8
+ export declare const plistPath: (label: string) => string;
9
+ /** The LaunchAgent: `node <bin> run` at login and after any exit. */
10
+ export declare const plistOf: (o: {
11
+ label: string;
12
+ node: string;
13
+ bin: string;
14
+ env: Readonly<Record<string, string>>;
15
+ paths: Harnessd.Paths;
16
+ }) => string;
17
+ export declare const loaded: (label: string) => boolean;
18
+ /** Writes the LaunchAgent and (re)loads it, which starts harnessd. */
19
+ export declare const load: (label: string, plist: string) => void;
20
+ /** Stops harnessd (it stops Claude Code first) and removes the LaunchAgent. */
21
+ export declare const unload: (label: string) => boolean;
22
+ //# sourceMappingURL=launchd.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launchd.d.ts","sourceRoot":"","sources":["../src/launchd.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,QAAQ,EAAE,oBAAiB;AAKzC;;;;GAIG;AACH,eAAO,MAAM,UAAU,GACrB,iBAA2B,EAC3B,aAA6B,WAiB9B,CAAC;AAEF,eAAO,MAAM,SAAS,GAAI,OAAO,MAAM,WACuB,CAAC;AAE/D,qEAAqE;AACrE,eAAO,MAAM,OAAO,GAAI,GAAG;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACtC,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC;CACvB,WAqCA,CAAC;AAOF,eAAO,MAAM,MAAM,GAAI,OAAO,MAAM,YACqB,CAAC;AAE1D,sEAAsE;AACtE,eAAO,MAAM,IAAI,GAAI,OAAO,MAAM,EAAE,OAAO,MAAM,SAShD,CAAC;AAEF,+EAA+E;AAC/E,eAAO,MAAM,MAAM,GAAI,OAAO,MAAM,YAYnC,CAAC"}
@@ -0,0 +1,88 @@
1
+ import { accessSync, constants, existsSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
+ import { spawnSync } from "node:child_process";
3
+ import { homedir } from "node:os";
4
+ import { delimiter, join } from "node:path";
5
+ // src/launchd.ts
6
+ const xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
7
+ /**
8
+ * The node the LaunchAgent starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
9
+ * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
10
+ * harnessd unable to start. None that is this one: `process.execPath`.
11
+ */
12
+ const stableNode = (execPath = process.execPath, path = process.env.PATH ?? "") => {
13
+ let real;
14
+ try {
15
+ real = realpathSync(execPath);
16
+ } catch {
17
+ return execPath;
18
+ }
19
+ for (const dir of path.split(delimiter)) {
20
+ if (!dir.startsWith("/")) continue;
21
+ const candidate = join(dir, "node");
22
+ try {
23
+ accessSync(candidate, constants.X_OK);
24
+ if (realpathSync(candidate) === real) return candidate;
25
+ } catch {}
26
+ }
27
+ return execPath;
28
+ };
29
+ const plistPath = (label) => join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
30
+ /** The LaunchAgent: `node <bin> run` at login and after any exit. */
31
+ const plistOf = (o) => `<?xml version="1.0" encoding="UTF-8"?>
32
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
33
+ <plist version="1.0">
34
+ <dict>
35
+ <key>Label</key>
36
+ <string>${xml(o.label)}</string>
37
+ <key>ProgramArguments</key>
38
+ <array>
39
+ <string>${xml(o.node)}</string>
40
+ <string>${xml(o.bin)}</string>
41
+ <string>run</string>
42
+ </array>
43
+ <key>EnvironmentVariables</key>
44
+ <dict>
45
+ ${Object.entries(o.env).map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join("\n")}
46
+ </dict>
47
+ <key>WorkingDirectory</key>
48
+ <string>${xml(o.paths.home)}</string>
49
+ <key>RunAtLoad</key>
50
+ <true/>
51
+ <key>KeepAlive</key>
52
+ <true/>
53
+ <key>ExitTimeOut</key>
54
+ <integer>30</integer>
55
+ <key>ProcessType</key>
56
+ <string>Interactive</string>
57
+ <key>StandardOutPath</key>
58
+ <string>${xml(join(o.paths.home, "launchd.log"))}</string>
59
+ <key>StandardErrorPath</key>
60
+ <string>${xml(join(o.paths.home, "launchd.log"))}</string>
61
+ </dict>
62
+ </plist>
63
+ `;
64
+ const domain = () => `gui/${process.getuid()}`;
65
+ const launchctl = (...args) => spawnSync("launchctl", args, { encoding: "utf8" });
66
+ const loaded = (label) => launchctl("print", `${domain()}/${label}`).status === 0;
67
+ /** Writes the LaunchAgent and (re)loads it, which starts harnessd. */
68
+ const load = (label, plist) => {
69
+ mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
70
+ if (loaded(label)) launchctl("bootout", `${domain()}/${label}`);
71
+ writeFileSync(plistPath(label), plist);
72
+ const result = launchctl("bootstrap", domain(), plistPath(label));
73
+ if (result.status !== 0) throw new Error(`launchctl bootstrap failed: ${(result.stderr || result.stdout).trim()}`);
74
+ };
75
+ /** Stops harnessd (it stops Claude Code first) and removes the LaunchAgent. */
76
+ const unload = (label) => {
77
+ if (loaded(label)) {
78
+ const result = launchctl("bootout", `${domain()}/${label}`);
79
+ if (result.status !== 0) throw new Error(`launchctl bootout failed: ${(result.stderr || result.stdout).trim()}`);
80
+ }
81
+ const plist = plistPath(label);
82
+ const had = existsSync(plist);
83
+ rmSync(plist, { force: true });
84
+ return had;
85
+ };
86
+ export { load, loaded, plistOf, plistPath, stableNode, unload };
87
+
88
+ //# sourceMappingURL=launchd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"launchd.js","names":[],"sources":["../src/launchd.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n mkdirSync,\n realpathSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport type { Harnessd } from \"./config\";\n\nconst xml = (value: string) =>\n value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\n/**\n * The node the LaunchAgent starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's\n * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave\n * harnessd unable to start. None that is this one: `process.execPath`.\n */\nexport const stableNode = (\n execPath = process.execPath,\n path = process.env.PATH ?? \"\",\n) => {\n let real: string;\n try {\n real = realpathSync(execPath);\n } catch {\n return execPath;\n }\n for (const dir of path.split(delimiter)) {\n if (!dir.startsWith(\"/\")) continue;\n const candidate = join(dir, \"node\");\n try {\n accessSync(candidate, constants.X_OK);\n if (realpathSync(candidate) === real) return candidate;\n } catch {}\n }\n return execPath;\n};\n\nexport const plistPath = (label: string) =>\n join(homedir(), \"Library\", \"LaunchAgents\", `${label}.plist`);\n\n/** The LaunchAgent: `node <bin> run` at login and after any exit. */\nexport const plistOf = (o: {\n label: string;\n node: string;\n bin: string;\n env: Readonly<Record<string, string>>;\n paths: Harnessd.Paths;\n}) => `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n <key>Label</key>\n <string>${xml(o.label)}</string>\n <key>ProgramArguments</key>\n <array>\n <string>${xml(o.node)}</string>\n <string>${xml(o.bin)}</string>\n <string>run</string>\n </array>\n <key>EnvironmentVariables</key>\n <dict>\n${Object.entries(o.env)\n .map(\n ([key, value]) =>\n ` <key>${xml(key)}</key>\\n <string>${xml(value)}</string>`,\n )\n .join(\"\\n\")}\n </dict>\n <key>WorkingDirectory</key>\n <string>${xml(o.paths.home)}</string>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>ExitTimeOut</key>\n <integer>30</integer>\n <key>ProcessType</key>\n <string>Interactive</string>\n <key>StandardOutPath</key>\n <string>${xml(join(o.paths.home, \"launchd.log\"))}</string>\n <key>StandardErrorPath</key>\n <string>${xml(join(o.paths.home, \"launchd.log\"))}</string>\n</dict>\n</plist>\n`;\n\nconst domain = () => `gui/${process.getuid!()}`;\n\nconst launchctl = (...args: string[]) =>\n spawnSync(\"launchctl\", args, { encoding: \"utf8\" });\n\nexport const loaded = (label: string) =>\n launchctl(\"print\", `${domain()}/${label}`).status === 0;\n\n/** Writes the LaunchAgent and (re)loads it, which starts harnessd. */\nexport const load = (label: string, plist: string) => {\n mkdirSync(join(homedir(), \"Library\", \"LaunchAgents\"), { recursive: true });\n if (loaded(label)) launchctl(\"bootout\", `${domain()}/${label}`);\n writeFileSync(plistPath(label), plist);\n const result = launchctl(\"bootstrap\", domain(), plistPath(label));\n if (result.status !== 0)\n throw new Error(\n `launchctl bootstrap failed: ${(result.stderr || result.stdout).trim()}`,\n );\n};\n\n/** Stops harnessd (it stops Claude Code first) and removes the LaunchAgent. */\nexport const unload = (label: string) => {\n if (loaded(label)) {\n const result = launchctl(\"bootout\", `${domain()}/${label}`);\n if (result.status !== 0)\n throw new Error(\n `launchctl bootout failed: ${(result.stderr || result.stdout).trim()}`,\n );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EnD,MAAa,UAAU,UACrB,UAAU,SAAS,GAAG,OAAO,EAAE,GAAG,OAAO,CAAC,CAAC,WAAW;;AAGxD,MAAa,QAAQ,OAAe,UAAkB;CACpD,UAAU,KAAK,QAAQ,GAAG,WAAW,cAAc,GAAG,EAAE,WAAW,KAAK,CAAC;CACzE,IAAI,OAAO,KAAK,GAAG,UAAU,WAAW,GAAG,OAAO,EAAE,GAAG,OAAO;CAC9D,cAAc,UAAU,KAAK,GAAG,KAAK;CACrC,MAAM,SAAS,UAAU,aAAa,OAAO,GAAG,UAAU,KAAK,CAAC;CAChE,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MACR,gCAAgC,OAAO,UAAU,OAAO,OAAA,CAAQ,KAAK,GACvE;AACJ;;AAGA,MAAa,UAAU,UAAkB;CACvC,IAAI,OAAO,KAAK,GAAG;EACjB,MAAM,SAAS,UAAU,WAAW,GAAG,OAAO,EAAE,GAAG,OAAO;EAC1D,IAAI,OAAO,WAAW,GACpB,MAAM,IAAI,MACR,8BAA8B,OAAO,UAAU,OAAO,OAAA,CAAQ,KAAK,GACrE;CACJ;CACA,MAAM,QAAQ,UAAU,KAAK;CAC7B,MAAM,MAAM,WAAW,KAAK;CAC5B,OAAO,OAAO,EAAE,OAAO,KAAK,CAAC;CAC7B,OAAO;AACT"}
package/dist/log.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** Appends timestamped lines to `file`, keeping one older file (`.1`) past 5 MB. */
2
+ export declare const logTo: (file: string, prefix?: string) => (line: string) => void;
3
+ //# sourceMappingURL=log.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.d.ts","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":"AAKA,oFAAoF;AACpF,eAAO,MAAM,KAAK,GACf,MAAM,MAAM,EAAE,eAAW,MACzB,MAAM,MAAM,SAQZ,CAAC"}
package/dist/log.js ADDED
@@ -0,0 +1,17 @@
1
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ // src/log.ts
4
+ const MAX_BYTES = 5242880;
5
+ /** Appends timestamped lines to `file`, keeping one older file (`.1`) past 5 MB. */
6
+ const logTo = (file, prefix = "") => (line) => {
7
+ try {
8
+ mkdirSync(dirname(file), { recursive: true });
9
+ try {
10
+ if (statSync(file).size > MAX_BYTES) renameSync(file, `${file}.1`);
11
+ } catch {}
12
+ appendFileSync(file, `${(/* @__PURE__ */ new Date()).toISOString()} ${prefix}${line}\n`);
13
+ } catch {}
14
+ };
15
+ export { logTo };
16
+
17
+ //# sourceMappingURL=log.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log.js","names":[],"sources":["../src/log.ts"],"sourcesContent":["import { appendFileSync, mkdirSync, renameSync, statSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nconst MAX_BYTES = 5 * 1024 * 1024;\n\n/** Appends timestamped lines to `file`, keeping one older file (`.1`) past 5 MB. */\nexport const logTo =\n (file: string, prefix = \"\") =>\n (line: string) => {\n try {\n mkdirSync(dirname(file), { recursive: true });\n try {\n if (statSync(file).size > MAX_BYTES) renameSync(file, `${file}.1`);\n } catch {}\n appendFileSync(file, `${new Date().toISOString()} ${prefix}${line}\\n`);\n } catch {}\n };\n"],"mappings":";;;AAGA,MAAM,YAAY;;AAGlB,MAAa,SACV,MAAc,SAAS,QACvB,SAAiB;CAChB,IAAI;EACF,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;EAC5C,IAAI;GACF,IAAI,SAAS,IAAI,CAAC,CAAC,OAAO,WAAW,WAAW,MAAM,GAAG,KAAK,GAAG;EACnE,QAAQ,CAAC;EACT,eAAe,MAAM,oBAAG,IAAI,KAAK,EAAA,CAAE,YAAY,EAAE,GAAG,SAAS,KAAK,GAAG;CACvE,QAAQ,CAAC;AACX"}
@@ -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"}