@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/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport {\n appendFileSync,\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { createConnection } from \"node:net\";\nimport { userInfo } from \"node:os\";\nimport { delimiter, dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { readStatus, serveChannel, statusFile } from \"./channel\";\nimport {\n DEFAULT_CONFIG,\n ownFolder,\n pathsOf,\n readConfig,\n type Harnessd,\n} from \"./config\";\nimport { ask, runDaemon, type Daemon } from \"./daemon\";\nimport { stableNode } from \"./launchd\";\nimport { logTo } from \"./log\";\nimport { ensureClaude, ensureSignedIn, ttyTerminal, type Setup } from \"./setup\";\nimport { CHANNELS_REFUSED } from \"./prompts\";\nimport {\n asUser,\n installService,\n lookUpUser,\n removeService,\n serviceIn,\n servicePath,\n serviceText,\n supportedPlatform,\n type Service,\n} from \"./service\";\n\nconst USAGE = `harnessd keeps Claude Code running on this computer, connected to the events of your agentic apps.\n\nusage: harnessd <command>\n\n service install Start harnessd now and at every login; with sudo, at every boot\n service uninstall Stop harnessd and remove its service\n status [--json] What runs, which conversation, each channel's events, and the log's last lines\n start Start Claude Code after a stop\n stop Stop Claude Code; harnessd stays up, and Claude Code stays stopped until start\n attach Open Claude Code's terminal; Ctrl-\\\\ detaches\n --version Print harnessd's version\n\nservice install takes:\n --user <name> With sudo: the user the boot service runs as; service uninstall takes it too\n --dry-run Print the service's file and change nothing\n --install-claude When Claude Code is missing, install it with Anthropic's installer without asking\n --skip-sign-in Install even when Claude Code isn't signed in, and print how to sign in\n\nSettings: ~/.config/harnessd/config.json. State and log: ~/.local/state/harnessd.\nXDG_CONFIG_HOME and XDG_STATE_HOME move them; HARNESSD_HOME puts both in one folder.`;\n\nconst VERSION = (\n createRequire(import.meta.url)(\"../package.json\") as { version: string }\n).version;\n\nconst DETACH = \"\\x1c\";\n\ntype Io = {\n out: (line: string) => void;\n err: (line: string) => void;\n /** The person to ask; none when harnessd runs from a script. */\n terminal?: Setup.Terminal | undefined;\n /** What the command was given on stdin, for a hook. */\n stdin?: () => Promise<string>;\n};\n\nconst stdin = async () => {\n let text = \"\";\n for await (const chunk of process.stdin) text += String(chunk);\n return text;\n};\n\nconst notRunning = (paths: Harnessd.Paths) =>\n `harnessd isn't running in ${paths.home}: harnessd service install starts it.`;\n\nconst usageError = (message: string) =>\n Object.assign(new Error(message), { usage: true });\n\n/** Refuses any argument a command doesn't take, so a typo never runs the command. */\nconst takes = (\n command: string,\n rest: readonly string[],\n allowed: readonly string[] = [],\n) => {\n const extra = rest.find((arg) => !allowed.includes(arg));\n if (extra !== undefined)\n throw usageError(\n `harnessd ${command} takes ${allowed.length > 0 ? `only ${allowed.join(\", \")}` : \"no arguments\"}, not ${extra}.`,\n );\n};\n\nconst tail = (file: string, lines: number) => {\n try {\n const text = readFileSync(file, \"utf8\").trimEnd();\n return text ? text.split(\"\\n\").slice(-lines) : [];\n } catch {\n return [];\n }\n};\n\nconst daemonStatus = async (paths: Harnessd.Paths) =>\n (\n (await ask(paths.socket, { command: \"status\" })) as\n | { status?: Daemon.Status }\n | undefined\n )?.status;\n\nconst START_WAIT_MS = 90_000;\n\n/** Waits until Claude Code runs, was stopped by hand, or failed to start; `not` is the harnessd an install replaces. */\nconst settled = async (\n paths: Harnessd.Paths,\n not?: number,\n waitMs = START_WAIT_MS,\n) => {\n const until = Date.now() + waitMs;\n for (;;) {\n const status = await daemonStatus(paths);\n const ours = status && status.daemonPid !== not ? status : undefined;\n if ((ours && ours.state !== \"starting\") || Date.now() >= until) return ours;\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n};\n\n/** After a failed start: the log lines that show why; resolves to the exit code. */\nconst showLog = (log: string, io: Io) => {\n for (const line of tail(log, 10)) io.err(` ${line}`);\n io.err(`log ${log}`);\n return 1;\n};\n\n/** Says why a start failed, with the log's last lines; resolves to the exit code. */\nconst startFailed = (\n paths: Harnessd.Paths,\n status: Daemon.Status | undefined,\n io: Io,\n) => {\n io.err(\n !status\n ? \"harnessd didn't start.\"\n : status.state === \"waiting\"\n ? `Claude Code didn't stay up${status.lastExit ? ` (exit code ${status.lastExit.code})` : \"\"}; harnessd keeps trying.`\n : \"Claude Code is still starting; harnessd status shows how it goes.\",\n );\n return showLog(status ? paths.log : paths.serviceLog, io);\n};\n\nconst command = async (\n paths: Harnessd.Paths,\n request: Daemon.Request,\n io: Io,\n) => {\n const answer = await ask(paths.socket, request);\n if (!answer) {\n io.err(notRunning(paths));\n return 1;\n }\n if (!answer.ok) {\n io.err(String(answer.message));\n return request.command === \"stop\" ? 1 : showLog(paths.log, io);\n }\n if (request.command !== \"stop\") {\n const status = await settled(paths);\n if (status?.state !== \"running\") return startFailed(paths, status, io);\n }\n io.out(String(answer.message));\n return 0;\n};\n\ntype ServiceFlags = {\n user?: string;\n dryRun?: true;\n installClaude?: true;\n skipSignIn?: true;\n};\n\n/** Who the service is for: with sudo, a boot service that runs as the named user; without, your own login item. */\nconst serviceTarget = (action: string, flags: ServiceFlags) => {\n const root = process.getuid?.() === 0;\n if (flags.user !== undefined && !root && !flags.dryRun)\n throw new Error(\n `A boot service needs root: sudo harnessd service ${action} --user ${flags.user}`,\n );\n const name = flags.user ?? (root ? process.env.SUDO_USER : undefined);\n if (root && name === undefined)\n throw new Error(\"Name the user harnessd runs as: --user <name>\");\n const user = name === undefined ? undefined : lookUpUser(name);\n // another account's harnessd lives in that account's own folders, not where this shell's variables point\n const caller = process.env.SUDO_USER ?? userInfo().username;\n const moved = [\"HARNESSD_HOME\", \"XDG_CONFIG_HOME\", \"XDG_STATE_HOME\"].find(\n (key) => process.env[key],\n );\n if (user && user.name !== caller && moved)\n throw new Error(\n `${moved} is set in your shell, and --user ${user.name} installs in ${user.name}'s own folders: unset it, or let ${user.name} run the install.`,\n );\n // from here on every path is the user's, not root's\n if (user)\n Object.assign(process.env, {\n HOME: user.home,\n USER: user.name,\n LOGNAME: user.name,\n });\n const paths = pathsOf();\n // elsewhere, the socket's place depends on who asks and on their login session: root, the service and the user's commands would each look somewhere else\n if (user && !paths.socket.startsWith(paths.home))\n throw new Error(\n `${paths.home} is too long a path for harnessd's socket, and a boot service keeps its socket there: set a shorter XDG_STATE_HOME or HARNESSD_HOME.`,\n );\n // every user's default harnessd has the same label, and boot services share one namespace\n const bootLabel = (name: string) =>\n paths.label === \"dev.harnessd\" ? `dev.harnessd.${name}` : paths.label;\n return {\n user,\n paths,\n label: user ? bootLabel(user.name) : paths.label,\n /** The other kind's file, when one is installed for this state folder: it holds one harnessd. */\n other: () => serviceIn(paths.home, user === undefined),\n };\n};\n\nconst uninstall = (flags: ServiceFlags, io: Io) => {\n const { user, paths, label, other } = serviceTarget(\"uninstall\", flags);\n if (removeService(label, user !== undefined)) {\n io.out(\n `Removed harnessd's service. Its settings stay in ${paths.config}, its conversation in ${paths.home}.`,\n );\n return 0;\n }\n const file = other();\n io[file ? \"err\" : \"out\"](\n file\n ? `harnessd is installed as a ${user ? \"login item\" : \"boot service\"} (${file}): run ${user ? \"\" : \"sudo \"}harnessd service uninstall.`\n : \"harnessd wasn't installed.\",\n );\n return file ? 1 : 0;\n};\n\nconst install = async (flags: ServiceFlags, bin: string, io: Io) => {\n // before anything is written: an install that can't go on leaves nothing behind\n supportedPlatform();\n if (bin.includes(\"/_npx/\"))\n throw new Error(\n \"Install harnessd first, so the service has a lasting copy to start: npm install -g @harness-sdk/harnessd\",\n );\n const { user, paths, label, other } = serviceTarget(\"install\", flags);\n const own = (process.env.PATH ?? \"/usr/bin:/bin\").split(delimiter);\n const terminal = flags.dryRun ? undefined : io.terminal;\n // a dry run changes nothing, so it installs nothing either\n const claude = await ensureClaude({\n terminal,\n user,\n install: flags.installClaude && !flags.dryRun,\n });\n const version = spawnSync(claude, [\"--version\"], {\n encoding: \"utf8\",\n timeout: 30_000,\n ...(user && process.getuid?.() === 0 && { uid: user.uid, gid: user.gid }),\n });\n if (version.status !== 0)\n throw new Error(\n `${claude} --version failed: ${(version.stderr || version.stdout || \"\").trim()}`,\n );\n const node = stableNode();\n const spec: Service.Spec = {\n label,\n node,\n bin,\n env: {\n // sudo's PATH may hold neither claude nor node, which Claude Code's own tools start\n PATH: [...new Set([...own, dirname(claude), dirname(node)])]\n .filter((dir) => dir.startsWith(\"/\"))\n .join(delimiter),\n ...(user && { HOME: user.home, USER: user.name, LOGNAME: user.name }),\n ...paths.env,\n },\n paths,\n ...(user && { user: user.name }),\n };\n const file = servicePath(label, user !== undefined);\n if (flags.dryRun) {\n io.out(\n `Would write ${file} and start it${user ? `, as root, to run as ${user.name} from every boot` : \"\"}:\\n\\n${serviceText(spec)}`,\n );\n return 0;\n }\n const taken = other();\n if (taken)\n throw new Error(\n `harnessd is already installed as a ${user ? \"login item\" : \"boot service\"} (${taken}): run ${user ? \"\" : \"sudo \"}harnessd service uninstall first.`,\n );\n const config = asUser(user, () => {\n ownFolder(paths.home);\n ownFolder(dirname(paths.config));\n if (!existsSync(paths.config))\n writeFileSync(\n paths.config,\n `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\\n`,\n );\n chmodSync(paths.config, 0o600);\n // the user's own file before a boot service's manager, as root, makes it: a later login item has to append to it\n appendFileSync(paths.serviceLog, \"\");\n const config = readConfig(paths);\n mkdirSync(config.folder, { recursive: true });\n return config;\n });\n const signIn = await ensureSignedIn({\n claude,\n paths,\n env: spec.env,\n user,\n terminal,\n skip: flags.skipSignIn,\n });\n\n const before = (await daemonStatus(paths))?.daemonPid;\n await installService(spec);\n const status = await settled(paths, before);\n if (status?.state !== \"running\" && status?.state !== \"stopped\")\n return startFailed(paths, status, io);\n const when = user ? `at every boot, as ${user.name}` : \"at every login\";\n io.out(\n [\n status.state === \"stopped\"\n ? `harnessd is installed for ${config.folder} and starts ${when}. Claude Code is stopped: harnessd start starts it.`\n : `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and ${when}.`,\n \" harnessd attach its terminal; Ctrl-\\\\ detaches\",\n \" harnessd status what runs and whether events arrive\",\n ...(signIn ? [signIn] : []),\n ...(user\n ? []\n : [\n process.platform === \"darwin\"\n ? \"It starts when you log in: turn on automatic login (System Settings > Users & Groups), so it comes back after a power cut.\"\n : \"It starts when you sign in and stops when you sign out.\",\n `For a start at boot, with nobody logged in: harnessd service uninstall, then ${process.platform === \"darwin\" ? \"sudo harnessd\" : 'sudo env \"PATH=$PATH\" harnessd'} service install`,\n ]),\n ].join(\"\\n\"),\n );\n return 0;\n};\n\nconst ago = (iso: string) => {\n const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1000));\n return s < 120\n ? `${s}s`\n : s < 7200\n ? `${Math.round(s / 60)}m`\n : s < 172_800\n ? `${Math.round(s / 3600)}h`\n : `${Math.round(s / 86_400)}d`;\n};\n\n/** Each channel as of the Claude Code that runs now: what an earlier run heard says nothing about this one. */\nconst channelReport = (\n paths: Harnessd.Paths,\n config: Harnessd.Config | undefined,\n running: Daemon.Status | undefined,\n) =>\n Object.fromEntries(\n Object.entries(config?.channels ?? {}).map(([name, channel]) => {\n const status = readStatus(statusFile(paths, name));\n const since =\n running?.state === \"running\" || running?.state === \"starting\"\n ? running.startedAt\n : undefined;\n const now = (at: string | undefined) =>\n since !== undefined && at !== undefined && at >= since;\n const events =\n since === undefined\n ? \"off (Claude Code isn't running)\"\n : running?.channelsRefused\n ? \"refused\"\n : now(status.heardAt)\n ? \"arriving\"\n : now(status.pushedAt)\n ? \"sent, not in the conversation yet\"\n : \"none yet\";\n return [\n name,\n {\n url: channel.url,\n events,\n ...status,\n },\n ];\n }),\n );\n\nconst status = async (paths: Harnessd.Paths, json: boolean, io: Io) => {\n const s = await daemonStatus(paths);\n let config: Harnessd.Config | undefined;\n let configError: string | undefined;\n try {\n config = readConfig(paths);\n } catch (error) {\n configError = error instanceof Error ? error.message : String(error);\n }\n const channels = channelReport(paths, config, s);\n // without a harnessd to ask, the service's own output says why\n const log = s || !existsSync(paths.serviceLog) ? paths.log : paths.serviceLog;\n const logTail = tail(log, 10);\n const code = s && !configError ? 0 : 1;\n if (json) {\n io.out(\n JSON.stringify({\n running: !!s,\n home: paths.home,\n config: paths.config,\n ...(s && { status: s }),\n ...(configError && { configError }),\n channels,\n log,\n logTail,\n }),\n );\n return code;\n }\n if (!s) io.out(notRunning(paths));\n else {\n const since = s.startedAt ? ` for ${ago(s.startedAt)}` : \"\";\n const what =\n s.state === \"running\"\n ? `Claude Code running${since} (pid ${s.pid})`\n : s.state === \"waiting\"\n ? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1000))}s` : \"\"}`\n : s.state === \"stopped\"\n ? \"Claude Code stopped (harnessd start starts it)\"\n : \"Claude Code starting\";\n io.out(`harnessd ${s.daemonPid}: ${what}`);\n if (s.account) io.out(`account ${s.account}`);\n for (const [name, stop] of Object.entries(s.accountsStopped ?? {}))\n io.out(\n `account ${name} stopped at ${stop.why}; harnessd tries it again after ${new Date(stop.until).toLocaleString()}`,\n );\n if (s.waitingOn)\n io.out(\n `Claude Code waits for an answer (${s.waitingOn}): harnessd attach, then answer it`,\n );\n if (s.sessionId)\n io.out(`conversation ${s.sessionId}${s.folder ? ` in ${s.folder}` : \"\"}`);\n if (s.restarts > 0 || s.lastExit)\n io.out(\n `restarts ${s.restarts}${s.lastExit ? `, last exit code ${s.lastExit.code} ${ago(s.lastExit.at)} ago` : \"\"}`,\n );\n }\n if (configError) io.out(configError);\n for (const [name, channel] of Object.entries(channels))\n io.out(`channel ${name}: events ${channel.events} (${channel.url})`);\n if (s?.channelsRefused && Object.keys(channels).length > 0)\n io.out(CHANNELS_REFUSED);\n io.out(`log ${log}`);\n for (const line of logTail) io.out(` ${line}`);\n return code;\n};\n\nconst attach = (paths: Harnessd.Paths, io: Io) =>\n new Promise<number>((resolve) => {\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n io.err(\"harnessd attach needs a terminal.\");\n return resolve(1);\n }\n const connection = createConnection(paths.socket);\n const send = (value: unknown) =>\n connection.write(`${JSON.stringify(value)}\\n`);\n const onResize = () =>\n send({\n resize: { cols: process.stdout.columns, rows: process.stdout.rows },\n });\n const onInput = (data: Buffer) => {\n const text = data.toString(\"utf8\");\n if (text.includes(DETACH)) connection.end();\n else send({ input: text });\n };\n let done = false;\n const finish = (code: number, line?: string) => {\n if (done) return;\n done = true;\n process.stdin.setRawMode(false);\n process.stdin.off(\"data\", onInput);\n process.stdin.pause();\n process.stdout.off(\"resize\", onResize);\n process.stdout.write(\"\\x1b[0m\\r\\n\");\n if (line) io.err(line);\n resolve(code);\n };\n connection.once(\"error\", () => finish(1, notRunning(paths)));\n connection.once(\"connect\", () => {\n send({\n command: \"attach\",\n cols: process.stdout.columns,\n rows: process.stdout.rows,\n });\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.on(\"data\", onInput);\n process.stdout.on(\"resize\", onResize);\n createInterface({ input: connection })\n .on(\"error\", () => {})\n .on(\"line\", (line) => {\n try {\n const message = JSON.parse(line) as { output?: string };\n if (typeof message.output === \"string\")\n process.stdout.write(message.output);\n } catch {}\n });\n });\n connection.once(\"close\", () =>\n finish(0, \"Detached; Claude Code keeps running.\"),\n );\n });\n\n/** Runs one harnessd command; resolves to the exit code. */\nexport const runHarnessd = async (\n argv: readonly string[],\n bin: string,\n io: Io = {\n out: (line) => void process.stdout.write(`${line}\\n`),\n err: (line) => void process.stderr.write(`${line}\\n`),\n terminal: ttyTerminal(),\n },\n): Promise<number> => {\n const [first, ...rest] = argv;\n if (\n first === undefined ||\n first === \"help\" ||\n argv.some((arg) => arg === \"--help\" || arg === \"-h\")\n ) {\n io.out(USAGE);\n return 0;\n }\n try {\n return await run(first, rest, bin, io);\n } catch (error) {\n if (!(error as { usage?: boolean }).usage) throw error;\n io.err(`${(error as Error).message} harnessd --help lists the commands.`);\n return 2;\n }\n};\n\nconst service = (rest: readonly string[], bin: string, io: Io) => {\n const [action, ...more] = rest;\n if (action !== \"install\" && action !== \"uninstall\")\n throw usageError(\"harnessd service takes install or uninstall.\");\n const flags: ServiceFlags = {};\n for (let i = 0; i < more.length; i++) {\n const arg = more[i]!;\n if (action === \"install\" && arg === \"--dry-run\") flags.dryRun = true;\n else if (action === \"install\" && arg === \"--install-claude\")\n flags.installClaude = true;\n else if (action === \"install\" && arg === \"--skip-sign-in\")\n flags.skipSignIn = true;\n else if (arg === \"--user\" && more[i + 1] !== undefined)\n flags.user = more[++i]!;\n else\n throw usageError(\n `harnessd service ${action} takes ${action === \"install\" ? \"--user <name>, --dry-run, --install-claude and --skip-sign-in\" : \"--user <name>\"}, not ${arg}.`,\n );\n }\n return action === \"install\" ? install(flags, bin, io) : uninstall(flags, io);\n};\n\nconst run = async (\n first: string,\n rest: readonly string[],\n bin: string,\n io: Io,\n): Promise<number> => {\n if (first === \"--version\") {\n takes(first, rest);\n io.out(VERSION);\n return 0;\n }\n if (first === \"service\") return service(rest, bin, io);\n const paths = pathsOf();\n switch (first) {\n case \"status\":\n takes(first, rest, [\"--json\"]);\n return status(paths, rest.includes(\"--json\"), io);\n case \"start\":\n case \"stop\":\n takes(first, rest);\n return command(paths, { command: first }, io);\n case \"attach\":\n takes(first, rest);\n return attach(paths, io);\n case \"run\":\n takes(first, rest);\n await runDaemon(paths, bin);\n return 0;\n case \"session-start\": {\n takes(first, rest);\n const input = JSON.parse(await (io.stdin ?? stdin)()) as {\n session_id?: unknown;\n agent_id?: unknown;\n };\n // a subagent's start, not the conversation's\n if (input.agent_id !== undefined) return 0;\n if (typeof input.session_id !== \"string\")\n throw new Error(\"Claude Code's SessionStart input has no session_id.\");\n const answer = await ask(paths.socket, {\n command: \"session-start\",\n sessionId: input.session_id,\n });\n if (answer?.ok) return 0;\n io.err(answer ? String(answer.message) : notRunning(paths));\n return 1;\n }\n case \"channel\": {\n const name = rest[0] ?? \"\";\n const channel = readConfig(paths).channels[name];\n if (!channel) throw new Error(`No channel \"${name}\" in ${paths.config}`);\n await serveChannel({\n name,\n channel,\n paths,\n log: logTo(paths.log, `channel ${name}: `),\n });\n return 0;\n }\n default:\n throw usageError(`Unknown command ${first}.`);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAuCA,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;AAqBd,MAAM,UACJ,cAAc,YAAY,GAAG,CAAC,CAAC,iBAAiB,CAAC,CACjD;AAEF,MAAM,SAAS;AAWf,MAAM,QAAQ,YAAY;CACxB,IAAI,OAAO;CACX,WAAW,MAAM,SAAS,QAAQ,OAAO,QAAQ,OAAO,KAAK;CAC7D,OAAO;AACT;AAEA,MAAM,cAAc,UAClB,6BAA6B,MAAM,KAAK;AAE1C,MAAM,cAAc,YAClB,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,EAAE,OAAO,KAAK,CAAC;;AAGnD,MAAM,SACJ,SACA,MACA,UAA6B,CAAC,MAC3B;CACH,MAAM,QAAQ,KAAK,MAAM,QAAQ,CAAC,QAAQ,SAAS,GAAG,CAAC;CACvD,IAAI,UAAU,KAAA,GACZ,MAAM,WACJ,YAAY,QAAQ,SAAS,QAAQ,SAAS,IAAI,QAAQ,QAAQ,KAAK,IAAI,MAAM,eAAe,QAAQ,MAAM,EAChH;AACJ;AAEA,MAAM,QAAQ,MAAc,UAAkB;CAC5C,IAAI;EACF,MAAM,OAAO,aAAa,MAAM,MAAM,CAAC,CAAC,QAAQ;EAChD,OAAO,OAAO,KAAK,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,IAAI,CAAC;CAClD,QAAQ;EACN,OAAO,CAAC;CACV;AACF;AAEA,MAAM,eAAe,OAAO,WAEvB,MAAM,IAAI,MAAM,QAAQ,EAAE,SAAS,SAAS,CAAC,EAAA,EAG7C;AA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O,OAAO,OAAO,EAAE;EACzB,KAAK;GACH,MAAM,OAAO,IAAI;GACjB,MAAM,UAAU,OAAO,GAAG;GAC1B,OAAO;EACT,KAAK,iBAAiB;GACpB,MAAM,OAAO,IAAI;GACjB,MAAM,QAAQ,KAAK,MAAM,OAAO,GAAG,SAAS,MAAA,CAAO,CAAC;GAKpD,IAAI,MAAM,aAAa,KAAA,GAAW,OAAO;GACzC,IAAI,OAAO,MAAM,eAAe,UAC9B,MAAM,IAAI,MAAM,qDAAqD;GACvE,MAAM,SAAS,MAAM,IAAI,MAAM,QAAQ;IACrC,SAAS;IACT,WAAW,MAAM;GACnB,CAAC;GACD,IAAI,QAAQ,IAAI,OAAO;GACvB,GAAG,IAAI,SAAS,OAAO,OAAO,OAAO,IAAI,WAAW,KAAK,CAAC;GAC1D,OAAO;EACT;EACA,KAAK,WAAW;GACd,MAAM,OAAO,KAAK,MAAM;GACxB,MAAM,UAAU,WAAW,KAAK,CAAC,CAAC,SAAS;GAC3C,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,eAAe,KAAK,OAAO,MAAM,QAAQ;GACvE,MAAM,aAAa;IACjB;IACA;IACA;IACA,KAAK,MAAM,MAAM,KAAK,WAAW,KAAK,GAAG;GAC3C,CAAC;GACD,OAAO;EACT;EACA,SACE,MAAM,WAAW,mBAAmB,MAAM,EAAE;CAChD;AACF"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { spawnSync } from \"node:child_process\";\nimport {\n appendFileSync,\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { createConnection } from \"node:net\";\nimport { userInfo } from \"node:os\";\nimport { delimiter, dirname } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport { processCliIo, runCli } from \"toolport/cli\";\nimport {\n readStatus,\n serveChannel,\n serverCli,\n subscriptionLabel,\n} from \"./channel\";\nimport {\n defaultConfig,\n ownFolder,\n pathsOf,\n readConfig,\n type Harnessd,\n} from \"./config\";\nimport { ask, runDaemon, type Daemon } from \"./daemon\";\nimport { stableNode } from \"./launchd\";\nimport { logTo } from \"./log\";\nimport { ensureClaude, ensureSignedIn, ttyTerminal, type Setup } from \"./setup\";\nimport { CHANNELS_REFUSED } from \"./prompts\";\nimport {\n asUser,\n installService,\n lookUpUser,\n removeService,\n serviceIn,\n servicePath,\n serviceText,\n supportedPlatform,\n type Service,\n} from \"./service\";\n\nconst USAGE = `harnessd keeps Claude Code running on this computer, connected to the events of your agentic apps.\n\nusage: harnessd <command>\n\n service install Start harnessd now and at every login; with sudo, at every boot\n service uninstall Stop harnessd and remove its service\n status [--json] What runs, which conversation, the channel's events, and the log's last lines\n start Start Claude Code after a stop\n stop Stop Claude Code; harnessd stays up, and Claude Code stays stopped until start\n attach Open Claude Code's terminal; Ctrl-\\\\ detaches\n tools <server> ... Run a server's tools, as the agent's <server> command does\n --version Print harnessd's version\n\nservice install takes:\n --user <name> With sudo: the user the boot service runs as; service uninstall takes it too\n --dry-run Print the service's file and change nothing\n --install-claude When Claude Code is missing, install it with Anthropic's installer without asking\n --skip-sign-in Install even when Claude Code isn't signed in, and print how to sign in\n\nSettings: ~/.config/harnessd/config.json. State and log: ~/.local/state/harnessd.\nXDG_CONFIG_HOME and XDG_STATE_HOME move them; HARNESSD_HOME puts both in one folder.`;\n\nconst VERSION = (\n createRequire(import.meta.url)(\"../package.json\") as { version: string }\n).version;\n\nconst DETACH = \"\\x1c\";\n\ntype Io = {\n out: (line: string) => void;\n err: (line: string) => void;\n /** The person to ask; none when harnessd runs from a script. */\n terminal?: Setup.Terminal | undefined;\n /** What the command was given on stdin, for a hook. */\n stdin?: () => Promise<string>;\n};\n\nconst stdin = async () => {\n let text = \"\";\n for await (const chunk of process.stdin) text += String(chunk);\n return text;\n};\n\nconst notRunning = (paths: Harnessd.Paths) =>\n `harnessd isn't running in ${paths.home}: harnessd service install starts it.`;\n\nconst usageError = (message: string) =>\n Object.assign(new Error(message), { usage: true });\n\n/** Refuses any argument a command doesn't take, so a typo never runs the command. */\nconst takes = (\n command: string,\n rest: readonly string[],\n allowed: readonly string[] = [],\n) => {\n const extra = rest.find((arg) => !allowed.includes(arg));\n if (extra !== undefined)\n throw usageError(\n `harnessd ${command} takes ${allowed.length > 0 ? `only ${allowed.join(\", \")}` : \"no arguments\"}, not ${extra}.`,\n );\n};\n\nconst tail = (file: string, lines: number) => {\n try {\n const text = readFileSync(file, \"utf8\").trimEnd();\n return text ? text.split(\"\\n\").slice(-lines) : [];\n } catch {\n return [];\n }\n};\n\nconst daemonStatus = async (paths: Harnessd.Paths) =>\n (\n (await ask(paths.socket, { command: \"status\" })) as\n | { status?: Daemon.Status }\n | undefined\n )?.status;\n\nconst START_WAIT_MS = 90_000;\n\n/** Waits until Claude Code runs, was stopped by hand, or failed to start; `not` is the harnessd an install replaces. */\nconst settled = async (\n paths: Harnessd.Paths,\n not?: number,\n waitMs = START_WAIT_MS,\n) => {\n const until = Date.now() + waitMs;\n for (;;) {\n const status = await daemonStatus(paths);\n const ours = status && status.daemonPid !== not ? status : undefined;\n if ((ours && ours.state !== \"starting\") || Date.now() >= until) return ours;\n await new Promise((resolve) => setTimeout(resolve, 250));\n }\n};\n\n/** After a failed start: the log lines that show why; resolves to the exit code. */\nconst showLog = (log: string, io: Io) => {\n for (const line of tail(log, 10)) io.err(` ${line}`);\n io.err(`log ${log}`);\n return 1;\n};\n\n/** Says why a start failed, with the log's last lines; resolves to the exit code. */\nconst startFailed = (\n paths: Harnessd.Paths,\n status: Daemon.Status | undefined,\n io: Io,\n) => {\n io.err(\n !status\n ? \"harnessd didn't start.\"\n : status.state === \"waiting\"\n ? `Claude Code didn't stay up${status.lastExit ? ` (exit code ${status.lastExit.code})` : \"\"}; harnessd keeps trying.`\n : \"Claude Code is still starting; harnessd status shows how it goes.\",\n );\n return showLog(status ? paths.log : paths.serviceLog, io);\n};\n\nconst command = async (\n paths: Harnessd.Paths,\n request: Daemon.Request,\n io: Io,\n) => {\n const answer = await ask(paths.socket, request);\n if (!answer) {\n io.err(notRunning(paths));\n return 1;\n }\n if (!answer.ok) {\n io.err(String(answer.message));\n return request.command === \"stop\" ? 1 : showLog(paths.log, io);\n }\n if (request.command !== \"stop\") {\n const status = await settled(paths);\n if (status?.state !== \"running\") return startFailed(paths, status, io);\n }\n io.out(String(answer.message));\n return 0;\n};\n\ntype ServiceFlags = {\n user?: string;\n dryRun?: true;\n installClaude?: true;\n skipSignIn?: true;\n};\n\n/** Who the service is for: with sudo, a boot service that runs as the named user; without, your own login item. */\nconst serviceTarget = (action: string, flags: ServiceFlags) => {\n const root = process.getuid?.() === 0;\n if (flags.user !== undefined && !root && !flags.dryRun)\n throw new Error(\n `A boot service needs root: sudo harnessd service ${action} --user ${flags.user}`,\n );\n const name = flags.user ?? (root ? process.env.SUDO_USER : undefined);\n if (root && name === undefined)\n throw new Error(\"Name the user harnessd runs as: --user <name>\");\n const user = name === undefined ? undefined : lookUpUser(name);\n // another account's harnessd lives in that account's own folders, not where this shell's variables point\n const caller = process.env.SUDO_USER ?? userInfo().username;\n const moved = [\"HARNESSD_HOME\", \"XDG_CONFIG_HOME\", \"XDG_STATE_HOME\"].find(\n (key) => process.env[key],\n );\n if (user && user.name !== caller && moved)\n throw new Error(\n `${moved} is set in your shell, and --user ${user.name} installs in ${user.name}'s own folders: unset it, or let ${user.name} run the install.`,\n );\n // from here on every path is the user's, not root's\n if (user)\n Object.assign(process.env, {\n HOME: user.home,\n USER: user.name,\n LOGNAME: user.name,\n });\n const paths = pathsOf();\n // elsewhere, the socket's place depends on who asks and on their login session: root, the service and the user's commands would each look somewhere else\n if (user && !paths.socket.startsWith(paths.home))\n throw new Error(\n `${paths.home} is too long a path for harnessd's socket, and a boot service keeps its socket there: set a shorter XDG_STATE_HOME or HARNESSD_HOME.`,\n );\n // every user's default harnessd has the same label, and boot services share one namespace\n const bootLabel = (name: string) =>\n paths.label === \"dev.harnessd\" ? `dev.harnessd.${name}` : paths.label;\n return {\n user,\n paths,\n label: user ? bootLabel(user.name) : paths.label,\n /** The other kind's file, when one is installed for this state folder: it holds one harnessd. */\n other: () => serviceIn(paths.home, user === undefined),\n };\n};\n\nconst uninstall = (flags: ServiceFlags, io: Io) => {\n const { user, paths, label, other } = serviceTarget(\"uninstall\", flags);\n if (removeService(label, user !== undefined)) {\n io.out(\n `Removed harnessd's service. Its settings stay in ${paths.config}, its conversation in ${paths.home}.`,\n );\n return 0;\n }\n const file = other();\n io[file ? \"err\" : \"out\"](\n file\n ? `harnessd is installed as a ${user ? \"login item\" : \"boot service\"} (${file}): run ${user ? \"\" : \"sudo \"}harnessd service uninstall.`\n : \"harnessd wasn't installed.\",\n );\n return file ? 1 : 0;\n};\n\nconst install = async (flags: ServiceFlags, bin: string, io: Io) => {\n // before anything is written: an install that can't go on leaves nothing behind\n supportedPlatform();\n if (bin.includes(\"/_npx/\"))\n throw new Error(\n \"Install harnessd first, so the service has a lasting copy to start: npm install -g @harness-sdk/harnessd\",\n );\n const { user, paths, label, other } = serviceTarget(\"install\", flags);\n const own = (process.env.PATH ?? \"/usr/bin:/bin\").split(delimiter);\n const terminal = flags.dryRun ? undefined : io.terminal;\n // a dry run changes nothing, so it installs nothing either\n const claude = await ensureClaude({\n terminal,\n user,\n install: flags.installClaude && !flags.dryRun,\n });\n const version = spawnSync(claude, [\"--version\"], {\n encoding: \"utf8\",\n timeout: 30_000,\n ...(user && process.getuid?.() === 0 && { uid: user.uid, gid: user.gid }),\n });\n if (version.status !== 0)\n throw new Error(\n `${claude} --version failed: ${(version.stderr || version.stdout || \"\").trim()}`,\n );\n const node = stableNode();\n const spec: Service.Spec = {\n label,\n node,\n bin,\n env: {\n // sudo's PATH may hold neither claude nor node, which Claude Code's own tools start\n PATH: [...new Set([...own, dirname(claude), dirname(node)])]\n .filter((dir) => dir.startsWith(\"/\"))\n .join(delimiter),\n ...(user && { HOME: user.home, USER: user.name, LOGNAME: user.name }),\n ...paths.env,\n },\n paths,\n ...(user && { user: user.name }),\n };\n const file = servicePath(label, user !== undefined);\n if (flags.dryRun) {\n io.out(\n `Would write ${file} and start it${user ? `, as root, to run as ${user.name} from every boot` : \"\"}:\\n\\n${serviceText(spec)}`,\n );\n return 0;\n }\n const taken = other();\n if (taken)\n throw new Error(\n `harnessd is already installed as a ${user ? \"login item\" : \"boot service\"} (${taken}): run ${user ? \"\" : \"sudo \"}harnessd service uninstall first.`,\n );\n const config = asUser(user, () => {\n ownFolder(paths.home);\n ownFolder(dirname(paths.config));\n if (!existsSync(paths.config))\n writeFileSync(\n paths.config,\n `${JSON.stringify(defaultConfig(), null, 2)}\\n`,\n );\n chmodSync(paths.config, 0o600);\n // the user's own file before a boot service's manager, as root, makes it: a later login item has to append to it\n appendFileSync(paths.serviceLog, \"\");\n const config = readConfig(paths);\n mkdirSync(config.folder, { recursive: true });\n return config;\n });\n const signIn = await ensureSignedIn({\n claude,\n paths,\n env: spec.env,\n user,\n terminal,\n skip: flags.skipSignIn,\n });\n\n const before = (await daemonStatus(paths))?.daemonPid;\n await installService(spec);\n const status = await settled(paths, before);\n if (status?.state !== \"running\" && status?.state !== \"stopped\")\n return startFailed(paths, status, io);\n const when = user ? `at every boot, as ${user.name}` : \"at every login\";\n io.out(\n [\n status.state === \"stopped\"\n ? `harnessd is installed for ${config.folder} and starts ${when}. Claude Code is stopped: harnessd start starts it.`\n : `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and ${when}.`,\n \" harnessd attach its terminal; Ctrl-\\\\ detaches\",\n \" harnessd status what runs and whether events arrive\",\n ...(signIn ? [signIn] : []),\n ...(user\n ? []\n : [\n process.platform === \"darwin\"\n ? \"It starts when you log in: turn on automatic login (System Settings > Users & Groups), so it comes back after a power cut.\"\n : \"It starts when you sign in and stops when you sign out.\",\n `For a start at boot, with nobody logged in: harnessd service uninstall, then ${process.platform === \"darwin\" ? \"sudo harnessd\" : 'sudo env \"PATH=$PATH\" harnessd'} service install`,\n ]),\n ].join(\"\\n\"),\n );\n return 0;\n};\n\nconst ago = (iso: string) => {\n const s = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 1000));\n return s < 120\n ? `${s}s`\n : s < 7200\n ? `${Math.round(s / 60)}m`\n : s < 172_800\n ? `${Math.round(s / 3600)}h`\n : `${Math.round(s / 86_400)}d`;\n};\n\n/** The channel as of the Claude Code that runs now (what an earlier run heard says nothing about this one); none without subscriptions. */\nconst channelReport = (\n paths: Harnessd.Paths,\n config: Harnessd.Config | undefined,\n running: Daemon.Status | undefined,\n) => {\n const subscribe = config?.channel.subscribe ?? [];\n if (subscribe.length === 0) return undefined;\n const status = readStatus(paths.channel);\n const since =\n running?.state === \"running\" || running?.state === \"starting\"\n ? running.startedAt\n : undefined;\n const now = (at: string | undefined) =>\n since !== undefined && at !== undefined && at >= since;\n const events =\n since === undefined\n ? \"off (Claude Code isn't running)\"\n : running?.channelsRefused\n ? \"refused\"\n : now(status.heardAt)\n ? \"arriving\"\n : now(status.pushedAt)\n ? \"sent, not in the conversation yet\"\n : \"none yet\";\n return {\n events,\n subscribe: subscribe.map(subscriptionLabel),\n ...(status.pushedAt && { pushedAt: status.pushedAt }),\n ...(status.heardAt && { heardAt: status.heardAt }),\n };\n};\n\n/** Each server: its URL, and the events the channel takes from it. */\nconst serverReport = (config: Harnessd.Config | undefined) =>\n Object.fromEntries(\n Object.entries(config?.servers ?? {}).map(([name, server]) => [\n name,\n {\n url: server.url,\n events: config!.channel.subscribe\n .filter((subscription) => subscription.server === name)\n .map((subscription) => subscription.event),\n },\n ]),\n );\n\nconst status = async (paths: Harnessd.Paths, json: boolean, io: Io) => {\n const s = await daemonStatus(paths);\n let config: Harnessd.Config | undefined;\n let configError: string | undefined;\n try {\n config = readConfig(paths);\n } catch (error) {\n configError = error instanceof Error ? error.message : String(error);\n }\n const channel = channelReport(paths, config, s);\n const servers = serverReport(config);\n // without a harnessd to ask, the service's own output says why\n const log = s || !existsSync(paths.serviceLog) ? paths.log : paths.serviceLog;\n const logTail = tail(log, 10);\n const code = s && !configError ? 0 : 1;\n if (json) {\n io.out(\n JSON.stringify({\n running: !!s,\n home: paths.home,\n config: paths.config,\n ...(s && { status: s }),\n ...(configError && { configError }),\n servers,\n ...(channel && { channel }),\n log,\n logTail,\n }),\n );\n return code;\n }\n if (!s) io.out(notRunning(paths));\n else {\n const since = s.startedAt ? ` for ${ago(s.startedAt)}` : \"\";\n const what =\n s.state === \"running\"\n ? `Claude Code${s.claudeVersion ? ` ${s.claudeVersion}` : \"\"} running${since} (pid ${s.pid})`\n : s.state === \"waiting\"\n ? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1000))}s` : \"\"}`\n : s.state === \"stopped\"\n ? \"Claude Code stopped (harnessd start starts it)\"\n : \"Claude Code starting\";\n io.out(`harnessd ${s.daemonPid}: ${what}`);\n if (s.update)\n io.out(\n s.update.at\n ? `updated from Claude Code ${s.update.from} to ${s.update.to} ${ago(s.update.at)} ago`\n : `Claude Code ${s.update.to} is installed; harnessd restarts into it once the agent is idle`,\n );\n if (s.account) io.out(`account ${s.account}`);\n for (const [name, stop] of Object.entries(s.accountsStopped ?? {}))\n io.out(\n `account ${name} stopped at ${stop.why}; harnessd tries it again after ${new Date(stop.until).toLocaleString()}`,\n );\n if (s.waitingOn)\n io.out(\n `Claude Code waits for an answer (${s.waitingOn}): harnessd attach, then answer it`,\n );\n if (s.sessionId)\n io.out(`conversation ${s.sessionId}${s.folder ? ` in ${s.folder}` : \"\"}`);\n if (s.restarts > 0 || s.lastExit)\n io.out(\n `restarts ${s.restarts}${s.lastExit ? `, last exit code ${s.lastExit.code} ${ago(s.lastExit.at)} ago` : \"\"}`,\n );\n }\n if (configError) io.out(configError);\n for (const [name, server] of Object.entries(servers))\n io.out(\n `server ${name}: the ${name} command, ${server.events.length > 0 ? `events ${server.events.join(\", \")}` : \"no events subscribed\"} (${server.url})`,\n );\n if (channel) {\n io.out(`channel: events ${channel.events}`);\n for (const label of channel.subscribe) io.out(` ${label}`);\n }\n if (s?.channelsRefused && channel) io.out(CHANNELS_REFUSED);\n io.out(`log ${log}`);\n for (const line of logTail) io.out(` ${line}`);\n return code;\n};\n\nconst attach = (paths: Harnessd.Paths, io: Io) =>\n new Promise<number>((resolve) => {\n if (!process.stdin.isTTY || !process.stdout.isTTY) {\n io.err(\"harnessd attach needs a terminal.\");\n return resolve(1);\n }\n const connection = createConnection(paths.socket);\n const send = (value: unknown) =>\n connection.write(`${JSON.stringify(value)}\\n`);\n const onResize = () =>\n send({\n resize: { cols: process.stdout.columns, rows: process.stdout.rows },\n });\n const onInput = (data: Buffer) => {\n const text = data.toString(\"utf8\");\n if (text.includes(DETACH)) connection.end();\n else send({ input: text });\n };\n let done = false;\n const finish = (code: number, line?: string) => {\n if (done) return;\n done = true;\n process.stdin.setRawMode(false);\n process.stdin.off(\"data\", onInput);\n process.stdin.pause();\n process.stdout.off(\"resize\", onResize);\n process.stdout.write(\"\\x1b[0m\\r\\n\");\n if (line) io.err(line);\n resolve(code);\n };\n connection.once(\"error\", () => finish(1, notRunning(paths)));\n connection.once(\"connect\", () => {\n send({\n command: \"attach\",\n cols: process.stdout.columns,\n rows: process.stdout.rows,\n });\n process.stdin.setRawMode(true);\n process.stdin.resume();\n process.stdin.on(\"data\", onInput);\n process.stdout.on(\"resize\", onResize);\n createInterface({ input: connection })\n .on(\"error\", () => {})\n .on(\"line\", (line) => {\n try {\n const message = JSON.parse(line) as { output?: string };\n if (typeof message.output === \"string\")\n process.stdout.write(message.output);\n } catch {}\n });\n });\n connection.once(\"close\", () =>\n finish(0, \"Detached; Claude Code keeps running.\"),\n );\n });\n\n/** Runs one harnessd command; resolves to the exit code. */\nexport const runHarnessd = async (\n argv: readonly string[],\n bin: string,\n io: Io = {\n out: (line) => void process.stdout.write(`${line}\\n`),\n err: (line) => void process.stderr.write(`${line}\\n`),\n terminal: ttyTerminal(),\n },\n): Promise<number> => {\n const [first, ...rest] = argv;\n if (\n first === undefined ||\n first === \"help\" ||\n // past a server's name, --help is that server's\n argv\n .slice(0, first === \"tools\" ? 2 : undefined)\n .some((arg) => arg === \"--help\" || arg === \"-h\")\n ) {\n io.out(USAGE);\n return 0;\n }\n try {\n return await run(first, rest, bin, io);\n } catch (error) {\n if (!(error as { usage?: boolean }).usage) throw error;\n io.err(`${(error as Error).message} harnessd --help lists the commands.`);\n return 2;\n }\n};\n\nconst service = (rest: readonly string[], bin: string, io: Io) => {\n const [action, ...more] = rest;\n if (action !== \"install\" && action !== \"uninstall\")\n throw usageError(\"harnessd service takes install or uninstall.\");\n const flags: ServiceFlags = {};\n for (let i = 0; i < more.length; i++) {\n const arg = more[i]!;\n if (action === \"install\" && arg === \"--dry-run\") flags.dryRun = true;\n else if (action === \"install\" && arg === \"--install-claude\")\n flags.installClaude = true;\n else if (action === \"install\" && arg === \"--skip-sign-in\")\n flags.skipSignIn = true;\n else if (arg === \"--user\" && more[i + 1] !== undefined)\n flags.user = more[++i]!;\n else\n throw usageError(\n `harnessd service ${action} takes ${action === \"install\" ? \"--user <name>, --dry-run, --install-claude and --skip-sign-in\" : \"--user <name>\"}, not ${arg}.`,\n );\n }\n return action === \"install\" ? install(flags, bin, io) : uninstall(flags, io);\n};\n\nconst run = async (\n first: string,\n rest: readonly string[],\n bin: string,\n io: Io,\n): Promise<number> => {\n if (first === \"--version\") {\n takes(first, rest);\n io.out(VERSION);\n return 0;\n }\n if (first === \"service\") return service(rest, bin, io);\n const paths = pathsOf();\n switch (first) {\n case \"status\":\n takes(first, rest, [\"--json\"]);\n return status(paths, rest.includes(\"--json\"), io);\n case \"start\":\n case \"stop\":\n takes(first, rest);\n return command(paths, { command: first }, io);\n case \"attach\":\n takes(first, rest);\n return attach(paths, io);\n case \"run\":\n takes(first, rest);\n await runDaemon(paths, bin);\n return 0;\n case \"session-start\": {\n takes(first, rest);\n const input = JSON.parse(await (io.stdin ?? stdin)()) as {\n session_id?: unknown;\n agent_id?: unknown;\n };\n // a subagent's start, not the conversation's\n if (input.agent_id !== undefined) return 0;\n if (typeof input.session_id !== \"string\")\n throw new Error(\"Claude Code's SessionStart input has no session_id.\");\n const answer = await ask(paths.socket, {\n command: \"session-start\",\n sessionId: input.session_id,\n });\n if (answer?.ok) return 0;\n io.err(answer ? String(answer.message) : notRunning(paths));\n return 1;\n }\n case \"idle\": {\n takes(first, rest);\n const answer = await ask(paths.socket, { command: \"idle\" });\n if (answer?.ok) return 0;\n io.err(answer ? String(answer.message) : notRunning(paths));\n return 1;\n }\n case \"channel\":\n takes(first, rest);\n await serveChannel({\n config: readConfig(paths),\n paths,\n log: logTo(paths.log, \"channel: \"),\n });\n return 0;\n case \"tools\": {\n const [name, ...args] = rest;\n if (name === undefined)\n throw usageError(\"harnessd tools takes a server's name.\");\n const { servers } = readConfig(paths);\n const server = Object.hasOwn(servers, name) ? servers[name] : undefined;\n if (!server) throw new Error(`No server \"${name}\" in ${paths.config}`);\n return runCli(serverCli(paths, name, server, process.env), {\n ...(await processCliIo(args)),\n stdout: io.out,\n stderr: io.err,\n });\n }\n default:\n throw usageError(`Unknown command ${first}.`);\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;;AA6CA,MAAM,QAAQ;;;;;;;;;;;;;;;;;;;;;AAsBd,MAAM,UACJ,cAAc,YAAY,GAAG,CAAC,CAAC,iBAAiB,CAAC,CACjD;AAEF,MAAM,SAAS;AAWf,MAAM,QAAQ,YAAY;CACxB,IAAI,OAAO;CACX,WAAW,MAAM,SAAS,QAAQ,OAAO,QAAQ,OAAO,KAAK;CAC7D,OAAO;AACT;AAEA,MAAM,cAAc,UAClB,6BAA6B,MAAM,KAAK;AAE1C,MAAM,cAAc,YAClB,OAAO,OAAO,IAAI,MAAM,OAAO,GAAG,EAAE,OAAO,KAAK,CAAC;;AAGnD,MAAM,SACJ,SACA,MACA,UAA6B,CAAC,MAC3B;CACH,MAAM,QAAQ,KAAK,MAAM,QAAQ,CAAC,QAAQ,SAAS,GAAG,CAAC;CACvD,IAAI,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M,QAAQ,QAAQ,GAAG,GAAG;IACzD,GAAI,MAAM,aAAa,IAAI;IAC3B,QAAQ,GAAG;IACX,QAAQ,GAAG;GACb,CAAC;EACH;EACA,SACE,MAAM,WAAW,mBAAmB,MAAM,EAAE;CAChD;AACF"}
package/dist/config.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export declare namespace Harnessd {
2
2
  /** `config.json`, read at every start of Claude Code. */
3
3
  type Config = {
4
+ /** The day the file was written, `YYYY-MM-DD`: harnessd behaves as it did on that day. */
5
+ readonly compatibilityDate: string;
4
6
  /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */
5
7
  readonly folder: string;
6
8
  /** More arguments for `claude`. */
@@ -9,8 +11,10 @@ export declare namespace Harnessd {
9
11
  readonly env: Readonly<Record<string, string>>;
10
12
  /** A shell command run before each start; its stdout is JSON `{ env?, args? }` for that start. */
11
13
  readonly prestart?: string;
12
- /** MCP servers whose events reach the agent, by name. */
13
- readonly channels: Readonly<Record<string, Channel>>;
14
+ /** MCP servers by name: each one's tools are a command of that name for the agent. */
15
+ readonly servers: Readonly<Record<string, Server>>;
16
+ /** The one channel: the server events that reach the agent. */
17
+ readonly channel: Channel;
14
18
  /** Claude accounts by name, in the order harnessd tries them: when one hits its usage limit or its sign-in fails, Claude Code goes on with the next. */
15
19
  readonly accounts: Readonly<Record<string, Account>>;
16
20
  };
@@ -19,15 +23,23 @@ export declare namespace Harnessd {
19
23
  readonly env: Readonly<Record<string, string>>;
20
24
  };
21
25
  /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */
22
- type Channel = {
26
+ type Server = {
23
27
  readonly url: string;
24
28
  readonly headers: Readonly<Record<string, string>>;
25
- /** Subscription arguments for its events, such as the board to follow; each event type takes the ones it declares. */
29
+ };
30
+ type Channel = {
31
+ /** The events that come in, each with its own arguments; nothing else does. */
32
+ readonly subscribe: readonly Subscription[];
33
+ };
34
+ /** One event type of one server, such as the board to follow for `task.handed`. */
35
+ type Subscription = {
36
+ readonly server: string;
37
+ readonly event: string;
26
38
  readonly arguments: Readonly<Record<string, string | number | boolean>>;
27
39
  };
28
40
  /** Where one harnessd keeps its files. */
29
41
  type Paths = {
30
- /** The folder harnessd writes to: its state, log and each channel's place. */
42
+ /** The folder harnessd writes to: its state, log and where the channel's events resume. */
31
43
  readonly home: string;
32
44
  readonly config: string;
33
45
  readonly state: string;
@@ -36,7 +48,9 @@ export declare namespace Harnessd {
36
48
  readonly serviceLog: string;
37
49
  readonly socket: string;
38
50
  readonly plugin: string;
39
- readonly channels: string;
51
+ /** The servers' commands, first on Claude Code's PATH. */
52
+ readonly bin: string;
53
+ readonly channel: string;
40
54
  readonly label: string;
41
55
  /** The environment that gives another process these same paths. */
42
56
  readonly env: Readonly<Record<string, string>>;
@@ -45,12 +59,21 @@ export declare namespace Harnessd {
45
59
  export declare const pathsOf: (env?: NodeJS.ProcessEnv) => Harnessd.Paths;
46
60
  /** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */
47
61
  export declare const ownFolder: (dir: string) => void;
48
- export declare const DEFAULT_CONFIG: {
62
+ /** The local date, as `compatibilityDate` takes it. */
63
+ export declare const today: (now?: Date) => string;
64
+ /** The file `harnessd service install` writes when there is none. */
65
+ export declare const defaultConfig: () => {
66
+ compatibilityDate: string;
49
67
  folder: string;
50
- channels: {};
68
+ servers: {};
69
+ channel: {
70
+ subscribe: never[];
71
+ };
51
72
  };
73
+ /** What tells one subscription from another: its server, event and arguments. */
74
+ export declare const subscriptionKey: (subscription: Harnessd.Subscription) => string;
52
75
  export declare const parseConfig: (raw: unknown) => Harnessd.Config;
53
76
  export declare const readConfig: (paths: Harnessd.Paths) => Harnessd.Config;
54
- /** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
55
- export declare const headersOf: (channel: Harnessd.Channel, env: NodeJS.ProcessEnv) => Record<string, string>;
77
+ /** A server's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
78
+ export declare const headersOf: (server: Harnessd.Server, env: N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,CAAC,MAY3D,CAAC;AAEF,+FAA+F;AAC/F,eAAO,MAAM,SAAS,GACpB,QAAQ,QAAQ,CAAC,MAAM,EACvB,KAAK,MAAM,CAAC,UAAU,KACrB,MAAM,CAAC,MAAM,EAAE,MAAM,CAWrB,CAAC"}
package/dist/config.js CHANGED
@@ -9,11 +9,7 @@ const LOOPBACK = /* @__PURE__ */ new Set([
9
9
  "[::1]"
10
10
  ]);
11
11
  const NAME = /^[a-z][a-z0-9-]{0,31}$/;
12
- const RESERVED = /* @__PURE__ */ new Set([
13
- "stream",
14
- "login",
15
- "help"
16
- ]);
12
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
17
13
  const SOCKET_MAX = 103;
18
14
  const XDG = [
19
15
  "XDG_CONFIG_HOME",
@@ -39,7 +35,8 @@ const pathsOf = (env = process.env) => {
39
35
  serviceLog: join(home, "service.log"),
40
36
  socket,
41
37
  plugin: join(home, "plugin"),
42
- channels: join(home, "channels"),
38
+ bin: join(home, "plugin", "bin"),
39
+ channel: join(home, "channel.json"),
43
40
  label: !one && stateHome === join(homedir(), ".local", "state") ? "dev.harnessd" : `dev.harnessd.${id}`,
44
41
  env: one ? { HARNESSD_HOME: one } : {
45
42
  HARNESSD_HOME: "",
@@ -57,10 +54,19 @@ const ownFolder = (dir) => {
57
54
  });
58
55
  chmodSync(dir, 448);
59
56
  };
60
- const DEFAULT_CONFIG = {
57
+ /** The local date, as `compatibilityDate` takes it. */
58
+ const today = (now = /* @__PURE__ */ new Date()) => [
59
+ now.getFullYear(),
60
+ now.getMonth() + 1,
61
+ now.getDate()
62
+ ].map((part) => String(part).padStart(2, "0")).join("-");
63
+ /** The file `harnessd service install` writes when there is none. */
64
+ const defaultConfig = () => ({
65
+ compatibilityDate: today(),
61
66
  folder: "~/agent",
62
- channels: {}
63
- };
67
+ servers: {},
68
+ channel: { subscribe: [] }
69
+ });
64
70
  const fail = (message) => {
65
71
  throw new Error(`config.json: ${message}`);
66
72
  };
@@ -75,50 +81,93 @@ const only = (value, keys, what) => {
75
81
  if (unknown !== void 0) fail(`${what} has no "${unknown}"; it takes ${keys.join(", ")}`);
76
82
  };
77
83
  const expandHome = (path) => path === "~" ? homedir() : path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
84
+ const scalars = (value, what) => {
85
+ if (value === void 0) return {};
86
+ if (!isRecord(value) || Object.values(value).some((v) => ![
87
+ "string",
88
+ "number",
89
+ "boolean"
90
+ ].includes(typeof v))) fail(`${what} must map names to strings, numbers or booleans`);
91
+ return value;
92
+ };
93
+ const parseServers = (value) => {
94
+ const servers = {};
95
+ if (value === void 0) return servers;
96
+ if (!isRecord(value)) fail("servers must map names to { url, headers }");
97
+ for (const [name, server] of Object.entries(value)) {
98
+ if (!NAME.test(name)) fail(`server "${name}" needs a name of lowercase letters, digits and dashes`);
99
+ if (!isRecord(server)) fail(`servers.${name} must be { url, headers }`);
100
+ const entry = server;
101
+ only(entry, ["url", "headers"], `servers.${name}`);
102
+ let url;
103
+ try {
104
+ url = new URL(String(entry.url));
105
+ } catch {}
106
+ if (!url || url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.has(url.hostname))) fail(`servers.${name}.url must be an https URL (http only on this computer: localhost, 127.0.0.1, [::1])`);
107
+ servers[name] = {
108
+ url: url.href,
109
+ headers: strings(entry.headers, `servers.${name}.headers`)
110
+ };
111
+ }
112
+ return servers;
113
+ };
114
+ const parseChannel = (value, servers) => {
115
+ if (value === void 0) return { subscribe: [] };
116
+ if (!isRecord(value)) fail("channel must be { subscribe }");
117
+ const entry = value;
118
+ only(entry, ["subscribe"], "channel");
119
+ const listed = entry.subscribe ?? [];
120
+ if (!Array.isArray(listed)) fail("channel.subscribe must be a list of { server, event, arguments }");
121
+ const seen = /* @__PURE__ */ new Set();
122
+ return { subscribe: listed.map((item, i) => {
123
+ const what = `channel.subscribe[${i}]`;
124
+ if (!isRecord(item)) fail(`${what} must be { server, event, arguments }`);
125
+ const one = item;
126
+ only(one, [
127
+ "server",
128
+ "event",
129
+ "arguments"
130
+ ], what);
131
+ if (typeof one.server !== "string" || !Object.hasOwn(servers, one.server)) fail(`${what}.server must name one of servers`);
132
+ if (typeof one.event !== "string" || one.event === "") fail(`${what}.event must name one of the server's events`);
133
+ const subscription = {
134
+ server: one.server,
135
+ event: one.event,
136
+ arguments: scalars(one.arguments, `${what}.arguments`)
137
+ };
138
+ const key = subscriptionKey(subscription);
139
+ if (seen.has(key)) fail(`${what} repeats an earlier subscription`);
140
+ seen.add(key);
141
+ return subscription;
142
+ }) };
143
+ };
144
+ /** What tells one subscription from another: its server, event and arguments. */
145
+ const subscriptionKey = (subscription) => JSON.stringify([
146
+ subscription.server,
147
+ subscription.event,
148
+ Object.entries(subscription.arguments).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
149
+ ]);
78
150
  const parseConfig = (raw) => {
79
151
  if (!isRecord(raw)) fail("must be a JSON object");
80
152
  const value = raw;
81
153
  only(value, [
154
+ "compatibilityDate",
82
155
  "folder",
83
156
  "args",
84
157
  "env",
85
158
  "prestart",
86
- "channels",
159
+ "servers",
160
+ "channel",
87
161
  "accounts"
88
162
  ], "it");
163
+ const date = value.compatibilityDate;
164
+ if (typeof date !== "string" || !DATE.test(date) || new Date(Date.parse(date) || 0).toISOString().slice(0, 10) !== date) fail("compatibilityDate must be a date, YYYY-MM-DD: the day the file was written");
89
165
  if (typeof value.folder !== "string" || value.folder === "") fail("folder must be a path");
90
166
  const args = value.args ?? [];
91
167
  if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string")) fail("args must be a list of strings");
92
168
  if (value.prestart !== void 0 && (typeof value.prestart !== "string" || value.prestart === "")) fail("prestart must be a shell command");
93
- const channels = {};
94
- const listed = value.channels ?? {};
95
- if (!isRecord(listed)) fail("channels must map names to { url, headers, arguments }");
96
- for (const [name, channel] of Object.entries(listed)) {
97
- if (!NAME.test(name) || RESERVED.has(name)) fail(`channel "${name}" needs a name of lowercase letters, digits and dashes, other than ${[...RESERVED].join(", ")}`);
98
- if (!isRecord(channel)) fail(`channels.${name} must be { url, headers, arguments }`);
99
- const entry = channel;
100
- only(entry, [
101
- "url",
102
- "headers",
103
- "arguments"
104
- ], `channels.${name}`);
105
- let url;
106
- try {
107
- url = new URL(String(entry.url));
108
- } catch {}
109
- if (!url || url.protocol !== "https:" && !(url.protocol === "http:" && LOOPBACK.has(url.hostname))) fail(`channels.${name}.url must be an https URL (http only on this computer: localhost, 127.0.0.1, [::1])`);
110
- const args = entry.arguments ?? {};
111
- if (!isRecord(args) || Object.values(args).some((v) => ![
112
- "string",
113
- "number",
114
- "boolean"
115
- ].includes(typeof v))) fail(`channels.${name}.arguments must map names to strings, numbers or booleans`);
116
- channels[name] = {
117
- url: url.href,
118
- headers: strings(entry.headers, `channels.${name}.headers`),
119
- arguments: args
120
- };
121
- }
169
+ const servers = parseServers(value.servers);
170
+ const channel = parseChannel(value.channel, servers);
122
171
  const accounts = {};
123
172
  const named = value.accounts === void 0 ? {} : value.accounts;
124
173
  if (!isRecord(named)) fail("accounts must map names to { env }");
@@ -132,11 +181,13 @@ const parseConfig = (raw) => {
132
181
  accounts[name] = { env };
133
182
  }
134
183
  return {
184
+ compatibilityDate: date,
135
185
  folder: resolve(expandHome(value.folder)),
136
186
  args,
137
187
  env: strings(value.env, "env"),
138
188
  ...value.prestart !== void 0 && { prestart: value.prestart },
139
- channels,
189
+ servers,
190
+ channel,
140
191
  accounts
141
192
  };
142
193
  };
@@ -150,12 +201,12 @@ const readConfig = (paths) => {
150
201
  }
151
202
  return parseConfig(raw);
152
203
  };
153
- /** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
154
- const headersOf = (channel, env) => Object.fromEntries(Object.entries(channel.headers).map(([key, value]) => [key, value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
204
+ /** A server's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */
205
+ const headersOf = (server, env) => Object.fromEntries(Object.entries(server.headers).map(([key, value]) => [key, value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => {
155
206
  const found = env[name];
156
207
  if (found === void 0) throw new Error(`header ${key} needs $${name}, which isn't set`);
157
208
  return found;
158
209
  })]));
159
- export { DEFAULT_CONFIG, headersOf, ownFolder, parseConfig, pathsOf, readConfig };
210
+ export { defaultConfig, headersOf, ownFolder, parseConfig, pathsOf, readConfig, subscriptionKey, today };
160
211
 
161
212
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve } from \"node:path\";\n\nexport namespace Harnessd {\n /** `config.json`, read at every start of Claude Code. */\n export type Config = {\n /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */\n readonly folder: string;\n /** More arguments for `claude`. */\n readonly args: readonly string[];\n /** More environment for `claude`. */\n readonly env: Readonly<Record<string, string>>;\n /** A shell command run before each start; its stdout is JSON `{ env?, args? }` for that start. */\n readonly prestart?: string;\n /** MCP servers whose events reach the agent, by name. */\n readonly channels: Readonly<Record<string, Channel>>;\n /** Claude accounts by name, in the order harnessd tries them: when one hits its usage limit or its sign-in fails, Claude Code goes on with the next. */\n readonly accounts: Readonly<Record<string, Account>>;\n };\n\n /** One Claude account: the environment that signs Claude Code in to it, such as a `claude setup-token` token in `CLAUDE_CODE_OAUTH_TOKEN`. None: this Mac's own sign-in. */\n export type Account = {\n readonly env: Readonly<Record<string, string>>;\n };\n\n /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */\n export type Channel = {\n readonly url: string;\n readonly headers: Readonly<Record<string, string>>;\n /** Subscription arguments for its events, such as the board to follow; each event type takes the ones it declares. */\n readonly arguments: Readonly<Record<string, string | number | boolean>>;\n };\n\n /** Where one harnessd keeps its files. */\n export type Paths = {\n /** The folder harnessd writes to: its state, log and each channel's place. */\n readonly home: string;\n readonly config: string;\n readonly state: string;\n readonly log: string;\n /** What harnessd itself prints, kept by the service that runs it: a start that failed says why here. */\n readonly serviceLog: string;\n readonly socket: string;\n readonly plugin: string;\n readonly channels: string;\n readonly label: string;\n /** The environment that gives another process these same paths. */\n readonly env: Readonly<Record<string, string>>;\n };\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\nconst NAME = /^[a-z][a-z0-9-]{0,31}$/;\n// toolport's CLI keeps these words for itself\nconst RESERVED = new Set([\"stream\", \"login\", \"help\"]);\n// macOS caps a socket path at 104 bytes\nconst SOCKET_MAX = 103;\n\nconst XDG = [\"XDG_CONFIG_HOME\", \"XDG_STATE_HOME\", \"XDG_RUNTIME_DIR\"] as const;\n\nconst tooLong = (socket: string) => Buffer.byteLength(socket) > SOCKET_MAX;\n\n// The XDG base directories: config.json in $XDG_CONFIG_HOME/harnessd (~/.config), everything harnessd writes in\n// $XDG_STATE_HOME/harnessd (~/.local/state). HARNESSD_HOME puts both in one folder. There is no --config flag:\n// the service and each channel's process must find the same file, and these variables already reach them.\nexport const pathsOf = (\n env: NodeJS.ProcessEnv = process.env,\n): Harnessd.Paths => {\n // the XDG spec ignores a relative path\n const xdg = Object.fromEntries(\n XDG.flatMap((key) =>\n env[key] && isAbsolute(env[key]) ? [[key, env[key]]] : [],\n ),\n ) as Partial<Record<(typeof XDG)[number], string>>;\n const one = env.HARNESSD_HOME ? resolve(env.HARNESSD_HOME) : undefined;\n const configHome = xdg.XDG_CONFIG_HOME ?? join(homedir(), \".config\");\n const stateHome = xdg.XDG_STATE_HOME ?? join(homedir(), \".local\", \"state\");\n const home = one ?? join(stateHome, \"harnessd\");\n const id = createHash(\"sha256\").update(home).digest(\"hex\").slice(0, 8);\n let socket = join(home, \"harnessd.sock\");\n if (!one && tooLong(socket))\n socket = xdg.XDG_RUNTIME_DIR\n ? join(xdg.XDG_RUNTIME_DIR, \"harnessd\", `${id}.sock`)\n : join(\"/tmp\", `harnessd-${process.getuid?.() ?? 0}`, `${id}.sock`);\n if (tooLong(socket))\n throw new Error(\n `${one ? \"HARNESSD_HOME\" : \"XDG_RUNTIME_DIR\"} is too long for a socket (${socket})`,\n );\n return {\n home,\n config: join(one ?? join(configHome, \"harnessd\"), \"config.json\"),\n state: join(home, \"state.json\"),\n log: join(home, \"harnessd.log\"),\n serviceLog: join(home, \"service.log\"),\n socket,\n plugin: join(home, \"plugin\"),\n channels: join(home, \"channels\"),\n label:\n !one && stateHome === join(homedir(), \".local\", \"state\")\n ? \"dev.harnessd\"\n : `dev.harnessd.${id}`,\n // every variable these paths came from, so nothing a child inherits moves them; \"\" reads as not set\n env: one\n ? { HARNESSD_HOME: one }\n : {\n HARNESSD_HOME: \"\",\n XDG_CONFIG_HOME: configHome,\n XDG_STATE_HOME: stateHome,\n ...(!socket.startsWith(home) && {\n XDG_RUNTIME_DIR: xdg.XDG_RUNTIME_DIR ?? \"\",\n }),\n },\n };\n};\n\n/** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */\nexport const ownFolder = (dir: string) => {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n};\n\nexport const DEFAULT_CONFIG = { folder: \"~/agent\", channels: {} };\n\nconst fail = (message: string): never => {\n throw new Error(`config.json: ${message}`);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst strings = (value: unknown, what: string): Record<string, string> => {\n if (value === undefined) return {};\n if (\n !isRecord(value) ||\n Object.values(value).some((v) => typeof v !== \"string\")\n )\n fail(`${what} must map names to strings`);\n return value as Record<string, string>;\n};\n\nconst only = (\n value: Record<string, unknown>,\n keys: readonly string[],\n what: string,\n) => {\n const unknown = Object.keys(value).find((key) => !keys.includes(key));\n if (unknown !== undefined)\n fail(`${what} has no \"${unknown}\"; it takes ${keys.join(\", \")}`);\n};\n\nconst expandHome = (path: string) =>\n path === \"~\"\n ? homedir()\n : path.startsWith(\"~/\")\n ? join(homedir(), path.slice(2))\n : path;\n\nexport const parseConfig = (raw: unknown): Harnessd.Config => {\n if (!isRecord(raw)) fail(\"must be a JSON object\");\n const value = raw as Record<string, unknown>;\n only(\n value,\n [\"folder\", \"args\", \"env\", \"prestart\", \"channels\", \"accounts\"],\n \"it\",\n );\n if (typeof value.folder !== \"string\" || value.folder === \"\")\n fail(\"folder must be a path\");\n const args = value.args ?? [];\n if (!Array.isArray(args) || args.some((arg) => typeof arg !== \"string\"))\n fail(\"args must be a list of strings\");\n if (\n value.prestart !== undefined &&\n (typeof value.prestart !== \"string\" || value.prestart === \"\")\n )\n fail(\"prestart must be a shell command\");\n const channels: Record<string, Harnessd.Channel> = {};\n const listed = value.channels ?? {};\n if (!isRecord(listed))\n fail(\"channels must map names to { url, headers, arguments }\");\n for (const [name, channel] of Object.entries(\n listed as Record<string, unknown>,\n )) {\n if (!NAME.test(name) || RESERVED.has(name))\n fail(\n `channel \"${name}\" needs a name of lowercase letters, digits and dashes, other than ${[...RESERVED].join(\", \")}`,\n );\n if (!isRecord(channel))\n fail(`channels.${name} must be { url, headers, arguments }`);\n const entry = channel as Record<string, unknown>;\n only(entry, [\"url\", \"headers\", \"arguments\"], `channels.${name}`);\n let url: URL | undefined;\n try {\n url = new URL(String(entry.url));\n } catch {}\n if (\n !url ||\n (url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && LOOPBACK.has(url.hostname)))\n )\n fail(\n `channels.${name}.url must be an https URL (http only on this computer: localhost, 127.0.0.1, [::1])`,\n );\n const args = entry.arguments ?? {};\n if (\n !isRecord(args) ||\n Object.values(args).some(\n (v) => ![\"string\", \"number\", \"boolean\"].includes(typeof v),\n )\n )\n fail(\n `channels.${name}.arguments must map names to strings, numbers or booleans`,\n );\n channels[name] = {\n url: url!.href,\n headers: strings(entry.headers, `channels.${name}.headers`),\n arguments: args as Record<string, string | number | boolean>,\n };\n }\n const accounts: Record<string, Harnessd.Account> = {};\n const named = value.accounts === undefined ? {} : value.accounts;\n if (!isRecord(named)) fail(\"accounts must map names to { env }\");\n for (const [name, account] of Object.entries(\n named as Record<string, unknown>,\n )) {\n if (!NAME.test(name))\n fail(\n `account \"${name}\" needs a name of lowercase letters, digits and dashes`,\n );\n if (!isRecord(account)) fail(`accounts.${name} must be { env }`);\n const entry = account as Record<string, unknown>;\n only(entry, [\"env\"], `accounts.${name}`);\n const env = strings(entry.env, `accounts.${name}.env`);\n // every account shares one conversation, so where Claude Code keeps it comes from the top-level env\n if (\"CLAUDE_CONFIG_DIR\" in env)\n fail(\n `accounts.${name}.env can't set CLAUDE_CONFIG_DIR; set it in the top-level env`,\n );\n accounts[name] = { env };\n }\n return {\n folder: resolve(expandHome(value.folder as string)),\n args: args as string[],\n env: strings(value.env, \"env\"),\n ...(value.prestart !== undefined && { prestart: value.prestart as string }),\n channels,\n accounts,\n };\n};\n\nexport const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {\n if (!existsSync(paths.config))\n throw new Error(`No ${paths.config}: run harnessd service install`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(paths.config, \"utf8\"));\n } catch (error) {\n throw new Error(\n `config.json isn't JSON: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return parseConfig(raw);\n};\n\n/** A channel's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */\nexport const headersOf = (\n channel: Harnessd.Channel,\n env: NodeJS.ProcessEnv,\n): Record<string, string> =>\n Object.fromEntries(\n Object.entries(channel.headers).map(([key, value]) => [\n key,\n value.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_, name: string) => {\n const found = env[name];\n if (found === undefined)\n throw new Error(`header ${key} needs $${name}, which isn't set`);\n return found;\n }),\n ]),\n );\n"],"mappings":";;;;;AAqDA,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAC5D,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAU;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,MAAM,QAAQ,oCAAoC,GAAG,SAAiB;CACpE,MAAM,QAAQ,IAAI;CAClB,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,UAAU,IAAI,UAAU,KAAK,kBAAkB;CACjE,OAAO;AACT,CAAC,CACH,CAAC,CACH"}
1
+ {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { chmodSync, existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve } from \"node:path\";\n\nexport namespace Harnessd {\n /** `config.json`, read at every start of Claude Code. */\n export type Config = {\n /** The day the file was written, `YYYY-MM-DD`: harnessd behaves as it did on that day. */\n readonly compatibilityDate: string;\n /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */\n readonly folder: string;\n /** More arguments for `claude`. */\n readonly args: readonly string[];\n /** More environment for `claude`. */\n readonly env: Readonly<Record<string, string>>;\n /** A shell command run before each start; its stdout is JSON `{ env?, args? }` for that start. */\n readonly prestart?: string;\n /** MCP servers by name: each one's tools are a command of that name for the agent. */\n readonly servers: Readonly<Record<string, Server>>;\n /** The one channel: the server events that reach the agent. */\n readonly channel: Channel;\n /** Claude accounts by name, in the order harnessd tries them: when one hits its usage limit or its sign-in fails, Claude Code goes on with the next. */\n readonly accounts: Readonly<Record<string, Account>>;\n };\n\n /** One Claude account: the environment that signs Claude Code in to it, such as a `claude setup-token` token in `CLAUDE_CODE_OAUTH_TOKEN`. None: this Mac's own sign-in. */\n export type Account = {\n readonly env: Readonly<Record<string, string>>;\n };\n\n /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */\n export type Server = {\n readonly url: string;\n readonly headers: Readonly<Record<string, string>>;\n };\n\n export type Channel = {\n /** The events that come in, each with its own arguments; nothing else does. */\n readonly subscribe: readonly Subscription[];\n };\n\n /** One event type of one server, such as the board to follow for `task.handed`. */\n export type Subscription = {\n readonly server: string;\n readonly event: string;\n readonly arguments: Readonly<Record<string, string | number | boolean>>;\n };\n\n /** Where one harnessd keeps its files. */\n export type Paths = {\n /** The folder harnessd writes to: its state, log and where the channel's events resume. */\n readonly home: string;\n readonly config: string;\n readonly state: string;\n readonly log: string;\n /** What harnessd itself prints, kept by the service that runs it: a start that failed says why here. */\n readonly serviceLog: string;\n readonly socket: string;\n readonly plugin: string;\n /** The servers' commands, first on Claude Code's PATH. */\n readonly bin: string;\n readonly channel: string;\n readonly label: string;\n /** The environment that gives another process these same paths. */\n readonly env: Readonly<Record<string, string>>;\n };\n}\n\nconst LOOPBACK = new Set([\"localhost\", \"127.0.0.1\", \"[::1]\"]);\nconst NAME = /^[a-z][a-z0-9-]{0,31}$/;\nconst DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n// macOS caps a socket path at 104 bytes\nconst SOCKET_MAX = 103;\n\nconst XDG = [\"XDG_CONFIG_HOME\", \"XDG_STATE_HOME\", \"XDG_RUNTIME_DIR\"] as const;\n\nconst tooLong = (socket: string) => Buffer.byteLength(socket) > SOCKET_MAX;\n\n// The XDG base directories: config.json in $XDG_CONFIG_HOME/harnessd (~/.config), everything harnessd writes in\n// $XDG_STATE_HOME/harnessd (~/.local/state). HARNESSD_HOME puts both in one folder. There is no --config flag:\n// the service, the channel's process and the servers' commands must find the same file, and these variables already reach them.\nexport const pathsOf = (\n env: NodeJS.ProcessEnv = process.env,\n): Harnessd.Paths => {\n // the XDG spec ignores a relative path\n const xdg = Object.fromEntries(\n XDG.flatMap((key) =>\n env[key] && isAbsolute(env[key]) ? [[key, env[key]]] : [],\n ),\n ) as Partial<Record<(typeof XDG)[number], string>>;\n const one = env.HARNESSD_HOME ? resolve(env.HARNESSD_HOME) : undefined;\n const configHome = xdg.XDG_CONFIG_HOME ?? join(homedir(), \".config\");\n const stateHome = xdg.XDG_STATE_HOME ?? join(homedir(), \".local\", \"state\");\n const home = one ?? join(stateHome, \"harnessd\");\n const id = createHash(\"sha256\").update(home).digest(\"hex\").slice(0, 8);\n let socket = join(home, \"harnessd.sock\");\n if (!one && tooLong(socket))\n socket = xdg.XDG_RUNTIME_DIR\n ? join(xdg.XDG_RUNTIME_DIR, \"harnessd\", `${id}.sock`)\n : join(\"/tmp\", `harnessd-${process.getuid?.() ?? 0}`, `${id}.sock`);\n if (tooLong(socket))\n throw new Error(\n `${one ? \"HARNESSD_HOME\" : \"XDG_RUNTIME_DIR\"} is too long for a socket (${socket})`,\n );\n return {\n home,\n config: join(one ?? join(configHome, \"harnessd\"), \"config.json\"),\n state: join(home, \"state.json\"),\n log: join(home, \"harnessd.log\"),\n serviceLog: join(home, \"service.log\"),\n socket,\n plugin: join(home, \"plugin\"),\n bin: join(home, \"plugin\", \"bin\"),\n channel: join(home, \"channel.json\"),\n label:\n !one && stateHome === join(homedir(), \".local\", \"state\")\n ? \"dev.harnessd\"\n : `dev.harnessd.${id}`,\n // every variable these paths came from, so nothing a child inherits moves them; \"\" reads as not set\n env: one\n ? { HARNESSD_HOME: one }\n : {\n HARNESSD_HOME: \"\",\n XDG_CONFIG_HOME: configHome,\n XDG_STATE_HOME: stateHome,\n ...(!socket.startsWith(home) && {\n XDG_RUNTIME_DIR: xdg.XDG_RUNTIME_DIR ?? \"\",\n }),\n },\n };\n};\n\n/** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */\nexport const ownFolder = (dir: string) => {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700);\n};\n\n/** The local date, as `compatibilityDate` takes it. */\nexport const today = (now = new Date()) =>\n [now.getFullYear(), now.getMonth() + 1, now.getDate()]\n .map((part) => String(part).padStart(2, \"0\"))\n .join(\"-\");\n\n/** The file `harnessd service install` writes when there is none. */\nexport const defaultConfig = () => ({\n compatibilityDate: today(),\n folder: \"~/agent\",\n servers: {},\n channel: { subscribe: [] },\n});\n\nconst fail = (message: string): never => {\n throw new Error(`config.json: ${message}`);\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst strings = (value: unknown, what: string): Record<string, string> => {\n if (value === undefined) return {};\n if (\n !isRecord(value) ||\n Object.values(value).some((v) => typeof v !== \"string\")\n )\n fail(`${what} must map names to strings`);\n return value as Record<string, string>;\n};\n\nconst only = (\n value: Record<string, unknown>,\n keys: readonly string[],\n what: string,\n) => {\n const unknown = Object.keys(value).find((key) => !keys.includes(key));\n if (unknown !== undefined)\n fail(`${what} has no \"${unknown}\"; it takes ${keys.join(\", \")}`);\n};\n\nconst expandHome = (path: string) =>\n path === \"~\"\n ? homedir()\n : path.startsWith(\"~/\")\n ? join(homedir(), path.slice(2))\n : path;\n\nconst scalars = (value: unknown, what: string) => {\n if (value === undefined) return {};\n if (\n !isRecord(value) ||\n Object.values(value).some(\n (v) => ![\"string\", \"number\", \"boolean\"].includes(typeof v),\n )\n )\n fail(`${what} must map names to strings, numbers or booleans`);\n return value as Record<string, string | number | boolean>;\n};\n\nconst parseServers = (value: unknown) => {\n const servers: Record<string, Harnessd.Server> = {};\n if (value === undefined) return servers;\n if (!isRecord(value)) fail(\"servers must map names to { url, headers }\");\n for (const [name, server] of Object.entries(\n value as Record<string, unknown>,\n )) {\n if (!NAME.test(name))\n fail(\n `server \"${name}\" needs a name of lowercase letters, digits and dashes`,\n );\n if (!isRecord(server)) fail(`servers.${name} must be { url, headers }`);\n const entry = server as Record<string, unknown>;\n only(entry, [\"url\", \"headers\"], `servers.${name}`);\n let url: URL | undefined;\n try {\n url = new URL(String(entry.url));\n } catch {}\n if (\n !url ||\n (url.protocol !== \"https:\" &&\n !(url.protocol === \"http:\" && LOOPBACK.has(url.hostname)))\n )\n fail(\n `servers.${name}.url must be an https URL (http only on this computer: localhost, 127.0.0.1, [::1])`,\n );\n servers[name] = {\n url: url!.href,\n headers: strings(entry.headers, `servers.${name}.headers`),\n };\n }\n return servers;\n};\n\nconst parseChannel = (\n value: unknown,\n servers: Readonly<Record<string, Harnessd.Server>>,\n): Harnessd.Channel => {\n if (value === undefined) return { subscribe: [] };\n if (!isRecord(value)) fail(\"channel must be { subscribe }\");\n const entry = value as Record<string, unknown>;\n only(entry, [\"subscribe\"], \"channel\");\n const listed = entry.subscribe ?? [];\n if (!Array.isArray(listed))\n fail(\"channel.subscribe must be a list of { server, event, arguments }\");\n const seen = new Set<string>();\n const subscribe = (listed as unknown[]).map((item, i) => {\n const what = `channel.subscribe[${i}]`;\n if (!isRecord(item)) fail(`${what} must be { server, event, arguments }`);\n const one = item as Record<string, unknown>;\n only(one, [\"server\", \"event\", \"arguments\"], what);\n if (typeof one.server !== \"string\" || !Object.hasOwn(servers, one.server))\n fail(`${what}.server must name one of servers`);\n if (typeof one.event !== \"string\" || one.event === \"\")\n fail(`${what}.event must name one of the server's events`);\n const subscription: Harnessd.Subscription = {\n server: one.server as string,\n event: one.event as string,\n arguments: scalars(one.arguments, `${what}.arguments`),\n };\n const key = subscriptionKey(subscription);\n if (seen.has(key)) fail(`${what} repeats an earlier subscription`);\n seen.add(key);\n return subscription;\n });\n return { subscribe };\n};\n\n/** What tells one subscription from another: its server, event and arguments. */\nexport const subscriptionKey = (subscription: Harnessd.Subscription) =>\n JSON.stringify([\n subscription.server,\n subscription.event,\n Object.entries(subscription.arguments).sort(([a], [b]) =>\n a < b ? -1 : a > b ? 1 : 0,\n ),\n ]);\n\nexport const parseConfig = (raw: unknown): Harnessd.Config => {\n if (!isRecord(raw)) fail(\"must be a JSON object\");\n const value = raw as Record<string, unknown>;\n only(\n value,\n [\n \"compatibilityDate\",\n \"folder\",\n \"args\",\n \"env\",\n \"prestart\",\n \"servers\",\n \"channel\",\n \"accounts\",\n ],\n \"it\",\n );\n const date = value.compatibilityDate;\n if (\n typeof date !== \"string\" ||\n !DATE.test(date) ||\n // Date rolls a day past the month's end over into the next month\n new Date(Date.parse(date) || 0).toISOString().slice(0, 10) !== date\n )\n fail(\n \"compatibilityDate must be a date, YYYY-MM-DD: the day the file was written\",\n );\n if (typeof value.folder !== \"string\" || value.folder === \"\")\n fail(\"folder must be a path\");\n const args = value.args ?? [];\n if (!Array.isArray(args) || args.some((arg) => typeof arg !== \"string\"))\n fail(\"args must be a list of strings\");\n if (\n value.prestart !== undefined &&\n (typeof value.prestart !== \"string\" || value.prestart === \"\")\n )\n fail(\"prestart must be a shell command\");\n const servers = parseServers(value.servers);\n const channel = parseChannel(value.channel, servers);\n const accounts: Record<string, Harnessd.Account> = {};\n const named = value.accounts === undefined ? {} : value.accounts;\n if (!isRecord(named)) fail(\"accounts must map names to { env }\");\n for (const [name, account] of Object.entries(\n named as Record<string, unknown>,\n )) {\n if (!NAME.test(name))\n fail(\n `account \"${name}\" needs a name of lowercase letters, digits and dashes`,\n );\n if (!isRecord(account)) fail(`accounts.${name} must be { env }`);\n const entry = account as Record<string, unknown>;\n only(entry, [\"env\"], `accounts.${name}`);\n const env = strings(entry.env, `accounts.${name}.env`);\n // every account shares one conversation, so where Claude Code keeps it comes from the top-level env\n if (\"CLAUDE_CONFIG_DIR\" in env)\n fail(\n `accounts.${name}.env can't set CLAUDE_CONFIG_DIR; set it in the top-level env`,\n );\n accounts[name] = { env };\n }\n return {\n compatibilityDate: date as string,\n folder: resolve(expandHome(value.folder as string)),\n args: args as string[],\n env: strings(value.env, \"env\"),\n ...(value.prestart !== undefined && { prestart: value.prestart as string }),\n servers,\n channel,\n accounts,\n };\n};\n\nexport const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {\n if (!existsSync(paths.config))\n throw new Error(`No ${paths.config}: run harnessd service install`);\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(paths.config, \"utf8\"));\n } catch (error) {\n throw new Error(\n `config.json isn't JSON: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return parseConfig(raw);\n};\n\n/** A server's headers with each `${VAR}` read from `env`; a variable that isn't set throws. */\nexport const headersOf = (\n server: Harnessd.Server,\n env: NodeJS.ProcessEnv,\n): Record<string, string> =>\n Object.fromEntries(\n Object.entries(server.headers).map(([key, value]) => [\n key,\n value.replace(/\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_, name: string) => {\n const found = env[name];\n if (found === undefined)\n throw new Error(`header ${key} needs $${name}, which isn't set`);\n return found;\n }),\n ]),\n );\n"],"mappings":";;;;;AAqEA,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAC5D,MAAM,OAAO;AACb,MAAM,OAAO;AAEb,MAAM,aAAa;AAEnB,MAAM,MAAM;CAAC;CAAmB;CAAkB;AAAiB;AAEnE,MAAM,WAAW,WAAmB,OAAO,WAAW,MAAM,IAAI;AAKhE,MAAa,WACX,MAAyB,QAAQ,QACd;CAEnB,MAAM,MAAM,OAAO,YACjB,IAAI,SAAS,QACX,IAAI,QAAQ,WAAW,IAAI,IAAI,IAAI,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,IAAI,CAAC,CAC1D,CACF;CACA,MAAM,MAAM,IAAI,gBAAgB,QAAQ,IAAI,aAAa,IAAI,KAAA;CAC7D,MAAM,aAAa,IAAI,mBAAmB,KAAK,QAAQ,GAAG,SAAS;CACnE,MAAM,YAAY,IAAI,kBAAkB,KAAK,QAAQ,GAAG,UAAU,OAAO;CACzE,MAAM,OAAO,OAAO,KAAK,WAAW,UAAU;CAC9C,MAAM,KAAK,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC;CACrE,IAAI,SAAS,KAAK,MAAM,eAAe;CACvC,IAAI,CAAC,OAAO,QAAQ,MAAM,GACxB,SAAS,IAAI,kBACT,KAAK,IAAI,iBAAiB,YAAY,GAAG,GAAG,MAAM,IAClD,KAAK,QAAQ,YAAY,QAAQ,SAAS,KAAK,KAAK,GAAG,GAAG,MAAM;CACtE,IAAI,QAAQ,MAAM,GAChB,MAAM,IAAI,MACR,GAAG,MAAM,kBAAkB,kBAAkB,6BAA6B,OAAO,EACnF;CACF,OAAO;EACL;EACA,QAAQ,KAAK,OAAO,KAAK,YAA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AAM;EACvC,MAAM,MAAM,QAAQ,MAAM,KAAK,YAAY,KAAK,KAAK;EAErD,IAAI,uBAAuB,KACzB,KACE,YAAY,KAAK,8DACnB;EACF,SAAS,QAAQ,EAAE,IAAI;CACzB;CACA,OAAO;EACL,mBAAmB;EACnB,QAAQ,QAAQ,WAAW,MAAM,MAAgB,CAAC;EAC5C;EACN,KAAK,QAAQ,MAAM,KAAK,KAAK;EAC7B,GAAI,MAAM,aAAa,KAAA,KAAa,EAAE,UAAU,MAAM,SAAmB;EACzE;EACA;EACA;CACF;AACF;AAEA,MAAa,cAAc,UAA2C;CACpE,IAAI,CAAC,WAAW,MAAM,MAAM,GAC1B,MAAM,IAAI,MAAM,MAAM,MAAM,OAAO,+BAA+B;CACpE,IAAI;CACJ,IAAI;EACF,MAAM,KAAK,MAAM,aAAa,MAAM,QAAQ,MAAM,CAAC;CACrD,SAAS,OAAO;EACd,MAAM,IAAI,MACR,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAClF;CACF;CACA,OAAO,YAAY,GAAG;AACxB;;AAGA,MAAa,aACX,QACA,QAEA,OAAO,YACL,OAAO,QAAQ,OAAO,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CACnD,KACA,MAAM,QAAQ,oCAAoC,GAAG,SAAiB;CACpE,MAAM,QAAQ,IAAI;CAClB,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MAAM,UAAU,IAAI,UAAU,KAAK,kBAAkB;CACjE,OAAO;AACT,CAAC,CACH,CAAC,CACH"}
package/dist/daemon.d.ts CHANGED
@@ -9,6 +9,10 @@ export declare namespace Daemon {
9
9
  | {
10
10
  readonly command: "session-start";
11
11
  readonly sessionId: string;
12
+ }
13
+ /** From Claude Code's Notification hook: it waits for input, with nothing running. */
14
+ | {
15
+ readonly command: "idle";
12
16
  } | {
13
17
  readonly command: "attach";
14
18
  readonly cols: number;
@@ -28,6 +32,14 @@ export declare namespace Daemon {
28
32
  readonly waitingOn?: string;
29
33
  /** Claude Code said managed settings keep channels out: it drops their events. */
30
34
  readonly channelsRefused?: true;
35
+ /** The version of the Claude Code that runs, or ran last. */
36
+ readonly claudeVersion?: string;
37
+ /** A newer Claude Code than the one that runs (no `at`: it starts once the agent is idle), or the last restart into one. */
38
+ readonly update?: {
39
+ readonly from: string;
40
+ readonly to: string;
41
+ readonly at?: string;
42
+ };
31
43
  };
32
44
  }
33
45
  /** Sends one request to a running harnessd; undefined when none answers. */
@@ -1 +1 @@
1
- {"version":3,"file":"daemon.d.ts","sourceRoot":"","sources":["../src/daemon.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAyB,KAAK,QAAQ,EAAE,oBAAiB;AAIhE,OAAO,EAAyB,KAAK,QAAQ,EAAE,sBAAmB;AAElE,yBAAiB,MAAM,CAAC;IACtB,0IAA0I;IAC1I,KAAY,OAAO,GACf;QAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAA;KAAE;IACnD,2EAA2E;OACzE;QAAE,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;QAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;KAAE,GACjE;QACE,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;QAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;QACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;KACvB,CAAC;IAEN,KAAY,MAAM,GAAG,QAAQ,CAAC,MAAM,GAAG;QACrC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;QAC3B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QACzB,uEAAuE;QACvE,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;QAC1B,gDAAgD;QAChD,QAAQ,CAAC,eAAe,CAAC,EAAE,QAAQ,CACjC,MAAM,CAAC,MAAM,EAAE;YAAE,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;YAAC,QAAQ,CA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