@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/dist/cli.js CHANGED
@@ -1,95 +1,220 @@
1
- import { MANAGED_SETTINGS, allowChannel, channelBlockers, which } from "./claude.js";
2
- import { DEFAULT_CONFIG, pathsOf, readConfig } from "./config.js";
3
- import { readStatus, serveChannel, statusFile } from "./channel.js";
1
+ import { defaultConfig, ownFolder, pathsOf, readConfig } from "./config.js";
2
+ import { readStatus, serveChannel, serverCli, subscriptionLabel } from "./channel.js";
4
3
  import { logTo } from "./log.js";
4
+ import { CHANNELS_REFUSED } from "./prompts.js";
5
5
  import { ask, runDaemon } from "./daemon.js";
6
- import { load, plistOf, stableNode, unload } from "./launchd.js";
7
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
8
- import { spawn, spawnSync } from "node:child_process";
6
+ import { stableNode } from "./launchd.js";
7
+ import { asUser, installService, lookUpUser, removeService, serviceIn, servicePath, serviceText, supportedPlatform } from "./service.js";
8
+ import { ensureClaude, ensureSignedIn, ttyTerminal } from "./setup.js";
9
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { spawnSync } from "node:child_process";
11
+ import { createRequire } from "node:module";
9
12
  import { createConnection } from "node:net";
13
+ import { userInfo } from "node:os";
14
+ import { delimiter, dirname } from "node:path";
10
15
  import { createInterface } from "node:readline";
16
+ import { processCliIo, runCli } from "toolport/cli";
11
17
  // src/cli.ts
12
- const USAGE = `harnessd keeps Claude Code running on this Mac, connected to the events of your agentic apps.
18
+ const USAGE = `harnessd keeps Claude Code running on this computer, connected to the events of your agentic apps.
13
19
 
14
20
  usage: harnessd <command>
15
21
 
16
- install Start harnessd now and at every login
17
- uninstall Stop harnessd and remove it from login
18
- status [--json] What runs, which conversation, and whether each channel's events arrive
19
- start Start Claude Code after a stop
20
- stop Stop Claude Code; it stays stopped until start
21
- new [message] Start a new conversation, with message as its first message
22
- attach Open Claude Code's terminal; Ctrl-\\ detaches
23
- logs Follow harnessd's log
22
+ service install Start harnessd now and at every login; with sudo, at every boot
23
+ service uninstall Stop harnessd and remove its service
24
+ status [--json] What runs, which conversation, the channel's events, and the log's last lines
25
+ start Start Claude Code after a stop
26
+ stop Stop Claude Code; harnessd stays up, and Claude Code stays stopped until start
27
+ attach Open Claude Code's terminal; Ctrl-\\ detaches
28
+ tools <server> ... Run a server's tools, as the agent's <server> command does
29
+ --version Print harnessd's version
24
30
 
25
- Settings: ~/.harnessd/config.json (HARNESSD_HOME moves the folder).`;
31
+ service install takes:
32
+ --user <name> With sudo: the user the boot service runs as; service uninstall takes it too
33
+ --dry-run Print the service's file and change nothing
34
+ --install-claude When Claude Code is missing, install it with Anthropic's installer without asking
35
+ --skip-sign-in Install even when Claude Code isn't signed in, and print how to sign in
36
+
37
+ Settings: ~/.config/harnessd/config.json. State and log: ~/.local/state/harnessd.
38
+ XDG_CONFIG_HOME and XDG_STATE_HOME move them; HARNESSD_HOME puts both in one folder.`;
39
+ const VERSION = createRequire(import.meta.url)("../package.json").version;
26
40
  const DETACH = "";
27
- const notRunning = (paths) => `harnessd isn't running in ${paths.home}: harnessd install starts it.`;
41
+ const stdin = async () => {
42
+ let text = "";
43
+ for await (const chunk of process.stdin) text += String(chunk);
44
+ return text;
45
+ };
46
+ const notRunning = (paths) => `harnessd isn't running in ${paths.home}: harnessd service install starts it.`;
47
+ const usageError = (message) => Object.assign(new Error(message), { usage: true });
48
+ /** Refuses any argument a command doesn't take, so a typo never runs the command. */
49
+ const takes = (command, rest, allowed = []) => {
50
+ const extra = rest.find((arg) => !allowed.includes(arg));
51
+ if (extra !== void 0) throw usageError(`harnessd ${command} takes ${allowed.length > 0 ? `only ${allowed.join(", ")}` : "no arguments"}, not ${extra}.`);
52
+ };
53
+ const tail = (file, lines) => {
54
+ try {
55
+ const text = readFileSync(file, "utf8").trimEnd();
56
+ return text ? text.split("\n").slice(-lines) : [];
57
+ } catch {
58
+ return [];
59
+ }
60
+ };
61
+ const daemonStatus = async (paths) => (await ask(paths.socket, { command: "status" }))?.status;
62
+ const START_WAIT_MS = 9e4;
63
+ /** Waits until Claude Code runs, was stopped by hand, or failed to start; `not` is the harnessd an install replaces. */
64
+ const settled = async (paths, not, waitMs = START_WAIT_MS) => {
65
+ const until = Date.now() + waitMs;
66
+ for (;;) {
67
+ const status = await daemonStatus(paths);
68
+ const ours = status && status.daemonPid !== not ? status : void 0;
69
+ if (ours && ours.state !== "starting" || Date.now() >= until) return ours;
70
+ await new Promise((resolve) => setTimeout(resolve, 250));
71
+ }
72
+ };
73
+ /** After a failed start: the log lines that show why; resolves to the exit code. */
74
+ const showLog = (log, io) => {
75
+ for (const line of tail(log, 10)) io.err(` ${line}`);
76
+ io.err(`log ${log}`);
77
+ return 1;
78
+ };
79
+ /** Says why a start failed, with the log's last lines; resolves to the exit code. */
80
+ const startFailed = (paths, status, io) => {
81
+ io.err(!status ? "harnessd didn't start." : status.state === "waiting" ? `Claude Code didn't stay up${status.lastExit ? ` (exit code ${status.lastExit.code})` : ""}; harnessd keeps trying.` : "Claude Code is still starting; harnessd status shows how it goes.");
82
+ return showLog(status ? paths.log : paths.serviceLog, io);
83
+ };
28
84
  const command = async (paths, request, io) => {
29
85
  const answer = await ask(paths.socket, request);
30
86
  if (!answer) {
31
87
  io.err(notRunning(paths));
32
88
  return 1;
33
89
  }
34
- io[answer.ok ? "out" : "err"](String(answer.message));
35
- return answer.ok ? 0 : 1;
90
+ if (!answer.ok) {
91
+ io.err(String(answer.message));
92
+ return request.command === "stop" ? 1 : showLog(paths.log, io);
93
+ }
94
+ if (request.command !== "stop") {
95
+ const status = await settled(paths);
96
+ if (status?.state !== "running") return startFailed(paths, status, io);
97
+ }
98
+ io.out(String(answer.message));
99
+ return 0;
36
100
  };
37
- const confirm = async (question) => {
38
- const lines = createInterface({
39
- input: process.stdin,
40
- output: process.stdout
101
+ /** Who the service is for: with sudo, a boot service that runs as the named user; without, your own login item. */
102
+ const serviceTarget = (action, flags) => {
103
+ const root = process.getuid?.() === 0;
104
+ if (flags.user !== void 0 && !root && !flags.dryRun) throw new Error(`A boot service needs root: sudo harnessd service ${action} --user ${flags.user}`);
105
+ const name = flags.user ?? (root ? process.env.SUDO_USER : void 0);
106
+ if (root && name === void 0) throw new Error("Name the user harnessd runs as: --user <name>");
107
+ const user = name === void 0 ? void 0 : lookUpUser(name);
108
+ const caller = process.env.SUDO_USER ?? userInfo().username;
109
+ const moved = [
110
+ "HARNESSD_HOME",
111
+ "XDG_CONFIG_HOME",
112
+ "XDG_STATE_HOME"
113
+ ].find((key) => process.env[key]);
114
+ if (user && user.name !== caller && moved) throw new Error(`${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.`);
115
+ if (user) Object.assign(process.env, {
116
+ HOME: user.home,
117
+ USER: user.name,
118
+ LOGNAME: user.name
41
119
  });
42
- const answer = await new Promise((resolve) => lines.question(`${question} [y/N] `, resolve));
43
- lines.close();
44
- return /^y(es)?$/i.test(answer.trim());
120
+ const paths = pathsOf();
121
+ if (user && !paths.socket.startsWith(paths.home)) throw new Error(`${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.`);
122
+ const bootLabel = (name) => paths.label === "dev.harnessd" ? `dev.harnessd.${name}` : paths.label;
123
+ return {
124
+ user,
125
+ paths,
126
+ label: user ? bootLabel(user.name) : paths.label,
127
+ /** The other kind's file, when one is installed for this state folder: it holds one harnessd. */
128
+ other: () => serviceIn(paths.home, user === void 0)
129
+ };
130
+ };
131
+ const uninstall = (flags, io) => {
132
+ const { user, paths, label, other } = serviceTarget("uninstall", flags);
133
+ if (removeService(label, user !== void 0)) {
134
+ io.out(`Removed harnessd's service. Its settings stay in ${paths.config}, its conversation in ${paths.home}.`);
135
+ return 0;
136
+ }
137
+ const file = other();
138
+ io[file ? "err" : "out"](file ? `harnessd is installed as a ${user ? "login item" : "boot service"} (${file}): run ${user ? "" : "sudo "}harnessd service uninstall.` : "harnessd wasn't installed.");
139
+ return file ? 1 : 0;
45
140
  };
46
- const install = async (paths, bin, io) => {
47
- if (process.platform !== "darwin") throw new Error("harnessd runs on macOS (it starts with launchd).");
48
- if (bin.includes("/_npx/")) throw new Error("Install harnessd first, so launchd has a lasting copy to start: npm install -g @harness-sdk/harnessd");
49
- const claude = which("claude");
141
+ const install = async (flags, bin, io) => {
142
+ supportedPlatform();
143
+ if (bin.includes("/_npx/")) throw new Error("Install harnessd first, so the service has a lasting copy to start: npm install -g @harness-sdk/harnessd");
144
+ const { user, paths, label, other } = serviceTarget("install", flags);
145
+ const own = (process.env.PATH ?? "/usr/bin:/bin").split(delimiter);
146
+ const terminal = flags.dryRun ? void 0 : io.terminal;
147
+ const claude = await ensureClaude({
148
+ terminal,
149
+ user,
150
+ install: flags.installClaude && !flags.dryRun
151
+ });
50
152
  const version = spawnSync(claude, ["--version"], {
51
153
  encoding: "utf8",
52
- timeout: 3e4
154
+ timeout: 3e4,
155
+ ...user && process.getuid?.() === 0 && {
156
+ uid: user.uid,
157
+ gid: user.gid
158
+ }
53
159
  });
54
160
  if (version.status !== 0) throw new Error(`${claude} --version failed: ${(version.stderr || version.stdout || "").trim()}`);
55
- mkdirSync(paths.home, { recursive: true });
56
- if (!existsSync(paths.config)) writeFileSync(paths.config, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`);
57
- const config = readConfig(paths);
58
- mkdirSync(config.folder, { recursive: true });
59
- const blockers = Object.keys(config.channels).length > 0 ? channelBlockers() : [];
60
- if (blockers.length > 0) {
61
- io.out(`Claude Code lets a channel in only when this Mac's managed settings list it:\n ${blockers.join("\n ")}`);
62
- if (process.stdin.isTTY && await confirm(`Let harnessd's channels in? This writes /Library/Application Support/ClaudeCode/managed-settings.json with sudo.`)) {
63
- if (spawnSync("sudo", [
64
- "sh",
65
- "-c",
66
- `mkdir -p "$(dirname "$1")" && cat > "$1"`,
67
- "sh",
68
- "/Library/Application Support/ClaudeCode/managed-settings.json"
69
- ], {
70
- input: `${JSON.stringify(allowChannel(), null, 2)}\n`,
71
- stdio: [
72
- "pipe",
73
- "inherit",
74
- "inherit"
75
- ]
76
- }).status !== 0) throw new Error(`Couldn't write ${MANAGED_SETTINGS}.`);
77
- } else io.out("Until they're let in, Claude Code drops the channels' events; harnessd status says so.");
78
- }
79
- const env = { PATH: process.env.PATH ?? "/usr/bin:/bin" };
80
- if (process.env.HARNESSD_HOME) env.HARNESSD_HOME = paths.home;
81
- load(paths.label, plistOf({
82
- label: paths.label,
83
- node: stableNode(),
161
+ const node = stableNode();
162
+ const spec = {
163
+ label,
164
+ node,
84
165
  bin,
85
- env,
86
- paths
87
- }));
166
+ env: {
167
+ PATH: [.../* @__PURE__ */ new Set([
168
+ ...own,
169
+ dirname(claude),
170
+ dirname(node)
171
+ ])].filter((dir) => dir.startsWith("/")).join(delimiter),
172
+ ...user && {
173
+ HOME: user.home,
174
+ USER: user.name,
175
+ LOGNAME: user.name
176
+ },
177
+ ...paths.env
178
+ },
179
+ paths,
180
+ ...user && { user: user.name }
181
+ };
182
+ const file = servicePath(label, user !== void 0);
183
+ if (flags.dryRun) {
184
+ io.out(`Would write ${file} and start it${user ? `, as root, to run as ${user.name} from every boot` : ""}:\n\n${serviceText(spec)}`);
185
+ return 0;
186
+ }
187
+ const taken = other();
188
+ if (taken) throw new Error(`harnessd is already installed as a ${user ? "login item" : "boot service"} (${taken}): run ${user ? "" : "sudo "}harnessd service uninstall first.`);
189
+ const config = asUser(user, () => {
190
+ ownFolder(paths.home);
191
+ ownFolder(dirname(paths.config));
192
+ if (!existsSync(paths.config)) writeFileSync(paths.config, `${JSON.stringify(defaultConfig(), null, 2)}\n`);
193
+ chmodSync(paths.config, 384);
194
+ appendFileSync(paths.serviceLog, "");
195
+ const config = readConfig(paths);
196
+ mkdirSync(config.folder, { recursive: true });
197
+ return config;
198
+ });
199
+ const signIn = await ensureSignedIn({
200
+ claude,
201
+ paths,
202
+ env: spec.env,
203
+ user,
204
+ terminal,
205
+ skip: flags.skipSignIn
206
+ });
207
+ const before = (await daemonStatus(paths))?.daemonPid;
208
+ await installService(spec);
209
+ const status = await settled(paths, before);
210
+ if (status?.state !== "running" && status?.state !== "stopped") return startFailed(paths, status, io);
211
+ const when = user ? `at every boot, as ${user.name}` : "at every login";
88
212
  io.out([
89
- `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and at every login.`,
90
- " harnessd attach its terminal: sign in there if Claude Code asks; Ctrl-\\ detaches",
213
+ status.state === "stopped" ? `harnessd is installed for ${config.folder} and starts ${when}. Claude Code is stopped: harnessd start starts it.` : `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and ${when}.`,
214
+ " harnessd attach its terminal; Ctrl-\\ detaches",
91
215
  " harnessd status what runs and whether events arrive",
92
- "Turn on automatic login (System Settings > Users & Groups), so harnessd comes back after a power cut."
216
+ ...signIn ? [signIn] : [],
217
+ ...user ? [] : [process.platform === "darwin" ? "It starts when you log in: turn on automatic login (System Settings > Users & Groups), so it comes back after a power cut." : "It starts when you sign in and stops when you sign out.", `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`]
93
218
  ].join("\n"));
94
219
  return 0;
95
220
  };
@@ -97,21 +222,27 @@ const ago = (iso) => {
97
222
  const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1e3));
98
223
  return s < 120 ? `${s}s` : s < 7200 ? `${Math.round(s / 60)}m` : s < 172800 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`;
99
224
  };
100
- /** Each channel as of the Claude Code that runs now: what an earlier run heard says nothing about this one. */
101
- const channelReport = (paths, config, running, blockers) => Object.fromEntries(Object.entries(config?.channels ?? {}).map(([name, channel]) => {
102
- const status = readStatus(statusFile(paths, name));
225
+ /** The channel as of the Claude Code that runs now (what an earlier run heard says nothing about this one); none without subscriptions. */
226
+ const channelReport = (paths, config, running) => {
227
+ const subscribe = config?.channel.subscribe ?? [];
228
+ if (subscribe.length === 0) return void 0;
229
+ const status = readStatus(paths.channel);
103
230
  const since = running?.state === "running" || running?.state === "starting" ? running.startedAt : void 0;
104
231
  const now = (at) => since !== void 0 && at !== void 0 && at >= since;
105
- const events = since === void 0 ? "off (Claude Code isn't running)" : now(status.heardAt) ? "arriving" : now(status.pushedAt) ? "sent, not in the conversation yet" : "none yet";
106
- return [name, {
107
- url: channel.url,
108
- events,
109
- ...status,
110
- ...blockers.length > 0 && { blockers }
111
- }];
112
- }));
232
+ return {
233
+ events: since === void 0 ? "off (Claude Code isn't running)" : running?.channelsRefused ? "refused" : now(status.heardAt) ? "arriving" : now(status.pushedAt) ? "sent, not in the conversation yet" : "none yet",
234
+ subscribe: subscribe.map(subscriptionLabel),
235
+ ...status.pushedAt && { pushedAt: status.pushedAt },
236
+ ...status.heardAt && { heardAt: status.heardAt }
237
+ };
238
+ };
239
+ /** Each server: its URL, and the events the channel takes from it. */
240
+ const serverReport = (config) => Object.fromEntries(Object.entries(config?.servers ?? {}).map(([name, server]) => [name, {
241
+ url: server.url,
242
+ events: config.channel.subscribe.filter((subscription) => subscription.server === name).map((subscription) => subscription.event)
243
+ }]));
113
244
  const status = async (paths, json, io) => {
114
- const answer = await ask(paths.socket, { command: "status" });
245
+ const s = await daemonStatus(paths);
115
246
  let config;
116
247
  let configError;
117
248
  try {
@@ -119,31 +250,47 @@ const status = async (paths, json, io) => {
119
250
  } catch (error) {
120
251
  configError = error instanceof Error ? error.message : String(error);
121
252
  }
122
- const blockers = config && Object.keys(config.channels).length > 0 ? channelBlockers() : [];
123
- const channels = channelReport(paths, config, answer?.status, blockers);
124
- const s = answer?.status;
253
+ const channel = channelReport(paths, config, s);
254
+ const servers = serverReport(config);
255
+ const log = s || !existsSync(paths.serviceLog) ? paths.log : paths.serviceLog;
256
+ const logTail = tail(log, 10);
257
+ const code = s && !configError ? 0 : 1;
125
258
  if (json) {
126
259
  io.out(JSON.stringify({
127
260
  running: !!s,
128
261
  home: paths.home,
262
+ config: paths.config,
129
263
  ...s && { status: s },
130
264
  ...configError && { configError },
131
- channels
265
+ servers,
266
+ ...channel && { channel },
267
+ log,
268
+ logTail
132
269
  }));
133
- return s ? 0 : 1;
270
+ return code;
134
271
  }
135
272
  if (!s) io.out(notRunning(paths));
136
273
  else {
137
274
  const since = s.startedAt ? ` for ${ago(s.startedAt)}` : "";
138
- const what = s.state === "running" ? `Claude Code running${since} (pid ${s.pid})` : s.state === "waiting" ? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1e3))}s` : ""}` : s.state === "stopped" ? "Claude Code stopped (harnessd start starts it)" : "Claude Code starting";
275
+ const what = s.state === "running" ? `Claude Code${s.claudeVersion ? ` ${s.claudeVersion}` : ""} running${since} (pid ${s.pid})` : s.state === "waiting" ? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1e3))}s` : ""}` : s.state === "stopped" ? "Claude Code stopped (harnessd start starts it)" : "Claude Code starting";
139
276
  io.out(`harnessd ${s.daemonPid}: ${what}`);
277
+ if (s.update) io.out(s.update.at ? `updated from Claude Code ${s.update.from} to ${s.update.to} ${ago(s.update.at)} ago` : `Claude Code ${s.update.to} is installed; harnessd restarts into it once the agent is idle`);
278
+ if (s.account) io.out(`account ${s.account}`);
279
+ for (const [name, stop] of Object.entries(s.accountsStopped ?? {})) io.out(`account ${name} stopped at ${stop.why}; harnessd tries it again after ${new Date(stop.until).toLocaleString()}`);
280
+ if (s.waitingOn) io.out(`Claude Code waits for an answer (${s.waitingOn}): harnessd attach, then answer it`);
140
281
  if (s.sessionId) io.out(`conversation ${s.sessionId}${s.folder ? ` in ${s.folder}` : ""}`);
141
282
  if (s.restarts > 0 || s.lastExit) io.out(`restarts ${s.restarts}${s.lastExit ? `, last exit code ${s.lastExit.code} ${ago(s.lastExit.at)} ago` : ""}`);
142
283
  }
143
284
  if (configError) io.out(configError);
144
- for (const [name, channel] of Object.entries(channels)) io.out(`channel ${name}: events ${channel.events} (${channel.url})`);
145
- if (blockers.length > 0 && Object.values(channels).some((c) => c.events !== "arriving")) io.out(`channels are blocked: ${blockers.join("; ")} (harnessd install lets them in)`);
146
- return s ? 0 : 1;
285
+ for (const [name, server] of Object.entries(servers)) io.out(`server ${name}: the ${name} command, ${server.events.length > 0 ? `events ${server.events.join(", ")}` : "no events subscribed"} (${server.url})`);
286
+ if (channel) {
287
+ io.out(`channel: events ${channel.events}`);
288
+ for (const label of channel.subscribe) io.out(` ${label}`);
289
+ }
290
+ if (s?.channelsRefused && channel) io.out(CHANNELS_REFUSED);
291
+ io.out(`log ${log}`);
292
+ for (const line of logTail) io.out(` ${line}`);
293
+ return code;
147
294
  };
148
295
  const attach = (paths, io) => new Promise((resolve) => {
149
296
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
@@ -184,7 +331,7 @@ const attach = (paths, io) => new Promise((resolve) => {
184
331
  process.stdin.resume();
185
332
  process.stdin.on("data", onInput);
186
333
  process.stdout.on("resize", onResize);
187
- createInterface({ input: connection }).on("line", (line) => {
334
+ createInterface({ input: connection }).on("error", () => {}).on("line", (line) => {
188
335
  try {
189
336
  const message = JSON.parse(line);
190
337
  if (typeof message.output === "string") process.stdout.write(message.output);
@@ -196,61 +343,100 @@ const attach = (paths, io) => new Promise((resolve) => {
196
343
  /** Runs one harnessd command; resolves to the exit code. */
197
344
  const runHarnessd = async (argv, bin, io = {
198
345
  out: (line) => void process.stdout.write(`${line}\n`),
199
- err: (line) => void process.stderr.write(`${line}\n`)
346
+ err: (line) => void process.stderr.write(`${line}\n`),
347
+ terminal: ttyTerminal()
200
348
  }) => {
201
- const paths = pathsOf();
202
349
  const [first, ...rest] = argv;
350
+ if (first === void 0 || first === "help" || argv.slice(0, first === "tools" ? 2 : void 0).some((arg) => arg === "--help" || arg === "-h")) {
351
+ io.out(USAGE);
352
+ return 0;
353
+ }
354
+ try {
355
+ return await run(first, rest, bin, io);
356
+ } catch (error) {
357
+ if (!error.usage) throw error;
358
+ io.err(`${error.message} harnessd --help lists the commands.`);
359
+ return 2;
360
+ }
361
+ };
362
+ const service = (rest, bin, io) => {
363
+ const [action, ...more] = rest;
364
+ if (action !== "install" && action !== "uninstall") throw usageError("harnessd service takes install or uninstall.");
365
+ const flags = {};
366
+ for (let i = 0; i < more.length; i++) {
367
+ const arg = more[i];
368
+ if (action === "install" && arg === "--dry-run") flags.dryRun = true;
369
+ else if (action === "install" && arg === "--install-claude") flags.installClaude = true;
370
+ else if (action === "install" && arg === "--skip-sign-in") flags.skipSignIn = true;
371
+ else if (arg === "--user" && more[i + 1] !== void 0) flags.user = more[++i];
372
+ else throw usageError(`harnessd service ${action} takes ${action === "install" ? "--user <name>, --dry-run, --install-claude and --skip-sign-in" : "--user <name>"}, not ${arg}.`);
373
+ }
374
+ return action === "install" ? install(flags, bin, io) : uninstall(flags, io);
375
+ };
376
+ const run = async (first, rest, bin, io) => {
377
+ if (first === "--version") {
378
+ takes(first, rest);
379
+ io.out(VERSION);
380
+ return 0;
381
+ }
382
+ if (first === "service") return service(rest, bin, io);
383
+ const paths = pathsOf();
203
384
  switch (first) {
204
- case "install": return install(paths, bin, io);
205
- case "uninstall": {
206
- const had = unload(paths.label);
207
- io.out(had ? `Removed harnessd from login. Its settings and conversation stay in ${paths.home}.` : "harnessd wasn't installed.");
208
- return 0;
209
- }
210
- case "status": return status(paths, rest.includes("--json"), io);
385
+ case "status":
386
+ takes(first, rest, ["--json"]);
387
+ return status(paths, rest.includes("--json"), io);
211
388
  case "start":
212
- case "stop": return command(paths, { command: first }, io);
213
- case "new": return command(paths, {
214
- command: "new",
215
- ...rest.length > 0 && { message: rest.join(" ") }
216
- }, io);
217
- case "attach": return attach(paths, io);
218
- case "logs": return new Promise((resolve) => {
219
- if (!existsSync(paths.log)) {
220
- io.err(`No log yet at ${paths.log}.`);
221
- return resolve(1);
222
- }
223
- spawn("tail", [
224
- "-n",
225
- "100",
226
- "-F",
227
- paths.log
228
- ], { stdio: "inherit" }).on("exit", (code) => resolve(code ?? 0));
229
- });
389
+ case "stop":
390
+ takes(first, rest);
391
+ return command(paths, { command: first }, io);
392
+ case "attach":
393
+ takes(first, rest);
394
+ return attach(paths, io);
230
395
  case "run":
396
+ takes(first, rest);
231
397
  await runDaemon(paths, bin);
232
398
  return 0;
233
- case "channel": {
234
- const name = rest[0] ?? "";
235
- const channel = readConfig(paths).channels[name];
236
- if (!channel) throw new Error(`No channel "${name}" in ${paths.config}`);
399
+ case "session-start": {
400
+ takes(first, rest);
401
+ const input = JSON.parse(await (io.stdin ?? stdin)());
402
+ if (input.agent_id !== void 0) return 0;
403
+ if (typeof input.session_id !== "string") throw new Error("Claude Code's SessionStart input has no session_id.");
404
+ const answer = await ask(paths.socket, {
405
+ command: "session-start",
406
+ sessionId: input.session_id
407
+ });
408
+ if (answer?.ok) return 0;
409
+ io.err(answer ? String(answer.message) : notRunning(paths));
410
+ return 1;
411
+ }
412
+ case "idle": {
413
+ takes(first, rest);
414
+ const answer = await ask(paths.socket, { command: "idle" });
415
+ if (answer?.ok) return 0;
416
+ io.err(answer ? String(answer.message) : notRunning(paths));
417
+ return 1;
418
+ }
419
+ case "channel":
420
+ takes(first, rest);
237
421
  await serveChannel({
238
- name,
239
- channel,
422
+ config: readConfig(paths),
240
423
  paths,
241
- log: logTo(paths.log, `channel ${name}: `)
424
+ log: logTo(paths.log, "channel: ")
242
425
  });
243
426
  return 0;
427
+ case "tools": {
428
+ const [name, ...args] = rest;
429
+ if (name === void 0) throw usageError("harnessd tools takes a server's name.");
430
+ const { servers } = readConfig(paths);
431
+ const server = Object.hasOwn(servers, name) ? servers[name] : void 0;
432
+ if (!server) throw new Error(`No server "${name}" in ${paths.config}`);
433
+ return runCli(serverCli(paths, name, server, process.env), {
434
+ ...await processCliIo(args),
435
+ stdout: io.out,
436
+ stderr: io.err
437
+ });
244
438
  }
245
- case void 0:
246
- case "help":
247
- case "--help":
248
- case "-h":
249
- io.out(USAGE);
250
- return first === void 0 ? 1 : 0;
251
- default:
252
- io.err(`Unknown command ${first}.\n\n${USAGE}`);
253
- return 2;
439
+ default: throw usageError(`Unknown command ${first}.`);
254
440
  }
255
441
  };
256
442
  export { runHarnessd };