dispach 0.1.1 → 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.
Files changed (78) hide show
  1. package/README.md +72 -13
  2. package/dist/{App-5a35bjkt.js → App-b1yrwrcq.js} +6 -6
  3. package/dist/{App-5a35bjkt.js.map → App-b1yrwrcq.js.map} +1 -1
  4. package/dist/{ConfigEditor-7nnc2ke6.js → ConfigEditor-n8hdw6r7.js} +2 -2
  5. package/dist/{KeyProbe-kbz0j6sm.js → KeyProbe-9jjeze5r.js} +2 -2
  6. package/dist/{Picker-2zjjt17a.js → Picker-hfeh1g6m.js} +3 -3
  7. package/dist/{Picker-2zjjt17a.js.map → Picker-hfeh1g6m.js.map} +1 -1
  8. package/dist/{SessionPicker-fyyvxy40.js → SessionPicker-zyqkg4dn.js} +3 -3
  9. package/dist/{SessionPicker-fyyvxy40.js.map → SessionPicker-zyqkg4dn.js.map} +1 -1
  10. package/dist/{SkillBrowser-x7r51zy0.js → SkillBrowser-3qdp8080.js} +3 -3
  11. package/dist/{SkillBrowser-x7r51zy0.js.map → SkillBrowser-3qdp8080.js.map} +1 -1
  12. package/dist/{WizardApp-v0dghsyw.js → WizardApp-vzpbydy3.js} +3 -3
  13. package/dist/{WizardApp-v0dghsyw.js.map → WizardApp-vzpbydy3.js.map} +1 -1
  14. package/dist/client.js +10 -10
  15. package/dist/client.js.map +4 -4
  16. package/dist/{config-9cv76yrk.js → config-g7za9x13.js} +5 -5
  17. package/dist/{config-9cv76yrk.js.map → config-g7za9x13.js.map} +1 -1
  18. package/dist/credential-npr6z8c8.js +19 -0
  19. package/dist/{credential-yxqj8x1f.js.map → credential-npr6z8c8.js.map} +2 -2
  20. package/dist/{index-zked16y4.js → index-02dn6m2j.js} +2 -2
  21. package/dist/{index-a4xqgdrm.js → index-0d93hyfc.js} +2 -2
  22. package/dist/{index-5t6wahx8.js → index-1c5113t4.js} +26 -26
  23. package/dist/index-1c5113t4.js.map +12 -0
  24. package/dist/{index-zxh0ntgf.js → index-258d8bzg.js} +2 -2
  25. package/dist/{index-nvm5hwe4.js → index-6p999cx4.js} +5 -5
  26. package/dist/{index-nvm5hwe4.js.map → index-6p999cx4.js.map} +1 -1
  27. package/dist/{index-73jfw4jp.js → index-6q4wf8e3.js} +2 -2
  28. package/dist/{index-r3wwvqzb.js → index-fecm8xe7.js} +16 -16
  29. package/dist/{index-r3wwvqzb.js.map → index-fecm8xe7.js.map} +2 -2
  30. package/dist/{index-83bqtze0.js → index-ff514z3y.js} +5 -5
  31. package/dist/{index-83bqtze0.js.map → index-ff514z3y.js.map} +1 -1
  32. package/dist/{index-17an0jqq.js → index-h9mw7b9d.js} +2 -2
  33. package/dist/{index-5x4dn0gg.js → index-hwpvhaza.js} +2 -2
  34. package/dist/{index-e0j1jafd.js → index-j55s3ehk.js} +5 -5
  35. package/dist/{index-e0j1jafd.js.map → index-j55s3ehk.js.map} +1 -1
  36. package/dist/{index-000rxxy3.js → index-mtn0g9vc.js} +4 -4
  37. package/dist/{index-000rxxy3.js.map → index-mtn0g9vc.js.map} +1 -1
  38. package/dist/{index-dwyr2kdm.js → index-qdbq8crg.js} +4 -4
  39. package/dist/{index-dwyr2kdm.js.map → index-qdbq8crg.js.map} +1 -1
  40. package/dist/{index-ez2mb28y.js → index-s9mbq7h6.js} +4 -4
  41. package/dist/{index-ez2mb28y.js.map → index-s9mbq7h6.js.map} +1 -1
  42. package/dist/{index-0b1hdwnm.js → index-tf71ap9v.js} +2 -2
  43. package/dist/index-ttwyrdjs.js +427 -0
  44. package/dist/index-ttwyrdjs.js.map +11 -0
  45. package/dist/{index-7z4sw2dm.js → index-tv4yv7d2.js} +162 -162
  46. package/dist/{index-7z4sw2dm.js.map → index-tv4yv7d2.js.map} +8 -8
  47. package/dist/{index-d69d6pkm.js → index-ty24n0jh.js} +35 -35
  48. package/dist/{index-d69d6pkm.js.map → index-ty24n0jh.js.map} +1 -1
  49. package/dist/{index-2wmsmcbr.js → index-vgc3y3rm.js} +4 -4
  50. package/dist/{index-2wmsmcbr.js.map → index-vgc3y3rm.js.map} +1 -1
  51. package/dist/index-whaw4b18.js +6 -0
  52. package/dist/index-whaw4b18.js.map +10 -0
  53. package/dist/index.js +50 -50
  54. package/dist/index.js.map +3 -3
  55. package/dist/lib/commands.d.ts.map +1 -1
  56. package/dist/lib/init-flow.d.ts +17 -4
  57. package/dist/lib/init-flow.d.ts.map +1 -1
  58. package/dist/lib/provision.d.ts.map +1 -1
  59. package/dist/{web-x77y8w3v.js → web-vkb16r62.js} +4 -4
  60. package/dist/{web-x77y8w3v.js.map → web-vkb16r62.js.map} +1 -1
  61. package/dist/wire.js +10 -10
  62. package/dist/wire.js.map +4 -4
  63. package/package.json +1 -1
  64. package/dist/credential-yxqj8x1f.js +0 -19
  65. package/dist/index-5t6wahx8.js.map +0 -12
  66. package/dist/index-9bkd0fdj.js +0 -427
  67. package/dist/index-9bkd0fdj.js.map +0 -11
  68. package/dist/index-xf178c4m.js +0 -6
  69. package/dist/index-xf178c4m.js.map +0 -10
  70. /package/dist/{ConfigEditor-7nnc2ke6.js.map → ConfigEditor-n8hdw6r7.js.map} +0 -0
  71. /package/dist/{KeyProbe-kbz0j6sm.js.map → KeyProbe-9jjeze5r.js.map} +0 -0
  72. /package/dist/{index-zked16y4.js.map → index-02dn6m2j.js.map} +0 -0
  73. /package/dist/{index-a4xqgdrm.js.map → index-0d93hyfc.js.map} +0 -0
  74. /package/dist/{index-zxh0ntgf.js.map → index-258d8bzg.js.map} +0 -0
  75. /package/dist/{index-73jfw4jp.js.map → index-6q4wf8e3.js.map} +0 -0
  76. /package/dist/{index-17an0jqq.js.map → index-h9mw7b9d.js.map} +0 -0
  77. /package/dist/{index-5x4dn0gg.js.map → index-hwpvhaza.js.map} +0 -0
  78. /package/dist/{index-0b1hdwnm.js.map → index-tf71ap9v.js.map} +0 -0
@@ -5,6 +5,6 @@
5
5
  "/**\n * `config` — a person changing an agent's settings without hand-editing YAML.\n *\n * ## Why this exists\n *\n * `config_read`/`config_set` shipped in Phase 3.6 and are the *agent's*. There was no equivalent for a\n * person, so the routes were editing `agent.yaml` by hand, re-running `init` into a fresh directory, or\n * asking the agent (which needs `config_set` pinned, a matching allow rule, and a restart).\n *\n * The inversion is the argument for the command. Decision 11.29 reserves `allowFrom`, `server.host`,\n * `server.tokenEnv` and `writeRoots` **for the person**, floored so the agent cannot widen its own\n * reach — and that is right. But the only editor ever built was the agent's, so the fields designated\n * as the person's had the worst ergonomics in the system: unvalidated YAML that fails at the next boot.\n * It compounds with `.env` being protected *precisely* so the agent cannot supply its own secrets,\n * which left the one actor who can fill in `MODEL_API_KEY` with no tool for doing it.\n *\n * ## What this does not own\n *\n * The write. `editManifest` places, validates against the real schema, checks that the providers still\n * resolve, and only then writes — one writer for every surface, because the three that existed made\n * the guarantee depend on which caller you happened to be.\n *\n * ## Why nothing here is floored\n *\n * The agent's floor exists because an agent that could widen its own inbound gate could be *talked\n * into* it by the message it is reading. A person at a terminal is not that threat. Two edits are\n * confirmed rather than refused — `tools.policy.deny` and `onMutate: allow` — and `lib/config-view.ts`\n * decides which, so \"what needs a confirmation\" is assertable without performing one.\n */\n\nimport { readFileSync } from \"node:fs\"\nimport {\n HarnessError,\n manifestDocument,\n manifestValueAt,\n nearest,\n parseSettingValue,\n processAlive,\n readManifestHeader,\n type Setting,\n SqliteStore,\n settingByPath,\n} from \"@dispach/core\"\nimport { applyAllow, applySecret, applySet, checkedHandle } from \"#lib/config-apply\"\nimport type { EditorRow } from \"#lib/config-editor\"\nimport { agentEnv } from \"#lib/config-env\"\nimport { applyEditorRow, currentValues, editorRowsFor } from \"#lib/config-rows\"\nimport {\n confirmationFor,\n envNeeds,\n renderChange,\n renderOne,\n renderSettings,\n settablePaths,\n showValue,\n unmet,\n} from \"#lib/config-view\"\nimport { askSecret, askYesNo } from \"#lib/confirm\"\nimport {\n ENTER_ALT_SCREEN,\n EXIT_FAILURE,\n EXIT_OK,\n FALLBACK_COLUMNS,\n MAX_SCREEN_ROWS,\n} from \"#lib/const\"\nimport { flushOutput, markAltScreen, onExit, restoreTerminal } from \"#lib/exit\"\nimport { negotiateKeyboard } from \"#lib/keyboard\"\nimport { resolveModeFromProcess } from \"#lib/output\"\nimport { bullet, keyValue } from \"#lib/render\"\nimport { resolveAgentRef, storePath } from \"#lib/sandbox\"\nimport { screenColumns } from \"#lib/screen\"\n\nexport interface ConfigCommandOptions {\n /** `list` | `get` | `set` | `env` | `allow`. */\n readonly action?: string\n /** A path or a sandbox agent name. */\n readonly ref?: string\n /** A setting path, an env variable name, or a handle, depending on the action. */\n readonly name?: string\n readonly value?: string\n readonly channel?: string\n readonly remove?: boolean\n readonly yes?: boolean\n readonly store?: string\n /** Injected by tests. */\n readonly confirm?: (question: string) => Promise<boolean>\n readonly secret?: (question: string) => Promise<string | undefined>\n /**\n * The `<ENVPREFIX>HOME` override that relocates the whole sandbox. **Not** the manifest\n * environment: that one is `ambientEnv`, computed from the resolved path, and answers \"is this\n * variable set\". Two env concepts in one options object want two names — conflating them has\n * already cost a round, where `skills install` consulted a different registry from `init`.\n */\n readonly sandboxEnv?: Readonly<Record<string, string | undefined>>\n readonly out?: (text: string) => void\n}\n\nconst ACTIONS = [\"list\", \"get\", \"set\", \"env\", \"allow\", \"edit\"] as const\n\n/**\n * Read the action and the agent out of the positionals, allowing `config <agent>` with no action.\n *\n * The editor is what most people want from this command, so typing its name and an agent has to work.\n * Disambiguated the way this repo already does it twice over: a slash command takes arguments only\n * after a token that is *exactly* a known command, and `resolveAgentRef` lets the filesystem win with a\n * note on genuine ambiguity. Here the six action words win, and anything else is an agent.\n *\n * The collision is an agent literally named after an action, and it gets the note rather than silence —\n * running the wrong thing quietly is the failure worth avoiding, and it does not look wrong in output.\n */\nexport function readAction(\n first: string | undefined,\n second: string | undefined,\n warn: (line: string) => void = (line) => process.stderr.write(line),\n): { readonly action: string; readonly ref: string | undefined } {\n const given = (first ?? \"\").trim()\n if (given === \"\") return { action: \"edit\", ref: undefined }\n if (!ACTIONS.includes(given as (typeof ACTIONS)[number])) {\n return { action: \"edit\", ref: given }\n }\n if (second !== undefined && ACTIONS.includes(second as (typeof ACTIONS)[number])) {\n // Both words are action names, so one of them is an agent and only the order says which. The\n // first wins, and the note is what stops a silently-wrong run — the same choice\n // `resolveAgentRef` makes for a bare name shadowed by a directory.\n warn(`note: reading \"${given}\" as the action and \"${second}\" as the agent\\n`)\n }\n if (second === undefined && given !== \"list\") {\n // A known action word with nothing after it. `config edit` alone is the editor with no agent,\n // which fails later with the usual missing-manifest error; anything else is ambiguous only if an\n // agent has that name, and `resolveAgentRef` is what finds out.\n return { action: given, ref: undefined }\n }\n return { action: given, ref: second }\n}\n\nexport async function configCommand(options: ConfigCommandOptions): Promise<number> {\n const out = options.out ?? ((text: string) => process.stdout.write(text))\n const action = options.action ?? \"\"\n if (!ACTIONS.includes(action as (typeof ACTIONS)[number])) {\n const suggestion = nearest(action, [...ACTIONS])\n throw new HarnessError({\n code: \"cli_config_action_unknown\",\n message: `\"${action}\" is not something config does.`,\n hint: `One of: ${ACTIONS.join(\", \")}.${\n suggestion === undefined ? \"\" : ` Did you mean ${suggestion}?`\n }`,\n })\n }\n\n const manifestPath = resolveAgentRef(options.ref ?? \"\", options.sandboxEnv)\n\n switch (action) {\n case \"list\": {\n out(`${renderSettings(currentValues(manifestPath), manifestPath)}\\n`)\n // What is currently missing belongs here rather than on every `set`: this is the command\n // whose job is the overview, and a note repeated on unrelated edits is one nobody reads.\n const missing = unmet(\n envNeeds(manifestDocument(readFileSync(manifestPath, \"utf8\"))),\n agentEnv(manifestPath),\n )\n for (const need of missing) {\n out(`\\n${bullet(`${need.name} is not set — ${need.why}`)}\\n`)\n out(`${bullet(`\\`config env <agent> ${need.name}\\` fills it in`)}\\n`)\n }\n return EXIT_OK\n }\n case \"get\":\n return get(manifestPath, options, out)\n case \"set\":\n return await set(manifestPath, options, out)\n case \"env\":\n return await env(manifestPath, options, out)\n case \"edit\":\n return await edit(manifestPath, options, out)\n default:\n return await allow(manifestPath, options, out)\n }\n}\n\nfunction get(\n manifestPath: string,\n options: ConfigCommandOptions,\n out: (text: string) => void,\n): number {\n const path = (options.name ?? \"\").trim()\n const setting = requireSetting(path)\n const row = currentValues(manifestPath).find((entry) => entry.setting.path === setting.path)\n out(`${renderOne(setting, row?.value)}\\n`)\n return EXIT_OK\n}\n\nfunction requireSetting(path: string): Setting {\n const found = settingByPath(path)\n if (found !== undefined) return found\n const suggestion = nearest(path, [...settablePaths()])\n throw new HarnessError({\n code: \"cli_config_path_unknown\",\n message: `\"${path}\" is not a setting.`,\n hint: `\\`config list <agent>\\` shows every one with its current value.${\n suggestion === undefined ? \"\" : ` Did you mean ${suggestion}?`\n }`,\n field: \"path\",\n })\n}\n\nasync function set(\n manifestPath: string,\n options: ConfigCommandOptions,\n out: (text: string) => void,\n): Promise<number> {\n const path = (options.name ?? \"\").trim()\n const setting = requireSetting(path)\n\n if (setting.via !== undefined) {\n throw new HarnessError({\n code: \"cli_config_needs_action\",\n message: `${setting.path} is not set by a dotted path.`,\n hint: `Use \\`${setting.via}\\` — it lives inside a list entry, and it gets its value checked against the service that issues it rather than written verbatim.`,\n field: \"path\",\n })\n }\n if (options.value === undefined) {\n throw new HarnessError({\n code: \"cli_config_value_missing\",\n message: `No value given for ${path}.`,\n hint: `A bare word, a number, a list as [\"a\", \"b\"], or a map as {k: v}. \\`config get <agent> ${path}\\` shows what it is now.`,\n field: \"value\",\n })\n }\n\n const value = parseSettingValue(options.value)\n\n // The confirmation, before anything is read or written. It is not a floor — these edits are the\n // person's to make — but both of them stop a check from running, and an edit whose whole effect is\n // invisible until something exploits it is worth one sentence and a keypress.\n const warning = confirmationFor(setting, value)\n if (warning !== undefined && options.yes !== true) {\n out(`${bullet(warning)}\\n`)\n const ask = options.confirm ?? askYesNo\n if (!(await ask(`Change ${setting.path} anyway?`))) {\n out(`${keyValue([{ label: \"unchanged\", value: setting.path }])}\\n`)\n return EXIT_OK\n }\n }\n\n // The agent's own layered environment, not this process's. `ambientEnv` alone does not do it: it\n // demotes a colliding cwd variable and never adds the agent's own file, so a token sitting beside\n // the manifest read as unset.\n const ambient = agentEnv(manifestPath)\n const before = unmet(\n envNeeds(manifestDocument(readFileSync(manifestPath, \"utf8\"))),\n ambient,\n ).map((need) => need.name)\n\n // `applySet` owns the write, so the editor and this command cannot validate a value differently.\n const result = await applySet(manifestPath, path, options.value)\n\n // Newly required only. Computed either side of the edit rather than guessed from the value, so\n // `server.enabled true` reports the token it has just made load-bearing and `limits.maxSteps 9`\n // reports nothing — which a live run got wrong in the other direction, warning that an agent with\n // a disabled server \"will refuse to start\".\n const pending = unmet(\n envNeeds(manifestDocument(readFileSync(manifestPath, \"utf8\"))),\n ambient,\n ).filter((need) => !before.includes(need.name))\n\n const held = await running(manifestPath, options)\n out(\n `${renderChange({\n path,\n before: result.before,\n after: value,\n file: manifestPath,\n reflowed: result.reflowed,\n ...(held === undefined ? {} : { running: held }),\n pending,\n restartHint: restartHint(held?.mode),\n })}\\n`,\n )\n return EXIT_OK\n}\n\n/**\n * How this agent comes back, phrased for how it is currently held.\n *\n * All three `RuntimeMode` values, because the generic sentence is useless for two of them. `embedded` is\n * the case that matters most and is easiest to miss: it is *this* session, so the answer is one word the\n * person can type — and a live run reported `pid 90050, embedded` under \"it is started again\", which is\n * true and gives them nothing.\n */\nfunction restartHint(mode: string | undefined): string {\n if (mode === \"daemon\") return \"`daemon restart <agent>`\"\n if (mode === \"embedded\") return \"`/restart` in this session\"\n if (mode === \"terminal\") return \"that process being started again\"\n return \"it is started again\"\n}\n\n/**\n * A live process holding this agent, or `undefined`.\n *\n * Never a refusal, only a note. Fixing a misconfiguration *while it is running and broken* is the main\n * thing this command is for, so refusing in that state would block the case it exists to serve.\n *\n * Liveness is re-checked rather than trusted: a lease row is a claim, and a boot that failed after\n * claiming leaves a row seconds old with no process under it — which once blocked every retry for\n * ninety seconds while naming a pid that no longer existed.\n */\nasync function running(\n manifestPath: string,\n options: ConfigCommandOptions,\n): Promise<{ readonly pid: number; readonly mode: string } | undefined> {\n let agentId: string | undefined\n try {\n agentId = readManifestHeader(manifestPath).id\n } catch {\n return undefined\n }\n if (agentId === undefined) return undefined\n\n try {\n const store = await SqliteStore.open({\n path: options.store ?? storePath(options.sandboxEnv),\n })\n try {\n for (const lease of await store.leases.all()) {\n if (lease.agentId !== agentId) continue\n if (!processAlive(lease.pid)) continue\n return { pid: lease.pid, mode: lease.mode }\n }\n } finally {\n await store.close()\n }\n } catch {\n // A missing or unreadable store is not a reason to refuse a manifest edit. The note is a\n // courtesy; the write is the command.\n return undefined\n }\n return undefined\n}\n\n/**\n * Put a secret in the `.env` beside the manifest.\n *\n * The value is prompted and never taken from an argument: an argument lands in shell history and in\n * `ps`, readable by every local process for the lifetime of the call. Not a TTY refuses rather than\n * reading a pipe, so a CI run is told nothing was written instead of a secret arriving from a source\n * the caller did not audit.\n *\n * Written 0600 whichever way the file arrived. Under a service manager this file is the *only* path\n * credentials take — launchd hands a job almost no environment and a plist carries none on purpose —\n * so tightening it is right even when this command did not create it.\n */\nasync function env(\n manifestPath: string,\n options: ConfigCommandOptions,\n out: (text: string) => void,\n): Promise<number> {\n const name = (options.name ?? \"\").trim()\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new HarnessError({\n code: \"cli_config_env_name_invalid\",\n message: `\"${name}\" is not an environment variable name.`,\n hint: \"Letters, digits and underscores, not starting with a digit — MODEL_API_KEY, TELEGRAM_BOT_TOKEN. `config list <agent>` shows which ones this agent names.\",\n field: \"name\",\n })\n }\n\n // Statically imported, not `await import`. A module reached both ways makes `bun build\n // --splitting` emit its exports twice and the binary refuses to parse — and `bun test` sails\n // through it, because tests import source and the failure is in the bundle. `confirm.ts` pulls in\n // only `node:readline`, so there is nothing to defer.\n const ask = options.secret ?? askSecret\n const value = await ask(`value for ${name} (not echoed):`)\n if (value === undefined) {\n throw new HarnessError({\n code: \"cli_config_env_no_value\",\n message: `Nothing was written for ${name}.`,\n hint: \"A secret is read from a prompt, never from an argument or a pipe — an argument is visible in `ps` and in shell history. Run this at a terminal, or edit the .env beside the manifest yourself.\",\n })\n }\n if (value === \"\") {\n throw new HarnessError({\n code: \"cli_config_env_empty\",\n message: `An empty value for ${name} would not start the agent.`,\n hint: \"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.\",\n })\n }\n\n // The write itself is `applySecret`, which the editor calls too — two callers deciding separately\n // whether to tighten the file's mode is the same class of split as two manifest writers.\n const applied = applySecret(manifestPath, name, value)\n out(`${keyValue([{ label: \"set\", value: applied.note }])}\\n`)\n out(`${bullet(\"takes effect the next time the agent starts\")}\\n`)\n return EXIT_OK\n}\n\n/**\n * Add or remove a handle on a channel's `allowFrom`.\n *\n * Its own action rather than a `config set` path for two reasons. The source editor matches `key:` at\n * an indent and cannot index a sequence, so the field is not addressable — and rewriting the whole\n * `channels` list to change one handle is the dead end this command exists to remove. The second is\n * better: a handle can be *checked against the service that issues it*, and an impossible one is\n * otherwise a bot that is connected, healthy and silently refusing the one person it was set up for.\n */\nasync function allow(\n manifestPath: string,\n options: ConfigCommandOptions,\n out: (text: string) => void,\n): Promise<number> {\n const channels = manifestValueAt(readFileSync(manifestPath, \"utf8\"), [\"channels\"])\n if (!Array.isArray(channels) || channels.length === 0) {\n throw new HarnessError({\n code: \"cli_config_no_channels\",\n message: \"This agent has no channels, so there is nobody to allow.\",\n hint: \"`config set <agent> channels '[{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]'` declares one first.\",\n })\n }\n\n const entries = channels.filter(\n (entry): entry is Record<string, unknown> =>\n typeof entry === \"object\" && entry !== null && !Array.isArray(entry),\n )\n const ids = entries.map((entry) => String(entry.id ?? \"\")).filter((id) => id !== \"\")\n const wanted = options.channel?.trim()\n if (wanted === undefined && entries.length > 1) {\n throw new HarnessError({\n code: \"cli_config_channel_ambiguous\",\n message: `This agent has ${entries.length} channels, so --channel says which.`,\n hint: `One of: ${ids.join(\", \")}.`,\n field: \"channel\",\n })\n }\n const at =\n wanted === undefined ? 0 : entries.findIndex((entry) => String(entry.id ?? \"\") === wanted)\n if (at === -1) {\n throw new HarnessError({\n code: \"cli_config_channel_unknown\",\n message: `No channel with id \"${wanted}\".`,\n hint: `Declared: ${ids.join(\", \")}.${\n nearest(wanted ?? \"\", ids) === undefined\n ? \"\"\n : ` Did you mean ${nearest(wanted ?? \"\", ids)}?`\n }`,\n field: \"channel\",\n })\n }\n\n const target = entries[at] as Record<string, unknown>\n const handle = checkedHandle(options.name ?? \"\", String(target.type ?? \"\"))\n const current = Array.isArray(target.allowFrom) ? target.allowFrom.map(String) : []\n\n const next =\n options.remove === true\n ? current.filter((entry) => entry !== handle)\n : current.includes(handle)\n ? current\n : [...current, handle]\n\n if (next.length === current.length && options.remove === true) {\n out(\n `${keyValue([\n { label: \"unchanged\", value: `${handle} was not on ${String(target.id)}` },\n ])}\\n`,\n )\n return EXIT_OK\n }\n if (next.length === current.length) {\n // Idempotent on purpose: running it twice is what somebody does when they are not sure it\n // took, and reporting a second write they did not make would be a small lie.\n out(\n `${keyValue([{ label: \"already allowed\", value: `${handle} on ${String(target.id)}` }])}\\n`,\n )\n return EXIT_OK\n }\n\n // `applyAllow` owns the write and the handle check, so the editor cannot validate a handle\n // differently from this command. It takes the whole list, because the whole list is what gets\n // written: one entry's key is not addressable by the source editor.\n const result = await applyAllow(manifestPath, String(target.id ?? \"\"), next)\n const held = await running(manifestPath, options)\n\n out(\n `${keyValue([\n { label: options.remove === true ? \"removed\" : \"allowed\", value: handle },\n { label: \"channel\", value: String(target.id) },\n { label: \"now\", value: showValue(next) },\n { label: \"file\", value: manifestPath },\n ])}\\n`,\n )\n if (result.reflowed) {\n out(`${bullet(\"the file was re-serialised — it is valid, and comments may have moved\")}\\n`)\n }\n if (held !== undefined) {\n out(\n `${bullet(\n `this agent is running (pid ${held.pid}, ${held.mode}) and holds its settings for its lifetime — the change applies after ${restartHint(held.mode)}`,\n )}\\n`,\n )\n }\n return EXIT_OK\n}\n\nexport const CONFIG_EXIT_FAILURE = EXIT_FAILURE\n\n/**\n * The editor, standalone.\n *\n * Alternate screen, because it waits for keys: it takes the terminal and gives it back. A changed flag\n * comes back through `onDone` so the one line printed afterwards can say a restart is needed — printed\n * on the real screen after the restore, because hard rule 8 does not stop applying when a screen closes.\n */\nasync function edit(\n manifestPath: string,\n options: ConfigCommandOptions,\n out: (text: string) => void,\n): Promise<number> {\n // Refused rather than attempted without a terminal. Two things went wrong otherwise, and the second\n // is the serious one: the alternate-screen sequence was written into a *pipe*, and Ink's own \"raw\n // mode is not supported\" error left the command exiting **0** — a failure that reported success,\n // which hard rule 8 exists to prevent. `browse` and `init` already ask this question the same way.\n const decision = resolveModeFromProcess({ plain: false, json: false, oneShot: false })\n if (decision.mode !== \"rich\") {\n throw new HarnessError({\n code: \"cli_config_edit_needs_terminal\",\n message: \"The settings editor needs a terminal.\",\n hint: `Not one here (${decision.because}). \\`config list\\` reads them and \\`config set\\` changes one, both of which work on a pipe.`,\n })\n }\n\n const [{ render }, { createElement }, { ConfigEditor }] = await Promise.all([\n import(\"ink\"),\n import(\"react\"),\n import(\"#components/ConfigEditor\"),\n ])\n\n let changed = false\n let finish: () => void = () => {}\n const closed = new Promise<void>((resolve) => {\n finish = resolve\n })\n\n markAltScreen()\n process.stdout.write(ENTER_ALT_SCREEN)\n\n // No wrapper component: the editor is a *view*, so it owns its own state and its single `useInput`,\n // exactly as `SkillBrowser` and `SessionPicker` do. Holding it here needed `useState` in this file,\n // which is a shared command path — and a static React import there costs ~170-210 ms on every\n // command including `validate --json`, which a boundaries test refuses outright.\n const instance = render(\n createElement(ConfigEditor, {\n rows: editorRowsFor(manifestPath),\n apply: (row: EditorRow, raw: string) => applyEditorRow(manifestPath, row, raw),\n reload: () => editorRowsFor(manifestPath),\n // A pty can report `columns === 0`, which `?? fallback` does not cover — measured, and it\n // once laid a picker's rows out for half the terminal, uniformly, on every row.\n columns: screenColumns(process.stdout.columns, FALLBACK_COLUMNS),\n window: MAX_SCREEN_ROWS,\n onDone: (didChange: boolean) => {\n changed = didChange\n finish()\n },\n }),\n { exitOnCtrlC: false, ...negotiateKeyboard() },\n )\n onExit(() => instance.unmount())\n await closed\n instance.unmount()\n restoreTerminal()\n await flushOutput()\n\n const held = await running(manifestPath, options)\n if (!changed) {\n out(`${keyValue([{ label: \"unchanged\", value: manifestPath }])}\\n`)\n return EXIT_OK\n }\n out(`${keyValue([{ label: \"changed\", value: manifestPath }])}\\n`)\n out(`${bullet(`takes effect after ${restartHint(held?.mode)}`)}\\n`)\n return EXIT_OK\n}\n"
6
6
  ],
7
7
  "mappings": ";idA8BA,uBAAS,gBAmET,IAAM,EAAU,CAAC,OAAQ,MAAO,MAAO,MAAO,QAAS,MAAM,EAatD,SAAS,EAAU,CACtB,EACA,EACA,EAA+B,CAAC,IAAS,QAAQ,OAAO,MAAM,CAAI,EACL,CAC7D,IAAM,GAAS,GAAS,IAAI,KAAK,EACjC,GAAI,IAAU,GAAI,MAAO,CAAE,OAAQ,OAAQ,IAAK,MAAU,EAC1D,GAAI,CAAC,EAAQ,SAAS,CAAiC,EACnD,MAAO,CAAE,OAAQ,OAAQ,IAAK,CAAM,EAExC,GAAI,IAAW,QAAa,EAAQ,SAAS,CAAkC,EAI3E,EAAK,kBAAkB,yBAA6B;AAAA,CAAwB,EAEhF,GAAI,IAAW,QAAa,IAAU,OAIlC,MAAO,CAAE,OAAQ,EAAO,IAAK,MAAU,EAE3C,MAAO,CAAE,OAAQ,EAAO,IAAK,CAAO,EAGxC,eAAsB,EAAa,CAAC,EAAgD,CAChF,IAAM,EAAM,EAAQ,MAAQ,CAAC,IAAiB,QAAQ,OAAO,MAAM,CAAI,GACjE,EAAS,EAAQ,QAAU,GACjC,GAAI,CAAC,EAAQ,SAAS,CAAkC,EAAG,CACvD,IAAM,EAAa,EAAQ,EAAQ,CAAC,GAAG,CAAO,CAAC,EAC/C,MAAM,IAAI,EAAa,CACnB,KAAM,4BACN,QAAS,IAAI,mCACb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AAmB,iBAAkB,MAAM,QAAQ,IAAI,CACjE,cACA,gBACA,oCACX,CAAC,EAEG,EAAU,GACV,EAAqB,IAAM,GACzB,EAAS,IAAI,QAAc,CAAC,IAAY,CAC1C,EAAS,EACZ,EAED,GAAc,EACd,QAAQ,OAAO,MAAM,EAAgB,EAMrC,IAAM,EAAW,EACb,EAAc,EAAc,CACxB,KAAM,GAAc,CAAY,EAChC,MAAO,CAAC,EAAgB,IAAgB,GAAe,EAAc,EAAK,CAAG,EAC7E,OAAQ,IAAM,GAAc,CAAY,EAGxC,QAAS,EAAc,QAAQ,OAAO,QAAS,CAAgB,EAC/D,OAAQ,GACR,OAAQ,CAAC,IAAuB,CAC5B,EAAU,EACV,EAAO,EAEf,CAAC,EACD,CAAE,YAAa,MAAU,EAAkB,CAAE,CACjD,EACA,EAAO,IAAM,EAAS,QAAQ,CAAC,EAC/B,MAAM,EACN,EAAS,QAAQ,EACjB,EAAgB,EAChB,MAAM,GAAY,EAElB,IAAM,EAAO,MAAM,EAAQ,EAAc,CAAO,EAChD,GAAI,CAAC,EAED,OADA,EAAI,GAAG,EAAS,CAAC,CAAE,MAAO,YAAa,MAAO,CAAa,CAAC,CAAC;AAAA,CAAK,EAC3D,EAIX,OAFA,EAAI,GAAG,EAAS,CAAC,CAAE,MAAO,UAAW,MAAO,CAAa,CAAC,CAAC;AAAA,CAAK,EAChE,EAAI,GAAG,EAAO,sBAAsB,EAAY,GAAM,IAAI,GAAG;AAAA,CAAK,EAC3D",
8
- "debugId": "77B7D4100F95487764756E2164756E21",
8
+ "debugId": "A1FEF871B88EA65364756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ import{e,nr}from"./index-tv4yv7d2.js";import"./index-ttwyrdjs.js";import"./index-whaw4b18.js";import{se}from"./index-hwpvhaza.js";import{Pe,Qe,ur,Kt}from"./index-qdbq8crg.js";import"./index-mtn0g9vc.js";function g(n){let t=/^(\d+)\s*(s|m|h|d)?$/.exec(n.trim());if(t===null)throw new se({code:"credential_usage",message:`--expires ${JSON.stringify(n)} is not a duration.`,hint:"Write it as 30s, 15m, 2h or 7d — or as a plain number of seconds."});let i=Number(t[1]);if(i===0)throw new se({code:"credential_usage",message:"--expires 0 would mint a credential that has already expired.",hint:"Leave the flag off for a key that never expires, or give it a real duration like 1h."});let s={s:1,m:60,h:3600,d:86400}[t[2]??"s"]??1;return i*s}function y(n){let t=n.split(",").map((s)=>s.trim().toLowerCase()).filter((s)=>s!==""),i=t.filter((s)=>!nr.includes(s));if(i.length>0)throw new se({code:"credential_usage",message:`--can names ${i.map((s)=>JSON.stringify(s)).join(", ")}, which is not a capability.`,hint:`The four are: ${nr.join(", ")}. read is every GET; chat sends a message, answers an approval and stops a turn; write covers schedules, phase and clearing a session; admin covers credentials, provisioning and start/stop.`});return t}function f(n){return n.split(",").map((t)=>t.trim()).filter((t)=>t!=="")}function l(n){let t=[];if(t.push(n.scope?.agents===void 0?"every agent":n.scope.agents.join(", ")),n.scope?.sessions!==void 0)t.push(`sessions ${n.scope.sessions}`);if(t.push(n.scope?.can===void 0?"all capabilities":n.scope.can.join("+")),n.expiresAt!==void 0)t.push(`until ${n.expiresAt}`);return t.join(" · ")}async function d(n){let t=await Pe(n);if(t===void 0)throw new se({code:"credential_usage",message:"No server is running, so there is nothing to mint a credential on.",hint:`A credential belongs to a server rather than to a file, so this command is an API client. Start one with \`${e.slug} serve\`, or use POST /v1/keys directly against a server you can already reach.`});return{lease:t,manifest:Kt(t.agentId)}}async function v(n){if(n.action==="create")return await h(n);if(n.action==="list")return await p(n);if(n.action==="revoke")return await m(n);throw new se({code:"credential_usage",message:`Unknown action ${JSON.stringify(n.action)}.`,hint:"The actions are create, list and revoke."})}async function h(n){let t=n.label?.trim();if(t===void 0||t==="")throw new se({code:"credential_usage",message:"--label is required.",hint:'A label is the only thing distinguishing two credentials in a listing, and "key 2" is a name nobody can act on when deciding which to revoke.'});let i={...n.agents===void 0?{}:{agents:f(n.agents)},...n.sessions===void 0?{}:{sessions:n.sessions},...n.can===void 0?{}:{can:y(n.can)},...n.expires===void 0?{}:{expiresIn:g(n.expires)}},{lease:s,manifest:o}=await d(n.store),a=await Qe(s,"/v1/keys",{label:t,...Object.keys(i).length===0?{}:{scope:i}},o);if(!a.ok)return c(a,"mint a credential");let r=a.body;if(n.json===!0)return process.stdout.write(`${JSON.stringify(r,null,2)}
3
+ `),0;return process.stdout.write(`${r.secret}
4
+ `),process.stderr.write(` ${r.label} · ${r.keyId}
5
+ `),process.stderr.write(` reaches ${l(r)}
6
+ `),process.stderr.write(` This is the only time the secret is shown. It is stored as a fingerprint and no route returns it.
7
+ `),0}async function p(n){let{lease:t,manifest:i}=await d(n.store),s=await ur(t,"GET","/v1/keys",i);if(!s.ok)return c(s,"list credentials");let o=s.body,a=o.keys??[];if(n.json===!0)return process.stdout.write(`${JSON.stringify(o,null,2)}
8
+ `),0;if(a.length===0)return process.stdout.write(`No credentials. The server token is the only way in.
9
+ `),0;for(let r of a){let u=r.revokedAt===void 0?"live":"revoked";process.stdout.write(`${r.keyId} ${u.padEnd(7)} ${r.label}
10
+ `),process.stdout.write(` reaches ${l(r)}
11
+ `),process.stdout.write(` created ${r.createdAt}${r.lastUsedAt===void 0?" · never used":` · last used ${r.lastUsedAt}`}
12
+ `)}return 0}async function m(n){let t=n.keyId?.trim();if(t===void 0||t==="")throw new se({code:"credential_usage",message:"Which credential?",hint:`\`${e.slug} credential list\` prints the ids. Revoking is permanent — a revoked secret can never be re-presented.`});let{lease:i,manifest:s}=await d(n.store),o=await ur(i,"DELETE",`/v1/keys/${encodeURIComponent(t)}`,s);if(!o.ok)return c(o,"revoke that credential");let a=o.body;if(n.json===!0)return process.stdout.write(`${JSON.stringify(a,null,2)}
13
+ `),0;return process.stdout.write(`revoked ${a.keyId} · ${a.label}
14
+ `),0}function c(n,t){if(process.stderr.write(`Could not ${t}${n.status===0?"":` (${n.status})`}: ${n.detail??"the host did not answer"}
15
+ `),n.hint!==void 0)process.stderr.write(` hint: ${n.hint}
16
+ `);return 1}export{v as credentialCommand};
17
+
18
+ //# debugId=A2FA2E4460FA817D64756E2164756E21
19
+ //# sourceMappingURL=credential-npr6z8c8.js.map
@@ -4,7 +4,7 @@
4
4
  "sourcesContent": [
5
5
  "/**\n * Operator credentials from a terminal: mint one, list them, revoke one.\n *\n * ## Why this is not called `keys`\n *\n * The `keys` command already exists and prints the bytes a terminal sends for a chord — a keyboard\n * diagnostic, nothing to do with credentials. Two unrelated meanings under one verb is the kind of\n * collision that costs somebody a confused minute every time they reach for either, so the new\n * surface takes the word the code and the spec already use for the thing: a **credential**.\n * `token` was the other candidate and loses to `server.tokenEnv`, which is a different credential\n * this command cannot mint or revoke.\n *\n * ## Why it talks to a running server rather than the store\n *\n * A key is a fingerprint in the shared store, so writing one directly would work — and would\n * bypass every check `POST /v1/keys` performs: the label rule, the scope validation, and the\n * refusal of a scope naming an agent that does not exist. That is the *\"a check only one surface\n * performs is a check the two disagree about\"* shape, on the surface where disagreeing means a\n * credential that the API would never have issued. So this is an HTTP client, and it says so when\n * there is no server to talk to.\n */\n\nimport { BRAND, CAPABILITIES, type Capability } from \"@dispach/core\"\nimport { UsageError } from \"#lib/args\"\nimport { anyLiveHost, callHost, manifestForId, postToHost } from \"#lib/lifecycle\"\n\nexport interface CredentialOptions {\n readonly action: string\n readonly keyId?: string\n readonly label?: string\n readonly agents?: string\n readonly sessions?: string\n readonly can?: string\n readonly expires?: string\n readonly json?: boolean\n readonly store?: string\n}\n\n/**\n * `1h`, `30m`, `7d`, `90s`, or plain seconds — into whole seconds.\n *\n * A suffix because \"how long should this credential live\" is a question people answer in hours and\n * days, and `3600` is a number somebody has to compute and can get wrong by a factor of sixty. Bare\n * digits stay accepted, since that is what the wire takes and a script already has the number.\n */\nexport function parseDuration(raw: string): number {\n const match = /^(\\d+)\\s*(s|m|h|d)?$/.exec(raw.trim())\n if (match === null) {\n throw new UsageError({\n code: \"credential_usage\",\n message: `--expires ${JSON.stringify(raw)} is not a duration.`,\n hint: \"Write it as 30s, 15m, 2h or 7d — or as a plain number of seconds.\",\n })\n }\n const value = Number(match[1])\n if (value === 0) {\n throw new UsageError({\n code: \"credential_usage\",\n message: \"--expires 0 would mint a credential that has already expired.\",\n hint: \"Leave the flag off for a key that never expires, or give it a real duration like 1h.\",\n })\n }\n const unit = { s: 1, m: 60, h: 3600, d: 86_400 }[match[2] ?? \"s\"] ?? 1\n return value * unit\n}\n\n/** `chat,read` → the capabilities, refusing anything that is not one rather than dropping it. */\nexport function parseCapabilities(raw: string): readonly Capability[] {\n const names = raw\n .split(\",\")\n .map((entry) => entry.trim().toLowerCase())\n .filter((entry) => entry !== \"\")\n const unknown = names.filter((name) => !(CAPABILITIES as readonly string[]).includes(name))\n if (unknown.length > 0) {\n throw new UsageError({\n code: \"credential_usage\",\n message: `--can names ${unknown.map((name) => JSON.stringify(name)).join(\", \")}, which is not a capability.`,\n hint: `The four are: ${CAPABILITIES.join(\", \")}. read is every GET; chat sends a message, answers an approval and stops a turn; write covers schedules, phase and clearing a session; admin covers credentials, provisioning and start/stop.`,\n })\n }\n // An empty list is *not* silently promoted to \"everything\": `--can \"\"` is a key that may do\n // nothing, which is a coherent thing to ask for and a confusing thing to be given instead.\n return names as readonly Capability[]\n}\n\n/** A comma list into ids, with the empty entries dropped rather than sent as `\"\"`. */\nfunction parseList(raw: string): readonly string[] {\n return raw\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\")\n}\n\ninterface KeyLike {\n readonly keyId: string\n readonly label: string\n readonly createdAt: string\n readonly lastUsedAt?: string\n readonly revokedAt?: string\n readonly expiresAt?: string\n readonly scope?: {\n readonly agents?: readonly string[]\n readonly sessions?: string\n readonly can?: readonly string[]\n }\n}\n\n/**\n * One line describing what a key reaches, for a listing.\n *\n * **Printed back after minting too**, which is the half that matters: a prefix is not a namespace —\n * `team_4` also matches `team_42:x` — so showing what the scope *says* at the moment it is created\n * is the only cheap place to notice that it says something other than what was meant. The same\n * argument `telegramHandle` makes about a username that cannot exist.\n */\nexport function describeScope(key: KeyLike): string {\n const parts: string[] = []\n parts.push(key.scope?.agents === undefined ? \"every agent\" : key.scope.agents.join(\", \"))\n if (key.scope?.sessions !== undefined) parts.push(`sessions ${key.scope.sessions}`)\n parts.push(key.scope?.can === undefined ? \"all capabilities\" : key.scope.can.join(\"+\"))\n if (key.expiresAt !== undefined) parts.push(`until ${key.expiresAt}`)\n return parts.join(\" · \")\n}\n\n/** The host to ask, or a refusal naming why there is none. */\nasync function host(store?: string) {\n const lease = await anyLiveHost(store)\n if (lease === undefined) {\n throw new UsageError({\n code: \"credential_usage\",\n message: \"No server is running, so there is nothing to mint a credential on.\",\n hint: `A credential belongs to a server rather than to a file, so this command is an API client. Start one with \\`${BRAND.slug} serve\\`, or use POST /v1/keys directly against a server you can already reach.`,\n })\n }\n return { lease, manifest: manifestForId(lease.agentId) }\n}\n\nexport async function credentialCommand(options: CredentialOptions): Promise<number> {\n if (options.action === \"create\") return await create(options)\n if (options.action === \"list\") return await list(options)\n if (options.action === \"revoke\") return await revoke(options)\n throw new UsageError({\n code: \"credential_usage\",\n message: `Unknown action ${JSON.stringify(options.action)}.`,\n hint: \"The actions are create, list and revoke.\",\n })\n}\n\nasync function create(options: CredentialOptions): Promise<number> {\n const label = options.label?.trim()\n if (label === undefined || label === \"\") {\n throw new UsageError({\n code: \"credential_usage\",\n message: \"--label is required.\",\n hint: 'A label is the only thing distinguishing two credentials in a listing, and \"key 2\" is a name nobody can act on when deciding which to revoke.',\n })\n }\n const scope = {\n ...(options.agents === undefined ? {} : { agents: parseList(options.agents) }),\n ...(options.sessions === undefined ? {} : { sessions: options.sessions }),\n ...(options.can === undefined ? {} : { can: parseCapabilities(options.can) }),\n ...(options.expires === undefined ? {} : { expiresIn: parseDuration(options.expires) }),\n }\n\n const { lease, manifest } = await host(options.store)\n const reply = await postToHost(\n lease,\n \"/v1/keys\",\n { label, ...(Object.keys(scope).length === 0 ? {} : { scope }) },\n manifest,\n )\n if (!reply.ok) return refused(reply, \"mint a credential\")\n\n const key = reply.body as KeyLike & { readonly secret: string }\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify(key, null, 2)}\\n`)\n return 0\n }\n /**\n * The secret, on its own line, **once**.\n *\n * It is not stored anywhere in a readable form and no route returns it again, so this is the\n * only moment it exists outside the caller's memory. Printed bare rather than inside a sentence\n * so that copying the line copies the credential and nothing else.\n */\n process.stdout.write(`${key.secret}\\n`)\n process.stderr.write(` ${key.label} · ${key.keyId}\\n`)\n process.stderr.write(` reaches ${describeScope(key)}\\n`)\n process.stderr.write(\n \" This is the only time the secret is shown. It is stored as a fingerprint and no route returns it.\\n\",\n )\n return 0\n}\n\nasync function list(options: CredentialOptions): Promise<number> {\n const { lease, manifest } = await host(options.store)\n const reply = await callHost(lease, \"GET\", \"/v1/keys\", manifest)\n if (!reply.ok) return refused(reply, \"list credentials\")\n\n const body = reply.body as { readonly keys?: readonly KeyLike[]; readonly scope?: string }\n const keys = body.keys ?? []\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify(body, null, 2)}\\n`)\n return 0\n }\n if (keys.length === 0) {\n process.stdout.write(\"No credentials. The server token is the only way in.\\n\")\n return 0\n }\n for (const key of keys) {\n // Revoked ones are shown rather than hidden, the same as the API's listing: the row is the\n // only record a credential ever existed, and hiding it makes a revocation unverifiable.\n const state = key.revokedAt === undefined ? \"live\" : \"revoked\"\n process.stdout.write(`${key.keyId} ${state.padEnd(7)} ${key.label}\\n`)\n process.stdout.write(` reaches ${describeScope(key)}\\n`)\n process.stdout.write(\n ` created ${key.createdAt}${key.lastUsedAt === undefined ? \" · never used\" : ` · last used ${key.lastUsedAt}`}\\n`,\n )\n }\n return 0\n}\n\nasync function revoke(options: CredentialOptions): Promise<number> {\n const keyId = options.keyId?.trim()\n if (keyId === undefined || keyId === \"\") {\n throw new UsageError({\n code: \"credential_usage\",\n message: \"Which credential?\",\n hint: `\\`${BRAND.slug} credential list\\` prints the ids. Revoking is permanent — a revoked secret can never be re-presented.`,\n })\n }\n const { lease, manifest } = await host(options.store)\n const reply = await callHost(lease, \"DELETE\", `/v1/keys/${encodeURIComponent(keyId)}`, manifest)\n if (!reply.ok) return refused(reply, \"revoke that credential\")\n const key = reply.body as KeyLike\n if (options.json === true) {\n process.stdout.write(`${JSON.stringify(key, null, 2)}\\n`)\n return 0\n }\n process.stdout.write(`revoked ${key.keyId} · ${key.label}\\n`)\n return 0\n}\n\n/** The server's own words, not a paraphrase — it knows why far better than this command does. */\nfunction refused(reply: { status: number; detail?: string; hint?: string }, what: string): number {\n process.stderr.write(\n `Could not ${what}${reply.status === 0 ? \"\" : ` (${reply.status})`}: ${reply.detail ?? \"the host did not answer\"}\\n`,\n )\n if (reply.hint !== undefined) process.stderr.write(` hint: ${reply.hint}\\n`)\n return 1\n}\n"
6
6
  ],
7
- "mappings": ";+KA6CO,SAAS,CAAa,CAAC,EAAqB,CAC/C,IAAM,EAAQ,uBAAuB,KAAK,EAAI,KAAK,CAAC,EACpD,GAAI,IAAU,KACV,MAAM,IAAI,GAAW,CACjB,KAAM,mBACN,QAAS,aAAa,KAAK,UAAU,CAAG,uBACxC,KAAM,mEACV,CAAC,EAEL,IAAM,EAAQ,OAAO,EAAM,EAAE,EAC7B,GAAI,IAAU,EACV,MAAM,IAAI,GAAW,CACjB,KAAM,mBACN,QAAS,gEACT,KAAM,sFACV,CAAC,EAEL,IAAM,EAAO,CAAE,EAAG,EAAG,EAAG,GAAI,EAAG,KAAM,EAAG,KAAO,EAAE,EAAM,IAAM,MAAQ,EACrE,OAAO,EAAQ,EAIZ,SAAS,CAAiB,CAAC,EAAoC,CAClE,IAAM,EAAQ,EACT,MAAM,GAAG,EACT,IAAI,CAAC,IAAU,EAAM,KAAK,EAAE,YAAY,CAAC,EACzC,OAAO,CAAC,IAAU,IAAU,EAAE,EAC7B,EAAU,EAAM,OAAO,CAAC,IAAS,CAAE,GAAmC,SAAS,CAAI,CAAC,EAC1F,GAAI,EAAQ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
- import{vn,Fo}from"./index-cqqb6gaq.js";import{o,I}from"./index-d4x6yvqh.js";import{ar,kt}from"./index-e0j1jafd.js";var B=1;function wn(t,l){let u=Math.max(1,l-B),r=t.value.split(`
2
+ import{vn,Fo}from"./index-cqqb6gaq.js";import{o,I}from"./index-d4x6yvqh.js";import{ar,kt}from"./index-j55s3ehk.js";var B=1;function wn(t,l){let u=Math.max(1,l-B),r=t.value.split(`
3
3
  `),i=ar(t),d=[],m=0,s=0;for(let[f,n]of r.entries()){let h=vn(n,u),b=f===i.line?Fo(n,i.column):-1,c=-1;if(b>=0){c=h.length-1;for(let[p,e]of h.entries())if(b<=e.to){c=p;break}}for(let[p,e]of h.entries()){if(p===c)m=d.length;d.push({start:s+e.from,end:s+e.to,lead:e.lead,text:e.text,caret:p===c?e.lead+Math.max(0,Math.min(b-e.from,e.to-e.from)):void 0})}s+=[...n].length+1}return{rows:d,caretRow:m}}function k(t,l){let u=[...t.text],r=[];for(let[i,d]of u.entries()){let m=i<t.lead?-1:t.start+(i-t.lead),s=l!==void 0&&m>=l.start&&m<l.end,f=t.caret===i,n=r.at(-1);if(n!==void 0&&!f&&!n.caret&&n.selected===s){r[r.length-1]={...n,text:n.text+d};continue}r.push({text:d,selected:s,caret:f})}if(t.caret!==void 0&&t.caret>=u.length)r.push({text:" ",selected:!1,caret:!0});return r}import{Box as _,Text as a}from"ink";import{jsx as y,jsxs as w}from"react/jsx-runtime";function bn({editor:t,placeholder:l,secret:u,gutter:r="",maxRows:i,columns:d}){let m=[...r].length,s=" ".repeat(m);if(t.value===""&&l!==void 0&&l!==""){let x=[...l];return w(a,{dimColor:!0,wrap:"truncate",children:[y(a,{color:o.accent,children:r}),y(a,{inverse:!0,children:x[0]??" "}),x.slice(1).join("")]})}let f=kt(t),{rows:n,caretRow:h}=wn(t,Math.max(1,(d??Number.MAX_SAFE_INTEGER)-m)),b=i??n.length,{from:c,to:p}=I(n.length,h,Math.max(1,b)),e=c,T=n.length-p;return w(_,{flexDirection:"column",children:[e>0?w(a,{dimColor:!0,wrap:"truncate",children:[s,"… ",e," line",e===1?"":"s"," above"]}):null,n.slice(c,p).map((x,v)=>{let C=c+v,M=u===!0?[...x.text].map(()=>"•"):[...x.text],S=C===c&&e===0?r:s;if(x.caret===void 0&&f===void 0)return w(a,{wrap:"truncate",children:[y(a,{color:o.accent,children:S}),M.join("")]},`row-${C}`);let A=k(x,f),L=0;return w(a,{wrap:"truncate",children:[y(a,{color:o.accent,children:S}),A.map((g)=>{let R=`run-${C}-${L}`;L+=[...g.text].length;let E=u===!0?[...g.text].map(()=>"•").join(""):g.text;if(g.caret)return y(a,{inverse:!0,children:E},R);if(g.selected)return y(a,{backgroundColor:o.selection,children:E},R);return y(a,{children:E},R)})]},`row-${C}`)}),T>0?w(a,{dimColor:!0,wrap:"truncate",children:[s,"… ",T," line",T===1?"":"s"," below"]}):null]})}
4
4
  export{wn,bn};
5
5
 
6
6
  //# debugId=3FDEB5D0EE7A656F64756E2164756E21
7
- //# sourceMappingURL=index-zked16y4.js.map
7
+ //# sourceMappingURL=index-02dn6m2j.js.map
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{j,$n}from"./index-2wmsmcbr.js";import{useStdout as u}from"ink";import{useEffect as i,useState as t}from"react";function s(e){let n=e?.columns,o=e?.rows;return{columns:n===void 0||n<=0?j:n,rows:o===void 0||o<=0?$n:o}}function re(){let{stdout:e}=u(),[n,o]=t(()=>s(e));return i(()=>{if(e===void 0)return;let r=()=>o(s(e));return e.on("resize",r),()=>void e.off("resize",r)},[e]),n}
2
+ import{j,$n}from"./index-vgc3y3rm.js";import{useStdout as u}from"ink";import{useEffect as i,useState as t}from"react";function s(e){let n=e?.columns,o=e?.rows;return{columns:n===void 0||n<=0?j:n,rows:o===void 0||o<=0?$n:o}}function re(){let{stdout:e}=u(),[n,o]=t(()=>s(e));return i(()=>{if(e===void 0)return;let r=()=>o(s(e));return e.on("resize",r),()=>void e.off("resize",r)},[e]),n}
3
3
  export{re};
4
4
 
5
5
  //# debugId=0E83A1C1932ED9F964756E2164756E21
6
- //# sourceMappingURL=index-a4xqgdrm.js.map
6
+ //# sourceMappingURL=index-0d93hyfc.js.map
@@ -1,17 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import{r,a,v,Ue,h,i,_e,P,g,Lt,No,$e,Ae,F,U}from"./index-7z4sw2dm.js";var ct="dispach",ut="Dispach",ht=1;function q(e,t){return{slug:e,name:t,envPrefix:`${e.toUpperCase()}_`,stateDir:`.${e}`,apiVersion:`${e}/v${ht}`,packageScope:`@${e}`}}var M=q(ct,ut),C=`${M.envPrefix}BRAND`,he=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;function me(e){return e.split("-").map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function pe(e){if(e===void 0)return M;let t=e.trim();if(t==="")throw Error(`${C} is set but empty. hint: unset ${C} entirely to use the default brand — an empty value `+'is treated as a mistake rather than as "no override", because a declared-but-unset variable is usually a container passing through a name it never assigned.');if(!he.test(t))throw Error(`${C}="${t}" is not a usable brand slug. hint: the slug becomes an env var prefix, a dot-directory, an npm scope, and the `+"manifest apiVersion, so it must be lowercase alphanumeric with inner hyphens — "+"e.g. acme or acme-run.");if(t===M.slug)return M;return q(t,me(t))}var Q=pe(process.env[C]);function ft(e,t){let n=Array.from({length:t.length+1},(s,o)=>o);for(let s=1;s<=e.length;s+=1){let o=[s];for(let d=1;d<=t.length;d+=1){let l=(n[d-1]??0)+(e[s-1]===t[d-1]?0:1),c=(o[d-1]??0)+1,m=(n[d]??0)+1;o.push(Math.min(l,c,m))}n=o}return n[t.length]??Math.max(e.length,t.length)}function rt(e,t){let n,s=Number.POSITIVE_INFINITY;for(let o of t){let d=ft(e,o);if(d<s)s=d,n=o}return n!==void 0&&s<=Math.max(2,Math.floor(e.length/3))?n:void 0}var ge=Symbol.for("dispach.HarnessError");function fe(e){return typeof e==="object"&&e!==null&&ge in e}class z extends Error{static ERROR_NAME="HarnessError";code;hint;field;details;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause});this.name=new.target.ERROR_NAME??"HarnessError",this[ge]=!0,this.code=e.code,this.hint=e.hint,this.field=e.field,this.details=e.details??[]}toDetail(){return this.field===void 0?{code:this.code,message:this.message,hint:this.hint}:{code:this.code,message:this.message,hint:this.hint,field:this.field}}format(){let e=[`${this.code}: ${this.message}`];if(this.field!==void 0)e.push(` field: ${this.field}`);if(e.push(` hint: ${this.hint}`),this.details.length===1)return e.join(`
2
+ import{r,a,v,Ue,h,i,$e,P,g,Lt,No,Ae,Re,F,U}from"./index-tv4yv7d2.js";var ct="dispach",ut="Dispach",ht=1;function q(e,t){return{slug:e,name:t,envPrefix:`${e.toUpperCase()}_`,stateDir:`.${e}`,apiVersion:`${e}/v${ht}`,packageScope:`@${e}`}}var M=q(ct,ut),C=`${M.envPrefix}BRAND`,me=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/;function pe(e){return e.split("-").map((t)=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function ge(e){if(e===void 0)return M;let t=e.trim();if(t==="")throw Error(`${C} is set but empty. hint: unset ${C} entirely to use the default brand — an empty value `+'is treated as a mistake rather than as "no override", because a declared-but-unset variable is usually a container passing through a name it never assigned.');if(!me.test(t))throw Error(`${C}="${t}" is not a usable brand slug. hint: the slug becomes an env var prefix, a dot-directory, an npm scope, and the `+"manifest apiVersion, so it must be lowercase alphanumeric with inner hyphens — "+"e.g. acme or acme-run.");if(t===M.slug)return M;return q(t,pe(t))}var Q=ge(process.env[C]);function ft(e,t){let n=Array.from({length:t.length+1},(s,o)=>o);for(let s=1;s<=e.length;s+=1){let o=[s];for(let d=1;d<=t.length;d+=1){let l=(n[d-1]??0)+(e[s-1]===t[d-1]?0:1),c=(o[d-1]??0)+1,m=(n[d]??0)+1;o.push(Math.min(l,c,m))}n=o}return n[t.length]??Math.max(e.length,t.length)}function rt(e,t){let n,s=Number.POSITIVE_INFINITY;for(let o of t){let d=ft(e,o);if(d<s)s=d,n=o}return n!==void 0&&s<=Math.max(2,Math.floor(e.length/3))?n:void 0}var ye=Symbol.for("dispach.HarnessError");function fe(e){return typeof e==="object"&&e!==null&&ye in e}class z extends Error{static ERROR_NAME="HarnessError";code;hint;field;details;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause});this.name=new.target.ERROR_NAME??"HarnessError",this[ye]=!0,this.code=e.code,this.hint=e.hint,this.field=e.field,this.details=e.details??[]}toDetail(){return this.field===void 0?{code:this.code,message:this.message,hint:this.hint}:{code:this.code,message:this.message,hint:this.hint,field:this.field}}format(){let e=[`${this.code}: ${this.message}`];if(this.field!==void 0)e.push(` field: ${this.field}`);if(e.push(` hint: ${this.hint}`),this.details.length===1)return e.join(`
3
3
  `);for(let t of this.details){if(e.push(""),e.push(` ${t.code}: ${t.message}`),t.field!==void 0)e.push(` field: ${t.field}`);e.push(` hint: ${t.hint}`)}return e.join(`
4
- `)}}class y extends z{static ERROR_NAME="ConfigError"}class f extends z{static ERROR_NAME="ToolError"}function ye(e,t){return new y({code:"tools_provider_alias_conflict",message:`The manifest sets tools.providers (${e.join(", ")}) and also the deprecated tools.provider${t===void 0?"Config":` (${t})`}.`,hint:`Keep tools.providers and delete the other two. Merging them would give the scalar a position in the map that nobody wrote, and provider order decides which one wins a slug collision${t===void 0?"":` — move ${t}'s settings into tools.providers.${t}`}.`,field:"tools.provider"})}function we(e,t){return new f({code:"workspace_not_editable",message:`${e} is declared editable: ${t}, so it cannot be written to.`,hint:"Point the write at a volatile file whose frontmatter allows it (editable: append or replace), or change that file's frontmatter. Read-only identity is deliberate — it is the most effective known mitigation for persona drift, so this refuses rather than silently doing nothing."})}function be(){return new f({code:"artifact_unavailable",message:"This runtime has no artifact store, so a compacted observation cannot be read back.",hint:"artifact_read only works inside a session backed by a store. If you are seeing a compaction pointer without one, the pointer was written by a different process — report the text of the pointer rather than guessing at what it replaced."})}function ve(e){return new f({code:"artifact_not_found",message:`No compacted observation is stored under ${JSON.stringify(e)} in this conversation.`,hint:"Copy the id exactly from the pointer in the conversation — it is not guessable and it is scoped to this conversation. If the pointer came from a session you have since switched away from, the observation is not reachable from here."})}var qt="0.1.1";var mt="What I already know, carried from before this conversation and kept current. "+"Not a transcript — these are standing facts about the person I work for and my own working notes. "+"If they ask what I know or remember about them, this is the answer.";var pt=3.8;function Ne(e){if(e==="")return 0;let t=0;for(let n=0;n<e.length;n+=1)if(e.charCodeAt(n)===10)t+=1;return Math.ceil(e.length/pt)+t}var Pe=["runtime.ready","store.ready","runtime.stopping","agent.loaded","agent.disposed","agent.warning","plugin.loaded","plugin.slow","approval.requested","approval.resolved","handoff.start","handoff.result","turn.start","context.assembled","context.dropped","context.pressure","compaction.stage","context.reset","phase.changed","model.call","model.chunk","model.retry","model.result","tool.call","tool.result","tool.gated","tool.repair","tools.refreshed","agent.channel.status","agent.channel.error","agent.channel.rejected","delivery.sent","delivery.retry","delivery.failed","delivery.uncertain","runtime.released","schedules.reconciled","schedule.fired","schedule.skipped","schedule.deferred","schedule.error","turn.end","error"],_=(e)=>String.fromCharCode(e),I=_(27),Ie=_(7),gt=new RegExp(`${I}\\[[0-?]*[ -/]*[@-~]`,"g"),yt=new RegExp(`${I}\\][\\s\\S]*?(?:${Ie}|${I}\\\\|$)`,"g"),wt=new RegExp(`${I}[P^_X][\\s\\S]*?(?:${I}\\\\|${Ie}|$)`,"g"),bt=new RegExp(`${I}[@-Z\\\\-_0-9=><]?`,"g"),vt=new RegExp(`[${_(128)}-${_(159)}]`,"g"),kt=new RegExp(`[${_(0)}-${_(8)}${_(11)}${_(12)}${_(14)}-${_(31)}${_(127)}]`,"g");function Se(e){return e.replace(/\r\n/g,`
4
+ `)}}class y extends z{static ERROR_NAME="ConfigError"}class f extends z{static ERROR_NAME="ToolError"}function we(e,t){return new y({code:"tools_provider_alias_conflict",message:`The manifest sets tools.providers (${e.join(", ")}) and also the deprecated tools.provider${t===void 0?"Config":` (${t})`}.`,hint:`Keep tools.providers and delete the other two. Merging them would give the scalar a position in the map that nobody wrote, and provider order decides which one wins a slug collision${t===void 0?"":` — move ${t}'s settings into tools.providers.${t}`}.`,field:"tools.provider"})}function be(e,t){return new f({code:"workspace_not_editable",message:`${e} is declared editable: ${t}, so it cannot be written to.`,hint:"Point the write at a volatile file whose frontmatter allows it (editable: append or replace), or change that file's frontmatter. Read-only identity is deliberate — it is the most effective known mitigation for persona drift, so this refuses rather than silently doing nothing."})}function ve(){return new f({code:"artifact_unavailable",message:"This runtime has no artifact store, so a compacted observation cannot be read back.",hint:"artifact_read only works inside a session backed by a store. If you are seeing a compaction pointer without one, the pointer was written by a different process — report the text of the pointer rather than guessing at what it replaced."})}function ke(e){return new f({code:"artifact_not_found",message:`No compacted observation is stored under ${JSON.stringify(e)} in this conversation.`,hint:"Copy the id exactly from the pointer in the conversation — it is not guessable and it is scoped to this conversation. If the pointer came from a session you have since switched away from, the observation is not reachable from here."})}var qt="0.1.2";var mt="What I already know, carried from before this conversation and kept current. "+"Not a transcript — these are standing facts about the person I work for and my own working notes. "+"If they ask what I know or remember about them, this is the answer.";var pt=3.8;function Se(e){if(e==="")return 0;let t=0;for(let n=0;n<e.length;n+=1)if(e.charCodeAt(n)===10)t+=1;return Math.ceil(e.length/pt)+t}var Me=["runtime.ready","store.ready","runtime.stopping","agent.loaded","agent.disposed","agent.warning","plugin.loaded","plugin.slow","approval.requested","approval.resolved","handoff.start","handoff.result","turn.start","context.assembled","context.dropped","context.pressure","compaction.stage","context.reset","phase.changed","model.call","model.chunk","model.retry","model.result","tool.call","tool.result","tool.gated","tool.repair","tools.refreshed","agent.channel.status","agent.channel.error","agent.channel.rejected","delivery.sent","delivery.retry","delivery.failed","delivery.uncertain","runtime.released","schedules.reconciled","schedule.fired","schedule.skipped","schedule.deferred","schedule.error","turn.end","error"],_=(e)=>String.fromCharCode(e),I=_(27),Ne=_(7),gt=new RegExp(`${I}\\[[0-?]*[ -/]*[@-~]`,"g"),yt=new RegExp(`${I}\\][\\s\\S]*?(?:${Ne}|${I}\\\\|$)`,"g"),wt=new RegExp(`${I}[P^_X][\\s\\S]*?(?:${I}\\\\|${Ne}|$)`,"g"),bt=new RegExp(`${I}[@-Z\\\\-_0-9=><]?`,"g"),vt=new RegExp(`[${_(128)}-${_(159)}]`,"g"),kt=new RegExp(`[${_(0)}-${_(8)}${_(11)}${_(12)}${_(14)}-${_(31)}${_(127)}]`,"g");function xe(e){return e.replace(/\r\n/g,`
5
5
  `).replace(/\r/g,`
6
- `).replace(yt,"").replace(wt,"").replace(gt,"").replace(bt,"").replace(vt,"").replace(kt,"")}var Tt=/\r\n\r\n|\n\n|\r\r/;function ke(e){let t=[],n,s,o;for(let d of e.split(/\r\n|\n|\r/)){if(d===""||d.startsWith(":"))continue;let l=d.indexOf(":"),c=l===-1?d:d.slice(0,l),m=l===-1?"":d.slice(l+1);if(m.startsWith(" "))m=m.slice(1);switch(c){case"data":t.push(m);break;case"event":n=m;break;case"id":s=m;break;case"retry":{let u=Number.parseInt(m,10);if(Number.isFinite(u))o=u;break}default:break}}if(t.length===0&&n===void 0)return;return{...n===void 0?{}:{event:n},data:t.join(`
7
- `),...s===void 0?{}:{id:s},...o===void 0?{}:{retry:o}}}async function*Fn(e){let t=new TextDecoder,n="";for await(let s of e){n+=typeof s==="string"?s:t.decode(s,{stream:!0});while(!0){let o=Tt.exec(n);if(o===null)break;let d=n.slice(0,o.index);n=n.slice(o.index+o[0].length);let l=ke(d);if(l!==void 0)yield l}}if(n+=t.decode(),n.trim()!==""){let s=ke(n);if(s!==void 0)yield s}}function Un(){return{push:(e)=>e,endStep:()=>"",end:()=>""}}var Oe="<<<",Re=">>>",H=/^\s*(?:[-*+]\s+|\d+[.)]\s+)?<?\s*action\s*:\s*(.+?)\s*>?\s*$/i,Et=/^\s*(?:[-*+]\s+|\d+[.)]\s+)?([A-Za-z_][\w.-]*?)\s*:\s*(.*)$/,J=/^\s*`{3,}\s*[\w+-]*\s*$/,Te=/^\s*end\s*$/i,_t=/^\s*<\s*action\s*>\s*$/i,Ee=/^\s*<\s*\/\s*action\s*>\s*$/i,At=/^\s*<\/?\s*[A-Za-z_][\w.:-]*\s*\/?\s*>\s*$/;function Y(e){return e.replace(/^[`'"*<]+/,"").replace(/[`'"*>]+$/,"").replace(/[.,;:]+$/,"").trim()}function Ce(e,t,n){let s=e.fields.get(t);if(s===void 0)e.fields.set(t,[n]);else s.push(n)}function De(e){if(e.block===void 0||e.heredocKey===void 0)return;let t=[...e.heredocLines];if(t[t.length-1]==="")t.pop();Ce(e.block,e.heredocKey,t.join(`
8
- `)),e.block.wrapped.add(e.heredocKey),e.heredocKey=void 0,e.heredocLines=[]}function N(e){if(De(e),e.block!==void 0)e.blocks.push(e.block);e.block=void 0,e.openKey=void 0,e.awaitingSlug=!1}function xe(){return{block:void 0,openKey:void 0,heredocKey:void 0,heredocLines:[],justClosed:!1,awaitingSlug:!1,text:[],blocks:[]}}function St(e,t,n){let s=t.trim();if(e.heredocKey!==void 0){if(s===Re){De(e);return}if(Te.test(s)){N(e),e.justClosed=!0;return}if(H.test(t)){N(e);let l=H.exec(t),c=Y(l?.[1]??"");if(c!=="")e.block={slug:c,fields:new Map,wrapped:new Set};return}e.heredocLines.push(t);return}let o=H.exec(t);if(o!==null){let l=Y(o[1]??"");if(N(e),l==="")return;e.block={slug:l,fields:new Map,wrapped:new Set};return}if(_t.test(t)){N(e),e.awaitingSlug=!0;return}if(e.awaitingSlug){if(s==="")return;if(Ee.test(t)){e.awaitingSlug=!1;return}let l=Y(s);if(e.awaitingSlug=!1,l!=="")e.block={slug:l,fields:new Map,wrapped:new Set};return}if(Ee.test(t)){if(e.block!==void 0)N(e),e.justClosed=!0;return}if(At.test(t))return;if(e.block===void 0){if(J.test(t)&&(e.justClosed||n())){e.justClosed=!1;return}if(e.text.push(t),s!=="")e.justClosed=!1;return}if(s===""){e.openKey=void 0;return}if(Te.test(s)){N(e),e.justClosed=!0;return}if(J.test(t))return;let d=Et.exec(t);if(d!==null){let l=(d[1]??"").trim(),c=(d[2]??"").trim();if(c===Oe)e.heredocKey=l,e.heredocLines=[],e.openKey=void 0;else Ce(e.block,l,c),e.openKey=l;return}if(e.openKey!==void 0){let l=e.block.fields.get(e.openKey),c=l?.[l.length-1];if(l!==void 0&&c!==void 0)l[l.length-1]=c===""?s:`${c}
9
- ${s}`;return}N(e),e.text.push(t)}function xt(e){if(/^\s*(?:[-*+]|\d+[.)]?)?\s*$/.test(e))return!0;let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)?/,"").toLowerCase(),n=t.startsWith("<")?t.slice(1):t;if("action:".startsWith(n)||n.startsWith("action:"))return!0;if(/^<\/?$/.test(t)||/^<\/?[a-z_][\w.:-]*>?$/.test(t))return!0;return/^`{1,3}[\w+-]*$/.test(t)}function V(e){return e.endsWith("\r")?e.slice(0,-1):e}function jn(){let e=xe(),t="",n=0,s,o="",d=!1,l=(p)=>{if(p==="")return"";if(p.trim()==="")return o+=p,"";let w=o+p;if(o="",d)return w;return d=!0,w.replace(/^\s+/,"")},c=(p,w)=>{let b=e.text.length;return St(e,p,()=>w!==void 0&&H.test(w)),e.text.length>b?p:void 0},m=(p,w,b)=>{let T=c(p,w);if(T===void 0)return"";return l(T.slice(b))+l(`
6
+ `).replace(yt,"").replace(wt,"").replace(gt,"").replace(bt,"").replace(vt,"").replace(kt,"")}var Tt=/\r\n\r\n|\n\n|\r\r/;function Te(e){let t=[],n,s,o;for(let d of e.split(/\r\n|\n|\r/)){if(d===""||d.startsWith(":"))continue;let l=d.indexOf(":"),c=l===-1?d:d.slice(0,l),m=l===-1?"":d.slice(l+1);if(m.startsWith(" "))m=m.slice(1);switch(c){case"data":t.push(m);break;case"event":n=m;break;case"id":s=m;break;case"retry":{let u=Number.parseInt(m,10);if(Number.isFinite(u))o=u;break}default:break}}if(t.length===0&&n===void 0)return;return{...n===void 0?{}:{event:n},data:t.join(`
7
+ `),...s===void 0?{}:{id:s},...o===void 0?{}:{retry:o}}}async function*Fn(e){let t=new TextDecoder,n="";for await(let s of e){n+=typeof s==="string"?s:t.decode(s,{stream:!0});while(!0){let o=Tt.exec(n);if(o===null)break;let d=n.slice(0,o.index);n=n.slice(o.index+o[0].length);let l=Te(d);if(l!==void 0)yield l}}if(n+=t.decode(),n.trim()!==""){let s=Te(n);if(s!==void 0)yield s}}function Un(){return{push:(e)=>e,endStep:()=>"",end:()=>""}}var Ie="<<<",Oe=">>>",D=/^\s*(?:[-*+]\s+|\d+[.)]\s+)?<?\s*action\s*:\s*(.+?)\s*>?\s*$/i,Et=/^\s*(?:[-*+]\s+|\d+[.)]\s+)?([A-Za-z_][\w.-]*?)\s*:\s*(.*)$/,Z=/^\s*`{3,}\s*[\w+-]*\s*$/,Y=/^\s*end\s*$/i,_t=/^\s*<\s*action\s*>\s*$/i,Ee=/^\s*<\s*\/\s*action\s*>\s*$/i,At=/^\s*<\/?\s*[A-Za-z_][\w.:-]*\s*\/?\s*>\s*$/;function V(e){return e.replace(/^[`'"*<]+/,"").replace(/[`'"*>]+$/,"").replace(/[.,;:]+$/,"").trim()}function Ce(e,t,n){let s=e.fields.get(t);if(s===void 0)e.fields.set(t,[n]);else s.push(n)}function Fe(e){if(e.block===void 0||e.heredocKey===void 0)return;let t=[...e.heredocLines];if(t[t.length-1]==="")t.pop();Ce(e.block,e.heredocKey,t.join(`
8
+ `)),e.block.wrapped.add(e.heredocKey),e.heredocKey=void 0,e.heredocLines=[]}function N(e){if(Fe(e),e.block!==void 0)e.blocks.push(e.block);e.block=void 0,e.openKey=void 0,e.awaitingSlug=!1}function _e(){return{block:void 0,openKey:void 0,severedKey:void 0,severedPending:void 0,heredocKey:void 0,heredocLines:[],justClosed:!1,awaitingSlug:!1,text:[],blocks:[]}}function St(e,t,n){let s=t.trim();if(e.heredocKey!==void 0){if(s===Oe){Fe(e);return}if(Y.test(s)){N(e),e.justClosed=!0;return}if(D.test(t)){N(e);let l=D.exec(t),c=V(l?.[1]??"");if(c!=="")e.block={slug:c,fields:new Map,wrapped:new Set,severed:new Set};return}e.heredocLines.push(t);return}let o=D.exec(t);if(o!==null){let l=V(o[1]??"");if(N(e),l==="")return;e.block={slug:l,fields:new Map,wrapped:new Set,severed:new Set};return}if(_t.test(t)){N(e),e.awaitingSlug=!0;return}if(e.awaitingSlug){if(s==="")return;if(Ee.test(t)){e.awaitingSlug=!1;return}let l=V(s);if(e.awaitingSlug=!1,l!=="")e.block={slug:l,fields:new Map,wrapped:new Set,severed:new Set};return}if(Ee.test(t)){if(e.block!==void 0)N(e),e.justClosed=!0;return}if(At.test(t))return;if(e.block===void 0){if(Z.test(t)&&(e.justClosed||n())){e.justClosed=!1;return}if(Y.test(s)&&e.severedPending!==void 0){e.severedPending.block.severed.add(e.severedPending.key),e.severedPending=void 0;return}if(D.test(t))e.severedPending=void 0;if(e.text.push(t),s!=="")e.justClosed=!1;return}if(s===""){if(e.openKey!==void 0)e.severedKey=e.openKey;e.openKey=void 0;return}if(Y.test(s)){e.severedKey=void 0,N(e),e.justClosed=!0;return}if(Z.test(t))return;let d=Et.exec(t);if(d!==null){let l=(d[1]??"").trim(),c=(d[2]??"").trim();if(e.severedKey=void 0,c===Ie)e.heredocKey=l,e.heredocLines=[],e.openKey=void 0;else Ce(e.block,l,c),e.openKey=l;return}if(e.openKey!==void 0){let l=e.block.fields.get(e.openKey),c=l?.[l.length-1];if(l!==void 0&&c!==void 0)l[l.length-1]=c===""?s:`${c}
9
+ ${s}`;return}if(e.severedKey!==void 0)e.severedPending={block:e.block,key:e.severedKey},e.severedKey=void 0;N(e),e.text.push(t)}function $t(e){if(/^\s*(?:[-*+]|\d+[.)]?)?\s*$/.test(e))return!0;let t=e.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)?/,"").toLowerCase(),n=t.startsWith("<")?t.slice(1):t;if("action:".startsWith(n)||n.startsWith("action:"))return!0;if(/^<\/?$/.test(t)||/^<\/?[a-z_][\w.:-]*>?$/.test(t))return!0;return/^`{1,3}[\w+-]*$/.test(t)}function J(e){return e.endsWith("\r")?e.slice(0,-1):e}function jn(){let e=_e(),t="",n=0,s,o="",d=!1,l=(p)=>{if(p==="")return"";if(p.trim()==="")return o+=p,"";let w=o+p;if(o="",d)return w;return d=!0,w.replace(/^\s+/,"")},c=(p,w)=>{let b=e.text.length;return St(e,p,()=>w!==void 0&&D.test(w)),e.text.length>b?p:void 0},m=(p,w,b)=>{let T=c(p,w);if(T===void 0)return"";return l(T.slice(b))+l(`
10
10
  `)},u=(p)=>{if(s===void 0)return"";let w=s;return s=void 0,m(w,p,0)};return{push(p){let w="";t+=p;let b=t.indexOf(`
11
- `);while(b!==-1){let E=V(t.slice(0,b));if(t=t.slice(b+1),w+=u(E),e.block===void 0&&J.test(E)&&!e.justClosed)s=E;else w+=m(E,void 0,n);n=0,b=t.indexOf(`
12
- `)}let T=V(t);if(e.block===void 0&&!e.awaitingSlug&&s===void 0&&!xt(T))w+=l(T.slice(n)),n=T.length;return w},endStep(){let p=k();return o=`
11
+ `);while(b!==-1){let E=J(t.slice(0,b));if(t=t.slice(b+1),w+=u(E),e.block===void 0&&Z.test(E)&&!e.justClosed)s=E;else w+=m(E,void 0,n);n=0,b=t.indexOf(`
12
+ `)}let T=J(t);if(e.block===void 0&&!e.awaitingSlug&&s===void 0&&!$t(T))w+=l(T.slice(n)),n=T.length;return w},endStep(){let p=k();return o=`
13
13
 
14
- `,e=xe(),p},end:k};function k(){let p=u(void 0),w=V(t);if(w!==""){let b=c(w,void 0);if(b!==void 0)p+=l(b.slice(n))}return t="",n=0,s=void 0,p}}var $s=`# Tools
14
+ `,e=_e(),p},end:k};function k(){let p=u(void 0),w=J(t);if(w!==""){let b=c(w,void 0);if(b!==void 0)p+=l(b.slice(n))}return t="",n=0,s=void 0,p}}var xs=`# Tools
15
15
 
16
16
  To use a tool, write an ACTION block. Start each line at the left margin, exactly like this:
17
17
 
@@ -25,42 +25,42 @@ every field name from that list, spelled exactly as it is written there.
25
25
 
26
26
  Rules for a block:
27
27
  - One field per line, written as \`name: value\`, where \`name\` is one of that tool's own field names.
28
- - For a value spanning several lines, open it with \`${Oe}\` and close it with \`${Re}\` alone on its own line.
28
+ - For a value spanning several lines, open it with \`${Ie}\` and close it with \`${Oe}\` alone on its own line.
29
29
  - Finish every block with \`END\` alone on its own line.
30
30
  - Several blocks are allowed. They run in the order you write them.
31
31
  - Use only the tools listed below, only their listed fields, and always give every required field.
32
32
 
33
33
  Anything you write outside a block is shown to the person you are talking to, so keep explanations
34
34
  short and keep them out of the block. When no tool fits, simply reply — never invent a tool, and
35
- never guess a value for a required field you have not been given.`;import{appendFile as Xe,mkdir as En,readFile as _n}from"node:fs/promises";import{join as Ge}from"node:path";import{appendFile as qe,mkdir as An,readFile as Sn,writeFile as xn}from"node:fs/promises";import{join as $n}from"node:path";import{readFile as Yn,writeFile as Vn}from"node:fs/promises";var $t=`${Q.slug}_`,Nt="0123456789abcdefghjkmnpqrstvwxyz",It=32;function zn(){let e=new Uint8Array(It);crypto.getRandomValues(e);let t="";for(let n of e)t+=Nt[n&31]??"0";return`${$t}${t}`}async function Bn(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map((n)=>n.toString(16).padStart(2,"0")).join("")}var Kn=64,Ot=new RegExp("[\\u0000-\\u001f\\u007f]");function Xr(e){if(e.trim()==="")return"A key label cannot be empty.";if(e.length>Kn)return`A key label is at most ${Kn} characters; this one is ${e.length}.`;if(Ot.test(e))return"A key label cannot contain control characters, including newlines and tabs.";return}function Rt(e){let t=`${e.channel}:${e.peerId}`;return e.thread===void 0||e.thread===""?t:`${t}:${e.thread}`}var Fe="0123456789abcdefghijklmnopqrstuvwxyz";function Mt(e){let t=new Uint8Array(e);crypto.getRandomValues(t);let n="";for(let s of t)n+=Fe[s%Fe.length];return n}function ae(e,t){return`${e}_${t.toString(36)}${Mt(8)}`}function Gt(e=Date.now()){return ae("t",e)}function Jr(e=Date.now()){return ae("r",e)}function Qr(e=Date.now()){return ae("k",e)}var je="phase_set",et="*",We="tag:";function eo(e){let t=Object.keys(e);return t.find((s)=>e[s]?.entry===!0)??t[0]}function He(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}function Ct(e,t){if(e===et)return!0;if(e.startsWith(We)){let n=e.slice(We.length).toLowerCase();return t.tags.some((s)=>s.toLowerCase()===n)}return He(e)===He(t.slug)}function Dt(e,t){let n=e[t];if(n===void 0)return[et];return n.allow.includes(je)?n.allow:[...n.allow,je]}function mr(e){return e!==void 0&&Object.keys(e).length>1}function to(e,t){return Object.keys(e).filter((n)=>Dt(e,n).some((s)=>Ct(s,t)))}var Me=["user","agent"];var Ut=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,Ft=/<!--[\s\S]*?-->/g,Pt=/\n{3,}/g;function jt(e){let t=Ut.exec(e);return t===null||t===void 0?e:e.slice(t[0].length)}function Wt(e){return e.replace(Ft,"").replace(Pt,`
35
+ never guess a value for a required field you have not been given.`;import{appendFile as Xe,mkdir as En,readFile as _n}from"node:fs/promises";import{join as Ge}from"node:path";import{appendFile as qe,mkdir as An,readFile as Sn,writeFile as $n}from"node:fs/promises";import{join as xn}from"node:path";import{readFile as Yn,writeFile as Vn}from"node:fs/promises";var xt=`${Q.slug}_`,Nt="0123456789abcdefghjkmnpqrstvwxyz",It=32;function zn(){let e=new Uint8Array(It);crypto.getRandomValues(e);let t="";for(let n of e)t+=Nt[n&31]??"0";return`${xt}${t}`}async function Bn(e){let t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return[...new Uint8Array(t)].map((n)=>n.toString(16).padStart(2,"0")).join("")}var Kn=64,Rt=new RegExp("[\\u0000-\\u001f\\u007f]");function Xr(e){if(e.trim()==="")return"A key label cannot be empty.";if(e.length>Kn)return`A key label is at most ${Kn} characters; this one is ${e.length}.`;if(Rt.test(e))return"A key label cannot contain control characters, including newlines and tabs.";return}function Ot(e){let t=`${e.channel}:${e.peerId}`;return e.thread===void 0||e.thread===""?t:`${t}:${e.thread}`}var Pe="0123456789abcdefghijklmnopqrstuvwxyz";function Mt(e){let t=new Uint8Array(e);crypto.getRandomValues(t);let n="";for(let s of t)n+=Pe[s%Pe.length];return n}function de(e,t){return`${e}_${t.toString(36)}${Mt(8)}`}function Gt(e=Date.now()){return de("t",e)}function Jr(e=Date.now()){return de("r",e)}function Qr(e=Date.now()){return de("k",e)}var je="phase_set",et="*",We="tag:";function eo(e){let t=Object.keys(e);return t.find((s)=>e[s]?.entry===!0)??t[0]}function He(e){return e.toLowerCase().replace(/[\s_.-]+/g,"")}function Ct(e,t){if(e===et)return!0;if(e.startsWith(We)){let n=e.slice(We.length).toLowerCase();return t.tags.some((s)=>s.toLowerCase()===n)}return He(e)===He(t.slug)}function Dt(e,t){let n=e[t];if(n===void 0)return[et];return n.allow.includes(je)?n.allow:[...n.allow,je]}function mr(e){return e!==void 0&&Object.keys(e).length>1}function to(e,t){return Object.keys(e).filter((n)=>Dt(e,n).some((s)=>Ct(s,t)))}var Le=["user","agent"];var Ut=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/,Ft=/<!--[\s\S]*?-->/g,Pt=/\n{3,}/g;function jt(e){let t=Ut.exec(e);return t===null||t===void 0?e:e.slice(t[0].length)}function Wt(e){return e.replace(Ft,"").replace(Pt,`
36
36
 
37
- `).trim()}var K={static:2000,volatile:3500,reminder:500,total:6000};var S=r().min(1),Ht=i({delimiters:g(["xml","markdown","plain"]).optional(),intensity:g(["emphatic","neutral","soft"]).optional(),examplesIn:g(["system","user"]).optional(),skillsIn:g(["system","user"]).optional()}).strict(),Kt=i({nativeTools:v().optional(),strictSchema:v().optional(),thinking:g(["none","anthropic","openai","deepseek"]).optional(),promptCache:g(["none","anthropic","openai"]).optional(),parallelToolCalls:v().optional(),contextWindow:a().int().positive().optional(),maxOutput:a().int().positive().optional(),promptStyle:Ht.optional()}).strict(),B=i({id:r().min(1),baseUrl:r().min(1),apiKeyEnv:r().min(1).optional(),temperature:a().min(0).max(2).optional(),topP:a().min(0).max(1).optional(),maxTokens:a().int().positive().optional(),reasoningEffort:g(["none","minimal","low","medium","high"]).optional(),headers:P(r(),r()).optional(),streamUsage:v().optional(),capabilities:Kt.optional()}).strict(),Bt=i({main:B,selector:B.optional(),compactor:B.optional()}).catchall(B),Xt=i({snip:a().default(0.6),micro:a().default(0.7),collapse:a().default(0.8),reset:a().default(0.88),trim:a().default(0.95)}).strict(),zt=i({static:a().int().positive().default(K.static),volatile:a().int().positive().default(K.volatile),reminder:a().int().positive().default(K.reminder),total:a().int().positive().default(K.total)}).strict(),Jt=i({perRuleSuccess:a().gt(0).lte(1).default(0.9),reliabilityTarget:a().gt(0).lt(1).default(0.8),onExceed:g(["fail","warn"]).default("fail")}).strict(),Qt=i({file:r().min(1),requires:i({contextWindow:r().min(1).optional(),class:g(["frontier","small"]).optional()}).strict().optional(),onUnmet:g(["distill","omit","fail"]).default("distill"),distilled:r().min(1).optional()}).strict(),en=i({dir:r().min(1),maxActive:a().int().nonnegative().default(2),budget:a().int().positive().default(600)}).strict(),tn=i({window:a().int().positive().optional(),reserveOutput:a().int().positive().default(4096),observationMaxTokens:a().int().positive().default(2000),files:h(r().min(1)).default([]),workspace:r().min(1).default("./workspace"),static:h(r().min(1)).default([]),volatile:h(r().min(1)).default([]),reminder:r().min(1).optional(),budgets:zt.prefault({}),rules:Jt.prefault({}),soul:Qt.optional(),compactionNotice:v().optional(),thresholds:Xt.prefault({})}).strict(),nn=i({max:a().int().positive().default(24),reserveWrite:a().int().nonnegative().default(6)}).strict(),sn=i({onMutate:g(["refuse","confirm","allow"]).default("refuse")}).strict(),rn=i({mode:g(["ask","allow","deny"]).default("allow"),allow:h(r().min(1)).default([]),deny:h(r().min(1)).default([]),onNoApprover:g(["deny","allow"]).default("deny")}).strict(),on=i({dialect:g(["nlt","native"]).default("nlt"),providers:P(S,P(r(),Ue())).default({}),provider:S.optional(),providerConfig:P(r(),Ue()).default({}),budget:nn.prefault({}),pinned:h(r().min(1)).default([]),search:i({enabled:v().default(!1)}).strict().prefault({}),local:h(r().min(1)).default([]),untrusted:sn.prefault({}),policy:rn.prefault({})}).strict(),an=i({allow:h(r().min(1)),entry:v().optional()}).strict(),dn=i({dir:r().min(1).default("./skills"),maxActive:a().int().nonnegative().default(1),threshold:a().default(0.35)}).strict(),ln=i({retriever:r().min(1).default("fts5"),dir:r().min(1).default("./memory"),maxActive:a().int().nonnegative().default(5),threshold:a().default(0.2),budget:a().int().positive().default(2000),includeHistory:v().default(!0)}).strict(),cn=i({type:S,id:S,allowFrom:h(r().min(1)).optional(),enabled:v().default(!0)}).passthrough(),tt=i({channel:S,to:r().min(1)}).strict(),un=i({default:S.optional(),targets:P(r(),tt).default({})}).strict(),re=No(()=>i({type:g(["string","number","integer","boolean","array","object"]),description:r().optional(),enum:h(_e([r(),a(),v()])).optional(),items:re.optional(),properties:P(r(),re).optional(),required:h(r()).optional()})),hn=i({id:S,manifest:r().min(1),task:r().min(1),artifact:i({type:Lt("object"),properties:P(r(),re),required:h(r()).optional()}).strict()}).strict(),fn=i({members:h(hn).min(1)}).strict(),nt=i({id:S,kind:g(["cron","every","at"]),expr:r().min(1),task:r().min(1),deliver:_e([Lt("none"),tt]),session:r().min(1).default("isolated"),role:S.optional(),enabled:v().default(!0),timezone:r().min(1).optional()}).strict(),mn=_e([r().min(1),i({spec:r().min(1),config:P(r(),Ue()).default({})}).strict()]),pn=i({identicalCalls:a().int().min(2).default(3)}).strict(),gn=i({maxSteps:a().int().positive().default(40),noProgress:pn.prefault({}),turnTimeoutMs:a().int().positive().default(1800000),toolTimeoutMs:a().int().positive().default(120000),maxParallelTools:a().int().positive().default(4)}).strict(),yn=i({enabled:v().default(!1),port:a().int().min(1).max(65535).default(7420),host:r().min(1).default("127.0.0.1"),tokenEnv:r().min(1).default(`${Q.envPrefix}API_TOKEN`),allowedOrigins:h(r().min(1)).default([]),allowedHosts:h(r().min(1)).default([])}).strict(),wn=i({apiVersion:r().min(1),id:S,name:r().min(1).optional(),extends:r().min(1).optional(),model:Bt,context:tn.prefault({}),tools:on.prefault({}),phases:P(r(),an).optional(),skills:dn.optional(),knowledge:en.optional(),memory:ln.optional(),channels:h(cn).default([]),delivery:un.optional(),schedules:h(nt).default([]),team:fn.optional(),plugins:h(mn).default([]),limits:gn.prefault({}),server:yn.prefault({})}).strict(),oe=["main","selector","compactor"];function bn(e){return oe.includes(e)}function Ke(e){return Object.keys(e).filter((t)=>!bn(t))}var vn={nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096},Z={nativeTools:!0,strictSchema:!1,thinking:"anthropic",promptCache:"none",parallelToolCalls:!0},ee="Thinking blocks must be replayed with tool results or multi-step reasoning degrades silently. Prompt caching is unavailable on the OpenAI-compatible endpoint; the native Messages API is the only route to it.",vo=[{pattern:"gpt-4o*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:128000,maxOutput:16384}},{pattern:"gpt-4.1*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:1e6,maxOutput:32768}},{pattern:"gpt-4-turbo*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:128000,maxOutput:4096}},{pattern:"gpt-3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:16385,maxOutput:4096}},{pattern:"gpt-5*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:200000,maxOutput:32768},note:"Deliberately conservative on window and output. Override if your endpoint serves more."},{pattern:"o1*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o3*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o4*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},...["claude-fable-5*","claude-opus-5*","claude-opus-4-8*","claude-opus-4-7*","claude-opus-4-6*","claude-sonnet-5*","claude-sonnet-4-6*"].map((e)=>({pattern:e,capabilities:{...Z,contextWindow:1e6,maxOutput:128000},note:ee})),{pattern:"claude-haiku-*",capabilities:{...Z,contextWindow:200000,maxOutput:64000},note:ee},{pattern:"claude-*",capabilities:{...Z,contextWindow:200000,maxOutput:8192},note:ee},{pattern:"gemini*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:1e6,maxOutput:8192}},{pattern:"qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192},note:"Served locally by Ollama, which reports no token usage unless model.<role>.streamUsage is set — token figures come from the estimator until it is. Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-13 against qwen3.5:9b on localhost:11434/v1"},{pattern:"qwen*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"llama*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:128000,maxOutput:4096}},{pattern:"mistral*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"mixtral*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"deepseek-v4-pro*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Reasoning tokens are billed to the output budget. With max_tokens=16 this model returned empty content and finish_reason=length; context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-12 against api.deepseek.com/v1"},{pattern:"deepseek-v4-flash*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:393216},verified:"2026-08-12 against api.deepseek.com/v1 (reasoning confirmed). Measured 2026-08-25 by `model probe --window`: contextWindow 1048576 as a ceiling — the endpoint refused a 1048576-token prompt and named that number; maxOutput 393216 from a refusal naming the range [1, 393216]; automatic prompt caching confirmed at 1024 of 1115 prompt tokens with no breakpoints sent, which is why promptCache stays `none` (it describes the runtime's job, not the provider's behaviour)."},{pattern:"deepseek-v4*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Family fallback for v4 ids this registry has not seen. Assumes reasoning, because both measured v4 models emit it."},{pattern:"deepseek-reasoner*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"Not served by the account this registry was tested against. Numbers are from provider documentation and are deliberately low — override them if your endpoint serves this id."},{pattern:"deepseek-chat*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:65536,maxOutput:8192},note:"Unverified, from provider documentation."},{pattern:"deepseek-r1*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"The open-weight name for the reasoner, used by self-hosted and Ollama deployments."},{pattern:"deepseek*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192}},{pattern:"gemma*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096}},{pattern:"phi*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:16384,maxOutput:4096}},{pattern:"*",capabilities:vn}];var Be=/^(?:timeout\s+\S+|time|nice(?:\s+-n\s+\S+)?|stdbuf(?:\s+-\S+)*|command|builtin)\s+/i;function kn(e){let t=e.trim();for(let n=0;n<4&&Be.test(t);n+=1)t=t.replace(Be,"").trim();return t}var Tn=/\s*(?:&&|\|\||;|\||&|\n)\s*/;function no(e){return e.split(Tn).map((t)=>kn(t)).filter((t)=>t!=="")}var Nn=/^(?:[-*+]|\d+[.)])[ \t]+\S/,In=/\*\*(\d{4})-(\d{2})-\d{2}T/;function On(e){let t=[],n=-1,s=(o)=>{if(n===-1)return;t.push({start:n,end:o,text:e.slice(n,o).join(`
38
- `).trimEnd()}),n=-1};for(let o=0;o<e.length;o+=1){let d=e[o]??"";if(Nn.test(d)){s(o),n=o;continue}if(n===-1)continue;if(d.trim()===""||/^[ \t]/.test(d))continue;s(o)}return s(e.length),t}function ie(e){return Ne(Wt(jt(e)))}function Rn(e,t){let n=In.exec(e);if(n!==null)return`${n[1]}-${n[2]}.md`;let s=t.getUTCFullYear(),o=`${t.getUTCMonth()+1}`.padStart(2,"0");return`${s}-${o}.md`}function Ln(e,t){let n=e.split(/\r?\n/),s=On(n),o=[],d=s,l=e,c=ie(l);while(c>t&&d.length>1){let m=d[0];if(m===void 0)break;o.push(m),d=d.slice(1),l=Mn(n,o),c=ie(l)}if(c<=t)return{evict:o,remaining:l,tokens:c};return{evict:o,remaining:l,tokens:c,shortfall:d.length<=1?`${c} tokens remain against a ${t}-token budget with one note left, so eviction cannot help`:`${c} tokens remain against a ${t}-token budget`}}function Mn(e,t){let n=new Set;for(let s of t)for(let o=s.start;o<s.end;o+=1)n.add(o);return e.filter((s,o)=>!n.has(o)).join(`
37
+ `).trim()}var K={static:2000,volatile:3500,reminder:500,total:6000};var S=r().min(1),Ht=i({delimiters:g(["xml","markdown","plain"]).optional(),intensity:g(["emphatic","neutral","soft"]).optional(),examplesIn:g(["system","user"]).optional(),skillsIn:g(["system","user"]).optional()}).strict(),Kt=i({nativeTools:v().optional(),strictSchema:v().optional(),thinking:g(["none","anthropic","openai","deepseek"]).optional(),promptCache:g(["none","anthropic","openai"]).optional(),parallelToolCalls:v().optional(),contextWindow:a().int().positive().optional(),maxOutput:a().int().positive().optional(),promptStyle:Ht.optional()}).strict(),B=i({id:r().min(1),baseUrl:r().min(1),apiKeyEnv:r().min(1).optional(),temperature:a().min(0).max(2).optional(),topP:a().min(0).max(1).optional(),maxTokens:a().int().positive().optional(),reasoningEffort:g(["none","minimal","low","medium","high"]).optional(),headers:P(r(),r()).optional(),streamUsage:v().optional(),capabilities:Kt.optional()}).strict(),Bt=i({main:B,selector:B.optional(),compactor:B.optional()}).catchall(B),Xt=i({snip:a().default(0.6),micro:a().default(0.7),collapse:a().default(0.8),reset:a().default(0.88),trim:a().default(0.95)}).strict(),zt=i({static:a().int().positive().default(K.static),volatile:a().int().positive().default(K.volatile),reminder:a().int().positive().default(K.reminder),total:a().int().positive().default(K.total)}).strict(),Jt=i({perRuleSuccess:a().gt(0).lte(1).default(0.9),reliabilityTarget:a().gt(0).lt(1).default(0.8),onExceed:g(["fail","warn"]).default("fail")}).strict(),Qt=i({file:r().min(1),requires:i({contextWindow:r().min(1).optional(),class:g(["frontier","small"]).optional()}).strict().optional(),onUnmet:g(["distill","omit","fail"]).default("distill"),distilled:r().min(1).optional()}).strict(),en=i({dir:r().min(1),maxActive:a().int().nonnegative().default(2),budget:a().int().positive().default(600)}).strict(),tn=i({window:a().int().positive().optional(),reserveOutput:a().int().positive().default(4096),observationMaxTokens:a().int().positive().default(2000),files:h(r().min(1)).default([]),workspace:r().min(1).default("./workspace"),static:h(r().min(1)).default([]),volatile:h(r().min(1)).default([]),reminder:r().min(1).optional(),budgets:zt.prefault({}),rules:Jt.prefault({}),soul:Qt.optional(),compactionNotice:v().optional(),thresholds:Xt.prefault({})}).strict(),nn=i({max:a().int().positive().default(24),reserveWrite:a().int().nonnegative().default(6)}).strict(),sn=i({onMutate:g(["refuse","confirm","allow"]).default("refuse")}).strict(),rn=i({mode:g(["ask","allow","deny"]).default("allow"),allow:h(r().min(1)).default([]),deny:h(r().min(1)).default([]),onNoApprover:g(["deny","allow"]).default("deny")}).strict(),on=i({dialect:g(["nlt","native"]).default("nlt"),providers:P(S,P(r(),Ue())).default({}),provider:S.optional(),providerConfig:P(r(),Ue()).default({}),budget:nn.prefault({}),pinned:h(r().min(1)).default([]),search:i({enabled:v().default(!1)}).strict().prefault({}),local:h(r().min(1)).default([]),untrusted:sn.prefault({}),policy:rn.prefault({})}).strict(),an=i({allow:h(r().min(1)),entry:v().optional()}).strict(),dn=i({dir:r().min(1).default("./skills"),maxActive:a().int().nonnegative().default(1),threshold:a().default(0.35)}).strict(),ln=i({retriever:r().min(1).default("fts5"),dir:r().min(1).default("./memory"),maxActive:a().int().nonnegative().default(5),threshold:a().default(0.2),budget:a().int().positive().default(2000),includeHistory:v().default(!0)}).strict(),cn=i({type:S,id:S,allowFrom:h(r().min(1)).optional(),enabled:v().default(!0)}).passthrough(),tt=i({channel:S,to:r().min(1)}).strict(),un=i({default:S.optional(),targets:P(r(),tt).default({})}).strict(),oe=No(()=>i({type:g(["string","number","integer","boolean","array","object"]),description:r().optional(),enum:h($e([r(),a(),v()])).optional(),items:oe.optional(),properties:P(r(),oe).optional(),required:h(r()).optional()})),hn=i({id:S,manifest:r().min(1),task:r().min(1),artifact:i({type:Lt("object"),properties:P(r(),oe),required:h(r()).optional()}).strict()}).strict(),fn=i({members:h(hn).min(1)}).strict(),nt=i({id:S,kind:g(["cron","every","at"]),expr:r().min(1),task:r().min(1),deliver:$e([Lt("none"),tt]),session:r().min(1).default("isolated"),role:S.optional(),enabled:v().default(!0),timezone:r().min(1).optional()}).strict(),mn=$e([r().min(1),i({spec:r().min(1),config:P(r(),Ue()).default({})}).strict()]),pn=i({identicalCalls:a().int().min(2).default(3)}).strict(),gn=i({maxSteps:a().int().positive().default(40),noProgress:pn.prefault({}),turnTimeoutMs:a().int().positive().default(1800000),toolTimeoutMs:a().int().positive().default(120000),maxParallelTools:a().int().positive().default(4)}).strict(),yn=i({enabled:v().default(!1),port:a().int().min(1).max(65535).default(7420),host:r().min(1).default("127.0.0.1"),tokenEnv:r().min(1).default(`${Q.envPrefix}API_TOKEN`),allowedOrigins:h(r().min(1)).default([]),allowedHosts:h(r().min(1)).default([])}).strict(),wn=i({apiVersion:r().min(1),id:S,name:r().min(1).optional(),extends:r().min(1).optional(),model:Bt,context:tn.prefault({}),tools:on.prefault({}),phases:P(r(),an).optional(),skills:dn.optional(),knowledge:en.optional(),memory:ln.optional(),channels:h(cn).default([]),delivery:un.optional(),schedules:h(nt).default([]),team:fn.optional(),plugins:h(mn).default([]),limits:gn.prefault({}),server:yn.prefault({})}).strict(),ie=["main","selector","compactor"];function bn(e){return ie.includes(e)}function Ke(e){return Object.keys(e).filter((t)=>!bn(t))}var vn={nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096},ee={nativeTools:!0,strictSchema:!1,thinking:"anthropic",promptCache:"none",parallelToolCalls:!0},te="Thinking blocks must be replayed with tool results or multi-step reasoning degrades silently. Prompt caching is unavailable on the OpenAI-compatible endpoint; the native Messages API is the only route to it.",ko=[{pattern:"gpt-4o*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:128000,maxOutput:16384}},{pattern:"gpt-4.1*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"none",promptCache:"openai",parallelToolCalls:!0,contextWindow:1e6,maxOutput:32768}},{pattern:"gpt-4-turbo*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:128000,maxOutput:4096}},{pattern:"gpt-3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:16385,maxOutput:4096}},{pattern:"gpt-5*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!0,contextWindow:200000,maxOutput:32768},note:"Deliberately conservative on window and output. Override if your endpoint serves more."},{pattern:"o1*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o3*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},{pattern:"o4*",capabilities:{nativeTools:!0,strictSchema:!0,thinking:"openai",promptCache:"openai",parallelToolCalls:!1,contextWindow:200000,maxOutput:1e5}},...["claude-fable-5*","claude-opus-5*","claude-opus-4-8*","claude-opus-4-7*","claude-opus-4-6*","claude-sonnet-5*","claude-sonnet-4-6*"].map((e)=>({pattern:e,capabilities:{...ee,contextWindow:1e6,maxOutput:128000},note:te})),{pattern:"claude-haiku-*",capabilities:{...ee,contextWindow:200000,maxOutput:64000},note:te},{pattern:"claude-*",family:!0,capabilities:{...ee,contextWindow:200000,maxOutput:8192},note:te},{pattern:"gemini*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:1e6,maxOutput:8192}},{pattern:"qwen3.5*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192},note:"Served locally by Ollama, which reports no token usage unless model.<role>.streamUsage is set — token figures come from the estimator until it is. Reasoning is billed to the output budget, so context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-13 against qwen3.5:9b on localhost:11434/v1"},{pattern:"qwen*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"llama*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:128000,maxOutput:4096}},{pattern:"mistral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"mixtral*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:32768,maxOutput:8192}},{pattern:"deepseek-v4-pro*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Reasoning tokens are billed to the output budget. With max_tokens=16 this model returned empty content and finish_reason=length; context.reserveOutput must cover reasoning plus the reply.",verified:"2026-08-12 against api.deepseek.com/v1"},{pattern:"deepseek-v4-flash*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:1048576,maxOutput:393216},verified:"2026-08-12 against api.deepseek.com/v1 (reasoning confirmed). Measured 2026-08-25 by `model probe --window`: contextWindow 1048576 as a ceiling — the endpoint refused a 1048576-token prompt and named that number; maxOutput 393216 from a refusal naming the range [1, 393216]; automatic prompt caching confirmed at 1024 of 1115 prompt tokens with no breakpoints sent, which is why promptCache stays `none` (it describes the runtime's job, not the provider's behaviour)."},{pattern:"deepseek-v4*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:393216,maxOutput:393216},note:"Family fallback for v4 ids this registry has not seen. Assumes reasoning, because both measured v4 models emit it."},{pattern:"deepseek-reasoner*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"Not served by the account this registry was tested against. Numbers are from provider documentation and are deliberately low — override them if your endpoint serves this id."},{pattern:"deepseek-chat*",capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!0,contextWindow:65536,maxOutput:8192},note:"Unverified, from provider documentation."},{pattern:"deepseek-r1*",capabilities:{nativeTools:!1,strictSchema:!1,thinking:"deepseek",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192},note:"The open-weight name for the reasoner, used by self-hosted and Ollama deployments."},{pattern:"deepseek*",family:!0,capabilities:{nativeTools:!0,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:65536,maxOutput:8192}},{pattern:"gemma*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:8192,maxOutput:4096}},{pattern:"phi*",family:!0,capabilities:{nativeTools:!1,strictSchema:!1,thinking:"none",promptCache:"none",parallelToolCalls:!1,contextWindow:16384,maxOutput:4096}},{pattern:"*",capabilities:vn}];var Be=/^(?:timeout\s+\S+|time|nice(?:\s+-n\s+\S+)?|stdbuf(?:\s+-\S+)*|command|builtin)\s+/i;function kn(e){let t=e.trim();for(let n=0;n<4&&Be.test(t);n+=1)t=t.replace(Be,"").trim();return t}var Tn=/\s*(?:&&|\|\||;|\||&|\n)\s*/;function no(e){return e.split(Tn).map((t)=>kn(t)).filter((t)=>t!=="")}var Nn=/^(?:[-*+]|\d+[.)])[ \t]+\S/,In=/\*\*(\d{4})-(\d{2})-\d{2}T/;function Rn(e){let t=[],n=-1,s=(o)=>{if(n===-1)return;t.push({start:n,end:o,text:e.slice(n,o).join(`
38
+ `).trimEnd()}),n=-1};for(let o=0;o<e.length;o+=1){let d=e[o]??"";if(Nn.test(d)){s(o),n=o;continue}if(n===-1)continue;if(d.trim()===""||/^[ \t]/.test(d))continue;s(o)}return s(e.length),t}function ae(e){return Se(Wt(jt(e)))}function On(e,t){let n=In.exec(e);if(n!==null)return`${n[1]}-${n[2]}.md`;let s=t.getUTCFullYear(),o=`${t.getUTCMonth()+1}`.padStart(2,"0");return`${s}-${o}.md`}function Ln(e,t){let n=e.split(/\r?\n/),s=Rn(n),o=[],d=s,l=e,c=ae(l);while(c>t&&d.length>1){let m=d[0];if(m===void 0)break;o.push(m),d=d.slice(1),l=Mn(n,o),c=ae(l)}if(c<=t)return{evict:o,remaining:l,tokens:c};return{evict:o,remaining:l,tokens:c,shortfall:d.length<=1?`${c} tokens remain against a ${t}-token budget with one note left, so eviction cannot help`:`${c} tokens remain against a ${t}-token budget`}}function Mn(e,t){let n=new Set;for(let s of t)for(let o=s.start;o<s.end;o+=1)n.add(o);return e.filter((s,o)=>!n.has(o)).join(`
39
39
  `).replace(/\n{3,}/g,`
40
40
 
41
41
  `)}async function Cn(e){let t=e.tags.length===0?"":` _(${e.tags.join(", ")})_`,n=`
42
42
  - **${e.now.toISOString()}**${t} ${e.text}
43
- `;await qe(e.path,n,"utf8");let s=await Sn(e.path,"utf8"),o=Ln(s,e.budget);if(o.evict.length===0)return{file:e.name,evicted:0,archives:[],...o.shortfall===void 0?{}:{shortfall:o.shortfall}};let d=new Map;for(let l of o.evict){let c=Rn(l.text,e.now);d.set(c,[...d.get(c)??[],l.text])}await An(e.archiveDir,{recursive:!0});for(let[l,c]of d)await qe($n(e.archiveDir,l),`${c.join(`
43
+ `;await qe(e.path,n,"utf8");let s=await Sn(e.path,"utf8"),o=Ln(s,e.budget);if(o.evict.length===0)return{file:e.name,evicted:0,archives:[],...o.shortfall===void 0?{}:{shortfall:o.shortfall}};let d=new Map;for(let l of o.evict){let c=On(l.text,e.now);d.set(c,[...d.get(c)??[],l.text])}await An(e.archiveDir,{recursive:!0});for(let[l,c]of d)await qe(xn(e.archiveDir,l),`${c.join(`
44
44
  `)}
45
- `,"utf8");return await xn(e.path,o.remaining,"utf8"),{file:e.name,evicted:o.evict.length,archives:[...d.keys()].sort(),...o.shortfall===void 0?{}:{shortfall:o.shortfall}}}var de="local",Ye="memory",ze="notes.md",Dn={spec:{slug:"now",provider:de,summary:"Reports the current date and time.",whenToUse:"you need today's date or the current time — including to work out what 'tomorrow' or 'in three hours' means",whenNotToUse:"the person already told you the date or time; use theirs rather than replacing it with the clock",mutating:!1,tags:["read","time"],parameters:{type:"object",properties:{timezone:{type:"string",description:"IANA name such as Europe/London. Defaults to UTC."},format:{type:"string",description:"iso for a machine-readable timestamp, human for a readable one",enum:["iso","human"],default:"iso"}}}},handler(e,t){let n=t.now(),s=typeof e.timezone==="string"&&e.timezone!==""?e.timezone:"UTC";if(e.format==="human")return`${new Intl.DateTimeFormat("en-GB",{dateStyle:"full",timeStyle:"short",timeZone:s}).format(n)} (${s})`;if(s==="UTC")return n.toISOString();return`${Pn(n,s)} (${s})`}};function Pn(e,t){let n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"longOffset"}).formatToParts(e),s=(d)=>n.find((l)=>l.type===d)?.value??"",o=s("timeZoneName").replace("GMT","");return`${s("year")}-${s("month")}-${s("day")}T${s("hour")}:${s("minute")}:${s("second")}${o===""?"Z":o}`}var Wn={spec:{slug:"memory_write",provider:de,summary:"Saves a short note for later recall.",whenToUse:"the person tells you something durable about themselves or their work that later conversations should know",whenNotToUse:"for anything already in this conversation, for secrets or credentials, or to store your own reasoning",mutating:!0,tags:["write","memory"],parameters:{type:"object",properties:{text:{type:"string",description:"The note, in one or two sentences."},tags:{type:"array",items:{type:"string"},description:"Optional labels."}},required:["text"]}},async handler(e,t){let n=typeof e.text==="string"?e.text.trim():"",s=Array.isArray(e.tags)?e.tags.map((u)=>String(u)):[],o=t.now().toISOString(),d=s.length===0?"":` _(${s.join(", ")})_`,l=`
45
+ `,"utf8");return await $n(e.path,o.remaining,"utf8"),{file:e.name,evicted:o.evict.length,archives:[...d.keys()].sort(),...o.shortfall===void 0?{}:{shortfall:o.shortfall}}}var le="local",Ye="memory",ze="notes.md",Dn={spec:{slug:"now",provider:le,summary:"Reports the current date and time.",whenToUse:"you need today's date or the current time — including to work out what 'tomorrow' or 'in three hours' means",whenNotToUse:"the person already told you the date or time; use theirs rather than replacing it with the clock",mutating:!1,tags:["read","time"],parameters:{type:"object",properties:{timezone:{type:"string",description:"IANA name such as Europe/London. Defaults to UTC."},format:{type:"string",description:"iso for a machine-readable timestamp, human for a readable one",enum:["iso","human"],default:"iso"}}}},handler(e,t){let n=t.now(),s=typeof e.timezone==="string"&&e.timezone!==""?e.timezone:"UTC";if(e.format==="human")return`${new Intl.DateTimeFormat("en-GB",{dateStyle:"full",timeStyle:"short",timeZone:s}).format(n)} (${s})`;if(s==="UTC")return n.toISOString();return`${Pn(n,s)} (${s})`}};function Pn(e,t){let n=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1,timeZoneName:"longOffset"}).formatToParts(e),s=(d)=>n.find((l)=>l.type===d)?.value??"",o=s("timeZoneName").replace("GMT","");return`${s("year")}-${s("month")}-${s("day")}T${s("hour")}:${s("minute")}:${s("second")}${o===""?"Z":o}`}var Wn={spec:{slug:"memory_write",provider:le,summary:"Saves a short note for later recall.",whenToUse:"the person tells you something durable about themselves or their work that later conversations should know",whenNotToUse:"for anything already in this conversation, for secrets or credentials, or to store your own reasoning",mutating:!0,tags:["write","memory"],parameters:{type:"object",properties:{text:{type:"string",description:"The note, in one or two sentences."},tags:{type:"array",items:{type:"string"},description:"Optional labels."}},required:["text"]}},async handler(e,t){let n=typeof e.text==="string"?e.text.trim():"",s=Array.isArray(e.tags)?e.tags.map((u)=>String(u)):[],o=t.now().toISOString(),d=s.length===0?"":` _(${s.join(", ")})_`,l=`
46
46
  - **${o}**${d} ${n}
47
- `,c=t.writeTarget;if(c?.mode==="refused")throw we(c.name,c.reason??"none");if(c?.path!==void 0){if(c.budget!==void 0&&t.memoryDir!==void 0&&c.eviction==="oldest"){let u=await Cn({path:c.path,name:c.name,budget:c.budget,archiveDir:t.memoryDir,text:n,tags:s,now:t.now()});if(u.shortfall!==void 0)return`Saved to ${u.file}, but it is still over budget: ${u.shortfall}. Ask the person to raise the budget or shorten the file — the agent will not load until they do.`;if(u.evicted===0)return`Saved to ${u.file}.`;return`Saved to ${u.file}. Moved ${u.evicted} older ${u.evicted===1?"note":"notes"} into ${u.archives.join(", ")}, still searchable.`}if(await Xe(c.path,l,"utf8"),c.budget!==void 0){let u=ie(await _n(c.path,"utf8"))-c.budget;if(u>0)return`Saved to ${c.name}, which is now ${u} tokens over its ${c.budget}-token budget. The agent will not load until that is fixed: add \`eviction: oldest\` to its frontmatter so older notes move to the memory directory, or raise the budget.`}return`Saved to ${c.name}.`}let m=Ge(t.dir,Ye);return await En(m,{recursive:!0}),await Xe(Ge(m,ze),l,"utf8"),`Saved to ${Ye}/${ze}.`}},Hn=1200,Xn=Hn*3,Gn={spec:{slug:"artifact_read",provider:de,summary:"Reads back a tool result that compaction replaced with a pointer.",whenToUse:"a compaction marker in this conversation names an id, and you need the tool result it replaced",whenNotToUse:"for anything still written out in the conversation, or to explore — every id comes from a marker, so there is nothing to browse",mutating:!1,tags:["read","context"],parameters:{type:"object",properties:{id:{type:"string",description:"The id printed inside the compaction marker, copied character for character."},from:{type:"integer",description:"Character offset to continue from. Omit for the beginning; a truncated reply says the number to pass."}},required:["id"]}},async handler(e,t){let n=typeof e.id==="string"?e.id.trim():"",s=typeof e.from==="number"&&e.from>0?Math.floor(e.from):0;if(t.readArtifact===void 0)throw be();let o=await t.readArtifact(n);if(o===void 0)throw ve(n);let d=o.slug===void 0?"observation":`${o.slug} observation`,l=o.content.slice(s,s+Xn),c=s+l.length,m=`Compacted ${d}, ${o.tokens} tokens${s===0?"":`, from character ${s}`}:`;if(c>=o.content.length)return`${m}
47
+ `,c=t.writeTarget;if(c?.mode==="refused")throw be(c.name,c.reason??"none");if(c?.path!==void 0){if(c.budget!==void 0&&t.memoryDir!==void 0&&c.eviction==="oldest"){let u=await Cn({path:c.path,name:c.name,budget:c.budget,archiveDir:t.memoryDir,text:n,tags:s,now:t.now()});if(u.shortfall!==void 0)return`Saved to ${u.file}, but it is still over budget: ${u.shortfall}. Ask the person to raise the budget or shorten the file — the agent will not load until they do.`;if(u.evicted===0)return`Saved to ${u.file}.`;return`Saved to ${u.file}. Moved ${u.evicted} older ${u.evicted===1?"note":"notes"} into ${u.archives.join(", ")}, still searchable.`}if(await Xe(c.path,l,"utf8"),c.budget!==void 0){let u=ae(await _n(c.path,"utf8"))-c.budget;if(u>0)return`Saved to ${c.name}, which is now ${u} tokens over its ${c.budget}-token budget. The agent will not load until that is fixed: add \`eviction: oldest\` to its frontmatter so older notes move to the memory directory, or raise the budget.`}return`Saved to ${c.name}.`}let m=Ge(t.dir,Ye);return await En(m,{recursive:!0}),await Xe(Ge(m,ze),l,"utf8"),`Saved to ${Ye}/${ze}.`}},Hn=1200,Xn=Hn*3,Gn={spec:{slug:"artifact_read",provider:le,summary:"Reads back a tool result that compaction replaced with a pointer.",whenToUse:"a compaction marker in this conversation names an id, and you need the tool result it replaced",whenNotToUse:"for anything still written out in the conversation, or to explore — every id comes from a marker, so there is nothing to browse",mutating:!1,tags:["read","context"],parameters:{type:"object",properties:{id:{type:"string",description:"The id printed inside the compaction marker, copied character for character."},from:{type:"integer",description:"Character offset to continue from. Omit for the beginning; a truncated reply says the number to pass."}},required:["id"]}},async handler(e,t){let n=typeof e.id==="string"?e.id.trim():"",s=typeof e.from==="number"&&e.from>0?Math.floor(e.from):0;if(t.readArtifact===void 0)throw ve();let o=await t.readArtifact(n);if(o===void 0)throw ke(n);let d=o.slug===void 0?"observation":`${o.slug} observation`,l=o.content.slice(s,s+Xn),c=s+l.length,m=`Compacted ${d}, ${o.tokens} tokens${s===0?"":`, from character ${s}`}:`;if(c>=o.content.length)return`${m}
48
48
  ${l}`;return`${m}
49
49
  ${l}
50
50
 
51
- [cut here — ${o.content.length-c} characters remain; continue with artifact_read(id, from: ${c})]`}};var qn=[Dn,Wn,Gn],Ao=qn.map((e)=>e.spec.slug);function Jn(e){let t=e.providers??{},n=Object.keys(t),s=e.provider,o=e.providerConfig??{};if(n.length>0&&(s!==void 0||Object.keys(o).length>0))throw ye(n,s);if(s!==void 0)return{selections:[{id:s,config:o,legacy:!0}],warnings:[{code:"tools_provider_deprecated",message:`tools.provider is deprecated; "${s}" was loaded as tools.providers.${s}.`,hint:`Rewrite it as:
51
+ [cut here — ${o.content.length-c} characters remain; continue with artifact_read(id, from: ${c})]`}};var qn=[Dn,Wn,Gn],So=qn.map((e)=>e.spec.slug);function Jn(e){let t=e.providers??{},n=Object.keys(t),s=e.provider,o=e.providerConfig??{};if(n.length>0&&(s!==void 0||Object.keys(o).length>0))throw we(n,s);if(s!==void 0)return{selections:[{id:s,config:o,legacy:!0}],warnings:[{code:"tools_provider_deprecated",message:`tools.provider is deprecated; "${s}" was loaded as tools.providers.${s}.`,hint:`Rewrite it as:
52
52
  tools:
53
53
  providers:
54
54
  ${s}: { … the contents of providerConfig … }
55
- The scalar permits exactly one provider, which is why an agent could not have the shell and the web at the same time. It still works and will keep working for now; nothing about the resolved catalogue changes.`,field:"tools.provider"}]};let d=n.map((l)=>({id:l,config:t[l]??{},legacy:!1}));if(Object.keys(o).length>0)return{selections:d,warnings:[{code:"tools_provider_config_orphaned",message:`tools.providerConfig has ${Object.keys(o).length} setting(s) and no tools.provider names a provider to apply them to, so they do nothing.`,hint:"Move them into the matching tools.providers.<id> block and delete tools.providerConfig. Reported rather than ignored: a configuration that looks applied and is not is worse than one that fails.",field:"tools.providerConfig"}]};return{selections:d,warnings:[]}}var Ve=new Map;function st(e){let t=Ve.get(e);if(t!==void 0)return t;let n;try{n=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch(s){throw new y({code:"schedule_timezone_unknown",message:`"${e}" is not a timezone this runtime recognises.`,hint:"Use an IANA name such as Asia/Dhaka, Europe/London or America/Sao_Paulo — not an abbreviation like BST and not a UTC offset. Omit the field to use the TZ environment variable, then UTC.",field:"timezone",cause:s})}return Ve.set(e,n),n}function Zn(e){st(e)}function G(e,t){let n=st(e).formatToParts(new Date(t)),s=(c)=>{let m=n.find((u)=>u.type===c);return m===void 0?0:Number(m.value)},o=s("year"),d=s("month"),l=s("day");return{year:o,month:d,day:l,hour:s("hour"),minute:s("minute"),second:s("second"),weekday:new Date(Date.UTC(o,d-1,l)).getUTCDay()}}function Qn(e,t){return G(e,t)}function Je(e,t){let n=G(e,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-(t-t%1000)}function es(e,t){let n=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second),s=n-Je(e,n);s=n-Je(e,s);let o=G(e,s);if(!(o.year===t.year&&o.month===t.month&&o.day===t.day&&o.hour===t.hour&&o.minute===t.minute&&o.second===t.second))return;let l=s-3600000,c=G(e,l);return c.year===t.year&&c.month===t.month&&c.day===t.day&&c.hour===t.hour&&c.minute===t.minute&&c.second===t.second?l:s}function ts(){return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}var ns=1462,ot=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],ss=["sun","mon","tue","wed","thu","fri","sat"],O={second:{min:0,max:59,label:"second"},minute:{min:0,max:59,label:"minute"},hour:{min:0,max:23,label:"hour"},dayOfMonth:{min:1,max:31,label:"day of month"},month:{min:1,max:12,names:ot,label:"month"},dayOfWeek:{min:0,max:7,names:ss,label:"day of week"}};function x(e,t,n,s){throw new y({code:"schedule_cron_malformed",message:`"${e}" is not a valid cron expression: ${t}`,hint:n,field:s})}function te(e,t,n,s){let o=t.names?.indexOf(e.toLowerCase());if(o!==void 0&&o!==-1)return o+(t.names===ot?1:0);if(!/^\d+$/.test(e))x(n,`"${e}" is not a ${t.label}.`,t.names===void 0?`The ${t.label} field takes numbers ${t.min}-${t.max}, ranges, steps and comma lists.`:`The ${t.label} field takes ${t.min}-${t.max} or a name (${t.names.slice(0,3).join(", ")}…).`,s);let d=Number(e);if(d<t.min||d>t.max)x(n,`${d} is outside the ${t.label} range ${t.min}-${t.max}.`,`Check the field order: ${t.label==="second"?"second minute hour day-of-month month day-of-week":"minute hour day-of-month month day-of-week"}.`,s);return d}function R(e,t,n,s){let o=new Set,d=!0;for(let l of e.split(",")){let c=l.trim();if(c==="")x(n,"an empty entry in a comma list.","Remove the stray comma.",s);let[m="",u]=c.split("/",2),k=u===void 0?1:Number(u);if(u!==void 0&&(!/^\d+$/.test(u)||k<1))x(n,`"${u}" is not a step.`,"A step is a whole number above zero, as in */15.",s);let p,w;if(m==="*"){if(p=t.min,w=t.max,k===1)d=!1}else if(m.includes("-")){let[b="",T=""]=m.split("-",2);if(p=te(b,t,n,s),w=te(T,t,n,s),p>w)x(n,`the range ${m} runs backwards.`,"Write the lower bound first, or use a comma list to wrap around.",s)}else p=te(m,t,n,s),w=u===void 0?p:t.max;for(let b=p;b<=w;b+=k)o.add(b)}if(o.size===0)x(n,"it matches nothing.","Every field must admit at least one value.",s);return{values:o,restricted:d}}function rs(e,t){let n=e.trim();if(n.startsWith("@"))x(n,"macros are not supported.",'Write the fields out — @daily is "0 0 * * *", @hourly is "0 * * * *", @weekly is "0 0 * * 0". For a plain interval use kind: every with an expression like 24h.',t);let s=n.split(/\s+/).filter((W)=>W!=="");if(s.length!==5&&s.length!==6)x(n,`it has ${s.length} field${s.length===1?"":"s"}, not 5 or 6.`,"Five fields are minute hour day-of-month month day-of-week. A sixth leading field is seconds.",t);let o=s.length===6,[d,l,c,m,u,k]=o?s:["0",...s],p=R(d??"0",O.second,n,t),w=R(l??"",O.minute,n,t),b=R(c??"",O.hour,n,t),T=R(m??"",O.dayOfMonth,n,t),E=R(u??"",O.month,n,t),A=R(k??"",O.dayOfWeek,n,t),ue=new Set;for(let W of A.values)ue.add(W===7?0:W);return{seconds:p.values,minutes:w.values,hours:b.values,daysOfMonth:T.values,months:E.values,daysOfWeek:ue,domRestricted:T.restricted,dowRestricted:A.restricted,source:n}}function os(e,t,n){let s=e.daysOfMonth.has(t),o=e.daysOfWeek.has(n);if(e.domRestricted&&e.dowRestricted)return s||o;if(e.domRestricted)return s;if(e.dowRestricted)return o;return!0}function Ze(e,t,n,s){let o=new Date(Date.UTC(e,t-1,n+s));return[o.getUTCFullYear(),o.getUTCMonth()+1,o.getUTCDate()]}function is(e,t,n){return new Date(Date.UTC(e,t-1,n)).getUTCDay()}function D(e,t,n){let s=Qn(n,t+1000),o=new Date(Date.UTC(s.year,s.month-1,s.day+ns)),[d,l,c]=[s.year,s.month,s.day],m=!0;while(Date.UTC(d,l-1,c)<=o.getTime()){if(!e.months.has(l)){[d,l,c]=l===12?[d+1,1,1]:[d,l+1,1],m=!1;continue}if(!os(e,c,is(d,l,c))){[d,l,c]=Ze(d,l,c,1),m=!1;continue}for(let u of[...e.hours].sort((k,p)=>k-p)){if(m&&u<s.hour)continue;for(let k of[...e.minutes].sort((p,w)=>p-w)){if(m&&u===s.hour&&k<s.minute)continue;for(let p of[...e.seconds].sort((w,b)=>w-b)){if(m&&u===s.hour&&k===s.minute&&p<s.second)continue;let w=es(n,{year:d,month:l,day:c,hour:u,minute:k,second:p});if(w!==void 0)return w}}}[d,l,c]=Ze(d,l,c,1),m=!1}return}var as=/^(\d+)(s|m|h|d)$/,ds={s:1000,m:60000,h:3600000,d:86400000},ls=1000,cs=315360000000;function us(e,t){let n=as.exec(e.trim());if(n===null)throw new y({code:"schedule_duration_malformed",message:`"${e}" is not a duration.`,hint:"A duration is a whole number and one unit: 90s, 15m, 2h, 7d. There is no combined form — write 90m rather than 1h30m.",field:t});let s=Number(n[1]),o=n[2]??"",d=s*(ds[o]??0);if(d<ls)throw new y({code:"schedule_duration_too_small",message:`"${e}" is under the one-second minimum.`,hint:"An interval below a second is a busy loop rather than a schedule. If the intent is to run continuously, a schedule is the wrong mechanism.",field:t});if(d>cs)throw new y({code:"schedule_duration_too_large",message:`"${e}" is over the ten-year maximum.`,hint:"An interval this long is almost always a unit typo — check whether d was meant where h was written.",field:t});return{ms:d,source:e.trim()}}var hs=315360000000,fs=900000,ne=1000;function it(e){let t=e.timezone??ts();Zn(t);let n=e.expr.trim();if(e.kind==="cron"){let o=rs(n,e.field);if(D(o,e.now,t)===void 0)throw new y({code:"schedule_cron_unsatisfiable",message:`"${n}" never matches a real date.`,hint:"The expression parses but names a day that does not occur — 30 February, or a weekday-and-date pair that never coincide. Checked over four years, so a leap-year schedule like 0 3 29 2 * is accepted.",field:e.field});return{kind:"cron",spec:o,zone:t,source:n}}if(e.kind==="every")return{kind:"every",every:us(n,e.field),zone:t,source:n};let s=Date.parse(n);if(Number.isNaN(s))throw new y({code:"schedule_at_malformed",message:`"${n}" is not an ISO 8601 instant.`,hint:"Write a full timestamp with an offset, as in 2026-12-25T09:00:00+06:00 or 2026-12-25T03:00:00Z. A bare date has no time of day.",field:e.field});if(s>e.now+hs)throw new y({code:"schedule_at_too_far",message:`${n} is more than ten years away.`,hint:"A one-shot this far out is almost always a year typo. Ten years is the documented bound.",field:e.field});return{kind:"at",at:s,zone:t,source:n}}function ms(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t}function ps(e,t){if(t===void 0||t<=0)return 0;let n=Math.min(Math.floor(t/10),fs);return n<=0?0:ms(e)%n}function gs(e,t){if(e.kind==="every")return e.every.ms;if(e.kind==="at")return;let n=D(e.spec,t,e.zone);if(n===void 0)return;let s=D(e.spec,n,e.zone);return s===void 0?void 0:s-n}function ys(e,t,n,s,o={}){if(e.kind==="at"){if(o.consumed===!0)return{runAt:void 0,anchor:void 0,missed:0,missedCapped:!1,late:!1};if(e.at<=s)return{runAt:s,anchor:e.at,missed:0,missedCapped:!1,late:!0};return{runAt:e.at,anchor:e.at,missed:0,missedCapped:!1,late:!1}}let d=ps(t,gs(e,n));if(e.kind==="every"){let u=s-n,k=u<=0?0:Math.floor(u/e.every.ms),p=Math.min(k,ne),w=k+1,b=n+w*e.every.ms;return{runAt:b+d,anchor:b,missed:p,missedCapped:k>ne,late:!1}}let l=n,c=0,m=!1;for(;;){let u=D(e.spec,l,e.zone);if(u===void 0)return{runAt:void 0,anchor:void 0,missed:c,missedCapped:m,late:!1};if(u+d>s)return{runAt:u+d,anchor:u,missed:c,missedCapped:m,late:!1};if(l=u,c+=1,c>=ne){m=!0;let k=D(e.spec,s,e.zone);return{runAt:k===void 0?void 0:k+d,anchor:k,missed:c,missedCapped:!0,late:!1}}}}function ws(e,t,n){let s=[],o=Array.isArray(e.schedules)?e.schedules:[],d=new Set((Array.isArray(e.channels)?e.channels:[]).map((u)=>u!==null&&typeof u==="object"&&!Array.isArray(u)?u.id:void 0).filter((u)=>typeof u==="string")),l=new Set([...oe,...Ke(t.model)]),c=new Set,m=new Set;for(let[u,k]of o.entries()){if(k===null||typeof k!=="object"||Array.isArray(k))continue;let p=k,w=typeof p.id==="string"?p.id:`[${u}]`;if(m.has(w))s.push({code:"schedule_id_duplicate",message:`Two schedules share the id "${w}".`,hint:"A schedule id is the key reconciliation matches on and the segment of its session key, so it must be unique within an agent.",field:`schedules[${u}].id`});m.add(w);let b=p.deliver;if(b===void 0)s.push({code:"schedule_missing_delivery",message:`Schedule "${w}" has no delivery target.`,hint:'Set deliver to { channel, to }, or the literal "none" to return results only via the event stream.',field:`schedules[${u}].deliver`});else if(b!=="none"&&typeof b==="object"&&!Array.isArray(b)){let A=b.channel;if(typeof A==="string"&&!d.has(A))s.push({code:"schedule_delivery_channel_unknown",message:`Schedule "${w}" delivers to "${A}", which is not a channel id on this agent.${d.size===0?" The agent declares no channels.":` Declared: ${[...d].join(", ")}.`}`,hint:`A delivery target names a channel's id, not its type. Use deliver: "none" to return results through the event stream instead.`,field:`schedules[${u}].deliver.channel`})}let T=p.role;if(typeof T==="string"){if(c.add(T),!l.has(T))s.push({code:"schedule_role_unknown",message:`Schedule "${w}" names the model role "${T}", which is not declared under model:. Declared: ${[...l].join(", ")}.`,hint:"Add the role under model:, or point the schedule at one of the declared roles. Omit role entirely to use main.",field:`schedules[${u}].role`})}let E=t.schedules[u];if(E!==void 0)try{it({id:E.id,kind:E.kind,expr:E.expr,timezone:E.timezone,now:n,field:`schedules[${u}].expr`})}catch(A){if(!(A instanceof z))throw A;s.push(A.toDetail())}}for(let u of Ke(t.model)){if(c.has(u))continue;s.push({code:"model_role_unreferenced",message:`model.${u} is declared but no schedule names it, so nothing will ever use it.`,hint:`If "${u}" was meant to be one of ${oe.join(", ")}, it is misspelled — and the misspelled one is silently falling back to main. Otherwise point a schedule at it with role: ${u}, or remove it.`,field:`model.${u}`})}return s}function at(e){if(typeof e!=="string")return String(e);let t=/^[A-Za-z0-9_./@~-]+$/.test(e),n=/^[A-Za-z0-9_./]/.test(e);if(!t||!n)return JSON.stringify(e);try{return F(e)===e?e:JSON.stringify(e)}catch{return JSON.stringify(e)}}function j(e){return e.length-e.trimStart().length}function le(e){let t=e.trim();return t===""||t.startsWith("#")}function Qe(e,t,n,s){let o=new RegExp(`^\\s{${n}}${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*:`);for(let d=s;d<e.length;d+=1){let l=e[d]??"";if(le(l))continue;if(j(l)<n)return;if(j(l)===n&&o.test(l))return d}return}function se(e,t,n){let s=t;for(let o=t+1;o<e.length;o+=1){let d=e[o]??"";if(le(d))continue;if(j(d)<=n)break;s=o}return s}function bs(e){let t;for(let n=0;n<e.length;n+=1){let s=e[n];if(t!==void 0){if(s===t)t=void 0;continue}if(s==='"'||s==="'"){t=s;continue}if(s!=="#"||n===0||!/\s/.test(e[n-1]??""))continue;let o=n;while(o>0&&/\s/.test(e[o-1]??""))o-=1;return e.slice(o)}return""}function ce(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function L(e,t,n){let s=" ".repeat(n);if(Array.isArray(t)){if(t.length===0)return[`${s}${e}: []`];return[`${s}${e}:`,...t.flatMap((o)=>vs(o,n+2))]}if(ce(t)){let o=Object.entries(t);if(o.length===0)return[`${s}${e}: {}`];return[`${s}${e}:`,...o.flatMap(([d,l])=>L(d,l,n+2))]}return[`${s}${e}: ${at(t)}`]}function vs(e,t){let n=" ".repeat(t);if(!ce(e))return[`${n}- ${at(e)}`];let s=Object.entries(e);if(s.length===0)return[`${n}- {}`];let o=s.flatMap(([c,m])=>L(c,m,t+2)),[d,...l]=o;return[`${n}- ${(d??"").trimStart()}`,...l]}function ks(e,t,n){if(t.length===0)return;let s=e.split(`
56
- `),o=0,d=0,l,c=0;for(;c<t.length-1;c+=1){let p=Qe(s,t[c]??"",d,o);if(p===void 0)break;l=p,o=p+1;let w=s.slice(p+1).find((b)=>!le(b)&&j(b)>d);if(w===void 0)return;d=j(w)}if(c<t.length-1){if(l===void 0)return;let p=se(s,l,d-1)+1;return[...s.slice(0,p),...dt(t.slice(c),n,d),...s.slice(p)].join(`
57
- `)}let m=t[t.length-1]??"",u=Qe(s,m,d,o);if(u!==void 0){let p=s[u]??"",w=Array.isArray(n)||ce(n)?"":bs(p),b=se(s,u,d),T=L(m,n,d);if(w!=="")T[0]=`${T[0]}${w}`;return[...s.slice(0,u),...T,...s.slice(b+1)].join(`
58
- `)}if(l===void 0)return;let k=se(s,l,d-1)+1;return[...s.slice(0,k),...L(m,n,d),...s.slice(k)].join(`
55
+ The scalar permits exactly one provider, which is why an agent could not have the shell and the web at the same time. It still works and will keep working for now; nothing about the resolved catalogue changes.`,field:"tools.provider"}]};let d=n.map((l)=>({id:l,config:t[l]??{},legacy:!1}));if(Object.keys(o).length>0)return{selections:d,warnings:[{code:"tools_provider_config_orphaned",message:`tools.providerConfig has ${Object.keys(o).length} setting(s) and no tools.provider names a provider to apply them to, so they do nothing.`,hint:"Move them into the matching tools.providers.<id> block and delete tools.providerConfig. Reported rather than ignored: a configuration that looks applied and is not is worse than one that fails.",field:"tools.providerConfig"}]};return{selections:d,warnings:[]}}var Ve=new Map;function st(e){let t=Ve.get(e);if(t!==void 0)return t;let n;try{n=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"})}catch(s){throw new y({code:"schedule_timezone_unknown",message:`"${e}" is not a timezone this runtime recognises.`,hint:"Use an IANA name such as Asia/Dhaka, Europe/London or America/Sao_Paulo — not an abbreviation like BST and not a UTC offset. Omit the field to use the TZ environment variable, then UTC.",field:"timezone",cause:s})}return Ve.set(e,n),n}function Zn(e){st(e)}function G(e,t){let n=st(e).formatToParts(new Date(t)),s=(c)=>{let m=n.find((u)=>u.type===c);return m===void 0?0:Number(m.value)},o=s("year"),d=s("month"),l=s("day");return{year:o,month:d,day:l,hour:s("hour"),minute:s("minute"),second:s("second"),weekday:new Date(Date.UTC(o,d-1,l)).getUTCDay()}}function Qn(e,t){return G(e,t)}function Je(e,t){let n=G(e,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-(t-t%1000)}function es(e,t){let n=Date.UTC(t.year,t.month-1,t.day,t.hour,t.minute,t.second),s=n-Je(e,n);s=n-Je(e,s);let o=G(e,s);if(!(o.year===t.year&&o.month===t.month&&o.day===t.day&&o.hour===t.hour&&o.minute===t.minute&&o.second===t.second))return;let l=s-3600000,c=G(e,l);return c.year===t.year&&c.month===t.month&&c.day===t.day&&c.hour===t.hour&&c.minute===t.minute&&c.second===t.second?l:s}function ts(){return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}var ns=1462,ot=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],ss=["sun","mon","tue","wed","thu","fri","sat"],R={second:{min:0,max:59,label:"second"},minute:{min:0,max:59,label:"minute"},hour:{min:0,max:23,label:"hour"},dayOfMonth:{min:1,max:31,label:"day of month"},month:{min:1,max:12,names:ot,label:"month"},dayOfWeek:{min:0,max:7,names:ss,label:"day of week"}};function x(e,t,n,s){throw new y({code:"schedule_cron_malformed",message:`"${e}" is not a valid cron expression: ${t}`,hint:n,field:s})}function ne(e,t,n,s){let o=t.names?.indexOf(e.toLowerCase());if(o!==void 0&&o!==-1)return o+(t.names===ot?1:0);if(!/^\d+$/.test(e))x(n,`"${e}" is not a ${t.label}.`,t.names===void 0?`The ${t.label} field takes numbers ${t.min}-${t.max}, ranges, steps and comma lists.`:`The ${t.label} field takes ${t.min}-${t.max} or a name (${t.names.slice(0,3).join(", ")}…).`,s);let d=Number(e);if(d<t.min||d>t.max)x(n,`${d} is outside the ${t.label} range ${t.min}-${t.max}.`,`Check the field order: ${t.label==="second"?"second minute hour day-of-month month day-of-week":"minute hour day-of-month month day-of-week"}.`,s);return d}function O(e,t,n,s){let o=new Set,d=!0;for(let l of e.split(",")){let c=l.trim();if(c==="")x(n,"an empty entry in a comma list.","Remove the stray comma.",s);let[m="",u]=c.split("/",2),k=u===void 0?1:Number(u);if(u!==void 0&&(!/^\d+$/.test(u)||k<1))x(n,`"${u}" is not a step.`,"A step is a whole number above zero, as in */15.",s);let p,w;if(m==="*"){if(p=t.min,w=t.max,k===1)d=!1}else if(m.includes("-")){let[b="",T=""]=m.split("-",2);if(p=ne(b,t,n,s),w=ne(T,t,n,s),p>w)x(n,`the range ${m} runs backwards.`,"Write the lower bound first, or use a comma list to wrap around.",s)}else p=ne(m,t,n,s),w=u===void 0?p:t.max;for(let b=p;b<=w;b+=k)o.add(b)}if(o.size===0)x(n,"it matches nothing.","Every field must admit at least one value.",s);return{values:o,restricted:d}}function rs(e,t){let n=e.trim();if(n.startsWith("@"))x(n,"macros are not supported.",'Write the fields out — @daily is "0 0 * * *", @hourly is "0 * * * *", @weekly is "0 0 * * 0". For a plain interval use kind: every with an expression like 24h.',t);let s=n.split(/\s+/).filter((H)=>H!=="");if(s.length!==5&&s.length!==6)x(n,`it has ${s.length} field${s.length===1?"":"s"}, not 5 or 6.`,"Five fields are minute hour day-of-month month day-of-week. A sixth leading field is seconds.",t);let o=s.length===6,[d,l,c,m,u,k]=o?s:["0",...s],p=O(d??"0",R.second,n,t),w=O(l??"",R.minute,n,t),b=O(c??"",R.hour,n,t),T=O(m??"",R.dayOfMonth,n,t),E=O(u??"",R.month,n,t),A=O(k??"",R.dayOfWeek,n,t),he=new Set;for(let H of A.values)he.add(H===7?0:H);return{seconds:p.values,minutes:w.values,hours:b.values,daysOfMonth:T.values,months:E.values,daysOfWeek:he,domRestricted:T.restricted,dowRestricted:A.restricted,source:n}}function os(e,t,n){let s=e.daysOfMonth.has(t),o=e.daysOfWeek.has(n);if(e.domRestricted&&e.dowRestricted)return s||o;if(e.domRestricted)return s;if(e.dowRestricted)return o;return!0}function Ze(e,t,n,s){let o=new Date(Date.UTC(e,t-1,n+s));return[o.getUTCFullYear(),o.getUTCMonth()+1,o.getUTCDate()]}function is(e,t,n){return new Date(Date.UTC(e,t-1,n)).getUTCDay()}function j(e,t,n){let s=Qn(n,t+1000),o=new Date(Date.UTC(s.year,s.month-1,s.day+ns)),[d,l,c]=[s.year,s.month,s.day],m=!0;while(Date.UTC(d,l-1,c)<=o.getTime()){if(!e.months.has(l)){[d,l,c]=l===12?[d+1,1,1]:[d,l+1,1],m=!1;continue}if(!os(e,c,is(d,l,c))){[d,l,c]=Ze(d,l,c,1),m=!1;continue}for(let u of[...e.hours].sort((k,p)=>k-p)){if(m&&u<s.hour)continue;for(let k of[...e.minutes].sort((p,w)=>p-w)){if(m&&u===s.hour&&k<s.minute)continue;for(let p of[...e.seconds].sort((w,b)=>w-b)){if(m&&u===s.hour&&k===s.minute&&p<s.second)continue;let w=es(n,{year:d,month:l,day:c,hour:u,minute:k,second:p});if(w!==void 0)return w}}}[d,l,c]=Ze(d,l,c,1),m=!1}return}var as=/^(\d+)(s|m|h|d)$/,ds={s:1000,m:60000,h:3600000,d:86400000},ls=1000,cs=315360000000;function us(e,t){let n=as.exec(e.trim());if(n===null)throw new y({code:"schedule_duration_malformed",message:`"${e}" is not a duration.`,hint:"A duration is a whole number and one unit: 90s, 15m, 2h, 7d. There is no combined form — write 90m rather than 1h30m.",field:t});let s=Number(n[1]),o=n[2]??"",d=s*(ds[o]??0);if(d<ls)throw new y({code:"schedule_duration_too_small",message:`"${e}" is under the one-second minimum.`,hint:"An interval below a second is a busy loop rather than a schedule. If the intent is to run continuously, a schedule is the wrong mechanism.",field:t});if(d>cs)throw new y({code:"schedule_duration_too_large",message:`"${e}" is over the ten-year maximum.`,hint:"An interval this long is almost always a unit typo — check whether d was meant where h was written.",field:t});return{ms:d,source:e.trim()}}var hs=315360000000,fs=900000,se=1000;function it(e){let t=e.timezone??ts();Zn(t);let n=e.expr.trim();if(e.kind==="cron"){let o=rs(n,e.field);if(j(o,e.now,t)===void 0)throw new y({code:"schedule_cron_unsatisfiable",message:`"${n}" never matches a real date.`,hint:"The expression parses but names a day that does not occur — 30 February, or a weekday-and-date pair that never coincide. Checked over four years, so a leap-year schedule like 0 3 29 2 * is accepted.",field:e.field});return{kind:"cron",spec:o,zone:t,source:n}}if(e.kind==="every")return{kind:"every",every:us(n,e.field),zone:t,source:n};let s=Date.parse(n);if(Number.isNaN(s))throw new y({code:"schedule_at_malformed",message:`"${n}" is not an ISO 8601 instant.`,hint:"Write a full timestamp with an offset, as in 2026-12-25T09:00:00+06:00 or 2026-12-25T03:00:00Z. A bare date has no time of day.",field:e.field});if(s>e.now+hs)throw new y({code:"schedule_at_too_far",message:`${n} is more than ten years away.`,hint:"A one-shot this far out is almost always a year typo. Ten years is the documented bound.",field:e.field});return{kind:"at",at:s,zone:t,source:n}}function ms(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t}function ps(e,t){if(t===void 0||t<=0)return 0;let n=Math.min(Math.floor(t/10),fs);return n<=0?0:ms(e)%n}function gs(e,t){if(e.kind==="every")return e.every.ms;if(e.kind==="at")return;let n=j(e.spec,t,e.zone);if(n===void 0)return;let s=j(e.spec,n,e.zone);return s===void 0?void 0:s-n}function ys(e,t,n,s,o={}){if(e.kind==="at"){if(o.consumed===!0)return{runAt:void 0,anchor:void 0,missed:0,missedCapped:!1,late:!1};if(e.at<=s)return{runAt:s,anchor:e.at,missed:0,missedCapped:!1,late:!0};return{runAt:e.at,anchor:e.at,missed:0,missedCapped:!1,late:!1}}let d=ps(t,gs(e,n));if(e.kind==="every"){let u=s-n,k=u<=0?0:Math.floor(u/e.every.ms),p=Math.min(k,se),w=k+1,b=n+w*e.every.ms;return{runAt:b+d,anchor:b,missed:p,missedCapped:k>se,late:!1}}let l=n,c=0,m=!1;for(;;){let u=j(e.spec,l,e.zone);if(u===void 0)return{runAt:void 0,anchor:void 0,missed:c,missedCapped:m,late:!1};if(u+d>s)return{runAt:u+d,anchor:u,missed:c,missedCapped:m,late:!1};if(l=u,c+=1,c>=se){m=!0;let k=j(e.spec,s,e.zone);return{runAt:k===void 0?void 0:k+d,anchor:k,missed:c,missedCapped:!0,late:!1}}}}function ws(e,t,n){let s=[],o=Array.isArray(e.schedules)?e.schedules:[],d=new Set((Array.isArray(e.channels)?e.channels:[]).map((u)=>u!==null&&typeof u==="object"&&!Array.isArray(u)?u.id:void 0).filter((u)=>typeof u==="string")),l=new Set([...ie,...Ke(t.model)]),c=new Set,m=new Set;for(let[u,k]of o.entries()){if(k===null||typeof k!=="object"||Array.isArray(k))continue;let p=k,w=typeof p.id==="string"?p.id:`[${u}]`;if(m.has(w))s.push({code:"schedule_id_duplicate",message:`Two schedules share the id "${w}".`,hint:"A schedule id is the key reconciliation matches on and the segment of its session key, so it must be unique within an agent.",field:`schedules[${u}].id`});m.add(w);let b=p.deliver;if(b===void 0)s.push({code:"schedule_missing_delivery",message:`Schedule "${w}" has no delivery target.`,hint:'Set deliver to { channel, to }, or the literal "none" to return results only via the event stream.',field:`schedules[${u}].deliver`});else if(b!=="none"&&typeof b==="object"&&!Array.isArray(b)){let A=b.channel;if(typeof A==="string"&&!d.has(A))s.push({code:"schedule_delivery_channel_unknown",message:`Schedule "${w}" delivers to "${A}", which is not a channel id on this agent.${d.size===0?" The agent declares no channels.":` Declared: ${[...d].join(", ")}.`}`,hint:`A delivery target names a channel's id, not its type. Use deliver: "none" to return results through the event stream instead.`,field:`schedules[${u}].deliver.channel`})}let T=p.role;if(typeof T==="string"){if(c.add(T),!l.has(T))s.push({code:"schedule_role_unknown",message:`Schedule "${w}" names the model role "${T}", which is not declared under model:. Declared: ${[...l].join(", ")}.`,hint:"Add the role under model:, or point the schedule at one of the declared roles. Omit role entirely to use main.",field:`schedules[${u}].role`})}let E=t.schedules[u];if(E!==void 0)try{it({id:E.id,kind:E.kind,expr:E.expr,timezone:E.timezone,now:n,field:`schedules[${u}].expr`})}catch(A){if(!(A instanceof z))throw A;s.push(A.toDetail())}}for(let u of Ke(t.model)){if(c.has(u))continue;s.push({code:"model_role_unreferenced",message:`model.${u} is declared but no schedule names it, so nothing will ever use it.`,hint:`If "${u}" was meant to be one of ${ie.join(", ")}, it is misspelled — and the misspelled one is silently falling back to main. Otherwise point a schedule at it with role: ${u}, or remove it.`,field:`model.${u}`})}return s}function at(e){if(typeof e!=="string")return String(e);let t=/^[A-Za-z0-9_./@~-]+$/.test(e),n=/^[A-Za-z0-9_./]/.test(e);if(!t||!n)return JSON.stringify(e);try{return F(e)===e?e:JSON.stringify(e)}catch{return JSON.stringify(e)}}function W(e){return e.length-e.trimStart().length}function ce(e){let t=e.trim();return t===""||t.startsWith("#")}function Qe(e,t,n,s){let o=new RegExp(`^\\s{${n}}${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*:`);for(let d=s;d<e.length;d+=1){let l=e[d]??"";if(ce(l))continue;if(W(l)<n)return;if(W(l)===n&&o.test(l))return d}return}function re(e,t,n){let s=t;for(let o=t+1;o<e.length;o+=1){let d=e[o]??"";if(ce(d))continue;if(W(d)<=n)break;s=o}return s}function bs(e){let t;for(let n=0;n<e.length;n+=1){let s=e[n];if(t!==void 0){if(s===t)t=void 0;continue}if(s==='"'||s==="'"){t=s;continue}if(s!=="#"||n===0||!/\s/.test(e[n-1]??""))continue;let o=n;while(o>0&&/\s/.test(e[o-1]??""))o-=1;return e.slice(o)}return""}function ue(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function L(e,t,n){let s=" ".repeat(n);if(Array.isArray(t)){if(t.length===0)return[`${s}${e}: []`];return[`${s}${e}:`,...t.flatMap((o)=>vs(o,n+2))]}if(ue(t)){let o=Object.entries(t);if(o.length===0)return[`${s}${e}: {}`];return[`${s}${e}:`,...o.flatMap(([d,l])=>L(d,l,n+2))]}return[`${s}${e}: ${at(t)}`]}function vs(e,t){let n=" ".repeat(t);if(!ue(e))return[`${n}- ${at(e)}`];let s=Object.entries(e);if(s.length===0)return[`${n}- {}`];let o=s.flatMap(([c,m])=>L(c,m,t+2)),[d,...l]=o;return[`${n}- ${(d??"").trimStart()}`,...l]}function ks(e,t,n){if(t.length===0)return;let s=e.split(`
56
+ `),o=0,d=0,l,c=0;for(;c<t.length-1;c+=1){let p=Qe(s,t[c]??"",d,o);if(p===void 0)break;l=p,o=p+1;let w=s.slice(p+1).find((b)=>!ce(b)&&W(b)>d);if(w===void 0)return;d=W(w)}if(c<t.length-1){if(l===void 0)return;let p=re(s,l,d-1)+1;return[...s.slice(0,p),...dt(t.slice(c),n,d),...s.slice(p)].join(`
57
+ `)}let m=t[t.length-1]??"",u=Qe(s,m,d,o);if(u!==void 0){let p=s[u]??"",w=Array.isArray(n)||ue(n)?"":bs(p),b=re(s,u,d),T=L(m,n,d);if(w!=="")T[0]=`${T[0]}${w}`;return[...s.slice(0,u),...T,...s.slice(b+1)].join(`
58
+ `)}if(l===void 0)return;let k=re(s,l,d-1)+1;return[...s.slice(0,k),...L(m,n,d),...s.slice(k)].join(`
59
59
  `)}function dt(e,t,n){let[s,...o]=e;if(s===void 0)return[];if(o.length===0)return L(s,t,n);return[`${" ".repeat(n)}${s}:`,...dt(o,t,n+Ts)]}var Ts=2;function Es(e,t,n){let s=e.split(`
60
60
  `),o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),d=new RegExp(`^#\\s*${o}\\s*:`),l=s.findIndex((u)=>d.test(u));if(l===-1)return;let c=l;while(/^#\s{2,}\S/.test(s[c+1]??""))c+=1;let m=/^#\s*Phase \d/.test(s[l-1]??"")?l-1:l;return[...s.slice(0,m),...L(t,n,0),...s.slice(c+1)].join(`
61
- `)}function _s(e,t){let n=[...t.path],s=n.join("."),o=lt(U(e),n),d=ks(e,n,t.value)??t.fallback?.(e)??(n.length===1?Es(e,n[0]??"",t.value):void 0),l;if(d===void 0){let p=U(e);p.setIn(n,t.value),l=String(p)}else l=d;let c=U(l);if(c.errors.length>0)throw X(s,`the result is not valid YAML — ${c.errors[0]?.message??"unparseable"}`);let m=wn.safeParse(c.toJS());if(!m.success){let p=m.error.issues[0];throw X(s,`${p?.path.join(".")??s}: ${p?.message??"does not fit the schema"}`)}let k=ws(c.toJS(),m.data,Date.now())[0];if(k!==void 0)throw X(s,`${k.message} ${k.hint}`);try{Jn(m.data.tools)}catch(p){throw X(s,p instanceof Error?p.message:"the providers block does not resolve")}return{next:l,before:o,reflowed:d===void 0,manifest:m.data}}async function Zt(e){let t;try{t=await Yn(e.file,"utf8")}catch(s){throw As(e.file,s)}let n=_s(t,e);return await Vn(e.file,n.next,"utf8"),{...n,after:e.value}}function Vt(e){let t=e.trim();if(t==="")return"";let n=U(t);if(n.errors.length>0)throw new z({code:"manifest_value_unreadable",message:`Cannot read ${JSON.stringify(e)} as a value.`,hint:'A bare word, a number, true or false, a list as ["a", "b"], or a map as {k: v}. Quote anything containing a colon or a "#".'});return n.toJS()}function ro(e,t){return lt(U(e),t)}function lt(e,t){let n=e.getIn([...t],!1);if(n===void 0||n===null)return;return $e(n)||Ae(n)?n.toJS(e):n}function As(e,t){return new z({code:"manifest_edit_unreadable",message:`Cannot read the manifest at ${e} to change it.`,hint:"Check the path and file permissions. Nothing was written.",cause:t})}function X(e,t){return new z({code:"manifest_edit_invalid",message:`Setting ${e} would make the manifest invalid: ${t}`,hint:"Nothing was written. Check the value's shape — a list is [a, b], a map is {k: v} — against the field this path names."})}var Le=[{path:"tools.local",means:"built-in tools: now, memory_write, artifact_read",agentListed:!0},{path:"tools.providers",means:"where tools come from, as a map — {system: {}} for shell and files, {web: {backend: tavily, apiKeyEnv: TAVILY_API_KEY}} for the internet. Several at once",toAgent:"A writeRoots key inside is refused",agentListed:!0},{path:"tools.pinned",means:"the tools from those providers this agent may call",agentListed:!0},{path:"tools.policy.allow",means:'rules permitting a call: "exec", or narrower like "exec(git *)". Also what lets a mutating tool run in a turn that has read untrusted content',agentListed:!0},{path:"tools.policy.deny",means:"rules refusing a call. Beats any allow rule",toAgent:"Replacing these is refused: it is the one edit whose only purpose is to remove a restriction someone set",agentListed:!0,confirm:"Deny rules are the restrictions that beat every allow rule. Replacing them removes whatever was deliberately put out of reach."},{path:"tools.policy.mode",means:"allow | ask | deny — for calls no rule mentions",agentListed:!0},{path:"tools.untrusted.onMutate",means:"refuse | confirm | allow — what happens when a tool that changes something is asked for in a turn that has read outside content",toAgent:'Cannot be set to "allow"',agentListed:!0,confirm:'Setting this to "allow" turns off the check that stops text from outside the conversation driving a tool that changes things. A fetched page that says "now delete the backups" would be acted on.'},{path:"tools.dialect",means:"nlt | native — how tool calls are written",agentListed:!0},{path:"model.main.id",means:"the model this agent runs on",agentListed:!0},{path:"model.main.temperature",means:"0 to 2",agentListed:!0},{path:"limits.maxSteps",means:"tool calls allowed in one turn",agentListed:!0},{path:"limits.toolTimeoutMs",means:"how long any single tool may take",agentListed:!0},{path:"context.observationMaxTokens",means:"how much of a tool's output reaches the model",agentListed:!0},{path:"channels",means:"how people reach this agent, as a list — [{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]. The token goes in the .env",toAgent:"The token itself goes in the .env, which only a person can write. allowFrom is refused here: who may talk to you is not yours to decide",agentListed:!0},{path:"delivery",means:"where a reply goes when a turn has no origin — {default: tg}. Names a channel id, not a channel type",agentListed:!0},{path:"schedules",means:'what runs unattended, as a list — [{id, kind: cron|every|at, expr, task, deliver}]. expr is a 5- or 6-field cron, a duration like 15m, or an ISO instant; deliver is {channel, to} or the literal "none"',toAgent:"Only `serve` fires these; under `run` they are validated and listed and no timer starts. deliver.to is the address a reply is *sent* to — on Telegram the numeric chat id, never an @handle, which addresses a channel and not a person. It is the id inbound messages arrive on, so read it off your own session keys (tg:<id>); allowFrom holds handles and confers nothing here. Set role to name a model other than main. The whole list is replaced, so read it first",agentListed:!0},{path:"server.enabled",means:"true | false — serve the HTTP API on 127.0.0.1",toAgent:"host and tokenEnv are refused: binding anywhere reachable is not yours to decide",agentListed:!0},{path:"server.port",means:"port for the HTTP API",agentListed:!0},{path:"channels[].allowFrom",means:"who may talk to this agent through a channel. Empty or absent refuses everyone — a bot that is connected, healthy and answering nobody is almost always this",agentListed:!1,via:"config allow"},{path:"server.host",means:"the address the HTTP API binds. 127.0.0.1 is local only; anything else is reachable from the network",agentListed:!1},{path:"server.tokenEnv",means:"the env var holding the bearer token the API requires. Without it the API is unauthenticated",agentListed:!1},{path:"tools.providers.<id>.writeRoots",means:"the directories a file tool may write to, for that provider. Nothing outside them is writable — and this binds file tools only, never exec, which carries its target inside a shell string",agentListed:!1}];function oo(e){return Le.find((t)=>t.path===e)}var pr=Le.filter((e)=>e.agentListed).map((e)=>e.path),Yt=Le.filter((e)=>e.via===void 0&&!e.path.includes("<")&&!e.path.includes("[")).map((e)=>e.path);var Lo=["Summarise the conversation above for your own future reference. You are writing notes to yourself, not a report for a person.","","The person's own requests are preserved verbatim below your summary, so do not restate them.","Keep: decisions taken and why, facts established by tool results, and anything still outstanding.","Drop: pleasantries, your own reasoning, and anything already superseded.","Write plain prose under 300 words. No headings, no preamble, no closing summary.","End with one line naming what this summary does not cover, so a later step knows to ask rather than assume."].join(`
62
- `);var Ss="schedule";function so(e,t,n){if(e.startsWith("shared:")){let s=e.slice(7);if(s!=="")return s}return Rt({channel:Ss,peerId:t,thread:n})}function io(e){let t=nt.safeParse(e.body);if(!t.success){let c=t.error.issues[0];throw new y({code:"schedule_invalid",message:`Schedule rejected: ${c?.path.join(".")??"body"} ${c?.message??"is invalid"}.`,hint:"A schedule needs id, kind (cron|every|at), expr, task and deliver. See docs/02-SPEC-MANIFEST.md.",...c?.path.length===void 0||c.path.length===0?{}:{field:c.path.join(".")}})}let n=t.data;if(n.deliver!=="none"){if(!e.channelIds.includes(n.deliver.channel))throw new y({code:"schedule_delivery_channel_unknown",message:`Schedule "${n.id}" delivers to "${n.deliver.channel}", which is not a channel id on this agent.${e.channelIds.length===0?" The agent declares no channels.":` Declared: ${e.channelIds.join(", ")}.`}`,hint:`A delivery target names a channel's id, not its type. Use deliver: "none" to return results through the event stream instead.`,field:"deliver.channel"})}if(n.role!==void 0&&!e.roleNames.includes(n.role))throw new y({code:"schedule_role_unknown",message:`Schedule "${n.id}" names the model role "${n.role}", which is not declared under model:. Declared: ${e.roleNames.join(", ")}.`,hint:"Add the role under model: in the manifest, or point the schedule at one of the declared roles. Omit role entirely to use main.",field:"role"});let s=it({id:n.id,kind:n.kind,expr:n.expr,timezone:n.timezone,now:e.now,field:"expr"}),o=new Date(e.now).toISOString(),d=ys(s,n.id,e.now,e.now),l=n.deliver==="none"?void 0:n.deliver;return{agentId:e.agentId,id:n.id,kind:n.kind,expr:n.expr,...n.timezone===void 0?{}:{timezone:n.timezone},task:n.task,...l===void 0?{}:{deliverChannel:l.channel,deliverTo:l.to},sessionMode:n.session,...n.role===void 0?{}:{role:n.role},enabled:n.enabled,origin:e.origin,anchorAt:d.anchor===void 0?o:new Date(d.anchor).toISOString(),nextRunAt:d.runAt===void 0?void 0:new Date(d.runAt).toISOString(),sourcePath:"",now:o}}var Mo=new Set("a an and are as at be but by do does for from had has have he her his i if in is it its me my not of on or our she that the their them then there they this to was we were what when which who will with you your would could should im ive dont its ill".split(" "));
63
- export{Q,rt,fe,z,y,f,qt,Pe,Se,Fn,Un,jn,zn,Bn,Kn,Xr,Gt,Jr,Qr,eo,mr,to,Me,no,Zt,Vt,ro,Le,oo,pr,Yt,so,io};
61
+ `)}function _s(e,t){let n=[...t.path],s=n.join("."),o=lt(U(e),n),d=ks(e,n,t.value)??t.fallback?.(e)??(n.length===1?Es(e,n[0]??"",t.value):void 0),l;if(d===void 0){let p=U(e);p.setIn(n,t.value),l=String(p)}else l=d;let c=U(l);if(c.errors.length>0)throw X(s,`the result is not valid YAML — ${c.errors[0]?.message??"unparseable"}`);let m=wn.safeParse(c.toJS());if(!m.success){let p=m.error.issues[0];throw X(s,`${p?.path.join(".")??s}: ${p?.message??"does not fit the schema"}`)}let k=ws(c.toJS(),m.data,Date.now())[0];if(k!==void 0)throw X(s,`${k.message} ${k.hint}`);try{Jn(m.data.tools)}catch(p){throw X(s,p instanceof Error?p.message:"the providers block does not resolve")}return{next:l,before:o,reflowed:d===void 0,manifest:m.data}}async function Zt(e){let t;try{t=await Yn(e.file,"utf8")}catch(s){throw As(e.file,s)}let n=_s(t,e);return await Vn(e.file,n.next,"utf8"),{...n,after:e.value}}function Vt(e){let t=e.trim();if(t==="")return"";let n=U(t);if(n.errors.length>0)throw new z({code:"manifest_value_unreadable",message:`Cannot read ${JSON.stringify(e)} as a value.`,hint:'A bare word, a number, true or false, a list as ["a", "b"], or a map as {k: v}. Quote anything containing a colon or a "#".'});return n.toJS()}function ro(e,t){return lt(U(e),t)}function lt(e,t){let n=e.getIn([...t],!1);if(n===void 0||n===null)return;return Ae(n)||Re(n)?n.toJS(e):n}function As(e,t){return new z({code:"manifest_edit_unreadable",message:`Cannot read the manifest at ${e} to change it.`,hint:"Check the path and file permissions. Nothing was written.",cause:t})}function X(e,t){return new z({code:"manifest_edit_invalid",message:`Setting ${e} would make the manifest invalid: ${t}`,hint:"Nothing was written. Check the value's shape — a list is [a, b], a map is {k: v} — against the field this path names."})}var De=[{path:"tools.local",means:"built-in tools: now, memory_write, artifact_read",agentListed:!0},{path:"tools.providers",means:"where tools come from, as a map — {system: {}} for shell and files, {web: {backend: tavily, apiKeyEnv: TAVILY_API_KEY}} for the internet. Several at once",toAgent:"A writeRoots key inside is refused",agentListed:!0},{path:"tools.pinned",means:"the tools from those providers this agent may call",agentListed:!0},{path:"tools.policy.allow",means:'rules permitting a call: "exec", or narrower like "exec(git *)". Also what lets a mutating tool run in a turn that has read untrusted content',agentListed:!0},{path:"tools.policy.deny",means:"rules refusing a call. Beats any allow rule",toAgent:"Replacing these is refused: it is the one edit whose only purpose is to remove a restriction someone set",agentListed:!0,confirm:"Deny rules are the restrictions that beat every allow rule. Replacing them removes whatever was deliberately put out of reach."},{path:"tools.policy.mode",means:"allow | ask | deny — for calls no rule mentions",agentListed:!0},{path:"tools.untrusted.onMutate",means:"refuse | confirm | allow — what happens when a tool that changes something is asked for in a turn that has read outside content",toAgent:'Cannot be set to "allow"',agentListed:!0,confirm:'Setting this to "allow" turns off the check that stops text from outside the conversation driving a tool that changes things. A fetched page that says "now delete the backups" would be acted on.'},{path:"tools.dialect",means:"nlt | native — how tool calls are written",agentListed:!0},{path:"model.main.id",means:"the model this agent runs on",agentListed:!0},{path:"model.main.temperature",means:"0 to 2",agentListed:!0},{path:"limits.maxSteps",means:"tool calls allowed in one turn",agentListed:!0},{path:"limits.toolTimeoutMs",means:"how long any single tool may take",agentListed:!0},{path:"context.observationMaxTokens",means:"how much of a tool's output reaches the model",agentListed:!0},{path:"channels",means:"how people reach this agent, as a list — [{type: telegram, id: tg, tokenEnv: TELEGRAM_BOT_TOKEN, mode: longpoll}]. The token goes in the .env",toAgent:"The token itself goes in the .env, which only a person can write. allowFrom is refused here: who may talk to you is not yours to decide",agentListed:!0},{path:"delivery",means:"where a reply goes when a turn has no origin — {default: tg}. Names a channel id, not a channel type",agentListed:!0},{path:"schedules",means:'what runs unattended, as a list — [{id, kind: cron|every|at, expr, task, deliver}]. expr is a 5- or 6-field cron, a duration like 15m, or an ISO instant; deliver is {channel, to} or the literal "none"',toAgent:"Only `serve` fires these; under `run` they are validated and listed and no timer starts. deliver.to is the address a reply is *sent* to — on Telegram the numeric chat id, never an @handle, which addresses a channel and not a person. It is the id inbound messages arrive on, so read it off your own session keys (tg:<id>); allowFrom holds handles and confers nothing here. Set role to name a model other than main. The whole list is replaced, so read it first",agentListed:!0},{path:"server.enabled",means:"true | false — serve the HTTP API on 127.0.0.1",toAgent:"host and tokenEnv are refused: binding anywhere reachable is not yours to decide",agentListed:!0},{path:"server.port",means:"port for the HTTP API",agentListed:!0},{path:"channels[].allowFrom",means:"who may talk to this agent through a channel. Empty or absent refuses everyone — a bot that is connected, healthy and answering nobody is almost always this",agentListed:!1,via:"config allow"},{path:"server.host",means:"the address the HTTP API binds. 127.0.0.1 is local only; anything else is reachable from the network",agentListed:!1},{path:"server.tokenEnv",means:"the env var holding the bearer token the API requires. Without it the API is unauthenticated",agentListed:!1},{path:"tools.providers.<id>.writeRoots",means:"the directories a file tool may write to, for that provider. Nothing outside them is writable — and this binds file tools only, never exec, which carries its target inside a shell string",agentListed:!1}];function oo(e){return De.find((t)=>t.path===e)}var pr=De.filter((e)=>e.agentListed).map((e)=>e.path),Yt=De.filter((e)=>e.via===void 0&&!e.path.includes("<")&&!e.path.includes("[")).map((e)=>e.path);var Mo=["Summarise the conversation above for your own future reference. You are writing notes to yourself, not a report for a person.","","The person's own requests are preserved verbatim below your summary, so do not restate them.","Keep: decisions taken and why, facts established by tool results, and anything still outstanding.","Drop: pleasantries, your own reasoning, and anything already superseded.","Write plain prose under 300 words. No headings, no preamble, no closing summary.","End with one line naming what this summary does not cover, so a later step knows to ask rather than assume."].join(`
62
+ `);var Ss="schedule";function so(e,t,n){if(e.startsWith("shared:")){let s=e.slice(7);if(s!=="")return s}return Ot({channel:Ss,peerId:t,thread:n})}function io(e){let t=nt.safeParse(e.body);if(!t.success){let c=t.error.issues[0];throw new y({code:"schedule_invalid",message:`Schedule rejected: ${c?.path.join(".")??"body"} ${c?.message??"is invalid"}.`,hint:"A schedule needs id, kind (cron|every|at), expr, task and deliver. See docs/02-SPEC-MANIFEST.md.",...c?.path.length===void 0||c.path.length===0?{}:{field:c.path.join(".")}})}let n=t.data;if(n.deliver!=="none"){if(!e.channelIds.includes(n.deliver.channel))throw new y({code:"schedule_delivery_channel_unknown",message:`Schedule "${n.id}" delivers to "${n.deliver.channel}", which is not a channel id on this agent.${e.channelIds.length===0?" The agent declares no channels.":` Declared: ${e.channelIds.join(", ")}.`}`,hint:`A delivery target names a channel's id, not its type. Use deliver: "none" to return results through the event stream instead.`,field:"deliver.channel"})}if(n.role!==void 0&&!e.roleNames.includes(n.role))throw new y({code:"schedule_role_unknown",message:`Schedule "${n.id}" names the model role "${n.role}", which is not declared under model:. Declared: ${e.roleNames.join(", ")}.`,hint:"Add the role under model: in the manifest, or point the schedule at one of the declared roles. Omit role entirely to use main.",field:"role"});let s=it({id:n.id,kind:n.kind,expr:n.expr,timezone:n.timezone,now:e.now,field:"expr"}),o=new Date(e.now).toISOString(),d=ys(s,n.id,e.now,e.now),l=n.deliver==="none"?void 0:n.deliver;return{agentId:e.agentId,id:n.id,kind:n.kind,expr:n.expr,...n.timezone===void 0?{}:{timezone:n.timezone},task:n.task,...l===void 0?{}:{deliverChannel:l.channel,deliverTo:l.to},sessionMode:n.session,...n.role===void 0?{}:{role:n.role},enabled:n.enabled,origin:e.origin,anchorAt:d.anchor===void 0?o:new Date(d.anchor).toISOString(),nextRunAt:d.runAt===void 0?void 0:new Date(d.runAt).toISOString(),sourcePath:"",now:o}}var Co=new Set("a an and are as at be but by do does for from had has have he her his i if in is it its me my not of on or our she that the their them then there they this to was we were what when which who will with you your would could should im ive dont its ill".split(" "));
63
+ export{Q,rt,fe,z,y,f,qt,Me,xe,Fn,Un,jn,zn,Bn,Kn,Xr,Gt,Jr,Qr,eo,mr,to,Le,no,Zt,Vt,ro,De,oo,pr,Yt,so,io};
64
64
 
65
- //# debugId=3DCD48EDAA86987664756E2164756E21
66
- //# sourceMappingURL=index-5t6wahx8.js.map
65
+ //# debugId=0082B7C7015811CC64756E2164756E21
66
+ //# sourceMappingURL=index-1c5113t4.js.map