@harness-sdk/harnessd 0.0.0-stage → 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 +54 -4
  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/src/config.ts ADDED
@@ -0,0 +1,203 @@
1
+ import { createHash } from "node:crypto";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+
6
+ export namespace Harnessd {
7
+ /** `config.json` in harnessd's home, read at every start of Claude Code. */
8
+ export type Config = {
9
+ /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */
10
+ readonly folder: string;
11
+ /** More arguments for `claude`. */
12
+ readonly args: readonly string[];
13
+ /** More environment for `claude`. */
14
+ readonly env: Readonly<Record<string, string>>;
15
+ /** A shell command run before each start; its stdout is JSON `{ env?, args? }` for that start. */
16
+ readonly prestart?: string;
17
+ /** MCP servers whose events reach the agent, by name. */
18
+ readonly channels: Readonly<Record<string, Channel>>;
19
+ };
20
+
21
+ /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */
22
+ export type Channel = {
23
+ readonly url: string;
24
+ readonly headers: Readonly<Record<string, string>>;
25
+ /** Subscription arguments for its events, such as the board to follow; each event type takes the ones it declares. */
26
+ readonly arguments: Readonly<Record<string, string | number | boolean>>;
27
+ };
28
+
29
+ /** Where one harnessd keeps its files. */
30
+ export type Paths = {
31
+ readonly home: string;
32
+ readonly config: string;
33
+ readonly state: string;
34
+ readonly log: string;
35
+ readonly socket: string;
36
+ readonly plugin: string;
37
+ readonly channels: string;
38
+ readonly label: string;
39
+ };
40
+ }
41
+
42
+ const DEFAULT_HOME = join(homedir(), ".harnessd");
43
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
44
+ const NAME = /^[a-z][a-z0-9-]{0,31}$/;
45
+ // toolport's CLI keeps these words for itself
46
+ const RESERVED = new Set(["stream", "login", "help"]);
47
+ // macOS caps a socket path at 104 bytes
48
+ const SOCKET_MAX = 103;
49
+
50
+ export const pathsOf = (
51
+ env: NodeJS.ProcessEnv = process.env,
52
+ ): Harnessd.Paths => {
53
+ const home = resolve(env.HARNESSD_HOME || DEFAULT_HOME);
54
+ const socket = join(home, "harnessd.sock");
55
+ if (Buffer.byteLength(socket) > SOCKET_MAX)
56
+ throw new Error(`HARNESSD_HOME is too long for a socket (${socket})`);
57
+ return {
58
+ home,
59
+ config: join(home, "config.json"),
60
+ state: join(home, "state.json"),
61
+ log: join(home, "harnessd.log"),
62
+ socket,
63
+ plugin: join(home, "plugin"),
64
+ channels: join(home, "channels"),
65
+ label:
66
+ home === DEFAULT_HOME
67
+ ? "dev.harnessd"
68
+ : `dev.harnessd.${createHash("sha256").update(home).digest("hex").slice(0, 8)}`,
69
+ };
70
+ };
71
+
72
+ export const DEFAULT_CONFIG = { folder: "~/agent", channels: {} };
73
+
74
+ const fail = (message: string): never => {
75
+ throw new Error(`config.json: ${message}`);
76
+ };
77
+
78
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
79
+ typeof value === "object" && value !== null && !Array.isArray(value);
80
+
81
+ const strings = (value: unknown, what: string): Record<string, string> => {
82
+ if (value === undefined) return {};
83
+ if (
84
+ !isRecord(value) ||
85
+ Object.values(value).some((v) => typeof v !== "string")
86
+ )
87
+ fail(`${what} must map names to strings`);
88
+ return value as Record<string, string>;
89
+ };
90
+
91
+ const only = (
92
+ value: Record<string, unknown>,
93
+ keys: readonly string[],
94
+ what: string,
95
+ ) => {
96
+ const unknown = Object.keys(value).find((key) => !keys.includes(key));
97
+ if (unknown !== undefined)
98
+ fail(`${what} has no "${unknown}"; it takes ${keys.join(", ")}`);
99
+ };
100
+
101
+ const expandHome = (path: string) =>
102
+ path === "~"
103
+ ? homedir()
104
+ : path.startsWith("~/")
105
+ ? join(homedir(), path.slice(2))
106
+ : path;
107
+
108
+ export const parseConfig = (raw: unknown): Harnessd.Config => {
109
+ if (!isRecord(raw)) fail("must be a JSON object");
110
+ const value = raw as Record<string, unknown>;
111
+ only(value, ["folder", "args", "env", "prestart", "channels"], "it");
112
+ if (typeof value.folder !== "string" || value.folder === "")
113
+ fail("folder must be a path");
114
+ const args = value.args ?? [];
115
+ if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string"))
116
+ fail("args must be a list of strings");
117
+ if (
118
+ value.prestart !== undefined &&
119
+ (typeof value.prestart !== "string" || value.prestart === "")
120
+ )
121
+ fail("prestart must be a shell command");
122
+ const channels: Record<string, Harnessd.Channel> = {};
123
+ const listed = value.channels ?? {};
124
+ if (!isRecord(listed))
125
+ fail("channels must map names to { url, headers, arguments }");
126
+ for (const [name, channel] of Object.entries(
127
+ listed as Record<string, unknown>,
128
+ )) {
129
+ if (!NAME.test(name) || RESERVED.has(name))
130
+ fail(
131
+ `channel "${name}" needs a name of lowercase letters, digits and dashes, other than ${[...RESERVED].join(", ")}`,
132
+ );
133
+ if (!isRecord(channel))
134
+ fail(`channels.${name} must be { url, headers, arguments }`);
135
+ const entry = channel as Record<string, unknown>;
136
+ only(entry, ["url", "headers", "arguments"], `channels.${name}`);
137
+ let url: URL | undefined;
138
+ try {
139
+ url = new URL(String(entry.url));
140
+ } catch {}
141
+ if (
142
+ !url ||
143
+ (url.protocol !== "https:" &&
144
+ !(url.protocol === "http:" && LOOPBACK.has(url.hostname)))
145
+ )
146
+ fail(
147
+ `channels.${name}.url must be an https URL (http only on this Mac: localhost, 127.0.0.1, [::1])`,
148
+ );
149
+ const args = entry.arguments ?? {};
150
+ if (
151
+ !isRecord(args) ||
152
+ Object.values(args).some(
153
+ (v) => !["string", "number", "boolean"].includes(typeof v),
154
+ )
155
+ )
156
+ fail(
157
+ `channels.${name}.arguments must map names to strings, numbers or booleans`,
158
+ );
159
+ channels[name] = {
160
+ url: url!.href,
161
+ headers: strings(entry.headers, `channels.${name}.headers`),
162
+ arguments: args as Record<string, string | number | boolean>,
163
+ };
164
+ }
165
+ return {
166
+ folder: resolve(expandHome(value.folder as string)),
167
+ args: args as string[],
168
+ env: strings(value.env, "env"),
169
+ ...(value.prestart !== undefined && { prestart: value.prestart as string }),
170
+ channels,
171
+ };
172
+ };
173
+
174
+ export const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {
175
+ if (!existsSync(paths.config))
176
+ throw new Error(`No ${paths.config}: run harnessd install`);
177
+ let raw: unknown;
178
+ try {
179
+ raw = JSON.parse(readFileSync(paths.config, "utf8"));
180
+ } catch (error) {
181
+ throw new Error(
182
+ `config.json isn't JSON: ${error instanceof Error ? error.message : String(error)}`,
183
+ );
184
+ }
185
+ return parseConfig(raw);
186
+ };
187
+
188
+ /** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
189
+ export const headersOf = (
190
+ channel: Harnessd.Channel,
191
+ env: NodeJS.ProcessEnv,
192
+ ): Record<string, string> =>
193
+ Object.fromEntries(
194
+ Object.entries(channel.headers).map(([key, value]) => [
195
+ key,
196
+ value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name: string) => {
197
+ const found = env[name];
198
+ if (found === undefined)
199
+ throw new Error(`header ${key} needs $${name}, which isn't set`);
200
+ return found;
201
+ }),
202
+ ]),
203
+ );
package/src/daemon.ts ADDED
@@ -0,0 +1,312 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ mkdirSync,
5
+ readFileSync,
6
+ rmSync,
7
+ statSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { createRequire } from "node:module";
11
+ import { createConnection, createServer, type Socket } from "node:net";
12
+ import { dirname, join } from "node:path";
13
+ import { createInterface } from "node:readline";
14
+ import type { IPty } from "node-pty";
15
+ import {
16
+ channelBlockers,
17
+ claudeArgs,
18
+ findTranscript,
19
+ prestart,
20
+ trustFolder,
21
+ which,
22
+ writePlugin,
23
+ } from "./claude";
24
+ import { readConfig, type Harnessd } from "./config";
25
+ import { logTo } from "./log";
26
+ import { IDLE_SIZE, scrollback } from "./terminal";
27
+ import { watchdog, type Watchdog } from "./watchdog";
28
+
29
+ export namespace Daemon {
30
+ /** A request on harnessd's socket: one line of JSON. An attach then streams `{ output }` lines and takes `{ input }` and `{ resize }`. */
31
+ export type Request =
32
+ | { readonly command: "status" | "stop" | "start" }
33
+ | { readonly command: "new"; readonly message?: string }
34
+ | {
35
+ readonly command: "attach";
36
+ readonly cols: number;
37
+ readonly rows: number;
38
+ };
39
+
40
+ export type Status = Watchdog.Status & {
41
+ readonly daemonPid: number;
42
+ readonly folder?: string;
43
+ };
44
+ }
45
+
46
+ // a Claude Code session's own markers, which the agent's session must not inherit
47
+ const OWN_ENV =
48
+ /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(ENTRYPOINT|SSE_PORT|CHILD_SESSION|SESSION_ID|HOST_SESSION_ID|MESSAGING_SOCKET|MESSAGING_TOKEN|EXECPATH))$/;
49
+
50
+ const VIEWER_BUFFER = 8 * 1024 * 1024;
51
+
52
+ const clamp = (value: unknown, min: number, max: number, fallback: number) =>
53
+ typeof value === "number" && Number.isFinite(value)
54
+ ? Math.max(min, Math.min(max, Math.floor(value)))
55
+ : fallback;
56
+
57
+ // node-pty's prebuilt spawn-helper ships without its executable bit; its install script, which pnpm skips, sets it
58
+ const loadPty = async () => {
59
+ const helper = join(
60
+ dirname(createRequire(import.meta.url).resolve("node-pty/package.json")),
61
+ "prebuilds",
62
+ `${process.platform}-${process.arch}`,
63
+ "spawn-helper",
64
+ );
65
+ if (existsSync(helper) && (statSync(helper).mode & 0o111) === 0)
66
+ chmodSync(helper, 0o755);
67
+ return import("node-pty");
68
+ };
69
+
70
+ /** Sends one request to a running harnessd; undefined when none answers. */
71
+ export const ask = (socket: string, request: Daemon.Request) =>
72
+ new Promise<Record<string, unknown> | undefined>((resolve) => {
73
+ if (!existsSync(socket)) return resolve(undefined);
74
+ const connection = createConnection(socket);
75
+ connection.once("error", () => resolve(undefined));
76
+ connection.once("connect", () =>
77
+ connection.write(`${JSON.stringify(request)}\n`),
78
+ );
79
+ const lines = createInterface({ input: connection });
80
+ lines.once("line", (line) => {
81
+ connection.end();
82
+ try {
83
+ resolve(JSON.parse(line));
84
+ } catch {
85
+ resolve(undefined);
86
+ }
87
+ });
88
+ lines.once("close", () => resolve(undefined));
89
+ });
90
+
91
+ /** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
92
+ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
93
+ mkdirSync(paths.home, { recursive: true });
94
+ const log = logTo(paths.log);
95
+ if (await ask(paths.socket, { command: "status" }))
96
+ throw new Error(`Another harnessd already runs in ${paths.home}`);
97
+ rmSync(paths.socket, { force: true });
98
+
99
+ const term = scrollback();
100
+ const viewers = new Set<Socket>();
101
+ let size = IDLE_SIZE;
102
+ let pty: IPty | undefined;
103
+ let folder: string | undefined;
104
+ const show = (data: string) => {
105
+ term.push(data);
106
+ const line = `${JSON.stringify({ output: data })}\n`;
107
+ for (const viewer of viewers) {
108
+ // a viewer that stops reading is let go rather than buffered without end
109
+ if (viewer.writableLength > VIEWER_BUFFER) viewer.destroy();
110
+ else viewer.write(line);
111
+ }
112
+ };
113
+
114
+ const state = {
115
+ read: (): Watchdog.State => {
116
+ try {
117
+ return JSON.parse(readFileSync(paths.state, "utf8")) as Watchdog.State;
118
+ } catch {
119
+ return {};
120
+ }
121
+ },
122
+ write: (value: Watchdog.State) =>
123
+ writeFileSync(paths.state, `${JSON.stringify(value)}\n`),
124
+ };
125
+
126
+ // what Claude Code last ran with (before its first start: the config's env): its CLAUDE_CONFIG_DIR says where its transcripts are
127
+ let claudeEnv: NodeJS.ProcessEnv | undefined;
128
+ const transcriptEnv = (): NodeJS.ProcessEnv => {
129
+ if (claudeEnv) return claudeEnv;
130
+ try {
131
+ return { ...process.env, ...readConfig(paths).env };
132
+ } catch {
133
+ return process.env;
134
+ }
135
+ };
136
+ const launch = async (start: Watchdog.Start): Promise<Watchdog.Run> => {
137
+ const config = readConfig(paths);
138
+ folder = config.folder;
139
+ mkdirSync(config.folder, { recursive: true });
140
+ const inherited = Object.fromEntries(
141
+ Object.entries(process.env).filter(([key]) => !OWN_ENV.test(key)),
142
+ ) as Record<string, string>;
143
+ const base: Record<string, string> = {
144
+ ...inherited,
145
+ ...config.env,
146
+ HARNESSD_HOME: paths.home,
147
+ };
148
+ const hook = config.prestart
149
+ ? await prestart(config.prestart, config.folder, base, log)
150
+ : { env: {}, args: [] };
151
+ const env = { ...base, ...hook.env };
152
+ claudeEnv = env;
153
+ if (!trustFolder(config.folder, env))
154
+ log(
155
+ "Claude Code has no settings yet: harnessd attach, then sign in and trust the folder",
156
+ );
157
+ const plugin = writePlugin(paths, config, bin) ? paths.plugin : undefined;
158
+ const blockers = plugin ? channelBlockers() : [];
159
+ if (blockers.length > 0)
160
+ log(
161
+ `Claude Code won't let the channels in: ${blockers.join("; ")} (harnessd install lets them in)`,
162
+ );
163
+ const file = which("claude", env.PATH);
164
+ const { spawn } = await loadPty();
165
+ const p = spawn(
166
+ file,
167
+ claudeArgs({
168
+ start,
169
+ plugin,
170
+ allowed: blockers.length === 0,
171
+ config,
172
+ extra: hook.args,
173
+ }),
174
+ {
175
+ name: "xterm-256color",
176
+ cols: size.cols,
177
+ rows: size.rows,
178
+ cwd: config.folder,
179
+ env,
180
+ },
181
+ );
182
+ pty = p;
183
+ show(
184
+ `\r\n\x1b[2m── harnessd started Claude Code ${new Date().toLocaleString()} ──\x1b[0m\r\n`,
185
+ );
186
+ p.onData(show);
187
+ const exited = new Promise<number>((resolve) =>
188
+ p.onExit(({ exitCode, signal }) => {
189
+ if (pty === p) pty = undefined;
190
+ resolve(signal ? 128 + signal : exitCode);
191
+ }),
192
+ );
193
+ return {
194
+ pid: p.pid,
195
+ exited,
196
+ kill: (signal) => {
197
+ try {
198
+ p.kill(signal);
199
+ } catch {}
200
+ },
201
+ };
202
+ };
203
+
204
+ const resize = (cols: number, rows: number) => {
205
+ if (cols === size.cols && rows === size.rows) return;
206
+ size = { cols, rows };
207
+ try {
208
+ pty?.resize(cols, rows);
209
+ } catch {}
210
+ };
211
+
212
+ const dog = watchdog({
213
+ launch,
214
+ state,
215
+ hasTranscript: (id) => findTranscript(id, transcriptEnv()) !== undefined,
216
+ log,
217
+ });
218
+
219
+ const status = (): Daemon.Status => ({
220
+ ...dog.status(),
221
+ daemonPid: process.pid,
222
+ ...(folder && { folder }),
223
+ });
224
+
225
+ const serve = (connection: Socket) => {
226
+ const reply = (value: unknown) =>
227
+ connection.end(`${JSON.stringify(value)}\n`);
228
+ const lines = createInterface({ input: connection });
229
+ let attached = false;
230
+ connection.on("error", () => {});
231
+ lines.on("line", async (line): Promise<void> => {
232
+ let message: Record<string, unknown>;
233
+ try {
234
+ message = JSON.parse(line);
235
+ } catch {
236
+ return void reply({ ok: false, message: "Not JSON." });
237
+ }
238
+ if (attached) {
239
+ if (typeof message.input === "string") pty?.write(message.input);
240
+ const asked = message.resize as
241
+ | { cols?: unknown; rows?: unknown }
242
+ | undefined;
243
+ if (asked)
244
+ resize(
245
+ clamp(asked.cols, 20, 500, size.cols),
246
+ clamp(asked.rows, 5, 300, size.rows),
247
+ );
248
+ return;
249
+ }
250
+ const request = message as Daemon.Request;
251
+ if (request.command === "status")
252
+ return void reply({ ok: true, status: status() });
253
+ if (request.command === "stop")
254
+ return void reply({ ok: true, message: await dog.stop() });
255
+ if (request.command === "start")
256
+ return void reply({ ok: true, message: await dog.start() });
257
+ if (request.command === "new") {
258
+ if (
259
+ request.message !== undefined &&
260
+ typeof request.message !== "string"
261
+ )
262
+ return void reply({ ok: false, message: "message must be text." });
263
+ return void reply({
264
+ ok: true,
265
+ message: await dog.fresh(request.message),
266
+ });
267
+ }
268
+ if (request.command === "attach") {
269
+ attached = true;
270
+ viewers.add(connection);
271
+ resize(
272
+ clamp(request.cols, 20, 500, IDLE_SIZE.cols),
273
+ clamp(request.rows, 5, 300, IDLE_SIZE.rows),
274
+ );
275
+ connection.write(`${JSON.stringify({ output: term.read() })}\n`);
276
+ connection.on("close", () => {
277
+ viewers.delete(connection);
278
+ if (viewers.size === 0) resize(IDLE_SIZE.cols, IDLE_SIZE.rows);
279
+ });
280
+ return;
281
+ }
282
+ reply({
283
+ ok: false,
284
+ message: `Unknown command ${String((request as { command?: unknown }).command)}.`,
285
+ });
286
+ });
287
+ };
288
+
289
+ const server = createServer(serve);
290
+ await new Promise<void>((resolve, reject) => {
291
+ server.once("error", reject);
292
+ server.listen(paths.socket, resolve);
293
+ });
294
+ log(`harnessd ${process.pid} started`);
295
+
296
+ let stopping = false;
297
+ const shutdown = async (signal: string) => {
298
+ if (stopping) return;
299
+ stopping = true;
300
+ log(`harnessd got ${signal}; stopping Claude Code`);
301
+ await dog.shutdown();
302
+ for (const viewer of viewers) viewer.end();
303
+ server.close();
304
+ rmSync(paths.socket, { force: true });
305
+ log(`harnessd ${process.pid} stopped`);
306
+ process.exit(0);
307
+ };
308
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));
309
+ process.on("SIGINT", () => void shutdown("SIGINT"));
310
+ process.on("SIGHUP", () => void shutdown("SIGHUP"));
311
+ await dog.run();
312
+ };
package/src/launchd.ts ADDED
@@ -0,0 +1,126 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import {
3
+ accessSync,
4
+ constants,
5
+ existsSync,
6
+ mkdirSync,
7
+ realpathSync,
8
+ rmSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { delimiter, join } from "node:path";
13
+ import type { Harnessd } from "./config";
14
+
15
+ const xml = (value: string) =>
16
+ value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
17
+
18
+ /**
19
+ * The node the LaunchAgent starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
20
+ * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
21
+ * harnessd unable to start. None that is this one: `process.execPath`.
22
+ */
23
+ export const stableNode = (
24
+ execPath = process.execPath,
25
+ path = process.env.PATH ?? "",
26
+ ) => {
27
+ let real: string;
28
+ try {
29
+ real = realpathSync(execPath);
30
+ } catch {
31
+ return execPath;
32
+ }
33
+ for (const dir of path.split(delimiter)) {
34
+ if (!dir.startsWith("/")) continue;
35
+ const candidate = join(dir, "node");
36
+ try {
37
+ accessSync(candidate, constants.X_OK);
38
+ if (realpathSync(candidate) === real) return candidate;
39
+ } catch {}
40
+ }
41
+ return execPath;
42
+ };
43
+
44
+ export const plistPath = (label: string) =>
45
+ join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
46
+
47
+ /** The LaunchAgent: `node <bin> run` at login and after any exit. */
48
+ export const plistOf = (o: {
49
+ label: string;
50
+ node: string;
51
+ bin: string;
52
+ env: Readonly<Record<string, string>>;
53
+ paths: Harnessd.Paths;
54
+ }) => `<?xml version="1.0" encoding="UTF-8"?>
55
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
56
+ <plist version="1.0">
57
+ <dict>
58
+ <key>Label</key>
59
+ <string>${xml(o.label)}</string>
60
+ <key>ProgramArguments</key>
61
+ <array>
62
+ <string>${xml(o.node)}</string>
63
+ <string>${xml(o.bin)}</string>
64
+ <string>run</string>
65
+ </array>
66
+ <key>EnvironmentVariables</key>
67
+ <dict>
68
+ ${Object.entries(o.env)
69
+ .map(
70
+ ([key, value]) =>
71
+ ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`,
72
+ )
73
+ .join("\n")}
74
+ </dict>
75
+ <key>WorkingDirectory</key>
76
+ <string>${xml(o.paths.home)}</string>
77
+ <key>RunAtLoad</key>
78
+ <true/>
79
+ <key>KeepAlive</key>
80
+ <true/>
81
+ <key>ExitTimeOut</key>
82
+ <integer>30</integer>
83
+ <key>ProcessType</key>
84
+ <string>Interactive</string>
85
+ <key>StandardOutPath</key>
86
+ <string>${xml(join(o.paths.home, "launchd.log"))}</string>
87
+ <key>StandardErrorPath</key>
88
+ <string>${xml(join(o.paths.home, "launchd.log"))}</string>
89
+ </dict>
90
+ </plist>
91
+ `;
92
+
93
+ const domain = () => `gui/${process.getuid!()}`;
94
+
95
+ const launchctl = (...args: string[]) =>
96
+ spawnSync("launchctl", args, { encoding: "utf8" });
97
+
98
+ export const loaded = (label: string) =>
99
+ launchctl("print", `${domain()}/${label}`).status === 0;
100
+
101
+ /** Writes the LaunchAgent and (re)loads it, which starts harnessd. */
102
+ export const load = (label: string, plist: string) => {
103
+ mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
104
+ if (loaded(label)) launchctl("bootout", `${domain()}/${label}`);
105
+ writeFileSync(plistPath(label), plist);
106
+ const result = launchctl("bootstrap", domain(), plistPath(label));
107
+ if (result.status !== 0)
108
+ throw new Error(
109
+ `launchctl bootstrap failed: ${(result.stderr || result.stdout).trim()}`,
110
+ );
111
+ };
112
+
113
+ /** Stops harnessd (it stops Claude Code first) and removes the LaunchAgent. */
114
+ export const unload = (label: string) => {
115
+ if (loaded(label)) {
116
+ const result = launchctl("bootout", `${domain()}/${label}`);
117
+ if (result.status !== 0)
118
+ throw new Error(
119
+ `launchctl bootout failed: ${(result.stderr || result.stdout).trim()}`,
120
+ );
121
+ }
122
+ const plist = plistPath(label);
123
+ const had = existsSync(plist);
124
+ rmSync(plist, { force: true });
125
+ return had;
126
+ };
package/src/log.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+
4
+ const MAX_BYTES = 5 * 1024 * 1024;
5
+
6
+ /** Appends timestamped lines to `file`, keeping one older file (`.1`) past 5 MB. */
7
+ export const logTo =
8
+ (file: string, prefix = "") =>
9
+ (line: string) => {
10
+ try {
11
+ mkdirSync(dirname(file), { recursive: true });
12
+ try {
13
+ if (statSync(file).size > MAX_BYTES) renameSync(file, `${file}.1`);
14
+ } catch {}
15
+ appendFileSync(file, `${new Date().toISOString()} ${prefix}${line}\n`);
16
+ } catch {}
17
+ };
@@ -0,0 +1,33 @@
1
+ /** The terminal's size while nobody is attached. */
2
+ export const IDLE_SIZE = { cols: 160, rows: 50 };
3
+
4
+ const SCROLLBACK_CHARS = 2 * 1024 * 1024;
5
+
6
+ /** The terminal's last ~2 MB of output, so an attach replays the screen before following it live. */
7
+ export const scrollback = (max = SCROLLBACK_CHARS) => {
8
+ let chunks: string[] = [];
9
+ let size = 0;
10
+ return {
11
+ push: (chunk: string) => {
12
+ if (!chunk) return;
13
+ chunks.push(chunk);
14
+ size += chunk.length;
15
+ while (chunks.length > 1 && size - chunks[0]!.length >= max)
16
+ size -= chunks.shift()!.length;
17
+ if (size > max) {
18
+ // cut at a line start, so the replay doesn't open inside an escape sequence
19
+ const first = chunks[0]!;
20
+ let from = first.length - (max - (size - first.length));
21
+ const newline = first.indexOf("\n", from);
22
+ if (newline !== -1) from = newline + 1;
23
+ chunks[0] = first.slice(from);
24
+ size -= from;
25
+ }
26
+ },
27
+ read: () => {
28
+ if (!size) return "";
29
+ chunks = [chunks.join("")];
30
+ return `\x1b[0m${chunks[0]}`;
31
+ },
32
+ };
33
+ };