@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.
- package/LICENSE +21 -0
- package/README.md +64 -2
- 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.d.ts +3 -0
- package/dist/bin.d.ts.map +1 -0
- package/dist/bin.js +19 -0
- package/dist/bin.js.map +1 -0
- package/dist/channel.d.ts +56 -0
- package/dist/channel.d.ts.map +1 -0
- package/dist/channel.js +356 -0
- package/dist/channel.js.map +1 -0
- package/dist/claude.d.ts +41 -0
- package/dist/claude.d.ts.map +1 -0
- package/dist/claude.js +152 -0
- package/dist/claude.js.map +1 -0
- package/dist/cli.d.ts +13 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +413 -0
- package/dist/cli.js.map +1 -0
- package/dist/config.d.ts +56 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +161 -0
- package/dist/config.js.map +1 -0
- package/dist/daemon.d.ts +37 -0
- package/dist/daemon.d.ts.map +1 -0
- package/dist/daemon.js +300 -0
- package/dist/daemon.js.map +1 -0
- package/dist/launchd.d.ts +18 -0
- package/dist/launchd.d.ts.map +1 -0
- package/dist/launchd.js +91 -0
- package/dist/launchd.js.map +1 -0
- package/dist/log.d.ts +3 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +17 -0
- package/dist/log.js.map +1 -0
- 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/terminal.d.ts +11 -0
- package/dist/terminal.d.ts.map +1 -0
- package/dist/terminal.js +36 -0
- package/dist/terminal.js.map +1 -0
- package/dist/watchdog.d.ts +83 -0
- package/dist/watchdog.d.ts.map +1 -0
- package/dist/watchdog.js +236 -0
- package/dist/watchdog.js.map +1 -0
- package/package.json +55 -6
- package/src/accounts.ts +242 -0
- package/src/bin.ts +24 -0
- package/src/channel.ts +461 -0
- package/src/claude.ts +249 -0
- package/src/cli.ts +633 -0
- package/src/config.ts +281 -0
- package/src/daemon.ts +379 -0
- package/src/launchd.ts +131 -0
- package/src/log.ts +17 -0
- 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/terminal.ts +33 -0
- package/src/watchdog.ts +318 -0
package/src/cli.ts
ADDED
|
@@ -0,0 +1,633 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import {
|
|
3
|
+
appendFileSync,
|
|
4
|
+
chmodSync,
|
|
5
|
+
existsSync,
|
|
6
|
+
mkdirSync,
|
|
7
|
+
readFileSync,
|
|
8
|
+
writeFileSync,
|
|
9
|
+
} from "node:fs";
|
|
10
|
+
import { createRequire } from "node:module";
|
|
11
|
+
import { createConnection } from "node:net";
|
|
12
|
+
import { userInfo } from "node:os";
|
|
13
|
+
import { delimiter, dirname } from "node:path";
|
|
14
|
+
import { createInterface } from "node:readline";
|
|
15
|
+
import { readStatus, serveChannel, statusFile } from "./channel";
|
|
16
|
+
import {
|
|
17
|
+
DEFAULT_CONFIG,
|
|
18
|
+
ownFolder,
|
|
19
|
+
pathsOf,
|
|
20
|
+
readConfig,
|
|
21
|
+
type Harnessd,
|
|
22
|
+
} from "./config";
|
|
23
|
+
import { ask, runDaemon, type Daemon } from "./daemon";
|
|
24
|
+
import { stableNode } from "./launchd";
|
|
25
|
+
import { logTo } from "./log";
|
|
26
|
+
import { ensureClaude, ensureSignedIn, ttyTerminal, type Setup } from "./setup";
|
|
27
|
+
import { CHANNELS_REFUSED } from "./prompts";
|
|
28
|
+
import {
|
|
29
|
+
asUser,
|
|
30
|
+
installService,
|
|
31
|
+
lookUpUser,
|
|
32
|
+
removeService,
|
|
33
|
+
serviceIn,
|
|
34
|
+
servicePath,
|
|
35
|
+
serviceText,
|
|
36
|
+
supportedPlatform,
|
|
37
|
+
type Service,
|
|
38
|
+
} from "./service";
|
|
39
|
+
|
|
40
|
+
const USAGE = `harnessd keeps Claude Code running on this computer, connected to the events of your agentic apps.
|
|
41
|
+
|
|
42
|
+
usage: harnessd <command>
|
|
43
|
+
|
|
44
|
+
service install Start harnessd now and at every login; with sudo, at every boot
|
|
45
|
+
service uninstall Stop harnessd and remove its service
|
|
46
|
+
status [--json] What runs, which conversation, each channel's events, and the log's last lines
|
|
47
|
+
start Start Claude Code after a stop
|
|
48
|
+
stop Stop Claude Code; harnessd stays up, and Claude Code stays stopped until start
|
|
49
|
+
attach Open Claude Code's terminal; Ctrl-\\ detaches
|
|
50
|
+
--version Print harnessd's version
|
|
51
|
+
|
|
52
|
+
service install takes:
|
|
53
|
+
--user <name> With sudo: the user the boot service runs as; service uninstall takes it too
|
|
54
|
+
--dry-run Print the service's file and change nothing
|
|
55
|
+
--install-claude When Claude Code is missing, install it with Anthropic's installer without asking
|
|
56
|
+
--skip-sign-in Install even when Claude Code isn't signed in, and print how to sign in
|
|
57
|
+
|
|
58
|
+
Settings: ~/.config/harnessd/config.json. State and log: ~/.local/state/harnessd.
|
|
59
|
+
XDG_CONFIG_HOME and XDG_STATE_HOME move them; HARNESSD_HOME puts both in one folder.`;
|
|
60
|
+
|
|
61
|
+
const VERSION = (
|
|
62
|
+
createRequire(import.meta.url)("../package.json") as { version: string }
|
|
63
|
+
).version;
|
|
64
|
+
|
|
65
|
+
const DETACH = "\x1c";
|
|
66
|
+
|
|
67
|
+
type Io = {
|
|
68
|
+
out: (line: string) => void;
|
|
69
|
+
err: (line: string) => void;
|
|
70
|
+
/** The person to ask; none when harnessd runs from a script. */
|
|
71
|
+
terminal?: Setup.Terminal | undefined;
|
|
72
|
+
/** What the command was given on stdin, for a hook. */
|
|
73
|
+
stdin?: () => Promise<string>;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const stdin = async () => {
|
|
77
|
+
let text = "";
|
|
78
|
+
for await (const chunk of process.stdin) text += String(chunk);
|
|
79
|
+
return text;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const notRunning = (paths: Harnessd.Paths) =>
|
|
83
|
+
`harnessd isn't running in ${paths.home}: harnessd service install starts it.`;
|
|
84
|
+
|
|
85
|
+
const usageError = (message: string) =>
|
|
86
|
+
Object.assign(new Error(message), { usage: true });
|
|
87
|
+
|
|
88
|
+
/** Refuses any argument a command doesn't take, so a typo never runs the command. */
|
|
89
|
+
const takes = (
|
|
90
|
+
command: string,
|
|
91
|
+
rest: readonly string[],
|
|
92
|
+
allowed: readonly string[] = [],
|
|
93
|
+
) => {
|
|
94
|
+
const extra = rest.find((arg) => !allowed.includes(arg));
|
|
95
|
+
if (extra !== undefined)
|
|
96
|
+
throw usageError(
|
|
97
|
+
`harnessd ${command} takes ${allowed.length > 0 ? `only ${allowed.join(", ")}` : "no arguments"}, not ${extra}.`,
|
|
98
|
+
);
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const tail = (file: string, lines: number) => {
|
|
102
|
+
try {
|
|
103
|
+
const text = readFileSync(file, "utf8").trimEnd();
|
|
104
|
+
return text ? text.split("\n").slice(-lines) : [];
|
|
105
|
+
} catch {
|
|
106
|
+
return [];
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const daemonStatus = async (paths: Harnessd.Paths) =>
|
|
111
|
+
(
|
|
112
|
+
(await ask(paths.socket, { command: "status" })) as
|
|
113
|
+
| { status?: Daemon.Status }
|
|
114
|
+
| undefined
|
|
115
|
+
)?.status;
|
|
116
|
+
|
|
117
|
+
const START_WAIT_MS = 90_000;
|
|
118
|
+
|
|
119
|
+
/** Waits until Claude Code runs, was stopped by hand, or failed to start; `not` is the harnessd an install replaces. */
|
|
120
|
+
const settled = async (
|
|
121
|
+
paths: Harnessd.Paths,
|
|
122
|
+
not?: number,
|
|
123
|
+
waitMs = START_WAIT_MS,
|
|
124
|
+
) => {
|
|
125
|
+
const until = Date.now() + waitMs;
|
|
126
|
+
for (;;) {
|
|
127
|
+
const status = await daemonStatus(paths);
|
|
128
|
+
const ours = status && status.daemonPid !== not ? status : undefined;
|
|
129
|
+
if ((ours && ours.state !== "starting") || Date.now() >= until) return ours;
|
|
130
|
+
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
/** After a failed start: the log lines that show why; resolves to the exit code. */
|
|
135
|
+
const showLog = (log: string, io: Io) => {
|
|
136
|
+
for (const line of tail(log, 10)) io.err(` ${line}`);
|
|
137
|
+
io.err(`log ${log}`);
|
|
138
|
+
return 1;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
/** Says why a start failed, with the log's last lines; resolves to the exit code. */
|
|
142
|
+
const startFailed = (
|
|
143
|
+
paths: Harnessd.Paths,
|
|
144
|
+
status: Daemon.Status | undefined,
|
|
145
|
+
io: Io,
|
|
146
|
+
) => {
|
|
147
|
+
io.err(
|
|
148
|
+
!status
|
|
149
|
+
? "harnessd didn't start."
|
|
150
|
+
: status.state === "waiting"
|
|
151
|
+
? `Claude Code didn't stay up${status.lastExit ? ` (exit code ${status.lastExit.code})` : ""}; harnessd keeps trying.`
|
|
152
|
+
: "Claude Code is still starting; harnessd status shows how it goes.",
|
|
153
|
+
);
|
|
154
|
+
return showLog(status ? paths.log : paths.serviceLog, io);
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const command = async (
|
|
158
|
+
paths: Harnessd.Paths,
|
|
159
|
+
request: Daemon.Request,
|
|
160
|
+
io: Io,
|
|
161
|
+
) => {
|
|
162
|
+
const answer = await ask(paths.socket, request);
|
|
163
|
+
if (!answer) {
|
|
164
|
+
io.err(notRunning(paths));
|
|
165
|
+
return 1;
|
|
166
|
+
}
|
|
167
|
+
if (!answer.ok) {
|
|
168
|
+
io.err(String(answer.message));
|
|
169
|
+
return request.command === "stop" ? 1 : showLog(paths.log, io);
|
|
170
|
+
}
|
|
171
|
+
if (request.command !== "stop") {
|
|
172
|
+
const status = await settled(paths);
|
|
173
|
+
if (status?.state !== "running") return startFailed(paths, status, io);
|
|
174
|
+
}
|
|
175
|
+
io.out(String(answer.message));
|
|
176
|
+
return 0;
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
type ServiceFlags = {
|
|
180
|
+
user?: string;
|
|
181
|
+
dryRun?: true;
|
|
182
|
+
installClaude?: true;
|
|
183
|
+
skipSignIn?: true;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/** Who the service is for: with sudo, a boot service that runs as the named user; without, your own login item. */
|
|
187
|
+
const serviceTarget = (action: string, flags: ServiceFlags) => {
|
|
188
|
+
const root = process.getuid?.() === 0;
|
|
189
|
+
if (flags.user !== undefined && !root && !flags.dryRun)
|
|
190
|
+
throw new Error(
|
|
191
|
+
`A boot service needs root: sudo harnessd service ${action} --user ${flags.user}`,
|
|
192
|
+
);
|
|
193
|
+
const name = flags.user ?? (root ? process.env.SUDO_USER : undefined);
|
|
194
|
+
if (root && name === undefined)
|
|
195
|
+
throw new Error("Name the user harnessd runs as: --user <name>");
|
|
196
|
+
const user = name === undefined ? undefined : lookUpUser(name);
|
|
197
|
+
// another account's harnessd lives in that account's own folders, not where this shell's variables point
|
|
198
|
+
const caller = process.env.SUDO_USER ?? userInfo().username;
|
|
199
|
+
const moved = ["HARNESSD_HOME", "XDG_CONFIG_HOME", "XDG_STATE_HOME"].find(
|
|
200
|
+
(key) => process.env[key],
|
|
201
|
+
);
|
|
202
|
+
if (user && user.name !== caller && moved)
|
|
203
|
+
throw new Error(
|
|
204
|
+
`${moved} is set in your shell, and --user ${user.name} installs in ${user.name}'s own folders: unset it, or let ${user.name} run the install.`,
|
|
205
|
+
);
|
|
206
|
+
// from here on every path is the user's, not root's
|
|
207
|
+
if (user)
|
|
208
|
+
Object.assign(process.env, {
|
|
209
|
+
HOME: user.home,
|
|
210
|
+
USER: user.name,
|
|
211
|
+
LOGNAME: user.name,
|
|
212
|
+
});
|
|
213
|
+
const paths = pathsOf();
|
|
214
|
+
// elsewhere, the socket's place depends on who asks and on their login session: root, the service and the user's commands would each look somewhere else
|
|
215
|
+
if (user && !paths.socket.startsWith(paths.home))
|
|
216
|
+
throw new Error(
|
|
217
|
+
`${paths.home} is too long a path for harnessd's socket, and a boot service keeps its socket there: set a shorter XDG_STATE_HOME or HARNESSD_HOME.`,
|
|
218
|
+
);
|
|
219
|
+
// every user's default harnessd has the same label, and boot services share one namespace
|
|
220
|
+
const bootLabel = (name: string) =>
|
|
221
|
+
paths.label === "dev.harnessd" ? `dev.harnessd.${name}` : paths.label;
|
|
222
|
+
return {
|
|
223
|
+
user,
|
|
224
|
+
paths,
|
|
225
|
+
label: user ? bootLabel(user.name) : paths.label,
|
|
226
|
+
/** The other kind's file, when one is installed for this state folder: it holds one harnessd. */
|
|
227
|
+
other: () => serviceIn(paths.home, user === undefined),
|
|
228
|
+
};
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const uninstall = (flags: ServiceFlags, io: Io) => {
|
|
232
|
+
const { user, paths, label, other } = serviceTarget("uninstall", flags);
|
|
233
|
+
if (removeService(label, user !== undefined)) {
|
|
234
|
+
io.out(
|
|
235
|
+
`Removed harnessd's service. Its settings stay in ${paths.config}, its conversation in ${paths.home}.`,
|
|
236
|
+
);
|
|
237
|
+
return 0;
|
|
238
|
+
}
|
|
239
|
+
const file = other();
|
|
240
|
+
io[file ? "err" : "out"](
|
|
241
|
+
file
|
|
242
|
+
? `harnessd is installed as a ${user ? "login item" : "boot service"} (${file}): run ${user ? "" : "sudo "}harnessd service uninstall.`
|
|
243
|
+
: "harnessd wasn't installed.",
|
|
244
|
+
);
|
|
245
|
+
return file ? 1 : 0;
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
const install = async (flags: ServiceFlags, bin: string, io: Io) => {
|
|
249
|
+
// before anything is written: an install that can't go on leaves nothing behind
|
|
250
|
+
supportedPlatform();
|
|
251
|
+
if (bin.includes("/_npx/"))
|
|
252
|
+
throw new Error(
|
|
253
|
+
"Install harnessd first, so the service has a lasting copy to start: npm install -g @harness-sdk/harnessd",
|
|
254
|
+
);
|
|
255
|
+
const { user, paths, label, other } = serviceTarget("install", flags);
|
|
256
|
+
const own = (process.env.PATH ?? "/usr/bin:/bin").split(delimiter);
|
|
257
|
+
const terminal = flags.dryRun ? undefined : io.terminal;
|
|
258
|
+
// a dry run changes nothing, so it installs nothing either
|
|
259
|
+
const claude = await ensureClaude({
|
|
260
|
+
terminal,
|
|
261
|
+
user,
|
|
262
|
+
install: flags.installClaude && !flags.dryRun,
|
|
263
|
+
});
|
|
264
|
+
const version = spawnSync(claude, ["--version"], {
|
|
265
|
+
encoding: "utf8",
|
|
266
|
+
timeout: 30_000,
|
|
267
|
+
...(user && process.getuid?.() === 0 && { uid: user.uid, gid: user.gid }),
|
|
268
|
+
});
|
|
269
|
+
if (version.status !== 0)
|
|
270
|
+
throw new Error(
|
|
271
|
+
`${claude} --version failed: ${(version.stderr || version.stdout || "").trim()}`,
|
|
272
|
+
);
|
|
273
|
+
const node = stableNode();
|
|
274
|
+
const spec: Service.Spec = {
|
|
275
|
+
label,
|
|
276
|
+
node,
|
|
277
|
+
bin,
|
|
278
|
+
env: {
|
|
279
|
+
// sudo's PATH may hold neither claude nor node, which Claude Code's own tools start
|
|
280
|
+
PATH: [...new Set([...own, dirname(claude), dirname(node)])]
|
|
281
|
+
.filter((dir) => dir.startsWith("/"))
|
|
282
|
+
.join(delimiter),
|
|
283
|
+
...(user && { HOME: user.home, USER: user.name, LOGNAME: user.name }),
|
|
284
|
+
...paths.env,
|
|
285
|
+
},
|
|
286
|
+
paths,
|
|
287
|
+
...(user && { user: user.name }),
|
|
288
|
+
};
|
|
289
|
+
const file = servicePath(label, user !== undefined);
|
|
290
|
+
if (flags.dryRun) {
|
|
291
|
+
io.out(
|
|
292
|
+
`Would write ${file} and start it${user ? `, as root, to run as ${user.name} from every boot` : ""}:\n\n${serviceText(spec)}`,
|
|
293
|
+
);
|
|
294
|
+
return 0;
|
|
295
|
+
}
|
|
296
|
+
const taken = other();
|
|
297
|
+
if (taken)
|
|
298
|
+
throw new Error(
|
|
299
|
+
`harnessd is already installed as a ${user ? "login item" : "boot service"} (${taken}): run ${user ? "" : "sudo "}harnessd service uninstall first.`,
|
|
300
|
+
);
|
|
301
|
+
const config = asUser(user, () => {
|
|
302
|
+
ownFolder(paths.home);
|
|
303
|
+
ownFolder(dirname(paths.config));
|
|
304
|
+
if (!existsSync(paths.config))
|
|
305
|
+
writeFileSync(
|
|
306
|
+
paths.config,
|
|
307
|
+
`${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`,
|
|
308
|
+
);
|
|
309
|
+
chmodSync(paths.config, 0o600);
|
|
310
|
+
// the user's own file before a boot service's manager, as root, makes it: a later login item has to append to it
|
|
311
|
+
appendFileSync(paths.serviceLog, "");
|
|
312
|
+
const config = readConfig(paths);
|
|
313
|
+
mkdirSync(config.folder, { recursive: true });
|
|
314
|
+
return config;
|
|
315
|
+
});
|
|
316
|
+
const signIn = await ensureSignedIn({
|
|
317
|
+
claude,
|
|
318
|
+
paths,
|
|
319
|
+
env: spec.env,
|
|
320
|
+
user,
|
|
321
|
+
terminal,
|
|
322
|
+
skip: flags.skipSignIn,
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const before = (await daemonStatus(paths))?.daemonPid;
|
|
326
|
+
await installService(spec);
|
|
327
|
+
const status = await settled(paths, before);
|
|
328
|
+
if (status?.state !== "running" && status?.state !== "stopped")
|
|
329
|
+
return startFailed(paths, status, io);
|
|
330
|
+
const when = user ? `at every boot, as ${user.name}` : "at every login";
|
|
331
|
+
io.out(
|
|
332
|
+
[
|
|
333
|
+
status.state === "stopped"
|
|
334
|
+
? `harnessd is installed for ${config.folder} and starts ${when}. Claude Code is stopped: harnessd start starts it.`
|
|
335
|
+
: `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and ${when}.`,
|
|
336
|
+
" harnessd attach its terminal; Ctrl-\\ detaches",
|
|
337
|
+
" harnessd status what runs and whether events arrive",
|
|
338
|
+
...(signIn ? [signIn] : []),
|
|
339
|
+
...(user
|
|
340
|
+
? []
|
|
341
|
+
: [
|
|
342
|
+
process.platform === "darwin"
|
|
343
|
+
? "It starts when you log in: turn on automatic login (System Settings > Users & Groups), so it comes back after a power cut."
|
|
344
|
+
: "It starts when you sign in and stops when you sign out.",
|
|
345
|
+
`For a start at boot, with nobody logged in: harnessd service uninstall, then ${process.platform === "darwin" ? "sudo harnessd" : 'sudo env "PATH=$PATH" harnessd'} service install`,
|
|
346
|
+
]),
|
|
347
|
+
].join("\n"),
|
|
348
|
+
);
|
|
349
|
+
return 0;
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
const ago = (iso: string) => {
|
|
353
|
+
const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1000));
|
|
354
|
+
return s < 120
|
|
355
|
+
? `${s}s`
|
|
356
|
+
: s < 7200
|
|
357
|
+
? `${Math.round(s / 60)}m`
|
|
358
|
+
: s < 172_800
|
|
359
|
+
? `${Math.round(s / 3600)}h`
|
|
360
|
+
: `${Math.round(s / 86_400)}d`;
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
/** Each channel as of the Claude Code that runs now: what an earlier run heard says nothing about this one. */
|
|
364
|
+
const channelReport = (
|
|
365
|
+
paths: Harnessd.Paths,
|
|
366
|
+
config: Harnessd.Config | undefined,
|
|
367
|
+
running: Daemon.Status | undefined,
|
|
368
|
+
) =>
|
|
369
|
+
Object.fromEntries(
|
|
370
|
+
Object.entries(config?.channels ?? {}).map(([name, channel]) => {
|
|
371
|
+
const status = readStatus(statusFile(paths, name));
|
|
372
|
+
const since =
|
|
373
|
+
running?.state === "running" || running?.state === "starting"
|
|
374
|
+
? running.startedAt
|
|
375
|
+
: undefined;
|
|
376
|
+
const now = (at: string | undefined) =>
|
|
377
|
+
since !== undefined && at !== undefined && at >= since;
|
|
378
|
+
const events =
|
|
379
|
+
since === undefined
|
|
380
|
+
? "off (Claude Code isn't running)"
|
|
381
|
+
: running?.channelsRefused
|
|
382
|
+
? "refused"
|
|
383
|
+
: now(status.heardAt)
|
|
384
|
+
? "arriving"
|
|
385
|
+
: now(status.pushedAt)
|
|
386
|
+
? "sent, not in the conversation yet"
|
|
387
|
+
: "none yet";
|
|
388
|
+
return [
|
|
389
|
+
name,
|
|
390
|
+
{
|
|
391
|
+
url: channel.url,
|
|
392
|
+
events,
|
|
393
|
+
...status,
|
|
394
|
+
},
|
|
395
|
+
];
|
|
396
|
+
}),
|
|
397
|
+
);
|
|
398
|
+
|
|
399
|
+
const status = async (paths: Harnessd.Paths, json: boolean, io: Io) => {
|
|
400
|
+
const s = await daemonStatus(paths);
|
|
401
|
+
let config: Harnessd.Config | undefined;
|
|
402
|
+
let configError: string | undefined;
|
|
403
|
+
try {
|
|
404
|
+
config = readConfig(paths);
|
|
405
|
+
} catch (error) {
|
|
406
|
+
configError = error instanceof Error ? error.message : String(error);
|
|
407
|
+
}
|
|
408
|
+
const channels = channelReport(paths, config, s);
|
|
409
|
+
// without a harnessd to ask, the service's own output says why
|
|
410
|
+
const log = s || !existsSync(paths.serviceLog) ? paths.log : paths.serviceLog;
|
|
411
|
+
const logTail = tail(log, 10);
|
|
412
|
+
const code = s && !configError ? 0 : 1;
|
|
413
|
+
if (json) {
|
|
414
|
+
io.out(
|
|
415
|
+
JSON.stringify({
|
|
416
|
+
running: !!s,
|
|
417
|
+
home: paths.home,
|
|
418
|
+
config: paths.config,
|
|
419
|
+
...(s && { status: s }),
|
|
420
|
+
...(configError && { configError }),
|
|
421
|
+
channels,
|
|
422
|
+
log,
|
|
423
|
+
logTail,
|
|
424
|
+
}),
|
|
425
|
+
);
|
|
426
|
+
return code;
|
|
427
|
+
}
|
|
428
|
+
if (!s) io.out(notRunning(paths));
|
|
429
|
+
else {
|
|
430
|
+
const since = s.startedAt ? ` for ${ago(s.startedAt)}` : "";
|
|
431
|
+
const what =
|
|
432
|
+
s.state === "running"
|
|
433
|
+
? `Claude Code running${since} (pid ${s.pid})`
|
|
434
|
+
: s.state === "waiting"
|
|
435
|
+
? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1000))}s` : ""}`
|
|
436
|
+
: s.state === "stopped"
|
|
437
|
+
? "Claude Code stopped (harnessd start starts it)"
|
|
438
|
+
: "Claude Code starting";
|
|
439
|
+
io.out(`harnessd ${s.daemonPid}: ${what}`);
|
|
440
|
+
if (s.account) io.out(`account ${s.account}`);
|
|
441
|
+
for (const [name, stop] of Object.entries(s.accountsStopped ?? {}))
|
|
442
|
+
io.out(
|
|
443
|
+
`account ${name} stopped at ${stop.why}; harnessd tries it again after ${new Date(stop.until).toLocaleString()}`,
|
|
444
|
+
);
|
|
445
|
+
if (s.waitingOn)
|
|
446
|
+
io.out(
|
|
447
|
+
`Claude Code waits for an answer (${s.waitingOn}): harnessd attach, then answer it`,
|
|
448
|
+
);
|
|
449
|
+
if (s.sessionId)
|
|
450
|
+
io.out(`conversation ${s.sessionId}${s.folder ? ` in ${s.folder}` : ""}`);
|
|
451
|
+
if (s.restarts > 0 || s.lastExit)
|
|
452
|
+
io.out(
|
|
453
|
+
`restarts ${s.restarts}${s.lastExit ? `, last exit code ${s.lastExit.code} ${ago(s.lastExit.at)} ago` : ""}`,
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
if (configError) io.out(configError);
|
|
457
|
+
for (const [name, channel] of Object.entries(channels))
|
|
458
|
+
io.out(`channel ${name}: events ${channel.events} (${channel.url})`);
|
|
459
|
+
if (s?.channelsRefused && Object.keys(channels).length > 0)
|
|
460
|
+
io.out(CHANNELS_REFUSED);
|
|
461
|
+
io.out(`log ${log}`);
|
|
462
|
+
for (const line of logTail) io.out(` ${line}`);
|
|
463
|
+
return code;
|
|
464
|
+
};
|
|
465
|
+
|
|
466
|
+
const attach = (paths: Harnessd.Paths, io: Io) =>
|
|
467
|
+
new Promise<number>((resolve) => {
|
|
468
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
469
|
+
io.err("harnessd attach needs a terminal.");
|
|
470
|
+
return resolve(1);
|
|
471
|
+
}
|
|
472
|
+
const connection = createConnection(paths.socket);
|
|
473
|
+
const send = (value: unknown) =>
|
|
474
|
+
connection.write(`${JSON.stringify(value)}\n`);
|
|
475
|
+
const onResize = () =>
|
|
476
|
+
send({
|
|
477
|
+
resize: { cols: process.stdout.columns, rows: process.stdout.rows },
|
|
478
|
+
});
|
|
479
|
+
const onInput = (data: Buffer) => {
|
|
480
|
+
const text = data.toString("utf8");
|
|
481
|
+
if (text.includes(DETACH)) connection.end();
|
|
482
|
+
else send({ input: text });
|
|
483
|
+
};
|
|
484
|
+
let done = false;
|
|
485
|
+
const finish = (code: number, line?: string) => {
|
|
486
|
+
if (done) return;
|
|
487
|
+
done = true;
|
|
488
|
+
process.stdin.setRawMode(false);
|
|
489
|
+
process.stdin.off("data", onInput);
|
|
490
|
+
process.stdin.pause();
|
|
491
|
+
process.stdout.off("resize", onResize);
|
|
492
|
+
process.stdout.write("\x1b[0m\r\n");
|
|
493
|
+
if (line) io.err(line);
|
|
494
|
+
resolve(code);
|
|
495
|
+
};
|
|
496
|
+
connection.once("error", () => finish(1, notRunning(paths)));
|
|
497
|
+
connection.once("connect", () => {
|
|
498
|
+
send({
|
|
499
|
+
command: "attach",
|
|
500
|
+
cols: process.stdout.columns,
|
|
501
|
+
rows: process.stdout.rows,
|
|
502
|
+
});
|
|
503
|
+
process.stdin.setRawMode(true);
|
|
504
|
+
process.stdin.resume();
|
|
505
|
+
process.stdin.on("data", onInput);
|
|
506
|
+
process.stdout.on("resize", onResize);
|
|
507
|
+
createInterface({ input: connection })
|
|
508
|
+
.on("error", () => {})
|
|
509
|
+
.on("line", (line) => {
|
|
510
|
+
try {
|
|
511
|
+
const message = JSON.parse(line) as { output?: string };
|
|
512
|
+
if (typeof message.output === "string")
|
|
513
|
+
process.stdout.write(message.output);
|
|
514
|
+
} catch {}
|
|
515
|
+
});
|
|
516
|
+
});
|
|
517
|
+
connection.once("close", () =>
|
|
518
|
+
finish(0, "Detached; Claude Code keeps running."),
|
|
519
|
+
);
|
|
520
|
+
});
|
|
521
|
+
|
|
522
|
+
/** Runs one harnessd command; resolves to the exit code. */
|
|
523
|
+
export const runHarnessd = async (
|
|
524
|
+
argv: readonly string[],
|
|
525
|
+
bin: string,
|
|
526
|
+
io: Io = {
|
|
527
|
+
out: (line) => void process.stdout.write(`${line}\n`),
|
|
528
|
+
err: (line) => void process.stderr.write(`${line}\n`),
|
|
529
|
+
terminal: ttyTerminal(),
|
|
530
|
+
},
|
|
531
|
+
): Promise<number> => {
|
|
532
|
+
const [first, ...rest] = argv;
|
|
533
|
+
if (
|
|
534
|
+
first === undefined ||
|
|
535
|
+
first === "help" ||
|
|
536
|
+
argv.some((arg) => arg === "--help" || arg === "-h")
|
|
537
|
+
) {
|
|
538
|
+
io.out(USAGE);
|
|
539
|
+
return 0;
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
return await run(first, rest, bin, io);
|
|
543
|
+
} catch (error) {
|
|
544
|
+
if (!(error as { usage?: boolean }).usage) throw error;
|
|
545
|
+
io.err(`${(error as Error).message} harnessd --help lists the commands.`);
|
|
546
|
+
return 2;
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
|
|
550
|
+
const service = (rest: readonly string[], bin: string, io: Io) => {
|
|
551
|
+
const [action, ...more] = rest;
|
|
552
|
+
if (action !== "install" && action !== "uninstall")
|
|
553
|
+
throw usageError("harnessd service takes install or uninstall.");
|
|
554
|
+
const flags: ServiceFlags = {};
|
|
555
|
+
for (let i = 0; i < more.length; i++) {
|
|
556
|
+
const arg = more[i]!;
|
|
557
|
+
if (action === "install" && arg === "--dry-run") flags.dryRun = true;
|
|
558
|
+
else if (action === "install" && arg === "--install-claude")
|
|
559
|
+
flags.installClaude = true;
|
|
560
|
+
else if (action === "install" && arg === "--skip-sign-in")
|
|
561
|
+
flags.skipSignIn = true;
|
|
562
|
+
else if (arg === "--user" && more[i + 1] !== undefined)
|
|
563
|
+
flags.user = more[++i]!;
|
|
564
|
+
else
|
|
565
|
+
throw usageError(
|
|
566
|
+
`harnessd service ${action} takes ${action === "install" ? "--user <name>, --dry-run, --install-claude and --skip-sign-in" : "--user <name>"}, not ${arg}.`,
|
|
567
|
+
);
|
|
568
|
+
}
|
|
569
|
+
return action === "install" ? install(flags, bin, io) : uninstall(flags, io);
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
const run = async (
|
|
573
|
+
first: string,
|
|
574
|
+
rest: readonly string[],
|
|
575
|
+
bin: string,
|
|
576
|
+
io: Io,
|
|
577
|
+
): Promise<number> => {
|
|
578
|
+
if (first === "--version") {
|
|
579
|
+
takes(first, rest);
|
|
580
|
+
io.out(VERSION);
|
|
581
|
+
return 0;
|
|
582
|
+
}
|
|
583
|
+
if (first === "service") return service(rest, bin, io);
|
|
584
|
+
const paths = pathsOf();
|
|
585
|
+
switch (first) {
|
|
586
|
+
case "status":
|
|
587
|
+
takes(first, rest, ["--json"]);
|
|
588
|
+
return status(paths, rest.includes("--json"), io);
|
|
589
|
+
case "start":
|
|
590
|
+
case "stop":
|
|
591
|
+
takes(first, rest);
|
|
592
|
+
return command(paths, { command: first }, io);
|
|
593
|
+
case "attach":
|
|
594
|
+
takes(first, rest);
|
|
595
|
+
return attach(paths, io);
|
|
596
|
+
case "run":
|
|
597
|
+
takes(first, rest);
|
|
598
|
+
await runDaemon(paths, bin);
|
|
599
|
+
return 0;
|
|
600
|
+
case "session-start": {
|
|
601
|
+
takes(first, rest);
|
|
602
|
+
const input = JSON.parse(await (io.stdin ?? stdin)()) as {
|
|
603
|
+
session_id?: unknown;
|
|
604
|
+
agent_id?: unknown;
|
|
605
|
+
};
|
|
606
|
+
// a subagent's start, not the conversation's
|
|
607
|
+
if (input.agent_id !== undefined) return 0;
|
|
608
|
+
if (typeof input.session_id !== "string")
|
|
609
|
+
throw new Error("Claude Code's SessionStart input has no session_id.");
|
|
610
|
+
const answer = await ask(paths.socket, {
|
|
611
|
+
command: "session-start",
|
|
612
|
+
sessionId: input.session_id,
|
|
613
|
+
});
|
|
614
|
+
if (answer?.ok) return 0;
|
|
615
|
+
io.err(answer ? String(answer.message) : notRunning(paths));
|
|
616
|
+
return 1;
|
|
617
|
+
}
|
|
618
|
+
case "channel": {
|
|
619
|
+
const name = rest[0] ?? "";
|
|
620
|
+
const channel = readConfig(paths).channels[name];
|
|
621
|
+
if (!channel) throw new Error(`No channel "${name}" in ${paths.config}`);
|
|
622
|
+
await serveChannel({
|
|
623
|
+
name,
|
|
624
|
+
channel,
|
|
625
|
+
paths,
|
|
626
|
+
log: logTo(paths.log, `channel ${name}: `),
|
|
627
|
+
});
|
|
628
|
+
return 0;
|
|
629
|
+
}
|
|
630
|
+
default:
|
|
631
|
+
throw usageError(`Unknown command ${first}.`);
|
|
632
|
+
}
|
|
633
|
+
};
|