@harness-sdk/harnessd 0.0.1 → 0.1.0

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