@harness-sdk/harnessd 0.0.0 → 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 (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -2
  3. package/dist/accounts.d.ts +66 -0
  4. package/dist/accounts.d.ts.map +1 -0
  5. package/dist/accounts.js +166 -0
  6. package/dist/accounts.js.map +1 -0
  7. package/dist/bin.d.ts +3 -0
  8. package/dist/bin.d.ts.map +1 -0
  9. package/dist/bin.js +19 -0
  10. package/dist/bin.js.map +1 -0
  11. package/dist/channel.d.ts +56 -0
  12. package/dist/channel.d.ts.map +1 -0
  13. package/dist/channel.js +356 -0
  14. package/dist/channel.js.map +1 -0
  15. package/dist/claude.d.ts +41 -0
  16. package/dist/claude.d.ts.map +1 -0
  17. package/dist/claude.js +152 -0
  18. package/dist/claude.js.map +1 -0
  19. package/dist/cli.d.ts +13 -0
  20. package/dist/cli.d.ts.map +1 -0
  21. package/dist/cli.js +413 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/config.d.ts +56 -0
  24. package/dist/config.d.ts.map +1 -0
  25. package/dist/config.js +161 -0
  26. package/dist/config.js.map +1 -0
  27. package/dist/daemon.d.ts +37 -0
  28. package/dist/daemon.d.ts.map +1 -0
  29. package/dist/daemon.js +300 -0
  30. package/dist/daemon.js.map +1 -0
  31. package/dist/launchd.d.ts +18 -0
  32. package/dist/launchd.d.ts.map +1 -0
  33. package/dist/launchd.js +91 -0
  34. package/dist/launchd.js.map +1 -0
  35. package/dist/log.d.ts +3 -0
  36. package/dist/log.d.ts.map +1 -0
  37. package/dist/log.js +17 -0
  38. package/dist/log.js.map +1 -0
  39. package/dist/prompts.d.ts +53 -0
  40. package/dist/prompts.d.ts.map +1 -0
  41. package/dist/prompts.js +171 -0
  42. package/dist/prompts.js.map +1 -0
  43. package/dist/service.d.ts +37 -0
  44. package/dist/service.d.ts.map +1 -0
  45. package/dist/service.js +71 -0
  46. package/dist/service.js.map +1 -0
  47. package/dist/setup.d.ts +37 -0
  48. package/dist/setup.d.ts.map +1 -0
  49. package/dist/setup.js +121 -0
  50. package/dist/setup.js.map +1 -0
  51. package/dist/system.d.ts +6 -0
  52. package/dist/system.d.ts.map +1 -0
  53. package/dist/system.js +16 -0
  54. package/dist/system.js.map +1 -0
  55. package/dist/systemd.d.ts +14 -0
  56. package/dist/systemd.d.ts.map +1 -0
  57. package/dist/systemd.js +62 -0
  58. package/dist/systemd.js.map +1 -0
  59. package/dist/terminal.d.ts +11 -0
  60. package/dist/terminal.d.ts.map +1 -0
  61. package/dist/terminal.js +36 -0
  62. package/dist/terminal.js.map +1 -0
  63. package/dist/watchdog.d.ts +83 -0
  64. package/dist/watchdog.d.ts.map +1 -0
  65. package/dist/watchdog.js +236 -0
  66. package/dist/watchdog.js.map +1 -0
  67. package/package.json +55 -6
  68. package/src/accounts.ts +242 -0
  69. package/src/bin.ts +24 -0
  70. package/src/channel.ts +461 -0
  71. package/src/claude.ts +249 -0
  72. package/src/cli.ts +633 -0
  73. package/src/config.ts +281 -0
  74. package/src/daemon.ts +379 -0
  75. package/src/launchd.ts +131 -0
  76. package/src/log.ts +17 -0
  77. package/src/prompts.ts +255 -0
  78. package/src/service.ts +145 -0
  79. package/src/setup.ts +188 -0
  80. package/src/system.ts +11 -0
  81. package/src/systemd.ts +78 -0
  82. package/src/terminal.ts +33 -0
  83. package/src/watchdog.ts +318 -0
package/src/launchd.ts ADDED
@@ -0,0 +1,131 @@
1
+ import {
2
+ accessSync,
3
+ constants,
4
+ existsSync,
5
+ mkdirSync,
6
+ realpathSync,
7
+ rmSync,
8
+ writeFileSync,
9
+ } from "node:fs";
10
+ import { homedir } from "node:os";
11
+ import { delimiter, dirname, join } from "node:path";
12
+ import type { Service } from "./service";
13
+ import { system } from "./system";
14
+
15
+ const xml = (value: string) =>
16
+ value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
17
+
18
+ /**
19
+ * The node the service starts: the first `node` on the PATH that is this node (a symlink such as Homebrew's
20
+ * /opt/homebrew/bin/node), so an upgrade that removes the versioned folder `process.execPath` points into doesn't leave
21
+ * harnessd unable to start. None that is this one: `process.execPath`.
22
+ */
23
+ export const stableNode = (
24
+ execPath = process.execPath,
25
+ path = process.env.PATH ?? "",
26
+ ) => {
27
+ let real: string;
28
+ try {
29
+ real = realpathSync(execPath);
30
+ } catch {
31
+ return execPath;
32
+ }
33
+ for (const dir of path.split(delimiter)) {
34
+ if (!dir.startsWith("/")) continue;
35
+ const candidate = join(dir, "node");
36
+ try {
37
+ accessSync(candidate, constants.X_OK);
38
+ if (realpathSync(candidate) === real) return candidate;
39
+ } catch {}
40
+ }
41
+ return execPath;
42
+ };
43
+
44
+ /** The entry's lines that name harnessd's state folder: what tells one harnessd's entry from another's. */
45
+ export const plistFolder = (home: string) =>
46
+ ` <key>WorkingDirectory</key>\n <string>${xml(home)}</string>`;
47
+
48
+ /** A LaunchAgent in the user's own folder, or for a boot service a LaunchDaemon. */
49
+ export const plistPath = (label: string, boot = false) =>
50
+ boot
51
+ ? `/Library/LaunchDaemons/${label}.plist`
52
+ : join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
53
+
54
+ /** The launchd entry: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
55
+ export const plistOf = (
56
+ o: Service.Spec,
57
+ ) => `<?xml version="1.0" encoding="UTF-8"?>
58
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
59
+ <plist version="1.0">
60
+ <dict>
61
+ <key>Label</key>
62
+ <string>${xml(o.label)}</string>
63
+ ${o.user === undefined ? "" : ` <key>UserName</key>\n <string>${xml(o.user)}</string>\n`} <key>ProgramArguments</key>
64
+ <array>
65
+ <string>${xml(o.node)}</string>
66
+ <string>${xml(o.bin)}</string>
67
+ <string>run</string>
68
+ </array>
69
+ <key>EnvironmentVariables</key>
70
+ <dict>
71
+ ${Object.entries(o.env)
72
+ .map(
73
+ ([key, value]) =>
74
+ ` <key>${xml(key)}</key>\n <string>${xml(value)}</string>`,
75
+ )
76
+ .join("\n")}
77
+ </dict>
78
+ ${plistFolder(o.paths.home)}
79
+ <key>RunAtLoad</key>
80
+ <true/>
81
+ <key>KeepAlive</key>
82
+ <true/>
83
+ <key>ExitTimeOut</key>
84
+ <integer>30</integer>
85
+ <key>ProcessType</key>
86
+ <string>Interactive</string>
87
+ <key>StandardOutPath</key>
88
+ <string>${xml(o.paths.serviceLog)}</string>
89
+ <key>StandardErrorPath</key>
90
+ <string>${xml(o.paths.serviceLog)}</string>
91
+ </dict>
92
+ </plist>
93
+ `;
94
+
95
+ const domain = (boot: boolean) =>
96
+ boot ? "system" : `gui/${process.getuid!()}`;
97
+
98
+ const launchctl = (...args: string[]) => system("launchctl", args);
99
+
100
+ const loaded = (label: string, boot: boolean) =>
101
+ launchctl("print", `${domain(boot)}/${label}`).status === 0;
102
+
103
+ /** Writes the launchd entry and (re)loads it, which starts harnessd. */
104
+ export const load = async (label: string, plist: string, boot: boolean) => {
105
+ mkdirSync(dirname(plistPath(label, boot)), { recursive: true });
106
+ if (loaded(label, boot)) launchctl("bootout", `${domain(boot)}/${label}`);
107
+ // bootout returns while the old harnessd still stops Claude Code; a bootstrap before it is gone fails
108
+ for (let i = 0; loaded(label, boot) && i < 400; i++)
109
+ await new Promise((resolve) => setTimeout(resolve, 100));
110
+ writeFileSync(plistPath(label, boot), plist, { mode: 0o644 });
111
+ const result = launchctl("bootstrap", domain(boot), plistPath(label, boot));
112
+ if (result.status !== 0)
113
+ throw new Error(
114
+ `launchctl bootstrap failed: ${(result.stderr || result.stdout).trim()}`,
115
+ );
116
+ };
117
+
118
+ /** Stops harnessd (it stops Claude Code first) and removes the launchd entry. */
119
+ export const unload = (label: string, boot: boolean) => {
120
+ if (loaded(label, boot)) {
121
+ const result = launchctl("bootout", `${domain(boot)}/${label}`);
122
+ if (result.status !== 0)
123
+ throw new Error(
124
+ `launchctl bootout failed: ${(result.stderr || result.stdout).trim()}`,
125
+ );
126
+ }
127
+ const plist = plistPath(label, boot);
128
+ const had = existsSync(plist);
129
+ rmSync(plist, { force: true });
130
+ return had;
131
+ };
package/src/log.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { appendFileSync, mkdirSync, renameSync, statSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+
4
+ const MAX_BYTES = 5 * 1024 * 1024;
5
+
6
+ /** Appends timestamped lines to `file`, keeping one older file (`.1`) past 5 MB. */
7
+ export const logTo =
8
+ (file: string, prefix = "") =>
9
+ (line: string) => {
10
+ try {
11
+ mkdirSync(dirname(file), { recursive: true });
12
+ try {
13
+ if (statSync(file).size > MAX_BYTES) renameSync(file, `${file}.1`);
14
+ } catch {}
15
+ appendFileSync(file, `${new Date().toISOString()} ${prefix}${line}\n`);
16
+ } catch {}
17
+ };
package/src/prompts.ts ADDED
@@ -0,0 +1,255 @@
1
+ import xterm from "@xterm/headless";
2
+
3
+ export namespace Prompts {
4
+ /** A screen where Claude Code waits for an answer before it goes on. */
5
+ export type Prompt = {
6
+ readonly name: string;
7
+ /** Matches the end of the screen, read without its whitespace. */
8
+ readonly shows: RegExp;
9
+ /** How the option harnessd picks starts, or "" where Enter is the answer. Absent: only a person can answer, and `harnessd status` says so. */
10
+ readonly pick?: string;
11
+ /** Answered only for a start whose arguments turn permission prompts off; otherwise a person answers. */
12
+ readonly forSkippedPermissions?: true;
13
+ /** What this screen asks about, read from the screen as drawn: it follows the name, as `<name>: <subject>`. */
14
+ readonly subject?: (screen: readonly string[]) => string | undefined;
15
+ };
16
+
17
+ export type Found = {
18
+ readonly prompt: Prompt;
19
+ /** The prompt's name, with what it asks about when the screen says. */
20
+ readonly name: string;
21
+ /** What to type, when harnessd answers this prompt. */
22
+ readonly keys?: string;
23
+ };
24
+
25
+ export type Options = {
26
+ /** Types into Claude Code's terminal. */
27
+ readonly write: (keys: string) => void;
28
+ readonly log: (line: string) => void;
29
+ readonly cols: number;
30
+ readonly rows: number;
31
+ readonly quietMs?: number;
32
+ };
33
+
34
+ export type Watcher = {
35
+ /** Claude Code's terminal output. */
36
+ readonly push: (data: string) => void;
37
+ readonly resize: (cols: number, rows: number) => void;
38
+ /** A new start of Claude Code: an empty screen. `skipsPermissions`: its arguments turn permission prompts off. */
39
+ readonly reset: (start?: { skipsPermissions?: boolean }) => void;
40
+ /** The prompt Claude Code waits at for a person, if any. */
41
+ readonly waitingOn: () => string | undefined;
42
+ /** Whether this start's screen said managed settings keep harnessd's channels out. */
43
+ readonly channelsRefused: () => boolean;
44
+ };
45
+ }
46
+
47
+ const CONFIRM = "Entertoconfirm·Esctocancel$";
48
+
49
+ /** The prompts of Claude Code 2.1 that stop a start nobody watches. */
50
+ export const PROMPTS: readonly Prompts.Prompt[] = [
51
+ {
52
+ name: "the text style",
53
+ shows:
54
+ /Choosethetextstylethatlooksbestwithyourterminal[^]*Syntaxtheme:[^\n]*$/,
55
+ pick: "",
56
+ },
57
+ {
58
+ name: "the security notes",
59
+ shows: /Securitynotes:[^]*PressEntertocontinue…?$/,
60
+ pick: "",
61
+ },
62
+ {
63
+ name: "trust in the agent's folder",
64
+ shows: new RegExp(
65
+ `Accessingworkspace:[^]*Yes,Itrustthisfolder\\n${CONFIRM}`,
66
+ ),
67
+ pick: "Yes,Itrustthisfolder",
68
+ },
69
+ {
70
+ name: "running without permission prompts",
71
+ shows: new RegExp(
72
+ `ClaudeCoderunninginBypassPermissionsmode[^]*Yes,Iaccept\\n${CONFIRM}`,
73
+ ),
74
+ pick: "Yes,Iaccept",
75
+ forSkippedPermissions: true,
76
+ },
77
+ {
78
+ // shown at every start with --dangerously-load-development-channels; only harnessd's own plugin is answered for
79
+ name: "loading harnessd's channels",
80
+ shows: new RegExp(
81
+ `WARNING:Loadingdevelopmentchannels[^]*\\nChannels:plugin:harnessd@inline\\n❯?1\\.Iamusingthisforlocaldevelopment[^]*${CONFIRM}`,
82
+ ),
83
+ pick: "Iamusingthisforlocaldevelopment",
84
+ },
85
+ {
86
+ name: "the API key in its environment",
87
+ shows: new RegExp(
88
+ `DetectedacustomAPIkeyinyourenvironment[^]*DoyouwanttousethisAPIkey\\?[^]*${CONFIRM}`,
89
+ ),
90
+ pick: "Yes",
91
+ },
92
+ {
93
+ name: "CLAUDE.md imports from outside the folder",
94
+ shows:
95
+ /AllowexternalCLAUDE\.mdfileimports\?[^]*Yes,allowexternalimports\nEntertoconfirm·Esctodisable$/,
96
+ pick: "Yes,allowexternalimports",
97
+ },
98
+ {
99
+ name: "what to do at its usage limit",
100
+ shows: new RegExp(
101
+ `Whatdoyouwanttodo\\?\\n❯?1\\.Stopandwaitforlimittoreset[^]*${CONFIRM}`,
102
+ ),
103
+ pick: "Waithere,thencontinueautomatically",
104
+ },
105
+ {
106
+ // shown once per account
107
+ name: "the new autocompact default",
108
+ shows:
109
+ /Autocompactnowdefaultsto\w+tokens\n[^]*Apply\(allmodels\)\n[^]*Entertoconfirm·Esctoclose$/,
110
+ pick: "Apply(allmodels)",
111
+ },
112
+ { name: "a sign-in", shows: /Selectloginmethod:(\n❯?\d\.[^\n]*)+$/ },
113
+ {
114
+ // a tool asks before it acts ("Bash command", "Create file"…): only a person approves it
115
+ name: "permission",
116
+ shows: /\nDoyouwantto[^\n]*\?\n❯?1\.Yes\n[^]*\nEsctocancel·Tabtoamend$/,
117
+ subject: (screen) => {
118
+ const rule = screen.findLastIndex((line) => /^─{10,}$/.test(line.trim()));
119
+ return screen
120
+ .slice(rule + 1)
121
+ .map((line) => line.trim())
122
+ .find((line) => line !== "");
123
+ },
124
+ },
125
+ {
126
+ name: "a question harnessd doesn't know",
127
+ shows: /\nEntertoconfirm·Escto\w+$/,
128
+ },
129
+ ];
130
+
131
+ const CURSOR = "❯";
132
+ const DOWN = "\x1b[B";
133
+ const UP = "\x1b[A";
134
+
135
+ /** The prompt a screen ends with, and the keys that answer it. */
136
+ export const findPrompt = (
137
+ screen: readonly string[],
138
+ prompts: readonly Prompts.Prompt[] = PROMPTS,
139
+ ): Prompts.Found | undefined => {
140
+ const lines = screen
141
+ .map((line) => line.replace(/\s+/g, ""))
142
+ .filter((line) => line !== "");
143
+ const text = lines.join("\n");
144
+ const prompt = prompts.find((p) => p.shows.test(text));
145
+ if (!prompt) return undefined;
146
+ const subject = prompt.subject?.(screen);
147
+ const name = subject ? `${prompt.name}: ${subject}` : prompt.name;
148
+ if (prompt.pick === undefined) return { prompt, name };
149
+ if (prompt.pick === "") return { prompt, name, keys: "\r" };
150
+ const cursor = lines.findLastIndex((line) => line.startsWith(CURSOR));
151
+ const option = lines.findLastIndex((line) =>
152
+ line
153
+ .replace(CURSOR, "")
154
+ .replace(/^\d+\./, "")
155
+ .startsWith(prompt.pick!),
156
+ );
157
+ // an option list harnessd can't read is left to a person
158
+ if (cursor === -1 || option === -1) return { prompt, name };
159
+ return {
160
+ prompt,
161
+ name,
162
+ keys: `${(option > cursor ? DOWN : UP).repeat(Math.abs(option - cursor))}\r`,
163
+ };
164
+ };
165
+
166
+ /** What harnessd says when Claude Code refuses its channels. */
167
+ export const CHANNELS_REFUSED =
168
+ "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.";
169
+
170
+ /** Claude Code's start notice when a Team or Enterprise organization's (or this Mac's) managed settings keep channels out. */
171
+ export const channelsRefused = (screen: readonly string[]) =>
172
+ /blockedbyorgpolicy\([^)]*plugin:harnessd@inline/.test(
173
+ screen.map((line) => line.replace(/\s+/g, "")).join(""),
174
+ );
175
+
176
+ const QUIET_MS = 500;
177
+ // a prompt still there after this many answers isn't taking them
178
+ const MAX_ANSWERS = 3;
179
+
180
+ /** Reads Claude Code's screen as its output arrives and answers the prompts harnessd knows. */
181
+ export const promptWatcher = (options: Prompts.Options): Prompts.Watcher => {
182
+ const term = new xterm.Terminal({
183
+ cols: options.cols,
184
+ rows: options.rows,
185
+ scrollback: 0,
186
+ allowProposedApi: true,
187
+ });
188
+ const answers = new Map<string, number>();
189
+ let waiting: string | undefined;
190
+ let refused = false;
191
+ let skipsPermissions = false;
192
+ let timer: ReturnType<typeof setTimeout> | undefined;
193
+
194
+ const screen = () => {
195
+ const buffer = term.buffer.active;
196
+ return Array.from(
197
+ { length: term.rows },
198
+ (_, row) =>
199
+ buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? "",
200
+ );
201
+ };
202
+ const wait = (name: string) => {
203
+ if (waiting === name) return;
204
+ waiting = name;
205
+ options.log(
206
+ `Claude Code waits for an answer (${name}): harnessd attach, then answer it`,
207
+ );
208
+ };
209
+ const check = () => {
210
+ const lines = screen();
211
+ if (!refused && channelsRefused(lines)) {
212
+ refused = true;
213
+ options.log(CHANNELS_REFUSED);
214
+ }
215
+ const found = findPrompt(lines);
216
+ if (!found) {
217
+ waiting = undefined;
218
+ return;
219
+ }
220
+ const { name } = found;
221
+ const answered = answers.get(name) ?? 0;
222
+ if (
223
+ found.keys === undefined ||
224
+ answered >= MAX_ANSWERS ||
225
+ (found.prompt.forSkippedPermissions && !skipsPermissions)
226
+ )
227
+ return wait(name);
228
+ answers.set(name, answered + 1);
229
+ waiting = undefined;
230
+ options.log(`answered Claude Code's prompt: ${name}`);
231
+ options.write(found.keys);
232
+ };
233
+
234
+ return {
235
+ push: (data) => {
236
+ clearTimeout(timer);
237
+ // the screen is read once the output has gone quiet, so a half-drawn prompt isn't answered
238
+ term.write(data, () => {
239
+ clearTimeout(timer);
240
+ timer = setTimeout(check, options.quietMs ?? QUIET_MS);
241
+ });
242
+ },
243
+ resize: (cols, rows) => term.resize(cols, rows),
244
+ reset: (start) => {
245
+ skipsPermissions = start?.skipsPermissions ?? false;
246
+ clearTimeout(timer);
247
+ term.reset();
248
+ answers.clear();
249
+ waiting = undefined;
250
+ refused = false;
251
+ },
252
+ waitingOn: () => waiting,
253
+ channelsRefused: () => refused,
254
+ };
255
+ };
package/src/service.ts ADDED
@@ -0,0 +1,145 @@
1
+ import type { Harnessd } from "./config";
2
+ import { readdirSync, readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { load, plistFolder, plistOf, plistPath, unload } from "./launchd";
5
+ import { disable, enable, unitFolder, unitOf, unitPath } from "./systemd";
6
+ import { system } from "./system";
7
+
8
+ export namespace Service {
9
+ /** What the system's service manager starts: `node <bin> run`, with this environment. */
10
+ export type Spec = {
11
+ readonly label: string;
12
+ readonly node: string;
13
+ readonly bin: string;
14
+ readonly env: Readonly<Record<string, string>>;
15
+ readonly paths: Harnessd.Paths;
16
+ /** A boot service that runs as this user, installed by root. Without it: the installing user's login item. */
17
+ readonly user?: string;
18
+ };
19
+
20
+ export type User = {
21
+ readonly name: string;
22
+ readonly uid: number;
23
+ readonly gid: number;
24
+ readonly home: string;
25
+ };
26
+ }
27
+
28
+ const on = <T>(platform: string, mac: () => T, linux: () => T): T => {
29
+ if (platform === "darwin") return mac();
30
+ if (platform === "linux") return linux();
31
+ throw new Error(
32
+ "harnessd runs on macOS (it starts with launchd) and on Linux (with systemd).",
33
+ );
34
+ };
35
+
36
+ export const supportedPlatform = (platform: string = process.platform) =>
37
+ on(
38
+ platform,
39
+ () => {},
40
+ () => {},
41
+ );
42
+
43
+ /** Where the service's file goes: a login item's in the user's home, a boot service's in the system's folder. */
44
+ export const servicePath = (
45
+ label: string,
46
+ boot: boolean,
47
+ platform: string = process.platform,
48
+ ) =>
49
+ on(
50
+ platform,
51
+ () => plistPath(label, boot),
52
+ () => unitPath(label, boot),
53
+ );
54
+
55
+ /**
56
+ * The installed service of one kind that runs harnessd in this state folder, whatever its label: the same folder
57
+ * reached through HARNESSD_HOME has another label than through the default paths.
58
+ */
59
+ export const serviceIn = (
60
+ home: string,
61
+ boot: boolean,
62
+ platform: string = process.platform,
63
+ dir = dirname(servicePath("dev.harnessd", boot, platform)),
64
+ ) => {
65
+ const folder = `${on(
66
+ platform,
67
+ () => plistFolder(home),
68
+ () => unitFolder(home),
69
+ )}\n`;
70
+ let names: string[] = [];
71
+ try {
72
+ names = readdirSync(dir);
73
+ } catch {}
74
+ return names
75
+ .filter((name) => /^(dev\.)?harnessd.*\.(plist|service)$/.test(name))
76
+ .map((name) => join(dir, name))
77
+ .find((file) => {
78
+ try {
79
+ return readFileSync(file, "utf8").includes(folder);
80
+ } catch {
81
+ return false;
82
+ }
83
+ });
84
+ };
85
+
86
+ export const serviceText = (
87
+ spec: Service.Spec,
88
+ platform: string = process.platform,
89
+ ) =>
90
+ on(
91
+ platform,
92
+ () => plistOf(spec),
93
+ () => unitOf(spec),
94
+ );
95
+
96
+ /** Registers harnessd with launchd or systemd and starts it. */
97
+ export const installService = async (spec: Service.Spec) =>
98
+ on(
99
+ process.platform,
100
+ () => load(spec.label, plistOf(spec), spec.user !== undefined),
101
+ async () => enable(spec.label, unitOf(spec), spec.user !== undefined),
102
+ );
103
+
104
+ /** Stops harnessd and removes its service; false when it wasn't installed. */
105
+ export const removeService = (label: string, boot: boolean) =>
106
+ on(
107
+ process.platform,
108
+ () => unload(label, boot),
109
+ () => disable(label, boot),
110
+ );
111
+
112
+ /** The user a boot service runs as, looked up by name: under sudo this process's own home is root's. */
113
+ export const lookUpUser = (name: string): Service.User => {
114
+ const said = (file: string, args: string[]) => {
115
+ const result = system(file, args);
116
+ return result.status === 0 ? result.stdout.trim() : "";
117
+ };
118
+ const known = /^[A-Za-z_][A-Za-z0-9_.-]*$/.test(name);
119
+ const uid = known ? said("id", ["-u", name]) : "";
120
+ const gid = known ? said("id", ["-g", name]) : "";
121
+ const home = known ? said("/bin/sh", ["-c", `echo ~${name}`]) : "";
122
+ if (!uid || !gid || !home.startsWith("/"))
123
+ throw new Error(`No user ${name} on this computer.`);
124
+ if (uid === "0")
125
+ throw new Error(
126
+ "Claude Code doesn't run without permission prompts as root: name another user with --user <name>.",
127
+ );
128
+ return { name, uid: Number(uid), gid: Number(gid), home };
129
+ };
130
+
131
+ /** Runs `write` as `user`, so the files root makes in the user's home are the user's. */
132
+ export const asUser = <T>(
133
+ user: Service.User | undefined,
134
+ write: () => T,
135
+ ): T => {
136
+ if (!user || process.getuid?.() !== 0) return write();
137
+ process.setegid!(user.gid);
138
+ process.seteuid!(user.uid);
139
+ try {
140
+ return write();
141
+ } finally {
142
+ process.seteuid!(0);
143
+ process.setegid!(0);
144
+ }
145
+ };