dispach 0.1.2 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +134 -85
- package/dist/App-qfqvx9c7.js +11 -0
- package/dist/{App-b1yrwrcq.js.map → App-qfqvx9c7.js.map} +6 -7
- package/dist/ConfigEditor-apcnj4nj.js +6 -0
- package/dist/{ConfigEditor-n8hdw6r7.js.map → ConfigEditor-apcnj4nj.js.map} +2 -2
- package/dist/KeyProbe-ya5t3v3v.js +5 -0
- package/dist/{KeyProbe-9jjeze5r.js.map → KeyProbe-ya5t3v3v.js.map} +2 -2
- package/dist/Picker-b7mn0mjg.js +5 -0
- package/dist/{Picker-hfeh1g6m.js.map → Picker-b7mn0mjg.js.map} +1 -1
- package/dist/SessionPicker-vacfwczg.js +5 -0
- package/dist/{SessionPicker-zyqkg4dn.js.map → SessionPicker-vacfwczg.js.map} +2 -2
- package/dist/SkillBrowser-66ntwaa9.js +5 -0
- package/dist/{SkillBrowser-3qdp8080.js.map → SkillBrowser-66ntwaa9.js.map} +1 -1
- package/dist/WizardApp-123998yh.js +5 -0
- package/dist/{WizardApp-vzpbydy3.js.map → WizardApp-123998yh.js.map} +3 -3
- package/dist/agents.d.ts +19 -3
- package/dist/agents.d.ts.map +1 -1
- package/dist/channels-q4fwqq87.js +31 -0
- package/dist/channels-q4fwqq87.js.map +10 -0
- package/dist/channels.d.ts +26 -0
- package/dist/channels.d.ts.map +1 -0
- package/dist/client.js +10 -10
- package/dist/client.js.map +3 -3
- package/dist/config-64q4mgxc.js +24 -0
- package/dist/{config-g7za9x13.js.map → config-64q4mgxc.js.map} +2 -2
- package/dist/{credential-npr6z8c8.js → credential-2sj7vsmw.js} +5 -5
- package/dist/{credential-npr6z8c8.js.map → credential-2sj7vsmw.js.map} +1 -1
- package/dist/daemon.d.ts.map +1 -1
- package/dist/index-0k3w2mxf.js +6 -0
- package/dist/{index-hwpvhaza.js.map → index-0k3w2mxf.js.map} +1 -1
- package/dist/index-1s81qstp.js +6 -0
- package/dist/{index-v8e92nfw.js.map → index-1s81qstp.js.map} +1 -1
- package/dist/index-2rycma8x.js +12 -0
- package/dist/{index-258d8bzg.js.map → index-2rycma8x.js.map} +4 -3
- package/dist/index-2zye08c4.js +6 -0
- package/dist/{index-vgc3y3rm.js.map → index-2zye08c4.js.map} +2 -2
- package/dist/{index-gme2egyq.js → index-3km1jwh7.js} +4 -4
- package/dist/{index-gme2egyq.js.map → index-3km1jwh7.js.map} +1 -1
- package/dist/index-3mtgcvkq.js +429 -0
- package/dist/index-3mtgcvkq.js.map +11 -0
- package/dist/index-4knb5vjm.js +90 -0
- package/dist/index-4knb5vjm.js.map +13 -0
- package/dist/{index-3g3ny01d.js → index-5nwwekk0.js} +4 -4
- package/dist/{index-3g3ny01d.js.map → index-5nwwekk0.js.map} +1 -1
- package/dist/index-5rm7dwq4.js +6 -0
- package/dist/index-5rm7dwq4.js.map +11 -0
- package/dist/index-79epttpm.js +6 -0
- package/dist/index-79epttpm.js.map +10 -0
- package/dist/{index-4cf6v9nb.js → index-7yk1zvds.js} +4 -4
- package/dist/{index-4cf6v9nb.js.map → index-7yk1zvds.js.map} +1 -1
- package/dist/index-81gb4ey4.js +6 -0
- package/dist/{index-4z7axw4r.js.map → index-81gb4ey4.js.map} +1 -1
- package/dist/index-8a5d8sfe.js +6 -0
- package/dist/{index-0d93hyfc.js.map → index-8a5d8sfe.js.map} +1 -1
- package/dist/index-a21zyy54.js +6 -0
- package/dist/index-a21zyy54.js.map +9 -0
- package/dist/index-b6da6c16.js +92 -0
- package/dist/index-b6da6c16.js.map +15 -0
- package/dist/index-byxrc961.js +903 -0
- package/dist/{index-tv4yv7d2.js.map → index-byxrc961.js.map} +16 -15
- package/dist/{index-ammv5st7.js → index-cgfg6t5a.js} +6 -6
- package/dist/{index-ammv5st7.js.map → index-cgfg6t5a.js.map} +1 -1
- package/dist/{index-s9mbq7h6.js → index-ehzwdnc3.js} +4 -4
- package/dist/{index-s9mbq7h6.js.map → index-ehzwdnc3.js.map} +1 -1
- package/dist/index-fzmmhmk2.js +7 -0
- package/dist/index-fzmmhmk2.js.map +11 -0
- package/dist/index-g3pk0kc0.js +6 -0
- package/dist/{index-9r0wyj6w.js.map → index-g3pk0kc0.js.map} +2 -2
- package/dist/index-h828nk24.js +153 -0
- package/dist/index-h828nk24.js.map +20 -0
- package/dist/{index-02dn6m2j.js → index-jq999vcw.js} +5 -5
- package/dist/{index-02dn6m2j.js.map → index-jq999vcw.js.map} +2 -2
- package/dist/index-k2aq5bg0.js +9 -0
- package/dist/{index-6p999cx4.js.map → index-k2aq5bg0.js.map} +4 -6
- package/dist/{index-cqqb6gaq.js → index-k3y8y3wj.js} +5 -5
- package/dist/{index-cqqb6gaq.js.map → index-k3y8y3wj.js.map} +1 -1
- package/dist/index-k59wwdgz.js +9 -0
- package/dist/{index-ff514z3y.js.map → index-k59wwdgz.js.map} +3 -5
- package/dist/index-nmnnwa02.js +6 -0
- package/dist/{index-6q4wf8e3.js.map → index-nmnnwa02.js.map} +1 -1
- package/dist/index-nn3tk25c.js +6 -0
- package/dist/{index-d4x6yvqh.js.map → index-nn3tk25c.js.map} +3 -4
- package/dist/index-q0hxh57v.js +126 -0
- package/dist/index-q0hxh57v.js.map +14 -0
- package/dist/index-srmhk9g5.js +11 -0
- package/dist/index-srmhk9g5.js.map +11 -0
- package/dist/index-swtyfhha.js +6 -0
- package/dist/{index-fex44816.js.map → index-swtyfhha.js.map} +2 -2
- package/dist/index-whq42sat.js +6 -0
- package/dist/{index-h9mw7b9d.js.map → index-whq42sat.js.map} +1 -1
- package/dist/{index-j7gyr5nx.js → index-wzsmh5j0.js} +7 -7
- package/dist/{index-j7gyr5nx.js.map → index-wzsmh5j0.js.map} +1 -1
- package/dist/{index-j55s3ehk.js → index-x7v1zq89.js} +7 -7
- package/dist/{index-j55s3ehk.js.map → index-x7v1zq89.js.map} +2 -2
- package/dist/index-xhzmv4dh.js +66 -0
- package/dist/index-xhzmv4dh.js.map +12 -0
- package/dist/index-xmv47vs0.js +6 -0
- package/dist/{index-gz9x25tz.js.map → index-xmv47vs0.js.map} +2 -2
- package/dist/index-y4c32wn7.js +6 -0
- package/dist/{index-qdbq8crg.js.map → index-y4c32wn7.js.map} +2 -2
- package/dist/index-yjcdp72k.js +6 -0
- package/dist/{index-tf71ap9v.js.map → index-yjcdp72k.js.map} +1 -1
- package/dist/index-zn24991r.js +6 -0
- package/dist/index-zn24991r.js.map +10 -0
- package/dist/index.js +374 -443
- package/dist/index.js.map +23 -27
- package/dist/init.d.ts.map +1 -1
- package/dist/lib/channel-actions.d.ts +103 -0
- package/dist/lib/channel-actions.d.ts.map +1 -0
- package/dist/lib/chat-frame.d.ts +12 -1
- package/dist/lib/chat-frame.d.ts.map +1 -1
- package/dist/lib/commands.d.ts +13 -0
- package/dist/lib/commands.d.ts.map +1 -1
- package/dist/lib/const.d.ts +1 -1
- package/dist/lib/host-actions.d.ts +121 -0
- package/dist/lib/host-actions.d.ts.map +1 -0
- package/dist/lib/init-flow.d.ts +32 -0
- package/dist/lib/init-flow.d.ts.map +1 -1
- package/dist/lib/init-whatsapp.d.ts +52 -0
- package/dist/lib/init-whatsapp.d.ts.map +1 -0
- package/dist/lib/plugin-install.d.ts +120 -0
- package/dist/lib/plugin-install.d.ts.map +1 -0
- package/dist/lib/providers.d.ts.map +1 -1
- package/dist/lib/provision.d.ts.map +1 -1
- package/dist/lib/readme-table.d.ts +15 -0
- package/dist/lib/readme-table.d.ts.map +1 -0
- package/dist/lib/sandbox.d.ts +15 -0
- package/dist/lib/sandbox.d.ts.map +1 -1
- package/dist/lib/schema.d.ts +34 -1
- package/dist/lib/schema.d.ts.map +1 -1
- package/dist/lib/subcommand.d.ts.map +1 -1
- package/dist/lib/web-url.d.ts +15 -0
- package/dist/lib/web-url.d.ts.map +1 -0
- package/dist/lib/wizard.d.ts.map +1 -1
- package/dist/memory.d.ts.map +1 -1
- package/dist/model.d.ts.map +1 -1
- package/dist/plugins.d.ts +27 -8
- package/dist/plugins.d.ts.map +1 -1
- package/dist/restart.d.ts +21 -0
- package/dist/restart.d.ts.map +1 -0
- package/dist/run.d.ts.map +1 -1
- package/dist/schedules.d.ts.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/sessions.d.ts.map +1 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/status.d.ts +16 -0
- package/dist/status.d.ts.map +1 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/validate.d.ts.map +1 -1
- package/dist/web-923c7f5e.js +14 -0
- package/dist/{web-vkb16r62.js.map → web-923c7f5e.js.map} +3 -3
- package/dist/web.d.ts +2 -13
- package/dist/web.d.ts.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/wrapper-0w9b3my0.js +11 -0
- package/dist/wrapper-0w9b3my0.js.map +23 -0
- package/package.json +6 -3
- package/dist/App-b1yrwrcq.js +0 -11
- package/dist/ConfigEditor-n8hdw6r7.js +0 -6
- package/dist/KeyProbe-9jjeze5r.js +0 -5
- package/dist/Picker-hfeh1g6m.js +0 -5
- package/dist/SessionPicker-zyqkg4dn.js +0 -5
- package/dist/SkillBrowser-3qdp8080.js +0 -5
- package/dist/WizardApp-vzpbydy3.js +0 -5
- package/dist/config-g7za9x13.js +0 -24
- package/dist/index-0d93hyfc.js +0 -6
- package/dist/index-1c5113t4.js +0 -66
- package/dist/index-1c5113t4.js.map +0 -12
- package/dist/index-258d8bzg.js +0 -12
- package/dist/index-4z7axw4r.js +0 -6
- package/dist/index-6p999cx4.js +0 -9
- package/dist/index-6q4wf8e3.js +0 -6
- package/dist/index-9r0wyj6w.js +0 -6
- package/dist/index-d4x6yvqh.js +0 -6
- package/dist/index-fecm8xe7.js +0 -77
- package/dist/index-fecm8xe7.js.map +0 -12
- package/dist/index-fex44816.js +0 -6
- package/dist/index-ff514z3y.js +0 -14
- package/dist/index-gz9x25tz.js +0 -6
- package/dist/index-h9mw7b9d.js +0 -6
- package/dist/index-hwpvhaza.js +0 -6
- package/dist/index-mtn0g9vc.js +0 -7
- package/dist/index-mtn0g9vc.js.map +0 -11
- package/dist/index-qdbq8crg.js +0 -6
- package/dist/index-tf71ap9v.js +0 -6
- package/dist/index-ttwyrdjs.js +0 -427
- package/dist/index-ttwyrdjs.js.map +0 -11
- package/dist/index-tv4yv7d2.js +0 -903
- package/dist/index-ty24n0jh.js +0 -167
- package/dist/index-ty24n0jh.js.map +0 -19
- package/dist/index-v8e92nfw.js +0 -6
- package/dist/index-vgc3y3rm.js +0 -6
- package/dist/index-whaw4b18.js +0 -6
- package/dist/index-whaw4b18.js.map +0 -10
- package/dist/web-vkb16r62.js +0 -14
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/daemon.ts", "../src/lib/daemon-plan.ts", "../src/lib/service-env.ts", "../src/lib/launchd.ts", "../src/lib/log-follow.ts", "../src/lib/service.ts", "../src/lib/systemd.ts", "../src/lib/bootstrap.ts", "../src/lib/host-actions.ts", "../src/lib/init-whatsapp.ts", "../src/lib/channel-actions.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * `daemon <action> <agent>` — keep an agent serving without a terminal open.\n *\n * ## Why this is a command and not a paragraph in the README\n *\n * Path resolution, and it is provable rather than arguable. The obvious hand-written plist —\n * `ProgramArguments: [\"~/.bun/bin/<binary>\", \"serve\", \"milo\"]` — **exits 127 forever**: the built\n * binary's first line is `#!/usr/bin/env node`, launchd's PATH is `/usr/bin:/bin:/usr/sbin:/sbin`,\n * and on a machine using a version manager there is no `node` in any of those. The failure lands in\n * a log file nobody has been told about. The gateway this runtime replaces ships an installer and\n * still got a version of this half-wrong — a Homebrew interpreter running an nvm-installed script.\n *\n * So the job is: resolve the interpreter and the script absolutely, resolve the manifest absolutely\n * (a bare agent name means something different from launchd's cwd of `/` than it does from the\n * directory you typed it in), carry no secrets, and refuse to install something that will not boot.\n *\n * No Ink and no React — a service command's output is read from a log at least as often as from a\n * terminal.\n */\n\nimport {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n readSync,\n statSync,\n} from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { dirname, join, resolve } from \"node:path\"\nimport { BRAND, HarnessError, processAlive, readManifestHeader, SqliteStore } from \"@dispach/core\"\nimport { EXIT_FAILURE, EXIT_OK, LOG_POLL_MS } from \"#lib/const\"\nimport {\n type Attention,\n agentFindings,\n attentionFrom,\n type BinaryFacts,\n type Finding,\n isLoopbackHost,\n renderStatus,\n type ServiceFacts,\n serverFindings,\n summariseStatus,\n} from \"#lib/daemon-plan\"\nimport { onExit } from \"#lib/exit\"\nimport {\n plistEnvAllowed,\n renderPlist,\n type ServicePlan,\n serverLabel,\n THROTTLE_SECONDS,\n} from \"#lib/launchd\"\nimport { liveHosts } from \"#lib/lifecycle\"\nimport { type FollowIO, followLogs } from \"#lib/log-follow\"\nimport { bytes, indent, keyValue, tildify } from \"#lib/render\"\nimport { listAgents, logPaths, sandboxRoot, serverLogPaths, storePath } from \"#lib/sandbox\"\nimport { type Exec, resolveServiceManager, unsupported } from \"#lib/service\"\nimport { renderUnit } from \"#lib/systemd\"\n\nexport const DAEMON_ACTIONS = [\n \"install\",\n \"uninstall\",\n \"start\",\n \"stop\",\n \"restart\",\n \"status\",\n \"logs\",\n] as const\nexport type DaemonAction = (typeof DAEMON_ACTIONS)[number]\n\nexport interface DaemonOptions {\n readonly action: string\n /** Absolute manifest path. Optional only for `status`, which can report on everything. */\n readonly manifestPath?: string\n readonly lines?: number\n readonly follow?: boolean\n readonly truncate?: boolean\n readonly dryRun?: boolean\n readonly json?: boolean\n /** Test seams. Nothing in `src/` outside this file passes them. */\n readonly exec?: Exec\n readonly platform?: string\n /** For the sandbox root and `XDG_CONFIG_HOME`. Injectable so a test needs no real HOME. */\n readonly env?: Readonly<Record<string, string | undefined>>\n /** The database to read leases from. Defaults to the sandbox's. */\n readonly store?: string\n}\n\nexport async function daemonCommand(options: DaemonOptions): Promise<number> {\n if (!(DAEMON_ACTIONS as readonly string[]).includes(options.action)) {\n throw new HarnessError({\n code: \"cli_daemon_unknown_action\",\n message: `daemon takes one of ${DAEMON_ACTIONS.join(\", \")}, not \"${options.action}\".`,\n hint: `Usage: ${BRAND.slug} daemon <action> <agent>. Run \\`${BRAND.slug} daemon --help\\` for what each one does.`,\n })\n }\n const action = options.action as DaemonAction\n\n /**\n * **Naming an agent is retired for every verb that installs or moves a unit.**\n *\n * One service hosts every agent now, so a per-agent unit is not a smaller version of this — it\n * is a second host claiming the same leases, which would leave the server reporting those\n * agents as served elsewhere indefinitely with nothing looking wrong. Refused rather than\n * silently reinterpreted, because a command that does something materially different from what\n * it says is worse than one that stops.\n *\n * `status` and `logs` still take one: those are questions about an agent rather than\n * instructions about a unit.\n */\n if (options.manifestPath !== undefined && action !== \"status\" && action !== \"logs\") {\n throw new HarnessError({\n code: \"daemon_per_agent_retired\",\n message: `daemon ${action} no longer takes an agent — one service hosts every agent.`,\n hint: `\\`${BRAND.slug} daemon ${action}\\` acts on that one service. Per-agent on/off is \\`${BRAND.slug} stop <agent>\\` and \\`${BRAND.slug} start <agent>\\`, which persist in the store rather than as a unit — so an agent you switch off stays off across a restart without the host going down with it.`,\n })\n }\n\n const platform = options.platform ?? process.platform\n const binary = binaryFacts()\n\n // The platform check runs *after* the paths are resolved, so the refusal can hand over the\n // ExecStart line rather than only naming the gap. `darwin` and `linux` both have a manager now;\n // anything else still refuses, and `status` answers from the lease alone everywhere.\n if (platform !== \"darwin\" && platform !== \"linux\" && action !== \"status\") {\n throw unsupported(platform, execStartLine(binary, options.manifestPath ?? \"<manifest>\"))\n }\n\n const manager =\n platform === \"darwin\" || platform === \"linux\"\n ? resolveServiceManager(platform, {\n home: homedir(),\n uid: process.getuid?.() ?? 0,\n envPrefix: BRAND.envPrefix,\n ...(options.exec === undefined ? {} : { exec: options.exec }),\n ...(options.env === undefined ? {} : { env: options.env }),\n })\n : undefined\n\n switch (action) {\n case \"status\":\n return await statusAction(options, manager)\n case \"install\":\n return await serverInstallAction(options, binary, manager)\n case \"uninstall\":\n return uninstallAction(options, manager)\n case \"start\":\n case \"stop\":\n case \"restart\":\n return lifecycleAction(action, manager)\n case \"logs\":\n return await logsAction(options)\n }\n}\n\n/**\n * Install **the** server unit: one process, hosting whatever the sandbox holds and has not stopped.\n *\n * No manifest anywhere in the plan, which is the change. `serve` with no argument reads the sandbox\n * at every start, so an agent provisioned tomorrow is hosted without touching the unit — where a\n * per-agent unit had to be installed per agent and could never host one that did not exist yet.\n *\n * Retirement happens **before** the install and is reported: a per-agent unit left beside this one\n * claims the same leases. `bootout` + `enable` + `rm`, in that order, because `launchctl enable` is\n * the only thing that clears an orphaned `disable` row and no verb deletes it — a label left\n * disabled makes a future job with that name install cleanly and silently never start.\n */\nasync function serverInstallAction(\n options: DaemonOptions,\n binary: BinaryFacts,\n manager: ReturnType<typeof resolveServiceManager> | undefined,\n): Promise<number> {\n const label = serverLabel(BRAND.slug)\n const logs = serverLogPaths(options.env)\n const retiring = (manager?.labels(`${BRAND.slug}.agent.`) ?? []).filter(\n (found) => found !== label,\n )\n const findings = [\n ...serverFindings({\n binary,\n retiring,\n servedElsewhere: (await liveHosts(options.store)).map((lease) => ({\n agentId: lease.agentId,\n pid: lease.pid,\n mode: lease.mode,\n })),\n }),\n /**\n * Plus each agent's own, which is how \"per-agent findings stay per-agent\" survives the\n * per-agent install being retired: they are still facts about one agent, reported by the\n * one install that exists. Read from the **header**, never a full load — a listing must not\n * depend on any agent's credentials being present, and this one runs over every agent in\n * the sandbox, so a single missing key would otherwise break the install of the host that\n * serves all the others.\n */\n ...listAgents(options.env).flatMap((agent) => {\n // Read once. `exactOptionalPropertyTypes` cannot narrow a second call, and a doubled\n // `statSync` per agent is a filesystem call for nothing.\n const mode = envMode(agent.dir)\n return agentFindings({\n agentId: agent.id ?? agent.ref,\n agentDir: agent.dir,\n ...(agent.problem === undefined ? {} : { problem: agent.problem }),\n ...(mode === undefined ? {} : { envFileMode: mode }),\n })\n }),\n ]\n\n const plan: ServicePlan = {\n label,\n // **No manifest.** The sandbox is the inventory, read at every start.\n programArguments: [\n binary.execPath,\n binary.scriptPath,\n \"serve\",\n \"--store\",\n storePath(),\n ].filter((argument) => argument !== \"\"),\n // The sandbox root rather than an agent's directory: there is no single agent here, and a\n // cwd that *is* an agent directory makes that agent's `.env` a layer in every other\n // agent's environment (decision 11.210).\n workingDirectory: sandboxRoot(options.env),\n stdoutPath: logs.out,\n stderrPath: logs.err,\n environment: serviceEnvironment(label),\n provenance: [\n `Generated by \\`${BRAND.slug} daemon install\\`. One service hosts every agent.`,\n \"Rewritten on every install — it names no agent, so there is nothing here to edit\",\n \"when you add one. Switch an agent off with `stop <agent>`, which persists.\",\n \"There are no secrets here and there never will be: a service manager echoes a\",\n \"unit's environment in plaintext to anything running as this user. Each agent\",\n \"reads its own credentials from the .env beside its manifest.\",\n ],\n }\n\n if (options.dryRun === true) {\n process.stdout.write(\n manager?.id === \"systemd\"\n ? renderUnit(plan, BRAND.envPrefix)\n : renderPlist(plan, BRAND.envPrefix),\n )\n if (findings.length > 0) process.stderr.write(renderFindings(findings))\n return EXIT_OK\n }\n\n for (const old of retiring) manager?.uninstall(old)\n if (findings.length > 0) process.stdout.write(renderFindings(findings))\n\n mkdirSync(dirname(logs.out), { recursive: true })\n manager?.install(plan)\n\n const followUp = manager?.followUp(label) ?? []\n process.stdout.write(\n `${label} — ${followUp.length === 0 ? \"service installed\" : \"unit written\"}\\n${keyValue([\n { label: \"runs\", value: `${short(binary.execPath)} … serve` },\n { label: \"hosts\", value: \"every agent in the sandbox that is not stopped\" },\n { label: \"logs\", value: short(logs.err) },\n { label: \"restarts\", value: `on crash only, at most one per ${THROTTLE_SECONDS}s` },\n ])}\\n`,\n )\n if (followUp.length > 0) {\n // The honest half of a manager that writes a unit and does not start it. Numbered, because\n // the order matters and because an unnumbered list of two commands reads as alternatives.\n process.stdout.write(\n `\\nNot started yet — run these:\\n${followUp\n .map((command, index) => ` ${index + 1}. ${command}`)\n .join(\"\\n\")}\\n`,\n )\n }\n const caution = manager?.caution()\n if (caution !== undefined) process.stdout.write(`\\n${caution}\\n`)\n\n process.stdout.write(\n `\\nA configuration error stops it once rather than looping — \\`${BRAND.slug} daemon status\\` says why.\\n`,\n )\n return EXIT_OK\n}\n\n// ─── facts ──────────────────────────────────────────────────────────────────────────────\n\n/**\n * The interpreter and the script, resolved through every symlink.\n *\n * `realpathSync` on both rather than trusting `argv[1]`: Node resolves the main module's realpath\n * today, but that is a flag away from changing (`--preserve-symlinks-main`), and a service\n * definition is not the place to depend on a default. On this machine the chain runs\n * `~/.bun/bin/<binary>` → the bun global directory → a `dist/index.js` inside a git checkout, which\n * is a fact the person installing deserves to be told (see `daemon_binary_in_checkout`).\n */\nfunction binaryFacts(): BinaryFacts {\n const execPath = realpathOr(process.execPath)\n const scriptPath = realpathOr(process.argv[1] ?? \"\")\n const gitRoot = findGitRoot(dirname(scriptPath))\n return { execPath, scriptPath, ...(gitRoot === undefined ? {} : { gitRoot }) }\n}\n\nfunction realpathOr(path: string): string {\n try {\n // Imported lazily so the pure-module boundary stays obvious: this file is the impure one.\n return require(\"node:fs\").realpathSync(path) as string\n } catch {\n return path\n }\n}\n\nfunction findGitRoot(from: string): string | undefined {\n let dir = from\n for (let depth = 0; depth < 40; depth += 1) {\n if (existsSync(join(dir, \".git\"))) return dir\n const parent = dirname(dir)\n if (parent === dir) return undefined\n dir = parent\n }\n return undefined\n}\n\nfunction execStartLine(binary: BinaryFacts, manifestPath: string): string {\n return `ExecStart=${binary.execPath} ${binary.scriptPath} serve ${manifestPath} --store ${storePath()}`\n}\n\n// ─── install ────────────────────────────────────────────────────────────────────────────\n\n/**\n * Four keys at most, and a throw in `renderPlist` if anything else appears.\n *\n * `PATH` is curated rather than copied from the installing shell — a developer's `$PATH` is full of\n * direnv and version-manager shims that are true for one directory and meaningless to a service.\n * But it must contain *something* useful: launchd's default has no node, bun, git or ripgrep, so an\n * agent whose `exec` works perfectly in the REPL answers \"command not found\" as a daemon, and the\n * model then invents a workaround rather than reporting a broken environment.\n */\nfunction serviceEnvironment(label: string): Record<string, string> {\n const home = homedir()\n const interpreterDir = dirname(realpathOr(process.execPath))\n const path = [\n interpreterDir,\n \"/opt/homebrew/bin\",\n \"/usr/local/bin\",\n \"/usr/bin\",\n \"/bin\",\n \"/usr/sbin\",\n \"/sbin\",\n ]\n .filter((entry, index, all) => all.indexOf(entry) === index)\n .join(\":\")\n\n const env: Record<string, string> = {\n HOME: home,\n PATH: path,\n // Set by the service definition and by nothing else, so `serve` can record \"daemon\" on its\n // runtime lease as a fact rather than inferring it from `ppid === 1`, which is also true of\n // any orphan.\n [`${BRAND.envPrefix}SERVICE`]: label,\n }\n const sandboxOverride = process.env[`${BRAND.envPrefix}HOME`]\n if (sandboxOverride !== undefined && sandboxOverride !== \"\") {\n // Without this the service would resolve a different sandbox — and therefore a different\n // store — from the shell that installed it.\n env[`${BRAND.envPrefix}HOME`] = sandboxOverride\n }\n return env\n}\n\nfunction envMode(agentDir: string): number | undefined {\n try {\n return statSync(join(agentDir, \".env\")).mode\n } catch {\n return undefined\n }\n}\n\nfunction renderFindings(findings: readonly Finding[]): string {\n return `${findings\n .map(\n (finding) =>\n `${finding.severity === \"block\" ? \"refused\" : \"warning\"}: ${finding.message}\\n hint: ${finding.hint}`,\n )\n .join(\"\\n\\n\")}\\n`\n}\n\n// ─── the rest ───────────────────────────────────────────────────────────────────────────\n\nfunction uninstallAction(\n options: DaemonOptions,\n manager: ReturnType<typeof resolveServiceManager> | undefined,\n): number {\n const label = serverLabel(BRAND.slug)\n const logs = serverLogPaths(options.env)\n // Retired per-agent units go too. Somebody uninstalling the host is not leaving one of those\n // behind on purpose, and a `disable` row it leaves is permanent.\n for (const old of (manager?.labels(`${BRAND.slug}.agent.`) ?? []).filter((l) => l !== label)) {\n manager?.uninstall(old)\n process.stdout.write(` also removed ${old}\\n`)\n }\n manager?.uninstall(label)\n process.stdout.write(\n `${label} — service removed\\n${keyValue([\n // Kept deliberately. Removing a service is not a reason to destroy the record of why it\n // was removed, which is very often the reason someone is removing it.\n { label: \"logs kept\", value: short(logs.err) },\n // Said out loud: the agents are *not* stopped. Their `agent_state` rows are untouched,\n // so reinstalling brings back exactly what was running — and an agent switched off with\n // `stop` is still off. Removing a unit must not quietly become removing configuration.\n { label: \"agents\", value: \"unchanged — nothing was switched off\" },\n ])}\\n`,\n )\n return EXIT_OK\n}\n\nfunction lifecycleAction(\n action: \"start\" | \"stop\" | \"restart\",\n manager: ReturnType<typeof resolveServiceManager> | undefined,\n): number {\n const label = serverLabel(BRAND.slug)\n if (manager === undefined) return EXIT_FAILURE\n if (action === \"start\") manager.start(label)\n if (action === \"stop\") manager.stop(label)\n if (action === \"restart\") manager.restart(label)\n const note =\n action === \"stop\"\n ? \" — the whole host. It stays stopped across a login until you start it again, and no\" +\n \" agent was switched off\"\n : \"\"\n process.stdout.write(`${label} — ${action}${action === \"stop\" ? \"ped\" : \"ed\"}${note}\\n`)\n return EXIT_OK\n}\n\nasync function statusAction(\n options: DaemonOptions,\n manager: ReturnType<typeof resolveServiceManager> | undefined,\n): Promise<number> {\n /**\n * Bare reports **the unit**; naming an agent reports that agent.\n *\n * Two different questions since one service hosts everything, and the bare form used to answer\n * the wrong one: it listed per-agent labels, so after 16.4 it said \"no agents are installed as\n * a service\" on a machine with a healthy server unit running — and pointed at the retired\n * `daemon install <agent>` to fix it.\n */\n const label = serverLabel(BRAND.slug)\n const hosts = await liveHosts(options.store)\n\n if (options.manifestPath === undefined) {\n const unitInstalled = manager?.state(label).installed === true\n if (!unitInstalled && hosts.length === 0) {\n process.stdout.write(\n `no server is installed and nothing is running\\n hint: \\`${BRAND.slug} daemon install\\` keeps one running after you close the terminal. One service hosts every agent.\\n`,\n )\n return EXIT_FAILURE\n }\n }\n\n const ids = options.manifestPath === undefined ? [label] : [agentIdOf(options.manifestPath)]\n\n const reports = await Promise.all(\n ids.map((id) =>\n gatherStatus(id, manager, {\n // The unit has a label and the server's own log; an agent has neither, and its\n // liveness is the lease's to report.\n ...(id === label ? { label } : {}),\n logs: id === label ? serverLogPaths(options.env) : logPaths(id),\n ...(options.store === undefined ? {} : { store: options.store }),\n // The unit holds one lease per agent it serves, so any of them is evidence that\n // *this* process is up — and the first is as good as any for an uptime.\n ...(id === label && hosts[0] !== undefined ? { leaseOf: hosts[0].agentId } : {}),\n }),\n ),\n )\n\n // What the unit is actually hosting, which no service manager can say. Printed before the\n // switched-off list below, so \"3 agents, 1 disabled\" reads as one thought.\n const hosted =\n options.manifestPath === undefined && hosts.length > 0\n ? hosts.map((lease) => lease.agentId).sort()\n : []\n /**\n * Agents that are switched off, which no other source here can see.\n *\n * `installedAgentIds` reads service labels and lease rows, and a stopped agent has neither — so\n * without this it is simply **absent** from the status of the thing it belongs to, which is the\n * \"I set this up and it is gone\" failure the durable switch exists to make explicable. The same\n * reason `listAgents` shows a broken directory rather than skipping it.\n */\n const switchedOff = (await disabledAgents()).filter(\n (entry) => options.manifestPath === undefined || ids.includes(entry.agentId),\n )\n\n if (options.json === true) {\n process.stdout.write(\n `${JSON.stringify({ agents: reports, hosting: hosted, disabled: switchedOff }, null, 2)}\\n`,\n )\n } else {\n for (const report of reports) {\n process.stdout.write(`${renderStatus(report.report)}\\n`)\n // Before the log tail and before the fix line, because \"running\" plus this is the\n // combination someone is actually here to resolve: the service is up and the agent is\n // still not answering them.\n for (const item of report.attention) {\n process.stdout.write(`\\n needs you ${item.summary}\\n ${item.fix}\\n`)\n }\n if (report.report.wantsStderrTail && report.tail !== \"\") {\n process.stdout.write(`\\n last lines of stderr:\\n${indent(report.tail, 4)}\\n`)\n }\n // The next command, spelled out. Someone reading this is mid-problem, and the point of\n // stopping once rather than looping is wasted if the way back is a guess.\n if (report.report.verdict === \"restart-loop\" || report.report.verdict === \"failed\") {\n process.stdout.write(\n `\\n fix correct the error above, then \\`${BRAND.slug} daemon restart ${report.agentId}\\`\\n`,\n )\n }\n process.stdout.write(\"\\n\")\n }\n\n if (hosted.length > 0) {\n process.stdout.write(\n ` hosting ${hosted.length} ${hosted.length === 1 ? \"agent\" : \"agents\"}: ${hosted.join(\", \")}\\n`,\n )\n }\n\n if (switchedOff.length > 0) {\n const count = `${switchedOff.length} ${switchedOff.length === 1 ? \"agent\" : \"agents\"}`\n process.stdout.write(` ${count} switched off, so nothing is hosting them:\\n`)\n for (const entry of switchedOff) {\n process.stdout.write(\n ` ${entry.agentId}${entry.reason === undefined ? \"\" : ` — ${entry.reason}`}` +\n `${entry.disabledAt === undefined ? \"\" : ` (since ${entry.disabledAt})`}\\n`,\n )\n }\n process.stdout.write(\n ` \\`${BRAND.slug} start <agent>\\` switches one back on — a restart alone will not.\\n\\n`,\n )\n }\n }\n // A switched-off agent is **not** unhealthy: it is in the state somebody asked for, and exiting\n // non-zero over it would make a deliberate stop look like a fault to a monitor.\n //\n // Non-zero when anything is unhealthy. Reporting a restart loop and exiting 0 is the shape hard\n // rule 8 forbids, and it is what makes this usable from a monitor without parsing text.\n return reports.every((report) => report.report.healthy) ? EXIT_OK : EXIT_FAILURE\n}\n\n/** Every agent with a `disabled` row, for the status block above. */\nasync function disabledAgents(): Promise<\n readonly { agentId: string; reason?: string; disabledAt?: string }[]\n> {\n try {\n const store = await SqliteStore.open({ path: storePath() })\n try {\n return (await store.agentState.list())\n .filter((state) => !state.enabled)\n .map((state) => ({\n agentId: state.agentId,\n ...(state.reason === undefined ? {} : { reason: state.reason }),\n ...(state.disabledAt === undefined ? {} : { disabledAt: state.disabledAt }),\n }))\n } finally {\n await store.close()\n }\n } catch {\n // No store is the ordinary first-run state, not an error for a status command.\n return []\n }\n}\n\n/**\n * One status report, for the server unit or for one agent.\n *\n * The label and the log paths are arguments rather than derived from `agentId`, which is what lets\n * the *unit* and an *agent* share this: there is one unit and many agents, so a function that\n * computed `labelFor(slug, agentId)` could only ever describe the retired per-agent shape.\n *\n * When `label` is absent there is no unit to ask about — that is an agent, whose liveness is the\n * lease's to report, and `installed: false` is then the honest answer rather than a gap.\n */\nasync function gatherStatus(\n agentId: string,\n manager: ReturnType<typeof resolveServiceManager> | undefined,\n options: {\n readonly label?: string\n readonly logs: { readonly out: string; readonly err: string }\n readonly store?: string\n /** The lease to read liveness from. The unit's own is whichever agent it happens to hold. */\n readonly leaseOf?: string\n },\n): Promise<{\n agentId: string\n report: ReturnType<typeof summariseStatus>\n tail: string\n attention: readonly Attention[]\n}> {\n const label = options.label\n const unit = label === undefined ? undefined : manager?.unitPath(label)\n const state = label === undefined ? undefined : manager?.state(label)\n const logs = options.logs\n\n let lease: Awaited<ReturnType<SqliteStore[\"leases\"][\"get\"]>>\n try {\n const store = await SqliteStore.open({ path: options.store ?? storePath() })\n lease = await store.leases.get(options.leaseOf ?? agentId)\n await store.close()\n } catch {\n lease = undefined\n }\n // A lease row is a claim, not a fact. A boot that fails *after* claiming — a missing channel\n // token, say — leaves one behind with no process under it, and reporting that as \"running in a\n // terminal\" is the exact class of lie slot 2 was fixed for: true of a record, false of the\n // moment. The runtime's own liveness probe, so the two cannot disagree about what alive means.\n if (lease !== undefined && !processAlive(lease.pid)) lease = undefined\n\n const stderrPath = state?.print?.stderrPath ?? logs.err\n const stderrBytes = sizeOf(stderrPath)\n const facts: ServiceFacts = {\n installed: (unit !== undefined && existsSync(unit)) || state?.installed === true,\n disabled: state?.disabled ?? false,\n ...(state?.pid === undefined ? {} : { pid: state.pid }),\n ...(state?.print?.runs === undefined ? {} : { runs: state.print.runs }),\n ...(state?.print?.lastExitCode === undefined\n ? {}\n : { lastExitCode: state.print.lastExitCode }),\n stderrPath: short(stderrPath),\n ...(stderrBytes === undefined ? {} : { stderrBytes }),\n ...(lease === undefined\n ? {}\n : {\n leasePid: lease.pid,\n leaseMode: lease.mode,\n leaseStartedAt: lease.startedAt,\n uptimeMs: Date.now() - Date.parse(lease.startedAt),\n }),\n }\n\n const report = summariseStatus(agentId, facts)\n // Read from *stdout*, not stderr: a refused sender is not an error, it is the runtime working\n // exactly as configured — which is why it never reaches the failure path and why a service can\n // be perfectly healthy and completely useless at the same time.\n const attention = attentionFrom(tail(logs.out, 200))\n\n return {\n agentId,\n report,\n tail: report.wantsStderrTail ? tail(stderrPath, 20) : \"\",\n attention,\n }\n}\n\n/**\n * The host's log, or one agent's — and naming an agent is now the *unusual* form.\n *\n * One service means one log, so bare is the normal case. An agent is still accepted because the\n * per-agent files exist on any machine that ran a per-agent unit before 16.4, and a command that\n * refused to show a log somebody is looking for would be worse than one that shows an old file.\n */\nasync function logsAction(options: DaemonOptions): Promise<number> {\n const named = options.manifestPath === undefined ? undefined : agentIdOf(options.manifestPath)\n const agentId = named ?? serverLabel(BRAND.slug)\n const logs = named === undefined ? serverLogPaths(options.env) : logPaths(named)\n if (options.truncate === true) {\n // Truncate rather than delete: launchd holds the file descriptor, so removing the file\n // leaves output flowing into a deleted inode — disk consumed, `ls` showing nothing.\n for (const path of [logs.out, logs.err]) {\n try {\n require(\"node:fs\").writeFileSync(path, \"\")\n } catch {\n // Nothing there yet is fine.\n }\n }\n process.stdout.write(`${agentId} — logs truncated\\n`)\n return EXIT_OK\n }\n const body = tail(logs.err, options.lines ?? 40)\n process.stdout.write(body === \"\" ? `${short(logs.err)} is empty\\n` : `${body}\\n`)\n if (options.follow !== true) return EXIT_OK\n\n // Both files, and that is the point of following rather than tailing one.\n //\n // A service can be perfectly healthy and completely useless at the same time: a sender refused by\n // `allowFrom` is the runtime working as configured, so it goes to *stdout* and never reaches the\n // failure path. `status` already reads both for exactly that reason. Somebody watching a log live is\n // watching because they do not trust what they are being told, and giving them half of it is how the\n // 57 MB lesson repeats — a good message in a file nobody opens.\n await followLogs(\n [\n { path: logs.err, label: \"stderr\" },\n { path: logs.out, label: \"stdout\" },\n ],\n followIO(),\n {\n // From the end of what was just printed, so nothing is reprinted and nothing that arrived\n // between the tail and the first poll is skipped.\n offsets: { [logs.err]: sizeOf(logs.err) ?? 0, [logs.out]: sizeOf(logs.out) ?? 0 },\n intervalMs: LOG_POLL_MS,\n },\n )\n return EXIT_OK\n}\n\n/**\n * The follower's streams, its clock, and its stop condition.\n *\n * `SIGINT` is claimed here and nowhere else in this file, which is safe precisely because\n * `installGuards` deliberately leaves it alone — the chat path owns it, and a guard that exited would\n * break the cancel-the-turn contract. A foreground `--follow` is the one command where ctrl-C means\n * \"stop watching\", so it handles it itself and removes the listener on the way out.\n */\nfunction followIO(): FollowIO {\n let stop = false\n let wake: (() => void) | undefined\n const onInterrupt = () => {\n stop = true\n // Wakes the pending sleep rather than waiting out the poll interval: a follower that took a\n // third of a second to notice ctrl-C would read as one that ignored it.\n wake?.()\n }\n process.on(\"SIGINT\", onInterrupt)\n onExit(() => {\n process.off(\"SIGINT\", onInterrupt)\n })\n\n return {\n sizeOf: (path) => sizeOf(path),\n read: (path, from, to) => {\n try {\n const handle = openSync(path, \"r\")\n try {\n const buffer = Buffer.alloc(to - from)\n const read = readSync(handle, buffer, 0, buffer.length, from)\n return buffer.subarray(0, read).toString(\"utf8\")\n } finally {\n closeSync(handle)\n }\n } catch {\n // Gone or unreadable between the stat and the read. Nothing to print, and the next poll\n // decides what that means.\n return \"\"\n }\n },\n write: (text) => void process.stdout.write(text),\n wait: (ms) =>\n new Promise<void>((resolve) => {\n if (stop) {\n resolve()\n return\n }\n const timer = setTimeout(resolve, ms)\n wake = () => {\n clearTimeout(timer)\n resolve()\n }\n }),\n stopped: () => stop,\n }\n}\n\n// ─── small helpers ──────────────────────────────────────────────────────────────────────\n\n/**\n * The manifest's own id, read without expanding env.\n *\n * `readManifestHeader`, never `loadManifest`: `status` and `uninstall` have to work on an agent\n * whose key is not exported, and a service command built on the loader would fail exactly when it\n * is most needed — on the machine where something is already wrong.\n */\nfunction agentIdOf(manifestPath: string): string {\n const header = readManifestHeader(manifestPath)\n if (header.id === undefined || header.id === \"\") {\n throw new HarnessError({\n code: \"cli_daemon_agent_id_missing\",\n message: `${manifestPath} declares no id, so there is no stable name to install a service under.`,\n hint: \"A service label is derived from the manifest id and has to survive a rename of the directory. Add `id: <name>` to the manifest.\",\n })\n }\n return header.id\n}\n\nfunction short(path: string): string {\n return tildify(resolve(path), homedir())\n}\n\nfunction sizeOf(path: string): number | undefined {\n try {\n return statSync(path).size\n } catch {\n return undefined\n }\n}\n\nfunction tail(path: string, lines: number): string {\n try {\n const body = readFileSync(path, \"utf8\").trimEnd()\n if (body === \"\") return \"\"\n return body.split(\"\\n\").slice(-lines).join(\"\\n\")\n } catch {\n return \"\"\n }\n}\n\n/** Re-exported so the boundaries test can assert this module carries no renderer import. */\nexport const DAEMON_ENV_ALLOWED = plistEnvAllowed(BRAND.envPrefix)\nexport const DAEMON_LOOPBACK = isLoopbackHost\nexport const DAEMON_BYTES = bytes\n",
|
|
6
|
+
"/**\n * The daemon's decisions, as pure functions: what would stop an install, and what a service's\n * state actually means.\n *\n * Facts in, verdicts out. Gathering the facts needs the filesystem, `launchctl` and a manifest\n * loader; *judging* them needs none of that, and separating the two is what makes the interesting\n * cases — a restart loop, a stale heartbeat, a binary inside a git checkout — testable as a table\n * rather than by breaking a real machine in nine different ways.\n *\n * No `node:*`, no `process`. This module is on the boundaries test's `PURE` list.\n */\n\nimport { bytes, duration, keyValue, type Row } from \"#lib/render\"\n\nexport type Severity = \"block\" | \"warn\"\n\nexport interface Finding {\n readonly code: string\n readonly severity: Severity\n readonly message: string\n /** Never optional. Hard rule 7, and a test asserts it over every finding this can produce. */\n readonly hint: string\n}\n\nexport interface BinaryFacts {\n /** `realpath(process.execPath)` — the interpreter, absolute. */\n readonly execPath: string\n /** `realpath(process.argv[1])` — the script, absolute. */\n readonly scriptPath: string\n /** Nearest ancestor of `scriptPath` holding a `.git`, if any. */\n readonly gitRoot?: string\n}\n\nexport interface AgentFindingFacts {\n readonly agentId: string\n readonly agentDir: string\n /** `undefined` when there is no `.env` beside the manifest. */\n readonly envFileMode?: number\n /** Set when the manifest could not be loaded at all. Reported, never fatal. */\n readonly problem?: string\n}\n\nconst LOOPBACK = new Set([\"127.0.0.1\", \"::1\", \"localhost\", \"0:0:0:0:0:0:0:1\"])\n\nexport function isLoopbackHost(host: string): boolean {\n return LOOPBACK.has(host.toLowerCase())\n}\n\n/**\n * What is worth saying about **one agent** when the host that will serve it is installed.\n *\n * ## Four blockers were deleted rather than moved, and each for a reason\n *\n * This was `preflightFindings`, gating `daemon install <agent>`. That install is retired — one\n * service hosts every agent — and with it three of its five blockers became *false* rather than\n * merely unreachable, which is worth recording so nobody restores them:\n *\n * - **`daemon_nothing_to_serve`** refused an agent with no enabled channel and `server.enabled`\n * false, because \"a background service would answer nothing\". Since 16.3 the host serves every\n * agent over `/v1` whatever that agent's own `server` block says, so an agent with no channel is\n * reachable from a browser and from the API — and a server with *no* agents is the designed\n * first-run state. Refusing here would make \"install and the API is up\" false.\n * - **`server_public_without_token`** duplicated `serve`'s own bind-time refusal one step earlier,\n * for a host whose address came from that agent's manifest. The unit names no manifest, so its\n * bind comes from the schema's loopback default and this cannot arise. `serve` still refuses it.\n * - **`daemon_label_taken`** was about two agents sharing one per-agent label. There is no\n * per-agent label.\n * - **`daemon_already_serving`** survives as `daemon_agents_held_elsewhere` on the server's own\n * list, as a **warning**: the host now starts and serves everything else rather than refusing,\n * which is 16.2a's partial-lease behaviour applied to an install.\n *\n * What is left is the one thing that is still true per agent and that nothing else says: the mode\n * of the file its credentials live in.\n */\nexport function agentFindings(facts: AgentFindingFacts): readonly Finding[] {\n const out: Finding[] = []\n\n if (facts.problem !== undefined) {\n out.push({\n code: \"daemon_agent_unreadable\",\n severity: \"warn\",\n message: `Agent \"${facts.agentId}\" could not be read: ${facts.problem}`,\n hint: \"The host skips an agent whose manifest will not load and serves the rest, so this is a warning rather than a refusal — `validate` on that agent says exactly what is wrong with it.\",\n })\n }\n\n if (facts.envFileMode !== undefined && (facts.envFileMode & 0o077) !== 0) {\n out.push({\n code: \"daemon_env_world_readable\",\n severity: \"warn\",\n message: `${facts.agentId}'s .env is mode ${(facts.envFileMode & 0o777).toString(8)} and holds its only secrets.`,\n hint: `Under a service manager that file is the *only* path credentials arrive by — a unit carries none on purpose, because its manager echoes the environment in plaintext. \\`chmod 600 ${facts.agentDir}/.env\\`.`,\n })\n }\n\n return out\n}\n\nexport function binaryWarnings(binary: BinaryFacts): readonly Finding[] {\n const out: Finding[] = []\n\n if (binary.gitRoot !== undefined) {\n out.push({\n code: \"daemon_binary_in_checkout\",\n severity: \"warn\",\n message: `The binary resolves to ${binary.scriptPath}, inside a git checkout at ${binary.gitRoot}.`,\n hint: \"A rebuild, a branch switch or a `git clean` changes or breaks what the service runs, and the failure arrives with no obvious connection to the change. Fine for testing; install a released build for a service you intend to leave running.\",\n })\n }\n\n if (/[/.](nvm|fnm|volta|asdf)\\//.test(binary.execPath)) {\n out.push({\n code: \"daemon_versioned_runtime\",\n severity: \"warn\",\n message: `The interpreter is a version-managed install: ${binary.execPath}`,\n hint: \"The absolute path is baked into the service definition, so removing that runtime version later kills the service with a message only the log file sees. A system or Homebrew install is more durable.\",\n })\n }\n\n return out\n}\n\nexport interface ServerPreflightFacts {\n readonly binary: BinaryFacts\n /** Retired per-agent labels found installed, which a bare install cleans up. */\n readonly retiring: readonly string[]\n /** Live leases held by other processes — agents the new unit would not be able to serve. */\n readonly servedElsewhere: readonly {\n readonly agentId: string\n readonly pid: number\n readonly mode: string\n }[]\n}\n\n/**\n * What to say before installing **the** server unit — a much shorter list, and deliberately so.\n *\n * Every blocker the per-agent list used to carry was a fact about one agent — its channel, its\n * token, its label — and a host that starts with no agents has none of those. `agentFindings` above\n * records which ones were deleted and why each one became false rather than merely unreachable.\n *\n * Nothing here blocks. The one thing that could — a conflicting label — is handled by *retiring* it\n * instead, because that is the only way to leave a working system behind: a per-agent unit left\n * beside the server unit contends for the same lease, so the server would report that agent as\n * served elsewhere indefinitely with nothing looking wrong.\n */\nexport function serverFindings(facts: ServerPreflightFacts): readonly Finding[] {\n const out: Finding[] = []\n\n for (const label of facts.retiring) {\n out.push({\n code: \"daemon_per_agent_retired\",\n severity: \"warn\",\n message: `Retiring ${label} — one service hosts every agent now.`,\n hint: \"It is unloaded, re-enabled and its definition removed. The re-enable is not cosmetic: a `disable` row persists across boots and no verb deletes it, so a label left disabled makes any future job with that name install cleanly and silently never start. Per-agent on/off is `stop <agent>`, which persists in the store instead.\",\n })\n }\n\n if (facts.servedElsewhere.length > 0) {\n const first = facts.servedElsewhere[0]\n out.push({\n code: \"daemon_agents_held_elsewhere\",\n severity: \"warn\",\n message: `${facts.servedElsewhere.length} agent(s) are held by other live processes — ${first?.agentId} by pid ${first?.pid} (${first?.mode}).`,\n hint: \"The service will start and serve everything else, and report those as served elsewhere rather than fighting for them — one listener per bot token is the whole reason the lease exists. `stop` with no agent ends the other processes.\",\n })\n }\n\n out.push(...binaryWarnings(facts.binary))\n\n return out\n}\n\n// ─── status ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * What a service is doing, in four states rather than two.\n *\n * `running` and `absent` are the easy ones. The pair that matters is `stopped` versus\n * `installed-idle`: a disabled job is simply *not listed* by `launchctl list`, so without the\n * disable registry those two are the same observation — and one of them means \"you asked for\n * this\" while the other means \"it died and launchd gave up\".\n */\nexport type Verdict =\n | \"running\"\n | \"failed\"\n | \"restart-loop\"\n | \"stopped\"\n | \"installed-idle\"\n | \"absent\"\n\nexport interface ServiceFacts {\n readonly installed: boolean\n readonly disabled: boolean\n readonly pid?: number\n readonly runs?: number\n readonly lastExitCode?: number\n readonly stderrPath?: string\n readonly stderrBytes?: number\n /** From the runtime lease — true even when launchd knows nothing, e.g. a terminal `serve`. */\n readonly leasePid?: number\n readonly leaseMode?: string\n readonly leaseStartedAt?: string\n readonly uptimeMs?: number\n}\n\n/**\n * Things a *running* service is saying that a person needs to see.\n *\n * `status` reporting \"running\" was true and useless: the bot was up, connected, and refusing every\n * message from the one person it had been set up for, because a handle in `allowFrom` was mistyped.\n * The refusal names the sender and the exact line to paste — and writes it to a log file, which is\n * the failure mode this whole phase is a reaction to, reached from a new direction.\n *\n * Health is not the only question. \"Is it running\" and \"is it working\" are different, and only the\n * second one is why anybody typed the command.\n */\nexport interface Attention {\n readonly code: string\n readonly summary: string\n readonly fix: string\n}\n\n/**\n * Only the current run.\n *\n * launchd *appends* to a service's log, so a denial from before you fixed the allowlist would\n * otherwise be reported forever — a warning that outlives its cause is one people learn to scroll\n * past, which is how you end up with a screen full of things that are all fine. Each start writes\n * the serving banner, so everything after the last one is this process and nothing else.\n */\nexport function currentRun(log: string, marker = \"serving on\"): string {\n const at = log.lastIndexOf(marker)\n return at === -1 ? log : log.slice(at)\n}\n\n/** Lines a running service wrote that mean it is up and not doing its job. */\nexport function attentionFrom(rawLog: string): readonly Attention[] {\n const log = currentRun(rawLog)\n const out: Attention[] = []\n\n // Every distinct sender it has turned away. Deduplicated, because a person who messages three\n // times produces three identical lines and a status screen should say it once.\n const denied = new Set<string>()\n for (const match of log.matchAll(/denied — Sender \"([^\"]+)\" is not in channel \"([^\"]+)\"/g)) {\n if (match[1] !== undefined) denied.add(`${match[1]}|${match[2] ?? \"\"}`)\n }\n for (const entry of denied) {\n const [sender, channel] = entry.split(\"|\")\n out.push({\n code: \"inbound_denied\",\n summary: `messages from ${sender} are being refused — they are not on channel \"${channel}\"'s allowFrom list`,\n fix: `add ${sender} to allowFrom in agent.yaml, then restart. An allowlist that is empty, or that has a typo in it, refuses silently from the sender's side: they see nothing at all.`,\n })\n }\n\n if (/channel_telegram_unauthorized|telegram_token_missing/.test(log)) {\n out.push({\n code: \"channel_unauthorized\",\n summary: \"the channel rejected its token\",\n fix: \"check the token in the .env beside the manifest, then restart.\",\n })\n }\n\n return out\n}\n\nexport interface StatusReport {\n readonly verdict: Verdict\n readonly healthy: boolean\n readonly headline: string\n readonly rows: readonly Row[]\n /** Print the tail of stderr. True whenever the thing is not simply running. */\n readonly wantsStderrTail: boolean\n}\n\n/** Three restarts is where \"it recovered\" stops being the likelier reading. */\nconst LOOP_RUNS = 3\n\nexport function summariseStatus(agentId: string, facts: ServiceFacts): StatusReport {\n const verdict = decide(facts)\n const rows: Row[] = []\n\n if (facts.pid !== undefined) {\n rows.push({\n label: \"state\",\n value: `running · pid ${facts.pid}`,\n ...(facts.uptimeMs === undefined ? {} : { note: `up ${duration(facts.uptimeMs)}` }),\n })\n } else if (facts.leasePid !== undefined) {\n // launchd knows nothing, but something holds the lease — a `serve` in a terminal. Worth\n // saying plainly: \"not installed\" alone would read as \"nothing is running\", which is the\n // opposite of the truth and is exactly the confusion slot 2 was fixed for.\n rows.push({\n label: \"state\",\n value: `running in a terminal · pid ${facts.leasePid}`,\n note: \"not installed as a service\",\n })\n }\n // No `else`. With nothing running the headline already carries the state, and repeating it as\n // a row two lines below is noise that makes the rows underneath — the ones with the actual\n // evidence — harder to find.\n\n if (facts.runs !== undefined && facts.runs > 1) {\n rows.push({\n label: \"starts\",\n value: String(facts.runs),\n ...(verdict === \"restart-loop\"\n ? { note: `launchd has restarted this ${facts.runs} times` }\n : { note: \"since the service was installed\" }),\n })\n }\n // Only when nothing is running. On a healthy service this is history — the failure you already\n // fixed — and printing a red-looking \"last exit code 1\" beside \"running\" invites a person to go\n // and debug something that is working.\n if (verdict !== \"running\" && facts.lastExitCode !== undefined && facts.lastExitCode !== 0) {\n rows.push({ label: \"last exit\", value: `code ${facts.lastExitCode}` })\n }\n if (facts.stderrPath !== undefined) {\n rows.push({\n label: \"logs\",\n value: facts.stderrPath,\n ...(facts.stderrBytes === undefined ? {} : { note: `(${bytes(facts.stderrBytes)})` }),\n })\n }\n\n return {\n verdict,\n healthy: verdict === \"running\",\n headline:\n verdict === \"restart-loop\"\n ? `${agentId} — RESTART LOOP`\n : `${agentId} — ${stateWord(verdict)}`,\n rows,\n wantsStderrTail:\n verdict === \"restart-loop\" || verdict === \"failed\" || verdict === \"installed-idle\",\n }\n}\n\nfunction decide(facts: ServiceFacts): Verdict {\n if (!facts.installed) return facts.leasePid === undefined ? \"absent\" : \"running\"\n // **A pid means running, with no qualification.** An earlier version also demanded the start\n // count be low and the uptime long, and that was wrong in a way only the real thing showed:\n // launchd's `runs` is cumulative for the life of the loaded job and never resets, so every\n // deliberate restart of a service that had *ever* failed came back seconds old with a high\n // count and was announced as a RESTART LOOP while working perfectly. A status command that\n // cries wolf on a healthy service is worse than one that says nothing.\n if (facts.pid !== undefined) return \"running\"\n if (facts.disabled) return \"stopped\"\n if ((facts.runs ?? 0) >= LOOP_RUNS && (facts.lastExitCode ?? 0) !== 0) return \"restart-loop\"\n // A single non-zero exit, which under `KeepAlive: {Crashed: true}` is the *designed* end state\n // for a misconfiguration: it stopped once instead of looping. Reporting that as \"installed, not\n // running\" would understate it into invisibility — the same understatement that let a job\n // restart 2,463 times with a perfectly good error message in a file nobody opened.\n if ((facts.lastExitCode ?? 0) !== 0) return \"failed\"\n return \"installed-idle\"\n}\n\nfunction stateWord(verdict: Verdict): string {\n switch (verdict) {\n case \"running\":\n return \"running\"\n case \"failed\":\n return \"STOPPED AFTER A FAILURE\"\n case \"restart-loop\":\n return \"exited · nothing is running\"\n case \"stopped\":\n return \"stopped by you\"\n case \"installed-idle\":\n return \"installed · not running\"\n case \"absent\":\n return \"not installed\"\n }\n}\n\n/** The body of a `status` block, minus the log tail the caller reads from disk. */\nexport function renderStatus(report: StatusReport): string {\n return `${report.headline}\\n${keyValue(report.rows)}`\n}\n",
|
|
7
|
+
"/**\n * What a service definition may carry in its environment, and the throw that enforces it.\n *\n * **One list, two renderers.** `launchctl print` echoes a loaded job's `EnvironmentVariables` in\n * plaintext to any process running as this user, and `systemctl show` does exactly the same for\n * `Environment=` — so a credential in either is a credential published, with nothing about the\n * running agent looking wrong. The list lived in `launchd.ts` while launchd was the only manager;\n * a second copy beside the systemd renderer is how one of them comes to allow a variable the other\n * refuses, and the dangerous direction is the one that silently allows more.\n *\n * An allowlist rather than a denylist, and enforced by a throw rather than by review, because the\n * failure is silent and permanent.\n */\n\n/**\n * The five that are not credentials.\n *\n * `HOME` because a service manager hands a job almost nothing — measured on macOS 26: `PATH` and\n * `SSH_AUTH_SOCK`, and that is all — and `HOME` is what decides the sandbox root. `PATH` because\n * `exec` runs shell commands and a service manager's default has no node, bun, git or brew in it.\n * `TMPDIR` because `exec` writes a child's output there. The two brand variables are a label and a\n * sandbox root, neither of which is a secret.\n */\nexport function serviceEnvAllowed(envPrefix: string): readonly string[] {\n return [\"HOME\", \"PATH\", \"TMPDIR\", `${envPrefix}SERVICE`, `${envPrefix}HOME`]\n}\n\n/**\n * Thrown by either renderer, with the same sentence.\n *\n * Not a `HarnessError`: this is a programming mistake in the CLI rather than a configuration\n * mistake by a person, and it has a `code` and a `hint` so whichever command was running can report\n * it the way it reports everything else.\n */\nexport class ServiceSecretError extends Error {\n readonly code = \"daemon_secret_in_service\"\n readonly hint: string\n constructor(key: string, allowed: readonly string[], manager: string) {\n super(`The service definition would carry an environment variable named ${key}.`)\n this.hint = `A ${manager} unit is readable and its manager echoes every environment value in plaintext to any process running as this user — so a credential here is a credential published. The agent reads its own secrets from the .env beside its manifest, which is what the service is pointed at. Only these may appear: ${allowed.join(\", \")}.`\n }\n}\n\n/** Refuse anything outside the allowlist. Called before a byte is written. */\nexport function assertNoSecrets(\n environment: Readonly<Record<string, string>>,\n envPrefix: string,\n manager: string,\n): void {\n const allowed = serviceEnvAllowed(envPrefix)\n for (const key of Object.keys(environment)) {\n if (!allowed.includes(key)) throw new ServiceSecretError(key, allowed, manager)\n }\n}\n",
|
|
8
|
+
"/**\n * launchd, as string transformations. Pure: no `node:*`, no `process`, no subprocess.\n *\n * Everything here is text in, text out — a plist rendered from a plan, and `launchctl` output\n * parsed into facts. That is what lets every plist key and every status decode be unit-tested\n * without installing a service on the machine running the tests, and it is why `service.ts`, which\n * actually shells out, contains almost no logic.\n *\n * ## The counter-example this file was written against\n *\n * `~/Library/LaunchAgents/ai.openclaw.gateway.plist`, on the author's machine, from the gateway\n * this runtime replaces. Three things it gets wrong, each reproduced here as a rule:\n *\n * 1. **It stores a live token as a literal string** in a `-rw-r--r--` file, and `launchctl print`\n * echoes `EnvironmentVariables` in plaintext to anything running as that user. Hard rule 10 says\n * secrets are env var *names* in config, never values, and a plist is config. So `renderPlist`\n * *throws* on a key outside `PLIST_ENV_ALLOWED` rather than trusting whoever builds the plan.\n * 2. **It runs a Homebrew interpreter against an nvm-installed script.** It works by accident and\n * dies when either moves. Interpreter and script are both resolved absolutely, by the caller,\n * and recorded.\n * 3. **`KeepAlive: true`.** At the time of writing that job reports `runs = 2463`,\n * `last exit code = 1`, and a 57 MB stderr log containing one sentence repeated every ten\n * seconds. The message is a good one — it names the cause and offers two remedies. It was\n * simply written somewhere nobody looks, thousands of times. See `KEEP_ALIVE`.\n */\n\nimport { assertNoSecrets } from \"#lib/service-env\"\n\n/**\n * Environment keys a generated service definition may carry — **moved to `service-env.ts`**.\n *\n * The systemd renderer needs the identical list: `systemctl show` exposes `Environment=` exactly as\n * `launchctl print` exposes `EnvironmentVariables`, so a second copy is how one manager comes to\n * permit a variable the other refuses, and the dangerous direction is the one that silently permits\n * more. Re-exported under the old name so every existing caller is unchanged.\n */\nexport { serviceEnvAllowed as plistEnvAllowed } from \"#lib/service-env\"\n\n/**\n * Restart on a crash signal, and on nothing else.\n *\n * The whole crash-loop answer, and it is structural rather than advisory. A deliberate non-zero\n * exit means the configuration is wrong — a manifest that will not load, a missing credential, a\n * port already taken — and relaunching that thirty times an hour produces the 57 MB log described\n * above. Under `Crashed` the job stops once, with the reason on disk, and `daemon status` says so.\n *\n * This is only safe because of a property the runtime already has: `ChannelHub.start()` catches\n * each transport's failure and boots anyway, so a Telegram outage or a rejected token never ends\n * the process. A non-zero exit therefore really is a misconfiguration and never a transient.\n *\n * The trade, stated rather than discovered: an uncaught exception also stops the service instead of\n * looping. A loud stop is the better failure — this codebase's whole objection to the OpenClaw job\n * is that nobody was ever told.\n */\nexport const KEEP_ALIVE = { Crashed: true } as const\n\n/** launchd's default is 10s. Higher, because a restart loop should cost less while it lasts. */\nexport const THROTTLE_SECONDS = 30\n/**\n * SIGTERM to SIGKILL. Must exceed the runtime's own stop deadline, or the reaper that kills\n * backgrounded `exec` children never finishes and they outlive the service.\n */\nexport const EXIT_TIMEOUT_SECONDS = 30\n\nexport interface ServicePlan {\n readonly label: string\n readonly programArguments: readonly string[]\n readonly workingDirectory: string\n readonly stdoutPath: string\n readonly stderrPath: string\n readonly environment: Readonly<Record<string, string>>\n /** Rendered into an XML comment. launchd has no `Comment` key — OpenClaw's is inert. */\n readonly provenance: readonly string[]\n}\n\n/**\n * The old name, kept as an alias so nothing that caught it stops catching it.\n *\n * The class itself is `ServiceSecretError` in `service-env.ts` — one error for two renderers, for\n * the reason the allowlist is one list.\n */\nexport { ServiceSecretError as PlistSecretError } from \"#lib/service-env\"\n\n/**\n * `<slug>.agent.<id>` — the **retired** per-agent label.\n *\n * Kept, and now only for retirement: one service hosts every agent, so this is what a bare\n * `daemon install` looks for in order to clean it up. Leaving a per-agent unit installed beside the\n * server unit is a broken state rather than a redundant one — both claim the same lease, so the\n * server reports that agent as served elsewhere indefinitely with nothing looking wrong.\n *\n * ⚠️ **`launchctl enable` is the only thing that clears an orphaned `disable` row**, and no verb\n * deletes it. Deleting the plist leaves `<slug>.agent.<id> => disabled` in\n * `/var/db/com.apple.xpc.launchd/` forever, so a future job reusing that label installs cleanly,\n * reports success and silently never starts. Retirement is therefore `bootout` + `enable` + `rm`,\n * in that order, and never just `rm`.\n */\nexport function labelFor(slug: string, agentId: string): string {\n return `${slug}.agent.${agentId}`\n}\n\n/**\n * `<slug>.server` — the one unit.\n *\n * One service for the host rather than one per agent, because per-agent on/off is durable *state*\n * (16.3's `agent_state`) and not a unit: `stop milo` leaves the host serving everything else, which\n * a unit-per-agent cannot express without N processes contending for one port.\n */\nexport function serverLabel(slug: string): string {\n return `${slug}.server`\n}\n\nexport function escapeXml(value: string): string {\n return value\n .replaceAll(\"&\", \"&\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\")\n .replaceAll('\"', \""\")\n .replaceAll(\"'\", \"'\")\n}\n\nexport function renderPlist(plan: ServicePlan, envPrefix: string): string {\n // The check is shared with the systemd renderer, so the two cannot disagree about what counts\n // as a secret — and it runs before a byte is written, so a throw leaves nothing half-installed.\n assertNoSecrets(plan.environment, envPrefix, \"launchd\")\n\n const args = plan.programArguments\n .map((arg) => ` <string>${escapeXml(arg)}</string>`)\n .join(\"\\n\")\n const env = Object.entries(plan.environment)\n .map(\n ([key, value]) =>\n ` <key>${escapeXml(key)}</key>\\n <string>${escapeXml(value)}</string>`,\n )\n .join(\"\\n\")\n const comment = plan.provenance.map((line) => ` ${escapeXml(line)}`).join(\"\\n\")\n\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!--\n${comment}\n-->\n<plist version=\"1.0\">\n <dict>\n <key>Label</key>\n <string>${escapeXml(plan.label)}</string>\n <key>ProgramArguments</key>\n <array>\n${args}\n </array>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <dict>\n <key>Crashed</key>\n <${KEEP_ALIVE.Crashed}/>\n </dict>\n <key>ThrottleInterval</key>\n <integer>${THROTTLE_SECONDS}</integer>\n <key>ExitTimeOut</key>\n <integer>${EXIT_TIMEOUT_SECONDS}</integer>\n <key>ProcessType</key>\n <string>Adaptive</string>\n <key>WorkingDirectory</key>\n <string>${escapeXml(plan.workingDirectory)}</string>\n <key>StandardOutPath</key>\n <string>${escapeXml(plan.stdoutPath)}</string>\n <key>StandardErrorPath</key>\n <string>${escapeXml(plan.stderrPath)}</string>\n <key>EnvironmentVariables</key>\n <dict>\n${env}\n </dict>\n </dict>\n</plist>\n`\n}\n\n// ─── reading launchctl back ──────────────────────────────────────────────────────────────\n\nexport interface ListEntry {\n readonly pid?: number\n /** Raw wait status, exactly as the column carries it. Decode with `decodeWaitStatus`. */\n readonly status: number\n readonly label: string\n}\n\n/** `launchctl list` — tab-separated `PID / Status / Label`, `-` for an absent pid. */\nexport function parseLaunchctlList(text: string): readonly ListEntry[] {\n const out: ListEntry[] = []\n for (const line of text.split(\"\\n\")) {\n const parts = line.split(\"\\t\")\n if (parts.length < 3) continue\n const [pid, status, label] = parts\n if (label === undefined || label === \"Label\" || label === \"\") continue\n const parsedStatus = Number.parseInt(status ?? \"\", 10)\n out.push({\n ...(pid === undefined || pid === \"-\" ? {} : { pid: Number.parseInt(pid, 10) }),\n status: Number.isFinite(parsedStatus) ? parsedStatus : 0,\n label,\n })\n }\n return out\n}\n\nexport interface PrintFacts {\n readonly pid?: number\n readonly runs?: number\n /** **Already decoded** by launchctl. Never pass this through `decodeWaitStatus`. */\n readonly lastExitCode?: number\n readonly jobState?: string\n readonly stdoutPath?: string\n readonly stderrPath?: string\n}\n\n/**\n * `launchctl print gui/$UID/<label>` — the only form carrying `runs`, which is what makes a\n * restart loop visible rather than merely a stopped job.\n *\n * Deliberately does **not** surface the `EnvironmentVariables` block it walks past. That output\n * echoes every value in plaintext, and a parser that lifted them into a struct would be one\n * `--json` away from writing somebody's bot token into a log file.\n */\nexport function parseLaunchctlPrint(text: string): PrintFacts {\n const facts: {\n pid?: number\n runs?: number\n lastExitCode?: number\n jobState?: string\n stdoutPath?: string\n stderrPath?: string\n } = {}\n for (const raw of text.split(\"\\n\")) {\n const line = raw.trim()\n const pid = /^pid = (\\d+)$/.exec(line)\n if (pid?.[1] !== undefined) facts.pid = Number.parseInt(pid[1], 10)\n const runs = /^runs = (\\d+)$/.exec(line)\n if (runs?.[1] !== undefined) facts.runs = Number.parseInt(runs[1], 10)\n const exit = /^last exit code = (-?\\d+)$/.exec(line)\n if (exit?.[1] !== undefined) facts.lastExitCode = Number.parseInt(exit[1], 10)\n const state = /^state = (.+)$/.exec(line)\n if (state?.[1] !== undefined) facts.jobState = state[1]\n const out = /^stdout path = (.+)$/.exec(line)\n if (out?.[1] !== undefined) facts.stdoutPath = out[1]\n const err = /^stderr path = (.+)$/.exec(line)\n if (err?.[1] !== undefined) facts.stderrPath = err[1]\n }\n return facts\n}\n\nexport interface WaitStatus {\n readonly exitCode?: number\n readonly signal?: number\n readonly signalName?: string\n}\n\nconst SIGNALS: Readonly<Record<number, string>> = {\n 1: \"SIGHUP\",\n 2: \"SIGINT\",\n 6: \"SIGABRT\",\n 9: \"SIGKILL\",\n 11: \"SIGSEGV\",\n 15: \"SIGTERM\",\n}\n\n/**\n * Decode `launchctl list`'s status column — and only that column.\n *\n * It is a raw `wait(2)` status: `256` means exit code 1, and a negative value names the signal that\n * killed the job. `launchctl print`'s `last exit code` is *already decoded*, and putting it through\n * here turns exit 1 into exit 0 — a broken service reported as a clean stop. Two sources, two\n * code paths, on purpose.\n */\nexport function decodeWaitStatus(raw: number): WaitStatus {\n if (!Number.isFinite(raw)) return {}\n if (raw < 0) {\n const signal = -raw\n return {\n signal,\n ...(SIGNALS[signal] === undefined ? {} : { signalName: SIGNALS[signal] }),\n }\n }\n return { exitCode: raw >= 256 ? raw >> 8 : raw }\n}\n\n/**\n * `launchctl print-disabled gui/$UID` → the labels explicitly disabled.\n *\n * Required, not optional. A disabled job is simply absent from `launchctl list`, so without this\n * \"you stopped it\" and \"it failed and was removed\" are the same observation — and `disable`\n * persists across boots, which is how a reinstall silently never starts.\n */\nexport function parseDisabled(text: string): readonly string[] {\n const out: string[] = []\n for (const raw of text.split(\"\\n\")) {\n const match = /^\\s*\"(.+)\"\\s*=>\\s*(disabled|true)\\s*$/.exec(raw)\n if (match?.[1] !== undefined) out.push(match[1])\n }\n return out\n}\n",
|
|
9
|
+
"/**\n * Following a log file that something else is writing.\n *\n * `daemon logs --follow` printed a tail and then a hint telling you to run `tail -f` yourself, which is\n * a flag documenting its own absence. Two things make the real implementation worth a module rather than\n * a few lines inline.\n *\n * **A service log is truncated, not rotated.** `daemon logs --truncate` empties the file in place,\n * because launchd holds the descriptor and deleting it leaves output flowing into a deleted inode — disk\n * consumed, `ls` showing nothing. So a follower has to notice the file getting *shorter* and start again\n * from the beginning; an offset carried blindly across a truncation reads garbage or, more often,\n * silently nothing ever again.\n *\n * **The decision is arithmetic and the reading is not.** `nextRead` is a pure function over two numbers\n * and holds everything worth asserting; `followLogs` is the loop, with its clock and its streams passed\n * in so a test can drive it against a temp directory in milliseconds.\n *\n * Polled rather than watched. `fs.watch` on macOS reports appends by another process unreliably, and a\n * follower that misses the line you are waiting for is worse than one that arrives 300 ms late — the\n * whole reason somebody is watching a log is that they do not trust what they are being told.\n */\n\nexport interface ReadStep {\n /** Byte offset to read from. */\n readonly from: number\n /** Byte offset to read to. Equal to `from` when there is nothing new. */\n readonly to: number\n /** The file got shorter, so this is a fresh start rather than a continuation. */\n readonly truncated: boolean\n}\n\n/**\n * What to read next, given where we stopped and how big the file is now.\n *\n * A file that shrank was emptied under us: read it from the start and say so, because the alternative —\n * carrying the old offset — means never printing another line and never explaining why.\n *\n * The blind spot, stated rather than wished away: a rewrite to *exactly* the same byte count reads as\n * \"nothing new\", because size is the only signal. Every size-based follower has this, `tail -f`\n * included, and the case that actually happens is caught — `--truncate` writes an empty file, and zero\n * is shorter than anything. A test asserts the blind spot so nobody discovers it as a mystery.\n */\nexport function nextRead(offset: number, size: number): ReadStep {\n if (size < offset) return { from: 0, to: size, truncated: true }\n return { from: offset, to: size, truncated: false }\n}\n\nexport interface FollowSource {\n readonly path: string\n /** Printed above a chunk when the source changes — `stderr`, `stdout`. */\n readonly label: string\n}\n\nexport interface FollowIO {\n /** Bytes currently in the file, or `undefined` if it does not exist yet. */\n sizeOf(path: string): number | undefined\n read(path: string, from: number, to: number): string\n write(text: string): void\n /** Resolves after `ms`, or immediately once the follow has been asked to stop. */\n wait(ms: number): Promise<void>\n /** Checked between polls. The caller owns whatever sets it — a signal, a keypress, a test. */\n stopped(): boolean\n}\n\n/**\n * Follow every source until asked to stop.\n *\n * Starting offsets come from the caller, which is what lets `daemon logs` print its tail with the\n * existing code and then continue from exactly where that ended — rather than reprinting it, or skipping\n * whatever arrived between the two.\n *\n * A label is printed only when the source changes. Following one file is the common case and a banner on\n * every chunk of it is noise; following two, the switch is the only thing that needs saying.\n */\nexport async function followLogs(\n sources: readonly FollowSource[],\n io: FollowIO,\n options: { readonly offsets: Readonly<Record<string, number>>; readonly intervalMs: number },\n): Promise<void> {\n const offsets = new Map(\n sources.map((source) => [source.path, options.offsets[source.path] ?? 0]),\n )\n let lastLabel: string | undefined\n\n while (!io.stopped()) {\n for (const source of sources) {\n const size = io.sizeOf(source.path)\n // Not written yet. Left at whatever offset it had rather than reset, so a file that appears\n // later is followed from its start without a truncation notice.\n if (size === undefined) continue\n const step = nextRead(offsets.get(source.path) ?? 0, size)\n offsets.set(source.path, step.to)\n if (step.truncated) {\n io.write(`\\n── ${source.label} was emptied ──\\n`)\n lastLabel = source.label\n }\n if (step.to <= step.from) continue\n const chunk = io.read(source.path, step.from, step.to)\n if (chunk === \"\") continue\n if (sources.length > 1 && source.label !== lastLabel) {\n io.write(`\\n── ${source.label} ──\\n`)\n lastLabel = source.label\n }\n io.write(chunk)\n }\n await io.wait(options.intervalMs)\n }\n}\n",
|
|
10
|
+
"/**\n * The service-manager seam, and the only place in this package that spawns a subprocess.\n *\n * Deliberately thin. Every decision lives in `daemon-plan.ts` and every string transformation in\n * `launchd.ts` and `systemd.ts`, all pure; what is left here is \"run the manager and hand back what\n * it said\", which is the part no test should be exercising against a real machine. `Exec` is\n * injectable for that reason — the daemon tests drive a fake and never touch the user's\n * `~/Library/LaunchAgents`.\n *\n * ## Linux is supported as far as it can be proven, and says where that ends\n *\n * This file used to refuse Linux outright, on the argument that *\"a systemd renderer nobody here\n * can execute would be a liability: wrong in ways no test catches, shipped with an acceptance\n * criterion that could not honestly be ticked.\"* Half of that expired when the product became a\n * server — Linux is where one runs — and half did not: a container has no systemd (PID 1 is the\n * entrypoint) and `systemctl --user` on a CI runner has no D-Bus user session, so nothing here can\n * drive the lifecycle verbs end to end.\n *\n * So the line is drawn by what is provable. `SystemdManager` **writes a real unit** — the text is\n * pure and fully tested — and its lifecycle verbs throw a refusal carrying the exact command\n * instead of pretending. `install` reports the two commands to run. An install that claimed success\n * while nothing was running is the failure this whole phase exists to remove, and that is the one\n * thing a half-built manager must not do.\n */\n\nimport { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from \"node:fs\"\nimport { basename, dirname, join } from \"node:path\"\nimport { HarnessError } from \"@dispach/core\"\nimport {\n EXIT_TIMEOUT_SECONDS,\n type PrintFacts,\n parseDisabled,\n parseLaunchctlList,\n parseLaunchctlPrint,\n renderPlist,\n type ServicePlan,\n} from \"#lib/launchd\"\nimport { spawnCapture } from \"#lib/spawn\"\nimport { renderUnit, followUp as systemdFollowUp, unitPath as systemdUnitPath } from \"#lib/systemd\"\n\nexport interface ExecResult {\n readonly code: number\n readonly stdout: string\n readonly stderr: string\n}\nexport type Exec = (command: string, args: readonly string[]) => ExecResult\n\nexport interface ServiceState {\n readonly installed: boolean\n readonly disabled: boolean\n readonly print?: PrintFacts\n readonly pid?: number\n /**\n * `false` when this manager cannot say whether the unit is *running*.\n *\n * True for launchd, which is read through `launchctl print`. False for systemd, where the\n * lifecycle is not driven from here — so `installed` there means \"the unit file exists\" and\n * nothing more, and a caller must fall back to the lease table rather than reporting a written\n * file as a running server.\n */\n readonly liveness: boolean\n}\n\nexport interface ServiceManager {\n readonly id: string\n unitPath(label: string): string\n install(plan: ServicePlan): void\n uninstall(label: string): void\n stop(label: string): void\n start(label: string): void\n restart(label: string): void\n state(label: string): ServiceState\n /** Every label this manager knows about that belongs to us, for a bare `status`. */\n labels(prefix: string): readonly string[]\n /**\n * Commands the person must run themselves after `install`, in order. Empty for launchd.\n *\n * The honest half of a manager that writes a unit and does not start it. Returned rather than\n * printed here so the caller decides where it goes — and returned rather than omitted so the\n * difference between the two platforms is in the type, where it cannot be forgotten.\n */\n followUp(label: string): readonly string[]\n /**\n * A platform-specific caution worth printing, or `undefined`.\n *\n * Exists for exactly one thing today: a systemd **user** unit stops when the user's last\n * session ends unless lingering is enabled for the account — so an always-on server installed\n * over SSH is gone when the connection closes. That is launchd's `disable` trap in a different\n * costume, and the cure is the same: say it where somebody is looking.\n */\n caution(): string | undefined\n}\n\n/**\n * How long to wait for a `bootout` to complete before bootstrapping over it.\n *\n * Generous relative to what it costs: a reinstall is a command somebody is watching, and the\n * failure being avoided is a unit that silently does not load. Well under `ExitTimeOut`, because a\n * job taking the full 30 s to die is a job with a problem of its own and the post-install check\n * will say so.\n */\nconst SETTLE_MS = 6_000\nconst SETTLE_POLL_MS = 200\n\nconst realExec: Exec = (command, args) => {\n const result = spawnCapture({ command, args })\n return { code: result.code, stdout: result.stdout, stderr: result.stderr }\n}\n\nexport interface ManagerOptions {\n readonly home: string\n readonly uid: number\n readonly envPrefix: string\n readonly exec?: Exec\n /** For `XDG_CONFIG_HOME` and `USER`. Injectable so a test needs no real environment. */\n readonly env?: Readonly<Record<string, string | undefined>>\n}\n\nexport function resolveServiceManager(platform: string, options: ManagerOptions): ServiceManager {\n if (platform === \"darwin\") return new LaunchdManager(options)\n if (platform === \"linux\") return new SystemdManager(options)\n throw unsupported(platform)\n}\n\n/**\n * Whether this platform's manager can *start* what it installs.\n *\n * Read by the first-run bootstrap, which must not install something it cannot start and then\n * report a running server: on Linux it prints the command instead. A predicate rather than a\n * `platform === \"darwin\"` test at the call site, so adding a manager that can execute does not\n * mean finding every place that assumed one could not.\n */\nexport function managerCanStart(platform: string): boolean {\n return platform === \"darwin\"\n}\n\n/**\n * The refusal, with the workaround's hard part already solved.\n *\n * Filled in by the caller, which knows the resolved paths — a message naming `ExecStart=` with real\n * absolute values is worth more than a paragraph explaining that they matter.\n */\nexport function unsupported(platform: string, execStart?: string): HarnessError {\n const recipe =\n execStart === undefined\n ? \"\"\n : ` For a systemd user unit, the line to write is:\\n\\n ${execStart}\\n Restart=on-failure\\n RestartSec=30\\n\\n Put no secrets in the unit: the agent reads the .env beside its manifest, and \\`systemctl show\\` echoes Environment= to anyone.`\n return new HarnessError({\n code: \"daemon_platform_unsupported\",\n message: `daemon installs a macOS LaunchAgent or a systemd user unit, and this platform is ${platform}.`,\n hint: `No service manager is implemented for this platform.${recipe} In a container, run \\`serve\\` in the foreground and let the container runtime supervise it; that is the deployment this runtime is designed around.`,\n })\n}\n\n/**\n * Writes a real systemd user unit. Does not start it — see the file comment.\n *\n * Every lifecycle verb throws a refusal carrying the exact command, which is the honest shape: a\n * manager that swallowed `start` would make `daemon install` report a running server on a platform\n * where nothing had been started, and that is the one failure this phase exists to remove.\n */\nclass SystemdManager implements ServiceManager {\n readonly id = \"systemd\"\n readonly #home: string\n readonly #envPrefix: string\n readonly #exec: Exec\n readonly #env: Readonly<Record<string, string | undefined>>\n\n constructor(options: ManagerOptions) {\n this.#home = options.home\n this.#envPrefix = options.envPrefix\n this.#exec = options.exec ?? realExec\n this.#env = options.env ?? process.env\n }\n\n unitPath(label: string): string {\n return systemdUnitPath(label, this.#home, this.#env)\n }\n\n install(plan: ServicePlan): void {\n const path = this.unitPath(plan.label)\n // Rendered before anything is written, because that is where the no-secrets rule is\n // enforced — the same ordering `LaunchdManager.install` has, for the same reason.\n const body = renderUnit(plan, this.#envPrefix)\n mkdirSync(dirname(path), { recursive: true })\n // 0600 is not the protection — `systemctl show` echoes `Environment=` whatever the mode —\n // but there is no reason for it to be readable.\n writeFileSync(path, body, { encoding: \"utf8\", mode: 0o600 })\n }\n\n uninstall(label: string): void {\n // The file only. Disabling it is the person's command, and saying so is better than a\n // silent half-removal that leaves `systemctl --user` still listing a unit we deleted.\n rmSync(this.unitPath(label), { force: true })\n }\n\n stop(label: string): void {\n throw this.#manual(`systemctl --user stop ${label}`)\n }\n\n start(label: string): void {\n throw this.#manual(`systemctl --user start ${label}`)\n }\n\n restart(label: string): void {\n throw this.#manual(`systemctl --user restart ${label}`)\n }\n\n /**\n * Whether the unit file exists, and nothing more.\n *\n * `liveness: false` is the load-bearing field. Without it a caller would read `installed: true`\n * as \"running\" and report a written file as a live server — so every surface that needs to know\n * whether something is actually up falls back to the lease table, which is a fact about a\n * process rather than about a file.\n */\n state(label: string): ServiceState {\n return { installed: existsSync(this.unitPath(label)), disabled: false, liveness: false }\n }\n\n labels(prefix: string): readonly string[] {\n // Read from the directory rather than from `systemctl list-units`, which needs the session\n // bus this manager deliberately does not depend on.\n try {\n return readdirSync(dirname(this.unitPath(prefix)))\n .filter((name) => name.startsWith(prefix) && name.endsWith(\".service\"))\n .map((name) => name.slice(0, -\".service\".length))\n .sort()\n } catch {\n // No unit directory yet is the ordinary state before a first install.\n return []\n }\n }\n\n followUp(label: string): readonly string[] {\n return systemdFollowUp(label, this.#user())\n }\n\n /**\n * The lingering warning, and only when lingering is actually off.\n *\n * `loginctl show-user` is a **read**, which is why executing it here does not contradict this\n * manager not driving the lifecycle — and a missing or failing `loginctl` returns the warning\n * rather than suppressing it, because the direction that matters is not silently reassuring\n * somebody that their service will survive a logout.\n */\n caution(): string | undefined {\n const user = this.#user()\n const result = this.#exec(\"loginctl\", [\"show-user\", user, \"--property=Linger\"])\n if (result.code === 0 && /Linger=yes/i.test(result.stdout)) return undefined\n return `A systemd user unit stops when your last session ends. \\`loginctl enable-linger ${user}\\` is what keeps it running after you log out or close an SSH connection.`\n }\n\n #user(): string {\n return this.#env.USER ?? this.#env.LOGNAME ?? basename(this.#home)\n }\n\n #manual(command: string): HarnessError {\n return new HarnessError({\n code: \"daemon_manual_step\",\n message: `This has to be run yourself: ${command}`,\n hint: `Unit files are written and read from here, and the lifecycle is not driven from here — nothing in this project's test environment can run \\`systemctl --user\\` (a container has no systemd, and a CI runner has no user session bus), and a command that reported success while nothing happened would be worse than this sentence. The unit is at ${this.unitPath(command.split(\" \").pop() ?? \"\")}.`,\n })\n }\n}\n\nclass LaunchdManager implements ServiceManager {\n readonly id = \"launchd\"\n readonly #home: string\n readonly #domain: string\n readonly #envPrefix: string\n readonly #exec: Exec\n\n constructor(options: ManagerOptions) {\n this.#home = options.home\n this.#domain = `gui/${options.uid}`\n this.#envPrefix = options.envPrefix\n this.#exec = options.exec ?? realExec\n }\n\n unitPath(label: string): string {\n return join(this.#home, \"Library\", \"LaunchAgents\", `${label}.plist`)\n }\n\n install(plan: ServicePlan): void {\n const path = this.unitPath(plan.label)\n // Rendered before anything is written, because `renderPlist` is where the no-secrets rule\n // is enforced — a throw must not leave a half-installed service behind.\n const body = renderPlist(plan, this.#envPrefix)\n\n mkdirSync(dirname(path), { recursive: true })\n mkdirSync(dirname(plan.stdoutPath), { recursive: true })\n\n // Unload an existing copy first; `bootstrap` over a loaded job is an error, not an update.\n this.#launchctl([\"bootout\", `${this.#domain}/${plan.label}`], { tolerate: true })\n /**\n * **Wait for the unload to finish.** `bootout` returns before the job is gone.\n *\n * Found by reinstalling over a *running* server: the bootout returned 0, the immediate\n * bootstrap also returned 0, and nothing was loaded afterwards — the command reported\n * \"service installed\" while `launchctl print` could not find the service at all. launchd's\n * own vocabulary for this is code 37, \"operation now in progress\", which it does not always\n * bother to produce.\n *\n * A first install has nothing to wait for and this returns immediately, which is why it\n * went unnoticed: the bug needs an existing *running* job, and the tests use a fake `Exec`.\n */\n this.#settle(plan.label)\n // 0600 is not the protection — `launchctl print` reads a loaded job's environment whatever\n // the file mode — but there is no reason for it to be readable and OpenClaw's is 0644.\n writeFileSync(path, body, { encoding: \"utf8\", mode: 0o600 })\n // Before bootstrap, and not optional: `disable` state persists across boots, so a service\n // that was once `daemon stop`ped would install cleanly here and then silently never start.\n this.#launchctl([\"enable\", `${this.#domain}/${plan.label}`], { tolerate: true })\n this.#launchctl([\"bootstrap\", this.#domain, path])\n\n /**\n * And check it is really there, because \"installed\" is a claim about a *running* job.\n *\n * The whole objection this project has to the service it replaces is that nobody was ever\n * told — so an install that cannot demonstrate a loaded job has to say so rather than print\n * four tidy rows about a unit launchd never took.\n */\n if (!this.state(plan.label).installed) {\n throw new HarnessError({\n code: \"daemon_not_loaded\",\n message: `${plan.label} was written to ${path} but launchd did not load it.`,\n hint: `\\`launchctl bootstrap\\` returned success and \\`launchctl print ${this.#domain}/${plan.label}\\` finds nothing, which usually means an earlier copy was still unloading. Try again in a moment. Over SSH with no desktop session the ${this.#domain} domain is unavailable and no LaunchAgent can load at all.`,\n })\n }\n }\n\n /**\n * Block until this label is no longer loaded, or until the budget runs out.\n *\n * A synchronous wait because `install` is synchronous, and making it async would ripple through\n * four callers for a path that runs once. `Atomics.wait` on a throwaway buffer is the standard\n * way to sleep a thread without a busy loop burning CPU while launchd works.\n *\n * Bounded, and silent when the budget runs out: the post-install check above is what reports a\n * failure, and it reports it with evidence rather than as a timeout nobody can act on.\n */\n #settle(label: string): void {\n const deadline = Date.now() + SETTLE_MS\n while (Date.now() < deadline) {\n if (this.#exec(\"launchctl\", [\"print\", `${this.#domain}/${label}`]).code !== 0) return\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, SETTLE_POLL_MS)\n }\n }\n\n uninstall(label: string): void {\n this.#launchctl([\"bootout\", `${this.#domain}/${label}`], { tolerate: true })\n // Re-enabled on the way out so a future install is not gated on a disable nobody remembers.\n this.#launchctl([\"enable\", `${this.#domain}/${label}`], { tolerate: true })\n rmSync(this.unitPath(label), { force: true })\n }\n\n stop(label: string): void {\n // Disable *and* unload. `bootout` alone stops it now and launchd loads it again at the next\n // login — the \"I stopped it and it was back after lunch\" surprise.\n this.#launchctl([\"disable\", `${this.#domain}/${label}`], { tolerate: true })\n this.#launchctl([\"bootout\", `${this.#domain}/${label}`], { tolerate: true })\n }\n\n start(label: string): void {\n this.#launchctl([\"enable\", `${this.#domain}/${label}`], { tolerate: true })\n this.#launchctl([\"bootstrap\", this.#domain, this.unitPath(label)])\n }\n\n restart(label: string): void {\n this.#launchctl([\"kickstart\", \"-k\", `${this.#domain}/${label}`])\n }\n\n state(label: string): ServiceState {\n const print = this.#exec(\"launchctl\", [\"print\", `${this.#domain}/${label}`])\n const disabled = parseDisabled(\n this.#exec(\"launchctl\", [\"print-disabled\", this.#domain]).stdout,\n ).includes(label)\n\n if (print.code !== 0) {\n // Not loaded. The plist may still exist on disk — a stopped service is exactly that —\n // so \"installed\" is a question for the caller, which can see the file.\n return { installed: false, disabled, liveness: true }\n }\n const facts = parseLaunchctlPrint(print.stdout)\n return {\n installed: true,\n disabled,\n liveness: true,\n print: facts,\n ...(facts.pid === undefined ? {} : { pid: facts.pid }),\n }\n }\n\n /**\n * Every label of ours, from **both** the loaded jobs and the plist directory.\n *\n * `launchctl list` alone was wrong, and wrong in the worst direction: **a disabled job is simply\n * absent from it**, which is the recorded trap this file already documents for `status` — and a\n * disabled per-agent unit is precisely the one whose retirement matters, because its `disable`\n * row persists across boots and no verb deletes it. So a bare `daemon install` found nothing to\n * retire on the one machine that had two of them, reported success, and left the rows behind.\n * Found by running the real install against a real `~/Library/LaunchAgents`, not by a test.\n *\n * The directory is authoritative for \"a definition exists\" and the list is authoritative for\n * \"it is loaded\"; retirement needs the union, because a unit that is either is a unit to remove.\n */\n labels(prefix: string): readonly string[] {\n const loaded = parseLaunchctlList(this.#exec(\"launchctl\", [\"list\"]).stdout)\n .map((entry) => entry.label)\n .filter((label) => label.startsWith(prefix))\n let onDisk: string[] = []\n try {\n onDisk = readdirSync(join(this.#home, \"Library\", \"LaunchAgents\"))\n .filter((name) => name.startsWith(prefix) && name.endsWith(\".plist\"))\n .map((name) => name.slice(0, -\".plist\".length))\n } catch {\n // No LaunchAgents directory yet is the ordinary state before a first install.\n }\n return [...new Set([...loaded, ...onDisk])].sort()\n }\n\n /** None: `install` bootstraps the job itself, so there is nothing left for anybody to run. */\n followUp(): readonly string[] {\n return []\n }\n\n /** None. A LaunchAgent's survival across a login is `RunAtLoad`, which the plist carries. */\n caution(): string | undefined {\n return undefined\n }\n\n #launchctl(args: readonly string[], options: { tolerate?: boolean } = {}): ExecResult {\n const result = this.#exec(\"launchctl\", args)\n if (result.code === 0 || options.tolerate === true) return result\n // launchctl's own stderr, verbatim. Its messages are terse — \"Bootstrap failed: 5:\n // Input/output error\" — and paraphrasing loses the code, which is the only searchable part.\n throw new HarnessError({\n code: \"daemon_launchctl_failed\",\n message: `launchctl ${args.join(\" \")} failed (${result.code}): ${result.stderr.trim() || \"no output\"}`,\n hint: `Code 5 usually means the service is already loaded — try \\`daemon restart\\`. Code 37 means an operation is still in progress; wait a moment. Code 125 or 112 means the ${this.#domain} domain is unavailable, which happens over SSH with no GUI session: a LaunchAgent needs a logged-in desktop session, and the exit timeout is ${EXIT_TIMEOUT_SECONDS}s.`,\n })\n }\n}\n",
|
|
11
|
+
"/**\n * The systemd user unit: rendered and written here, enabled by two commands the person runs.\n *\n * ## Why this stops short of running `systemctl`\n *\n * `service.ts` refused Linux entirely on the argument that *\"a systemd renderer nobody here can\n * execute would be a liability: wrong in ways no test catches, shipped with an acceptance criterion\n * that could not honestly be ticked.\"* Half of that argument has expired — Linux is the platform a\n * server runs on — and half has not: a container has no systemd (PID 1 is the entrypoint) and\n * `systemctl --user` on a CI runner has no D-Bus user session, so nothing in this project's test\n * environment can drive the lifecycle verbs end to end.\n *\n * So the split is by what can be *proven*. The unit text is pure and fully tested; writing a file\n * is ordinary I/O; and `enable --now` is printed rather than executed, because an install that\n * reports success while nothing runs is the failure mode this whole phase exists to remove. Two\n * commands is a worse experience than one and an honest one.\n *\n * ## `enable-linger` is not a footnote\n *\n * A systemd *user* unit is stopped when the user's last session ends, unless lingering is enabled\n * for that account. Without it, an always-on agent server installed over SSH is gone the moment the\n * connection closes — which is precisely launchd's `disable` trap in a different costume: installs\n * cleanly, reports success, and is not there later. So the line is printed with the reason attached,\n * and `daemon status` warns when lingering is off.\n *\n * ## What is deliberately the same as launchd\n *\n * `Restart=on-failure` mirrors `KeepAlive: {Crashed: true}` and `RestartSec` mirrors\n * `ThrottleInterval`: a configuration fault must stop once rather than retry into a log nobody\n * opens, which is the 57 MB lesson. `TimeoutStopSec` mirrors `ExitTimeOut`, and must exceed the\n * runtime's own stop deadline or the reaper that kills backgrounded `exec` children never finishes.\n * And the environment goes through the same `assertNoSecrets` — `systemctl show` echoes\n * `Environment=` exactly as `launchctl print` echoes `EnvironmentVariables`.\n */\n\nimport { join } from \"node:path\"\nimport { EXIT_TIMEOUT_SECONDS, type ServicePlan, THROTTLE_SECONDS } from \"#lib/launchd\"\nimport { assertNoSecrets } from \"#lib/service-env\"\n\n/** `~/.config/systemd/user/<label>.service`, honouring `XDG_CONFIG_HOME` when it is set. */\nexport function unitPath(\n label: string,\n home: string,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const configHome = env.XDG_CONFIG_HOME\n const base = configHome === undefined || configHome === \"\" ? join(home, \".config\") : configHome\n return join(base, \"systemd\", \"user\", `${label}.service`)\n}\n\n/**\n * Escape a value for a systemd unit.\n *\n * Nothing like XML escaping: systemd's parser treats a value as literal to end of line, so the only\n * thing that can break a line is a **newline**. A path containing one is refused rather than\n * silently truncated — a unit whose `ExecStart` stops halfway is a service that runs the wrong\n * command, which is worse than a command that fails here.\n */\nexport function assertUnitSafe(value: string, field: string): void {\n if (/[\\r\\n]/.test(value)) {\n throw new Error(\n `${field} contains a newline, which systemd cannot express. hint: a unit value runs to end of line, so this would silently truncate rather than fail — rename the path.`,\n )\n }\n}\n\n/**\n * Quote one `ExecStart` argument.\n *\n * systemd splits `ExecStart` on whitespace, so a path with a space in it becomes two arguments —\n * and a sandbox under `/Users/Some Name/` is an ordinary thing to have. Double quotes are systemd's\n * own quoting, with backslash escaping inside them.\n */\nexport function quoteArg(arg: string): string {\n if (!/[\\s\"\\\\]/.test(arg)) return arg\n return `\"${arg.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`\n}\n\nexport function renderUnit(plan: ServicePlan, envPrefix: string): string {\n assertNoSecrets(plan.environment, envPrefix, \"systemd\")\n for (const arg of plan.programArguments) assertUnitSafe(arg, \"ExecStart\")\n assertUnitSafe(plan.workingDirectory, \"WorkingDirectory\")\n for (const [key, value] of Object.entries(plan.environment)) {\n assertUnitSafe(value, `Environment=${key}`)\n }\n\n const exec = plan.programArguments.map(quoteArg).join(\" \")\n const environment = Object.entries(plan.environment)\n .map(([key, value]) => `Environment=${key}=${value}`)\n .join(\"\\n\")\n const comment = plan.provenance.map((line) => `# ${line}`).join(\"\\n\")\n\n // No StandardOutput/StandardError: systemd's default is the journal, which rotates, is\n // searchable and survives a disk filling up — none of which a plain append-only file does.\n // `daemon logs` reads `journalctl` on this platform for the same reason.\n return `${comment}\n\n[Unit]\nDescription=${plan.label}\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nExecStart=${exec}\nWorkingDirectory=${plan.workingDirectory}\n${environment}\n# A configuration fault stops the service once rather than retrying into a log nobody opens.\n# Mirrors launchd's KeepAlive: {Crashed: true} — see launchd.ts for why that is structural.\nRestart=on-failure\nRestartSec=${THROTTLE_SECONDS}\n# Must exceed the runtime's own stop deadline, or the reaper that kills backgrounded exec\n# children never finishes and they outlive the service.\nTimeoutStopSec=${EXIT_TIMEOUT_SECONDS}\nKillMode=mixed\n\n[Install]\nWantedBy=default.target\n`\n}\n\n/** The commands a person runs after the unit is written, in the order they run them. */\nexport function followUp(label: string, user: string): readonly string[] {\n return [\n `systemctl --user daemon-reload`,\n `systemctl --user enable --now ${label}`,\n `loginctl enable-linger ${user}`,\n ]\n}\n\n/** How to read the log on this platform. The journal, not a file — see `renderUnit`. */\nexport function logCommand(label: string): string {\n return `journalctl --user -u ${label} -f`\n}\n",
|
|
12
|
+
"/**\n * First run: if no server is up, put one up — and say so in one line.\n *\n * This is the most invasive thing the product does, and it is defensible only because of four\n * properties, each of which is a line of code below rather than an intention:\n *\n * 1. **It is announced**, in one line, naming the command that undoes it.\n * 2. **It is skipped for every command that does not want a host** — `CommandSpec.needsServer` is a\n * required field so that decision is taken per command rather than inherited from a list in\n * `index.ts` that a new command is silently absent from, or silently included in.\n * 3. **It never runs inside a container**, which *is* the daemon, or under CI, or when the escape\n * hatch is set. A service manager inside a container is a second supervisor arguing with the\n * first.\n * 4. **It never fails the command it was asked for.** A LaunchAgent needs a GUI session, so over\n * SSH `launchctl bootstrap` returns 125 or 112 — and a listing command that died because a\n * background service could not be installed would be a far worse product than one without any\n * of this. Every failure degrades to a printed line.\n *\n * ## Why it does not start a service it cannot start\n *\n * On Linux the unit is written and not enabled — `systemctl --user` is not driven from here (see\n * `service.ts`). Bootstrapping there would mean writing a file and reporting a running server,\n * which is the exact failure this phase exists to remove, so on a platform whose manager cannot\n * start what it installs the bootstrap **prints the command and writes nothing**.\n */\n\nimport { existsSync } from \"node:fs\"\nimport { BRAND } from \"@dispach/core\"\nimport { liveHosts } from \"#lib/lifecycle\"\nimport { managerCanStart } from \"#lib/service\"\n\nexport interface BootstrapOptions {\n /** From `CommandSpec.needsServer`. False short-circuits everything. */\n readonly needsServer: boolean\n readonly platform?: string\n readonly env?: Readonly<Record<string, string | undefined>>\n /** `--no-bootstrap`. */\n readonly disabled?: boolean\n /** Injected by tests; the real one installs and starts the unit. */\n readonly install?: () => Promise<BootstrapResult>\n /** The store to look for a live host in. `serve --store` has one, so this does too. */\n readonly store?: string\n}\n\nexport type BootstrapResult =\n | { readonly kind: \"started\"; readonly label: string }\n | { readonly kind: \"manual\"; readonly lines: readonly string[] }\n | { readonly kind: \"failed\"; readonly message: string; readonly hint: string }\n\n/** Why nothing was done, when nothing was done. Returned rather than logged, so a test can read it. */\nexport type BootstrapOutcome =\n | { readonly kind: \"skipped\"; readonly reason: SkipReason }\n | { readonly kind: \"already\" }\n | BootstrapResult\n\nexport type SkipReason =\n | \"command-needs-no-server\"\n | \"disabled-by-flag\"\n | \"disabled-by-env\"\n | \"in-container\"\n | \"in-ci\"\n | \"is-the-service\"\n\n/**\n * Are we inside a container?\n *\n * A container is already supervised by whatever started it, and its entrypoint is `serve` — so it\n * neither wants a bootstrap nor has a terminal to lose. `/.dockerenv` is Docker's own marker; the\n * `container` variable covers podman and a hand-rolled image.\n *\n * Exported because the *banner* needs it too, and for the reason `browsableHost` gives about having\n * had two copies before a third caller arrived: the sign-off line told a container operator to\n * press ctrl-c in a terminal that does not exist and to run `daemon install` against a supervisor\n * that is already doing the job.\n */\nexport function inContainer(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): boolean {\n return existsSync(\"/.dockerenv\") || env.container !== undefined\n}\n\n/**\n * Why we are not doing this, checked before anything is read.\n *\n * Ordered cheapest-first and by *specificity*: `is-the-service` is checked before `in-container`\n * because a service process is the one case where being wrong would be recursive, and the reason is\n * worth reporting accurately when a test asks.\n */\nexport function skipReason(options: BootstrapOptions): SkipReason | undefined {\n const env = options.env ?? process.env\n if (!options.needsServer) return \"command-needs-no-server\"\n if (options.disabled === true) return \"disabled-by-flag\"\n if (env[`${BRAND.envPrefix}SERVICE`] !== undefined) return \"is-the-service\"\n if (env[`${BRAND.envPrefix}NO_BOOTSTRAP`] !== undefined) return \"disabled-by-env\"\n if (inContainer(env)) return \"in-container\"\n // Not politeness: a CI job that installed a LaunchAgent would leave it behind on a shared\n // runner, and the job after it would inherit a server nobody asked for.\n if (env.CI !== undefined) return \"in-ci\"\n return undefined\n}\n\n/**\n * Put a server up if one is not already up.\n *\n * \"Already up\" is decided from the **lease table plus pid liveness**, which is the same witness\n * every other surface uses — `liveHosts` filters on `process.kill(pid, 0)`, so a row left behind by\n * a boot that died after claiming does not read as a running server. No HTTP probe: a lease with a\n * live pid is a process hosting agents whether or not it serves HTTP, and a `run` REPL holding one\n * is a reason not to install a second host underneath somebody.\n */\nexport async function ensureServer(options: BootstrapOptions): Promise<BootstrapOutcome> {\n const skip = skipReason(options)\n if (skip !== undefined) return { kind: \"skipped\", reason: skip }\n\n const hosts = await liveHosts(options.store)\n if (hosts.length > 0) return { kind: \"already\" }\n\n const platform = options.platform ?? process.platform\n if (!managerCanStart(platform)) {\n // Write nothing and claim nothing. See the file comment.\n return {\n kind: \"manual\",\n lines: [`${BRAND.slug} daemon install`],\n }\n }\n\n const install = options.install\n if (install === undefined) {\n return {\n kind: \"failed\",\n message: \"no installer was supplied\",\n hint: \"This is a wiring mistake rather than a configuration one: `ensureServer` is called with an `install` callback by `index.ts`.\",\n }\n }\n\n try {\n return await install()\n } catch (error) {\n // Never rethrown. A command that failed because a *background service* could not be\n // installed would be a worse product than one with no bootstrap at all — and over SSH on\n // macOS this is the ordinary outcome, because a LaunchAgent needs a GUI session.\n const detail = error instanceof Error ? error.message : String(error)\n return {\n kind: \"failed\",\n message: detail,\n hint: `The command ran anyway. \\`${BRAND.slug} daemon install\\` reports the same failure with more detail — on macOS over SSH it is usually that a LaunchAgent needs a logged-in desktop session.`,\n }\n }\n}\n\n/**\n * The one line, and it is the whole justification for doing this at all.\n *\n * Written to **stderr**, so it never lands in the middle of `--json` output somebody is piping into\n * `jq` — the announcement matters to a person and is noise to a script. Every branch names what to\n * type next: the undo for a success, the do-it-yourself for a platform we do not drive, and the\n * diagnostic command for a failure.\n */\nexport function announce(outcome: BootstrapOutcome): string | undefined {\n switch (outcome.kind) {\n case \"started\":\n return `started the background server · \\`${BRAND.slug} daemon uninstall\\` to undo\\n`\n case \"manual\":\n return `no server is running · ${outcome.lines.join(\", then \")}\\n`\n case \"failed\":\n return `could not start a background server: ${outcome.message}\\n hint: ${outcome.hint}\\n`\n default:\n // `skipped` and `already` are the ordinary states and say nothing. A line on every\n // invocation is a line nobody reads, which is how the one that matters gets missed.\n return undefined\n }\n}\n",
|
|
13
|
+
"/**\n * Getting an agent hosted, adopted and reloaded — the sequence three commands share.\n *\n * `init`, `channels pair` and `restart` each need the same three moves: make sure a host is up\n * (the bootstrap), have it adopt the agent (`POST /start`), and have it pick up a change\n * (`POST /reload`). Written once, because three copies is how one of them comes to do the middle\n * step and skip the last — and a pairing whose session sits on disk unread by the process that is\n * supposed to answer is exactly the \"paired, now run `serve` by hand\" dead end this exists to close.\n *\n * Everything here talks to a host through the lease table and HTTP, never through the service\n * manager: a host started by hand, by launchd, by systemd or by a container is the same host once\n * it holds a lease, and the lease is the one witness every surface already trusts.\n */\n\nimport type { LeaseRecord } from \"@dispach/core\"\nimport { BRAND } from \"@dispach/core\"\nimport { daemonCommand } from \"#daemon\"\nimport { type BootstrapOutcome, type BootstrapResult, ensureServer } from \"#lib/bootstrap\"\nimport { EXIT_OK } from \"#lib/const\"\nimport {\n agentIdFor,\n anyLiveHost,\n callHost,\n type HostReply,\n liveHostOf,\n postToHost,\n} from \"#lib/lifecycle\"\n\n/**\n * Install and start the server unit, as the bootstrap does it.\n *\n * Reuses `daemonCommand` rather than reaching into the service layer, so a bootstrapped unit and\n * one installed by hand are byte-identical — a second plan builder is how the two come to differ in\n * a way nobody notices until one of them will not start. Its output is swallowed: the bootstrap's\n * whole contract is *one line*, and `daemon install`'s four-row report in front of `agents` would\n * be the opposite.\n */\nexport async function installServerUnit(): Promise<BootstrapResult> {\n const write = process.stdout.write.bind(process.stdout)\n // Replaced rather than piped, because `daemon install` writes with `process.stdout.write`\n // directly and there is nothing to intercept further down. Restored in a `finally`, or every\n // subsequent line of this process would vanish.\n process.stdout.write = (() => true) as typeof process.stdout.write\n try {\n const code = await daemonCommand({ action: \"install\" })\n if (code !== EXIT_OK) {\n return {\n kind: \"failed\",\n message: `daemon install exited ${code}`,\n hint: `Run \\`${BRAND.slug} daemon install\\` to see what it said.`,\n }\n }\n return { kind: \"started\", label: `${BRAND.slug}.server` }\n } finally {\n process.stdout.write = write\n }\n}\n\nexport type Installer = () => Promise<BootstrapResult>\n\nexport interface EnsureHostOptions {\n /** How to start one when none is up. Absent means \"do not try\" — a test, or a caller that must not install. */\n readonly install?: Installer\n readonly store?: string\n readonly env?: Readonly<Record<string, string | undefined>>\n /** How long to wait for a freshly started server to claim its lease. */\n readonly waitMs?: number\n}\n\n/** How long a just-installed unit gets to boot and publish an address before we stop waiting. */\nconst HOST_WAIT_MS = 15_000\nconst HOST_POLL_MS = 250\n\n/**\n * A host with an HTTP address, starting one if allowed and none is up.\n *\n * `host` is `undefined` when nothing could be reached — a platform we do not drive, a container,\n * CI, no installer, or a unit that installed and did not come up in time. The outcome says which,\n * and the caller prints `announce(outcome)` so the person sees the same one line the bootstrap\n * prints everywhere else.\n */\nexport async function ensureHost(\n options: EnsureHostOptions = {},\n): Promise<{ readonly outcome: BootstrapOutcome; readonly host: LeaseRecord | undefined }> {\n const outcome = await ensureServer({\n needsServer: true,\n disabled: options.install === undefined,\n ...(options.install === undefined ? {} : { install: options.install }),\n ...(options.store === undefined ? {} : { store: options.store }),\n ...(options.env === undefined ? {} : { env: options.env }),\n })\n // Only a start is worth waiting on: `already` answers now, and every other kind means no host\n // is coming.\n const deadline =\n Date.now() + (outcome.kind === \"started\" ? (options.waitMs ?? HOST_WAIT_MS) : 0)\n for (;;) {\n const host = await anyLiveHost(options.store)\n if (host !== undefined || Date.now() >= deadline) return { outcome, host }\n await new Promise((resolve) => setTimeout(resolve, HOST_POLL_MS))\n }\n}\n\n/**\n * Have `host` serve this agent, unless something already does.\n *\n * `POST /v1/agents/:id/start` is also what `start` posts; a running host that already holds the\n * lease is left alone rather than asked to start what it is serving.\n */\nexport async function adoptOnHost(\n host: LeaseRecord,\n manifestPath: string,\n store?: string,\n): Promise<HostReply & { readonly already?: true }> {\n const agentId = agentIdFor(manifestPath)\n const holder = await liveHostOf(agentId, store)\n if (holder !== undefined && holder.baseUrl !== undefined) {\n return { ok: true, status: 200, already: true }\n }\n return await postToHost(\n host,\n `/v1/agents/${encodeURIComponent(agentId)}/start`,\n {},\n manifestPath,\n )\n}\n\nexport type ReloadResult =\n | { readonly kind: \"reloaded\"; readonly pid: number; readonly adopted: readonly string[] }\n | { readonly kind: \"busy\"; readonly pid: number }\n | {\n readonly kind: \"failed\"\n readonly pid: number\n readonly status: number\n readonly detail?: string\n readonly hint?: string\n }\n | { readonly kind: \"no-host\" }\n\n/**\n * Ask the host holding this agent to rebuild it from disk.\n *\n * `POST /v1/agents/:id/reload` disposes and re-creates the agent from its manifest, so a pairing\n * written beside it, a token added to `.env` or an edited `agent.yaml` take effect without a\n * restart of the process that hosts every other agent too. `409` is a turn in flight and is\n * reported as such rather than retried: the person asked for a reload, not for a turn to be cut.\n */\nexport async function reloadOnHost(manifestPath: string, store?: string): Promise<ReloadResult> {\n const agentId = agentIdFor(manifestPath)\n const holder = await liveHostOf(agentId, store)\n if (holder === undefined || holder.baseUrl === undefined) return { kind: \"no-host\" }\n const reply = await postToHost(\n holder,\n `/v1/agents/${encodeURIComponent(agentId)}/reload`,\n {},\n manifestPath,\n )\n if (reply.ok) {\n const body = reply.body as { adopted?: readonly string[] } | undefined\n return { kind: \"reloaded\", pid: holder.pid, adopted: body?.adopted ?? [] }\n }\n if (reply.status === 409) return { kind: \"busy\", pid: holder.pid }\n return {\n kind: \"failed\",\n pid: holder.pid,\n status: reply.status,\n ...(reply.detail === undefined ? {} : { detail: reply.detail }),\n ...(reply.hint === undefined ? {} : { hint: reply.hint }),\n }\n}\n\nexport interface LiveChannel {\n readonly id: string\n readonly status: string\n readonly detail?: string\n readonly input?: {\n readonly kind: string\n readonly payload: string\n readonly expiresAt?: string\n }\n}\n\n/**\n * The channel states the host holding this agent reports, or `undefined` when nothing does.\n *\n * Best effort throughout: a host that refuses, has no HTTP, or answers something unexpected leaves\n * the caller with the manifest view rather than a failed command. Reading a file must not start\n * depending on a socket.\n */\nexport async function liveChannels(\n manifestPath: string,\n store?: string,\n): Promise<Map<string, LiveChannel> | undefined> {\n const agentId = agentIdFor(manifestPath)\n if (agentId === \"\") return undefined\n const holder = await liveHostOf(agentId, store)\n if (holder === undefined || holder.baseUrl === undefined) return undefined\n const reply = await callHost(\n holder,\n \"GET\",\n `/v1/agents/${encodeURIComponent(agentId)}`,\n manifestPath,\n )\n if (!reply.ok) return undefined\n const body = reply.body as { channels?: readonly LiveChannel[] } | undefined\n if (body?.channels === undefined) return undefined\n return new Map(body.channels.map((channel) => [channel.id, channel]))\n}\n\nexport type HostPairOutcome = \"paired\" | \"no-code\" | \"timeout\"\n\nexport interface WaitForPairingOptions {\n readonly manifestPath: string\n readonly channelId: string\n readonly store?: string\n readonly out?: (text: string) => void\n /** How long to wait for the host to offer a code. */\n readonly codeWaitMs?: number\n /** How long to wait for the phone once the code is on screen. */\n readonly pairWaitMs?: number\n readonly pollMs?: number\n}\n\nconst CODE_WAIT_MS = 25_000\nconst PAIR_WAIT_MS = 120_000\nconst POLL_MS = 2_000\n\n/**\n * Show the code the host is offering and wait for the phone.\n *\n * The host does the pairing — it holds the socket to WhatsApp, and when the phone accepts, the\n * session is already in the process that will answer. Nothing to reload afterwards, which is the\n * whole reason this path is preferred over pairing in this process and asking the host to pick it\n * up. Bounded twice: for the code to appear and for the phone to act, each named on the way out.\n */\nexport async function waitForPairing(options: WaitForPairingOptions): Promise<HostPairOutcome> {\n const out = options.out ?? ((text: string) => process.stdout.write(text))\n const poll = options.pollMs ?? POLL_MS\n let shown: string | undefined\n let deadline = Date.now() + (options.codeWaitMs ?? CODE_WAIT_MS)\n while (Date.now() < deadline) {\n const now = (await liveChannels(options.manifestPath, options.store))?.get(\n options.channelId,\n )\n if (now?.status === \"connected\") {\n out(`Paired. ${options.channelId} is linked.\\n`)\n return \"paired\"\n }\n if (now?.input !== undefined && now.input.payload !== shown) {\n if (shown === undefined) deadline = Date.now() + (options.pairWaitMs ?? PAIR_WAIT_MS)\n shown = now.input.payload\n const code = shown.replace(/(.{4})(?=.)/g, \"$1 \")\n out(\n `\\n${now.detail ?? \"On the phone: WhatsApp › Settings › Linked devices › Link with phone number. Enter this code\"}:\\n\\n ${code}\\n\\nWaiting — this finishes on its own, or press ctrl-c and pair later.\\n`,\n )\n }\n await new Promise((resolve) => setTimeout(resolve, poll))\n }\n return shown === undefined ? \"no-code\" : \"timeout\"\n}\n",
|
|
14
|
+
"/**\n * Pairing WhatsApp during `init`, between writing the files and finishing.\n *\n * ## Why here rather than \"run these two commands afterwards\"\n *\n * Somebody who has just typed their WhatsApp number has said what they want; sending them away to\n * start a server and run a second command to collect a code is answering a question with homework.\n * The catalogue interlude set the precedent — an answer that costs time gets its own screen inside\n * the flow, not a paragraph of instructions after it.\n *\n * It sits **after the files are written** for the same reason the skills install does: the channel\n * is constructed from the manifest that was just validated, so there is exactly one description of\n * this channel rather than a second one assembled from the answers.\n *\n * ## What it must not do\n *\n * **It must never fail the init and must never hang.** The agent is already written and valid by the\n * time this runs; a pairing that does not happen is a thing to do later, not a reason to have no\n * agent. Every path here reports and returns, and the wait is bounded — which matters more than\n * usual because the transport **does not pair under Bun**, where no code ever arrives and an\n * unbounded wait would turn the last step of onboarding into a hang.\n *\n * **It is skipped without a terminal.** A scripted `--yes` run has nobody to read a code or hold a\n * phone, and opening a socket to WhatsApp in CI is the expensive default the wizard's own fallback\n * rule exists to prevent. The commands that do it later are named instead.\n */\n\nimport { BRAND, type ChannelHost, type ChannelInput, type ChannelTransport } from \"@dispach/core\"\nimport { CHANNELS } from \"#lib/providers\"\n\n/** How long to wait for a code before saying where to get one later. */\nconst CODE_WAIT_MS = 25_000\n\n/**\n * How long to keep waiting for the phone after the code is on screen.\n *\n * Generous, because the clock a person is working against is finding their phone and typing eight\n * characters. Bounded anyway: an `init` that never returns is worse than one that says \"carry on\n * when you are ready\" and names the command that shows the state.\n */\nconst PAIR_WAIT_MS = 120_000\n\nexport interface PairRequest {\n readonly manifestPath: string\n readonly dir: string\n readonly number: string\n readonly channelId: string\n /** Where the manifest keeps the session. Defaults to the channel's own default. */\n readonly authDir?: string\n /** Injected by tests, which never reach WhatsApp. */\n readonly factory?: typeof CHANNELS.whatsapp\n readonly codeWaitMs?: number\n readonly pairWaitMs?: number\n readonly out?: (text: string) => void\n}\n\nexport type PairOutcome = \"paired\" | \"code-shown\" | \"no-code\" | \"unavailable\"\n\n/**\n * Offer a pairing code and wait for the phone. Never throws.\n *\n * Returns what happened so the caller's closing message can be honest about it — a \"next steps\"\n * block that says \"scan the code\" after no code appeared is the kind of true-sounding wrong this\n * project keeps finding.\n */\nexport async function pairWhatsApp(request: PairRequest): Promise<PairOutcome> {\n const write = request.out ?? ((text: string) => process.stdout.write(text))\n const factory = request.factory ?? CHANNELS.whatsapp\n if (factory === undefined) return \"unavailable\"\n\n let transport: ChannelTransport\n try {\n transport = factory({\n id: request.channelId,\n agentId: \"\",\n dir: request.dir,\n env: {},\n config: { authDir: request.authDir ?? \"./.whatsapp\", pairWith: request.number },\n })\n } catch {\n // A number the channel refuses was already refused by the wizard, so this is a build that\n // cannot supply the channel at all. Nothing to say that the caller cannot say better.\n return \"unavailable\"\n }\n\n let code: string | undefined\n let paired = false\n let failure: string | undefined\n let wake: (() => void) | undefined\n const bump = (): void => {\n wake?.()\n wake = undefined\n }\n\n const host: ChannelHost = {\n receive: () => {},\n status: (status: string, detail?: string, input?: ChannelInput) => {\n if (status === \"needs_input\" && input !== undefined && code === undefined) {\n code = input.payload\n bump()\n }\n if (status === \"connected\") {\n paired = true\n bump()\n }\n void detail\n },\n // Reported rather than swallowed: the Bun limitation arrives here, and it is the one\n // sentence that explains an empty wait.\n error: (detail: unknown) => {\n const message = (detail as { message?: string } | undefined)?.message\n if (message !== undefined && failure === undefined) failure = message\n },\n } as unknown as ChannelHost\n\n const until = async (deadline: number, done: () => boolean): Promise<void> => {\n const end = Date.now() + deadline\n while (!done() && Date.now() < end) {\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, Math.min(500, end - Date.now()))\n wake = () => {\n clearTimeout(timer)\n resolve()\n }\n })\n }\n }\n\n try {\n await transport.start(host)\n write(\"\\nConnecting to WhatsApp…\\n\")\n await until(request.codeWaitMs ?? CODE_WAIT_MS, () => code !== undefined || paired)\n\n if (code === undefined && !paired) {\n write(`\\nNo pairing code arrived${failure === undefined ? \"\" : ` — ${failure}`}\\n`)\n return \"no-code\"\n }\n if (code !== undefined && !paired) {\n write(\n `\\nOn the phone: WhatsApp › Settings › Linked devices › Link with phone number.\\n` +\n `Enter this code for +${request.number}:\\n\\n ${grouped(code)}\\n\\n` +\n `Waiting — this finishes on its own, or press ctrl-c and pair later.\\n`,\n )\n await until(request.pairWaitMs ?? PAIR_WAIT_MS, () => paired)\n }\n if (paired) {\n write(`\\nPaired. WhatsApp is linked to +${request.number}.\\n`)\n return \"paired\"\n }\n return \"code-shown\"\n } catch {\n return \"no-code\"\n } finally {\n // Always, including on the paired path: the credentials are on disk and the agent's own\n // run is what should hold the socket. Leaving this one open would put two linked devices\n // on one session.\n await transport.stop().catch(() => {})\n }\n}\n\n/** WhatsApp shows its code as two groups of four. Display only — the value is never rewritten. */\nfunction grouped(code: string): string {\n return code.length === 8 ? `${code.slice(0, 4)} ${code.slice(4)}` : code\n}\n\n/** What to tell somebody who did not finish pairing here. One sentence per route. */\nexport function pairLater(agentRef: string): string {\n return ` Pair WhatsApp later: \\`${BRAND.slug} channels pair ${agentRef} wa\\` — or from the web UI.\\n`\n}\n",
|
|
15
|
+
"/**\n * Connect, disconnect, re-credential and unpair a channel — the four things a person does to one.\n *\n * ## Why this is a module rather than four call sites\n *\n * Every one of these was *possible* already and reachable from nowhere obvious. Disabling a channel\n * meant `config set <agent> channels '[{...the whole list again...}]'`; changing a token meant\n * knowing that `tokenEnv` names a variable and that `config env` writes it; relinking WhatsApp meant\n * finding a directory and deleting it. A capability reachable only by somebody who already knows the\n * field names is a capability the surface is hiding — the standing rule that put every provider in\n * `init`, and the same one applies to the thing a person touches most after creating an agent.\n *\n * So: one module, read by the `channels` command and by the HTTP routes the browser calls. Two\n * surfaces over one implementation, which is the only way they cannot disagree — and the lesson this\n * project has paid for repeatedly, most recently where `validate` and `run` disagreed about a cold\n * Composio cache.\n *\n * ## What \"connect\" means, and what it cannot mean\n *\n * `enabled: true` in the manifest, and nothing more. A channel is constructed at boot and\n * `Runtime.create` is what starts it, so flipping the flag on a running agent takes effect at its\n * next start — `manifest_changed` already says so for every other setting and this is no different.\n * Pretending otherwise by hot-starting a transport here would make \"connected\" mean two different\n * things depending on which surface you asked.\n */\n\nimport { existsSync, readFileSync, rmSync } from \"node:fs\"\nimport { dirname, isAbsolute, join, resolve } from \"node:path\"\nimport {\n type AgentManifest,\n editManifest,\n HarnessError,\n parseDotEnv,\n readManifestHeader,\n} from \"@dispach/core\"\nimport { applySecret, envPathOf } from \"#lib/config-apply\"\n\n/** One channel as every surface reports it, before any runtime state is layered on. */\nexport interface ChannelEntry {\n readonly id: string\n readonly type: string\n readonly enabled: boolean\n /** The env var this channel's credential lives in, when it has one. */\n readonly credentialEnv?: string\n /**\n * Whether that variable currently has a value.\n *\n * The **name and whether it is set**, never the value. A surface that could read a credential\n * back is one a leaked operator key turns into a credential dump, and nothing needs it: the only\n * question anybody asks is \"is this filled in\".\n */\n readonly credentialSet?: boolean\n /**\n * The WhatsApp account this channel links to, when one is configured.\n *\n * Its presence is what decides *how* pairing happens — a code typed into the phone rather than\n * a QR — so a listing that did not carry it had to describe the method with a constant, and\n * that constant said \"paired by QR\" for a channel that pairs by code and has never paired.\n */\n readonly pairWith?: string\n /**\n * Whether a pairing already exists on disk.\n *\n * A fact about the filesystem rather than about a running process, which is exactly why it\n * belongs in a manifest-reading listing: \"is this linked\" is answerable without a host, and\n * answering it is the difference between \"connected\" and something true.\n */\n readonly paired?: boolean\n /** Where a WhatsApp session lives, as written. Relative paths are relative to the manifest. */\n readonly authDir?: string\n /** Senders this channel accepts. Inbound only. */\n readonly allowFrom: readonly string[]\n}\n\n/**\n * Which manifest field holds a channel's credential variable, by channel type.\n *\n * A small table rather than a convention, because it *is* small and a convention would be a guess:\n * `tokenEnv` is Telegram's word and a plugin picks its own. A type that is not here has no\n * credential in the `.env` — WhatsApp is the case, and its pairing is `reset` rather than a value.\n */\nconst CREDENTIAL_FIELD: ReadonlyMap<string, string> = new Map([[\"telegram\", \"tokenEnv\"]])\n\nexport function channelsOf(manifestPath: string): readonly ChannelEntry[] {\n const header = readManifestHeader(manifestPath)\n const declared = header.channels ?? []\n const envPath = envPathOf(manifestPath)\n const env = existsSync(envPath) ? parseDotEnv(readFileSync(envPath, \"utf8\")) : {}\n\n return declared.map((channel) => {\n const field = CREDENTIAL_FIELD.get(channel.type)\n const variable =\n field === undefined\n ? undefined\n : typeof (channel as Record<string, unknown>)[field] === \"string\"\n ? ((channel as Record<string, unknown>)[field] as string)\n : undefined\n return {\n id: channel.id,\n type: channel.type,\n // Absent means enabled, which is the schema's default and what a reader expects.\n enabled: channel.enabled !== false,\n ...(variable === undefined ? {} : { credentialEnv: variable }),\n ...(variable === undefined ? {} : { credentialSet: (env[variable] ?? \"\") !== \"\" }),\n ...(typeof (channel as Record<string, unknown>).pairWith === \"string\"\n ? { pairWith: (channel as Record<string, unknown>).pairWith as string }\n : {}),\n ...(channel.type === \"whatsapp\"\n ? { paired: hasPairing(manifestPath, channel as Record<string, unknown>) }\n : {}),\n ...(typeof (channel as Record<string, unknown>).authDir === \"string\"\n ? { authDir: (channel as Record<string, unknown>).authDir as string }\n : {}),\n allowFrom: channel.allowFrom ?? [],\n }\n })\n}\n\n/**\n * Flip one channel's `enabled`, leaving every other entry byte-identical.\n *\n * Read-modify-write through `editManifest`, the one manifest writer, rather than asking a caller to\n * send the whole `channels` list back. Sending the list is what `config set` does and it is right\n * for a person editing YAML; for a button it would mean the browser reconstructing an array it did\n * not author, and two clients racing on that lose an entry rather than a flag.\n */\nexport async function setChannelEnabled(\n manifestPath: string,\n channelId: string,\n enabled: boolean,\n): Promise<{ readonly note: string; readonly changed: boolean }> {\n const entries = readManifestHeader(manifestPath).channels ?? []\n const existing = entries.find((entry) => entry.id === channelId)\n if (existing === undefined)\n throw unknownChannel(\n channelId,\n entries.map((e) => e.id),\n )\n if ((existing.enabled !== false) === enabled) {\n return {\n note: `Channel \"${channelId}\" is already ${enabled ? \"connected\" : \"disconnected\"}.`,\n changed: false,\n }\n }\n\n await editManifest({\n file: manifestPath,\n path: [\"channels\"],\n value: entries.map((entry) =>\n entry.id === channelId ? { ...entry, enabled } : { ...entry },\n ),\n })\n return {\n note: enabled\n ? `Channel \"${channelId}\" is connected — it starts at the agent's next start.`\n : `Channel \"${channelId}\" is disconnected. A disabled channel is never constructed, so it reads no credential and opens no socket.`,\n changed: true,\n }\n}\n\n/**\n * Write a channel's credential into the `.env` beside the manifest.\n *\n * The variable is the one the *manifest* names, resolved here rather than taken from the caller: a\n * surface that let a client name the variable would let it write any variable at all, including the\n * API token this server authenticates with.\n */\nexport function setChannelCredential(\n manifestPath: string,\n channelId: string,\n value: string,\n): { readonly note: string; readonly variable: string } {\n const entries = readManifestHeader(manifestPath).channels ?? []\n const existing = entries.find((entry) => entry.id === channelId)\n if (existing === undefined)\n throw unknownChannel(\n channelId,\n entries.map((e) => e.id),\n )\n\n const field = CREDENTIAL_FIELD.get(existing.type)\n const variable =\n field === undefined\n ? undefined\n : typeof (existing as Record<string, unknown>)[field] === \"string\"\n ? ((existing as Record<string, unknown>)[field] as string)\n : undefined\n if (variable === undefined) {\n throw new HarnessError({\n code: \"channel_has_no_credential\",\n message: `Channel \"${channelId}\" (type ${existing.type}) keeps no credential in the .env.`,\n hint:\n existing.type === \"whatsapp\"\n ? \"WhatsApp is paired by scanning a QR, not by a value anybody types. Use `channels unpair` to forget the current pairing and scan a new code.\"\n : \"Only a channel whose manifest entry names an environment variable has one to set. Check the entry's own fields.\",\n field: `channels[${channelId}]`,\n })\n }\n\n const applied = applySecret(manifestPath, variable, value)\n return {\n note: `${applied.note}. It is read at the agent's next start.`,\n variable,\n }\n}\n\nfunction unknownChannel(channelId: string, known: readonly string[]): HarnessError {\n return new HarnessError({\n code: \"channel_unknown\",\n message: `This agent declares no channel with id \"${channelId}\".`,\n hint:\n known.length === 0\n ? \"It declares no channels at all. Add one with `config set <agent> channels`, or answer the channel questions in `init`.\"\n : `Declared: ${known.join(\", \")}. The id is the channel's own, not its type.`,\n field: \"channelId\",\n })\n}\n\n/**\n * Delete a stored pairing on disk.\n *\n * The on-disk path, used when no live transport can be asked — a stopped agent, or one whose\n * channels a `run`-mode host never started. Both routes end in the same state, which is the state a\n * first start produces.\n */\nexport function unpairChannel(manifestPath: string, channelId: string): { readonly note: string } {\n const entries = readManifestHeader(manifestPath).channels ?? []\n const existing = entries.find((entry) => entry.id === channelId)\n if (existing === undefined)\n throw unknownChannel(\n channelId,\n entries.map((e) => e.id),\n )\n const dir = pairingDirOf(manifestPath, existing)\n if (dir === undefined) {\n throw new HarnessError({\n code: \"channel_has_no_pairing\",\n message: `Channel \"${channelId}\" (type ${existing.type}) stores no pairing.`,\n hint: \"Only a channel linked by scanning a code has one to forget. A credential somebody typed is changed with `channels credential`, and a channel is switched off with `channels disconnect`.\",\n field: `channels[${channelId}]`,\n })\n }\n rmSync(dir, { recursive: true, force: true })\n return {\n note: `Forgot the pairing — deleted ${dir}. The next start offers a new code to scan; the old device may still be listed on the phone, which is the only place it can be removed.`,\n }\n}\n\n/** Where a channel that stores a pairing keeps it, so a stopped agent can be unpaired too. */\nexport function pairingDirOf(\n manifestPath: string,\n channel: { readonly type: string; readonly authDir?: unknown },\n): string | undefined {\n if (channel.type !== \"whatsapp\") return undefined\n const configured = typeof channel.authDir === \"string\" ? channel.authDir : \"./.whatsapp\"\n return join(dirname(manifestPath), configured)\n}\n\nexport type { AgentManifest }\n\n/**\n * Whether this WhatsApp session is actually linked to an account.\n *\n * **`creds.json` existing is not the answer**, which is the second false claim this listing had:\n * Baileys writes that file the moment it connects, carrying freshly generated keys and\n * `registered: false`, so a channel that has never paired in its life has one. Measured on a live\n * run — the listing said `linked` and `needs_input` in the same row. `registered` inside it is the\n * real signal and is the same field the transport's own pairing guard reads.\n *\n * Unreadable or malformed reads as **not** linked: the cost of saying \"not linked yet\" about a\n * working channel is a person re-running a command, and the cost of the reverse is somebody\n * waiting for a pairing that nothing is going to offer.\n */\nfunction hasPairing(manifestPath: string, channel: Record<string, unknown>): boolean {\n const configured = typeof channel.authDir === \"string\" ? channel.authDir : \"./.whatsapp\"\n const dir = isAbsolute(configured) ? configured : resolve(dirname(manifestPath), configured)\n const file = join(dir, \"creds.json\")\n if (!existsSync(file)) return false\n try {\n const creds = JSON.parse(readFileSync(file, \"utf8\")) as { registered?: unknown }\n return creds.registered === true\n } catch {\n return false\n }\n}\n"
|
|
16
|
+
],
|
|
17
|
+
"mappings": ";0ZAoBA,oBACI,iBACA,gBACA,eACA,mBACA,eACA,eACA,iBAEJ,kBAAS,gBACT,kBAAS,UAAS,cAAM,mBC4CjB,SAAS,CAAa,CAAC,EAA8C,CACxE,IAAM,EAAiB,CAAC,EAExB,GAAI,EAAM,UAAY,OAClB,E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AI,EAAQ,OAAS,WAAY,OACjC,IAAM,EAAa,OAAO,EAAQ,UAAY,SAAW,EAAQ,QAAU,cAC3E,OAAO,GAAK,GAAQ,CAAY,EAAG,CAAU,EAkBjD,SAAS,EAAU,CAAC,EAAsB,EAA2C,CACjF,IAAM,EAAa,OAAO,EAAQ,UAAY,SAAW,EAAQ,QAAU,cACrE,EAAM,GAAW,CAAU,EAAI,EAAa,GAAQ,GAAQ,CAAY,EAAG,CAAU,EACrF,EAAO,GAAK,EAAK,YAAY,EACnC,GAAI,CAAC,GAAW,CAAI,EAAG,MAAO,GAC9B,GAAI,CAEA,OADc,KAAK,MAAM,GAAa,EAAM,MAAM,CAAC,EACtC,aAAe,GAC9B,KAAM,CACJ,MAAO",
|
|
18
|
+
"debugId": "B3E03F0C31FC776E64756E2164756E21",
|
|
19
|
+
"names": []
|
|
20
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`),i=
|
|
4
|
-
export{
|
|
2
|
+
import{jt,pi}from"./index-k3y8y3wj.js";import{o}from"./index-nn3tk25c.js";import{Kn,vA}from"./index-x7v1zq89.js";import{G}from"./index-zn24991r.js";var B=1;function Yt(t,l){let u=Math.max(1,l-B),r=t.value.split(`
|
|
3
|
+
`),i=Kn(t),d=[],m=0,s=0;for(let[f,n]of r.entries()){let h=jt(n,u),b=f===i.line?pi(n,i.column):-1,c=-1;if(b>=0){c=h.length-1;for(let[p,e]of h.entries())if(b<=e.to){c=p;break}}for(let[p,e]of h.entries()){if(p===c)m=d.length;d.push({start:s+e.from,end:s+e.to,lead:e.lead,text:e.text,caret:p===c?e.lead+Math.max(0,Math.min(b-e.from,e.to-e.from)):void 0})}s+=[...n].length+1}return{rows:d,caretRow:m}}function k(t,l){let u=[...t.text],r=[];for(let[i,d]of u.entries()){let m=i<t.lead?-1:t.start+(i-t.lead),s=l!==void 0&&m>=l.start&&m<l.end,f=t.caret===i,n=r.at(-1);if(n!==void 0&&!f&&!n.caret&&n.selected===s){r[r.length-1]={...n,text:n.text+d};continue}r.push({text:d,selected:s,caret:f})}if(t.caret!==void 0&&t.caret>=u.length)r.push({text:" ",selected:!1,caret:!0});return r}import{Box as _,Text as a}from"ink";import{jsx as y,jsxs as w}from"react/jsx-runtime";function Jt({editor:t,placeholder:l,secret:u,gutter:r="",maxRows:i,columns:d}){let m=[...r].length,s=" ".repeat(m);if(t.value===""&&l!==void 0&&l!==""){let x=[...l];return w(a,{dimColor:!0,wrap:"truncate",children:[y(a,{color:o.accent,children:r}),y(a,{inverse:!0,children:x[0]??" "}),x.slice(1).join("")]})}let f=vA(t),{rows:n,caretRow:h}=Yt(t,Math.max(1,(d??Number.MAX_SAFE_INTEGER)-m)),b=i??n.length,{from:c,to:p}=G(n.length,h,Math.max(1,b)),e=c,T=n.length-p;return w(_,{flexDirection:"column",children:[e>0?w(a,{dimColor:!0,wrap:"truncate",children:[s,"… ",e," line",e===1?"":"s"," above"]}):null,n.slice(c,p).map((x,v)=>{let C=c+v,M=u===!0?[...x.text].map(()=>"•"):[...x.text],S=C===c&&e===0?r:s;if(x.caret===void 0&&f===void 0)return w(a,{wrap:"truncate",children:[y(a,{color:o.accent,children:S}),M.join("")]},`row-${C}`);let A=k(x,f),L=0;return w(a,{wrap:"truncate",children:[y(a,{color:o.accent,children:S}),A.map((g)=>{let R=`run-${C}-${L}`;L+=[...g.text].length;let E=u===!0?[...g.text].map(()=>"•").join(""):g.text;if(g.caret)return y(a,{inverse:!0,children:E},R);if(g.selected)return y(a,{backgroundColor:o.selection,children:E},R);return y(a,{children:E},R)})]},`row-${C}`)}),T>0?w(a,{dimColor:!0,wrap:"truncate",children:[s,"… ",T," line",T===1?"":"s"," below"]}):null]})}
|
|
4
|
+
export{Yt,Jt};
|
|
5
5
|
|
|
6
|
-
//# debugId=
|
|
7
|
-
//# sourceMappingURL=index-
|
|
6
|
+
//# debugId=1C0C369D3F789F5864756E2164756E21
|
|
7
|
+
//# sourceMappingURL=index-jq999vcw.js.map
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"/**\n * The composer's visual rows and where the caret sits on them. Pure, so the layout is arithmetic.\n *\n * ## Why the input box needs its own wrapping at all\n *\n * It rendered each logical line with `wrap=\"truncate\"` and no wrapping of its own, which is half of the\n * rule `lib/wrap.ts` states and the half that does not work. Ink truncates to the width Yoga measured,\n * and a `<Box>` with no explicit width takes its *content* width — so a long message made the box wider\n * than the terminal, and what happened next was the terminal's decision rather than ours. Measured at 100\n * columns: VS Code cut the line at the border and took the caret with it, so you could not see what you\n * were typing; Warp wrapped the over-wide row and the tail landed on top of the right-hand border. One\n * cause, two symptoms, and neither reproducible in the other terminal.\n *\n * So the composer wraps its own text, exactly as the transcript and the live pane do, and every row is\n * drawn `wrap=\"truncate\"` as a backstop rather than as the layout.\n *\n * ## One column is reserved, deliberately\n *\n * The caret is drawn as an inverse cell, so it needs a cell — including when it sits at the end of a line\n * that exactly fills the row. Wrapping to `columns - 1` buys that cell once, for every row, with no\n * special case; the alternative is an extra visual row that appears and disappears as you type past the\n * edge, which moves the whole frame on a surface that has no room to move.\n *\n * ## One derivation, two callers\n *\n * `LineCursor` draws these rows and `chat-frame.promptRows` counts them. That is the pairing the repo has\n * been bitten by before — a component that grows a row without the frame arithmetic knowing is a frame\n * taller than the terminal, which on the alternate buffer is corruption rather than crowding. Here the\n * count is `layout.rows.length` plus the notices, by construction.\n */\n\nimport { lineInfo } from \"#editor\"\nimport type { EditorState } from \"#lib/types\"\nimport { expandColumn, wrapRows } from \"#lib/wrap\"\n\n/** A cell reserved so the caret has somewhere to sit at the end of a full row. */\nconst CARET_CELL = 1\n\nexport interface ComposerRow {\n /** What is painted, hanging indent included. Never wider than the window. */\n readonly text: string\n /** Where the caret sits in this row, or `undefined` when it is on another row. */\n readonly caret: number | undefined\n /**\n * Buffer-absolute code-point offsets of the source this row draws, `start` inclusive and `end` not.\n *\n * Absolute rather than line-relative, which is the only form a selection can use: `wrapRows` reports\n * offsets into a single *line*, and a selection is a range over the whole buffer. Adding the line's own\n * start here is the one place that translation belongs — a renderer recomputing it would need the\n * split, the tab expansion and the wrap all over again to get the same number.\n */\n readonly start: number\n readonly end: number\n /** Columns of `text` that are re-applied indent, which no selection may highlight. */\n readonly lead: number\n}\n\n/** A run of a row that is drawn the same way: selected or not, caret or not. */\nexport interface RowSegment {\n readonly text: string\n readonly selected: boolean\n /** The single cell the caret inverts. Never wider than one code point. */\n readonly caret: boolean\n}\n\nexport interface ComposerLayout {\n /** Every visual row of the buffer, in order. At least one, even for an empty buffer. */\n readonly rows: readonly ComposerRow[]\n /** Index into `rows` holding the caret. */\n readonly caretRow: number\n}\n\n/**\n * Every visual row of `editor`'s buffer at `columns`, and which one the caret is on.\n *\n * `columns` is the width available *inside* whatever draws it — a caller with a border and padding\n * subtracts those first, because this cannot see them.\n */\nexport function composerLayout(editor: EditorState, columns: number): ComposerLayout {\n const width = Math.max(1, columns - CARET_CELL)\n const lines = editor.value.split(\"\\n\")\n const cursor = lineInfo(editor)\n\n const rows: ComposerRow[] = []\n let caretRow = 0\n // Where each line starts in the buffer, in code points. The `+ 1` is the newline itself, which no row\n // draws and every offset after it has to account for.\n let base = 0\n for (const [at, line] of lines.entries()) {\n const wrapped = wrapRows(line, width)\n // The caret's column has to be translated into the same tab-expanded coordinates the rows are\n // measured in, or a line containing a tab puts it seven columns to the left of where it is.\n const column = at === cursor.line ? expandColumn(line, cursor.column) : -1\n // Walked backwards so a caret exactly on a break lands at the *end* of the earlier row rather\n // than the start of the later one, which is where a person expects it after pressing → .\n let on = -1\n if (column >= 0) {\n on = wrapped.length - 1\n for (const [n, row] of wrapped.entries()) {\n if (column <= row.to) {\n on = n\n break\n }\n }\n }\n for (const [n, row] of wrapped.entries()) {\n if (n === on) caretRow = rows.length\n rows.push({\n start: base + row.from,\n end: base + row.to,\n lead: row.lead,\n text: row.text,\n // Clamped into the row: a caret past `to` can only mean the source column sat in the\n // whitespace a break consumed, and the end of the row is the honest place for it.\n caret:\n n === on\n ? row.lead + Math.max(0, Math.min(column - row.from, row.to - row.from))\n : undefined,\n })\n }\n base += [...line].length + 1\n }\n return { rows, caretRow }\n}\n\n/**\n * One row, split into the runs a renderer can paint in one go.\n *\n * Built as runs rather than as three slices because the caret can sit anywhere — including inside the\n * selection — and slicing for both produces overlapping ranges that have to be reconciled. Walking the row\n * once and grouping adjacent code points by how they are drawn has no such case, and the caret staying\n * exactly one cell wide is a property of the walk rather than something to remember.\n *\n * The indent is never selected. Those columns are chrome the wrap re-applied; highlighting them would\n * suggest text is included that no offset in the buffer corresponds to.\n */\nexport function rowSegments(\n row: ComposerRow,\n selection: { readonly start: number; readonly end: number } | undefined,\n): readonly RowSegment[] {\n const cells = [...row.text]\n const segments: RowSegment[] = []\n for (const [column, cell] of cells.entries()) {\n // A column past the indent maps back to the source by the same arithmetic the caret uses; one\n // inside it maps to nothing, which is why it can never be selected.\n const offset = column < row.lead ? -1 : row.start + (column - row.lead)\n const isSelected =\n selection !== undefined && offset >= selection.start && offset < selection.end\n const isCaret = row.caret === column\n const last = segments.at(-1)\n // The caret is its own run always, so it stays one cell wide even in the middle of a selection.\n if (last !== undefined && !isCaret && !last.caret && last.selected === isSelected) {\n segments[segments.length - 1] = { ...last, text: last.text + cell }\n continue\n }\n segments.push({ text: cell, selected: isSelected, caret: isCaret })\n }\n // A caret past the last character has no cell to invert, so it needs one. Same reason `LineCursor`\n // inverts a trailing space today.\n if (row.caret !== undefined && row.caret >= cells.length) {\n segments.push({ text: \" \", selected: false, caret: true })\n }\n return segments\n}\n",
|
|
6
6
|
"/**\n * Editable text with an inverse-video cursor — the rendering half of `editor.ts`.\n *\n * Shared by the chat composer and the wizard's text fields, so there is one cursor implementation:\n * code-point split (never UTF-16 units), the character under the cursor drawn inverse, and a trailing\n * space inverted when the cursor sits at the end. When the buffer is empty and a placeholder is given,\n * the placeholder renders dim with the cursor on its first character — the affordance every modern CLI\n * uses for \"press enter to accept this\".\n *\n * ## Why it renders rows rather than lines\n *\n * The chat buffer became multi-line in Phase 5.5, and the alternative to generalising this was a second\n * component for the composer — which would be a second cursor implementation, the exact thing this file\n * was extracted to prevent. So it renders a column of rows with a caller-supplied `gutter`, and a\n * single-line field is the one-row case of that.\n *\n * A **row is not a line**, and conflating them was the defect. Nothing here wrapped: each logical line was\n * handed to Ink with `wrap=\"truncate\"`, so a message wider than the box was cut and the caret went with it\n * — you could not see what you were typing. `composerLayout` now decides the rows and where the caret sits\n * on them, `wrap=\"truncate\"` is a backstop rather than the layout, and `chat-frame.promptRows` counts the\n * same rows this draws.\n *\n * Two consequences worth stating. The cursor is never drawn *on* a newline: the line break is structure\n * rather than a character, so the caret sits at the end of one row or the start of the next, which is\n * where a person expects it. And the view scrolls to follow the caret through `viewport()` — the same\n * function the catalogue list uses, because \"keep the interesting row visible\" is one rule.\n */\n\nimport { Box, Text } from \"ink\"\nimport { selectionRange } from \"#editor\"\nimport { composerLayout, rowSegments } from \"#lib/composer\"\nimport { viewport } from \"#lib/rows\"\nimport { THEME } from \"#lib/theme\"\nimport type { EditorState } from \"#lib/types\"\n\nexport interface LineCursorProps {\n readonly editor: EditorState\n readonly placeholder?: string\n /**\n * Render every character as a dot. For a value that must not appear on screen, in scrollback, or\n * over a shoulder — the cursor still moves normally, because the editing model is unchanged and\n * only the rendering differs.\n */\n readonly secret?: boolean\n /**\n * Drawn before the first line. Continuation lines get an equal-width blank, so the text stays in\n * one column and a two-line message does not look like two messages.\n */\n readonly gutter?: string\n /** Visible rows before the view starts scrolling to follow the cursor. */\n readonly maxRows?: number\n /**\n * Columns available for the text, the gutter included.\n *\n * Required for anything that can hold a long message. Omitted, nothing wraps and a line wider than\n * whatever draws this is truncated by Ink at a width nobody chose — which is what this component did\n * everywhere until Phase 5.6.\n */\n readonly columns?: number\n}\n\nexport function LineCursor({\n editor,\n placeholder,\n secret,\n gutter = \"\",\n maxRows,\n columns,\n}: LineCursorProps) {\n const lead = [...gutter].length\n const pad = \" \".repeat(lead)\n\n if (editor.value === \"\" && placeholder !== undefined && placeholder !== \"\") {\n const chars = [...placeholder]\n return (\n <Text dimColor wrap=\"truncate\">\n <Text color={THEME.accent}>{gutter}</Text>\n <Text inverse>{chars[0] ?? \" \"}</Text>\n {chars.slice(1).join(\"\")}\n </Text>\n )\n }\n\n // The gutter is drawn on the first row and matched by a blank on every row after it, so the text\n // stays in one column — which means the text itself only ever gets what is left.\n // Derived here rather than passed in: it is a function of the editor state this component already\n // has, and a prop would let a caller draw a highlight the reducer does not believe in.\n const selection = selectionRange(editor)\n const { rows: all, caretRow } = composerLayout(\n editor,\n Math.max(1, (columns ?? Number.MAX_SAFE_INTEGER) - lead),\n )\n const window = maxRows ?? all.length\n const { from, to } = viewport(all.length, caretRow, Math.max(1, window))\n const hiddenAbove = from\n const hiddenBelow = all.length - to\n\n return (\n <Box flexDirection=\"column\">\n {hiddenAbove > 0 ? (\n <Text dimColor wrap=\"truncate\">\n {pad}… {hiddenAbove} line{hiddenAbove === 1 ? \"\" : \"s\"} above\n </Text>\n ) : null}\n {all.slice(from, to).map((row, offset) => {\n const at = from + offset\n // Masked per code point, so the dot count matches what was typed rather than its byte\n // length.\n const chars = secret === true ? [...row.text].map(() => \"•\") : [...row.text]\n const glyph = at === from && hiddenAbove === 0 ? gutter : pad\n if (row.caret === undefined && selection === undefined) {\n return (\n // Keyed by index: two identical rows in a message are not the same row, and a\n // content key would collapse them.\n <Text key={`row-${at}`} wrap=\"truncate\">\n <Text color={THEME.accent}>{glyph}</Text>\n {chars.join(\"\")}\n </Text>\n )\n }\n // Runs rather than slices. The caret can sit inside the selection, and slicing for both\n // produces overlapping ranges that have to be reconciled; `rowSegments` walks the row once\n // and the caret stays one cell wide by construction. Masking is applied after the split so\n // a secret field's dots line up with the runs rather than with the source.\n const runs = rowSegments(row, selection)\n let column = 0\n return (\n <Text key={`row-${at}`} wrap=\"truncate\">\n <Text color={THEME.accent}>{glyph}</Text>\n {runs.map((run) => {\n const key = `run-${at}-${column}`\n column += [...run.text].length\n const text =\n secret === true ? [...run.text].map(() => \"•\").join(\"\") : run.text\n // Inverting a trailing space is how the caret stays visible at end of line;\n // `rowSegments` supplies that space when the caret is past the last character.\n if (run.caret) {\n return (\n <Text key={key} inverse>\n {text}\n </Text>\n )\n }\n if (run.selected) {\n return (\n <Text key={key} backgroundColor={THEME.selection}>\n {text}\n </Text>\n )\n }\n return <Text key={key}>{text}</Text>\n })}\n </Text>\n )\n })}\n {hiddenBelow > 0 ? (\n <Text dimColor wrap=\"truncate\">\n {pad}… {hiddenBelow} line{hiddenBelow === 1 ? \"\" : \"s\"} below\n </Text>\n ) : null}\n </Box>\n )\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": ";oJAoCA,IAAM,EAAa,EA0CZ,SAAS,EAAc,CAAC,EAAqB,EAAiC,CACjF,IAAM,EAAQ,KAAK,IAAI,EAAG,EAAU,CAAU,EACxC,EAAQ,EAAO,MAAM,MAAM;AAAA,CAAI,EAC/B,EAAS,GAAS,CAAM,EAExB,EAAsB,CAAC,EACzB,EAAW,EAGX,EAAO,EACX,QAAY,EAAI,KAAS,EAAM,QAAQ,EAAG,CACtC,IAAM,EAAU,GAAS,EAAM,CAAK,EAG9B,EAAS,IAAO,EAAO,KAAO,GAAa,EAAM,EAAO,MAAM,EAAI,GAGpE,EAAK,GACT,GAAI,GAAU,EAAG,CACb,EAAK,EAAQ,OAAS,EACtB,QAAY,EAAG,KAAQ,EAAQ,QAAQ,EACnC,GAAI,GAAU,EAAI,GAAI,CAClB,EAAK,EACL,OAIZ,QAAY,EAAG,KAAQ,EAAQ,QAAQ,EAAG,CACtC,GAAI,IAAM,EAAI,EAAW,EAAK,OAC9B,EAAK,KAAK,CACN,MAAO,EAAO,EAAI,KAClB,IAAK,EAAO,EAAI,GAChB,KAAM,EAAI,KACV,KAAM,EAAI,KAGV,MACI,IAAM,EACA,EAAI,KAAO,KAAK,IAAI,EAAG,KAAK,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E,IAAI,IAAM,GAAG,EAAE,KAAK,EAAE,EAAI,EAAI,KAGlE,GAAI,EAAI,MACJ,OACI,EAEE,EAFF,CAAgB,QAAO,GAAvB,SACK,GADM,CAET,EAGV,GAAI,EAAI,SACJ,OACI,EAEE,EAFF,CAAgB,gBAAiB,EAAM,UAAvC,SACK,GADM,CAET,EAGV,OAAO,EAAwB,EAAxB,UAAiB,GAAN,CAAa,EAClC,IAxBM,OAAO,GAyBhB,EAET,EACA,EAAc,EACX,EAEE,EAFF,CAAM,SAAQ,GAAC,KAAK,WAApB,SAEE,CADG,EADL,KACY,EADZ,QAC8B,IAAgB,EAAI,GAAK,IADvD,UAEE,EACF,MACN",
|
|
9
|
+
"debugId": "1C0C369D3F789F5864756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{bi}from"./index-nn3tk25c.js";import{Ri,Xt,Gi,Fi,i,Hi}from"./index-2zye08c4.js";function p(){return{out:process.stdout,in:process.stdin}}var o=[],s=!1,a=!1,r=!1,u=!1,d=!1,c=!1,l=!1;function Qt(){r=!0}function he(){r=!0,u=!0}function _o(){r=!0,d=!0}function qo(){r=!0,c=!0}function h(e){o.push(e)}function zo(){l=!0}function ie(e=p()){if(a||!r)return;if(a=!0,e.in.isTTY===!0&&e.in.setRawMode!==void 0)e.in.setRawMode(!1);if(e.out.isTTY!==!0)return;if(e.out.write(`${Xt}${Ri}`),d)e.out.write(bi);if(c)e.out.write(Fi);if(u)e.out.write(Gi)}async function pe(e=process.stdout){if(e.writableEnded===!0||e.destroyed===!0)return;await new Promise((n)=>{e.write("",()=>n())})}async function m(){for(let e of[...o].reverse())try{await e()}catch(n){process.stderr.write(`warning: cleanup failed: ${n instanceof Error?n.message:String(n)}
|
|
3
|
+
`)}o.length=0}async function w(e){await m(),ie(),process.exitCode=e,await pe()}async function yn(e){await w(e),process.exit(e)}function Vo(){if(s)return;s=!0,process.on("exit",()=>ie()),process.on("SIGTERM",()=>{if(l)return;yn(Hi)});let e=(n)=>(t)=>{ie();let f=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`
|
|
4
|
+
${n}: ${f}
|
|
5
|
+
`),yn(i)};process.on("uncaughtException",e("uncaught exception")),process.on("unhandledRejection",e("unhandled rejection"))}
|
|
6
|
+
export{Qt,he,_o,qo,h,zo,ie,pe,yn,Vo};
|
|
7
|
+
|
|
8
|
+
//# debugId=0F7325DCACA7341764756E2164756E21
|
|
9
|
+
//# sourceMappingURL=index-k2aq5bg0.js.map
|