@harness-sdk/harnessd 0.0.2 → 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.
- package/README.md +20 -8
- package/dist/channel.d.ts +15 -10
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +112 -157
- package/dist/channel.js.map +1 -1
- package/dist/claude.d.ts +9 -4
- package/dist/claude.d.ts.map +1 -1
- package/dist/claude.js +53 -29
- package/dist/claude.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +58 -27
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +33 -10
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +94 -43
- package/dist/config.js.map +1 -1
- package/dist/daemon.d.ts +12 -0
- package/dist/daemon.d.ts.map +1 -1
- package/dist/daemon.js +66 -4
- package/dist/daemon.js.map +1 -1
- package/package.json +4 -10
- package/src/channel.ts +151 -172
- package/src/claude.ts +55 -28
- package/src/cli.ts +98 -48
- package/src/config.ts +155 -57
- package/src/daemon.ts +86 -3
package/dist/channel.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel.js","names":[],"sources":["../src/channel.ts"],"sourcesContent":["import {\n closeSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n renameSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport { dirname, join } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { runCli } from \"toolport/cli\";\nimport { handleMcpMessage } from \"toolport/mcp\";\nimport { fromMcpServer, type McpToolkit } from \"toolport/mcp-client\";\nimport { findTranscript } from \"./claude\";\nimport { headersOf, type Harnessd } from \"./config\";\n\nexport namespace Channel {\n /** What a channel keeps in harnessd's home: where its events resume, and whether Claude Code hears them. */\n export type Status = {\n readonly cursor?: string;\n /** When this Claude Code process got its first event. */\n readonly pushedAt?: string;\n /** When one of its events first showed up in the conversation's transcript. */\n readonly heardAt?: string;\n };\n\n export type Options = {\n readonly name: string;\n readonly channel: Harnessd.Channel;\n readonly paths: Harnessd.Paths;\n readonly send: (message: Record<string, unknown>) => void;\n readonly log: (line: string) => void;\n readonly env?: NodeJS.ProcessEnv;\n readonly fetch?: typeof fetch;\n readonly startMs?: number;\n readonly checkMs?: number;\n };\n\n export type Server = {\n readonly handle: (\n request: Request,\n ) => Promise<Record<string, unknown> | undefined>;\n readonly stop: () => Promise<void>;\n };\n\n export type Request = {\n jsonrpc: \"2.0\";\n id?: string | number;\n method: string;\n params?: Record<string, unknown>;\n };\n}\n\nconst CHANNEL = \"notifications/claude/channel\";\n// Claude Code registers no channel on 2026-07-28 or later\nconst PROTOCOL = \"2025-06-18\";\nconst protocolFor = (asked: unknown) =>\n typeof asked === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}$/.test(asked) &&\n asked < \"2026-07-28\"\n ? asked\n : PROTOCOL;\n// Claude Code drops what a channel sends before it registers, just after `initialized`\nconst START_MS = 1500;\nconst CHECK_MS = 5000;\nconst CONNECT_WAIT_MS = 5000;\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst unref = (timer: unknown) => (timer as { unref?: () => void }).unref?.();\n\n/** Subscription arguments as toolport's `stream` takes them: kebab-case flags, `--x` and `--no-x` for booleans. */\nexport const streamFlags = (\n args: Readonly<Record<string, string | number | boolean>>,\n) =>\n Object.entries(args).flatMap(([key, value]) => {\n const flag = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/_/g, \"-\")\n .toLowerCase();\n return typeof value === \"boolean\"\n ? [value ? `--${flag}` : `--no-${flag}`]\n : [`--${flag}`, String(value)];\n });\n\nexport const statusFile = (paths: Harnessd.Paths, name: string) =>\n join(paths.channels, `${name}.json`);\n\nexport const readStatus = (file: string): Channel.Status => {\n try {\n return JSON.parse(readFileSync(file, \"utf8\")) as Channel.Status;\n } catch {\n return {};\n }\n};\n\nconst writeStatus = (file: string, status: Channel.Status) => {\n mkdirSync(dirname(file), { recursive: true });\n // replaced whole, so a crash mid-write never loses the cursor\n const temp = `${file}.${process.pid}`;\n writeFileSync(temp, `${JSON.stringify(status)}\\n`);\n renameSync(temp, file);\n};\n\n/** 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. */\nexport const channelMessage = (line: {\n name: string;\n data: unknown;\n gap?: boolean;\n delivery: string;\n}) => {\n if (line.gap)\n return {\n content: `Some ${line.name} events were missed (the server no longer had them): read its state again.`,\n meta: { event: line.name, gap: \"true\", delivery: line.delivery },\n };\n const data = line.data;\n const meta: Record<string, string> = {};\n if (typeof data === \"object\" && data !== null && !Array.isArray(data))\n for (const [key, value] of Object.entries(data)) {\n if (key === \"text\" || key === \"source\" || !IDENTIFIER.test(key)) continue;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n )\n meta[key] = String(value).replace(/[<>\"]/g, \"\").slice(0, 200);\n }\n meta.event = line.name;\n meta.delivery = line.delivery;\n const text = (data as { text?: unknown } | null)?.text;\n return {\n content: typeof text === \"string\" ? text : JSON.stringify(data),\n meta,\n };\n};\n\n/** The deliveries of this channel's messages in a transcript's whole lines from byte `from` on, and where those lines end. */\nconst deliveriesIn = (file: string, from: number, source: string) => {\n try {\n const buffer = Buffer.alloc(Math.max(0, statSync(file).size - from));\n const fd = openSync(file, \"r\");\n try {\n readSync(fd, buffer, 0, buffer.length, from);\n } finally {\n closeSync(fd);\n }\n const whole = buffer.lastIndexOf(10) + 1;\n const text = buffer.subarray(0, whole).toString(\"utf8\");\n // in the JSONL the tag's quotes are escaped\n const tag = new RegExp(\n `<channel source=\\\\\\\\?\"${source.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\\\\\?\"([^>]*)>`,\n \"g\",\n );\n const found: string[] = [];\n for (const [, attributes] of text.matchAll(tag)) {\n const delivery = /delivery=\\\\?\"([a-f0-9]+\\.\\d+)\\\\?\"/.exec(attributes!);\n if (delivery) found.push(delivery[1]!);\n }\n return { found, next: from + whole };\n } catch {\n return { found: [], next: from };\n }\n};\n\nconst sizeOf = (file: string | undefined) => {\n try {\n return file ? statSync(file).size : 0;\n } catch {\n return 0;\n }\n};\n\n/**\n * `harnessd channel <name>`: the stdio MCP server Claude Code runs for one channel. It follows the MCP server's push\n * events (`events/stream`) and hands each to Claude Code as a channel message, and it serves that server's tools, so\n * the agent answers there. Where the events resume is saved only once Claude Code is seen to hear them: an event it\n * dropped (a channel it didn't let in) comes again at the next start.\n */\nexport const channelServer = (options: Channel.Options): Channel.Server => {\n const env = options.env ?? process.env;\n const source = `plugin:harnessd:${options.name}`;\n const file = statusFile(options.paths, options.name);\n const saved = readStatus(file);\n let status: Channel.Status = saved.cursor ? { cursor: saved.cursor } : {};\n writeStatus(file, status);\n const controller = new AbortController();\n let following: Promise<void> | undefined;\n const transcript = () =>\n env.CLAUDE_CODE_SESSION_ID\n ? findTranscript(env.CLAUDE_CODE_SESSION_ID, env)\n : undefined;\n // a resumed conversation's earlier lines belong to earlier runs\n let from = sizeOf(transcript());\n // a payload can't name a later event's delivery: each run's numbers carry a random prefix\n const nonce = randomBytes(4).toString(\"hex\");\n let delivery = 0;\n let lastCursor = status.cursor;\n const unconfirmed: { delivery: string; cursor: string | undefined }[] = [];\n const heard = new Set<string>();\n let check: ReturnType<typeof setInterval> | undefined;\n\n const save = (patch: Channel.Status) => {\n status = { ...status, ...patch };\n writeStatus(file, status);\n };\n\n // The cursor moves only through events the transcript shows, in order; Claude Code takes them in the order sent.\n const confirm = () => {\n const at = transcript();\n if (at === undefined) return;\n const read = deliveriesIn(at, from, source);\n from = read.next;\n for (const n of read.found) heard.add(n);\n let cursor: string | undefined;\n while (unconfirmed.length > 0 && heard.has(unconfirmed[0]!.delivery)) {\n const event = unconfirmed.shift()!;\n heard.delete(event.delivery);\n cursor = event.cursor ?? cursor;\n if (!status.heardAt) {\n save({ heardAt: new Date().toISOString() });\n options.log(`Claude Code hears ${options.name}'s events`);\n }\n }\n if (cursor !== undefined) save({ cursor });\n };\n\n const onLine = (raw: string) => {\n let line: { name?: string; data?: unknown; cursor?: string; gap?: boolean };\n try {\n line = JSON.parse(raw);\n } catch {\n return;\n }\n if (typeof line.name !== \"string\") return;\n if (!status.pushedAt) save({ pushedAt: new Date().toISOString() });\n if (!check) {\n check = setInterval(confirm, options.checkMs ?? CHECK_MS);\n unref(check);\n }\n const cursor =\n typeof line.cursor === \"string\" && line.cursor ? line.cursor : undefined;\n if (cursor) lastCursor = cursor;\n const id = `${nonce}.${++delivery}`;\n unconfirmed.push({ delivery: id, cursor });\n options.send({\n jsonrpc: \"2.0\",\n method: CHANNEL,\n params: channelMessage({\n name: line.name,\n data: line.data ?? null,\n ...(line.gap && { gap: true }),\n delivery: id,\n }),\n });\n };\n\n const follow = async () => {\n let backoff = 5000;\n while (!controller.signal.aborted) {\n const startedAt = Date.now();\n let code: number;\n try {\n const cursor = lastCursor;\n code = await runCli(\n {\n name: \"harnessd\",\n configDir: join(options.paths.home, \"auth\"),\n servers: {\n [options.name]: {\n url: options.channel.url,\n headers: headersOf(options.channel, env),\n ...(options.fetch && { fetch: options.fetch }),\n },\n },\n },\n {\n argv: [\n \"stream\",\n ...(cursor ? [\"--from\", cursor] : []),\n ...streamFlags(options.channel.arguments),\n ],\n stdout: onLine,\n stderr: (line) => options.log(`${options.name}: ${line}`),\n signal: controller.signal,\n },\n );\n } catch (error) {\n code = 1;\n options.log(\n `${options.name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (controller.signal.aborted) return;\n if (Date.now() - startedAt > 10 * 60_000) backoff = 5000;\n options.log(\n `${options.name}: the event stream ended (exit ${code}); following again in ${Math.round(backoff / 1000)}s`,\n );\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, backoff);\n controller.signal.addEventListener(\n \"abort\",\n () => (clearTimeout(timer), resolve()),\n { once: true },\n );\n });\n backoff = Math.min(backoff * 2, 5 * 60_000);\n }\n };\n\n let toolkit: Promise<McpToolkit> | undefined;\n let announced = false;\n const connect = () =>\n (toolkit ??= fromMcpServer({\n url: options.channel.url,\n headers: () => headersOf(options.channel, env),\n ...(options.fetch && { fetch: options.fetch }),\n name: options.name,\n }).catch((error: unknown) => {\n toolkit = undefined;\n throw error;\n }));\n const withTimeout = <T>(promise: Promise<T>, ms: number) =>\n Promise.race([\n promise,\n new Promise<undefined>((resolve) => unref(setTimeout(resolve, ms))),\n ]).catch(() => undefined);\n // The server was down when Claude Code asked for the tools: list them once it's back.\n const retryTools = async () => {\n let wait = 5000;\n while (!controller.signal.aborted) {\n await new Promise((resolve) => unref(setTimeout(resolve, wait)));\n try {\n await connect();\n if (!announced) {\n announced = true;\n options.send({\n jsonrpc: \"2.0\",\n method: \"notifications/tools/list_changed\",\n });\n }\n return;\n } catch {\n wait = Math.min(wait * 2, 5 * 60_000);\n }\n }\n };\n\n const instructions = (upstream: string | undefined) =>\n [\n `Events from ${options.name} arrive here for the whole session, one per message: <channel source=\"${source}\" event=\"…\" …>the event</channel>. Act on each.`,\n `To answer or act on ${options.name}, use this server's tools: they are ${options.name}'s own.`,\n ...(upstream ? [`${options.name} says: ${upstream}`] : []),\n ].join(\" \");\n\n const handle = async (\n request: Channel.Request,\n ): Promise<Record<string, unknown> | undefined> => {\n const result = (value: unknown) => ({\n jsonrpc: \"2.0\",\n id: request.id,\n result: value,\n });\n switch (request.method) {\n case \"initialize\": {\n const kit = await withTimeout(connect(), CONNECT_WAIT_MS);\n return result({\n protocolVersion: protocolFor(request.params?.protocolVersion),\n capabilities: {\n experimental: { \"claude/channel\": {} },\n tools: { listChanged: true },\n },\n serverInfo: { name: `harnessd-${options.name}`, version: \"1.0.0\" },\n instructions: instructions(kit?.description),\n });\n }\n case \"notifications/initialized\":\n unref(\n setTimeout(() => {\n if (!controller.signal.aborted) following ??= follow();\n }, options.startMs ?? START_MS),\n );\n return undefined;\n case \"tools/list\":\n case \"tools/call\": {\n let kit: McpToolkit;\n try {\n kit = await connect();\n } catch (error) {\n options.log(\n `${options.name}: couldn't reach its tools: ${error instanceof Error ? error.message : String(error)}`,\n );\n if (request.method === \"tools/list\") {\n void retryTools();\n return result({ tools: [] });\n }\n return result({\n content: [\n {\n type: \"text\",\n text: `${options.name} can't be reached right now.`,\n },\n ],\n isError: true,\n });\n }\n announced = true;\n return (await handleMcpMessage(kit, request)) ?? undefined;\n }\n case \"ping\":\n return result({});\n default:\n if (request.id === undefined) return undefined;\n return {\n jsonrpc: \"2.0\",\n id: request.id,\n error: {\n code: -32601,\n message: `Method not found: ${request.method}`,\n },\n };\n }\n };\n\n return {\n handle,\n stop: async () => {\n controller.abort();\n clearInterval(check);\n await following;\n await (await toolkit?.catch(() => undefined))?.close();\n },\n };\n};\n\n/** Serves one channel on stdin and stdout until Claude Code closes stdin. */\nexport const serveChannel = async (options: Omit<Channel.Options, \"send\">) => {\n const write = (message: unknown) =>\n void process.stdout.write(`${JSON.stringify(message)}\\n`);\n const server = channelServer({ ...options, send: write });\n const end = () => void server.stop().finally(() => process.exit(0));\n process.once(\"SIGTERM\", end);\n process.once(\"SIGINT\", end);\n for await (const line of createInterface({ input: process.stdin })) {\n if (!line.trim()) continue;\n let request: Channel.Request;\n try {\n request = JSON.parse(line);\n } catch {\n write({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32700, message: \"Parse error\" },\n });\n continue;\n }\n void server.handle(request).then((response) => response && write(response));\n }\n await server.stop();\n};\n"],"mappings":";;;;;;;;;;AAwDA,MAAM,UAAU;AAEhB,MAAM,WAAW;AACjB,MAAM,eAAe,UACnB,OAAO,UAAU,YACjB,sBAAsB,KAAK,KAAK,KAChC,QAAQ,eACJ,QACA;AAEN,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,SAAS,UAAoB,MAAiC,QAAQ;;AAG5E,MAAa,eACX,SAEA,OAAO,QAAQ,IAAI,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;C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AAO,KAAA,GAAW,OAAO,KAAA;IACrC,OAAO;KACL,SAAS;KACT,IAAI,QAAQ;KACZ,OAAO;MACL,MAAM;MACN,SAAS,qBAAqB,QAAQ;KACxC;IACF;EACJ;CACF;CAEA,OAAO;EACL;EACA,MAAM,YAAY;GAChB,WAAW,MAAM;GACjB,cAAc,KAAK;GACnB,MAAM;GACN,OAAO,MAAM,SAAS,YAAY,KAAA,CAAS,EAAA,EAAI,MAAM;EACvD;CACF;AACF;;AAGA,MAAa,eAAe,OAAO,YAA2C;CAC5E,MAAM,SAAS,YACb,KAAK,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,OAAO,EAAE,GAAG;CAC1D,MAAM,SAAS,cAAc;EAAE,GAAG;EAAS,MAAM;CAAM,CAAC;CACxD,MAAM,YAAY,KAAK,OAAO,KAAK,CAAC,CAAC,cAAc,QAAQ,KAAK,CAAC,CAAC;CAClE,QAAQ,KAAK,WAAW,GAAG;CAC3B,QAAQ,KAAK,UAAU,GAAG;CAC1B,WAAW,MAAM,QAAQ,gBAAgB,EAAE,OAAO,QAAQ,MAAM,CAAC,GAAG;EAClE,IAAI,CAAC,KAAK,KAAK,GAAG;EAClB,IAAI;EACJ,IAAI;GACF,UAAU,KAAK,MAAM,IAAI;EAC3B,QAAQ;GACN,MAAM;IACJ,SAAS;IACT,IAAI;IACJ,OAAO;KAAE,MAAM;KAAQ,SAAS;IAAc;GAChD,CAAC;GACD;EACF;EACA,OAAY,OAAO,OAAO,CAAC,CAAC,MAAM,aAAa,YAAY,MAAM,QAAQ,CAAC;CAC5E;CACA,MAAM,OAAO,KAAK;AACpB"}
|
|
1
|
+
{"version":3,"file":"channel.js","names":[],"sources":["../src/channel.ts"],"sourcesContent":["import {\n closeSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n renameSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { randomBytes } from \"node:crypto\";\nimport { dirname, join } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { runCli, type CliOptions } from \"toolport/cli\";\nimport { CHANNEL_SERVER, findTranscript } from \"./claude\";\nimport { headersOf, subscriptionKey, type Harnessd } from \"./config\";\n\nexport namespace Channel {\n /** What the channel keeps in harnessd's home: where each subscription's events resume, and whether Claude Code hears them. */\n export type Status = {\n /** Each subscription's cursor, by its key. */\n readonly cursors?: Readonly<Record<string, string>>;\n /** When this Claude Code process got its first event. */\n readonly pushedAt?: string;\n /** When one of its events first showed up in the conversation's transcript. */\n readonly heardAt?: string;\n };\n\n export type Options = {\n readonly config: Harnessd.Config;\n readonly paths: Harnessd.Paths;\n readonly send: (message: Record<string, unknown>) => void;\n readonly log: (line: string) => void;\n readonly env?: NodeJS.ProcessEnv;\n readonly fetch?: typeof fetch;\n readonly startMs?: number;\n readonly checkMs?: number;\n };\n\n export type Server = {\n readonly handle: (\n request: Request,\n ) => Promise<Record<string, unknown> | undefined>;\n readonly stop: () => Promise<void>;\n };\n\n export type Request = {\n jsonrpc: \"2.0\";\n id?: string | number;\n method: string;\n params?: Record<string, unknown>;\n };\n}\n\nconst CHANNEL = \"notifications/claude/channel\";\n// Claude Code registers no channel on 2026-07-28 or later\nconst PROTOCOL = \"2025-06-18\";\nconst protocolFor = (asked: unknown) =>\n typeof asked === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}$/.test(asked) &&\n asked < \"2026-07-28\"\n ? asked\n : PROTOCOL;\n// Claude Code drops what a channel sends before it registers, just after `initialized`\nconst START_MS = 1500;\nconst CHECK_MS = 5000;\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst unref = (timer: unknown) => (timer as { unref?: () => void }).unref?.();\n\n/** Subscription arguments as toolport's `stream` takes them: kebab-case flags, `--x` and `--no-x` for booleans. */\nexport const streamFlags = (\n args: Readonly<Record<string, string | number | boolean>>,\n) =>\n Object.entries(args).flatMap(([key, value]) => {\n const flag = key\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/_/g, \"-\")\n .toLowerCase();\n return typeof value === \"boolean\"\n ? [value ? `--${flag}` : `--no-${flag}`]\n : [`--${flag}`, String(value)];\n });\n\n/** A server's command, `harnessd tools <server>`, which the channel's subscriptions run too: one sign-in serves both. */\nexport const serverCli = (\n paths: Harnessd.Paths,\n name: string,\n server: Harnessd.Server,\n env: NodeJS.ProcessEnv,\n fetch?: typeof globalThis.fetch,\n): CliOptions => ({\n name,\n configDir: join(paths.home, \"auth\"),\n servers: {\n [name]: {\n url: server.url,\n headers: headersOf(server, env),\n root: true,\n ...(fetch && { fetch }),\n },\n },\n});\n\n/** A subscription as the log and `harnessd status` name it: `board task.handed --board AUI`. */\nexport const subscriptionLabel = (subscription: Harnessd.Subscription) =>\n [\n subscription.server,\n subscription.event,\n ...streamFlags(subscription.arguments),\n ].join(\" \");\n\nexport const readStatus = (file: string): Channel.Status => {\n try {\n return JSON.parse(readFileSync(file, \"utf8\")) as Channel.Status;\n } catch {\n return {};\n }\n};\n\n/** 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. */\nexport const channelMessage = (line: {\n server: string;\n name: string;\n data: unknown;\n gap?: boolean;\n delivery: string;\n}) => {\n if (line.gap)\n return {\n content: `Some ${line.name} events were missed (${line.server} no longer had them): read its state again.`,\n meta: {\n server: line.server,\n event: line.name,\n gap: \"true\",\n delivery: line.delivery,\n },\n };\n const data = line.data;\n const meta: Record<string, string> = {};\n if (typeof data === \"object\" && data !== null && !Array.isArray(data))\n for (const [key, value] of Object.entries(data)) {\n if (key === \"text\" || key === \"source\" || !IDENTIFIER.test(key)) continue;\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n )\n meta[key] = String(value).replace(/[<>\"]/g, \"\").slice(0, 200);\n }\n meta.server = line.server;\n meta.event = line.name;\n meta.delivery = line.delivery;\n const text = (data as { text?: unknown } | null)?.text;\n return {\n content: typeof text === \"string\" ? text : JSON.stringify(data),\n meta,\n };\n};\n\n/** The deliveries of this channel's messages in a transcript's whole lines from byte `from` on, and where those lines end. */\nconst deliveriesIn = (file: string, from: number, source: string) => {\n try {\n const buffer = Buffer.alloc(Math.max(0, statSync(file).size - from));\n const fd = openSync(file, \"r\");\n try {\n readSync(fd, buffer, 0, buffer.length, from);\n } finally {\n closeSync(fd);\n }\n const whole = buffer.lastIndexOf(10) + 1;\n const text = buffer.subarray(0, whole).toString(\"utf8\");\n // in the JSONL the tag's quotes are escaped\n const tag = new RegExp(\n `<channel source=\\\\\\\\?\"${source.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")}\\\\\\\\?\"([^>]*)>`,\n \"g\",\n );\n const found: string[] = [];\n for (const [, attributes] of text.matchAll(tag)) {\n const delivery = /delivery=\\\\?\"([a-f0-9]+\\.\\d+)\\\\?\"/.exec(attributes!);\n if (delivery) found.push(delivery[1]!);\n }\n return { found, next: from + whole };\n } catch {\n return { found: [], next: from };\n }\n};\n\nconst sizeOf = (file: string | undefined) => {\n try {\n return file ? statSync(file).size : 0;\n } catch {\n return 0;\n }\n};\n\n/**\n * `harnessd channel`: the stdio MCP server Claude Code runs for harnessd's one channel. It follows each subscription\n * of the config (one `events/stream` each) and hands every event to Claude Code as a channel message. Where a\n * subscription's events resume is saved only once Claude Code is seen to hear them: an event it dropped (a channel it\n * didn't let in) comes again at the next start. The agent answers with the servers' commands, not here.\n */\nexport const channelServer = (options: Channel.Options): Channel.Server => {\n const env = options.env ?? process.env;\n const { servers } = options.config;\n const subscriptions = options.config.channel.subscribe.map(\n (subscription) => ({ subscription, key: subscriptionKey(subscription) }),\n );\n const source = `plugin:harnessd:${CHANNEL_SERVER}`;\n const file = options.paths.channel;\n const saved = readStatus(file).cursors ?? {};\n // a subscription no longer in the config leaves no cursor behind\n const cursors: Record<string, string> = Object.fromEntries(\n subscriptions.flatMap(({ key }) =>\n typeof saved[key] === \"string\" ? [[key, saved[key]]] : [],\n ),\n );\n let status: Channel.Status = { cursors };\n const save = (patch: Channel.Status) => {\n status = { ...status, ...patch };\n mkdirSync(dirname(file), { recursive: true });\n // replaced whole, so a crash mid-write never loses a cursor\n const temp = `${file}.${process.pid}`;\n writeFileSync(temp, `${JSON.stringify(status)}\\n`);\n renameSync(temp, file);\n };\n save({});\n const controller = new AbortController();\n let following: Promise<unknown> | undefined;\n const transcript = () =>\n env.CLAUDE_CODE_SESSION_ID\n ? findTranscript(env.CLAUDE_CODE_SESSION_ID, env)\n : undefined;\n // a resumed conversation's earlier lines belong to earlier runs\n let from = sizeOf(transcript());\n // a payload can't name a later event's delivery: each run's numbers carry a random prefix\n const nonce = randomBytes(4).toString(\"hex\");\n let delivery = 0;\n const unconfirmed: {\n delivery: string;\n key: string;\n cursor: string | undefined;\n }[] = [];\n const heard = new Set<string>();\n let check: ReturnType<typeof setInterval> | undefined;\n\n // A cursor moves only through events the transcript shows, in order; Claude Code takes them in the order sent.\n const confirm = () => {\n const at = transcript();\n if (at === undefined) return;\n const read = deliveriesIn(at, from, source);\n from = read.next;\n for (const n of read.found) heard.add(n);\n const moved: Record<string, string> = {};\n while (unconfirmed.length > 0 && heard.has(unconfirmed[0]!.delivery)) {\n const event = unconfirmed.shift()!;\n heard.delete(event.delivery);\n if (event.cursor !== undefined) moved[event.key] = event.cursor;\n if (!status.heardAt) {\n save({ heardAt: new Date().toISOString() });\n options.log(\"Claude Code hears the channel's events\");\n }\n }\n if (Object.keys(moved).length > 0)\n save({ cursors: { ...status.cursors, ...moved } });\n };\n\n const follow = async ({\n subscription,\n key,\n }: (typeof subscriptions)[number]) => {\n const label = subscriptionLabel(subscription);\n const server = servers[subscription.server]!;\n // where a reconnect of this process resumes: past every event sent, heard or not\n let lastCursor: string | undefined = cursors[key];\n const onLine = (raw: string) => {\n let line: {\n name?: string;\n data?: unknown;\n cursor?: string;\n gap?: boolean;\n };\n try {\n line = JSON.parse(raw);\n } catch {\n return;\n }\n if (typeof line.name !== \"string\") return;\n if (!status.pushedAt) save({ pushedAt: new Date().toISOString() });\n if (!check) {\n check = setInterval(confirm, options.checkMs ?? CHECK_MS);\n unref(check);\n }\n const cursor =\n typeof line.cursor === \"string\" && line.cursor\n ? line.cursor\n : undefined;\n if (cursor) lastCursor = cursor;\n const id = `${nonce}.${++delivery}`;\n unconfirmed.push({ delivery: id, key, cursor });\n options.send({\n jsonrpc: \"2.0\",\n method: CHANNEL,\n params: channelMessage({\n server: subscription.server,\n name: line.name,\n data: line.data ?? null,\n ...(line.gap && { gap: true }),\n delivery: id,\n }),\n });\n };\n let backoff = 5000;\n while (!controller.signal.aborted) {\n const startedAt = Date.now();\n let code: number;\n try {\n const cursor = lastCursor;\n code = await runCli(\n serverCli(\n options.paths,\n subscription.server,\n server,\n env,\n options.fetch,\n ),\n {\n argv: [\n \"stream\",\n subscription.event,\n ...(cursor ? [\"--from\", cursor] : []),\n ...streamFlags(subscription.arguments),\n ],\n stdout: onLine,\n stderr: (line) => options.log(`${label}: ${line}`),\n signal: controller.signal,\n },\n );\n } catch (error) {\n code = 1;\n options.log(\n `${label}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (controller.signal.aborted) return;\n if (Date.now() - startedAt > 10 * 60_000) backoff = 5000;\n options.log(\n `${label}: the event stream ended (exit ${code}); following again in ${Math.round(backoff / 1000)}s`,\n );\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, backoff);\n controller.signal.addEventListener(\n \"abort\",\n () => (clearTimeout(timer), resolve()),\n { once: true },\n );\n });\n backoff = Math.min(backoff * 2, 5 * 60_000);\n }\n };\n\n const names = Object.keys(servers);\n const instructions = [\n `Events arrive here for the whole session, one per message: <channel source=\"${source}\" server=\"…\" event=\"…\" …>the event</channel>. Act on each.`,\n `To answer or act, run the server's command in the shell: ${names.map((name) => `\\`${name}\\``).join(\", \")}. \\`<command> --help\\` lists its tools.`,\n ].join(\" \");\n\n const handle = async (\n request: Channel.Request,\n ): Promise<Record<string, unknown> | undefined> => {\n const result = (value: unknown) => ({\n jsonrpc: \"2.0\",\n id: request.id,\n result: value,\n });\n switch (request.method) {\n case \"initialize\":\n return result({\n protocolVersion: protocolFor(request.params?.protocolVersion),\n capabilities: { experimental: { \"claude/channel\": {} } },\n serverInfo: { name: \"harnessd\", version: \"1.0.0\" },\n instructions,\n });\n case \"notifications/initialized\":\n unref(\n setTimeout(() => {\n if (!controller.signal.aborted)\n following ??= Promise.all(subscriptions.map(follow));\n }, options.startMs ?? START_MS),\n );\n return undefined;\n case \"ping\":\n return result({});\n default:\n if (request.id === undefined) return undefined;\n return {\n jsonrpc: \"2.0\",\n id: request.id,\n error: {\n code: -32601,\n message: `Method not found: ${request.method}`,\n },\n };\n }\n };\n\n return {\n handle,\n stop: async () => {\n controller.abort();\n clearInterval(check);\n await following;\n },\n };\n};\n\n/** Serves the channel on stdin and stdout until Claude Code closes stdin. */\nexport const serveChannel = async (options: Omit<Channel.Options, \"send\">) => {\n const write = (message: unknown) =>\n void process.stdout.write(`${JSON.stringify(message)}\\n`);\n const server = channelServer({ ...options, send: write });\n const end = () => void server.stop().finally(() => process.exit(0));\n process.once(\"SIGTERM\", end);\n process.once(\"SIGINT\", end);\n for await (const line of createInterface({ input: process.stdin })) {\n if (!line.trim()) continue;\n let request: Channel.Request;\n try {\n request = JSON.parse(line);\n } catch {\n write({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32700, message: \"Parse error\" },\n });\n continue;\n }\n void server.handle(request).then((response) => response && write(response));\n }\n await server.stop();\n};\n"],"mappings":";;;;;;;;AAsDA,MAAM,UAAU;AAEhB,MAAM,WAAW;AACjB,MAAM,eAAe,UACnB,OAAO,UAAU,YACjB,sBAAsB,KAAK,KAAK,KAChC,QAAQ,eACJ,QACA;AAEN,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,aAAa;AACnB,MAAM,SAAS,UAAoB,MAAiC,QAAQ;;AAG5E,MAAa,eACX,SAEA,OAAO,QAAQ,IAAI,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;CAC7C,MAAM,OAAO,IACV,QAAQ,sBAAsB,OAA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Q,CAAC;CAC5E;CACA,MAAM,OAAO,KAAK;AACpB"}
|
package/dist/claude.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import type { Harnessd } from "./config.js";
|
|
|
2
2
|
import type { Watchdog } from "./watchdog.js";
|
|
3
3
|
/** How Claude Code names a `--plugin-dir` plugin. */
|
|
4
4
|
export declare const PLUGIN = "harnessd@inline";
|
|
5
|
+
/** The channel's MCP server in harnessd's plugin, and so each event's `source`: `plugin:harnessd:channel`. */
|
|
6
|
+
export declare const CHANNEL_SERVER = "channel";
|
|
5
7
|
/**
|
|
6
8
|
* Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
|
|
7
9
|
* `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field
|
|
@@ -13,17 +15,20 @@ export declare const findTranscript: (sessionId: string, env?: NodeJS.ProcessEnv
|
|
|
13
15
|
/** The first `name` on `path` that can run. */
|
|
14
16
|
export declare const which: (name: string, path?: string) => string;
|
|
15
17
|
/**
|
|
16
|
-
* harnessd's plugin, written before each start:
|
|
17
|
-
*
|
|
18
|
-
* /clear or a /resume is the conversation the next start
|
|
18
|
+
* harnessd's plugin, written before each start: the channel's MCP server (`harnessd channel`) when the config
|
|
19
|
+
* subscribes to events, a command per server in its `bin` (`harnessd tools <server>`), a SessionStart hook that
|
|
20
|
+
* tells harnessd which conversation Claude Code is in, so a /clear or a /resume is the conversation the next start
|
|
21
|
+
* resumes, and a Notification hook that tells harnessd when Claude Code waits for input with nothing running.
|
|
19
22
|
*/
|
|
20
23
|
export declare const writePlugin: (paths: Harnessd.Paths, config: Harnessd.Config, bin: string) => void;
|
|
24
|
+
/** The version a claude command prints, such as `2.1.335`; none when it doesn't run or prints no version. */
|
|
25
|
+
export declare const claudeVersion: (file: string, env: NodeJS.ProcessEnv) => Promise<string | undefined>;
|
|
21
26
|
/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */
|
|
22
27
|
export declare const skipsPermissions: (args: readonly string[]) => boolean;
|
|
23
28
|
/**
|
|
24
29
|
* The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
|
|
25
30
|
* decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
|
|
26
|
-
* its
|
|
31
|
+
* its channel loads with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
|
|
27
32
|
* Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
|
|
28
33
|
*/
|
|
29
34
|
export declare const claudeArgs: (o: {
|
package/dist/claude.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude.d.ts","sourceRoot":"","sources":["../src/claude.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,QAAQ,EAAE,oBAAiB;AACzC,OAAO,KAAK,EAAE,QAAQ,EAAE,sBAAmB;AAE3C,qDAAqD;AACrD,eAAO,MAAM,MAAM,oBAAoB,CAAC;AAKxC;;;;GAIG;AACH,eAAO,MAAM,WAAW,GACtB,QAAQ,MAAM,EACd,MAAK,MAAM,CAAC,UAAwB,KACnC,OAqBF,CAAC;AAEF,gEAAgE;AAChE,eAAO,MAAM,cAAc,GACzB,WAAW,MAAM,EACjB,MAAK,MAAM,CAAC,UAAwB,KACnC,MAAM,GAAG,SASX,CAAC;AAEF,+CAA+C;AAC/C,eAAO,MAAM,KAAK,GAAI,MAAM,MAAM,EAAE,aAA6B,WAYhE,CAAC;AAIF
|
|
1
|
+
{"version":3,"file":"claude.d.ts","sourceRoot":"","sources":["../src/claude.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,QAAQ,EAAE,oBAAiB;AACzC,OAAO,KAAK,EAAE,QAAQ,EAAE,sBAAmB;AAE3C,qDAAqD;AACrD,eAAO,MAAM,MAAM,oBAAoB,CAAC;AAExC,8GAA8G;AAC9G,eAAO,MAAM,cAAc,YAAY,CAAC;AAKxC;;;;GAIG;AACH,eAAO,MAAM,WAAW,GACtB,QAA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claude Code names a `--plugin-dir` plugin. */
|
|
7
7
|
const PLUGIN = "harnessd@inline";
|
|
8
|
+
/** The channel's MCP server in harnessd's plugin, and so each event's `source`: `plugin:harnessd:channel`. */
|
|
9
|
+
const CHANNEL_SERVER = "channel";
|
|
8
10
|
const claudeDir = (env) => env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
|
|
9
11
|
/**
|
|
10
12
|
* Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's
|
|
@@ -55,9 +57,10 @@ const which = (name, path = process.env.PATH ?? "") => {
|
|
|
55
57
|
};
|
|
56
58
|
const shellQuote = (text) => `'${text.replaceAll("'", "'\\''")}'`;
|
|
57
59
|
/**
|
|
58
|
-
* harnessd's plugin, written before each start:
|
|
59
|
-
*
|
|
60
|
-
* /clear or a /resume is the conversation the next start
|
|
60
|
+
* harnessd's plugin, written before each start: the channel's MCP server (`harnessd channel`) when the config
|
|
61
|
+
* subscribes to events, a command per server in its `bin` (`harnessd tools <server>`), a SessionStart hook that
|
|
62
|
+
* tells harnessd which conversation Claude Code is in, so a /clear or a /resume is the conversation the next start
|
|
63
|
+
* resumes, and a Notification hook that tells harnessd when Claude Code waits for input with nothing running.
|
|
61
64
|
*/
|
|
62
65
|
const writePlugin = (paths, config, bin) => {
|
|
63
66
|
rmSync(paths.plugin, {
|
|
@@ -65,39 +68,60 @@ const writePlugin = (paths, config, bin) => {
|
|
|
65
68
|
force: true
|
|
66
69
|
});
|
|
67
70
|
mkdirSync(join(paths.plugin, ".claude-plugin"), { recursive: true });
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
71
|
+
mkdirSync(paths.bin, { recursive: true });
|
|
72
|
+
const exports = Object.entries(paths.env).map(([name, value]) => `${name}=${shellQuote(value)}`);
|
|
73
|
+
const harnessd = [shellQuote(process.execPath), shellQuote(bin)];
|
|
74
|
+
for (const name of Object.keys(config.servers)) writeFileSync(join(paths.bin, name), [
|
|
75
|
+
"#!/bin/sh",
|
|
76
|
+
...exports.map((line) => `export ${line}`),
|
|
77
|
+
`exec ${[
|
|
78
|
+
...harnessd,
|
|
79
|
+
"tools",
|
|
80
|
+
name
|
|
81
|
+
].join(" ")} "$@"`,
|
|
82
|
+
""
|
|
83
|
+
].join("\n"), { mode: 493 });
|
|
84
|
+
const hook = (command) => [
|
|
85
|
+
...exports,
|
|
86
|
+
...harnessd,
|
|
87
|
+
command
|
|
74
88
|
].join(" ");
|
|
75
89
|
const manifest = {
|
|
76
90
|
name: "harnessd",
|
|
77
91
|
version: "1.0.0",
|
|
78
|
-
description: "harnessd's
|
|
79
|
-
...
|
|
80
|
-
mcpServers:
|
|
92
|
+
description: "harnessd's channel of the servers' events, and its SessionStart and Notification hooks",
|
|
93
|
+
...config.channel.subscribe.length > 0 && {
|
|
94
|
+
mcpServers: { ["channel"]: {
|
|
81
95
|
command: process.execPath,
|
|
82
|
-
args: [
|
|
83
|
-
bin,
|
|
84
|
-
"channel",
|
|
85
|
-
name
|
|
86
|
-
],
|
|
96
|
+
args: [bin, "channel"],
|
|
87
97
|
env: paths.env
|
|
88
|
-
}
|
|
89
|
-
channels:
|
|
90
|
-
server:
|
|
91
|
-
displayName:
|
|
92
|
-
}
|
|
98
|
+
} },
|
|
99
|
+
channels: [{
|
|
100
|
+
server: "channel",
|
|
101
|
+
displayName: "harnessd"
|
|
102
|
+
}]
|
|
93
103
|
},
|
|
94
|
-
hooks: {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
104
|
+
hooks: {
|
|
105
|
+
SessionStart: [{ hooks: [{
|
|
106
|
+
type: "command",
|
|
107
|
+
command: hook("session-start")
|
|
108
|
+
}] }],
|
|
109
|
+
Notification: [{
|
|
110
|
+
matcher: "idle_prompt",
|
|
111
|
+
hooks: [{
|
|
112
|
+
type: "command",
|
|
113
|
+
command: hook("idle")
|
|
114
|
+
}]
|
|
115
|
+
}]
|
|
116
|
+
}
|
|
98
117
|
};
|
|
99
118
|
writeFileSync(join(paths.plugin, ".claude-plugin", "plugin.json"), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
100
119
|
};
|
|
120
|
+
/** The version a claude command prints, such as `2.1.335`; none when it doesn't run or prints no version. */
|
|
121
|
+
const claudeVersion = (file, env) => new Promise((resolve) => execFile(file, ["--version"], {
|
|
122
|
+
env,
|
|
123
|
+
timeout: 3e4
|
|
124
|
+
}, (error, stdout) => resolve(error ? void 0 : /^\s*(\d+\.\d+\.\d+\S*)/.exec(stdout)?.[1])));
|
|
101
125
|
/** Whether these claude arguments pick a permission mode themselves. */
|
|
102
126
|
const picksPermissionMode = (args) => args.some((arg) => arg === "--dangerously-skip-permissions" || arg === "--permission-mode" || arg.startsWith("--permission-mode="));
|
|
103
127
|
/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */
|
|
@@ -105,14 +129,14 @@ const skipsPermissions = (args) => args.some((arg, i) => arg === "--dangerously-
|
|
|
105
129
|
/**
|
|
106
130
|
* The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which
|
|
107
131
|
* decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so
|
|
108
|
-
* its
|
|
132
|
+
* its channel loads with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude
|
|
109
133
|
* Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).
|
|
110
134
|
*/
|
|
111
135
|
const claudeArgs = (o) => [
|
|
112
136
|
...picksPermissionMode([...o.config.args, ...o.extra]) ? [] : ["--permission-mode", "auto"],
|
|
113
137
|
"--plugin-dir",
|
|
114
138
|
o.plugin,
|
|
115
|
-
...
|
|
139
|
+
...o.config.channel.subscribe.length > 0 ? ["--dangerously-load-development-channels", `plugin:${PLUGIN}`] : [],
|
|
116
140
|
...o.start.resume ? ["--resume", o.start.sessionId] : ["--session-id", o.start.sessionId],
|
|
117
141
|
...o.start.prompt ? [o.start.prompt] : [],
|
|
118
142
|
...o.config.args,
|
|
@@ -147,6 +171,6 @@ const prestart = (command, folder, env, log) => new Promise((resolve, reject) =>
|
|
|
147
171
|
});
|
|
148
172
|
});
|
|
149
173
|
});
|
|
150
|
-
export { PLUGIN, claudeArgs, findTranscript, prestart, skipsPermissions, trustFolder, which, writePlugin };
|
|
174
|
+
export { CHANNEL_SERVER, PLUGIN, claudeArgs, claudeVersion, findTranscript, prestart, skipsPermissions, trustFolder, which, writePlugin };
|
|
151
175
|
|
|
152
176
|
//# sourceMappingURL=claude.js.map
|
package/dist/claude.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude.js","names":[],"sources":["../src/claude.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport type { Harnessd } from \"./config\";\nimport type { Watchdog } from \"./watchdog\";\n\n/** How Claude Code names a `--plugin-dir` plugin. */\nexport const PLUGIN = \"harnessd@inline\";\n\nconst claudeDir = (env: NodeJS.ProcessEnv) =>\n env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n\n/**\n * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's\n * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field\n * changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.\n */\nexport const trustFolder = (\n folder: string,\n env: NodeJS.ProcessEnv = process.env,\n): boolean => {\n const file = env.CLAUDE_CONFIG_DIR\n ? join(env.CLAUDE_CONFIG_DIR, \".claude.json\")\n : join(homedir(), \".claude.json\");\n if (!existsSync(file)) return false;\n const text = readFileSync(file, \"utf8\");\n const config = JSON.parse(text) as {\n projects?: Record<string, { hasTrustDialogAccepted?: boolean }>;\n };\n const key = realpathSync(folder);\n if (config.projects?.[key]?.hasTrustDialogAccepted === true) return true;\n config.projects = {\n ...config.projects,\n [key]: { ...config.projects?.[key], hasTrustDialogAccepted: true },\n };\n const pretty = text.trimEnd() === JSON.stringify(JSON.parse(text), null, 2);\n const written = `${pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)}${text.endsWith(\"\\n\") ? \"\\n\" : \"\"}`;\n const temp = `${file}.harnessd-${process.pid}`;\n writeFileSync(temp, written, { mode: statSync(file).mode & 0o777 });\n renameSync(temp, file);\n return true;\n};\n\n/** A conversation's transcript, wherever Claude Code put it. */\nexport const findTranscript = (\n sessionId: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | undefined => {\n const projects = join(claudeDir(env), \"projects\");\n try {\n for (const dir of readdirSync(projects)) {\n const file = join(projects, dir, `${sessionId}.jsonl`);\n if (existsSync(file)) return file;\n }\n } catch {}\n return undefined;\n};\n\n/** The first `name` on `path` that can run. */\nexport const which = (name: string, path = process.env.PATH ?? \"\") => {\n if (name.includes(\"/\")) return name;\n for (const dir of path.split(delimiter)) {\n if (!dir) continue;\n try {\n accessSync(join(dir, name), constants.X_OK);\n return join(dir, name);\n } catch {}\n }\n throw new Error(\n `${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`,\n );\n};\n\nconst shellQuote = (text: string) => `'${text.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n/**\n * harnessd's plugin, written before each start: one MCP server per channel of the config, each\n * `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a\n * /clear or a /resume is the conversation the next start resumes.\n */\nexport const writePlugin = (\n paths: Harnessd.Paths,\n config: Harnessd.Config,\n bin: string,\n) => {\n rmSync(paths.plugin, { recursive: true, force: true });\n mkdirSync(join(paths.plugin, \".claude-plugin\"), { recursive: true });\n const names = Object.keys(config.channels);\n const sessionStart = [\n ...Object.entries(paths.env).map(\n ([name, value]) => `${name}=${shellQuote(value)}`,\n ),\n shellQuote(process.execPath),\n shellQuote(bin),\n \"session-start\",\n ].join(\" \");\n const manifest = {\n name: \"harnessd\",\n version: \"1.0.0\",\n description:\n \"harnessd's channels, each one's events and tools, and its SessionStart hook\",\n ...(names.length > 0 && {\n mcpServers: Object.fromEntries(\n names.map((name) => [\n name,\n {\n command: process.execPath,\n args: [bin, \"channel\", name],\n env: paths.env,\n },\n ]),\n ),\n channels: names.map((name) => ({ server: name, displayName: name })),\n }),\n hooks: {\n SessionStart: [{ hooks: [{ type: \"command\", command: sessionStart }] }],\n },\n };\n writeFileSync(\n join(paths.plugin, \".claude-plugin\", \"plugin.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n );\n};\n\n/** Whether these claude arguments pick a permission mode themselves. */\nconst picksPermissionMode = (args: readonly string[]) =>\n args.some(\n (arg) =>\n arg === \"--dangerously-skip-permissions\" ||\n arg === \"--permission-mode\" ||\n arg.startsWith(\"--permission-mode=\"),\n );\n\n/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */\nexport const skipsPermissions = (args: readonly string[]) =>\n args.some(\n (arg, i) =>\n arg === \"--dangerously-skip-permissions\" ||\n arg === \"--permission-mode=bypassPermissions\" ||\n (arg === \"bypassPermissions\" && args[i - 1] === \"--permission-mode\"),\n );\n\n/**\n * The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which\n * decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so\n * its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude\n * Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).\n */\nexport const claudeArgs = (o: {\n start: Watchdog.Start;\n plugin: string;\n config: Harnessd.Config;\n extra: readonly string[];\n}) => [\n ...(picksPermissionMode([...o.config.args, ...o.extra])\n ? []\n : [\"--permission-mode\", \"auto\"]),\n \"--plugin-dir\",\n o.plugin,\n ...(Object.keys(o.config.channels).length > 0\n ? [\"--dangerously-load-development-channels\", `plugin:${PLUGIN}`]\n : []),\n ...(o.start.resume\n ? [\"--resume\", o.start.sessionId]\n : [\"--session-id\", o.start.sessionId]),\n // before the config's arguments: after a list flag (--add-dir…) claude would take it as one more value\n ...(o.start.prompt ? [o.start.prompt] : []),\n ...o.config.args,\n ...o.extra,\n];\n\nexport type Prestart = { env: Record<string, string>; args: string[] };\n\n/** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */\nexport const prestart = (\n command: string,\n folder: string,\n env: NodeJS.ProcessEnv,\n log: (line: string) => void,\n) =>\n new Promise<Prestart>((resolve, reject) => {\n execFile(\n \"/bin/sh\",\n [\"-c\", command],\n { cwd: folder, env, timeout: 60_000, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n for (const line of stderr.split(\"\\n\"))\n if (line.trim()) log(`prestart: ${line}`);\n if (error)\n return reject(\n new Error(`prestart failed: ${error.message.split(\"\\n\")[0]}`),\n );\n if (!stdout.trim()) return resolve({ env: {}, args: [] });\n let parsed: unknown;\n try {\n parsed = JSON.parse(stdout);\n } catch {\n return reject(\n new Error(\n \"prestart printed something other than JSON { env?, args? }\",\n ),\n );\n }\n const {\n env: more = {},\n args = [],\n ...rest\n } = (parsed ?? {}) as { env?: unknown; args?: unknown };\n if (\n typeof parsed !== \"object\" ||\n Object.keys(rest).length > 0 ||\n typeof more !== \"object\" ||\n more === null ||\n Object.values(more).some((v) => typeof v !== \"string\") ||\n !Array.isArray(args) ||\n args.some((a) => typeof a !== \"string\")\n )\n return reject(\n new Error(\n \"prestart's JSON must be { env?: { NAME: string }, args?: string[] }\",\n ),\n );\n // harnessd finds the conversation before prestart runs, so where Claude Code keeps it comes from config.json\n if (\"CLAUDE_CONFIG_DIR\" in more)\n return reject(\n new Error(\n \"prestart can't set CLAUDE_CONFIG_DIR; set it in config.json's env\",\n ),\n );\n resolve({\n env: more as Record<string, string>,\n args: args as string[],\n });\n },\n );\n });\n"],"mappings":";;;;;;AAoBA,MAAa,SAAS;AAEtB,MAAM,aAAa,QACjB,IAAI,qBAAqB,K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AM,EACJ,KAAK,OAAO,CAAC,GACb,OAAO,CAAC,GACR,GAAG,SACA,UAAU,CAAC;EAChB,IACE,OAAO,WAAW,YAClB,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,KAC3B,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,OAAO,IAAI,CAAC,CAAC,MAAM,MAAM,OAAO,MAAM,QAAQ,KACrD,CAAC,MAAM,QAAQ,IAAI,KACnB,KAAK,MAAM,MAAM,OAAO,MAAM,QAAQ,GAEtC,OAAO,uBACL,IAAI,MACF,qEACF,CACF;EAEF,IAAI,uBAAuB,MACzB,OAAO,uBACL,IAAI,MACF,mEACF,CACF;EACF,QAAQ;GACN,KAAK;GACC;EACR,CAAC;CACH,CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"claude.js","names":[],"sources":["../src/claude.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport type { Harnessd } from \"./config\";\nimport type { Watchdog } from \"./watchdog\";\n\n/** How Claude Code names a `--plugin-dir` plugin. */\nexport const PLUGIN = \"harnessd@inline\";\n\n/** The channel's MCP server in harnessd's plugin, and so each event's `source`: `plugin:harnessd:channel`. */\nexport const CHANNEL_SERVER = \"channel\";\n\nconst claudeDir = (env: NodeJS.ProcessEnv) =>\n env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n\n/**\n * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's\n * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field\n * changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.\n */\nexport const trustFolder = (\n folder: string,\n env: NodeJS.ProcessEnv = process.env,\n): boolean => {\n const file = env.CLAUDE_CONFIG_DIR\n ? join(env.CLAUDE_CONFIG_DIR, \".claude.json\")\n : join(homedir(), \".claude.json\");\n if (!existsSync(file)) return false;\n const text = readFileSync(file, \"utf8\");\n const config = JSON.parse(text) as {\n projects?: Record<string, { hasTrustDialogAccepted?: boolean }>;\n };\n const key = realpathSync(folder);\n if (config.projects?.[key]?.hasTrustDialogAccepted === true) return true;\n config.projects = {\n ...config.projects,\n [key]: { ...config.projects?.[key], hasTrustDialogAccepted: true },\n };\n const pretty = text.trimEnd() === JSON.stringify(JSON.parse(text), null, 2);\n const written = `${pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)}${text.endsWith(\"\\n\") ? \"\\n\" : \"\"}`;\n const temp = `${file}.harnessd-${process.pid}`;\n writeFileSync(temp, written, { mode: statSync(file).mode & 0o777 });\n renameSync(temp, file);\n return true;\n};\n\n/** A conversation's transcript, wherever Claude Code put it. */\nexport const findTranscript = (\n sessionId: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | undefined => {\n const projects = join(claudeDir(env), \"projects\");\n try {\n for (const dir of readdirSync(projects)) {\n const file = join(projects, dir, `${sessionId}.jsonl`);\n if (existsSync(file)) return file;\n }\n } catch {}\n return undefined;\n};\n\n/** The first `name` on `path` that can run. */\nexport const which = (name: string, path = process.env.PATH ?? \"\") => {\n if (name.includes(\"/\")) return name;\n for (const dir of path.split(delimiter)) {\n if (!dir) continue;\n try {\n accessSync(join(dir, name), constants.X_OK);\n return join(dir, name);\n } catch {}\n }\n throw new Error(\n `${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`,\n );\n};\n\nconst shellQuote = (text: string) => `'${text.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n/**\n * harnessd's plugin, written before each start: the channel's MCP server (`harnessd channel`) when the config\n * subscribes to events, a command per server in its `bin` (`harnessd tools <server>`), a SessionStart hook that\n * tells harnessd which conversation Claude Code is in, so a /clear or a /resume is the conversation the next start\n * resumes, and a Notification hook that tells harnessd when Claude Code waits for input with nothing running.\n */\nexport const writePlugin = (\n paths: Harnessd.Paths,\n config: Harnessd.Config,\n bin: string,\n) => {\n rmSync(paths.plugin, { recursive: true, force: true });\n mkdirSync(join(paths.plugin, \".claude-plugin\"), { recursive: true });\n mkdirSync(paths.bin, { recursive: true });\n const exports = Object.entries(paths.env).map(\n ([name, value]) => `${name}=${shellQuote(value)}`,\n );\n const harnessd = [shellQuote(process.execPath), shellQuote(bin)];\n for (const name of Object.keys(config.servers))\n writeFileSync(\n join(paths.bin, name),\n [\n \"#!/bin/sh\",\n ...exports.map((line) => `export ${line}`),\n `exec ${[...harnessd, \"tools\", name].join(\" \")} \"$@\"`,\n \"\",\n ].join(\"\\n\"),\n { mode: 0o755 },\n );\n const hook = (command: string) =>\n [...exports, ...harnessd, command].join(\" \");\n const manifest = {\n name: \"harnessd\",\n version: \"1.0.0\",\n description:\n \"harnessd's channel of the servers' events, and its SessionStart and Notification hooks\",\n ...(config.channel.subscribe.length > 0 && {\n mcpServers: {\n [CHANNEL_SERVER]: {\n command: process.execPath,\n args: [bin, \"channel\"],\n env: paths.env,\n },\n },\n channels: [{ server: CHANNEL_SERVER, displayName: \"harnessd\" }],\n }),\n hooks: {\n SessionStart: [\n { hooks: [{ type: \"command\", command: hook(\"session-start\") }] },\n ],\n // Claude Code's own idle: a minute after a turn, with no background agent or dialog\n Notification: [\n {\n matcher: \"idle_prompt\",\n hooks: [{ type: \"command\", command: hook(\"idle\") }],\n },\n ],\n },\n };\n writeFileSync(\n join(paths.plugin, \".claude-plugin\", \"plugin.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n );\n};\n\n/** The version a claude command prints, such as `2.1.335`; none when it doesn't run or prints no version. */\nexport const claudeVersion = (file: string, env: NodeJS.ProcessEnv) =>\n new Promise<string | undefined>((resolve) =>\n execFile(file, [\"--version\"], { env, timeout: 30_000 }, (error, stdout) =>\n resolve(error ? undefined : /^\\s*(\\d+\\.\\d+\\.\\d+\\S*)/.exec(stdout)?.[1]),\n ),\n );\n\n/** Whether these claude arguments pick a permission mode themselves. */\nconst picksPermissionMode = (args: readonly string[]) =>\n args.some(\n (arg) =>\n arg === \"--dangerously-skip-permissions\" ||\n arg === \"--permission-mode\" ||\n arg.startsWith(\"--permission-mode=\"),\n );\n\n/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */\nexport const skipsPermissions = (args: readonly string[]) =>\n args.some(\n (arg, i) =>\n arg === \"--dangerously-skip-permissions\" ||\n arg === \"--permission-mode=bypassPermissions\" ||\n (arg === \"bypassPermissions\" && args[i - 1] === \"--permission-mode\"),\n );\n\n/**\n * The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which\n * decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so\n * its channel loads with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude\n * Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).\n */\nexport const claudeArgs = (o: {\n start: Watchdog.Start;\n plugin: string;\n config: Harnessd.Config;\n extra: readonly string[];\n}) => [\n ...(picksPermissionMode([...o.config.args, ...o.extra])\n ? []\n : [\"--permission-mode\", \"auto\"]),\n \"--plugin-dir\",\n o.plugin,\n ...(o.config.channel.subscribe.length > 0\n ? [\"--dangerously-load-development-channels\", `plugin:${PLUGIN}`]\n : []),\n ...(o.start.resume\n ? [\"--resume\", o.start.sessionId]\n : [\"--session-id\", o.start.sessionId]),\n // before the config's arguments: after a list flag (--add-dir…) claude would take it as one more value\n ...(o.start.prompt ? [o.start.prompt] : []),\n ...o.config.args,\n ...o.extra,\n];\n\nexport type Prestart = { env: Record<string, string>; args: string[] };\n\n/** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */\nexport const prestart = (\n command: string,\n folder: string,\n env: NodeJS.ProcessEnv,\n log: (line: string) => void,\n) =>\n new Promise<Prestart>((resolve, reject) => {\n execFile(\n \"/bin/sh\",\n [\"-c\", command],\n { cwd: folder, env, timeout: 60_000, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n for (const line of stderr.split(\"\\n\"))\n if (line.trim()) log(`prestart: ${line}`);\n if (error)\n return reject(\n new Error(`prestart failed: ${error.message.split(\"\\n\")[0]}`),\n );\n if (!stdout.trim()) return resolve({ env: {}, args: [] });\n let parsed: unknown;\n try {\n parsed = JSON.parse(stdout);\n } catch {\n return reject(\n new Error(\n \"prestart printed something other than JSON { env?, args? }\",\n ),\n );\n }\n const {\n env: more = {},\n args = [],\n ...rest\n } = (parsed ?? {}) as { env?: unknown; args?: unknown };\n if (\n typeof parsed !== \"object\" ||\n Object.keys(rest).length > 0 ||\n typeof more !== \"object\" ||\n more === null ||\n Object.values(more).some((v) => typeof v !== \"string\") ||\n !Array.isArray(args) ||\n args.some((a) => typeof a !== \"string\")\n )\n return reject(\n new Error(\n \"prestart's JSON must be { env?: { NAME: string }, args?: string[] }\",\n ),\n );\n // harnessd finds the conversation before prestart runs, so where Claude Code keeps it comes from config.json\n if (\"CLAUDE_CONFIG_DIR\" in more)\n return reject(\n new Error(\n \"prestart can't set CLAUDE_CONFIG_DIR; set it in config.json's env\",\n ),\n );\n resolve({\n env: more as Record<string, string>,\n args: args as string[],\n });\n },\n );\n });\n"],"mappings":";;;;;;AAoBA,MAAa,SAAS;;AAGtB,MAAa,iBAAiB;AAE9B,MAAM,aAAa,QACjB,IAAI,qBAAqB,KAAK,QAAQ,GAAG,SAAS;;;;;;AAOpD,MAAa,eACX,QACA,MAAyB,QAAQ,QACrB;CACZ,MAAM,OAAO,IAAI,oBACb,KAAK,IAAI,mBAAmB,cAAc,IAC1C,KAAK,QAAQ,GAAG,cAAc;CAClC,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,MAAM,OAAO,aAAa,MAAM,MAAM;CACtC,MAAM,SAAS,KAAK,MAAM,IAAI;CAG9B,MAAM,MAAM,aAAa,MAAM;CAC/B,IAAI,OAAO,WAAW,IAAI,EAAE,2BAA2B,MAAM,OAAO;C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,CAAC,IAAI,CAC9D;EACF,IAAI,CAAC,OAAO,KAAK,GAAG,OAAO,QAAQ;GAAE,KAAK,CAAC;GAAG,MAAM,CAAC;EAAE,CAAC;EACxD,IAAI;EACJ,IAAI;GACF,SAAS,KAAK,MAAM,MAAM;EAC5B,QAAQ;GACN,OAAO,uBACL,IAAI,MACF,4DACF,CACF;EACF;EACA,MAAM,EACJ,KAAK,OAAO,CAAC,GACb,OAAO,CAAC,GACR,GAAG,SACA,UAAU,CAAC;EAChB,IACE,OAAO,WAAW,YAClB,OAAO,KAAK,IAAI,CAAC,CAAC,SAAS,KAC3B,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,OAAO,IAAI,CAAC,CAAC,MAAM,MAAM,OAAO,MAAM,QAAQ,KACrD,CAAC,MAAM,QAAQ,IAAI,KACnB,KAAK,MAAM,MAAM,OAAO,MAAM,QAAQ,GAEtC,OAAO,uBACL,IAAI,MACF,qEACF,CACF;EAEF,IAAI,uBAAuB,MACzB,OAAO,uBACL,IAAI,MACF,mEACF,CACF;EACF,QAAQ;GACN,KAAK;GACC;EACR,CAAC;CACH,CACF;AACF,CAAC"}
|
package/dist/cli.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AA+BA,OAAO,EAA6C,KAAK,KAAK,EAAE,mBAAgB;AA0ChF,KAAK,EAAE,GAAG;IACR,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,gEAAgE;IAChE,QAAQ,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;IACtC,uDAAuD;IACvD,KAAK,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;CAC/B,CAAC;AAwdF,4DAA4D;AAC5D,eAAO,MAAM,WAAW,GACtB,MAAM,SAAS,MAAM,EAAE,EACvB,KAAK,MAAM,EACX,KAAI,EAIH,KACA,OAAO,CAAC,MAAM,CAoBhB,CAAC"}
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { readStatus, serveChannel,
|
|
1
|
+
import { defaultConfig, ownFolder, pathsOf, readConfig } from "./config.js";
|
|
2
|
+
import { readStatus, serveChannel, serverCli, subscriptionLabel } from "./channel.js";
|
|
3
3
|
import { logTo } from "./log.js";
|
|
4
4
|
import { CHANNELS_REFUSED } from "./prompts.js";
|
|
5
5
|
import { ask, runDaemon } from "./daemon.js";
|
|
@@ -13,6 +13,7 @@ import { createConnection } from "node:net";
|
|
|
13
13
|
import { userInfo } from "node:os";
|
|
14
14
|
import { delimiter, dirname } from "node:path";
|
|
15
15
|
import { createInterface } from "node:readline";
|
|
16
|
+
import { processCliIo, runCli } from "toolport/cli";
|
|
16
17
|
// src/cli.ts
|
|
17
18
|
const USAGE = `harnessd keeps Claude Code running on this computer, connected to the events of your agentic apps.
|
|
18
19
|
|
|
@@ -20,10 +21,11 @@ usage: harnessd <command>
|
|
|
20
21
|
|
|
21
22
|
service install Start harnessd now and at every login; with sudo, at every boot
|
|
22
23
|
service uninstall Stop harnessd and remove its service
|
|
23
|
-
status [--json] What runs, which conversation,
|
|
24
|
+
status [--json] What runs, which conversation, the channel's events, and the log's last lines
|
|
24
25
|
start Start Claude Code after a stop
|
|
25
26
|
stop Stop Claude Code; harnessd stays up, and Claude Code stays stopped until start
|
|
26
27
|
attach Open Claude Code's terminal; Ctrl-\\ detaches
|
|
28
|
+
tools <server> ... Run a server's tools, as the agent's <server> command does
|
|
27
29
|
--version Print harnessd's version
|
|
28
30
|
|
|
29
31
|
service install takes:
|
|
@@ -187,7 +189,7 @@ const install = async (flags, bin, io) => {
|
|
|
187
189
|
const config = asUser(user, () => {
|
|
188
190
|
ownFolder(paths.home);
|
|
189
191
|
ownFolder(dirname(paths.config));
|
|
190
|
-
if (!existsSync(paths.config)) writeFileSync(paths.config, `${JSON.stringify(
|
|
192
|
+
if (!existsSync(paths.config)) writeFileSync(paths.config, `${JSON.stringify(defaultConfig(), null, 2)}\n`);
|
|
191
193
|
chmodSync(paths.config, 384);
|
|
192
194
|
appendFileSync(paths.serviceLog, "");
|
|
193
195
|
const config = readConfig(paths);
|
|
@@ -220,18 +222,25 @@ const ago = (iso) => {
|
|
|
220
222
|
const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1e3));
|
|
221
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`;
|
|
222
224
|
};
|
|
223
|
-
/**
|
|
224
|
-
const channelReport = (paths, config, running) =>
|
|
225
|
-
const
|
|
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);
|
|
226
230
|
const since = running?.state === "running" || running?.state === "starting" ? running.startedAt : void 0;
|
|
227
231
|
const now = (at) => since !== void 0 && at !== void 0 && at >= since;
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
...status
|
|
233
|
-
}
|
|
234
|
-
}
|
|
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
|
+
}]));
|
|
235
244
|
const status = async (paths, json, io) => {
|
|
236
245
|
const s = await daemonStatus(paths);
|
|
237
246
|
let config;
|
|
@@ -241,7 +250,8 @@ const status = async (paths, json, io) => {
|
|
|
241
250
|
} catch (error) {
|
|
242
251
|
configError = error instanceof Error ? error.message : String(error);
|
|
243
252
|
}
|
|
244
|
-
const
|
|
253
|
+
const channel = channelReport(paths, config, s);
|
|
254
|
+
const servers = serverReport(config);
|
|
245
255
|
const log = s || !existsSync(paths.serviceLog) ? paths.log : paths.serviceLog;
|
|
246
256
|
const logTail = tail(log, 10);
|
|
247
257
|
const code = s && !configError ? 0 : 1;
|
|
@@ -252,7 +262,8 @@ const status = async (paths, json, io) => {
|
|
|
252
262
|
config: paths.config,
|
|
253
263
|
...s && { status: s },
|
|
254
264
|
...configError && { configError },
|
|
255
|
-
|
|
265
|
+
servers,
|
|
266
|
+
...channel && { channel },
|
|
256
267
|
log,
|
|
257
268
|
logTail
|
|
258
269
|
}));
|
|
@@ -261,8 +272,9 @@ const status = async (paths, json, io) => {
|
|
|
261
272
|
if (!s) io.out(notRunning(paths));
|
|
262
273
|
else {
|
|
263
274
|
const since = s.startedAt ? ` for ${ago(s.startedAt)}` : "";
|
|
264
|
-
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";
|
|
265
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`);
|
|
266
278
|
if (s.account) io.out(`account ${s.account}`);
|
|
267
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()}`);
|
|
268
280
|
if (s.waitingOn) io.out(`Claude Code waits for an answer (${s.waitingOn}): harnessd attach, then answer it`);
|
|
@@ -270,8 +282,12 @@ const status = async (paths, json, io) => {
|
|
|
270
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` : ""}`);
|
|
271
283
|
}
|
|
272
284
|
if (configError) io.out(configError);
|
|
273
|
-
for (const [name,
|
|
274
|
-
if (
|
|
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);
|
|
275
291
|
io.out(`log ${log}`);
|
|
276
292
|
for (const line of logTail) io.out(` ${line}`);
|
|
277
293
|
return code;
|
|
@@ -331,7 +347,7 @@ const runHarnessd = async (argv, bin, io = {
|
|
|
331
347
|
terminal: ttyTerminal()
|
|
332
348
|
}) => {
|
|
333
349
|
const [first, ...rest] = argv;
|
|
334
|
-
if (first === void 0 || first === "help" || argv.some((arg) => arg === "--help" || arg === "-h")) {
|
|
350
|
+
if (first === void 0 || first === "help" || argv.slice(0, first === "tools" ? 2 : void 0).some((arg) => arg === "--help" || arg === "-h")) {
|
|
335
351
|
io.out(USAGE);
|
|
336
352
|
return 0;
|
|
337
353
|
}
|
|
@@ -393,17 +409,32 @@ const run = async (first, rest, bin, io) => {
|
|
|
393
409
|
io.err(answer ? String(answer.message) : notRunning(paths));
|
|
394
410
|
return 1;
|
|
395
411
|
}
|
|
396
|
-
case "
|
|
397
|
-
|
|
398
|
-
const
|
|
399
|
-
if (
|
|
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);
|
|
400
421
|
await serveChannel({
|
|
401
|
-
|
|
402
|
-
channel,
|
|
422
|
+
config: readConfig(paths),
|
|
403
423
|
paths,
|
|
404
|
-
log: logTo(paths.log,
|
|
424
|
+
log: logTo(paths.log, "channel: ")
|
|
405
425
|
});
|
|
406
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
|
+
});
|
|
407
438
|
}
|
|
408
439
|
default: throw usageError(`Unknown command ${first}.`);
|
|
409
440
|
}
|