@harness-sdk/harnessd 0.0.0-stage → 0.0.1

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 (53) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -2
  3. package/dist/bin.d.ts +3 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +15 -0
  6. package/dist/bin.js.map +1 -0
  7. package/dist/channel.d.ts +56 -0
  8. package/dist/channel.d.ts.map +1 -0
  9. package/dist/channel.js +356 -0
  10. package/dist/channel.js.map +1 -0
  11. package/dist/claude.d.ts +42 -0
  12. package/dist/claude.d.ts.map +1 -0
  13. package/dist/claude.js +166 -0
  14. package/dist/claude.js.map +1 -0
  15. package/dist/cli.d.ts +8 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +258 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/config.d.ts +43 -0
  20. package/dist/config.d.ts.map +1 -0
  21. package/dist/config.js +121 -0
  22. package/dist/config.js.map +1 -0
  23. package/dist/daemon.d.ts +24 -0
  24. package/dist/daemon.d.ts.map +1 -0
  25. package/dist/daemon.js +239 -0
  26. package/dist/daemon.js.map +1 -0
  27. package/dist/launchd.d.ts +22 -0
  28. package/dist/launchd.d.ts.map +1 -0
  29. package/dist/launchd.js +88 -0
  30. package/dist/launchd.js.map +1 -0
  31. package/dist/log.d.ts +3 -0
  32. package/dist/log.d.ts.map +1 -0
  33. package/dist/log.js +17 -0
  34. package/dist/log.js.map +1 -0
  35. package/dist/terminal.d.ts +11 -0
  36. package/dist/terminal.d.ts.map +1 -0
  37. package/dist/terminal.js +36 -0
  38. package/dist/terminal.js.map +1 -0
  39. package/dist/watchdog.d.ts +73 -0
  40. package/dist/watchdog.d.ts.map +1 -0
  41. package/dist/watchdog.js +230 -0
  42. package/dist/watchdog.js.map +1 -0
  43. package/package.json +54 -4
  44. package/src/bin.ts +18 -0
  45. package/src/channel.ts +461 -0
  46. package/src/claude.ts +274 -0
  47. package/src/cli.ts +372 -0
  48. package/src/config.ts +203 -0
  49. package/src/daemon.ts +312 -0
  50. package/src/launchd.ts +126 -0
  51. package/src/log.ts +17 -0
  52. package/src/terminal.ts +33 -0
  53. package/src/watchdog.ts +310 -0
package/src/claude.ts ADDED
@@ -0,0 +1,274 @@
1
+ import { execFile } from "node:child_process";
2
+ import {
3
+ accessSync,
4
+ constants,
5
+ existsSync,
6
+ mkdirSync,
7
+ readFileSync,
8
+ readdirSync,
9
+ realpathSync,
10
+ renameSync,
11
+ rmSync,
12
+ statSync,
13
+ writeFileSync,
14
+ } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { delimiter, join } from "node:path";
17
+ import type { Harnessd } from "./config";
18
+ import type { Watchdog } from "./watchdog";
19
+
20
+ /** How Claude Code names a `--plugin-dir` plugin, and what `--channels` takes. */
21
+ export const PLUGIN = "harnessd@inline";
22
+ export const MANAGED_SETTINGS =
23
+ "/Library/Application Support/ClaudeCode/managed-settings.json";
24
+
25
+ const claudeDir = (env: NodeJS.ProcessEnv) =>
26
+ env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
27
+
28
+ /**
29
+ * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
30
+ * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field
31
+ * changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.
32
+ */
33
+ export const trustFolder = (
34
+ folder: string,
35
+ env: NodeJS.ProcessEnv = process.env,
36
+ ): boolean => {
37
+ const file = env.CLAUDE_CONFIG_DIR
38
+ ? join(env.CLAUDE_CONFIG_DIR, ".claude.json")
39
+ : join(homedir(), ".claude.json");
40
+ if (!existsSync(file)) return false;
41
+ const text = readFileSync(file, "utf8");
42
+ const config = JSON.parse(text) as {
43
+ projects?: Record<string, { hasTrustDialogAccepted?: boolean }>;
44
+ };
45
+ const key = realpathSync(folder);
46
+ if (config.projects?.[key]?.hasTrustDialogAccepted === true) return true;
47
+ config.projects = {
48
+ ...config.projects,
49
+ [key]: { ...config.projects?.[key], hasTrustDialogAccepted: true },
50
+ };
51
+ const pretty = text.trimEnd() === JSON.stringify(JSON.parse(text), null, 2);
52
+ const written = `${pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)}${text.endsWith("\n") ? "\n" : ""}`;
53
+ const temp = `${file}.harnessd-${process.pid}`;
54
+ writeFileSync(temp, written, { mode: statSync(file).mode & 0o777 });
55
+ renameSync(temp, file);
56
+ return true;
57
+ };
58
+
59
+ /** A conversation's transcript, wherever Claude Code put it. */
60
+ export const findTranscript = (
61
+ sessionId: string,
62
+ env: NodeJS.ProcessEnv = process.env,
63
+ ): string | undefined => {
64
+ const projects = join(claudeDir(env), "projects");
65
+ try {
66
+ for (const dir of readdirSync(projects)) {
67
+ const file = join(projects, dir, `${sessionId}.jsonl`);
68
+ if (existsSync(file)) return file;
69
+ }
70
+ } catch {}
71
+ return undefined;
72
+ };
73
+
74
+ /** The first `name` on `path` that can run. */
75
+ export const which = (name: string, path = process.env.PATH ?? "") => {
76
+ if (name.includes("/")) return name;
77
+ for (const dir of path.split(delimiter)) {
78
+ if (!dir) continue;
79
+ try {
80
+ accessSync(join(dir, name), constants.X_OK);
81
+ return join(dir, name);
82
+ } catch {}
83
+ }
84
+ throw new Error(
85
+ `${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`,
86
+ );
87
+ };
88
+
89
+ /**
90
+ * harnessd's plugin, written before each start from the config's channels: one MCP server per channel, each
91
+ * `harnessd channel <name>`. None: no plugin.
92
+ */
93
+ export const writePlugin = (
94
+ paths: Harnessd.Paths,
95
+ config: Harnessd.Config,
96
+ bin: string,
97
+ ): boolean => {
98
+ rmSync(paths.plugin, { recursive: true, force: true });
99
+ const names = Object.keys(config.channels);
100
+ if (names.length === 0) return false;
101
+ mkdirSync(join(paths.plugin, ".claude-plugin"), { recursive: true });
102
+ const manifest = {
103
+ name: "harnessd",
104
+ version: "1.0.0",
105
+ description: "harnessd's channels: each one's events, and its tools",
106
+ mcpServers: Object.fromEntries(
107
+ names.map((name) => [
108
+ name,
109
+ {
110
+ command: process.execPath,
111
+ args: [bin, "channel", name],
112
+ env: { HARNESSD_HOME: paths.home },
113
+ },
114
+ ]),
115
+ ),
116
+ channels: names.map((name) => ({ server: name, displayName: name })),
117
+ };
118
+ writeFileSync(
119
+ join(paths.plugin, ".claude-plugin", "plugin.json"),
120
+ `${JSON.stringify(manifest, null, 2)}\n`,
121
+ );
122
+ return true;
123
+ };
124
+
125
+ /**
126
+ * The claude command line for one start (after the binary). `--channels` names the plugin only when the managed
127
+ * settings let it in: a refused entry there also shuts out the same plugin loaded with the development flag.
128
+ */
129
+ export const claudeArgs = (o: {
130
+ start: Watchdog.Start;
131
+ plugin: string | undefined;
132
+ allowed: boolean;
133
+ config: Harnessd.Config;
134
+ extra: readonly string[];
135
+ }) => [
136
+ "--dangerously-skip-permissions",
137
+ ...(o.plugin ? ["--plugin-dir", o.plugin] : []),
138
+ ...(o.plugin && o.allowed ? ["--channels", `plugin:${PLUGIN}`] : []),
139
+ ...(o.start.resume
140
+ ? ["--resume", o.start.sessionId]
141
+ : ["--session-id", o.start.sessionId]),
142
+ // before the config's arguments: after a list flag (--add-dir…) claude would take it as one more value
143
+ ...(o.start.prompt ? [o.start.prompt] : []),
144
+ ...o.config.args,
145
+ ...o.extra,
146
+ ];
147
+
148
+ export type Prestart = { env: Record<string, string>; args: string[] };
149
+
150
+ /** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */
151
+ export const prestart = (
152
+ command: string,
153
+ folder: string,
154
+ env: NodeJS.ProcessEnv,
155
+ log: (line: string) => void,
156
+ ) =>
157
+ new Promise<Prestart>((resolve, reject) => {
158
+ execFile(
159
+ "/bin/sh",
160
+ ["-c", command],
161
+ { cwd: folder, env, timeout: 60_000, maxBuffer: 16 * 1024 * 1024 },
162
+ (error, stdout, stderr) => {
163
+ for (const line of stderr.split("\n"))
164
+ if (line.trim()) log(`prestart: ${line}`);
165
+ if (error)
166
+ return reject(
167
+ new Error(`prestart failed: ${error.message.split("\n")[0]}`),
168
+ );
169
+ if (!stdout.trim()) return resolve({ env: {}, args: [] });
170
+ let parsed: unknown;
171
+ try {
172
+ parsed = JSON.parse(stdout);
173
+ } catch {
174
+ return reject(
175
+ new Error(
176
+ "prestart printed something other than JSON { env?, args? }",
177
+ ),
178
+ );
179
+ }
180
+ const {
181
+ env: more = {},
182
+ args = [],
183
+ ...rest
184
+ } = (parsed ?? {}) as { env?: unknown; args?: unknown };
185
+ if (
186
+ typeof parsed !== "object" ||
187
+ Object.keys(rest).length > 0 ||
188
+ typeof more !== "object" ||
189
+ more === null ||
190
+ Object.values(more).some((v) => typeof v !== "string") ||
191
+ !Array.isArray(args) ||
192
+ args.some((a) => typeof a !== "string")
193
+ )
194
+ return reject(
195
+ new Error(
196
+ "prestart's JSON must be { env?: { NAME: string }, args?: string[] }",
197
+ ),
198
+ );
199
+ // harnessd finds the conversation before prestart runs, so where Claude Code keeps it comes from config.json
200
+ if ("CLAUDE_CONFIG_DIR" in more)
201
+ return reject(
202
+ new Error(
203
+ "prestart can't set CLAUDE_CONFIG_DIR; set it in config.json's env",
204
+ ),
205
+ );
206
+ resolve({
207
+ env: more as Record<string, string>,
208
+ args: args as string[],
209
+ });
210
+ },
211
+ );
212
+ });
213
+
214
+ /** What keeps harnessd's channels out of Claude Code on this Mac: its managed settings must let `harnessd@inline` in. */
215
+ export const channelBlockers = (file = MANAGED_SETTINGS): string[] => {
216
+ let settings: { channelsEnabled?: unknown; allowedChannelPlugins?: unknown } =
217
+ {};
218
+ try {
219
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
220
+ if (typeof parsed === "object" && parsed !== null) settings = parsed;
221
+ } catch {}
222
+ const listed =
223
+ Array.isArray(settings.allowedChannelPlugins) &&
224
+ settings.allowedChannelPlugins.some(
225
+ (entry: unknown) =>
226
+ entry === PLUGIN ||
227
+ (typeof entry === "object" &&
228
+ entry !== null &&
229
+ (entry as { plugin?: unknown }).plugin === "harnessd" &&
230
+ (entry as { marketplace?: unknown }).marketplace === "inline"),
231
+ );
232
+ return [
233
+ ...(settings.channelsEnabled === true
234
+ ? []
235
+ : [`${file} doesn't set channelsEnabled: true`]),
236
+ ...(listed
237
+ ? []
238
+ : [`${file} doesn't list ${PLUGIN} in allowedChannelPlugins`]),
239
+ ];
240
+ };
241
+
242
+ /** The managed settings with harnessd's channel let in; a list that wasn't there starts with Anthropic's own channels. */
243
+ export const allowChannel = (
244
+ file = MANAGED_SETTINGS,
245
+ ): Record<string, unknown> => {
246
+ // only a missing file starts from nothing: anything else there is policy to keep
247
+ const settings: Record<string, unknown> = existsSync(file)
248
+ ? JSON.parse(readFileSync(file, "utf8"))
249
+ : {};
250
+ if (
251
+ typeof settings !== "object" ||
252
+ settings === null ||
253
+ Array.isArray(settings)
254
+ )
255
+ throw new Error(
256
+ `${file} isn't a JSON object; harnessd won't write over it`,
257
+ );
258
+ const list = Array.isArray(settings.allowedChannelPlugins)
259
+ ? settings.allowedChannelPlugins
260
+ : ["telegram", "discord", "imessage", "fakechat"].map((plugin) => ({
261
+ marketplace: "claude-plugins-official",
262
+ plugin,
263
+ }));
264
+ return {
265
+ ...settings,
266
+ channelsEnabled: true,
267
+ allowedChannelPlugins: [
268
+ ...list.filter(
269
+ (entry) => !(typeof entry === "object" && entry?.plugin === "harnessd"),
270
+ ),
271
+ { marketplace: "inline", plugin: "harnessd" },
272
+ ],
273
+ };
274
+ };
package/src/cli.ts ADDED
@@ -0,0 +1,372 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
3
+ import { createConnection } from "node:net";
4
+ import { createInterface } from "node:readline";
5
+ 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";
13
+ import { ask, runDaemon, type Daemon } from "./daemon";
14
+ import { load, plistOf, stableNode, unload } from "./launchd";
15
+ import { logTo } from "./log";
16
+
17
+ const USAGE = `harnessd keeps Claude Code running on this Mac, connected to the events of your agentic apps.
18
+
19
+ usage: harnessd <command>
20
+
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
29
+
30
+ Settings: ~/.harnessd/config.json (HARNESSD_HOME moves the folder).`;
31
+
32
+ const DETACH = "\x1c";
33
+
34
+ type Io = { out: (line: string) => void; err: (line: string) => void };
35
+
36
+ const notRunning = (paths: Harnessd.Paths) =>
37
+ `harnessd isn't running in ${paths.home}: harnessd install starts it.`;
38
+
39
+ const command = async (
40
+ paths: Harnessd.Paths,
41
+ request: Daemon.Request,
42
+ io: Io,
43
+ ) => {
44
+ const answer = await ask(paths.socket, request);
45
+ if (!answer) {
46
+ io.err(notRunning(paths));
47
+ return 1;
48
+ }
49
+ io[answer.ok ? "out" : "err"](String(answer.message));
50
+ return answer.ok ? 0 : 1;
51
+ };
52
+
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),
60
+ );
61
+ lines.close();
62
+ return /^y(es)?$/i.test(answer.trim());
63
+ };
64
+
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).");
68
+ if (bin.includes("/_npx/"))
69
+ throw new Error(
70
+ "Install harnessd first, so launchd has a lasting copy to start: npm install -g @harness-sdk/harnessd",
71
+ );
72
+ const claude = which("claude");
73
+ const version = spawnSync(claude, ["--version"], {
74
+ encoding: "utf8",
75
+ timeout: 30_000,
76
+ });
77
+ if (version.status !== 0)
78
+ throw new Error(
79
+ `${claude} --version failed: ${(version.stderr || version.stdout || "").trim()}`,
80
+ );
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) {
90
+ io.out(
91
+ `Claude Code lets a channel in only when this Mac's managed settings list it:\n ${blockers.join("\n ")}`,
92
+ );
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
+ );
119
+ }
120
+
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
+ );
129
+ io.out(
130
+ [
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",
133
+ " 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.",
135
+ ].join("\n"),
136
+ );
137
+ return 0;
138
+ };
139
+
140
+ const ago = (iso: string) => {
141
+ const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1000));
142
+ return s < 120
143
+ ? `${s}s`
144
+ : s < 7200
145
+ ? `${Math.round(s / 60)}m`
146
+ : s < 172_800
147
+ ? `${Math.round(s / 3600)}h`
148
+ : `${Math.round(s / 86_400)}d`;
149
+ };
150
+
151
+ /** Each channel as of the Claude Code that runs now: what an earlier run heard says nothing about this one. */
152
+ const channelReport = (
153
+ paths: Harnessd.Paths,
154
+ config: Harnessd.Config | undefined,
155
+ running: Daemon.Status | undefined,
156
+ blockers: string[],
157
+ ) =>
158
+ 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
+ }),
185
+ );
186
+
187
+ 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;
191
+ let config: Harnessd.Config | undefined;
192
+ let configError: string | undefined;
193
+ try {
194
+ config = readConfig(paths);
195
+ } catch (error) {
196
+ configError = error instanceof Error ? error.message : String(error);
197
+ }
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;
202
+ if (json) {
203
+ io.out(
204
+ JSON.stringify({
205
+ running: !!s,
206
+ home: paths.home,
207
+ ...(s && { status: s }),
208
+ ...(configError && { configError }),
209
+ channels,
210
+ }),
211
+ );
212
+ return s ? 0 : 1;
213
+ }
214
+ if (!s) io.out(notRunning(paths));
215
+ else {
216
+ const since = s.startedAt ? ` for ${ago(s.startedAt)}` : "";
217
+ const what =
218
+ s.state === "running"
219
+ ? `Claude Code running${since} (pid ${s.pid})`
220
+ : s.state === "waiting"
221
+ ? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1000))}s` : ""}`
222
+ : s.state === "stopped"
223
+ ? "Claude Code stopped (harnessd start starts it)"
224
+ : "Claude Code starting";
225
+ io.out(`harnessd ${s.daemonPid}: ${what}`);
226
+ if (s.sessionId)
227
+ io.out(`conversation ${s.sessionId}${s.folder ? ` in ${s.folder}` : ""}`);
228
+ if (s.restarts > 0 || s.lastExit)
229
+ io.out(
230
+ `restarts ${s.restarts}${s.lastExit ? `, last exit code ${s.lastExit.code} ${ago(s.lastExit.at)} ago` : ""}`,
231
+ );
232
+ }
233
+ 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
+ )
240
+ io.out(
241
+ `channels are blocked: ${blockers.join("; ")} (harnessd install lets them in)`,
242
+ );
243
+ return s ? 0 : 1;
244
+ };
245
+
246
+ const attach = (paths: Harnessd.Paths, io: Io) =>
247
+ new Promise<number>((resolve) => {
248
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
249
+ io.err("harnessd attach needs a terminal.");
250
+ return resolve(1);
251
+ }
252
+ const connection = createConnection(paths.socket);
253
+ const send = (value: unknown) =>
254
+ connection.write(`${JSON.stringify(value)}\n`);
255
+ const onResize = () =>
256
+ send({
257
+ resize: { cols: process.stdout.columns, rows: process.stdout.rows },
258
+ });
259
+ const onInput = (data: Buffer) => {
260
+ const text = data.toString("utf8");
261
+ if (text.includes(DETACH)) connection.end();
262
+ else send({ input: text });
263
+ };
264
+ let done = false;
265
+ const finish = (code: number, line?: string) => {
266
+ if (done) return;
267
+ done = true;
268
+ process.stdin.setRawMode(false);
269
+ process.stdin.off("data", onInput);
270
+ process.stdin.pause();
271
+ process.stdout.off("resize", onResize);
272
+ process.stdout.write("\x1b[0m\r\n");
273
+ if (line) io.err(line);
274
+ resolve(code);
275
+ };
276
+ connection.once("error", () => finish(1, notRunning(paths)));
277
+ connection.once("connect", () => {
278
+ send({
279
+ command: "attach",
280
+ cols: process.stdout.columns,
281
+ rows: process.stdout.rows,
282
+ });
283
+ process.stdin.setRawMode(true);
284
+ process.stdin.resume();
285
+ process.stdin.on("data", onInput);
286
+ 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
+ });
294
+ });
295
+ connection.once("close", () =>
296
+ finish(0, "Detached; Claude Code keeps running."),
297
+ );
298
+ });
299
+
300
+ /** Runs one harnessd command; resolves to the exit code. */
301
+ export const runHarnessd = async (
302
+ argv: readonly string[],
303
+ bin: string,
304
+ io: Io = {
305
+ out: (line) => void process.stdout.write(`${line}\n`),
306
+ err: (line) => void process.stderr.write(`${line}\n`),
307
+ },
308
+ ): Promise<number> => {
309
+ const paths = pathsOf();
310
+ 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.",
320
+ );
321
+ return 0;
322
+ }
323
+ case "status":
324
+ return status(paths, rest.includes("--json"), io);
325
+ case "start":
326
+ case "stop":
327
+ 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
+ case "attach":
335
+ 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
+ case "run":
348
+ await runDaemon(paths, bin);
349
+ 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}`);
354
+ await serveChannel({
355
+ name,
356
+ channel,
357
+ paths,
358
+ log: logTo(paths.log, `channel ${name}: `),
359
+ });
360
+ return 0;
361
+ }
362
+ case undefined:
363
+ case "help":
364
+ case "--help":
365
+ case "-h":
366
+ io.out(USAGE);
367
+ return first === undefined ? 1 : 0;
368
+ default:
369
+ io.err(`Unknown command ${first}.\n\n${USAGE}`);
370
+ return 2;
371
+ }
372
+ };