dispach 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +131 -31
- package/dist/App-b1yrwrcq.js +11 -0
- package/dist/{App-dxqm39zx.js.map → App-b1yrwrcq.js.map} +1 -1
- package/dist/{ConfigEditor-7v5nebvy.js → ConfigEditor-n8hdw6r7.js} +4 -4
- package/dist/{ConfigEditor-7v5nebvy.js.map → ConfigEditor-n8hdw6r7.js.map} +1 -1
- package/dist/{KeyProbe-vjhmdpx6.js → KeyProbe-9jjeze5r.js} +3 -3
- package/dist/{KeyProbe-vjhmdpx6.js.map → KeyProbe-9jjeze5r.js.map} +1 -1
- package/dist/{Picker-jxaesaxy.js → Picker-hfeh1g6m.js} +3 -3
- package/dist/{Picker-jxaesaxy.js.map → Picker-hfeh1g6m.js.map} +1 -1
- package/dist/{SessionPicker-z2t0p4b5.js → SessionPicker-zyqkg4dn.js} +3 -3
- package/dist/{SessionPicker-z2t0p4b5.js.map → SessionPicker-zyqkg4dn.js.map} +1 -1
- package/dist/{SkillBrowser-yyf2gy0q.js → SkillBrowser-3qdp8080.js} +3 -3
- package/dist/{SkillBrowser-yyf2gy0q.js.map → SkillBrowser-3qdp8080.js.map} +1 -1
- package/dist/WizardApp-vzpbydy3.js +5 -0
- package/dist/{WizardApp-12ndxgqv.js.map → WizardApp-vzpbydy3.js.map} +1 -1
- package/dist/client.js +10 -10
- package/dist/client.js.map +5 -5
- package/dist/{config-yz0nz51b.js → config-g7za9x13.js} +13 -13
- package/dist/{config-yz0nz51b.js.map → config-g7za9x13.js.map} +1 -1
- package/dist/credential-npr6z8c8.js +19 -0
- package/dist/{credential-wgt4gvcz.js.map → credential-npr6z8c8.js.map} +2 -2
- package/dist/index-02dn6m2j.js +7 -0
- package/dist/{index-h2yds678.js.map → index-02dn6m2j.js.map} +1 -1
- package/dist/index-0d93hyfc.js +6 -0
- package/dist/{index-rqbtm761.js.map → index-0d93hyfc.js.map} +1 -1
- package/dist/index-1c5113t4.js +66 -0
- package/dist/index-1c5113t4.js.map +12 -0
- package/dist/{index-3nwfz9jq.js → index-258d8bzg.js} +10 -10
- package/dist/{index-3nwfz9jq.js.map → index-258d8bzg.js.map} +1 -1
- package/dist/{index-9d011p3q.js → index-3g3ny01d.js} +4 -4
- package/dist/{index-9d011p3q.js.map → index-3g3ny01d.js.map} +1 -1
- package/dist/{index-8bmhd2hj.js → index-4cf6v9nb.js} +4 -4
- package/dist/{index-8bmhd2hj.js.map → index-4cf6v9nb.js.map} +1 -1
- package/dist/{index-bwckzbf8.js → index-4z7axw4r.js} +4 -4
- package/dist/{index-bwckzbf8.js.map → index-4z7axw4r.js.map} +1 -1
- package/dist/{index-xgqzk5cq.js → index-6p999cx4.js} +6 -6
- package/dist/{index-xgqzk5cq.js.map → index-6p999cx4.js.map} +1 -1
- package/dist/index-6q4wf8e3.js +6 -0
- package/dist/{index-jym27m75.js.map → index-6q4wf8e3.js.map} +1 -1
- package/dist/{index-cx3vz7sf.js → index-9r0wyj6w.js} +4 -4
- package/dist/{index-cx3vz7sf.js.map → index-9r0wyj6w.js.map} +1 -1
- package/dist/{index-j97vttdt.js → index-ammv5st7.js} +6 -6
- package/dist/{index-j97vttdt.js.map → index-ammv5st7.js.map} +1 -1
- package/dist/{index-qc2vrq9z.js → index-cqqb6gaq.js} +5 -5
- package/dist/{index-qc2vrq9z.js.map → index-cqqb6gaq.js.map} +1 -1
- package/dist/{index-jk0def33.js → index-d4x6yvqh.js} +4 -4
- package/dist/{index-jk0def33.js.map → index-d4x6yvqh.js.map} +1 -1
- package/dist/index-fecm8xe7.js +77 -0
- package/dist/index-fecm8xe7.js.map +12 -0
- package/dist/{index-e8n70sgj.js → index-fex44816.js} +4 -4
- package/dist/{index-e8n70sgj.js.map → index-fex44816.js.map} +1 -1
- package/dist/{index-gbnc99j8.js → index-ff514z3y.js} +9 -9
- package/dist/{index-gbnc99j8.js.map → index-ff514z3y.js.map} +1 -1
- package/dist/{index-t1xvacym.js → index-gme2egyq.js} +4 -4
- package/dist/{index-t1xvacym.js.map → index-gme2egyq.js.map} +1 -1
- package/dist/{index-mrtb5y08.js → index-gz9x25tz.js} +4 -4
- package/dist/{index-mrtb5y08.js.map → index-gz9x25tz.js.map} +1 -1
- package/dist/{index-9nsfs0vy.js → index-h9mw7b9d.js} +4 -4
- package/dist/{index-9nsfs0vy.js.map → index-h9mw7b9d.js.map} +1 -1
- package/dist/{index-6b7qvh1x.js → index-hwpvhaza.js} +4 -4
- package/dist/{index-6b7qvh1x.js.map → index-hwpvhaza.js.map} +1 -1
- package/dist/{index-6z0yr17z.js → index-j55s3ehk.js} +7 -7
- package/dist/{index-6z0yr17z.js.map → index-j55s3ehk.js.map} +1 -1
- package/dist/{index-mgdgx22q.js → index-j7gyr5nx.js} +6 -6
- package/dist/{index-mgdgx22q.js.map → index-j7gyr5nx.js.map} +1 -1
- package/dist/{index-7da4fqcr.js → index-mtn0g9vc.js} +5 -5
- package/dist/{index-7da4fqcr.js.map → index-mtn0g9vc.js.map} +1 -1
- package/dist/{index-rqzg861g.js → index-qdbq8crg.js} +4 -4
- package/dist/{index-rqzg861g.js.map → index-qdbq8crg.js.map} +1 -1
- package/dist/{index-xqyms08r.js → index-s9mbq7h6.js} +4 -4
- package/dist/{index-xqyms08r.js.map → index-s9mbq7h6.js.map} +1 -1
- package/dist/{index-9f9pp2ef.js → index-tf71ap9v.js} +4 -4
- package/dist/{index-9f9pp2ef.js.map → index-tf71ap9v.js.map} +1 -1
- package/dist/index-ttwyrdjs.js +427 -0
- package/dist/index-ttwyrdjs.js.map +11 -0
- package/dist/{index-2cvtz0fy.js → index-tv4yv7d2.js} +228 -228
- package/dist/{index-2cvtz0fy.js.map → index-tv4yv7d2.js.map} +9 -9
- package/dist/{index-fvhg0xyd.js → index-ty24n0jh.js} +79 -79
- package/dist/{index-fvhg0xyd.js.map → index-ty24n0jh.js.map} +1 -1
- package/dist/index-v8e92nfw.js +6 -0
- package/dist/{index-b8zwg8a3.js.map → index-v8e92nfw.js.map} +1 -1
- package/dist/index-vgc3y3rm.js +6 -0
- package/dist/{index-my5cjx00.js.map → index-vgc3y3rm.js.map} +1 -1
- package/dist/index-whaw4b18.js +6 -0
- package/dist/index-whaw4b18.js.map +10 -0
- package/dist/index.js +202 -198
- package/dist/index.js.map +6 -6
- package/dist/lib/bootstrap.d.ts +13 -0
- package/dist/lib/bootstrap.d.ts.map +1 -1
- package/dist/lib/commands.d.ts.map +1 -1
- package/dist/lib/init-flow.d.ts +17 -4
- package/dist/lib/init-flow.d.ts.map +1 -1
- package/dist/lib/provision.d.ts.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/{web-w7r68df1.js → web-vkb16r62.js} +5 -5
- package/dist/{web-w7r68df1.js.map → web-vkb16r62.js.map} +1 -1
- package/dist/wire.js +10 -10
- package/dist/wire.js.map +4 -4
- package/package.json +2 -2
- package/dist/App-dxqm39zx.js +0 -11
- package/dist/WizardApp-12ndxgqv.js +0 -5
- package/dist/credential-wgt4gvcz.js +0 -19
- package/dist/index-9pj1ws0p.js +0 -77
- package/dist/index-9pj1ws0p.js.map +0 -12
- package/dist/index-b5wwtxzk.js +0 -66
- package/dist/index-b5wwtxzk.js.map +0 -12
- package/dist/index-b8zwg8a3.js +0 -6
- package/dist/index-bry9bzt3.js +0 -427
- package/dist/index-bry9bzt3.js.map +0 -11
- package/dist/index-h2yds678.js +0 -7
- package/dist/index-jym27m75.js +0 -6
- package/dist/index-my5cjx00.js +0 -6
- package/dist/index-rqbtm761.js +0 -6
- package/dist/index-yr25dnf5.js +0 -6
- package/dist/index-yr25dnf5.js.map +0 -10
package/dist/index.js.map
CHANGED
|
@@ -12,11 +12,11 @@
|
|
|
12
12
|
"/**\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",
|
|
13
13
|
"/**\n * `init [dir]` — one command from installed binary to an agent that answers.\n *\n * Interactive at a terminal, flag-driven everywhere else, and the same flow either way: the\n * questions live in `lib/init-flow.ts` as pure data, this file just asks them. Non-interactive\n * runs (`--yes`, a pipe, CI) take each question's default and refuse — naming the missing flags —\n * when a question has none, because inventing an agent name is not a default, it is a guess.\n *\n * Nothing is written over an existing file, there is no `--force`, and the wizard never asks for\n * the API key itself: typing a secret into a prompt invites shoulder-surfing, and passing one as\n * a flag writes it into shell history. The generated `.env` carries an empty `KEY=` line and the\n * next-steps block says to fill it.\n *\n * Before exiting 0 the generated directory is validated with the *real* loader — the same\n * sequence `validate` runs — so a template bug is this command's failure, never the user's first.\n */\n\nimport { basename, dirname, join, resolve } from \"node:path\"\nimport {\n BRAND,\n HarnessError,\n loadManifest,\n resolveCapabilities,\n resolveWorkspace,\n ruleBudgetFailure,\n VERSION,\n} from \"@dispach/core\"\nimport { installRefs } from \"#browse\"\nimport { daemonCommand } from \"#daemon\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { markTerminalDirty, onExit } from \"#lib/exit\"\nimport {\n COMPOSIO_KEY_ENV,\n composioEnabled,\n type InitAnswers,\n type InitStep,\n planFiles,\n type QuestionDefaults,\n SKILLS_CHOICES,\n TELEGRAM_TOKEN_ENV,\n validateAnswer,\n webBackendByValue,\n} from \"#lib/init-flow\"\nimport { findAndInstallSkill } from \"#lib/init-skills\"\nimport { negotiateKeyboard } from \"#lib/keyboard\"\nimport { resolveModeFromProcess } from \"#lib/output\"\nimport { CHANNEL_IDS, PROVIDER_IDS } from \"#lib/providers\"\nimport { complete, FLAG_FOR, fillDefaults, writeAgentFiles } from \"#lib/provision\"\nimport { agentsDir, outsideSandboxNote } from \"#lib/sandbox\"\nimport type { InitOptions } from \"#lib/schema\"\n\n/** Which flag supplies each step, for the refusal that names what is missing. */\n\nexport type InitResult =\n | { readonly kind: \"ok\"; readonly manifestPath: string }\n | { readonly kind: \"aborted\" }\n | { readonly kind: \"failed\"; readonly code: number }\n\n/** The variable `web_search` will read, or undefined when this agent does not search. */\nfunction searchKeyVar(answers: InitAnswers): string | undefined {\n if (answers.web !== \"search\") return undefined\n return webBackendByValue(answers.webBackend ?? \"tavily\")?.apiKeyEnv\n}\n\nexport async function initCommand(options: InitOptions): Promise<number> {\n const result = await runInit(options)\n if (result.kind === \"aborted\") {\n process.stdout.write(\"nothing written\\n\")\n return EXIT_OK\n }\n return result.kind === \"failed\" ? result.code : EXIT_OK\n}\n\n/**\n * The same flow, returning the created manifest's path — the picker's \"create a new agent\" chains\n * straight into `run` through this, so there is exactly one wizard entry point.\n */\nexport async function initInteractive(options: InitOptions): Promise<InitResult> {\n return runInit(options)\n}\n\nasync function runInit(options: InitOptions): Promise<InitResult> {\n const partial = fromFlags(options)\n\n // Interactive only when `run` would have rendered rich: both streams are terminals and\n // nothing (CI, NO_COLOR, --plain, a dumb TERM) asked for scriptable behaviour. `--yes` opts\n // out even at a terminal.\n const decision = resolveModeFromProcess({\n json: false,\n plain: options.plain === true,\n oneShot: false,\n })\n const interactive = decision.mode === \"rich\" && options.yes !== true\n\n // The dir question defaults into the home sandbox, computed here because the flow module is\n // pure and may not touch the filesystem or environment. An explicit [dir] still overrides.\n const defaults = { agentDirBase: agentsDir() }\n\n if (interactive) {\n // The Ink wizard, lazily — the renderer must never be paid for by a flag-driven run.\n // Its confirm screen replaces the readline summary too: undefined means the person\n // backed out, and nothing is written.\n const collected = await runWizard(partial, defaults)\n if (collected === undefined) return { kind: \"aborted\" }\n Object.assign(partial, collected)\n } else {\n fillDefaults(\n partial,\n options.yes === true ? \"--yes was passed\" : decision.because,\n defaults,\n )\n }\n\n const answers = complete(partial, defaults)\n const targetDir = resolve(process.cwd(), answers.dir)\n\n // Said before anything is written, not after: the cost of an out-of-sandbox agent is paid by\n // every later command, and the only moment it is cheap to reconsider is now. Never a refusal —\n // an agent living in a project checkout is a real thing to want, and the failure this replaces\n // was silence, not permission.\n const note = outsideSandboxNote(targetDir)\n if (note !== undefined) process.stderr.write(`${note}\\n`)\n const manifestPath = join(targetDir, \"agent.yaml\")\n const files = planFiles(answers)\n\n // Per-target checks rather than \"directory not empty\": a fresh `git init`'d directory must\n // work, and the refusal names every collision at once rather than one per run.\n // The one writer, shared with `POST /v1/agents`. Two would be the shape this repo keeps\n // paying for: right when written, divergent at the next change, with the symptom being an\n // agent that works when created one way and not the other.\n writeAgentFiles(targetDir, files)\n\n // The real loader, on the real output. The one concession: when the named key var is not in\n // the environment yet — the normal case, the next-steps block is about to say \"set it\" — it\n // is stubbed so `validateApiKeyEnv` passes while every structural check (schema, budgets,\n // tiers, rule guard, rendering) runs for real. When the var is already exported, no stub:\n // a full honest validate.\n // Hoisted out of the try below, because installing a skill needs the same stub: a manifest written\n // sixty milliseconds ago names a key variable whose line is deliberately empty, so *every* load during\n // init has to tolerate it, not just this one.\n const keyVar = answers.apiKeyEnv\n const needsStub =\n keyVar !== undefined &&\n answers.apiKey === undefined &&\n (process.env[keyVar] === undefined || process.env[keyVar] === \"\")\n const envOverlay = needsStub && keyVar !== undefined ? { [keyVar]: \"(pending)\" } : undefined\n\n let distilled = false\n try {\n const loaded = loadManifest(join(targetDir, \"agent.yaml\"), {\n knownProviders: PROVIDER_IDS,\n knownChannels: CHANNEL_IDS,\n ...(needsStub ? { env: { ...process.env, [keyVar]: \"(pending)\" } } : {}),\n })\n const capabilities = resolveCapabilities(\n loaded.manifest.model.main.id,\n loaded.manifest.model.main.capabilities,\n )\n const { workspace, warnings } = resolveWorkspace(loaded, capabilities.promptStyle)\n const ruleFailure = ruleBudgetFailure(workspace, loaded.manifest.context.rules)\n if (ruleFailure !== undefined && loaded.manifest.context.rules.onExceed === \"fail\") {\n throw ruleFailure\n }\n // The gate's own verdict, read from its own warning rather than re-derived: on 3 of the\n // 4 concrete presets the compact file is what actually ships, and a done screen that did\n // not say so would leave the person editing a SOUL.md their model never reads first.\n distilled = warnings.some((warning) => warning.code === \"soul_distilled\")\n } catch (error) {\n // The files stay on disk — they are inspectable evidence — but the exit is a failure and\n // the loader's own report is printed verbatim. A generated agent that cannot load is this\n // command's bug, and hiding it behind exit 0 would be rule 8's exact shape.\n if (error instanceof HarnessError) {\n process.stderr.write(\n `init wrote ${files.length} files to ${targetDir}, but the result does not load:\\n${error.format()}\\n`,\n )\n return { kind: \"failed\", code: EXIT_FAILURE }\n }\n throw error\n }\n\n // Installed *before* the next steps are printed, so the last screen can say what happened\n // rather than instructing someone to do the thing that just happened. The first version had it\n // the other way round and read as a contradiction.\n //\n // The very first version did not install at all, reasoning that the .env would still be empty\n // and the install check would refuse. True of a scripted `--yes` run and false of the one that\n // matters: at a terminal the wizard *asks* for the bot token and writes it, so by this line the\n // agent is complete. Telling someone who just answered \"yes, keep it running\" to go and type\n // another command is answering a question with homework.\n //\n // Guarded rather than assumed — `daemon install` runs its own checks and refuses if something\n // is missing, and a refusal falls back to naming the command. The one outcome that must not\n // happen is a silent skip after somebody said yes.\n process.stdout.write(`wrote ${files.length} files to ${targetDir} — validated ok\\n`)\n\n // After the load check, so a skill is only ever added to an agent already known to be valid; before\n // the service install, so what gets started is the finished agent rather than one a skill lands in a\n // second later. Cannot fail the init: every failure path inside reports and returns.\n //\n // Nothing is *chosen* here. At a terminal the wizard already showed the catalogue between two of its\n // questions and collected refs into `skillsPick`; this installs them, with one summary rather than one\n // report per skill. A scripted run has no picker, so `--skills \"<phrase>\"` ranks and installs the best\n // match instead — the same interactive/scripted split this command makes everywhere else.\n if (answers.skills === \"find\") {\n const refs = (answers.skillsPick ?? \"\")\n .split(\",\")\n .map((ref) => ref.trim())\n .filter((ref) => ref !== \"\")\n if (refs.length > 0) {\n installRefs(refs, manifestPath, {\n ...(envOverlay === undefined ? {} : { envOverlay }),\n })\n } else if (!interactive) {\n await findAndInstallSkill({\n answers,\n manifestPath,\n ...(envOverlay === undefined ? {} : { envOverlay }),\n })\n }\n }\n\n let installed = false\n if (answers.daemon === \"service\") {\n process.stdout.write(\"\\n\")\n try {\n installed = (await daemonCommand({ action: \"install\", manifestPath })) === EXIT_OK\n } catch (error) {\n process.stderr.write(\n `the background service was not installed: ${\n error instanceof HarnessError ? error.message : String(error)\n }\\n`,\n )\n }\n }\n\n process.stdout.write(nextSteps(answers, targetDir, distilled, installed))\n return { kind: \"ok\", manifestPath: join(targetDir, \"agent.yaml\") }\n}\n\n/**\n * `--skills` as a choice, or as a search phrase.\n *\n * `--skills starter` and `--skills none` are the choices; `--skills \"pdf tables\"` means \"find one\", with\n * those words. Told apart by membership in `SKILLS_CHOICES` rather than by shape, so the set of choices\n * stays the only thing that decides — and a phrase is never mistaken for a mistyped choice, because a\n * mistyped choice becomes a search that reports finding nothing rather than silently doing something else.\n */\nfunction skillsPair(raw: string | undefined): [InitStep, string | undefined][] {\n if (raw === undefined) return []\n if (SKILLS_CHOICES.some((choice) => choice.value === raw)) return [[\"skills\", raw]]\n return [\n [\"skills\", \"find\"],\n [\"skillsSearch\", raw],\n ]\n}\n\n/** Flag values pass the same per-step validation the wizard applies — a bad flag fails by name. */\nfunction fromFlags(options: InitOptions): Partial<Record<InitStep, string>> {\n const given: Partial<Record<InitStep, string>> = {}\n const pairs: readonly [InitStep, string | undefined][] = [\n [\"user\", options.user],\n [\"name\", options.name],\n [\"purpose\", options.purpose],\n [\"preset\", options.preset],\n [\"model\", options.model],\n [\"baseUrl\", options.baseUrl],\n [\"apiKeyEnv\", options.apiKeyEnv],\n [\"system\", options.system],\n [\"web\", options.web],\n [\"webBackend\", options.webBackend],\n [\"composio\", options.composio],\n [\"telegram\", options.telegram],\n [\"telegramAllow\", options.telegramAllow],\n [\"server\", options.server],\n [\"schedules\", options.schedules],\n // `--skills` takes a choice name *or* the words to search for, and the sugar is here rather than\n // in `validateAnswer` so the per-step validation stays strict — a flag that quietly accepted\n // anything is a flag that mistypes `startr` into a search query for \"startr\".\n ...skillsPair(options.skills),\n [\"daemon\", options.daemon],\n [\"dir\", options.dir],\n ]\n for (const [step, raw] of pairs) {\n if (raw === undefined) continue\n const checked = validateAnswer(step, raw)\n if (!checked.ok) {\n throw new HarnessError({\n code: \"cli_init_flag_invalid\",\n message: `${FLAG_FOR[step]} is ${JSON.stringify(raw)}, which ${checked.reason}`,\n hint: \"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them.\",\n })\n }\n given[step] = checked.value\n }\n return given\n}\n\n/**\n * The Ink wizard, mounted lazily — the renderer must never be paid for by a flag-driven run.\n *\n * Same shape as run.ts's rich path: literal `import(\"ink\")`, `markTerminalDirty()` before the\n * render, `exitOnCtrlC: false` (the wizard owns ^C as abort), `onExit` unmount. The component\n * calls `onDone` with the collected answers (or undefined on abort) and exits itself; the value\n * is read after `waitUntilExit`.\n */\nasync function runWizard(\n partial: Partial<Record<InitStep, string>>,\n defaults: QuestionDefaults,\n): Promise<Partial<Record<InitStep, string>> | undefined> {\n const [{ render }, { createElement }, { WizardApp }] = await Promise.all([\n import(\"ink\"),\n import(\"react\"),\n import(\"#components/WizardApp\"),\n ])\n\n let collected: Partial<Record<InitStep, string>> | undefined\n markTerminalDirty()\n const instance = render(\n createElement(WizardApp, {\n title: `${BRAND.name} ${VERSION}`,\n given: partial,\n defaults,\n onDone: (answers) => {\n collected = answers\n },\n }),\n { exitOnCtrlC: false, ...negotiateKeyboard() },\n )\n onExit(() => instance.unmount())\n await instance.waitUntilExit()\n instance.unmount()\n return collected\n}\n\nfunction nextSteps(\n answers: InitAnswers,\n targetDir: string,\n distilled: boolean,\n installed = false,\n): string {\n // An agent inside the sandbox runs by bare name from anywhere; anything else by path.\n const inSandbox = dirname(targetDir) === agentsDir()\n const runRef = inSandbox ? basename(targetDir) : join(targetDir, \"agent.yaml\")\n const manifest = join(targetDir, \"agent.yaml\")\n\n const steps: string[] = []\n // Only when there is genuinely nothing to run with. Telling someone to add a key they just\n // typed in is the kind of instruction people learn to skip past.\n if (answers.apiKeyEnv !== undefined && answers.apiKey === undefined) {\n steps.push(`Add your key: edit ${join(targetDir, \".env\")} and set ${answers.apiKeyEnv}=`)\n }\n // Same rule as the model key: only when there is genuinely nothing to search with. A search\n // agent whose key is blank starts fine and fails at the first web_search naming the variable —\n // which is the right failure and a poor first impression if nobody said so here.\n const searchVar = searchKeyVar(answers)\n if (searchVar !== undefined && answers.webKey === undefined) {\n steps.push(\n `Add your search key: edit ${join(targetDir, \".env\")} and set ${searchVar}= — web_fetch works without it, web_search does not`,\n )\n }\n // The key, and only the key. Discovering and connecting an app is now something to *ask the\n // agent for* rather than a setup chore — which is the whole change, so a next step telling\n // someone to go and warm a cache would be describing the flow this replaced.\n if (composioEnabled(answers) && answers.composioKey === undefined) {\n steps.push(\n `Add your Composio key: edit ${join(targetDir, \".env\")} and set ${COMPOSIO_KEY_ENV}=`,\n )\n }\n // The bot token, and only when it is genuinely missing. A channel whose token is blank fails\n // the *load* — the factory reads it at boot — so this is not a first-turn surprise, it is a\n // `serve` that will not start at all.\n if (answers.telegram === \"connected\" && answers.telegramToken === undefined) {\n steps.push(\n `Add your bot token: message @BotFather with /newbot, then edit ` +\n `${join(targetDir, \".env\")} and set ${TELEGRAM_TOKEN_ENV}=`,\n )\n }\n // `run` never starts a channel and never binds a port, so an agent configured for either has a\n // second thing to know. Said here rather than discovered — the whole reason these capabilities\n // became questions is that a generated file was hiding them. One step rather than two once the\n // service is up: \"run it\" and \"and by the way run starts nothing\" are the same sentence, and\n // printing both made steps 1 and 2 read as duplicates of each other.\n const reachable = answers.telegram === \"connected\" || answers.server === \"local\"\n const what =\n answers.telegram === \"connected\" && answers.server === \"local\"\n ? \"the Telegram bot and the HTTP API\"\n : answers.telegram === \"connected\"\n ? \"the Telegram bot\"\n : \"the HTTP API\"\n if (reachable && installed) {\n steps.push(\n `${BRAND.slug} run ${runRef} — talks to it right here. It starts no channel and binds ` +\n `no port; ${what} belongs to the service, which is already up.`,\n )\n } else {\n steps.push(`${BRAND.slug} run ${runRef}`)\n }\n if (reachable) {\n if (!installed) {\n steps.push(`${BRAND.slug} serve ${runRef} — starts ${what}; \\`run\\` starts neither`)\n }\n // And the half `serve` does not cover: it lives and dies with its terminal. Printed only\n // when they asked for it, and only as a command — `init` deliberately does not install,\n // because the token in step 1 is usually still missing at this moment and the check that\n // exists to catch that would refuse. A service that fails from birth is the exact failure\n // this capability was built against.\n if (answers.daemon === \"service\" && !installed) {\n // Only when the install did not happen. Printed unconditionally it read as a\n // contradiction — a next step telling you to run the command whose output was two\n // lines above.\n steps.push(\n `${BRAND.slug} daemon install ${runRef} — the same thing, supervised: starts at ` +\n `login and survives a reboot. Do this once the key and token above are in .env; ` +\n `the install checks them and refuses without them, on purpose.`,\n )\n }\n }\n if (answers.telegram === \"connected\" && answers.telegramAllow === undefined) {\n steps.push(\n `Message the bot. Nobody is on its allowFrom yet, so it will refuse you — and print ` +\n `the exact line to paste into agent.yaml.`,\n )\n }\n if (composioEnabled(answers)) {\n steps.push(\n `Ask it for an app — \"connect my Gmail\" — and it finds the tools, gives you the ` +\n `sign-in link, and pins what you need. New tools go live on the next restart.`,\n )\n }\n // Named here whatever was answered, because this is the one screen everybody reads and the sources\n // registry was otherwise reachable only by someone who already knew the word `sources`. The line\n // changes with the answer: somebody who now has a real skill wants \"add another\", somebody holding a\n // template wants \"or take a real one\", and somebody who declined wants to know the option exists.\n steps.push(\n answers.skills === \"find\"\n ? `Add more skills: \\`${BRAND.slug} sources search <what it should do>\\` ranks every skill in the catalogues, then \\`${BRAND.slug} skills install ${runRef} <source>/<skill>\\`.`\n : answers.skills === \"starter\"\n ? `Fill in workspace-level skills/starter/SKILL.md, or take a real one — \\`${BRAND.slug} sources search <what it should do>\\` searches 440+ from two catalogues.`\n : `Skills are off but the directory is there — \\`${BRAND.slug} sources search <what it should do>\\` finds one, \\`${BRAND.slug} skills new ${runRef} <name>\\` writes one.`,\n )\n steps.push(\n `Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — ` +\n `\\`${BRAND.slug} workspace ${manifest}\\` shows exactly what still reads as a template.`,\n )\n\n // Said before the numbered list, because it changes what the list means: with a service\n // installed, `serve` is not something you need to run and the agent is already answering.\n const serviceNote = installed\n ? `\\nit is running in the background now — \\`${BRAND.slug} daemon status ${runRef}\\` at any time,\\nand \\`${BRAND.slug} stop\\` turns everything off.\\n`\n : \"\"\n\n const soulNote = distilled\n ? `\\nthis model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a\\nfrontier-class model, and activates automatically if you upgrade.\\n`\n : \"\"\n\n return (\n `${soulNote}${serviceNote}\\n` +\n steps.map((step, index) => ` ${index + 1}. ${step}\\n`).join(\"\")\n )\n}\n",
|
|
14
14
|
"/**\n * `init --skills find`: search the catalogues and install the best match, during setup.\n *\n * ## Why this exists\n *\n * The question used to be \"starter template or empty directory\", and a fresh agent asked what skills it\n * had answered — after four tool calls — that it had one, the blank template, and so \"effectively zero\n * working skills\". Both answers were technically the offer and neither was a skill. Meanwhile `sources\n * search` existed and nothing anywhere mentioned it: a capability reachable only by someone who already\n * knows the command name, which is decision 4.53's exact shape and the reason every capability the\n * runtime has is a question in `init`.\n *\n * ## Words, not a slug\n *\n * A slug is something you only have if you already know the catalogue, which is the state this question\n * exists to fix. So the wizard asks what the agent will do often and this ranks 440-odd real skills\n * against it with **`bm25Selector` — the same function that decides activation at runtime**. What init\n * installs is therefore what will actually fire, and a phrase that installs nothing is a phrase that\n * would have activated nothing.\n *\n * ## Three things it must not do\n *\n * Fail the init. A network that is down, no `git`, or a phrase that matches nothing all leave a valid\n * agent with an empty skills directory and a sentence saying so — never a broken agent and never a\n * silent substitution of some other answer, which would be answering a question the person did not ask.\n *\n * Reach a network on a scripted run. The `skills` fallback is `starter`, so `--yes` and every\n * non-interactive path arrive here with nothing to do. Only an explicit answer gets here.\n *\n * Leave the agent unbootable. A skill declaring Python fails at *load* on a machine without it, so the\n * catalogue is loaded once after installing and anything that breaks it is removed again. Installing a\n * skill that stops the agent starting would be strictly worse than installing none.\n */\n\nimport { rmSync } from \"node:fs\"\nimport { isAbsolute, join, resolve } from \"node:path\"\nimport {\n bm25Selector,\n HarnessError,\n loadManifest,\n loadSkills,\n resolveCapabilities,\n type Skill,\n} from \"@dispach/core\"\nimport { EXIT_OK } from \"#lib/const\"\nimport type { InitAnswers } from \"#lib/init-flow\"\nimport { forgetOrigin } from \"#lib/origins\"\nimport { CHANNEL_IDS, PROVIDER_IDS, scriptRunner } from \"#lib/providers\"\nimport { bullet, indent } from \"#lib/render\"\nimport {\n type CatalogueEntry,\n fetchSource,\n type Git,\n isCached,\n readCatalogue,\n} from \"#lib/source-cache\"\nimport { loadSources } from \"#lib/sources\"\nimport { skillsCommand } from \"#skills\"\n\nexport interface FindSkillOptions {\n readonly answers: InitAnswers\n readonly manifestPath: string\n /** Layered onto the manifest environment — `init` stubs the key it has written as an empty line. */\n readonly envOverlay?: Readonly<Record<string, string | undefined>>\n /** Injected by the tests, which never reach a network. */\n readonly git?: Git\n readonly env?: Readonly<Record<string, string | undefined>>\n}\n\n/** How many alternatives are named when the top match is installed, so the choice is inspectable. */\nconst ALTERNATIVES = 3\n\nexport async function findAndInstallSkill(options: FindSkillOptions): Promise<void> {\n if (options.answers.skills !== \"find\") return\n const words = options.answers.skillsSearch?.trim() ?? \"\"\n if (words === \"\") {\n // Reachable by pressing enter through the wizard with no purpose set, since the phrase defaults\n // to the purpose. Said out loud: an answer of \"yes, find one\" followed by silence and an empty\n // directory is the shape hard rule 8 exists for.\n process.stdout.write(\n \"\\nno words to search for, so no skill was installed — `sources search <words>` when you know what you want\\n\",\n )\n return\n }\n\n const sources = loadSources(options.env)\n if (sources.length === 0) {\n process.stdout.write(\n \"\\nno skill sources are configured, so there was nothing to search\\n\\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\\n\",\n )\n return\n }\n\n process.stdout.write(\n `\\nsearching ${sources.length} skill source(s) for ${JSON.stringify(words)}\\n`,\n )\n const entries: CatalogueEntry[] = []\n const unreachable: string[] = []\n for (const spec of sources) {\n if (!isCached(spec.name, options.env)) {\n try {\n await fetchSource(spec, {\n ...(options.env === undefined ? {} : { env: options.env }),\n ...(options.git === undefined ? {} : { git: options.git }),\n })\n } catch (error) {\n unreachable.push(\n `${spec.name} — ${error instanceof HarnessError ? error.message : String(error)}`,\n )\n continue\n }\n }\n entries.push(...readCatalogue(spec, options.env))\n }\n for (const line of unreachable) process.stdout.write(indent(`could not fetch ${line}\\n`))\n\n if (entries.length === 0) {\n process.stdout.write(\n `${indent(\"no source could be read, so no skill was installed — the directory is there and empty\")}\\n${indent(\"`sources update` reports why; `sources search <words>` when it works\", 4)}\\n`,\n )\n return\n }\n\n const ranked = rank(words, entries)\n if (ranked.length === 0) {\n process.stdout.write(\n `${indent(`nothing in ${entries.length} skills matches those words, so none was installed`)}\\n${indent(\"the ranking is lexical: try the words a skill's own description would use, with `sources search`\", 4)}\\n`,\n )\n return\n }\n\n const best = ranked[0] as CatalogueEntry\n const ref = `${best.source}/${best.skill}`\n process.stdout.write(`${indent(`best of ${entries.length}: ${ref}`)}\\n`)\n if (ranked.length > 1) {\n // The runners-up, so the pick is inspectable rather than magic — and so a wrong first choice is\n // one `skills install` away from being fixed instead of a mystery.\n process.stdout.write(\n `${indent(\n `also matched: ${ranked\n .slice(1, 1 + ALTERNATIVES)\n .map((entry) => `${entry.source}/${entry.skill}`)\n .join(\", \")}`,\n 4,\n )}\\n`,\n )\n }\n process.stdout.write(\"\\n\")\n\n // The install itself is `skills install`, called rather than reimplemented: it owns the budget\n // check, the destination-name-from-frontmatter rule, the provenance record and the disclosure of\n // installed code. A second copy here would be the one that drifts.\n const code = skillsCommand({\n action: \"install\",\n manifestPath: options.manifestPath,\n name: ref,\n // The same registry this function just searched. Without it `install` resolves the ref against\n // the real home directory while the search read a sandbox — two different catalogues inside one\n // command, which is exactly how it failed the first time.\n ...(options.env === undefined ? {} : { sandboxEnv: options.env }),\n ...(options.envOverlay === undefined ? {} : { envOverlay: options.envOverlay }),\n })\n if (code !== EXIT_OK) return\n\n const broke = brokenBy(options.manifestPath, options.envOverlay)\n if (broke !== undefined) {\n // Removed rather than left with a warning. A skill that fails the load means the agent does not\n // start at all, and finishing init by handing someone an agent that cannot boot — with the fix\n // being \"delete the thing init just installed\" — is worse than installing nothing.\n rollback(options.manifestPath, best.skill, options.envOverlay)\n process.stdout.write(\n `\\n${bullet(`${ref} was removed again: it does not load on this machine`)}\\n${indent(broke, 4)}\\n${indent(\"everything else is fine; `sources search` for one that needs no extra runtime\", 4)}\\n`,\n )\n }\n}\n\nfunction rank(words: string, entries: readonly CatalogueEntry[]): readonly CatalogueEntry[] {\n const byKey = new Map<string, CatalogueEntry>()\n const skills: Skill[] = entries\n .filter((entry) => entry.problem === undefined)\n .map((entry) => {\n const key = `${entry.source}/${entry.skill}`\n byKey.set(key, entry)\n return {\n name: key,\n dir: entry.dir,\n tokens: entry.tokens,\n scripts: [],\n ignoredScripts: [],\n frontmatter: { name: key, description: entry.description, metadata: {} },\n }\n })\n return bm25Selector(words, skills)\n .filter((scored) => scored.score > 0)\n .map((scored) => byKey.get(scored.skill.name))\n .filter((entry): entry is CatalogueEntry => entry !== undefined)\n}\n\n/**\n * The message a freshly-installed skill would fail the agent's boot with, or `undefined`.\n *\n * `loadSkills` rather than `validate`: the two ask different questions, and a missing interpreter is\n * invisible to the manifest loader — it is the *catalogue* scan that probes for `python3` and refuses.\n */\nfunction brokenBy(\n manifestPath: string,\n envOverlay?: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n try {\n const loaded = loadManifest(manifestPath, {\n knownProviders: PROVIDER_IDS,\n knownChannels: CHANNEL_IDS,\n // Or an unfilled key is reported as the freshly-installed skill's fault, and the skill is\n // rolled back for something that has nothing to do with it.\n ...(envOverlay === undefined ? {} : { env: { ...process.env, ...envOverlay } }),\n })\n const configured = loaded.manifest.skills\n if (configured === undefined) return undefined\n const capabilities = resolveCapabilities(\n loaded.manifest.model.main.id,\n loaded.manifest.model.main.capabilities,\n )\n loadSkills({\n dir: isAbsolute(configured.dir) ? configured.dir : resolve(loaded.dir, configured.dir),\n maxActive: configured.maxActive,\n threshold: configured.threshold,\n style: capabilities.promptStyle,\n agentDir: loaded.dir,\n runner: scriptRunner(),\n })\n return undefined\n } catch (error) {\n return error instanceof HarnessError ? error.message : String(error)\n }\n}\n\nfunction rollback(\n manifestPath: string,\n name: string,\n envOverlay?: Readonly<Record<string, string | undefined>>,\n): void {\n try {\n const loaded = loadManifest(manifestPath, {\n knownProviders: PROVIDER_IDS,\n knownChannels: CHANNEL_IDS,\n ...(envOverlay === undefined ? {} : { env: { ...process.env, ...envOverlay } }),\n })\n const configured = loaded.manifest.skills\n if (configured === undefined) return\n const dir = isAbsolute(configured.dir)\n ? configured.dir\n : resolve(loaded.dir, configured.dir)\n rmSync(join(dir, name), { recursive: true, force: true })\n forgetOrigin(dir, name)\n } catch {\n // The caller is already reporting a failure and naming the skill; a second failure here would\n // replace that report with a stack trace about cleanup.\n }\n}\n",
|
|
15
|
-
"/**\n * Writing an agent to disk — the one path, shared by `init` and by `POST /v1/agents`.\n *\n * ## Why this module exists at all\n *\n * Provisioning has two front doors now: a wizard at a terminal and an HTTP route a browser or a\n * platform calls. They must produce **byte-identical** agents, and the only way to promise that is\n * for there to be one writer. Two would be the shape this repo keeps paying for — right when\n * written, divergent at the next change, with the symptom being an agent that works when created\n * one way and not the other.\n *\n * `complete` and `fillDefaults` moved here from `init.ts` for that reason: they *are* the funnel\n * both paths pass through, and `complete`'s own comments are a monument to what happens when a\n * default lives anywhere else (`apiKeyEnv` was dropped from generated manifests entirely when its\n * question was removed, and `--schedules daily` was accepted and lost in two separate literals).\n *\n * ## What the HTTP path is allowed to decide, and what it is not\n *\n * **Not the directory.** `dir` and `dirChoice` are refused over the wire and the agent always lands\n * in the sandbox. Where an agent lives on disk is the operator's decision, not a caller's — and a\n * route that honoured a path would write wherever it was pointed, which is a very short step from\n * a request that overwrites something. The route is loopback-gated in this phase, and that gate is\n * not a reason to also hand over the filesystem.\n *\n * **Not which variables hold secrets.** A secret answer is written into the `.env` at `0600` once\n * and no route ever reads it back. `SECRET_STEPS` is what a client masks; nothing here echoes one.\n */\n\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\"\nimport { dirname, join, resolve } from \"node:path\"\nimport { HarnessError } from \"@dispach/core\"\nimport {\n dirFor,\n type GeneratedFile,\n type InitAnswers,\n type InitStep,\n nextQuestion,\n type PartialAnswers,\n planFiles,\n presetById,\n type Question,\n type QuestionDefaults,\n SECRET_STEPS,\n STEP_ORDER,\n validateAnswer,\n} from \"#lib/init-flow\"\n\nexport const FLAG_FOR: Record<InitStep, string> = {\n user: \"--user\",\n name: \"--name\",\n purpose: \"--purpose\",\n preset: \"--preset\",\n model: \"--model\",\n baseUrl: \"--base-url\",\n apiKeyEnv: \"--api-key-env\",\n // No flag, on purpose: a key on the command line lands in shell history. With --yes the .env\n // is written with an empty value and the next steps say where to put it.\n apiKey: \"(asked at the prompt only)\",\n system: \"--system\",\n web: \"--web\",\n webBackend: \"--web-backend\",\n // No flag, same reason as the model key.\n webKey: \"(asked at the prompt only)\",\n composio: \"--composio\",\n composioKey: \"(asked at the prompt only)\",\n telegram: \"--telegram\",\n telegramAllow: \"--telegram-allow\",\n // No flag, same reason as every other secret: a token on a command line lands in history.\n telegramToken: \"(asked at the prompt only)\",\n schedules: \"--schedules\",\n server: \"--server\",\n skills: \"--skills\",\n skillsSearch: \"--skills\",\n skillsPick: \"--skills\",\n daemon: \"--daemon\",\n // Never asked and never a flag — generated, because it is ours rather than a third party's.\n serverToken: \"(generated)\",\n dirChoice: \"--dir\",\n dir: \"--dir\",\n}\n\n/**\n * Non-interactive: every unanswered question takes its default, and a question with no default is\n * a refusal, not a guess. All gaps report at once — with `--preset custom` that is the endpoint\n * flags too, not just the names — and the refusal says *why* the questions could not be asked,\n * which is the mode decision's `because` string doing its first useful work.\n */\nexport function fillDefaults(\n partial: Partial<Record<InitStep, string>>,\n because: string,\n defaults: QuestionDefaults,\n): void {\n const missing: InitStep[] = []\n for (;;) {\n const question = nextQuestion(partial, defaults)\n if (question === undefined) break\n if (question.optional === true) {\n // An empty answer is the answer. Refusing here would make `--yes` demand a secret it\n // deliberately offers no flag for.\n partial[question.step] = \"\"\n continue\n }\n if (question.fallback === \"\") {\n missing.push(question.step)\n // Placeholder purely to advance the walk; discarded by the throw below.\n partial[question.step] = \"(missing)\"\n continue\n }\n const checked = validateAnswer(question.step, question.fallback)\n if (checked.ok) partial[question.step] = checked.value\n }\n if (missing.length > 0) {\n const flags = missing.map((step) => FLAG_FOR[step]).join(\", \")\n throw new HarnessError({\n code: \"cli_init_missing_answers\",\n message: `Not interactive (${because}), and ${missing.join(\", \")} ${missing.length === 1 ? \"has\" : \"have\"} no default.`,\n hint: `Pass ${flags} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`,\n })\n }\n}\n\nexport function complete(\n partial: Partial<Record<InitStep, string>>,\n defaults: QuestionDefaults,\n): InitAnswers {\n // `apiKeyEnv` and `apiKey` legitimately stay undefined — the first for a keyless endpoint, the\n // second for anyone exporting the variable another way. Everything else is present once\n // nextQuestion returns undefined.\n const answers = partial as Record<\n Exclude<\n InitStep,\n | \"apiKeyEnv\"\n | \"apiKey\"\n | \"webBackend\"\n | \"webKey\"\n | \"composioKey\"\n | \"skillsSearch\"\n | \"skillsPick\"\n | \"schedules\"\n | \"dir\"\n | \"dirChoice\"\n >,\n string\n > & {\n /**\n * Undefined unless `--schedules` was passed: this capability has no wizard step at all.\n * Defaulted below, at the funnel, for the reason `apiKeyEnv` is.\n */\n schedules?: string\n /** Undefined unless the skills answer was `find`; its question is skipped otherwise. */\n skillsSearch?: string\n /** Undefined unless the wizard's catalogue step ran and something was ticked. */\n skillsPick?: string\n apiKeyEnv?: string\n apiKey?: string\n // Both stay undefined unless the web answer was `search` — the flow skips their questions,\n // so `nextQuestion` returning undefined does not mean they were answered.\n webBackend?: string\n webKey?: string\n /** Undefined unless the Composio answer was `connected`, for the same reason. */\n composioKey?: string\n /** Both stay undefined unless the Telegram answer was `connected`. */\n telegramToken?: string\n telegramAllow?: string\n /** Undefined unless `dirChoice` was `custom`; derived below otherwise. */\n dir?: string\n /** Undefined when `--dir` answered the question, which is what skips it. */\n dirChoice?: string\n }\n // Which variable holds the key is no longer asked — it comes from `--api-key-env`, or from the\n // preset. Defaulted HERE, at the one funnel both the wizard and the scripted path pass through:\n // when this lived in the question list, removing the question silently dropped `apiKeyEnv` from\n // the manifest altogether and generated an agent with no key configuration at all.\n const preset = presetById(answers.preset)\n const keyVar = answers.apiKeyEnv ?? preset?.apiKeyEnv\n\n // `dir` stops being asked the moment the answer is `sandbox` or `here`, so its value has to be\n // derived at this funnel — the same rule `apiKeyEnv` above is a monument to. `dirFor` is the one\n // derivation, shared with the confirm screen, so the summary cannot describe a directory other\n // than the one written. An explicit answer still wins: `--dir` sets both fields.\n const dir = answers.dir ?? dirFor(answers.dirChoice, answers.name, defaults)\n if (dir === undefined) {\n throw new HarnessError({\n code: \"cli_init_no_directory\",\n message: `The directory answer was ${JSON.stringify(answers.dirChoice)}, which resolves to no path.`,\n hint: \"This is a bug in the CLI: every dirChoice except `custom` must derive a path in `dirFor`, and `custom` must have asked the dir question. Pass --dir <path> to get past it.\",\n })\n }\n\n return {\n user: answers.user,\n name: answers.name,\n purpose: answers.purpose,\n preset: answers.preset as InitAnswers[\"preset\"],\n model: answers.model,\n baseUrl: answers.baseUrl,\n system: answers.system,\n web: answers.web,\n ...(answers.webBackend === undefined ? {} : { webBackend: answers.webBackend }),\n ...(answers.webKey === undefined || answers.webKey === \"\"\n ? {}\n : { webKey: answers.webKey }),\n composio: answers.composio,\n ...(answers.composioKey === undefined || answers.composioKey === \"\"\n ? {}\n : { composioKey: answers.composioKey }),\n telegram: answers.telegram,\n ...(answers.telegramToken === undefined || answers.telegramToken === \"\"\n ? {}\n : { telegramToken: answers.telegramToken }),\n ...(answers.telegramAllow === undefined || answers.telegramAllow === \"\"\n ? {}\n : { telegramAllow: answers.telegramAllow }),\n // `none` writes the commented block with its worked example — see SCHEDULE_CHOICES. Defaulted\n // here rather than as a step fallback because there is no step: this funnel is the one place\n // both the wizard and `--schedules daily` pass through, which is the lesson `apiKeyEnv` above\n // records from the last time a question was removed and its field silently went missing.\n schedules: answers.schedules ?? \"none\",\n server: answers.server,\n skills: answers.skills,\n // Carried explicitly. This funnel is a literal, not a spread, so a step that is collected and not\n // listed here is silently dropped — which is what happened: `--skills \"pdf tables\"` set the answer\n // to `find` and lost the words, and init reported \"no words to search for\" about a phrase the\n // person had just typed. The same shape as `apiKeyEnv` above, and the reason that comment exists.\n ...(answers.skillsSearch === undefined || answers.skillsSearch === \"\"\n ? {}\n : { skillsSearch: answers.skillsSearch }),\n ...(answers.skillsPick === undefined || answers.skillsPick === \"\"\n ? {}\n : { skillsPick: answers.skillsPick }),\n daemon: answers.daemon,\n // Minted here rather than in the flow, which is a PURE module and must stay deterministic.\n // Only for an agent that asked for a server: an unused 64-hex string in every generated\n // .env is a secret nobody chose and one more thing to wonder about.\n ...(answers.server === \"local\" ? { serverToken: randomToken() } : {}),\n ...(keyVar === undefined ? {} : { apiKeyEnv: keyVar }),\n ...(answers.apiKey === undefined || answers.apiKey === \"\"\n ? {}\n : { apiKey: answers.apiKey }),\n ...(answers.dirChoice === undefined ? {} : { dirChoice: answers.dirChoice }),\n dir,\n }\n}\n\n/**\n * The server token a generated manifest names, when the server answer asked for one.\n *\n * Moved here verbatim with `complete`, its only caller. 256 bits of `crypto.getRandomValues`, hex.\n */\nfunction randomToken(): string {\n const bytes = new Uint8Array(32)\n crypto.getRandomValues(bytes)\n return [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\n// ─── the shared writer ──────────────────────────────────────────────────────────────────\n\n/**\n * Write a planned agent, refusing rather than overwriting.\n *\n * Per-target checks rather than \"directory not empty\": a fresh `git init`'d directory must work,\n * and the refusal names every collision at once rather than one per run.\n *\n * `.env` alone gets `0600`. It holds every credential this agent has — the model key, a bot token,\n * a Composio key — and the default `0644` made all of them readable by anything running on the\n * machine. That matters more under a service manager, which hands a job almost no environment and\n * whose unit carries no secrets by design, so this file is the *only* path credentials arrive by.\n */\nexport function writeAgentFiles(targetDir: string, files: readonly GeneratedFile[]): void {\n const collisions = files\n .map((file) => join(targetDir, file.relPath))\n .filter((path) => existsSync(path))\n if (collisions.length > 0) {\n throw new HarnessError({\n code: \"cli_init_target_exists\",\n message: `${collisions.length} of the files init would write already exist: ${collisions.join(\", \")}`,\n hint: \"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable.\",\n })\n }\n\n for (const file of files) {\n const path = join(targetDir, file.relPath)\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, file.contents, {\n encoding: \"utf8\",\n ...(file.relPath === \".env\" ? { mode: 0o600 } : {}),\n })\n }\n}\n\n// ─── the HTTP-facing half ───────────────────────────────────────────────────────────────\n\n/**\n * What opens a step that is not always asked.\n *\n * `telegramToken` is a question only for somebody who said `telegram: connected`, and\n * `nextQuestion` expresses that as a `continue` a client cannot see. This is the same fact,\n * declared — so a browser can render the whole question set and reveal a field when the choice\n * that opens it is made, without re-implementing the walk. A hard-coded condition in the page\n * would be the two-hand-kept-lists shape that `GET /v1/provision` exists to prevent.\n *\n * **Evaluate it transitively.** A step is askable when its requirement is met *and* the step named\n * in that requirement is itself askable. `webKey` requires `web: search`; `web` requires nothing,\n * so the recursion terminates at the default path. Only the nearest opening choice is recorded,\n * because attributing a step to every ancestor would be a second encoding of `STEP_ORDER`'s shape.\n */\nexport interface StepRequirement {\n readonly step: InitStep\n /** The canonical answer — the choice's `value`, never a menu index. See `canonical`. */\n readonly value: string\n}\n\n/** One question, as a client that is not a terminal needs to see it. */\nexport interface ProvisionStep {\n readonly step: InitStep\n readonly prompt: string\n /**\n * The offered default, as a value a client can use. Empty means the answer is required unless\n * `optional`.\n *\n * **Canonical, never the wizard's own `fallback`.** A `Question` for a menu carries `\"1\"` —\n * a 1-based index, which `validateAnswer` accepts from a terminal and which matches no\n * `choices[].value` at all. Served raw it gave a `<select>` no selectable default; worse, the\n * walk fed it back to itself, `presetById(\"1\")` answered `undefined`, and `model` and `baseUrl`\n * were therefore served with **empty** defaults where the terminal offers a real model id.\n */\n readonly fallback: string\n /** An empty answer is a real answer. See `Question.optional`. */\n readonly optional: boolean\n /** Mask it, never echo it, never log it. Derived from `SECRET_STEPS`, not restated. */\n readonly secret: boolean\n /** Absent means always asked. See `StepRequirement`. */\n readonly requires?: StepRequirement\n readonly choices?: readonly {\n readonly value: string\n readonly label: string\n /** The dim half of a row — a reason, not a second label. See `Question.options`. */\n readonly hint?: string\n }[]\n}\n\n/**\n * Steps no API caller may answer, with the reason each is refused.\n *\n * One map, read by two things that must agree: `provisionSteps` leaves these out of the served\n * list, and `provisionAgent` throws when one arrives anyway. Held together because a question\n * offered by one and refused by the other puts a field in front of somebody that cannot be\n * submitted — and the reverse, a step quietly *accepted* and acted on by nobody, is worse.\n *\n * `daemon` is the one found by building the browser form. It was in `FLAG_FOR`, so it validated\n * and landed in `answers`, and **only `init.ts` ever reads it** — so\n * `POST /v1/agents {\"answers\":{\"daemon\":\"service\"}}` answered `201` and installed no service. It is\n * also the question a running host has already answered: the response's `adopted` field *is* \"yes,\n * it is running in the background\". It stayed invisible because the walk skips it unless a channel\n * or the server is on, which the default path never is.\n */\nconst REFUSED_STEPS: ReadonlyMap<InitStep, { readonly code: string; readonly hint: string }> =\n new Map([\n [\n \"dir\",\n {\n code: \"provision_directory_refused\",\n hint: \"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else.\",\n },\n ],\n [\n \"dirChoice\",\n {\n code: \"provision_directory_refused\",\n hint: \"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else.\",\n },\n ],\n [\n \"daemon\",\n {\n code: \"provision_daemon_refused\",\n hint: \"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process.\",\n },\n ],\n ])\n\n/**\n * Choices a step offers at a terminal and the API cannot honour, with the reason.\n *\n * `skills: find` is a **screen**, not an answer: the terminal mounts a catalogue picker and writes\n * the chosen refs into `skillsPick`. Over the wire it was accepted and produced `skills/.keep` —\n * byte-identical to `none`, while the choice's own label promises a catalogue search. Filtered out\n * of the served choices *and* refused, for the same reason `REFUSED_STEPS` is one map.\n */\nconst REFUSED_CHOICES: ReadonlyMap<\n InitStep,\n ReadonlyMap<string, { readonly code: string; readonly hint: string }>\n> = new Map([\n [\n \"skills\",\n new Map([\n [\n \"find\",\n {\n code: \"provision_skills_search_refused\",\n hint: \"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists.\",\n },\n ],\n ]),\n ],\n])\n\n/**\n * The answer a client should send for a question's default.\n *\n * `validateAnswer` rather than a lookup, because it is the same function the route validates the\n * answer with — so the served default cannot be a value the route would reject. A fallback that\n * does not validate (the empty one on a required text question) passes through unchanged: empty is\n * what \"you must answer this\" looks like on the wire, and `optional` says which it is.\n */\nfunction canonical(question: Question): string {\n const checked = validateAnswer(question.step, question.fallback)\n return checked.ok ? checked.value : question.fallback\n}\n\n/**\n * One question, for a client that is not a terminal.\n *\n * Exported so the forwarding can be tested against a question carrying a `hint` — only the location\n * question has one today, and that one is filtered out of the served list, so a test over the real\n * walk would assert this by having no data. `secret` is read from `SECRET_STEPS` rather than\n * restated, which is the half that must not drift: a second list of which answers are credentials\n * is the one worth getting wrong.\n */\nexport function toProvisionStep(question: Question, opened?: StepRequirement): ProvisionStep {\n const refused = REFUSED_CHOICES.get(question.step)\n return {\n step: question.step,\n prompt: question.prompt,\n fallback: canonical(question),\n optional: question.optional === true,\n secret: SECRET_STEPS.has(question.step),\n ...(opened === undefined ? {} : { requires: opened }),\n ...(question.options === undefined\n ? {}\n : {\n choices: question.options\n .filter((option) => refused?.has(option.value) !== true)\n .map((option) => ({\n value: option.value,\n label: option.label,\n // `hint` kept separate from `label`: it is the dim half of a row, a reason\n // rather than a second label. Folding the two together is what produced a\n // 79-column row that wrapped at 80 into a line with no pointer and no number.\n ...(option.hint === undefined ? {} : { hint: option.hint }),\n })),\n }),\n }\n}\n\n/** How far a single walk may go before something is wrong. `STEP_ORDER` is 21 long. */\nconst WALK_GUARD = 64\n\n/**\n * Every question the wizard can ask, in asking order, with its choices and what opens it.\n *\n * **Walked from `nextQuestion` rather than written down**, which is the whole reason this is safe to\n * serve: the terminal's order, prompts, defaults and choice lists come from the same walk, so a\n * browser cannot render a stale form. A hand-kept list here would be the \"two lists\" shape that has\n * already cost this repo several rounds — `NO_MANIFEST`, `DOCUMENTED_CTRL_LETTERS`,\n * `THRESHOLD_ORDER`, each right when written and wrong at the next addition.\n *\n * ## Why one walk is not enough\n *\n * `nextQuestion` skips a question whose opening answer was not given, so following the **default**\n * path lists thirteen of the eighteen askable steps and omits every credential but the model key:\n * `telegramToken`, `telegramAllow`, `webBackend`, `webKey`, `composioKey`. A browser built on that\n * could ask for a Telegram agent and not for its token, and would write an agent whose `.env` has\n * to be filled at a terminal before it can start — which is the opposite of what provisioning from\n * a browser is for.\n *\n * So the default path is walked first and its finds carry no `requires`; then every choice it\n * offered is walked as a **branch**, and a step seen for the first time there is attributed to the\n * branch that opened it. Breadth-first, so a step reachable two ways is attributed to the\n * shallowest — and each `step=value` pair is walked at most once, which is what bounds this to\n * roughly twenty short walks rather than a combinatorial explosion.\n *\n * The seed carries the **whole path** taken to reach a branch, not just its own answer: seeded with\n * `webBackend` alone, `nextQuestion` skips it, because it is a question only for somebody who\n * already said `web: search`.\n *\n * Ordering is restored from `STEP_ORDER` at the end, because a branch's finds are discovered after\n * the default path has run past them and \"in asking order\" is what the wire promises.\n *\n * `REFUSED_STEPS` is omitted rather than offered: a question the route rejects is a field that\n * cannot be submitted, which is worse than not asking.\n */\nexport function provisionSteps(defaults: QuestionDefaults): readonly ProvisionStep[] {\n const found = new Map<InitStep, ProvisionStep>()\n const walked = new Set<string>()\n\n /** Follow one path to its end; return every branch it declined to take. */\n const walk = (\n seed: PartialAnswers,\n opened?: StepRequirement,\n ): readonly { readonly seed: PartialAnswers; readonly opened: StepRequirement }[] => {\n const answers: PartialAnswers = { ...seed }\n const branches: { readonly seed: PartialAnswers; readonly opened: StepRequirement }[] = []\n // Bounded: `nextQuestion` is a pure walk over a fixed order, so it terminates — but a bug\n // there would hang a request rather than fail one, and a request that never answers is the\n // worst failure an HTTP surface has.\n for (let guard = 0; guard < WALK_GUARD; guard += 1) {\n const question: Question | undefined = nextQuestion(answers, defaults)\n if (question === undefined) break\n const value = canonical(question)\n if (!REFUSED_STEPS.has(question.step) && !found.has(question.step)) {\n found.set(question.step, toProvisionStep(question, opened))\n }\n for (const option of question.options ?? []) {\n if (option.value === value) continue\n if (REFUSED_CHOICES.get(question.step)?.has(option.value) === true) continue\n branches.push({\n seed: { ...answers, [question.step]: option.value },\n opened: { step: question.step, value: option.value },\n })\n }\n /**\n * The **canonical** answer advances the walk, not the wizard's `fallback`.\n *\n * Storing `\"1\"` made the walk unable to read its own answers: `presetById(\"1\")` is\n * `undefined`, so `model` and `baseUrl` were offered with empty defaults, and every\n * branch test (`partial.web !== \"search\"`) compared against an index. An optional step\n * with no fallback answers empty, which is what it means — refusing there would make\n * this list unreachable past the first secret.\n */\n answers[question.step] = value\n }\n return branches\n }\n\n const queue = [...walk({})]\n for (let guard = 0; guard < WALK_GUARD && queue.length > 0; guard += 1) {\n const next = queue.splice(0, queue.length)\n for (const branch of next) {\n const key = `${branch.opened.step}=${branch.opened.value}`\n if (walked.has(key)) continue\n walked.add(key)\n queue.push(...walk(branch.seed, branch.opened))\n }\n }\n\n return [...found.values()].sort(\n (a, b) => STEP_ORDER.indexOf(a.step) - STEP_ORDER.indexOf(b.step),\n )\n}\n\nexport interface ProvisionRequest {\n /** A subset of the steps. Anything absent takes its default, as `init --yes` does. */\n readonly answers: Readonly<Record<string, string>>\n readonly defaults: QuestionDefaults\n}\n\nexport interface ProvisionResult {\n readonly agentId: string\n readonly dir: string\n readonly manifestPath: string\n /** Relative paths written, so a caller can report what it made without re-reading the disk. */\n readonly files: readonly string[]\n}\n\n/**\n * Validate a partial answer set, fill the rest from defaults, and write the agent.\n *\n * The HTTP twin of `init --yes --name x --preset y`, and deliberately built from the same three\n * calls in the same order: `validateAnswer` per supplied step, `fillDefaults` for the rest,\n * `complete` as the funnel. A route that assembled answers any other way would be a second\n * definition of what a valid agent is.\n */\nexport function provisionAgent(input: ProvisionRequest): ProvisionResult {\n const partial: PartialAnswers = {}\n\n for (const [key, raw] of Object.entries(input.answers)) {\n const step = key as InitStep\n if (!(step in FLAG_FOR)) {\n throw new HarnessError({\n code: \"provision_unknown_answer\",\n message: `\"${key}\" is not a question this runtime asks.`,\n hint: \"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.\",\n field: key,\n })\n }\n /**\n * Refused, never ignored, and read off `REFUSED_STEPS` rather than named here.\n *\n * **The directory is not a caller's to choose.** Silently writing somewhere other than\n * where a request asked is the class of surprise this repo writes decisions about, and a\n * route that *honoured* a path would write wherever it was pointed. The loopback gate is\n * not a reason to hand over the filesystem as well. `daemon` is refused for the opposite\n * reason: it was accepted and acted on by nobody.\n */\n const refusedStep = REFUSED_STEPS.get(step)\n if (refusedStep !== undefined) {\n throw new HarnessError({\n code: refusedStep.code,\n message: `\"${key}\" cannot be set over the API.`,\n hint: refusedStep.hint,\n field: key,\n })\n }\n /**\n * A choice this step offers at a terminal and the API cannot honour.\n *\n * Checked **before** `validateAnswer`, which accepts it: it is a real answer to a real\n * question, and the problem is that the half implementing it lives in `init.ts`. Refusing\n * it after validation would report it as an invalid value, which is a lie about why.\n */\n const refusedChoice = REFUSED_CHOICES.get(step)?.get(raw.trim().toLowerCase())\n if (refusedChoice !== undefined) {\n throw new HarnessError({\n code: refusedChoice.code,\n message: `${key} is ${JSON.stringify(raw)}, which this runtime cannot do over the API.`,\n hint: refusedChoice.hint,\n field: key,\n })\n }\n const checked = validateAnswer(step, raw)\n if (!checked.ok) {\n throw new HarnessError({\n code: \"provision_answer_invalid\",\n message: `${key} is ${JSON.stringify(raw)}, which ${checked.reason}`,\n hint: \"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.\",\n field: key,\n })\n }\n partial[step] = checked.value\n }\n\n // Everything unanswered takes its default, and anything with no default is refused by name —\n // the same sentence `init --yes` gives, from the same function.\n fillDefaults(partial, \"this is the provisioning API\", input.defaults)\n const answers: InitAnswers = complete(partial, input.defaults)\n\n /**\n * The sandbox, always — and **the injected base, never `agentsDir()` directly**.\n *\n * Recomputed from the agent's own name so nothing a caller sent can reach `resolve`; taken from\n * `defaults.agentDirBase` so a test can point it at a tmpdir. Calling `agentsDir()` here read\n * the *real* sandbox root and the first run of this module.s tests wrote three agents into the\n * author's own sandbox — which is precisely the hazard `lib/sandbox.ts` documents: sandbox paths\n * come from there and nowhere else, and a caller that computes one itself has bypassed the\n * override every test depends on.\n */\n const targetDir = resolve(join(input.defaults.agentDirBase, answers.name))\n const files = planFiles({ ...answers, dir: targetDir })\n writeAgentFiles(targetDir, files)\n\n return {\n agentId: answers.name,\n dir: targetDir,\n manifestPath: join(targetDir, \"agent.yaml\"),\n files: files.map((file) => file.relPath),\n }\n}\n",
|
|
15
|
+
"/**\n * Writing an agent to disk — the one path, shared by `init` and by `POST /v1/agents`.\n *\n * ## Why this module exists at all\n *\n * Provisioning has two front doors now: a wizard at a terminal and an HTTP route a browser or a\n * platform calls. They must produce **byte-identical** agents, and the only way to promise that is\n * for there to be one writer. Two would be the shape this repo keeps paying for — right when\n * written, divergent at the next change, with the symptom being an agent that works when created\n * one way and not the other.\n *\n * `complete` and `fillDefaults` moved here from `init.ts` for that reason: they *are* the funnel\n * both paths pass through, and `complete`'s own comments are a monument to what happens when a\n * default lives anywhere else (`apiKeyEnv` was dropped from generated manifests entirely when its\n * question was removed, and `--schedules daily` was accepted and lost in two separate literals).\n *\n * ## What the HTTP path is allowed to decide, and what it is not\n *\n * **Not the directory.** `dir` and `dirChoice` are refused over the wire and the agent always lands\n * in the sandbox. Where an agent lives on disk is the operator's decision, not a caller's — and a\n * route that honoured a path would write wherever it was pointed, which is a very short step from\n * a request that overwrites something. The route is loopback-gated in this phase, and that gate is\n * not a reason to also hand over the filesystem.\n *\n * **Not which variables hold secrets.** A secret answer is written into the `.env` at `0600` once\n * and no route ever reads it back. `SECRET_STEPS` is what a client masks; nothing here echoes one.\n */\n\nimport { existsSync, mkdirSync, writeFileSync } from \"node:fs\"\nimport { dirname, join, resolve } from \"node:path\"\nimport { HarnessError } from \"@dispach/core\"\nimport {\n dirFor,\n type GeneratedFile,\n type InitAnswers,\n type InitStep,\n nextQuestion,\n type PartialAnswers,\n planFiles,\n presetById,\n type Question,\n type QuestionDefaults,\n SECRET_STEPS,\n STEP_ORDER,\n slugify,\n validateAnswer,\n} from \"#lib/init-flow\"\n\nexport const FLAG_FOR: Record<InitStep, string> = {\n user: \"--user\",\n name: \"--name\",\n purpose: \"--purpose\",\n preset: \"--preset\",\n model: \"--model\",\n baseUrl: \"--base-url\",\n apiKeyEnv: \"--api-key-env\",\n // No flag, on purpose: a key on the command line lands in shell history. With --yes the .env\n // is written with an empty value and the next steps say where to put it.\n apiKey: \"(asked at the prompt only)\",\n system: \"--system\",\n web: \"--web\",\n webBackend: \"--web-backend\",\n // No flag, same reason as the model key.\n webKey: \"(asked at the prompt only)\",\n composio: \"--composio\",\n composioKey: \"(asked at the prompt only)\",\n telegram: \"--telegram\",\n telegramAllow: \"--telegram-allow\",\n // No flag, same reason as every other secret: a token on a command line lands in history.\n telegramToken: \"(asked at the prompt only)\",\n schedules: \"--schedules\",\n server: \"--server\",\n skills: \"--skills\",\n skillsSearch: \"--skills\",\n skillsPick: \"--skills\",\n daemon: \"--daemon\",\n // Never asked and never a flag — generated, because it is ours rather than a third party's.\n serverToken: \"(generated)\",\n dirChoice: \"--dir\",\n dir: \"--dir\",\n}\n\n/**\n * Non-interactive: every unanswered question takes its default, and a question with no default is\n * a refusal, not a guess. All gaps report at once — with `--preset custom` that is the endpoint\n * flags too, not just the names — and the refusal says *why* the questions could not be asked,\n * which is the mode decision's `because` string doing its first useful work.\n */\nexport function fillDefaults(\n partial: Partial<Record<InitStep, string>>,\n because: string,\n defaults: QuestionDefaults,\n): void {\n const missing: InitStep[] = []\n for (;;) {\n const question = nextQuestion(partial, defaults)\n if (question === undefined) break\n if (question.optional === true) {\n // An empty answer is the answer. Refusing here would make `--yes` demand a secret it\n // deliberately offers no flag for.\n partial[question.step] = \"\"\n continue\n }\n if (question.fallback === \"\") {\n missing.push(question.step)\n // Placeholder purely to advance the walk; discarded by the throw below.\n partial[question.step] = \"(missing)\"\n continue\n }\n const checked = validateAnswer(question.step, question.fallback)\n if (checked.ok) partial[question.step] = checked.value\n }\n if (missing.length > 0) {\n const flags = missing.map((step) => FLAG_FOR[step]).join(\", \")\n throw new HarnessError({\n code: \"cli_init_missing_answers\",\n message: `Not interactive (${because}), and ${missing.join(\", \")} ${missing.length === 1 ? \"has\" : \"have\"} no default.`,\n hint: `Pass ${flags} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`,\n })\n }\n}\n\nexport function complete(\n partial: Partial<Record<InitStep, string>>,\n defaults: QuestionDefaults,\n): InitAnswers {\n // `apiKeyEnv` and `apiKey` legitimately stay undefined — the first for a keyless endpoint, the\n // second for anyone exporting the variable another way. Everything else is present once\n // nextQuestion returns undefined.\n const answers = partial as Record<\n Exclude<\n InitStep,\n | \"apiKeyEnv\"\n | \"apiKey\"\n | \"webBackend\"\n | \"webKey\"\n | \"composioKey\"\n | \"skillsSearch\"\n | \"skillsPick\"\n | \"schedules\"\n | \"server\"\n | \"dir\"\n | \"dirChoice\"\n >,\n string\n > & {\n /**\n * Undefined unless `--schedules` was passed: this capability has no wizard step at all.\n * Defaulted below, at the funnel, for the reason `apiKeyEnv` is.\n */\n schedules?: string\n /**\n * Undefined unless `--server` was passed. Same shape as `schedules`, and for the same\n * reason: the question was withdrawn in 0.1.2 and the flag stayed.\n */\n server?: string\n /** Undefined unless the skills answer was `find`; its question is skipped otherwise. */\n skillsSearch?: string\n /** Undefined unless the wizard's catalogue step ran and something was ticked. */\n skillsPick?: string\n apiKeyEnv?: string\n apiKey?: string\n // Both stay undefined unless the web answer was `search` — the flow skips their questions,\n // so `nextQuestion` returning undefined does not mean they were answered.\n webBackend?: string\n webKey?: string\n /** Undefined unless the Composio answer was `connected`, for the same reason. */\n composioKey?: string\n /** Both stay undefined unless the Telegram answer was `connected`. */\n telegramToken?: string\n telegramAllow?: string\n /** Undefined unless `dirChoice` was `custom`; derived below otherwise. */\n dir?: string\n /** Undefined when `--dir` answered the question, which is what skips it. */\n dirChoice?: string\n }\n // Which variable holds the key is no longer asked — it comes from `--api-key-env`, or from the\n // preset. Defaulted HERE, at the one funnel both the wizard and the scripted path pass through:\n // when this lived in the question list, removing the question silently dropped `apiKeyEnv` from\n // the manifest altogether and generated an agent with no key configuration at all.\n const preset = presetById(answers.preset)\n const keyVar = answers.apiKeyEnv ?? preset?.apiKeyEnv\n /**\n * Resolved **once**, above the literal, because two things read it.\n *\n * `server` stopped being a wizard step in 0.1.2 and is defaulted here. Written as\n * `answers.server ?? \"local\"` inline, the field below got the default and the `serverToken`\n * line twenty rows down went on reading `answers.server` — which is `undefined` whenever\n * `--server` was not passed. So the manifest said `enabled: true`, the `.env` carried no token,\n * and the agent refused to start: one value, two readers, one of them wrong.\n */\n const server = answers.server ?? \"local\"\n\n // `dir` stops being asked the moment the answer is `sandbox` or `here`, so its value has to be\n // derived at this funnel — the same rule `apiKeyEnv` above is a monument to. `dirFor` is the one\n // derivation, shared with the confirm screen, so the summary cannot describe a directory other\n // than the one written. An explicit answer still wins: `--dir` sets both fields.\n const dir = answers.dir ?? dirFor(answers.dirChoice, answers.name, defaults)\n if (dir === undefined) {\n throw new HarnessError({\n code: \"cli_init_no_directory\",\n message: `The directory answer was ${JSON.stringify(answers.dirChoice)}, which resolves to no path.`,\n hint: \"This is a bug in the CLI: every dirChoice except `custom` must derive a path in `dirFor`, and `custom` must have asked the dir question. Pass --dir <path> to get past it.\",\n })\n }\n\n return {\n user: answers.user,\n name: answers.name,\n purpose: answers.purpose,\n preset: answers.preset as InitAnswers[\"preset\"],\n model: answers.model,\n baseUrl: answers.baseUrl,\n system: answers.system,\n web: answers.web,\n ...(answers.webBackend === undefined ? {} : { webBackend: answers.webBackend }),\n ...(answers.webKey === undefined || answers.webKey === \"\"\n ? {}\n : { webKey: answers.webKey }),\n composio: answers.composio,\n ...(answers.composioKey === undefined || answers.composioKey === \"\"\n ? {}\n : { composioKey: answers.composioKey }),\n telegram: answers.telegram,\n ...(answers.telegramToken === undefined || answers.telegramToken === \"\"\n ? {}\n : { telegramToken: answers.telegramToken }),\n ...(answers.telegramAllow === undefined || answers.telegramAllow === \"\"\n ? {}\n : { telegramAllow: answers.telegramAllow }),\n // `none` writes the commented block with its worked example — see SCHEDULE_CHOICES. Defaulted\n // here rather than as a step fallback because there is no step: this funnel is the one place\n // both the wizard and `--schedules daily` pass through, which is the lesson `apiKeyEnv` above\n // records from the last time a question was removed and its field silently went missing.\n schedules: answers.schedules ?? \"none\",\n /**\n * **On by default, and no longer asked.** \"Serve the HTTP API?\" defaulted to *No* —\n * `fallback: \"1\"` is a 1-based menu index and element 0 of `SERVER_CHOICES` is `none` — so\n * `--yes`, this funnel and `GET /v1/provision` all produced an agent with its API switched\n * off. Which is asking whether somebody wants the product: an always-on server is what this\n * is, and the TUI and web UI are *views* onto it. Same argument that withdrew the\n * `schedules` question one field above. Resolved at `server` near the top of this function.\n */\n server,\n skills: answers.skills,\n // Carried explicitly. This funnel is a literal, not a spread, so a step that is collected and not\n // listed here is silently dropped — which is what happened: `--skills \"pdf tables\"` set the answer\n // to `find` and lost the words, and init reported \"no words to search for\" about a phrase the\n // person had just typed. The same shape as `apiKeyEnv` above, and the reason that comment exists.\n ...(answers.skillsSearch === undefined || answers.skillsSearch === \"\"\n ? {}\n : { skillsSearch: answers.skillsSearch }),\n ...(answers.skillsPick === undefined || answers.skillsPick === \"\"\n ? {}\n : { skillsPick: answers.skillsPick }),\n daemon: answers.daemon,\n // Minted here rather than in the flow, which is a PURE module and must stay deterministic.\n // Only for an agent that asked for a server: an unused 64-hex string in every generated\n // .env is a secret nobody chose and one more thing to wonder about.\n // Reads the **resolved** value, not `answers.server`. It read the raw input, which is now\n // `undefined` whenever `--server` was not passed — so the manifest said `enabled: true` and\n // the `.env` carried no token, and the agent would have refused to start. Caught by a test\n // that reads the generated `.env` rather than this object, which is the guard this repo has\n // needed for this exact shape six times.\n ...(server === \"local\" ? { serverToken: randomToken() } : {}),\n ...(keyVar === undefined ? {} : { apiKeyEnv: keyVar }),\n ...(answers.apiKey === undefined || answers.apiKey === \"\"\n ? {}\n : { apiKey: answers.apiKey }),\n ...(answers.dirChoice === undefined ? {} : { dirChoice: answers.dirChoice }),\n dir,\n }\n}\n\n/**\n * The server token a generated manifest names, when the server answer asked for one.\n *\n * Moved here verbatim with `complete`, its only caller. 256 bits of `crypto.getRandomValues`, hex.\n */\nfunction randomToken(): string {\n const bytes = new Uint8Array(32)\n crypto.getRandomValues(bytes)\n return [...bytes].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\n// ─── the shared writer ──────────────────────────────────────────────────────────────────\n\n/**\n * Write a planned agent, refusing rather than overwriting.\n *\n * Per-target checks rather than \"directory not empty\": a fresh `git init`'d directory must work,\n * and the refusal names every collision at once rather than one per run.\n *\n * `.env` alone gets `0600`. It holds every credential this agent has — the model key, a bot token,\n * a Composio key — and the default `0644` made all of them readable by anything running on the\n * machine. That matters more under a service manager, which hands a job almost no environment and\n * whose unit carries no secrets by design, so this file is the *only* path credentials arrive by.\n */\nexport function writeAgentFiles(targetDir: string, files: readonly GeneratedFile[]): void {\n const collisions = files\n .map((file) => join(targetDir, file.relPath))\n .filter((path) => existsSync(path))\n if (collisions.length > 0) {\n throw new HarnessError({\n code: \"cli_init_target_exists\",\n message: `${collisions.length} of the files init would write already exist: ${collisions.join(\", \")}`,\n hint: \"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable.\",\n })\n }\n\n for (const file of files) {\n const path = join(targetDir, file.relPath)\n mkdirSync(dirname(path), { recursive: true })\n writeFileSync(path, file.contents, {\n encoding: \"utf8\",\n ...(file.relPath === \".env\" ? { mode: 0o600 } : {}),\n })\n }\n}\n\n// ─── the HTTP-facing half ───────────────────────────────────────────────────────────────\n\n/**\n * What opens a step that is not always asked.\n *\n * `telegramToken` is a question only for somebody who said `telegram: connected`, and\n * `nextQuestion` expresses that as a `continue` a client cannot see. This is the same fact,\n * declared — so a browser can render the whole question set and reveal a field when the choice\n * that opens it is made, without re-implementing the walk. A hard-coded condition in the page\n * would be the two-hand-kept-lists shape that `GET /v1/provision` exists to prevent.\n *\n * **Evaluate it transitively.** A step is askable when its requirement is met *and* the step named\n * in that requirement is itself askable. `webKey` requires `web: search`; `web` requires nothing,\n * so the recursion terminates at the default path. Only the nearest opening choice is recorded,\n * because attributing a step to every ancestor would be a second encoding of `STEP_ORDER`'s shape.\n */\nexport interface StepRequirement {\n readonly step: InitStep\n /** The canonical answer — the choice's `value`, never a menu index. See `canonical`. */\n readonly value: string\n}\n\n/** One question, as a client that is not a terminal needs to see it. */\nexport interface ProvisionStep {\n readonly step: InitStep\n readonly prompt: string\n /**\n * The offered default, as a value a client can use. Empty means the answer is required unless\n * `optional`.\n *\n * **Canonical, never the wizard's own `fallback`.** A `Question` for a menu carries `\"1\"` —\n * a 1-based index, which `validateAnswer` accepts from a terminal and which matches no\n * `choices[].value` at all. Served raw it gave a `<select>` no selectable default; worse, the\n * walk fed it back to itself, `presetById(\"1\")` answered `undefined`, and `model` and `baseUrl`\n * were therefore served with **empty** defaults where the terminal offers a real model id.\n */\n readonly fallback: string\n /** An empty answer is a real answer. See `Question.optional`. */\n readonly optional: boolean\n /** Mask it, never echo it, never log it. Derived from `SECRET_STEPS`, not restated. */\n readonly secret: boolean\n /** Absent means always asked. See `StepRequirement`. */\n readonly requires?: StepRequirement\n readonly choices?: readonly {\n readonly value: string\n readonly label: string\n /** The dim half of a row — a reason, not a second label. See `Question.options`. */\n readonly hint?: string\n }[]\n}\n\n/**\n * Steps no API caller may answer, with the reason each is refused.\n *\n * One map, read by two things that must agree: `provisionSteps` leaves these out of the served\n * list, and `provisionAgent` throws when one arrives anyway. Held together because a question\n * offered by one and refused by the other puts a field in front of somebody that cannot be\n * submitted — and the reverse, a step quietly *accepted* and acted on by nobody, is worse.\n *\n * `daemon` is the one found by building the browser form. It was in `FLAG_FOR`, so it validated\n * and landed in `answers`, and **only `init.ts` ever reads it** — so\n * `POST /v1/agents {\"answers\":{\"daemon\":\"service\"}}` answered `201` and installed no service. It is\n * also the question a running host has already answered: the response's `adopted` field *is* \"yes,\n * it is running in the background\". It stayed invisible because the walk skips it unless a channel\n * or the server is on, which the default path never is.\n */\nconst REFUSED_STEPS: ReadonlyMap<InitStep, { readonly code: string; readonly hint: string }> =\n new Map([\n [\n \"dir\",\n {\n code: \"provision_directory_refused\",\n hint: \"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else.\",\n },\n ],\n [\n \"dirChoice\",\n {\n code: \"provision_directory_refused\",\n hint: \"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else.\",\n },\n ],\n [\n \"daemon\",\n {\n code: \"provision_daemon_refused\",\n hint: \"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process.\",\n },\n ],\n ])\n\n/**\n * Choices a step offers at a terminal and the API cannot honour, with the reason.\n *\n * `skills: find` is a **screen**, not an answer: the terminal mounts a catalogue picker and writes\n * the chosen refs into `skillsPick`. Over the wire it was accepted and produced `skills/.keep` —\n * byte-identical to `none`, while the choice's own label promises a catalogue search. Filtered out\n * of the served choices *and* refused, for the same reason `REFUSED_STEPS` is one map.\n */\nconst REFUSED_CHOICES: ReadonlyMap<\n InitStep,\n ReadonlyMap<string, { readonly code: string; readonly hint: string }>\n> = new Map([\n [\n \"skills\",\n new Map([\n [\n \"find\",\n {\n code: \"provision_skills_search_refused\",\n hint: \"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists.\",\n },\n ],\n ]),\n ],\n])\n\n/**\n * The answer a client should send for a question's default.\n *\n * `validateAnswer` rather than a lookup, because it is the same function the route validates the\n * answer with — so the served default cannot be a value the route would reject. A fallback that\n * does not validate (the empty one on a required text question) passes through unchanged: empty is\n * what \"you must answer this\" looks like on the wire, and `optional` says which it is.\n */\nfunction canonical(question: Question): string {\n const checked = validateAnswer(question.step, question.fallback)\n return checked.ok ? checked.value : question.fallback\n}\n\n/**\n * One question, for a client that is not a terminal.\n *\n * Exported so the forwarding can be tested against a question carrying a `hint` — only the location\n * question has one today, and that one is filtered out of the served list, so a test over the real\n * walk would assert this by having no data. `secret` is read from `SECRET_STEPS` rather than\n * restated, which is the half that must not drift: a second list of which answers are credentials\n * is the one worth getting wrong.\n */\nexport function toProvisionStep(question: Question, opened?: StepRequirement): ProvisionStep {\n const refused = REFUSED_CHOICES.get(question.step)\n return {\n step: question.step,\n prompt: question.prompt,\n fallback: canonical(question),\n optional: question.optional === true,\n secret: SECRET_STEPS.has(question.step),\n ...(opened === undefined ? {} : { requires: opened }),\n ...(question.options === undefined\n ? {}\n : {\n choices: question.options\n .filter((option) => refused?.has(option.value) !== true)\n .map((option) => ({\n value: option.value,\n label: option.label,\n // `hint` kept separate from `label`: it is the dim half of a row, a reason\n // rather than a second label. Folding the two together is what produced a\n // 79-column row that wrapped at 80 into a line with no pointer and no number.\n ...(option.hint === undefined ? {} : { hint: option.hint }),\n })),\n }),\n }\n}\n\n/** How far a single walk may go before something is wrong. `STEP_ORDER` is 21 long. */\nconst WALK_GUARD = 64\n\n/**\n * Every question the wizard can ask, in asking order, with its choices and what opens it.\n *\n * **Walked from `nextQuestion` rather than written down**, which is the whole reason this is safe to\n * serve: the terminal's order, prompts, defaults and choice lists come from the same walk, so a\n * browser cannot render a stale form. A hand-kept list here would be the \"two lists\" shape that has\n * already cost this repo several rounds — `NO_MANIFEST`, `DOCUMENTED_CTRL_LETTERS`,\n * `THRESHOLD_ORDER`, each right when written and wrong at the next addition.\n *\n * ## Why one walk is not enough\n *\n * `nextQuestion` skips a question whose opening answer was not given, so following the **default**\n * path lists thirteen of the eighteen askable steps and omits every credential but the model key:\n * `telegramToken`, `telegramAllow`, `webBackend`, `webKey`, `composioKey`. A browser built on that\n * could ask for a Telegram agent and not for its token, and would write an agent whose `.env` has\n * to be filled at a terminal before it can start — which is the opposite of what provisioning from\n * a browser is for.\n *\n * So the default path is walked first and its finds carry no `requires`; then every choice it\n * offered is walked as a **branch**, and a step seen for the first time there is attributed to the\n * branch that opened it. Breadth-first, so a step reachable two ways is attributed to the\n * shallowest — and each `step=value` pair is walked at most once, which is what bounds this to\n * roughly twenty short walks rather than a combinatorial explosion.\n *\n * The seed carries the **whole path** taken to reach a branch, not just its own answer: seeded with\n * `webBackend` alone, `nextQuestion` skips it, because it is a question only for somebody who\n * already said `web: search`.\n *\n * Ordering is restored from `STEP_ORDER` at the end, because a branch's finds are discovered after\n * the default path has run past them and \"in asking order\" is what the wire promises.\n *\n * `REFUSED_STEPS` is omitted rather than offered: a question the route rejects is a field that\n * cannot be submitted, which is worse than not asking.\n */\nexport function provisionSteps(defaults: QuestionDefaults): readonly ProvisionStep[] {\n const found = new Map<InitStep, ProvisionStep>()\n const walked = new Set<string>()\n\n /** Follow one path to its end; return every branch it declined to take. */\n const walk = (\n seed: PartialAnswers,\n opened?: StepRequirement,\n ): readonly { readonly seed: PartialAnswers; readonly opened: StepRequirement }[] => {\n const answers: PartialAnswers = { ...seed }\n const branches: { readonly seed: PartialAnswers; readonly opened: StepRequirement }[] = []\n // Bounded: `nextQuestion` is a pure walk over a fixed order, so it terminates — but a bug\n // there would hang a request rather than fail one, and a request that never answers is the\n // worst failure an HTTP surface has.\n for (let guard = 0; guard < WALK_GUARD; guard += 1) {\n const question: Question | undefined = nextQuestion(answers, defaults)\n if (question === undefined) break\n const value = canonical(question)\n if (!REFUSED_STEPS.has(question.step) && !found.has(question.step)) {\n found.set(question.step, toProvisionStep(question, opened))\n }\n for (const option of question.options ?? []) {\n if (option.value === value) continue\n if (REFUSED_CHOICES.get(question.step)?.has(option.value) === true) continue\n branches.push({\n seed: { ...answers, [question.step]: option.value },\n opened: { step: question.step, value: option.value },\n })\n }\n /**\n * The **canonical** answer advances the walk, not the wizard's `fallback`.\n *\n * Storing `\"1\"` made the walk unable to read its own answers: `presetById(\"1\")` is\n * `undefined`, so `model` and `baseUrl` were offered with empty defaults, and every\n * branch test (`partial.web !== \"search\"`) compared against an index. An optional step\n * with no fallback answers empty, which is what it means — refusing there would make\n * this list unreachable past the first secret.\n */\n answers[question.step] = value\n }\n return branches\n }\n\n const queue = [...walk({})]\n for (let guard = 0; guard < WALK_GUARD && queue.length > 0; guard += 1) {\n const next = queue.splice(0, queue.length)\n for (const branch of next) {\n const key = `${branch.opened.step}=${branch.opened.value}`\n if (walked.has(key)) continue\n walked.add(key)\n queue.push(...walk(branch.seed, branch.opened))\n }\n }\n\n return [...found.values()].sort(\n (a, b) => STEP_ORDER.indexOf(a.step) - STEP_ORDER.indexOf(b.step),\n )\n}\n\nexport interface ProvisionRequest {\n /** A subset of the steps. Anything absent takes its default, as `init --yes` does. */\n readonly answers: Readonly<Record<string, string>>\n readonly defaults: QuestionDefaults\n}\n\nexport interface ProvisionResult {\n readonly agentId: string\n readonly dir: string\n readonly manifestPath: string\n /** Relative paths written, so a caller can report what it made without re-reading the disk. */\n readonly files: readonly string[]\n}\n\n/**\n * Validate a partial answer set, fill the rest from defaults, and write the agent.\n *\n * The HTTP twin of `init --yes --name x --preset y`, and deliberately built from the same three\n * calls in the same order: `validateAnswer` per supplied step, `fillDefaults` for the rest,\n * `complete` as the funnel. A route that assembled answers any other way would be a second\n * definition of what a valid agent is.\n */\nexport function provisionAgent(input: ProvisionRequest): ProvisionResult {\n const partial: PartialAnswers = {}\n\n for (const [key, raw] of Object.entries(input.answers)) {\n const step = key as InitStep\n if (!(step in FLAG_FOR)) {\n throw new HarnessError({\n code: \"provision_unknown_answer\",\n message: `\"${key}\" is not a question this runtime asks.`,\n hint: \"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.\",\n field: key,\n })\n }\n /**\n * Refused, never ignored, and read off `REFUSED_STEPS` rather than named here.\n *\n * **The directory is not a caller's to choose.** Silently writing somewhere other than\n * where a request asked is the class of surprise this repo writes decisions about, and a\n * route that *honoured* a path would write wherever it was pointed. The loopback gate is\n * not a reason to hand over the filesystem as well. `daemon` is refused for the opposite\n * reason: it was accepted and acted on by nobody.\n */\n const refusedStep = REFUSED_STEPS.get(step)\n if (refusedStep !== undefined) {\n throw new HarnessError({\n code: refusedStep.code,\n message: `\"${key}\" cannot be set over the API.`,\n hint: refusedStep.hint,\n field: key,\n })\n }\n /**\n * A choice this step offers at a terminal and the API cannot honour.\n *\n * Checked **before** `validateAnswer`, which accepts it: it is a real answer to a real\n * question, and the problem is that the half implementing it lives in `init.ts`. Refusing\n * it after validation would report it as an invalid value, which is a lie about why.\n */\n const refusedChoice = REFUSED_CHOICES.get(step)?.get(raw.trim().toLowerCase())\n if (refusedChoice !== undefined) {\n throw new HarnessError({\n code: refusedChoice.code,\n message: `${key} is ${JSON.stringify(raw)}, which this runtime cannot do over the API.`,\n hint: refusedChoice.hint,\n field: key,\n })\n }\n const checked = validateAnswer(step, raw)\n if (!checked.ok) {\n throw new HarnessError({\n code: \"provision_answer_invalid\",\n message: `${key} is ${JSON.stringify(raw)}, which ${checked.reason}`,\n hint: \"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.\",\n field: key,\n })\n }\n partial[step] = checked.value\n }\n\n // Everything unanswered takes its default, and anything with no default is refused by name —\n // the same sentence `init --yes` gives, from the same function.\n fillDefaults(partial, \"this is the provisioning API\", input.defaults)\n const answers: InitAnswers = complete(partial, input.defaults)\n\n /**\n * The sandbox, always — and **the injected base, never `agentsDir()` directly**.\n *\n * Recomputed from the agent's own name so nothing a caller sent can reach `resolve`; taken from\n * `defaults.agentDirBase` so a test can point it at a tmpdir. Calling `agentsDir()` here read\n * the *real* sandbox root and the first run of this module.s tests wrote three agents into the\n * author's own sandbox — which is precisely the hazard `lib/sandbox.ts` documents: sandbox paths\n * come from there and nowhere else, and a caller that computes one itself has bypassed the\n * override every test depends on.\n */\n /**\n * **Through `dirFor`, and the slug — not the typed name.**\n *\n * This read `join(agentDirBase, answers.name)` and returned `agentId: answers.name`, while the\n * manifest it writes declares `id: slugify(name)` and the terminal derives its directory\n * through the same `slugify` (`dirFor`). So one question had two answers depending on the\n * surface, and a name that is not already kebab-case broke three things at once:\n *\n * - `POST /v1/agents` answered `{ id: \"Milo\", adopted: [\"milo\"] }`, so the browser's\n * `adopted.includes(id)` was false and it reported a running agent as **\"written, and not\n * running\"** — with no error text, because there had been no error.\n * - the directory landed at `agents/Milo` while every route keys on `milo`, so\n * `validate milo` at a terminal was refused with *\"Known agents: Milo. Did you mean Milo?\"*\n * - 17.4's acceptance missed all of it by provisioning an agent called `vela`, already a slug.\n *\n * `dirFor` is the shared derivation rather than a second copy of it, which is the rule this\n * module's own comment fifteen lines up is a monument to. `agentId` is the id the *manifest*\n * declares, because that is what `Runtime.adopt` returns and what every route addresses.\n */\n const slug = slugify(answers.name)\n const derived = dirFor(\"sandbox\", answers.name, input.defaults)\n if (derived === undefined) {\n throw new HarnessError({\n code: \"provision_dir_unresolved\",\n message: `No directory could be derived for ${JSON.stringify(answers.name)}.`,\n hint: 'This is a bug in the CLI: `dirFor(\"sandbox\", …)` must always resolve a path. It returns undefined only when the name is missing, which `complete()` has already refused.',\n field: \"name\",\n })\n }\n const targetDir = resolve(derived)\n const files = planFiles({ ...answers, dir: targetDir })\n writeAgentFiles(targetDir, files)\n\n return {\n agentId: slug,\n dir: targetDir,\n manifestPath: join(targetDir, \"agent.yaml\"),\n files: files.map((file) => file.relPath),\n }\n}\n",
|
|
16
16
|
"/**\n * A read-only tap on stdin, opened before Ink attaches.\n *\n * ## Why a tap at all\n *\n * `useInput` cannot tell you what the terminal sent. Two independent things need that fact:\n *\n * 1. **Modifier correction.** Ink folds the super bit into `meta` on its legacy path, so `cmd+left` and\n * `option+left` arrive as the same keystroke. `lib/csi.ts` decodes the modifier from the bytes; this is\n * what gets the bytes to it.\n * 2. **The `keys` probe.** For a special key Ink reports `input: \"\"`, so a probe built on `input` printed\n * an empty byte row for every arrow, Home and cmd chord — the exact keys worth probing.\n *\n * ## Why it is safe\n *\n * Two listeners on one `data` event both receive the chunk; this consumes nothing from Ink. Ordering is\n * registration order, which is why `openTap` has to be called **before** `render` — that is what\n * guarantees a chunk is parsed and queued by the time `useInput` fires for it. Opened by the host rather\n * than by a component for exactly that reason: a component cannot register before the renderer that mounts\n * it.\n *\n * The queue is drained by *identity*, not by position (`withRealModifiers`), so an unmatched record waits\n * for the keystroke it belongs to instead of being applied to the wrong one. A record nothing ever claims\n * is dropped once the queue passes `MAX_QUEUED`, which keeps a terminal that emits sequences we do not\n * recognise from growing an array for the life of the session.\n */\n\nimport { type CsiKey, csiKeys, withRealModifiers } from \"#lib/csi\"\nimport type { KeyState } from \"#lib/types\"\n\n/**\n * How many unclaimed records to keep.\n *\n * Small on purpose: a keystroke is claimed by the very next `useInput`, so anything still queued after a\n * handful of presses was never going to be claimed. Bounded rather than cleared, because a burst of key\n * repeat legitimately queues several at once.\n */\nconst MAX_QUEUED = 16\n\nexport interface StdinTap {\n /** The key Ink reported, with its modifiers read off the wire where they could be. */\n correct(key: KeyState, input: string): KeyState\n /** The oldest unread chunk, for a probe that wants to print bytes. */\n takeRaw(): string | undefined\n close(): void\n}\n\ninterface DataStream {\n on(event: \"data\", listener: (chunk: Buffer | string) => void): unknown\n off(event: \"data\", listener: (chunk: Buffer | string) => void): unknown\n}\n\nexport function openTap(stdin: DataStream = process.stdin): StdinTap {\n const records: CsiKey[] = []\n const raw: string[] = []\n\n const listener = (chunk: Buffer | string): void => {\n const text = typeof chunk === \"string\" ? chunk : chunk.toString(\"utf8\")\n raw.push(text)\n if (raw.length > MAX_QUEUED) raw.splice(0, raw.length - MAX_QUEUED)\n records.push(...csiKeys(text))\n if (records.length > MAX_QUEUED) records.splice(0, records.length - MAX_QUEUED)\n }\n\n stdin.on(\"data\", listener)\n\n return {\n correct: (key: KeyState, input: string) => withRealModifiers(key, input, records),\n takeRaw: () => raw.shift(),\n close: () => {\n stdin.off(\"data\", listener)\n },\n }\n}\n",
|
|
17
17
|
"/**\n * Which terminal this is, and what it would take to make shift+enter send a newline.\n *\n * ## The problem, stated once\n *\n * A terminal sends the byte `CR` for enter. For shift+enter it sends… `CR`. The two are the same\n * keystroke as far as the process is concerned, which is why every terminal-based chat app either\n * documents a different chord or asks you to install a key binding.\n *\n * The sequence to install is `CSI 13;2u` — the kitty keyboard protocol's encoding of \"return with\n * shift\". Ink already parses it into `return + shift` (measured, not assumed), so nothing in the runtime\n * needs to change: the terminal either sends something distinguishable or it does not.\n *\n * ⌥⏎ is always available and needs none of this, because it arrives as `ESC` then `CR` — two bytes, and\n * therefore already distinguishable. That is why it is the documented chord and this command is an\n * optional convenience rather than a prerequisite.\n *\n * ## Why some terminals are written and others are explained\n *\n * A terminal whose configuration is a text file can be edited safely: append a line, keep a backup, and\n * a person can read the diff. A terminal whose configuration is a binary plist inside an array of\n * profiles cannot — iTerm2 also holds its preferences in memory and rewrites them on quit, so an edit\n * made underneath it is silently discarded. Writing one anyway would produce the worst outcome\n * available: a command that reports success and changes nothing.\n *\n * So `write` terminals get a file edit and `explain` terminals get the exact steps. The difference is a\n * property of the terminal, recorded here rather than discovered per user.\n *\n * Pure and PURE-listed: detection is a function of the environment *passed in*, and the recipes are\n * data. The file I/O lives in `terminal-setup.ts`.\n */\n\n/** The sequence a terminal must send for shift+enter. Ink parses this into `return + shift`. */\nexport const SHIFT_ENTER_SEQUENCE = \"\\u001B[13;2u\"\n\n/** The same thing spelled for a config file that wants an escaped literal rather than the byte. */\nexport const SHIFT_ENTER_ESCAPED = \"\\\\x1b[13;2u\"\n\nimport { BRAND } from \"@dispach/core\"\n\nexport type TerminalId =\n | \"vscode\"\n | \"ghostty\"\n | \"kitty\"\n | \"wezterm\"\n | \"iterm2\"\n | \"apple\"\n | \"warp\"\n | \"unknown\"\n\nexport interface TerminalRecipe {\n readonly id: TerminalId\n readonly name: string\n /**\n * `write` — the configuration is a text file this command can append to.\n * `explain` — it is not, so the steps are printed and a person performs them.\n * `unverified` — the terminal is known, and there is no recipe anyone has checked.\n *\n * The third state earns itself because both alternatives are worse. Reporting a known terminal as\n * \"not recognised\" is a lie about what we know; inventing a recipe for it produces the one outcome\n * this module is arranged to avoid — a command that reports success and changes nothing. Found by\n * running the command: the author's own terminal turned out to be one of these.\n *\n * There was briefly a fourth, `none` — \"nothing to configure\" — added when the kitty keyboard protocol\n * turned out to make shift+⏎ work in Warp on its own. It is gone, because the measurement behind it was\n * incomplete: the protocol fixes the *arrow* chords and not the letter ones, so Warp does have a step\n * after all. Recorded here rather than silently reverted, because the mistake is the useful part — a\n * state was invented for a case that a fuller measurement dissolved, and a state nothing reaches is\n * exactly the dead vocabulary this repo keeps removing.\n */\n readonly how: \"write\" | \"explain\" | \"unverified\"\n /** Path relative to the home directory. Absent for an `explain` terminal. */\n readonly configPath?: string\n /** The line to add. Absent for an `explain` terminal. */\n readonly line?: string\n /** How to tell whether the line is already there — a substring, not a regex, so it cannot over-match. */\n readonly marker?: string\n /** For `explain`: the steps, in order. */\n readonly steps?: readonly string[]\n /** Why this terminal cannot be configured automatically. Present whenever `how` is `explain`. */\n readonly reason?: string\n}\n\nconst RECIPES: readonly TerminalRecipe[] = [\n {\n id: \"vscode\",\n name: \"VS Code's integrated terminal\",\n how: \"write\",\n configPath: \"Library/Application Support/Code/User/keybindings.json\",\n // `sendSequence` is the only command that can put arbitrary bytes on the pty; the JSON escape\n // is what VS Code's argument parser expects, not a shell escape.\n line: `{ \"key\": \"shift+enter\", \"command\": \"workbench.action.terminal.sendSequence\", \"args\": { \"text\": \"\\\\u001b[13;2u\" } }`,\n marker: \"workbench.action.terminal.sendSequence\",\n },\n {\n id: \"ghostty\",\n name: \"Ghostty\",\n how: \"write\",\n configPath: \".config/ghostty/config\",\n line: `keybind = shift+enter=text:${SHIFT_ENTER_ESCAPED}`,\n marker: \"shift+enter=text:\",\n },\n {\n id: \"kitty\",\n name: \"kitty\",\n how: \"write\",\n configPath: \".config/kitty/kitty.conf\",\n // kitty speaks this protocol natively, but only advertises it to an application that asks. Ink\n // does not ask, so the mapping is still needed.\n line: `map shift+enter send_text all ${SHIFT_ENTER_ESCAPED}`,\n marker: \"map shift+enter send_text\",\n },\n {\n id: \"wezterm\",\n name: \"WezTerm\",\n how: \"write\",\n configPath: \".wezterm.lua\",\n line: `-- shift+enter: { key = 'Enter', mods = 'SHIFT', action = wezterm.action.SendString '\\\\x1b[13;2u' },`,\n marker: \"mods = 'SHIFT', action = wezterm.action.SendString\",\n },\n {\n id: \"warp\",\n name: \"Warp\",\n how: \"explain\",\n // Corrected twice, and the second correction is the instructive one.\n //\n // It was `unverified`. Then the kitty keyboard protocol turned out to fix the *arrow* chords, so\n // this became `none` — nothing to configure. Measured against a real session, that was wrong for\n // **letters**: ⌥r still arrives as the composed character `®`, because Warp resolves Option to a\n // character before the protocol layer ever sees the key. Pushing `CSI > 3 u` does not change it.\n //\n // So there is one thing to configure after all, and it is a Warp setting rather than a file. What\n // it buys is only the option-*letter* chords: ⌥←/⌥→ and every cmd chord already work without it,\n // because those carry their modifier inside the sequence.\n reason: \"Option is resolved to a character before the keyboard protocol sees it, so ⌥ plus a letter arrives as text like `®` unless Warp is told otherwise\",\n steps: [\n \"Settings → Features → Keys → tick “Left and Right Option Key is Meta”\",\n \"That is only needed for ⌥ plus a *letter*. ⌥ and cmd with arrows already work, and so does shift+⏎\",\n `Every letter chord here has a control-key twin that needs none of this — \\`${BRAND.slug} keys\\` shows exactly what your terminal sends`,\n ],\n },\n {\n id: \"iterm2\",\n name: \"iTerm2\",\n how: \"explain\",\n reason: \"its preferences are a binary plist it rewrites on quit, so an edit made underneath it is discarded\",\n steps: [\n \"Settings → Profiles → Keys → Key Mappings\",\n \"Press +, then press shift and return together to capture the key\",\n \"Set Action to “Send Hex Codes”\",\n \"Enter: 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75\",\n ],\n },\n {\n id: \"apple\",\n name: \"Terminal.app\",\n how: \"explain\",\n reason: \"its key bindings live in the same binary preferences file, and it caches them while running\",\n steps: [\n \"Settings → Profiles → Keyboard\",\n \"Press +, choose Return as the key and tick Shift\",\n \"Set Action to “Send Text” and enter: \\\\033[13;2u\",\n ],\n },\n]\n\n/**\n * Which terminal is running this, from the environment it was given.\n *\n * Order matters. VS Code sets `TERM_PROGRAM=vscode` while its integrated terminal may *also* be running\n * under another emulator's variables, and the innermost one is the one whose key bindings apply. The\n * program-specific variables are therefore checked before the generic `TERM`, which is the only one a\n * multiplexer rewrites.\n */\nexport function detectTerminal(env: Readonly<Record<string, string | undefined>>): TerminalId {\n const program = env.TERM_PROGRAM ?? \"\"\n if (program === \"vscode\") return \"vscode\"\n if (program === \"ghostty\" || env.GHOSTTY_RESOURCES_DIR !== undefined) return \"ghostty\"\n if (env.KITTY_WINDOW_ID !== undefined || env.TERM === \"xterm-kitty\") return \"kitty\"\n if (env.WEZTERM_PANE !== undefined) return \"wezterm\"\n if (program === \"WarpTerminal\") return \"warp\"\n if (program === \"iTerm.app\") return \"iterm2\"\n if (program === \"Apple_Terminal\") return \"apple\"\n return \"unknown\"\n}\n\nexport function recipeFor(id: TerminalId): TerminalRecipe | undefined {\n return RECIPES.find((recipe) => recipe.id === id)\n}\n\n/** Every terminal this command knows, for `--help` and for the \"not this one\" message. */\nexport function knownTerminals(): readonly TerminalRecipe[] {\n return RECIPES\n}\n\n/**\n * Is the binding already installed?\n *\n * Substring rather than an exact line, because a person may have written it differently — a different\n * indent, a comment after it, VS Code's own formatting of the JSON. Reporting \"already configured\" for a\n * hand-written equivalent is right; rewriting it would produce a duplicate binding whose behaviour\n * depends on which the terminal reads last.\n */\nexport function alreadyConfigured(contents: string, recipe: TerminalRecipe): boolean {\n return recipe.marker !== undefined && contents.includes(recipe.marker)\n}\n\n/**\n * The file's new contents.\n *\n * VS Code's `keybindings.json` is an array, so the line goes *inside* it and cannot simply be appended;\n * everything else is a line-oriented config where appending is correct. Both cases keep whatever was\n * there — this never rewrites a file it did not author.\n */\nexport function withBinding(contents: string, recipe: TerminalRecipe): string | undefined {\n const line = recipe.line\n if (line === undefined) return undefined\n if (recipe.id !== \"vscode\") {\n const body = contents.trimEnd()\n return body === \"\" ? `${line}\\n` : `${body}\\n${line}\\n`\n }\n\n // An empty or missing keybindings.json becomes a one-element array. Anything else must be an array\n // literal, and the insert goes after the opening bracket so no trailing-comma question arises.\n const body = contents.trim()\n if (body === \"\" || body === \"[]\") return `[\\n ${line}\\n]\\n`\n const open = body.indexOf(\"[\")\n if (open === -1) return undefined\n const rest = body.slice(open + 1).trimStart()\n // `]` immediately after the bracket means the array only *looked* non-empty (comments, whitespace).\n const separator = rest.startsWith(\"]\") ? \"\" : \",\"\n return `${body.slice(0, open + 1)}\\n ${line}${separator}\\n${body.slice(open + 1)}`\n}\n",
|
|
18
18
|
"/**\n * `keys` — press a chord and see what actually arrived.\n *\n * The instrument this repo did not have. Every previous round of keyboard work was diagnosed by reading\n * Ink's parser and reasoning about what a terminal *probably* sends, which is exactly what CLAUDE.md says\n * not to do — and it is how `⌥r` stayed broken through nine rounds while every test passed: the tests\n * built `KeyState` objects by hand, so they proved the switch and never the delivery.\n *\n * Three layers per keystroke, so a failure names which one is wrong: the bytes the terminal wrote, Ink's\n * reading of them, and the intent this repo's keymap resolved. Paste it into an issue and there is nothing\n * left to guess about.\n */\n\nimport { HarnessError } from \"@dispach/core\"\nimport { ENTER_ALT_SCREEN, EXIT_OK, FALLBACK_COLUMNS } from \"#lib/const\"\nimport { flushOutput, markAltScreen, onExit, restoreTerminal } from \"#lib/exit\"\nimport { negotiateKeyboard } from \"#lib/keyboard\"\nimport { resolveModeFromProcess } from \"#lib/output\"\nimport { screenColumns } from \"#lib/screen\"\nimport { openTap } from \"#lib/stdin-tap\"\nimport { detectTerminal, recipeFor } from \"#lib/terminal\"\n\nexport interface KeysCommandOptions {\n readonly noEnhancedKeys?: boolean\n}\n\nexport async function keysCommand(options: KeysCommandOptions = {}): Promise<number> {\n // A surface that mounts Ink refuses a non-terminal. Without the check the alternate-screen sequence\n // goes into a pipe and Ink's own raw-mode error leaves the command exiting 0 — a failure reporting\n // success, which hard rule 8 exists to prevent. Name the alternative: \"needs a terminal\" on its own\n // is a dead end for somebody scripting.\n const decision = resolveModeFromProcess({ plain: false, json: false, oneShot: false })\n if (decision.mode !== \"rich\") {\n throw new HarnessError({\n code: \"cli_keys_needs_terminal\",\n message: \"The key probe needs a terminal — it has nothing to read on a pipe.\",\n hint: `Not one here (${decision.because}). Run it in the terminal whose keys you want to inspect; there is no scripted form, because the answer is a property of that terminal.`,\n })\n }\n\n const keyboard = negotiateKeyboard(options.noEnhancedKeys)\n const asked = keyboard.kittyKeyboard !== undefined\n const id = detectTerminal(process.env)\n const terminal = recipeFor(id)?.name ?? id\n\n const [{ render }, { createElement }, { KeyProbe }] = await Promise.all([\n import(\"ink\"),\n import(\"react\"),\n import(\"#components/KeyProbe\"),\n ])\n\n let finish: () => void = () => {}\n const closed = new Promise<void>((resolve) => {\n finish = resolve\n })\n\n // Before `render`, for the reason `lib/stdin-tap.ts` gives: `useInput` reports `input: \"\"` for a\n // special key, so a probe built on `input` alone shows no bytes for any arrow, Home, or cmd chord —\n // exactly the keys it exists to diagnose. The same tap also corrects the modifiers, so the probe\n // reports what the chat will actually resolve rather than what Ink said in isolation.\n const tap = openTap()\n onExit(() => {\n tap.close()\n })\n\n markAltScreen()\n process.stdout.write(ENTER_ALT_SCREEN)\n\n const instance = render(\n createElement(KeyProbe, {\n // A pty can report `columns === 0`, which `?? fallback` does not cover.\n columns: screenColumns(process.stdout.columns, FALLBACK_COLUMNS),\n asked,\n terminal,\n takeRaw: tap.takeRaw,\n correctKeys: tap.correct,\n onDone: finish,\n }),\n { exitOnCtrlC: false, ...keyboard },\n )\n onExit(() => instance.unmount())\n await closed\n instance.unmount()\n tap.close()\n restoreTerminal()\n await flushOutput()\n return EXIT_OK\n}\n",
|
|
19
|
-
"/**\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 * 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
|
|
19
|
+
"/**\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",
|
|
20
20
|
"/**\n * Help text, rendered from the command table.\n *\n * Generated rather than written, so a flag the parser honours cannot be missing from the help and\n * a flag the help promises cannot be missing from the parser. A test asserts exactly that.\n */\n\nimport { BRAND } from \"@dispach/core\"\nimport { COMMANDS, flagsFor, GLOBAL_FLAGS } from \"#lib/commands\"\nimport type { CommandSpec, FlagSpec } from \"#lib/schema\"\n\nconst FLAG_COLUMN = 24\nconst ENV_COLUMN = 22\n\nfunction usageLine(command: CommandSpec): string {\n const args = command.args\n .map((arg) => {\n const body = arg.variadic === true ? `${arg.name}...` : arg.name\n return arg.required ? `<${body}>` : `[${body}]`\n })\n .join(\" \")\n return `${BRAND.slug} ${command.name}${args === \"\" ? \"\" : ` ${args}`}`\n}\n\nfunction flagLine(flag: FlagSpec): string {\n const long =\n flag.placeholder === undefined ? `--${flag.name}` : `--${flag.name} <${flag.placeholder}>`\n const forms = flag.short === undefined ? long : `-${flag.short}, ${long}`\n const trailer = flag.defaultHelp === undefined ? \"\" : ` (default ${flag.defaultHelp})`\n return ` ${forms.padEnd(FLAG_COLUMN)}${flag.help}${trailer}`\n}\n\nconst SESSION_KEY_NOTE = `Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound\ndelivery reads the channel back out of the key.`\n\n/**\n * The fixed set an argument accepts, listed rather than described.\n *\n * A command whose first positional is a verb has to enumerate its verbs somewhere a check can see.\n * Before this they lived inside a prose `help` string, so nothing could tell whether the command\n * still accepted what the help claimed — and `daemon` has seven of them.\n */\nfunction choiceLines(command: CommandSpec): readonly string[] {\n const out: string[] = []\n for (const arg of command.args) {\n if (arg.choices === undefined || arg.choices.length === 0) continue\n const width = Math.max(...arg.choices.map((choice) => choice.value.length)) + 2\n out.push(\"\", `${arg.name}:`)\n for (const choice of arg.choices) {\n out.push(` ${choice.value.padEnd(width)}${choice.help}`)\n }\n }\n return out\n}\n\n/** Help for one command, or for the whole tool when `command` is absent. */\nexport function helpText(command?: CommandSpec): string {\n if (command !== undefined) {\n const lines = [\n command.summary,\n \"\",\n \"usage:\",\n ` ${usageLine(command)} [flags]`,\n ...choiceLines(command),\n \"\",\n \"flags:\",\n ...flagsFor(command).map(flagLine),\n ]\n if (command.flags.some((flag) => flag.name === \"session\")) lines.push(\"\", SESSION_KEY_NOTE)\n return `${lines.join(\"\\n\")}\\n`\n }\n\n const width = Math.max(...COMMANDS.map((command) => usageLine(command).length)) + 2\n return `${[\n `${BRAND.name} — a lightweight, model-agnostic agent runtime`,\n \"\",\n \"usage:\",\n ...COMMANDS.map((command) => ` ${usageLine(command).padEnd(width)}${command.summary}`),\n ` ${BRAND.slug} --version`,\n ` ${BRAND.slug} --help`,\n \"\",\n `Per-command flags: ${BRAND.slug} <command> --help`,\n \"\",\n \"global flags:\",\n ...GLOBAL_FLAGS.map(flagLine),\n \"\",\n SESSION_KEY_NOTE,\n \"\",\n \"environment:\",\n ` ${`${BRAND.envPrefix}BRAND`.padEnd(ENV_COLUMN)}rebrand every derived path, env prefix, and apiVersion`,\n ` ${\"NO_COLOR\".padEnd(ENV_COLUMN)}set to anything to force plain output`,\n ` ${\"DEBUG\".padEnd(ENV_COLUMN)}print stack traces on failure`,\n ].join(\"\\n\")}\\n`\n}\n",
|
|
21
21
|
"/**\n * Silence the runtime warnings this project has already decided about, and nothing else.\n *\n * Under Node every command printed two lines of Node's own noise into the middle of its output:\n *\n * ```\n * milo — running\n * state running · pid 14922 up 24s\n *\n * (node:30494) ExperimentalWarning: SQLite is an experimental feature and might change at any time\n * (Use `node --trace-warnings ...` to show where the warning was created)\n * ```\n *\n * That warning is true, unavoidable and *already answered*: `node:sqlite` is a deliberate soft-compat\n * target with a documented adapter (`store/sqlite/driver.ts`), CI runs the whole core suite under it,\n * and the six behavioural divergences from `bun:sqlite` are enumerated in that file. Nobody running\n * the binary learns anything from it. It is the same shape as a `trust: \"trusted\"` declaration with\n * no `trustReason`: **a warning present for every correct run is a warning nobody reads**, and its\n * cost is that it trains the eye to skip the region of the screen where a real warning would appear.\n *\n * Two things keep this from becoming a way to lose warnings that matter.\n *\n * **The list is specific and each entry carries its reason.** Not \"drop every `ExperimentalWarning`\" —\n * the next experimental API this CLI starts depending on should be loud, because that is news. An\n * entry here is a claim that someone looked at this exact warning and accepted it.\n *\n * **`--trace-warnings` disables the whole mechanism.** Somebody passing it is debugging warnings, and\n * a filter that hides one from the person who explicitly asked to see them is a filter that wastes an\n * afternoon.\n *\n * Wrapping `process.emitWarning` rather than replacing the `warning` listener is deliberate: the\n * listener route means reimplementing Node's `(node:PID) [CODE] Name: message` format and its\n * printed-once `--trace-warnings` hint, and a hand-rolled copy of those drifts from the real thing\n * silently. Wrapping the emitter leaves every warning we do *not* suppress formatted by Node itself.\n *\n * What makes the filter effective is the *call site*, not import order: `openDatabase` reaches\n * `node:sqlite` through a dynamic `import()` inside the function, so the warning fires when a store\n * opens rather than when a module loads, and `index.ts` installs this well before that. The module\n * still imports nothing — pinned by a test — so it stays movable to the front of the graph if an\n * eager `node:sqlite` import ever changes that, and so it can never be the thing that pulls core in\n * early.\n */\n\ninterface AcceptedWarning {\n readonly name: string\n /** Matched against the warning text with `includes`, so it is a stable substring, not a regex. */\n readonly contains: string\n /** Why this one is accepted. An entry without a reason is an entry nobody can review. */\n readonly because: string\n}\n\n/**\n * Warnings this project has looked at and accepted. Adding a line is a decision; it belongs in a\n * review alongside whatever made the warning appear.\n */\nexport const ACCEPTED_WARNINGS: readonly AcceptedWarning[] = [\n {\n name: \"ExperimentalWarning\",\n contains: \"SQLite is an experimental feature\",\n because:\n \"node:sqlite is a declared soft-compat target with an adapter and a dual-runtime test suite; the experimental status is the reason the adapter exists, not news about this run.\",\n },\n]\n\n/**\n * Whether a warning is one of the accepted set. Pure, so the table above can be asserted without\n * emitting anything into a test runner's output.\n */\nexport function isAcceptedWarning(name: string, message: string): boolean {\n return ACCEPTED_WARNINGS.some(\n (accepted) => accepted.name === name && message.includes(accepted.contains),\n )\n}\n\n/**\n * How the process was invoked. Taken as an argument rather than read here so a test does not depend\n * on the flags its own runner happened to be started with — the filter would silently not install\n * under a `--trace-warnings` test run, and the failure would look like a broken filter.\n */\nexport interface WarningEnv {\n readonly execArgv: readonly string[]\n readonly nodeOptions: string | undefined\n}\n\n/** `--trace-warnings` anywhere in the invocation turns the filter off entirely. */\nexport function tracingWarnings(env: WarningEnv): boolean {\n const flag = \"--trace-warnings\"\n return env.execArgv.includes(flag) || (env.nodeOptions ?? \"\").includes(flag)\n}\n\n/** The real emitter, kept so the wrap can be undone and so a second install is a no-op. */\nlet original: typeof process.emitWarning | undefined\n\n/**\n * Install the filter. Idempotent — wrapping the wrapper would leave the process one frame deeper for\n * every call, and nothing would report it.\n */\nexport function quietAcceptedWarnings(\n env: WarningEnv = { execArgv: process.execArgv, nodeOptions: process.env.NODE_OPTIONS },\n): void {\n if (original) return\n if (tracingWarnings(env)) return\n\n const emit = process.emitWarning\n original = emit\n process.emitWarning = (warning: string | Error, ...rest: unknown[]): void => {\n const name = typeof warning === \"string\" ? nameFrom(rest) : warning.name\n const message = typeof warning === \"string\" ? warning : warning.message\n if (isAcceptedWarning(name, message)) return\n Reflect.apply(emit, process, [warning, ...rest])\n }\n}\n\n/**\n * `process.emitWarning(\"text\", \"ExperimentalWarning\", code?)` puts the name in the second argument;\n * an omitted one means Node's default of `Warning`.\n */\nfunction nameFrom(rest: readonly unknown[]): string {\n const type = rest[0]\n return typeof type === \"string\" ? type : \"Warning\"\n}\n\n/** Tests only: put the real emitter back, so each case installs into a fresh process state. */\nexport function resetForTests(): void {\n if (!original) return\n process.emitWarning = original\n original = undefined\n}\n",
|
|
22
22
|
"/**\n * `memory` — search what the agent remembers, or rebuild the index from the files.\n *\n * Both actions are questions about the **index**, not about the files: the files are canonical and a\n * person can already read them with `cat`. What they cannot see is what the retriever would return for\n * a given question, which is the only thing that decides whether a fact reaches the model.\n *\n * ## Why search does not apply the threshold\n *\n * A turn applies `memory.threshold` and injects what clears it. A person running this is usually asking\n * the opposite question — *why did it not recall that?* — and a floor that hid the near-misses would\n * make the command useless for exactly that. So everything ranked is printed, with the ones below the\n * floor marked and excluded from the count. `--all` is therefore about *widening the candidate set*,\n * not about revealing something withheld.\n *\n * The carried file is included for the same reason. A note saved a minute ago is still in `MEMORY.md`\n * and is deliberately excluded from slot 7 — so \"still in MEMORY.md, which is why it is not under\n * Remembered\" is a real and useful answer that a search hiding it could never give.\n *\n * Neither Ink nor React is imported here: this is a report, and the lazy-Ink boundary is what keeps\n * every non-interactive command under a tenth of a second.\n */\n\nimport { Runtime } from \"@dispach/core\"\nimport { ambientEnv } from \"#lib/ambient\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { BUILT_IN_PLUGINS, CHANNELS, scriptRunner, TOOL_PROVIDERS } from \"#lib/providers\"\nimport { keyValue } from \"#lib/render\"\nimport { storePath } from \"#lib/sandbox\"\nimport type { MemoryOptions } from \"#lib/schema\"\n\n/** Enough of a passage to recognize it, on one line. */\nconst PREVIEW_CHARS = 96\n\nexport async function memoryCommand(options: MemoryOptions): Promise<number> {\n const runtime = await Runtime.create({\n agents: [options.manifestPath],\n // The sandbox store — the same one `run` writes to, or this searches an index nothing built.\n store: options.store ?? storePath(),\n toolProviders: TOOL_PROVIDERS,\n builtInPlugins: BUILT_IN_PLUGINS,\n scriptRunner: scriptRunner(),\n channels: CHANNELS,\n env: ambientEnv([options.manifestPath]),\n })\n\n try {\n const agent = runtime.list()[0]\n if (agent === undefined) throw new Error(\"The manifest produced no agent.\")\n\n if (options.action === \"rebuild\") {\n const report = await agent.rebuildMemory()\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify(report, null, 2)}\\n`)\n return EXIT_OK\n }\n process.stdout.write(\n keyValue([\n { label: \"passages\", value: String(report.passages) },\n { label: \"files read\", value: String(report.indexed.length) },\n // Named separately from the files because they answer a different question. A\n // rebuild re-indexes conversations whether or not anyone asked, since `clear` wipes\n // both namespaces — so the count is how the person finds out it happened.\n {\n label: \"conversations\",\n value:\n report.sessions.length === 0\n ? \"none indexed — memory.includeHistory is off, or there are no sessions yet\"\n : String(report.sessions.length),\n },\n {\n label: \"dropped\",\n value: report.dropped.length === 0 ? \"\" : report.dropped.join(\", \"),\n },\n ]),\n )\n // Named rather than counted: after a rebuild every file was read, so a list of them is the\n // information — and an empty one means the memory directory has nothing in it yet.\n process.stdout.write(\n report.indexed.length === 0 && report.sessions.length === 0\n ? \"\\nNothing to index. Memory files are written by `memory_write` and by hand, and conversations are indexed at the end of each turn.\\n\"\n : `\\nRead: ${[...report.indexed, ...report.sessions].join(\", \")}\\n`,\n )\n return EXIT_OK\n }\n\n const query = options.query ?? \"\"\n if (query.trim() === \"\") {\n process.stderr.write(\n \"memory search needs something to search for.\\n\" +\n ' hint: quote a phrase — `memory search <agent> \"the deploy pipeline\"`. An empty query cannot rank anything, which is different from finding nothing.\\n',\n )\n return EXIT_FAILURE\n }\n\n const result = await agent.searchMemory({\n query,\n // `--all` widens the candidate set rather than lowering a floor; the floor is never applied\n // here at all.\n limit: options.limit ?? 10,\n })\n\n const above = result.hits.filter((hit) => hit.score >= result.threshold)\n const shown = options.all === true ? result.hits : above\n\n if (options.json === true) {\n process.stdout.write(\n `${JSON.stringify(\n {\n query,\n corpus: result.corpus,\n threshold: result.threshold,\n carried: result.carried ?? null,\n hits: shown.map((hit) => ({\n source: hit.passage.source,\n at: hit.passage.at,\n score: hit.score,\n lexical: hit.lexical,\n coverage: hit.coverage,\n tokens: hit.tokens,\n wouldInject: hit.score >= result.threshold,\n carried: hit.passage.source === result.carried,\n text: hit.passage.text,\n })),\n },\n null,\n 2,\n )}\\n`,\n )\n return EXIT_OK\n }\n\n process.stdout.write(\n keyValue([\n {\n label: \"corpus\",\n value: `${result.corpus} passage${result.corpus === 1 ? \"\" : \"s\"}`,\n },\n { label: \"threshold\", value: result.threshold.toFixed(2) },\n { label: \"above it\", value: String(above.length) },\n ]),\n )\n\n if (result.corpus === 0) {\n process.stdout.write(\n \"\\nNothing indexed. `memory_write` fills the carried file, and eviction moves older notes into the memory directory.\\n\",\n )\n return EXIT_OK\n }\n if (shown.length === 0) {\n process.stdout.write(\n `\\nNothing ${options.all === true ? \"matched\" : `scored above ${result.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.\\n`,\n )\n return EXIT_OK\n }\n\n // `score` and `lexical` both, because a ranking nobody can explain is a ranking nobody trusts:\n // the pair distinguishes \"retrieved because it is about your question\" from \"retrieved because\n // it is recent\". A passage below the threshold is marked rather than hidden — the question this\n // command exists for is usually \"why was that *not* recalled\".\n const sourceWidth = Math.max(6, ...shown.map((hit) => label(hit, result.carried).length))\n process.stdout.write(\n `\\n${pad(\"SCORE\", 6)} ${pad(\"LEXICAL\", 7)} ${pad(\"COVER\", 5)} ${pad(\"SOURCE\", sourceWidth)} ${pad(\"LEARNED\", 10)} PASSAGE\\n`,\n )\n for (const hit of shown) {\n const mark = hit.score >= result.threshold ? \" \" : \"·\"\n process.stdout.write(\n `${pad(hit.score.toFixed(3), 6)} ${pad(hit.lexical.toFixed(3), 7)} ` +\n `${pad(hit.coverage.toFixed(2), 5)} ` +\n `${pad(label(hit, result.carried), sourceWidth)} ${pad(hit.passage.at.slice(0, 10), 10)} ` +\n `${mark}${preview(hit.passage.text)}\\n`,\n )\n }\n\n if (options.all === true && above.length < shown.length) {\n process.stdout.write(\n `\\n${shown.length - above.length} shown below the threshold; a turn would not inject those.\\n`,\n )\n }\n if (\n result.carried !== undefined &&\n shown.some((h) => h.passage.source === result.carried)\n ) {\n process.stdout.write(\n `\\n${result.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.\\n`,\n )\n }\n return EXIT_OK\n } finally {\n await runtime.stop(\"cli-exit\")\n }\n}\n\nfunction preview(text: string): string {\n const flat = text.replace(/\\s+/g, \" \").trim()\n return flat.length <= PREVIEW_CHARS ? flat : `${flat.slice(0, PREVIEW_CHARS - 1)}…`\n}\n\nfunction pad(text: string, width: number): string {\n return text.length >= width ? text : text + \" \".repeat(width - text.length)\n}\n\n/** The source, marked when it is the file already carried in every prompt. */\nfunction label(\n hit: { readonly passage: { readonly source: string } },\n carried: string | undefined,\n): string {\n return hit.passage.source === carried ? `${hit.passage.source} *` : hit.passage.source\n}\n",
|
|
@@ -27,11 +27,11 @@
|
|
|
27
27
|
"/**\n * What removing an agent would actually take, and what should stop it.\n *\n * Facts in, a listing and an ordered plan out. Gathering the facts needs the filesystem, the store and\n * `launchctl`; deciding what to do with them needs none of that — and the interesting cases here are\n * exactly the ones that are painful to produce on a real machine: a manifest id shared by two\n * directories, a live lease, an installed service, rows nobody claims. A table beats breaking a\n * sandbox nine different ways.\n *\n * ## Why the listing and the deletion come from one place\n *\n * The confirmation is a listing plus the agent's name typed back, and the listing *is* `--dry-run` —\n * one code path, so what a dry run shows is what a real run does. Deriving the two separately is how a\n * confirmation comes to describe something other than what happens, which for an irreversible command\n * is the worst available failure: the person read it, agreed to it, and got something else.\n *\n * No `node:*`, no `process`. This module is on the boundaries test's `PURE` list.\n */\n\nimport type { AgentFootprint } from \"@dispach/core\"\nimport { bytes, keyValue, type Row } from \"#lib/render\"\n\nexport interface Finding {\n readonly code: string\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\n/** A file the removal would delete, and what it costs to keep. */\nexport interface FileFacts {\n readonly path: string\n readonly bytes: number\n}\n\nexport interface RemovalFacts {\n /** The directory name — what was typed, and what the confirmation asks to be typed back. */\n readonly ref: string\n /** The manifest id. Keys the store, the logs and the service label; may differ from `ref`. */\n readonly agentId: string\n readonly dir: string\n /** Files under `dir`, counted and summed. Empty when the directory could not be read. */\n readonly files: { readonly count: number; readonly bytes: number }\n /** What the store holds for `agentId`. */\n readonly footprint: AgentFootprint\n /** Log files that exist. Absent entries are simply not listed. */\n readonly logs: readonly FileFacts[]\n /**\n * Other sandbox directories whose manifest id is also `agentId`.\n *\n * The refusal case. Store rows, logs and the service label are all keyed by id, so removing this\n * agent's *data* would remove theirs.\n */\n readonly sharesIdWith: readonly string[]\n /** A live process holding the lease, if any. */\n readonly running?: { readonly pid: number; readonly mode: string }\n /** The launchd label, when a service is installed under it. */\n readonly service?: string\n /** Only the directory goes; the store, the logs and the service are left alone. */\n readonly filesOnly: boolean\n}\n\n/**\n * What must not be removed, and why.\n *\n * **A shared manifest id blocks, rather than degrading to a partial removal.** Deleting store rows by\n * `agent_id` when two directories answer to that id destroys the other agent's conversations and\n * memory, and reports success — the silent-loss shape hard rule 8 exists to prevent. Falling back to\n * files-only automatically was the alternative and is worse in a quieter way: it leaves rows that\n * `agentIds` will list forever as belonging to nobody, having told the person their agent was gone.\n *\n * `--files-only` clears it, because then the id is not being acted on at all.\n */\nexport function removalFindings(facts: RemovalFacts): readonly Finding[] {\n if (facts.filesOnly || facts.sharesIdWith.length === 0) return []\n const others = facts.sharesIdWith.join(\", \")\n return [\n {\n code: \"cli_agent_id_shared\",\n message: `\"${facts.ref}\" has the manifest id \"${facts.agentId}\", which is also used by ${others} — removing its data would take that agent's sessions and memory too.`,\n hint: `Change one manifest's id and run \\`memory rebuild\\` for it, or pass --files-only to delete just the ${facts.ref} directory and leave the store alone.`,\n },\n ]\n}\n\nexport type StepKind = \"stop\" | \"service\" | \"store\" | \"logs\" | \"directory\"\n\nexport interface Step {\n readonly kind: StepKind\n /** What this step will do, in the imperative. Shown before it happens. */\n readonly detail: string\n}\n\n/**\n * The steps, in the order they must run.\n *\n * The order is not cosmetic:\n *\n * 1. **Stop first.** A process holding the lease is still writing sessions, and a graceful stop is the\n * only path that runs `provider.stop()` — the sole reaper for backgrounded `exec` children. Deleting\n * a running agent's directory would leave a live process serving from a manifest that no longer\n * exists, with orphaned shells behind it.\n * 2. **Service next.** `disable` persists across boots and `bootout` does not, so both are needed: a\n * label left enabled comes back at the next login and fails forever against a deleted manifest.\n * 3. **Store, then logs, then the directory last.** Every earlier step is recoverable — an agent whose\n * rows are gone still loads and still runs. The directory is the only irreplaceable part, so it goes\n * when nothing else can fail; the reverse order leaves a manifest-less agent whose data is\n * unreachable and whose name nothing can name.\n */\nexport function removalSteps(facts: RemovalFacts): readonly Step[] {\n const steps: Step[] = []\n if (facts.running !== undefined) {\n steps.push({\n kind: \"stop\",\n detail: `stop pid ${facts.running.pid} (${facts.running.mode}) — gracefully, so anything it left running in the background is reaped`,\n })\n }\n if (!facts.filesOnly && facts.service !== undefined) {\n steps.push({\n kind: \"service\",\n detail: `disable and unload ${facts.service}`,\n })\n }\n if (!facts.filesOnly) {\n const f = facts.footprint\n steps.push({\n kind: \"store\",\n detail: `delete ${plural(f.sessions, \"conversation\")}, ${plural(f.messages, \"message\")}, ${plural(f.passages, \"memory passage\")}`,\n })\n if (facts.logs.length > 0) {\n steps.push({ kind: \"logs\", detail: `delete ${plural(facts.logs.length, \"log file\")}` })\n }\n }\n steps.push({ kind: \"directory\", detail: `delete ${facts.dir}` })\n return steps\n}\n\n/**\n * The listing shown before anything happens, and printed on its own by `--dry-run`.\n *\n * Every row is a number somebody might want to stop over. A zero row is still shown where its absence\n * would be ambiguous — `service not installed` is information, and omitting it invites the reading\n * that a service was quietly left behind.\n */\nexport function renderRemoval(facts: RemovalFacts): string {\n const f = facts.footprint\n const rows: Row[] = [\n {\n label: \"directory\",\n value: `${facts.dir}`,\n note: `${plural(facts.files.count, \"file\")}, ${bytes(facts.files.bytes)}`,\n },\n ]\n if (facts.agentId !== facts.ref) {\n // Worth its own row whenever they differ: everything except the directory is keyed by the id,\n // so a person who only knows the ref is reading a listing about a name they have not seen.\n rows.push({\n label: \"manifest id\",\n value: facts.agentId,\n note: \"keys the store, logs and service\",\n })\n }\n if (facts.filesOnly) {\n rows.push({\n label: \"keeping\",\n value: `${plural(f.sessions, \"conversation\")}, ${plural(f.passages, \"memory passage\")}, and the logs`,\n note: \"--files-only\",\n })\n } else {\n rows.push(\n {\n label: \"sessions\",\n value: `${plural(f.sessions, \"conversation\")}, ${plural(f.messages, \"message\")}, ${plural(f.turns, \"turn\")}`,\n },\n {\n label: \"memory\",\n value: `${plural(f.passages, \"passage\")} from ${plural(f.memorySources, \"source\")}`,\n },\n {\n label: \"outbox\",\n value:\n f.outbox === 0\n ? \"nothing queued\"\n : `${plural(f.outbox, \"delivery\")}${f.outboxPending === 0 ? \"\" : `, ${f.outboxPending} not yet sent`}`,\n // A pending delivery is a reply somebody is waiting for, and removal abandons it.\n ...(f.outboxPending === 0 ? {} : { note: \"abandoned\" }),\n },\n {\n label: \"schedules\",\n value: f.schedules === 0 ? \"none\" : plural(f.schedules, \"schedule\"),\n // A schedule is the one thing here that would keep *firing* if it survived, so its\n // removal is the part of this listing least likely to be regretted and most likely\n // to be missed if it were absent.\n ...(f.schedules === 0 ? {} : { note: \"stops firing\" }),\n },\n {\n label: \"logs\",\n value:\n facts.logs.length === 0\n ? \"none\"\n : `${plural(facts.logs.length, \"file\")}, ${bytes(facts.logs.reduce((n, l) => n + l.bytes, 0))}`,\n },\n { label: \"service\", value: facts.service ?? \"not installed\" },\n )\n }\n rows.push({\n label: \"running\",\n value:\n facts.running === undefined ? \"no\" : `pid ${facts.running.pid} (${facts.running.mode})`,\n })\n return keyValue(rows)\n}\n\n/** An agent id with rows or logs in the sandbox that no directory claims. */\nexport interface Orphan {\n readonly agentId: string\n readonly footprint: AgentFootprint\n readonly logs: readonly FileFacts[]\n}\n\n/**\n * The listing for `--prune`.\n *\n * Separate from `renderRemoval` because it answers a different question — not \"what does this agent\n * own\" but \"what is left over\" — and because an orphan has no directory, no ref and no manifest, so\n * most of the other rows would be empty or a lie.\n */\nexport function renderOrphans(orphans: readonly Orphan[]): string {\n if (orphans.length === 0) return \"\"\n return orphans\n .map((orphan) => {\n const f = orphan.footprint\n const parts: string[] = []\n if (f.sessions > 0) {\n parts.push(\n `${plural(f.sessions, \"conversation\")}, ${plural(f.messages, \"message\")}`,\n )\n }\n if (f.passages > 0) parts.push(`${plural(f.passages, \"memory passage\")}`)\n if (f.outbox > 0) parts.push(`${plural(f.outbox, \"queued delivery\")}`)\n if (f.schedules > 0) parts.push(`${plural(f.schedules, \"schedule\")}`)\n if (f.lease) parts.push(\"a stale lease\")\n if (orphan.logs.length > 0) {\n parts.push(\n `${plural(orphan.logs.length, \"log file\")}, ${bytes(orphan.logs.reduce((n, l) => n + l.bytes, 0))}`,\n )\n }\n // Never empty: an orphan is only listed because *something* references the id, so an empty\n // parts list would mean the caller found it by some route this cannot describe.\n return ` ${orphan.agentId} ${parts.length === 0 ? \"rows with no detail\" : parts.join(\" · \")}`\n })\n .join(\"\\n\")\n}\n\nfunction plural(count: number, noun: string): string {\n return `${count} ${noun}${count === 1 ? \"\" : \"s\"}`\n}\n",
|
|
28
28
|
"/**\n * `stop [agent]` — the switch that turns everything off.\n *\n * Every other way to stop an agent needs you to know what is running first: `daemon stop` needs the\n * label, ctrl-c needs the terminal that started it, `kill` needs the pid. This one needs nothing —\n * it finds the services *and* the loose `serve` you left in a tab three days ago, stops both, and\n * says what it stopped. That is the whole design brief: a person reaching for this is not in a\n * position to go looking.\n *\n * **Stopped means stopped.** A service is disabled as well as unloaded, because `bootout` alone\n * comes back at the next login and \"I stopped it and it was running again after lunch\" is the exact\n * failure a safety switch may not have. Reversible, loudly: the output names `daemon start`.\n *\n * **SIGTERM first, always.** A graceful stop is the only path that runs `provider.stop()`, which\n * reaps the child processes `exec` backgrounded — so killing hard to be thorough is how you end up\n * with the orphans that took this machine to a load average of 351. SIGKILL is the last resort,\n * after a grace period, and it says out loud what may have been left behind.\n *\n * ## Naming an agent and naming nothing are different commands\n *\n * They were the same command with a filter until one process could host several agents, at which\n * point the filter became wrong: killing the process that holds `milo`'s lease takes `alpha` and\n * `beta` down with it. So:\n *\n * - **`stop <agent>`** writes that agent off in the store and asks its host to drop it. The host\n * keeps running, every other agent it holds keeps running, and the row is what makes it stay off\n * across a restart. It does **not** touch any service: a service hosting three agents is not\n * something to unload because one of them was switched off.\n * - **`stop`** is unchanged — the whole host goes down, services disabled so they stay down, and\n * nothing per-agent is written. That asymmetry is deliberate: `daemon start` should bring back\n * exactly what was running, and an agent stopped by name should still be off when it does.\n *\n * The per-agent path falls back to signalling the process when the lease carries no address, which\n * is a `run` REPL or an embedded runtime — real states that serve no HTTP, and the only ones where\n * \"stop this agent\" and \"stop that process\" are still the same thing.\n */\n\nimport { homedir } from \"node:os\"\nimport { BRAND, HarnessError, processAlive, readManifestHeader, SqliteStore } from \"@dispach/core\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { labelFor } from \"#lib/launchd\"\nimport { liveHostOf, postToHost, writeAgentState } from \"#lib/lifecycle\"\nimport { bullet, keyValue, type Row } from \"#lib/render\"\nimport { storePath } from \"#lib/sandbox\"\nimport { type Exec, resolveServiceManager, type ServiceManager } from \"#lib/service\"\n\n/** How long a process gets to shut down cleanly before the last resort. */\nconst GRACE_MS = 12_000\nconst POLL_MS = 250\n\nexport interface StopOptions {\n /**\n * Absolute manifest path. Omitted means the whole host — see the file comment.\n *\n * Present and absent are two different commands rather than one with a filter: naming an agent\n * writes the durable switch and asks its host to drop it, and naming nothing takes the host\n * down. Conflating them is how stopping one agent stopped three.\n */\n readonly manifestPath?: string\n /** Why, recorded on the row and shown wherever the agent is reported as off. */\n readonly reason?: string\n /** The database to read leases and state from. Defaults to the sandbox's. */\n readonly store?: string\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}\n\ninterface Target {\n readonly agentId: string\n /** A LaunchAgent exists for it. */\n readonly service: boolean\n /** A live process holds its runtime lease. */\n readonly pid?: number\n readonly mode?: string\n}\n\ntype Outcome = Target & {\n readonly stopped: boolean\n /** Present when the graceful stop ran out of time. */\n readonly forced?: boolean\n readonly note: string\n}\n\nexport async function stopCommand(options: StopOptions): Promise<number> {\n if (options.manifestPath !== undefined) {\n return await stopOneAgent(options, options.manifestPath)\n }\n return await stopEverything(options)\n}\n\n/**\n * Switch one agent off and drop it from its host.\n *\n * The state is written **first**, and the order matters: a host told to drop an agent before the row\n * exists would come back hosting it at the next restart with nobody having asked, which is the\n * failure the row exists to prevent. This way round, a host that cannot be reached leaves the agent\n * marked off, and the next start honours it — so the command's promise holds even when the request\n * does not land.\n */\nasync function stopOneAgent(options: StopOptions, manifestPath: string): Promise<number> {\n const agentId = agentIdOf(manifestPath)\n const notes: string[] = []\n\n if (options.dryRun === true) {\n const host = await liveHostOf(agentId, options.store)\n process.stdout.write(\n `would stop 1 agent:\\n${bullet(\n `${agentId} — ${\n host === undefined\n ? \"not running; would be switched off for the next start\"\n : host.baseUrl === undefined\n ? `pid ${host.pid} (${host.mode}), which serves no HTTP — would be signalled`\n : `pid ${host.pid} (${host.mode}) at ${host.baseUrl}, which would drop it and keep serving`\n }`,\n )}\\n`,\n )\n return EXIT_OK\n }\n\n await writeAgentState(agentId, false, options.reason, options.store)\n notes.push(\"switched off for the next start\")\n\n const host = await liveHostOf(agentId, options.store)\n let stopped = true\n if (host === undefined) {\n notes.push(\"nothing was running\")\n } else if (host.baseUrl === undefined) {\n // A `run` REPL or an embedded runtime: no HTTP to ask, and stopping the agent really is\n // stopping the process, because that process is hosting exactly this conversation.\n const graceful = await signalAndWait(host.pid, \"SIGTERM\")\n stopped = graceful || (await signalAndWait(host.pid, \"SIGKILL\", true))\n notes.push(\n graceful\n ? `pid ${host.pid} stopped cleanly`\n : stopped\n ? `pid ${host.pid} had to be killed`\n : `pid ${host.pid} would not stop — check it by hand`,\n )\n } else {\n const reply = await postToHost(\n host,\n `/v1/agents/${encodeURIComponent(agentId)}/stop`,\n options.reason === undefined ? {} : { reason: options.reason },\n manifestPath,\n )\n if (reply.ok) {\n notes.push(`pid ${host.pid} dropped it and kept serving`)\n } else if (reply.status === 409) {\n // A turn is running. The row is already written, so the agent is off at the next start\n // either way — this is the one case where the command reports partial success, because\n // claiming it stopped while a turn is mid-generation would be a lie.\n stopped = false\n notes.push(reply.detail ?? \"a turn is running\")\n } else if (reply.status === 401) {\n stopped = false\n notes.push(\n `pid ${host.pid} refused the request — set ${BRAND.envPrefix}API_TOKEN to the server's token`,\n )\n } else {\n stopped = false\n notes.push(\n `pid ${host.pid} at ${host.baseUrl} could not be reached${\n reply.detail === undefined ? \"\" : `: ${reply.detail}`\n }`,\n )\n }\n }\n\n const outcome: Outcome = {\n agentId,\n service: false,\n ...(host === undefined ? {} : { pid: host.pid, mode: host.mode }),\n stopped,\n note: notes.join(\" · \"),\n }\n\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify({ stopped: [outcome] }, null, 2)}\\n`)\n } else {\n process.stdout.write(\n `${keyValue([\n {\n label: agentId,\n value: stopped ? \"stopped\" : \"NOT FULLY STOPPED\",\n note: outcome.note,\n },\n ])}\\n`,\n )\n process.stdout.write(\n `\\nStays off across restarts. \\`${BRAND.slug} start ${agentId}\\` switches it back on.\\n`,\n )\n }\n return stopped ? EXIT_OK : EXIT_FAILURE\n}\n\nasync function stopEverything(options: StopOptions): Promise<number> {\n const platform = options.platform ?? process.platform\n // Only launchd is managed, but the lease half works everywhere — a `serve` in a terminal is a\n // process with a pid on any platform, and refusing to stop it because this is not macOS would\n // make the safety switch useless exactly where there is no service manager to fall back on.\n const manager =\n platform === \"darwin\"\n ? resolveServiceManager(platform, {\n home: homedir(),\n uid: process.getuid?.() ?? 0,\n envPrefix: BRAND.envPrefix,\n ...(options.exec === undefined ? {} : { exec: options.exec }),\n })\n : undefined\n\n // No filter any more: naming an agent takes the per-agent path above, and this one is the\n // whole host. A `stop <agent>` that unloaded a service hosting three agents would be the\n // failure 16.2a's shared process introduced.\n const targets = await findTargets(manager, options.store)\n\n if (targets.length === 0) {\n process.stdout.write(\n options.json === true\n ? `${JSON.stringify({ stopped: [] })}\\n`\n : \"Nothing is running — no service is installed and no process holds an agent.\\n\",\n )\n // Zero. For a command whose job is to reach a state, already being in it is success.\n return EXIT_OK\n }\n\n if (options.dryRun === true) {\n process.stdout.write(\n `would stop ${targets.length} ${targets.length === 1 ? \"agent\" : \"agents\"}:\\n${targets\n .map((target) => bullet(describe(target)))\n .join(\"\\n\")}\\n`,\n )\n return EXIT_OK\n }\n\n const outcomes: Outcome[] = []\n for (const target of targets) outcomes.push(await stopOne(target, manager))\n\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify({ stopped: outcomes }, null, 2)}\\n`)\n } else {\n const rows: Row[] = outcomes.map((outcome) => ({\n label: outcome.agentId,\n value: outcome.stopped ? \"stopped\" : \"STILL RUNNING\",\n note: outcome.note,\n }))\n process.stdout.write(`${keyValue(rows)}\\n`)\n\n if (outcomes.some((outcome) => outcome.service && outcome.stopped)) {\n process.stdout.write(\n `\\nServices are disabled as well as unloaded, so they stay stopped across a reboot.\\nStart one again with \\`${BRAND.slug} daemon start <agent>\\`.\\n`,\n )\n }\n if (outcomes.some((outcome) => outcome.forced === true)) {\n process.stdout.write(\n `\\nSomething had to be killed rather than asked. A forced stop skips the runtime's own\\ncleanup, so a command the agent had left running in the background may still be alive —\\n\\`ps\\` will show it if so.\\n`,\n )\n }\n }\n\n return outcomes.every((outcome) => outcome.stopped) ? EXIT_OK : EXIT_FAILURE\n}\n\n/**\n * Everything that could be running, from both sources.\n *\n * Two sources because neither is complete. `launchctl` knows about installed services and nothing\n * about the `serve` you started by hand; the lease table knows about any live process and nothing\n * about a service that is installed but currently down. A safety switch that consulted one of them\n * would leave the other running and report success.\n */\nasync function findTargets(\n manager: ServiceManager | undefined,\n storeFile?: string,\n): Promise<readonly Target[]> {\n const prefix = `${BRAND.slug}.agent.`\n const byId = new Map<string, Target>()\n\n for (const label of manager?.labels(prefix) ?? []) {\n const agentId = label.slice(prefix.length)\n byId.set(agentId, { agentId, service: true })\n }\n\n try {\n const store = await SqliteStore.open({ path: storeFile ?? storePath() })\n for (const lease of await store.leases.all()) {\n // Not this process, and not a row whose process is already gone — a stale lease is not\n // something to stop, and reporting it as one would make the command lie about its work.\n if (lease.pid === process.pid || !processAlive(lease.pid)) continue\n byId.set(lease.agentId, {\n agentId: lease.agentId,\n service: byId.get(lease.agentId)?.service === true,\n pid: lease.pid,\n mode: lease.mode,\n })\n }\n await store.close()\n } catch {\n // No store yet means nothing has ever run. Not an error for this command.\n }\n\n return [...byId.values()].sort((a, b) => a.agentId.localeCompare(b.agentId))\n}\n\nasync function stopOne(target: Target, manager: ServiceManager | undefined): Promise<Outcome> {\n const notes: string[] = []\n\n // The service first. Unloading it sends SIGTERM to the process itself, so doing this before the\n // direct signal avoids racing launchd's own restart policy — and disabling means it will not be\n // back at the next login.\n if (target.service && manager !== undefined) {\n try {\n manager.stop(labelFor(BRAND.slug, target.agentId))\n notes.push(\"service disabled and unloaded\")\n } catch (error) {\n notes.push(\n `service could not be unloaded: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n }\n\n if (target.pid === undefined) {\n return { ...target, stopped: true, note: notes.join(\" · \") || \"no process was running\" }\n }\n\n // Already gone, most likely because unloading the service took it with it.\n if (!processAlive(target.pid)) {\n return { ...target, stopped: true, note: notes.join(\" · \") || `pid ${target.pid} exited` }\n }\n\n const graceful = await signalAndWait(target.pid, \"SIGTERM\")\n if (graceful) {\n notes.push(`pid ${target.pid} stopped cleanly`)\n return { ...target, stopped: true, note: notes.join(\" · \") }\n }\n\n // Last resort, and by process *group* — `sh -c \"a | b | c\"` killed by pid orphans two of three,\n // which is the shape decision 4.88 was written about.\n const forced = await signalAndWait(target.pid, \"SIGKILL\", true)\n notes.push(\n forced\n ? `pid ${target.pid} did not stop in ${Math.round(GRACE_MS / 1000)}s and was killed`\n : `pid ${target.pid} would not stop, even killed — check it by hand`,\n )\n return { ...target, stopped: forced, forced: true, note: notes.join(\" · \") }\n}\n\nasync function signalAndWait(pid: number, signal: NodeJS.Signals, group = false): Promise<boolean> {\n try {\n process.kill(group ? -pid : pid, signal)\n } catch (error) {\n // ESRCH means it went away between the check and the signal, which is the outcome we want.\n if ((error as NodeJS.ErrnoException).code === \"ESRCH\") return true\n // A group kill can fail where the single-pid kill would not; fall back rather than give up.\n if (group) {\n try {\n process.kill(pid, signal)\n } catch {\n return !processAlive(pid)\n }\n }\n }\n\n const deadline = Date.now() + (signal === \"SIGKILL\" ? 3_000 : GRACE_MS)\n while (Date.now() < deadline) {\n if (!processAlive(pid)) return true\n await new Promise((resolve) => setTimeout(resolve, POLL_MS))\n }\n return !processAlive(pid)\n}\n\nfunction describe(target: Target): string {\n const parts: string[] = []\n if (target.service) parts.push(\"background service\")\n if (target.pid !== undefined)\n parts.push(`pid ${target.pid}${target.mode === undefined ? \"\" : ` (${target.mode})`}`)\n return `${target.agentId} — ${parts.join(\", \")}`\n}\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_stop_agent_id_missing\",\n message: `${manifestPath} declares no id, so there is nothing to match a running agent against.`,\n hint: `Add \\`id: <name>\\` to the manifest, or run \\`${BRAND.slug} stop\\` with no argument to stop everything.`,\n })\n }\n return header.id\n}\n",
|
|
29
29
|
"/**\n * The `run` command. Two renderers, one setup.\n *\n * The rich path is the Ink app; the plain path is line-oriented and writes tokens to stdout as they\n * arrive. Which one runs is decided once, by `resolveMode`, and never re-decided mid-process.\n *\n * **Ink is imported lazily, and only on the rich path.** Measured: `react` + `ink` cost ~65 ms to\n * import under Bun and ~170-210 ms under Node, against a ~70 ms total runtime for `validate --json`.\n * A static import at the top of this file would be paid by every invocation of every command, so the\n * dynamic `import()` below is load-bearing rather than stylistic. A test asserts it stays that way.\n *\n * The plain path keeps Phase 1's behaviour deliberately unchanged, including the Ctrl-C contract and\n * the streaming writes, because both were verified against a real endpoint and a real SIGINT.\n */\n\nimport { randomBytes } from \"node:crypto\"\nimport { existsSync } from \"node:fs\"\nimport { createInterface, type Interface } from \"node:readline\"\nimport { createClient } from \"@dispach/client\"\nimport {\n type Agent,\n type AnyEvent,\n BRAND,\n defaultStorePath,\n describeWindowSource,\n type ErrorDetail,\n endedBadly,\n endNote,\n HarnessError,\n processAlive,\n Runtime as RuntimeClass,\n VERSION,\n windowReport,\n} from \"@dispach/core\"\nimport { fetchCatalogue } from \"#browse\"\nimport { initInteractive } from \"#init\"\nimport { ambientEnv, demotedKeys } from \"#lib/ambient\"\nimport { installReport } from \"#lib/browse\"\nimport {\n ENTER_ALT_SCREEN,\n EXIT_FAILURE,\n EXIT_OK,\n FALLBACK_COLUMNS,\n PROMPT,\n SESSION_PICKER_ROWS,\n} from \"#lib/const\"\nimport {\n flushOutput,\n markAltScreen,\n markMouse,\n markTerminalDirty,\n onExit,\n restoreTerminal,\n} from \"#lib/exit\"\nimport { negotiateKeyboard } from \"#lib/keyboard\"\nimport { agentIdFor, hostToken, liveHostOf } from \"#lib/lifecycle\"\nimport { ENABLE_MOUSE } from \"#lib/mouse\"\nimport { resolveModeFromProcess } from \"#lib/output\"\nimport { BUILT_IN_PLUGINS, CHANNELS, scriptRunner, TOOL_PROVIDERS } from \"#lib/providers\"\nimport { keyValue } from \"#lib/render\"\nimport { priorMessages, reopenNote, resumeNotice } from \"#lib/resume\"\nimport { listAgents, storePath } from \"#lib/sandbox\"\nimport type { RunOptions } from \"#lib/schema\"\nimport { screenColumns } from \"#lib/screen\"\nimport {\n type ContextView,\n contextReport,\n resolveSessionCommand,\n sessionHelpText,\n toolsReport,\n unknownCommandText,\n} from \"#lib/session-commands\"\nimport { newSessionKey } from \"#lib/session-key\"\nimport {\n type AgentSource,\n embeddedSource,\n hostFrom,\n type LiveHost,\n remoteSource,\n type SourceSession,\n} from \"#lib/source\"\nimport type { CatalogueEntry } from \"#lib/source-cache\"\nimport { openTap } from \"#lib/stdin-tap\"\nimport type { RenderMode } from \"#lib/types\"\nimport { type InstallOutcome, skillsCommand } from \"#skills\"\nimport { type PriorMessage, seed, seedHistory } from \"#transcript\"\n\n/** Opening lines: what is loaded, what session, and whether the last turn finished. */\nasync function bannerLines(\n agent: Agent,\n sessionKey: string,\n storeLocation: string,\n bootMs: number,\n /**\n * Why this banner is being printed.\n *\n * A boolean answered \"is this the first one\" and there are now four answers: a `/restart` rebuilt the\n * agent, a session switch rebuilt it to move conversations, and `/new` rebuilt it onto a conversation\n * that did not exist a moment ago. They need different sentences — the restart note is about\n * configuration and would be a lie about a switch — and they agree about the boot number, because in\n * every case the process has been alive for however long the last conversation lasted and\n * time-since-process-start has stopped meaning anything.\n *\n * Closed on purpose: a new reason cannot be added without the compiler demanding a sentence for it.\n */\n reopened: \"first\" | \"restart\" | \"switch\" | \"new\",\n demoted: readonly string[] = [],\n /**\n * The conversation being left behind, for the one sentence that has to name it.\n *\n * Last, after the defaulted `demoted`: inserted next to `reopened` where it reads best, it would\n * have silently taken the argument the existing call site passes for `demoted`. A positional\n * parameter is added at the end or every caller is re-read.\n */\n previousKey?: string,\n) {\n const described = agent.describe()\n const [turns, resumed] = await Promise.all([\n agent.turns(sessionKey, 1),\n agent.store.messages.count(agent.id, sessionKey),\n ])\n\n // The title first, then the session. The rich path drops the title row — its one-line header restates\n // it, and the two together put the same brand, agent and model on screen twice — so anything that is\n // *not* in that header has to live below it. `window` moved down for exactly that reason: it is a fact\n // about this session's budget rather than part of the title.\n const lines = [\n `${BRAND.name} ${VERSION} · ${described.id} · ${described.model}`,\n `session ${sessionKey} · ${resumed} message(s) · window ${described.window} · store ${storeLocation}`,\n // Points at `/help` rather than listing commands: the list belongs to the table that\n // implements them, and a banner enumerating a subset is the drift this change removed.\n `ready in ${bootMs.toFixed(0)} ms · /help for commands and keys · /exit to leave`,\n ]\n\n // One function decides the sentence, and it is pure — see `lib/resume.ts`. Written inline here it\n // needed a live agent and a store to reach, so the only part of this banner a person reads was the\n // only part nothing could check.\n const note = reopenNote(reopened, previousKey)\n if (note !== undefined) lines.push(note)\n\n // Naming a reaped turn is the point of reaping it: the previous run died mid-generation, and the\n // person restarting is the one who needs to know.\n if (turns[0]?.errorCode === \"turn_abandoned\") {\n lines.push(\n \"note: the previous turn in this session did not finish — the process exited while it was generating.\",\n )\n }\n\n // Load warnings, read off the agent rather than caught on the bus.\n //\n // `Runtime.create` emits them as `agent.warning` during boot — which finishes *before* this\n // command subscribes to anything, so every one of them has been landing in an empty room: a\n // trimmed catalogue, a tool declared trusted by its provider, a shell that can only run once a\n // turn. Silent, and precisely the class of thing the loud resolution path exists to prevent.\n //\n // Reading the resolved state instead of racing the bus is also the more honest fix. These are\n // properties of the loaded agent, not events, and something that is true for the whole session\n // belongs where a person will still see it after scrolling.\n for (const warning of [...agent.warnings, ...agent.tools.warnings]) {\n lines.push(`note: ${warning.message}\\n ${warning.hint}`)\n }\n\n // The other half of the same honesty. Core warns when the environment *took* a variable from the\n // agent's own .env; this says when the CLI decided a .env in the current directory should not\n // have. Someone who just wrote MODEL_ID into a project file and finds their agent ignoring it\n // needs the sentence as much as the person who found their agent obeying it.\n if (demoted.length > 0) {\n lines.push(\n `note: ${demoted.join(\", \")} in the .env here ${demoted.length === 1 ? \"was\" : \"were\"} ignored — this agent's own .env sets ${demoted.length === 1 ? \"it\" : \"them\"}.\\n A .env in the directory you launched from configures that project, not an agent living somewhere else. Export the variable to override the agent's own file.`,\n )\n }\n\n return lines\n}\n\nexport async function runCommand(options: RunOptions): Promise<number> {\n const oneShot = options.once !== undefined\n const decision = resolveModeFromProcess({\n json: false,\n plain: options.plain === true,\n oneShot,\n })\n const { mode } = decision\n\n // No agent named: the sandbox decides. One agent auto-runs; several open the picker at a\n // terminal and list plainly everywhere else; none goes straight to the wizard (rich) or an\n // error naming `init` (plain) — an empty sandbox with no guidance is a dead end.\n if (options.manifestPath === undefined) {\n const picked = await pickFromSandbox(mode, decision.because, options)\n if (typeof picked === \"number\") return picked\n return runCommand({ ...options, manifestPath: picked })\n }\n\n // The CLI opts into persistence explicitly — core defaults to memory so that embedding the\n // library never writes to someone's working directory uninvited. The default store lives at\n // the sandbox root: one store for every agent, wherever `run` is invoked from — a cwd-relative\n // default gave the same agent a different session history in every directory.\n const legacy = defaultStorePath()\n if (options.store === undefined && options.ephemeral !== true && existsSync(legacy)) {\n process.stdout.write(\n `note: a session store exists at ${legacy} from an earlier version — pass --store ${legacy} to keep using it; the default is now ${storePath()}\\n`,\n )\n }\n // One teardown for however many runtimes this call goes through. Registering inside the loop\n // would hold a reference to every dead one; `Runtime.stop` is already idempotent, so the live\n // reference is the only thing that has to move.\n let current: RuntimeClass | undefined\n onExit(() => current?.stop(\"cli-exit\"))\n\n // Outlives every runtime this call builds. See `Wired.reader`.\n const reader: { current: Interface | undefined } = { current: undefined }\n // The unsent message, carried across a `/restart` for the same reason the reader is: both belong to\n // the command rather than to one mount, and the restart tears the mount down.\n const draft: { current: string } = { current: \"\" }\n\n // Resolved once per call and then carried, because `/restart` must not silently move the conversation.\n //\n // Empty rather than absent means a bare `--session`: \"ask me which one\". Resolution needs the store, so\n // it happens inside the loop once a runtime exists — and the box is what keeps a picked key stable\n // across a restart, the same reason the reader and the draft live out here.\n const session: { current: string | undefined } = { current: options.sessionKey }\n // Whether the splash stands in for the transcript. Carried beside the key, and both survive a\n // `/restart` — which is not new, so the restarted session goes straight to the conversation.\n const freshSession = { current: false }\n /** The key the last iteration was on, for the `/new` banner. Undefined on the first. */\n const leaving: { current: string | undefined } = { current: undefined }\n const quiet = options.quiet === true\n // Why the loop is on this iteration. `switch` is set by the in-session picker, which reaches the loop\n // the same way `/restart` does — by unmounting — because `useReducer`'s initial state only seeds on\n // mount, so a transcript cannot be re-keyed in place. Rebuilding is a hundred and fifty milliseconds\n // and it re-reads the store, which is exactly what moving to another conversation wants.\n let reopened: \"first\" | \"restart\" | \"switch\" | \"new\" = \"first\"\n /**\n * A conversation the running session asked to move to. Applied at the top of the next iteration.\n *\n * Carries its *reason* rather than sitting beside a second `mintedNew` boolean: two pieces of state\n * answering one question is how they come to disagree, and `reopened` is a closed union, so a reason\n * with no banner sentence is a compile error rather than a silent rebuild nobody explains.\n */\n const switchTo: { current: { key: string; reason: \"switch\" | \"new\" } | undefined } = {\n current: undefined,\n }\n\n /**\n * **Attach to a live host, or build a runtime — never both.**\n *\n * This is 17.1, and the sequence that makes it necessary is one command long: `run` declares\n * `needsServer`, so since 16.4 it already installs and starts a server — and then built a\n * *second* runtime for an agent that server was holding. Two processes on one SQLite file are\n * not two views of a conversation; they are two writers, and the runtime said so out loud, in\n * slot 2, to the model (`declined`, decision 5.17).\n *\n * `--ephemeral` is excluded by definition: it asks for an in-memory store, which is a request\n * for a runtime of one's own. Everything else attaches when something is there to attach to,\n * `--input` included — the plan's wording put one-shots on the embedded path, but its stated\n * reason was \"starts no channels or schedules\", and attaching starts none either. What a\n * one-shot gains is the thing the phase is about: one writer.\n *\n * Nothing here falls back *from* attached to embedded. If a host holds the lease and cannot be\n * reached, that is a fault to report rather than route around: quietly starting a second\n * runtime is exactly the state this removes, and it would look like success.\n */\n const attached =\n options.ephemeral === true\n ? undefined\n : hostFrom(await liveHostOf(agentIdFor(options.manifestPath), options.store))\n if (attached !== undefined) {\n return await runAttached({\n ...options,\n host: attached,\n mode: mode === \"rich\" ? \"rich\" : \"plain\",\n quiet,\n oneShot,\n reader,\n draft,\n session,\n random: randomBytes,\n })\n }\n\n // `/restart` rebuilds the agent in this process rather than replacing the process.\n //\n // The settings an agent booted with are fixed for its lifetime — the catalogue is resolved once,\n // and slot 1 is rendered once, both deliberately — so a configuration change genuinely needs a new\n // agent and there is no honest way to apply one in place. Re-execing would work and would throw\n // away the terminal; this keeps the scrollback, and the conversation was never in memory anyway.\n for (;;) {\n const runtime = await RuntimeClass.create({\n agents: [options.manifestPath],\n toolProviders: TOOL_PROVIDERS,\n builtInPlugins: BUILT_IN_PLUGINS,\n scriptRunner: scriptRunner(),\n channels: CHANNELS,\n // A `.env` in the directory this was launched from loses to the agent's own. See\n // `lib/ambient.ts` — core's \"real environment wins\" is untouched; this decides what\n // counts as the real environment.\n env: ambientEnv([options.manifestPath]),\n store: options.ephemeral === true ? \":memory:\" : (options.store ?? storePath()),\n })\n current = runtime\n\n const agent = runtime.list()[0]\n if (agent === undefined) throw new Error(\"The manifest produced no agent.\")\n\n // The conversation this run belongs to.\n //\n // After the runtime, because both interesting answers read the store: `--continue` wants the most\n // recent conversation and a bare `--session` wants the list. Once resolved it is carried, so a\n // `/restart` rebuilds the agent and stays in the same conversation.\n if (session.current === undefined || session.current === \"\") {\n const resolved = await resolveSession({\n list: () => source.sessions(),\n mode,\n asked: session.current,\n wantsContinue: options.continueSession === true,\n random: randomBytes,\n })\n if (typeof resolved === \"number\") {\n await runtime.stop(\"cli-exit\")\n return resolved\n }\n session.current = resolved.sessionKey\n freshSession.current = resolved.fresh\n }\n const sessionKey = session.current\n\n // Reasoning is shown by default on a model that has any.\n //\n // It used to be opt-in behind --show-reasoning, which meant the normal experience of a\n // reasoning model was a cursor sitting still for thirty seconds with nothing to look at,\n // and no indication anything was happening. The thinking is the only signal there is\n // during that time, and it is already being streamed and thrown away. `--no-reasoning`\n // turns it off; `--show-reasoning` stays, and is now a no-op that harms nobody's scripts.\n const reasons = agent.roles.main.capabilities.thinking !== \"none\"\n const showReasoning = options.noReasoning === true ? false : reasons\n\n const banner =\n quiet || oneShot\n ? []\n : await bannerLines(\n agent,\n sessionKey,\n runtime.store.location,\n // After a restart the process has been alive for however long the conversation\n // lasted, so time-since-process-start stops meaning anything. The first boot\n // reports it because that is the number the sub-second claim is about.\n reopened === \"first\" ? runtime.boot.processMs : runtime.boot.bootMs,\n reopened,\n demotedKeys([options.manifestPath]),\n leaving.current,\n )\n\n // The conversation so far, for the rich path only. `history` is the same read `send` performs, so\n // what is painted is exactly what the model is conditioned on — minus the runtime's own messages,\n // which `origin` identifies and which are not part of the conversation a person is resuming.\n // Which origins and roles count, and why each exclusion is deliberate, is `lib/resume.ts` —\n // extracted so it can be tested without standing up a runtime, which is what let the previous\n // two versions of this be wrong in a way only a live resume would show.\n const prior: readonly PriorMessage[] =\n mode === \"rich\" && !quiet && !oneShot\n ? priorMessages(await agent.history(sessionKey), agent.describe().dialect)\n : []\n\n const source = embeddedSource({\n agent,\n bus: runtime.bus,\n send: (text, sendOptions) => agent.send(text, sendOptions),\n history: async (key) =>\n priorMessages(await agent.history(key), agent.describe().dialect),\n sessions: async () => await agent.store.sessions.list(agent.id),\n clearSession: async (key) => {\n await agent.clearSession(key)\n },\n context: async (key) => contextViewOf(agent, key),\n streamFilter: () => agent.streamFilter(),\n description: {\n agentId: agent.id,\n name: agent.describe().name,\n model: agent.describe().model,\n dialect: agent.describe().dialect,\n window: agent.describe().window,\n catalogueTokens: agent.describe().catalogueTokens,\n thinking: agent.roles.main.capabilities.thinking,\n // Read off the agent, never caught on the bus: `Runtime.create` emits\n // `agent.warning` during boot, which finishes before anything could subscribe.\n warnings: [...agent.warnings, ...agent.tools.warnings],\n },\n })\n\n const wired = {\n ...options,\n source,\n embedded: { agent, runtime },\n sessionKey,\n banner,\n prior,\n quiet,\n reader,\n draft,\n showReasoning,\n freshSession: freshSession.current,\n switchTo,\n random: randomBytes,\n }\n const outcome = mode === \"rich\" ? await runRich(wired) : await runPlain(wired)\n\n await runtime.stop(outcome === RESTART ? \"restart\" : \"cli-exit\")\n if (outcome !== RESTART) return outcome\n if (switchTo.current === undefined) {\n reopened = \"restart\"\n } else {\n reopened = switchTo.current.reason\n // Read before the key is replaced: the sentence a `/new` prints is about the conversation\n // being left, which is the one thing the next banner cannot derive from its own state.\n leaving.current = sessionKey\n session.current = switchTo.current.key\n switchTo.current = undefined\n }\n // The splash does not come back after a rebuild, even when the key is unchanged and nothing has\n // been sent. The reason for the rebuild is a line in the banner, and a welcome screen in front of it\n // would hide the one sentence explaining what just happened.\n freshSession.current = false\n }\n}\n\n/**\n * What a renderer returns when the answer is \"build it again\", not \"we are done\".\n *\n * A symbol rather than a magic exit code: every other value this returns is a process exit status, and\n * a status that secretly means something else is the kind of overload that survives until someone\n * returns it by accident.\n */\n/** One install per skill, so a partial failure keeps the successful ones with a reason for the rest. */\nfunction installSkills(\n skills: readonly CatalogueEntry[],\n manifestPath: string,\n): readonly InstallOutcome[] {\n const outcomes: InstallOutcome[] = []\n for (const entry of skills) {\n skillsCommand({\n action: \"install\",\n manifestPath,\n name: `${entry.source}/${entry.skill}`,\n quiet: true,\n collect: outcomes,\n })\n }\n return outcomes\n}\n\nconst RESTART = Symbol(\"restart\")\ntype RunOutcome = number | typeof RESTART\n\n/**\n * Bare `run`: resolve the sandbox into either a manifest path to run or an exit code.\n *\n * The picker is the third Ink surface, mounted the same lazy way; picking unmounts it before the\n * chat mounts, so the two screens stack naturally in scrollback. \"Create a new agent\" chains\n * through `initInteractive` — one wizard entry point — and straight into the chat with the result.\n */\nasync function pickFromSandbox(\n mode: string,\n because: string,\n options: RunOptions,\n): Promise<string | number> {\n const agents = listAgents()\n\n if (agents.length === 0) {\n if (mode === \"rich\") {\n // First run, empty sandbox: the wizard IS the answer to \"run what?\".\n const created = await initInteractive({ plain: options.plain === true })\n if (created.kind === \"aborted\") {\n process.stdout.write(\"nothing to run\\n\")\n return EXIT_OK\n }\n if (created.kind === \"failed\") return created.code\n return created.manifestPath\n }\n throw new HarnessError({\n code: \"cli_sandbox_empty\",\n message: \"No agent named, and the sandbox is empty.\",\n hint: `Create one with \\`${BRAND.slug} init\\`, or pass a path to an agent.yaml.`,\n })\n }\n\n if (agents.length === 1 && agents[0] !== undefined) {\n // The overwhelmingly common case costs zero keystrokes; saying so keeps it explicable.\n process.stdout.write(`running ${agents[0].ref} — the only agent in the sandbox\\n`)\n return agents[0].manifestPath\n }\n\n if (mode !== \"rich\") {\n // Scriptable contexts get the list and a non-zero exit: nothing ran.\n for (const agent of agents) {\n process.stdout.write(\n `${agent.ref}\\t${agent.problem ?? agent.modelId ?? \"?\"}\\t${agent.dir}\\n`,\n )\n }\n process.stderr.write(\n `pass an agent name or a manifest path — the picker needs a terminal (${because})\\n`,\n )\n return EXIT_FAILURE\n }\n\n const [{ render }, { createElement }, { Picker }] = await Promise.all([\n import(\"ink\"),\n import(\"react\"),\n import(\"#components/Picker\"),\n ])\n let result: { kind: \"run\"; manifestPath: string } | { kind: \"create\" } | { kind: \"quit\" } = {\n kind: \"quit\",\n }\n // eslint-free narrowing escape: the callback assignment below is invisible to control-flow\n // analysis, so the read after waitUntilExit goes through a widened alias.\n markTerminalDirty()\n const instance = render(\n createElement(Picker, {\n title: `${BRAND.name} ${VERSION}`,\n agents,\n onDone: (picked) => {\n result = picked\n },\n }),\n { exitOnCtrlC: false, ...negotiateKeyboard(options.noEnhancedKeys) },\n )\n onExit(() => instance.unmount())\n await instance.waitUntilExit()\n instance.unmount()\n\n const picked = result as\n | { kind: \"run\"; manifestPath: string }\n | { kind: \"create\" }\n | { kind: \"quit\" }\n if (picked.kind === \"quit\") {\n process.stdout.write(\"nothing run\\n\")\n return EXIT_OK\n }\n if (picked.kind === \"create\") {\n const created = await initInteractive({ plain: options.plain === true })\n if (created.kind === \"aborted\") {\n process.stdout.write(\"nothing to run\\n\")\n return EXIT_OK\n }\n if (created.kind === \"failed\") return created.code\n return created.manifestPath\n }\n return picked.manifestPath\n}\n\n/**\n * Which conversation this run belongs to, or an exit code if the answer is \"none\".\n *\n * Three inputs, and the contradictory pair is refused rather than ranked. `--continue --session x` says\n * both \"the most recent one\" and \"this one\"; picking a winner would silently ignore half of what was\n * typed, and there is no reading of it that is obviously intended.\n *\n * The default is a **new** key. That is the behaviour change: every run used to land in `local:default`,\n * so an agent's store was one unbroken transcript and this morning's question was conditioned on\n * yesterday's debugging. It applies to `--input` too, which makes a scripted one-shot stateless unless it\n * names a session — deliberately, because a one-shot that quietly accumulated history grows its own\n * context until compaction starts thrashing, and `--session` is right there for the case somebody wants\n * the thread.\n */\nexport interface ResolvedSession {\n readonly sessionKey: string\n /**\n * The key was generated for this run, so there is nothing behind it.\n *\n * Carried rather than re-derived from a message count, because the two answers differ: a conversation\n * that was resumed and then cleared has no messages and is not new. This is what puts the splash in\n * front of a new conversation and keeps it away from a resumed one.\n */\n readonly fresh: boolean\n}\n\nasync function resolveSession(input: {\n /**\n * How to list conversations — not an `Agent`.\n *\n * The only thing this ever wanted from one, and taking the list instead is what lets an\n * attached run reuse it verbatim: it asks the *host* for its sessions, where an embedded run\n * asks its own store. A second copy of this function for the attached path would be a second\n * set of answers to \"what does `--continue` mean when there is nothing stored\", and those are\n * the cases somebody gets wrong once and never notices.\n */\n readonly list: () => Promise<readonly SourceSession[]>\n readonly mode: RenderMode\n /** `\"\"` for a bare `--session`; `undefined` for not asked at all. */\n readonly asked: string | undefined\n readonly wantsContinue: boolean\n readonly random: (count: number) => Uint8Array\n}): Promise<ResolvedSession | number> {\n const fresh = (): ResolvedSession => ({\n sessionKey: newSessionKey(input.random),\n fresh: true,\n })\n\n if (input.wantsContinue && input.asked === \"\") {\n throw new HarnessError({\n code: \"cli_session_ambiguous\",\n message: \"--continue and a bare --session ask for different things.\",\n hint: \"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one.\",\n })\n }\n\n if (input.wantsContinue) {\n const stored = await input.list()\n const recent = mostRecent(stored)\n if (recent === undefined) {\n // Not an error: an agent you have never talked to has no most-recent conversation, and refusing\n // would make `-c` unusable as a habit — you would have to remember whether this is the first time.\n process.stdout.write(\n \"no stored conversation with this agent yet — starting a new one\\n\",\n )\n return fresh()\n }\n return { sessionKey: recent.sessionKey, fresh: false }\n }\n\n if (input.asked === \"\") {\n const stored = await input.list()\n if (stored.length === 0) {\n process.stdout.write(\n \"no stored conversation with this agent yet — starting a new one\\n\",\n )\n return fresh()\n }\n if (input.mode !== \"rich\") {\n // The plain path lists them and refuses, rather than guessing. Same shape as the agent picker:\n // a surface that needs a keyboard says so and prints what you would have chosen from.\n for (const row of [...stored].sort(byRecency)) {\n process.stdout.write(\n `${row.sessionKey}\\t${row.messages}\\t${row.turns}\\t${row.lastActivityAt}\\n`,\n )\n }\n process.stderr.write(\n \"pass --session <key> — the picker needs a terminal, and --continue takes the most recent without one\\n\",\n )\n return EXIT_FAILURE\n }\n const picked = await pickSession([...stored].sort(byRecency))\n // Esc means \"leave things as they are\", which for a run that has not started yet is a new\n // conversation rather than no conversation. Quitting would make esc a way to fail to launch.\n return picked === undefined ? fresh() : { sessionKey: picked, fresh: false }\n }\n\n return input.asked === undefined ? fresh() : { sessionKey: input.asked, fresh: false }\n}\n\n/** Most recently touched first. One comparator, so the picker and `--continue` agree about \"recent\". */\nfunction byRecency(left: SourceSession, right: SourceSession): number {\n return Date.parse(right.lastActivityAt) - Date.parse(left.lastActivityAt)\n}\n\nfunction mostRecent(sessions: readonly SourceSession[]): SourceSession | undefined {\n return [...sessions].sort(byRecency)[0]\n}\n\n/** The session picker, mounted the same lazy way as every other Ink surface. */\nasync function pickSession(sessions: readonly SourceSession[]): Promise<string | undefined> {\n const [{ render }, { createElement }, { SessionPicker }] = await Promise.all([\n import(\"ink\"),\n import(\"react\"),\n import(\"#components/SessionPicker\"),\n ])\n\n let picked: string | undefined\n markTerminalDirty()\n const instance = render(\n createElement(SessionPicker, {\n sessions: sessions.map((row) => ({\n sessionKey: row.sessionKey,\n messages: row.messages,\n turns: row.turns,\n lastActivityAt: row.lastActivityAt,\n phase: row.phase,\n })),\n now: Date.now(),\n columns: screenColumns(process.stdout.columns, FALLBACK_COLUMNS),\n maxRows: SESSION_PICKER_ROWS,\n onDone: (key) => {\n picked = key\n instance.unmount()\n },\n }),\n { exitOnCtrlC: false, ...negotiateKeyboard() },\n )\n onExit(() => instance.unmount())\n await instance.waitUntilExit()\n return picked\n}\n\n/**\n * The banner for an attached run. Shorter than the embedded one, and short for a reason.\n *\n * Three of `bannerLines`' facts are about a runtime *in this process* and would be lies here: the\n * boot figure (nothing booted), the store location (none is open), and any warning read off a live\n * agent at load. What replaces them is the one fact an attached run has and an embedded one does\n * not — **where the agent actually is** — because \"this is a view\" is only useful if it says a view\n * of *what*, and a pid plus an address is what somebody can act on.\n *\n * Synchronous, unlike its embedded twin: everything it prints came back with the description.\n */\nfunction attachedBanner(\n source: AgentSource,\n sessionKey: string,\n host: LiveHost,\n reopened: \"first\" | \"restart\" | \"switch\" | \"new\",\n previousKey?: string,\n): readonly string[] {\n const described = source.describe()\n const lines = [\n `${BRAND.name} ${VERSION} · ${described.agentId} · ${described.model}`,\n `session ${sessionKey} · window ${described.window} · attached to ${host.baseUrl} (pid ${host.pid})`,\n // The sentence that makes the mode legible. Without it, `/exit` leaving a bot answering\n // Telegram reads as a command that failed to stop something.\n `a view — the agent keeps running when you leave · /help for commands · /exit to detach`,\n ]\n const note = reopenNote(reopened, previousKey)\n if (note !== undefined) lines.push(note)\n // Read off the description rather than caught on the stream: these are emitted during the\n // host's boot, which finished long before this process subscribed to anything.\n for (const warning of described.warnings) lines.push(`warning: ${warning.message}`)\n return lines\n}\n\n/**\n * A run that is a **view**: no runtime, no store, no lease.\n *\n * The mirror of the loop below, and deliberately shorter, because most of what that loop does is\n * about owning a runtime. There is no rebuild here — `/restart` asks the host to replace the agent\n * and the screen stays up, since there is nothing in this process to rebuild — so the only reason\n * to go round again is a conversation switch.\n *\n * It opens no database on purpose. Reading history and sessions locally would make the store path a\n * second source of truth that can disagree with the host while both look correct: a stale `--store`\n * would show a different conversation than the one being appended to. The lease carries a\n * `baseUrl` (16.3) precisely so this does not have to guess a port either.\n */\nasync function runAttached(\n input: RunOptions & {\n readonly host: LiveHost\n readonly mode: \"rich\" | \"plain\"\n readonly quiet: boolean\n readonly oneShot: boolean\n readonly reader: { current: Interface | undefined }\n readonly draft: { current: string }\n readonly session: { current: string | undefined }\n readonly random: (count: number) => Uint8Array\n },\n): Promise<number> {\n const manifestPath = input.manifestPath ?? \"\"\n const agentId = agentIdFor(manifestPath)\n // The credential comes from the manifest's *layered* env, which is the same place `serve` read\n // it — never from `ambientEnv`, which answers \"what is in this process\" and made a token sitting\n // beside the manifest invisible once already.\n const token = hostToken(manifestPath)\n const client = createClient({\n baseUrl: input.host.baseUrl,\n ...(token === undefined ? {} : { token }),\n })\n\n const described = await client.agent(agentId).describe()\n const source = remoteSource({\n client,\n agentId,\n host: input.host,\n description: {\n agentId,\n name: described.name,\n model: described.model ?? \"unknown\",\n dialect: described.dialect ?? \"nlt\",\n window: described.window ?? 0,\n catalogueTokens: described.catalogueTokens ?? 0,\n // Not on the wire: a description says what the agent is, and whether a model reasons is\n // a capability the host resolved. Reasoning streams whenever the host sends it, which\n // is the honest default — `--no-reasoning` still turns it off.\n thinking: \"unknown\",\n // `WireError` is the client's name for the same `{code, message, hint, field?}`. A\n // cast rather than a remap: remapping four fields by hand is where a `field` goes\n // missing and nothing reports it.\n warnings: (described.warnings ?? []) as readonly ErrorDetail[],\n },\n })\n\n const switchTo: { current: { key: string; reason: \"switch\" | \"new\" } | undefined } = {\n current: undefined,\n }\n let reopened: \"first\" | \"restart\" | \"switch\" | \"new\" = \"first\"\n const leaving: { current: string | undefined } = { current: undefined }\n const freshSession = { current: false }\n\n for (;;) {\n if (input.session.current === undefined || input.session.current === \"\") {\n const resolved = await resolveSession({\n list: () => source.sessions(),\n mode: input.mode,\n asked: input.session.current,\n wantsContinue: input.continueSession === true,\n random: input.random,\n })\n if (typeof resolved === \"number\") return resolved\n input.session.current = resolved.sessionKey\n freshSession.current = resolved.fresh\n }\n const sessionKey = input.session.current ?? \"\"\n\n const banner =\n input.quiet || input.oneShot\n ? []\n : attachedBanner(source, sessionKey, input.host, reopened, leaving.current)\n\n const prior =\n input.mode === \"rich\" && !input.quiet && !input.oneShot\n ? await source.history(sessionKey)\n : []\n\n const wired: Wired = {\n ...input,\n source,\n sessionKey,\n banner,\n prior,\n quiet: input.quiet,\n reader: input.reader,\n draft: input.draft,\n showReasoning: input.noReasoning !== true,\n freshSession: freshSession.current,\n switchTo,\n random: input.random,\n }\n const outcome = input.mode === \"rich\" ? await runRich(wired) : await runPlain(wired)\n if (outcome !== RESTART) {\n await source.close()\n return outcome\n }\n // The only way back round: a conversation switch. `/restart` never gets here, because\n // attached it is a request to the host and the screen never comes down.\n if (switchTo.current === undefined) {\n reopened = \"restart\"\n } else {\n reopened = switchTo.current.reason\n leaving.current = sessionKey\n input.session.current = switchTo.current.key\n switchTo.current = undefined\n }\n freshSession.current = false\n }\n}\n\ninterface Wired extends RunOptions {\n /**\n * Where the agent is. What the screen gets, and the only one of these two an attached run has.\n *\n * `agent` stays beside it for the helpers that genuinely need a live one — the banner's boot\n * figure, the manifest dump `/status` prints embedded. Those are facts about a runtime *in this\n * process*, so an attached run answers them differently rather than not at all.\n */\n readonly source: AgentSource\n /**\n * The live runtime, when this process is the one hosting.\n *\n * **Absent when attached**, which is the shape of the whole change: a view of somebody else's\n * agent has no `Agent` object and no store handle, and the compiler is what stops a helper\n * quietly reaching for one. Everything the screen needs goes through `source`; what is left\n * here are the facts that are only true of a runtime *in this process* — the boot figure, and\n * the manifest dump `/status` prints embedded.\n */\n readonly embedded?: { readonly agent: Agent; readonly runtime: RuntimeClass }\n /**\n * Resolved, not the raw flag: on by default for a model that reasons, off under\n * `--no-reasoning`. Narrowed to a required boolean here so no renderer has to re-decide.\n */\n readonly showReasoning: boolean\n readonly sessionKey: string\n readonly banner: readonly string[]\n readonly quiet: boolean\n /** The session key was generated for this run, so the splash stands in for an empty transcript. */\n readonly freshSession: boolean\n /**\n * The conversation as it already stands, for the rich path to paint.\n *\n * Read here rather than inside the component because the host owns the store. Empty on a fresh\n * session, and empty on the plain path deliberately: `--plain` has to match a pipe byte for byte,\n * and a piped REPL replaying its own history would change what every existing script reads.\n */\n readonly prior: readonly PriorMessage[]\n /**\n * Where the running session asked to move to, and why. Read by the loop, not by the renderer.\n *\n * The reason rides with the key because the loop has to tell a `/sessions` switch from a `/new`, and\n * a second boolean beside this box would be a second answer to one question.\n */\n readonly switchTo: { current: { key: string; reason: \"switch\" | \"new\" } | undefined }\n /** Six bytes, injected so a test gets the key it asked for. `randomBytes` in production. */\n readonly random: (count: number) => Uint8Array\n /**\n * The line reader, owned by `runCommand` so it survives a `/restart`.\n *\n * Rebuilding it per runtime is the obvious thing and it breaks: a second `createInterface` over a\n * pipe that the first one already read to EOF returns immediately, so everything after `/restart`\n * is silently dropped. A terminal probably tolerates it — and \"probably\" is the problem, since it\n * cannot be tested where there is no tty. Sharing one reader removes the difference rather than\n * betting on it.\n */\n readonly reader: { current: Interface | undefined }\n /** The unsent message, surviving a restart. Empty on a fresh run. */\n readonly draft: { current: string }\n}\n\n/**\n * The Ink app.\n *\n * `exitOnCtrlC: false` is not optional. Ink's default is to handle Ctrl-C itself and exit the\n * process, which would silently undo the contract Phase 1 established and measured — Ctrl-C cancels\n * the turn, not the process — and the failure would look like \"cancellation kills the session\".\n */\nasync function runRich(wired: Wired): Promise<RunOutcome> {\n const [{ render }, { createElement }, { App }] = await Promise.all([\n import(\"ink\"),\n import(\"react\"),\n import(\"#components/App\"),\n ])\n\n // The session takes the whole terminal.\n //\n // `markAltScreen` before the sequence, not after: it is what teaches every exit route — an explicit\n // `finish`, a signal, a crash guard, `process.on(\"exit\")` — to swap back out. Setting it and failing\n // to enter would be the worse order, because a `1049l` sent to a terminal that never entered the\n // buffer clears the output that was just written to it.\n //\n // The buffer is discarded on the way out and never joins the scrollback, which is the whole point and\n // also the cost: the conversation is gone from the screen the moment the session ends. That is what\n // the pointer line below exists for, and what makes `^C` take two presses.\n // Before `render`, which is the whole point: two listeners on one `data` event both receive the\n // chunk, ordering is registration order, and this one has to have parsed a sequence before Ink's\n // handler fires for it. `lib/csi.ts` says what it is for — Ink merges the super bit into `meta`, so\n // without this `cmd+←` is `⌥←`.\n const tap = openTap()\n onExit(() => {\n tap.close()\n })\n\n markAltScreen()\n // Tracking with the buffer swap, and only here: the chat is the one surface whose keymap claims every\n // mouse report, and a surface that asked for them without claiming them would have Ink type them into\n // it as text. `markMouse` is what teaches every exit route to switch it off again — including a crash,\n // because leaving it on hands the shell a terminal that reports clicks into its prompt.\n markMouse()\n process.stdout.write(`${ENTER_ALT_SCREEN}${ENABLE_MOUSE}`)\n\n let restart = false\n const instance = render(\n createElement(App, {\n source: wired.source,\n onSwitch: (sessionKey: string, draft: string) => {\n // The same route a `/restart` takes, for the reason stated at `reopened`: a transcript\n // cannot be re-keyed in place, so the conversation moves by rebuilding.\n restart = true\n wired.switchTo.current = { key: sessionKey, reason: \"switch\" }\n wired.draft.current = draft\n },\n onNew: (draft: string) => {\n // Identical to `onSwitch` but for a key that did not exist a moment ago. Minted here\n // rather than in the component: `run.ts` owns the randomness and its injection point,\n // and a component that reaches for crypto is one no test can pin to a known key.\n restart = true\n wired.switchTo.current = { key: newSessionKey(wired.random), reason: \"new\" }\n wired.draft.current = draft\n },\n sessions: async () => {\n // Through the source, so an attached view lists the conversations the *host* has\n // rather than whatever a local store happens to hold. That is the whole reason an\n // attached run opens no database: two readings of \"which conversations exist\" can\n // disagree while both look correct, and only one of them is being written to.\n const stored = await wired.source.sessions()\n return [...stored].sort(byRecency).map((row) => ({\n sessionKey: row.sessionKey,\n messages: row.messages,\n turns: row.turns,\n lastActivityAt: row.lastActivityAt,\n phase: row.phase,\n }))\n },\n onRestart: (draft: string) => {\n restart = true\n // Written into the box the loop owns, the same way the readline instance is carried.\n // A local would be lost the moment this function returns, which is exactly when the\n // next mount needs it.\n wired.draft.current = draft\n },\n sessionKey: wired.sessionKey,\n model: wired.source.describe().model,\n agentName: wired.source.describe().agentId,\n // Only before the first message, and only in a conversation with nothing behind it.\n freshSession: wired.freshSession,\n // The count in the one-line header. The messages themselves are in the banner, which scrolls;\n // on a surface with no scrollback a session-wide fact that has scrolled away is a fact nobody\n // has, so the header keeps the number and says where to find the text.\n warnings: wired.source.describe().warnings.map((warning) => warning.message),\n // Without the title row: `titleLine` above the transcript already carries the brand, the\n // agent and the model, and printing both put one sentence on screen twice — measured at 100\n // columns, rows 6 and 8 of a fresh session. The plain path keeps it, because there is no\n // header there and it is the only place the version appears.\n initial: seedHistory(seed(wired.banner.slice(1)), wired.prior),\n correctKeys: tap.correct,\n showReasoning: wired.showReasoning,\n quiet: wired.quiet,\n // So a slash command runs against *this* agent: without it a child would resolve whichever\n // agent the cwd suggests, which would not look wrong in the output.\n ...(wired.manifestPath === undefined ? {} : { manifestPath: wired.manifestPath }),\n // The host owns the filesystem and the network; the screen owns neither. Injected here rather\n // than imported by the component, which also keeps `browse.ts` out of its import graph.\n catalogue: {\n load: (onStatus: (line: string) => void) => fetchCatalogue({ onStatus }),\n install: async (skills, into) => installReport(installSkills(skills, into)),\n },\n // The same definition the plain REPL calls at its own `/status`, reached through a callback\n // rather than by handing the component a runtime — one function, two callers, so the two\n // paths cannot come to disagree about whether a channel is connected.\n // Two statuses, chosen by which kind of run this is — never one with half its\n // sentences blanked. See `attachedStatus`.\n status: () =>\n wired.embedded === undefined\n ? attachedStatus(wired.source)\n : sessionStatus(wired.embedded),\n contextView: () => sessionContext(wired, wired.sessionKey),\n ...(wired.draft.current === \"\" ? {} : { initialDraft: wired.draft.current }),\n }),\n { exitOnCtrlC: false, ...negotiateKeyboard(wired.noEnhancedKeys) },\n )\n onExit(() => instance.unmount())\n\n await instance.waitUntilExit()\n\n // Restore *before* writing, or the notice lands on the buffer that is about to be discarded.\n // `restoreTerminal` is idempotent and runs again from the exit hook, so doing it here costs nothing\n // and is the only way to get a byte onto the shell's own screen.\n restoreTerminal()\n if (!restart) {\n process.stdout.write(\n resumeNotice({\n ref: wired.source.describe().agentId,\n sessionKey: wired.sessionKey,\n }),\n )\n }\n return restart ? RESTART : EXIT_OK\n}\n\n/** Line-oriented, and byte-identical whether stdout is a terminal or a pipe. */\nasync function runPlain(wired: Wired): Promise<RunOutcome> {\n const { source, sessionKey, quiet } = wired\n\n let atLineStart = true\n const write = (text: string) => {\n if (text === \"\") return\n process.stdout.write(text)\n atLineStart = text.endsWith(\"\\n\")\n }\n /** A line of its own, whatever the reply was part-way through writing. */\n const row = (text: string) => {\n if (!atLineStart) write(\"\\n\")\n write(`${text}\\n`)\n }\n\n if (wired.banner.length > 0) write(`${wired.banner.join(\"\\n\")}\\n\\n`)\n\n // A one-shot run prints the answer and nothing else, because something is parsing it. Tool rows\n // are for a person watching, so they follow the same rule as the banner and the stats line.\n const showRows = !quiet && wired.once === undefined\n\n // Streaming goes through the bus rather than a callback: the CLI is a subscriber like any other,\n // which is what keeps the server and the CLI from needing different cores.\n let streaming = false\n let lastKind: \"text\" | \"reasoning\" | undefined\n\n // With a line-oriented dialect the invocation *is* text, so raw deltas would put `ACTION:` and\n // `END` in front of the person and run them into the answer. The filter comes from the agent\n // rather than being chosen here: which dialect is in play is config, and one place decides it.\n // One per turn, told where the steps end — it owns the paragraph break between them.\n let filter = source.streamFilter()\n\n const show = (text: string) => {\n if (text === \"\") return\n write(text)\n streaming = true\n }\n\n /**\n * One wildcard subscription, switching on type — not seven by name.\n *\n * Named subscriptions were right while this read a bus directly. They are not expressible over\n * a source, which hands out one stream, and that turns out to be the better shape for the same\n * reason `useTurn` already gives: a subscription list silently misses any event a later phase\n * adds, while a switch with no branch simply ignores it. `{ chunks: true }` is the source's\n * business now, which is where it belongs — this path has always needed per-token frames and\n * had to remember to ask.\n */\n const unsubscribe = wired.source.subscribe((event: AnyEvent) => {\n switch (event.type) {\n case \"model.result\":\n show(filter.endStep())\n return\n\n case \"model.chunk\": {\n const { delta, kind } = event.data\n if (kind === \"reasoning\" && wired.showReasoning !== true) return\n\n // A reasoning model streams its scratchpad and then its answer with no separator of\n // its own, so the two run together mid-sentence. The label is worth two lines: the\n // whole point of showing reasoning is being able to tell it apart from the reply.\n if (kind !== lastKind) {\n if (lastKind !== undefined) write(\"\\n\\n\")\n if (wired.showReasoning === true) {\n write(kind === \"reasoning\" ? \"· reasoning ·\\n\" : \"· reply ·\\n\")\n }\n lastKind = kind\n }\n\n // Reasoning is not parsed for tool calls, so it is not filtered for them either.\n if (kind === \"reasoning\") {\n write(delta)\n streaming = true\n return\n }\n show(filter.push(delta))\n return\n }\n\n case \"tool.result\": {\n if (!showRows) return\n const { slug, ok, latencyMs, truncated } = event.data\n row(\n ` · ${slug} — ${ok ? \"ok\" : \"failed\"} · ${latencyMs} ms${truncated ? \" · observation trimmed\" : \"\"}`,\n )\n return\n }\n\n // Every warning, and exempt from `showRows` like a gated call. It used to be one code —\n // `manifest_changed` — so an agent that rewrote its own configuration was reported and\n // everything else was not: a truncated reply, a repeated call, a compactor that silently\n // fell back to a mechanical digest, a prompt over the window. `showRows` exists to keep a\n // one-shot run free of *progress* rows, and a warning is not progress.\n case \"agent.warning\":\n row(` · ${event.data.message}\\n ${event.data.hint}`)\n return\n\n case \"tool.repair\":\n // Worth a line of its own: a silent repair looks like a slow turn.\n if (showRows)\n row(` · ${event.data.slugs.join(\", \")} — could not be used, asking again`)\n return\n\n // Deliberately NOT gated on `showRows`. Every other row here is for a person watching,\n // and suppressing them in a one-shot run is right — but a blocked write is the run doing\n // less than it was asked to, and a scripted caller parsing the output needs to know that\n // even more than a person does.\n case \"tool.gated\":\n row(` · ${event.data.slug} — blocked: ${event.data.reason}`)\n return\n\n // Also not gated on `showRows`. The ladder ran and the budget was still short, so history\n // was cut anyway — the same class as a blocked write: the run did less than it was asked\n // to, and for six phases the only trace was a field on `AssembledContext` nothing read.\n case \"context.dropped\":\n row(\n ` · context: ${event.data.messages} older message(s) did not fit the ${event.data.budget}-token budget and were left out`,\n )\n return\n\n default:\n return\n }\n })\n\n /**\n * A typed line that was a command rather than a prompt.\n *\n * Shared by both input branches, and driven by the same table the rich path uses. Before this,\n * the banner advertised `/help` and this path had no case for it, so it went to the model as a\n * prompt — a billed call answering a question about the CLI it knows nothing about.\n */\n const dispatch = async (\n trimmed: string,\n ): Promise<\"exit\" | \"restart\" | \"handled\" | \"prompt\"> => {\n const command = resolveSessionCommand(trimmed)\n if (command === undefined) return \"prompt\"\n switch (command.kind) {\n case \"exit\":\n return \"exit\"\n case \"restart\": {\n /**\n * Attached, this is a request to the host — and the loop does not go round.\n *\n * The same branch `App` takes, and it has to be here too for the reason the\n * both-paths guard exists one file over: a command handled on one output path and\n * not the other is invisible. Left alone, the plain path returned `\"restart\"`, the\n * attached loop re-banners, and it printed *\"the configuration on disk is now the\n * one in force\"* — a sentence about a rebuild that never happened, which is worse\n * than doing nothing because somebody would believe it.\n */\n const reload = source.reload\n if (reload === undefined) return \"restart\"\n try {\n const adopted = await reload()\n row(`reloaded ${adopted.join(\", \")} — this conversation continues`)\n } catch (error) {\n row(\n `could not reload: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n return \"handled\"\n }\n case \"new\":\n // The same outcome `/restart` returns, with a key in the box — which is exactly what the\n // rich path's `onNew` does. No new outcome value: the loop below already turns \"restart\"\n // into `RESTART`, and the box is what makes this a move rather than a rebuild in place.\n wired.switchTo.current = { key: newSessionKey(wired.random), reason: \"new\" }\n return \"restart\"\n case \"help\":\n row(sessionHelpText())\n return \"handled\"\n case \"tools\":\n row(toolsReport(await source.tools()))\n return \"handled\"\n case \"status\":\n row(\n wired.embedded === undefined\n ? await attachedStatus(source)\n : await sessionStatus(wired.embedded),\n )\n return \"handled\"\n case \"context\":\n row(await sessionContext(wired, sessionKey))\n return \"handled\"\n case \"reset\":\n await source.clearSession(sessionKey)\n row(\"session cleared — memory files on disk are untouched\")\n return \"handled\"\n case \"unknown\":\n row(unknownCommandText(command))\n return \"handled\"\n case \"command\":\n // A CLI command typed at the plain prompt. Not run here: the plain path is a pipe's\n // path, and a command that expects to own the terminal has no business in one. Named\n // rather than silently sent to the model, which is the failure this dispatch exists for.\n row(\n `${command.name} is a command, not a prompt — run it at a terminal, or in another shell as \\`${BRAND.slug} ${command.name}${command.rest === \"\" ? \"\" : ` ${command.rest}`}\\``,\n )\n return \"handled\"\n }\n }\n\n let controller: AbortController | undefined\n let cancelledAt = 0\n let exitCode: RunOutcome = EXIT_OK\n\n const onInterrupt = (rl = wired.reader.current): void => {\n if (controller !== undefined && !controller.signal.aborted) {\n cancelledAt = performance.now()\n controller.abort()\n return\n }\n // Closing the readline interface ends the `for await` loop, which returns through the\n // `finally` below. Calling process.exit here would discard a non-zero code set by an earlier\n // failed turn, and could truncate piped output mid-write.\n rl?.close()\n write(\"\\n\")\n }\n\n const runOne = async (input: string): Promise<void> => {\n controller = new AbortController()\n streaming = false\n lastKind = undefined\n filter = source.streamFilter()\n\n const result = await source.send(input, { sessionKey, signal: controller.signal })\n controller = undefined\n\n // The filter withholds a trailing line break, since it cannot know whether more follows.\n show(filter.end())\n if (streaming && !atLineStart) write(\"\\n\")\n else if (!streaming && result.text !== \"\") write(`${result.text}\\n`)\n\n // One formatter for every ending, shared with the transcript. The previous version had a\n // sentence for three of the six reasons and printed the `max_steps` one only when the reply was\n // empty — so an agent that stopped mid-task having produced prose said nothing at all.\n const note = endNote(result.reason, {\n steps: result.steps,\n durationMs: result.durationMs,\n ...(cancelledAt === 0 ? {} : { cancelledAfterMs: performance.now() - cancelledAt }),\n })\n if (note !== undefined) write(`\\n(${note})\\n`)\n if (result.reason === \"error\" && result.error !== undefined) {\n process.stderr.write(\n `\\n${result.error.code}: ${result.error.message}\\n hint: ${result.error.hint}\\n`,\n )\n }\n if (endedBadly(result.reason)) exitCode = EXIT_FAILURE\n\n if (!quiet && result.reason === \"final\") {\n write(\n ` ${result.tokens.prompt} prompt · ${result.tokens.output} output · ${result.durationMs} ms\\n\\n`,\n )\n }\n\n // Bound the memory a long piped session can hold: stdout to a pipe is asynchronous, and a\n // slow reader would otherwise let unwritten replies accumulate for the life of the process.\n await flushOutput()\n }\n\n const sigintHandler = () => onInterrupt()\n process.on(\"SIGINT\", sigintHandler)\n\n try {\n if (wired.once !== undefined) {\n await runOne(wired.once)\n return exitCode\n }\n\n if (process.stdin.isTTY !== true) {\n const rl = wired.reader.current ?? createInterface({ input: process.stdin })\n wired.reader.current = rl\n for await (const line of rl) {\n const trimmed = line.trim()\n if (trimmed === \"\") continue\n // Commands work in a pipe too. A script that pipes `/exit` means it — this branch\n // used to skip the word and keep reading, which is the one place the piped path\n // disagreed with the terminal about what a typed line meant.\n const outcome = await dispatch(trimmed)\n if (outcome === \"exit\") break\n if (outcome === \"restart\") {\n exitCode = RESTART\n break\n }\n if (outcome === \"handled\") continue\n await runOne(trimmed)\n }\n return exitCode\n }\n\n // `terminal: false` is the whole point of this branch.\n //\n // Node's readline decides for itself whether to run in terminal mode, by reading\n // `output.isTTY` — so at a terminal it repaints the prompt with cursor-control sequences\n // (`ESC[1G`, `ESC[0J`, `ESC[3G`) that the same command piped never emits. That silently\n // breaks the property plain mode exists for: `--plain` at a terminal must produce exactly\n // what a pipe produces. Only the rich path is allowed to move a cursor.\n //\n // The cost is that readline no longer echoes or edits: the tty driver does both, because\n // nothing here puts stdin in raw mode. Typing, backspace and Ctrl-D behave as they do in any\n // line-buffered program. Arrow-key history is lost on this path — the rich path owns that.\n const rl =\n wired.reader.current ??\n createInterface({\n input: process.stdin,\n output: process.stdout,\n prompt: PROMPT,\n terminal: false,\n })\n wired.reader.current = rl\n // Outside terminal mode readline never emits its own SIGINT, so the process-level handler\n // installed below is the only one that fires. It closes `reader`, which ends the loop.\n rl.prompt()\n for await (const line of rl) {\n const trimmed = line.trim()\n\n if (trimmed === \"\") {\n rl.prompt()\n continue\n }\n\n const outcome = await dispatch(trimmed)\n if (outcome === \"exit\") break\n if (outcome === \"restart\") {\n exitCode = RESTART\n break\n }\n if (outcome === \"handled\") {\n rl.prompt()\n continue\n }\n\n await runOne(trimmed)\n rl.prompt()\n }\n // Closed only when this really is the end. A restart hands the same reader to the next\n // runtime, and closing it here would end the session the restart was meant to continue.\n if (exitCode !== RESTART) {\n rl.close()\n wired.reader.current = undefined\n }\n return exitCode\n } finally {\n process.off(\"SIGINT\", sigintHandler)\n unsubscribe()\n }\n}\n\n/**\n * `/status` — what this agent is, and what is actually running.\n *\n * The human twin of context slot 2. That block tells the *model* its model, window, channels,\n * server and permissions on every turn; until this existed the person at the prompt could not see\n * any of it, which is the same asymmetry slot 2 was added to remove, pointed the other way.\n *\n * State, not configuration, for the same reason slot 2 is: told only what the manifest says, an\n * agent under `run` concluded its Telegram runtime had died and reported that nothing was listening\n * on its port — from inside the running process. Every statement was true of the file and false of\n * the moment. So a configured-but-not-started channel says exactly that, and names what does start\n * it.\n */\n/**\n * `/status` for a run that owns its runtime — the manifest, and what is actually running here.\n *\n * Takes the embedded pair rather than the whole `Wired` so the compiler decides where it can be\n * called from. Every sentence it prints is about *this process*: whether channels are connected in\n * this session, whether the port is bound here, which store file is open. An attached run answers\n * the same question about a different process and therefore has its own version — `attachedStatus`\n * — rather than this one with the interesting halves blanked out.\n */\nasync function sessionStatus(embedded: {\n readonly agent: Agent\n readonly runtime: RuntimeClass\n}): Promise<string> {\n const { agent, runtime } = embedded\n const described = agent.describe()\n const manifest = agent.manifest\n // `channels.started`, never \"are any registered\". A binding exists under `run` too, so reading\n // its presence as \"connected\" is decision 5.17's bug wearing a different hat — and it was,\n // until this screen was built and said so out loud.\n const configured = manifest.channels\n .filter((channel) => channel.enabled)\n .map((channel) => `${channel.id} (${channel.type})`)\n .join(\", \")\n const channels =\n configured === \"\"\n ? \"none — reached through this session and the HTTP API only\"\n : runtime.channels.started\n ? `${configured} — connected in this session`\n : `${configured} — configured, NOT running here; \\`serve\\` starts channels, \\`run\\` does not`\n\n const server = !manifest.server.enabled\n ? \"off\"\n : `enabled on ${manifest.server.host}:${manifest.server.port}, NOT bound here — \\`serve\\` binds it`\n\n // Per role, and only the roles carrying their own configuration: an agent can run three models on\n // three endpoints, and until this existed only main's window was reported anywhere at all — so a\n // compactor budgeting against the fallback's 8,192 had nothing that could say so.\n const windows = windowReport(manifest)\n const others = windows.filter(\n (entry) => entry.role !== \"main\" && entry.role === entry.configuredAs,\n )\n\n return keyValue([\n { label: \"agent\", value: `${described.id} (${described.name})` },\n {\n label: \"model\",\n value: `${described.model} · ${manifest.tools.dialect} · ${described.window} token window (${describeWindowSource(windows[0]?.window)})`,\n },\n ...others.map((entry) => ({\n label: entry.role,\n value: `${entry.modelId} · ${entry.window.contextWindow} token window (${describeWindowSource(entry.window)})`,\n })),\n { label: \"channels\", value: channels },\n { label: \"http api\", value: server },\n { label: \"store\", value: runtime.store.location },\n { label: \"background\", value: await supervision(runtime, described.id) },\n ])\n}\n\n/**\n * `/status` for a run that is a **view** — what it is attached to, and what the host says.\n *\n * Not `sessionStatus` with the runtime facts blanked out. The interesting sentences there are all\n * about the process rendering them — \"connected in this session\", \"NOT bound here\", which store\n * file is open — and every one of them would be a lie about an agent hosted somewhere else. The\n * question a person types `/status` to ask is the same; the true answer is different.\n *\n * Decision 5.17's failure, one process boundary out, is exactly what this exists to avoid: an agent\n * was told its Telegram channel was not running *in this session* while a `serve` in the next\n * terminal was polling it. The host's own view of its channels is the honest source, so that is\n * what is printed — with the pid and address, because \"somewhere else\" is not an answer somebody\n * can act on.\n */\nasync function attachedStatus(source: AgentSource): Promise<string> {\n const described = source.describe()\n const host = source.host\n const [tools, sessions] = await Promise.all([source.tools(), source.sessions()])\n return keyValue([\n { label: \"agent\", value: `${described.agentId} (${described.name})` },\n {\n label: \"attached to\",\n value: host === undefined ? \"a host\" : `${host.baseUrl} · pid ${host.pid}`,\n },\n {\n label: \"this session\",\n value: \"a view — the agent runs in the host, and stays running when this exits\",\n },\n { label: \"model\", value: `${described.model} · ${described.window} token window` },\n { label: \"dialect\", value: described.dialect },\n {\n label: \"tools\",\n value: `${tools.tools.length} pinned · ${tools.catalogueTokens} catalogue tokens per turn`,\n },\n { label: \"conversations\", value: `${sessions.length} on this agent` },\n {\n label: \"warnings\",\n value:\n described.warnings.length === 0\n ? \"none\"\n : described.warnings.map((warning) => warning.message).join(\"; \"),\n },\n ])\n}\n\n/**\n * `/context` — what is in the prompt right now, and what the percentage is a percentage of.\n *\n * Through `previewContext`, which calls `assembleContext` with the same arguments `send` does. A\n * second assembly here would answer a question about a prompt nothing sends, and would drift the\n * first time a slot moved — the rule the HTTP surface's context endpoint already follows.\n */\n/**\n * The view `/context` renders, from a live agent.\n *\n * Extracted from `sessionContext` so the source can hand one back without the formatter caring\n * where it came from. Everything but `windowSource` is `previewContext`'s own output — which is\n * exactly what `GET /v1/agents/:id/context` returns, because that route calls the same method with\n * the same arguments `send` does rather than rebuilding the argument list.\n */\nasync function contextViewOf(agent: Agent, sessionKey: string): Promise<ContextView> {\n const preview = await agent.previewContext({ sessionKey })\n const [main] = windowReport(agent.manifest)\n return {\n slots: preview.slots,\n history: preview.history,\n cache: preview.cache,\n total: preview.total,\n window: preview.window,\n windowSource: describeWindowSource(main?.window),\n wireTokens: preview.wireTokens,\n reserveOutput: preview.reserveOutput,\n calibration: preview.calibration,\n lastCompaction:\n preview.compactions === 0\n ? undefined\n : `${preview.compactions} stage${preview.compactions === 1 ? \"\" : \"s\"} run this session`,\n }\n}\n\nasync function sessionContext(wired: Wired, sessionKey: string): Promise<string> {\n return contextReport(await wired.source.context(sessionKey))\n}\n\n/**\n * Who, if anyone, is keeping this agent up — and the three answers are genuinely different.\n *\n * \"Not supervised\" was the first version, derived from this runtime not holding the lease. It was\n * wrong in the most misleading direction available: a REPL correctly *declines* the lease when a\n * service already holds it, so an agent that had been running as a daemon for a week reported\n * itself unsupervised to the person looking straight at it.\n */\nasync function supervision(runtime: RuntimeClass, agentId: string): Promise<string> {\n if (runtime.owned.includes(agentId)) return \"this session is serving this agent\"\n const lease = await runtime.store.leases.get(agentId)\n if (lease !== undefined && processAlive(lease.pid)) {\n return lease.mode === \"daemon\"\n ? `running as a background service · pid ${lease.pid} · \\`${BRAND.slug} daemon status ${agentId}\\``\n : `served by another session · pid ${lease.pid} (${lease.mode})`\n }\n return `not supervised — \\`${BRAND.slug} daemon install ${agentId}\\` keeps it running without a terminal`\n}\n",
|
|
30
|
-
"// src/errors.ts\nclass DispachError extends Error {\n code;\n hint;\n field;\n status;\n request;\n constructor(detail, context = {}) {\n super(detail.hint === undefined ? detail.message : `${detail.message}\n hint: ${detail.hint}`);\n this.name = \"DispachError\";\n this.code = detail.code;\n this.hint = detail.hint ?? \"\";\n this.field = detail.field;\n this.status = context.status;\n this.request = context.method === undefined || context.path === undefined ? undefined : { method: context.method, path: context.path };\n if (context.cause !== undefined)\n this.cause = context.cause;\n }\n}\nfunction transportError(error, context) {\n const because = error instanceof Error ? error.message : String(error);\n return new DispachError({\n code: \"transport_failed\",\n message: `${context.method} ${context.path} did not reach ${context.baseUrl}: ${because}`,\n hint: \"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe.\"\n }, { ...context, cause: error });\n}\nasync function errorFromResponse(response, context) {\n let detail;\n try {\n const body = await response.json();\n if (typeof body.error?.code === \"string\" && typeof body.error.message === \"string\") {\n detail = {\n code: body.error.code,\n message: body.error.message,\n ...body.error.hint === undefined ? {} : { hint: body.error.hint },\n ...body.error.field === undefined ? {} : { field: body.error.field }\n };\n }\n } catch {}\n return new DispachError(detail ?? {\n code: `http_${response.status}`,\n message: `${context.method} ${context.path} returned ${response.status} with no error body.`,\n hint: \"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it.\"\n }, { status: response.status, ...context });\n}\n\n// src/stream.ts\nimport { EVENT_TYPES, parseSSE } from \"@dispach/core/wire\";\nvar REAL_EVENTS = new Set(EVENT_TYPES);\nasync function* frames(body) {\n for await (const frame of parseSSE(streamToIterable(body))) {\n if (frame.event === undefined || frame.data === \"\")\n continue;\n let data;\n try {\n data = JSON.parse(frame.data);\n } catch {\n continue;\n }\n yield { name: frame.event, data };\n }\n}\nasync function* streamToIterable(stream) {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n return;\n if (value !== undefined)\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\nasync function* turnStreamItems(body) {\n for await (const { name, data } of frames(body)) {\n if (REAL_EVENTS.has(name)) {\n yield { kind: \"event\", event: data };\n continue;\n }\n const record = data ?? {};\n switch (name) {\n case \"turn.accepted\":\n yield {\n kind: \"accepted\",\n turnId: String(record.turnId ?? \"\"),\n sessionKey: String(record.sessionKey ?? \"\")\n };\n break;\n case \"stream.replay\":\n yield {\n kind: \"replay\",\n report: {\n state: record.state === \"ended\" ? \"ended\" : \"running\",\n events: Number(record.events ?? 0),\n truncated: record.truncated === true,\n dropped: Number(record.dropped ?? 0),\n chunks: record.chunks === \"start\" || record.chunks === \"partial\" ? record.chunks : \"none\"\n }\n };\n break;\n case \"stream.ended\":\n yield {\n kind: \"ended\",\n turnId: String(record.turnId ?? \"\"),\n status: String(record.status ?? \"unknown\"),\n steps: typeof record.steps === \"number\" ? record.steps : undefined,\n errorCode: typeof record.errorCode === \"string\" ? record.errorCode : undefined\n };\n break;\n case \"stream.unavailable\":\n yield {\n kind: \"unavailable\",\n turnId: String(record.turnId ?? \"\"),\n reason: String(record.reason ?? \"not observable from this process\")\n };\n break;\n default:\n break;\n }\n }\n}\nasync function* eventStreamItems(body) {\n for await (const { name, data } of frames(body)) {\n if (REAL_EVENTS.has(name)) {\n yield { kind: \"event\", event: data };\n continue;\n }\n if (name === \"stream.subscribed\") {\n const record = data ?? {};\n yield {\n kind: \"subscribed\",\n report: {\n agentId: typeof record.agentId === \"string\" ? record.agentId : null,\n types: Array.isArray(record.types) ? record.types : null,\n chunks: record.chunks === true,\n implied: typeof record.implied === \"string\" ? record.implied : undefined\n }\n };\n }\n }\n}\nasync function* textDeltas(items, options = {}) {\n for await (const item of items) {\n if (item.kind === \"replay\" && item.report.truncated && options.allowTruncated !== true) {\n throw new DispachError({\n code: \"replay_truncated\",\n message: `This turn's replay is missing its oldest ${item.report.dropped} event(s), so the text reconstructed from it would be incomplete.`,\n hint: \"Read the finished text from GET /v1/agents/:id/turns/:turnId, or pass { allowTruncated: true } to accept a fragment. Streaming from the start of a turn is never truncated — this only happens when reattaching to one that has already produced more events than the buffer holds.\"\n });\n }\n if (item.kind === \"unavailable\") {\n throw new DispachError({\n code: \"turn_not_observable\",\n message: `Turn ${item.turnId} is recorded as running but is not observable here: ${item.reason}.`,\n hint: \"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome.\"\n });\n }\n if (item.kind !== \"event\")\n continue;\n if (item.event.type !== \"model.chunk\")\n continue;\n const data = item.event.data;\n if (data.kind === \"reasoning\")\n continue;\n if (typeof data.delta === \"string\")\n yield data.delta;\n }\n}\n\n// src/index.ts\nfunction isEvent(event, type) {\n return event.type === type;\n}\nfunction createClient(options) {\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? fetch;\n const headers = (extra = {}) => ({\n ...options.token === undefined ? {} : { authorization: `Bearer ${options.token}` },\n ...extra\n });\n async function request(method, path, init = {}) {\n let response;\n try {\n response = await doFetch(`${base}${path}`, {\n method,\n headers: headers({\n ...init.body === undefined ? {} : { \"content-type\": \"application/json\" },\n ...init.accept === undefined ? {} : { accept: init.accept },\n ...init.headers\n }),\n ...init.body === undefined ? {} : { body: JSON.stringify(init.body) },\n ...init.signal === undefined ? {} : { signal: init.signal }\n });\n } catch (error) {\n throw transportError(error, { method, path, baseUrl: base });\n }\n if (!response.ok)\n throw await errorFromResponse(response, { method, path });\n return response;\n }\n async function json(method, path, init) {\n return await (await request(method, path, init ?? {})).json();\n }\n async function streamBody(path, signal) {\n const response = await request(\"GET\", path, {\n accept: \"text/event-stream\",\n ...signal === undefined ? {} : { signal }\n });\n if (response.body === null) {\n throw new DispachError({\n code: \"no_response_body\",\n message: `GET ${path} returned ${response.status} with no body to read.`,\n hint: \"An SSE route always has a body. A missing one means something between you and the server buffered the response — commonly a proxy without streaming enabled.\"\n }, { status: response.status, method: \"GET\", path });\n }\n return response.body;\n }\n function turnHandle(agentId, turnId, sessionKey, facts = {}) {\n const query = (opts) => opts?.chunks === true ? \"?chunks=true\" : \"\";\n const handle = {\n turnId,\n sessionKey,\n replayed: facts.replayed === true,\n async* stream(opts) {\n const body = await streamBody(`/v1/agents/${encodeURIComponent(agentId)}/turns/${encodeURIComponent(turnId)}/stream${query(opts)}`, opts?.signal);\n yield* turnStreamItems(body);\n },\n async* tokens(opts) {\n yield* textDeltas(handle.stream({ chunks: true, ...opts }), {\n ...opts?.allowTruncated === undefined ? {} : { allowTruncated: opts.allowTruncated }\n });\n },\n async text() {\n for await (const item of handle.stream()) {\n if (item.kind === \"ended\")\n break;\n if (item.kind === \"unavailable\")\n break;\n if (item.kind === \"event\" && item.event.type === \"turn.end\")\n break;\n }\n return (await handle.get()).text;\n },\n get: () => json(\"GET\", `/v1/agents/${encodeURIComponent(agentId)}/turns/${encodeURIComponent(turnId)}`),\n async stop() {\n await request(\"POST\", `/v1/agents/${encodeURIComponent(agentId)}/turns/${encodeURIComponent(turnId)}/stop`);\n }\n };\n return handle;\n }\n function agent(id) {\n const at = (suffix) => `/v1/agents/${encodeURIComponent(id)}${suffix}`;\n return {\n id,\n async send(text, opts) {\n const accepted = await json(\"POST\", at(\"/messages\"), {\n body: {\n text,\n ...opts?.sessionKey === undefined ? {} : { sessionKey: opts.sessionKey },\n ...opts?.deliver === undefined ? {} : { deliver: opts.deliver },\n ...opts?.from === undefined ? {} : { from: opts.from }\n },\n ...opts?.idempotencyKey === undefined ? {} : { headers: { \"idempotency-key\": opts.idempotencyKey } },\n ...opts?.signal === undefined ? {} : { signal: opts.signal }\n });\n return turnHandle(id, accepted.turnId, accepted.sessionKey, {\n replayed: accepted.replayed === true\n });\n },\n turn: (turnId) => turnHandle(id, turnId, \"\"),\n describe: () => json(\"GET\", at(\"\")),\n tools: () => json(\"GET\", at(\"/tools\")),\n skills: () => json(\"GET\", at(\"/skills\")),\n sessions: () => json(\"GET\", at(\"/sessions\")),\n messages: (sessionKey, options) => {\n const query = new URLSearchParams;\n if (options?.before !== undefined)\n query.set(\"before\", String(options.before));\n if (options?.limit !== undefined)\n query.set(\"limit\", String(options.limit));\n const suffix = query.size === 0 ? \"\" : `?${query.toString()}`;\n return json(\"GET\", at(`/sessions/${encodeURIComponent(sessionKey)}/messages${suffix}`));\n },\n clearSession: (sessionKey) => json(\"DELETE\", at(`/sessions/${encodeURIComponent(sessionKey)}`)),\n reload: () => json(\"POST\", at(\"/reload\"), {\n body: {}\n }),\n schedules: async () => (await json(\"GET\", at(\"/schedules\"))).schedules,\n approvals: async () => (await json(\"GET\", at(\"/approvals\"))).approvals,\n createSchedule: (schedule) => json(\"POST\", at(\"/schedules\"), { body: schedule }),\n updateSchedule: (scheduleId, patch) => json(\"PATCH\", at(`/schedules/${encodeURIComponent(scheduleId)}`), {\n body: patch\n }),\n deleteSchedule: async (scheduleId) => {\n await json(\"DELETE\", at(`/schedules/${encodeURIComponent(scheduleId)}`));\n },\n runSchedule: (scheduleId) => json(\"POST\", at(`/schedules/${encodeURIComponent(scheduleId)}/run`), { body: {} }),\n session: (sessionKey) => json(\"GET\", at(`/sessions/${encodeURIComponent(sessionKey)}`)),\n setPhase: (sessionKey, phase) => json(\"POST\", at(`/sessions/${encodeURIComponent(sessionKey)}/phase`), { body: { phase } }),\n approve: async (approvalId, granted) => {\n await json(\"POST\", at(`/approvals/${encodeURIComponent(approvalId)}`), {\n body: { granted }\n });\n },\n stop: (reason) => json(\"POST\", at(\"/stop\"), {\n body: reason === undefined ? {} : { reason }\n }),\n start: () => json(\"POST\", at(\"/start\"), { body: {} }),\n context: (opts) => {\n const params = new URLSearchParams;\n if (opts?.sessionKey !== undefined)\n params.set(\"sessionKey\", opts.sessionKey);\n if (opts?.input !== undefined)\n params.set(\"input\", opts.input);\n const query = params.size === 0 ? \"\" : `?${params.toString()}`;\n return json(\"GET\", at(`/context${query}`));\n }\n };\n }\n return {\n agent,\n agents: () => json(\"GET\", \"/v1/agents\"),\n health: () => json(\"GET\", \"/v1/health\"),\n async ready() {\n try {\n await request(\"GET\", \"/v1/ready\");\n return true;\n } catch (error) {\n if (error instanceof DispachError && error.status === 503)\n return false;\n throw error;\n }\n },\n provision: () => json(\"GET\", \"/v1/provision\"),\n keys: () => json(\"GET\", \"/v1/keys\"),\n createKey: (input) => json(\"POST\", \"/v1/keys\", { body: input }),\n revokeKey: (keyId) => json(\"DELETE\", `/v1/keys/${encodeURIComponent(keyId)}`),\n createAgent: (answers) => json(\"POST\", \"/v1/agents\", { body: { answers } }),\n async* events(opts) {\n const params = new URLSearchParams;\n if (opts?.agentId !== undefined)\n params.set(\"agentId\", opts.agentId);\n if (opts?.types !== undefined && opts.types.length > 0) {\n params.set(\"types\", opts.types.join(\",\"));\n }\n if (opts?.chunks === true)\n params.set(\"chunks\", \"true\");\n const query = params.size === 0 ? \"\" : `?${params.toString()}`;\n const body = await streamBody(`/v1/events${query}`, opts?.signal);\n yield* eventStreamItems(body);\n }\n };\n}\nexport {\n DispachError,\n createClient,\n isEvent\n};\n\n//# debugId=B5E8D32E95F7E32D64756E2164756E21\n//# sourceMappingURL=index.js.map\n",
|
|
30
|
+
"// src/errors.ts\nclass DispachError extends Error {\n code;\n hint;\n field;\n status;\n request;\n constructor(detail, context = {}) {\n super(detail.hint === undefined ? detail.message : `${detail.message}\n hint: ${detail.hint}`);\n this.name = \"DispachError\";\n this.code = detail.code;\n this.hint = detail.hint ?? \"\";\n this.field = detail.field;\n this.status = context.status;\n this.request = context.method === undefined || context.path === undefined ? undefined : { method: context.method, path: context.path };\n if (context.cause !== undefined)\n this.cause = context.cause;\n }\n}\nfunction transportError(error, context) {\n const because = error instanceof Error ? error.message : String(error);\n return new DispachError({\n code: \"transport_failed\",\n message: `${context.method} ${context.path} did not reach ${context.baseUrl}: ${because}`,\n hint: \"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe.\"\n }, { ...context, cause: error });\n}\nasync function errorFromResponse(response, context) {\n let detail;\n try {\n const body = await response.json();\n if (typeof body.error?.code === \"string\" && typeof body.error.message === \"string\") {\n detail = {\n code: body.error.code,\n message: body.error.message,\n ...body.error.hint === undefined ? {} : { hint: body.error.hint },\n ...body.error.field === undefined ? {} : { field: body.error.field }\n };\n }\n } catch {}\n return new DispachError(detail ?? {\n code: `http_${response.status}`,\n message: `${context.method} ${context.path} returned ${response.status} with no error body.`,\n hint: \"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it.\"\n }, { status: response.status, ...context });\n}\n\n// src/stream.ts\nimport { EVENT_TYPES, parseSSE } from \"@dispach/core/wire\";\nvar REAL_EVENTS = new Set(EVENT_TYPES);\nasync function* frames(body) {\n for await (const frame of parseSSE(streamToIterable(body))) {\n if (frame.event === undefined || frame.data === \"\")\n continue;\n let data;\n try {\n data = JSON.parse(frame.data);\n } catch {\n continue;\n }\n yield { name: frame.event, data };\n }\n}\nasync function* streamToIterable(stream) {\n const reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n return;\n if (value !== undefined)\n yield value;\n }\n } finally {\n reader.releaseLock();\n }\n}\nasync function* turnStreamItems(body) {\n for await (const { name, data } of frames(body)) {\n if (REAL_EVENTS.has(name)) {\n yield { kind: \"event\", event: data };\n continue;\n }\n const record = data ?? {};\n switch (name) {\n case \"turn.accepted\":\n yield {\n kind: \"accepted\",\n turnId: String(record.turnId ?? \"\"),\n sessionKey: String(record.sessionKey ?? \"\")\n };\n break;\n case \"stream.replay\":\n yield {\n kind: \"replay\",\n report: {\n state: record.state === \"ended\" ? \"ended\" : \"running\",\n events: Number(record.events ?? 0),\n truncated: record.truncated === true,\n dropped: Number(record.dropped ?? 0),\n chunks: record.chunks === \"start\" || record.chunks === \"partial\" ? record.chunks : \"none\"\n }\n };\n break;\n case \"stream.ended\":\n yield {\n kind: \"ended\",\n turnId: String(record.turnId ?? \"\"),\n status: String(record.status ?? \"unknown\"),\n steps: typeof record.steps === \"number\" ? record.steps : undefined,\n errorCode: typeof record.errorCode === \"string\" ? record.errorCode : undefined\n };\n break;\n case \"stream.unavailable\":\n yield {\n kind: \"unavailable\",\n turnId: String(record.turnId ?? \"\"),\n reason: String(record.reason ?? \"not observable from this process\")\n };\n break;\n default:\n break;\n }\n }\n}\nasync function* eventStreamItems(body) {\n for await (const { name, data } of frames(body)) {\n if (REAL_EVENTS.has(name)) {\n yield { kind: \"event\", event: data };\n continue;\n }\n if (name === \"stream.subscribed\") {\n const record = data ?? {};\n yield {\n kind: \"subscribed\",\n report: {\n agentId: typeof record.agentId === \"string\" ? record.agentId : null,\n types: Array.isArray(record.types) ? record.types : null,\n chunks: record.chunks === true,\n implied: typeof record.implied === \"string\" ? record.implied : undefined\n }\n };\n }\n }\n}\nasync function* textDeltas(items, options = {}) {\n for await (const item of items) {\n if (item.kind === \"replay\" && item.report.truncated && options.allowTruncated !== true) {\n throw new DispachError({\n code: \"replay_truncated\",\n message: `This turn's replay is missing its oldest ${item.report.dropped} event(s), so the text reconstructed from it would be incomplete.`,\n hint: \"Read the finished text from GET /v1/agents/:id/turns/:turnId, or pass { allowTruncated: true } to accept a fragment. Streaming from the start of a turn is never truncated — this only happens when reattaching to one that has already produced more events than the buffer holds.\"\n });\n }\n if (item.kind === \"unavailable\") {\n throw new DispachError({\n code: \"turn_not_observable\",\n message: `Turn ${item.turnId} is recorded as running but is not observable here: ${item.reason}.`,\n hint: \"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome.\"\n });\n }\n if (item.kind !== \"event\")\n continue;\n if (item.event.type !== \"model.chunk\")\n continue;\n const data = item.event.data;\n if (data.kind === \"reasoning\")\n continue;\n if (typeof data.delta === \"string\")\n yield data.delta;\n }\n}\n\n// src/index.ts\nfunction isEvent(event, type) {\n return event.type === type;\n}\nfunction createClient(options) {\n const base = options.baseUrl.replace(/\\/+$/, \"\");\n const doFetch = options.fetch ?? fetch;\n const headers = (extra = {}) => ({\n ...options.token === undefined ? {} : { authorization: `Bearer ${options.token}` },\n ...extra\n });\n async function request(method, path, init = {}) {\n let response;\n try {\n response = await doFetch(`${base}${path}`, {\n method,\n headers: headers({\n ...init.body === undefined ? {} : { \"content-type\": \"application/json\" },\n ...init.accept === undefined ? {} : { accept: init.accept },\n ...init.headers\n }),\n ...init.body === undefined ? {} : { body: JSON.stringify(init.body) },\n ...init.signal === undefined ? {} : { signal: init.signal }\n });\n } catch (error) {\n throw transportError(error, { method, path, baseUrl: base });\n }\n if (!response.ok)\n throw await errorFromResponse(response, { method, path });\n return response;\n }\n async function json(method, path, init) {\n return await (await request(method, path, init ?? {})).json();\n }\n async function streamBody(path, signal) {\n const response = await request(\"GET\", path, {\n accept: \"text/event-stream\",\n ...signal === undefined ? {} : { signal }\n });\n if (response.body === null) {\n throw new DispachError({\n code: \"no_response_body\",\n message: `GET ${path} returned ${response.status} with no body to read.`,\n hint: \"An SSE route always has a body. A missing one means something between you and the server buffered the response — commonly a proxy without streaming enabled.\"\n }, { status: response.status, method: \"GET\", path });\n }\n return response.body;\n }\n function turnHandle(agentId, turnId, sessionKey, facts = {}) {\n const query = (opts) => opts?.chunks === true ? \"?chunks=true\" : \"\";\n const handle = {\n turnId,\n sessionKey,\n replayed: facts.replayed === true,\n async* stream(opts) {\n const body = await streamBody(`/v1/agents/${encodeURIComponent(agentId)}/turns/${encodeURIComponent(turnId)}/stream${query(opts)}`, opts?.signal);\n yield* turnStreamItems(body);\n },\n async* tokens(opts) {\n yield* textDeltas(handle.stream({ chunks: true, ...opts }), {\n ...opts?.allowTruncated === undefined ? {} : { allowTruncated: opts.allowTruncated }\n });\n },\n async text() {\n for await (const item of handle.stream()) {\n if (item.kind === \"ended\")\n break;\n if (item.kind === \"unavailable\")\n break;\n if (item.kind === \"event\" && item.event.type === \"turn.end\")\n break;\n }\n return (await handle.get()).text;\n },\n get: () => json(\"GET\", `/v1/agents/${encodeURIComponent(agentId)}/turns/${encodeURIComponent(turnId)}`),\n async stop() {\n await request(\"POST\", `/v1/agents/${encodeURIComponent(agentId)}/turns/${encodeURIComponent(turnId)}/stop`);\n }\n };\n return handle;\n }\n function agent(id) {\n const at = (suffix) => `/v1/agents/${encodeURIComponent(id)}${suffix}`;\n return {\n id,\n async send(text, opts) {\n const accepted = await json(\"POST\", at(\"/messages\"), {\n body: {\n text,\n ...opts?.sessionKey === undefined ? {} : { sessionKey: opts.sessionKey },\n ...opts?.deliver === undefined ? {} : { deliver: opts.deliver },\n ...opts?.from === undefined ? {} : { from: opts.from }\n },\n ...opts?.idempotencyKey === undefined ? {} : { headers: { \"idempotency-key\": opts.idempotencyKey } },\n ...opts?.signal === undefined ? {} : { signal: opts.signal }\n });\n return turnHandle(id, accepted.turnId, accepted.sessionKey, {\n replayed: accepted.replayed === true\n });\n },\n turn: (turnId) => turnHandle(id, turnId, \"\"),\n describe: () => json(\"GET\", at(\"\")),\n tools: () => json(\"GET\", at(\"/tools\")),\n skills: () => json(\"GET\", at(\"/skills\")),\n sessions: () => json(\"GET\", at(\"/sessions\")),\n messages: (sessionKey, options) => {\n const query = new URLSearchParams;\n if (options?.before !== undefined)\n query.set(\"before\", String(options.before));\n if (options?.limit !== undefined)\n query.set(\"limit\", String(options.limit));\n const suffix = query.size === 0 ? \"\" : `?${query.toString()}`;\n return json(\"GET\", at(`/sessions/${encodeURIComponent(sessionKey)}/messages${suffix}`));\n },\n clearSession: (sessionKey) => json(\"DELETE\", at(`/sessions/${encodeURIComponent(sessionKey)}`)),\n reload: () => json(\"POST\", at(\"/reload\"), {\n body: {}\n }),\n schedules: async () => (await json(\"GET\", at(\"/schedules\"))).schedules,\n approvals: async () => (await json(\"GET\", at(\"/approvals\"))).approvals,\n createSchedule: (schedule) => json(\"POST\", at(\"/schedules\"), { body: schedule }),\n updateSchedule: (scheduleId, patch) => json(\"PATCH\", at(`/schedules/${encodeURIComponent(scheduleId)}`), {\n body: patch\n }),\n deleteSchedule: async (scheduleId) => {\n await json(\"DELETE\", at(`/schedules/${encodeURIComponent(scheduleId)}`));\n },\n runSchedule: (scheduleId) => json(\"POST\", at(`/schedules/${encodeURIComponent(scheduleId)}/run`), { body: {} }),\n config: () => json(\"GET\", at(\"/config\")),\n setConfig: (path, value, options) => json(\"PATCH\", at(\"/config\"), {\n body: {\n path,\n value,\n ...options?.confirm === undefined ? {} : { confirm: options.confirm }\n }\n }),\n session: (sessionKey) => json(\"GET\", at(`/sessions/${encodeURIComponent(sessionKey)}`)),\n setPhase: (sessionKey, phase) => json(\"POST\", at(`/sessions/${encodeURIComponent(sessionKey)}/phase`), { body: { phase } }),\n approve: async (approvalId, granted) => {\n await json(\"POST\", at(`/approvals/${encodeURIComponent(approvalId)}`), {\n body: { granted }\n });\n },\n stop: (reason) => json(\"POST\", at(\"/stop\"), {\n body: reason === undefined ? {} : { reason }\n }),\n start: () => json(\"POST\", at(\"/start\"), { body: {} }),\n context: (opts) => {\n const params = new URLSearchParams;\n if (opts?.sessionKey !== undefined)\n params.set(\"sessionKey\", opts.sessionKey);\n if (opts?.input !== undefined)\n params.set(\"input\", opts.input);\n const query = params.size === 0 ? \"\" : `?${params.toString()}`;\n return json(\"GET\", at(`/context${query}`));\n }\n };\n }\n return {\n agent,\n agents: () => json(\"GET\", \"/v1/agents\"),\n health: () => json(\"GET\", \"/v1/health\"),\n async ready() {\n try {\n await request(\"GET\", \"/v1/ready\");\n return true;\n } catch (error) {\n if (error instanceof DispachError && error.status === 503)\n return false;\n throw error;\n }\n },\n provision: () => json(\"GET\", \"/v1/provision\"),\n keys: () => json(\"GET\", \"/v1/keys\"),\n createKey: (input) => json(\"POST\", \"/v1/keys\", { body: input }),\n revokeKey: (keyId) => json(\"DELETE\", `/v1/keys/${encodeURIComponent(keyId)}`),\n createAgent: (answers) => json(\"POST\", \"/v1/agents\", { body: { answers } }),\n async* events(opts) {\n const params = new URLSearchParams;\n if (opts?.agentId !== undefined)\n params.set(\"agentId\", opts.agentId);\n if (opts?.types !== undefined && opts.types.length > 0) {\n params.set(\"types\", opts.types.join(\",\"));\n }\n if (opts?.chunks === true)\n params.set(\"chunks\", \"true\");\n const query = params.size === 0 ? \"\" : `?${params.toString()}`;\n const body = await streamBody(`/v1/events${query}`, opts?.signal);\n yield* eventStreamItems(body);\n }\n };\n}\nexport {\n DispachError,\n createClient,\n isEvent\n};\n\n//# debugId=E51A5D16959F38AC64756E2164756E21\n//# sourceMappingURL=index.js.map\n",
|
|
31
31
|
"/**\n * The conversation a resumed session paints, out of the messages the store kept.\n *\n * Pure, and extracted from `run` for one reason: it was four chained lambdas inside a function that\n * needs a live runtime to call, so the only way to check it was to resume a real session and look. The\n * shape it decides has already been wrong twice — first painting nothing at all under a banner that\n * said `17 message(s)`, then painting every turn except the ones that called a tool — and both times\n * the layers around it were individually correct.\n *\n * What counts as part of the conversation:\n *\n * - No `origin` — a person's message, or a reply the model wrote as its final answer.\n * - `origin: \"call\"` — a tool-calling step. Its prose is narration the live session *did* show as it\n * streamed, so excluding the row made a resumed transcript differ from the one that had been on\n * screen. Under NLT the row also holds the ACTION block, which `proseOf` removes.\n *\n * What does not, and why each is deliberate rather than unhandled:\n *\n * - `origin: \"observation\"` — text a stranger wrote. It reaches the model inside a fence; painting it\n * as part of the conversation would present it as something the agent or the person said.\n * - `origin: \"repair\"` and `origin: \"digest\"` — the runtime talking to itself about a malformed call\n * or a compacted history. True of the prompt, not of anything anybody said.\n * - `role: \"system\"` and `role: \"tool\"` — the assembled prefix and native tool results, neither of\n * which was ever on screen.\n */\n\nimport type { ChatMessage, DialectId } from \"@dispach/core\"\nimport { BRAND, proseOf } from \"@dispach/core\"\nimport { DIM_STYLE, RESET_STYLE } from \"#lib/const\"\nimport type { PriorMessage } from \"#transcript\"\n\n/**\n * `history` in order, reduced to what a reader saw. Empty prose is dropped, not painted blank.\n *\n * A step that called a tool without narrating it produces no text at all, and a blank message row in a\n * resumed transcript reads as content that failed to load.\n */\nexport function priorMessages(\n history: readonly ChatMessage[],\n dialect: DialectId,\n): readonly PriorMessage[] {\n const shown: PriorMessage[] = []\n for (const message of history) {\n if (message.origin !== undefined && message.origin !== \"call\") continue\n if (message.role !== \"user\" && message.role !== \"assistant\") continue\n const text = proseOf(message, dialect)\n if (text === \"\") continue\n shown.push({ role: message.role, text })\n }\n return shown\n}\n\n/**\n * The note a clean exit leaves on the shell's own screen.\n *\n * Nothing else survives. That was the decision and the alternate screen enforces it whether we agree or\n * not — so the one thing worth printing is not the conversation, which is in the store, but the command\n * that reaches it again.\n *\n * Two lines and faint, which is a change from the one bright line this used to be. The old form led with\n * `session <key> ·` and buried the command behind `resume with:`, so the half a person needs to *copy*\n * sat at the end of a sentence they had to read first. The key is not lost by dropping the prefix — it is\n * inside the command, which is the only place it is any use. And faint because this is the epilogue: the\n * work is over, and a line as loud as the output above it reads as one more result.\n *\n * The agent is named by the ref `resolveAgentRef` accepts rather than by a path, because a line you\n * cannot paste is a line that reads as help and is not.\n */\nexport function resumeNotice(input: {\n readonly ref: string | undefined\n readonly sessionKey: string\n}): string {\n // Named rather than omitted when the id is missing: a command with a placeholder in it says what is\n // wanted where it is wanted, and a command silently missing its agent looks complete and is not.\n const ref = input.ref ?? \"<your agent>\"\n const command = `${BRAND.slug} run ${ref} --session ${input.sessionKey}`\n // The blank line above separates it from whatever the shell had on screen before the session took it.\n // The reset precedes the last newline so the prompt after it is not faint.\n return `\\n${DIM_STYLE}Resume this session with:\\n${command}${RESET_STYLE}\\n`\n}\n\n/**\n * Why a banner is being printed, as the one sentence a person reads.\n *\n * Four answers, and they are genuinely different things to say: a `/restart` is about *configuration*\n * and would be a lie about a switch; a `/new` opened a conversation that did not exist a moment ago,\n * and the only thing worth saying about it is what happened to the one being left.\n *\n * Extracted from `bannerLines` because that function needs a live agent and a store to call, so the\n * sentence selection — the only part a person actually reads — could not be checked without resuming a\n * real session and looking. Exactly the reason `priorMessages` above lives here.\n *\n * The return is `undefined` for a first run: nothing has happened yet that needs explaining.\n */\nexport function reopenNote(\n reopened: \"first\" | \"restart\" | \"switch\" | \"new\",\n previousKey?: string,\n): string | undefined {\n switch (reopened) {\n case \"first\":\n return undefined\n case \"restart\":\n return \"restarted — the configuration on disk is now the one in force; the conversation continues from the store.\"\n case \"switch\":\n // What was left behind is worth naming: the previous conversation is still in the store, and\n // the key in the banner above is the one that reaches this one again.\n return \"switched conversation — the one you left is still in the store, under its own key.\"\n case \"new\":\n // By name, unlike the switch sentence. After a `/new` the conversation you left is on screen\n // nowhere — the picker lists it, but only once you know to go looking — and the whole promise\n // of the command is that nothing was destroyed. Claiming that without naming the key is\n // asking to be taken on trust.\n return previousKey === undefined\n ? \"new conversation — the one you left is still in the store, under its own key.\"\n : `new conversation — the one you left is ${previousKey}, still in the store. /sessions goes back to it.`\n }\n}\n",
|
|
32
32
|
"/**\n * What a chat view needs from an agent, and the two ways of supplying it.\n *\n * ## Why this exists\n *\n * `run` built a `Runtime` in its own process and handed the resulting `Agent` and `EventBus`\n * straight to the screen. That was right while the CLI *was* the product; it stopped being right\n * the moment a server is always on, because `run` then starts a **second** runtime for an agent\n * something else is already hosting. Two processes on one SQLite file is not two views of one\n * conversation — it is two writers, and slot 2 told the model as much (`declined`, decision 5.17),\n * which is the runtime being honest about a situation nobody wanted.\n *\n * So the screen takes an `AgentSource` instead. `embeddedSource` is today's behaviour, for the\n * cases where nothing else is hosting: a container, CI, `--ephemeral`, a machine whose bootstrap\n * was suppressed. `remoteSource` is the same shape over `/v1`, and is what a terminal gets when a\n * live host holds the agent.\n *\n * ## Why the two implementations are small\n *\n * Because the *views* were already projections. `toolsView` takes a structural `AgentToolsSource`\n * rather than an `Agent`, `ContextView` and `SessionRowSource` are plain data, and `endNote` lives\n * in core precisely so four callers cannot word a turn's ending four ways. Almost nothing here\n * formats anything; it fetches, and hands back the shapes the formatters already read.\n *\n * ## The one thing that is genuinely different\n *\n * **Cancellation.** Embedded, a turn is an in-process promise and an `AbortController` reaches it.\n * Attached, the turn belongs to the server — the recorded rule is that turns are detached from the\n * client connection and are never cancelled on disconnect — so stopping one is a *request*, naming\n * the turn. `send` takes a signal on both paths and each honours it its own way, so the caller\n * keeps one contract and `useTurn` never learns which it is talking to.\n */\n\nimport type { AnyEvent, ErrorDetail, StreamFilter, TurnEndReason } from \"@dispach/core\"\nimport { createNltStreamFilter, passThroughFilter } from \"@dispach/core/wire\"\nimport { priorMessages } from \"#lib/resume\"\nimport { type ContextView, type ToolsView, toolsView } from \"#lib/session-commands\"\nimport type { PriorMessage } from \"#transcript\"\n\n/** The facts a banner, a status line and a reasoning decision are made from. */\nexport interface SourceDescription {\n readonly agentId: string\n readonly name: string\n readonly model: string\n readonly dialect: string\n readonly window: number\n /** What the catalogue costs per turn — the figure `/tools` reports and a person trims against. */\n readonly catalogueTokens: number\n /** `\"none\"` when the model does not reason, which is what decides streaming it by default. */\n readonly thinking: string\n readonly warnings: readonly ErrorDetail[]\n}\n\n/** One conversation, as the session picker reads it. */\nexport interface SourceSession {\n readonly sessionKey: string\n readonly channel: string\n readonly turns: number\n readonly messages: number\n readonly lastActivityAt: string\n readonly phase?: string\n}\n\nexport interface SendOptions {\n readonly sessionKey: string\n readonly signal: AbortSignal\n}\n\n/**\n * How a turn ended, in the shape both renderers already read.\n *\n * `send` resolves with this rather than `void` because the plain path needs it: `endNote` takes a\n * reason and a step count, `endedBadly` decides the exit status, and the stats line is the one\n * thing a scripted run prints that is not the reply. Attached, every field comes off `turn.end`\n * and the `error` event rather than out of a returned object — which is the same information, and\n * is why this is a shape rather than core's `TurnResult`.\n */\nexport interface TurnOutcome {\n /** The reply. Empty on the streaming path, where it has already been written out. */\n readonly text: string\n readonly reason: TurnEndReason\n readonly steps: number\n readonly durationMs: number\n readonly tokens: { readonly prompt: number; readonly output: number }\n readonly error?: ErrorDetail\n}\n\nexport interface AgentSource {\n /**\n * Which of the two this is.\n *\n * Read by the banner and by `/status`, never to choose behaviour — a caller branching on this\n * is a caller that should have been given a method. The one legitimate use is telling somebody\n * what they are looking at, and that is exactly the sentence a person needs when the same\n * command does two things.\n */\n readonly kind: \"embedded\" | \"attached\"\n readonly agentId: string\n /** Where the agent actually runs, when it is somewhere else. */\n readonly host?: { readonly baseUrl: string; readonly pid: number }\n\n describe(): SourceDescription\n /**\n * Every event for this runtime, chunks included. Returns the unsubscribe.\n *\n * Chunks are not optional and never have been: this is the one wildcard subscriber in the tree\n * that genuinely wants per-token frames, which is why they are opt-in everywhere else. Dropping\n * the flag does not break anything loudly — the TUI simply stops streaming.\n */\n subscribe(handler: (event: AnyEvent) => void): () => void\n /** Resolves when the turn has ended, on both paths, so `busy` means the same thing. */\n send(text: string, options: SendOptions): Promise<TurnOutcome>\n /**\n * A fresh filter for the dialect in use.\n *\n * The wire carries **unfiltered** chunks — deliberately, since a stream nobody has filtered is\n * the one a debugger wants and the tool block is what the next model call sees. So an attached\n * view does the same work the embedded one does, from the dialect its description already\n * carries. Without it a chat bubble shows `ACTION: now / format: human / END`.\n */\n streamFilter(): StreamFilter\n history(sessionKey: string): Promise<readonly PriorMessage[]>\n sessions(): Promise<readonly SourceSession[]>\n clearSession(sessionKey: string): Promise<void>\n tools(): Promise<ToolsView>\n context(sessionKey: string): Promise<ContextView>\n /**\n * Ask the **host** to replace this agent. Present only when attached.\n *\n * Absent means the caller owns the runtime and rebuilds it itself, which is what `/restart` has\n * always done — the optional method is the capability, the same way `AppProps.catalogue` and\n * `status` are. Resolves with every agent that came back: replacing a supervisor replaces its\n * team, because they load from one manifest as one unit.\n */\n readonly reload?: () => Promise<readonly string[]>\n /** Release whatever this holds. Never stops the agent — an attached view owns nothing. */\n close(): Promise<void>\n}\n\n/** The parts of a live `Agent` this needs, structurally, so a test needs no runtime. */\nexport interface EmbeddedAgent {\n readonly id: string\n describe(): { readonly dialect: string; readonly catalogueTokens: number }\n readonly tools: {\n specs(): readonly {\n readonly slug: string\n readonly mutating: boolean\n readonly trust?: string\n readonly trustReason?: string\n readonly summary: string\n }[]\n }\n}\n\n/** The bus half, equally narrow. */\nexport interface EmbeddedBus {\n on(\n type: \"*\",\n handler: (event: AnyEvent) => void,\n options?: { readonly chunks?: boolean },\n ): () => void\n}\n\n/** `createNltStreamFilter` for `nlt`, a pass-through otherwise. One place decides it. */\nexport function filterFor(dialect: string): StreamFilter {\n return dialect === \"nlt\" ? createNltStreamFilter() : passThroughFilter()\n}\n\n/**\n * Today's behaviour, unchanged, behind the interface.\n *\n * Everything here is a one-liner over an object this process already holds, which is the point: the\n * embedded path must not get slower or subtler for the sake of the remote one, and a reader should\n * be able to see at a glance that nothing was smuggled in.\n */\nexport function embeddedSource(input: {\n readonly agent: EmbeddedAgent\n readonly bus: EmbeddedBus\n /** `agent.send`, narrowed — the loop's own signature, not re-declared here. */\n readonly send: (text: string, options: SendOptions & { source: \"repl\" }) => Promise<TurnOutcome>\n readonly history: (sessionKey: string) => Promise<readonly PriorMessage[]>\n readonly sessions: () => Promise<readonly SourceSession[]>\n readonly clearSession: (sessionKey: string) => Promise<void>\n readonly context: (sessionKey: string) => Promise<ContextView>\n readonly streamFilter: () => StreamFilter\n readonly description: SourceDescription\n}): AgentSource {\n return {\n kind: \"embedded\",\n agentId: input.agent.id,\n describe: () => input.description,\n // `{ chunks: true }` is not a tuning knob. Every other wildcard subscriber — `/v1/events`,\n // the WebSocket bridge, every plugin watcher — must stay off the per-token path, so the\n // flag is opt-in and this is the one caller that opts in.\n subscribe: (handler) => input.bus.on(\"*\", handler, { chunks: true }),\n send: (text, options) => input.send(text, { ...options, source: \"repl\" }),\n streamFilter: input.streamFilter,\n history: input.history,\n sessions: input.sessions,\n clearSession: input.clearSession,\n // Built from the live registry rather than fetched, and `toolsView` takes the structural\n // source rather than an `Agent`, which is why this is a projection and not a copy.\n tools: async () => toolsView(input.agent),\n context: input.context,\n // No `reload`: the caller owns the runtime and rebuilds it. `/restart` has always worked\n // that way, and an optional method is how this interface spells a capability.\n close: async () => {},\n }\n}\n\n/**\n * The same shape over `/v1`, for an agent something else is already hosting.\n *\n * Three things here are not translations of the embedded path, and each is a decision.\n *\n * **One subscription, not two.** The events come from `GET /v1/events` and the turn is followed on\n * that same stream. Using a turn's own `/stream` as well would deliver every chunk twice, because\n * the firehose already carries them — so `send` resolves by watching for its own `turn.end` rather\n * than by draining a second stream.\n *\n * **Cancellation is a request.** Turns are detached from the client connection by design and are\n * never cancelled on disconnect, so an abort here POSTs a stop naming the turn. It is best-effort\n * in one specific way worth knowing: the turn id only exists once the send has been accepted, so an\n * abort in the window before that is remembered and applied when the id arrives, rather than lost.\n *\n * **Filtering is ours.** The wire carries unfiltered chunks — deliberately, per the wire entry's\n * own docstring — so this rebuilds the dialect's filter from the description it already fetched.\n * Without it a reply renders as `ACTION: now / format: human / END`.\n */\n/**\n * The parts of the API client this needs, structurally.\n *\n * Narrow for the same two reasons `EmbeddedAgent` is — a fake is a plain object, and anything else\n * reached for is a type error rather than a surprise — and for a third: naming the client's own\n * exported type would put the product name in a `packages/cli` source file, which hard rule 3 and\n * a boundaries test both forbid. The real client satisfies this without being named.\n */\nexport interface ApiClient {\n agent(id: string): {\n send(\n text: string,\n options?: { readonly sessionKey?: string },\n ): Promise<{ readonly turnId: string }>\n turn(turnId: string): { stop(): Promise<void> }\n messages(sessionKey: string): Promise<{\n readonly messages: readonly {\n readonly role: string\n readonly content: string\n readonly origin?: string\n }[]\n }>\n clearSession(sessionKey: string): Promise<unknown>\n reload(): Promise<{ readonly adopted: readonly string[] }>\n tools(): Promise<\n readonly {\n readonly slug: string\n readonly summary: string\n readonly mutating: boolean\n readonly trust: string\n readonly trustReason?: string\n }[]\n >\n sessions(): Promise<readonly SourceSession[]>\n context(options: { readonly sessionKey: string }): Promise<unknown>\n }\n events(options: {\n readonly agentId?: string\n readonly chunks?: boolean\n readonly signal?: AbortSignal\n }): AsyncGenerator<{ readonly kind: string; readonly event?: AnyEvent }>\n}\n\nexport function remoteSource(input: {\n readonly client: ApiClient\n readonly agentId: string\n /** Fetched once at attach, so `describe()` can stay synchronous like the embedded one. */\n readonly description: SourceDescription\n readonly host: { readonly baseUrl: string; readonly pid: number }\n}): AgentSource {\n const agent = input.client.agent(input.agentId)\n /** Fans one SSE stream out to every subscriber, so attaching twice opens one connection. */\n const handlers = new Set<(event: AnyEvent) => void>()\n const abort = new AbortController()\n let pump: Promise<void> | undefined\n\n const start = (): void => {\n if (pump !== undefined) return\n pump = (async () => {\n for await (const item of input.client.events({\n agentId: input.agentId,\n // The one wildcard in the tree that genuinely wants tokens — see `AgentSource`.\n chunks: true,\n signal: abort.signal,\n })) {\n if (item.kind !== \"event\" || item.event === undefined) continue\n for (const handler of handlers) handler(item.event)\n }\n })().catch(() => {\n // A dropped stream is reported through the transcript by the turn that notices it, not\n // by throwing into a `for await` nobody is awaiting. Swallowing it here would be the\n // silent failure hard rule 8 forbids if this were the only signal — it is not: a send\n // whose `turn.end` never arrives rejects, which is where a person is actually looking.\n })\n }\n\n return {\n kind: \"attached\",\n agentId: input.agentId,\n host: input.host,\n describe: () => input.description,\n subscribe: (handler) => {\n handlers.add(handler)\n start()\n return () => handlers.delete(handler)\n },\n send: async (text, options) => {\n let stopped = false\n let turnId: string | undefined\n const onAbort = (): void => {\n stopped = true\n // Fire-and-forget: the abort is the caller saying stop, and a failed stop request\n // must not reject the send — the turn's own end is what resolves this.\n if (turnId !== undefined)\n void agent\n .turn(turnId)\n .stop()\n .catch(() => {})\n }\n options.signal.addEventListener(\"abort\", onAbort, { once: true })\n\n /**\n * The outcome, assembled from the stream rather than returned by the send.\n *\n * `POST /messages` answers 202 the moment the turn is accepted — turns are detached\n * from the client connection by design — so everything the plain path prints comes off\n * `turn.end`, and the failure detail off the `error` event that precedes it. Collected\n * here rather than by the caller because both renderers would otherwise assemble it,\n * and two assemblies of one fact is how they come to disagree.\n */\n let failure: ErrorDetail | undefined\n const ended = new Promise<TurnOutcome>((resolve) => {\n const off = (event: AnyEvent): void => {\n if (\n turnId !== undefined &&\n event.turnId !== undefined &&\n event.turnId !== turnId\n )\n return\n if (event.type === \"error\") {\n failure = event.data\n return\n }\n if (event.type !== \"turn.end\") return\n handlers.delete(off)\n resolve({\n // Empty on purpose: the chunks have already been written by whoever is\n // subscribed, and handing back a second copy would print the reply twice.\n text: \"\",\n reason: event.data.reason,\n steps: event.data.steps,\n durationMs: event.data.durationMs,\n tokens: event.data.tokens,\n ...(failure === undefined ? {} : { error: failure }),\n })\n }\n handlers.add(off)\n start()\n })\n\n try {\n const handle = await agent.send(text, { sessionKey: options.sessionKey })\n turnId = handle.turnId\n // Aborted while the request was in flight. The listener above had no id to name, so\n // it is applied here instead of being dropped — the window is small and a stop that\n // silently did nothing is the worst available outcome for a cancel key.\n if (stopped)\n void agent\n .turn(turnId)\n .stop()\n .catch(() => {})\n return await ended\n } finally {\n options.signal.removeEventListener(\"abort\", onAbort)\n }\n },\n streamFilter: () => filterFor(input.description.dialect),\n history: async (sessionKey) => {\n const page = await agent.messages(sessionKey)\n // Oldest-first for the screen; the API pages newest-first because that is how a UI\n // scrolls back. `priorMessages` decides what is shown — one rule, in `lib/resume.ts`,\n // because which origins count has been got wrong twice.\n return priorMessages(\n [...page.messages].reverse().map((message) => ({\n role: message.role as \"user\" | \"assistant\",\n content: message.content,\n ...(message.origin === undefined ? {} : { origin: message.origin }),\n })) as Parameters<typeof priorMessages>[0],\n input.description.dialect as Parameters<typeof priorMessages>[1],\n )\n },\n sessions: () => agent.sessions(),\n clearSession: async (sessionKey) => {\n await agent.clearSession(sessionKey)\n },\n tools: async () => {\n const tools = await agent.tools()\n return {\n dialect: input.description.dialect,\n catalogueTokens: input.description.catalogueTokens,\n tools: tools.map((tool) => ({\n slug: tool.slug,\n mutating: tool.mutating,\n trust: tool.trust,\n ...(tool.trustReason === undefined ? {} : { trustReason: tool.trustReason }),\n summary: tool.summary,\n })),\n }\n },\n context: async (sessionKey) => {\n // The route calls `previewContext` with the same arguments `send` does, so this is the\n // same object the embedded path builds — only `windowSource` is ours, because a\n // description carries the window and not where it came from.\n const preview = (await agent.context({ sessionKey })) as Omit<\n ContextView,\n \"windowSource\"\n > & {\n readonly compactions?: number\n }\n return {\n ...preview,\n windowSource: \"as the host resolved it\",\n ...(preview.lastCompaction === undefined && preview.compactions !== undefined\n ? {\n lastCompaction:\n preview.compactions === 0\n ? undefined\n : `${preview.compactions} stage${preview.compactions === 1 ? \"\" : \"s\"} run this session`,\n }\n : {}),\n }\n },\n reload: async () => (await agent.reload()).adopted,\n close: async () => {\n abort.abort()\n handlers.clear()\n },\n }\n}\n\n/**\n * Whether something else is already hosting this agent, and where.\n *\n * Both halves matter and neither is guessable. A lease says **who** is serving an agent right now;\n * its `base_url` — published after the bind, cleared on takeover — says where, because a manifest's\n * `server.port` is only what the file asked for and `--port 0` means the port does not exist until\n * the socket does. A host serving no HTTP has a lease and no address, and cannot be attached to.\n *\n * `processAlive` is checked inside `liveHostOf` for the recorded reason: a lease row is a claim,\n * not a fact, and a boot that failed *after* claiming leaves a fresh heartbeat with no process\n * under it. A dead pid outranks a recent timestamp.\n */\nexport interface LiveHost {\n readonly baseUrl: string\n readonly pid: number\n}\n\nexport function hostFrom(\n lease: { readonly pid: number; readonly baseUrl?: string } | undefined,\n): LiveHost | undefined {\n if (lease?.baseUrl === undefined || lease.baseUrl === \"\") return undefined\n return { baseUrl: lease.baseUrl, pid: lease.pid }\n}\n",
|
|
33
33
|
"/**\n * The `schedules` command — what is scheduled, when it fires next, and whether the last run worked.\n *\n * **It reads, enables and disables. It does not write a schedule.** Creating one here would be a\n * third writer beside the manifest and the API, each with its own idea of a valid expression, and\n * the manifest is where a schedule belongs — it survives a rebuild and shows up in a diff. What the\n * CLI adds is the two questions a file cannot answer: when this actually fires next, and how the\n * last run went.\n *\n * The distinction the listing exists to make is the one `status` had to learn: **running and working\n * are different questions.** A schedule can be perfectly configured, listed, enabled, and silently\n * failing every night — so `LAST` carries the outcome, not just the time.\n */\n\nimport { Runtime, type ScheduleRecord } from \"@dispach/core\"\nimport { ambientEnv } from \"#lib/ambient\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { onExit } from \"#lib/exit\"\nimport { BUILT_IN_PLUGINS, CHANNELS, scriptRunner, TOOL_PROVIDERS } from \"#lib/providers\"\nimport { ago } from \"#lib/render\"\nimport { storePath } from \"#lib/sandbox\"\nimport type { SchedulesOptions } from \"#lib/schema\"\n\nfunction pad(value: string, width: number): string {\n return value.length >= width ? value : value + \" \".repeat(width - value.length)\n}\n\n/**\n * When it next fires, in words.\n *\n * A schedule that is *disabled* has a due time — it is kept current so enabling it does not fire it\n * at once — and printing that time would say it is about to run. `off` is the true answer.\n */\nfunction nextIn(schedule: ScheduleRecord, now: number): string {\n if (!schedule.enabled) return \"off\"\n if (schedule.nextRunAt === undefined) return \"done\"\n const delta = Date.parse(schedule.nextRunAt) - now\n if (delta <= 0) return \"due\"\n const minutes = Math.round(delta / 60_000)\n if (minutes < 60) return `in ${minutes}m`\n const hours = Math.round(delta / 3_600_000)\n return hours < 48 ? `in ${hours}h` : `in ${Math.round(hours / 24)}d`\n}\n\n/** The outcome of the last run, which is the half of \"is this working\" a due time cannot answer. */\nfunction lastRun(schedule: ScheduleRecord, now: number): string {\n if (schedule.lastFiredAt === undefined) return \"never run\"\n const when = ago(schedule.lastFiredAt, now)\n if (schedule.lastStatus === \"error\") return `FAILED ${when}`\n return `ok ${when}`\n}\n\nfunction printList(schedules: readonly ScheduleRecord[], now: number): void {\n if (schedules.length === 0) {\n // Exit 0: an agent with no schedules is a correct answer to the question asked. The line\n // says where they come from, because \"none\" alone leaves somebody looking for a subcommand.\n process.stdout.write(\"no schedules — add a `schedules:` block to the manifest\\n\")\n return\n }\n\n const idWidth = Math.max(8, ...schedules.map((s) => s.id.length))\n const whenWidth = Math.max(4, ...schedules.map((s) => `${s.kind} ${s.expr}`.length))\n process.stdout.write(\n `${pad(\"SCHEDULE\", idWidth)} ${pad(\"WHEN\", whenWidth)} ${pad(\"NEXT\", 7)} LAST\\n`,\n )\n for (const schedule of schedules) {\n process.stdout.write(\n `${pad(schedule.id, idWidth)} ${pad(`${schedule.kind} ${schedule.expr}`, whenWidth)} ` +\n `${pad(nextIn(schedule, now), 7)} ${lastRun(schedule, now)}\\n`,\n )\n }\n\n // Named once at the bottom rather than as a column: it is true of every row and a column would\n // spend width repeating it.\n const failing = schedules.filter((s) => s.lastStatus === \"error\")\n if (failing.length > 0) {\n process.stdout.write(\n `\\n${failing.length} failing — \\`schedules --id ${failing[0]?.id}\\` for the error\\n`,\n )\n }\n}\n\nfunction printOne(schedule: ScheduleRecord): void {\n const rows: [string, string][] = [\n [\"kind\", `${schedule.kind} ${schedule.expr}`],\n [\"timezone\", schedule.timezone ?? \"(host)\"],\n [\"task\", schedule.task],\n [\n \"deliver\",\n schedule.deliverChannel === undefined\n ? \"none — the reply reaches the event stream only\"\n : `${schedule.deliverChannel} → ${schedule.deliverTo}`,\n ],\n [\"session\", schedule.sessionMode],\n [\"model role\", schedule.role ?? \"main\"],\n [\"enabled\", schedule.enabled ? \"yes\" : \"no\"],\n [\"declared in\", schedule.origin === \"manifest\" ? \"agent.yaml\" : \"the API\"],\n [\"next run\", schedule.nextRunAt ?? \"(never again)\"],\n [\"runs\", String(schedule.runs)],\n [\"last run\", schedule.lastFiredAt ?? \"never\"],\n [\"last status\", schedule.lastStatus ?? \"-\"],\n ]\n if (schedule.lastError !== undefined) rows.push([\"last error\", schedule.lastError])\n\n const width = Math.max(...rows.map(([label]) => label.length))\n process.stdout.write(`${schedule.id}\\n`)\n for (const [label, value] of rows) {\n process.stdout.write(` ${pad(label, width)} ${value}\\n`)\n }\n}\n\n/** One address this agent has actually been reached on, and can therefore deliver to. */\nexport interface Recipient {\n readonly channelId: string\n readonly address: string\n readonly lastSeen: string\n}\n\n/**\n * Addresses `deliver.to` can name, derived from sessions this agent has actually had.\n *\n * **Observed, never guessed.** The alternative — asking the transport to resolve a handle — is the\n * thing that cannot work: Telegram will not tell a bot the chat id behind an `@name`, and a private\n * chat has no other address. What the store holds is the id a real inbound message arrived on, which\n * is the one value known to route.\n *\n * Filtered to *declared channel ids*, so `local`, `api` and `schedule` sessions are left out. They\n * are sessions and they are not places a reply can be sent, and listing them under a heading that\n * says \"what deliver.to takes\" would be four wrong answers beside one right one.\n *\n * Pure, and takes plain rows rather than a store, so the shaping is testable without a runtime.\n */\nexport function recipientsFrom(\n sessions: readonly {\n readonly channel: string\n readonly peerId: string\n readonly lastActivityAt: string\n }[],\n channelIds: readonly string[],\n): readonly Recipient[] {\n const declared = new Set(channelIds)\n const latest = new Map<string, Recipient>()\n\n for (const session of sessions) {\n if (!declared.has(session.channel)) continue\n const key = `${session.channel}\\u0000${session.peerId}`\n const seen = latest.get(key)\n // One row per address, carrying the most recent contact: the same peer opens a new session\n // per thread, and three rows for one person is a list that has to be read twice.\n if (seen !== undefined && seen.lastSeen >= session.lastActivityAt) continue\n latest.set(key, {\n channelId: session.channel,\n address: session.peerId,\n lastSeen: session.lastActivityAt,\n })\n }\n\n return [...latest.values()].sort((a, b) =>\n a.channelId === b.channelId\n ? b.lastSeen.localeCompare(a.lastSeen)\n : a.channelId.localeCompare(b.channelId),\n )\n}\n\nfunction printRecipients(recipients: readonly Recipient[], now: number): void {\n if (recipients.length === 0) {\n // Exit 0 and say why it is empty. \"None\" on its own reads as a broken query, and the real\n // cause is almost always that nobody has messaged the agent yet.\n process.stdout.write(\n \"no addresses yet — this agent has had no conversation on a declared channel.\\n\" +\n \" An address appears here once a first message arrives on one.\\n\",\n )\n return\n }\n\n const channelWidth = Math.max(7, ...recipients.map((r) => r.channelId.length))\n const addressWidth = Math.max(7, ...recipients.map((r) => r.address.length))\n process.stdout.write(\n `${pad(\"CHANNEL\", channelWidth)} ${pad(\"ADDRESS\", addressWidth)} LAST SEEN\\n`,\n )\n for (const recipient of recipients) {\n process.stdout.write(\n `${pad(recipient.channelId, channelWidth)} ${pad(recipient.address, addressWidth)} ` +\n `${ago(recipient.lastSeen, now)}\\n`,\n )\n }\n\n // The whole reason the listing exists, so it is not left to be inferred from the shape of the\n // values. A handle is what `allowFrom` holds and what a person recognises, and for a private\n // chat it is the one thing that cannot work.\n process.stdout.write(\n \"\\nUse an ADDRESS in deliver.to. On Telegram an @name addresses a channel and\\n\" +\n \"never a person — a private chat is reached by the numeric id above.\\n\",\n )\n}\n\nexport async function schedulesCommand(options: SchedulesOptions): Promise<number> {\n const runtime = await Runtime.create({\n agents: [options.manifestPath],\n // The sandbox store — the same one `serve` writes to, or this inspects nothing.\n store: options.store ?? storePath(),\n toolProviders: TOOL_PROVIDERS,\n builtInPlugins: BUILT_IN_PLUGINS,\n scriptRunner: scriptRunner(),\n channels: CHANNELS,\n env: ambientEnv([options.manifestPath]),\n // Read-only, and a lease is a claim to *serve*. Taking one here would make a listing refuse\n // to run while the agent is actually being served, which is when it is most wanted.\n lease: false,\n })\n onExit(() => runtime.stop(\"cli-exit\"))\n\n const agent = runtime.list()[0]\n if (agent === undefined) throw new Error(\"The manifest produced no agent.\")\n const now = Date.now()\n\n for (const [id, enabled] of [\n [options.enable, true],\n [options.disable, false],\n ] as const) {\n if (id === undefined) continue\n const existing = await agent.store.schedules.get(agent.id, id)\n if (existing === undefined) {\n process.stderr.write(\n `no schedule \"${id}\" on ${agent.id}\\n` +\n \" hint: run `schedules` with no flags to see what this agent has.\\n\",\n )\n return EXIT_FAILURE\n }\n\n // **Refused for a manifest-owned schedule, rather than written and silently undone.**\n //\n // The manifest owns the schedules it declares — reconciliation at the next boot restores\n // every field from the file, `enabled` included. Writing the store here therefore reported\n // success on a change that lasted until the next start of the process, which is rule 8's\n // exact shape: the flag worked, the listing agreed, and one restart later it was back on.\n // Caught by running the two commands in sequence rather than by reading either.\n //\n // Not fixed by editing `agent.yaml` from here: `manifest/edit.ts` is deliberately the one\n // writer, and a schedule lives in a sequence whose index this command has no business\n // knowing. Naming the edit is more useful than performing it — it is one line, it shows up\n // in a diff, and it survives.\n if (existing.origin === \"manifest\") {\n process.stderr.write(\n `${id} is declared in agent.yaml, so the manifest decides whether it runs.\\n` +\n ` Writing it here would last until the next start — reconciliation restores every\\n` +\n ` field from the file, enabled included.\\n\\n` +\n ` hint: set \\`enabled: ${enabled}\\` on the \"${id}\" entry under schedules: in\\n` +\n ` ${options.manifestPath}\\n`,\n )\n return EXIT_FAILURE\n }\n\n await agent.store.schedules.setEnabled(agent.id, id, enabled, new Date(now).toISOString())\n // Said plainly, because the surprising reading is the other one: enabling does not fire.\n process.stdout.write(\n enabled\n ? `${id} enabled — it fires at its next occurrence, not now\\n`\n : `${id} disabled — still listed, and it keeps its place in the sequence\\n`,\n )\n }\n\n if (options.recipients === true) {\n const recipients = recipientsFrom(\n await agent.store.sessions.list(agent.id),\n agent.manifest.channels.map((channel) => channel.id),\n )\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify({ recipients }, null, 2)}\\n`)\n return EXIT_OK\n }\n printRecipients(recipients, now)\n return EXIT_OK\n }\n\n const schedules = await agent.store.schedules.list(agent.id)\n\n if (options.json) {\n process.stdout.write(`${JSON.stringify({ schedules }, null, 2)}\\n`)\n return EXIT_OK\n }\n\n if (options.id !== undefined) {\n const one = schedules.find((schedule) => schedule.id === options.id)\n if (one === undefined) {\n process.stderr.write(`no schedule \"${options.id}\" on ${agent.id}\\n`)\n return EXIT_FAILURE\n }\n printOne(one)\n return EXIT_OK\n }\n\n if (options.enable === undefined && options.disable === undefined) {\n printList(schedules, now)\n }\n return EXIT_OK\n}\n",
|
|
34
|
-
"/**\n * The `serve` command: `<binary> serve <manifest> [--port N] [--host H]`.\n *\n * Boots a runtime with channels started, binds the HTTP surface, and stays up until interrupted.\n * The only long-running command in the binary, and the only one that opens a listening socket.\n *\n * **Channels start here and nowhere else.** `run` constructs the same runtime with\n * `startChannels: false`, because a REPL that silently began answering Telegram messages while you\n * typed at it would be a surprise, and a one-shot `run --input` that opened a long-poll would hang\n * on exit. The flag decides *whether*, never *when* — either way nothing connects before\n * `runtime.ready`.\n *\n * No Ink. A server writes lines to stdout and is very often not attached to a terminal at all; a\n * rendering framework on this path would cost more than the whole command and produce escape codes\n * in a log file.\n */\n\nimport {\n AgentManifestSchema,\n BRAND,\n EventBus,\n HarnessError,\n loadManifest,\n Runtime,\n} from \"@dispach/core\"\nimport {\n claimCommand,\n claimUrl,\n createApprovalRegistry,\n createClaimTicket,\n serve,\n} from \"@dispach/server\"\nimport { ambientEnv } from \"#lib/ambient\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { claimSignals, onExit } from \"#lib/exit\"\nimport { hostableAgents, manifestForId } from \"#lib/lifecycle\"\nimport {\n BUILT_IN_PLUGINS,\n CHANNEL_IDS,\n CHANNELS,\n PROVIDER_IDS,\n scriptRunner,\n TOOL_PROVIDERS,\n} from \"#lib/providers\"\nimport { provisionAgent, provisionSteps } from \"#lib/provision\"\nimport { agentsDir, storePath } from \"#lib/sandbox\"\n\nexport interface ServeOptions {\n /**\n * Zero or more manifests. The process hosts every agent they produce.\n *\n * Plural since 16.2a: decision 8.5 has said \"one process hosts N agents\" since the beginning\n * and core was built that way — `RuntimeOptions.agents` is already an array — so a single path\n * here was the only thing pinning the product to one agent.\n *\n * **Empty means the sandbox's agents**, which is what the service unit runs and what makes the\n * product always-on: a host that has to be told which agents to serve cannot serve one that was\n * provisioned after it started. Naming manifests is the container's shape, where the agent\n * arrives on a mount and the sandbox is not the inventory.\n */\n readonly manifestPaths: readonly string[]\n readonly port?: number\n readonly host?: string\n readonly store?: string\n /** Print a one-time claim even when a key already exists. The lockout escape. */\n readonly claim?: boolean\n readonly json?: boolean\n}\n\n/**\n * The `server:` block a manifest that declares none resolves to.\n *\n * Asked of the **schema** rather than written out here, so a bare `serve` and a manifest with no\n * `server:` block cannot come to disagree about the port — which they would the first time somebody\n * changed the default in one place. Parsing an empty object is the cheapest way to ask a Zod schema\n * what its defaults are.\n */\nfunction defaultServerConfig(): ReturnType<typeof AgentManifestSchema.parse>[\"server\"] {\n return AgentManifestSchema.shape.server.parse({})\n}\n\nexport async function serveCommand(options: ServeOptions): Promise<number> {\n const env = ambientEnv(options.manifestPaths)\n\n /**\n * What to host, and what is switched off.\n *\n * Read before the runtime exists, because it decides which agents the runtime is *asked* for —\n * a disabled agent is not loaded at all, so there is nothing to filter afterwards. The switch is\n * honoured for an explicitly named manifest too, and that is deliberate: the launchd trap this\n * table is modelled on is precisely a job that installs cleanly, reports success and silently\n * never starts, and the cure is not to make the durable state easy to bypass — it is to say so.\n */\n // The same path the runtime will open, not the sandbox default: `serve --store` exists, and\n // a host reading its on/off switch from a different database than the one it serves out of\n // is wrong in exactly the configuration that is easiest to miss.\n const storeFile = options.store ?? storePath()\n const hostable = await hostableAgents(options.manifestPaths, env, storeFile)\n const switchedOff = hostable.filter((entry) => !entry.enabled)\n const wanted = hostable.filter((entry) => entry.enabled)\n\n const manifests = wanted.map((entry) => ({\n path: entry.manifestPath,\n loaded: loadManifest(entry.manifestPath, {\n knownProviders: PROVIDER_IDS,\n knownChannels: CHANNEL_IDS,\n env,\n }),\n }))\n /**\n * **Zero agents is a running server, not a failure.**\n *\n * The whole point of an always-on host is that the API exists before there is anything to talk\n * to: the binary is installed, the server is up, and provisioning reaches it. A refusal here\n * would make the first-run experience \"install, then find something to serve, then start\", and\n * would turn a container whose only agent somebody stopped into a crash loop.\n *\n * So the server config comes from the first manifest when there is one, and from the schema's\n * defaults when there is not — which is the same thing a manifest that declares no `server:`\n * block resolves to.\n */\n const first = manifests[0]\n const loaded = first?.loaded\n const config = loaded?.manifest.server ?? defaultServerConfig()\n\n /**\n * **The bind is process-level, so a disagreement about it is refused rather than ignored.**\n *\n * One process, one socket, one token — so with several manifests the server config can only\n * come from one of them, and silently taking the first would make a manifest that carefully\n * declares `port: 7500` a file whose setting does nothing. That is the \"looks configured and is\n * not\" shape, and it is worse here than elsewhere because the symptom is a port somebody else\n * is already using.\n *\n * Compared after defaults are applied, which is what makes this correct rather than pedantic:\n * an unset `port` *is* 7420, so a manifest that says 7420 and one that says nothing agree, and\n * one that says 7500 disagrees with both.\n */\n for (const entry of manifests.slice(1)) {\n const other = entry.loaded.manifest.server\n for (const [field, mine, theirs, settled] of [\n // **A flag settles the question, so it also settles the disagreement.** `--port` and\n // `--host` override every manifest, so refusing because two of them disagree about a\n // value nothing is going to read would be a refusal the operator has already answered.\n // `tokenEnv` has no flag, so a disagreement there is always live.\n [\"server.port\", config.port, other.port, options.port !== undefined],\n [\"server.host\", config.host, other.host, options.host !== undefined],\n [\"server.tokenEnv\", config.tokenEnv, other.tokenEnv, false],\n ] as const) {\n if (settled || mine === theirs) continue\n throw new HarnessError({\n code: \"serve_bind_conflict\",\n message: `${first?.path ?? \"the first manifest\"} sets ${field} to ${String(mine)} and ${entry.path} sets it to ${String(theirs)}.`,\n hint: \"One process binds one socket with one token, so these have to agree. Make them match, or run the disagreeing agent in its own process — a second `serve` on its own port.\",\n field,\n })\n }\n }\n // Flags win over the manifest: the manifest is the deployment's intent and a flag is this\n // invocation's. `--port 0` is honoured — it means \"any free port\", which a test wants.\n const port = options.port ?? config.port\n const host = options.host ?? config.host\n // `loaded.env`, never `env`. `ambientEnv` returns the *process* environment — the agent's own\n // `.env` beside the manifest is layered in by `loadManifest`, which is why every other\n // credential in this runtime is read from the manifest's live env. Reading the ambient one\n // here meant a token sitting in the agent's `.env` was invisible, and the banner said\n // \"unauthenticated\" while the file plainly had it. Same mistake `Agent.create` documents:\n // the manifest's live env, not the ambient one.\n // `loaded.env`, never `env`. `ambientEnv` returns the *process* environment; the agent's own\n // `.env` beside the manifest is layered in by `loadManifest`. With no manifest at all there is\n // no agent env to layer, so the process environment is the only source there is — which is the\n // service unit's shape, where the variable comes from the unit definition.\n const token = loaded === undefined ? env[config.tokenEnv] : loaded.env[config.tokenEnv]\n\n // Set by the generated service definition and by nothing else, so this is a fact rather than a\n // guess. `ppid === 1` would also be true of any orphaned process, and getting it wrong means\n // telling someone to press ctrl-c at a log file.\n const asDaemon = env[`${BRAND.envPrefix}SERVICE`] !== undefined\n\n // Subscribed BEFORE the runtime exists, which is what the `bus` option is for. Channels start\n // inside `Runtime.create` — after `runtime.ready`, but still inside the call — so a listener\n // attached afterwards misses every status and error they emitted on the way up. Same trap as\n // the boot warnings that landed in an empty room for weeks: anything true during boot has to be\n // subscribed to before boot.\n const bus = new EventBus({ runtimeId: `rt_${Date.now().toString(36)}` })\n if (options.json !== true) {\n bus.on(\"agent.channel.status\", (event) => {\n const data = event.data as {\n channelId: string\n status: string\n detail?: string\n input?: { kind: string; expiresAt?: string }\n }\n /**\n * A `needs_input` names where the payload is, and never prints it.\n *\n * The payload is a QR's bytes — unreadable in a log, and hundreds of characters of it\n * would bury the sentence that matters. But a line saying only \"needs_input\" is the\n * 57 MB-log failure in one line: true, and no route to acting on it. The agent\n * resource carries the payload because `statusOf` returns it, so that is what this\n * points at.\n */\n const waiting =\n data.input === undefined\n ? \"\"\n : ` (${data.input.kind}${\n data.input.expiresAt === undefined\n ? \"\"\n : `, expires ${data.input.expiresAt}`\n } — GET /v1/agents/${event.agentId ?? \"\"} carries it)`\n process.stdout.write(\n ` ${data.channelId}: ${data.status}${data.detail === undefined ? \"\" : ` — ${data.detail}`}${waiting}\\n`,\n )\n })\n bus.on(\"agent.channel.error\", (event) => {\n const data = event.data as { channelId: string; message: string; hint: string }\n process.stderr.write(` ${data.channelId}: ${data.message}\\n hint: ${data.hint}\\n`)\n })\n // The one thing a person watching a bot most wants to see, and it is otherwise only in the\n // event stream: who was refused, and the line that would let them in.\n bus.on(\"agent.channel.rejected\", (event) => {\n const data = event.data as { channelId: string; reason: string; detail: string }\n process.stdout.write(` ${data.channelId}: ${data.reason} — ${data.detail}\\n`)\n })\n }\n\n /**\n * Created before the runtime, because the runtime is constructed *with* the approver.\n *\n * That ordering is the whole reason this lives here and not inside `serve()`: `Runtime.create`\n * takes `approve` and cannot hand back the function it was built with, so the registry has to\n * exist first and then be given to both. Same shape as the shared `running` map, one layer\n * further out.\n *\n * Supplying it is also what silences `confirm_without_approver` — `Agent.create` keys that\n * warning on `approve` being absent, so an agent with `onMutate: \"confirm\"` stops warning under\n * `serve` and keeps warning under `run`, which is exactly true of the two surfaces today.\n */\n const approvals = createApprovalRegistry()\n\n const runtime = await Runtime.create({\n agents: manifests.map((entry) => entry.path),\n // The seam `ToolContext.approve` declared in Phase 3 and nothing ever filled. A blocked\n // call now emits `approval.requested` and waits for a POST; an unanswered one ends with the\n // turn, because core races the approver against the turn's own signal rather than starting\n // a second clock.\n approve: approvals.approver,\n env,\n bus,\n toolProviders: TOOL_PROVIDERS,\n builtInPlugins: BUILT_IN_PLUGINS,\n scriptRunner: scriptRunner(),\n channels: CHANNELS,\n // The one call site that passes this. See the file comment.\n startChannels: true,\n // Same rule and the same reason: `serve` is the only command that fires schedules. A REPL\n // that started firing them while somebody typed at it would be a surprise, and a one-shot\n // `run --input` that armed a timer would not exit.\n startSchedules: true,\n // `run` and `sessions` have resolved this default since the sandbox landed; `serve` never\n // did, so it silently took core's `\":memory:\"` — correct as a *library* default, since\n // constructing a Runtime must not create a directory in someone's working tree, and wrong\n // for the one command built to stay up. The cost was invisible and total: every channel\n // conversation started blank after a restart, `sessions` could not see a single turn that\n // arrived over a channel, and Phase 4's exactly-once outbox was unreachable through the\n // only command that has channels — the queue was created and destroyed per process, so a\n // crash mid-delivery lost the queue rather than recovering it.\n store: storeFile,\n // Recorded on the runtime lease and read back only to phrase a refusal. `<PREFIX>SERVICE`\n // is set by the generated service definition and by nothing else, so this is a fact rather\n // than a guess — `ppid === 1` would also be true of any orphaned process.\n mode: asDaemon ? \"daemon\" : \"terminal\",\n })\n\n // Claimed and *registered* before the socket binds, and that ordering is the bug this fixes.\n //\n // Both used to sit after the banner. So between \"serving on …\" reaching stdout and\n // `waitForSignal()` registering its handlers there was a window with **no handler at all** — and\n // in it, SIGINT takes its default action and kills the process outright: exit code `null`, no\n // outbox flush, no lease release, and none of the backgrounded `exec` children reaped.\n //\n // Not a theoretical window. CI caught it as `Expected: 0, Received: null` on a loaded two-core\n // runner, where the work between the two points takes long enough to lose the race — and the\n // real-world shape is worse than a red test: an orchestrator that restarts a container promptly\n // sends its signal into exactly that gap, which is the failure `claimSignals` was introduced to\n // prevent in the first place.\n //\n // The promise is created here and awaited far below. A signal arriving in between resolves it\n // immediately, so an early stop is honoured rather than missed.\n claimSignals()\n const stopRequested = waitForSignal()\n\n /**\n * The one-time bootstrap credential, minted only when there is nothing to bootstrap *from*.\n *\n * Printed while no operator key is live, and otherwise not — a fresh claim at every boot would\n * leave a standing credential in the log, which is the opposite of a one-time ticket. `--claim`\n * overrides that, because a claim printed only while no key exists is a claim unavailable to\n * exactly the person who has lost theirs.\n *\n * Minted after `Runtime.create` because the store has to be open to ask, and before the bind\n * because the handler needs it — the same ordering `approvals` has one layer up.\n */\n const liveKeys = await runtime.store.operatorKeys.liveCount()\n const claim = liveKeys === 0 || options.claim === true ? createClaimTicket() : undefined\n\n let running: Awaited<ReturnType<typeof serve>>\n try {\n running = await serve({\n runtime,\n host,\n port,\n approvals,\n // The origin allowlists, from the manifest. Passed rather than defaulted, because the\n // guard's *default* behaviour is what protects a server whose operator configured\n // nothing — these two only widen it.\n allowedOrigins: config.allowedOrigins,\n allowedHosts: config.allowedHosts,\n /**\n * How `POST /v1/agents/:id/start` finds a manifest for an agent this host is not\n * holding. Injected because `packages/server` may not import the CLI, and the sandbox\n * layout is the CLI's — the same seam 16.5's provisioning route needs.\n *\n * Matched on the manifest's **id**, not on the directory name, because `:id` in the\n * route is an agent id and the two are allowed to differ for a hand-copied directory.\n */\n resolveAgent: (agentId) => manifestForId(agentId, env),\n /**\n * How `POST /v1/agents` creates one. The server owns the route and the gate; this is\n * the implementation, injected because `packages/server` may not import the CLI.\n *\n * Both halves come from `lib/provision.ts`, which is also what `init` writes through —\n * so an agent provisioned over HTTP is byte-identical to one created at a terminal, and\n * the step list a browser renders is the walk the wizard performs.\n *\n * Injected **unconditionally**, including in the container. What keeps provisioning out\n * of there is the loopback gate rather than this absence — the image's `CMD` binds\n * `0.0.0.0`, so the route answers `403`. A container that deliberately binds loopback\n * and wants to provision into itself is then a thing that works, which is the right\n * answer for `docker run -it … init`'s neighbour.\n */\n provision: {\n steps: () => provisionSteps({ agentDirBase: agentsDir(env) }),\n create: (answers) =>\n provisionAgent({ answers, defaults: { agentDirBase: agentsDir(env) } }),\n },\n ...(claim === undefined ? {} : { claim }),\n ...(token === undefined || token === \"\" ? {} : { token }),\n })\n } catch (error) {\n // The runtime is already up; leaving it running after a failed bind would hold the store\n // open and keep channels polling with nothing serving.\n await runtime.stop(\"server failed to bind\")\n if (error instanceof HarnessError) throw error\n throw new HarnessError({\n code: \"server_bind_failed\",\n message: `Could not bind ${host}:${port}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n hint: \"Another process is probably on that port. Pass --port, or set server.port in the manifest.\",\n cause: error,\n })\n }\n\n /**\n * Tell the lease rows where this host answers, now that the socket exists.\n *\n * After the bind and not before, because `--port 0` means the port is not known until then —\n * and this is the whole mechanism behind `stop <agent>`: one process hosts several agents, so\n * stopping one has to be a request naming it rather than a signal to the process.\n */\n await runtime.publishAddress(running.url)\n\n const agents = runtime.list()\n\n // Name the process after what it is serving.\n //\n // Without this a long-running service is a bare interpreter in Activity Monitor and in `ps`,\n // indistinguishable from every other one on the machine — and the one place a person looks when\n // something is eating CPU is exactly the place it was anonymous.\n //\n // **One agent gets its name; several get a count.** Listing them would blow the 16-character\n // `comm` truncation on the second id and leave a fragment, which is worse than a number.\n //\n // Two stated costs. Assigning `process.title` overwrites the argv region, so `ps` shows this\n // instead of the full command line — the arguments stay visible in `launchctl print` and in\n // `daemon status`. And **Bun ignores the assignment entirely**: measured against the same\n // manifest, Node shows the title while `bun` and the compiled binary both show raw argv.\n // So this works on the soft-compat runtime and nowhere else, which is worth knowing before\n // relying on it — the line stays because it costs nothing where it does not work.\n const firstAgent = agents[0]\n if (firstAgent !== undefined) {\n process.title =\n agents.length === 1\n ? `${BRAND.slug} ${firstAgent.id}`\n : `${BRAND.slug} ${agents.length} agents`\n }\n // The port is bound now, which `Runtime.create` could not know — it returns before `serve` runs.\n // Told before the first turn, so slot 2 says \"on\" rather than \"enabled but not listening\".\n for (const agent of agents) agent.reportRuntimeState({ serverListening: true })\n\n if (options.json === true) {\n process.stdout.write(\n `${JSON.stringify({\n url: running.url,\n websocket: running.websocket,\n authenticated: token !== undefined && token !== \"\",\n keys: liveKeys,\n ...(claim === undefined ? {} : { claim: claim.token }),\n agents: agents.map((agent) => ({\n id: agent.id,\n channels: runtime.channels.statusOf(agent.id),\n })),\n // Named even when empty, so a scripted caller can tell \"nothing was declined\" from\n // \"this build does not report it\".\n declined: runtime.declined.map((held) => ({\n agentId: held.agentId,\n pid: held.pid,\n mode: held.mode,\n since: held.startedAt,\n })),\n // Same reasoning, and the more important of the two: an agent absent from this\n // report with no line explaining it is the \"I set this up and it is not running\"\n // failure the durable switch exists to make explicable.\n disabled: switchedOff.map((entry) => ({\n agentId: entry.agentId,\n ...(entry.reason === undefined ? {} : { reason: entry.reason }),\n })),\n })}\\n`,\n )\n } else {\n process.stdout.write(`${BRAND.name} serving on ${running.url}\\n`)\n for (const agent of agents) {\n const channels = runtime.channels.statusOf(agent.id)\n const suffix =\n channels.length === 0\n ? \"no channels\"\n : channels.map((c) => `${c.id} (${c.type})`).join(\", \")\n // Schedules named on the banner for the reason the 57 MB log taught: this is the last\n // place a person looks before walking away, and \"it is set up\" is exactly the belief a\n // schedule that never fires depends on going unchecked.\n const enabled = agent.manifest.schedules.filter((schedule) => schedule.enabled)\n const scheduled =\n agent.manifest.schedules.length === 0\n ? \"\"\n : `, ${enabled.length} schedule${enabled.length === 1 ? \"\" : \"s\"}${\n agent.manifest.schedules.length > enabled.length\n ? ` (+${agent.manifest.schedules.length - enabled.length} disabled)`\n : \"\"\n }`\n process.stdout.write(` ${agent.id} — ${suffix}${scheduled}\\n`)\n }\n\n /**\n * What this process is **not** serving, and why that has to be said.\n *\n * A lease refused means another live process is already serving that agent, and the claim\n * now declines it rather than refusing the whole boot — so without this line a host asked\n * for five agents comes up reporting four and looks entirely healthy. That is the\n * looks-fine-and-is-not shape, one process boundary out, and the same one slot 2's\n * `servedElsewhere` exists for.\n *\n * The pid is printed because it is the only actionable thing here — the `stop` command\n * is the next command, and knowing which process to expect it to reach is the difference\n * between running it and wondering.\n */\n /**\n * What is switched off, and how to switch it back on.\n *\n * The line is the whole reason a durable stop is safe to have. launchd's `disable` persists\n * across boots and no verb deletes the row, so a job with that label installs cleanly,\n * reports success and never starts — 2,463 restarts into a 57 MB log, with message quality\n * never the problem. A persistent switch is only defensible when the thing it switches off\n * says so at the moment somebody is looking.\n */\n for (const entry of switchedOff) {\n process.stdout.write(\n ` ${entry.agentId} — stopped${\n entry.reason === undefined ? \"\" : ` (${entry.reason})`\n }, \\`${BRAND.slug} start ${entry.agentId}\\`\\n`,\n )\n }\n\n for (const held of runtime.declined) {\n process.stdout.write(\n ` ${held.agentId} — NOT served here: pid ${held.pid} (${held.mode}) already has it\\n`,\n )\n }\n if (runtime.declined.length > 0) {\n process.stdout.write(\n ` \\`${BRAND.slug} stop <agent>\\` ends the other one, or leave it — nothing here is broken.\\n`,\n )\n }\n if (claim !== undefined) {\n // Printed here rather than logged at debug level for the reason the 57 MB log taught:\n // this is the line somebody is looking at, and a bootstrap credential in a file nobody\n // opens is a bootstrap nobody performs. Reading it is what confers first ownership, and\n // that is a real boundary — `docker logs` already reveals the agent's conversations, so\n // this grants nothing new to anyone who can see it.\n // The URL first, because opening it is what most people will do and the page does the\n // exchange properly — it POSTs the token rather than spending it on a GET. The `curl`\n // line stays for the case a browser cannot reach: a headless box, a CI step, a platform\n // minting its first key.\n process.stdout.write(\n ` open once to claim this server:\\n ${claimUrl(host, running.port, claim.token)}\\n` +\n ` without a browser: ${claimCommand(host, running.port, claim.token)}\\n`,\n )\n if (token === undefined || token === \"\") {\n // The latch in `createHandler`: a live key makes this server demand a credential.\n // Said out loud, because minting one on an open server *changes* what the server\n // is, and discovering that by being locked out of your own loopback port is the\n // worst way to learn it.\n process.stdout.write(\n \" the first key closes this server — every route then needs a credential.\\n\",\n )\n }\n }\n if (token === undefined || token === \"\") {\n // Loopback-only, or `serve` would have refused to bind. Said out loud anyway: someone\n // who later changes the host needs to know the token was never set.\n process.stdout.write(\n ` unauthenticated — loopback only. Set ${config.tokenEnv} to bind a public host.\\n`,\n )\n }\n if (!running.websocket) {\n process.stdout.write(\" /v1/ws unavailable under Node — SSE and HTTP are unaffected.\\n\")\n }\n // The single highest-value place to mention the daemon: this is the exact moment a person\n // learns that `serve` lives and dies with the terminal it was typed into. Left unsaid, the\n // discovery happens later, by the agent going quiet with nothing to explain it.\n if (asDaemon) {\n process.stdout.write(\n ` running as a background service · ${BRAND.slug} daemon status ${agents[0]?.id ?? \"\"}\\n`,\n )\n } else {\n process.stdout.write(\n ` ctrl-c to stop — this ends when the terminal does. \\`${BRAND.slug} daemon install ${\n agents[0]?.id ?? \"<agent>\"\n }\\` keeps it running.\\n`,\n )\n }\n }\n\n // Registered as a *teardown*, not as a second signal handler, and that distinction was a live\n // bug. `installGuards` already owns SIGTERM and answers it with `finishNow(EXIT_SIGTERM)`,\n // which hard-exits; this module used to register its own `process.once(\"SIGTERM\")` alongside\n // it. Both fired, and the hard exit won — so `runtime.stop()` never completed. No outbox\n // flush, no clean database close, and no `provider.stop()`, which is the only thing that reaps\n // the child processes `exec` backgrounds. Invisible at a terminal, because ctrl-C sends SIGINT\n // and the guard deliberately ignores that one; unavoidable under a service manager, where\n // SIGTERM is how every stop and every restart happens.\n //\n // `finish()` awaits `runTeardowns()`, so putting the shutdown here means the signal path waits\n // for it instead of racing it.\n let stopped = false\n const shutdown = async () => {\n if (stopped) return\n stopped = true\n await running.stop()\n await runtime.stop(\"interrupted\")\n }\n onExit(shutdown)\n\n await stopRequested\n\n process.stdout.write(\"stopping\\n\")\n await shutdown()\n // Zero, deliberately, and it is load-bearing rather than cosmetic. A requested stop is not a\n // fault, and the generated service definition restarts only on a crash signal — so a non-zero\n // exit here would be read by the supervisor as \"this configuration is broken, stay down\".\n return EXIT_OK\n}\n\n/**\n * Resolve on SIGINT or SIGTERM.\n *\n * Both, because SIGINT is a person at a terminal and SIGTERM is an orchestrator, and a container\n * that ignored SIGTERM would be killed after its grace period — mid-delivery, which is the one\n * moment the outbox's recovery path exists to survive and would rather not exercise.\n */\nfunction waitForSignal(): Promise<void> {\n return new Promise((resolve) => {\n const finish = () => {\n process.off(\"SIGINT\", finish)\n process.off(\"SIGTERM\", finish)\n resolve()\n }\n process.once(\"SIGINT\", finish)\n process.once(\"SIGTERM\", finish)\n })\n}\n\n/** Re-exported for the boundaries test, which asserts this module imports no renderer. */\nexport const SERVE_EXIT_FAILURE = EXIT_FAILURE\n",
|
|
34
|
+
"/**\n * The `serve` command: `<binary> serve <manifest> [--port N] [--host H]`.\n *\n * Boots a runtime with channels started, binds the HTTP surface, and stays up until interrupted.\n * The only long-running command in the binary, and the only one that opens a listening socket.\n *\n * **Channels start here and nowhere else.** `run` constructs the same runtime with\n * `startChannels: false`, because a REPL that silently began answering Telegram messages while you\n * typed at it would be a surprise, and a one-shot `run --input` that opened a long-poll would hang\n * on exit. The flag decides *whether*, never *when* — either way nothing connects before\n * `runtime.ready`.\n *\n * No Ink. A server writes lines to stdout and is very often not attached to a terminal at all; a\n * rendering framework on this path would cost more than the whole command and produce escape codes\n * in a log file.\n */\n\nimport { dirname, resolve } from \"node:path\"\nimport {\n AgentManifestSchema,\n agentPluginSupply,\n BRAND,\n EventBus,\n HarnessError,\n isHarnessError,\n loadManifest,\n Runtime,\n readManifestHeader,\n} from \"@dispach/core\"\nimport {\n browsableHost,\n claimCommand,\n claimUrl,\n createApprovalRegistry,\n createClaimTicket,\n serve,\n} from \"@dispach/server\"\nimport { ambientEnv } from \"#lib/ambient\"\nimport { inContainer } from \"#lib/bootstrap\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { claimSignals, onExit } from \"#lib/exit\"\nimport { hostableAgents, manifestForId } from \"#lib/lifecycle\"\nimport { BUILT_IN_PLUGINS, CHANNELS, scriptRunner, TOOL_PROVIDERS } from \"#lib/providers\"\nimport { provisionAgent, provisionSteps } from \"#lib/provision\"\nimport { agentsDir, storePath } from \"#lib/sandbox\"\n\nexport interface ServeOptions {\n /**\n * Zero or more manifests. The process hosts every agent they produce.\n *\n * Plural since 16.2a: decision 8.5 has said \"one process hosts N agents\" since the beginning\n * and core was built that way — `RuntimeOptions.agents` is already an array — so a single path\n * here was the only thing pinning the product to one agent.\n *\n * **Empty means the sandbox's agents**, which is what the service unit runs and what makes the\n * product always-on: a host that has to be told which agents to serve cannot serve one that was\n * provisioned after it started. Naming manifests is the container's shape, where the agent\n * arrives on a mount and the sandbox is not the inventory.\n */\n readonly manifestPaths: readonly string[]\n readonly port?: number\n readonly host?: string\n readonly store?: string\n /** Print a one-time claim even when a key already exists. The lockout escape. */\n readonly claim?: boolean\n readonly json?: boolean\n}\n\n/**\n * The `server:` block a manifest that declares none resolves to.\n *\n * Asked of the **schema** rather than written out here, so a bare `serve` and a manifest with no\n * `server:` block cannot come to disagree about the port — which they would the first time somebody\n * changed the default in one place. Parsing an empty object is the cheapest way to ask a Zod schema\n * what its defaults are.\n */\nfunction defaultServerConfig(): ReturnType<typeof AgentManifestSchema.parse>[\"server\"] {\n return AgentManifestSchema.shape.server.parse({})\n}\n\nexport async function serveCommand(options: ServeOptions): Promise<number> {\n const env = ambientEnv(options.manifestPaths)\n\n /**\n * What to host, and what is switched off.\n *\n * Read before the runtime exists, because it decides which agents the runtime is *asked* for —\n * a disabled agent is not loaded at all, so there is nothing to filter afterwards. The switch is\n * honoured for an explicitly named manifest too, and that is deliberate: the launchd trap this\n * table is modelled on is precisely a job that installs cleanly, reports success and silently\n * never starts, and the cure is not to make the durable state easy to bypass — it is to say so.\n */\n // The same path the runtime will open, not the sandbox default: `serve --store` exists, and\n // a host reading its on/off switch from a different database than the one it serves out of\n // is wrong in exactly the configuration that is easiest to miss.\n const storeFile = options.store ?? storePath()\n const hostable = await hostableAgents(options.manifestPaths, env, storeFile)\n const switchedOff = hostable.filter((entry) => !entry.enabled)\n const wanted = hostable.filter((entry) => entry.enabled)\n\n /**\n * **A discovered agent that will not load is skipped; a named one still refuses.**\n *\n * The asymmetry is the whole point, and it was found by running the container rather than by\n * reading this. `init` writes a manifest whose `.env` holds `MODEL_API_KEY=` — empty, by its\n * own design, since step 1 of what it prints is \"add your key\". A bare `serve` hosts every\n * enabled agent in the sandbox, so one freshly created agent made `loadManifest` throw, the\n * host exited 1, and `restart: unless-stopped` restarted it into the same failure: **9\n * restarts, the API gone, the web UI gone** — the always-on server that exists to provision\n * agents taken down by an agent halfway through being provisioned. The message was perfect and\n * went to `docker logs`, which is the 57 MB lesson with the polarity reversed: not a bad\n * message in a file nobody opens, a correct one nobody can act on because the thing that would\n * let them act is what died.\n *\n * So a host does not get to fail because one of N agents is misconfigured. That is the same\n * reasoning `listAgents` uses to show a broken directory rather than omitting it, and the same\n * reasoning behind `GET /v1/agents` carrying a stopped row: the listing says what exists, the\n * resource says what is running.\n *\n * A **named** manifest is the other case and keeps throwing. The caller asked for that agent by\n * path, so quietly serving something else is the worse error — exactly the direction\n * `hostableAgents` already distinguishes, which is why the condition here is the same one.\n */\n const discovered = options.manifestPaths.length === 0\n const manifests: { path: string; loaded: ReturnType<typeof loadManifest> }[] = []\n const broken: { path: string; detail: string; hint?: string }[] = []\n for (const entry of wanted) {\n try {\n /**\n * **Two passes, because `serve` is what hosts channels and a plugin may supply one.**\n *\n * This used to be one `loadManifest` against the static `CHANNEL_IDS` and\n * `PROVIDER_IDS` tables, and that made `PluginContext.defineChannel` — documented\n * public API — **not work through this binary at all**: a manifest naming a\n * plugin-supplied channel was refused with `channel_type_unknown` here, before the\n * plugin that would have satisfied it was ever imported. `Runtime.create` had always\n * been right, passing `Object.keys(supply.channels)`; it simply never got the chance.\n *\n * The recorded hazard with its polarity reversed — *a check only one surface performs\n * is a check the two disagree about*, refusing a correct manifest rather than admitting\n * a broken one — and invisible because `telegram` arrives from the CLI's own table and\n * never through the plugin path, so the public API had no in-tree consumer.\n *\n * `validate.ts` is the surface that already does this and the two now agree, which is\n * the argument for this shape over moving the check into `Runtime.create`: that would\n * need core to know whether the caller *named* these manifests or discovered them —\n * the asymmetry below, which belongs to the caller — and a manifest naming a genuinely\n * unknown channel would then throw from an unguarded `sources.map` and take the whole\n * host down, which is the crash loop this loop exists to prevent, arriving by another\n * route.\n *\n * The cost is one extra `setup()` for an agent that declares plugins.\n * `agentPluginSupply` returns immediately when `refs` is empty, so an agent with no\n * `plugins:` block — which is nearly all of them — pays nothing at all. And the load\n * happening **here** is a strengthening rather than a cost: a plugin that throws on\n * import used to do it inside `Runtime.create`, where it killed the host, and now makes\n * one discovered agent broken-and-skipped like any other bad manifest.\n */\n const header = readManifestHeader(entry.manifestPath)\n const supply = await agentPluginSupply({\n refs: header.plugins ?? [],\n agentId: header.id ?? entry.manifestPath,\n paths: {\n workspace: dirname(resolve(entry.manifestPath)),\n state: dirname(resolve(entry.manifestPath)),\n manifest: resolve(entry.manifestPath),\n },\n env,\n // A throwaway bus, like `validate`'s: `Runtime.create` loads these again and emits\n // the real `plugin.loaded` on the real bus, and a pre-load emitting onto it would\n // report every plugin twice to anything watching.\n bus: new EventBus({ runtimeId: \"serve-preload\" }),\n builtIn: BUILT_IN_PLUGINS,\n base: { toolProviders: TOOL_PROVIDERS, channels: CHANNELS },\n })\n manifests.push({\n path: entry.manifestPath,\n loaded: loadManifest(entry.manifestPath, {\n knownProviders: Object.keys(supply.toolProviders),\n knownChannels: Object.keys(supply.channels),\n env,\n }),\n })\n } catch (error) {\n if (!discovered) throw error\n broken.push({\n path: entry.manifestPath,\n detail: isHarnessError(error) ? error.message : String(error),\n ...(isHarnessError(error) && error.hint !== undefined ? { hint: error.hint } : {}),\n })\n }\n }\n /**\n * **Zero agents is a running server, not a failure.**\n *\n * The whole point of an always-on host is that the API exists before there is anything to talk\n * to: the binary is installed, the server is up, and provisioning reaches it. A refusal here\n * would make the first-run experience \"install, then find something to serve, then start\", and\n * would turn a container whose only agent somebody stopped into a crash loop.\n *\n * So the server config comes from the first manifest when there is one, and from the schema's\n * defaults when there is not — which is the same thing a manifest that declares no `server:`\n * block resolves to.\n */\n const first = manifests[0]\n const loaded = first?.loaded\n const config = loaded?.manifest.server ?? defaultServerConfig()\n\n /**\n * **The bind is process-level, so a disagreement about it is refused rather than ignored.**\n *\n * One process, one socket, one token — so with several manifests the server config can only\n * come from one of them, and silently taking the first would make a manifest that carefully\n * declares `port: 7500` a file whose setting does nothing. That is the \"looks configured and is\n * not\" shape, and it is worse here than elsewhere because the symptom is a port somebody else\n * is already using.\n *\n * Compared after defaults are applied, which is what makes this correct rather than pedantic:\n * an unset `port` *is* 7420, so a manifest that says 7420 and one that says nothing agree, and\n * one that says 7500 disagrees with both.\n */\n for (const entry of manifests.slice(1)) {\n const other = entry.loaded.manifest.server\n for (const [field, mine, theirs, settled] of [\n // **A flag settles the question, so it also settles the disagreement.** `--port` and\n // `--host` override every manifest, so refusing because two of them disagree about a\n // value nothing is going to read would be a refusal the operator has already answered.\n // `tokenEnv` has no flag, so a disagreement there is always live.\n [\"server.port\", config.port, other.port, options.port !== undefined],\n [\"server.host\", config.host, other.host, options.host !== undefined],\n [\"server.tokenEnv\", config.tokenEnv, other.tokenEnv, false],\n ] as const) {\n if (settled || mine === theirs) continue\n throw new HarnessError({\n code: \"serve_bind_conflict\",\n message: `${first?.path ?? \"the first manifest\"} sets ${field} to ${String(mine)} and ${entry.path} sets it to ${String(theirs)}.`,\n hint: \"One process binds one socket with one token, so these have to agree. Make them match, or run the disagreeing agent in its own process — a second `serve` on its own port.\",\n field,\n })\n }\n }\n // Flags win over the manifest: the manifest is the deployment's intent and a flag is this\n // invocation's. `--port 0` is honoured — it means \"any free port\", which a test wants.\n const port = options.port ?? config.port\n const host = options.host ?? config.host\n // `loaded.env`, never `env`. `ambientEnv` returns the *process* environment — the agent's own\n // `.env` beside the manifest is layered in by `loadManifest`, which is why every other\n // credential in this runtime is read from the manifest's live env. Reading the ambient one\n // here meant a token sitting in the agent's `.env` was invisible, and the banner said\n // \"unauthenticated\" while the file plainly had it. Same mistake `Agent.create` documents:\n // the manifest's live env, not the ambient one.\n // `loaded.env`, never `env`. `ambientEnv` returns the *process* environment; the agent's own\n // `.env` beside the manifest is layered in by `loadManifest`. With no manifest at all there is\n // no agent env to layer, so the process environment is the only source there is — which is the\n // service unit's shape, where the variable comes from the unit definition.\n const token = loaded === undefined ? env[config.tokenEnv] : loaded.env[config.tokenEnv]\n\n // Set by the generated service definition and by nothing else, so this is a fact rather than a\n // guess. `ppid === 1` would also be true of any orphaned process, and getting it wrong means\n // telling someone to press ctrl-c at a log file.\n const asDaemon = env[`${BRAND.envPrefix}SERVICE`] !== undefined\n\n // Subscribed BEFORE the runtime exists, which is what the `bus` option is for. Channels start\n // inside `Runtime.create` — after `runtime.ready`, but still inside the call — so a listener\n // attached afterwards misses every status and error they emitted on the way up. Same trap as\n // the boot warnings that landed in an empty room for weeks: anything true during boot has to be\n // subscribed to before boot.\n const bus = new EventBus({ runtimeId: `rt_${Date.now().toString(36)}` })\n if (options.json !== true) {\n bus.on(\"agent.channel.status\", (event) => {\n const data = event.data as {\n channelId: string\n status: string\n detail?: string\n input?: { kind: string; expiresAt?: string }\n }\n /**\n * A `needs_input` names where the payload is, and never prints it.\n *\n * The payload is a QR's bytes — unreadable in a log, and hundreds of characters of it\n * would bury the sentence that matters. But a line saying only \"needs_input\" is the\n * 57 MB-log failure in one line: true, and no route to acting on it. The agent\n * resource carries the payload because `statusOf` returns it, so that is what this\n * points at.\n */\n const waiting =\n data.input === undefined\n ? \"\"\n : ` (${data.input.kind}${\n data.input.expiresAt === undefined\n ? \"\"\n : `, expires ${data.input.expiresAt}`\n } — GET /v1/agents/${event.agentId ?? \"\"} carries it)`\n process.stdout.write(\n ` ${data.channelId}: ${data.status}${data.detail === undefined ? \"\" : ` — ${data.detail}`}${waiting}\\n`,\n )\n })\n bus.on(\"agent.channel.error\", (event) => {\n const data = event.data as { channelId: string; message: string; hint: string }\n process.stderr.write(` ${data.channelId}: ${data.message}\\n hint: ${data.hint}\\n`)\n })\n // The one thing a person watching a bot most wants to see, and it is otherwise only in the\n // event stream: who was refused, and the line that would let them in.\n bus.on(\"agent.channel.rejected\", (event) => {\n const data = event.data as { channelId: string; reason: string; detail: string }\n process.stdout.write(` ${data.channelId}: ${data.reason} — ${data.detail}\\n`)\n })\n }\n\n /**\n * Created before the runtime, because the runtime is constructed *with* the approver.\n *\n * That ordering is the whole reason this lives here and not inside `serve()`: `Runtime.create`\n * takes `approve` and cannot hand back the function it was built with, so the registry has to\n * exist first and then be given to both. Same shape as the shared `running` map, one layer\n * further out.\n *\n * Supplying it is also what silences `confirm_without_approver` — `Agent.create` keys that\n * warning on `approve` being absent, so an agent with `onMutate: \"confirm\"` stops warning under\n * `serve` and keeps warning under `run`, which is exactly true of the two surfaces today.\n */\n const approvals = createApprovalRegistry()\n\n const runtime = await Runtime.create({\n agents: manifests.map((entry) => entry.path),\n // The seam `ToolContext.approve` declared in Phase 3 and nothing ever filled. A blocked\n // call now emits `approval.requested` and waits for a POST; an unanswered one ends with the\n // turn, because core races the approver against the turn's own signal rather than starting\n // a second clock.\n approve: approvals.approver,\n env,\n bus,\n toolProviders: TOOL_PROVIDERS,\n builtInPlugins: BUILT_IN_PLUGINS,\n scriptRunner: scriptRunner(),\n channels: CHANNELS,\n // The one call site that passes this. See the file comment.\n startChannels: true,\n // Same rule and the same reason: `serve` is the only command that fires schedules. A REPL\n // that started firing them while somebody typed at it would be a surprise, and a one-shot\n // `run --input` that armed a timer would not exit.\n startSchedules: true,\n // `run` and `sessions` have resolved this default since the sandbox landed; `serve` never\n // did, so it silently took core's `\":memory:\"` — correct as a *library* default, since\n // constructing a Runtime must not create a directory in someone's working tree, and wrong\n // for the one command built to stay up. The cost was invisible and total: every channel\n // conversation started blank after a restart, `sessions` could not see a single turn that\n // arrived over a channel, and Phase 4's exactly-once outbox was unreachable through the\n // only command that has channels — the queue was created and destroyed per process, so a\n // crash mid-delivery lost the queue rather than recovering it.\n store: storeFile,\n // Recorded on the runtime lease and read back only to phrase a refusal. `<PREFIX>SERVICE`\n // is set by the generated service definition and by nothing else, so this is a fact rather\n // than a guess — `ppid === 1` would also be true of any orphaned process.\n mode: asDaemon ? \"daemon\" : \"terminal\",\n })\n\n // Claimed and *registered* before the socket binds, and that ordering is the bug this fixes.\n //\n // Both used to sit after the banner. So between \"serving on …\" reaching stdout and\n // `waitForSignal()` registering its handlers there was a window with **no handler at all** — and\n // in it, SIGINT takes its default action and kills the process outright: exit code `null`, no\n // outbox flush, no lease release, and none of the backgrounded `exec` children reaped.\n //\n // Not a theoretical window. CI caught it as `Expected: 0, Received: null` on a loaded two-core\n // runner, where the work between the two points takes long enough to lose the race — and the\n // real-world shape is worse than a red test: an orchestrator that restarts a container promptly\n // sends its signal into exactly that gap, which is the failure `claimSignals` was introduced to\n // prevent in the first place.\n //\n // The promise is created here and awaited far below. A signal arriving in between resolves it\n // immediately, so an early stop is honoured rather than missed.\n claimSignals()\n const stopRequested = waitForSignal()\n\n /**\n * The one-time bootstrap credential, minted only when there is nothing to bootstrap *from*.\n *\n * Printed while no operator key is live, and otherwise not — a fresh claim at every boot would\n * leave a standing credential in the log, which is the opposite of a one-time ticket. `--claim`\n * overrides that, because a claim printed only while no key exists is a claim unavailable to\n * exactly the person who has lost theirs.\n *\n * Minted after `Runtime.create` because the store has to be open to ask, and before the bind\n * because the handler needs it — the same ordering `approvals` has one layer up.\n */\n const liveKeys = await runtime.store.operatorKeys.liveCount()\n const claim = liveKeys === 0 || options.claim === true ? createClaimTicket() : undefined\n\n let running: Awaited<ReturnType<typeof serve>>\n try {\n running = await serve({\n runtime,\n host,\n port,\n approvals,\n // The origin allowlists, from the manifest. Passed rather than defaulted, because the\n // guard's *default* behaviour is what protects a server whose operator configured\n // nothing — these two only widen it.\n allowedOrigins: config.allowedOrigins,\n allowedHosts: config.allowedHosts,\n /**\n * How `POST /v1/agents/:id/start` finds a manifest for an agent this host is not\n * holding. Injected because `packages/server` may not import the CLI, and the sandbox\n * layout is the CLI's — the same seam 16.5's provisioning route needs.\n *\n * Matched on the manifest's **id**, not on the directory name, because `:id` in the\n * route is an agent id and the two are allowed to differ for a hand-copied directory.\n */\n resolveAgent: (agentId) => manifestForId(agentId, env),\n /**\n * How `POST /v1/agents` creates one. The server owns the route and the gate; this is\n * the implementation, injected because `packages/server` may not import the CLI.\n *\n * Both halves come from `lib/provision.ts`, which is also what `init` writes through —\n * so an agent provisioned over HTTP is byte-identical to one created at a terminal, and\n * the step list a browser renders is the walk the wizard performs.\n *\n * Injected **unconditionally**, including in the container. What keeps provisioning out\n * of there is the loopback gate rather than this absence — the image's `CMD` binds\n * `0.0.0.0`, so the route answers `403`. A container that deliberately binds loopback\n * and wants to provision into itself is then a thing that works, which is the right\n * answer for `docker run -it … init`'s neighbour.\n */\n provision: {\n steps: () => provisionSteps({ agentDirBase: agentsDir(env) }),\n create: (answers) =>\n provisionAgent({ answers, defaults: { agentDirBase: agentsDir(env) } }),\n },\n ...(claim === undefined ? {} : { claim }),\n ...(token === undefined || token === \"\" ? {} : { token }),\n })\n } catch (error) {\n // The runtime is already up; leaving it running after a failed bind would hold the store\n // open and keep channels polling with nothing serving.\n await runtime.stop(\"server failed to bind\")\n if (error instanceof HarnessError) throw error\n throw new HarnessError({\n code: \"server_bind_failed\",\n message: `Could not bind ${host}:${port}: ${\n error instanceof Error ? error.message : String(error)\n }`,\n hint: \"Another process is probably on that port. Pass --port, or set server.port in the manifest.\",\n cause: error,\n })\n }\n\n /**\n * Tell the lease rows where this host answers, now that the socket exists.\n *\n * After the bind and not before, because `--port 0` means the port is not known until then —\n * and this is the whole mechanism behind `stop <agent>`: one process hosts several agents, so\n * stopping one has to be a request naming it rather than a signal to the process.\n */\n await runtime.publishAddress(running.url)\n\n const agents = runtime.list()\n\n // Name the process after what it is serving.\n //\n // Without this a long-running service is a bare interpreter in Activity Monitor and in `ps`,\n // indistinguishable from every other one on the machine — and the one place a person looks when\n // something is eating CPU is exactly the place it was anonymous.\n //\n // **One agent gets its name; several get a count.** Listing them would blow the 16-character\n // `comm` truncation on the second id and leave a fragment, which is worse than a number.\n //\n // Two stated costs. Assigning `process.title` overwrites the argv region, so `ps` shows this\n // instead of the full command line — the arguments stay visible in `launchctl print` and in\n // `daemon status`. And **Bun ignores the assignment entirely**: measured against the same\n // manifest, Node shows the title while `bun` and the compiled binary both show raw argv.\n // So this works on the soft-compat runtime and nowhere else, which is worth knowing before\n // relying on it — the line stays because it costs nothing where it does not work.\n const firstAgent = agents[0]\n if (firstAgent !== undefined) {\n process.title =\n agents.length === 1\n ? `${BRAND.slug} ${firstAgent.id}`\n : `${BRAND.slug} ${agents.length} agents`\n }\n // The port is bound now, which `Runtime.create` could not know — it returns before `serve` runs.\n // Told before the first turn, so slot 2 says \"on\" rather than \"enabled but not listening\".\n for (const agent of agents) agent.reportRuntimeState({ serverListening: true })\n\n if (options.json === true) {\n process.stdout.write(\n `${JSON.stringify({\n url: running.url,\n websocket: running.websocket,\n authenticated: token !== undefined && token !== \"\",\n keys: liveKeys,\n ...(claim === undefined ? {} : { claim: claim.token }),\n agents: agents.map((agent) => ({\n id: agent.id,\n channels: runtime.channels.statusOf(agent.id),\n })),\n // Named even when empty, so a scripted caller can tell \"nothing was declined\" from\n // \"this build does not report it\".\n declined: runtime.declined.map((held) => ({\n agentId: held.agentId,\n pid: held.pid,\n mode: held.mode,\n since: held.startedAt,\n })),\n // Same reasoning, and the more important of the two: an agent absent from this\n // report with no line explaining it is the \"I set this up and it is not running\"\n // failure the durable switch exists to make explicable.\n disabled: switchedOff.map((entry) => ({\n agentId: entry.agentId,\n ...(entry.reason === undefined ? {} : { reason: entry.reason }),\n })),\n // A third way an agent can be absent, and the one that reads as a bug rather than\n // as a choice: its manifest would not load. Named for the same reason as the two\n // above — a scripted caller has to be able to tell \"no agent is broken\" from \"this\n // build does not say\".\n broken: broken.map((entry) => ({\n path: entry.path,\n detail: entry.detail,\n ...(entry.hint === undefined ? {} : { hint: entry.hint }),\n })),\n })}\\n`,\n )\n } else {\n /**\n * **A bind is not an address.** `running.url` carries whatever was bound, so the container\n * printed `http://0.0.0.0:7420` — a URL a browser does nothing with, as the first and most\n * prominent line of the banner. `browsableHost` has existed since Phase 13 for exactly\n * this and its own docstring notes it had two copies before a third caller arrived; this is\n * the fourth, and it never got it. A laptop cannot show the defect: `serve` there binds\n * `127.0.0.1` and the substitution never fires.\n *\n * The bind is still named when it differs, because \"listening on every interface\" is a\n * security-relevant fact and quietly showing loopback instead would hide it.\n */\n const browsable = `http://${browsableHost(host)}:${running.port}`\n const boundNote = browsable === running.url ? \"\" : ` (bound ${host} — every interface)`\n process.stdout.write(`${BRAND.name} serving on ${browsable}${boundNote}\\n`)\n\n /**\n * The web UI and the reference, named because nothing named them.\n *\n * Both have been served unauthenticated since they shipped and neither appeared anywhere a\n * person looks — the API reference in particular, which is the single thing most worth\n * knowing about a server you have just started and cannot yet call. A surface nobody is\n * told about is a surface nobody has, which is the `includeHistory` shape applied to a page\n * rather than to a field.\n */\n process.stdout.write(` web UI ${browsable}/ · API reference ${browsable}/docs\\n`)\n for (const agent of agents) {\n const channels = runtime.channels.statusOf(agent.id)\n const suffix =\n channels.length === 0\n ? \"no channels\"\n : channels.map((c) => `${c.id} (${c.type})`).join(\", \")\n // Schedules named on the banner for the reason the 57 MB log taught: this is the last\n // place a person looks before walking away, and \"it is set up\" is exactly the belief a\n // schedule that never fires depends on going unchecked.\n const enabled = agent.manifest.schedules.filter((schedule) => schedule.enabled)\n const scheduled =\n agent.manifest.schedules.length === 0\n ? \"\"\n : `, ${enabled.length} schedule${enabled.length === 1 ? \"\" : \"s\"}${\n agent.manifest.schedules.length > enabled.length\n ? ` (+${agent.manifest.schedules.length - enabled.length} disabled)`\n : \"\"\n }`\n process.stdout.write(` ${agent.id} — ${suffix}${scheduled}\\n`)\n }\n\n /**\n * What this process is **not** serving, and why that has to be said.\n *\n * A lease refused means another live process is already serving that agent, and the claim\n * now declines it rather than refusing the whole boot — so without this line a host asked\n * for five agents comes up reporting four and looks entirely healthy. That is the\n * looks-fine-and-is-not shape, one process boundary out, and the same one slot 2's\n * `servedElsewhere` exists for.\n *\n * The pid is printed because it is the only actionable thing here — the `stop` command\n * is the next command, and knowing which process to expect it to reach is the difference\n * between running it and wondering.\n */\n /**\n * What is switched off, and how to switch it back on.\n *\n * The line is the whole reason a durable stop is safe to have. launchd's `disable` persists\n * across boots and no verb deletes the row, so a job with that label installs cleanly,\n * reports success and never starts — 2,463 restarts into a 57 MB log, with message quality\n * never the problem. A persistent switch is only defensible when the thing it switches off\n * says so at the moment somebody is looking.\n */\n for (const entry of switchedOff) {\n process.stdout.write(\n ` ${entry.agentId} — stopped${\n entry.reason === undefined ? \"\" : ` (${entry.reason})`\n }, \\`${BRAND.slug} start ${entry.agentId}\\`\\n`,\n )\n }\n\n /**\n * What would not load, with the reason and the file.\n *\n * Printed rather than thrown, because throwing is what took the host down — and printed\n * *loudly*, because \"skipped\" is the one state a person reads as working. The path is the\n * actionable half: the fix is almost always a key missing from the `.env` beside it, which\n * is precisely the state `init` leaves an agent in on purpose.\n */\n for (const entry of broken) {\n process.stdout.write(` ${entry.path} — NOT served: ${entry.detail}\\n`)\n if (entry.hint !== undefined) process.stdout.write(` hint: ${entry.hint}\\n`)\n }\n\n for (const held of runtime.declined) {\n process.stdout.write(\n ` ${held.agentId} — NOT served here: pid ${held.pid} (${held.mode}) already has it\\n`,\n )\n }\n if (runtime.declined.length > 0) {\n process.stdout.write(\n ` \\`${BRAND.slug} stop <agent>\\` ends the other one, or leave it — nothing here is broken.\\n`,\n )\n }\n if (claim !== undefined) {\n // Printed here rather than logged at debug level for the reason the 57 MB log taught:\n // this is the line somebody is looking at, and a bootstrap credential in a file nobody\n // opens is a bootstrap nobody performs. Reading it is what confers first ownership, and\n // that is a real boundary — `docker logs` already reveals the agent's conversations, so\n // this grants nothing new to anyone who can see it.\n // The URL first, because opening it is what most people will do and the page does the\n // exchange properly — it POSTs the token rather than spending it on a GET. The `curl`\n // line stays for the case a browser cannot reach: a headless box, a CI step, a platform\n // minting its first key.\n process.stdout.write(\n ` open once to claim this server:\\n ${claimUrl(host, running.port, claim.token)}\\n` +\n ` without a browser: ${claimCommand(host, running.port, claim.token)}\\n`,\n )\n if (token === undefined || token === \"\") {\n // The latch in `createHandler`: a live key makes this server demand a credential.\n // Said out loud, because minting one on an open server *changes* what the server\n // is, and discovering that by being locked out of your own loopback port is the\n // worst way to learn it.\n process.stdout.write(\n \" the first key closes this server — every route then needs a credential.\\n\",\n )\n }\n }\n if (token === undefined || token === \"\") {\n // Loopback-only, or `serve` would have refused to bind. Said out loud anyway: someone\n // who later changes the host needs to know the token was never set.\n process.stdout.write(\n ` unauthenticated — loopback only. Set ${config.tokenEnv} to bind a public host.\\n`,\n )\n }\n if (!running.websocket) {\n process.stdout.write(\" /v1/ws unavailable under Node — SSE and HTTP are unaffected.\\n\")\n }\n // The single highest-value place to mention the daemon: this is the exact moment a person\n // learns that `serve` lives and dies with the terminal it was typed into. Left unsaid, the\n // discovery happens later, by the agent going quiet with nothing to explain it.\n if (asDaemon) {\n process.stdout.write(\n ` running as a background service · ${BRAND.slug} daemon status ${agents[0]?.id ?? \"\"}\\n`,\n )\n } else if (inContainer()) {\n /**\n * A container has no terminal to lose and is already supervised.\n *\n * The generic line told an operator reading `docker logs` to press ctrl-c — in a\n * terminal that does not exist — and to run `daemon install <agent>`, which is both the\n * per-agent form 16.4 retires *and* a second supervisor underneath the one that started\n * this process. Two pieces of advice, neither actionable, on the last line of the only\n * output a container deployment has.\n */\n process.stdout.write(\n \" supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.\\n\",\n )\n } else {\n process.stdout.write(\n ` ctrl-c to stop — this ends when the terminal does. \\`${BRAND.slug} daemon install${\n agents[0]?.id === undefined ? \"\" : ` ${agents[0].id}`\n }\\` keeps it running.\\n`,\n )\n }\n }\n\n // Registered as a *teardown*, not as a second signal handler, and that distinction was a live\n // bug. `installGuards` already owns SIGTERM and answers it with `finishNow(EXIT_SIGTERM)`,\n // which hard-exits; this module used to register its own `process.once(\"SIGTERM\")` alongside\n // it. Both fired, and the hard exit won — so `runtime.stop()` never completed. No outbox\n // flush, no clean database close, and no `provider.stop()`, which is the only thing that reaps\n // the child processes `exec` backgrounds. Invisible at a terminal, because ctrl-C sends SIGINT\n // and the guard deliberately ignores that one; unavoidable under a service manager, where\n // SIGTERM is how every stop and every restart happens.\n //\n // `finish()` awaits `runTeardowns()`, so putting the shutdown here means the signal path waits\n // for it instead of racing it.\n let stopped = false\n const shutdown = async () => {\n if (stopped) return\n stopped = true\n await running.stop()\n await runtime.stop(\"interrupted\")\n }\n onExit(shutdown)\n\n await stopRequested\n\n process.stdout.write(\"stopping\\n\")\n await shutdown()\n // Zero, deliberately, and it is load-bearing rather than cosmetic. A requested stop is not a\n // fault, and the generated service definition restarts only on a crash signal — so a non-zero\n // exit here would be read by the supervisor as \"this configuration is broken, stay down\".\n return EXIT_OK\n}\n\n/**\n * Resolve on SIGINT or SIGTERM.\n *\n * Both, because SIGINT is a person at a terminal and SIGTERM is an orchestrator, and a container\n * that ignored SIGTERM would be killed after its grace period — mid-delivery, which is the one\n * moment the outbox's recovery path exists to survive and would rather not exercise.\n */\nfunction waitForSignal(): Promise<void> {\n return new Promise((resolve) => {\n const finish = () => {\n process.off(\"SIGINT\", finish)\n process.off(\"SIGTERM\", finish)\n resolve()\n }\n process.once(\"SIGINT\", finish)\n process.once(\"SIGTERM\", finish)\n })\n}\n\n/** Re-exported for the boundaries test, which asserts this module imports no renderer. */\nexport const SERVE_EXIT_FAILURE = EXIT_FAILURE\n",
|
|
35
35
|
"/**\n * The `sessions` command — inspect what the store holds.\n *\n * This exists to make persistence observable from outside the process that wrote it. A store you\n * cannot look into is a store you cannot debug, and \"the history is in there somewhere\" is not a\n * claim anyone should have to take on faith.\n *\n * It opens the same database the chat session uses, which is safe while a turn is running: the driver\n * puts the file in WAL mode, so a reader does not block a writer.\n */\n\nimport { type Agent, Runtime, type SessionSummary } from \"@dispach/core\"\nimport { ambientEnv } from \"#lib/ambient\"\nimport { DEFAULT_ROW_LIMIT, EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { onExit } from \"#lib/exit\"\nimport { BUILT_IN_PLUGINS, CHANNELS, scriptRunner, TOOL_PROVIDERS } from \"#lib/providers\"\nimport { ago } from \"#lib/render\"\nimport { storePath } from \"#lib/sandbox\"\nimport type { SessionsOptions } from \"#lib/schema\"\n\nfunction pad(value: string, width: number): string {\n return value.length >= width ? value : value + \" \".repeat(width - value.length)\n}\n\n/**\n * Collapse a schedule's per-run sessions into one row.\n *\n * An isolated scheduled run gets a fresh session every time — `schedule:<id>:<runId>` — which is\n * what keeps a daily brief from accumulating history it was never asked to carry, and what makes\n * \"what did last Tuesday's brief say\" a question with an answer. The cost lands here: a 15-minute\n * schedule writes about 35,000 sessions a year, and unfolded they bury every conversation a person\n * actually had.\n *\n * Folded by the schedule id, newest run's activity shown, with the count beside it. The individual\n * keys are still addressable — `--session schedule:brief:r_…` reads one — so nothing is hidden,\n * only summarized.\n */\ninterface ListRow {\n readonly sessionKey: string\n readonly phase: string | undefined\n messages: number\n turns: number\n lastActivityAt: string\n runs?: number\n}\n\nfunction foldScheduleRuns(sessions: readonly SessionSummary[]): readonly ListRow[] {\n const folded = new Map<string, ListRow>()\n const out: ListRow[] = []\n\n for (const session of sessions) {\n const parts = session.sessionKey.split(\":\")\n // Exactly three segments, the first `schedule`: anything else is somebody's own key and is\n // left alone. A two-segment `schedule:brief` is a shared-session schedule and is a real\n // single conversation, not a run.\n const row: ListRow = {\n sessionKey: session.sessionKey,\n phase: session.phase,\n messages: session.messages,\n turns: session.turns,\n lastActivityAt: session.lastActivityAt,\n }\n\n if (parts.length !== 3 || parts[0] !== \"schedule\") {\n out.push(row)\n continue\n }\n\n const id = `schedule:${parts[1]}`\n const seen = folded.get(id)\n if (seen === undefined) {\n const entry: ListRow = { ...row, sessionKey: `${id}:*`, runs: 1 }\n folded.set(id, entry)\n out.push(entry)\n continue\n }\n seen.runs = (seen.runs ?? 1) + 1\n seen.messages += session.messages\n seen.turns += session.turns\n // The listing sorts by activity, so the fold keeps the most recent of the group.\n if (session.lastActivityAt > seen.lastActivityAt) {\n seen.lastActivityAt = session.lastActivityAt\n }\n }\n\n return out\n}\n\nfunction printList(sessions: readonly SessionSummary[]): void {\n if (sessions.length === 0) {\n // Exit 0: an agent with no conversations yet is a correct answer to the question asked, not\n // a failure. The line says so rather than printing nothing.\n process.stdout.write(\"no sessions yet\\n\")\n return\n }\n\n const rows = foldScheduleRuns(sessions)\n const keyWidth = Math.max(7, ...rows.map((s) => s.sessionKey.length))\n process.stdout.write(\n `${pad(\"SESSION\", keyWidth)} ${pad(\"MSGS\", 5)} ${pad(\"TURNS\", 5)} ${pad(\"PHASE\", 8)} LAST\\n`,\n )\n for (const session of rows) {\n const runs =\n session.runs === undefined\n ? \"\"\n : ` (${session.runs} run${session.runs === 1 ? \"\" : \"s\"})`\n process.stdout.write(\n `${pad(session.sessionKey, keyWidth)} ${pad(String(session.messages), 5)} ` +\n `${pad(String(session.turns), 5)} ${pad(session.phase ?? \"-\", 8)} ${ago(session.lastActivityAt, Date.now())}${runs}\\n`,\n )\n }\n}\n\nasync function printMessages(agent: Agent, sessionKey: string, limit: number): Promise<void> {\n const page = await agent.store.messages.page(agent.id, sessionKey, { limit })\n if (page.messages.length === 0) {\n process.stdout.write(`no messages in ${sessionKey}\\n`)\n return\n }\n // Oldest-first for reading, though the page came back newest-first for the cursor.\n for (const message of [...page.messages].reverse()) {\n process.stdout.write(`${message.role}: ${message.content}\\n`)\n }\n if (page.nextBefore !== undefined) {\n process.stdout.write(\"\\n… older messages exist; raise --limit\\n\")\n }\n}\n\nasync function printTurns(agent: Agent, sessionKey: string, limit: number): Promise<void> {\n const turns = await agent.turns(sessionKey, limit)\n if (turns.length === 0) {\n process.stdout.write(`no turns in ${sessionKey}\\n`)\n return\n }\n process.stdout.write(\n `${pad(\"TURN\", 22)} ${pad(\"STATUS\", 9)} ${pad(\"STEPS\", 5)} ${pad(\"TOKENS\", 13)} ${pad(\"MS\", 6)} SOURCE\\n`,\n )\n for (const turn of turns) {\n process.stdout.write(\n `${pad(turn.turnId, 22)} ${pad(turn.status, 9)} ${pad(String(turn.steps), 5)} ` +\n `${pad(`${turn.promptTokens}/${turn.outputTokens}`, 13)} ` +\n `${pad(String(turn.durationMs ?? \"-\"), 6)} ${turn.source}\\n`,\n )\n if (turn.errorCode !== undefined) {\n process.stdout.write(` ${turn.errorCode}: ${turn.errorMessage}\\n`)\n if (turn.errorHint !== undefined) process.stdout.write(` hint: ${turn.errorHint}\\n`)\n }\n }\n}\n\nexport async function sessionsCommand(options: SessionsOptions): Promise<number> {\n const runtime = await Runtime.create({\n agents: [options.manifestPath],\n // The sandbox store — the same default `run` writes to, or `sessions` inspects nothing.\n store: options.store ?? storePath(),\n toolProviders: TOOL_PROVIDERS,\n builtInPlugins: BUILT_IN_PLUGINS,\n scriptRunner: scriptRunner(),\n channels: CHANNELS,\n env: ambientEnv([options.manifestPath]),\n })\n onExit(() => runtime.stop(\"cli-exit\"))\n\n const agent = runtime.list()[0]\n if (agent === undefined) throw new Error(\"The manifest produced no agent.\")\n\n const limit = options.limit ?? DEFAULT_ROW_LIMIT\n\n if (options.clear === true) {\n if (options.sessionKey === undefined) {\n throw new Error(\n \"--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.\",\n )\n }\n const before = await agent.store.messages.count(agent.id, options.sessionKey)\n await agent.clearSession(options.sessionKey)\n process.stdout.write(\n `cleared ${options.sessionKey}: ${before} message(s) removed, memory files untouched\\n`,\n )\n return EXIT_OK\n }\n\n if (options.json === true) {\n const payload =\n options.sessionKey === undefined\n ? { store: runtime.store.location, sessions: await agent.sessions() }\n : {\n store: runtime.store.location,\n session: await agent.store.sessions.get(agent.id, options.sessionKey),\n messages: (\n await agent.store.messages.page(agent.id, options.sessionKey, { limit })\n ).messages,\n turns: await agent.turns(options.sessionKey, limit),\n }\n process.stdout.write(`${JSON.stringify(payload, null, 2)}\\n`)\n return EXIT_OK\n }\n\n process.stdout.write(`store: ${runtime.store.location}\\n\\n`)\n\n if (options.sessionKey === undefined) {\n printList(await agent.sessions())\n return EXIT_OK\n }\n\n const session = await agent.store.sessions.get(agent.id, options.sessionKey)\n if (session === undefined) {\n // Exit 1: the user named a session that is not there. Printing \"0 messages\" would answer a\n // question they did not ask and hide the typo.\n process.stderr.write(\n `no session \"${options.sessionKey}\" for agent ${agent.id}\\n` +\n ` hint: run \\`sessions ${options.manifestPath}\\` to list the keys that exist\\n`,\n )\n return EXIT_FAILURE\n }\n\n if (options.turns === true) await printTurns(agent, options.sessionKey, limit)\n else await printMessages(agent, options.sessionKey, limit)\n return EXIT_OK\n}\n",
|
|
36
36
|
"/**\n * `soul distill <file>` — scaffold a hand-edited compact identity from a long-form document.\n *\n * A scaffold, never a summary. The command copies the document's *structure* — its headings, and\n * its `<rules>` blocks verbatim, because rules are exactly what must survive distillation and\n * copying is not summarising — and leaves a placeholder under each heading for the author to fill.\n * Automatic summarisation of an identity document drops exactly the parts that produce voice,\n * which is why `onUnmet: distill` ships a committed file and not a runtime transformation.\n *\n * The placeholders are the `{{NAME}}` form the `workspace` command already warns about, on\n * purpose: an unedited scaffold keeps reporting itself until a person has written every section.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\"\nimport { basename, dirname, join } from \"node:path\"\nimport { HarnessError, parseWorkspaceFile } from \"@dispach/core\"\nimport { EXIT_OK } from \"#lib/const\"\n\nexport interface SoulOptions {\n readonly action: string\n readonly file: string\n readonly out?: string\n}\n\nconst HEADING = /^(#{1,6})\\s+(.*)$/\nconst RULES_OPEN = /^[ \\t]*<rules(?:\\s[^>]*)?>[ \\t]*$/\nconst RULES_CLOSE = /^[ \\t]*<\\/rules>[ \\t]*$/\nconst FENCE = /^\\s*(?:```|~~~)/\n\nexport function soulCommand(options: SoulOptions): number {\n if (options.action !== \"distill\") {\n throw new HarnessError({\n code: \"cli_soul_unknown_action\",\n message: `soul takes the action \"distill\", not \"${options.action}\".`,\n hint: \"Usage: soul distill <file> [--out <path>]. It scaffolds a compact identity file from a long-form document; the scaffold is edited by hand and named in context.soul.distilled.\",\n })\n }\n\n let raw: string\n try {\n raw = readFileSync(options.file, \"utf8\")\n } catch {\n throw new HarnessError({\n code: \"cli_soul_file_missing\",\n message: `${options.file} is not readable.`,\n hint: \"Point soul distill at the long-form identity document named by context.soul.file.\",\n })\n }\n\n const source = basename(options.file)\n const out =\n options.out ?? join(dirname(options.file), `${source.replace(/\\.md$/i, \"\")}.compact.md`)\n\n if (existsSync(out)) {\n throw new HarnessError({\n code: \"cli_soul_out_exists\",\n message: `${out} already exists, and a scaffold must not overwrite a file someone has edited.`,\n hint: \"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable.\",\n })\n }\n\n // The comments below are authoring guidance in the same sense as the workspace templates':\n // the loader strips them before injection, so they are free at runtime.\n const { body } = parseWorkspaceFile(source, raw)\n const scaffold = buildScaffold(source, body)\n\n writeFileSync(out, scaffold, \"utf8\")\n process.stdout.write(\n `wrote ${out}\\n` +\n `\\n` +\n `The scaffold copies ${source}'s headings and its <rules> blocks verbatim, and leaves a\\n` +\n `{{PLACEHOLDER}} under each heading. Now:\\n` +\n ` 1. Fill every placeholder by hand — two or three sentences that must survive, in the\\n` +\n ` document's own voice. The workspace command warns until none are left.\\n` +\n ` 2. Name the file in context.soul.distilled.\\n`,\n )\n return EXIT_OK\n}\n\n/**\n * Structure over prose: headings and rules survive, everything else becomes a named placeholder.\n *\n * Deliberately line-oriented and fence-aware, like the renderer — a heading inside a fence is a\n * demonstration, not a section.\n */\nfunction buildScaffold(source: string, body: string): string {\n const lines: string[] = [\n \"---\",\n \"tier: static\",\n \"---\",\n \"\",\n \"<!--\",\n `Compact identity scaffolded from ${source}. This file is the one small models actually`,\n `run on, so every sentence here is paid for on every turn — keep it to the few that`,\n `produce the voice. The long document stays the source of truth; edit it first, then`,\n `re-derive this by hand. These comments are stripped before injection and cost nothing.`,\n \"-->\",\n \"\",\n ]\n\n let inFence = false\n let inRules = false\n let sections = 0\n let sawHeading = false\n\n for (const line of body.split(\"\\n\")) {\n if (FENCE.test(line)) {\n inFence = !inFence\n if (inRules) lines.push(line)\n continue\n }\n if (inFence) {\n if (inRules) lines.push(line)\n continue\n }\n\n if (RULES_OPEN.test(line)) {\n inRules = true\n lines.push(line)\n continue\n }\n if (inRules) {\n lines.push(line)\n if (RULES_CLOSE.test(line)) {\n inRules = false\n lines.push(\"\")\n }\n continue\n }\n\n const heading = HEADING.exec(line)\n if (heading !== null) {\n sawHeading = true\n sections += 1\n lines.push(line)\n lines.push(\"\")\n lines.push(`{{SECTION_${sections}}}`)\n lines.push(\"\")\n }\n }\n\n if (!sawHeading) {\n lines.push(`{{ESSENCE}}`)\n lines.push(\"\")\n }\n\n return `${lines\n .join(\"\\n\")\n .replace(/\\n{3,}/g, \"\\n\\n\")\n .trimEnd()}\\n`\n}\n",
|
|
37
37
|
"/**\n * `sources list|add|remove|update|search` — the repositories skills are found in.\n *\n * A separate command from `skills`, and the split is the point: **`skills` acts on one agent and always\n * takes a manifest; `sources` is machine-level and never takes one.** Folding these together would have\n * meant a positional whose meaning changes with the verb — the agent for `list`, a sub-verb for\n * `sources`, a query for `search` — which reads badly in `--help` and parses worse. The boundary also\n * happens to be the one this codebase keeps arriving at: what the agent may do is the agent's, and where\n * things come from is the person's.\n *\n * `search` fetches a source that has never been fetched, and never refreshes one that has. That makes\n * the first search work on a new machine with no setup, which is the whole point of shipping defaults,\n * while keeping \"go and talk to the network again\" an explicit `update`. Both announce what they are\n * doing before they do it, because a command that pauses for nine seconds with no output is\n * indistinguishable from one that has hung — which is exactly the failure this file's git wrapper exists\n * to prevent.\n */\n\nimport { bm25Selector, HarnessError, nearest, type ScoredSkill, type Skill } from \"@dispach/core\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { bullet, indent, keyValue, section } from \"#lib/render\"\nimport {\n type CatalogueEntry,\n fetchSource,\n type Git,\n isCached,\n readCatalogue,\n readMeta,\n} from \"#lib/source-cache\"\nimport {\n addSource,\n DEFAULT_SOURCES,\n isSourceName,\n loadSources,\n parseSourceUrl,\n registryPath,\n removeSource,\n type SourceSpec,\n} from \"#lib/sources\"\n\nexport const SOURCES_ACTIONS = [\"list\", \"add\", \"remove\", \"update\", \"search\"] as const\n\nexport interface SourcesOptions {\n readonly action: string\n /** Everything after the action: a name, a URL, a query. Meaning is the action's. */\n readonly rest: readonly string[]\n readonly path?: string\n readonly ref?: string\n readonly json?: boolean\n /** Injected by the tests, which never reach a network. */\n readonly git?: Git\n readonly env?: Readonly<Record<string, string | undefined>>\n}\n\n/** How many search hits are printed before the rest are counted. */\nconst TOP = 12\n\nexport async function sourcesCommand(options: SourcesOptions): Promise<number> {\n try {\n switch (options.action) {\n case \"list\":\n return list(options)\n case \"add\":\n return add(options)\n case \"remove\":\n return drop(options)\n case \"update\":\n return await update(options)\n case \"search\":\n return await search(options)\n default:\n // Unreachable through the dispatcher, which checks against the spec's choices.\n throw new HarnessError({\n code: \"sources_action_unknown\",\n message: `${options.action} is not a sources action`,\n hint: `One of: ${SOURCES_ACTIONS.join(\", \")}.`,\n })\n }\n } catch (error) {\n if (error instanceof HarnessError) {\n process.stdout.write(`${error.message}\\n\\n ${error.hint}\\n`)\n return EXIT_FAILURE\n }\n throw error\n }\n}\n\nfunction list(options: SourcesOptions): number {\n const sources = loadSources(options.env)\n const rows = sources.map((spec) => {\n const meta = readMeta(spec.name, options.env)\n return {\n ...spec,\n cached: isCached(spec.name, options.env),\n commit: meta.commit,\n fetchedAt: meta.fetchedAt,\n skills: meta.skills,\n }\n })\n\n if (options.json === true) {\n process.stdout.write(\n `${JSON.stringify({ registry: registryPath(options.env), sources: rows }, null, 2)}\\n`,\n )\n return EXIT_OK\n }\n\n if (rows.length === 0) {\n process.stdout.write(\n `every built-in source has been removed, and none has been added\\n\\n \\`sources add <name> <url>\\` to add one, or \\`sources add ${DEFAULT_SOURCES[0]?.name ?? \"anthropic\"} ${DEFAULT_SOURCES[0]?.url ?? \"\"}\\` to put a built-in back.\\n`,\n )\n return EXIT_OK\n }\n\n process.stdout.write(section(\"sources\", true))\n for (const row of rows) {\n process.stdout.write(\n `\\n${bullet(`${row.name}${row.builtin === true ? \" (built-in)\" : \"\"}`)}\\n`,\n )\n process.stdout.write(\n indent(\n keyValue([\n { label: \"url\", value: row.url },\n ...(row.path === undefined ? [] : [{ label: \"path\", value: row.path }]),\n ...(row.ref === undefined ? [] : [{ label: \"branch\", value: row.ref }]),\n {\n label: \"cached\",\n value: row.cached\n ? `${row.skills ?? \"?\"} skills at ${row.commit ?? \"?\"}, fetched ${row.fetchedAt ?? \"at an unknown time\"}`\n : \"never fetched — `sources update` or just search, which fetches on demand\",\n },\n ]),\n 4,\n ),\n )\n }\n process.stdout.write(`\\n${section(\"registry\")}\\n${indent(registryPath(options.env))}\\n`)\n return EXIT_OK\n}\n\nfunction add(options: SourcesOptions): number {\n const [first, second] = options.rest\n if (first === undefined) {\n throw new HarnessError({\n code: \"sources_add_incomplete\",\n message: \"sources add needs a repository\",\n hint: \"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood.\",\n })\n }\n\n // `add <url>` and `add <name> <url>` are told apart by which argument looks like a repository,\n // rather than by counting: a one-argument form that guessed wrong would silently register a source\n // called `https:` and fail on the next line.\n const named = second !== undefined\n const rawUrl = named ? (second as string) : first\n const parsed = parseSourceUrl(rawUrl)\n const name = named ? first : derive(parsed.url)\n\n if (!isSourceName(name)) {\n throw new HarnessError({\n code: \"sources_name_invalid\",\n message: `${JSON.stringify(name)} is not usable as a source name`,\n hint: \"Lowercase letters, digits and single hyphens — it becomes a directory in the cache and the prefix in `install <agent> <source>/<skill>`.\",\n })\n }\n\n const existing = loadSources(options.env).find((spec) => spec.name === name)\n if (existing !== undefined && !named) {\n throw new HarnessError({\n code: \"sources_name_taken\",\n message: `${name} is already a source, pointing at ${existing.url}`,\n hint: `Give this one its own name: \\`sources add <name> ${rawUrl}\\`.`,\n })\n }\n\n // A flag beats the URL, so a page URL can be added and then narrowed without retyping it.\n const path = options.path ?? parsed.path\n const ref = options.ref ?? parsed.ref\n const spec: SourceSpec = {\n name,\n url: parsed.url,\n ...(path === undefined ? {} : { path }),\n ...(ref === undefined ? {} : { ref }),\n }\n addSource(spec, options.env)\n\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify({ added: spec }, null, 2)}\\n`)\n return EXIT_OK\n }\n process.stdout.write(\n `${keyValue([\n { label: existing === undefined ? \"added\" : \"replaced\", value: name },\n { label: \"url\", value: spec.url },\n ...(spec.path === undefined\n ? [\n {\n label: \"path\",\n value: \"the whole repository — `--path skills` if the skills live in a subdirectory\",\n },\n ]\n : [{ label: \"path\", value: spec.path }]),\n ...(spec.ref === undefined ? [] : [{ label: \"branch\", value: spec.ref }]),\n ])}\\n`,\n )\n process.stdout.write(\n `${section(\"next\")}\\n${bullet(`sources update ${name}`)}\\n${bullet(\"sources search <what you need>\")}\\n`,\n )\n return EXIT_OK\n}\n\n/**\n * A name for a repository nobody named: its owner.\n *\n * `anthropics/skills` → `anthropics`, `github/awesome-copilot` → `github`. The repository half is the\n * wrong choice — half the candidates on any search are called `skills`, so it collides immediately and\n * carries no information.\n */\nfunction derive(url: string): string {\n const segments = url\n .replace(/\\.git$/, \"\")\n .split(/[:/]/)\n .filter((part) => part.length > 0)\n const owner = segments[segments.length - 2] ?? \"\"\n return owner\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-|-$/g, \"\")\n}\n\nfunction drop(options: SourcesOptions): number {\n const name = options.rest[0]\n if (name === undefined) {\n throw new HarnessError({\n code: \"sources_remove_incomplete\",\n message: \"sources remove needs a name\",\n hint: \"`sources list` shows them.\",\n })\n }\n const known = loadSources(options.env).map((spec) => spec.name)\n if (!removeSource(name, options.env)) {\n const suggestion = nearest(name, known)\n throw new HarnessError({\n code: \"sources_unknown\",\n message: `no source called ${name}`,\n hint:\n suggestion === undefined\n ? `Configured: ${known.join(\", \") || \"none\"}.`\n : `Did you mean ${suggestion}?`,\n })\n }\n const builtin = DEFAULT_SOURCES.some((spec) => spec.name === name)\n process.stdout.write(\n `removed ${name}${builtin ? \" — a built-in, so it stays out until `sources add` puts it back\" : \"\"}\\n`,\n )\n process.stdout.write(\n \"\\n The cached copy is left on disk; nothing already installed into an agent is touched.\\n\",\n )\n return EXIT_OK\n}\n\nasync function update(options: SourcesOptions): Promise<number> {\n const configured = loadSources(options.env)\n const wanted =\n options.rest.length === 0\n ? configured\n : options.rest.map((name) => {\n const found = configured.find((spec) => spec.name === name)\n if (found === undefined) {\n const suggestion = nearest(\n name,\n configured.map((spec) => spec.name),\n )\n throw new HarnessError({\n code: \"sources_unknown\",\n message: `no source called ${name}`,\n hint:\n suggestion === undefined\n ? `Configured: ${configured.map((spec) => spec.name).join(\", \") || \"none\"}.`\n : `Did you mean ${suggestion}?`,\n })\n }\n return found\n })\n\n if (wanted.length === 0) {\n process.stdout.write(\"no sources configured\\n\\n `sources add <url>` to add one.\\n\")\n return EXIT_OK\n }\n\n const done: { name: string; commit: string; skills: number }[] = []\n const failed: { name: string; reason: string }[] = []\n for (const spec of wanted) {\n // Announced before the work, not after: a clone of a large repository takes seconds and silence\n // is how a person decides a command has hung.\n if (options.json !== true) process.stdout.write(`fetching ${spec.name} … `)\n try {\n const result = await fetchSource(spec, {\n ...(options.env === undefined ? {} : { env: options.env }),\n ...(options.git === undefined ? {} : { git: options.git }),\n })\n done.push({ name: spec.name, commit: result.commit, skills: result.skills })\n if (options.json !== true) {\n process.stdout.write(\n `${result.skills} skills at ${result.commit}${result.unfiltered && spec.path !== undefined ? \" (full clone — the server refused a partial one)\" : \"\"}\\n`,\n )\n }\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error)\n failed.push({ name: spec.name, reason })\n if (options.json !== true) process.stdout.write(`failed\\n`)\n if (options.json !== true && error instanceof HarnessError) {\n process.stdout.write(`${indent(error.message)}\\n${indent(error.hint, 4)}\\n`)\n }\n }\n }\n\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify({ updated: done, failed }, null, 2)}\\n`)\n }\n // One source failing is not the command failing, but a run where nothing worked exits non-zero —\n // hard rule 8: nothing fails silently and exits 0.\n return done.length === 0 ? EXIT_FAILURE : EXIT_OK\n}\n\n/**\n * Rank every skill in every source against a query, with the same scorer that decides activation.\n *\n * Deliberate reuse rather than convenience: `bm25Selector` is what the runtime will run against the\n * installed skill's own frontmatter on every turn, so what ranks first here is what will actually\n * activate there. A separate search ranking would let a skill look like the obvious answer in the\n * catalogue and never fire once installed, and nothing would report the discrepancy.\n */\nasync function search(options: SourcesOptions): Promise<number> {\n const query = options.rest.join(\" \").trim()\n const configured = loadSources(options.env)\n if (configured.length === 0) {\n process.stdout.write(\"no sources configured\\n\\n `sources add <url>` to add one.\\n\")\n return EXIT_FAILURE\n }\n\n const cold = configured.filter((spec) => !isCached(spec.name, options.env))\n for (const spec of cold) {\n if (options.json !== true)\n process.stdout.write(`fetching ${spec.name} for the first time … `)\n try {\n const result = await fetchSource(spec, {\n ...(options.env === undefined ? {} : { env: options.env }),\n ...(options.git === undefined ? {} : { git: options.git }),\n })\n if (options.json !== true) process.stdout.write(`${result.skills} skills\\n`)\n } catch (error) {\n if (options.json !== true) {\n process.stdout.write(`failed\\n`)\n if (error instanceof HarnessError)\n process.stdout.write(`${indent(error.message)}\\n`)\n }\n }\n }\n\n const entries = configured.flatMap((spec) => readCatalogue(spec, options.env))\n if (entries.length === 0) {\n process.stdout.write(\n \"\\nnothing to search — no source has been fetched successfully\\n\\n `sources update` reports why.\\n\",\n )\n return EXIT_FAILURE\n }\n\n const ranked = query.length === 0 ? entries : rank(query, entries)\n if (ranked.length === 0) {\n process.stdout.write(\n `\\nnothing in ${entries.length} skills across ${configured.length} sources matches ${JSON.stringify(query)}\\n\\n Try the words a skill's own description would use — the ranking is lexical, not semantic. \\`sources search\\` with no query lists everything.\\n`,\n )\n return EXIT_OK\n }\n\n if (options.json === true) {\n process.stdout.write(\n `${JSON.stringify(\n {\n query,\n searched: entries.length,\n results: ranked.map((entry) => ({\n source: entry.source,\n skill: entry.skill,\n description: entry.description,\n tokens: entry.tokens,\n scripts: entry.scripts.length,\n repoPath: entry.repoPath,\n ...(entry.problem === undefined ? {} : { problem: entry.problem }),\n })),\n },\n null,\n 2,\n )}\\n`,\n )\n return EXIT_OK\n }\n\n const shown = ranked.slice(0, TOP)\n process.stdout.write(\n `\\n${section(query.length === 0 ? `${entries.length} skills` : `${ranked.length} of ${entries.length} skills match ${JSON.stringify(query)}`, true)}\\n`,\n )\n for (const entry of shown) {\n process.stdout.write(\n `${bullet(`${entry.source}/${entry.skill}`)} ${entry.tokens} tokens${\n entry.scripts.length === 0\n ? \"\"\n : `, ${entry.scripts.length} runnable file${entry.scripts.length === 1 ? \"\" : \"s\"}`\n }${entry.problem === undefined ? \"\" : \" — will not load\"}\\n`,\n )\n const summary = entry.problem ?? entry.description\n process.stdout.write(\n `${indent(summary.length > 160 ? `${summary.slice(0, 157)}…` : summary, 4)}\\n`,\n )\n }\n if (ranked.length > shown.length) {\n process.stdout.write(\n `\\n${indent(`… and ${ranked.length - shown.length} more; narrow the query or use --json`)}\\n`,\n )\n }\n process.stdout.write(\n `\\n${section(\"install\")}\\n${indent(`skills install <agent> ${shown[0]?.source}/${shown[0]?.skill}`)}\\n`,\n )\n return EXIT_OK\n}\n\nfunction rank(query: string, entries: readonly CatalogueEntry[]): readonly CatalogueEntry[] {\n const byKey = new Map<string, CatalogueEntry>()\n const skills: Skill[] = entries.map((entry) => {\n const key = `${entry.source}/${entry.skill}`\n byKey.set(key, entry)\n return {\n // The scorer reads `name` and `description` only, so a source-qualified name is what keeps\n // two sources' `pdf` apart in the result set without changing what is scored.\n name: key,\n dir: entry.dir,\n tokens: entry.tokens,\n scripts: [],\n ignoredScripts: [],\n frontmatter: { name: key, description: entry.description, metadata: {} },\n }\n })\n return bm25Selector(query, skills)\n .filter((scored: ScoredSkill) => scored.score > 0)\n .map((scored) => byKey.get(scored.skill.name))\n .filter((entry): entry is CatalogueEntry => entry !== undefined)\n}\n",
|
|
@@ -42,7 +42,7 @@
|
|
|
42
42
|
"/**\n * The `workspace <manifest>` command — the authoring rules, checked.\n *\n * Deliberately a separate command from `validate`. That one answers \"does this load?\", which is a\n * question with a yes or a no; this one answers \"is this written well?\", which is a judgement. They\n * report differently because they are different: a budget bust stops the runtime, and a rule with no\n * stated reason is a note from a careful reader.\n *\n * So every finding here is a warning and the command exits 0 by default. `--strict` is for CI, where\n * \"warnings you have decided to live with\" and \"warnings nobody has read\" look identical and only a\n * non-zero exit tells them apart.\n */\n\nimport {\n checkAuthoring,\n type ErrorDetail,\n HarnessError,\n loadManifest,\n resolveCapabilities,\n resolveWorkspace,\n ruleBudgetFailure,\n} from \"@dispach/core\"\nimport { ambientEnv } from \"#lib/ambient\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { CHANNEL_IDS, PROVIDER_IDS } from \"#lib/providers\"\n\nexport interface WorkspaceOptions {\n readonly manifestPath: string\n readonly json?: boolean\n readonly strict?: boolean\n}\n\nexport function workspaceCommand(options: WorkspaceOptions): number {\n try {\n const loaded = loadManifest(options.manifestPath, {\n knownProviders: PROVIDER_IDS,\n knownChannels: CHANNEL_IDS,\n // The same environment `run` will use, or this validates a different agent — the\n // failure that rule exists for is a validator that disagrees with the runtime.\n env: ambientEnv([options.manifestPath]),\n })\n const { manifest } = loaded\n const capabilities = resolveCapabilities(\n manifest.model.main.id,\n manifest.model.main.capabilities,\n )\n\n // The same resolution `run` uses, soul gate included — the file the gate selects is a file\n // someone wrote, and its writing deserves the same reading as any other identity file.\n const { workspace, warnings } = resolveWorkspace(loaded, capabilities.promptStyle)\n\n // The authoring checks read the *authored* text, never the rendered form. An author fixes\n // what they wrote, and telling them about a heading the renderer inserted would send them\n // looking for a line that is not in their file.\n const findings: ErrorDetail[] = [\n ...warnings,\n ...checkAuthoring(\n workspace.files.map((file) => ({\n name: file.name,\n authored: file.authored,\n tier: file.tier,\n field: file.field,\n })),\n ),\n ]\n const ruleFailure = ruleBudgetFailure(workspace, manifest.context.rules)\n if (ruleFailure !== undefined) findings.push(ruleFailure.toDetail())\n\n if (options.json === true) {\n process.stdout.write(\n `${JSON.stringify(\n {\n ok: findings.length === 0,\n path: loaded.path,\n promptStyle: capabilities.promptStyle,\n files: workspace.files.map((file) => ({\n name: file.name,\n tier: file.tier,\n editable: file.editable,\n tokens: file.tokens,\n budget: file.budget,\n })),\n tokens: workspace.tokens,\n findings,\n },\n null,\n 2,\n )}\\n`,\n )\n return options.strict === true && findings.length > 0 ? EXIT_FAILURE : EXIT_OK\n }\n\n const style = capabilities.promptStyle\n process.stdout.write(\n `${loaded.path}\\n` +\n ` rendering delimiters=${style.delimiters} intensity=${style.intensity} examplesIn=${style.examplesIn}\\n` +\n ` total ${workspace.tokens.total} tokens (static ${workspace.tokens.static}, volatile ${workspace.tokens.volatile}, reminder ${workspace.tokens.reminder})\\n`,\n )\n\n for (const file of workspace.files) {\n process.stdout.write(\n ` ${file.name.padEnd(14)} ${file.tier.padEnd(9)} ${String(file.tokens).padStart(5)}/${file.budget} tokens, editable=${file.editable}\\n`,\n )\n }\n\n if (findings.length === 0) {\n process.stdout.write(\"\\nno findings\\n\")\n return EXIT_OK\n }\n\n for (const finding of findings) {\n process.stdout.write(`\\n ${finding.code}: ${finding.message}\\n`)\n process.stdout.write(` hint: ${finding.hint}\\n`)\n }\n // Counted rather than merely listed: \"three findings\" is the sentence someone acts on, and\n // scrolling back to count them is how a fourth one goes unnoticed.\n process.stdout.write(`\\n${findings.length} finding(s)\\n`)\n\n return options.strict === true ? EXIT_FAILURE : EXIT_OK\n } catch (error) {\n if (options.json === true && error instanceof HarnessError) {\n process.stdout.write(\n `${JSON.stringify({ ok: false, error: error.toDetail(), details: error.details }, null, 2)}\\n`,\n )\n return EXIT_FAILURE\n }\n throw error\n }\n}\n",
|
|
43
43
|
"/**\n * The entry point: parse, dispatch, exit.\n *\n * No shebang here — the build prepends one via `--banner`. Two would be a syntax error, and the\n * source is never executed directly: `bun run src/index.ts` and `node dist/index.js` are the two\n * supported ways in.\n *\n * Three rules hold here and nowhere else.\n *\n * **It imports no Ink and no React.** The rich renderer is reached through a dynamic `import()` in\n * `run.ts`, because loading it costs ~170-210 ms under Node — more than the entire runtime of\n * `validate --json`. A static import anywhere on this path would be paid by every command.\n *\n * **Commands return exit codes; they never call `process.exit`.** Exiting mid-write discards buffered\n * stdout when the output is a pipe, which is how `--json` gets read. This file is the one exception,\n * on the last line, and only after `finish` has drained the output — a command that exits by itself\n * skips the teardowns and the drain both.\n *\n * **Asking for help is a success.** The previous entry point set exit code 1 for `--help` given\n * without a command, reporting failure for the one thing that had worked.\n */\n\nimport { BRAND, HarnessError, VERSION } from \"@dispach/core\"\nimport { agentsCommand } from \"#agents\"\nimport { browseCommand } from \"#browse\"\nimport { daemonCommand } from \"#daemon\"\nimport { initCommand } from \"#init\"\nimport { keysCommand } from \"#keys\"\nimport { parse } from \"#lib/args\"\nimport { announce, type BootstrapResult, ensureServer } from \"#lib/bootstrap\"\nimport { askExactly, askYesNo } from \"#lib/confirm\"\nimport { EXIT_FAILURE, EXIT_OK } from \"#lib/const\"\nimport { readEnv } from \"#lib/env\"\nimport { finishNow, installGuards } from \"#lib/exit\"\nimport { helpText } from \"#lib/help\"\nimport { resolveAgentRef } from \"#lib/sandbox\"\nimport { quietAcceptedWarnings } from \"#lib/warnings\"\nimport { memoryCommand } from \"#memory\"\nimport { modelCommand } from \"#model\"\nimport { pluginsCommand } from \"#plugins\"\nimport { removeCommand } from \"#remove\"\nimport { runCommand } from \"#run\"\nimport { schedulesCommand } from \"#schedules\"\nimport { serveCommand } from \"#serve\"\nimport { sessionsCommand } from \"#sessions\"\nimport { skillsCommand } from \"#skills\"\nimport { soulCommand } from \"#soul\"\nimport { sourcesCommand } from \"#sources\"\nimport { startCommand } from \"#start\"\nimport { stopCommand } from \"#stop\"\nimport { terminalSetupCommand } from \"#terminal-setup\"\nimport { toolsCommand } from \"#tools\"\nimport { validateCommand } from \"#validate\"\nimport { workspaceCommand } from \"#workspace\"\n\nfunction report(error: unknown): number {\n if (error instanceof HarnessError) {\n // `format()` prints the code, the field, the hint, and every sub-failure — so a command line\n // with two mistakes in it reports both rather than one at a time.\n process.stderr.write(`${error.format()}\\n`)\n } else if (error instanceof Error) {\n process.stderr.write(`${error.message}\\n`)\n if (readEnv().debug && error.stack !== undefined) process.stderr.write(`${error.stack}\\n`)\n } else {\n process.stderr.write(`${String(error)}\\n`)\n }\n return EXIT_FAILURE\n}\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 */\nasync 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\nasync function dispatch(argv: readonly string[]): Promise<number> {\n const result = parse(argv)\n\n switch (result.kind) {\n case \"version\":\n process.stdout.write(`${VERSION}\\n`)\n return EXIT_OK\n\n case \"help\":\n process.stdout.write(helpText(result.command))\n return EXIT_OK\n\n case \"usage\":\n // Invoked with nothing to do. The help goes to stdout because it was not an error in the\n // arguments — but the code is non-zero, because nothing was accomplished.\n process.stdout.write(helpText())\n return EXIT_FAILURE\n\n case \"command\":\n break\n }\n\n const { command, positionals, flags } = result.parsed\n // Present when the command's first argument is required; `init` and `run` legitimately take\n // none. Each case knows which it is.\n const manifestPath = positionals[0] as string\n // Every manifest-taking command accepts a sandbox agent name too — one resolver, applied\n // here at the dispatch layer, so `sessions milo` works the moment `run milo` does. The\n // resolution throws with the candidate list and a nearest-match hint.\n const resolved = (): string => resolveAgentRef(manifestPath)\n\n /**\n * First run: if this command wants a host and none is up, put one up and say so in one line.\n *\n * Here rather than in each command, because \"does this want a host\" is declared on the spec\n * (`CommandSpec.needsServer`, required) and this is the one place that reads it — a hand-kept\n * list of command names would be the drift `session-commands.ts` was written to end, with a new\n * command silently absent from it or silently included in it.\n *\n * **Before the switch and after the parse**, which matters in both directions: `--help`,\n * `--version` and a usage error have already returned above, so asking for help never installs\n * anything; and an unparseable command line never gets this far either.\n *\n * The announcement goes to **stderr** so it cannot land in the middle of `--json` output\n * somebody is piping into `jq`. It never throws — see `ensureServer`.\n */\n // `--store` only when this command declares it. `flags.str` throws for an undeclared flag —\n // deliberately, since reading one is a CLI bug — and the bootstrap is global, so it cannot\n // assume a per-command flag exists. Asking the spec is the honest version of that question.\n const storeFlag = command.flags.some((flag) => flag.name === \"store\")\n ? flags.str(\"store\")\n : undefined\n const bootstrap = await ensureServer({\n needsServer: command.needsServer,\n disabled: flags.bool(\"no-bootstrap\"),\n install: () => installServerUnit(),\n ...(storeFlag === undefined ? {} : { store: storeFlag }),\n })\n const note = announce(bootstrap)\n if (note !== undefined) process.stderr.write(note)\n\n switch (command.name) {\n case \"init\": {\n // `--dir`, never a positional: `init milo` read as the agent's name and meant the\n // directory. The parser refuses a positional now, with the spec's own two-readings hint.\n const dir = flags.str(\"dir\")\n const user = flags.str(\"user\")\n const name = flags.str(\"name\")\n const purpose = flags.str(\"purpose\")\n const preset = flags.str(\"preset\")\n const model = flags.str(\"model\")\n const baseUrl = flags.str(\"base-url\")\n const apiKeyEnv = flags.str(\"api-key-env\")\n const system = flags.str(\"system\")\n const web = flags.str(\"web\")\n const webBackend = flags.str(\"web-backend\")\n const composio = flags.str(\"composio\")\n const telegram = flags.str(\"telegram\")\n const telegramAllow = flags.str(\"telegram-allow\")\n const server = flags.str(\"server\")\n const schedules = flags.str(\"schedules\")\n const skills = flags.str(\"skills\")\n const daemon = flags.str(\"daemon\")\n return await initCommand({\n ...(dir === undefined ? {} : { dir }),\n ...(user === undefined ? {} : { user }),\n ...(name === undefined ? {} : { name }),\n ...(purpose === undefined ? {} : { purpose }),\n ...(preset === undefined ? {} : { preset }),\n ...(model === undefined ? {} : { model }),\n ...(baseUrl === undefined ? {} : { baseUrl }),\n ...(apiKeyEnv === undefined ? {} : { apiKeyEnv }),\n ...(system === undefined ? {} : { system }),\n ...(web === undefined ? {} : { web }),\n ...(webBackend === undefined ? {} : { webBackend }),\n ...(composio === undefined ? {} : { composio }),\n ...(telegram === undefined ? {} : { telegram }),\n ...(schedules === undefined ? {} : { schedules }),\n ...(telegramAllow === undefined ? {} : { telegramAllow }),\n ...(server === undefined ? {} : { server }),\n ...(skills === undefined ? {} : { skills }),\n ...(daemon === undefined ? {} : { daemon }),\n yes: flags.bool(\"yes\"),\n plain: flags.bool(\"plain\"),\n })\n }\n\n case \"run\": {\n const session = flags.str(\"session\")\n const input = flags.str(\"input\")\n const store = flags.str(\"store\")\n return await runCommand({\n // Bare `run` hands the sandbox the decision; a given ref resolves path-or-name.\n ...(positionals[0] === undefined ? {} : { manifestPath: resolved() }),\n ...(session === undefined ? {} : { sessionKey: session }),\n continueSession: flags.bool(\"continue\"),\n ...(input === undefined ? {} : { once: input }),\n ...(store === undefined ? {} : { store }),\n ephemeral: flags.bool(\"ephemeral\"),\n quiet: flags.bool(\"quiet\"),\n showReasoning: flags.bool(\"show-reasoning\"),\n noReasoning: flags.bool(\"no-reasoning\"),\n // Only when actually written. `flags.bool` returns `false` for an absent boolean, and\n // passing that would turn \"no opinion\" into \"definitely on\" and override the env var.\n ...(flags.bool(\"no-enhanced-keys\") ? { noEnhancedKeys: true } : {}),\n plain: flags.bool(\"plain\"),\n })\n }\n\n case \"schedules\": {\n const store = flags.str(\"store\")\n const id = flags.str(\"id\")\n const enable = flags.str(\"enable\")\n const disable = flags.str(\"disable\")\n return await schedulesCommand({\n manifestPath: resolved(),\n ...(store === undefined ? {} : { store }),\n ...(id === undefined ? {} : { id }),\n ...(enable === undefined ? {} : { enable }),\n ...(disable === undefined ? {} : { disable }),\n recipients: flags.bool(\"recipients\"),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"sessions\": {\n const session = flags.str(\"session\")\n const store = flags.str(\"store\")\n const limit = flags.num(\"limit\")\n return await sessionsCommand({\n manifestPath: resolved(),\n ...(session === undefined ? {} : { sessionKey: session }),\n ...(store === undefined ? {} : { store }),\n ...(limit === undefined ? {} : { limit }),\n json: flags.bool(\"json\"),\n clear: flags.bool(\"clear\"),\n turns: flags.bool(\"turns\"),\n })\n }\n\n case \"memory\": {\n const limit = flags.num(\"limit\")\n const store = flags.str(\"store\")\n return await memoryCommand({\n // Positional 0 is the action, as for `soul` and `daemon` — so `resolved()` must not run\n // here; the manifest is positional 1.\n action: manifestPath,\n manifestPath: resolveAgentRef(positionals[1] ?? \"\"),\n ...(positionals[2] === undefined ? {} : { query: positionals[2] }),\n ...(limit === undefined ? {} : { limit }),\n ...(store === undefined ? {} : { store }),\n all: flags.bool(\"all\"),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"config\": {\n // As for `soul` and `daemon`, positional 0 is the action, so `resolved()` must not run —\n // the agent is positional 1 and this command resolves it itself.\n const { configCommand, readAction } = await import(\"#config\")\n // `config <agent>` with no action is the editor, so the split is not positional. The six\n // action words win and anything else is an agent — the same rule a slash command uses.\n const asked = readAction(manifestPath, positionals[1])\n return await configCommand({\n action: asked.action,\n ...(asked.ref === undefined ? {} : { ref: asked.ref }),\n ...(positionals[2] === undefined ? {} : { name: positionals[2] }),\n ...(positionals[3] === undefined ? {} : { value: positionals[3] }),\n ...(flags.str(\"channel\") === undefined\n ? {}\n : { channel: flags.str(\"channel\") as string }),\n remove: flags.bool(\"remove\"),\n yes: flags.bool(\"yes\"),\n ...(flags.str(\"store\") === undefined\n ? {}\n : { store: flags.str(\"store\") as string }),\n })\n }\n\n case \"validate\":\n return await validateCommand({ manifestPath: resolved(), json: flags.bool(\"json\") })\n\n case \"workspace\":\n return workspaceCommand({\n manifestPath: resolved(),\n json: flags.bool(\"json\"),\n strict: flags.bool(\"strict\"),\n })\n\n case \"soul\": {\n const out = flags.str(\"out\")\n return soulCommand({\n // For this command the first positional is the action, not a manifest.\n action: manifestPath,\n file: positionals[1] as string,\n ...(out === undefined ? {} : { out }),\n })\n }\n\n case \"skills\": {\n // Bare `skills` is the catalogue. Checked before the manifest is resolved, because browsing\n // is not about an agent — the agent is chosen on the second screen.\n if (positionals.length === 0) {\n return await browseCommand({\n plain: flags.bool(\"plain\"),\n json: flags.bool(\"json\"),\n })\n }\n // Positional 0 is the action, so the manifest is positional 1 — the same shape `soul` uses\n // and the reason `resolved()` is not called here.\n const skill = positionals[2]\n return skillsCommand({\n action: manifestPath,\n manifestPath: resolveAgentRef(positionals[1] ?? \"\"),\n ...(skill === undefined ? {} : { name: skill }),\n json: flags.bool(\"json\"),\n strict: flags.bool(\"strict\"),\n })\n }\n\n case \"sources\": {\n // Positional 0 is the action and there is no manifest, so `resolveAgentRef` never runs —\n // this command answers about the machine, not about an agent.\n const path = flags.str(\"path\")\n const ref = flags.str(\"ref\")\n return await sourcesCommand({\n action: manifestPath,\n rest: positionals.slice(1),\n ...(path === undefined ? {} : { path }),\n ...(ref === undefined ? {} : { ref }),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"plugins\":\n return await pluginsCommand({\n manifestPath: resolveAgentRef(positionals[0] ?? \"\"),\n json: flags.bool(\"json\"),\n })\n\n case \"agents\":\n return await agentsCommand({\n manifestPaths: positionals.map((ref) => resolveAgentRef(ref)),\n json: flags.bool(\"json\"),\n })\n\n case \"serve\": {\n const port = flags.num(\"port\")\n const host = flags.str(\"host\")\n const store = flags.str(\"store\")\n return await serveCommand({\n manifestPaths: positionals.map((ref) => resolveAgentRef(ref)),\n ...(port === undefined ? {} : { port }),\n ...(host === undefined ? {} : { host }),\n ...(store === undefined ? {} : { store }),\n claim: flags.bool(\"claim\"),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"keys\":\n return await keysCommand({ noEnhancedKeys: flags.bool(\"no-enhanced-keys\") })\n\n case \"terminal-setup\":\n return await terminalSetupCommand({\n dryRun: flags.bool(\"dry-run\"),\n yes: flags.bool(\"yes\"),\n json: flags.bool(\"json\"),\n confirm: askYesNo,\n })\n\n case \"remove\":\n return await removeCommand({\n // A bare ref, never `resolved()`: removal is about a sandbox directory, and a resolved\n // manifest path would make `remove ./anything` look supported. `remove.ts` refuses a path.\n ...(manifestPath === undefined ? {} : { ref: manifestPath }),\n dryRun: flags.bool(\"dry-run\"),\n filesOnly: flags.bool(\"files-only\"),\n prune: flags.bool(\"prune\"),\n all: flags.bool(\"all\"),\n yes: flags.bool(\"yes\"),\n json: flags.bool(\"json\"),\n ...(flags.str(\"store\") === undefined\n ? {}\n : { store: flags.str(\"store\") as string }),\n confirm: askExactly,\n })\n\n case \"stop\": {\n const reason = flags.str(\"reason\")\n return await stopCommand({\n // Optional on purpose: bare `stop` is the whole host, and naming an agent is a\n // different command rather than the same one with a filter — see stop.ts.\n ...(manifestPath === undefined ? {} : { manifestPath: resolved() }),\n dryRun: flags.bool(\"dry-run\"),\n ...(reason === undefined ? {} : { reason }),\n ...(flags.str(\"store\") === undefined\n ? {}\n : { store: flags.str(\"store\") as string }),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"start\":\n return await startCommand({\n manifestPath: resolved(),\n ...(flags.str(\"store\") === undefined\n ? {}\n : { store: flags.str(\"store\") as string }),\n json: flags.bool(\"json\"),\n })\n\n case \"web\": {\n const { webCommand } = await import(\"#web\")\n return await webCommand({\n // The action is positional 0 and the agent positional 1 — the `daemon install\n // <agent>` shape, which `manifestIndex` already reads off this spec, so the parser\n // and the help needed no change for a nested verb.\n action: manifestPath as \"run\" | \"open\" | \"url\" | undefined,\n ...(positionals[1] === undefined\n ? {}\n : { manifestPath: resolveAgentRef(positionals[1]) }),\n noOpen: flags.bool(\"no-open\"),\n ...(flags.str(\"store\") === undefined\n ? {}\n : { store: flags.str(\"store\") as string }),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"credential\": {\n const { credentialCommand } = await import(\"#credential\")\n return await credentialCommand({\n // Action at positional 0 and the id at 1 — the `web run <agent>` shape, which\n // `manifestIndex` already reads off the spec, so the parser needed no change.\n action: manifestPath ?? \"\",\n ...(positionals[1] === undefined ? {} : { keyId: positionals[1] }),\n ...(flags.str(\"label\") === undefined\n ? {}\n : { label: flags.str(\"label\") as string }),\n ...(flags.str(\"agents\") === undefined\n ? {}\n : { agents: flags.str(\"agents\") as string }),\n ...(flags.str(\"sessions\") === undefined\n ? {}\n : { sessions: flags.str(\"sessions\") as string }),\n ...(flags.str(\"can\") === undefined ? {} : { can: flags.str(\"can\") as string }),\n ...(flags.str(\"expires\") === undefined\n ? {}\n : { expires: flags.str(\"expires\") as string }),\n ...(flags.str(\"store\") === undefined\n ? {}\n : { store: flags.str(\"store\") as string }),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"daemon\": {\n const lines = flags.num(\"lines\")\n return await daemonCommand({\n // As for `soul`, the first positional is the action rather than a manifest — so\n // `resolved()` must not run here. The agent is positional 1, and it is optional:\n // bare `daemon status` reports on every installed agent.\n action: manifestPath,\n ...(positionals[1] === undefined\n ? {}\n : { manifestPath: resolveAgentRef(positionals[1]) }),\n ...(lines === undefined ? {} : { lines }),\n follow: flags.bool(\"follow\"),\n truncate: flags.bool(\"truncate\"),\n dryRun: flags.bool(\"dry-run\"),\n ...(flags.str(\"store\") === undefined\n ? {}\n : { store: flags.str(\"store\") as string }),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"model\": {\n const price = flags.num(\"price\")\n return await modelCommand({\n manifestPath: resolveAgentRef(positionals[1] as string),\n window: flags.bool(\"window\"),\n ...(price === undefined ? {} : { price }),\n write: flags.bool(\"write\"),\n yes: flags.bool(\"yes\"),\n json: flags.bool(\"json\"),\n })\n }\n\n case \"tools\":\n return await toolsCommand({\n manifestPath: resolved(),\n warm: flags.bool(\"warm\"),\n json: flags.bool(\"json\"),\n })\n\n default:\n // Unreachable: `parse` refuses an unknown command with a suggestion. Present so that\n // adding a command to lib/commands.ts without wiring it fails loudly rather than\n // silently doing nothing and exiting 0.\n throw new HarnessError({\n code: \"cli_command_unwired\",\n message: `Command \"${command.name}\" is declared but not wired up.`,\n hint: \"Add a case for it in src/index.ts.\",\n })\n }\n}\n\n// Before anything opens a store, which is what makes Node emit its `node:sqlite` experimental\n// warning into the middle of a command's output. See `lib/warnings.ts` for what is filtered and why\n// the list is specific rather than \"every ExperimentalWarning\".\nquietAcceptedWarnings()\ninstallGuards()\n\n// One way out for every route, so the terminal is restored and buffered output drains before the\n// process ends — and then the process actually ends.\n//\n// `finish` alone was the bug: it sets `process.exitCode` and lets the event loop empty, which assumes\n// the loop can empty. A runtime leaves a keep-alive socket to the tool provider in Node's global\n// `fetch` pool, so it does not — measured at 180 seconds still alive after `/exit`, and the `tools`\n// command killed at 30. `lib/exit.ts` carries the numbers.\nawait dispatch(process.argv.slice(2))\n .catch(report)\n .then((code) => finishNow(code))\n"
|
|
44
44
|
],
|
|
45
|
-
"mappings": ";snCAgBA,eAAsB,EAAa,CAAC,EAAyC,CACzE,IAAM,EAAU,MAAM,EAAQ,OAAO,CACjC,OAAQ,CAAC,GAAG,EAAQ,aAAa,EACjC,cAAe,EACf,eAAgB,EAChB,aAAc,EAAa,EAC3B,SAAU,EACV,IAAK,EAAW,EAAQ,aAAa,EAGrC,MAAO,EAAU,EACjB,MAAO,EACX,CAAC,EACD,EAAO,IAAM,EAAQ,KAAK,UAAU,CAAC,EAErC,IAAM,EAAY,EAAQ,KAAK,EAAE,IAAI,CAAC,IAAU,EAAM,SAAS,CAAC,EAK1D,EAAU,IAAI,IACpB,QAAW,KAAS,MAAM,EAAQ,MAAM,OAAO,IAAI,EAAG,CAClD,GAAI,EAAM,YAAc,EAAQ,WAAa,CAAC,EAAa,EAAM,GAAG,EAAG,SACvE,IAAM,EAAQ,KAAK,IAAI,EAAI,KAAK,MAAM,EAAM,SAAS,EACrD,EAAQ,IACJ,EAAM,QACN,aAAa,EAAM,cAAc,EAAM,MACnC,OAAO,SAAS,CAAK,EAAI,SAAS,GAAS,CAAK,IAAM,IAE9D,EAGJ,GAAI,EAAQ,OAAS,GAajB,OAZA,QAAQ,OAAO,MACX,GAAG,KAAK,UACJ,CACI,OAAQ,EAAU,IAAI,CAAC,KAAW,IAC3B,EACH,QAAS,EAAQ,IAAI,EAAM,EAAE,GAAK,IACtC,EAAE,CACN,EACA,KACA,CACJ;AAAA,CACJ,EACO,EAKX,IAAM,EAAc,EAAU,IAAI,CAAC,KAAW,CAC1C,MAAO,EAAM,GACb,MAAO,GAAG,EAAM,UAAU,OA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