@harness-sdk/harnessd 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +14 -13
  2. package/dist/accounts.d.ts +66 -0
  3. package/dist/accounts.d.ts.map +1 -0
  4. package/dist/accounts.js +166 -0
  5. package/dist/accounts.js.map +1 -0
  6. package/dist/bin.js +4 -0
  7. package/dist/bin.js.map +1 -1
  8. package/dist/channel.js +1 -1
  9. package/dist/claude.d.ts +12 -13
  10. package/dist/claude.d.ts.map +1 -1
  11. package/dist/claude.js +45 -59
  12. package/dist/claude.js.map +1 -1
  13. package/dist/cli.d.ts +5 -0
  14. package/dist/cli.d.ts.map +1 -1
  15. package/dist/cli.js +269 -114
  16. package/dist/cli.js.map +1 -1
  17. package/dist/config.d.ts +14 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +53 -13
  20. package/dist/config.js.map +1 -1
  21. package/dist/daemon.d.ts +17 -4
  22. package/dist/daemon.d.ts.map +1 -1
  23. package/dist/daemon.js +112 -51
  24. package/dist/daemon.js.map +1 -1
  25. package/dist/launchd.d.ts +12 -16
  26. package/dist/launchd.d.ts.map +1 -1
  27. package/dist/launchd.js +28 -25
  28. package/dist/launchd.js.map +1 -1
  29. package/dist/prompts.d.ts +53 -0
  30. package/dist/prompts.d.ts.map +1 -0
  31. package/dist/prompts.js +171 -0
  32. package/dist/prompts.js.map +1 -0
  33. package/dist/service.d.ts +37 -0
  34. package/dist/service.d.ts.map +1 -0
  35. package/dist/service.js +71 -0
  36. package/dist/service.js.map +1 -0
  37. package/dist/setup.d.ts +37 -0
  38. package/dist/setup.d.ts.map +1 -0
  39. package/dist/setup.js +121 -0
  40. package/dist/setup.js.map +1 -0
  41. package/dist/system.d.ts +6 -0
  42. package/dist/system.d.ts.map +1 -0
  43. package/dist/system.js +16 -0
  44. package/dist/system.js.map +1 -0
  45. package/dist/systemd.d.ts +14 -0
  46. package/dist/systemd.d.ts.map +1 -0
  47. package/dist/systemd.js +62 -0
  48. package/dist/systemd.js.map +1 -0
  49. package/dist/watchdog.d.ts +14 -4
  50. package/dist/watchdog.d.ts.map +1 -1
  51. package/dist/watchdog.js +30 -24
  52. package/dist/watchdog.js.map +1 -1
  53. package/package.json +5 -3
  54. package/src/accounts.ts +242 -0
  55. package/src/bin.ts +6 -0
  56. package/src/claude.ts +65 -90
  57. package/src/cli.ts +413 -152
  58. package/src/config.ts +92 -14
  59. package/src/daemon.ts +131 -64
  60. package/src/launchd.ts +40 -35
  61. package/src/prompts.ts +255 -0
  62. package/src/service.ts +145 -0
  63. package/src/setup.ts +188 -0
  64. package/src/system.ts +11 -0
  65. package/src/systemd.ts +78 -0
  66. package/src/watchdog.ts +41 -33
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["import { spawn, spawnSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\";\nimport { createConnection } from \"node:net\";\nimport { createInterface } from \"node:readline\";\nimport {\n allowChannel,\n channelBlockers,\n MANAGED_SETTINGS,\n which,\n} from \"./claude\";\nimport { readStatus, serveChannel, statusFile } from \"./channel\";\nimport { DEFAULT_CONFIG, pathsOf, readConfig, type Harnessd } from \"./config\";\nimport { ask, runDaemon, type Daemon } from \"./daemon\";\nimport { load, plistOf, stableNode, unload } from \"./launchd\";\nimport { logTo } from \"./log\";\n\nconst USAGE = `harnessd keeps Claude Code running on this Mac, connected to the events of your agentic apps.\n\nusage: harnessd <command>\n\n install Start harnessd now and at every login\n uninstall Stop harnessd and remove it from login\n status [--json] What runs, which conversation, and whether each channel's events arrive\n start Start Claude Code after a stop\n stop Stop Claude Code; it stays stopped until start\n new [message] Start a new conversation, with message as its first message\n attach Open Claude Code's terminal; Ctrl-\\\\ detaches\n logs Follow harnessd's log\n\nSettings: ~/.harnessd/config.json (HARNESSD_HOME moves the folder).`;\n\nconst DETACH = \"\\x1c\";\n\ntype Io = { out: (line: string) => void; err: (line: string) => void };\n\nconst notRunning = (paths: Harnessd.Paths) =>\n `harnessd isn't running in ${paths.home}: harnessd install starts it.`;\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 io[answer.ok ? \"out\" : \"err\"](String(answer.message));\n return answer.ok ? 0 : 1;\n};\n\nconst confirm = async (question: string) => {\n const lines = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const answer = await new Promise<string>((resolve) =>\n lines.question(`${question} [y/N] `, resolve),\n );\n lines.close();\n return /^y(es)?$/i.test(answer.trim());\n};\n\nconst install = async (paths: Harnessd.Paths, bin: string, io: Io) => {\n if (process.platform !== \"darwin\")\n throw new Error(\"harnessd runs on macOS (it starts with launchd).\");\n if (bin.includes(\"/_npx/\"))\n throw new Error(\n \"Install harnessd first, so launchd has a lasting copy to start: npm install -g @harness-sdk/harnessd\",\n );\n const claude = which(\"claude\");\n const version = spawnSync(claude, [\"--version\"], {\n encoding: \"utf8\",\n timeout: 30_000,\n });\n if (version.status !== 0)\n throw new Error(\n `${claude} --version failed: ${(version.stderr || version.stdout || \"\").trim()}`,\n );\n mkdirSync(paths.home, { recursive: true });\n if (!existsSync(paths.config))\n writeFileSync(paths.config, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\\n`);\n const config = readConfig(paths);\n mkdirSync(config.folder, { recursive: true });\n\n const blockers =\n Object.keys(config.channels).length > 0 ? channelBlockers() : [];\n if (blockers.length > 0) {\n io.out(\n `Claude Code lets a channel in only when this Mac's managed settings list it:\\n ${blockers.join(\"\\n \")}`,\n );\n if (\n process.stdin.isTTY &&\n (await confirm(\n `Let harnessd's channels in? This writes ${MANAGED_SETTINGS} with sudo.`,\n ))\n ) {\n const written = spawnSync(\n \"sudo\",\n [\n \"sh\",\n \"-c\",\n `mkdir -p \"$(dirname \"$1\")\" && cat > \"$1\"`,\n \"sh\",\n MANAGED_SETTINGS,\n ],\n {\n input: `${JSON.stringify(allowChannel(), null, 2)}\\n`,\n stdio: [\"pipe\", \"inherit\", \"inherit\"],\n },\n );\n if (written.status !== 0)\n throw new Error(`Couldn't write ${MANAGED_SETTINGS}.`);\n } else\n io.out(\n \"Until they're let in, Claude Code drops the channels' events; harnessd status says so.\",\n );\n }\n\n const env: Record<string, string> = {\n PATH: process.env.PATH ?? \"/usr/bin:/bin\",\n };\n if (process.env.HARNESSD_HOME) env.HARNESSD_HOME = paths.home;\n load(\n paths.label,\n plistOf({ label: paths.label, node: stableNode(), bin, env, paths }),\n );\n io.out(\n [\n `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and at every login.`,\n \" harnessd attach its terminal: sign in there if Claude Code asks; Ctrl-\\\\ detaches\",\n \" harnessd status what runs and whether events arrive\",\n \"Turn on automatic login (System Settings > Users & Groups), so harnessd comes back after a power cut.\",\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 blockers: string[],\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 : 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 ...(blockers.length > 0 && { blockers }),\n },\n ];\n }),\n );\n\nconst status = async (paths: Harnessd.Paths, json: boolean, io: Io) => {\n const answer = (await ask(paths.socket, { command: \"status\" })) as\n | { status?: Daemon.Status }\n | undefined;\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 blockers =\n config && Object.keys(config.channels).length > 0 ? channelBlockers() : [];\n const channels = channelReport(paths, config, answer?.status, blockers);\n const s = answer?.status;\n if (json) {\n io.out(\n JSON.stringify({\n running: !!s,\n home: paths.home,\n ...(s && { status: s }),\n ...(configError && { configError }),\n channels,\n }),\n );\n return s ? 0 : 1;\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.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 (\n blockers.length > 0 &&\n Object.values(channels).some((c) => c.events !== \"arriving\")\n )\n io.out(\n `channels are blocked: ${blockers.join(\"; \")} (harnessd install lets them in)`,\n );\n return s ? 0 : 1;\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 }).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 },\n): Promise<number> => {\n const paths = pathsOf();\n const [first, ...rest] = argv;\n switch (first) {\n case \"install\":\n return install(paths, bin, io);\n case \"uninstall\": {\n const had = unload(paths.label);\n io.out(\n had\n ? `Removed harnessd from login. Its settings and conversation stay in ${paths.home}.`\n : \"harnessd wasn't installed.\",\n );\n return 0;\n }\n case \"status\":\n return status(paths, rest.includes(\"--json\"), io);\n case \"start\":\n case \"stop\":\n return command(paths, { command: first }, io);\n case \"new\":\n return command(\n paths,\n { command: \"new\", ...(rest.length > 0 && { message: rest.join(\" \") }) },\n io,\n );\n case \"attach\":\n return attach(paths, io);\n case \"logs\":\n return new Promise((resolve) => {\n if (!existsSync(paths.log)) {\n io.err(`No log yet at ${paths.log}.`);\n return resolve(1);\n }\n spawn(\"tail\", [\"-n\", \"100\", \"-F\", paths.log], { stdio: \"inherit\" }).on(\n \"exit\",\n (code) => resolve(code ?? 0),\n );\n });\n case \"run\":\n await runDaemon(paths, bin);\n return 0;\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 case undefined:\n case \"help\":\n case \"--help\":\n case \"-h\":\n io.out(USAGE);\n return first === undefined ? 1 : 0;\n default:\n io.err(`Unknown command ${first}.\\n\\n${USAGE}`);\n return 2;\n }\n};\n"],"mappings":";;;;;;;;;;;AAgBA,MAAM,QAAQ;;;;;;;;;;;;;;AAed,MAAM,SAAS;AAIf,MAAM,cAAc,UAClB,6BAA6B,MAAM,KAAK;AAE1C,MAAM,UAAU,OACd,OACA,SACA,OACG;CACH,MAAM,SAAS,MAAM,IAAI,MAAM,QAAQ,OAAO;CAC9C,IAAI,CAAC,QAAQ;EACX,GAAG,IAAI,WAAW,KAAK,CAAC;EACxB,OAAO;CACT;CACA,GAAG,OAAO,KAAK,QAAQ,MAAM,CAAC,OAAO,OAAO,OAAO,CAAC;CACpD,OAAO,OAAO,KAAK,IAAI;AACzB;AAEA,MAAM,UAAU,OAAO,aAAqB;CAC1C,MAAM,QAAQ,gBAAgB;EAC5B,OAAO,QAAQ;EACf,QAAQ,QAAQ;CAClB,CAAC;CACD,MAAM,SAAS,MAAM,IAAI,SAAiB,YACxC,MAAM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AE,SAAS,KAAK,KAAK,GAAG,EAAE;EAAG,GACtE,EACF;EACF,KAAK,UACH,OAAO,OAAO,OAAO,EAAE;EACzB,KAAK,QACH,OAAO,IAAI,SAAS,YAAY;GAC9B,IAAI,CAAC,WAAW,MAAM,GAAG,GAAG;IAC1B,GAAG,IAAI,iBAAiB,MAAM,IAAI,EAAE;IACpC,OAAO,QAAQ,CAAC;GAClB;GACA,MAAM,QAAQ;IAAC;IAAM;IAAO;IAAM,MAAM;GAAG,GAAG,EAAE,OAAO,UAAU,CAAC,CAAC,CAAC,GAClE,SACC,SAAS,QAAQ,QAAQ,CAAC,CAC7B;EACF,CAAC;EACH,KAAK;GACH,MAAM,UAAU,OAAO,GAAG;GAC1B,OAAO;EACT,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,KAAK,KAAA;EACL,KAAK;EACL,KAAK;EACL,KAAK;GACH,GAAG,IAAI,KAAK;GACZ,OAAO,UAAU,KAAA,IAAY,IAAI;EACnC;GACE,GAAG,IAAI,mBAAmB,MAAM,OAAO,OAAO;GAC9C,OAAO;CACX;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 { 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,MA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O,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"}
package/dist/config.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export declare namespace Harnessd {
2
- /** `config.json` in harnessd's home, read at every start of Claude Code. */
2
+ /** `config.json`, read at every start of Claude Code. */
3
3
  type Config = {
4
4
  /** The agent's folder: Claude Code runs here and reads its CLAUDE.md. */
5
5
  readonly folder: string;
@@ -11,6 +11,12 @@ export declare namespace Harnessd {
11
11
  readonly prestart?: string;
12
12
  /** MCP servers whose events reach the agent, by name. */
13
13
  readonly channels: Readonly<Record<string, Channel>>;
14
+ /** 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
+ readonly accounts: Readonly<Record<string, Account>>;
16
+ };
17
+ /** 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. */
18
+ type Account = {
19
+ readonly env: Readonly<Record<string, string>>;
14
20
  };
15
21
  /** A Streamable HTTP MCP server; `${VAR}` in a header reads the environment. */
16
22
  type Channel = {
@@ -21,17 +27,24 @@ export declare namespace Harnessd {
21
27
  };
22
28
  /** Where one harnessd keeps its files. */
23
29
  type Paths = {
30
+ /** The folder harnessd writes to: its state, log and each channel's place. */
24
31
  readonly home: string;
25
32
  readonly config: string;
26
33
  readonly state: string;
27
34
  readonly log: string;
35
+ /** What harnessd itself prints, kept by the service that runs it: a start that failed says why here. */
36
+ readonly serviceLog: string;
28
37
  readonly socket: string;
29
38
  readonly plugin: string;
30
39
  readonly channels: string;
31
40
  readonly label: string;
41
+ /** The environment that gives another process these same paths. */
42
+ readonly env: Readonly<Record<string, string>>;
32
43
  };
33
44
  }
34
45
  export declare const pathsOf: (env?: NodeJS.ProcessEnv) => Harnessd.Paths;
46
+ /** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */
47
+ export declare const ownFolder: (dir: string) => void;
35
48
  export declare const DEFAULT_CONFIG: {
36
49
  folder: string;
37
50
  channels: {};
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAKA,yBAAiB,QAAQ,CAAC;IACxB,4EAA4E;IAC5E,KAAY,MAAM,GAAG;QACnB,yEAAyE;QACzE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;QACxB,mCAAmC;QACnC,QAAQ,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;QACjC,qCAAqC;QACrC,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;QAC/C,kGAAkG;QAClG,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAC3B,yDAAyD;QACzD,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;KACtD,CAAC;IAEF,gFAAgF;IAChF,KAAY,OAAO,GAAG;QACpB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;QACnD,sHAAsH;QACtH,QAAQ,CAAC,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,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EAAmE;QACnE,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;KAChD,CAAC;CACH;AAgBD,eAAO,MAAM,OAAO,GAClB,MAAK,MAAM,CAAC,UAAwB,KACnC,QAAQ,CAAC,KA8CX,CAAC;AAEF,oHAAoH;AACpH,eAAO,MAAM,SAAS,GAAI,KAAK,MAAM,SAGpC,CAAC;AAEF,eAAO,MAAM,cAAc;;;CAAsC,CAAC;AAoClE,eAAO,MAAM,WAAW,GAAI,KAAK,OAAO,KAAG,QAAQ,CAAC,MA0FnD,CAAC;AAEF,eAAO,MAAM,UAAU,GAAI,OAAO,QAAQ,CAAC,KAAK,KAAG,QAAQ,CAAC,MAY3D,CAAC;AAEF,gGAAgG;AAChG,eAAO,MAAM,SAAS,GACpB,SAAS,QAAQ,CAAC,OAAO,EACzB,KAAK,MAAM,CAAC,UAAU,KACrB,MAAM,CAAC,MAAM,EAAE,MAAM,CAWrB,CAAC"}
package/dist/config.js CHANGED
@@ -1,9 +1,8 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { join, resolve } from "node:path";
3
+ import { isAbsolute, join, resolve } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
5
  // src/config.ts
6
- const DEFAULT_HOME = join(homedir(), ".harnessd");
7
6
  const LOOPBACK = /* @__PURE__ */ new Set([
8
7
  "localhost",
9
8
  "127.0.0.1",
@@ -16,21 +15,48 @@ const RESERVED = /* @__PURE__ */ new Set([
16
15
  "help"
17
16
  ]);
18
17
  const SOCKET_MAX = 103;
18
+ const XDG = [
19
+ "XDG_CONFIG_HOME",
20
+ "XDG_STATE_HOME",
21
+ "XDG_RUNTIME_DIR"
22
+ ];
23
+ const tooLong = (socket) => Buffer.byteLength(socket) > SOCKET_MAX;
19
24
  const pathsOf = (env = process.env) => {
20
- const home = resolve(env.HARNESSD_HOME || DEFAULT_HOME);
21
- const socket = join(home, "harnessd.sock");
22
- if (Buffer.byteLength(socket) > SOCKET_MAX) throw new Error(`HARNESSD_HOME is too long for a socket (${socket})`);
25
+ const xdg = Object.fromEntries(XDG.flatMap((key) => env[key] && isAbsolute(env[key]) ? [[key, env[key]]] : []));
26
+ const one = env.HARNESSD_HOME ? resolve(env.HARNESSD_HOME) : void 0;
27
+ const configHome = xdg.XDG_CONFIG_HOME ?? join(homedir(), ".config");
28
+ const stateHome = xdg.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
29
+ const home = one ?? join(stateHome, "harnessd");
30
+ const id = createHash("sha256").update(home).digest("hex").slice(0, 8);
31
+ let socket = join(home, "harnessd.sock");
32
+ if (!one && tooLong(socket)) socket = xdg.XDG_RUNTIME_DIR ? join(xdg.XDG_RUNTIME_DIR, "harnessd", `${id}.sock`) : join("/tmp", `harnessd-${process.getuid?.() ?? 0}`, `${id}.sock`);
33
+ if (tooLong(socket)) throw new Error(`${one ? "HARNESSD_HOME" : "XDG_RUNTIME_DIR"} is too long for a socket (${socket})`);
23
34
  return {
24
35
  home,
25
- config: join(home, "config.json"),
36
+ config: join(one ?? join(configHome, "harnessd"), "config.json"),
26
37
  state: join(home, "state.json"),
27
38
  log: join(home, "harnessd.log"),
39
+ serviceLog: join(home, "service.log"),
28
40
  socket,
29
41
  plugin: join(home, "plugin"),
30
42
  channels: join(home, "channels"),
31
- label: home === DEFAULT_HOME ? "dev.harnessd" : `dev.harnessd.${createHash("sha256").update(home).digest("hex").slice(0, 8)}`
43
+ label: !one && stateHome === join(homedir(), ".local", "state") ? "dev.harnessd" : `dev.harnessd.${id}`,
44
+ env: one ? { HARNESSD_HOME: one } : {
45
+ HARNESSD_HOME: "",
46
+ XDG_CONFIG_HOME: configHome,
47
+ XDG_STATE_HOME: stateHome,
48
+ ...!socket.startsWith(home) && { XDG_RUNTIME_DIR: xdg.XDG_RUNTIME_DIR ?? "" }
49
+ }
32
50
  };
33
51
  };
52
+ /** Makes one of harnessd's folders, for this user only: its files hold account tokens and the conversation's id. */
53
+ const ownFolder = (dir) => {
54
+ mkdirSync(dir, {
55
+ recursive: true,
56
+ mode: 448
57
+ });
58
+ chmodSync(dir, 448);
59
+ };
34
60
  const DEFAULT_CONFIG = {
35
61
  folder: "~/agent",
36
62
  channels: {}
@@ -57,7 +83,8 @@ const parseConfig = (raw) => {
57
83
  "args",
58
84
  "env",
59
85
  "prestart",
60
- "channels"
86
+ "channels",
87
+ "accounts"
61
88
  ], "it");
62
89
  if (typeof value.folder !== "string" || value.folder === "") fail("folder must be a path");
63
90
  const args = value.args ?? [];
@@ -79,7 +106,7 @@ const parseConfig = (raw) => {
79
106
  try {
80
107
  url = new URL(String(entry.url));
81
108
  } catch {}
82
- 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 Mac: localhost, 127.0.0.1, [::1])`);
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])`);
83
110
  const args = entry.arguments ?? {};
84
111
  if (!isRecord(args) || Object.values(args).some((v) => ![
85
112
  "string",
@@ -92,16 +119,29 @@ const parseConfig = (raw) => {
92
119
  arguments: args
93
120
  };
94
121
  }
122
+ const accounts = {};
123
+ const named = value.accounts === void 0 ? {} : value.accounts;
124
+ if (!isRecord(named)) fail("accounts must map names to { env }");
125
+ for (const [name, account] of Object.entries(named)) {
126
+ if (!NAME.test(name)) fail(`account "${name}" needs a name of lowercase letters, digits and dashes`);
127
+ if (!isRecord(account)) fail(`accounts.${name} must be { env }`);
128
+ const entry = account;
129
+ only(entry, ["env"], `accounts.${name}`);
130
+ const env = strings(entry.env, `accounts.${name}.env`);
131
+ if ("CLAUDE_CONFIG_DIR" in env) fail(`accounts.${name}.env can't set CLAUDE_CONFIG_DIR; set it in the top-level env`);
132
+ accounts[name] = { env };
133
+ }
95
134
  return {
96
135
  folder: resolve(expandHome(value.folder)),
97
136
  args,
98
137
  env: strings(value.env, "env"),
99
138
  ...value.prestart !== void 0 && { prestart: value.prestart },
100
- channels
139
+ channels,
140
+ accounts
101
141
  };
102
142
  };
103
143
  const readConfig = (paths) => {
104
- if (!existsSync(paths.config)) throw new Error(`No ${paths.config}: run harnessd install`);
144
+ if (!existsSync(paths.config)) throw new Error(`No ${paths.config}: run harnessd service install`);
105
145
  let raw;
106
146
  try {
107
147
  raw = JSON.parse(readFileSync(paths.config, "utf8"));
@@ -116,6 +156,6 @@ const headersOf = (channel, env) => Object.fromEntries(Object.entries(channel.he
116
156
  if (found === void 0) throw new Error(`header ${key} needs $${name}, which isn't set`);
117
157
  return found;
118
158
  })]));
119
- export { DEFAULT_CONFIG, headersOf, parseConfig, pathsOf, readConfig };
159
+ export { DEFAULT_CONFIG, headersOf, ownFolder, parseConfig, pathsOf, readConfig };
120
160
 
121
161
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":[],"sources":["../src/config.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\n\nexport namespace Harnessd {\n /** `config.json` in harnessd's home, 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 };\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 readonly home: string;\n readonly config: string;\n readonly state: string;\n readonly log: string;\n readonly socket: string;\n readonly plugin: string;\n readonly channels: string;\n readonly label: string;\n };\n}\n\nconst DEFAULT_HOME = join(homedir(), \".harnessd\");\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\nexport const pathsOf = (\n env: NodeJS.ProcessEnv = process.env,\n): Harnessd.Paths => {\n const home = resolve(env.HARNESSD_HOME || DEFAULT_HOME);\n const socket = join(home, \"harnessd.sock\");\n if (Buffer.byteLength(socket) > SOCKET_MAX)\n throw new Error(`HARNESSD_HOME is too long for a socket (${socket})`);\n return {\n home,\n config: join(home, \"config.json\"),\n state: join(home, \"state.json\"),\n log: join(home, \"harnessd.log\"),\n socket,\n plugin: join(home, \"plugin\"),\n channels: join(home, \"channels\"),\n label:\n home === DEFAULT_HOME\n ? \"dev.harnessd\"\n : `dev.harnessd.${createHash(\"sha256\").update(home).digest(\"hex\").slice(0, 8)}`,\n };\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(value, [\"folder\", \"args\", \"env\", \"prestart\", \"channels\"], \"it\");\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 Mac: 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 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 };\n};\n\nexport const readConfig = (paths: Harnessd.Paths): Harnessd.Config => {\n if (!existsSync(paths.config))\n throw new Error(`No ${paths.config}: run harnessd 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":";;;;;AAyCA,MAAM,eAAe,KAAK,QAAQ,GAAG,WAAW;AAChD,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;AAC5D,MAAM,OAAO;AAEb,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAU;CAAS;AAAM,CAAC;AAEpD,MAAM,aAAa;AAEnB,MAAa,WACX,MAAyB,QAAQ,QACd;CACnB,MAAM,OAAO,QAAQ,IAAI,iBAAiB,YAAY;CACtD,MAAM,SAAS,KAAK,MAAM,eAAe;CACzC,IAAI,OAAO,WAAW,MAAM,IAAI,YAC9B,MAAM,IAAI,MAAM,2CAA2C,OAAO,EAAE;CACtE,OAAO;EACL;EACA,QAAQ,KAAK,MAAM,aAAa;EAChC,OAAO,KAAK,MAAM,YAAY;EAC9B,KAAK,KAAK,MAAM,cAAc;EAC9B;EACA,QAAQ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EAC5C;EACN,KAAK,QAAQ,MAAM,KAAK,KAAK;EAC7B,GAAI,MAAM,aAAa,KAAA,KAAa,EAAE,UAAU,MAAM,SAAmB;EACzE;CACF;AACF;AAEA,MAAa,cAAc,UAA2C;CACpE,IAAI,CAAC,WAAW,MAAM,MAAM,GAC1B,MAAM,IAAI,MAAM,MAAM,MAAM,OAAO,uBAAuB;CAC5D,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,SACA,QAEA,OAAO,YACL,OAAO,QAAQ,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CACpD,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"}
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;CAAS;AAAM,CAAC;AAEpD,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,MA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F;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,SACA,QAEA,OAAO,YACL,OAAO,QAAQ,QAAQ,OAAO,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CACpD,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
@@ -4,9 +4,11 @@ export declare namespace Daemon {
4
4
  /** A request on harnessd's socket: one line of JSON. An attach then streams `{ output }` lines and takes `{ input }` and `{ resize }`. */
5
5
  type Request = {
6
6
  readonly command: "status" | "stop" | "start";
7
- } | {
8
- readonly command: "new";
9
- readonly message?: string;
7
+ }
8
+ /** From Claude Code's SessionStart hook: the conversation it is in now. */
9
+ | {
10
+ readonly command: "session-start";
11
+ readonly sessionId: string;
10
12
  } | {
11
13
  readonly command: "attach";
12
14
  readonly cols: number;
@@ -15,10 +17,21 @@ export declare namespace Daemon {
15
17
  type Status = Watchdog.Status & {
16
18
  readonly daemonPid: number;
17
19
  readonly folder?: string;
20
+ /** The account Claude Code runs on, when the config names accounts. */
21
+ readonly account?: string;
22
+ /** The accounts passed over, and until when. */
23
+ readonly accountsStopped?: Readonly<Record<string, {
24
+ readonly why: string;
25
+ readonly until: string;
26
+ }>>;
27
+ /** The prompt Claude Code waits at until a person answers it. */
28
+ readonly waitingOn?: string;
29
+ /** Claude Code said managed settings keep channels out: it drops their events. */
30
+ readonly channelsRefused?: true;
18
31
  };
19
32
  }
20
33
  /** Sends one request to a running harnessd; undefined when none answers. */
21
34
  export declare const ask: (socket: string, request: Daemon.Request) => Promise<Record<string, unknown> | undefined>;
22
- /** `harnessd run`: what launchd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
35
+ /** `harnessd run`: what launchd or systemd keeps running. It keeps Claude Code running on a terminal and answers on its socket. */
23
36
  export declare const runDaemon: (paths: Harnessd.Paths, bin: string) => Promise<void>;
24
37
  //# sourceMappingURL=daemon.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"daemon.d.ts","sourceRoot":"","sources":["../src/daemon.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAc,KAAK,QAAQ,EAAE,oBAAiB;AAGrD,OAAO,EAAY,KAAK,QAAQ,EAAE,sBAAmB;AAErD,yBAAiB,MAAM,CAAC;IACtB,0IAA0I;IAC1I,KAAY,OAAO,GACf;QAAE,QAAQ,CAAC,OAAO,EAAE,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAA;KAAE,GACjD;QAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;QAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,GACtD;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;KAC1B,CAAC;CACH;AA0BD,4EAA4E;AAC5E,eAAO,MAAM,GAAG,GAAI,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,OAAO,iDAkBvD,CAA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