@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
@@ -1 +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,E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;YAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;YAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;SAAE,CAAC,CACjE,CAAC;QACF,iEAAiE;QACjE,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;QAC5B,kFAAkF;QAClF,QAAQ,CAAC,eAAe,CAAC,EAAE,IAAI,CAAC;QAChC,6DAA6D;QAC7D,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;QAChC,4HAA4H;QAC5H,QAAQ,CAAC,MAAM,CAAC,EAAE;YAChB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;YACtB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;YACpB,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC;SACtB,CAAC;KACH,CAAC;CACH;AAkBD,4EAA4E;AAC5E,eAAO,MAAM,GAAG,GAAI,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,OAAO,iDAoBvD,CAAC;AAEL,mIAAmI;AACnI,eAAO,MAAM,SAAS,GAAU,OAAO,QAAQ,CAAC,KAAK,EAAE,KAAK,MAAM,kBAkWjE,CAAC"}
package/dist/daemon.js CHANGED
@@ -1,22 +1,20 @@
1
- import { channelBlockers, claudeArgs, findTranscript, prestart, trustFolder, which, writePlugin } from "./claude.js";
2
- import { readConfig } from "./config.js";
1
+ import { accountRun, rotation } from "./accounts.js";
2
+ import { claudeArgs, claudeVersion, findTranscript, prestart, skipsPermissions, trustFolder, which, writePlugin } from "./claude.js";
3
+ import { ownFolder, readConfig } from "./config.js";
3
4
  import { logTo } from "./log.js";
5
+ import { promptWatcher } from "./prompts.js";
4
6
  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 { NOT_STARTED, watchdog } from "./watchdog.js";
8
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
7
9
  import { createConnection, createServer } from "node:net";
10
+ import { delimiter, dirname } from "node:path";
8
11
  import { createInterface } from "node:readline";
9
- import { dirname, join } from "node:path";
10
- import { createRequire } from "node:module";
11
12
  // src/daemon.ts
12
13
  const OWN_ENV = /^(CLAUDECODE|CLAUDE_PID|CLAUDE_CODE_(ENTRYPOINT|SSE_PORT|CHILD_SESSION|SESSION_ID|HOST_SESSION_ID|MESSAGING_SOCKET|MESSAGING_TOKEN|EXECPATH))$/;
13
14
  const VIEWER_BUFFER = 8388608;
15
+ const UPDATE_CHECK_MS = 36e5;
16
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
17
  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
18
  /** Sends one request to a running harnessd; undefined when none answers. */
21
19
  const ask = (socket, request) => new Promise((resolve) => {
22
20
  if (!existsSync(socket)) return resolve(void 0);
@@ -24,6 +22,7 @@ const ask = (socket, request) => new Promise((resolve) => {
24
22
  connection.once("error", () => resolve(void 0));
25
23
  connection.once("connect", () => connection.write(`${JSON.stringify(request)}\n`));
26
24
  const lines = createInterface({ input: connection });
25
+ lines.once("error", () => resolve(void 0));
27
26
  lines.once("line", (line) => {
28
27
  connection.end();
29
28
  try {
@@ -34,9 +33,18 @@ const ask = (socket, request) => new Promise((resolve) => {
34
33
  });
35
34
  lines.once("close", () => resolve(void 0));
36
35
  });
37
- /** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
36
+ /** `harnessd run`: what launchd or systemd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
38
37
  const runDaemon = async (paths, bin) => {
39
- mkdirSync(paths.home, { recursive: true });
38
+ ownFolder(paths.home);
39
+ ownFolder(dirname(paths.config));
40
+ const socketDir = dirname(paths.socket);
41
+ if (socketDir !== paths.home) {
42
+ mkdirSync(socketDir, {
43
+ recursive: true,
44
+ mode: 448
45
+ });
46
+ if (statSync(socketDir).uid !== process.getuid()) throw new Error(`${socketDir} belongs to another user`);
47
+ }
40
48
  const log = logTo(paths.log);
41
49
  if (await ask(paths.socket, { command: "status" })) throw new Error(`Another harnessd already runs in ${paths.home}`);
42
50
  rmSync(paths.socket, { force: true });
@@ -51,6 +59,11 @@ const runDaemon = async (paths, bin) => {
51
59
  for (const viewer of viewers) if (viewer.writableLength > VIEWER_BUFFER) viewer.destroy();
52
60
  else viewer.write(line);
53
61
  };
62
+ const prompts = promptWatcher({
63
+ write: (keys) => pty?.write(keys),
64
+ log,
65
+ ...size
66
+ });
54
67
  const state = {
55
68
  read: () => {
56
69
  try {
@@ -73,15 +86,32 @@ const runDaemon = async (paths, bin) => {
73
86
  return process.env;
74
87
  }
75
88
  };
89
+ let claude;
90
+ let idleAt;
91
+ let update;
92
+ let accounts = {};
93
+ let account;
94
+ const rota = rotation({ accounts: () => Object.fromEntries(Object.entries(accounts).map(([name, { env }]) => [name, env])) });
76
95
  const launch = async (start) => {
77
96
  const config = readConfig(paths);
97
+ accounts = config.accounts;
98
+ account = rota.pick(state.read().account);
99
+ if (account !== void 0) state.write({
100
+ ...state.read(),
101
+ account
102
+ });
78
103
  folder = config.folder;
79
104
  mkdirSync(config.folder, { recursive: true });
80
105
  const base = {
81
106
  ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !OWN_ENV.test(key))),
82
107
  ...config.env,
83
- HARNESSD_HOME: paths.home
108
+ ...account !== void 0 && {
109
+ ...config.accounts[account].env,
110
+ HARNESSD_ACCOUNT: account
111
+ },
112
+ ...paths.env
84
113
  };
114
+ if (account !== void 0) log(`Claude Code runs on account ${account}`);
85
115
  const hook = config.prestart ? await prestart(config.prestart, config.folder, base, log) : {
86
116
  env: {},
87
117
  args: []
@@ -91,35 +121,77 @@ const runDaemon = async (paths, bin) => {
91
121
  ...hook.env
92
122
  };
93
123
  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
- });
124
+ trustFolder(config.folder, env);
125
+ writePlugin(paths, config, bin);
126
+ const onAccount = account !== void 0 && Object.keys(config.accounts).length > 1 ? accountRun({
127
+ account,
128
+ rotation: rota,
129
+ sessionId: () => dog.status().sessionId ?? start.sessionId,
130
+ file: (id) => findTranscript(id, env),
131
+ restart: (reason, pid) => void dog.restart(reason, pid),
132
+ log
133
+ }) : void 0;
134
+ let handover;
135
+ let p;
136
+ let args;
137
+ let file;
138
+ let version;
139
+ const spawnEnv = {
140
+ ...env,
141
+ PATH: [paths.bin, ...env.PATH ? [env.PATH] : []].join(delimiter)
142
+ };
143
+ try {
144
+ file = which("claude", env.PATH);
145
+ version = await claudeVersion(file, spawnEnv);
146
+ const { spawn } = await import("@lydell/node-pty");
147
+ args = claudeArgs({
148
+ start,
149
+ plugin: paths.plugin,
150
+ config,
151
+ extra: hook.args
152
+ });
153
+ p = spawn(file, args, {
154
+ name: "xterm-256color",
155
+ cols: size.cols,
156
+ rows: size.rows,
157
+ cwd: config.folder,
158
+ env: spawnEnv
159
+ });
160
+ } catch (error) {
161
+ onAccount?.exited();
162
+ throw error;
163
+ }
164
+ onAccount?.started(p.pid);
113
165
  pty = p;
166
+ claude = {
167
+ pid: p.pid,
168
+ file,
169
+ env: spawnEnv,
170
+ version
171
+ };
172
+ idleAt = void 0;
173
+ if (update && !update.at && version === update.to) update = {
174
+ ...update,
175
+ at: (/* @__PURE__ */ new Date()).toISOString()
176
+ };
177
+ prompts.reset({ skipsPermissions: skipsPermissions(args) });
114
178
  show(`\r\n\x1b[2m── harnessd started Claude Code ${(/* @__PURE__ */ new Date()).toLocaleString()} ──\x1b[0m\r\n`);
115
- p.onData(show);
179
+ p.onData((data) => {
180
+ show(data);
181
+ prompts.push(data);
182
+ });
116
183
  const exited = new Promise((resolve) => p.onExit(({ exitCode, signal }) => {
117
- if (pty === p) pty = void 0;
184
+ handover = onAccount?.exited();
185
+ if (pty === p) {
186
+ pty = void 0;
187
+ prompts.reset();
188
+ }
118
189
  resolve(signal ? 128 + signal : exitCode);
119
190
  }));
120
191
  return {
121
192
  pid: p.pid,
122
193
  exited,
194
+ ended: () => handover,
123
195
  kill: (signal) => {
124
196
  try {
125
197
  p.kill(signal);
@@ -133,6 +205,7 @@ const runDaemon = async (paths, bin) => {
133
205
  cols,
134
206
  rows
135
207
  };
208
+ prompts.resize(cols, rows);
136
209
  try {
137
210
  pty?.resize(cols, rows);
138
211
  } catch {}
@@ -143,13 +216,61 @@ const runDaemon = async (paths, bin) => {
143
216
  hasTranscript: (id) => findTranscript(id, transcriptEnv()) !== void 0,
144
217
  log
145
218
  });
146
- const status = () => ({
147
- ...dog.status(),
148
- daemonPid: process.pid,
149
- ...folder && { folder }
150
- });
219
+ const idle = () => {
220
+ if (idleAt === void 0 || prompts.waitingOn()) return false;
221
+ const sessionId = dog.status().sessionId;
222
+ const file = sessionId && findTranscript(sessionId, transcriptEnv());
223
+ try {
224
+ return !file || statSync(file).mtimeMs <= idleAt;
225
+ } catch {
226
+ return true;
227
+ }
228
+ };
229
+ const checkUpdate = async () => {
230
+ const run = claude;
231
+ if (run?.version === void 0) return;
232
+ const installed = await claudeVersion(run.file, run.env);
233
+ if (run !== claude) return;
234
+ if (installed === void 0 || installed === run.version) {
235
+ if (update && !update.at) update = void 0;
236
+ return;
237
+ }
238
+ const found = update?.to !== installed || update.at !== void 0;
239
+ if (found) update = {
240
+ from: run.version,
241
+ to: installed
242
+ };
243
+ if (!idle()) {
244
+ if (found) log(`Claude Code ${installed} is installed; harnessd restarts into it once the agent is idle`);
245
+ return;
246
+ }
247
+ log(`restarting Claude Code ${run.version} into ${installed}`);
248
+ await dog.restart(`it was updated from ${run.version} to ${installed}`, run.pid);
249
+ };
250
+ const status = () => {
251
+ const waitingOn = prompts.waitingOn();
252
+ const stops = rota.marks();
253
+ return {
254
+ ...dog.status(),
255
+ daemonPid: process.pid,
256
+ ...folder && { folder },
257
+ ...waitingOn && { waitingOn },
258
+ ...prompts.channelsRefused() && { channelsRefused: true },
259
+ ...claude?.version !== void 0 && { claudeVersion: claude.version },
260
+ ...update && { update },
261
+ ...account !== void 0 && { account },
262
+ ...Object.keys(stops).length > 0 && { accountsStopped: Object.fromEntries(Object.entries(stops).map(([name, { why, until }]) => [name, {
263
+ why,
264
+ until: new Date(until).toISOString()
265
+ }])) }
266
+ };
267
+ };
151
268
  const serve = (connection) => {
152
269
  const reply = (value) => connection.end(`${JSON.stringify(value)}\n`);
270
+ const done = (message) => reply({
271
+ ok: message !== NOT_STARTED,
272
+ message
273
+ });
153
274
  const lines = createInterface({ input: connection });
154
275
  let attached = false;
155
276
  connection.on("error", () => {});
@@ -179,19 +300,20 @@ const runDaemon = async (paths, bin) => {
179
300
  ok: true,
180
301
  message: await dog.stop()
181
302
  });
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({
303
+ if (request.command === "start") return void done(await dog.start());
304
+ if (request.command === "session-start") {
305
+ if (!SESSION_ID.test(String(request.sessionId))) return void reply({
188
306
  ok: false,
189
- message: "message must be text."
190
- });
191
- reply({
192
- ok: true,
193
- message: await dog.fresh(request.message)
307
+ message: "sessionId must be a conversation id."
194
308
  });
309
+ dog.follow(request.sessionId);
310
+ reply({ ok: true });
311
+ return;
312
+ }
313
+ if (request.command === "idle") {
314
+ idleAt = Date.now();
315
+ reply({ ok: true });
316
+ checkUpdate();
195
317
  return;
196
318
  }
197
319
  if (request.command === "attach") {
@@ -217,6 +339,7 @@ const runDaemon = async (paths, bin) => {
217
339
  server.listen(paths.socket, resolve);
218
340
  });
219
341
  log(`harnessd ${process.pid} started`);
342
+ setInterval(() => void checkUpdate(), UPDATE_CHECK_MS);
220
343
  let stopping = false;
221
344
  const shutdown = async (signal) => {
222
345
  if (stopping) return;
@@ -1 +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,O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mB,OAAQ,QAAkC,OAAO,EAAE;GACjF,CAAC;EACH,CAAC;CACH;CAEA,MAAM,SAAS,aAAa,KAAK;CACjC,MAAM,IAAI,SAAe,SAAS,WAAW;EAC3C,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,MAAM,QAAQ,OAAO;CACrC,CAAC;CACD,IAAI,YAAY,QAAQ,IAAI,SAAS;CAErC,IAAI,WAAW;CACf,MAAM,WAAW,OAAO,WAAmB;EACzC,IAAI,UAAU;EACd,WAAW;EACX,IAAI,gBAAgB,OAAO,uBAAuB;EAClD,MAAM,IAAI,SAAS;EACnB,KAAK,MAAM,UAAU,SAAS,OAAO,IAAI;EACzC,OAAO,MAAM;EACb,OAAO,MAAM,QAAQ,EAAE,OAAO,KAAK,CAAC;EACpC,IAAI,YAAY,QAAQ,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"}
1
+ {"version":3,"file":"daemon.js","names":[],"sources":["../src/daemon.ts"],"sourcesContent":["import {\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createConnection, createServer, type Socket } from \"node:net\";\nimport { delimiter, dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport type { IPty } from \"@lydell/node-pty\";\nimport { accountRun, rotation } from \"./accounts\";\nimport {\n claudeArgs,\n claudeVersion,\n skipsPermissions,\n findTranscript,\n prestart,\n trustFolder,\n which,\n writePlugin,\n} from \"./claude\";\nimport { ownFolder, readConfig, type Harnessd } from \"./config\";\nimport { logTo } from \"./log\";\nimport { promptWatcher } from \"./prompts\";\nimport { IDLE_SIZE, scrollback } from \"./terminal\";\nimport { NOT_STARTED, 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 /** From Claude Code's SessionStart hook: the conversation it is in now. */\n | { readonly command: \"session-start\"; readonly sessionId: string }\n /** From Claude Code's Notification hook: it waits for input, with nothing running. */\n | { readonly command: \"idle\" }\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 /** The account Claude Code runs on, when the config names accounts. */\n readonly account?: string;\n /** The accounts passed over, and until when. */\n readonly accountsStopped?: Readonly<\n Record<string, { readonly why: string; readonly until: string }>\n >;\n /** The prompt Claude Code waits at until a person answers it. */\n readonly waitingOn?: string;\n /** Claude Code said managed settings keep channels out: it drops their events. */\n readonly channelsRefused?: true;\n /** The version of the Claude Code that runs, or ran last. */\n readonly claudeVersion?: string;\n /** A newer Claude Code than the one that runs (no `at`: it starts once the agent is idle), or the last restart into one. */\n readonly update?: {\n readonly from: string;\n readonly to: string;\n readonly at?: string;\n };\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 UPDATE_CHECK_MS = 60 * 60_000;\n\nconst SESSION_ID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\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/** 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 // readline passes the connection's error on: a socket file nobody listens on (harnessd was killed) is no answer\n lines.once(\"error\", () => resolve(undefined));\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 or systemd 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 ownFolder(paths.home);\n ownFolder(dirname(paths.config));\n const socketDir = dirname(paths.socket);\n if (socketDir !== paths.home) {\n mkdirSync(socketDir, { recursive: true, mode: 0o700 });\n // a socket outside harnessd's folder sits in a shared one, where another user may have made its folder first\n if (statSync(socketDir).uid !== process.getuid!())\n throw new Error(`${socketDir} belongs to another user`);\n }\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 prompts = promptWatcher({\n write: (keys) => pty?.write(keys),\n log,\n ...size,\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 // the Claude Code that runs: how to ask the installed one its version, and which version this one is\n let claude:\n | {\n pid: number;\n file: string;\n env: NodeJS.ProcessEnv;\n version: string | undefined;\n }\n | undefined;\n // when Claude Code last said it waits for input with nothing running\n let idleAt: number | undefined;\n let update: Daemon.Status[\"update\"];\n let accounts: Harnessd.Config[\"accounts\"] = {};\n let account: string | undefined;\n const rota = rotation({\n accounts: () =>\n Object.fromEntries(\n Object.entries(accounts).map(([name, { env }]) => [name, env]),\n ),\n });\n const launch = async (start: Watchdog.Start): Promise<Watchdog.Run> => {\n const config = readConfig(paths);\n accounts = config.accounts;\n account = rota.pick(state.read().account);\n if (account !== undefined) state.write({ ...state.read(), account });\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 ...(account !== undefined && {\n ...config.accounts[account]!.env,\n HARNESSD_ACCOUNT: account,\n }),\n ...paths.env,\n };\n if (account !== undefined) log(`Claude Code runs on account ${account}`);\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 trustFolder(config.folder, env);\n writePlugin(paths, config, bin);\n // from before the start, so a refusal Claude Code writes at once is read\n const onAccount =\n account !== undefined && Object.keys(config.accounts).length > 1\n ? accountRun({\n account,\n rotation: rota,\n sessionId: () => dog.status().sessionId ?? start.sessionId,\n file: (id) => findTranscript(id, env),\n restart: (reason, pid) => void dog.restart(reason, pid),\n log,\n })\n : undefined;\n let handover: string | undefined;\n let p: IPty;\n let args: string[];\n let file: string;\n let version: string | undefined;\n // the servers' commands, ahead of any other command of the same name; after claude is found\n const spawnEnv = {\n ...env,\n PATH: [paths.bin, ...(env.PATH ? [env.PATH] : [])].join(delimiter),\n };\n try {\n file = which(\"claude\", env.PATH);\n version = await claudeVersion(file, spawnEnv);\n const { spawn } = await import(\"@lydell/node-pty\");\n args = claudeArgs({\n start,\n plugin: paths.plugin,\n config,\n extra: hook.args,\n });\n p = spawn(file, args, {\n name: \"xterm-256color\",\n cols: size.cols,\n rows: size.rows,\n cwd: config.folder,\n env: spawnEnv,\n });\n } catch (error) {\n onAccount?.exited();\n throw error;\n }\n onAccount?.started(p.pid);\n pty = p;\n claude = { pid: p.pid, file, env: spawnEnv, version };\n idleAt = undefined;\n if (update && !update.at && version === update.to)\n update = { ...update, at: new Date().toISOString() };\n prompts.reset({ skipsPermissions: skipsPermissions(args) });\n show(\n `\\r\\n\\x1b[2m── harnessd started Claude Code ${new Date().toLocaleString()} ──\\x1b[0m\\r\\n`,\n );\n p.onData((data) => {\n show(data);\n prompts.push(data);\n });\n const exited = new Promise<number>((resolve) =>\n p.onExit(({ exitCode, signal }) => {\n // the last lines too: an account that stopped right before the exit isn't started again\n handover = onAccount?.exited();\n if (pty === p) {\n pty = undefined;\n prompts.reset();\n }\n resolve(signal ? 128 + signal : exitCode);\n }),\n );\n return {\n pid: p.pid,\n exited,\n ended: () => handover,\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 prompts.resize(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 idle = () => {\n if (idleAt === undefined || prompts.waitingOn()) return false;\n // a line written since: a turn ran after Claude Code said it was idle\n const sessionId = dog.status().sessionId;\n const file = sessionId && findTranscript(sessionId, transcriptEnv());\n try {\n return !file || statSync(file).mtimeMs <= idleAt;\n } catch {\n return true;\n }\n };\n\n // Claude Code's own updater installs a new version, which the one that runs only uses from its next start\n const checkUpdate = async () => {\n const run = claude;\n if (run?.version === undefined) return;\n const installed = await claudeVersion(run.file, run.env);\n if (run !== claude) return;\n if (installed === undefined || installed === run.version) {\n if (update && !update.at) update = undefined;\n return;\n }\n const found = update?.to !== installed || update.at !== undefined;\n if (found) update = { from: run.version, to: installed };\n if (!idle()) {\n if (found)\n log(\n `Claude Code ${installed} is installed; harnessd restarts into it once the agent is idle`,\n );\n return;\n }\n log(`restarting Claude Code ${run.version} into ${installed}`);\n await dog.restart(\n `it was updated from ${run.version} to ${installed}`,\n run.pid,\n );\n };\n\n const status = (): Daemon.Status => {\n const waitingOn = prompts.waitingOn();\n const stops = rota.marks();\n return {\n ...dog.status(),\n daemonPid: process.pid,\n ...(folder && { folder }),\n ...(waitingOn && { waitingOn }),\n ...(prompts.channelsRefused() && { channelsRefused: true as const }),\n ...(claude?.version !== undefined && { claudeVersion: claude.version }),\n ...(update && { update }),\n ...(account !== undefined && { account }),\n ...(Object.keys(stops).length > 0 && {\n accountsStopped: Object.fromEntries(\n Object.entries(stops).map(([name, { why, until }]) => [\n name,\n { why, until: new Date(until).toISOString() },\n ]),\n ),\n }),\n };\n };\n\n const serve = (connection: Socket) => {\n const reply = (value: unknown) =>\n connection.end(`${JSON.stringify(value)}\\n`);\n const done = (message: string) =>\n reply({ ok: message !== NOT_STARTED, message });\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\") return void done(await dog.start());\n if (request.command === \"session-start\") {\n if (!SESSION_ID.test(String(request.sessionId)))\n return void reply({\n ok: false,\n message: \"sessionId must be a conversation id.\",\n });\n dog.follow(request.sessionId);\n return void reply({ ok: true });\n }\n if (request.command === \"idle\") {\n idleAt = Date.now();\n reply({ ok: true });\n return void checkUpdate();\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 setInterval(() => void checkUpdate(), UPDATE_CHECK_MS);\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":";;;;;;;;;;;;AAoEA,MA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CAAC;CACD,IAAI,YAAY,QAAQ,IAAI,SAAS;CACrC,kBAAkB,KAAK,YAAY,GAAG,eAAe;CAErD,IAAI,WAAW;CACf,MAAM,WAAW,OAAO,WAAmB;EACzC,IAAI,UAAU;EACd,WAAW;EACX,IAAI,gBAAgB,OAAO,uBAAuB;EAClD,MAAM,IAAI,SAAS;EACnB,KAAK,MAAM,UAAU,SAAS,OAAO,IAAI;EACzC,OAAO,MAAM;EACb,OAAO,MAAM,QAAQ,EAAE,OAAO,KAAK,CAAC;EACpC,IAAI,YAAY,QAAQ,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"}
package/dist/launchd.d.ts CHANGED
@@ -1,22 +1,18 @@
1
- import type { Harnessd } from "./config.js";
1
+ import type { Service } from "./service.js";
2
2
  /**
3
- * The node the LaunchAgent starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
3
+ * The node the service starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
4
4
  * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
5
5
  * harnessd unable to start. None that is this one: `process.execPath`.
6
6
  */
7
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;
8
+ /** The entry's lines that name harnessd's state folder: what tells one harnessd's entry from another's. */
9
+ export declare const plistFolder: (home: string) => string;
10
+ /** A LaunchAgent in the user's own folder, or for a boot service a LaunchDaemon. */
11
+ export declare const plistPath: (label: string, boot?: boolean) => string;
12
+ /** The launchd entry: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
13
+ export declare const plistOf: (o: Service.Spec) => string;
14
+ /** Writes the launchd entry and (re)loads it, which starts harnessd. */
15
+ export declare const load: (label: string, plist: string, boot: boolean) => Promise<void>;
16
+ /** Stops harnessd (it stops Claude Code first) and removes the launchd entry. */
17
+ export declare const unload: (label: string, boot: boolean) => boolean;
22
18
  //# sourceMappingURL=launchd.d.ts.map
@@ -1 +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"}
1
+ {"version":3,"file":"launchd.d.ts","sourceRoot":"","sources":["../src/launchd.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,OAAO,EAAE,qBAAkB;AAMzC;;;;GAIG;AACH,eAAO,MAAM,UAAU,GACrB,iBAA2B,EAC3B,aAA6B,WAiB9B,CAAC;AAEF,2GAA2G;AAC3G,eAAO,MAAM,WAAW,GAAI,MAAM,MAAM,WAC0B,CAAC;AAEnE,oFAAoF;AACpF,eAAO,MAAM,SAAS,GAAI,OAAO,MAAM,EAAE,cAAY,WAGa,CAAC;AAEnE,4GAA4G;AAC5G,eAAO,MAAM,OAAO,GAClB,GAAG,OAAO,CAAC,IAAI,WAqChB,CAAC;AAUF,wEAAwE;AACxE,eAAO,MAAM,IAAI,GAAU,OAAO,MAAM,EAAE,OAAO,MAAM,EAAE,MAAM,OAAO,kBAYrE,CAAC;AAEF,iFAAiF;AACjF,eAAO,MAAM,MAAM,GAAI,OAAO,MAAM,EAAE,MAAM,OAAO,YAYlD,CAAC"}
package/dist/launchd.js CHANGED
@@ -1,11 +1,11 @@
1
+ import { system } from "./system.js";
1
2
  import { accessSync, constants, existsSync, mkdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
- import { spawnSync } from "node:child_process";
3
3
  import { homedir } from "node:os";
4
- import { delimiter, join } from "node:path";
4
+ import { delimiter, dirname, join } from "node:path";
5
5
  // src/launchd.ts
6
6
  const xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
7
7
  /**
8
- * The node the LaunchAgent starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
8
+ * The node the service starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
9
9
  * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
10
10
  * harnessd unable to start. None that is this one: `process.execPath`.
11
11
  */
@@ -26,15 +26,18 @@ const stableNode = (execPath = process.execPath, path = process.env.PATH ?? "")
26
26
  }
27
27
  return execPath;
28
28
  };
29
- const plistPath = (label) => join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
30
- /** The LaunchAgent: `node <bin> run` at login and after any exit. */
29
+ /** The entry's lines that name harnessd's state folder: what tells one harnessd's entry from another's. */
30
+ const plistFolder = (home) => ` <key>WorkingDirectory</key>\n <string>${xml(home)}</string>`;
31
+ /** A LaunchAgent in the user's own folder, or for a boot service a LaunchDaemon. */
32
+ const plistPath = (label, boot = false) => boot ? `/Library/LaunchDaemons/${label}.plist` : join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
33
+ /** The launchd entry: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
31
34
  const plistOf = (o) => `<?xml version="1.0" encoding="UTF-8"?>
32
35
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
33
36
  <plist version="1.0">
34
37
  <dict>
35
38
  <key>Label</key>
36
39
  <string>${xml(o.label)}</string>
37
- <key>ProgramArguments</key>
40
+ ${o.user === void 0 ? "" : ` <key>UserName</key>\n <string>${xml(o.user)}</string>\n`} <key>ProgramArguments</key>
38
41
  <array>
39
42
  <string>${xml(o.node)}</string>
40
43
  <string>${xml(o.bin)}</string>
@@ -44,8 +47,7 @@ const plistOf = (o) => `<?xml version="1.0" encoding="UTF-8"?>
44
47
  <dict>
45
48
  ${Object.entries(o.env).map(([key, value]) => ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`).join("\n")}
46
49
  </dict>
47
- <key>WorkingDirectory</key>
48
- <string>${xml(o.paths.home)}</string>
50
+ ${plistFolder(o.paths.home)}
49
51
  <key>RunAtLoad</key>
50
52
  <true/>
51
53
  <key>KeepAlive</key>
@@ -55,34 +57,35 @@ ${Object.entries(o.env).map(([key, value]) => ` <key>${xml(key)}</key>\n <
55
57
  <key>ProcessType</key>
56
58
  <string>Interactive</string>
57
59
  <key>StandardOutPath</key>
58
- <string>${xml(join(o.paths.home, "launchd.log"))}</string>
60
+ <string>${xml(o.paths.serviceLog)}</string>
59
61
  <key>StandardErrorPath</key>
60
- <string>${xml(join(o.paths.home, "launchd.log"))}</string>
62
+ <string>${xml(o.paths.serviceLog)}</string>
61
63
  </dict>
62
64
  </plist>
63
65
  `;
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));
66
+ const domain = (boot) => boot ? "system" : `gui/${process.getuid()}`;
67
+ const launchctl = (...args) => system("launchctl", args);
68
+ const loaded = (label, boot) => launchctl("print", `${domain(boot)}/${label}`).status === 0;
69
+ /** Writes the launchd entry and (re)loads it, which starts harnessd. */
70
+ const load = async (label, plist, boot) => {
71
+ mkdirSync(dirname(plistPath(label, boot)), { recursive: true });
72
+ if (loaded(label, boot)) launchctl("bootout", `${domain(boot)}/${label}`);
73
+ for (let i = 0; loaded(label, boot) && i < 400; i++) await new Promise((resolve) => setTimeout(resolve, 100));
74
+ writeFileSync(plistPath(label, boot), plist, { mode: 420 });
75
+ const result = launchctl("bootstrap", domain(boot), plistPath(label, boot));
73
76
  if (result.status !== 0) throw new Error(`launchctl bootstrap failed: ${(result.stderr || result.stdout).trim()}`);
74
77
  };
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}`);
78
+ /** Stops harnessd (it stops Claude Code first) and removes the launchd entry. */
79
+ const unload = (label, boot) => {
80
+ if (loaded(label, boot)) {
81
+ const result = launchctl("bootout", `${domain(boot)}/${label}`);
79
82
  if (result.status !== 0) throw new Error(`launchctl bootout failed: ${(result.stderr || result.stdout).trim()}`);
80
83
  }
81
- const plist = plistPath(label);
84
+ const plist = plistPath(label, boot);
82
85
  const had = existsSync(plist);
83
86
  rmSync(plist, { force: true });
84
87
  return had;
85
88
  };
86
- export { load, loaded, plistOf, plistPath, stableNode, unload };
89
+ export { load, plistFolder, plistOf, plistPath, stableNode, unload };
87
90
 
88
91
  //# sourceMappingURL=launchd.js.map
@@ -1 +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 );\n }\n const plist = plistPath(label);\n const had = existsSync(plist);\n rmSync(plist, { force: true });\n return had;\n};\n"],"mappings":";;;;;AAcA,MAAM,OAAO,UACX,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;;;;;;AAOzE,MAAa,cACX,WAAW,QAAQ,UACnB,OAAO,QAAQ,IAAI,QAAQ,OACxB;CACH,IAAI;CACJ,IAAI;EACF,OAAO,aAAa,QAAQ;CAC9B,QAAQ;EACN,OAAO;CACT;CACA,KAAK,MAAM,OAAO,KAAK,MAAM,SAAS,GAAG;EACvC,IAAI,CAAC,IAAI,WAAW,GAAG,GAAG;EAC1B,MAAM,YAAY,KAAK,KAAK,MAAM;EAClC,IAAI;GACF,WAAW,WAAW,UAAU,IAAI;GACpC,IAAI,aAAa,SAAS,MAAM,MAAM,OAAO;EAC/C,QAAQ,CAAC;CACX;CACA,OAAO;AACT;AAEA,MAAa,aAAa,UACxB,KAAK,QAAQ,GAAG,WAAW,gBAAgB,GAAG,MAAM,OAAO;;AAG7D,MAAa,WAAW,MAMlB;;;;;YAKM,IAAI,EAAE,KAAK,EAAE;;;cAGX,IAAI,EAAE,IAAI,EAAE;cACZ,IAAI,EAAE,GAAG,EAAE;;;;;EAKvB,OAAO,QAAQ,EAAE,GAAG,CAAC,CACpB,KACE,CAAC,KAAK,WACL,YAAY,IAAI,GAAG,EAAE,sBAAsB,IAAI,KAAK,EAAE,UAC1D,CAAC,CACA,KAAK,IAAI,EAAE;;;YAGF,IAAI,EAAE,MAAM,IAAI,EAAE;;;;;;;;;;YAUlB,IAAI,KAAK,EAAE,MAAM,MAAM,aAAa,CAAC,EAAE;;YAEvC,IAAI,KAAK,EAAE,MAAM,MAAM,aAAa,CAAC,EAAE;;;;AAKnD,MAAM,eAAe,OAAO,QAAQ,OAAQ;AAE5C,MAAM,aAAa,GAAG,SACpB,UAAU,aAAa,MAAM,EAAE,UAAU,OAAO,CAAC;AAEnD,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"}
1
+ {"version":3,"file":"launchd.js","names":[],"sources":["../src/launchd.ts"],"sourcesContent":["import {\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, dirname, join } from \"node:path\";\nimport type { Service } from \"./service\";\nimport { system } from \"./system\";\n\nconst xml = (value: string) =>\n value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\n/**\n * The node the service 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\n/** The entry's lines that name harnessd's state folder: what tells one harnessd's entry from another's. */\nexport const plistFolder = (home: string) =>\n ` <key>WorkingDirectory</key>\\n <string>${xml(home)}</string>`;\n\n/** A LaunchAgent in the user's own folder, or for a boot service a LaunchDaemon. */\nexport const plistPath = (label: string, boot = false) =>\n boot\n ? `/Library/LaunchDaemons/${label}.plist`\n : join(homedir(), \"Library\", \"LaunchAgents\", `${label}.plist`);\n\n/** The launchd entry: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */\nexport const plistOf = (\n o: Service.Spec,\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${o.user === undefined ? \"\" : ` <key>UserName</key>\\n <string>${xml(o.user)}</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${plistFolder(o.paths.home)}\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(o.paths.serviceLog)}</string>\n <key>StandardErrorPath</key>\n <string>${xml(o.paths.serviceLog)}</string>\n</dict>\n</plist>\n`;\n\nconst domain = (boot: boolean) =>\n boot ? \"system\" : `gui/${process.getuid!()}`;\n\nconst launchctl = (...args: string[]) => system(\"launchctl\", args);\n\nconst loaded = (label: string, boot: boolean) =>\n launchctl(\"print\", `${domain(boot)}/${label}`).status === 0;\n\n/** Writes the launchd entry and (re)loads it, which starts harnessd. */\nexport const load = async (label: string, plist: string, boot: boolean) => {\n mkdirSync(dirname(plistPath(label, boot)), { recursive: true });\n if (loaded(label, boot)) launchctl(\"bootout\", `${domain(boot)}/${label}`);\n // bootout returns while the old harnessd still stops Claude Code; a bootstrap before it is gone fails\n for (let i = 0; loaded(label, boot) && i < 400; i++)\n await new Promise((resolve) => setTimeout(resolve, 100));\n writeFileSync(plistPath(label, boot), plist, { mode: 0o644 });\n const result = launchctl(\"bootstrap\", domain(boot), plistPath(label, boot));\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 launchd entry. */\nexport const unload = (label: string, boot: boolean) => {\n if (loaded(label, boot)) {\n const result = launchctl(\"bootout\", `${domain(boot)}/${label}`);\n if (result.status !== 0)\n throw new Error(\n `launchctl bootout failed: ${(result.stderr || result.stdout).trim()}`,\n );\n }\n const plist = plistPath(label, boot);\n const had = existsSync(plist);\n rmSync(plist, { force: true });\n return had;\n};\n"],"mappings":";;;;;AAcA,MAAM,OAAO,UACX,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;;;;;;AAOzE,MAAa,cACX,WAAW,QAAQ,UACnB,OAAO,QAAQ,IAAI,QAAQ,OACxB;CACH,IAAI;CACJ,IAAI;EACF,OAAO,aAAa,QAAQ;CAC9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