@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.
Files changed (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +64 -2
  3. package/dist/accounts.d.ts +66 -0
  4. package/dist/accounts.d.ts.map +1 -0
  5. package/dist/accounts.js +166 -0
  6. package/dist/accounts.js.map +1 -0
  7. package/dist/bin.d.ts +3 -0
  8. package/dist/bin.d.ts.map +1 -0
  9. package/dist/bin.js +19 -0
  10. package/dist/bin.js.map +1 -0
  11. package/dist/channel.d.ts +56 -0
  12. package/dist/channel.d.ts.map +1 -0
  13. package/dist/channel.js +356 -0
  14. package/dist/channel.js.map +1 -0
  15. package/dist/claude.d.ts +41 -0
  16. package/dist/claude.d.ts.map +1 -0
  17. package/dist/claude.js +152 -0
  18. package/dist/claude.js.map +1 -0
  19. package/dist/cli.d.ts +13 -0
  20. package/dist/cli.d.ts.map +1 -0
  21. package/dist/cli.js +413 -0
  22. package/dist/cli.js.map +1 -0
  23. package/dist/config.d.ts +56 -0
  24. package/dist/config.d.ts.map +1 -0
  25. package/dist/config.js +161 -0
  26. package/dist/config.js.map +1 -0
  27. package/dist/daemon.d.ts +37 -0
  28. package/dist/daemon.d.ts.map +1 -0
  29. package/dist/daemon.js +300 -0
  30. package/dist/daemon.js.map +1 -0
  31. package/dist/launchd.d.ts +18 -0
  32. package/dist/launchd.d.ts.map +1 -0
  33. package/dist/launchd.js +91 -0
  34. package/dist/launchd.js.map +1 -0
  35. package/dist/log.d.ts +3 -0
  36. package/dist/log.d.ts.map +1 -0
  37. package/dist/log.js +17 -0
  38. package/dist/log.js.map +1 -0
  39. package/dist/prompts.d.ts +53 -0
  40. package/dist/prompts.d.ts.map +1 -0
  41. package/dist/prompts.js +171 -0
  42. package/dist/prompts.js.map +1 -0
  43. package/dist/service.d.ts +37 -0
  44. package/dist/service.d.ts.map +1 -0
  45. package/dist/service.js +71 -0
  46. package/dist/service.js.map +1 -0
  47. package/dist/setup.d.ts +37 -0
  48. package/dist/setup.d.ts.map +1 -0
  49. package/dist/setup.js +121 -0
  50. package/dist/setup.js.map +1 -0
  51. package/dist/system.d.ts +6 -0
  52. package/dist/system.d.ts.map +1 -0
  53. package/dist/system.js +16 -0
  54. package/dist/system.js.map +1 -0
  55. package/dist/systemd.d.ts +14 -0
  56. package/dist/systemd.d.ts.map +1 -0
  57. package/dist/systemd.js +62 -0
  58. package/dist/systemd.js.map +1 -0
  59. package/dist/terminal.d.ts +11 -0
  60. package/dist/terminal.d.ts.map +1 -0
  61. package/dist/terminal.js +36 -0
  62. package/dist/terminal.js.map +1 -0
  63. package/dist/watchdog.d.ts +83 -0
  64. package/dist/watchdog.d.ts.map +1 -0
  65. package/dist/watchdog.js +236 -0
  66. package/dist/watchdog.js.map +1 -0
  67. package/package.json +55 -6
  68. package/src/accounts.ts +242 -0
  69. package/src/bin.ts +24 -0
  70. package/src/channel.ts +461 -0
  71. package/src/claude.ts +249 -0
  72. package/src/cli.ts +633 -0
  73. package/src/config.ts +281 -0
  74. package/src/daemon.ts +379 -0
  75. package/src/launchd.ts +131 -0
  76. package/src/log.ts +17 -0
  77. package/src/prompts.ts +255 -0
  78. package/src/service.ts +145 -0
  79. package/src/setup.ts +188 -0
  80. package/src/system.ts +11 -0
  81. package/src/systemd.ts +78 -0
  82. package/src/terminal.ts +33 -0
  83. package/src/watchdog.ts +318 -0
package/src/channel.ts ADDED
@@ -0,0 +1,461 @@
1
+ import {
2
+ closeSync,
3
+ mkdirSync,
4
+ openSync,
5
+ readFileSync,
6
+ readSync,
7
+ renameSync,
8
+ statSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import { randomBytes } from "node:crypto";
12
+ import { dirname, join } from "node:path";
13
+ import { createInterface } from "node:readline";
14
+ import { runCli } from "toolport/cli";
15
+ import { handleMcpMessage } from "toolport/mcp";
16
+ import { fromMcpServer, type McpToolkit } from "toolport/mcp-client";
17
+ import { findTranscript } from "./claude";
18
+ import { headersOf, type Harnessd } from "./config";
19
+
20
+ export namespace Channel {
21
+ /** What a channel keeps in harnessd's home: where its events resume, and whether Claude Code hears them. */
22
+ export type Status = {
23
+ readonly cursor?: string;
24
+ /** When this Claude Code process got its first event. */
25
+ readonly pushedAt?: string;
26
+ /** When one of its events first showed up in the conversation's transcript. */
27
+ readonly heardAt?: string;
28
+ };
29
+
30
+ export type Options = {
31
+ readonly name: string;
32
+ readonly channel: Harnessd.Channel;
33
+ readonly paths: Harnessd.Paths;
34
+ readonly send: (message: Record<string, unknown>) => void;
35
+ readonly log: (line: string) => void;
36
+ readonly env?: NodeJS.ProcessEnv;
37
+ readonly fetch?: typeof fetch;
38
+ readonly startMs?: number;
39
+ readonly checkMs?: number;
40
+ };
41
+
42
+ export type Server = {
43
+ readonly handle: (
44
+ request: Request,
45
+ ) => Promise<Record<string, unknown> | undefined>;
46
+ readonly stop: () => Promise<void>;
47
+ };
48
+
49
+ export type Request = {
50
+ jsonrpc: "2.0";
51
+ id?: string | number;
52
+ method: string;
53
+ params?: Record<string, unknown>;
54
+ };
55
+ }
56
+
57
+ const CHANNEL = "notifications/claude/channel";
58
+ // Claude Code registers no channel on 2026-07-28 or later
59
+ const PROTOCOL = "2025-06-18";
60
+ const protocolFor = (asked: unknown) =>
61
+ typeof asked === "string" &&
62
+ /^\d{4}-\d{2}-\d{2}$/.test(asked) &&
63
+ asked < "2026-07-28"
64
+ ? asked
65
+ : PROTOCOL;
66
+ // Claude Code drops what a channel sends before it registers, just after `initialized`
67
+ const START_MS = 1500;
68
+ const CHECK_MS = 5000;
69
+ const CONNECT_WAIT_MS = 5000;
70
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
71
+ const unref = (timer: unknown) => (timer as { unref?: () => void }).unref?.();
72
+
73
+ /** Subscription arguments as toolport's `stream` takes them: kebab-case flags, `--x` and `--no-x` for booleans. */
74
+ export const streamFlags = (
75
+ args: Readonly<Record<string, string | number | boolean>>,
76
+ ) =>
77
+ Object.entries(args).flatMap(([key, value]) => {
78
+ const flag = key
79
+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")
80
+ .replace(/_/g, "-")
81
+ .toLowerCase();
82
+ return typeof value === "boolean"
83
+ ? [value ? `--${flag}` : `--no-${flag}`]
84
+ : [`--${flag}`, String(value)];
85
+ });
86
+
87
+ export const statusFile = (paths: Harnessd.Paths, name: string) =>
88
+ join(paths.channels, `${name}.json`);
89
+
90
+ export const readStatus = (file: string): Channel.Status => {
91
+ try {
92
+ return JSON.parse(readFileSync(file, "utf8")) as Channel.Status;
93
+ } catch {
94
+ return {};
95
+ }
96
+ };
97
+
98
+ const writeStatus = (file: string, status: Channel.Status) => {
99
+ mkdirSync(dirname(file), { recursive: true });
100
+ // replaced whole, so a crash mid-write never loses the cursor
101
+ const temp = `${file}.${process.pid}`;
102
+ writeFileSync(temp, `${JSON.stringify(status)}\n`);
103
+ renameSync(temp, file);
104
+ };
105
+
106
+ /** One event as Claude Code shows it: its `text`, else its data as JSON, with its scalar fields as tag attributes and its delivery id. */
107
+ export const channelMessage = (line: {
108
+ name: string;
109
+ data: unknown;
110
+ gap?: boolean;
111
+ delivery: string;
112
+ }) => {
113
+ if (line.gap)
114
+ return {
115
+ content: `Some ${line.name} events were missed (the server no longer had them): read its state again.`,
116
+ meta: { event: line.name, gap: "true", delivery: line.delivery },
117
+ };
118
+ const data = line.data;
119
+ const meta: Record<string, string> = {};
120
+ if (typeof data === "object" && data !== null && !Array.isArray(data))
121
+ for (const [key, value] of Object.entries(data)) {
122
+ if (key === "text" || key === "source" || !IDENTIFIER.test(key)) continue;
123
+ if (
124
+ typeof value === "string" ||
125
+ typeof value === "number" ||
126
+ typeof value === "boolean"
127
+ )
128
+ meta[key] = String(value).replace(/[<>"]/g, "").slice(0, 200);
129
+ }
130
+ meta.event = line.name;
131
+ meta.delivery = line.delivery;
132
+ const text = (data as { text?: unknown } | null)?.text;
133
+ return {
134
+ content: typeof text === "string" ? text : JSON.stringify(data),
135
+ meta,
136
+ };
137
+ };
138
+
139
+ /** The deliveries of this channel's messages in a transcript's whole lines from byte `from` on, and where those lines end. */
140
+ const deliveriesIn = (file: string, from: number, source: string) => {
141
+ try {
142
+ const buffer = Buffer.alloc(Math.max(0, statSync(file).size - from));
143
+ const fd = openSync(file, "r");
144
+ try {
145
+ readSync(fd, buffer, 0, buffer.length, from);
146
+ } finally {
147
+ closeSync(fd);
148
+ }
149
+ const whole = buffer.lastIndexOf(10) + 1;
150
+ const text = buffer.subarray(0, whole).toString("utf8");
151
+ // in the JSONL the tag's quotes are escaped
152
+ const tag = new RegExp(
153
+ `<channel source=\\\\?"${source.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\\\?"([^>]*)>`,
154
+ "g",
155
+ );
156
+ const found: string[] = [];
157
+ for (const [, attributes] of text.matchAll(tag)) {
158
+ const delivery = /delivery=\\?"([a-f0-9]+\.\d+)\\?"/.exec(attributes!);
159
+ if (delivery) found.push(delivery[1]!);
160
+ }
161
+ return { found, next: from + whole };
162
+ } catch {
163
+ return { found: [], next: from };
164
+ }
165
+ };
166
+
167
+ const sizeOf = (file: string | undefined) => {
168
+ try {
169
+ return file ? statSync(file).size : 0;
170
+ } catch {
171
+ return 0;
172
+ }
173
+ };
174
+
175
+ /**
176
+ * `harnessd channel <name>`: the stdio MCP server Claude Code runs for one channel. It follows the MCP server's push
177
+ * events (`events/stream`) and hands each to Claude Code as a channel message, and it serves that server's tools, so
178
+ * the agent answers there. Where the events resume is saved only once Claude Code is seen to hear them: an event it
179
+ * dropped (a channel it didn't let in) comes again at the next start.
180
+ */
181
+ export const channelServer = (options: Channel.Options): Channel.Server => {
182
+ const env = options.env ?? process.env;
183
+ const source = `plugin:harnessd:${options.name}`;
184
+ const file = statusFile(options.paths, options.name);
185
+ const saved = readStatus(file);
186
+ let status: Channel.Status = saved.cursor ? { cursor: saved.cursor } : {};
187
+ writeStatus(file, status);
188
+ const controller = new AbortController();
189
+ let following: Promise<void> | undefined;
190
+ const transcript = () =>
191
+ env.CLAUDE_CODE_SESSION_ID
192
+ ? findTranscript(env.CLAUDE_CODE_SESSION_ID, env)
193
+ : undefined;
194
+ // a resumed conversation's earlier lines belong to earlier runs
195
+ let from = sizeOf(transcript());
196
+ // a payload can't name a later event's delivery: each run's numbers carry a random prefix
197
+ const nonce = randomBytes(4).toString("hex");
198
+ let delivery = 0;
199
+ let lastCursor = status.cursor;
200
+ const unconfirmed: { delivery: string; cursor: string | undefined }[] = [];
201
+ const heard = new Set<string>();
202
+ let check: ReturnType<typeof setInterval> | undefined;
203
+
204
+ const save = (patch: Channel.Status) => {
205
+ status = { ...status, ...patch };
206
+ writeStatus(file, status);
207
+ };
208
+
209
+ // The cursor moves only through events the transcript shows, in order; Claude Code takes them in the order sent.
210
+ const confirm = () => {
211
+ const at = transcript();
212
+ if (at === undefined) return;
213
+ const read = deliveriesIn(at, from, source);
214
+ from = read.next;
215
+ for (const n of read.found) heard.add(n);
216
+ let cursor: string | undefined;
217
+ while (unconfirmed.length > 0 && heard.has(unconfirmed[0]!.delivery)) {
218
+ const event = unconfirmed.shift()!;
219
+ heard.delete(event.delivery);
220
+ cursor = event.cursor ?? cursor;
221
+ if (!status.heardAt) {
222
+ save({ heardAt: new Date().toISOString() });
223
+ options.log(`Claude Code hears ${options.name}'s events`);
224
+ }
225
+ }
226
+ if (cursor !== undefined) save({ cursor });
227
+ };
228
+
229
+ const onLine = (raw: string) => {
230
+ let line: { name?: string; data?: unknown; cursor?: string; gap?: boolean };
231
+ try {
232
+ line = JSON.parse(raw);
233
+ } catch {
234
+ return;
235
+ }
236
+ if (typeof line.name !== "string") return;
237
+ if (!status.pushedAt) save({ pushedAt: new Date().toISOString() });
238
+ if (!check) {
239
+ check = setInterval(confirm, options.checkMs ?? CHECK_MS);
240
+ unref(check);
241
+ }
242
+ const cursor =
243
+ typeof line.cursor === "string" && line.cursor ? line.cursor : undefined;
244
+ if (cursor) lastCursor = cursor;
245
+ const id = `${nonce}.${++delivery}`;
246
+ unconfirmed.push({ delivery: id, cursor });
247
+ options.send({
248
+ jsonrpc: "2.0",
249
+ method: CHANNEL,
250
+ params: channelMessage({
251
+ name: line.name,
252
+ data: line.data ?? null,
253
+ ...(line.gap && { gap: true }),
254
+ delivery: id,
255
+ }),
256
+ });
257
+ };
258
+
259
+ const follow = async () => {
260
+ let backoff = 5000;
261
+ while (!controller.signal.aborted) {
262
+ const startedAt = Date.now();
263
+ let code: number;
264
+ try {
265
+ const cursor = lastCursor;
266
+ code = await runCli(
267
+ {
268
+ name: "harnessd",
269
+ configDir: join(options.paths.home, "auth"),
270
+ servers: {
271
+ [options.name]: {
272
+ url: options.channel.url,
273
+ headers: headersOf(options.channel, env),
274
+ ...(options.fetch && { fetch: options.fetch }),
275
+ },
276
+ },
277
+ },
278
+ {
279
+ argv: [
280
+ "stream",
281
+ ...(cursor ? ["--from", cursor] : []),
282
+ ...streamFlags(options.channel.arguments),
283
+ ],
284
+ stdout: onLine,
285
+ stderr: (line) => options.log(`${options.name}: ${line}`),
286
+ signal: controller.signal,
287
+ },
288
+ );
289
+ } catch (error) {
290
+ code = 1;
291
+ options.log(
292
+ `${options.name}: ${error instanceof Error ? error.message : String(error)}`,
293
+ );
294
+ }
295
+ if (controller.signal.aborted) return;
296
+ if (Date.now() - startedAt > 10 * 60_000) backoff = 5000;
297
+ options.log(
298
+ `${options.name}: the event stream ended (exit ${code}); following again in ${Math.round(backoff / 1000)}s`,
299
+ );
300
+ await new Promise<void>((resolve) => {
301
+ const timer = setTimeout(resolve, backoff);
302
+ controller.signal.addEventListener(
303
+ "abort",
304
+ () => (clearTimeout(timer), resolve()),
305
+ { once: true },
306
+ );
307
+ });
308
+ backoff = Math.min(backoff * 2, 5 * 60_000);
309
+ }
310
+ };
311
+
312
+ let toolkit: Promise<McpToolkit> | undefined;
313
+ let announced = false;
314
+ const connect = () =>
315
+ (toolkit ??= fromMcpServer({
316
+ url: options.channel.url,
317
+ headers: () => headersOf(options.channel, env),
318
+ ...(options.fetch && { fetch: options.fetch }),
319
+ name: options.name,
320
+ }).catch((error: unknown) => {
321
+ toolkit = undefined;
322
+ throw error;
323
+ }));
324
+ const withTimeout = <T>(promise: Promise<T>, ms: number) =>
325
+ Promise.race([
326
+ promise,
327
+ new Promise<undefined>((resolve) => unref(setTimeout(resolve, ms))),
328
+ ]).catch(() => undefined);
329
+ // The server was down when Claude Code asked for the tools: list them once it's back.
330
+ const retryTools = async () => {
331
+ let wait = 5000;
332
+ while (!controller.signal.aborted) {
333
+ await new Promise((resolve) => unref(setTimeout(resolve, wait)));
334
+ try {
335
+ await connect();
336
+ if (!announced) {
337
+ announced = true;
338
+ options.send({
339
+ jsonrpc: "2.0",
340
+ method: "notifications/tools/list_changed",
341
+ });
342
+ }
343
+ return;
344
+ } catch {
345
+ wait = Math.min(wait * 2, 5 * 60_000);
346
+ }
347
+ }
348
+ };
349
+
350
+ const instructions = (upstream: string | undefined) =>
351
+ [
352
+ `Events from ${options.name} arrive here for the whole session, one per message: <channel source="${source}" event="…" …>the event</channel>. Act on each.`,
353
+ `To answer or act on ${options.name}, use this server's tools: they are ${options.name}'s own.`,
354
+ ...(upstream ? [`${options.name} says: ${upstream}`] : []),
355
+ ].join(" ");
356
+
357
+ const handle = async (
358
+ request: Channel.Request,
359
+ ): Promise<Record<string, unknown> | undefined> => {
360
+ const result = (value: unknown) => ({
361
+ jsonrpc: "2.0",
362
+ id: request.id,
363
+ result: value,
364
+ });
365
+ switch (request.method) {
366
+ case "initialize": {
367
+ const kit = await withTimeout(connect(), CONNECT_WAIT_MS);
368
+ return result({
369
+ protocolVersion: protocolFor(request.params?.protocolVersion),
370
+ capabilities: {
371
+ experimental: { "claude/channel": {} },
372
+ tools: { listChanged: true },
373
+ },
374
+ serverInfo: { name: `harnessd-${options.name}`, version: "1.0.0" },
375
+ instructions: instructions(kit?.description),
376
+ });
377
+ }
378
+ case "notifications/initialized":
379
+ unref(
380
+ setTimeout(() => {
381
+ if (!controller.signal.aborted) following ??= follow();
382
+ }, options.startMs ?? START_MS),
383
+ );
384
+ return undefined;
385
+ case "tools/list":
386
+ case "tools/call": {
387
+ let kit: McpToolkit;
388
+ try {
389
+ kit = await connect();
390
+ } catch (error) {
391
+ options.log(
392
+ `${options.name}: couldn't reach its tools: ${error instanceof Error ? error.message : String(error)}`,
393
+ );
394
+ if (request.method === "tools/list") {
395
+ void retryTools();
396
+ return result({ tools: [] });
397
+ }
398
+ return result({
399
+ content: [
400
+ {
401
+ type: "text",
402
+ text: `${options.name} can't be reached right now.`,
403
+ },
404
+ ],
405
+ isError: true,
406
+ });
407
+ }
408
+ announced = true;
409
+ return (await handleMcpMessage(kit, request)) ?? undefined;
410
+ }
411
+ case "ping":
412
+ return result({});
413
+ default:
414
+ if (request.id === undefined) return undefined;
415
+ return {
416
+ jsonrpc: "2.0",
417
+ id: request.id,
418
+ error: {
419
+ code: -32601,
420
+ message: `Method not found: ${request.method}`,
421
+ },
422
+ };
423
+ }
424
+ };
425
+
426
+ return {
427
+ handle,
428
+ stop: async () => {
429
+ controller.abort();
430
+ clearInterval(check);
431
+ await following;
432
+ await (await toolkit?.catch(() => undefined))?.close();
433
+ },
434
+ };
435
+ };
436
+
437
+ /** Serves one channel on stdin and stdout until Claude Code closes stdin. */
438
+ export const serveChannel = async (options: Omit<Channel.Options, "send">) => {
439
+ const write = (message: unknown) =>
440
+ void process.stdout.write(`${JSON.stringify(message)}\n`);
441
+ const server = channelServer({ ...options, send: write });
442
+ const end = () => void server.stop().finally(() => process.exit(0));
443
+ process.once("SIGTERM", end);
444
+ process.once("SIGINT", end);
445
+ for await (const line of createInterface({ input: process.stdin })) {
446
+ if (!line.trim()) continue;
447
+ let request: Channel.Request;
448
+ try {
449
+ request = JSON.parse(line);
450
+ } catch {
451
+ write({
452
+ jsonrpc: "2.0",
453
+ id: null,
454
+ error: { code: -32700, message: "Parse error" },
455
+ });
456
+ continue;
457
+ }
458
+ void server.handle(request).then((response) => response && write(response));
459
+ }
460
+ await server.stop();
461
+ };
package/src/claude.ts ADDED
@@ -0,0 +1,249 @@
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. */
21
+ export const PLUGIN = "harnessd@inline";
22
+
23
+ const claudeDir = (env: NodeJS.ProcessEnv) =>
24
+ env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
25
+
26
+ /**
27
+ * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
28
+ * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field
29
+ * changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.
30
+ */
31
+ export const trustFolder = (
32
+ folder: string,
33
+ env: NodeJS.ProcessEnv = process.env,
34
+ ): boolean => {
35
+ const file = env.CLAUDE_CONFIG_DIR
36
+ ? join(env.CLAUDE_CONFIG_DIR, ".claude.json")
37
+ : join(homedir(), ".claude.json");
38
+ if (!existsSync(file)) return false;
39
+ const text = readFileSync(file, "utf8");
40
+ const config = JSON.parse(text) as {
41
+ projects?: Record<string, { hasTrustDialogAccepted?: boolean }>;
42
+ };
43
+ const key = realpathSync(folder);
44
+ if (config.projects?.[key]?.hasTrustDialogAccepted === true) return true;
45
+ config.projects = {
46
+ ...config.projects,
47
+ [key]: { ...config.projects?.[key], hasTrustDialogAccepted: true },
48
+ };
49
+ const pretty = text.trimEnd() === JSON.stringify(JSON.parse(text), null, 2);
50
+ const written = `${pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)}${text.endsWith("\n") ? "\n" : ""}`;
51
+ const temp = `${file}.harnessd-${process.pid}`;
52
+ writeFileSync(temp, written, { mode: statSync(file).mode & 0o777 });
53
+ renameSync(temp, file);
54
+ return true;
55
+ };
56
+
57
+ /** A conversation's transcript, wherever Claude Code put it. */
58
+ export const findTranscript = (
59
+ sessionId: string,
60
+ env: NodeJS.ProcessEnv = process.env,
61
+ ): string | undefined => {
62
+ const projects = join(claudeDir(env), "projects");
63
+ try {
64
+ for (const dir of readdirSync(projects)) {
65
+ const file = join(projects, dir, `${sessionId}.jsonl`);
66
+ if (existsSync(file)) return file;
67
+ }
68
+ } catch {}
69
+ return undefined;
70
+ };
71
+
72
+ /** The first `name` on `path` that can run. */
73
+ export const which = (name: string, path = process.env.PATH ?? "") => {
74
+ if (name.includes("/")) return name;
75
+ for (const dir of path.split(delimiter)) {
76
+ if (!dir) continue;
77
+ try {
78
+ accessSync(join(dir, name), constants.X_OK);
79
+ return join(dir, name);
80
+ } catch {}
81
+ }
82
+ throw new Error(
83
+ `${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`,
84
+ );
85
+ };
86
+
87
+ const shellQuote = (text: string) => `'${text.replaceAll("'", "'\\''")}'`;
88
+
89
+ /**
90
+ * harnessd's plugin, written before each start: one MCP server per channel of the config, each
91
+ * `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a
92
+ * /clear or a /resume is the conversation the next start resumes.
93
+ */
94
+ export const writePlugin = (
95
+ paths: Harnessd.Paths,
96
+ config: Harnessd.Config,
97
+ bin: string,
98
+ ) => {
99
+ rmSync(paths.plugin, { recursive: true, force: true });
100
+ mkdirSync(join(paths.plugin, ".claude-plugin"), { recursive: true });
101
+ const names = Object.keys(config.channels);
102
+ const sessionStart = [
103
+ ...Object.entries(paths.env).map(
104
+ ([name, value]) => `${name}=${shellQuote(value)}`,
105
+ ),
106
+ shellQuote(process.execPath),
107
+ shellQuote(bin),
108
+ "session-start",
109
+ ].join(" ");
110
+ const manifest = {
111
+ name: "harnessd",
112
+ version: "1.0.0",
113
+ description:
114
+ "harnessd's channels, each one's events and tools, and its SessionStart hook",
115
+ ...(names.length > 0 && {
116
+ mcpServers: Object.fromEntries(
117
+ names.map((name) => [
118
+ name,
119
+ {
120
+ command: process.execPath,
121
+ args: [bin, "channel", name],
122
+ env: paths.env,
123
+ },
124
+ ]),
125
+ ),
126
+ channels: names.map((name) => ({ server: name, displayName: name })),
127
+ }),
128
+ hooks: {
129
+ SessionStart: [{ hooks: [{ type: "command", command: sessionStart }] }],
130
+ },
131
+ };
132
+ writeFileSync(
133
+ join(paths.plugin, ".claude-plugin", "plugin.json"),
134
+ `${JSON.stringify(manifest, null, 2)}\n`,
135
+ );
136
+ };
137
+
138
+ /** Whether these claude arguments pick a permission mode themselves. */
139
+ const picksPermissionMode = (args: readonly string[]) =>
140
+ args.some(
141
+ (arg) =>
142
+ arg === "--dangerously-skip-permissions" ||
143
+ arg === "--permission-mode" ||
144
+ arg.startsWith("--permission-mode="),
145
+ );
146
+
147
+ /** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */
148
+ export const skipsPermissions = (args: readonly string[]) =>
149
+ args.some(
150
+ (arg, i) =>
151
+ arg === "--dangerously-skip-permissions" ||
152
+ arg === "--permission-mode=bypassPermissions" ||
153
+ (arg === "bypassPermissions" && args[i - 1] === "--permission-mode"),
154
+ );
155
+
156
+ /**
157
+ * The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
158
+ * decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
159
+ * its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
160
+ * Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
161
+ */
162
+ export const claudeArgs = (o: {
163
+ start: Watchdog.Start;
164
+ plugin: string;
165
+ config: Harnessd.Config;
166
+ extra: readonly string[];
167
+ }) => [
168
+ ...(picksPermissionMode([...o.config.args, ...o.extra])
169
+ ? []
170
+ : ["--permission-mode", "auto"]),
171
+ "--plugin-dir",
172
+ o.plugin,
173
+ ...(Object.keys(o.config.channels).length > 0
174
+ ? ["--dangerously-load-development-channels", `plugin:${PLUGIN}`]
175
+ : []),
176
+ ...(o.start.resume
177
+ ? ["--resume", o.start.sessionId]
178
+ : ["--session-id", o.start.sessionId]),
179
+ // before the config's arguments: after a list flag (--add-dir…) claude would take it as one more value
180
+ ...(o.start.prompt ? [o.start.prompt] : []),
181
+ ...o.config.args,
182
+ ...o.extra,
183
+ ];
184
+
185
+ export type Prestart = { env: Record<string, string>; args: string[] };
186
+
187
+ /** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */
188
+ export const prestart = (
189
+ command: string,
190
+ folder: string,
191
+ env: NodeJS.ProcessEnv,
192
+ log: (line: string) => void,
193
+ ) =>
194
+ new Promise<Prestart>((resolve, reject) => {
195
+ execFile(
196
+ "/bin/sh",
197
+ ["-c", command],
198
+ { cwd: folder, env, timeout: 60_000, maxBuffer: 16 * 1024 * 1024 },
199
+ (error, stdout, stderr) => {
200
+ for (const line of stderr.split("\n"))
201
+ if (line.trim()) log(`prestart: ${line}`);
202
+ if (error)
203
+ return reject(
204
+ new Error(`prestart failed: ${error.message.split("\n")[0]}`),
205
+ );
206
+ if (!stdout.trim()) return resolve({ env: {}, args: [] });
207
+ let parsed: unknown;
208
+ try {
209
+ parsed = JSON.parse(stdout);
210
+ } catch {
211
+ return reject(
212
+ new Error(
213
+ "prestart printed something other than JSON { env?, args? }",
214
+ ),
215
+ );
216
+ }
217
+ const {
218
+ env: more = {},
219
+ args = [],
220
+ ...rest
221
+ } = (parsed ?? {}) as { env?: unknown; args?: unknown };
222
+ if (
223
+ typeof parsed !== "object" ||
224
+ Object.keys(rest).length > 0 ||
225
+ typeof more !== "object" ||
226
+ more === null ||
227
+ Object.values(more).some((v) => typeof v !== "string") ||
228
+ !Array.isArray(args) ||
229
+ args.some((a) => typeof a !== "string")
230
+ )
231
+ return reject(
232
+ new Error(
233
+ "prestart's JSON must be { env?: { NAME: string }, args?: string[] }",
234
+ ),
235
+ );
236
+ // harnessd finds the conversation before prestart runs, so where Claude Code keeps it comes from config.json
237
+ if ("CLAUDE_CONFIG_DIR" in more)
238
+ return reject(
239
+ new Error(
240
+ "prestart can't set CLAUDE_CONFIG_DIR; set it in config.json's env",
241
+ ),
242
+ );
243
+ resolve({
244
+ env: more as Record<string, string>,
245
+ args: args as string[],
246
+ });
247
+ },
248
+ );
249
+ });