@tangle-network/agent-runtime 0.156.0 → 0.158.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 (81) hide show
  1. package/dist/{activation-B4fRz8QL.js → activation-CLicee7D.js} +3 -3
  2. package/dist/{activation-B4fRz8QL.js.map → activation-CLicee7D.js.map} +1 -1
  3. package/dist/agent.d.ts +2 -2
  4. package/dist/agent.js +2 -2
  5. package/dist/analyst-loop.d.ts +1 -1
  6. package/dist/{authoring-C4uCoDmO.js → authoring-rIDPzwYY.js} +2 -2
  7. package/dist/{authoring-C4uCoDmO.js.map → authoring-rIDPzwYY.js.map} +1 -1
  8. package/dist/candidate-execution/index.js +4 -4
  9. package/dist/{candidate-execution-Ic92NMl9.js → candidate-execution-izJj02pU.js} +4 -4
  10. package/dist/{candidate-execution-Ic92NMl9.js.map → candidate-execution-izJj02pU.js.map} +1 -1
  11. package/dist/conversation.d.ts +1 -1
  12. package/dist/durable.d.ts +11 -8
  13. package/dist/durable.js +2 -4
  14. package/dist/durable.js.map +1 -1
  15. package/dist/{environment-provider-Dz9JB-X_.js → environment-provider-Bn3652YU.js} +2 -2
  16. package/dist/{environment-provider-Dz9JB-X_.js.map → environment-provider-Bn3652YU.js.map} +1 -1
  17. package/dist/{environment-provider-C_QI6VCG.d.ts → environment-provider-BobKk46F.d.ts} +3 -3
  18. package/dist/environment-provider.d.ts +1 -1
  19. package/dist/environment-provider.js +1 -1
  20. package/dist/{graph-BibNm6a-.js → graph-BGPO6z_u.js} +4 -3
  21. package/dist/graph-BGPO6z_u.js.map +1 -0
  22. package/dist/{improvement-cycle-g6RsxGbg.js → improvement-cycle-BEENaoCb.js} +11 -7
  23. package/dist/improvement-cycle-BEENaoCb.js.map +1 -0
  24. package/dist/{index-DPFUNEdU.d.ts → index-CLt9zpuD.d.ts} +3 -3
  25. package/dist/{index-B2A_KtAZ.d.ts → index-Dto3D25e.d.ts} +16 -12
  26. package/dist/{index-BYGBIxtx.d.ts → index-W5WVBUlZ.d.ts} +4 -4
  27. package/dist/index.d.ts +9 -9
  28. package/dist/index.js +11 -11
  29. package/dist/intelligence.d.ts +7 -11
  30. package/dist/intelligence.js +6 -6
  31. package/dist/intelligence.js.map +1 -1
  32. package/dist/kernel.d.ts +7 -7
  33. package/dist/kernel.js +8 -8
  34. package/dist/{knowledge-DeP-wG8l.js → knowledge-HDCUV1kZ.js} +5 -5
  35. package/dist/{knowledge-DeP-wG8l.js.map → knowledge-HDCUV1kZ.js.map} +1 -1
  36. package/dist/knowledge.d.ts +1 -1
  37. package/dist/knowledge.js +1 -1
  38. package/dist/{loop-runner-bin-9VUQihh7.d.ts → loop-runner-bin-BEzvqbgg.d.ts} +3 -3
  39. package/dist/{loop-runner-bin-LvaprzUz.js → loop-runner-bin-UNn0NLv2.js} +3 -3
  40. package/dist/{loop-runner-bin-LvaprzUz.js.map → loop-runner-bin-UNn0NLv2.js.map} +1 -1
  41. package/dist/loop-runner-bin.d.ts +1 -1
  42. package/dist/loop-runner-bin.js +1 -1
  43. package/dist/mcp/bin.js +3 -3
  44. package/dist/mcp/index.d.ts +6 -6
  45. package/dist/mcp/index.js +5 -5
  46. package/dist/mcp/index.js.map +1 -1
  47. package/dist/{openai-tools-CkSQJppW.js → openai-tools-D1VQ5e9p.js} +2 -2
  48. package/dist/{openai-tools-CkSQJppW.js.map → openai-tools-D1VQ5e9p.js.map} +1 -1
  49. package/dist/{openai-tools-z-whdYNC.d.ts → openai-tools-wkxQ2aEw.d.ts} +2 -2
  50. package/dist/{prepare-DcMjMdj-.js → prepare-VLGnSyav.js} +2 -2
  51. package/dist/{prepare-DcMjMdj-.js.map → prepare-VLGnSyav.js.map} +1 -1
  52. package/dist/primeintellect/index.d.ts +1 -1
  53. package/dist/profiles.d.ts +2 -166
  54. package/dist/{protected-model-port-BzUkspPP.js → protected-model-port-CcCH0Uji.js} +2 -2
  55. package/dist/{protected-model-port-BzUkspPP.js.map → protected-model-port-CcCH0Uji.js.map} +1 -1
  56. package/dist/{redact-BT7-mX8G.d.ts → redact-0AK8JmHW.d.ts} +13 -10
  57. package/dist/researcher-BMFFPwKb.js.map +1 -1
  58. package/dist/{runtime-DuueBLeO.d.ts → runtime-BzY66cd6.d.ts} +4 -4
  59. package/dist/{runtime-D-NDRp4y.js → runtime-CTs2JsG9.js} +8 -8
  60. package/dist/{runtime-D-NDRp4y.js.map → runtime-CTs2JsG9.js.map} +1 -1
  61. package/dist/{spawn-journal-duo0EkOp.js → spawn-journal-oewq1g2h.js} +1 -4
  62. package/dist/{spawn-journal-duo0EkOp.js.map → spawn-journal-oewq1g2h.js.map} +1 -1
  63. package/dist/{stream-agent-turn-BbcwWw_J.d.ts → stream-agent-turn-jaaFaSXM.d.ts} +3 -3
  64. package/dist/{structural-rollout-B1TocSdq.js → structural-rollout-Cj58xALQ.js} +3 -3
  65. package/dist/{structural-rollout-B1TocSdq.js.map → structural-rollout-Cj58xALQ.js.map} +1 -1
  66. package/dist/substrate-AJoT4HIz.d.ts +284 -0
  67. package/dist/{supervise-BVE0XAJa.js → supervise-CqwjiXlX.js} +3 -3
  68. package/dist/{supervise-BVE0XAJa.js.map → supervise-CqwjiXlX.js.map} +1 -1
  69. package/dist/{supervisor-BmXD0WCJ.js → supervisor-ZlQy5Fwl.js} +6 -33
  70. package/dist/supervisor-ZlQy5Fwl.js.map +1 -0
  71. package/dist/testing.d.ts +2 -2
  72. package/dist/testing.js +12 -12
  73. package/dist/{types-Cz5mCGlY.d.ts → types-BBXdSns1.d.ts} +8 -8
  74. package/dist/{types-DeX8ibLc.d.ts → types-DpdfZoQ3.d.ts} +6 -3
  75. package/dist/{workspace-archive-bugA3OwU.js → workspace-archive-BptlGCEU.js} +2 -2
  76. package/dist/{workspace-archive-bugA3OwU.js.map → workspace-archive-BptlGCEU.js.map} +1 -1
  77. package/package.json +3 -3
  78. package/dist/graph-BibNm6a-.js.map +0 -1
  79. package/dist/improvement-cycle-g6RsxGbg.js.map +0 -1
  80. package/dist/substrate-BcnuSHXm.d.ts +0 -117
  81. package/dist/supervisor-BmXD0WCJ.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"researcher-BMFFPwKb.js","names":[],"sources":["../src/profiles/researcher.ts"],"sourcesContent":["/**\n * Opinionated preset for source-grounded research\n * tasks. The agent is told to:\n * - bound its work to a single `knowledgeNamespace`\n * - emit `items[]` carrying provenance + confidence\n * - emit `citations[]` linking quotes back to source urls\n * - emit `proposedWrites[]` — never call materialize itself\n * - describe `gaps` it could not answer\n *\n * The profile is stateless and agent-agnostic. The caller supplies the exact execution profile;\n * this preset adds only the researcher prompt, tools, parser, and validator.\n *\n * Propose-don't-apply: the profile NEVER writes to the knowledge base.\n * It produces `proposedWrites: KnowledgeUpdate[]` in the output. The\n * caller (gtm-agent, journey-eval, user) decides whether to feed those\n * updates through `applyKnowledgeWriteBlocks` / a KbStore put.\n *\n * Namespace isolation: every `KnowledgeItem` + `KnowledgeUpdate` in the\n * output carries `namespace`. The validator hard-fails when any item\n * touches a namespace other than `task.knowledgeNamespace`.\n *\n * @experimental\n */\n\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { ConfigError } from '../errors'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport type {\n AgentRunSpec,\n DefaultVerdict,\n Driver,\n OutputAdapter,\n Validator,\n} from '../runtime/types'\n\n/** Source families a researcher profile may prefer for a task. @experimental */\nexport type ResearchSource = 'web' | 'corpus' | 'twitter' | 'github' | 'docs'\n\n/** Task contract for a source-grounded research agent. @experimental */\nexport interface ResearchTask {\n /** The research question to answer. */\n question: string\n /** Bound: e.g. \"audience for cpg-founder ICP\". */\n scope?: string\n /** Multi-tenant scope (customer-id, workspace-id). Validator enforces. */\n knowledgeNamespace: string\n sources?: ResearchSource[]\n recencyWindow?: { since?: Date; until?: Date }\n maxItems?: number\n /** Per-item minimum confidence in [0, 1]. Validator scores recall vs this. */\n minConfidence?: number\n}\n\n/**\n * Knowledge item emitted by the researcher.\n *\n * Profile-local type. When agent-knowledge promotes `KnowledgeClaim` →\n * top-level `KnowledgeItem` substrate-wide, these fields collapse 1:1.\n *\n * @experimental\n */\nexport interface KnowledgeItem {\n id: string\n /** Multi-tenant scope. MUST equal `task.knowledgeNamespace`. */\n namespace: string\n /** The factual claim, in the researcher's words. */\n claim: string\n /** Provenance — at least one entry required. */\n evidence: Array<{ source: string; quote?: string; url?: string; capturedAt: number }>\n /** Researcher's self-reported confidence in [0, 1]. */\n confidence: number\n /** Prior item ids this supersedes (chain). */\n supersedes?: string[]\n /** Set if the agent is retracting an earlier item. Unix ms. */\n retractedAt?: number\n authoredBy: { kind: 'human' | 'agent'; id: string }\n}\n\n/**\n * A proposed write to the knowledge base. The profile does NOT apply\n * these — the caller decides.\n *\n * @experimental\n */\nexport type KnowledgeUpdate =\n | { kind: 'insert'; namespace: string; item: KnowledgeItem }\n | { kind: 'supersede'; namespace: string; previousId: string; item: KnowledgeItem }\n | { kind: 'retract'; namespace: string; itemId: string; reason: string }\n\n/**\n * Researcher output. Required fields are typed; optional fields preserve\n * the agent's free-form intelligence (`notes`, `raw`). The validator\n * enforces the typed minimum.\n *\n * @experimental\n */\nexport interface ResearchOutput {\n items: KnowledgeItem[]\n citations: Array<{ url: string; quote: string; confidence: number }>\n proposedWrites: KnowledgeUpdate[]\n gaps?: string[]\n notes?: string\n /** Anything the agent emitted beyond the typed fields. */\n raw?: unknown\n}\n\n/** Options for the source-grounded researcher profile preset. @experimental */\nexport interface ResearcherProfileOptions {\n /** Caller-owned exact harness/provider/model identity. */\n profile: AgentProfile\n /** Custom system prompt replacement. Default = built-in researcher preset. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `profile.name`. */\n name?: string\n /**\n * Default 0.7. Minimum (citations with quote) / items ratio for `valid=true`.\n * Below this floor, citation_density scores < 1 and the item set is gated.\n */\n citationDensityMin?: number\n}\n\nconst DEFAULT_CITATION_DENSITY_MIN = 0.7\n\n/** Build a source-grounded researcher profile with output parsing and validation. @experimental */\nexport function researcherProfile(options: ResearcherProfileOptions & { task?: ResearchTask }): {\n profile: AgentProfile\n taskToPrompt: (task: ResearchTask) => string\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n agentRunSpec: AgentRunSpec<ResearchTask>\n} {\n const base = agentProfileSchema.parse(options.profile) as AgentProfile\n assertExecutableAgentProfile(base, 'researcherProfile')\n const name = options.name ?? base.name\n const systemPrompt = options.systemPrompt ?? RESEARCHER_SYSTEM_PROMPT\n const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const profile: AgentProfile = {\n ...base,\n name,\n description: base.description ?? \"Source-grounded research agent. Propose-don't-apply.\",\n prompt: { ...base.prompt, systemPrompt },\n tools: { web_search: true, fs: true, shell: true, ...base.tools },\n metadata: { ...base.metadata, role: 'researcher' },\n }\n const output: OutputAdapter<ResearchOutput> = { parse: parseResearcherEvents }\n const validator: Validator<ResearchOutput> = options.task\n ? createResearcherValidator(options.task, { citationDensityMin })\n : createResearcherValidator(\n { question: '', knowledgeNamespace: '' },\n { citationDensityMin, namespaceCheck: false },\n )\n const agentRunSpec: AgentRunSpec<ResearchTask> = {\n name,\n profile,\n taskToPrompt: formatResearcherPrompt,\n }\n return { profile, taskToPrompt: formatResearcherPrompt, output, validator, agentRunSpec }\n}\n\n/** @experimental */\nexport interface MultiHarnessResearcherFanoutOptions {\n /** Exact execution profiles, one per parallel researcher. */\n profiles: ReadonlyArray<AgentProfile>\n /** Default citation density floor for the shared validator. */\n citationDensityMin?: number\n /** Optional task — narrows the validator's namespace check. */\n task?: ResearchTask\n}\n\n/**\n * Build a fanout topology over multiple harnesses. The kernel round-robins\n * `agentRuns` across the N parallel iterations and the `FanoutVote` driver\n * picks the highest-scoring valid output.\n *\n * @experimental\n */\nexport function multiHarnessResearcherFanout(options: MultiHarnessResearcherFanoutOptions): {\n agentRuns: AgentRunSpec<ResearchTask>[]\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n driver: Driver<ResearchTask, ResearchOutput, 'done'>\n} {\n if (options.profiles.length === 0) {\n throw new ConfigError('multiHarnessResearcherFanout: at least one exact profile is required')\n }\n const agentRuns = options.profiles.map((profile) => {\n const { agentRunSpec } = researcherProfile({ profile })\n return agentRunSpec\n })\n const { output, validator } = researcherProfile({\n profile: options.profiles[0]!,\n citationDensityMin: options.citationDensityMin,\n task: options.task,\n })\n // Single fanout round across the N harnesses, then stop: the kernel\n // round-robins `agentRuns` over the N branches and selects the winner\n // (best valid score) across all iterations via `defaultSelectWinner`.\n const driver: Driver<ResearchTask, ResearchOutput, 'done'> = {\n name: 'researcher-fanout',\n async plan(task, history) {\n return history.length === 0 ? Array.from({ length: agentRuns.length }, () => task) : []\n },\n // 'done' is a terminal decision in the kernel; the loop finalizes after\n // the single fanout round and selects the winner via `defaultSelectWinner`.\n decide() {\n return 'done'\n },\n describePlan() {\n return { kind: 'fanout' }\n },\n }\n return { agentRuns, output, validator, driver }\n}\n\n/**\n * Build a validator that closes over a specific `ResearchTask`'s constraints.\n *\n * Checks in order:\n * 1. Items must be non-empty.\n * 2. Every item carries `evidence.length >= 1`.\n * 3. Every item + proposedWrite is scoped to `task.knowledgeNamespace`\n * (hard-fail on any namespace mismatch — defence in depth for the\n * multi-tenant invariant).\n * 4. Citation density (citations with quote / items) >= floor.\n *\n * Aggregate score:\n * 0.4 · citation_density\n * + 0.2 · source_diversity (distinct sources / max(items, 1))\n * + 0.2 · recency_match (mean fraction within `recencyWindow`)\n * + 0.2 · (1 − gaps/maxGaps), maxGaps = max(items, 1)\n *\n * @experimental\n */\nexport function createResearcherValidator(\n task: ResearchTask,\n config: { citationDensityMin?: number; namespaceCheck?: boolean } = {},\n): Validator<ResearchOutput> {\n const citationDensityMin = config.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const namespaceCheck = config.namespaceCheck ?? true\n return {\n async validate(output) {\n const notes: string[] = []\n const scores: Record<string, number> = {}\n let pass = true\n\n if (!Array.isArray(output.items) || output.items.length === 0) {\n pass = false\n notes.push('no items')\n scores.items = 0\n } else {\n scores.items = 1\n }\n\n const missingEvidence = (output.items ?? []).filter(\n (item) => !Array.isArray(item.evidence) || item.evidence.length === 0,\n )\n if (missingEvidence.length > 0) {\n pass = false\n notes.push(`${missingEvidence.length} item(s) without evidence`)\n scores.provenance = 0\n } else {\n scores.provenance = 1\n }\n\n if (namespaceCheck) {\n const foreignItems = (output.items ?? []).filter(\n (item) => item.namespace !== task.knowledgeNamespace,\n )\n const foreignWrites = (output.proposedWrites ?? []).filter(\n (write) => write.namespace !== task.knowledgeNamespace,\n )\n if (foreignItems.length > 0 || foreignWrites.length > 0) {\n pass = false\n notes.push(\n `namespace violation: ${foreignItems.length} item(s) + ${foreignWrites.length} write(s) ` +\n `outside ${task.knowledgeNamespace}`,\n )\n scores.namespace = 0\n } else {\n scores.namespace = 1\n }\n }\n\n const itemCount = Math.max(output.items?.length ?? 0, 1)\n const citationsWithQuote = (output.citations ?? []).filter(\n (citation) => typeof citation.quote === 'string' && citation.quote.length > 0,\n ).length\n const citationDensity = Math.min(1, citationsWithQuote / itemCount)\n if (citationDensity < citationDensityMin) {\n pass = false\n notes.push(\n `citation density ${citationDensity.toFixed(2)} below floor ${citationDensityMin.toFixed(2)}`,\n )\n }\n scores.citation_density = citationDensity\n\n const sourceSet = new Set<string>()\n for (const item of output.items ?? []) {\n for (const evidence of item.evidence ?? []) {\n if (evidence.source) sourceSet.add(evidence.source)\n }\n }\n scores.source_diversity = Math.min(1, sourceSet.size / itemCount)\n\n scores.recency_match = recencyMatchScore(output.items ?? [], task.recencyWindow)\n\n const maxGaps = itemCount\n const gapCount = output.gaps?.length ?? 0\n scores.gap_coverage = Math.max(0, 1 - gapCount / maxGaps)\n\n const score =\n 0.4 * scores.citation_density +\n 0.2 * scores.source_diversity +\n 0.2 * scores.recency_match +\n 0.2 * scores.gap_coverage\n\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n },\n }\n}\n\nfunction recencyMatchScore(items: KnowledgeItem[], window: ResearchTask['recencyWindow']): number {\n if (!window || (window.since === undefined && window.until === undefined)) return 1\n if (items.length === 0) return 0\n const sinceMs = window.since?.getTime() ?? Number.NEGATIVE_INFINITY\n const untilMs = window.until?.getTime() ?? Number.POSITIVE_INFINITY\n let hits = 0\n let total = 0\n for (const item of items) {\n for (const evidence of item.evidence ?? []) {\n if (typeof evidence.capturedAt !== 'number') continue\n total += 1\n if (evidence.capturedAt >= sinceMs && evidence.capturedAt <= untilMs) hits += 1\n }\n }\n return total === 0 ? 0 : hits / total\n}\n\n/** Built-in source-grounded research contract added to a caller-owned exact profile. */\nexport const RESEARCHER_SYSTEM_PROMPT = [\n 'You are a research agent. Your job is to answer a research question with',\n 'source-grounded knowledge items that the caller will choose whether to',\n 'persist to a multi-tenant knowledge base.',\n '',\n 'Hard rules:',\n \" 1. Every item you emit MUST carry the task's knowledgeNamespace exactly.\",\n ' Never write to a different namespace.',\n ' 2. Every item MUST carry at least one evidence entry with a source.',\n ' A quote + url is strongly preferred; capturedAt is unix ms.',\n ' 3. You propose writes — you do NOT apply them. The caller decides.',\n ' 4. Self-report confidence honestly in [0, 1]. Do not inflate.',\n ' 5. List what you could not answer in `gaps`. Better to admit a gap',\n ' than fabricate.',\n '',\n 'When you finish, emit a single final structured message of the shape:',\n ' ```json',\n ' { \"items\": [{ \"id\": \"...\", \"namespace\": \"...\", \"claim\": \"...\",',\n ' \"evidence\": [{ \"source\": \"...\", \"quote\": \"...\",',\n ' \"url\": \"...\", \"capturedAt\": 0 }],',\n ' \"confidence\": 0.0,',\n ' \"authoredBy\": { \"kind\": \"agent\", \"id\": \"...\" } }],',\n ' \"citations\": [{ \"url\": \"...\", \"quote\": \"...\", \"confidence\": 0.0 }],',\n ' \"proposedWrites\": [{ \"kind\": \"insert\", \"namespace\": \"...\",',\n ' \"item\": { /* same shape as items[] */ } }],',\n ' \"gaps\": [\"...\"],',\n ' \"notes\": \"free-form commentary\" }',\n ' ```',\n].join('\\n')\n\nfunction formatResearcherPrompt(task: ResearchTask): string {\n const sources = task.sources?.length ? task.sources.join(', ') : '(no preference)'\n const window = formatRecencyWindow(task.recencyWindow)\n return [\n `Question: ${task.question}`,\n `Knowledge namespace (DO NOT cross): ${task.knowledgeNamespace}`,\n `Scope: ${task.scope ?? '(unspecified)'}`,\n `Preferred sources: ${sources}`,\n `Recency window: ${window}`,\n `Max items: ${task.maxItems ?? '(no cap)'}`,\n `Per-item minimum confidence: ${task.minConfidence ?? '(no floor)'}`,\n '',\n 'Produce knowledge items with provenance + citations + proposed writes.',\n 'List gaps for anything you could not answer. Emit the final JSON',\n 'result block exactly as instructed.',\n ].join('\\n')\n}\n\nfunction formatRecencyWindow(window: ResearchTask['recencyWindow']): string {\n if (!window) return '(none)'\n const since = window.since ? window.since.toISOString() : '-∞'\n const until = window.until ? window.until.toISOString() : 'now'\n return `${since} .. ${until}`\n}\n\n/**\n * Walk the event stream and return the last structured `research.result`\n * payload. Falls back to scanning text deltas for a fenced JSON block.\n */\nfunction parseResearcherEvents(events: SandboxEvent[]): ResearchOutput {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const type = String(event.type ?? '')\n const data = isRecord(event.data) ? event.data : {}\n if (type === 'result' || type === 'final' || type === 'research.result') {\n const direct = coerceResearchOutput(data.result ?? data.output ?? data)\n // opencode reports the agent's terminal answer in `finalText` (not result/output).\n // Parse it too, and prefer it when `direct` is an all-empty shape — otherwise an\n // event carrying both `{items:[],citations:[],proposedWrites:[]}` and a rich\n // finalText would silently drop the real answer.\n const finalText = pickString(data.finalText)\n const fenced = finalText ? extractFencedJson(finalText) : undefined\n const fromFinalText = fenced ? coerceResearchOutput(fenced) : undefined\n if (direct && !isEmptyOutput(direct)) return direct\n if (fromFinalText) return fromFinalText\n if (direct) return direct\n }\n }\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const data = isRecord(event.data) ? event.data : {}\n const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.finalText)\n if (!text) continue\n const fenced = extractFencedJson(text)\n if (!fenced) continue\n const coerced = coerceResearchOutput(fenced)\n if (coerced) return coerced\n }\n return { items: [], citations: [], proposedWrites: [] }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** A coerced output that carries no items, citations, or proposed writes. */\nfunction isEmptyOutput(o: ResearchOutput): boolean {\n return o.items.length === 0 && o.citations.length === 0 && o.proposedWrites.length === 0\n}\n\nfunction pickString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction extractFencedJson(text: string): unknown | undefined {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)\n if (!match) return undefined\n const body = (match[1] ?? '').trim()\n if (!body) return undefined\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction coerceResearchOutput(value: unknown): ResearchOutput | undefined {\n if (!isRecord(value)) return undefined\n const items = coerceItems(value.items)\n const citations = coerceCitations(value.citations)\n const proposedWrites = coerceProposedWrites(value.proposedWrites)\n // Reject completely empty payloads — those signal \"no result block\",\n // not \"a valid empty result\".\n if (items === undefined && citations === undefined && proposedWrites === undefined) {\n return undefined\n }\n const output: ResearchOutput = {\n items: items ?? [],\n citations: citations ?? [],\n proposedWrites: proposedWrites ?? [],\n }\n if (Array.isArray(value.gaps)) {\n output.gaps = value.gaps.filter((entry): entry is string => typeof entry === 'string')\n }\n const notes = pickString(value.notes)\n if (notes) output.notes = notes\n // Preserve any extra fields the agent emitted that don't fit the typed\n // surface — callers can inspect `raw` without forcing them through the\n // typed coercion. We only include `raw` when the agent emitted fields\n // beyond the known set.\n const known = new Set(['items', 'citations', 'proposedWrites', 'gaps', 'notes'])\n const extras: Record<string, unknown> = {}\n let extrasCount = 0\n for (const [key, val] of Object.entries(value)) {\n if (known.has(key)) continue\n extras[key] = val\n extrasCount += 1\n }\n if (extrasCount > 0) output.raw = extras\n return output\n}\n\nfunction coerceItems(value: unknown): KnowledgeItem[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeItem[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const id = pickString(entry.id)\n const namespace = pickString(entry.namespace)\n const claim = pickString(entry.claim)\n const evidence = coerceEvidence(entry.evidence)\n const confidence = toFiniteNumber(entry.confidence)\n const authoredBy = coerceAuthoredBy(entry.authoredBy)\n if (!id || !namespace || !claim || !authoredBy) continue\n const item: KnowledgeItem = {\n id,\n namespace,\n claim,\n evidence,\n confidence: clamp01(confidence),\n authoredBy,\n }\n if (Array.isArray(entry.supersedes)) {\n item.supersedes = entry.supersedes.filter((s): s is string => typeof s === 'string')\n }\n const retractedAt = toFiniteNumber(entry.retractedAt)\n if (retractedAt > 0) item.retractedAt = retractedAt\n out.push(item)\n }\n return out\n}\n\nfunction coerceEvidence(value: unknown): KnowledgeItem['evidence'] {\n if (!Array.isArray(value)) return []\n const out: KnowledgeItem['evidence'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const source = pickString(entry.source)\n if (!source) continue\n const item: KnowledgeItem['evidence'][number] = {\n source,\n capturedAt: toFiniteNumber(entry.capturedAt),\n }\n const quote = pickString(entry.quote)\n if (quote) item.quote = quote\n const url = pickString(entry.url)\n if (url) item.url = url\n out.push(item)\n }\n return out\n}\n\nfunction coerceAuthoredBy(value: unknown): KnowledgeItem['authoredBy'] | undefined {\n if (!isRecord(value)) return undefined\n const kind = value.kind === 'human' || value.kind === 'agent' ? value.kind : undefined\n const id = pickString(value.id)\n if (!kind || !id) return undefined\n return { kind, id }\n}\n\nfunction coerceCitations(value: unknown): ResearchOutput['citations'] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: ResearchOutput['citations'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const url = pickString(entry.url)\n const quote = pickString(entry.quote)\n if (!url || !quote) continue\n out.push({ url, quote, confidence: clamp01(toFiniteNumber(entry.confidence)) })\n }\n return out\n}\n\nfunction coerceProposedWrites(value: unknown): KnowledgeUpdate[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeUpdate[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const namespace = pickString(entry.namespace)\n if (!namespace) continue\n if (entry.kind === 'insert') {\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!item) continue\n out.push({ kind: 'insert', namespace, item })\n } else if (entry.kind === 'supersede') {\n const previousId = pickString(entry.previousId)\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!previousId || !item) continue\n out.push({ kind: 'supersede', namespace, previousId, item })\n } else if (entry.kind === 'retract') {\n const itemId = pickString(entry.itemId)\n const reason = pickString(entry.reason)\n if (!itemId || !reason) continue\n out.push({ kind: 'retract', namespace, itemId, reason })\n }\n }\n return out\n}\n\nfunction toFiniteNumber(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n if (value < 0) return 0\n if (value > 1) return 1\n return value\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA0HA,MAAM,+BAA+B;;AAGrC,SAAgB,kBAAkB,SAMhC;CACA,MAAM,OAAO,mBAAmB,MAAM,QAAQ,OAAO;CACrD,6BAA6B,MAAM,mBAAmB;CACtD,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAClC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,qBAAqB,QAAQ,sBAAsB;CACzD,MAAM,UAAwB;EAC5B,GAAG;EACH;EACA,aAAa,KAAK,eAAe;EACjC,QAAQ;GAAE,GAAG,KAAK;GAAQ;EAAa;EACvC,OAAO;GAAE,YAAY;GAAM,IAAI;GAAM,OAAO;GAAM,GAAG,KAA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* Opinionated preset for source-grounded research\n * tasks. The agent is told to:\n * - bound its work to a single `knowledgeNamespace`\n * - emit `items[]` carrying provenance + confidence\n * - emit `citations[]` linking quotes back to source urls\n * - emit `proposedWrites[]` — never call materialize itself\n * - describe `gaps` it could not answer\n *\n * The profile is stateless and agent-agnostic. The caller supplies the exact execution profile;\n * this preset adds only the researcher prompt, tools, parser, and validator.\n *\n * Propose-don't-apply: the profile NEVER writes to the knowledge base.\n * It produces `proposedWrites: KnowledgeUpdate[]` in the output. The\n * caller (gtm-agent, journey-eval, user) decides whether to feed those\n * updates through `applyKnowledgeWriteBlocks` / a KbStore put.\n *\n * Namespace isolation: every `KnowledgeItem` + `KnowledgeUpdate` in the\n * output carries `namespace`. The validator hard-fails when any item\n * touches a namespace other than `task.knowledgeNamespace`.\n *\n * @experimental\n */\n\nimport { type AgentProfile, agentProfileSchema } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { ConfigError } from '../errors'\nimport { assertExecutableAgentProfile } from '../runtime/supervise/model-policy'\nimport type {\n AgentRunSpec,\n DefaultVerdict,\n Driver,\n OutputAdapter,\n Validator,\n} from '../runtime/types'\n\n/** Source families a researcher profile may prefer for a task. One owner: the delegation\n * vocabulary (`DelegateResearchArgs.sources`) re-exports this type rather than restating it.\n * @experimental */\nexport type ResearchSource = 'web' | 'corpus' | 'twitter' | 'github' | 'docs'\n\n/** Task contract for a source-grounded research agent. @experimental */\nexport interface ResearchTask {\n /** The research question to answer. */\n question: string\n /** Bound: e.g. \"audience for cpg-founder ICP\". */\n scope?: string\n /** Multi-tenant scope (customer-id, workspace-id). Validator enforces. */\n knowledgeNamespace: string\n sources?: ResearchSource[]\n recencyWindow?: { since?: Date; until?: Date }\n maxItems?: number\n /** Per-item minimum confidence in [0, 1]. Validator scores recall vs this. */\n minConfidence?: number\n}\n\n/**\n * Knowledge item emitted by the researcher.\n *\n * Profile-local type. When agent-knowledge promotes `KnowledgeClaim` →\n * top-level `KnowledgeItem` substrate-wide, these fields collapse 1:1.\n *\n * @experimental\n */\nexport interface KnowledgeItem {\n id: string\n /** Multi-tenant scope. MUST equal `task.knowledgeNamespace`. */\n namespace: string\n /** The factual claim, in the researcher's words. */\n claim: string\n /** Provenance — at least one entry required. */\n evidence: Array<{ source: string; quote?: string; url?: string; capturedAt: number }>\n /** Researcher's self-reported confidence in [0, 1]. */\n confidence: number\n /** Prior item ids this supersedes (chain). */\n supersedes?: string[]\n /** Set if the agent is retracting an earlier item. Unix ms. */\n retractedAt?: number\n authoredBy: { kind: 'human' | 'agent'; id: string }\n}\n\n/**\n * A proposed write to the knowledge base. The profile does NOT apply\n * these — the caller decides.\n *\n * @experimental\n */\nexport type KnowledgeUpdate =\n | { kind: 'insert'; namespace: string; item: KnowledgeItem }\n | { kind: 'supersede'; namespace: string; previousId: string; item: KnowledgeItem }\n | { kind: 'retract'; namespace: string; itemId: string; reason: string }\n\n/**\n * Researcher output. Required fields are typed; optional fields preserve\n * the agent's free-form intelligence (`notes`, `raw`). The validator\n * enforces the typed minimum.\n *\n * @experimental\n */\nexport interface ResearchOutput {\n items: KnowledgeItem[]\n citations: Array<{ url: string; quote: string; confidence: number }>\n proposedWrites: KnowledgeUpdate[]\n gaps?: string[]\n notes?: string\n /** Anything the agent emitted beyond the typed fields. */\n raw?: unknown\n}\n\n/** Options for the source-grounded researcher profile preset. @experimental */\nexport interface ResearcherProfileOptions {\n /** Caller-owned exact harness/provider/model identity. */\n profile: AgentProfile\n /** Custom system prompt replacement. Default = built-in researcher preset. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `profile.name`. */\n name?: string\n /**\n * Default 0.7. Minimum (citations with quote) / items ratio for `valid=true`.\n * Below this floor, citation_density scores < 1 and the item set is gated.\n */\n citationDensityMin?: number\n}\n\nconst DEFAULT_CITATION_DENSITY_MIN = 0.7\n\n/** Build a source-grounded researcher profile with output parsing and validation. @experimental */\nexport function researcherProfile(options: ResearcherProfileOptions & { task?: ResearchTask }): {\n profile: AgentProfile\n taskToPrompt: (task: ResearchTask) => string\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n agentRunSpec: AgentRunSpec<ResearchTask>\n} {\n const base = agentProfileSchema.parse(options.profile) as AgentProfile\n assertExecutableAgentProfile(base, 'researcherProfile')\n const name = options.name ?? base.name\n const systemPrompt = options.systemPrompt ?? RESEARCHER_SYSTEM_PROMPT\n const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const profile: AgentProfile = {\n ...base,\n name,\n description: base.description ?? \"Source-grounded research agent. Propose-don't-apply.\",\n prompt: { ...base.prompt, systemPrompt },\n tools: { web_search: true, fs: true, shell: true, ...base.tools },\n metadata: { ...base.metadata, role: 'researcher' },\n }\n const output: OutputAdapter<ResearchOutput> = { parse: parseResearcherEvents }\n const validator: Validator<ResearchOutput> = options.task\n ? createResearcherValidator(options.task, { citationDensityMin })\n : createResearcherValidator(\n { question: '', knowledgeNamespace: '' },\n { citationDensityMin, namespaceCheck: false },\n )\n const agentRunSpec: AgentRunSpec<ResearchTask> = {\n name,\n profile,\n taskToPrompt: formatResearcherPrompt,\n }\n return { profile, taskToPrompt: formatResearcherPrompt, output, validator, agentRunSpec }\n}\n\n/** @experimental */\nexport interface MultiHarnessResearcherFanoutOptions {\n /** Exact execution profiles, one per parallel researcher. */\n profiles: ReadonlyArray<AgentProfile>\n /** Default citation density floor for the shared validator. */\n citationDensityMin?: number\n /** Optional task — narrows the validator's namespace check. */\n task?: ResearchTask\n}\n\n/**\n * Build a fanout topology over multiple harnesses. The kernel round-robins\n * `agentRuns` across the N parallel iterations and the `FanoutVote` driver\n * picks the highest-scoring valid output.\n *\n * @experimental\n */\nexport function multiHarnessResearcherFanout(options: MultiHarnessResearcherFanoutOptions): {\n agentRuns: AgentRunSpec<ResearchTask>[]\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n driver: Driver<ResearchTask, ResearchOutput, 'done'>\n} {\n if (options.profiles.length === 0) {\n throw new ConfigError('multiHarnessResearcherFanout: at least one exact profile is required')\n }\n const agentRuns = options.profiles.map((profile) => {\n const { agentRunSpec } = researcherProfile({ profile })\n return agentRunSpec\n })\n const { output, validator } = researcherProfile({\n profile: options.profiles[0]!,\n citationDensityMin: options.citationDensityMin,\n task: options.task,\n })\n // Single fanout round across the N harnesses, then stop: the kernel\n // round-robins `agentRuns` over the N branches and selects the winner\n // (best valid score) across all iterations via `defaultSelectWinner`.\n const driver: Driver<ResearchTask, ResearchOutput, 'done'> = {\n name: 'researcher-fanout',\n async plan(task, history) {\n return history.length === 0 ? Array.from({ length: agentRuns.length }, () => task) : []\n },\n // 'done' is a terminal decision in the kernel; the loop finalizes after\n // the single fanout round and selects the winner via `defaultSelectWinner`.\n decide() {\n return 'done'\n },\n describePlan() {\n return { kind: 'fanout' }\n },\n }\n return { agentRuns, output, validator, driver }\n}\n\n/**\n * Build a validator that closes over a specific `ResearchTask`'s constraints.\n *\n * Checks in order:\n * 1. Items must be non-empty.\n * 2. Every item carries `evidence.length >= 1`.\n * 3. Every item + proposedWrite is scoped to `task.knowledgeNamespace`\n * (hard-fail on any namespace mismatch — defence in depth for the\n * multi-tenant invariant).\n * 4. Citation density (citations with quote / items) >= floor.\n *\n * Aggregate score:\n * 0.4 · citation_density\n * + 0.2 · source_diversity (distinct sources / max(items, 1))\n * + 0.2 · recency_match (mean fraction within `recencyWindow`)\n * + 0.2 · (1 − gaps/maxGaps), maxGaps = max(items, 1)\n *\n * @experimental\n */\nexport function createResearcherValidator(\n task: ResearchTask,\n config: { citationDensityMin?: number; namespaceCheck?: boolean } = {},\n): Validator<ResearchOutput> {\n const citationDensityMin = config.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const namespaceCheck = config.namespaceCheck ?? true\n return {\n async validate(output) {\n const notes: string[] = []\n const scores: Record<string, number> = {}\n let pass = true\n\n if (!Array.isArray(output.items) || output.items.length === 0) {\n pass = false\n notes.push('no items')\n scores.items = 0\n } else {\n scores.items = 1\n }\n\n const missingEvidence = (output.items ?? []).filter(\n (item) => !Array.isArray(item.evidence) || item.evidence.length === 0,\n )\n if (missingEvidence.length > 0) {\n pass = false\n notes.push(`${missingEvidence.length} item(s) without evidence`)\n scores.provenance = 0\n } else {\n scores.provenance = 1\n }\n\n if (namespaceCheck) {\n const foreignItems = (output.items ?? []).filter(\n (item) => item.namespace !== task.knowledgeNamespace,\n )\n const foreignWrites = (output.proposedWrites ?? []).filter(\n (write) => write.namespace !== task.knowledgeNamespace,\n )\n if (foreignItems.length > 0 || foreignWrites.length > 0) {\n pass = false\n notes.push(\n `namespace violation: ${foreignItems.length} item(s) + ${foreignWrites.length} write(s) ` +\n `outside ${task.knowledgeNamespace}`,\n )\n scores.namespace = 0\n } else {\n scores.namespace = 1\n }\n }\n\n const itemCount = Math.max(output.items?.length ?? 0, 1)\n const citationsWithQuote = (output.citations ?? []).filter(\n (citation) => typeof citation.quote === 'string' && citation.quote.length > 0,\n ).length\n const citationDensity = Math.min(1, citationsWithQuote / itemCount)\n if (citationDensity < citationDensityMin) {\n pass = false\n notes.push(\n `citation density ${citationDensity.toFixed(2)} below floor ${citationDensityMin.toFixed(2)}`,\n )\n }\n scores.citation_density = citationDensity\n\n const sourceSet = new Set<string>()\n for (const item of output.items ?? []) {\n for (const evidence of item.evidence ?? []) {\n if (evidence.source) sourceSet.add(evidence.source)\n }\n }\n scores.source_diversity = Math.min(1, sourceSet.size / itemCount)\n\n scores.recency_match = recencyMatchScore(output.items ?? [], task.recencyWindow)\n\n const maxGaps = itemCount\n const gapCount = output.gaps?.length ?? 0\n scores.gap_coverage = Math.max(0, 1 - gapCount / maxGaps)\n\n const score =\n 0.4 * scores.citation_density +\n 0.2 * scores.source_diversity +\n 0.2 * scores.recency_match +\n 0.2 * scores.gap_coverage\n\n const verdict: DefaultVerdict = {\n valid: pass,\n score: Number.isFinite(score) ? score : 0,\n scores,\n }\n if (notes.length > 0) verdict.notes = notes.join('; ')\n return verdict\n },\n }\n}\n\nfunction recencyMatchScore(items: KnowledgeItem[], window: ResearchTask['recencyWindow']): number {\n if (!window || (window.since === undefined && window.until === undefined)) return 1\n if (items.length === 0) return 0\n const sinceMs = window.since?.getTime() ?? Number.NEGATIVE_INFINITY\n const untilMs = window.until?.getTime() ?? Number.POSITIVE_INFINITY\n let hits = 0\n let total = 0\n for (const item of items) {\n for (const evidence of item.evidence ?? []) {\n if (typeof evidence.capturedAt !== 'number') continue\n total += 1\n if (evidence.capturedAt >= sinceMs && evidence.capturedAt <= untilMs) hits += 1\n }\n }\n return total === 0 ? 0 : hits / total\n}\n\n/** Built-in source-grounded research contract added to a caller-owned exact profile. */\nexport const RESEARCHER_SYSTEM_PROMPT = [\n 'You are a research agent. Your job is to answer a research question with',\n 'source-grounded knowledge items that the caller will choose whether to',\n 'persist to a multi-tenant knowledge base.',\n '',\n 'Hard rules:',\n \" 1. Every item you emit MUST carry the task's knowledgeNamespace exactly.\",\n ' Never write to a different namespace.',\n ' 2. Every item MUST carry at least one evidence entry with a source.',\n ' A quote + url is strongly preferred; capturedAt is unix ms.',\n ' 3. You propose writes — you do NOT apply them. The caller decides.',\n ' 4. Self-report confidence honestly in [0, 1]. Do not inflate.',\n ' 5. List what you could not answer in `gaps`. Better to admit a gap',\n ' than fabricate.',\n '',\n 'When you finish, emit a single final structured message of the shape:',\n ' ```json',\n ' { \"items\": [{ \"id\": \"...\", \"namespace\": \"...\", \"claim\": \"...\",',\n ' \"evidence\": [{ \"source\": \"...\", \"quote\": \"...\",',\n ' \"url\": \"...\", \"capturedAt\": 0 }],',\n ' \"confidence\": 0.0,',\n ' \"authoredBy\": { \"kind\": \"agent\", \"id\": \"...\" } }],',\n ' \"citations\": [{ \"url\": \"...\", \"quote\": \"...\", \"confidence\": 0.0 }],',\n ' \"proposedWrites\": [{ \"kind\": \"insert\", \"namespace\": \"...\",',\n ' \"item\": { /* same shape as items[] */ } }],',\n ' \"gaps\": [\"...\"],',\n ' \"notes\": \"free-form commentary\" }',\n ' ```',\n].join('\\n')\n\nfunction formatResearcherPrompt(task: ResearchTask): string {\n const sources = task.sources?.length ? task.sources.join(', ') : '(no preference)'\n const window = formatRecencyWindow(task.recencyWindow)\n return [\n `Question: ${task.question}`,\n `Knowledge namespace (DO NOT cross): ${task.knowledgeNamespace}`,\n `Scope: ${task.scope ?? '(unspecified)'}`,\n `Preferred sources: ${sources}`,\n `Recency window: ${window}`,\n `Max items: ${task.maxItems ?? '(no cap)'}`,\n `Per-item minimum confidence: ${task.minConfidence ?? '(no floor)'}`,\n '',\n 'Produce knowledge items with provenance + citations + proposed writes.',\n 'List gaps for anything you could not answer. Emit the final JSON',\n 'result block exactly as instructed.',\n ].join('\\n')\n}\n\nfunction formatRecencyWindow(window: ResearchTask['recencyWindow']): string {\n if (!window) return '(none)'\n const since = window.since ? window.since.toISOString() : '-∞'\n const until = window.until ? window.until.toISOString() : 'now'\n return `${since} .. ${until}`\n}\n\n/**\n * Walk the event stream and return the last structured `research.result`\n * payload. Falls back to scanning text deltas for a fenced JSON block.\n */\nfunction parseResearcherEvents(events: SandboxEvent[]): ResearchOutput {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const type = String(event.type ?? '')\n const data = isRecord(event.data) ? event.data : {}\n if (type === 'result' || type === 'final' || type === 'research.result') {\n const direct = coerceResearchOutput(data.result ?? data.output ?? data)\n // opencode reports the agent's terminal answer in `finalText` (not result/output).\n // Parse it too, and prefer it when `direct` is an all-empty shape — otherwise an\n // event carrying both `{items:[],citations:[],proposedWrites:[]}` and a rich\n // finalText would silently drop the real answer.\n const finalText = pickString(data.finalText)\n const fenced = finalText ? extractFencedJson(finalText) : undefined\n const fromFinalText = fenced ? coerceResearchOutput(fenced) : undefined\n if (direct && !isEmptyOutput(direct)) return direct\n if (fromFinalText) return fromFinalText\n if (direct) return direct\n }\n }\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const data = isRecord(event.data) ? event.data : {}\n const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.finalText)\n if (!text) continue\n const fenced = extractFencedJson(text)\n if (!fenced) continue\n const coerced = coerceResearchOutput(fenced)\n if (coerced) return coerced\n }\n return { items: [], citations: [], proposedWrites: [] }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\n/** A coerced output that carries no items, citations, or proposed writes. */\nfunction isEmptyOutput(o: ResearchOutput): boolean {\n return o.items.length === 0 && o.citations.length === 0 && o.proposedWrites.length === 0\n}\n\nfunction pickString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction extractFencedJson(text: string): unknown | undefined {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)\n if (!match) return undefined\n const body = (match[1] ?? '').trim()\n if (!body) return undefined\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction coerceResearchOutput(value: unknown): ResearchOutput | undefined {\n if (!isRecord(value)) return undefined\n const items = coerceItems(value.items)\n const citations = coerceCitations(value.citations)\n const proposedWrites = coerceProposedWrites(value.proposedWrites)\n // Reject completely empty payloads — those signal \"no result block\",\n // not \"a valid empty result\".\n if (items === undefined && citations === undefined && proposedWrites === undefined) {\n return undefined\n }\n const output: ResearchOutput = {\n items: items ?? [],\n citations: citations ?? [],\n proposedWrites: proposedWrites ?? [],\n }\n if (Array.isArray(value.gaps)) {\n output.gaps = value.gaps.filter((entry): entry is string => typeof entry === 'string')\n }\n const notes = pickString(value.notes)\n if (notes) output.notes = notes\n // Preserve any extra fields the agent emitted that don't fit the typed\n // surface — callers can inspect `raw` without forcing them through the\n // typed coercion. We only include `raw` when the agent emitted fields\n // beyond the known set.\n const known = new Set(['items', 'citations', 'proposedWrites', 'gaps', 'notes'])\n const extras: Record<string, unknown> = {}\n let extrasCount = 0\n for (const [key, val] of Object.entries(value)) {\n if (known.has(key)) continue\n extras[key] = val\n extrasCount += 1\n }\n if (extrasCount > 0) output.raw = extras\n return output\n}\n\nfunction coerceItems(value: unknown): KnowledgeItem[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeItem[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const id = pickString(entry.id)\n const namespace = pickString(entry.namespace)\n const claim = pickString(entry.claim)\n const evidence = coerceEvidence(entry.evidence)\n const confidence = toFiniteNumber(entry.confidence)\n const authoredBy = coerceAuthoredBy(entry.authoredBy)\n if (!id || !namespace || !claim || !authoredBy) continue\n const item: KnowledgeItem = {\n id,\n namespace,\n claim,\n evidence,\n confidence: clamp01(confidence),\n authoredBy,\n }\n if (Array.isArray(entry.supersedes)) {\n item.supersedes = entry.supersedes.filter((s): s is string => typeof s === 'string')\n }\n const retractedAt = toFiniteNumber(entry.retractedAt)\n if (retractedAt > 0) item.retractedAt = retractedAt\n out.push(item)\n }\n return out\n}\n\nfunction coerceEvidence(value: unknown): KnowledgeItem['evidence'] {\n if (!Array.isArray(value)) return []\n const out: KnowledgeItem['evidence'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const source = pickString(entry.source)\n if (!source) continue\n const item: KnowledgeItem['evidence'][number] = {\n source,\n capturedAt: toFiniteNumber(entry.capturedAt),\n }\n const quote = pickString(entry.quote)\n if (quote) item.quote = quote\n const url = pickString(entry.url)\n if (url) item.url = url\n out.push(item)\n }\n return out\n}\n\nfunction coerceAuthoredBy(value: unknown): KnowledgeItem['authoredBy'] | undefined {\n if (!isRecord(value)) return undefined\n const kind = value.kind === 'human' || value.kind === 'agent' ? value.kind : undefined\n const id = pickString(value.id)\n if (!kind || !id) return undefined\n return { kind, id }\n}\n\nfunction coerceCitations(value: unknown): ResearchOutput['citations'] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: ResearchOutput['citations'] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const url = pickString(entry.url)\n const quote = pickString(entry.quote)\n if (!url || !quote) continue\n out.push({ url, quote, confidence: clamp01(toFiniteNumber(entry.confidence)) })\n }\n return out\n}\n\nfunction coerceProposedWrites(value: unknown): KnowledgeUpdate[] | undefined {\n if (!Array.isArray(value)) return undefined\n const out: KnowledgeUpdate[] = []\n for (const entry of value) {\n if (!isRecord(entry)) continue\n const namespace = pickString(entry.namespace)\n if (!namespace) continue\n if (entry.kind === 'insert') {\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!item) continue\n out.push({ kind: 'insert', namespace, item })\n } else if (entry.kind === 'supersede') {\n const previousId = pickString(entry.previousId)\n const items = coerceItems([entry.item])\n const item = items?.[0]\n if (!previousId || !item) continue\n out.push({ kind: 'supersede', namespace, previousId, item })\n } else if (entry.kind === 'retract') {\n const itemId = pickString(entry.itemId)\n const reason = pickString(entry.reason)\n if (!itemId || !reason) continue\n out.push({ kind: 'retract', namespace, itemId, reason })\n }\n }\n return out\n}\n\nfunction toFiniteNumber(value: unknown): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0\n}\n\nfunction clamp01(value: number): number {\n if (!Number.isFinite(value)) return 0\n if (value < 0) return 0\n if (value > 1) return 1\n return value\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4HA,MAAM,+BAA+B;;AAGrC,SAAgB,kBAAkB,SAMhC;CACA,MAAM,OAAO,mBAAmB,MAAM,QAAQ,OAAO;CACrD,6BAA6B,MAAM,mBAAmB;CACtD,MAAM,OAAO,QAAQ,QAAQ,KAAK;CAClC,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,qBAAqB,QAAQ,sBAAsB;CACzD,MAAM,UAAwB;EAC5B,GAAG;EACH;EACA,aAAa,KAAK,eAAe;EACjC,QAAQ;GAAE,GAAG,KAAK;GAAQ;EAAa;EACvC,OAAO;GAAE,YAAY;GAAM,IAAI;GAAM,OAAO;GAAM,GAAG,KAAK;EAAM;EAChE,UAAU;GAAE,GAAG,KAAK;GAAU,MAAM;EAAa;CACnD;CAaA,OAAO;EAAE;EAAS,cAAc;EAAwB,QA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OAAO,KAAA;CAClC,MAAM,MAAyB,CAAC;CAChC,KAAK,MAAM,SAAS,OAAO;EACzB,IAAI,CAAC,SAAS,KAAK,GAAG;EACtB,MAAM,YAAY,WAAW,MAAM,SAAS;EAC5C,IAAI,CAAC,WAAW;EAChB,IAAI,MAAM,SAAS,UAAU;GAE3B,MAAM,OADQ,YAAY,CAAC,MAAM,IAAI,CACpB,CAAC,GAAG;GACrB,IAAI,CAAC,MAAM;GACX,IAAI,KAAK;IAAE,MAAM;IAAU;IAAW;GAAK,CAAC;EAC9C,OAAO,IAAI,MAAM,SAAS,aAAa;GACrC,MAAM,aAAa,WAAW,MAAM,UAAU;GAE9C,MAAM,OADQ,YAAY,CAAC,MAAM,IAAI,CACpB,CAAC,GAAG;GACrB,IAAI,CAAC,cAAc,CAAC,MAAM;GAC1B,IAAI,KAAK;IAAE,MAAM;IAAa;IAAW;IAAY;GAAK,CAAC;EAC7D,OAAO,IAAI,MAAM,SAAS,WAAW;GACnC,MAAM,SAAS,WAAW,MAAM,MAAM;GACtC,MAAM,SAAS,WAAW,MAAM,MAAM;GACtC,IAAI,CAAC,UAAU,CAAC,QAAQ;GACxB,IAAI,KAAK;IAAE,MAAM;IAAW;IAAW;IAAQ;GAAO,CAAC;EACzD;CACF;CACA,OAAO;AACT;AAEA,SAAS,eAAe,OAAwB;CAC9C,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE;AAEA,SAAS,QAAQ,OAAuB;CACtC,IAAI,CAAC,OAAO,SAAS,KAAK,GAAG,OAAO;CACpC,IAAI,QAAQ,GAAG,OAAO;CACtB,IAAI,QAAQ,GAAG,OAAO;CACtB,OAAO;AACT"}
@@ -1,6 +1,6 @@
1
- import { E as SandboxClient, at as RuntimeStreamEvent, i as ExecCtx, k as Validator } from "./types-DeX8ibLc.js";
2
- import { B as Scope, Cn as ExecutorProgress, _ as ExecutorRegistry, a as DefaultVerdict, g as ExecutorProgressEvent, gn as TraceSource, l as ExecutorCancellation, p as ExecutorFactory, q as Spend, rt as UsageEvent, u as ExecutorCancellationRequest, y as ExecutorToolCall } from "./types-Cz5mCGlY.js";
3
- import { i as AgentEnvironmentProvider, o as AgentEnvironmentProviderRegistry, w as ProviderExecutorOptions } from "./environment-provider-C_QI6VCG.js";
1
+ import { E as SandboxClient, at as RuntimeStreamEvent, i as ExecCtx, k as Validator } from "./types-DpdfZoQ3.js";
2
+ import { K as Spend, Sn as ExecutorProgress, _ as ExecutorRegistry, a as DefaultVerdict, g as ExecutorProgressEvent, hn as TraceSource, l as ExecutorCancellation, nt as UsageEvent, p as ExecutorFactory, u as ExecutorCancellationRequest, y as ExecutorToolCall, z as Scope } from "./types-BBXdSns1.js";
3
+ import { i as AgentEnvironmentProvider, o as AgentEnvironmentProviderRegistry, w as ProviderExecutorOptions } from "./environment-provider-BobKk46F.js";
4
4
  import { AgentProfile, AgentProfileMcpServer, HarnessType, ReasoningEffort, StreamEvent } from "@tangle-network/agent-interface";
5
5
  import { WorkspacePlanReceipt } from "@tangle-network/agent-profile-materialize";
6
6
  import { ChildProcess } from "node:child_process";
@@ -1374,4 +1374,4 @@ declare function createExecutor(config: ExecutorConfig): ExecutorFactory<unknown
1374
1374
  declare function createExecutorRegistry(): ExecutorRegistry;
1375
1375
  //#endregion
1376
1376
  export { LocalHarnessResult as $, extractLlmCallEvent as A, PeerMailReadout as At, resolveMcpServerLaunch as B, JsonRpcMessage as Bt, createInbox as C, DEFAULT_PEER_MAIL_LIMITS as Ct, SandboxToolPartState as D, PeerMailKind as Dt, SandboxServedBackend as E, PeerMailEvent as Et, sumSandboxUsage as F, claimsAuthority as Ft, WorktreeHarnessResult as G, secretEnvOfMcpServer as H, McpToolDescriptor as Ht, KeyProvider as I, createPeerMailbox as It, CodexExecutionPolicy as J, WorktreeProfileMaterializationReceipt as K, ResolvedMcpServerLaunch as L, isPeerMailEnvelope as Lt, mapSandboxToolEvent as M, PeerMailSendInput as Mt, sandboxEventServedBackend as N, PeerMailbox as Nt, assertSandboxServedModel as O, PeerMailLimits as Ot, sandboxProgressEvents as P, PeerMailboxOptions as Pt, LocalHarness as Q, envKeyProvider as R, peerMailTools as Rt, PeerInboxMessage as S, AUTHORITY_MARKERS as St, SandboxOutputMarker as T, PeerMailEnvelope as Tt, WorktreeCheckRunner as U, McpTransport as Ut, resolveSecretEnv as V, JsonRpcResponse as Vt, WorktreeCommandResult as W, DEFAULT_LOCAL_HARNESS as X, CodexTokenUsage as Y, LOCAL_HARNESSES as Z, SteerableSandboxSession as _, ToolLoopChat as _t, CliWorktreeSeam as a, CreateWorktreeOptions as at, Inbox as b, ToolLoopMessageRecord as bt, RouterSeam as c, GitRunner as ct, cliWorktreeExecutor as d, captureWorktreeDiff as dt, RunLocalHarnessOptions as et, createExecutor as f, createWorktree as ft, SteerableSandboxArgs as g, ToolLoopCallContext as gt, SandboxSteeringOptions as h, ToolSpec as ht, CliWorktreeBridgeSeam as i, runLocalHarness as it, mapSandboxEvent as j, PeerMailRefusal as jt, createSandboxToolPartState as k, PeerMailOutcome as kt, RouterToolsSeam as l, RemoveWorktreeOptions as lt, DEFAULT_SANDBOX_STEERING_MAX_TURNS as m, RouterTransportConfig as mt, BridgeSeam as n, localHarnessExecutable as nt, ExecutorConfig as o, DiffOptions as ot, createExecutorRegistry as p, removeWorktree as pt, CodexExecutionEvidence as q, CliSeam as r, parseCodexTokenUsage as rt, ProviderSeam as s, DiffResult as st, BridgeModelCredential as t, harnessSupportsReasoningEffort as tt, SandboxSeam as u, WorktreeHandle as ut, createSteerableSandboxSession as v, ToolLoopCompaction as vt, SandboxLeafOut as w, PEER_MAIL_WIRE_KEY as wt, InboxMessage as x, ToolLoopToolCall as xt, AuthorityInboxMessage as y, ToolLoopCompactionOptions as yt, mcpSecretEnvMetadataKey as z, peerMailVerbNames as zt };
1377
- //# sourceMappingURL=runtime-DuueBLeO.d.ts.map
1377
+ //# sourceMappingURL=runtime-BzY66cd6.d.ts.map
@@ -2,20 +2,20 @@ import { A as assertEventBinding, B as exactContinuedControlRef, D as abortError
2
2
  import { c as RetainedInteractiveAdmissionError, d as RetainedRunDispatchBindingError, l as RetainedInteractiveBindingError, m as ValidationError, n as AnalystError, s as PlannerError, u as RetainedRunAdmissionError } from "./errors-CDZ8XsVj.js";
3
3
  import "./stream-agent-turn-FRZAuXAL.js";
4
4
  import { n as detachedSnapshot } from "./snapshot-CTAf4uuA.js";
5
- import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, s as insideCursorNamespace, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal-duo0EkOp.js";
5
+ import { i as InMemorySpawnJournal, r as InMemoryResultBlobStore, s as insideCursorNamespace, v as isTraceAnalysisStore, x as contentAddress } from "./spawn-journal-oewq1g2h.js";
6
6
  import { c as isAbortError, d as randomSuffix, i as cloneSpend, m as stringifySafe, p as sleep, r as chargedTokens, s as hasCompleteCacheBreakdown, t as addSpend, y as zeroSpend } from "./util-D6ZEuBMi.js";
7
7
  import { i as writeAllBytes, n as parseCommittedJsonLines, r as prepareJsonlAppend, t as isNoEntError } from "./jsonl-file-CDfsCI5s.js";
8
8
  import { i as redactProtectedValue, r as redactProtectedReason } from "./protected-redaction--F3v1oo8.js";
9
9
  import { c as notifySandboxEventObserver, m as parseCanonicalTransportEvent, p as extractTransportEventIdentity } from "./sandbox-events-BVjstFgb.js";
10
10
  import { n as executableAgentSpecSnapshot, t as executableAgentProfileSnapshot } from "./executable-spec-7ovS7PBo.js";
11
11
  import { c as profileModelExecutionSettings, i as concreteModelId, l as profileProviderModel, o as enforceTokenLimits, t as assertExecutableAgentProfile } from "./model-policy-Sw4ywhtL.js";
12
- import { B as createExecutorRegistry, Ct as canonicalObservedModel, E as rollingDispatch, H as createWorktreeCliExecutor, St as runBrainLoop, X as createPushTraceSource, _t as runAgentRounds, g as settledToIteration, ht as defaultSelectWinner, l as withDriverExecutor, n as createSupervisor, vt as createSandboxLineage, xt as routerBrain, yt as probeSandboxCapabilities, z as createExecutor } from "./supervisor-BmXD0WCJ.js";
13
- import "./environment-provider-Dz9JB-X_.js";
12
+ import { B as createExecutorRegistry, Ct as canonicalObservedModel, E as rollingDispatch, H as createWorktreeCliExecutor, St as runBrainLoop, X as createPushTraceSource, _t as runAgentRounds, g as settledToIteration, ht as defaultSelectWinner, l as withDriverExecutor, n as createSupervisor, vt as createSandboxLineage, xt as routerBrain, yt as probeSandboxCapabilities, z as createExecutor } from "./supervisor-ZlQy5Fwl.js";
13
+ import "./environment-provider-Bn3652YU.js";
14
14
  import { i as notifyRuntimeHookEvent } from "./runtime-hooks-tXpAarhW.js";
15
- import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-B1TocSdq.js";
16
- import { At as gateOnDeliverable, jt as mapExecutorResult, n as supervise } from "./supervise-BVE0XAJa.js";
17
- import "./authoring-C4uCoDmO.js";
18
- import "./graph-BibNm6a-.js";
15
+ import { C as observe, O as strategyAuthorMethod, T as profileChatClient, b as sample, v as refine, x as sampleThenRefine, y as runAgentic } from "./structural-rollout-Cj58xALQ.js";
16
+ import { At as gateOnDeliverable, jt as mapExecutorResult, n as supervise } from "./supervise-CqwjiXlX.js";
17
+ import "./authoring-rIDPzwYY.js";
18
+ import "./graph-BGPO6z_u.js";
19
19
  import { AgentEnvironmentCapabilitiesSchema, AgentExactRunControlRefSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentNativeContextContinuationResultSchema, AgentTurnResultSchema, InteractionAcknowledgementSchema, InteractionResponseCommandSchema, NativeContextBoundaryProofSchema, NativeContextContinuationRequestSchema, RuntimeEventEnvelopeSchema, TerminalReplayWindowSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionControlClaimRequestDigest, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionRunRef, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentNativeContextContinuationResultMatchesRequest, agentProfileSchema, canonicalAgentProfileDigest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, nativeContextContinuationTurnDigest, validateAgentProfileSecurity } from "@tangle-network/agent-interface";
20
20
  import { CODING_HARNESSES, DEFAULT_TRACE_ANALYST_KINDS, InMemoryTraceStore, OUTPUT_VALUE, benjaminiHochberg, buildTrajectory, computeFindingId as computeFindingId$1, confidenceInterval, expandProfileAxes, makeFinding as makeFinding$1, pairedBootstrap, paretoFrontier, wilcoxonSignedRank, wilson } from "@tangle-network/agent-eval";
21
21
  import { heldoutSignificance, runProfileMatrix } from "@tangle-network/agent-eval/campaign";
@@ -7130,4 +7130,4 @@ function tail(s) {
7130
7130
  //#endregion
7131
7131
  export { definePersona as $, discriminatingMeans as A, sentinelCompletion as At, printBenchmarkReport as B, McpSpawnFault as Bt, withUntrackedArtifacts as C, localSandboxClient as Ct, chatTransportExecutor as D, superviseDispatch as Dt, runCoderChecks as E, loopDispatch as Et, authorStrategy as F, renderLeaderboardMarkdown as Ft, startRetainedInteractiveRun as G, envKeyProvider as Gt, claimRetainedInteractiveControl as H, materializeLocalMcp as Ht, strategyAuthorContract as I, renderLeaderboardSvg as It, startRetainedRun as J, resolveSecretEnv as Jt, reconnectRetainedRun as K, mcpSecretEnvMetadataKey as Kt, strategyAuthorSystemPrompt as L, renderPairwiseMarkdown as Lt, runStrategyEvolution as M, leaderboard as Mt, selectChampion as N, pairwiseSignificance as Nt, chatWorkerSeam as O, completionAuthorizes as Ot, assertStrategyContract as P, renderLeaderboardHtml as Pt, trajectoryReport as Q, SandboxRunAbortError as R, auditIntent as Rt, copyUntrackedIntoClone as S, resolveSandboxClient as St, patchDelivered as T, loopCampaignDispatch as Tt, reconnectRetainedInteractiveRun as U, createMcpEnvironment as Ut, runBenchmark as V, connectStdioMcp as Vt, recoverRetainedInteractiveRun as W, sanitizeMcpToolSchema as Wt, promotionGate as X, startRetainedRunInEnvironment as Y, secretEnvOfMcpServer as Yt, equalKOnCost as Z, NOTE_MAX_CHARS as _, createScopeAnalyst as _t, localShell as a, InMemoryCorpus as at, composeWorkerEvidence as b, harvestCorpus as bt, createVerifierEnvironment as c, flatWidenGate as ct, harvestSurfaceDiffs as d, pipeline as dt, runPersonified as et, analystsFromRegistry as f, selectValidWinner as ft, EVIDENCE_MAX_CHARS as g, buildSteerContext as gt, worktreeFanout as h, assertTraceDerivedFindings as ht, jjWorkspace as i, FileCorpus as it, pickChampion as j, stopSentinel as jt, createChatSessionStore as k, deterministicCompletion as kt, boxSurfaceReader as l, loopUntil as lt, superviseSurface as m, widen as mt, makeFinding$1 as n, createShapeRegistry as nt, runInWorkspace as o, renderCorpusToInstructions as ot, failuresAnalyst as p, verify as pt, recoverRetainedRun as q, resolveMcpServerLaunch as qt, gitWorkspace as r, registerShape as rt, createWaterfallCollector as s, fanout as st, computeFindingId$1 as t, builtinShapes as tt, fsSurfaceReader as u, panel as ut, VERIFY_TAIL_CHARS as v, registryScopeAnalyst as vt, analyzeTrace as w, inlineSandboxClient as wt, settledWorkerOut as x, defineLeaderboard as xt, closingWorkerNote as y, inProcessSandboxClient as yt, openSandboxRun as z, defaultAuditorInstruction as zt };
7132
7132
 
7133
- //# sourceMappingURL=runtime-D-NDRp4y.js.map
7133
+ //# sourceMappingURL=runtime-CTs2JsG9.js.map