@tangle-network/agent-runtime 0.192.5 → 0.194.0

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 (114) hide show
  1. package/dist/{activation-CsJctnHp.js → activation-BQFIiyUG.js} +3 -3
  2. package/dist/{activation-CsJctnHp.js.map → activation-BQFIiyUG.js.map} +1 -1
  3. package/dist/agent.d.ts +1 -1
  4. package/dist/agent.js +2 -2
  5. package/dist/candidate-execution/index.js +4 -4
  6. package/dist/{candidate-execution-BSkZErxD.js → candidate-execution-B6CDW-fp.js} +4 -4
  7. package/dist/{candidate-execution-BSkZErxD.js.map → candidate-execution-B6CDW-fp.js.map} +1 -1
  8. package/dist/{conversation-DILnmy84.js → conversation-BXPWMOSd.js} +4 -5
  9. package/dist/{conversation-DILnmy84.js.map → conversation-BXPWMOSd.js.map} +1 -1
  10. package/dist/conversation.d.ts +1 -1
  11. package/dist/conversation.js +1 -1
  12. package/dist/{coordination-driver-pQobxl2Z.js → coordination-driver-iSN-m3VX.js} +287 -250
  13. package/dist/coordination-driver-iSN-m3VX.js.map +1 -0
  14. package/dist/{authoring-D-nXk29K.js → delegate-DCC2muUd.js} +56 -13
  15. package/dist/delegate-DCC2muUd.js.map +1 -0
  16. package/dist/delegation-status-BlsbSeOB.js +358 -0
  17. package/dist/delegation-status-BlsbSeOB.js.map +1 -0
  18. package/dist/durable.d.ts +2 -2
  19. package/dist/durable.js +3 -3
  20. package/dist/{environment-provider-DEwsolvi.js → environment-provider-Dr-wfnHg.js} +422 -8
  21. package/dist/environment-provider-Dr-wfnHg.js.map +1 -0
  22. package/dist/{environment-provider-CJ43FJfJ.d.ts → environment-provider-adVa6X7a.d.ts} +2 -2
  23. package/dist/environment-provider.d.ts +1 -1
  24. package/dist/environment-provider.js +1 -1
  25. package/dist/{graph-Ba4ZJ5jU.js → graph-DghidDx5.js} +138 -5
  26. package/dist/graph-DghidDx5.js.map +1 -0
  27. package/dist/graph.d.ts +3 -3
  28. package/dist/graph.js +4 -5
  29. package/dist/graph.js.map +1 -1
  30. package/dist/{improve-Cbbt3jE6.d.ts → improve-COGzLCiY.d.ts} +3 -3
  31. package/dist/{improvement-cycle-D9FWTakR.js → improvement-cycle-DeS1ZC5B.js} +6 -6
  32. package/dist/{improvement-cycle-D9FWTakR.js.map → improvement-cycle-DeS1ZC5B.js.map} +1 -1
  33. package/dist/{index-B_fEqr5V.d.ts → index-BEPjOPwH.d.ts} +66 -69
  34. package/dist/{index-COznK4kB.d.ts → index-CrBgLCIf.d.ts} +4 -4
  35. package/dist/{index-OSRVFARy.d.ts → index-DO6DHgRP.d.ts} +2 -2
  36. package/dist/index.d.ts +8 -8
  37. package/dist/index.js +13 -13
  38. package/dist/intelligence.d.ts +5 -5
  39. package/dist/intelligence.js +6 -6
  40. package/dist/{executable-spec-DxuiDFAU.js → jsonl-file-Bh1Q9nt0.js} +59 -3
  41. package/dist/jsonl-file-Bh1Q9nt0.js.map +1 -0
  42. package/dist/kernel.d.ts +6 -6
  43. package/dist/kernel.js +11 -12
  44. package/dist/{knowledge-rzv8sBV9.js → knowledge-B5okOzBQ.js} +6 -6
  45. package/dist/{knowledge-rzv8sBV9.js.map → knowledge-B5okOzBQ.js.map} +1 -1
  46. package/dist/knowledge.d.ts +1 -1
  47. package/dist/knowledge.js +1 -1
  48. package/dist/{loop-runner-bin-DiiZMHw7.d.ts → loop-runner-bin-Clc5IAwu.d.ts} +3 -3
  49. package/dist/{loop-runner-bin-ClpCHpzR.js → loop-runner-bin-U1J6x_UF.js} +3 -3
  50. package/dist/{loop-runner-bin-ClpCHpzR.js.map → loop-runner-bin-U1J6x_UF.js.map} +1 -1
  51. package/dist/loop-runner-bin.d.ts +1 -1
  52. package/dist/loop-runner-bin.js +1 -1
  53. package/dist/{materialization-CekWK6OO.js → materialization-vZssF9Nx.js} +28 -3
  54. package/dist/materialization-vZssF9Nx.js.map +1 -0
  55. package/dist/mcp/bin.js +3 -3
  56. package/dist/mcp/index.d.ts +4 -4
  57. package/dist/mcp/index.js +8 -8
  58. package/dist/mcp/index.js.map +1 -1
  59. package/dist/{openai-tools-BNBrKvZr.js → openai-tools-DmvmaG0a.js} +2 -2
  60. package/dist/{openai-tools-BNBrKvZr.js.map → openai-tools-DmvmaG0a.js.map} +1 -1
  61. package/dist/{prepare-B5fJ7mLS.js → prepare-C29kNAon.js} +9 -14
  62. package/dist/prepare-C29kNAon.js.map +1 -0
  63. package/dist/primeintellect/index.d.ts +1 -1
  64. package/dist/profiles.js +1 -1
  65. package/dist/{protected-model-port-B0xFSAjt.js → protected-model-port-CKYND416.js} +2 -2
  66. package/dist/{protected-model-port-B0xFSAjt.js.map → protected-model-port-CKYND416.js.map} +1 -1
  67. package/dist/{provision-supervisor-DiHm_bvQ.js → provision-supervisor-CRPbnJiB.js} +12 -14
  68. package/dist/provision-supervisor-CRPbnJiB.js.map +1 -0
  69. package/dist/{redact-Ct7s2j86.js → redact-BOU77QfQ.js} +1120 -64
  70. package/dist/redact-BOU77QfQ.js.map +1 -0
  71. package/dist/{researcher-hgPa5p9i.js → researcher-Cp4JRbFp.js} +2 -2
  72. package/dist/researcher-Cp4JRbFp.js.map +1 -0
  73. package/dist/{runtime-DI4mJNXI.d.ts → runtime-B8x43nGP.d.ts} +5 -4
  74. package/dist/{runtime-CVdsAHEN.js → runtime-BVrqSu0-.js} +36 -25
  75. package/dist/{runtime-CVdsAHEN.js.map → runtime-BVrqSu0-.js.map} +1 -1
  76. package/dist/server-D6XmE1Du.js +1311 -0
  77. package/dist/server-D6XmE1Du.js.map +1 -0
  78. package/dist/{stream-agent-turn-_GgUW49y.d.ts → stream-agent-turn-B-gtBlOy.d.ts} +2 -2
  79. package/dist/{stream-agent-turn-DWWe_7bh.js → stream-agent-turn-DOtEsvCV.js} +3 -3
  80. package/dist/{stream-agent-turn-DWWe_7bh.js.map → stream-agent-turn-DOtEsvCV.js.map} +1 -1
  81. package/dist/{structural-rollout-NrtKSgCE.js → structural-rollout-BcPXFzVb.js} +16 -43
  82. package/dist/structural-rollout-BcPXFzVb.js.map +1 -0
  83. package/dist/{supervise-Cr6JEoIg.js → supervise-C0V3pZXK.js} +179 -1980
  84. package/dist/supervise-C0V3pZXK.js.map +1 -0
  85. package/dist/testing.d.ts +2 -2
  86. package/dist/testing.js +13 -13
  87. package/dist/tui/index.d.ts +1 -1
  88. package/dist/tui/index.js +1 -1
  89. package/dist/{types-DKA_PDv0.d.ts → types-B_pNTBjK.d.ts} +25 -29
  90. package/dist/{workspace-archive-yAPDklLV.js → workspace-archive-BCezkeIk.js} +2 -2
  91. package/dist/{workspace-archive-yAPDklLV.js.map → workspace-archive-BCezkeIk.js.map} +1 -1
  92. package/package.json +1 -1
  93. package/skills/codemode/SKILL.md +2 -2
  94. package/skills/supervise/SKILL.md +93 -26
  95. package/dist/authoring-D-nXk29K.js.map +0 -1
  96. package/dist/coordination-driver-pQobxl2Z.js.map +0 -1
  97. package/dist/environment-provider-DEwsolvi.js.map +0 -1
  98. package/dist/executable-spec-DxuiDFAU.js.map +0 -1
  99. package/dist/graph-Ba4ZJ5jU.js.map +0 -1
  100. package/dist/jsonl-file-CDfsCI5s.js +0 -59
  101. package/dist/jsonl-file-CDfsCI5s.js.map +0 -1
  102. package/dist/materialization-CekWK6OO.js.map +0 -1
  103. package/dist/prepare-B5fJ7mLS.js.map +0 -1
  104. package/dist/provision-supervisor-DiHm_bvQ.js.map +0 -1
  105. package/dist/redact-Ct7s2j86.js.map +0 -1
  106. package/dist/researcher-hgPa5p9i.js.map +0 -1
  107. package/dist/snapshot-CTAf4uuA.js +0 -26
  108. package/dist/snapshot-CTAf4uuA.js.map +0 -1
  109. package/dist/spawn-journal-B9eTmVAn.js +0 -999
  110. package/dist/spawn-journal-B9eTmVAn.js.map +0 -1
  111. package/dist/structural-rollout-NrtKSgCE.js.map +0 -1
  112. package/dist/supervise-Cr6JEoIg.js.map +0 -1
  113. package/dist/util-mCNUeboW.js +0 -419
  114. package/dist/util-mCNUeboW.js.map +0 -1
@@ -1,4 +1,5 @@
1
- import { S as supervisorPolicyPrompt } from "./supervise-Cr6JEoIg.js";
1
+ import { i as ConfigError } from "./errors-CDZ8XsVj.js";
2
+ import { n as supervise } from "./supervise-C0V3pZXK.js";
2
3
  import { agentProfileSchema } from "@tangle-network/agent-interface";
3
4
  import { computeFindingId, makeFinding } from "@tangle-network/agent-eval";
4
5
  //#region src/runtime/supervise/authoring.ts
@@ -32,17 +33,10 @@ function asAuthoredProfile(raw) {
32
33
  }
33
34
  };
34
35
  }
35
- /** The supervisor SKILL the how-to the supervisor reads (its system prompt). THE optimizable
36
- * surface: editing this changes how the supervisor designs every agent it spawns.
37
- *
38
- * The POLICY paragraph is the registry's one `supervisor/policy` entry — the same stance
39
- * `defaultSupervisorPrompt` carries — so both front doors run the same work-vs-delegate rule;
40
- * this function ADDS the profile-authoring skill (how to WRITE the workers it spawns), which is
41
- * additive craft, not a different policy. */
36
+ /** The supervisor skill: an explicit profile-authoring instruction, never an implicit Runtime
37
+ * policy. Editing this text changes how a profile designs the descendants it spawns. */
42
38
  function supervisorInstructions(opts) {
43
39
  return [
44
- supervisorPolicyPrompt.text,
45
- "",
46
40
  "Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.",
47
41
  "",
48
42
  "For the task you are given:",
@@ -52,7 +46,9 @@ function supervisorInstructions(opts) {
52
46
  " • prompt.systemPrompt: rich instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.",
53
47
  " • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.",
54
48
  " • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.",
55
- " • metadata.role=\"driver\" when this child should be a sub-supervisor that may author and drive its own children.",
49
+ " • tools.agent_runtime_coordination_spawn_worker: true ONLY when this child should author and drive descendants. Add only the other agent_runtime_coordination_<verb> tools it will call, such as await_event or steer_agent.",
50
+ " • A child with spawn_worker MUST carry this complete profile-authoring instruction as an immutable resources.skills entry with resources.failOnError: true, so it can author its own descendants from the same contract.",
51
+ " • metadata may describe the work, but it never grants recursion or selects a Runtime execution path.",
56
52
  " NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.",
57
53
  "3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.",
58
54
  "4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.",
@@ -162,6 +158,53 @@ function profileRichnessFinding(richness, opts) {
162
158
  });
163
159
  }
164
160
  //#endregion
165
- export { supervisorInstructions as a, profileRichnessFinding as i, assessAuthoredProfile as n, defaultProfileRichnessThresholds as r, asAuthoredProfile as t };
161
+ //#region src/runtime/supervise/delegate.ts
162
+ /**
163
+ *
164
+ * `delegate` — the one generic delegation verb. You hand it an INTENT (what you want done) and it
165
+ * hands that intent to a default AUTHORING supervisor: a router-brained supervisor whose standing
166
+ * instruction is `supervisorInstructions()` (the authoring-agent-profiles skill). The supervisor
167
+ * DECOMPOSES the intent and AUTHORS the worker profile it needs per sub-task — there is NO hardcoded
168
+ * coder/researcher profile here. That is the whole point: `delegate('fix the failing test', …)` and
169
+ * `delegate('research X and cite sources', …)` route through the SAME front door; the supervisor
170
+ * writes a code-shaped or research-shaped worker on its own.
171
+ *
172
+ * It is a thin wrapper over `supervise()` — the one front door — so the conserved-budget pool, the
173
+ * completion oracle (`deliverable`), the coordination toolbox, and equal-compute accounting all come
174
+ * for free; nothing is hand-rolled. The result is `supervise()`'s `SupervisedResult` returned
175
+ * UNCHANGED, so its `spentTotal` (`{ iterations, tokens, usd, ms }`) rides straight back to the
176
+ * caller on BOTH paths — a `winner` carries the delivered worker's spend, a `no-winner` carries the
177
+ * spend incurred before it failed. That cost channel means a `delegate()` caller always learns what
178
+ * the delegation actually spent.
179
+ *
180
+ * @experimental
181
+ */
182
+ /** The conserved pool a `delegate()` call applies when the caller does not pass its own `budget`.
183
+ * A modest token ceiling + a small iteration ceiling — generous enough for a few-worker decompose,
184
+ * bounded enough that an unsupervised intent cannot run away. Callers override via `opts.budget`. */
185
+ const defaultDelegateBudget = {
186
+ maxIterations: 50,
187
+ maxTokens: 2e5
188
+ };
189
+ /**
190
+ * Delegate an INTENT to a default authoring supervisor and return its `SupervisedResult` unchanged.
191
+ *
192
+ * The supervisor authors + spawns whatever worker the intent needs over the conserved-budget pool;
193
+ * `result.spentTotal` reports what the whole delegation actually cost. A `winner` result carries the
194
+ * authored worker's delivered output; a `no-winner` result names why (never a fabricated success).
195
+ */
196
+ async function delegate(intent, opts) {
197
+ if (typeof intent !== "string" || intent.trim().length === 0) throw new ConfigError("delegate: `intent` must be a non-empty string");
198
+ return supervise(opts.supervisorProfile, intent, {
199
+ budget: opts.budget ?? defaultDelegateBudget,
200
+ ...opts.backend ? { backend: opts.backend } : {},
201
+ ...opts.deliverable ? { deliverable: opts.deliverable } : {},
202
+ router: opts.router,
203
+ ...opts.allowedModels ? { allowedModels: opts.allowedModels } : {},
204
+ ...opts.runId ? { runId: opts.runId } : {}
205
+ });
206
+ }
207
+ //#endregion
208
+ export { defaultProfileRichnessThresholds as a, assessAuthoredProfile as i, delegate as n, profileRichnessFinding as o, asAuthoredProfile as r, supervisorInstructions as s, defaultDelegateBudget as t };
166
209
 
167
- //# sourceMappingURL=authoring-D-nXk29K.js.map
210
+ //# sourceMappingURL=delegate-DCC2muUd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegate-DCC2muUd.js","names":[],"sources":["../src/runtime/supervise/authoring.ts","../src/runtime/supervise/delegate.ts"],"sourcesContent":["/**\n *\n * The supervisor's intelligence is AUTHORING the agents it spawns — not pressing buttons.\n *\n * Every agent here is three things: instructions (system prompt), tools, and a model — its\n * `AgentProfile`. The supervisor's job is to WRITE those profiles: read the task, decompose it,\n * and for each sub-task author a tailored worker recipe. `supervisorInstructions` is the how-to the\n * supervisor reads; canonical Runtime executors materialize the resulting profile.\n *\n * The skill is the single OPTIMIZABLE surface: edit it → the supervisor designs better agents.\n * That is the self-improvement lever (the prompt/skill lever), not the execution plumbing.\n *\n * @experimental\n */\n\nimport { type AnalystFinding, computeFindingId, makeFinding } from '@tangle-network/agent-eval'\nimport {\n type AgentProfile,\n type AgentProfilePrompt,\n agentProfileSchema,\n} from '@tangle-network/agent-interface'\n\n/** What the supervisor AUTHORS per sub-task: one complete canonical profile whose name and\n * task-specific system prompt are present. Every other `AgentProfile` axis is preserved exactly. */\nexport type AuthoredProfile = AgentProfile & {\n readonly name: string\n readonly prompt: AgentProfilePrompt & { readonly systemPrompt: string }\n}\n\n/** Narrow an untyped `spawn_worker` profile argument to an `AuthoredProfile`, or null if the\n * supervisor failed to author one (empty/placeholder profile — a skill violation worth catching). */\nexport function asAuthoredProfile(raw: unknown): AuthoredProfile | null {\n const parsed = agentProfileSchema.safeParse(raw)\n if (!parsed.success) return null\n const systemPrompt = parsed.data.prompt?.systemPrompt\n if (typeof systemPrompt !== 'string' || systemPrompt.trim().length === 0) return null\n return {\n ...parsed.data,\n name:\n typeof parsed.data.name === 'string' && parsed.data.name.length > 0\n ? parsed.data.name\n : 'worker',\n prompt: { ...parsed.data.prompt, systemPrompt },\n }\n}\n\n/** The supervisor skill: an explicit profile-authoring instruction, never an implicit Runtime\n * policy. Editing this text changes how a profile designs the descendants it spawns. */\nexport function supervisorInstructions(opts?: { goal?: string }): string {\n return [\n 'Your delegation craft is AUTHORING: a spawned worker is exactly as good as the profile you write.',\n '',\n 'For the task you are given:',\n '1. DECOMPOSE it into the smallest set of sub-tasks a single focused worker can each deliver.',\n '2. For EACH sub-task, AUTHOR a worker by calling spawn_worker with a COMPLETE `profile`:',\n ' • name and description: who this specialist is and why it exists.',\n ' • prompt.systemPrompt: rich instructions for THIS sub-task — exact output, process, evidence, and what \"done\" means.',\n ' • model.default, model.reasoningEffort, and harness: choose the execution system deliberately when the task benefits from it.',\n ' • tools, mcp, resources.skills/files/instructions, hooks, subagents, permissions, and modes: grant or attach every capability the worker needs; omit an axis only when it is intentionally unnecessary.',\n ' • tools.agent_runtime_coordination_spawn_worker: true ONLY when this child should author and drive descendants. Add only the other agent_runtime_coordination_<verb> tools it will call, such as await_event or steer_agent.',\n ' • A child with spawn_worker MUST carry this complete profile-authoring instruction as an immutable resources.skills entry with resources.failOnError: true, so it can author its own descendants from the same contract.',\n ' • metadata may describe the work, but it never grants recursion or selects a Runtime execution path.',\n ' NEVER spawn a worker with an empty profile. The quality of the worker IS the quality of the profile you write.',\n \"3. await_event (kinds:['settled']) to collect each worker. Its result says valid:true only if the deployable check passed.\",\n '4. If a worker did NOT deliver, AUTHOR A NEW profile whose prompt.systemPrompt names the SPECIFIC failure and how to fix it — never just retry the same profile.',\n \"5. read_journal to re-read YOUR OWN record before you decide the next move: every spawn you made, every settle, every question and answer, every steer, every analyst finding — oldest first, this node only, including what you did before a restart. Use it to see what you already tried instead of trying it again. It is paged: pass the returned nextRow as the next call's sinceRow, narrow with kinds, and raise limit/maxBytes only as far as you will actually read. A truncated:true page means a bound cut it short — keep paging before you conclude you have read everything.\",\n '6. AUTHOR YOUR OWN LENS when the questions you can already ask of a settled trace do not cover the failure you are chasing: define_analyst takes an id, a description, an area, the question in your own words, the instructions for answering it with trace evidence, and the smallest toolGroup that can answer it (model is the seat it runs on; omit it for the run default). It is DATA, never code. Then run_analyst it on any settled worker like a lens the run shipped with, and read the finding. list_analysts shows what you have. Define a lens when you need a different question asked — not a second copy of a question already on the menu.',\n '7. EVERY refusal you get back carries a `reason` naming the exact unmet condition. Read it and change that condition — a spawn refused for max-live-workers needs an await_event, an invalid-profile needs the named field fixed, a submit_result refused because the check THREW is a broken check to report, not a result to resubmit. Never repeat a call that was refused without changing what it was refused for.',\n '8. ask_parent ONLY when you genuinely cannot decide, and then READ ITS OUTCOME. \"queued-for-parent\" means an inbox above you now holds the question. \"no-parent\" means no inbox above you is configured to receive it: the question is still on the run record for anyone watching, but nothing will route an answer back to you, so do not block. Decide it with answer_question, or answer_question with deferReason to record that it stays open, and carry on — a blocking question left undecided also refuses your stop.',\n '9. Stop (reply with no tool call) once the work is delivered.',\n ...(opts?.goal ? ['', `The goal: ${opts.goal}`] : []),\n ].join('\\n')\n}\n\n// ── Profile-richness gate ────────────────────────────────────────────────────\n//\n// The supervisor's product is the worker PROFILE it authors. The failure mode the existing\n// gates miss: `asAuthoredProfile` / `local-harness` only reject a FULLY EMPTY system prompt —\n// a two-sentence stub passes. `assessAuthoredProfile` OBSERVES the authored artifact (it reads\n// no judge verdict, so it steers cleanly past `assertTraceDerivedFindings`) and flags THIN:\n// a short/few-line system prompt, OR no tools, OR no skills, OR no MCP when the task needs one.\n// It emits a real `AnalystFinding` so it rides the SAME coordination bus the driver pulls via\n// `await_event({kinds:['finding']})` — the supervisor can self-correct and re-author richer.\n\n/** Thresholds below which a system prompt is treated as a thin stub. Tunable per call. */\nexport interface ProfileRichnessThresholds {\n /** A prompt shorter than this many characters is thin (default 600). */\n readonly minSystemPromptChars: number\n /** A prompt with fewer than this many non-blank lines is thin (default 6). */\n readonly minSystemPromptLines: number\n}\n\n/** Default thresholds for `ProfileRichnessThresholds` — 600 chars / 6 lines minimum system prompt. */\nexport const defaultProfileRichnessThresholds: ProfileRichnessThresholds = {\n minSystemPromptChars: 600,\n minSystemPromptLines: 6,\n}\n\n/** Per-field verdict on one authored profile — the raw material the bench renders + scores. */\nexport interface ProfileRichness {\n readonly name: string\n /** The resolved system prompt (canonical `prompt.systemPrompt`, the sandbox `prompt.system`\n * convention, or a bare-string prompt — whichever the author used). */\n readonly systemPrompt: string\n readonly systemPromptChars: number\n readonly systemPromptLines: number\n readonly sentenceCount: number\n readonly hasDescription: boolean\n readonly hasTools: boolean\n readonly hasSkills: boolean\n readonly hasMcp: boolean\n readonly hasSubagents: boolean\n /** 0..1 — fraction of richness signals present (prompt-depth + the four levers). */\n readonly richness: number\n /** True when the supervisor authored a stub instead of a real profile. */\n readonly thin: boolean\n /** The specific reasons it is thin (empty when rich) — used in the finding's action. */\n readonly reasons: string[]\n}\n\n/** Read the system prompt from any authored shape: canonical `prompt.systemPrompt`, the sandbox\n * `prompt.system` convention, or a bare-string `prompt`. */\nfunction resolveSystemPrompt(profile: AgentProfile): string {\n const pr = (profile as { prompt?: unknown }).prompt\n if (typeof pr === 'string') return pr\n if (pr && typeof pr === 'object') {\n const o = pr as { systemPrompt?: unknown; system?: unknown }\n if (typeof o.systemPrompt === 'string') return o.systemPrompt\n if (typeof o.system === 'string') return o.system\n }\n return ''\n}\n\n/** OBSERVE one authored `AgentProfile` and score its richness (no judge verdict is read). The task\n * context (`needsMcp`) lets a domain say \"this work needs a data/tool MCP\" so a missing MCP counts. */\nexport function assessAuthoredProfile(\n profile: AgentProfile,\n opts?: { needsMcp?: boolean; thresholds?: Partial<ProfileRichnessThresholds> },\n): ProfileRichness {\n const th = { ...defaultProfileRichnessThresholds, ...(opts?.thresholds ?? {}) }\n const systemPrompt = resolveSystemPrompt(profile)\n const trimmed = systemPrompt.trim()\n const systemPromptChars = trimmed.length\n const systemPromptLines = trimmed\n ? trimmed.split('\\n').filter((l) => l.trim().length > 0).length\n : 0\n const sentenceCount = trimmed\n ? (trimmed.match(/[.!?](\\s|$)/g) ?? []).length || (trimmed ? 1 : 0)\n : 0\n const hasDescription =\n typeof profile.description === 'string' && profile.description.trim().length > 0\n const tools = (profile as { tools?: Record<string, unknown> }).tools\n const hasTools = !!tools && Object.keys(tools).length > 0\n const skills = (profile.resources as { skills?: unknown[] } | undefined)?.skills\n const hasSkills = Array.isArray(skills) && skills.length > 0\n const mcp = (profile as { mcp?: Record<string, unknown> }).mcp\n const hasMcp = !!mcp && Object.keys(mcp).length > 0\n const subagents = (profile as { subagents?: Record<string, unknown> }).subagents\n const hasSubagents = !!subagents && Object.keys(subagents).length > 0\n\n const reasons: string[] = []\n const promptThin =\n systemPromptChars < th.minSystemPromptChars || systemPromptLines < th.minSystemPromptLines\n if (promptThin)\n reasons.push(\n `system prompt is thin (${systemPromptChars} chars, ${systemPromptLines} lines; need ≥${th.minSystemPromptChars} chars and ≥${th.minSystemPromptLines} lines)`,\n )\n if (!hasTools)\n reasons.push('no tools granted (a worker can only act through the tools you grant it)')\n if (!hasSkills) reasons.push('no skills attached (no reusable how-to notes injected)')\n if (opts?.needsMcp && !hasMcp) reasons.push('no MCP server, but the task needs data/tool access')\n\n // Richness = fraction of signals present. Prompt-depth is one signal; the four levers are the rest.\n const signals = [!promptThin, hasTools, hasSkills, hasDescription, opts?.needsMcp ? hasMcp : true]\n const richness = signals.filter(Boolean).length / signals.length\n // THIN ⟺ the prompt is a stub OR the worker has no levers at all (no tools AND no skills AND no mcp).\n const thin = promptThin || (!hasTools && !hasSkills && !hasMcp)\n\n return {\n name: profile.name ?? 'worker',\n systemPrompt,\n systemPromptChars,\n systemPromptLines,\n sentenceCount,\n hasDescription,\n hasTools,\n hasSkills,\n hasMcp,\n hasSubagents,\n richness,\n thin,\n reasons,\n }\n}\n\n/** Turn a {@link ProfileRichness} verdict into a bus-routable `AnalystFinding` (area `profile-quality`).\n * Severity scales with thinness; the recommended action names the MISSING lever so the supervisor can\n * re-author. `subject` = the worker name so per-worker findings diff cleanly across re-authors. */\nexport function profileRichnessFinding(\n richness: ProfileRichness,\n opts?: { analystId?: string; runId?: string },\n): AnalystFinding {\n const analyst_id = opts?.analystId ?? 'profile-richness'\n const subject = richness.name\n const claim = richness.thin\n ? `Worker \"${richness.name}\" was authored as a THIN profile: ${richness.reasons.join('; ')}.`\n : `Worker \"${richness.name}\" was authored as a rich profile (richness ${(richness.richness * 100).toFixed(0)}%).`\n const severity: AnalystFinding['severity'] = richness.thin\n ? richness.richness < 0.25\n ? 'high'\n : 'medium'\n : 'info'\n return makeFinding({\n analyst_id,\n severity,\n area: 'profile-quality',\n claim,\n subject,\n confidence: 0.9,\n evidence_refs: [\n {\n kind: 'metric',\n uri: `profile:${subject}`,\n excerpt: `chars=${richness.systemPromptChars} lines=${richness.systemPromptLines} tools=${richness.hasTools} skills=${richness.hasSkills} mcp=${richness.hasMcp} richness=${richness.richness.toFixed(2)}`,\n },\n ],\n ...(richness.thin\n ? { recommended_action: `Re-author \"${richness.name}\" with: ${richness.reasons.join('; ')}.` }\n : {}),\n id_basis: computeFindingId({\n analyst_id,\n area: 'profile-quality',\n subject,\n claim: `richness:${richness.thin ? 'thin' : 'rich'}`,\n }),\n })\n}\n","/**\n *\n * `delegate` — the one generic delegation verb. You hand it an INTENT (what you want done) and it\n * hands that intent to a default AUTHORING supervisor: a router-brained supervisor whose standing\n * instruction is `supervisorInstructions()` (the authoring-agent-profiles skill). The supervisor\n * DECOMPOSES the intent and AUTHORS the worker profile it needs per sub-task — there is NO hardcoded\n * coder/researcher profile here. That is the whole point: `delegate('fix the failing test', …)` and\n * `delegate('research X and cite sources', …)` route through the SAME front door; the supervisor\n * writes a code-shaped or research-shaped worker on its own.\n *\n * It is a thin wrapper over `supervise()` — the one front door — so the conserved-budget pool, the\n * completion oracle (`deliverable`), the coordination toolbox, and equal-compute accounting all come\n * for free; nothing is hand-rolled. The result is `supervise()`'s `SupervisedResult` returned\n * UNCHANGED, so its `spentTotal` (`{ iterations, tokens, usd, ms }`) rides straight back to the\n * caller on BOTH paths — a `winner` carries the delivered worker's spend, a `no-winner` carries the\n * spend incurred before it failed. That cost channel means a `delegate()` caller always learns what\n * the delegation actually spent.\n *\n * @experimental\n */\n\nimport { ConfigError } from '../../errors'\nimport type { RouterTransportConfig } from '../router-client'\nimport type { DeliverableSpec } from './completion-gate'\nimport type { ExecutorConfig } from './runtime'\nimport { supervise } from './supervise'\nimport type { SupervisorProfile } from './supervisor-agent'\nimport type { Budget, SupervisedResult } from './types'\n\n/** The conserved pool a `delegate()` call applies when the caller does not pass its own `budget`.\n * A modest token ceiling + a small iteration ceiling — generous enough for a few-worker decompose,\n * bounded enough that an unsupervised intent cannot run away. Callers override via `opts.budget`. */\nexport const defaultDelegateBudget: Budget = { maxIterations: 50, maxTokens: 200_000 }\n\n/** Inputs to {@link delegate}. The intent is the first positional arg; everything here is optional\n * with explicit execution identity, so the common call names one exact supervisor profile. */\nexport interface DelegateOptions<Out = unknown> {\n /** The completion oracle (settled ⟺ delivered) the authored workers settle against. Strongly\n * recommended — without it the supervisor trusts a worker's self-report. For a code intent,\n * `patchDelivered()` is the canonical example; for a free-form answer, a content check. */\n readonly deliverable?: DeliverableSpec<Out>\n /** WHERE the authored workers run — the worker-execution backend (`router-tools` / `sandbox` /\n * `cli-worktree` / …). The supervisor authors the worker PROFILE; this is the substrate it runs\n * on. Provide this OR `makeWorkerAgent`-style wiring through `supervise()` is unavailable. */\n readonly backend?: ExecutorConfig\n /** The conserved compute pool for the whole delegation. Defaults to {@link defaultDelegateBudget}. */\n readonly budget?: Budget\n /** Exact executable authoring supervisor. Model, prompt, harness, and provider live here. */\n readonly supervisorProfile: SupervisorProfile\n /** Router endpoint/auth for a `cli-base` supervisor; contains no behavioral settings. */\n readonly router: RouterTransportConfig\n /** Restrict the run to this subset of models (forwarded to `supervise()`). */\n readonly allowedModels?: readonly string[]\n readonly runId?: string\n}\n\n/**\n * Delegate an INTENT to a default authoring supervisor and return its `SupervisedResult` unchanged.\n *\n * The supervisor authors + spawns whatever worker the intent needs over the conserved-budget pool;\n * `result.spentTotal` reports what the whole delegation actually cost. A `winner` result carries the\n * authored worker's delivered output; a `no-winner` result names why (never a fabricated success).\n */\nexport async function delegate<Out = unknown>(\n intent: string,\n opts: DelegateOptions<Out>,\n): Promise<SupervisedResult<Out>> {\n if (typeof intent !== 'string' || intent.trim().length === 0) {\n throw new ConfigError('delegate: `intent` must be a non-empty string')\n }\n return supervise(opts.supervisorProfile, intent, {\n budget: opts.budget ?? defaultDelegateBudget,\n ...(opts.backend ? { backend: opts.backend } : {}),\n ...(opts.deliverable ? { deliverable: opts.deliverable as DeliverableSpec<unknown> } : {}),\n router: opts.router,\n ...(opts.allowedModels ? { allowedModels: opts.allowedModels } : {}),\n ...(opts.runId ? { runId: opts.runId } : {}),\n }) as Promise<SupervisedResult<Out>>\n}\n"],"mappings":";;;;;;;;;;;;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K;EACb,GAAI,KAAK,gBAAgB,EAAE,eAAe,KAAK,cAAc,IAAI,CAAC;EAClE,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;CAC5C,CAAC;AACH"}
@@ -0,0 +1,358 @@
1
+ import { o as NotFoundError } from "./errors-CDZ8XsVj.js";
2
+ //#region src/mcp/feedback-store.ts
3
+ /** In-memory `FeedbackStore` — suitable for single-process use and tests. @stable */
4
+ var InMemoryFeedbackStore = class {
5
+ events = [];
6
+ async put(event) {
7
+ this.events.push({ ...event });
8
+ }
9
+ async list(filter = {}) {
10
+ let out = this.events;
11
+ if (filter.namespace !== void 0) out = out.filter((event) => event.namespace === filter.namespace);
12
+ if (filter.refersToRef !== void 0) out = out.filter((event) => event.refersTo.ref === filter.refersToRef);
13
+ return out.map((event) => ({ ...event }));
14
+ }
15
+ };
16
+ /**
17
+ * Project a `FeedbackEvent` down to the snapshot shape carried on
18
+ * `delegation_history` entries.
19
+ *
20
+ * @stable
21
+ */
22
+ function eventToSnapshot(event) {
23
+ const snap = {
24
+ id: event.id,
25
+ score: event.rating.score,
26
+ by: event.by,
27
+ notes: event.rating.notes,
28
+ capturedAt: event.capturedAt
29
+ };
30
+ if (event.rating.label) snap.label = event.rating.label;
31
+ return snap;
32
+ }
33
+ //#endregion
34
+ //#region src/mcp/tools/delegate-feedback.ts
35
+ /** MCP tool name for the `delegate_feedback` feedback-recording tool. @stable */
36
+ const DELEGATE_FEEDBACK_TOOL_NAME = "delegate_feedback";
37
+ /** Human-readable description of the `delegate_feedback` MCP tool, injected into the tool manifest. @stable */
38
+ const DELEGATE_FEEDBACK_DESCRIPTION = [
39
+ "Record feedback on a delegation, artifact, or outcome. Synchronous — the",
40
+ "event is durably stored when this call returns.",
41
+ "",
42
+ "Use when: you (the agent), the user, or a downstream judge has formed an",
43
+ "opinion about a piece of work and want it persisted for calibration,",
44
+ "pricing, or future routing. Every call is a new event — multiple ratings",
45
+ "on the same target are expected and never deduped.",
46
+ "",
47
+ "`refersTo.kind`:",
48
+ " - \"delegation\": ref is a taskId returned by delegate_ui_audit",
49
+ " - \"artifact\": ref is a URI/path/git-sha — anything you can dereference",
50
+ " - \"outcome\": ref is a free-form description of a downstream result",
51
+ "",
52
+ "`by`:",
53
+ " - \"agent\": the agent itself rated the work",
54
+ " - \"user\": the human user rated it",
55
+ " - \"downstream-judge\": an automated evaluator emitted the rating",
56
+ "",
57
+ "When ref names a known taskId, the rating is also attached to the",
58
+ "delegation record so delegation_history surfaces it inline."
59
+ ].join("\n");
60
+ /** JSON Schema for `delegate_feedback` tool arguments (`refersTo`, `rating`, `by`, optional fields). @stable */
61
+ const DELEGATE_FEEDBACK_INPUT_SCHEMA = {
62
+ type: "object",
63
+ properties: {
64
+ refersTo: {
65
+ type: "object",
66
+ properties: {
67
+ kind: {
68
+ type: "string",
69
+ enum: [
70
+ "delegation",
71
+ "artifact",
72
+ "outcome"
73
+ ]
74
+ },
75
+ ref: { type: "string" }
76
+ },
77
+ required: ["kind", "ref"],
78
+ additionalProperties: false
79
+ },
80
+ rating: {
81
+ type: "object",
82
+ properties: {
83
+ score: {
84
+ type: "number",
85
+ minimum: 0,
86
+ maximum: 1
87
+ },
88
+ label: {
89
+ type: "string",
90
+ enum: [
91
+ "good",
92
+ "bad",
93
+ "neutral",
94
+ "mixed"
95
+ ]
96
+ },
97
+ notes: { type: "string" }
98
+ },
99
+ required: ["score", "notes"],
100
+ additionalProperties: false
101
+ },
102
+ by: {
103
+ type: "string",
104
+ enum: [
105
+ "agent",
106
+ "user",
107
+ "downstream-judge"
108
+ ]
109
+ },
110
+ capturedAt: { type: "string" },
111
+ namespace: { type: "string" }
112
+ },
113
+ required: [
114
+ "refersTo",
115
+ "rating",
116
+ "by"
117
+ ],
118
+ additionalProperties: false
119
+ };
120
+ /** Parse and validate raw MCP tool input into typed `DelegateFeedbackArgs`; throws `TypeError` on bad input. @stable */
121
+ function validateDelegateFeedbackArgs(raw) {
122
+ if (raw === null || typeof raw !== "object") throw new TypeError("delegate_feedback: arguments must be an object");
123
+ const value = raw;
124
+ const refersTo = validateRefersTo(value.refersTo);
125
+ const rating = validateRating(value.rating);
126
+ const by = value.by;
127
+ if (by !== "agent" && by !== "user" && by !== "downstream-judge") throw new TypeError("delegate_feedback: `by` must be one of \"agent\" | \"user\" | \"downstream-judge\"");
128
+ const args = {
129
+ refersTo,
130
+ rating,
131
+ by
132
+ };
133
+ if (value.capturedAt !== void 0) {
134
+ if (typeof value.capturedAt !== "string" || Number.isNaN(Date.parse(value.capturedAt))) throw new TypeError("delegate_feedback: `capturedAt` must be an ISO datetime");
135
+ args.capturedAt = value.capturedAt;
136
+ }
137
+ if (typeof value.namespace === "string") args.namespace = value.namespace;
138
+ return args;
139
+ }
140
+ function validateRefersTo(raw) {
141
+ if (raw === null || typeof raw !== "object") throw new TypeError("delegate_feedback: `refersTo` must be an object");
142
+ const value = raw;
143
+ const kind = value.kind;
144
+ if (kind !== "delegation" && kind !== "artifact" && kind !== "outcome") throw new TypeError("delegate_feedback: `refersTo.kind` must be one of \"delegation\" | \"artifact\" | \"outcome\"");
145
+ const ref = value.ref;
146
+ if (typeof ref !== "string" || ref.trim().length === 0) throw new TypeError("delegate_feedback: `refersTo.ref` must be a non-empty string");
147
+ return {
148
+ kind,
149
+ ref: ref.trim()
150
+ };
151
+ }
152
+ function validateRating(raw) {
153
+ if (raw === null || typeof raw !== "object") throw new TypeError("delegate_feedback: `rating` must be an object");
154
+ const value = raw;
155
+ const score = Number(value.score);
156
+ if (!Number.isFinite(score) || score < 0 || score > 1) throw new RangeError("delegate_feedback: `rating.score` must be a number in [0, 1]");
157
+ const notes = value.notes;
158
+ if (typeof notes !== "string") throw new TypeError("delegate_feedback: `rating.notes` must be a string");
159
+ const rating = {
160
+ score,
161
+ notes
162
+ };
163
+ const label = value.label;
164
+ if (label !== void 0) {
165
+ if (label !== "good" && label !== "bad" && label !== "neutral" && label !== "mixed") throw new TypeError("delegate_feedback: `rating.label` must be one of \"good\" | \"bad\" | \"neutral\" | \"mixed\"");
166
+ rating.label = label;
167
+ }
168
+ return rating;
169
+ }
170
+ /** Build the MCP tool handler that persists feedback events and attaches them to delegation records. @stable */
171
+ function createDelegateFeedbackHandler(options) {
172
+ const generateId = options.generateId ?? randomFeedbackId;
173
+ const now = options.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
174
+ return async (raw) => {
175
+ const args = validateDelegateFeedbackArgs(raw);
176
+ const id = generateId();
177
+ const event = {
178
+ id,
179
+ refersTo: args.refersTo,
180
+ rating: args.rating,
181
+ by: args.by,
182
+ capturedAt: args.capturedAt ?? now(),
183
+ namespace: args.namespace
184
+ };
185
+ await options.store.put(event);
186
+ if (args.refersTo.kind === "delegation") options.queue.attachFeedback(args.refersTo.ref, eventToSnapshot(event));
187
+ return {
188
+ recorded: true,
189
+ id
190
+ };
191
+ };
192
+ }
193
+ function randomFeedbackId() {
194
+ return `fbk-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
195
+ }
196
+ //#endregion
197
+ //#region src/mcp/types.ts
198
+ /**
199
+ * Every delegation profile a queued record can carry. One owner: the tool schemas and validators
200
+ * that filter on a profile read this list, so a profile added here cannot be one a tool refuses.
201
+ * @experimental
202
+ */
203
+ const delegationProfiles = [
204
+ "coder",
205
+ "researcher",
206
+ "ui-auditor"
207
+ ];
208
+ //#endregion
209
+ //#region src/mcp/tools/delegation-history.ts
210
+ /** MCP tool name for the `delegation_history` read-past-delegations tool. @stable */
211
+ const DELEGATION_HISTORY_TOOL_NAME = "delegation_history";
212
+ /** Human-readable description of the `delegation_history` MCP tool, injected into the tool manifest. @stable */
213
+ const DELEGATION_HISTORY_DESCRIPTION = [
214
+ "Read past delegations newest-first. Each entry carries the original",
215
+ "arguments, current status, cost, and any feedback attached via",
216
+ "delegate_feedback.",
217
+ "",
218
+ "Use when: you want to introspect prior decisions — \"have I asked this",
219
+ "question before?",
220
+ "did the last patch land?",
221
+ "what's the historical",
222
+ "success rate of coder delegations on this repo?\". Feed the results back",
223
+ "into your own routing and calibration.",
224
+ "",
225
+ "Each entry carries `hasTrace` — when true, the full loop-trace span tree",
226
+ "is retrievable via delegation_status { taskId, includeTrace: true }.",
227
+ "",
228
+ `Filters: \`namespace\` (multi-tenant scope), \`profile\` (${delegationProfiles.map((profile) => `"${profile}"`).join(" | ")}),`,
229
+ "`since` (ISO date — only delegations started at-or-after). `limit` defaults",
230
+ "to 50, capped at 500."
231
+ ].join("\n");
232
+ /** JSON Schema for `delegation_history` tool arguments (optional `namespace`, `profile`, `since`, `limit`). @stable */
233
+ const DELEGATION_HISTORY_INPUT_SCHEMA = {
234
+ type: "object",
235
+ properties: {
236
+ namespace: { type: "string" },
237
+ profile: {
238
+ type: "string",
239
+ enum: delegationProfiles
240
+ },
241
+ since: {
242
+ type: "string",
243
+ description: "ISO datetime — earliest startedAt to include."
244
+ },
245
+ limit: {
246
+ type: "integer",
247
+ minimum: 1,
248
+ maximum: 500
249
+ }
250
+ },
251
+ additionalProperties: false
252
+ };
253
+ /** Parse and validate raw MCP tool input into typed `DelegationHistoryArgs`; throws `TypeError` on bad input. @stable */
254
+ function validateDelegationHistoryArgs(raw) {
255
+ if (raw === void 0 || raw === null) return {};
256
+ if (typeof raw !== "object") throw new TypeError("delegation_history: arguments must be an object");
257
+ const value = raw;
258
+ const out = {};
259
+ if (value.namespace !== void 0) {
260
+ if (typeof value.namespace !== "string") throw new TypeError("delegation_history: `namespace` must be a string");
261
+ out.namespace = value.namespace;
262
+ }
263
+ if (value.profile !== void 0) {
264
+ if (!delegationProfiles.includes(value.profile)) throw new TypeError(`delegation_history: \`profile\` must be one of ${delegationProfiles.join(", ")}`);
265
+ out.profile = value.profile;
266
+ }
267
+ if (value.since !== void 0) {
268
+ if (typeof value.since !== "string" || Number.isNaN(Date.parse(value.since))) throw new TypeError("delegation_history: `since` must be an ISO datetime");
269
+ out.since = value.since;
270
+ }
271
+ if (value.limit !== void 0) {
272
+ const n = Number(value.limit);
273
+ if (!Number.isFinite(n) || n < 1 || n > 500) throw new RangeError("delegation_history: `limit` must be an integer in [1, 500]");
274
+ out.limit = Math.trunc(n);
275
+ }
276
+ return out;
277
+ }
278
+ /** Build the MCP tool handler that reads filtered past delegations from a `DelegationTaskQueue`. @stable */
279
+ function createDelegationHistoryHandler(options) {
280
+ return async (raw) => {
281
+ const args = validateDelegationHistoryArgs(raw);
282
+ return { delegations: options.queue.history(args) };
283
+ };
284
+ }
285
+ //#endregion
286
+ //#region src/mcp/tools/delegation-status.ts
287
+ /**
288
+ *
289
+ * `delegation_status` MCP tool — synchronous poll. Returns the current
290
+ * state machine + optional progress + final result (when terminal).
291
+ *
292
+ * @stable
293
+ */
294
+ /** MCP tool name for the `delegation_status` synchronous-poll tool. @stable */
295
+ const DELEGATION_STATUS_TOOL_NAME = "delegation_status";
296
+ /** Human-readable description of the `delegation_status` MCP tool, injected into the tool manifest. @stable */
297
+ const DELEGATION_STATUS_DESCRIPTION = [
298
+ "Poll the status of an async delegation. Returns the current state",
299
+ "(pending | running | completed | failed | cancelled), optional progress,",
300
+ "and the final result when status === \"completed\".",
301
+ "",
302
+ "Use when: you previously kicked off an async delegation (delegate_ui_audit)",
303
+ "and need to know whether the work is done. The agent's right rhythm is to",
304
+ "call this every minute or two while waiting; do not busy-poll.",
305
+ "",
306
+ "For a completed delegate_ui_audit run, `result.output` is the array of UI",
307
+ "findings — one self-contained Markdown finding per issue, each with an",
308
+ "embedded screenshot and a suggested fix.",
309
+ "",
310
+ "Pass includeTrace: true to also receive the journaled loop-trace span",
311
+ "tree (loop → round → iteration, with placement/cost/verdict metadata).",
312
+ "Default false — keep routine polls light.",
313
+ "",
314
+ "Throws NotFoundError when taskId is unknown — never silently returns",
315
+ "`pending` for a typo."
316
+ ].join("\n");
317
+ /** JSON Schema for `delegation_status` tool arguments (`taskId` + optional `includeTrace`). @stable */
318
+ const DELEGATION_STATUS_INPUT_SCHEMA = {
319
+ type: "object",
320
+ properties: {
321
+ taskId: {
322
+ type: "string",
323
+ description: "Returned by delegate_ui_audit."
324
+ },
325
+ includeTrace: {
326
+ type: "boolean",
327
+ description: "Also return the journaled loop-trace span tree for this delegation. Default false."
328
+ }
329
+ },
330
+ required: ["taskId"],
331
+ additionalProperties: false
332
+ };
333
+ /** Parse and validate raw MCP tool input into typed `DelegationStatusArgs`; throws `TypeError` on bad input. @stable */
334
+ function validateDelegationStatusArgs(raw) {
335
+ if (raw === null || typeof raw !== "object") throw new TypeError("delegation_status: arguments must be an object");
336
+ const value = raw;
337
+ const taskId = value.taskId;
338
+ if (typeof taskId !== "string" || taskId.trim().length === 0) throw new TypeError("delegation_status: `taskId` must be a non-empty string");
339
+ const out = { taskId: taskId.trim() };
340
+ if (value.includeTrace !== void 0) {
341
+ if (typeof value.includeTrace !== "boolean") throw new TypeError("delegation_status: `includeTrace` must be a boolean");
342
+ out.includeTrace = value.includeTrace;
343
+ }
344
+ return out;
345
+ }
346
+ /** Build the MCP tool handler that polls a `DelegationTaskQueue` for task status. @stable */
347
+ function createDelegationStatusHandler(options) {
348
+ return async (raw) => {
349
+ const args = validateDelegationStatusArgs(raw);
350
+ const status = options.queue.status(args.taskId, args.includeTrace !== void 0 ? { includeTrace: args.includeTrace } : void 0);
351
+ if (!status) throw new NotFoundError(`delegation_status: unknown taskId "${args.taskId}"`);
352
+ return status;
353
+ };
354
+ }
355
+ //#endregion
356
+ export { InMemoryFeedbackStore as _, validateDelegationStatusArgs as a, DELEGATION_HISTORY_TOOL_NAME as c, delegationProfiles as d, DELEGATE_FEEDBACK_DESCRIPTION as f, validateDelegateFeedbackArgs as g, createDelegateFeedbackHandler as h, createDelegationStatusHandler as i, createDelegationHistoryHandler as l, DELEGATE_FEEDBACK_TOOL_NAME as m, DELEGATION_STATUS_INPUT_SCHEMA as n, DELEGATION_HISTORY_DESCRIPTION as o, DELEGATE_FEEDBACK_INPUT_SCHEMA as p, DELEGATION_STATUS_TOOL_NAME as r, DELEGATION_HISTORY_INPUT_SCHEMA as s, DELEGATION_STATUS_DESCRIPTION as t, validateDelegationHistoryArgs as u, eventToSnapshot as v };
357
+
358
+ //# sourceMappingURL=delegation-status-BlsbSeOB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation-status-BlsbSeOB.js","names":[],"sources":["../src/mcp/feedback-store.ts","../src/mcp/tools/delegate-feedback.ts","../src/mcp/types.ts","../src/mcp/tools/delegation-history.ts","../src/mcp/tools/delegation-status.ts"],"sourcesContent":["/**\n *\n * Feedback persistence surface for the MCP layer.\n *\n * Feedback storage is product policy, so the MCP layer depends on this narrow\n * interface instead of choosing a knowledge store. The default implementation\n * is in-memory; consumers wire their own durable adapter via\n * `createMcpServer({ feedbackStore })`.\n *\n * Feedback events are append-only: every rating is a new event with a\n * fresh id, even when the same delegation is rated multiple times. The\n * caller decides how to roll up scores downstream.\n *\n * @stable\n */\n\nimport type { DelegateFeedbackArgs, DelegationFeedbackSnapshot } from './types'\n\n/** @stable */\nexport interface FeedbackEvent {\n id: string\n refersTo: DelegateFeedbackArgs['refersTo']\n rating: DelegateFeedbackArgs['rating']\n by: DelegateFeedbackArgs['by']\n capturedAt: string\n namespace?: string\n}\n\n/** @stable */\nexport interface FeedbackStore {\n /** Append a new event. Never dedupes — every rating is its own event. */\n put(event: FeedbackEvent): Promise<void>\n /**\n * List events filtered by `namespace`. When `namespace` is omitted, list\n * across all namespaces. Returns events in insertion order.\n */\n list(filter?: { namespace?: string; refersToRef?: string }): Promise<FeedbackEvent[]>\n}\n\n/** In-memory `FeedbackStore` — suitable for single-process use and tests. @stable */\nexport class InMemoryFeedbackStore implements FeedbackStore {\n private readonly events: FeedbackEvent[] = []\n\n async put(event: FeedbackEvent): Promise<void> {\n this.events.push({ ...event })\n }\n\n async list(filter: { namespace?: string; refersToRef?: string } = {}): Promise<FeedbackEvent[]> {\n let out = this.events\n if (filter.namespace !== undefined) {\n out = out.filter((event) => event.namespace === filter.namespace)\n }\n if (filter.refersToRef !== undefined) {\n out = out.filter((event) => event.refersTo.ref === filter.refersToRef)\n }\n return out.map((event) => ({ ...event }))\n }\n}\n\n/**\n * Project a `FeedbackEvent` down to the snapshot shape carried on\n * `delegation_history` entries.\n *\n * @stable\n */\nexport function eventToSnapshot(event: FeedbackEvent): DelegationFeedbackSnapshot {\n const snap: DelegationFeedbackSnapshot = {\n id: event.id,\n score: event.rating.score,\n by: event.by,\n notes: event.rating.notes,\n capturedAt: event.capturedAt,\n }\n if (event.rating.label) snap.label = event.rating.label\n return snap\n}\n","/**\n *\n * `delegate_feedback` MCP tool — synchronous record of agent / user /\n * downstream-judge feedback on a delegation, artifact, or outcome.\n *\n * The store is append-only. Every rating is its own event; no dedupe.\n * When `refersTo.kind === 'delegation'`, the snapshot is also attached\n * to the matching queue record so `delegation_history` surfaces it\n * inline without a join.\n *\n * @stable\n */\n\nimport type { FeedbackStore } from '../feedback-store'\nimport { eventToSnapshot } from '../feedback-store'\nimport type { DelegationTaskQueue } from '../task-queue'\nimport type {\n DelegateFeedbackArgs,\n DelegateFeedbackResult,\n FeedbackRating,\n FeedbackRefersTo,\n} from '../types'\n\n/** MCP tool name for the `delegate_feedback` feedback-recording tool. @stable */\nexport const DELEGATE_FEEDBACK_TOOL_NAME = 'delegate_feedback'\n\n/** Human-readable description of the `delegate_feedback` MCP tool, injected into the tool manifest. @stable */\nexport const DELEGATE_FEEDBACK_DESCRIPTION = [\n 'Record feedback on a delegation, artifact, or outcome. Synchronous — the',\n 'event is durably stored when this call returns.',\n '',\n 'Use when: you (the agent), the user, or a downstream judge has formed an',\n 'opinion about a piece of work and want it persisted for calibration,',\n 'pricing, or future routing. Every call is a new event — multiple ratings',\n 'on the same target are expected and never deduped.',\n '',\n '`refersTo.kind`:',\n ' - \"delegation\": ref is a taskId returned by delegate_ui_audit',\n ' - \"artifact\": ref is a URI/path/git-sha — anything you can dereference',\n ' - \"outcome\": ref is a free-form description of a downstream result',\n '',\n '`by`:',\n ' - \"agent\": the agent itself rated the work',\n ' - \"user\": the human user rated it',\n ' - \"downstream-judge\": an automated evaluator emitted the rating',\n '',\n 'When ref names a known taskId, the rating is also attached to the',\n 'delegation record so delegation_history surfaces it inline.',\n].join('\\n')\n\n/** JSON Schema for `delegate_feedback` tool arguments (`refersTo`, `rating`, `by`, optional fields). @stable */\nexport const DELEGATE_FEEDBACK_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n refersTo: {\n type: 'object',\n properties: {\n kind: { type: 'string', enum: ['delegation', 'artifact', 'outcome'] },\n ref: { type: 'string' },\n },\n required: ['kind', 'ref'],\n additionalProperties: false,\n },\n rating: {\n type: 'object',\n properties: {\n score: { type: 'number', minimum: 0, maximum: 1 },\n label: { type: 'string', enum: ['good', 'bad', 'neutral', 'mixed'] },\n notes: { type: 'string' },\n },\n required: ['score', 'notes'],\n additionalProperties: false,\n },\n by: { type: 'string', enum: ['agent', 'user', 'downstream-judge'] },\n capturedAt: { type: 'string' },\n namespace: { type: 'string' },\n },\n required: ['refersTo', 'rating', 'by'],\n additionalProperties: false,\n} as const\n\n/** Parse and validate raw MCP tool input into typed `DelegateFeedbackArgs`; throws `TypeError` on bad input. @stable */\nexport function validateDelegateFeedbackArgs(raw: unknown): DelegateFeedbackArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const refersTo = validateRefersTo(value.refersTo)\n const rating = validateRating(value.rating)\n const by = value.by\n if (by !== 'agent' && by !== 'user' && by !== 'downstream-judge') {\n throw new TypeError(\n 'delegate_feedback: `by` must be one of \"agent\" | \"user\" | \"downstream-judge\"',\n )\n }\n const args: DelegateFeedbackArgs = { refersTo, rating, by }\n if (value.capturedAt !== undefined) {\n if (typeof value.capturedAt !== 'string' || Number.isNaN(Date.parse(value.capturedAt))) {\n throw new TypeError('delegate_feedback: `capturedAt` must be an ISO datetime')\n }\n args.capturedAt = value.capturedAt\n }\n if (typeof value.namespace === 'string') args.namespace = value.namespace\n return args\n}\n\nfunction validateRefersTo(raw: unknown): FeedbackRefersTo {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: `refersTo` must be an object')\n }\n const value = raw as Record<string, unknown>\n const kind = value.kind\n if (kind !== 'delegation' && kind !== 'artifact' && kind !== 'outcome') {\n throw new TypeError(\n 'delegate_feedback: `refersTo.kind` must be one of \"delegation\" | \"artifact\" | \"outcome\"',\n )\n }\n const ref = value.ref\n if (typeof ref !== 'string' || ref.trim().length === 0) {\n throw new TypeError('delegate_feedback: `refersTo.ref` must be a non-empty string')\n }\n return { kind, ref: ref.trim() }\n}\n\nfunction validateRating(raw: unknown): FeedbackRating {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: `rating` must be an object')\n }\n const value = raw as Record<string, unknown>\n const score = Number(value.score)\n if (!Number.isFinite(score) || score < 0 || score > 1) {\n throw new RangeError('delegate_feedback: `rating.score` must be a number in [0, 1]')\n }\n const notes = value.notes\n if (typeof notes !== 'string') {\n throw new TypeError('delegate_feedback: `rating.notes` must be a string')\n }\n const rating: FeedbackRating = { score, notes }\n const label = value.label\n if (label !== undefined) {\n if (label !== 'good' && label !== 'bad' && label !== 'neutral' && label !== 'mixed') {\n throw new TypeError(\n 'delegate_feedback: `rating.label` must be one of \"good\" | \"bad\" | \"neutral\" | \"mixed\"',\n )\n }\n rating.label = label\n }\n return rating\n}\n\n/** @stable */\nexport interface DelegateFeedbackHandlerOptions {\n queue: DelegationTaskQueue\n store: FeedbackStore\n generateId?: () => string\n now?: () => string\n}\n\n/** Build the MCP tool handler that persists feedback events and attaches them to delegation records. @stable */\nexport function createDelegateFeedbackHandler(\n options: DelegateFeedbackHandlerOptions,\n): (raw: unknown) => Promise<DelegateFeedbackResult> {\n const generateId = options.generateId ?? randomFeedbackId\n const now = options.now ?? (() => new Date().toISOString())\n return async (raw) => {\n const args = validateDelegateFeedbackArgs(raw)\n const id = generateId()\n const event = {\n id,\n refersTo: args.refersTo,\n rating: args.rating,\n by: args.by,\n capturedAt: args.capturedAt ?? now(),\n namespace: args.namespace,\n }\n await options.store.put(event)\n if (args.refersTo.kind === 'delegation') {\n options.queue.attachFeedback(args.refersTo.ref, eventToSnapshot(event))\n }\n return { recorded: true, id }\n }\n}\n\nfunction randomFeedbackId(): string {\n const t = Date.now().toString(36)\n const r = Math.random().toString(36).slice(2, 10)\n return `fbk-${t}-${r}`\n}\n","/**\n *\n * MCP delegation tool surface — the typed inputs/outputs the product agent\n * sees over the wire. These types are the contract; the JSON schemas under\n * `tools/*` mirror them for the MCP `tools/list` advertisement.\n *\n * Async semantics: `delegate_ui_audit` returns a `taskId` immediately. The\n * product agent polls `delegation_status` until the task transitions to\n * `completed` | `failed` | `cancelled`. `delegate_feedback` +\n * `delegation_history` are synchronous reads / writes against the local\n * task queue + feedback store.\n *\n * @experimental\n */\n\nimport type { CoderTask } from '../profiles/coder'\nimport type { ResearchSource } from '../profiles/researcher'\nimport type { UiFinding, UiLens } from '../profiles/ui-auditor/substrate'\nimport type { DelegationTraceSpan } from './delegation-trace'\nimport type { CoderOutput } from './detached-coder'\n\n/**\n * Every delegation profile a queued record can carry. One owner: the tool schemas and validators\n * that filter on a profile read this list, so a profile added here cannot be one a tool refuses.\n * @experimental\n */\nexport const delegationProfiles = ['coder', 'researcher', 'ui-auditor'] as const\n\n/** @experimental */\nexport type DelegationProfile = (typeof delegationProfiles)[number]\n\n/** @experimental */\nexport type DelegationStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'\n\n/**\n * Minimal `CoderTask` overrides exposed over the MCP wire. The full\n * `CoderTask` carries fields the kernel synthesizes from `goal` +\n * `repoRoot` — the agent only edits the few that materially gate\n * validator behavior.\n *\n * @experimental\n */\nexport interface DelegateCodeConfig {\n testCmd?: string\n typecheckCmd?: string\n forbiddenPaths?: string[]\n maxDiffLines?: number\n}\n\n/** @experimental */\nexport interface DelegateCodeArgs {\n /** Natural-language description of what the coder must accomplish. */\n goal: string\n /** Absolute path inside the sandbox where the repo lives. */\n repoRoot: string\n /** Optional free-form context the agent surfaces in the prompt prelude. */\n contextHint?: string\n /**\n * When > 1, dispatches `multiHarnessCoderFanout` across the delegate's configured exact profiles\n * and picks the highest-scoring passing patch. Default 1.\n */\n variants?: number\n /** Validator + prompt overrides the agent knows for this repo. */\n config?: DelegateCodeConfig\n /** Multi-tenant scope (customer-id, workspace-id). */\n namespace?: string\n}\n\n/** @experimental */\nexport interface DelegateCodeResult {\n taskId: string\n /** Best-effort hint — coder loops can take minutes-to-hours. */\n estimatedDurationMs?: number\n}\n\nexport type { ResearchSource }\n\n/** @experimental */\nexport interface DelegateResearchConfig {\n recencyWindow?: { since?: string; until?: string }\n maxItems?: number\n minConfidence?: number\n}\n\n/** @experimental */\nexport interface DelegateResearchArgs {\n question: string\n namespace: string\n scope?: string\n sources?: ResearchSource[]\n variants?: number\n config?: DelegateResearchConfig\n}\n\n/** @experimental */\nexport interface DelegateResearchResult {\n taskId: string\n estimatedDurationMs?: number\n}\n\n/** @experimental */\nexport interface FeedbackRefersTo {\n kind: 'delegation' | 'artifact' | 'outcome'\n /** For `'delegation'`, this is the taskId. */\n ref: string\n}\n\n/** @experimental */\nexport interface FeedbackRating {\n /** [0, 1]. */\n score: number\n label?: 'good' | 'bad' | 'neutral' | 'mixed'\n notes: string\n}\n\n/** @experimental */\nexport interface DelegateFeedbackArgs {\n refersTo: FeedbackRefersTo\n rating: FeedbackRating\n by: 'agent' | 'user' | 'downstream-judge'\n /** ISO timestamp; defaults to server clock when omitted. */\n capturedAt?: string\n namespace?: string\n}\n\n/** @experimental */\nexport interface DelegateFeedbackResult {\n recorded: true\n id: string\n}\n\n/** @experimental */\nexport interface DelegationStatusArgs {\n taskId: string\n /**\n * Return the delegation's compact loop-trace span tree alongside the\n * status. Default false — status polls stay light; opt in when you need\n * the topology (which iterations ran, where they were placed, what each\n * cost) rather than just the state machine.\n */\n includeTrace?: boolean\n}\n\n/** @experimental */\nexport interface DelegationProgress {\n iteration: number\n phase: string\n}\n\n/** @experimental */\nexport interface DelegationError {\n message: string\n kind: string\n}\n\n/**\n * Polymorphic `result` field: `CoderOutput` when the underlying profile\n * is `'coder'`, a structurally-typed research output when `'researcher'`.\n * The MCP wire carries it as JSON either way.\n *\n * @experimental\n */\nexport type DelegationResultPayload =\n | { profile: 'coder'; output: CoderOutput }\n | { profile: 'researcher'; output: ResearchOutputShape }\n | { profile: 'ui-auditor'; output: UiAuditorDelegationOutput }\n\n/**\n * Wire-shape of a completed UI-audit delegation. The `findings` array\n * contains every finding persisted to the workspace during the run,\n * already enriched with `id` and `createdAt` by the writer. `workspaceDir`\n * is the absolute path to the workspace; `indexFile` is the workspace-\n * relative path to the regenerated index.md.\n *\n * @experimental\n */\nexport interface UiAuditorDelegationOutput {\n workspaceDir: string\n indexFile: string\n findings: UiFinding[]\n /** Total iterations the loop ran for this delegation. */\n iterations: number\n}\n\n/** @experimental */\nexport type UiAuditLensFilter = readonly UiLens[]\n\n/** Optional per-route capture spec the agent surfaces over the wire. */\nexport interface DelegateUiAuditRoute {\n /** Stable route name (used in screenshot filenames + finding metadata). */\n name: string\n /** Fully-qualified URL. */\n url: string\n /** Viewports to capture at. Defaults to `[{ width: 1280, height: 800 }]`. */\n viewports?: readonly { width: number; height: number }[]\n /** Default false. Full-page captures for the broad lenses. */\n fullPage?: boolean\n /** Selector to wait for before capture. */\n waitFor?: string\n}\n\n/** @experimental */\nexport interface DelegateUiAuditConfig {\n /**\n * Lenses to iterate. Default: every lens except `'other'`. Order is\n * preserved — the driver iterates lens-by-lens.\n */\n lenses?: UiAuditLensFilter\n /** Maximum total iterations across all (lens × route) pairs. Default 33 (11 lenses × 3 routes). */\n maxIterations?: number\n /** Maximum concurrent iterations within a single plan() round. Default 2. */\n maxConcurrency?: number\n /** Free-form product context surfaced to the judge. */\n productContext?: string\n}\n\n/** @experimental */\nexport interface DelegateUiAuditArgs {\n /** Workspace root for the audit (absolute path). */\n workspaceDir: string\n /** Routes to audit. Must be non-empty. */\n routes: readonly DelegateUiAuditRoute[]\n /** Multi-tenant scope. */\n namespace?: string\n config?: DelegateUiAuditConfig\n}\n\n/** @experimental */\nexport interface DelegateUiAuditResult {\n taskId: string\n estimatedDurationMs?: number\n}\n\n/**\n * Provider-neutral research output carried over the MCP boundary. The MCP\n * layer accepts this structural shape instead of coupling its wire contract to\n * one research implementation.\n *\n * @experimental\n */\nexport interface ResearchOutputShape {\n items: unknown[]\n citations: unknown[]\n proposedWrites: unknown[]\n gaps?: string[]\n notes?: string\n [key: string]: unknown\n}\n\n/** @experimental */\nexport interface DelegationStatusResult {\n taskId: string\n profile: DelegationProfile\n status: DelegationStatus\n progress?: DelegationProgress\n result?: DelegationResultPayload\n error?: DelegationError\n costUsd?: number\n startedAt: string\n completedAt?: string\n /** Compact loop-trace span tree; present only when `includeTrace: true` was passed and spans were recorded. */\n trace?: DelegationTraceSpan[]\n /** Present when oldest trace spans were dropped to honor the trace caps. */\n traceTruncated?: true\n /** Inherited trace identity recorded at submit — join key into the caller's trace. */\n traceId?: string\n /** Caller span that dispatched the delegation, when one was inherited. */\n parentSpanId?: string\n}\n\n/** @experimental */\nexport interface DelegationHistoryArgs {\n namespace?: string\n profile?: DelegationProfile\n /** ISO date — only delegations started at-or-after `since` are returned. */\n since?: string\n /** Default 50. Hard cap 500. */\n limit?: number\n}\n\n/** @experimental */\nexport interface DelegationFeedbackSnapshot {\n id: string\n score: number\n label?: FeedbackRating['label']\n by: DelegateFeedbackArgs['by']\n notes: string\n capturedAt: string\n}\n\n/** @experimental */\nexport interface DelegationHistoryEntry {\n taskId: string\n profile: DelegationProfile\n namespace?: string\n args: DelegateCodeArgs | DelegateResearchArgs | DelegateUiAuditArgs\n status: DelegationStatus\n feedback?: DelegationFeedbackSnapshot[]\n costUsd?: number\n startedAt: string\n completedAt?: string\n /**\n * True when the record carries a journaled loop trace. History stays\n * light by design — fetch the spans via\n * `delegation_status { taskId, includeTrace: true }`.\n */\n hasTrace: boolean\n /** Inherited trace identity recorded at submit — join key into the caller's trace. */\n traceId?: string\n}\n\n/** @experimental */\nexport interface DelegationHistoryResult {\n delegations: DelegationHistoryEntry[]\n}\n\n/**\n * Re-export `CoderTask` so callers wiring custom delegates don't have to\n * import from `./profiles` themselves.\n *\n * @experimental\n */\nexport type { CoderOutput, CoderTask }\n","/**\n *\n * `delegation_history` MCP tool — synchronous read of past delegations.\n * The agent uses this for self-introspection — \"have I delegated this\n * kind of task before? did it work?\" — and calibration.\n *\n * @stable\n */\n\nimport type {\n DelegationHistoryArgs,\n DelegationHistoryResult,\n DelegationProfile,\n DelegationTaskQueue,\n} from '../task-queue'\nimport { delegationProfiles } from '../types'\n\n/** MCP tool name for the `delegation_history` read-past-delegations tool. @stable */\nexport const DELEGATION_HISTORY_TOOL_NAME = 'delegation_history'\n\n/** Human-readable description of the `delegation_history` MCP tool, injected into the tool manifest. @stable */\nexport const DELEGATION_HISTORY_DESCRIPTION = [\n 'Read past delegations newest-first. Each entry carries the original',\n 'arguments, current status, cost, and any feedback attached via',\n 'delegate_feedback.',\n '',\n 'Use when: you want to introspect prior decisions — \"have I asked this',\n 'question before?',\n 'did the last patch land?',\n \"what's the historical\",\n 'success rate of coder delegations on this repo?\". Feed the results back',\n 'into your own routing and calibration.',\n '',\n 'Each entry carries `hasTrace` — when true, the full loop-trace span tree',\n 'is retrievable via delegation_status { taskId, includeTrace: true }.',\n '',\n `Filters: \\`namespace\\` (multi-tenant scope), \\`profile\\` (${delegationProfiles\n .map((profile) => `\"${profile}\"`)\n .join(' | ')}),`,\n '`since` (ISO date — only delegations started at-or-after). `limit` defaults',\n 'to 50, capped at 500.',\n].join('\\n')\n\n/** JSON Schema for `delegation_history` tool arguments (optional `namespace`, `profile`, `since`, `limit`). @stable */\nexport const DELEGATION_HISTORY_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n namespace: { type: 'string' },\n profile: { type: 'string', enum: delegationProfiles },\n since: { type: 'string', description: 'ISO datetime — earliest startedAt to include.' },\n limit: { type: 'integer', minimum: 1, maximum: 500 },\n },\n additionalProperties: false,\n} as const\n\n/** Parse and validate raw MCP tool input into typed `DelegationHistoryArgs`; throws `TypeError` on bad input. @stable */\nexport function validateDelegationHistoryArgs(raw: unknown): DelegationHistoryArgs {\n if (raw === undefined || raw === null) return {}\n if (typeof raw !== 'object') {\n throw new TypeError('delegation_history: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const out: DelegationHistoryArgs = {}\n if (value.namespace !== undefined) {\n if (typeof value.namespace !== 'string') {\n throw new TypeError('delegation_history: `namespace` must be a string')\n }\n out.namespace = value.namespace\n }\n if (value.profile !== undefined) {\n if (!delegationProfiles.includes(value.profile as DelegationProfile)) {\n throw new TypeError(\n `delegation_history: \\`profile\\` must be one of ${delegationProfiles.join(', ')}`,\n )\n }\n out.profile = value.profile as DelegationProfile\n }\n if (value.since !== undefined) {\n if (typeof value.since !== 'string' || Number.isNaN(Date.parse(value.since))) {\n throw new TypeError('delegation_history: `since` must be an ISO datetime')\n }\n out.since = value.since\n }\n if (value.limit !== undefined) {\n const n = Number(value.limit)\n if (!Number.isFinite(n) || n < 1 || n > 500) {\n throw new RangeError('delegation_history: `limit` must be an integer in [1, 500]')\n }\n out.limit = Math.trunc(n)\n }\n return out\n}\n\n/** @stable */\nexport interface DelegationHistoryHandlerOptions {\n queue: DelegationTaskQueue\n}\n\n/** Build the MCP tool handler that reads filtered past delegations from a `DelegationTaskQueue`. @stable */\nexport function createDelegationHistoryHandler(\n options: DelegationHistoryHandlerOptions,\n): (raw: unknown) => Promise<DelegationHistoryResult> {\n return async (raw) => {\n const args = validateDelegationHistoryArgs(raw)\n return { delegations: options.queue.history(args) }\n }\n}\n","/**\n *\n * `delegation_status` MCP tool — synchronous poll. Returns the current\n * state machine + optional progress + final result (when terminal).\n *\n * @stable\n */\n\nimport { NotFoundError } from '../../errors'\nimport type {\n DelegationStatusArgs,\n DelegationStatusResult,\n DelegationTaskQueue,\n} from '../task-queue'\n\n/** MCP tool name for the `delegation_status` synchronous-poll tool. @stable */\nexport const DELEGATION_STATUS_TOOL_NAME = 'delegation_status'\n\n/** Human-readable description of the `delegation_status` MCP tool, injected into the tool manifest. @stable */\nexport const DELEGATION_STATUS_DESCRIPTION = [\n 'Poll the status of an async delegation. Returns the current state',\n '(pending | running | completed | failed | cancelled), optional progress,',\n 'and the final result when status === \"completed\".',\n '',\n 'Use when: you previously kicked off an async delegation (delegate_ui_audit)',\n \"and need to know whether the work is done. The agent's right rhythm is to\",\n 'call this every minute or two while waiting; do not busy-poll.',\n '',\n 'For a completed delegate_ui_audit run, `result.output` is the array of UI',\n 'findings — one self-contained Markdown finding per issue, each with an',\n 'embedded screenshot and a suggested fix.',\n '',\n 'Pass includeTrace: true to also receive the journaled loop-trace span',\n 'tree (loop → round → iteration, with placement/cost/verdict metadata).',\n 'Default false — keep routine polls light.',\n '',\n 'Throws NotFoundError when taskId is unknown — never silently returns',\n '`pending` for a typo.',\n].join('\\n')\n\n/** JSON Schema for `delegation_status` tool arguments (`taskId` + optional `includeTrace`). @stable */\nexport const DELEGATION_STATUS_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n taskId: { type: 'string', description: 'Returned by delegate_ui_audit.' },\n includeTrace: {\n type: 'boolean',\n description:\n 'Also return the journaled loop-trace span tree for this delegation. Default false.',\n },\n },\n required: ['taskId'],\n additionalProperties: false,\n} as const\n\n/** Parse and validate raw MCP tool input into typed `DelegationStatusArgs`; throws `TypeError` on bad input. @stable */\nexport function validateDelegationStatusArgs(raw: unknown): DelegationStatusArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegation_status: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const taskId = value.taskId\n if (typeof taskId !== 'string' || taskId.trim().length === 0) {\n throw new TypeError('delegation_status: `taskId` must be a non-empty string')\n }\n const out: DelegationStatusArgs = { taskId: taskId.trim() }\n if (value.includeTrace !== undefined) {\n if (typeof value.includeTrace !== 'boolean') {\n throw new TypeError('delegation_status: `includeTrace` must be a boolean')\n }\n out.includeTrace = value.includeTrace\n }\n return out\n}\n\n/** @stable */\nexport interface DelegationStatusHandlerOptions {\n queue: DelegationTaskQueue\n}\n\n/** Build the MCP tool handler that polls a `DelegationTaskQueue` for task status. @stable */\nexport function createDelegationStatusHandler(\n options: DelegationStatusHandlerOptions,\n): (raw: unknown) => Promise<DelegationStatusResult> {\n return async (raw) => {\n const args = validateDelegationStatusArgs(raw)\n const status = options.queue.status(\n args.taskId,\n args.includeTrace !== undefined ? { includeTrace: args.includeTrace } : undefined,\n )\n if (!status) {\n throw new NotFoundError(`delegation_status: unknown taskId \"${args.taskId}\"`)\n }\n return status\n }\n}\n"],"mappings":";;;AAwCA,IAAa,wBAAb,MAA4D;CAC1D,SAA2C,CAAC;CAE5C,MAAM,IAAI,OAAqC;EAC7C,KAAK,OAAO,KAAK,EAAE,GAAG,MAAM,CAAC;CAC/B;CAEA,MAAM,KAAK,SAAuD,CAAC,GAA6B;EAC9F,IAAI,MAAM,KAAK;EACf,IAAI,OAAO,cAAc,KAAA,GACvB,MAAM,IAAI,QAAQ,UAAU,MAAM,cAAc,OAAO,SAAS;EAElE,IAAI,OAAO,gBAAgB,KAAA,GACzB,MAAM,IAAI,QAAQ,UAAU,MAAM,SAAS,QAAQ,OAAO,WAAW;EAEvE,OAAO,IAAI,KAAK,WAAW,EAAE,GAAG,MAAM,EAAE;CAC1C;AACF;;;;;;;AAQA,SAAgB,gBAAgB,OAAkD;CAChF,MAAM,OAAmC;EACvC,IAAI,MAAM;EACV,OAAO,MAAM,OAAO;EACpB,IAAI,MAAM;EACV,OAAO,MAAM,OAAO;EACpB,YAAY,MAAM;CACpB;CACA,IAAI,MAAM,OAAO,OAAO,KAAK,QAAQ,MAAM,OAAO;CAClD,OAAO;AACT;;;;ACnDA,MAAa,8BAA8B;;AAG3C,MAAa,gCAAgC;CAC3C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,IAAI;;AAGX,MAAa,iCAAiC;C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S,MAAM;CACrB,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,CAAC,CAAC,WAAW,GACzD,MAAM,IAAI,UAAU,wDAAwD;CAE9E,MAAM,MAA4B,EAAE,QAAQ,OAAO,KAAK,EAAE;CAC1D,IAAI,MAAM,iBAAiB,KAAA,GAAW;EACpC,IAAI,OAAO,MAAM,iBAAiB,WAChC,MAAM,IAAI,UAAU,qDAAqD;EAE3E,IAAI,eAAe,MAAM;CAC3B;CACA,OAAO;AACT;;AAQA,SAAgB,8BACd,SACmD;CACnD,OAAO,OAAO,QAAQ;EACpB,MAAM,OAAO,6BAA6B,GAAG;EAC7C,MAAM,SAAS,QAAQ,MAAM,OAC3B,KAAK,QACL,KAAK,iBAAiB,KAAA,IAAY,EAAE,cAAc,KAAK,aAAa,IAAI,KAAA,CAC1E;EACA,IAAI,CAAC,QACH,MAAM,IAAI,cAAc,sCAAsC,KAAK,OAAO,EAAE;EAE9E,OAAO;CACT;AACF"}
package/dist/durable.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { Bo as SuperviseOptions, Wo as supervise, ms as SupervisorProfile } from "./index-B_fEqr5V.js";
1
+ import { Uo as supervise, ps as SupervisorProfile, zo as SuperviseOptions } from "./index-BEPjOPwH.js";
2
2
  import { l as RuntimeHooks, o as RuntimeHookEvent, r as RuntimeDecisionPoint } from "./runtime-hooks-Bj6wJHlH.js";
3
- import { E as NodeId, Y as SpendGap, j as ProviderModelExecutionEvidence, k as ProfileMaterializationReceipt, lt as WorkerTraceEvidence, o as ExecutionBindingReceipt, q as Spend } from "./types-DKA_PDv0.js";
3
+ import { E as NodeId, Y as SpendGap, j as ProviderModelExecutionEvidence, k as ProfileMaterializationReceipt, lt as WorkerTraceEvidence, o as ExecutionBindingReceipt, q as Spend } from "./types-B_pNTBjK.js";
4
4
  //#region src/durable/chat-engine.d.ts
5
5
  /**
6
6
  * `handleChatTurn` is a framework-neutral chat-turn HTTP orchestrator.
package/dist/durable.js CHANGED
@@ -1,7 +1,7 @@
1
- import { b as zeroSpend, i as cloneSpend, t as addSpend } from "./util-mCNUeboW.js";
2
- import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-CDfsCI5s.js";
1
+ import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-Bh1Q9nt0.js";
2
+ import { E as zeroSpend, s as addSpend, u as cloneSpend } from "./environment-provider-Dr-wfnHg.js";
3
3
  import { a as withPursuitContext, t as composeRuntimeHooks } from "./runtime-hooks-tXpAarhW.js";
4
- import { n as supervise } from "./supervise-Cr6JEoIg.js";
4
+ import { n as supervise } from "./supervise-C0V3pZXK.js";
5
5
  import { createHash } from "node:crypto";
6
6
  import { readFile } from "node:fs/promises";
7
7
  import { resolve } from "node:path";