@harness-sdk/harnessd 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +14 -13
  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.js +1 -1
  9. package/dist/claude.d.ts +12 -13
  10. package/dist/claude.d.ts.map +1 -1
  11. package/dist/claude.js +45 -59
  12. package/dist/claude.js.map +1 -1
  13. package/dist/cli.d.ts +5 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +269 -114
  16. package/dist/cli.js.map +1 -1
  17. package/dist/config.d.ts +14 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +53 -13
  20. package/dist/config.js.map +1 -1
  21. package/dist/daemon.d.ts +17 -4
  22. package/dist/daemon.d.ts.map +1 -1
  23. package/dist/daemon.js +112 -51
  24. package/dist/daemon.js.map +1 -1
  25. package/dist/launchd.d.ts +12 -16
  26. package/dist/launchd.d.ts.map +1 -1
  27. package/dist/launchd.js +28 -25
  28. package/dist/launchd.js.map +1 -1
  29. package/dist/prompts.d.ts +53 -0
  30. package/dist/prompts.d.ts.map +1 -0
  31. package/dist/prompts.js +171 -0
  32. package/dist/prompts.js.map +1 -0
  33. package/dist/service.d.ts +37 -0
  34. package/dist/service.d.ts.map +1 -0
  35. package/dist/service.js +71 -0
  36. package/dist/service.js.map +1 -0
  37. package/dist/setup.d.ts +37 -0
  38. package/dist/setup.d.ts.map +1 -0
  39. package/dist/setup.js +121 -0
  40. package/dist/setup.js.map +1 -0
  41. package/dist/system.d.ts +6 -0
  42. package/dist/system.d.ts.map +1 -0
  43. package/dist/system.js +16 -0
  44. package/dist/system.js.map +1 -0
  45. package/dist/systemd.d.ts +14 -0
  46. package/dist/systemd.d.ts.map +1 -0
  47. package/dist/systemd.js +62 -0
  48. package/dist/systemd.js.map +1 -0
  49. package/dist/watchdog.d.ts +14 -4
  50. package/dist/watchdog.d.ts.map +1 -1
  51. package/dist/watchdog.js +30 -24
  52. package/dist/watchdog.js.map +1 -1
  53. package/package.json +5 -3
  54. package/src/accounts.ts +242 -0
  55. package/src/bin.ts +6 -0
  56. package/src/claude.ts +65 -90
  57. package/src/cli.ts +413 -152
  58. package/src/config.ts +92 -14
  59. package/src/daemon.ts +131 -64
  60. package/src/launchd.ts +40 -35
  61. package/src/prompts.ts +255 -0
  62. package/src/service.ts +145 -0
  63. package/src/setup.ts +188 -0
  64. package/src/system.ts +11 -0
  65. package/src/systemd.ts +78 -0
  66. package/src/watchdog.ts +41 -33
package/dist/daemon.js CHANGED
@@ -1,22 +1,19 @@
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, 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 { 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 SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
16
  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
17
  /** Sends one request to a running harnessd; undefined when none answers. */
21
18
  const ask = (socket, request) => new Promise((resolve) => {
22
19
  if (!existsSync(socket)) return resolve(void 0);
@@ -24,6 +21,7 @@ const ask = (socket, request) => new Promise((resolve) => {
24
21
  connection.once("error", () => resolve(void 0));
25
22
  connection.once("connect", () => connection.write(`${JSON.stringify(request)}\n`));
26
23
  const lines = createInterface({ input: connection });
24
+ lines.once("error", () => resolve(void 0));
27
25
  lines.once("line", (line) => {
28
26
  connection.end();
29
27
  try {
@@ -34,9 +32,18 @@ const ask = (socket, request) => new Promise((resolve) => {
34
32
  });
35
33
  lines.once("close", () => resolve(void 0));
36
34
  });
37
- /** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
35
+ /** `harnessd run`: what launchd or systemd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
38
36
  const runDaemon = async (paths, bin) => {
39
- mkdirSync(paths.home, { recursive: true });
37
+ ownFolder(paths.home);
38
+ ownFolder(dirname(paths.config));
39
+ const socketDir = dirname(paths.socket);
40
+ if (socketDir !== paths.home) {
41
+ mkdirSync(socketDir, {
42
+ recursive: true,
43
+ mode: 448
44
+ });
45
+ if (statSync(socketDir).uid !== process.getuid()) throw new Error(`${socketDir} belongs to another user`);
46
+ }
40
47
  const log = logTo(paths.log);
41
48
  if (await ask(paths.socket, { command: "status" })) throw new Error(`Another harnessd already runs in ${paths.home}`);
42
49
  rmSync(paths.socket, { force: true });
@@ -51,6 +58,11 @@ const runDaemon = async (paths, bin) => {
51
58
  for (const viewer of viewers) if (viewer.writableLength > VIEWER_BUFFER) viewer.destroy();
52
59
  else viewer.write(line);
53
60
  };
61
+ const prompts = promptWatcher({
62
+ write: (keys) => pty?.write(keys),
63
+ log,
64
+ ...size
65
+ });
54
66
  const state = {
55
67
  read: () => {
56
68
  try {
@@ -73,15 +85,29 @@ const runDaemon = async (paths, bin) => {
73
85
  return process.env;
74
86
  }
75
87
  };
88
+ let accounts = {};
89
+ let account;
90
+ const rota = rotation({ accounts: () => Object.fromEntries(Object.entries(accounts).map(([name, { env }]) => [name, env])) });
76
91
  const launch = async (start) => {
77
92
  const config = readConfig(paths);
93
+ accounts = config.accounts;
94
+ account = rota.pick(state.read().account);
95
+ if (account !== void 0) state.write({
96
+ ...state.read(),
97
+ account
98
+ });
78
99
  folder = config.folder;
79
100
  mkdirSync(config.folder, { recursive: true });
80
101
  const base = {
81
102
  ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !OWN_ENV.test(key))),
82
103
  ...config.env,
83
- HARNESSD_HOME: paths.home
104
+ ...account !== void 0 && {
105
+ ...config.accounts[account].env,
106
+ HARNESSD_ACCOUNT: account
107
+ },
108
+ ...paths.env
84
109
  };
110
+ if (account !== void 0) log(`Claude Code runs on account ${account}`);
85
111
  const hook = config.prestart ? await prestart(config.prestart, config.folder, base, log) : {
86
112
  env: {},
87
113
  args: []
@@ -91,35 +117,59 @@ const runDaemon = async (paths, bin) => {
91
117
  ...hook.env
92
118
  };
93
119
  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
- });
120
+ trustFolder(config.folder, env);
121
+ writePlugin(paths, config, bin);
122
+ const onAccount = account !== void 0 && Object.keys(config.accounts).length > 1 ? accountRun({
123
+ account,
124
+ rotation: rota,
125
+ sessionId: () => dog.status().sessionId ?? start.sessionId,
126
+ file: (id) => findTranscript(id, env),
127
+ restart: (reason, pid) => void dog.restart(reason, pid),
128
+ log
129
+ }) : void 0;
130
+ let handover;
131
+ let p;
132
+ let args;
133
+ try {
134
+ const file = which("claude", env.PATH);
135
+ const { spawn } = await import("@lydell/node-pty");
136
+ args = claudeArgs({
137
+ start,
138
+ plugin: paths.plugin,
139
+ config,
140
+ extra: hook.args
141
+ });
142
+ p = spawn(file, args, {
143
+ name: "xterm-256color",
144
+ cols: size.cols,
145
+ rows: size.rows,
146
+ cwd: config.folder,
147
+ env
148
+ });
149
+ } catch (error) {
150
+ onAccount?.exited();
151
+ throw error;
152
+ }
153
+ onAccount?.started(p.pid);
113
154
  pty = p;
155
+ prompts.reset({ skipsPermissions: skipsPermissions(args) });
114
156
  show(`\r\n\x1b[2m── harnessd started Claude Code ${(/* @__PURE__ */ new Date()).toLocaleString()} ──\x1b[0m\r\n`);
115
- p.onData(show);
157
+ p.onData((data) => {
158
+ show(data);
159
+ prompts.push(data);
160
+ });
116
161
  const exited = new Promise((resolve) => p.onExit(({ exitCode, signal }) => {
117
- if (pty === p) pty = void 0;
162
+ handover = onAccount?.exited();
163
+ if (pty === p) {
164
+ pty = void 0;
165
+ prompts.reset();
166
+ }
118
167
  resolve(signal ? 128 + signal : exitCode);
119
168
  }));
120
169
  return {
121
170
  pid: p.pid,
122
171
  exited,
172
+ ended: () => handover,
123
173
  kill: (signal) => {
124
174
  try {
125
175
  p.kill(signal);
@@ -133,6 +183,7 @@ const runDaemon = async (paths, bin) => {
133
183
  cols,
134
184
  rows
135
185
  };
186
+ prompts.resize(cols, rows);
136
187
  try {
137
188
  pty?.resize(cols, rows);
138
189
  } catch {}
@@ -143,13 +194,28 @@ const runDaemon = async (paths, bin) => {
143
194
  hasTranscript: (id) => findTranscript(id, transcriptEnv()) !== void 0,
144
195
  log
145
196
  });
146
- const status = () => ({
147
- ...dog.status(),
148
- daemonPid: process.pid,
149
- ...folder && { folder }
150
- });
197
+ const status = () => {
198
+ const waitingOn = prompts.waitingOn();
199
+ const stops = rota.marks();
200
+ return {
201
+ ...dog.status(),
202
+ daemonPid: process.pid,
203
+ ...folder && { folder },
204
+ ...waitingOn && { waitingOn },
205
+ ...prompts.channelsRefused() && { channelsRefused: true },
206
+ ...account !== void 0 && { account },
207
+ ...Object.keys(stops).length > 0 && { accountsStopped: Object.fromEntries(Object.entries(stops).map(([name, { why, until }]) => [name, {
208
+ why,
209
+ until: new Date(until).toISOString()
210
+ }])) }
211
+ };
212
+ };
151
213
  const serve = (connection) => {
152
214
  const reply = (value) => connection.end(`${JSON.stringify(value)}\n`);
215
+ const done = (message) => reply({
216
+ ok: message !== NOT_STARTED,
217
+ message
218
+ });
153
219
  const lines = createInterface({ input: connection });
154
220
  let attached = false;
155
221
  connection.on("error", () => {});
@@ -179,19 +245,14 @@ const runDaemon = async (paths, bin) => {
179
245
  ok: true,
180
246
  message: await dog.stop()
181
247
  });
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({
248
+ if (request.command === "start") return void done(await dog.start());
249
+ if (request.command === "session-start") {
250
+ if (!SESSION_ID.test(String(request.sessionId))) return void reply({
188
251
  ok: false,
189
- message: "message must be text."
190
- });
191
- reply({
192
- ok: true,
193
- message: await dog.fresh(request.message)
252
+ message: "sessionId must be a conversation id."
194
253
  });
254
+ dog.follow(request.sessionId);
255
+ reply({ ok: true });
195
256
  return;
196
257
  }
197
258
  if (request.command === "attach") {
@@ -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,OAAO,OAAO;AAChB;;AAGA,MAAa,OAAO,QAAgB,YAClC,IAAI,SAA8C,YAAY;CAC5D,IAAI,CAAC,WAAW,MAAM,GAAG,OAAO,QAAQ,KAAA,CAAS;CACjD,MAAM,aAAa,iBAAiB,MAAM;CAC1C,WAAW,KAAK,eAAe,QAAQ,KAAA,CAAS,CAAC;CACjD,WAAW,KAAK,iBACd,WAAW,MAAM,GAAG,KAAK,UAAU,OAAO,EAAE,GAAG,CACjD;CACA,MAAM,QAAQ,gBAAgB,EAAE,OAAO,WAAW,CAAC;CAC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BAAuB;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 { 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 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 | {\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 };\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 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 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 try {\n const file = which(\"claude\", env.PATH);\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,\n });\n } catch (error) {\n onAccount?.exited();\n throw error;\n }\n onAccount?.started(p.pid);\n pty = p;\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 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 ...(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 === \"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":";;;;;;;;;;;;AAyDA,MAAM,UACJ;AAEF,MAAM,gBAAgB;AAEtB,MAAM,aACJ;AAEF,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,MAAa,OAAO,QAAgB,YAClC,IAAI,SAA8C,YAAY;CAC5D,IAAI,CAAC,WAAW,MAAM,GAAG,OAAO,QAAQ,KAAA,CAAS;CACjD,MAAM,aAAa,iBAAiB,MAAM;CAC1C,WAAW,KAAK,eAAe,QAAQ,KAAA,CAAS,CAAC;CACjD,WAAW,KAAK,iBACd,WAAW,MAAM,GAAG,KAAK,UAAU,OAAO,EAAE,GAAG,CACjD;CACA,MAAM,QAAQ,gBAAgB,EAAE,OAAO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QAAQ,KAAK,KAAK,EAAE,CAAC,EAAE,GAAG;IAC/D,WAAW,GAAG,eAAe;KAC3B,QAAQ,OAAO,UAAU;KACzB,IAAI,QAAQ,SAAS,GAAG,OAAO,UAAU,MAAM,UAAU,IAAI;IAC/D,CAAC;IACD;GACF;GACA,MAAM;IACJ,IAAI;IACJ,SAAS,mBAAmB,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"}
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,QAA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+ {"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;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;;AAGA,MAAa,eAAe,SAC1B,4CAA4C,IAAI,IAAI,EAAE;;AAGxD,MAAa,aAAa,OAAe,OAAO,UAC9C,OACI,0BAA0B,MAAM,UAChC,KAAK,QAAQ,GAAG,WAAW,gBAAgB,GAAG,MAAM,OAAO;;AAGjE,MAAa,WACX,MACG;;;;;YAKO,IAAI,EAAE,KAAK,EAAE;EACvB,EAAE,SAAS,KAAA,IAAY,KAAK,oCAAoC,IAAI,EAAE,IAAI,EAAE,aAAa;;cAE7E,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;;EAEZ,YAAY,EAAE,MAAM,IAAI,EAAE;;;;;;;;;;YAU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+1,53 @@
1
+ export declare namespace Prompts {
2
+ /** A screen where Claude Code waits for an answer before it goes on. */
3
+ type Prompt = {
4
+ readonly name: string;
5
+ /** Matches the end of the screen, read without its whitespace. */
6
+ readonly shows: RegExp;
7
+ /** How the option harnessd picks starts, or "" where Enter is the answer. Absent: only a person can answer, and `harnessd status` says so. */
8
+ readonly pick?: string;
9
+ /** Answered only for a start whose arguments turn permission prompts off; otherwise a person answers. */
10
+ readonly forSkippedPermissions?: true;
11
+ /** What this screen asks about, read from the screen as drawn: it follows the name, as `<name>: <subject>`. */
12
+ readonly subject?: (screen: readonly string[]) => string | undefined;
13
+ };
14
+ type Found = {
15
+ readonly prompt: Prompt;
16
+ /** The prompt's name, with what it asks about when the screen says. */
17
+ readonly name: string;
18
+ /** What to type, when harnessd answers this prompt. */
19
+ readonly keys?: string;
20
+ };
21
+ type Options = {
22
+ /** Types into Claude Code's terminal. */
23
+ readonly write: (keys: string) => void;
24
+ readonly log: (line: string) => void;
25
+ readonly cols: number;
26
+ readonly rows: number;
27
+ readonly quietMs?: number;
28
+ };
29
+ type Watcher = {
30
+ /** Claude Code's terminal output. */
31
+ readonly push: (data: string) => void;
32
+ readonly resize: (cols: number, rows: number) => void;
33
+ /** A new start of Claude Code: an empty screen. `skipsPermissions`: its arguments turn permission prompts off. */
34
+ readonly reset: (start?: {
35
+ skipsPermissions?: boolean;
36
+ }) => void;
37
+ /** The prompt Claude Code waits at for a person, if any. */
38
+ readonly waitingOn: () => string | undefined;
39
+ /** Whether this start's screen said managed settings keep harnessd's channels out. */
40
+ readonly channelsRefused: () => boolean;
41
+ };
42
+ }
43
+ /** The prompts of Claude Code 2.1 that stop a start nobody watches. */
44
+ export declare const PROMPTS: readonly Prompts.Prompt[];
45
+ /** The prompt a screen ends with, and the keys that answer it. */
46
+ export declare const findPrompt: (screen: readonly string[], prompts?: readonly Prompts.Prompt[]) => Prompts.Found | undefined;
47
+ /** What harnessd says when Claude Code refuses its channels. */
48
+ export declare const CHANNELS_REFUSED = "Claude Code refused harnessd's channels: managed settings block channels (channelsEnabled isn't true), so their events are dropped. Whoever manages Claude Code's settings for this organization or this computer has to set channelsEnabled; harnessd leaves them alone.";
49
+ /** Claude Code's start notice when a Team or Enterprise organization's (or this Mac's) managed settings keep channels out. */
50
+ export declare const channelsRefused: (screen: readonly string[]) => boolean;
51
+ /** Reads Claude Code's screen as its output arrives and answers the prompts harnessd knows. */
52
+ export declare const promptWatcher: (options: Prompts.Options) => Prompts.Watcher;
53
+ //# sourceMappingURL=prompts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompts.d.ts","sourceRoot":"","sources":["../src/prompts.ts"],"names":[],"mappings":"AAEA,yBAAiB,OAAO,CAAC;IACvB,wEAAwE;IACxE,KAAY,MAAM,GAAG;QACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QACtB,kEAAkE;QAClE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;QACvB,8IAA8I;QAC9I,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QACvB,yGAAyG;QACzG,QAAQ,CAAC,qBAAqB,CAAC,EAAE,IAAI,CAAC;QACtC,+GAA+G;QAC/G,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,KAAK,MAAM,GAAG,SAAS,CAAC;KACtE,CAAC;IAEF,KAAY,KAAK,GAAG;QAClB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QACxB,uEAAuE;QACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QACtB,uDAAuD;QACvD,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IAEF,KAAY,OAAO,GAAG;QACpB,yCAAyC;QACzC,QAAQ,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;QACvC,QAAQ,CAAC,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CA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