@harness-sdk/harnessd 0.0.1 → 0.1.0

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 (70) hide show
  1. package/README.md +31 -18
  2. package/dist/accounts.d.ts +66 -0
  3. package/dist/accounts.d.ts.map +1 -0
  4. package/dist/accounts.js +166 -0
  5. package/dist/accounts.js.map +1 -0
  6. package/dist/bin.js +4 -0
  7. package/dist/bin.js.map +1 -1
  8. package/dist/channel.d.ts +15 -10
  9. package/dist/channel.d.ts.map +1 -1
  10. package/dist/channel.js +113 -158
  11. package/dist/channel.js.map +1 -1
  12. package/dist/claude.d.ts +17 -13
  13. package/dist/claude.d.ts.map +1 -1
  14. package/dist/claude.js +69 -59
  15. package/dist/claude.js.map +1 -1
  16. package/dist/cli.d.ts +5 -0
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +317 -131
  19. package/dist/cli.js.map +1 -1
  20. package/dist/config.d.ts +46 -10
  21. package/dist/config.d.ts.map +1 -1
  22. package/dist/config.js +142 -51
  23. package/dist/config.js.map +1 -1
  24. package/dist/daemon.d.ts +29 -4
  25. package/dist/daemon.d.ts.map +1 -1
  26. package/dist/daemon.js +174 -51
  27. package/dist/daemon.js.map +1 -1
  28. package/dist/launchd.d.ts +12 -16
  29. package/dist/launchd.d.ts.map +1 -1
  30. package/dist/launchd.js +28 -25
  31. package/dist/launchd.js.map +1 -1
  32. package/dist/prompts.d.ts +53 -0
  33. package/dist/prompts.d.ts.map +1 -0
  34. package/dist/prompts.js +171 -0
  35. package/dist/prompts.js.map +1 -0
  36. package/dist/service.d.ts +37 -0
  37. package/dist/service.d.ts.map +1 -0
  38. package/dist/service.js +71 -0
  39. package/dist/service.js.map +1 -0
  40. package/dist/setup.d.ts +37 -0
  41. package/dist/setup.d.ts.map +1 -0
  42. package/dist/setup.js +121 -0
  43. package/dist/setup.js.map +1 -0
  44. package/dist/system.d.ts +6 -0
  45. package/dist/system.d.ts.map +1 -0
  46. package/dist/system.js +16 -0
  47. package/dist/system.js.map +1 -0
  48. package/dist/systemd.d.ts +14 -0
  49. package/dist/systemd.d.ts.map +1 -0
  50. package/dist/systemd.js +62 -0
  51. package/dist/systemd.js.map +1 -0
  52. package/dist/watchdog.d.ts +14 -4
  53. package/dist/watchdog.d.ts.map +1 -1
  54. package/dist/watchdog.js +30 -24
  55. package/dist/watchdog.js.map +1 -1
  56. package/package.json +8 -12
  57. package/src/accounts.ts +242 -0
  58. package/src/bin.ts +6 -0
  59. package/src/channel.ts +151 -172
  60. package/src/claude.ts +90 -88
  61. package/src/cli.ts +494 -183
  62. package/src/config.ts +239 -63
  63. package/src/daemon.ts +215 -65
  64. package/src/launchd.ts +40 -35
  65. package/src/prompts.ts +255 -0
  66. package/src/service.ts +145 -0
  67. package/src/setup.ts +188 -0
  68. package/src/system.ts +11 -0
  69. package/src/systemd.ts +78 -0
  70. package/src/watchdog.ts +41 -33
package/src/daemon.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import {
2
- chmodSync,
3
2
  existsSync,
4
3
  mkdirSync,
5
4
  readFileSync,
@@ -7,30 +6,35 @@ import {
7
6
  statSync,
8
7
  writeFileSync,
9
8
  } from "node:fs";
10
- import { createRequire } from "node:module";
11
9
  import { createConnection, createServer, type Socket } from "node:net";
12
- import { dirname, join } from "node:path";
10
+ import { delimiter, dirname } from "node:path";
13
11
  import { createInterface } from "node:readline";
14
- import type { IPty } from "node-pty";
12
+ import type { IPty } from "@lydell/node-pty";
13
+ import { accountRun, rotation } from "./accounts";
15
14
  import {
16
- channelBlockers,
17
15
  claudeArgs,
16
+ claudeVersion,
17
+ skipsPermissions,
18
18
  findTranscript,
19
19
  prestart,
20
20
  trustFolder,
21
21
  which,
22
22
  writePlugin,
23
23
  } from "./claude";
24
- import { readConfig, type Harnessd } from "./config";
24
+ import { ownFolder, readConfig, type Harnessd } from "./config";
25
25
  import { logTo } from "./log";
26
+ import { promptWatcher } from "./prompts";
26
27
  import { IDLE_SIZE, scrollback } from "./terminal";
27
- import { watchdog, type Watchdog } from "./watchdog";
28
+ import { NOT_STARTED, watchdog, type Watchdog } from "./watchdog";
28
29
 
29
30
  export namespace Daemon {
30
31
  /** A request on harnessd's socket: one line of JSON. An attach then streams `{ output }` lines and takes `{ input }` and `{ resize }`. */
31
32
  export type Request =
32
33
  | { readonly command: "status" | "stop" | "start" }
33
- | { readonly command: "new"; readonly message?: string }
34
+ /** From Claude Code's SessionStart hook: the conversation it is in now. */
35
+ | { readonly command: "session-start"; readonly sessionId: string }
36
+ /** From Claude Code's Notification hook: it waits for input, with nothing running. */
37
+ | { readonly command: "idle" }
34
38
  | {
35
39
  readonly command: "attach";
36
40
  readonly cols: number;
@@ -40,6 +44,24 @@ export namespace Daemon {
40
44
  export type Status = Watchdog.Status & {
41
45
  readonly daemonPid: number;
42
46
  readonly folder?: string;
47
+ /** The account Claude Code runs on, when the config names accounts. */
48
+ readonly account?: string;
49
+ /** The accounts passed over, and until when. */
50
+ readonly accountsStopped?: Readonly<
51
+ Record<string, { readonly why: string; readonly until: string }>
52
+ >;
53
+ /** The prompt Claude Code waits at until a person answers it. */
54
+ readonly waitingOn?: string;
55
+ /** Claude Code said managed settings keep channels out: it drops their events. */
56
+ readonly channelsRefused?: true;
57
+ /** The version of the Claude Code that runs, or ran last. */
58
+ readonly claudeVersion?: string;
59
+ /** A newer Claude Code than the one that runs (no `at`: it starts once the agent is idle), or the last restart into one. */
60
+ readonly update?: {
61
+ readonly from: string;
62
+ readonly to: string;
63
+ readonly at?: string;
64
+ };
43
65
  };
44
66
  }
45
67
 
@@ -49,24 +71,16 @@ const OWN_ENV =
49
71
 
50
72
  const VIEWER_BUFFER = 8 * 1024 * 1024;
51
73
 
74
+ const UPDATE_CHECK_MS = 60 * 60_000;
75
+
76
+ const SESSION_ID =
77
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
78
+
52
79
  const clamp = (value: unknown, min: number, max: number, fallback: number) =>
53
80
  typeof value === "number" && Number.isFinite(value)
54
81
  ? Math.max(min, Math.min(max, Math.floor(value)))
55
82
  : fallback;
56
83
 
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
84
  /** Sends one request to a running harnessd; undefined when none answers. */
71
85
  export const ask = (socket: string, request: Daemon.Request) =>
72
86
  new Promise<Record<string, unknown> | undefined>((resolve) => {
@@ -77,6 +91,8 @@ export const ask = (socket: string, request: Daemon.Request) =>
77
91
  connection.write(`${JSON.stringify(request)}\n`),
78
92
  );
79
93
  const lines = createInterface({ input: connection });
94
+ // readline passes the connection's error on: a socket file nobody listens on (harnessd was killed) is no answer
95
+ lines.once("error", () => resolve(undefined));
80
96
  lines.once("line", (line) => {
81
97
  connection.end();
82
98
  try {
@@ -88,9 +104,17 @@ export const ask = (socket: string, request: Daemon.Request) =>
88
104
  lines.once("close", () => resolve(undefined));
89
105
  });
90
106
 
91
- /** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
107
+ /** `harnessd run`: what launchd or systemd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
92
108
  export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
93
- mkdirSync(paths.home, { recursive: true });
109
+ ownFolder(paths.home);
110
+ ownFolder(dirname(paths.config));
111
+ const socketDir = dirname(paths.socket);
112
+ if (socketDir !== paths.home) {
113
+ mkdirSync(socketDir, { recursive: true, mode: 0o700 });
114
+ // a socket outside harnessd's folder sits in a shared one, where another user may have made its folder first
115
+ if (statSync(socketDir).uid !== process.getuid!())
116
+ throw new Error(`${socketDir} belongs to another user`);
117
+ }
94
118
  const log = logTo(paths.log);
95
119
  if (await ask(paths.socket, { command: "status" }))
96
120
  throw new Error(`Another harnessd already runs in ${paths.home}`);
@@ -111,6 +135,12 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
111
135
  }
112
136
  };
113
137
 
138
+ const prompts = promptWatcher({
139
+ write: (keys) => pty?.write(keys),
140
+ log,
141
+ ...size,
142
+ });
143
+
114
144
  const state = {
115
145
  read: (): Watchdog.State => {
116
146
  try {
@@ -133,8 +163,31 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
133
163
  return process.env;
134
164
  }
135
165
  };
166
+ // the Claude Code that runs: how to ask the installed one its version, and which version this one is
167
+ let claude:
168
+ | {
169
+ pid: number;
170
+ file: string;
171
+ env: NodeJS.ProcessEnv;
172
+ version: string | undefined;
173
+ }
174
+ | undefined;
175
+ // when Claude Code last said it waits for input with nothing running
176
+ let idleAt: number | undefined;
177
+ let update: Daemon.Status["update"];
178
+ let accounts: Harnessd.Config["accounts"] = {};
179
+ let account: string | undefined;
180
+ const rota = rotation({
181
+ accounts: () =>
182
+ Object.fromEntries(
183
+ Object.entries(accounts).map(([name, { env }]) => [name, env]),
184
+ ),
185
+ });
136
186
  const launch = async (start: Watchdog.Start): Promise<Watchdog.Run> => {
137
187
  const config = readConfig(paths);
188
+ accounts = config.accounts;
189
+ account = rota.pick(state.read().account);
190
+ if (account !== undefined) state.write({ ...state.read(), account });
138
191
  folder = config.folder;
139
192
  mkdirSync(config.folder, { recursive: true });
140
193
  const inherited = Object.fromEntries(
@@ -143,56 +196,92 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
143
196
  const base: Record<string, string> = {
144
197
  ...inherited,
145
198
  ...config.env,
146
- HARNESSD_HOME: paths.home,
199
+ ...(account !== undefined && {
200
+ ...config.accounts[account]!.env,
201
+ HARNESSD_ACCOUNT: account,
202
+ }),
203
+ ...paths.env,
147
204
  };
205
+ if (account !== undefined) log(`Claude Code runs on account ${account}`);
148
206
  const hook = config.prestart
149
207
  ? await prestart(config.prestart, config.folder, base, log)
150
208
  : { env: {}, args: [] };
151
209
  const env = { ...base, ...hook.env };
152
210
  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({
211
+ trustFolder(config.folder, env);
212
+ writePlugin(paths, config, bin);
213
+ // from before the start, so a refusal Claude Code writes at once is read
214
+ const onAccount =
215
+ account !== undefined && Object.keys(config.accounts).length > 1
216
+ ? accountRun({
217
+ account,
218
+ rotation: rota,
219
+ sessionId: () => dog.status().sessionId ?? start.sessionId,
220
+ file: (id) => findTranscript(id, env),
221
+ restart: (reason, pid) => void dog.restart(reason, pid),
222
+ log,
223
+ })
224
+ : undefined;
225
+ let handover: string | undefined;
226
+ let p: IPty;
227
+ let args: string[];
228
+ let file: string;
229
+ let version: string | undefined;
230
+ // the servers' commands, ahead of any other command of the same name; after claude is found
231
+ const spawnEnv = {
232
+ ...env,
233
+ PATH: [paths.bin, ...(env.PATH ? [env.PATH] : [])].join(delimiter),
234
+ };
235
+ try {
236
+ file = which("claude", env.PATH);
237
+ version = await claudeVersion(file, spawnEnv);
238
+ const { spawn } = await import("@lydell/node-pty");
239
+ args = claudeArgs({
168
240
  start,
169
- plugin,
170
- allowed: blockers.length === 0,
241
+ plugin: paths.plugin,
171
242
  config,
172
243
  extra: hook.args,
173
- }),
174
- {
244
+ });
245
+ p = spawn(file, args, {
175
246
  name: "xterm-256color",
176
247
  cols: size.cols,
177
248
  rows: size.rows,
178
249
  cwd: config.folder,
179
- env,
180
- },
181
- );
250
+ env: spawnEnv,
251
+ });
252
+ } catch (error) {
253
+ onAccount?.exited();
254
+ throw error;
255
+ }
256
+ onAccount?.started(p.pid);
182
257
  pty = p;
258
+ claude = { pid: p.pid, file, env: spawnEnv, version };
259
+ idleAt = undefined;
260
+ if (update && !update.at && version === update.to)
261
+ update = { ...update, at: new Date().toISOString() };
262
+ prompts.reset({ skipsPermissions: skipsPermissions(args) });
183
263
  show(
184
264
  `\r\n\x1b[2m── harnessd started Claude Code ${new Date().toLocaleString()} ──\x1b[0m\r\n`,
185
265
  );
186
- p.onData(show);
266
+ p.onData((data) => {
267
+ show(data);
268
+ prompts.push(data);
269
+ });
187
270
  const exited = new Promise<number>((resolve) =>
188
271
  p.onExit(({ exitCode, signal }) => {
189
- if (pty === p) pty = undefined;
272
+ // the last lines too: an account that stopped right before the exit isn't started again
273
+ handover = onAccount?.exited();
274
+ if (pty === p) {
275
+ pty = undefined;
276
+ prompts.reset();
277
+ }
190
278
  resolve(signal ? 128 + signal : exitCode);
191
279
  }),
192
280
  );
193
281
  return {
194
282
  pid: p.pid,
195
283
  exited,
284
+ ended: () => handover,
196
285
  kill: (signal) => {
197
286
  try {
198
287
  p.kill(signal);
@@ -204,6 +293,7 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
204
293
  const resize = (cols: number, rows: number) => {
205
294
  if (cols === size.cols && rows === size.rows) return;
206
295
  size = { cols, rows };
296
+ prompts.resize(cols, rows);
207
297
  try {
208
298
  pty?.resize(cols, rows);
209
299
  } catch {}
@@ -216,15 +306,72 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
216
306
  log,
217
307
  });
218
308
 
219
- const status = (): Daemon.Status => ({
220
- ...dog.status(),
221
- daemonPid: process.pid,
222
- ...(folder && { folder }),
223
- });
309
+ const idle = () => {
310
+ if (idleAt === undefined || prompts.waitingOn()) return false;
311
+ // a line written since: a turn ran after Claude Code said it was idle
312
+ const sessionId = dog.status().sessionId;
313
+ const file = sessionId && findTranscript(sessionId, transcriptEnv());
314
+ try {
315
+ return !file || statSync(file).mtimeMs <= idleAt;
316
+ } catch {
317
+ return true;
318
+ }
319
+ };
320
+
321
+ // Claude Code's own updater installs a new version, which the one that runs only uses from its next start
322
+ const checkUpdate = async () => {
323
+ const run = claude;
324
+ if (run?.version === undefined) return;
325
+ const installed = await claudeVersion(run.file, run.env);
326
+ if (run !== claude) return;
327
+ if (installed === undefined || installed === run.version) {
328
+ if (update && !update.at) update = undefined;
329
+ return;
330
+ }
331
+ const found = update?.to !== installed || update.at !== undefined;
332
+ if (found) update = { from: run.version, to: installed };
333
+ if (!idle()) {
334
+ if (found)
335
+ log(
336
+ `Claude Code ${installed} is installed; harnessd restarts into it once the agent is idle`,
337
+ );
338
+ return;
339
+ }
340
+ log(`restarting Claude Code ${run.version} into ${installed}`);
341
+ await dog.restart(
342
+ `it was updated from ${run.version} to ${installed}`,
343
+ run.pid,
344
+ );
345
+ };
346
+
347
+ const status = (): Daemon.Status => {
348
+ const waitingOn = prompts.waitingOn();
349
+ const stops = rota.marks();
350
+ return {
351
+ ...dog.status(),
352
+ daemonPid: process.pid,
353
+ ...(folder && { folder }),
354
+ ...(waitingOn && { waitingOn }),
355
+ ...(prompts.channelsRefused() && { channelsRefused: true as const }),
356
+ ...(claude?.version !== undefined && { claudeVersion: claude.version }),
357
+ ...(update && { update }),
358
+ ...(account !== undefined && { account }),
359
+ ...(Object.keys(stops).length > 0 && {
360
+ accountsStopped: Object.fromEntries(
361
+ Object.entries(stops).map(([name, { why, until }]) => [
362
+ name,
363
+ { why, until: new Date(until).toISOString() },
364
+ ]),
365
+ ),
366
+ }),
367
+ };
368
+ };
224
369
 
225
370
  const serve = (connection: Socket) => {
226
371
  const reply = (value: unknown) =>
227
372
  connection.end(`${JSON.stringify(value)}\n`);
373
+ const done = (message: string) =>
374
+ reply({ ok: message !== NOT_STARTED, message });
228
375
  const lines = createInterface({ input: connection });
229
376
  let attached = false;
230
377
  connection.on("error", () => {});
@@ -252,18 +399,20 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
252
399
  return void reply({ ok: true, status: status() });
253
400
  if (request.command === "stop")
254
401
  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
- });
402
+ if (request.command === "start") return void done(await dog.start());
403
+ if (request.command === "session-start") {
404
+ if (!SESSION_ID.test(String(request.sessionId)))
405
+ return void reply({
406
+ ok: false,
407
+ message: "sessionId must be a conversation id.",
408
+ });
409
+ dog.follow(request.sessionId);
410
+ return void reply({ ok: true });
411
+ }
412
+ if (request.command === "idle") {
413
+ idleAt = Date.now();
414
+ reply({ ok: true });
415
+ return void checkUpdate();
267
416
  }
268
417
  if (request.command === "attach") {
269
418
  attached = true;
@@ -292,6 +441,7 @@ export const runDaemon = async (paths: Harnessd.Paths, bin: string) => {
292
441
  server.listen(paths.socket, resolve);
293
442
  });
294
443
  log(`harnessd ${process.pid} started`);
444
+ setInterval(() => void checkUpdate(), UPDATE_CHECK_MS);
295
445
 
296
446
  let stopping = false;
297
447
  const shutdown = async (signal: string) => {
package/src/launchd.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { spawnSync } from "node:child_process";
2
1
  import {
3
2
  accessSync,
4
3
  constants,
@@ -9,14 +8,15 @@ import {
9
8
  writeFileSync,
10
9
  } from "node:fs";
11
10
  import { homedir } from "node:os";
12
- import { delimiter, join } from "node:path";
13
- import type { Harnessd } from "./config";
11
+ import { delimiter, dirname, join } from "node:path";
12
+ import type { Service } from "./service";
13
+ import { system } from "./system";
14
14
 
15
15
  const xml = (value: string) =>
16
16
  value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
17
17
 
18
18
  /**
19
- * The node the LaunchAgent starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
19
+ * The node the service starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
20
20
  * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
21
21
  * harnessd unable to start. None that is this one: `process.execPath`.
22
22
  */
@@ -41,23 +41,26 @@ export const stableNode = (
41
41
  return execPath;
42
42
  };
43
43
 
44
- export const plistPath = (label: string) =>
45
- join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
44
+ /** The entry's lines that name harnessd's state folder: what tells one harnessd's entry from another's. */
45
+ export const plistFolder = (home: string) =>
46
+ ` <key>WorkingDirectory</key>\n <string>${xml(home)}</string>`;
46
47
 
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"?>
48
+ /** A LaunchAgent in the user's own folder, or for a boot service a LaunchDaemon. */
49
+ export const plistPath = (label: string, boot = false) =>
50
+ boot
51
+ ? `/Library/LaunchDaemons/${label}.plist`
52
+ : join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
53
+
54
+ /** The launchd entry: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
55
+ export const plistOf = (
56
+ o: Service.Spec,
57
+ ) => `<?xml version="1.0" encoding="UTF-8"?>
55
58
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
56
59
  <plist version="1.0">
57
60
  <dict>
58
61
  <key>Label</key>
59
62
  <string>${xml(o.label)}</string>
60
- <key>ProgramArguments</key>
63
+ ${o.user === undefined ? "" : ` <key>UserName</key>\n <string>${xml(o.user)}</string>\n`} <key>ProgramArguments</key>
61
64
  <array>
62
65
  <string>${xml(o.node)}</string>
63
66
  <string>${xml(o.bin)}</string>
@@ -72,8 +75,7 @@ ${Object.entries(o.env)
72
75
  )
73
76
  .join("\n")}
74
77
  </dict>
75
- <key>WorkingDirectory</key>
76
- <string>${xml(o.paths.home)}</string>
78
+ ${plistFolder(o.paths.home)}
77
79
  <key>RunAtLoad</key>
78
80
  <true/>
79
81
  <key>KeepAlive</key>
@@ -83,43 +85,46 @@ ${Object.entries(o.env)
83
85
  <key>ProcessType</key>
84
86
  <string>Interactive</string>
85
87
  <key>StandardOutPath</key>
86
- <string>${xml(join(o.paths.home, "launchd.log"))}</string>
88
+ <string>${xml(o.paths.serviceLog)}</string>
87
89
  <key>StandardErrorPath</key>
88
- <string>${xml(join(o.paths.home, "launchd.log"))}</string>
90
+ <string>${xml(o.paths.serviceLog)}</string>
89
91
  </dict>
90
92
  </plist>
91
93
  `;
92
94
 
93
- const domain = () => `gui/${process.getuid!()}`;
95
+ const domain = (boot: boolean) =>
96
+ boot ? "system" : `gui/${process.getuid!()}`;
94
97
 
95
- const launchctl = (...args: string[]) =>
96
- spawnSync("launchctl", args, { encoding: "utf8" });
98
+ const launchctl = (...args: string[]) => system("launchctl", args);
97
99
 
98
- export const loaded = (label: string) =>
99
- launchctl("print", `${domain()}/${label}`).status === 0;
100
+ const loaded = (label: string, boot: boolean) =>
101
+ launchctl("print", `${domain(boot)}/${label}`).status === 0;
100
102
 
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));
103
+ /** Writes the launchd entry and (re)loads it, which starts harnessd. */
104
+ export const load = async (label: string, plist: string, boot: boolean) => {
105
+ mkdirSync(dirname(plistPath(label, boot)), { recursive: true });
106
+ if (loaded(label, boot)) launchctl("bootout", `${domain(boot)}/${label}`);
107
+ // bootout returns while the old harnessd still stops Claude Code; a bootstrap before it is gone fails
108
+ for (let i = 0; loaded(label, boot) && i < 400; i++)
109
+ await new Promise((resolve) => setTimeout(resolve, 100));
110
+ writeFileSync(plistPath(label, boot), plist, { mode: 0o644 });
111
+ const result = launchctl("bootstrap", domain(boot), plistPath(label, boot));
107
112
  if (result.status !== 0)
108
113
  throw new Error(
109
114
  `launchctl bootstrap failed: ${(result.stderr || result.stdout).trim()}`,
110
115
  );
111
116
  };
112
117
 
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}`);
118
+ /** Stops harnessd (it stops Claude Code first) and removes the launchd entry. */
119
+ export const unload = (label: string, boot: boolean) => {
120
+ if (loaded(label, boot)) {
121
+ const result = launchctl("bootout", `${domain(boot)}/${label}`);
117
122
  if (result.status !== 0)
118
123
  throw new Error(
119
124
  `launchctl bootout failed: ${(result.stderr || result.stdout).trim()}`,
120
125
  );
121
126
  }
122
- const plist = plistPath(label);
127
+ const plist = plistPath(label, boot);
123
128
  const had = existsSync(plist);
124
129
  rmSync(plist, { force: true });
125
130
  return had;