@tangle-network/agent-runtime 0.37.0 → 0.38.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.
@@ -0,0 +1,261 @@
1
+ // src/analyst-loop/run-analyst-loop.ts
2
+ import { diffFindings } from "@tangle-network/agent-eval";
3
+ async function runAnalystLoop(opts) {
4
+ const log = opts.log ?? defaultLog;
5
+ const strategy = opts.priorFindingsStrategy ?? "per-kind";
6
+ const emit = makeEmitter(opts.onEvent);
7
+ const startedAt = Date.now();
8
+ const baselineRunId = resolveBaselineRunId(opts);
9
+ const priorAll = baselineRunId ? opts.findingsStore?.loadRun(baselineRunId) ?? [] : [];
10
+ log("baseline resolved", { baselineRunId, prior_findings: priorAll.length });
11
+ await emit({
12
+ type: "baseline-resolved",
13
+ runId: opts.runId,
14
+ baselineRunId,
15
+ priorFindingCount: priorAll.length
16
+ });
17
+ const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list());
18
+ const analystResult = await runRegistry(opts, priorFindings, emit);
19
+ log("analyst run complete", {
20
+ findings: analystResult.findings.length,
21
+ cost_usd: analystResult.total_cost_usd,
22
+ per_analyst: analystResult.per_analyst.map((s) => ({
23
+ id: s.analyst_id,
24
+ status: s.status,
25
+ n: s.findings_count
26
+ }))
27
+ });
28
+ if (opts.findingsStore && analystResult.findings.length > 0) {
29
+ await opts.findingsStore.append(opts.runId, analystResult.findings);
30
+ await emit({
31
+ type: "findings-persisted",
32
+ runId: opts.runId,
33
+ count: analystResult.findings.length
34
+ });
35
+ }
36
+ let diff = null;
37
+ if (baselineRunId && analystResult.findings.length > 0) {
38
+ diff = diffFindings(
39
+ priorAll.map((f) => ({ ...f })),
40
+ analystResult.findings.map((f) => ({ ...f, run_id: opts.runId }))
41
+ );
42
+ log("diff vs baseline", {
43
+ appeared: diff.appeared.length,
44
+ disappeared: diff.disappeared.length,
45
+ persisted: diff.persisted.length,
46
+ changed: diff.changed.length
47
+ });
48
+ await emit({
49
+ type: "diff-computed",
50
+ runId: opts.runId,
51
+ baselineRunId,
52
+ appeared: diff.appeared.length,
53
+ disappeared: diff.disappeared.length,
54
+ persisted: diff.persisted.length,
55
+ changed: diff.changed.length
56
+ });
57
+ }
58
+ let knowledge = null;
59
+ if (opts.knowledgeAdapter) {
60
+ knowledge = await runKnowledgeAdapter(opts, analystResult.findings, log, emit);
61
+ }
62
+ let improvement = null;
63
+ if (opts.improvementAdapter) {
64
+ improvement = await runImprovementAdapter(opts, analystResult.findings, log, emit);
65
+ }
66
+ await emit({
67
+ type: "loop-completed",
68
+ runId: opts.runId,
69
+ durationMs: Date.now() - startedAt
70
+ });
71
+ return {
72
+ runId: opts.runId,
73
+ baselineRunId,
74
+ analystResult,
75
+ diff,
76
+ knowledge,
77
+ improvement
78
+ };
79
+ }
80
+ function makeEmitter(onEvent) {
81
+ if (!onEvent) return async () => {
82
+ };
83
+ return async (event) => {
84
+ await onEvent(event);
85
+ };
86
+ }
87
+ async function runRegistry(opts, priorFindings, emit) {
88
+ const reg = opts.registry;
89
+ if (typeof reg.runStream === "function" && opts.onEvent) {
90
+ let final = null;
91
+ for await (const ev of reg.runStream(opts.runId, opts.inputs, { priorFindings })) {
92
+ await emit({ type: "analyst", runId: opts.runId, event: ev });
93
+ if (ev.type === "run-completed") final = ev.result;
94
+ }
95
+ if (!final) {
96
+ throw new Error("runAnalystLoop: registry.runStream ended without run-completed event");
97
+ }
98
+ return final;
99
+ }
100
+ return opts.registry.run(opts.runId, opts.inputs, { priorFindings });
101
+ }
102
+ function resolveBaselineRunId(opts) {
103
+ if (opts.baselineRunId === null) return null;
104
+ if (typeof opts.baselineRunId === "string") return opts.baselineRunId;
105
+ if (!opts.findingsStore) return null;
106
+ const all = opts.findingsStore.loadAll();
107
+ let last = null;
108
+ for (const row of all) {
109
+ if (row.run_id === opts.runId) continue;
110
+ last = row.run_id;
111
+ }
112
+ return last;
113
+ }
114
+ function buildPriorFindingsInput(prior, strategy, registry) {
115
+ if (strategy === "none" || prior.length === 0) return void 0;
116
+ const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest);
117
+ if (strategy === "wildcard") {
118
+ return { "*": stripped };
119
+ }
120
+ void registry;
121
+ return stripped;
122
+ }
123
+ async function runKnowledgeAdapter(opts, findings, log, emit) {
124
+ const adapter = opts.knowledgeAdapter;
125
+ const batch = await adapter.proposeFromFindings(findings);
126
+ log("knowledge.proposeFromFindings", {
127
+ proposals: batch.proposals.length,
128
+ skipped: batch.skipped,
129
+ errors: batch.errors.length
130
+ });
131
+ await emit({
132
+ type: "knowledge-proposed",
133
+ runId: opts.runId,
134
+ proposalCount: batch.proposals.length,
135
+ skipped: batch.skipped,
136
+ errors: batch.errors.length
137
+ });
138
+ const auto = opts.autoApply?.knowledge ?? false;
139
+ const threshold = opts.autoApply?.knowledgeConfidenceThreshold ?? 0.85;
140
+ if (!auto || !adapter.apply) {
141
+ await emit({
142
+ type: "knowledge-applied",
143
+ runId: opts.runId,
144
+ writtenCount: 0,
145
+ withheldForReview: batch.proposals.length
146
+ });
147
+ return {
148
+ proposals: batch.proposals,
149
+ applied: [],
150
+ skipped: batch.skipped,
151
+ errors: batch.errors,
152
+ withheld_for_review: batch.proposals.length
153
+ };
154
+ }
155
+ const findingsById = new Map(findings.map((f) => [f.finding_id, f]));
156
+ const safe = [];
157
+ let withheld = 0;
158
+ for (const p of batch.proposals) {
159
+ const src = p.sourceFindingId ? findingsById.get(p.sourceFindingId) : void 0;
160
+ if (!src) {
161
+ withheld += 1;
162
+ continue;
163
+ }
164
+ if (src.confidence < threshold) {
165
+ withheld += 1;
166
+ continue;
167
+ }
168
+ safe.push(p);
169
+ }
170
+ const result = await adapter.apply(safe);
171
+ log("knowledge.apply", {
172
+ applied: result.written.length,
173
+ withheld_for_review: withheld,
174
+ warnings: result.warnings.length
175
+ });
176
+ await emit({
177
+ type: "knowledge-applied",
178
+ runId: opts.runId,
179
+ writtenCount: result.written.length,
180
+ withheldForReview: withheld
181
+ });
182
+ return {
183
+ proposals: batch.proposals,
184
+ applied: result.written,
185
+ skipped: batch.skipped,
186
+ errors: batch.errors,
187
+ withheld_for_review: withheld
188
+ };
189
+ }
190
+ async function runImprovementAdapter(opts, findings, log, emit) {
191
+ const adapter = opts.improvementAdapter;
192
+ const batch = await adapter.proposeFromFindings(findings);
193
+ log("improvement.proposeFromFindings", {
194
+ edits: batch.edits.length,
195
+ skipped: batch.skipped,
196
+ errors: batch.errors.length
197
+ });
198
+ await emit({
199
+ type: "improvement-proposed",
200
+ runId: opts.runId,
201
+ editCount: batch.edits.length,
202
+ skipped: batch.skipped,
203
+ errors: batch.errors.length
204
+ });
205
+ const auto = opts.autoApply?.improvement ?? false;
206
+ const threshold = opts.autoApply?.improvementConfidenceThreshold ?? 0.9;
207
+ if (!auto || !adapter.apply) {
208
+ await emit({
209
+ type: "improvement-applied",
210
+ runId: opts.runId,
211
+ appliedCount: 0,
212
+ withheldForReview: batch.edits.length
213
+ });
214
+ return {
215
+ edits: batch.edits,
216
+ applied: [],
217
+ skipped: batch.skipped,
218
+ errors: batch.errors,
219
+ withheld_for_review: batch.edits.length
220
+ };
221
+ }
222
+ const findingsById = new Map(findings.map((f) => [f.finding_id, f]));
223
+ const safe = [];
224
+ let withheld = 0;
225
+ for (const e of batch.edits) {
226
+ const src = e.sourceFindingId ? findingsById.get(e.sourceFindingId) : void 0;
227
+ if (!src || src.confidence < threshold) {
228
+ withheld += 1;
229
+ continue;
230
+ }
231
+ safe.push(e);
232
+ }
233
+ const result = await adapter.apply(safe);
234
+ log("improvement.apply", {
235
+ applied: result.applied.length,
236
+ withheld_for_review: withheld,
237
+ warnings: result.warnings.length
238
+ });
239
+ await emit({
240
+ type: "improvement-applied",
241
+ runId: opts.runId,
242
+ appliedCount: result.applied.length,
243
+ withheldForReview: withheld
244
+ });
245
+ return {
246
+ edits: batch.edits,
247
+ applied: result.applied,
248
+ skipped: batch.skipped,
249
+ errors: batch.errors,
250
+ withheld_for_review: withheld
251
+ };
252
+ }
253
+ function defaultLog(msg, fields) {
254
+ if (fields) console.log(`[analyst-loop] ${msg}`, fields);
255
+ else console.log(`[analyst-loop] ${msg}`);
256
+ }
257
+
258
+ export {
259
+ runAnalystLoop
260
+ };
261
+ //# sourceMappingURL=chunk-XBUG326M.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/analyst-loop/run-analyst-loop.ts"],"sourcesContent":["/**\n * `runAnalystLoop` — the one call agent apps reach for to close the\n * recursive-self-improvement loop.\n *\n * 1. Load baseline findings (last run, or the slice the caller specifies)\n * 2. Run the analyst registry with priorFindings injected\n * 3. Persist the new run's findings to the ledger\n * 4. Diff the new run against the baseline\n * 5. Hand the findings to the knowledge adapter → proposals (and\n * optionally apply them) → wiki edits\n * 6. Hand the findings to the improvement adapter → prompt / tool /\n * scaffolding edits (review-only by default)\n * 7. Return a single report the consumer renders / persists / acts on.\n *\n * Adapters are optional: the loop works as a \"run + diff + report\"\n * primitive when no adapters are wired; it closes end-to-end when\n * both adapters are wired.\n */\n\nimport type { AnalystFinding, AnalystRunResult, FindingsDiff } from '@tangle-network/agent-eval'\nimport { diffFindings } from '@tangle-network/agent-eval'\n\nimport type {\n AnalystLoopEvent,\n AnalystRegistryStreamingLike,\n ImprovementReport,\n KnowledgeReport,\n RunAnalystLoopOpts,\n RunAnalystLoopResult,\n} from './types'\n\nexport async function runAnalystLoop<TProposal = unknown, TEdit = unknown>(\n opts: RunAnalystLoopOpts,\n): Promise<RunAnalystLoopResult<TProposal, TEdit>> {\n const log = opts.log ?? defaultLog\n const strategy = opts.priorFindingsStrategy ?? 'per-kind'\n const emit = makeEmitter(opts.onEvent)\n const startedAt = Date.now()\n\n // 1. Resolve baseline + load prior findings.\n const baselineRunId = resolveBaselineRunId(opts)\n const priorAll: ReadonlyArray<AnalystFinding & { run_id: string }> = baselineRunId\n ? (opts.findingsStore?.loadRun(baselineRunId) ?? [])\n : []\n log('baseline resolved', { baselineRunId, prior_findings: priorAll.length })\n await emit({\n type: 'baseline-resolved',\n runId: opts.runId,\n baselineRunId,\n priorFindingCount: priorAll.length,\n })\n\n // 2. Run the registry. Strategy controls how analysts see priors.\n // When the registry exposes runStream, forward each event verbatim\n // so subscribers see per-analyst progress in real time.\n const priorFindings = buildPriorFindingsInput(priorAll, strategy, opts.registry.list())\n const analystResult = await runRegistry(opts, priorFindings, emit)\n log('analyst run complete', {\n findings: analystResult.findings.length,\n cost_usd: analystResult.total_cost_usd,\n per_analyst: analystResult.per_analyst.map((s) => ({\n id: s.analyst_id,\n status: s.status,\n n: s.findings_count,\n })),\n })\n\n // 3. Persist the new run before any side-effecting adapter runs so\n // the ledger is the source of truth even if an adapter throws.\n if (opts.findingsStore && analystResult.findings.length > 0) {\n await opts.findingsStore.append(opts.runId, analystResult.findings)\n await emit({\n type: 'findings-persisted',\n runId: opts.runId,\n count: analystResult.findings.length,\n })\n }\n\n // 4. Diff vs baseline.\n let diff: FindingsDiff | null = null\n if (baselineRunId && analystResult.findings.length > 0) {\n diff = diffFindings(\n priorAll.map((f) => ({ ...f })),\n analystResult.findings.map((f) => ({ ...f, run_id: opts.runId })),\n )\n log('diff vs baseline', {\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n await emit({\n type: 'diff-computed',\n runId: opts.runId,\n baselineRunId,\n appeared: diff.appeared.length,\n disappeared: diff.disappeared.length,\n persisted: diff.persisted.length,\n changed: diff.changed.length,\n })\n }\n\n // 5. Knowledge adapter — proposals + optional auto-apply.\n let knowledge: KnowledgeReport<TProposal> | null = null\n if (opts.knowledgeAdapter) {\n knowledge = await runKnowledgeAdapter(opts, analystResult.findings, log, emit)\n }\n\n // 6. Improvement adapter — prompt / tool / scaffolding edits.\n let improvement: ImprovementReport<TEdit> | null = null\n if (opts.improvementAdapter) {\n improvement = await runImprovementAdapter(opts, analystResult.findings, log, emit)\n }\n\n await emit({\n type: 'loop-completed',\n runId: opts.runId,\n durationMs: Date.now() - startedAt,\n })\n\n return {\n runId: opts.runId,\n baselineRunId,\n analystResult,\n diff,\n knowledge,\n improvement,\n }\n}\n\ntype Emitter = (event: AnalystLoopEvent) => Promise<void>\n\nfunction makeEmitter(onEvent: RunAnalystLoopOpts['onEvent']): Emitter {\n if (!onEvent) return async () => {}\n return async (event) => {\n await onEvent(event)\n }\n}\n\nasync function runRegistry(\n opts: RunAnalystLoopOpts,\n priorFindings: ReturnType<typeof buildPriorFindingsInput>,\n emit: Emitter,\n): Promise<AnalystRunResult> {\n const reg = opts.registry as AnalystRegistryStreamingLike\n if (typeof reg.runStream === 'function' && opts.onEvent) {\n let final: AnalystRunResult | null = null\n for await (const ev of reg.runStream(opts.runId, opts.inputs, { priorFindings })) {\n await emit({ type: 'analyst', runId: opts.runId, event: ev })\n if (ev.type === 'run-completed') final = ev.result\n }\n if (!final) {\n throw new Error('runAnalystLoop: registry.runStream ended without run-completed event')\n }\n return final\n }\n return opts.registry.run(opts.runId, opts.inputs, { priorFindings })\n}\n\nfunction resolveBaselineRunId(opts: RunAnalystLoopOpts): string | null {\n if (opts.baselineRunId === null) return null\n if (typeof opts.baselineRunId === 'string') return opts.baselineRunId\n if (!opts.findingsStore) return null\n const all = opts.findingsStore.loadAll()\n let last: string | null = null\n for (const row of all) {\n if (row.run_id === opts.runId) continue\n last = row.run_id\n }\n return last\n}\n\nfunction buildPriorFindingsInput(\n prior: ReadonlyArray<AnalystFinding & { run_id: string }>,\n strategy: 'per-kind' | 'wildcard' | 'none',\n registry: ReadonlyArray<{ id: string }>,\n): ReadonlyArray<AnalystFinding> | Record<string, ReadonlyArray<AnalystFinding>> | undefined {\n if (strategy === 'none' || prior.length === 0) return undefined\n const stripped = prior.map(({ run_id: _run_id, ...rest }) => rest as AnalystFinding)\n if (strategy === 'wildcard') {\n return { '*': stripped }\n }\n void registry\n return stripped\n}\n\nasync function runKnowledgeAdapter<TProposal>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<KnowledgeReport<TProposal>> {\n const adapter = opts.knowledgeAdapter!\n const batch = await adapter.proposeFromFindings(findings)\n log('knowledge.proposeFromFindings', {\n proposals: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'knowledge-proposed',\n runId: opts.runId,\n proposalCount: batch.proposals.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n const auto = opts.autoApply?.knowledge ?? false\n const threshold = opts.autoApply?.knowledgeConfidenceThreshold ?? 0.85\n\n if (!auto || !adapter.apply) {\n await emit({\n type: 'knowledge-applied',\n runId: opts.runId,\n writtenCount: 0,\n withheldForReview: batch.proposals.length,\n })\n return {\n proposals: batch.proposals as TProposal[],\n applied: [],\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: batch.proposals.length,\n }\n }\n\n const findingsById = new Map(findings.map((f) => [f.finding_id, f]))\n const safe: TProposal[] = []\n let withheld = 0\n for (const p of batch.proposals as Array<TProposal & { sourceFindingId?: string }>) {\n const src = p.sourceFindingId ? findingsById.get(p.sourceFindingId) : undefined\n if (!src) {\n withheld += 1\n continue\n }\n if (src.confidence < threshold) {\n withheld += 1\n continue\n }\n safe.push(p)\n }\n const result = await adapter.apply(safe)\n log('knowledge.apply', {\n applied: result.written.length,\n withheld_for_review: withheld,\n warnings: result.warnings.length,\n })\n await emit({\n type: 'knowledge-applied',\n runId: opts.runId,\n writtenCount: result.written.length,\n withheldForReview: withheld,\n })\n return {\n proposals: batch.proposals as TProposal[],\n applied: result.written,\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: withheld,\n }\n}\n\nasync function runImprovementAdapter<TEdit>(\n opts: RunAnalystLoopOpts,\n findings: ReadonlyArray<AnalystFinding>,\n log: NonNullable<RunAnalystLoopOpts['log']>,\n emit: Emitter,\n): Promise<ImprovementReport<TEdit>> {\n const adapter = opts.improvementAdapter!\n const batch = await adapter.proposeFromFindings(findings)\n log('improvement.proposeFromFindings', {\n edits: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n await emit({\n type: 'improvement-proposed',\n runId: opts.runId,\n editCount: batch.edits.length,\n skipped: batch.skipped,\n errors: batch.errors.length,\n })\n\n const auto = opts.autoApply?.improvement ?? false\n const threshold = opts.autoApply?.improvementConfidenceThreshold ?? 0.9\n\n if (!auto || !adapter.apply) {\n await emit({\n type: 'improvement-applied',\n runId: opts.runId,\n appliedCount: 0,\n withheldForReview: batch.edits.length,\n })\n return {\n edits: batch.edits as TEdit[],\n applied: [],\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: batch.edits.length,\n }\n }\n\n const findingsById = new Map(findings.map((f) => [f.finding_id, f]))\n const safe: TEdit[] = []\n let withheld = 0\n for (const e of batch.edits as Array<TEdit & { sourceFindingId?: string }>) {\n const src = e.sourceFindingId ? findingsById.get(e.sourceFindingId) : undefined\n if (!src || src.confidence < threshold) {\n withheld += 1\n continue\n }\n safe.push(e)\n }\n const result = await adapter.apply(safe)\n log('improvement.apply', {\n applied: result.applied.length,\n withheld_for_review: withheld,\n warnings: result.warnings.length,\n })\n await emit({\n type: 'improvement-applied',\n runId: opts.runId,\n appliedCount: result.applied.length,\n withheldForReview: withheld,\n })\n return {\n edits: batch.edits as TEdit[],\n applied: result.applied,\n skipped: batch.skipped,\n errors: batch.errors,\n withheld_for_review: withheld,\n }\n}\n\nfunction defaultLog(msg: string, fields?: Record<string, unknown>): void {\n if (fields) console.log(`[analyst-loop] ${msg}`, fields)\n else console.log(`[analyst-loop] ${msg}`)\n}\n"],"mappings":";AAoBA,SAAS,oBAAoB;AAW7B,eAAsB,eACpB,MACiD;AACjD,QAAM,MAAM,KAAK,OAAO;AACxB,QAAM,WAAW,KAAK,yBAAyB;AAC/C,QAAM,OAAO,YAAY,KAAK,OAAO;AACrC,QAAM,YAAY,KAAK,IAAI;AAG3B,QAAM,gBAAgB,qBAAqB,IAAI;AAC/C,QAAM,WAA+D,gBAChE,KA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AAA,IAChB,SAAS,MAAM;AAAA,IACf,QAAQ,MAAM;AAAA,IACd,qBAAqB;AAAA,EACvB;AACF;AAEA,SAAS,WAAW,KAAa,QAAwC;AACvE,MAAI,OAAQ,SAAQ,IAAI,kBAAkB,GAAG,IAAI,MAAM;AAAA,MAClD,SAAQ,IAAI,kBAAkB,GAAG,EAAE;AAC1C;","names":[]}
@@ -16,6 +16,62 @@ import {
16
16
  DELEGATION_STATUS_TOOL_NAME
17
17
  } from "./chunk-V6GURW4W.js";
18
18
 
19
+ // src/mcp/kb-gate.ts
20
+ var norm = (s) => s.toLowerCase().replace(/\s+/g, " ").trim();
21
+ function valueAppears(value, passageNorm) {
22
+ if (passageNorm.includes(norm(String(value)))) return true;
23
+ if (typeof value !== "number" || !Number.isFinite(value)) return false;
24
+ const forms = [value.toLocaleString("en-US")];
25
+ if (Math.abs(value) >= 1e9) forms.push(`${trimZero(value / 1e9)} billion`);
26
+ if (Math.abs(value) >= 1e6) forms.push(`${trimZero(value / 1e6)} million`);
27
+ return forms.some((f) => passageNorm.includes(norm(f)));
28
+ }
29
+ function trimZero(n) {
30
+ return Number.isInteger(n) ? String(n) : String(Number(n.toFixed(2)));
31
+ }
32
+ function builtinJudges(minPassageChars, selfArtifactKinds) {
33
+ const kinds = selfArtifactKinds.map((k) => k.toLowerCase());
34
+ return [
35
+ {
36
+ name: "passage-non-empty",
37
+ judge: (c) => c.verbatimPassage.trim().length >= minPassageChars ? { accept: true } : { accept: false, reason: `passage shorter than ${minPassageChars} chars` }
38
+ },
39
+ {
40
+ // THE anti-hallucination floor — the passage must literally be in the source.
41
+ name: "passage-present",
42
+ judge: (c) => norm(c.sourceText).includes(norm(c.verbatimPassage)) ? { accept: true } : { accept: false, reason: "verbatim passage not found in source (unbacked fact)" }
43
+ },
44
+ {
45
+ name: "value-in-passage",
46
+ judge: (c) => c.value === void 0 || valueAppears(c.value, norm(c.verbatimPassage)) ? { accept: true } : { accept: false, reason: `value ${JSON.stringify(c.value)} not present in passage` }
47
+ },
48
+ {
49
+ name: "no-circular-citation",
50
+ judge: (c) => {
51
+ if (!c.citation || kinds.length === 0) return { accept: true };
52
+ const cite = c.citation.toLowerCase();
53
+ const hit = kinds.find((k) => cite.includes(k));
54
+ return hit ? { accept: false, reason: `circular citation to self-generated artifact "${hit}"` } : { accept: true };
55
+ }
56
+ }
57
+ ];
58
+ }
59
+ function createKbGate(options = {}) {
60
+ const judges = [
61
+ ...builtinJudges(options.minPassageChars ?? 12, options.selfArtifactKinds ?? []),
62
+ ...options.judges ?? []
63
+ ];
64
+ return async (candidate) => {
65
+ for (const j of judges) {
66
+ const verdict = await j.judge(candidate);
67
+ if (!verdict.accept) {
68
+ return { accepted: false, vetoedBy: j.name, reason: verdict.reason };
69
+ }
70
+ }
71
+ return { accepted: true };
72
+ };
73
+ }
74
+
19
75
  // src/mcp/openai-tools.ts
20
76
  function buildTool(name, description, parameters) {
21
77
  return {
@@ -389,6 +445,7 @@ async function exportEvalRuns(events, config) {
389
445
  }
390
446
 
391
447
  export {
448
+ createKbGate,
392
449
  mcpToolsForRuntimeMcp,
393
450
  mcpToolsForRuntimeMcpSubset,
394
451
  createOtelExporter,
@@ -397,4 +454,4 @@ export {
397
454
  INTELLIGENCE_WIRE_VERSION,
398
455
  exportEvalRuns
399
456
  };
400
- //# sourceMappingURL=chunk-T3GJBKHA.js.map
457
+ //# sourceMappingURL=chunk-Z523NPJK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/kb-gate.ts","../src/mcp/openai-tools.ts","../src/otel-export.ts"],"sourcesContent":["/**\n * @experimental\n *\n * `createKbGate` — the valid-only knowledge-base growth gate, distilled from\n * physim's KB-research subsystem. A research-in-a-loop delegate (or any KB\n * writer) runs candidate facts through this before persisting, so the KB grows\n * with ONLY grounded facts — hallucinated, unsourced, or laundered claims are\n * vetoed at the gate.\n *\n * Fail-closed by construction: every judge must `accept`; the FIRST veto wins\n * and the fact is rejected. The non-negotiable floor (always on, can't be\n * disabled) is the **passage-present guard** — a fact's `verbatimPassage` MUST\n * literally appear in its `sourceText`. That single check kills the dominant\n * failure mode (a confident claim decoupled from any real source).\n *\n * Pure + dependency-free: it operates on fact candidates, not on a store, so it\n * composes with `@tangle-network/agent-knowledge` or any persistence layer\n * without importing it. The remediation policy (correct-on-veto vs\n * escalate-as-unverified) is the caller's — this returns the verdict; it never\n * drops a fact silently.\n */\n\n/** @experimental A fact proposed for the KB, with its grounding. */\nexport interface FactCandidate {\n /** The atomic claim text. */\n claim: string\n /** Optional extracted value (number or string) the claim asserts. */\n value?: string | number\n /** Verbatim span lifted from the source that backs the claim. */\n verbatimPassage: string\n /** The raw source text the passage must be grounded in. */\n sourceText: string\n /** Where the fact claims to come from — checked for circular/self citations. */\n citation?: string\n}\n\n/** @experimental */\nexport interface FactJudgeVerdict {\n accept: boolean\n reason?: string\n}\n\n/** @experimental A pluggable fact validator. Throw is NOT allowed — return a\n * verdict; a thrown judge is a programmer error, not a veto. */\nexport interface FactJudge {\n name: string\n judge(candidate: FactCandidate): FactJudgeVerdict | Promise<FactJudgeVerdict>\n}\n\n/** @experimental */\nexport interface KbGateResult {\n accepted: boolean\n /** Name of the judge that vetoed; undefined when accepted. */\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface CreateKbGateOptions {\n /** Extra judges appended after the built-in floor (e.g. an LLM judge). */\n judges?: FactJudge[]\n /** Minimum verbatim-passage length. Default 12 — kills empty/stub passages. */\n minPassageChars?: number\n /**\n * Citation tokens that denote a SELF-generated artifact (e.g. `'spec'`,\n * `'cad_params'`, `'requirements'`). A citation naming one is circular\n * (laundering) — the fact cites a derived artifact, not a real source.\n * Default `[]` (no circular check unless the consumer declares its kinds).\n */\n selfArtifactKinds?: string[]\n}\n\nconst norm = (s: string): string => s.toLowerCase().replace(/\\s+/g, ' ').trim()\n\n/** Does `value` appear in the (normalized) passage — literally, comma-grouped,\n * or in billion/million shorthand (the forms a source actually writes). */\nfunction valueAppears(value: string | number, passageNorm: string): boolean {\n if (passageNorm.includes(norm(String(value)))) return true\n if (typeof value !== 'number' || !Number.isFinite(value)) return false\n const forms = [value.toLocaleString('en-US')]\n if (Math.abs(value) >= 1e9) forms.push(`${trimZero(value / 1e9)} billion`)\n if (Math.abs(value) >= 1e6) forms.push(`${trimZero(value / 1e6)} million`)\n return forms.some((f) => passageNorm.includes(norm(f)))\n}\n\nfunction trimZero(n: number): string {\n return Number.isInteger(n) ? String(n) : String(Number(n.toFixed(2)))\n}\n\n/** The always-on floor judges. Order matters: cheapest / most-fundamental first. */\nfunction builtinJudges(minPassageChars: number, selfArtifactKinds: string[]): FactJudge[] {\n const kinds = selfArtifactKinds.map((k) => k.toLowerCase())\n return [\n {\n name: 'passage-non-empty',\n judge: (c) =>\n c.verbatimPassage.trim().length >= minPassageChars\n ? { accept: true }\n : { accept: false, reason: `passage shorter than ${minPassageChars} chars` },\n },\n {\n // THE anti-hallucination floor — the passage must literally be in the source.\n name: 'passage-present',\n judge: (c) =>\n norm(c.sourceText).includes(norm(c.verbatimPassage))\n ? { accept: true }\n : { accept: false, reason: 'verbatim passage not found in source (unbacked fact)' },\n },\n {\n name: 'value-in-passage',\n judge: (c) =>\n c.value === undefined || valueAppears(c.value, norm(c.verbatimPassage))\n ? { accept: true }\n : { accept: false, reason: `value ${JSON.stringify(c.value)} not present in passage` },\n },\n {\n name: 'no-circular-citation',\n judge: (c) => {\n if (!c.citation || kinds.length === 0) return { accept: true }\n const cite = c.citation.toLowerCase()\n const hit = kinds.find((k) => cite.includes(k))\n return hit\n ? { accept: false, reason: `circular citation to self-generated artifact \"${hit}\"` }\n : { accept: true }\n },\n },\n ]\n}\n\n/**\n * @experimental\n *\n * Build a fail-closed KB gate. The returned function runs the built-in floor\n * (passage-non-empty → passage-present → value-in-passage → no-circular-citation)\n * then any consumer judges, returning on the first veto.\n */\nexport function createKbGate(\n options: CreateKbGateOptions = {},\n): (candidate: FactCandidate) => Promise<KbGateResult> {\n const judges = [\n ...builtinJudges(options.minPassageChars ?? 12, options.selfArtifactKinds ?? []),\n ...(options.judges ?? []),\n ]\n return async (candidate) => {\n for (const j of judges) {\n const verdict = await j.judge(candidate)\n if (!verdict.accept) {\n return { accepted: false, vetoedBy: j.name, reason: verdict.reason }\n }\n }\n return { accepted: true }\n }\n}\n","/**\n * @experimental\n *\n * OpenAI Chat Completions `tools[]` projection of the 5 agent-runtime MCP\n * delegation tools.\n *\n * Use when configuring `createOpenAICompatibleBackend({ tools: ... })` so the\n * model can call `delegate_code`, `delegate_research`, `delegate_feedback`,\n * `delegation_status`, and `delegation_history` through the OpenAI-compat\n * transport (tcloud, OpenRouter, OpenAI direct, cli-bridge). The runtime\n * surfaces tool calls as `tool_call` stream events — execution is the\n * caller's responsibility (typically the parent sandbox runtime's MCP\n * mount).\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_CODE_DESCRIPTION,\n DELEGATE_CODE_INPUT_SCHEMA,\n DELEGATE_CODE_TOOL_NAME,\n} from './tools/delegate-code'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATE_RESEARCH_DESCRIPTION,\n DELEGATE_RESEARCH_INPUT_SCHEMA,\n DELEGATE_RESEARCH_TOOL_NAME,\n} from './tools/delegate-research'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compat backend JSON-serializes the body so a shallow copy\n // into a plain object is sufficient — and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n * @experimental\n *\n * Returns the 5 delegation tools projected into OpenAI Chat Completions\n * `tools[]` shape. The order is stable: `delegate_code`,\n * `delegate_research`, `delegate_feedback`, `delegation_status`,\n * `delegation_history`.\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_CODE_TOOL_NAME,\n DELEGATE_CODE_DESCRIPTION,\n DELEGATE_CODE_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATE_RESEARCH_TOOL_NAME,\n DELEGATE_RESEARCH_DESCRIPTION,\n DELEGATE_RESEARCH_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n * @experimental\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n","/**\n * OTEL span exporter — streams LoopTraceEvents to an OTLP/HTTP collector.\n *\n * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env\n * when no explicit config is given. Keeps the runtime dep-free from\n * @opentelemetry/sdk-trace-base — minimal OTLP/JSON serializer.\n *\n * The exporter accepts both raw OtelSpan objects and LoopTraceEvents\n * (which get converted to OTLP spans automatically).\n */\n\nexport interface OtelExportConfig {\n /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */\n endpoint?: string\n /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */\n headers?: Record<string, string>\n /** Batch size before flush. Default 64. */\n batchSize?: number\n /** Flush interval ms. Default 5000. */\n flushIntervalMs?: number\n /** Resource attributes stamped on every export. */\n resourceAttributes?: Record<string, string | number | boolean>\n /** Service name. Default 'agent-runtime'. */\n serviceName?: string\n}\n\nexport interface OtelExporter {\n /** Export a span. */\n exportSpan(span: OtelSpan): void\n /** Force flush pending spans. */\n flush(): Promise<void>\n /** Shutdown cleanly. */\n shutdown(): Promise<void>\n}\n\nexport interface OtelSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind?: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes?: OtelAttribute[]\n status?: { code: number; message?: string }\n}\n\nexport interface OtelAttribute {\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n}\n\ninterface OtlpResourceSpans {\n resource: { attributes: OtelAttribute[] }\n scopeSpans: Array<{ scope: { name: string; version: string }; spans: OtelSpan[] }>\n}\n\ninterface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\n\nconst SCOPE = { name: '@tangle-network/agent-runtime', version: '0.33.0' }\n\n/**\n * Current (non-deprecated) OpenTelemetry GenAI semantic-convention keys.\n * Registry: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/\n * NB: `gen_ai.system` / `gen_ai.usage.prompt_tokens` / `completion_tokens` are\n * DEPRECATED — do not emit them. We use `provider.name` + `input/output_tokens`.\n */\nconst GEN_AI = {\n operation: 'gen_ai.operation.name',\n agentName: 'gen_ai.agent.name',\n conversationId: 'gen_ai.conversation.id',\n inputTokens: 'gen_ai.usage.input_tokens',\n outputTokens: 'gen_ai.usage.output_tokens',\n} as const\n\n/**\n * Create an OTEL exporter. Returns undefined when no endpoint is configured.\n */\nexport function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined {\n const resolvedEndpoint =\n config?.endpoint ??\n (typeof process !== 'undefined' ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : undefined)\n if (!resolvedEndpoint) return undefined\n const endpoint: string = resolvedEndpoint\n\n const headers = config?.headers ?? parseHeadersFromEnv()\n const batchSize = config?.batchSize ?? 64\n const flushIntervalMs = config?.flushIntervalMs ?? 5000\n const serviceName = config?.serviceName ?? 'agent-runtime'\n const resourceAttrs = config?.resourceAttributes ?? {}\n\n const pending: OtelSpan[] = []\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n const exporter: OtelExporter = {\n exportSpan(span: OtelSpan): void {\n if (stopped) return\n pending.push(span)\n if (pending.length >= batchSize) {\n void doFlush()\n }\n },\n\n async flush(): Promise<void> {\n await doFlush()\n },\n\n async shutdown(): Promise<void> {\n stopped = true\n if (timer !== undefined) {\n clearInterval(timer)\n timer = undefined\n }\n await doFlush()\n },\n }\n\n timer = setInterval(() => {\n if (pending.length > 0) void doFlush()\n }, flushIntervalMs)\n if (typeof timer === 'object' && 'unref' in timer) {\n ;(timer as NodeJS.Timeout).unref()\n }\n\n async function doFlush(): Promise<void> {\n if (pending.length === 0) return\n const batch = pending.splice(0)\n const body: OtlpExport = {\n resourceSpans: [\n {\n resource: {\n attributes: toAttributes({\n 'service.name': serviceName,\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: SCOPE, spans: batch }],\n },\n ],\n }\n const url = `${endpoint.replace(/\\/+$/, '')}/v1/traces`\n try {\n await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...headers },\n body: JSON.stringify(body),\n })\n } catch {\n // Best-effort — telemetry export must not crash the runtime.\n }\n }\n\n return exporter\n}\n\n/**\n * Convert a LoopTraceEvent into an OtelSpan for export.\n */\nexport function loopEventToOtelSpan(\n event: {\n kind: string\n runId: string\n timestamp: number\n payload: object\n },\n traceId: string,\n parentSpanId?: string,\n): OtelSpan {\n const spanId = generateSpanId()\n const attrs: Record<string, string | number | boolean> = {\n 'loop.event_kind': event.kind,\n 'loop.run_id': event.runId,\n }\n for (const [k, v] of Object.entries(event.payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n attrs[`loop.${k}`] = v\n }\n }\n const ts = msToNs(event.timestamp)\n return {\n traceId: padTraceId(traceId),\n spanId,\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name: event.kind,\n kind: 1,\n startTimeUnixNano: ts,\n endTimeUnixNano: ts,\n attributes: toAttributes(attrs),\n status: { code: 1 },\n }\n}\n\n/**\n * Build a nested, real-duration OTLP span tree for ONE loop run from its full\n * ordered `LoopTraceEvent` stream. Unlike `loopEventToOtelSpan` (one flat,\n * zero-duration span per event), this reconstructs the topology hierarchy a\n * GenAI trace viewer renders natively:\n *\n * loop (invoke_workflow)\n * └─ loop.round[k] (invoke_workflow) ← tangle.loop.move.{kind,width,rationale}\n * ├─ loop.iteration[i] (invoke_agent) ← gen_ai.agent.name + usage + verdict + placement\n * └─ …\n *\n * Attributes follow the current GenAI semconv (`gen_ai.*`) where they apply and\n * a namespaced `tangle.loop.*` / `tangle.cost.usd` extension for topology /\n * verdict / placement / cost (not yet standardized). Pure: feed it a buffered\n * per-runId event array (e.g. flushed on `loop.ended`) and export the result.\n */\nexport function buildLoopOtelSpans(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n traceId: string,\n rootParentSpanId?: string,\n): OtelSpan[] {\n if (events.length === 0) return []\n const tid = padTraceId(traceId)\n const out: OtelSpan[] = []\n const num = (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) ? v : undefined\n const str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined\n const rec = (v: unknown): Record<string, unknown> =>\n v && typeof v === 'object' ? (v as Record<string, unknown>) : {}\n\n const started = events.find((e) => e.kind === 'loop.started')\n const ended = events.find((e) => e.kind === 'loop.ended')\n const runId = events[0]?.runId ?? ''\n const rootStart = started?.timestamp ?? events[0]!.timestamp\n const rootEnd = ended?.timestamp ?? events[events.length - 1]!.timestamp\n const rootId = generateSpanId()\n\n const make = (\n spanId: string,\n parentSpanId: string | undefined,\n name: string,\n startMs: number,\n endMs: number,\n attrs: Record<string, string | number | boolean>,\n statusCode = 1,\n ): OtelSpan => ({\n traceId: tid,\n spanId,\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name,\n kind: 1,\n startTimeUnixNano: msToNs(startMs),\n endTimeUnixNano: msToNs(endMs),\n attributes: toAttributes(attrs),\n status: { code: statusCode },\n })\n\n // root\n const sp = rec(started?.payload)\n const rootAttrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n [GEN_AI.conversationId]: runId,\n 'tangle.loop.driver': str(sp.driver) ?? 'driver',\n }\n if (Array.isArray(sp.agentRunNames) && sp.agentRunNames.length > 0) {\n rootAttrs['tangle.loop.agents'] = sp.agentRunNames.map(String).join(',')\n }\n if (ended) {\n const ep = rec(ended.payload)\n const win = num(ep.winnerIterationIndex)\n if (win !== undefined) rootAttrs['tangle.loop.winner.iteration_index'] = win\n const cost = num(ep.totalCostUsd)\n if (cost !== undefined) rootAttrs['tangle.cost.usd'] = cost\n const dur = num(ep.durationMs)\n if (dur !== undefined) rootAttrs['tangle.loop.duration_ms'] = dur\n const iters = num(ep.iterations)\n if (iters !== undefined) rootAttrs['tangle.loop.iterations'] = iters\n }\n out.push(make(rootId, rootParentSpanId, 'loop', rootStart, rootEnd, rootAttrs))\n\n // rounds + iterations\n const iterStartTs = new Map<number, number>()\n const placementByIdx = new Map<number, Record<string, string>>()\n let currentRoundId: string | undefined\n let pendingRound:\n | { id: string; start: number; attrs: Record<string, string | number | boolean> }\n | undefined\n const flushRound = (endMs: number) => {\n if (!pendingRound) return\n out.push(\n make(pendingRound.id, rootId, 'loop.round', pendingRound.start, endMs, pendingRound.attrs),\n )\n pendingRound = undefined\n }\n\n for (const e of events) {\n const p = rec(e.payload)\n switch (e.kind) {\n case 'loop.plan': {\n flushRound(e.timestamp)\n const id = generateSpanId()\n const roundIdx = num(p.roundIndex) ?? 0\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n 'tangle.loop.round.index': roundIdx,\n 'tangle.loop.move.kind': str(p.moveKind) ?? 'unknown',\n 'tangle.loop.move.round': roundIdx,\n 'tangle.loop.move.width': num(p.plannedCount) ?? 0,\n }\n const r = str(p.rationale)\n if (r) attrs['tangle.loop.move.rationale'] = r\n const parent = num(p.parentIndex)\n if (parent !== undefined) attrs['tangle.loop.move.parent_index'] = parent\n if (Array.isArray(p.childIndices) && p.childIndices.length > 0) {\n attrs['tangle.loop.move.child_indices'] = p.childIndices.map(String).join(',')\n }\n pendingRound = { id, start: e.timestamp, attrs }\n currentRoundId = id\n break\n }\n case 'loop.iteration.started': {\n const idx = num(p.iterationIndex)\n if (idx !== undefined) iterStartTs.set(idx, e.timestamp)\n break\n }\n case 'loop.iteration.dispatch': {\n const idx = num(p.iterationIndex)\n if (idx === undefined) break\n const place: Record<string, string> = {}\n const kind = str(p.placement)\n if (kind) place['tangle.loop.placement.kind'] = kind\n const sid = str(p.sandboxId)\n if (sid) place['tangle.sandbox.id'] = sid\n const fid = str(p.fleetId)\n if (fid) place['tangle.fleet.id'] = fid\n const mid = str(p.machineId)\n if (mid) place['tangle.machine.id'] = mid\n placementByIdx.set(idx, place)\n break\n }\n case 'loop.iteration.ended': {\n const idx = num(p.iterationIndex) ?? 0\n const start = iterStartTs.get(idx) ?? e.timestamp\n const err = str(p.error)\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_agent',\n 'tangle.loop.iteration.index': idx,\n }\n const agent = str(p.agentRunName)\n if (agent) attrs[GEN_AI.agentName] = agent\n const tu = rec(p.tokenUsage)\n const inTok = num(tu.input)\n if (inTok !== undefined) attrs[GEN_AI.inputTokens] = inTok\n const outTok = num(tu.output)\n if (outTok !== undefined) attrs[GEN_AI.outputTokens] = outTok\n const cost = num(p.costUsd)\n if (cost !== undefined) attrs['tangle.cost.usd'] = cost\n const verdict = rec(p.verdict)\n if (typeof verdict.valid === 'boolean') attrs['tangle.loop.verdict.valid'] = verdict.valid\n const score = num(verdict.score)\n if (score !== undefined) attrs['tangle.loop.verdict.score'] = score\n if (err) attrs['tangle.loop.error'] = err\n const gid = num(p.groupId)\n if (gid !== undefined) attrs['tangle.loop.iteration.group_id'] = gid\n const par = num(p.parentIndex)\n if (par !== undefined) attrs['tangle.loop.iteration.parent_index'] = par\n const dur = num(p.durationMs)\n if (dur !== undefined) attrs['tangle.loop.iteration.duration_ms'] = dur\n const preview = str(p.outputPreview)\n if (preview) attrs['tangle.loop.iteration.output_preview'] = preview\n Object.assign(attrs, placementByIdx.get(idx) ?? {})\n out.push(\n make(\n generateSpanId(),\n currentRoundId ?? rootId,\n 'loop.iteration',\n start,\n e.timestamp,\n attrs,\n err ? 2 : 1,\n ),\n )\n break\n }\n case 'loop.decision': {\n if (pendingRound) {\n const dec = str(p.decision)\n if (dec) pendingRound.attrs['tangle.loop.decision'] = dec\n flushRound(e.timestamp)\n }\n currentRoundId = undefined\n break\n }\n }\n }\n flushRound(rootEnd)\n return out\n}\n\nfunction parseHeadersFromEnv(): Record<string, string> {\n if (typeof process === 'undefined') return {}\n const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(',')) {\n const eq = pair.indexOf('=')\n if (eq < 0) continue\n const key = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n if (key) out[key] = value\n }\n return out\n}\n\nfunction toAttributes(record: Record<string, string | number | boolean>): OtelAttribute[] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\nfunction msToNs(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n\nfunction padSpanId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 16).padEnd(16, '0')\n}\n\nfunction padTraceId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 32).padEnd(32, '0')\n}\n\nfunction generateSpanId(): string {\n const bytes = new Uint8Array(8)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── Eval-run ingest (self-improvement provenance) ───────────────────────────\n//\n// Tangle Intelligence has a first-class, non-trace record for self-improvement\n// runs: POST /v1/ingest/eval-runs (\"Mode D\"). Each generation carries a\n// `surfaceHash` (the proposed-change identity) + arbitrary `surface` provenance;\n// a later `gate-decided` event re-emits the same `runId` (idempotent upsert) with\n// a real `gateDecision` + `holdoutLift`, so proposal→verdict is one diffable\n// record. This is how a consumer's RSI loop records WHAT it changed, WHY, from\n// which evidence — the audit trail behind agentic self-improvement.\n\n/** Wire version the eval-runs ingest enforces (X-Tangle-Wire-Version + body). */\nexport const INTELLIGENCE_WIRE_VERSION = '2026-05-26.v1'\n\nexport interface EvalRunGeneration {\n /** 0-based ordinal of this generation within the run (required by ingest). */\n index: number\n /** Identity of the proposed surface change (content-addressed hash). */\n surfaceHash: string\n /** Arbitrary provenance for this generation (rationale, evidence, source). */\n surface?: unknown\n /** Per-scenario results; empty until the generation is measured. */\n cells?: unknown[]\n /** Mean composite score (0 when unmeasured — pair with labels.measured). */\n compositeMean: number\n costUsd: number\n durationMs: number\n}\n\nexport interface EvalRunEvent {\n runId: string\n runDir: string\n /** ISO timestamp. */\n timestamp: string\n status:\n | 'started'\n | 'baseline-complete'\n | 'generation-complete'\n | 'gate-decided'\n | 'finished'\n | 'errored'\n labels?: Record<string, string>\n baseline?: EvalRunGeneration\n generations?: EvalRunGeneration[]\n gateDecision?: 'ship' | 'hold' | 'need_more_work' | 'model_ceiling' | 'arch_ceiling'\n holdoutLift?: number\n totalCostUsd: number\n totalDurationMs: number\n errorMessage?: string\n}\n\nexport interface EvalRunsExportConfig {\n /** Bearer key — tenant is resolved server-side from it. Reads TANGLE_API_KEY. */\n apiKey?: string\n /** Intelligence base. Reads INTELLIGENCE_BASE env, else prod. */\n base?: string\n /** Idempotency-Key header (e.g. the runId) — safe retries + upsert. */\n idempotencyKey?: string\n}\n\nexport interface EvalRunsExportResult {\n ok: boolean\n status: number\n accepted: number\n rejected: Array<{ index: number; reason: string }>\n}\n\nconst DEFAULT_INTELLIGENCE_BASE = 'https://intelligence.tangle.tools'\n\n/**\n * Ship self-improvement eval-run events to Tangle Intelligence. Unlike the\n * best-effort span exporter, this RESOLVES with the ingest verdict (accepted /\n * rejected per event) so a consumer's loop can assert its provenance landed.\n * Throws only on a missing key or network failure.\n */\nexport async function exportEvalRuns(\n events: EvalRunEvent[],\n config?: EvalRunsExportConfig,\n): Promise<EvalRunsExportResult> {\n if (events.length === 0) return { ok: true, status: 0, accepted: 0, rejected: [] }\n const apiKey =\n config?.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n if (!apiKey)\n throw new Error('exportEvalRuns: apiKey required (pass config.apiKey or set TANGLE_API_KEY)')\n const base =\n config?.base ??\n (typeof process !== 'undefined' ? process.env.INTELLIGENCE_BASE : undefined) ??\n DEFAULT_INTELLIGENCE_BASE\n const url = `${base.replace(/\\/+$/, '')}/v1/ingest/eval-runs`\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${apiKey}`,\n 'X-Tangle-Wire-Version': INTELLIGENCE_WIRE_VERSION,\n ...(config?.idempotencyKey ? { 'Idempotency-Key': config.idempotencyKey } : {}),\n },\n body: JSON.stringify({ wireVersion: INTELLIGENCE_WIRE_VERSION, events }),\n })\n let parsed: { accepted?: number; rejected?: Array<{ index: number; reason: string }> } = {}\n try {\n parsed = (await res.json()) as typeof parsed\n } catch {\n // non-JSON body (e.g. 5xx HTML) — leave parsed empty\n }\n return {\n ok: res.ok,\n status: res.status,\n accepted: parsed.accepted ?? (res.ok ? events.length : 0),\n rejected: parsed.rejected ?? [],\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwEA,IAAM,OAAO,CAAC,MAAsB,EAAE,YAAY,EAAE,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAI9E,SAAS,aAAa,OAAwB,aAA8B;AAC1E,MAAI,YAAY,SAAS,KAAK,OAAO,KAAK,CAAC,CAAC,EAAG,QAAO;AACtD,MAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAAS,KAAK,EAAG,QAAO;AACjE,QAAM,QAAQ,CAAC,MAAM,eAAe,OAAO,CAAC;AAC5C,MAAI,KAAK,IAAI,KAAK,KAAK,IAAK,OAAM,KAAK,GAAG,SAAS,QAAQ,GAAG,CAAC,UAAU;AACzE,MAAI,KAAK,IAAI,KAAK,KAAK,IAAK,OAAM,KAAK,GAAG,SAAS,QAAQ,GAAG,CAAC,UAAU;AACzE,SAAO,MAAM,KAAK,CAAC,MAAM,YAAY,SAAS,KAAK,CAAC,CAAC,CAAC;AACxD;AAEA,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EACpB,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAC1C,KAAK,EAAE;AACZ;AAaO,IAAM,4BAA4B;AAuDzC,IAAM,4BAA4B;AAQlC,eAAsB,eACpB,QACA,QAC+B;AAC/B,MAAI,OAAO,WAAW,EAAG,QAAO,EAAE,IAAI,MAAM,QAAQ,GAAG,UAAU,GAAG,UAAU,CAAC,EAAE;AACjF,QAAM,SACJ,QAAQ,WAAW,OAAO,YAAY,cAAc,QAAQ,IAAI,iBAAiB;AACnF,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,4EAA4E;AAC9F,QAAM,OACJ,QAAQ,SACP,OAAO,YAAY,cAAc,QAAQ,IAAI,oBAAoB,WAClE;AACF,QAAM,MAAM,GAAG,KAAK,QAAQ,QAAQ,EAAE,CAAC;AACvC,QAAM,MAAM,MAAM,MAAM,KAAK;AAAA,IAC3B,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,MAAM;AAAA,MAC/B,yBAAyB;AAAA,MACzB,GAAI,QAAQ,iBAAiB,EAAE,mBAAmB,OAAO,eAAe,IAAI,CAAC;AAAA,IAC/E;AAAA,IACA,MAAM,KAAK,UAAU,EAAE,aAAa,2BAA2B,OAAO,CAAC;AAAA,EACzE,CAAC;AACD,MAAI,SAAqF,CAAC;AAC1F,MAAI;AACF,aAAU,MAAM,IAAI,KAAK;AAAA,EAC3B,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,QAAQ,IAAI;AAAA,IACZ,UAAU,OAAO,aAAa,IAAI,KAAK,OAAO,SAAS;AAAA,IACvD,UAAU,OAAO,YAAY,CAAC;AAAA,EAChC;AACF;","names":[]}
@@ -0,0 +1,106 @@
1
+ import { I as Iteration, D as Driver } from './types-CmkQl8qE.js';
2
+
3
+ /**
4
+ * @experimental
5
+ *
6
+ * Dynamic driver — the agent authors the loop topology at runtime.
7
+ *
8
+ * Where `refine` and `fanout-vote` encode a fixed shape as a pure function of
9
+ * history, this driver delegates the per-round shape to an injected
10
+ * `TopologyPlanner`. Each round the planner inspects the task + iteration
11
+ * history and emits one `TopologyMove`:
12
+ * - `refine` → one task next round (optionally rewritten from the prior attempt)
13
+ * - `fanout` → N tasks next round (the kernel round-robins `agentRuns`, so a
14
+ * 2-harness fanout dispatches branch 0 to harness A and branch 1 to harness B)
15
+ * - `stop` → terminate; the kernel selects the winner across all iterations
16
+ *
17
+ * The planner is the brain; this driver is the structure. It maps moves onto
18
+ * the kernel's `plan`/`decide` contract, enforces the iteration + fanout caps,
19
+ * and fails loud on a malformed move. The planner is injected exactly like
20
+ * `refine`'s `refineTask` and `fanout-vote`'s `selector` — so a test can drive
21
+ * a deterministic policy through the real kernel, and production can wire it to
22
+ * an LLM via `createSandboxPlanner`.
23
+ *
24
+ * Topology is orthogonal to harness: the planner never names a backend. Which
25
+ * harness runs a branch is decided by the `AgentRunSpec` the kernel round-robins
26
+ * to, so one dynamic driver works across claude-code, codex, opencode, pi —
27
+ * including fanning a single round across several at once.
28
+ */
29
+
30
+ /** Terminal once `decide` returns `'done'` (a kernel terminal decision). */
31
+ type DynamicDecision = 'continue' | 'done';
32
+ /**
33
+ * One topology decision for the next round. `fanout` carries explicit tasks
34
+ * rather than a count so the planner can issue heterogeneous branches (a
35
+ * different sub-task per harness); pass N copies of one task for a homogeneous
36
+ * fanout that relies on `agentRuns` diversity instead.
37
+ *
38
+ * @experimental
39
+ */
40
+ type TopologyMove<Task> = {
41
+ kind: 'refine';
42
+ task: Task;
43
+ rationale?: string;
44
+ } | {
45
+ kind: 'fanout';
46
+ tasks: Task[];
47
+ rationale?: string;
48
+ } | {
49
+ kind: 'stop';
50
+ rationale?: string;
51
+ };
52
+ /** @experimental */
53
+ interface PlannerContext<Task, Output> {
54
+ /** The root task the loop was invoked with — stable across rounds. */
55
+ task: Task;
56
+ /** Every iteration so far, in dispatch order, with outputs + verdicts. */
57
+ history: ReadonlyArray<Iteration<Task, Output>>;
58
+ /** `history.length` — iterations already spent. */
59
+ iterationsSpent: number;
60
+ /** Iterations left before the driver's `maxIterations` cap forces a stop. */
61
+ iterationsRemaining: number;
62
+ }
63
+ /**
64
+ * Chooses the next topology move from the task + history. Sync or async; an
65
+ * async planner is where an LLM call goes (see `createSandboxPlanner`).
66
+ *
67
+ * @experimental
68
+ */
69
+ type TopologyPlanner<Task, Output> = (ctx: PlannerContext<Task, Output>) => TopologyMove<Task> | Promise<TopologyMove<Task>>;
70
+ /** @experimental */
71
+ interface CreateDynamicDriverOptions<Task, Output> {
72
+ /** The agent-authored topology policy. Invoked once per round in `plan`. */
73
+ planner: TopologyPlanner<Task, Output>;
74
+ /**
75
+ * Hard safety cap on total iterations. When reached, the driver stops before
76
+ * consulting the planner. Default 8. Set the kernel's `runLoop`
77
+ * `maxIterations >= ` this so the driver's cap governs and the loop closes on
78
+ * a clean `'done'` rather than a truncated `'continue'`.
79
+ */
80
+ maxIterations?: number;
81
+ /** Max branches a single `fanout` move may dispatch. Default 4. */
82
+ maxFanout?: number;
83
+ /** Stable identifier surfaced in trace events. Default `'dynamic'`. */
84
+ name?: string;
85
+ }
86
+ /** @experimental */
87
+ declare function createDynamicDriver<Task, Output>(options: CreateDynamicDriverOptions<Task, Output>): Driver<Task, Output, DynamicDecision>;
88
+ /**
89
+ * Compact, planner-friendly view of iteration history — what an LLM planner
90
+ * needs to choose the next move without the raw event streams. Output is
91
+ * truncated so a long run's prompt stays bounded.
92
+ *
93
+ * @experimental
94
+ */
95
+ declare function summarizeHistory<Task, Output>(history: ReadonlyArray<Iteration<Task, Output>>, opts?: {
96
+ maxOutputChars?: number;
97
+ }): Array<{
98
+ index: number;
99
+ agentRunName: string;
100
+ valid?: boolean;
101
+ score?: number;
102
+ error?: string;
103
+ output?: string;
104
+ }>;
105
+
106
+ export { type CreateDynamicDriverOptions as C, type DynamicDecision as D, type PlannerContext as P, type TopologyPlanner as T, type TopologyMove as a, createDynamicDriver as c, summarizeHistory as s };
@@ -1,5 +1,5 @@
1
1
  import { FindingSubject, AnalystFinding } from '@tangle-network/agent-eval';
2
- import { I as ImprovementAdapter } from './types-D_MXrmJP.js';
2
+ import { I as ImprovementAdapter } from './types-p8dWBIXL.js';
3
3
 
4
4
  /**
5
5
  * `AgentSurfaces` — declarative map of the mutable file/directory paths