@tangle-network/agent-runtime 0.105.0 → 0.106.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 (218) hide show
  1. package/README.md +2 -2
  2. package/dist/activation-CRjVfOiy.js +203 -0
  3. package/dist/activation-CRjVfOiy.js.map +1 -0
  4. package/dist/activation-DyWB0K6E.d.ts +98 -0
  5. package/dist/agent.d.ts +216 -234
  6. package/dist/agent.js +615 -547
  7. package/dist/agent.js.map +1 -1
  8. package/dist/analyst-loop-DGdtVENg.js +517 -0
  9. package/dist/analyst-loop-DGdtVENg.js.map +1 -0
  10. package/dist/analyst-loop.d.ts +10 -43
  11. package/dist/analyst-loop.js +2 -11
  12. package/dist/backends-Dy8NujB4.js +713 -0
  13. package/dist/backends-Dy8NujB4.js.map +1 -0
  14. package/dist/candidate-execution/index.d.ts +4 -192
  15. package/dist/candidate-execution/index.js +5 -66
  16. package/dist/candidate-execution-DqMbv1rU.js +488 -0
  17. package/dist/candidate-execution-DqMbv1rU.js.map +1 -0
  18. package/dist/coder-yhVWbdWc.js +40 -0
  19. package/dist/coder-yhVWbdWc.js.map +1 -0
  20. package/dist/conversation-XucG_K3l.js +1265 -0
  21. package/dist/conversation-XucG_K3l.js.map +1 -0
  22. package/dist/conversation.d.ts +2 -804
  23. package/dist/conversation.js +2 -55
  24. package/dist/environment-provider-CfLUmKmf.js +1168 -0
  25. package/dist/environment-provider-CfLUmKmf.js.map +1 -0
  26. package/dist/environment-provider-IUGU3epE.d.ts +964 -0
  27. package/dist/environment-provider.d.ts +2 -78
  28. package/dist/environment-provider.js +2 -18
  29. package/dist/errors-DEAvWQPy.js +111 -0
  30. package/dist/errors-DEAvWQPy.js.map +1 -0
  31. package/dist/improvement-adapter-Cr5TBSji.d.ts +166 -0
  32. package/dist/improvement-cycle-C095kS_g.js +2624 -0
  33. package/dist/improvement-cycle-C095kS_g.js.map +1 -0
  34. package/dist/index-BGdxAwfO.d.ts +838 -0
  35. package/dist/index-C-FYUuFG.d.ts +193 -0
  36. package/dist/index-CbNM40xG.d.ts +140 -0
  37. package/dist/index-DruSKs3Z.d.ts +7224 -0
  38. package/dist/index-Efjb3nrQ.d.ts +671 -0
  39. package/dist/index.d.ts +14 -1058
  40. package/dist/index.js +2106 -2082
  41. package/dist/index.js.map +1 -1
  42. package/dist/intelligence.d.ts +768 -889
  43. package/dist/intelligence.js +1466 -1367
  44. package/dist/intelligence.js.map +1 -1
  45. package/dist/{kb-gate-CwHO0vz6.d.ts → kb-gate-C8z2juK8.d.ts} +33 -31
  46. package/dist/kb-gate-DpaSwXVx.js +80 -0
  47. package/dist/kb-gate-DpaSwXVx.js.map +1 -0
  48. package/dist/knowledge-Ku-mPP4f.js +433 -0
  49. package/dist/knowledge-Ku-mPP4f.js.map +1 -0
  50. package/dist/knowledge.d.ts +2 -150
  51. package/dist/knowledge.js +2 -40
  52. package/dist/local-harness-Dh8PJ0ot.d.ts +455 -0
  53. package/dist/loop-runner-bin-BXsFEUcf.d.ts +162 -0
  54. package/dist/loop-runner-bin-BwjQ1NfH.js +268 -0
  55. package/dist/loop-runner-bin-BwjQ1NfH.js.map +1 -0
  56. package/dist/loop-runner-bin.d.ts +2 -15
  57. package/dist/loop-runner-bin.js +2 -24
  58. package/dist/loops.d.ts +5 -4164
  59. package/dist/loops.js +8 -419
  60. package/dist/mcp/bin.d.ts +1 -1
  61. package/dist/mcp/bin.js +116 -146
  62. package/dist/mcp/bin.js.map +1 -1
  63. package/dist/mcp/index.d.ts +295 -436
  64. package/dist/mcp/index.js +1242 -1177
  65. package/dist/mcp/index.js.map +1 -1
  66. package/dist/mcp/memory-bin.d.ts +1 -1
  67. package/dist/mcp/memory-bin.js +37 -16
  68. package/dist/mcp/memory-bin.js.map +1 -1
  69. package/dist/memory-server-DL6cE2Ag.js +234 -0
  70. package/dist/memory-server-DL6cE2Ag.js.map +1 -0
  71. package/dist/model-resolution-Btd9iIKV.js +98 -0
  72. package/dist/model-resolution-Btd9iIKV.js.map +1 -0
  73. package/dist/openai-tools-B68JaOCx.d.ts +24 -0
  74. package/dist/openai-tools-CKLy1C7M.js +44 -0
  75. package/dist/openai-tools-CKLy1C7M.js.map +1 -0
  76. package/dist/otel-export-D34IQW1C.js +843 -0
  77. package/dist/otel-export-D34IQW1C.js.map +1 -0
  78. package/dist/platform.d.ts +188 -185
  79. package/dist/platform.js +185 -218
  80. package/dist/platform.js.map +1 -1
  81. package/dist/prepare-B53sPV7M.js +4292 -0
  82. package/dist/prepare-B53sPV7M.js.map +1 -0
  83. package/dist/primeintellect/index.d.ts +149 -145
  84. package/dist/primeintellect/index.js +626 -1003
  85. package/dist/primeintellect/index.js.map +1 -1
  86. package/dist/profiles.d.ts +296 -490
  87. package/dist/profiles.js +722 -749
  88. package/dist/profiles.js.map +1 -1
  89. package/dist/protected-model-port-BLPH5VVv.js +722 -0
  90. package/dist/protected-model-port-BLPH5VVv.js.map +1 -0
  91. package/dist/protected-model-port-BP6Z4eau.d.ts +283 -0
  92. package/dist/protected-redaction--F3v1oo8.js +200 -0
  93. package/dist/protected-redaction--F3v1oo8.js.map +1 -0
  94. package/dist/redact-D-u-rrcn.js +82 -0
  95. package/dist/redact-D-u-rrcn.js.map +1 -0
  96. package/dist/redact-kbIOjfjM.d.ts +452 -0
  97. package/dist/researcher-CoVqNhfI.js +433 -0
  98. package/dist/researcher-CoVqNhfI.js.map +1 -0
  99. package/dist/runtime-BG0BziaP.js +5408 -0
  100. package/dist/runtime-BG0BziaP.js.map +1 -0
  101. package/dist/sandbox-events-DeI5xX8P.js +316 -0
  102. package/dist/sandbox-events-DeI5xX8P.js.map +1 -0
  103. package/dist/spawn-journal-CwPvKUTa.js +456 -0
  104. package/dist/spawn-journal-CwPvKUTa.js.map +1 -0
  105. package/dist/structural-rollout-IXUEplky.js +1445 -0
  106. package/dist/structural-rollout-IXUEplky.js.map +1 -0
  107. package/dist/substrate-B0TYNrXn.js +27 -0
  108. package/dist/substrate-B0TYNrXn.js.map +1 -0
  109. package/dist/{substrate-Dyiqmd3o.d.ts → substrate-BcnuSHXm.d.ts} +57 -54
  110. package/dist/supervise-BiRutHS9.js +7321 -0
  111. package/dist/supervise-BiRutHS9.js.map +1 -0
  112. package/dist/supervisor-DTKhF-RV.js +3826 -0
  113. package/dist/supervisor-DTKhF-RV.js.map +1 -0
  114. package/dist/testing.d.ts +4 -3
  115. package/dist/testing.js +2478 -2637
  116. package/dist/testing.js.map +1 -1
  117. package/dist/tool-server-RcWgLIsL.js +141 -0
  118. package/dist/tool-server-RcWgLIsL.js.map +1 -0
  119. package/dist/trace-propagation-CJJC7SVB.js +57 -0
  120. package/dist/trace-propagation-CJJC7SVB.js.map +1 -0
  121. package/dist/types-BaIpb0XT.d.ts +492 -0
  122. package/dist/types-BevOjfTY.d.ts +765 -0
  123. package/dist/types-C9j4qg6l.d.ts +500 -0
  124. package/dist/types-Cja5OTGh.d.ts +190 -0
  125. package/dist/util-MVgdwuIS.js +145 -0
  126. package/dist/util-MVgdwuIS.js.map +1 -0
  127. package/dist/workspace-archive-BosQiotA.js +575 -0
  128. package/dist/workspace-archive-BosQiotA.js.map +1 -0
  129. package/package.json +43 -56
  130. package/skills/build-with-agent-runtime/SKILL.md +1 -0
  131. package/dist/activation-Cm-9MMX1.d.ts +0 -69
  132. package/dist/analyst-loop.js.map +0 -1
  133. package/dist/backends-BO4Jqoe2.d.ts +0 -134
  134. package/dist/candidate-execution/index.js.map +0 -1
  135. package/dist/chunk-2KGAN2HM.js +0 -1256
  136. package/dist/chunk-2KGAN2HM.js.map +0 -1
  137. package/dist/chunk-2VZYRB55.js +0 -834
  138. package/dist/chunk-2VZYRB55.js.map +0 -1
  139. package/dist/chunk-3MDZX7YU.js +0 -125
  140. package/dist/chunk-3MDZX7YU.js.map +0 -1
  141. package/dist/chunk-5IBQAPVB.js +0 -29
  142. package/dist/chunk-5IBQAPVB.js.map +0 -1
  143. package/dist/chunk-5QOB7H74.js +0 -387
  144. package/dist/chunk-5QOB7H74.js.map +0 -1
  145. package/dist/chunk-C5RTIBNZ.js +0 -48
  146. package/dist/chunk-C5RTIBNZ.js.map +0 -1
  147. package/dist/chunk-CTRA64LY.js +0 -680
  148. package/dist/chunk-CTRA64LY.js.map +0 -1
  149. package/dist/chunk-DPEUKJRO.js +0 -27
  150. package/dist/chunk-DPEUKJRO.js.map +0 -1
  151. package/dist/chunk-FD2MBMOH.js +0 -494
  152. package/dist/chunk-FD2MBMOH.js.map +0 -1
  153. package/dist/chunk-H5QPIZNX.js +0 -907
  154. package/dist/chunk-H5QPIZNX.js.map +0 -1
  155. package/dist/chunk-HLKC4UYB.js +0 -3514
  156. package/dist/chunk-HLKC4UYB.js.map +0 -1
  157. package/dist/chunk-HNP72PNU.js +0 -192
  158. package/dist/chunk-HNP72PNU.js.map +0 -1
  159. package/dist/chunk-ISPWRSEC.js +0 -408
  160. package/dist/chunk-ISPWRSEC.js.map +0 -1
  161. package/dist/chunk-KRBFHMV6.js +0 -1228
  162. package/dist/chunk-KRBFHMV6.js.map +0 -1
  163. package/dist/chunk-M22PL4GH.js +0 -171
  164. package/dist/chunk-M22PL4GH.js.map +0 -1
  165. package/dist/chunk-NURIQBJQ.js +0 -72
  166. package/dist/chunk-NURIQBJQ.js.map +0 -1
  167. package/dist/chunk-OPVWXJ2H.js +0 -75
  168. package/dist/chunk-OPVWXJ2H.js.map +0 -1
  169. package/dist/chunk-PZZKQVQV.js +0 -52
  170. package/dist/chunk-PZZKQVQV.js.map +0 -1
  171. package/dist/chunk-Q2JSAVQ3.js +0 -671
  172. package/dist/chunk-Q2JSAVQ3.js.map +0 -1
  173. package/dist/chunk-RDOAVVHY.js +0 -699
  174. package/dist/chunk-RDOAVVHY.js.map +0 -1
  175. package/dist/chunk-SGKPNBXE.js +0 -60
  176. package/dist/chunk-SGKPNBXE.js.map +0 -1
  177. package/dist/chunk-SMQXZGLZ.js +0 -351
  178. package/dist/chunk-SMQXZGLZ.js.map +0 -1
  179. package/dist/chunk-UHEZW5BU.js +0 -2918
  180. package/dist/chunk-UHEZW5BU.js.map +0 -1
  181. package/dist/chunk-UPWGXKXB.js +0 -254
  182. package/dist/chunk-UPWGXKXB.js.map +0 -1
  183. package/dist/chunk-VISA6CI3.js +0 -200
  184. package/dist/chunk-VISA6CI3.js.map +0 -1
  185. package/dist/chunk-WMTCUOQL.js +0 -474
  186. package/dist/chunk-WMTCUOQL.js.map +0 -1
  187. package/dist/chunk-WRTOVNN4.js +0 -4728
  188. package/dist/chunk-WRTOVNN4.js.map +0 -1
  189. package/dist/chunk-WSTRQZYQ.js +0 -5576
  190. package/dist/chunk-WSTRQZYQ.js.map +0 -1
  191. package/dist/chunk-XBG2W2VW.js +0 -6434
  192. package/dist/chunk-XBG2W2VW.js.map +0 -1
  193. package/dist/chunk-YEJR7IXO.js +0 -68
  194. package/dist/chunk-YEJR7IXO.js.map +0 -1
  195. package/dist/chunk-YJZA2BIK.js +0 -1338
  196. package/dist/chunk-YJZA2BIK.js.map +0 -1
  197. package/dist/completion-gate-BMy5LGoP.d.ts +0 -256
  198. package/dist/conversation.js.map +0 -1
  199. package/dist/coordination-BZZSVYpZ.d.ts +0 -2570
  200. package/dist/environment-provider.js.map +0 -1
  201. package/dist/improvement-adapter-HAZz-7vK.d.ts +0 -203
  202. package/dist/knowledge.js.map +0 -1
  203. package/dist/local-harness-BDNcl6jI.d.ts +0 -175
  204. package/dist/loop-runner-bin-68aoM9-7.d.ts +0 -199
  205. package/dist/loop-runner-bin.js.map +0 -1
  206. package/dist/loops.js.map +0 -1
  207. package/dist/openai-tools-fnj6SRVg.d.ts +0 -46
  208. package/dist/protected-model-port-B4t-OQjL.d.ts +0 -271
  209. package/dist/redact-BuFjxBUJ.d.ts +0 -481
  210. package/dist/sanitize-DEbPNtyI.d.ts +0 -328
  211. package/dist/structural-rollout-DEh6CEsa.d.ts +0 -446
  212. package/dist/supervise-4_48wwvy.d.ts +0 -379
  213. package/dist/types-BCoemcXU.d.ts +0 -802
  214. package/dist/types-BwoZWq-i.d.ts +0 -510
  215. package/dist/types-Cbp72qyu.d.ts +0 -491
  216. package/dist/types-CmYCMbFT.d.ts +0 -203
  217. package/dist/types-CvNwMzQt.d.ts +0 -957
  218. package/dist/worktree-fanout-DxhAWr5Z.d.ts +0 -999
@@ -0,0 +1,433 @@
1
+ //#region src/profiles/researcher.ts
2
+ const DEFAULT_HARNESS = "opencode/zai-coding-plan/glm-5.1";
3
+ const DEFAULT_CITATION_DENSITY_MIN = .7;
4
+ /** Build a source-grounded researcher profile with output parsing and validation. @experimental */
5
+ function researcherProfile(options = {}) {
6
+ const harness = options.harness ?? DEFAULT_HARNESS;
7
+ const name = options.name ?? `researcher-${harness}`;
8
+ const systemPrompt = options.systemPrompt ?? DEFAULT_RESEARCHER_SYSTEM_PROMPT;
9
+ const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN;
10
+ const profile = {
11
+ name,
12
+ description: "Source-grounded research agent. Propose-don't-apply.",
13
+ prompt: { systemPrompt },
14
+ model: options.model ? { default: options.model } : void 0,
15
+ tools: {
16
+ web_search: true,
17
+ fs: true,
18
+ shell: true
19
+ },
20
+ metadata: {
21
+ backendType: harness,
22
+ role: "researcher"
23
+ }
24
+ };
25
+ return {
26
+ profile,
27
+ taskToPrompt: formatResearcherPrompt,
28
+ output: { parse: parseResearcherEvents },
29
+ validator: options.task ? createResearcherValidator(options.task, { citationDensityMin }) : createResearcherValidator({
30
+ question: "",
31
+ knowledgeNamespace: ""
32
+ }, {
33
+ citationDensityMin,
34
+ namespaceCheck: false
35
+ }),
36
+ agentRunSpec: {
37
+ name,
38
+ profile,
39
+ taskToPrompt: formatResearcherPrompt
40
+ }
41
+ };
42
+ }
43
+ /**
44
+ * Build a fanout topology over multiple harnesses. The kernel round-robins
45
+ * `agentRuns` across the N parallel iterations and the `FanoutVote` driver
46
+ * picks the highest-scoring valid output.
47
+ *
48
+ * @experimental
49
+ */
50
+ function multiHarnessResearcherFanout(options = {}) {
51
+ const harnesses = options.harnesses && options.harnesses.length > 0 ? options.harnesses : [
52
+ "opencode/zai-coding-plan/glm-5.1",
53
+ "claude-code",
54
+ "codex"
55
+ ];
56
+ const models = options.models ?? [];
57
+ const agentRuns = harnesses.map((harness, i) => {
58
+ const { agentRunSpec } = researcherProfile({
59
+ harness,
60
+ model: models[i]
61
+ });
62
+ return agentRunSpec;
63
+ });
64
+ const { output, validator } = researcherProfile({
65
+ citationDensityMin: options.citationDensityMin,
66
+ task: options.task
67
+ });
68
+ return {
69
+ agentRuns,
70
+ output,
71
+ validator,
72
+ driver: {
73
+ name: "researcher-fanout",
74
+ async plan(task, history) {
75
+ return history.length === 0 ? Array.from({ length: harnesses.length }, () => task) : [];
76
+ },
77
+ decide() {
78
+ return "done";
79
+ },
80
+ describePlan() {
81
+ return { kind: "fanout" };
82
+ }
83
+ }
84
+ };
85
+ }
86
+ /**
87
+ * Build a validator that closes over a specific `ResearchTask`'s constraints.
88
+ *
89
+ * Checks in order:
90
+ * 1. Items must be non-empty.
91
+ * 2. Every item carries `evidence.length >= 1`.
92
+ * 3. Every item + proposedWrite is scoped to `task.knowledgeNamespace`
93
+ * (hard-fail on any namespace mismatch — defence in depth for the
94
+ * multi-tenant invariant).
95
+ * 4. Citation density (citations with quote / items) >= floor.
96
+ *
97
+ * Aggregate score:
98
+ * 0.4 · citation_density
99
+ * + 0.2 · source_diversity (distinct sources / max(items, 1))
100
+ * + 0.2 · recency_match (mean fraction within `recencyWindow`)
101
+ * + 0.2 · (1 − gaps/maxGaps), maxGaps = max(items, 1)
102
+ *
103
+ * @experimental
104
+ */
105
+ function createResearcherValidator(task, config = {}) {
106
+ const citationDensityMin = config.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN;
107
+ const namespaceCheck = config.namespaceCheck ?? true;
108
+ return { async validate(output) {
109
+ const notes = [];
110
+ const scores = {};
111
+ let pass = true;
112
+ if (!Array.isArray(output.items) || output.items.length === 0) {
113
+ pass = false;
114
+ notes.push("no items");
115
+ scores.items = 0;
116
+ } else scores.items = 1;
117
+ const missingEvidence = (output.items ?? []).filter((item) => !Array.isArray(item.evidence) || item.evidence.length === 0);
118
+ if (missingEvidence.length > 0) {
119
+ pass = false;
120
+ notes.push(`${missingEvidence.length} item(s) without evidence`);
121
+ scores.provenance = 0;
122
+ } else scores.provenance = 1;
123
+ if (namespaceCheck) {
124
+ const foreignItems = (output.items ?? []).filter((item) => item.namespace !== task.knowledgeNamespace);
125
+ const foreignWrites = (output.proposedWrites ?? []).filter((write) => write.namespace !== task.knowledgeNamespace);
126
+ if (foreignItems.length > 0 || foreignWrites.length > 0) {
127
+ pass = false;
128
+ notes.push(`namespace violation: ${foreignItems.length} item(s) + ${foreignWrites.length} write(s) outside ${task.knowledgeNamespace}`);
129
+ scores.namespace = 0;
130
+ } else scores.namespace = 1;
131
+ }
132
+ const itemCount = Math.max(output.items?.length ?? 0, 1);
133
+ const citationsWithQuote = (output.citations ?? []).filter((citation) => typeof citation.quote === "string" && citation.quote.length > 0).length;
134
+ const citationDensity = Math.min(1, citationsWithQuote / itemCount);
135
+ if (citationDensity < citationDensityMin) {
136
+ pass = false;
137
+ notes.push(`citation density ${citationDensity.toFixed(2)} below floor ${citationDensityMin.toFixed(2)}`);
138
+ }
139
+ scores.citation_density = citationDensity;
140
+ const sourceSet = /* @__PURE__ */ new Set();
141
+ for (const item of output.items ?? []) for (const evidence of item.evidence ?? []) if (evidence.source) sourceSet.add(evidence.source);
142
+ scores.source_diversity = Math.min(1, sourceSet.size / itemCount);
143
+ scores.recency_match = recencyMatchScore(output.items ?? [], task.recencyWindow);
144
+ const maxGaps = itemCount;
145
+ const gapCount = output.gaps?.length ?? 0;
146
+ scores.gap_coverage = Math.max(0, 1 - gapCount / maxGaps);
147
+ const score = .4 * scores.citation_density + .2 * scores.source_diversity + .2 * scores.recency_match + .2 * scores.gap_coverage;
148
+ const verdict = {
149
+ valid: pass,
150
+ score: Number.isFinite(score) ? score : 0,
151
+ scores
152
+ };
153
+ if (notes.length > 0) verdict.notes = notes.join("; ");
154
+ return verdict;
155
+ } };
156
+ }
157
+ function recencyMatchScore(items, window) {
158
+ if (!window || window.since === void 0 && window.until === void 0) return 1;
159
+ if (items.length === 0) return 0;
160
+ const sinceMs = window.since?.getTime() ?? Number.NEGATIVE_INFINITY;
161
+ const untilMs = window.until?.getTime() ?? Number.POSITIVE_INFINITY;
162
+ let hits = 0;
163
+ let total = 0;
164
+ for (const item of items) for (const evidence of item.evidence ?? []) {
165
+ if (typeof evidence.capturedAt !== "number") continue;
166
+ total += 1;
167
+ if (evidence.capturedAt >= sinceMs && evidence.capturedAt <= untilMs) hits += 1;
168
+ }
169
+ return total === 0 ? 0 : hits / total;
170
+ }
171
+ const DEFAULT_RESEARCHER_SYSTEM_PROMPT = [
172
+ "You are a research agent. Your job is to answer a research question with",
173
+ "source-grounded knowledge items that the caller will choose whether to",
174
+ "persist to a multi-tenant knowledge base.",
175
+ "",
176
+ "Hard rules:",
177
+ " 1. Every item you emit MUST carry the task's knowledgeNamespace exactly.",
178
+ " Never write to a different namespace.",
179
+ " 2. Every item MUST carry at least one evidence entry with a source.",
180
+ " A quote + url is strongly preferred; capturedAt is unix ms.",
181
+ " 3. You propose writes — you do NOT apply them. The caller decides.",
182
+ " 4. Self-report confidence honestly in [0, 1]. Do not inflate.",
183
+ " 5. List what you could not answer in `gaps`. Better to admit a gap",
184
+ " than fabricate.",
185
+ "",
186
+ "When you finish, emit a single final structured message of the shape:",
187
+ " ```json",
188
+ " { \"items\": [{ \"id\": \"...\", \"namespace\": \"...\", \"claim\": \"...\",",
189
+ " \"evidence\": [{ \"source\": \"...\", \"quote\": \"...\",",
190
+ " \"url\": \"...\", \"capturedAt\": 0 }],",
191
+ " \"confidence\": 0.0,",
192
+ " \"authoredBy\": { \"kind\": \"agent\", \"id\": \"...\" } }],",
193
+ " \"citations\": [{ \"url\": \"...\", \"quote\": \"...\", \"confidence\": 0.0 }],",
194
+ " \"proposedWrites\": [{ \"kind\": \"insert\", \"namespace\": \"...\",",
195
+ " \"item\": { /* same shape as items[] */ } }],",
196
+ " \"gaps\": [\"...\"],",
197
+ " \"notes\": \"free-form commentary\" }",
198
+ " ```"
199
+ ].join("\n");
200
+ function formatResearcherPrompt(task) {
201
+ const sources = task.sources?.length ? task.sources.join(", ") : "(no preference)";
202
+ const window = formatRecencyWindow(task.recencyWindow);
203
+ return [
204
+ `Question: ${task.question}`,
205
+ `Knowledge namespace (DO NOT cross): ${task.knowledgeNamespace}`,
206
+ `Scope: ${task.scope ?? "(unspecified)"}`,
207
+ `Preferred sources: ${sources}`,
208
+ `Recency window: ${window}`,
209
+ `Max items: ${task.maxItems ?? "(no cap)"}`,
210
+ `Per-item minimum confidence: ${task.minConfidence ?? "(no floor)"}`,
211
+ "",
212
+ "Produce knowledge items with provenance + citations + proposed writes.",
213
+ "List gaps for anything you could not answer. Emit the final JSON",
214
+ "result block exactly as instructed."
215
+ ].join("\n");
216
+ }
217
+ function formatRecencyWindow(window) {
218
+ if (!window) return "(none)";
219
+ return `${window.since ? window.since.toISOString() : "-∞"} .. ${window.until ? window.until.toISOString() : "now"}`;
220
+ }
221
+ /**
222
+ * Walk the event stream and return the last structured `research.result`
223
+ * payload. Falls back to scanning text deltas for a fenced JSON block.
224
+ */
225
+ function parseResearcherEvents(events) {
226
+ for (let i = events.length - 1; i >= 0; i -= 1) {
227
+ const event = events[i];
228
+ if (!event) continue;
229
+ const type = String(event.type ?? "");
230
+ const data = isRecord(event.data) ? event.data : {};
231
+ if (type === "result" || type === "final" || type === "research.result") {
232
+ const direct = coerceResearchOutput(data.result ?? data.output ?? data);
233
+ const finalText = pickString(data.finalText);
234
+ const fenced = finalText ? extractFencedJson(finalText) : void 0;
235
+ const fromFinalText = fenced ? coerceResearchOutput(fenced) : void 0;
236
+ if (direct && !isEmptyOutput(direct)) return direct;
237
+ if (fromFinalText) return fromFinalText;
238
+ if (direct) return direct;
239
+ }
240
+ }
241
+ for (let i = events.length - 1; i >= 0; i -= 1) {
242
+ const event = events[i];
243
+ if (!event) continue;
244
+ const data = isRecord(event.data) ? event.data : {};
245
+ const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.finalText);
246
+ if (!text) continue;
247
+ const fenced = extractFencedJson(text);
248
+ if (!fenced) continue;
249
+ const coerced = coerceResearchOutput(fenced);
250
+ if (coerced) return coerced;
251
+ }
252
+ return {
253
+ items: [],
254
+ citations: [],
255
+ proposedWrites: []
256
+ };
257
+ }
258
+ function isRecord(value) {
259
+ return value !== null && typeof value === "object" && !Array.isArray(value);
260
+ }
261
+ /** A coerced output that carries no items, citations, or proposed writes. */
262
+ function isEmptyOutput(o) {
263
+ return o.items.length === 0 && o.citations.length === 0 && o.proposedWrites.length === 0;
264
+ }
265
+ function pickString(value) {
266
+ return typeof value === "string" && value.length > 0 ? value : void 0;
267
+ }
268
+ function extractFencedJson(text) {
269
+ const match = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
270
+ if (!match) return void 0;
271
+ const body = (match[1] ?? "").trim();
272
+ if (!body) return void 0;
273
+ try {
274
+ return JSON.parse(body);
275
+ } catch {
276
+ return;
277
+ }
278
+ }
279
+ function coerceResearchOutput(value) {
280
+ if (!isRecord(value)) return void 0;
281
+ const items = coerceItems(value.items);
282
+ const citations = coerceCitations(value.citations);
283
+ const proposedWrites = coerceProposedWrites(value.proposedWrites);
284
+ if (items === void 0 && citations === void 0 && proposedWrites === void 0) return;
285
+ const output = {
286
+ items: items ?? [],
287
+ citations: citations ?? [],
288
+ proposedWrites: proposedWrites ?? []
289
+ };
290
+ if (Array.isArray(value.gaps)) output.gaps = value.gaps.filter((entry) => typeof entry === "string");
291
+ const notes = pickString(value.notes);
292
+ if (notes) output.notes = notes;
293
+ const known = /* @__PURE__ */ new Set([
294
+ "items",
295
+ "citations",
296
+ "proposedWrites",
297
+ "gaps",
298
+ "notes"
299
+ ]);
300
+ const extras = {};
301
+ let extrasCount = 0;
302
+ for (const [key, val] of Object.entries(value)) {
303
+ if (known.has(key)) continue;
304
+ extras[key] = val;
305
+ extrasCount += 1;
306
+ }
307
+ if (extrasCount > 0) output.raw = extras;
308
+ return output;
309
+ }
310
+ function coerceItems(value) {
311
+ if (!Array.isArray(value)) return void 0;
312
+ const out = [];
313
+ for (const entry of value) {
314
+ if (!isRecord(entry)) continue;
315
+ const id = pickString(entry.id);
316
+ const namespace = pickString(entry.namespace);
317
+ const claim = pickString(entry.claim);
318
+ const evidence = coerceEvidence(entry.evidence);
319
+ const confidence = toFiniteNumber(entry.confidence);
320
+ const authoredBy = coerceAuthoredBy(entry.authoredBy);
321
+ if (!id || !namespace || !claim || !authoredBy) continue;
322
+ const item = {
323
+ id,
324
+ namespace,
325
+ claim,
326
+ evidence,
327
+ confidence: clamp01(confidence),
328
+ authoredBy
329
+ };
330
+ if (Array.isArray(entry.supersedes)) item.supersedes = entry.supersedes.filter((s) => typeof s === "string");
331
+ const retractedAt = toFiniteNumber(entry.retractedAt);
332
+ if (retractedAt > 0) item.retractedAt = retractedAt;
333
+ out.push(item);
334
+ }
335
+ return out;
336
+ }
337
+ function coerceEvidence(value) {
338
+ if (!Array.isArray(value)) return [];
339
+ const out = [];
340
+ for (const entry of value) {
341
+ if (!isRecord(entry)) continue;
342
+ const source = pickString(entry.source);
343
+ if (!source) continue;
344
+ const item = {
345
+ source,
346
+ capturedAt: toFiniteNumber(entry.capturedAt)
347
+ };
348
+ const quote = pickString(entry.quote);
349
+ if (quote) item.quote = quote;
350
+ const url = pickString(entry.url);
351
+ if (url) item.url = url;
352
+ out.push(item);
353
+ }
354
+ return out;
355
+ }
356
+ function coerceAuthoredBy(value) {
357
+ if (!isRecord(value)) return void 0;
358
+ const kind = value.kind === "human" || value.kind === "agent" ? value.kind : void 0;
359
+ const id = pickString(value.id);
360
+ if (!kind || !id) return void 0;
361
+ return {
362
+ kind,
363
+ id
364
+ };
365
+ }
366
+ function coerceCitations(value) {
367
+ if (!Array.isArray(value)) return void 0;
368
+ const out = [];
369
+ for (const entry of value) {
370
+ if (!isRecord(entry)) continue;
371
+ const url = pickString(entry.url);
372
+ const quote = pickString(entry.quote);
373
+ if (!url || !quote) continue;
374
+ out.push({
375
+ url,
376
+ quote,
377
+ confidence: clamp01(toFiniteNumber(entry.confidence))
378
+ });
379
+ }
380
+ return out;
381
+ }
382
+ function coerceProposedWrites(value) {
383
+ if (!Array.isArray(value)) return void 0;
384
+ const out = [];
385
+ for (const entry of value) {
386
+ if (!isRecord(entry)) continue;
387
+ const namespace = pickString(entry.namespace);
388
+ if (!namespace) continue;
389
+ if (entry.kind === "insert") {
390
+ const item = coerceItems([entry.item])?.[0];
391
+ if (!item) continue;
392
+ out.push({
393
+ kind: "insert",
394
+ namespace,
395
+ item
396
+ });
397
+ } else if (entry.kind === "supersede") {
398
+ const previousId = pickString(entry.previousId);
399
+ const item = coerceItems([entry.item])?.[0];
400
+ if (!previousId || !item) continue;
401
+ out.push({
402
+ kind: "supersede",
403
+ namespace,
404
+ previousId,
405
+ item
406
+ });
407
+ } else if (entry.kind === "retract") {
408
+ const itemId = pickString(entry.itemId);
409
+ const reason = pickString(entry.reason);
410
+ if (!itemId || !reason) continue;
411
+ out.push({
412
+ kind: "retract",
413
+ namespace,
414
+ itemId,
415
+ reason
416
+ });
417
+ }
418
+ }
419
+ return out;
420
+ }
421
+ function toFiniteNumber(value) {
422
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
423
+ }
424
+ function clamp01(value) {
425
+ if (!Number.isFinite(value)) return 0;
426
+ if (value < 0) return 0;
427
+ if (value > 1) return 1;
428
+ return value;
429
+ }
430
+ //#endregion
431
+ export { multiHarnessResearcherFanout as n, researcherProfile as r, createResearcherValidator as t };
432
+
433
+ //# sourceMappingURL=researcher-CoVqNhfI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"researcher-CoVqNhfI.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. `harness` selects the\n * sandbox-SDK backend. For heterogeneous fanout, use\n * `multiHarnessResearcherFanout`.\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 } from '@tangle-network/agent-interface'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\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 /** Sandbox-SDK backend.type. Default `'opencode/zai-coding-plan/glm-5.1'`. */\n harness?: string\n /** Default model id passed in `AgentProfile.model.default`. */\n model?: string\n /** Custom system prompt replacement. Default = built-in researcher preset. */\n systemPrompt?: string\n /** Stable name for `AgentRunSpec.name`. Default = `researcher-${harness}`. */\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_HARNESS = 'opencode/zai-coding-plan/glm-5.1'\nconst DEFAULT_CITATION_DENSITY_MIN = 0.7\n\n/** Build a source-grounded researcher profile with output parsing and validation. @experimental */\nexport function researcherProfile(\n options: ResearcherProfileOptions & { task?: ResearchTask } = {},\n): {\n profile: AgentProfile\n taskToPrompt: (task: ResearchTask) => string\n output: OutputAdapter<ResearchOutput>\n validator: Validator<ResearchOutput>\n agentRunSpec: AgentRunSpec<ResearchTask>\n} {\n const harness = options.harness ?? DEFAULT_HARNESS\n const name = options.name ?? `researcher-${harness}`\n const systemPrompt = options.systemPrompt ?? DEFAULT_RESEARCHER_SYSTEM_PROMPT\n const citationDensityMin = options.citationDensityMin ?? DEFAULT_CITATION_DENSITY_MIN\n const profile: AgentProfile = {\n name,\n description: \"Source-grounded research agent. Propose-don't-apply.\",\n prompt: { systemPrompt },\n model: options.model ? { default: options.model } : undefined,\n tools: { web_search: true, fs: true, shell: true },\n metadata: { backendType: harness, 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 /** Backend.type identifiers, one per parallel agent. */\n harnesses?: string[]\n /** Optional per-harness model override. Indexed parallel to `harnesses`. */\n models?: (string | undefined)[]\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 const harnesses =\n options.harnesses && options.harnesses.length > 0\n ? options.harnesses\n : ['opencode/zai-coding-plan/glm-5.1', 'claude-code', 'codex']\n const models = options.models ?? []\n const agentRuns = harnesses.map((harness, i) => {\n const { agentRunSpec } = researcherProfile({ harness, model: models[i] })\n return agentRunSpec\n })\n const { output, validator } = researcherProfile({\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: harnesses.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\nconst DEFAULT_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":";AA2HA,MAAM,kBAAkB;AACxB,MAAM,+BAA+B;;AAGrC,SAAgB,kBACd,UAA8D,CAAC,GAO/D;CACA,MAAM,UAAU,QAAQ,WAAW;CACnC,MAAM,OAAO,QAAQ,QAAQ,cAAc;CAC3C,MAAM,eAAe,QAAQ,gBAAgB;CAC7C,MAAM,qBAAqB,QAAQ,sBAAsB;CACzD,MAAM,UAAwB;EAC5B;EACA,aAAa;EACb,QAAQ,EAAE,aAAa;EACvB,OAAO,QAAQ,QAAQ,EAAE,SAAS,QAAQ,MAAM,IAAI,KAAA;EACpD,OAAO;GAAE,YAAY;GAAM,IAAI;GAAM,OAAO;EAAK;EACjD,UAAU;GAAE,aAAa;GAAS,MAAM;EAAa;CACvD;CAaA,OAAO;EAAE;EAAS,cAAc;EAAwB,QAAA,EAZR,OAAO,sBAYM;EAAG,WAXnB,QAAQ,OACjD,0BAA0B,QAAQ,MAAM,EAAE,mBAAmB,CAAC,IAC9D,0BACE;GAAE,UAAU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