@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.
- package/README.md +31 -18
- package/dist/accounts.d.ts +66 -0
- package/dist/accounts.d.ts.map +1 -0
- package/dist/accounts.js +166 -0
- package/dist/accounts.js.map +1 -0
- package/dist/bin.js +4 -0
- package/dist/bin.js.map +1 -1
- package/dist/channel.d.ts +15 -10
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +113 -158
- package/dist/channel.js.map +1 -1
- package/dist/claude.d.ts +17 -13
- package/dist/claude.d.ts.map +1 -1
- package/dist/claude.js +69 -59
- package/dist/claude.js.map +1 -1
- package/dist/cli.d.ts +5 -0
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +317 -131
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +46 -10
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +142 -51
- package/dist/config.js.map +1 -1
- package/dist/daemon.d.ts +29 -4
- package/dist/daemon.d.ts.map +1 -1
- package/dist/daemon.js +174 -51
- package/dist/daemon.js.map +1 -1
- package/dist/launchd.d.ts +12 -16
- package/dist/launchd.d.ts.map +1 -1
- package/dist/launchd.js +28 -25
- package/dist/launchd.js.map +1 -1
- package/dist/prompts.d.ts +53 -0
- package/dist/prompts.d.ts.map +1 -0
- package/dist/prompts.js +171 -0
- package/dist/prompts.js.map +1 -0
- package/dist/service.d.ts +37 -0
- package/dist/service.d.ts.map +1 -0
- package/dist/service.js +71 -0
- package/dist/service.js.map +1 -0
- package/dist/setup.d.ts +37 -0
- package/dist/setup.d.ts.map +1 -0
- package/dist/setup.js +121 -0
- package/dist/setup.js.map +1 -0
- package/dist/system.d.ts +6 -0
- package/dist/system.d.ts.map +1 -0
- package/dist/system.js +16 -0
- package/dist/system.js.map +1 -0
- package/dist/systemd.d.ts +14 -0
- package/dist/systemd.d.ts.map +1 -0
- package/dist/systemd.js +62 -0
- package/dist/systemd.js.map +1 -0
- package/dist/watchdog.d.ts +14 -4
- package/dist/watchdog.d.ts.map +1 -1
- package/dist/watchdog.js +30 -24
- package/dist/watchdog.js.map +1 -1
- package/package.json +8 -12
- package/src/accounts.ts +242 -0
- package/src/bin.ts +6 -0
- package/src/channel.ts +151 -172
- package/src/claude.ts +90 -88
- package/src/cli.ts +494 -183
- package/src/config.ts +239 -63
- package/src/daemon.ts +215 -65
- package/src/launchd.ts +40 -35
- package/src/prompts.ts +255 -0
- package/src/service.ts +145 -0
- package/src/setup.ts +188 -0
- package/src/system.ts +11 -0
- package/src/systemd.ts +78 -0
- package/src/watchdog.ts +41 -33
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
|
+
};
|
package/src/setup.ts
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { chmodSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { delimiter, join } from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline/promises";
|
|
6
|
+
import { which } from "./claude";
|
|
7
|
+
import { readConfig, type Harnessd } from "./config";
|
|
8
|
+
import { asUser, type Service } from "./service";
|
|
9
|
+
|
|
10
|
+
export namespace Setup {
|
|
11
|
+
/** The person at `harnessd service install`; none when it runs from a script. */
|
|
12
|
+
export type Terminal = {
|
|
13
|
+
readonly confirm: (question: string) => Promise<boolean>;
|
|
14
|
+
readonly line: (question: string) => Promise<string>;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Anthropic's installer for Claude Code. */
|
|
19
|
+
export const INSTALLER = "curl -fsSL https://claude.ai/install.sh | bash";
|
|
20
|
+
|
|
21
|
+
export const ttyTerminal = (): Setup.Terminal | undefined => {
|
|
22
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return undefined;
|
|
23
|
+
const line = async (question: string) => {
|
|
24
|
+
const lines = createInterface({
|
|
25
|
+
input: process.stdin,
|
|
26
|
+
output: process.stdout,
|
|
27
|
+
});
|
|
28
|
+
try {
|
|
29
|
+
return (await lines.question(question)).trim();
|
|
30
|
+
} finally {
|
|
31
|
+
lines.close();
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
return {
|
|
35
|
+
line,
|
|
36
|
+
confirm: async (question) =>
|
|
37
|
+
/^y(es)?$/i.test(await line(`${question} [y/n] `)),
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// under sudo, Claude Code's own commands run as the user the service is for
|
|
42
|
+
const as = (user: Service.User | undefined) =>
|
|
43
|
+
user && process.getuid?.() === 0 ? { uid: user.uid, gid: user.gid } : {};
|
|
44
|
+
|
|
45
|
+
/** The `claude` on the PATH or where Anthropic's installer puts it; none: installs it with `install`, or after a yes on the terminal. */
|
|
46
|
+
export const ensureClaude = async (o: {
|
|
47
|
+
terminal: Setup.Terminal | undefined;
|
|
48
|
+
user: Service.User | undefined;
|
|
49
|
+
/** `--install-claude`: runs the installer without asking. */
|
|
50
|
+
install?: boolean | undefined;
|
|
51
|
+
}) => {
|
|
52
|
+
const find = () => {
|
|
53
|
+
try {
|
|
54
|
+
return which(
|
|
55
|
+
"claude",
|
|
56
|
+
`${process.env.PATH ?? "/usr/bin:/bin"}${delimiter}${join(homedir(), ".local", "bin")}`,
|
|
57
|
+
);
|
|
58
|
+
} catch {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const found = find();
|
|
63
|
+
if (found) return found;
|
|
64
|
+
if (
|
|
65
|
+
!o.install &&
|
|
66
|
+
!(await o.terminal?.confirm(
|
|
67
|
+
`Claude Code isn't installed. Install it now with Anthropic's installer (${INSTALLER})?`,
|
|
68
|
+
))
|
|
69
|
+
)
|
|
70
|
+
throw new Error(
|
|
71
|
+
`Claude Code isn't installed. Add --install-claude to install it with Anthropic's installer (${INSTALLER}), or install it yourself and run harnessd service install again.`,
|
|
72
|
+
);
|
|
73
|
+
const ran = spawnSync("/bin/bash", ["-c", INSTALLER], {
|
|
74
|
+
stdio: "inherit",
|
|
75
|
+
...as(o.user),
|
|
76
|
+
});
|
|
77
|
+
const installed = ran.status === 0 ? find() : undefined;
|
|
78
|
+
if (!installed)
|
|
79
|
+
throw new Error(
|
|
80
|
+
"The installer left no claude command on the PATH or in ~/.local/bin. Install Claude Code yourself, then run harnessd service install again.",
|
|
81
|
+
);
|
|
82
|
+
return installed;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Checks that Claude Code is signed in the way the service can use, and offers the sign-in on the terminal: Claude
|
|
87
|
+
* Code's own for a login item, a `claude setup-token` token for a boot service and for Linux without a desktop.
|
|
88
|
+
* Without a sign-in it throws what to run; with `skip` it asks nothing and resolves to that instead. Resolves to
|
|
89
|
+
* nothing when Claude Code is signed in, or when a prestart command may sign it in.
|
|
90
|
+
*/
|
|
91
|
+
export const ensureSignedIn = async (o: {
|
|
92
|
+
claude: string;
|
|
93
|
+
paths: Harnessd.Paths;
|
|
94
|
+
/** The environment the service starts harnessd with. */
|
|
95
|
+
env: Readonly<Record<string, string>>;
|
|
96
|
+
user: Service.User | undefined;
|
|
97
|
+
terminal: Setup.Terminal | undefined;
|
|
98
|
+
/** `--skip-sign-in`: the install goes on without a sign-in. */
|
|
99
|
+
skip?: boolean | undefined;
|
|
100
|
+
platform?: string;
|
|
101
|
+
}): Promise<string | undefined> => {
|
|
102
|
+
const platform = o.platform ?? process.platform;
|
|
103
|
+
const { accounts, prestart } = readConfig(o.paths);
|
|
104
|
+
// a prestart command may fetch the sign-in at each start: what it prints then isn't known now
|
|
105
|
+
if (prestart !== undefined) return undefined;
|
|
106
|
+
const [account] = Object.keys(accounts);
|
|
107
|
+
const env = () => {
|
|
108
|
+
const config = readConfig(o.paths);
|
|
109
|
+
return {
|
|
110
|
+
HOME: homedir(),
|
|
111
|
+
...o.env,
|
|
112
|
+
...config.env,
|
|
113
|
+
...(account !== undefined && config.accounts[account]!.env),
|
|
114
|
+
};
|
|
115
|
+
};
|
|
116
|
+
const signedIn = () => {
|
|
117
|
+
const status = spawnSync(o.claude, ["auth", "status", "--json"], {
|
|
118
|
+
encoding: "utf8",
|
|
119
|
+
env: env(),
|
|
120
|
+
timeout: 30_000,
|
|
121
|
+
...as(o.user),
|
|
122
|
+
});
|
|
123
|
+
let auth: { loggedIn?: boolean; authMethod?: string } = {};
|
|
124
|
+
try {
|
|
125
|
+
auth = JSON.parse(status.stdout);
|
|
126
|
+
} catch {}
|
|
127
|
+
// a Mac's boot service starts outside any login, where the keychain's sign-in can't be read
|
|
128
|
+
const keychainOnly =
|
|
129
|
+
o.user !== undefined &&
|
|
130
|
+
platform === "darwin" &&
|
|
131
|
+
auth.authMethod === "claude.ai";
|
|
132
|
+
return auth.loggedIn === true && !keychainOnly;
|
|
133
|
+
};
|
|
134
|
+
if (signedIn()) return undefined;
|
|
135
|
+
|
|
136
|
+
const token =
|
|
137
|
+
o.user !== undefined ||
|
|
138
|
+
(platform === "linux" &&
|
|
139
|
+
!process.env.DISPLAY &&
|
|
140
|
+
!process.env.WAYLAND_DISPLAY);
|
|
141
|
+
const again = "then run harnessd service install again";
|
|
142
|
+
const how =
|
|
143
|
+
account !== undefined
|
|
144
|
+
? `Claude Code isn't signed in on account ${account}: set its env in ${o.paths.config}, ${again}.`
|
|
145
|
+
: token
|
|
146
|
+
? `Claude Code isn't signed in. Run claude setup-token, put its token in ${o.paths.config} as "env": { "CLAUDE_CODE_OAUTH_TOKEN": "<token>" }, ${again}.`
|
|
147
|
+
: `Claude Code isn't signed in. Run claude auth login, ${again}.`;
|
|
148
|
+
// once the service runs, Claude Code's own sign-in screen is another way
|
|
149
|
+
if (o.skip)
|
|
150
|
+
return account === undefined && !token
|
|
151
|
+
? `${how.slice(0, -1)}; or sign in inside harnessd attach.`
|
|
152
|
+
: how;
|
|
153
|
+
const stop = new Error(
|
|
154
|
+
`${how}\nTo install without a sign-in, add --skip-sign-in.`,
|
|
155
|
+
);
|
|
156
|
+
if (
|
|
157
|
+
account !== undefined ||
|
|
158
|
+
!(await o.terminal?.confirm(
|
|
159
|
+
token
|
|
160
|
+
? "Claude Code isn't signed in. Make a sign-in token now (claude setup-token)?"
|
|
161
|
+
: "Claude Code isn't signed in. Sign in now (claude auth login)?",
|
|
162
|
+
))
|
|
163
|
+
)
|
|
164
|
+
throw stop;
|
|
165
|
+
spawnSync(o.claude, token ? ["setup-token"] : ["auth", "login"], {
|
|
166
|
+
stdio: "inherit",
|
|
167
|
+
env: env(),
|
|
168
|
+
...as(o.user),
|
|
169
|
+
});
|
|
170
|
+
if (token) {
|
|
171
|
+
const pasted = (
|
|
172
|
+
await o.terminal!.line("Paste the token claude setup-token printed: ")
|
|
173
|
+
).replace(/\s+/g, "");
|
|
174
|
+
if (pasted)
|
|
175
|
+
asUser(o.user, () => {
|
|
176
|
+
const raw = JSON.parse(readFileSync(o.paths.config, "utf8")) as {
|
|
177
|
+
env?: Record<string, string>;
|
|
178
|
+
};
|
|
179
|
+
writeFileSync(
|
|
180
|
+
o.paths.config,
|
|
181
|
+
`${JSON.stringify({ ...raw, env: { ...raw.env, CLAUDE_CODE_OAUTH_TOKEN: pasted } }, null, 2)}\n`,
|
|
182
|
+
);
|
|
183
|
+
chmodSync(o.paths.config, 0o600);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
if (!signedIn()) throw stop;
|
|
187
|
+
return undefined;
|
|
188
|
+
};
|
package/src/system.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Runs one of the system's own commands (launchctl, systemctl, id), found in the system's folders only: under sudo the
|
|
5
|
+
* PATH is the caller's, and what runs as root must not come from it.
|
|
6
|
+
*/
|
|
7
|
+
export const system = (file: string, args: readonly string[]) =>
|
|
8
|
+
spawnSync(file, args, {
|
|
9
|
+
encoding: "utf8",
|
|
10
|
+
env: { ...process.env, PATH: "/usr/sbin:/usr/bin:/sbin:/bin" },
|
|
11
|
+
});
|
package/src/systemd.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import type { Service } from "./service";
|
|
5
|
+
import { system } from "./system";
|
|
6
|
+
|
|
7
|
+
// systemd reads `%` as a specifier everywhere, and `$` as a variable in a command line
|
|
8
|
+
const quoted = (value: string) =>
|
|
9
|
+
`"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
|
|
10
|
+
|
|
11
|
+
const plain = (path: string) => path.replace(/%/g, "%%");
|
|
12
|
+
|
|
13
|
+
/** The unit's line that names harnessd's state folder: what tells one harnessd's unit from another's. */
|
|
14
|
+
export const unitFolder = (home: string) => `WorkingDirectory=${plain(home)}`;
|
|
15
|
+
|
|
16
|
+
/** The unit's name: `harnessd.service`, or `harnessd-<id>.service` for a state folder of its own. */
|
|
17
|
+
export const unitName = (label: string) =>
|
|
18
|
+
`${label.replace(/^dev\./, "").replace(/\./g, "-")}.service`;
|
|
19
|
+
|
|
20
|
+
/** A user unit in the user's own folder, or for a boot service a system unit. */
|
|
21
|
+
export const unitPath = (label: string, boot = false) =>
|
|
22
|
+
boot
|
|
23
|
+
? `/etc/systemd/system/${unitName(label)}`
|
|
24
|
+
: join(homedir(), ".config", "systemd", "user", unitName(label));
|
|
25
|
+
|
|
26
|
+
/** The systemd unit: `node <bin> run` at login (with `user`: at boot, as that user) and after any exit. */
|
|
27
|
+
export const unitOf = (o: Service.Spec) => `[Unit]
|
|
28
|
+
Description=harnessd keeps Claude Code running
|
|
29
|
+
StartLimitIntervalSec=0
|
|
30
|
+
${o.user === undefined ? "" : "After=network-online.target\nWants=network-online.target\n"}
|
|
31
|
+
[Service]
|
|
32
|
+
${o.user === undefined ? "" : `User=${o.user}\n`}ExecStart=${[o.node, o.bin, "run"].map((arg) => quoted(arg).replace(/\$/g, "$$$$")).join(" ")}
|
|
33
|
+
${unitFolder(o.paths.home)}
|
|
34
|
+
${Object.entries(o.env)
|
|
35
|
+
.map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`)
|
|
36
|
+
.join("\n")}
|
|
37
|
+
Restart=always
|
|
38
|
+
RestartSec=5
|
|
39
|
+
KillMode=mixed
|
|
40
|
+
TimeoutStopSec=30
|
|
41
|
+
StandardOutput=append:${plain(o.paths.serviceLog)}
|
|
42
|
+
StandardError=append:${plain(o.paths.serviceLog)}
|
|
43
|
+
|
|
44
|
+
[Install]
|
|
45
|
+
WantedBy=${o.user === undefined ? "default.target" : "multi-user.target"}
|
|
46
|
+
`;
|
|
47
|
+
|
|
48
|
+
const systemctl = (boot: boolean, ...args: string[]) => {
|
|
49
|
+
const result = system("systemctl", [...(boot ? [] : ["--user"]), ...args]);
|
|
50
|
+
if (result.status === 0) return;
|
|
51
|
+
const said = (result.stderr || result.stdout || String(result.error)).trim();
|
|
52
|
+
throw new Error(
|
|
53
|
+
/connect to bus|No medium found/.test(said)
|
|
54
|
+
? `systemd has no session for this user (${said}). Sign in at the machine or over SSH, not through su or sudo -u, and run it again.`
|
|
55
|
+
: `systemctl ${args.join(" ")} failed: ${said}`,
|
|
56
|
+
);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** Writes the unit, enables it and (re)starts it, which starts harnessd. */
|
|
60
|
+
export const enable = (label: string, unit: string, boot: boolean) => {
|
|
61
|
+
// before the unit is written: without systemd to reach, no file is left behind
|
|
62
|
+
systemctl(boot, "show-environment");
|
|
63
|
+
mkdirSync(dirname(unitPath(label, boot)), { recursive: true });
|
|
64
|
+
writeFileSync(unitPath(label, boot), unit, { mode: 0o644 });
|
|
65
|
+
systemctl(boot, "daemon-reload");
|
|
66
|
+
systemctl(boot, "enable", unitName(label));
|
|
67
|
+
systemctl(boot, "restart", unitName(label));
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** Stops harnessd (it stops Claude Code first) and removes the unit. */
|
|
71
|
+
export const disable = (label: string, boot: boolean) => {
|
|
72
|
+
const had = existsSync(unitPath(label, boot));
|
|
73
|
+
if (!had) return false;
|
|
74
|
+
systemctl(boot, "disable", "--now", unitName(label));
|
|
75
|
+
rmSync(unitPath(label, boot), { force: true });
|
|
76
|
+
systemctl(boot, "daemon-reload");
|
|
77
|
+
return true;
|
|
78
|
+
};
|