@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
@@ -1 +1 @@
1
- {"version":3,"file":"claude.js","names":[],"sources":["../src/claude.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport type { Harnessd } from \"./config\";\nimport type { Watchdog } from \"./watchdog\";\n\n/** How Claude Code names a `--plugin-dir` plugin, and what `--channels` takes. */\nexport const PLUGIN = \"harnessd@inline\";\nexport const MANAGED_SETTINGS =\n \"/Library/Application Support/ClaudeCode/managed-settings.json\";\n\nconst claudeDir = (env: NodeJS.ProcessEnv) =>\n env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n\n/**\n * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's\n * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field\n * changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.\n */\nexport const trustFolder = (\n folder: string,\n env: NodeJS.ProcessEnv = process.env,\n): boolean => {\n const file = env.CLAUDE_CONFIG_DIR\n ? join(env.CLAUDE_CONFIG_DIR, \".claude.json\")\n : join(homedir(), \".claude.json\");\n if (!existsSync(file)) return false;\n const text = readFileSync(file, \"utf8\");\n const config = JSON.parse(text) as {\n projects?: Record<string, { hasTrustDialogAccepted?: boolean }>;\n };\n const key = realpathSync(folder);\n if (config.projects?.[key]?.hasTrustDialogAccepted === true) return true;\n config.projects = {\n ...config.projects,\n [key]: { ...config.projects?.[key], hasTrustDialogAccepted: true },\n };\n const pretty = text.trimEnd() === JSON.stringify(JSON.parse(text), null, 2);\n const written = `${pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)}${text.endsWith(\"\\n\") ? \"\\n\" : \"\"}`;\n const temp = `${file}.harnessd-${process.pid}`;\n writeFileSync(temp, written, { mode: statSync(file).mode & 0o777 });\n renameSync(temp, file);\n return true;\n};\n\n/** A conversation's transcript, wherever Claude Code put it. */\nexport const findTranscript = (\n sessionId: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | undefined => {\n const projects = join(claudeDir(env), \"projects\");\n try {\n for (const dir of readdirSync(projects)) {\n const file = join(projects, dir, `${sessionId}.jsonl`);\n if (existsSync(file)) return file;\n }\n } catch {}\n return undefined;\n};\n\n/** The first `name` on `path` that can run. */\nexport const which = (name: string, path = process.env.PATH ?? \"\") => {\n if (name.includes(\"/\")) return name;\n for (const dir of path.split(delimiter)) {\n if (!dir) continue;\n try {\n accessSync(join(dir, name), constants.X_OK);\n return join(dir, name);\n } catch {}\n }\n throw new Error(\n `${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`,\n );\n};\n\n/**\n * harnessd's plugin, written before each start from the config's channels: one MCP server per channel, each\n * `harnessd channel <name>`. None: no plugin.\n */\nexport const writePlugin = (\n paths: Harnessd.Paths,\n config: Harnessd.Config,\n bin: string,\n): boolean => {\n rmSync(paths.plugin, { recursive: true, force: true });\n const names = Object.keys(config.channels);\n if (names.length === 0) return false;\n mkdirSync(join(paths.plugin, \".claude-plugin\"), { recursive: true });\n const manifest = {\n name: \"harnessd\",\n version: \"1.0.0\",\n description: \"harnessd's channels: each one's events, and its tools\",\n mcpServers: Object.fromEntries(\n names.map((name) => [\n name,\n {\n command: process.execPath,\n args: [bin, \"channel\", name],\n env: { HARNESSD_HOME: paths.home },\n },\n ]),\n ),\n channels: names.map((name) => ({ server: name, displayName: name })),\n };\n writeFileSync(\n join(paths.plugin, \".claude-plugin\", \"plugin.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n );\n return true;\n};\n\n/**\n * The claude command line for one start (after the binary). `--channels` names the plugin only when the managed\n * settings let it in: a refused entry there also shuts out the same plugin loaded with the development flag.\n */\nexport const claudeArgs = (o: {\n start: Watchdog.Start;\n plugin: string | undefined;\n allowed: boolean;\n config: Harnessd.Config;\n extra: readonly string[];\n}) => [\n \"--dangerously-skip-permissions\",\n ...(o.plugin ? [\"--plugin-dir\", o.plugin] : []),\n ...(o.plugin && o.allowed ? [\"--channels\", `plugin:${PLUGIN}`] : []),\n ...(o.start.resume\n ? [\"--resume\", o.start.sessionId]\n : [\"--session-id\", o.start.sessionId]),\n // before the config's arguments: after a list flag (--add-dir…) claude would take it as one more value\n ...(o.start.prompt ? [o.start.prompt] : []),\n ...o.config.args,\n ...o.extra,\n];\n\nexport type Prestart = { env: Record<string, string>; args: string[] };\n\n/** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */\nexport const prestart = (\n command: string,\n folder: string,\n env: NodeJS.ProcessEnv,\n log: (line: string) => void,\n) =>\n new Promise<Prestart>((resolve, reject) => {\n execFile(\n \"/bin/sh\",\n [\"-c\", command],\n { cwd: folder, env, timeout: 60_000, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n for (const line of stderr.split(\"\\n\"))\n if (line.trim()) log(`prestart: ${line}`);\n if (error)\n return reject(\n new Error(`prestart failed: ${error.message.split(\"\\n\")[0]}`),\n );\n if (!stdout.trim()) return resolve({ env: {}, args: [] });\n let parsed: unknown;\n try {\n parsed = JSON.parse(stdout);\n } catch {\n return reject(\n new Error(\n \"prestart printed something other than JSON { env?, args? }\",\n ),\n );\n }\n const {\n env: more = {},\n args = [],\n ...rest\n } = (parsed ?? {}) as { env?: unknown; args?: unknown };\n if (\n typeof parsed !== \"object\" ||\n Object.keys(rest).length > 0 ||\n typeof more !== \"object\" ||\n more === null ||\n Object.values(more).some((v) => typeof v !== \"string\") ||\n !Array.isArray(args) ||\n args.some((a) => typeof a !== \"string\")\n )\n return reject(\n new Error(\n \"prestart's JSON must be { env?: { NAME: string }, args?: string[] }\",\n ),\n );\n // harnessd finds the conversation before prestart runs, so where Claude Code keeps it comes from config.json\n if (\"CLAUDE_CONFIG_DIR\" in more)\n return reject(\n new Error(\n \"prestart can't set CLAUDE_CONFIG_DIR; set it in config.json's env\",\n ),\n );\n resolve({\n env: more as Record<string, string>,\n args: args as string[],\n });\n },\n );\n });\n\n/** What keeps harnessd's channels out of Claude Code on this Mac: its managed settings must let `harnessd@inline` in. */\nexport const channelBlockers = (file = MANAGED_SETTINGS): string[] => {\n let settings: { channelsEnabled?: unknown; allowedChannelPlugins?: unknown } =\n {};\n try {\n const parsed: unknown = JSON.parse(readFileSync(file, \"utf8\"));\n if (typeof parsed === \"object\" && parsed !== null) settings = parsed;\n } catch {}\n const listed =\n Array.isArray(settings.allowedChannelPlugins) &&\n settings.allowedChannelPlugins.some(\n (entry: unknown) =>\n entry === PLUGIN ||\n (typeof entry === \"object\" &&\n entry !== null &&\n (entry as { plugin?: unknown }).plugin === \"harnessd\" &&\n (entry as { marketplace?: unknown }).marketplace === \"inline\"),\n );\n return [\n ...(settings.channelsEnabled === true\n ? []\n : [`${file} doesn't set channelsEnabled: true`]),\n ...(listed\n ? []\n : [`${file} doesn't list ${PLUGIN} in allowedChannelPlugins`]),\n ];\n};\n\n/** The managed settings with harnessd's channel let in; a list that wasn't there starts with Anthropic's own channels. */\nexport const allowChannel = (\n file = MANAGED_SETTINGS,\n): Record<string, unknown> => {\n // only a missing file starts from nothing: anything else there is policy to keep\n const settings: Record<string, unknown> = existsSync(file)\n ? JSON.parse(readFileSync(file, \"utf8\"))\n : {};\n if (\n typeof settings !== \"object\" ||\n settings === null ||\n Array.isArray(settings)\n )\n throw new Error(\n `${file} isn't a JSON object; harnessd won't write over it`,\n );\n const list = Array.isArray(settings.allowedChannelPlugins)\n ? settings.allowedChannelPlugins\n : [\"telegram\", \"discord\", \"imessage\", \"fakechat\"].map((plugin) => ({\n marketplace: \"claude-plugins-official\",\n plugin,\n }));\n return {\n ...settings,\n channelsEnabled: true,\n allowedChannelPlugins: [\n ...list.filter(\n (entry) => !(typeof entry === \"object\" && entry?.plugin === \"harnessd\"),\n ),\n { marketplace: \"inline\", plugin: \"harnessd\" },\n ],\n };\n};\n"],"mappings":";;;;;;AAoBA,MAAa,SAAS;AACtB,MAAa,mBACX;AAEF,MAAM,aAAa,QACjB,IAAI,qBAAqB,KAAK,QAAQ,GAAG,SAAS;;;;;;AAOpD,MAAa,eACX,QACA,MAAyB,QAAQ,QACrB;CACZ,MAAM,OAAO,IAAI,oBACb,KAAK,IAAI,mBAAmB,cAAc,IAC1C,KAAK,QAAQ,GAAG,cAAc;CAClC,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,MAAM,OAAO,aAAa,MAAM,MAAM;CACtC,MAAM,SAAS,KAAK,MAAM,IAAI;CAG9B,MAAM,MAAM,aAAa,MAAM;CAC/B,IAAI,OAAO,WAAW,IAAI,EAAE,2BAA2B,MAAM,OAAO;CACpE,OAAO,WAAW;EAChB,GAAG,OAAO;GACT,MAAM;GAAE,GAAG,OAAO,WAAW;GAAM,wBAAwB;EAAK;CACnE;CAEA,MAAM,UAAU,GADD,KAAK,QAAQ,MAAM,KAAK,UAAU,KAAK,MAAM,IAAI,GAAG,MAAM,CAAC,IAC9C,KAAK,UAAU,QAAQ,MAAM,CAAC,IAAI,KAAK,UAAU,MAAM,IAAI,KAAK,SAAS,IAAI,IAAI,O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U,CAAC,CAAC,KAAK,YAAY;EAC/D,aAAa;EACb;CACF,EAAE;CACN,OAAO;EACL,GAAG;EACH,iBAAiB;EACjB,uBAAuB,CACrB,GAAG,KAAK,QACL,UAAU,EAAE,OAAO,UAAU,YAAY,OAAO,WAAW,WAC9D,GACA;GAAE,aAAa;GAAU,QAAQ;EAAW,CAC9C;CACF;AACF"}
1
+ {"version":3,"file":"claude.js","names":[],"sources":["../src/claude.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n realpathSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport type { Harnessd } from \"./config\";\nimport type { Watchdog } from \"./watchdog\";\n\n/** How Claude Code names a `--plugin-dir` plugin. */\nexport const PLUGIN = \"harnessd@inline\";\n\nconst claudeDir = (env: NodeJS.ProcessEnv) =>\n env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n\n/**\n * Records the folder as trusted where Claude Code keeps its answer to the trust dialog (its global config's\n * `projects[<folder>].hasTrustDialogAccepted`), so an unattended start doesn't stop at that dialog. Only that field\n * changes; a Mac where Claude Code never ran has no config yet, and the dialog comes with the sign-in.\n */\nexport const trustFolder = (\n folder: string,\n env: NodeJS.ProcessEnv = process.env,\n): boolean => {\n const file = env.CLAUDE_CONFIG_DIR\n ? join(env.CLAUDE_CONFIG_DIR, \".claude.json\")\n : join(homedir(), \".claude.json\");\n if (!existsSync(file)) return false;\n const text = readFileSync(file, \"utf8\");\n const config = JSON.parse(text) as {\n projects?: Record<string, { hasTrustDialogAccepted?: boolean }>;\n };\n const key = realpathSync(folder);\n if (config.projects?.[key]?.hasTrustDialogAccepted === true) return true;\n config.projects = {\n ...config.projects,\n [key]: { ...config.projects?.[key], hasTrustDialogAccepted: true },\n };\n const pretty = text.trimEnd() === JSON.stringify(JSON.parse(text), null, 2);\n const written = `${pretty ? JSON.stringify(config, null, 2) : JSON.stringify(config)}${text.endsWith(\"\\n\") ? \"\\n\" : \"\"}`;\n const temp = `${file}.harnessd-${process.pid}`;\n writeFileSync(temp, written, { mode: statSync(file).mode & 0o777 });\n renameSync(temp, file);\n return true;\n};\n\n/** A conversation's transcript, wherever Claude Code put it. */\nexport const findTranscript = (\n sessionId: string,\n env: NodeJS.ProcessEnv = process.env,\n): string | undefined => {\n const projects = join(claudeDir(env), \"projects\");\n try {\n for (const dir of readdirSync(projects)) {\n const file = join(projects, dir, `${sessionId}.jsonl`);\n if (existsSync(file)) return file;\n }\n } catch {}\n return undefined;\n};\n\n/** The first `name` on `path` that can run. */\nexport const which = (name: string, path = process.env.PATH ?? \"\") => {\n if (name.includes(\"/\")) return name;\n for (const dir of path.split(delimiter)) {\n if (!dir) continue;\n try {\n accessSync(join(dir, name), constants.X_OK);\n return join(dir, name);\n } catch {}\n }\n throw new Error(\n `${name} isn't on PATH (${path}); install Claude Code: curl -fsSL https://claude.ai/install.sh | bash`,\n );\n};\n\nconst shellQuote = (text: string) => `'${text.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n/**\n * harnessd's plugin, written before each start: one MCP server per channel of the config, each\n * `harnessd channel <name>`, and a SessionStart hook that tells harnessd which conversation Claude Code is in, so a\n * /clear or a /resume is the conversation the next start resumes.\n */\nexport const writePlugin = (\n paths: Harnessd.Paths,\n config: Harnessd.Config,\n bin: string,\n) => {\n rmSync(paths.plugin, { recursive: true, force: true });\n mkdirSync(join(paths.plugin, \".claude-plugin\"), { recursive: true });\n const names = Object.keys(config.channels);\n const sessionStart = [\n ...Object.entries(paths.env).map(\n ([name, value]) => `${name}=${shellQuote(value)}`,\n ),\n shellQuote(process.execPath),\n shellQuote(bin),\n \"session-start\",\n ].join(\" \");\n const manifest = {\n name: \"harnessd\",\n version: \"1.0.0\",\n description:\n \"harnessd's channels, each one's events and tools, and its SessionStart hook\",\n ...(names.length > 0 && {\n mcpServers: Object.fromEntries(\n names.map((name) => [\n name,\n {\n command: process.execPath,\n args: [bin, \"channel\", name],\n env: paths.env,\n },\n ]),\n ),\n channels: names.map((name) => ({ server: name, displayName: name })),\n }),\n hooks: {\n SessionStart: [{ hooks: [{ type: \"command\", command: sessionStart }] }],\n },\n };\n writeFileSync(\n join(paths.plugin, \".claude-plugin\", \"plugin.json\"),\n `${JSON.stringify(manifest, null, 2)}\\n`,\n );\n};\n\n/** Whether these claude arguments pick a permission mode themselves. */\nconst picksPermissionMode = (args: readonly string[]) =>\n args.some(\n (arg) =>\n arg === \"--dangerously-skip-permissions\" ||\n arg === \"--permission-mode\" ||\n arg.startsWith(\"--permission-mode=\"),\n );\n\n/** Whether these claude arguments turn permission prompts off: the config's `args` (or prestart's) ask for it, harnessd never does. */\nexport const skipsPermissions = (args: readonly string[]) =>\n args.some(\n (arg, i) =>\n arg === \"--dangerously-skip-permissions\" ||\n arg === \"--permission-mode=bypassPermissions\" ||\n (arg === \"bypassPermissions\" && args[i - 1] === \"--permission-mode\"),\n );\n\n/**\n * The claude command line for one start (after the binary). Claude Code runs in its auto permission mode, which\n * decides each action itself, unless the config's arguments pick another mode. harnessd's plugin is written on this Mac at each start, so\n * its channels load with Claude Code's flag for local channels, which asks for no entry in an approved list. Claude\n * Code then asks once per start whether this is local development; harnessd answers that (see prompts.ts).\n */\nexport const claudeArgs = (o: {\n start: Watchdog.Start;\n plugin: string;\n config: Harnessd.Config;\n extra: readonly string[];\n}) => [\n ...(picksPermissionMode([...o.config.args, ...o.extra])\n ? []\n : [\"--permission-mode\", \"auto\"]),\n \"--plugin-dir\",\n o.plugin,\n ...(Object.keys(o.config.channels).length > 0\n ? [\"--dangerously-load-development-channels\", `plugin:${PLUGIN}`]\n : []),\n ...(o.start.resume\n ? [\"--resume\", o.start.sessionId]\n : [\"--session-id\", o.start.sessionId]),\n // before the config's arguments: after a list flag (--add-dir…) claude would take it as one more value\n ...(o.start.prompt ? [o.start.prompt] : []),\n ...o.config.args,\n ...o.extra,\n];\n\nexport type Prestart = { env: Record<string, string>; args: string[] };\n\n/** Runs the config's prestart command in the agent's folder: its stdout is JSON `{ env?, args? }`, or nothing. */\nexport const prestart = (\n command: string,\n folder: string,\n env: NodeJS.ProcessEnv,\n log: (line: string) => void,\n) =>\n new Promise<Prestart>((resolve, reject) => {\n execFile(\n \"/bin/sh\",\n [\"-c\", command],\n { cwd: folder, env, timeout: 60_000, maxBuffer: 16 * 1024 * 1024 },\n (error, stdout, stderr) => {\n for (const line of stderr.split(\"\\n\"))\n if (line.trim()) log(`prestart: ${line}`);\n if (error)\n return reject(\n new Error(`prestart failed: ${error.message.split(\"\\n\")[0]}`),\n );\n if (!stdout.trim()) return resolve({ env: {}, args: [] });\n let parsed: unknown;\n try {\n parsed = JSON.parse(stdout);\n } catch {\n return reject(\n new Error(\n \"prestart printed something other than JSON { env?, args? }\",\n ),\n );\n }\n const {\n env: more = {},\n args = [],\n ...rest\n } = (parsed ?? {}) as { env?: unknown; args?: unknown };\n if (\n typeof parsed !== \"object\" ||\n Object.keys(rest).length > 0 ||\n typeof more !== \"object\" ||\n more === null ||\n Object.values(more).some((v) => typeof v !== \"string\") ||\n !Array.isArray(args) ||\n args.some((a) => typeof a !== \"string\")\n )\n return reject(\n new Error(\n \"prestart's JSON must be { env?: { NAME: string }, args?: string[] }\",\n ),\n );\n // harnessd finds the conversation before prestart runs, so where Claude Code keeps it comes from config.json\n if (\"CLAUDE_CONFIG_DIR\" in more)\n return reject(\n new Error(\n \"prestart can't set CLAUDE_CONFIG_DIR; set it in config.json's env\",\n ),\n );\n resolve({\n env: more as Record<string, string>,\n args: args as string[],\n });\n },\n );\n });\n"],"mappings":";;;;;;AAoBA,MAAa,SAAS;AAEtB,MAAM,aAAa,QACjB,IAAI,qBAAqB,KAAK,QAAQ,GAAG,SAAS;;;;;;AAOpD,MAAa,eACX,QACA,MAAyB,QAAQ,QACrB;CACZ,MAAM,OAAO,IAAI,oBACb,KAAK,IAAI,mBAAmB,cAAc,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,SAAS,KAC3B,OAAO,SAAS,YAChB,SAAS,QACT,OAAO,OAAO,IAAI,CAAC,CAAC,MAAM,MAAM,OAAO,MAAM,QAAQ,KACrD,CAAC,MAAM,QAAQ,IAAI,KACnB,KAAK,MAAM,MAAM,OAAO,MAAM,QAAQ,GAEtC,OAAO,uBACL,IAAI,MACF,qEACF,CACF;EAEF,IAAI,uBAAuB,MACzB,OAAO,uBACL,IAAI,MACF,mEACF,CACF;EACF,QAAQ;GACN,KAAK;GACC;EACR,CAAC;CACH,CACF;AACF,CAAC"}
package/dist/cli.d.ts CHANGED
@@ -1,6 +1,11 @@
1
+ import { type Setup } from "./setup.js";
1
2
  type Io = {
2
3
  out: (line: string) => void;
3
4
  err: (line: string) => void;
5
+ /** The person to ask; none when harnessd runs from a script. */
6
+ terminal?: Setup.Terminal | undefined;
7
+ /** What the command was given on stdin, for a hook. */
8
+ stdin?: () => Promise<string>;
4
9
  };
5
10
  /** Runs one harnessd command; resolves to the exit code. */
6
11
  export declare const runHarnessd: (argv: readonly string[], bin: string, io?: Io) => Promise<number>;
package/dist/cli.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAiCA,KAAK,EAAE,GAAG;IAAE,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAAC,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAA;CAAE,CAAC;AA0QvE,4DAA4D;AAC5D,eAAO,MAAM,WAAW,GACtB,MAAM,SAAS,MAAM,EAAE,EACvB,KAAK,MAAM,EACX,KAAI,EAGH,KACA,OAAO,CAAC,MAAM,CAgEhB,CAAC"}
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAyBA,OAAO,EAA6C,KAAK,KAAK,EAAE,mBAAgB;AAyChF,KAAK,EAAE,GAAG;IACR,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,gEAAgE;IAChE,QAAQ,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,SAAS,CAAC;IACtC,uDAAuD;IACvD,KAAK,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;CAC/B,CAAC;AAgcF,4DAA4D;AAC5D,eAAO,MAAM,WAAW,GACtB,MAAM,SAAS,MAAM,EAAE,EACvB,KAAK,MAAM,EACX,KAAI,EAIH,KACA,OAAO,CAAC,MAAM,CAiBhB,CAAC"}
package/dist/cli.js CHANGED
@@ -1,95 +1,218 @@
1
- import { MANAGED_SETTINGS, allowChannel, channelBlockers, which } from "./claude.js";
2
- import { DEFAULT_CONFIG, pathsOf, readConfig } from "./config.js";
1
+ import { DEFAULT_CONFIG, ownFolder, pathsOf, readConfig } from "./config.js";
3
2
  import { readStatus, serveChannel, statusFile } from "./channel.js";
4
3
  import { logTo } from "./log.js";
4
+ import { CHANNELS_REFUSED } from "./prompts.js";
5
5
  import { ask, runDaemon } from "./daemon.js";
6
- import { load, plistOf, stableNode, unload } from "./launchd.js";
7
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
8
- import { spawn, spawnSync } from "node:child_process";
6
+ import { stableNode } from "./launchd.js";
7
+ import { asUser, installService, lookUpUser, removeService, serviceIn, servicePath, serviceText, supportedPlatform } from "./service.js";
8
+ import { ensureClaude, ensureSignedIn, ttyTerminal } from "./setup.js";
9
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { spawnSync } from "node:child_process";
11
+ import { createRequire } from "node:module";
9
12
  import { createConnection } from "node:net";
13
+ import { userInfo } from "node:os";
14
+ import { delimiter, dirname } from "node:path";
10
15
  import { createInterface } from "node:readline";
11
16
  // src/cli.ts
12
- const USAGE = `harnessd keeps Claude Code running on this Mac, connected to the events of your agentic apps.
17
+ const USAGE = `harnessd keeps Claude Code running on this computer, connected to the events of your agentic apps.
13
18
 
14
19
  usage: harnessd <command>
15
20
 
16
- install Start harnessd now and at every login
17
- uninstall Stop harnessd and remove it from login
18
- status [--json] What runs, which conversation, and whether each channel's events arrive
19
- start Start Claude Code after a stop
20
- stop Stop Claude Code; it stays stopped until start
21
- new [message] Start a new conversation, with message as its first message
22
- attach Open Claude Code's terminal; Ctrl-\\ detaches
23
- logs Follow harnessd's log
21
+ service install Start harnessd now and at every login; with sudo, at every boot
22
+ service uninstall Stop harnessd and remove its service
23
+ status [--json] What runs, which conversation, each channel's events, and the log's last lines
24
+ start Start Claude Code after a stop
25
+ stop Stop Claude Code; harnessd stays up, and Claude Code stays stopped until start
26
+ attach Open Claude Code's terminal; Ctrl-\\ detaches
27
+ --version Print harnessd's version
24
28
 
25
- Settings: ~/.harnessd/config.json (HARNESSD_HOME moves the folder).`;
29
+ service install takes:
30
+ --user <name> With sudo: the user the boot service runs as; service uninstall takes it too
31
+ --dry-run Print the service's file and change nothing
32
+ --install-claude When Claude Code is missing, install it with Anthropic's installer without asking
33
+ --skip-sign-in Install even when Claude Code isn't signed in, and print how to sign in
34
+
35
+ Settings: ~/.config/harnessd/config.json. State and log: ~/.local/state/harnessd.
36
+ XDG_CONFIG_HOME and XDG_STATE_HOME move them; HARNESSD_HOME puts both in one folder.`;
37
+ const VERSION = createRequire(import.meta.url)("../package.json").version;
26
38
  const DETACH = "";
27
- const notRunning = (paths) => `harnessd isn't running in ${paths.home}: harnessd install starts it.`;
39
+ const stdin = async () => {
40
+ let text = "";
41
+ for await (const chunk of process.stdin) text += String(chunk);
42
+ return text;
43
+ };
44
+ const notRunning = (paths) => `harnessd isn't running in ${paths.home}: harnessd service install starts it.`;
45
+ const usageError = (message) => Object.assign(new Error(message), { usage: true });
46
+ /** Refuses any argument a command doesn't take, so a typo never runs the command. */
47
+ const takes = (command, rest, allowed = []) => {
48
+ const extra = rest.find((arg) => !allowed.includes(arg));
49
+ if (extra !== void 0) throw usageError(`harnessd ${command} takes ${allowed.length > 0 ? `only ${allowed.join(", ")}` : "no arguments"}, not ${extra}.`);
50
+ };
51
+ const tail = (file, lines) => {
52
+ try {
53
+ const text = readFileSync(file, "utf8").trimEnd();
54
+ return text ? text.split("\n").slice(-lines) : [];
55
+ } catch {
56
+ return [];
57
+ }
58
+ };
59
+ const daemonStatus = async (paths) => (await ask(paths.socket, { command: "status" }))?.status;
60
+ const START_WAIT_MS = 9e4;
61
+ /** Waits until Claude Code runs, was stopped by hand, or failed to start; `not` is the harnessd an install replaces. */
62
+ const settled = async (paths, not, waitMs = START_WAIT_MS) => {
63
+ const until = Date.now() + waitMs;
64
+ for (;;) {
65
+ const status = await daemonStatus(paths);
66
+ const ours = status && status.daemonPid !== not ? status : void 0;
67
+ if (ours && ours.state !== "starting" || Date.now() >= until) return ours;
68
+ await new Promise((resolve) => setTimeout(resolve, 250));
69
+ }
70
+ };
71
+ /** After a failed start: the log lines that show why; resolves to the exit code. */
72
+ const showLog = (log, io) => {
73
+ for (const line of tail(log, 10)) io.err(` ${line}`);
74
+ io.err(`log ${log}`);
75
+ return 1;
76
+ };
77
+ /** Says why a start failed, with the log's last lines; resolves to the exit code. */
78
+ const startFailed = (paths, status, io) => {
79
+ io.err(!status ? "harnessd didn't start." : status.state === "waiting" ? `Claude Code didn't stay up${status.lastExit ? ` (exit code ${status.lastExit.code})` : ""}; harnessd keeps trying.` : "Claude Code is still starting; harnessd status shows how it goes.");
80
+ return showLog(status ? paths.log : paths.serviceLog, io);
81
+ };
28
82
  const command = async (paths, request, io) => {
29
83
  const answer = await ask(paths.socket, request);
30
84
  if (!answer) {
31
85
  io.err(notRunning(paths));
32
86
  return 1;
33
87
  }
34
- io[answer.ok ? "out" : "err"](String(answer.message));
35
- return answer.ok ? 0 : 1;
88
+ if (!answer.ok) {
89
+ io.err(String(answer.message));
90
+ return request.command === "stop" ? 1 : showLog(paths.log, io);
91
+ }
92
+ if (request.command !== "stop") {
93
+ const status = await settled(paths);
94
+ if (status?.state !== "running") return startFailed(paths, status, io);
95
+ }
96
+ io.out(String(answer.message));
97
+ return 0;
36
98
  };
37
- const confirm = async (question) => {
38
- const lines = createInterface({
39
- input: process.stdin,
40
- output: process.stdout
99
+ /** Who the service is for: with sudo, a boot service that runs as the named user; without, your own login item. */
100
+ const serviceTarget = (action, flags) => {
101
+ const root = process.getuid?.() === 0;
102
+ if (flags.user !== void 0 && !root && !flags.dryRun) throw new Error(`A boot service needs root: sudo harnessd service ${action} --user ${flags.user}`);
103
+ const name = flags.user ?? (root ? process.env.SUDO_USER : void 0);
104
+ if (root && name === void 0) throw new Error("Name the user harnessd runs as: --user <name>");
105
+ const user = name === void 0 ? void 0 : lookUpUser(name);
106
+ const caller = process.env.SUDO_USER ?? userInfo().username;
107
+ const moved = [
108
+ "HARNESSD_HOME",
109
+ "XDG_CONFIG_HOME",
110
+ "XDG_STATE_HOME"
111
+ ].find((key) => process.env[key]);
112
+ if (user && user.name !== caller && moved) throw new Error(`${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.`);
113
+ if (user) Object.assign(process.env, {
114
+ HOME: user.home,
115
+ USER: user.name,
116
+ LOGNAME: user.name
41
117
  });
42
- const answer = await new Promise((resolve) => lines.question(`${question} [y/N] `, resolve));
43
- lines.close();
44
- return /^y(es)?$/i.test(answer.trim());
118
+ const paths = pathsOf();
119
+ if (user && !paths.socket.startsWith(paths.home)) throw new Error(`${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.`);
120
+ const bootLabel = (name) => paths.label === "dev.harnessd" ? `dev.harnessd.${name}` : paths.label;
121
+ return {
122
+ user,
123
+ paths,
124
+ label: user ? bootLabel(user.name) : paths.label,
125
+ /** The other kind's file, when one is installed for this state folder: it holds one harnessd. */
126
+ other: () => serviceIn(paths.home, user === void 0)
127
+ };
45
128
  };
46
- const install = async (paths, bin, io) => {
47
- if (process.platform !== "darwin") throw new Error("harnessd runs on macOS (it starts with launchd).");
48
- if (bin.includes("/_npx/")) throw new Error("Install harnessd first, so launchd has a lasting copy to start: npm install -g @harness-sdk/harnessd");
49
- const claude = which("claude");
129
+ const uninstall = (flags, io) => {
130
+ const { user, paths, label, other } = serviceTarget("uninstall", flags);
131
+ if (removeService(label, user !== void 0)) {
132
+ io.out(`Removed harnessd's service. Its settings stay in ${paths.config}, its conversation in ${paths.home}.`);
133
+ return 0;
134
+ }
135
+ const file = other();
136
+ io[file ? "err" : "out"](file ? `harnessd is installed as a ${user ? "login item" : "boot service"} (${file}): run ${user ? "" : "sudo "}harnessd service uninstall.` : "harnessd wasn't installed.");
137
+ return file ? 1 : 0;
138
+ };
139
+ const install = async (flags, bin, io) => {
140
+ supportedPlatform();
141
+ if (bin.includes("/_npx/")) throw new Error("Install harnessd first, so the service has a lasting copy to start: npm install -g @harness-sdk/harnessd");
142
+ const { user, paths, label, other } = serviceTarget("install", flags);
143
+ const own = (process.env.PATH ?? "/usr/bin:/bin").split(delimiter);
144
+ const terminal = flags.dryRun ? void 0 : io.terminal;
145
+ const claude = await ensureClaude({
146
+ terminal,
147
+ user,
148
+ install: flags.installClaude && !flags.dryRun
149
+ });
50
150
  const version = spawnSync(claude, ["--version"], {
51
151
  encoding: "utf8",
52
- timeout: 3e4
152
+ timeout: 3e4,
153
+ ...user && process.getuid?.() === 0 && {
154
+ uid: user.uid,
155
+ gid: user.gid
156
+ }
53
157
  });
54
158
  if (version.status !== 0) throw new Error(`${claude} --version failed: ${(version.stderr || version.stdout || "").trim()}`);
55
- mkdirSync(paths.home, { recursive: true });
56
- if (!existsSync(paths.config)) writeFileSync(paths.config, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`);
57
- const config = readConfig(paths);
58
- mkdirSync(config.folder, { recursive: true });
59
- const blockers = Object.keys(config.channels).length > 0 ? channelBlockers() : [];
60
- if (blockers.length > 0) {
61
- io.out(`Claude Code lets a channel in only when this Mac's managed settings list it:\n ${blockers.join("\n ")}`);
62
- if (process.stdin.isTTY && await confirm(`Let harnessd's channels in? This writes /Library/Application Support/ClaudeCode/managed-settings.json with sudo.`)) {
63
- if (spawnSync("sudo", [
64
- "sh",
65
- "-c",
66
- `mkdir -p "$(dirname "$1")" && cat > "$1"`,
67
- "sh",
68
- "/Library/Application Support/ClaudeCode/managed-settings.json"
69
- ], {
70
- input: `${JSON.stringify(allowChannel(), null, 2)}\n`,
71
- stdio: [
72
- "pipe",
73
- "inherit",
74
- "inherit"
75
- ]
76
- }).status !== 0) throw new Error(`Couldn't write ${MANAGED_SETTINGS}.`);
77
- } else io.out("Until they're let in, Claude Code drops the channels' events; harnessd status says so.");
78
- }
79
- const env = { PATH: process.env.PATH ?? "/usr/bin:/bin" };
80
- if (process.env.HARNESSD_HOME) env.HARNESSD_HOME = paths.home;
81
- load(paths.label, plistOf({
82
- label: paths.label,
83
- node: stableNode(),
159
+ const node = stableNode();
160
+ const spec = {
161
+ label,
162
+ node,
84
163
  bin,
85
- env,
86
- paths
87
- }));
164
+ env: {
165
+ PATH: [.../* @__PURE__ */ new Set([
166
+ ...own,
167
+ dirname(claude),
168
+ dirname(node)
169
+ ])].filter((dir) => dir.startsWith("/")).join(delimiter),
170
+ ...user && {
171
+ HOME: user.home,
172
+ USER: user.name,
173
+ LOGNAME: user.name
174
+ },
175
+ ...paths.env
176
+ },
177
+ paths,
178
+ ...user && { user: user.name }
179
+ };
180
+ const file = servicePath(label, user !== void 0);
181
+ if (flags.dryRun) {
182
+ io.out(`Would write ${file} and start it${user ? `, as root, to run as ${user.name} from every boot` : ""}:\n\n${serviceText(spec)}`);
183
+ return 0;
184
+ }
185
+ const taken = other();
186
+ if (taken) throw new Error(`harnessd is already installed as a ${user ? "login item" : "boot service"} (${taken}): run ${user ? "" : "sudo "}harnessd service uninstall first.`);
187
+ const config = asUser(user, () => {
188
+ ownFolder(paths.home);
189
+ ownFolder(dirname(paths.config));
190
+ if (!existsSync(paths.config)) writeFileSync(paths.config, `${JSON.stringify(DEFAULT_CONFIG, null, 2)}\n`);
191
+ chmodSync(paths.config, 384);
192
+ appendFileSync(paths.serviceLog, "");
193
+ const config = readConfig(paths);
194
+ mkdirSync(config.folder, { recursive: true });
195
+ return config;
196
+ });
197
+ const signIn = await ensureSignedIn({
198
+ claude,
199
+ paths,
200
+ env: spec.env,
201
+ user,
202
+ terminal,
203
+ skip: flags.skipSignIn
204
+ });
205
+ const before = (await daemonStatus(paths))?.daemonPid;
206
+ await installService(spec);
207
+ const status = await settled(paths, before);
208
+ if (status?.state !== "running" && status?.state !== "stopped") return startFailed(paths, status, io);
209
+ const when = user ? `at every boot, as ${user.name}` : "at every login";
88
210
  io.out([
89
- `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and at every login.`,
90
- " harnessd attach its terminal: sign in there if Claude Code asks; Ctrl-\\ detaches",
211
+ status.state === "stopped" ? `harnessd is installed for ${config.folder} and starts ${when}. Claude Code is stopped: harnessd start starts it.` : `harnessd runs Claude Code in ${config.folder} (${version.stdout.trim()}), now and ${when}.`,
212
+ " harnessd attach its terminal; Ctrl-\\ detaches",
91
213
  " harnessd status what runs and whether events arrive",
92
- "Turn on automatic login (System Settings > Users & Groups), so harnessd comes back after a power cut."
214
+ ...signIn ? [signIn] : [],
215
+ ...user ? [] : [process.platform === "darwin" ? "It starts when you log in: turn on automatic login (System Settings > Users & Groups), so it comes back after a power cut." : "It starts when you sign in and stops when you sign out.", `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`]
93
216
  ].join("\n"));
94
217
  return 0;
95
218
  };
@@ -98,20 +221,19 @@ const ago = (iso) => {
98
221
  return s < 120 ? `${s}s` : s < 7200 ? `${Math.round(s / 60)}m` : s < 172800 ? `${Math.round(s / 3600)}h` : `${Math.round(s / 86400)}d`;
99
222
  };
100
223
  /** Each channel as of the Claude Code that runs now: what an earlier run heard says nothing about this one. */
101
- const channelReport = (paths, config, running, blockers) => Object.fromEntries(Object.entries(config?.channels ?? {}).map(([name, channel]) => {
224
+ const channelReport = (paths, config, running) => Object.fromEntries(Object.entries(config?.channels ?? {}).map(([name, channel]) => {
102
225
  const status = readStatus(statusFile(paths, name));
103
226
  const since = running?.state === "running" || running?.state === "starting" ? running.startedAt : void 0;
104
227
  const now = (at) => since !== void 0 && at !== void 0 && at >= since;
105
- const events = since === void 0 ? "off (Claude Code isn't running)" : now(status.heardAt) ? "arriving" : now(status.pushedAt) ? "sent, not in the conversation yet" : "none yet";
228
+ const events = since === void 0 ? "off (Claude Code isn't running)" : running?.channelsRefused ? "refused" : now(status.heardAt) ? "arriving" : now(status.pushedAt) ? "sent, not in the conversation yet" : "none yet";
106
229
  return [name, {
107
230
  url: channel.url,
108
231
  events,
109
- ...status,
110
- ...blockers.length > 0 && { blockers }
232
+ ...status
111
233
  }];
112
234
  }));
113
235
  const status = async (paths, json, io) => {
114
- const answer = await ask(paths.socket, { command: "status" });
236
+ const s = await daemonStatus(paths);
115
237
  let config;
116
238
  let configError;
117
239
  try {
@@ -119,31 +241,40 @@ const status = async (paths, json, io) => {
119
241
  } catch (error) {
120
242
  configError = error instanceof Error ? error.message : String(error);
121
243
  }
122
- const blockers = config && Object.keys(config.channels).length > 0 ? channelBlockers() : [];
123
- const channels = channelReport(paths, config, answer?.status, blockers);
124
- const s = answer?.status;
244
+ const channels = channelReport(paths, config, s);
245
+ const log = s || !existsSync(paths.serviceLog) ? paths.log : paths.serviceLog;
246
+ const logTail = tail(log, 10);
247
+ const code = s && !configError ? 0 : 1;
125
248
  if (json) {
126
249
  io.out(JSON.stringify({
127
250
  running: !!s,
128
251
  home: paths.home,
252
+ config: paths.config,
129
253
  ...s && { status: s },
130
254
  ...configError && { configError },
131
- channels
255
+ channels,
256
+ log,
257
+ logTail
132
258
  }));
133
- return s ? 0 : 1;
259
+ return code;
134
260
  }
135
261
  if (!s) io.out(notRunning(paths));
136
262
  else {
137
263
  const since = s.startedAt ? ` for ${ago(s.startedAt)}` : "";
138
264
  const what = s.state === "running" ? `Claude Code running${since} (pid ${s.pid})` : s.state === "waiting" ? `Claude Code starting again${s.nextStartAt ? ` in ${Math.max(0, Math.round((Date.parse(s.nextStartAt) - Date.now()) / 1e3))}s` : ""}` : s.state === "stopped" ? "Claude Code stopped (harnessd start starts it)" : "Claude Code starting";
139
265
  io.out(`harnessd ${s.daemonPid}: ${what}`);
266
+ if (s.account) io.out(`account ${s.account}`);
267
+ for (const [name, stop] of Object.entries(s.accountsStopped ?? {})) io.out(`account ${name} stopped at ${stop.why}; harnessd tries it again after ${new Date(stop.until).toLocaleString()}`);
268
+ if (s.waitingOn) io.out(`Claude Code waits for an answer (${s.waitingOn}): harnessd attach, then answer it`);
140
269
  if (s.sessionId) io.out(`conversation ${s.sessionId}${s.folder ? ` in ${s.folder}` : ""}`);
141
270
  if (s.restarts > 0 || s.lastExit) io.out(`restarts ${s.restarts}${s.lastExit ? `, last exit code ${s.lastExit.code} ${ago(s.lastExit.at)} ago` : ""}`);
142
271
  }
143
272
  if (configError) io.out(configError);
144
273
  for (const [name, channel] of Object.entries(channels)) io.out(`channel ${name}: events ${channel.events} (${channel.url})`);
145
- if (blockers.length > 0 && Object.values(channels).some((c) => c.events !== "arriving")) io.out(`channels are blocked: ${blockers.join("; ")} (harnessd install lets them in)`);
146
- return s ? 0 : 1;
274
+ if (s?.channelsRefused && Object.keys(channels).length > 0) io.out(CHANNELS_REFUSED);
275
+ io.out(`log ${log}`);
276
+ for (const line of logTail) io.out(` ${line}`);
277
+ return code;
147
278
  };
148
279
  const attach = (paths, io) => new Promise((resolve) => {
149
280
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
@@ -184,7 +315,7 @@ const attach = (paths, io) => new Promise((resolve) => {
184
315
  process.stdin.resume();
185
316
  process.stdin.on("data", onInput);
186
317
  process.stdout.on("resize", onResize);
187
- createInterface({ input: connection }).on("line", (line) => {
318
+ createInterface({ input: connection }).on("error", () => {}).on("line", (line) => {
188
319
  try {
189
320
  const message = JSON.parse(line);
190
321
  if (typeof message.output === "string") process.stdout.write(message.output);
@@ -196,40 +327,72 @@ const attach = (paths, io) => new Promise((resolve) => {
196
327
  /** Runs one harnessd command; resolves to the exit code. */
197
328
  const runHarnessd = async (argv, bin, io = {
198
329
  out: (line) => void process.stdout.write(`${line}\n`),
199
- err: (line) => void process.stderr.write(`${line}\n`)
330
+ err: (line) => void process.stderr.write(`${line}\n`),
331
+ terminal: ttyTerminal()
200
332
  }) => {
201
- const paths = pathsOf();
202
333
  const [first, ...rest] = argv;
334
+ if (first === void 0 || first === "help" || argv.some((arg) => arg === "--help" || arg === "-h")) {
335
+ io.out(USAGE);
336
+ return 0;
337
+ }
338
+ try {
339
+ return await run(first, rest, bin, io);
340
+ } catch (error) {
341
+ if (!error.usage) throw error;
342
+ io.err(`${error.message} harnessd --help lists the commands.`);
343
+ return 2;
344
+ }
345
+ };
346
+ const service = (rest, bin, io) => {
347
+ const [action, ...more] = rest;
348
+ if (action !== "install" && action !== "uninstall") throw usageError("harnessd service takes install or uninstall.");
349
+ const flags = {};
350
+ for (let i = 0; i < more.length; i++) {
351
+ const arg = more[i];
352
+ if (action === "install" && arg === "--dry-run") flags.dryRun = true;
353
+ else if (action === "install" && arg === "--install-claude") flags.installClaude = true;
354
+ else if (action === "install" && arg === "--skip-sign-in") flags.skipSignIn = true;
355
+ else if (arg === "--user" && more[i + 1] !== void 0) flags.user = more[++i];
356
+ else throw usageError(`harnessd service ${action} takes ${action === "install" ? "--user <name>, --dry-run, --install-claude and --skip-sign-in" : "--user <name>"}, not ${arg}.`);
357
+ }
358
+ return action === "install" ? install(flags, bin, io) : uninstall(flags, io);
359
+ };
360
+ const run = async (first, rest, bin, io) => {
361
+ if (first === "--version") {
362
+ takes(first, rest);
363
+ io.out(VERSION);
364
+ return 0;
365
+ }
366
+ if (first === "service") return service(rest, bin, io);
367
+ const paths = pathsOf();
203
368
  switch (first) {
204
- case "install": return install(paths, bin, io);
205
- case "uninstall": {
206
- const had = unload(paths.label);
207
- io.out(had ? `Removed harnessd from login. Its settings and conversation stay in ${paths.home}.` : "harnessd wasn't installed.");
208
- return 0;
209
- }
210
- case "status": return status(paths, rest.includes("--json"), io);
369
+ case "status":
370
+ takes(first, rest, ["--json"]);
371
+ return status(paths, rest.includes("--json"), io);
211
372
  case "start":
212
- case "stop": return command(paths, { command: first }, io);
213
- case "new": return command(paths, {
214
- command: "new",
215
- ...rest.length > 0 && { message: rest.join(" ") }
216
- }, io);
217
- case "attach": return attach(paths, io);
218
- case "logs": return new Promise((resolve) => {
219
- if (!existsSync(paths.log)) {
220
- io.err(`No log yet at ${paths.log}.`);
221
- return resolve(1);
222
- }
223
- spawn("tail", [
224
- "-n",
225
- "100",
226
- "-F",
227
- paths.log
228
- ], { stdio: "inherit" }).on("exit", (code) => resolve(code ?? 0));
229
- });
373
+ case "stop":
374
+ takes(first, rest);
375
+ return command(paths, { command: first }, io);
376
+ case "attach":
377
+ takes(first, rest);
378
+ return attach(paths, io);
230
379
  case "run":
380
+ takes(first, rest);
231
381
  await runDaemon(paths, bin);
232
382
  return 0;
383
+ case "session-start": {
384
+ takes(first, rest);
385
+ const input = JSON.parse(await (io.stdin ?? stdin)());
386
+ if (input.agent_id !== void 0) return 0;
387
+ if (typeof input.session_id !== "string") throw new Error("Claude Code's SessionStart input has no session_id.");
388
+ const answer = await ask(paths.socket, {
389
+ command: "session-start",
390
+ sessionId: input.session_id
391
+ });
392
+ if (answer?.ok) return 0;
393
+ io.err(answer ? String(answer.message) : notRunning(paths));
394
+ return 1;
395
+ }
233
396
  case "channel": {
234
397
  const name = rest[0] ?? "";
235
398
  const channel = readConfig(paths).channels[name];
@@ -242,15 +405,7 @@ const runHarnessd = async (argv, bin, io = {
242
405
  });
243
406
  return 0;
244
407
  }
245
- case void 0:
246
- case "help":
247
- case "--help":
248
- case "-h":
249
- io.out(USAGE);
250
- return first === void 0 ? 1 : 0;
251
- default:
252
- io.err(`Unknown command ${first}.\n\n${USAGE}`);
253
- return 2;
408
+ default: throw usageError(`Unknown command ${first}.`);
254
409
  }
255
410
  };
256
411
  export { runHarnessd };