@tangle-network/agent-runtime 0.82.0 → 0.83.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.
- package/README.md +4 -0
- package/dist/agent.d.ts +5 -3
- package/dist/agent.js +7 -7
- package/dist/agent.js.map +1 -1
- package/dist/analyst-loop.d.ts +3 -2
- package/dist/analyst-loop.js +2 -2
- package/dist/{chunk-A7LZR5DT.js → chunk-4WXGK6GV.js} +2 -2
- package/dist/chunk-4WXGK6GV.js.map +1 -0
- package/dist/{chunk-UZ5SODU7.js → chunk-5IBQAPVB.js} +1 -1
- package/dist/chunk-5IBQAPVB.js.map +1 -0
- package/dist/{chunk-5JAUQZQA.js → chunk-7LO5GMAO.js} +1 -1
- package/dist/chunk-7LO5GMAO.js.map +1 -0
- package/dist/{chunk-H7IBHAFT.js → chunk-BZF3KQ6G.js} +1 -1
- package/dist/chunk-BZF3KQ6G.js.map +1 -0
- package/dist/{chunk-WIR4HOOJ.js → chunk-DPEUKJRO.js} +1 -1
- package/dist/chunk-DPEUKJRO.js.map +1 -0
- package/dist/{chunk-DJQFJEOD.js → chunk-J3N6GODQ.js} +2 -2
- package/dist/chunk-J3N6GODQ.js.map +1 -0
- package/dist/{chunk-GRAGM4MC.js → chunk-NURIQBJQ.js} +1 -1
- package/dist/chunk-NURIQBJQ.js.map +1 -0
- package/dist/{chunk-JYURIKPF.js → chunk-QDVLTRCP.js} +4 -4
- package/dist/chunk-QDVLTRCP.js.map +1 -0
- package/dist/{chunk-FNMGYYSS.js → chunk-SGKPNBXE.js} +1 -1
- package/dist/chunk-SGKPNBXE.js.map +1 -0
- package/dist/{chunk-CO2KBPRE.js → chunk-SSA6OERV.js} +6 -6
- package/dist/chunk-SSA6OERV.js.map +1 -0
- package/dist/{chunk-SRGV56W4.js → chunk-UD4BHQMI.js} +2 -2
- package/dist/{chunk-SRGV56W4.js.map → chunk-UD4BHQMI.js.map} +1 -1
- package/dist/{chunk-KSGHI53L.js → chunk-UJ3ONGHR.js} +6 -6
- package/dist/chunk-UJ3ONGHR.js.map +1 -0
- package/dist/{chunk-LWGVVP2C.js → chunk-VNOOH22O.js} +2 -2
- package/dist/chunk-VNOOH22O.js.map +1 -0
- package/dist/{chunk-NBV35BR6.js → chunk-YEJR7IXO.js} +1 -1
- package/dist/chunk-YEJR7IXO.js.map +1 -0
- package/dist/{chunk-C2FZ6GR6.js → chunk-YPA5MLVE.js} +2 -2
- package/dist/chunk-YPA5MLVE.js.map +1 -0
- package/dist/{coordination-BI9tpcmF.d.ts → coordination-CuDLO8wj.d.ts} +53 -32
- package/dist/environment-provider.d.ts +2 -2
- package/dist/environment-provider.js +1 -1
- package/dist/{improvement-adapter-CioiEE2z.d.ts → improvement-adapter-CDR8QNVM.d.ts} +3 -0
- package/dist/index.d.ts +163 -49
- package/dist/index.js +43 -13
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +14 -8
- package/dist/intelligence.js +1 -1
- package/dist/intelligence.js.map +1 -1
- package/dist/{kb-gate-CuzMYGYM.d.ts → kb-gate-CwHO0vz6.d.ts} +4 -2
- package/dist/lifecycle.d.ts +2 -2
- package/dist/lifecycle.js +3 -3
- package/dist/{local-harness-DU7yV6mG.d.ts → local-harness-sI0S_XNA.d.ts} +2 -1
- package/dist/{loop-runner-bin-CBkLsyFg.d.ts → loop-runner-bin-hQDUL8Ld.d.ts} +28 -13
- package/dist/loop-runner-bin.d.ts +7 -7
- package/dist/loop-runner-bin.js +10 -10
- package/dist/loops.d.ts +102 -45
- package/dist/loops.js +7 -7
- package/dist/mcp/bin.js +8 -8
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +44 -38
- package/dist/mcp/index.js +11 -11
- package/dist/mcp/index.js.map +1 -1
- package/dist/{mcp-serve-verifier-BvMAV_8U.d.ts → mcp-serve-verifier-FL7-ZEb_.d.ts} +8 -3
- package/dist/{openai-tools-B-3v06BE.d.ts → openai-tools-BnrOmGjN.d.ts} +7 -4
- package/dist/platform.d.ts +4 -0
- package/dist/platform.js.map +1 -1
- package/dist/profiles.d.ts +36 -23
- package/dist/profiles.js +2 -2
- package/dist/profiles.js.map +1 -1
- package/dist/{router-client-D6Ocf4jG.d.ts → router-client-r8y_VFVM.d.ts} +1 -0
- package/dist/{substrate-rNj6TDc3.d.ts → substrate-DO2GHNg2.d.ts} +5 -3
- package/dist/{types-By9LXllv.d.ts → types-Driepl87.d.ts} +3 -2
- package/dist/{types-BF-MEsQB.d.ts → types-ESeMOj94.d.ts} +26 -11
- package/dist/{worktree-fanout-D9Z2dMS9.d.ts → worktree-fanout-D6xR2CIA.d.ts} +16 -10
- package/dist/{worktree-harness-Dx8XULW3.d.ts → worktree-harness-CX_McRLp.d.ts} +11 -8
- package/package.json +1 -1
- package/dist/chunk-5JAUQZQA.js.map +0 -1
- package/dist/chunk-A7LZR5DT.js.map +0 -1
- package/dist/chunk-C2FZ6GR6.js.map +0 -1
- package/dist/chunk-CO2KBPRE.js.map +0 -1
- package/dist/chunk-DJQFJEOD.js.map +0 -1
- package/dist/chunk-FNMGYYSS.js.map +0 -1
- package/dist/chunk-GRAGM4MC.js.map +0 -1
- package/dist/chunk-H7IBHAFT.js.map +0 -1
- package/dist/chunk-JYURIKPF.js.map +0 -1
- package/dist/chunk-KSGHI53L.js.map +0 -1
- package/dist/chunk-LWGVVP2C.js.map +0 -1
- package/dist/chunk-NBV35BR6.js.map +0 -1
- package/dist/chunk-UZ5SODU7.js.map +0 -1
- package/dist/chunk-WIR4HOOJ.js.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/otel-export.ts
|
|
2
|
-
var SCOPE = { name: "@tangle-network/agent-runtime", version: "0.
|
|
2
|
+
var SCOPE = { name: "@tangle-network/agent-runtime", version: "0.83.0" };
|
|
3
3
|
var GEN_AI = {
|
|
4
4
|
operation: "gen_ai.operation.name",
|
|
5
5
|
agentName: "gen_ai.agent.name",
|
|
@@ -378,4 +378,4 @@ export {
|
|
|
378
378
|
INTELLIGENCE_WIRE_VERSION,
|
|
379
379
|
exportEvalRuns
|
|
380
380
|
};
|
|
381
|
-
//# sourceMappingURL=chunk-
|
|
381
|
+
//# sourceMappingURL=chunk-UD4BHQMI.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/otel-export.ts"],"sourcesContent":["/**\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.82.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 single flat OtelSpan whose attribute keys are emitted VERBATIM — no\n * `loop.` namespace. Use for non-loop spans (e.g. the intelligence per-run\n * span) whose keys ARE the downstream contract (`gen_ai.request.model`,\n * `tangle.sessionId`) and are exact-matched by readers. `loopEventToOtelSpan`\n * namespaces payload keys because loop payload fields are free-form; do not\n * reuse it for spans with contract keys.\n */\nexport function flatOtelSpan(\n name: string,\n attributes: Record<string, string | number | boolean>,\n traceId: string,\n timestampMs: number,\n parentSpanId?: string,\n): OtelSpan {\n const ts = msToNs(timestampMs)\n return {\n traceId: padTraceId(traceId),\n spanId: generateSpanId(),\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name,\n kind: 1,\n startTimeUnixNano: ts,\n endTimeUnixNano: ts,\n attributes: toAttributes(attributes),\n status: { code: 1 },\n }\n}\n\n/**\n * Sink-neutral node in a reconstructed loop span tree. The root node's\n * `parentSpanId` is `undefined` — sinks decide how to parent it (the OTEL\n * mapper attaches the inherited delegation span; the delegation journal\n * leaves it as the tree root).\n */\nexport interface LoopSpanNode {\n spanId: string\n parentSpanId?: string\n /** `'loop'` | `'loop.round'` | `'loop.iteration'`. */\n name: string\n /** Topology level: loop root, plan round, or iteration branch. */\n kind: 'loop' | 'round' | 'branch'\n startMs: number\n endMs: number\n attrs: Record<string, string | number | boolean>\n /** True when the iteration carried an error — maps to OTEL status code 2. */\n error: boolean\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 const tid = padTraceId(traceId)\n return buildLoopSpanNodes(events).map((node) => ({\n traceId: tid,\n spanId: node.spanId,\n parentSpanId: node.parentSpanId\n ? padSpanId(node.parentSpanId)\n : rootParentSpanId\n ? padSpanId(rootParentSpanId)\n : undefined,\n name: node.name,\n kind: 1,\n startTimeUnixNano: msToNs(node.startMs),\n endTimeUnixNano: msToNs(node.endMs),\n attributes: toAttributes(node.attrs),\n status: { code: node.error ? 2 : 1 },\n }))\n}\n\n/**\n * Sink-neutral core behind {@link buildLoopOtelSpans}: reconstruct the\n * loop → round → branch span tree from one run's ordered `LoopTraceEvent`\n * stream. Consumed by the OTEL mapper above and by the MCP delegation\n * journal's compact trace tee — one topology reconstruction, two sinks.\n * Tolerates partial streams (a run that never reached `loop.ended` closes\n * at the last observed event's timestamp).\n */\nexport function buildLoopSpanNodes(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n): LoopSpanNode[] {\n if (events.length === 0) return []\n const out: LoopSpanNode[] = []\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 kind: LoopSpanNode['kind'],\n startMs: number,\n endMs: number,\n attrs: Record<string, string | number | boolean>,\n error = false,\n ): LoopSpanNode => ({\n spanId,\n parentSpanId,\n name,\n kind,\n startMs,\n endMs,\n attrs,\n error,\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 // Explicit run identity under the tangle namespace so a consuming system of\n // record (Tangle Intelligence's run spine) maps this span tree to one run\n // deterministically, instead of inferring it from the conversation id.\n 'tangle.run.id': 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 // Subject grain: the primary agent/profile this run drove. Lets the spine\n // group runs under the thing being worked on rather than one service-wide\n // bucket. `agentRunNames[0]` is the lead agent on a fan-out.\n rootAttrs['tangle.subject.key'] = String(sp.agentRunNames[0])\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, undefined, 'loop', '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(\n pendingRound.id,\n rootId,\n 'loop.round',\n 'round',\n pendingRound.start,\n endMs,\n pendingRound.attrs,\n ),\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 'branch',\n start,\n e.timestamp,\n attrs,\n err !== undefined,\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":";AA6DA,IAAM,QAAQ,EAAE,MAAM,iCAAiC,SAAS,SAAS;AAQzE,IAAM,SAAS;AAAA,EACb,WAAW;AAAA,EACX,WAAW;A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H,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":[]}
|
|
1
|
+
{"version":3,"sources":["../src/otel-export.ts"],"sourcesContent":["/**\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.83.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 single flat OtelSpan whose attribute keys are emitted VERBATIM — no\n * `loop.` namespace. Use for non-loop spans (e.g. the intelligence per-run\n * span) whose keys ARE the downstream contract (`gen_ai.request.model`,\n * `tangle.sessionId`) and are exact-matched by readers. `loopEventToOtelSpan`\n * namespaces payload keys because loop payload fields are free-form; do not\n * reuse it for spans with contract keys.\n */\nexport function flatOtelSpan(\n name: string,\n attributes: Record<string, string | number | boolean>,\n traceId: string,\n timestampMs: number,\n parentSpanId?: string,\n): OtelSpan {\n const ts = msToNs(timestampMs)\n return {\n traceId: padTraceId(traceId),\n spanId: generateSpanId(),\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name,\n kind: 1,\n startTimeUnixNano: ts,\n endTimeUnixNano: ts,\n attributes: toAttributes(attributes),\n status: { code: 1 },\n }\n}\n\n/**\n * Sink-neutral node in a reconstructed loop span tree. The root node's\n * `parentSpanId` is `undefined` — sinks decide how to parent it (the OTEL\n * mapper attaches the inherited delegation span; the delegation journal\n * leaves it as the tree root).\n */\nexport interface LoopSpanNode {\n spanId: string\n parentSpanId?: string\n /** `'loop'` | `'loop.round'` | `'loop.iteration'`. */\n name: string\n /** Topology level: loop root, plan round, or iteration branch. */\n kind: 'loop' | 'round' | 'branch'\n startMs: number\n endMs: number\n attrs: Record<string, string | number | boolean>\n /** True when the iteration carried an error — maps to OTEL status code 2. */\n error: boolean\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 const tid = padTraceId(traceId)\n return buildLoopSpanNodes(events).map((node) => ({\n traceId: tid,\n spanId: node.spanId,\n parentSpanId: node.parentSpanId\n ? padSpanId(node.parentSpanId)\n : rootParentSpanId\n ? padSpanId(rootParentSpanId)\n : undefined,\n name: node.name,\n kind: 1,\n startTimeUnixNano: msToNs(node.startMs),\n endTimeUnixNano: msToNs(node.endMs),\n attributes: toAttributes(node.attrs),\n status: { code: node.error ? 2 : 1 },\n }))\n}\n\n/**\n * Sink-neutral core behind {@link buildLoopOtelSpans}: reconstruct the\n * loop → round → branch span tree from one run's ordered `LoopTraceEvent`\n * stream. Consumed by the OTEL mapper above and by the MCP delegation\n * journal's compact trace tee — one topology reconstruction, two sinks.\n * Tolerates partial streams (a run that never reached `loop.ended` closes\n * at the last observed event's timestamp).\n */\nexport function buildLoopSpanNodes(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n): LoopSpanNode[] {\n if (events.length === 0) return []\n const out: LoopSpanNode[] = []\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 kind: LoopSpanNode['kind'],\n startMs: number,\n endMs: number,\n attrs: Record<string, string | number | boolean>,\n error = false,\n ): LoopSpanNode => ({\n spanId,\n parentSpanId,\n name,\n kind,\n startMs,\n endMs,\n attrs,\n error,\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 // Explicit run identity under the tangle namespace so a consuming system of\n // record (Tangle Intelligence's run spine) maps this span tree to one run\n // deterministically, instead of inferring it from the conversation id.\n 'tangle.run.id': 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 // Subject grain: the primary agent/profile this run drove. Lets the spine\n // group runs under the thing being worked on rather than one service-wide\n // bucket. `agentRunNames[0]` is the lead agent on a fan-out.\n rootAttrs['tangle.subject.key'] = String(sp.agentRunNames[0])\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, undefined, 'loop', '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(\n pendingRound.id,\n rootId,\n 'loop.round',\n 'round',\n pendingRound.start,\n endMs,\n pendingRound.attrs,\n ),\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 'branch',\n start,\n e.timestamp,\n attrs,\n err !== undefined,\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":";AA6DA,IAAM,QAAQ,EAAE,MAAM,iCAAiC,SAAS,SAAS;AAQzE,IAAM,SAAS;AAAA,EACb,WAAW;AAAA,EACX,WAAW;AAAA,EACX,gBAAgB;AAAA,EAChB,aAAa;AAAA,EACb,cAAc;AAChB;AAKO,SAAS,mBAAmB,QAAqD;AACtF,QAAM,mBACJ,QAAQ,aACP,OAAO,YAAY,cAAc,QAAQ,IAAI,8BAA8B;AAC9E,MAAI,CAAC,iBAAkB,QAAO;AAC9B,QAAM,WAAmB;AAEzB,QAAM,UAAU,QAAQ,WAAW,oBAAoB;AACvD,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,kBAAkB,QAAQ,mBAAmB;AACnD,QAAM,cAAc,QAAQ,eAAe;AAC3C,QAAM,gBAAgB,QAAQ,sBAAsB,CAAC;AAErD,QAAM,UAAsB,CAAC;AAC7B,MAAI;AACJ,MAAI,UAAU;AAEd,QAAM,WAAyB;AAAA,IAC7B,WAAW,MAAsB;AAC/B,UAAI,QAAS;AACb,cAAQ,KAAK,IAAI;AACjB,UAAI,QAAQ,UAAU,WAAW;AAC/B,aAAK,QAAQ;AAAA,MACf;AAAA,IACF;AAAA,IAEA,MAAM,QAAuB;AAC3B,YAAM,QAA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IAAI,KAAK,OAAO,SAAS;AAAA,IACvD,UAAU,OAAO,YAAY,CAAC;AAAA,EAChC;AACF;","names":[]}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createKbGate
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-SGKPNBXE.js";
|
|
4
4
|
import {
|
|
5
5
|
definePersona,
|
|
6
6
|
runPersonified,
|
|
7
7
|
worktreeFanout
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-QDVLTRCP.js";
|
|
9
9
|
import {
|
|
10
10
|
createExecutorRegistry
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-SSA6OERV.js";
|
|
12
12
|
import {
|
|
13
13
|
runAnalystLoop
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-YPA5MLVE.js";
|
|
15
15
|
import {
|
|
16
16
|
ConfigError
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-YEJR7IXO.js";
|
|
18
18
|
|
|
19
19
|
// src/loop-runner.ts
|
|
20
20
|
import {
|
|
@@ -196,4 +196,4 @@ export {
|
|
|
196
196
|
runLoopRunnerCli,
|
|
197
197
|
parseLoopRunnerArgv
|
|
198
198
|
};
|
|
199
|
-
//# sourceMappingURL=chunk-
|
|
199
|
+
//# sourceMappingURL=chunk-UJ3ONGHR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/loop-runner.ts","../src/loop-runner-bin.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → closed-loop text/config optimization (selfImprove, held-out gated)\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { Scenario } from '@tangle-network/agent-eval/campaign'\nimport {\n type SelfImproveOptions,\n type SelfImproveResult,\n selfImprove,\n} from '@tangle-network/agent-eval/contract'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a {@link DelegatedLoopResult}. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\nexport interface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\nexport interface WorktreeLoopRunnerOptions {\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runLoop` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: { name: 'worktree-coder' }, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\nexport interface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\nexport interface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `self-improve` mode — agent-eval's one-call closed improvement loop (held-out gated).\n *\n * @experimental\n */\nexport function selfImproveLoopRunner<TScenario extends Scenario, TArtifact>(\n options: SelfImproveOptions<TScenario, TArtifact>,\n): DelegatedLoopRunner<SelfImproveResult<TScenario, TArtifact>> {\n return async () => selfImprove<TScenario, TArtifact>(options)\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n","#!/usr/bin/env node\n/**\n *\n * `agent-runtime-loop` — the schedulable entrypoint for the configured\n * delegated loop-runner. A cron job / routine / Makefile target invokes:\n *\n * agent-runtime-loop --mode research --config ./loops.config.js\n *\n * The config module wires the registry (with full access to env / creds —\n * which is why the deps live there, not in this generic bin). It must default-\n * export a `DelegatedLoopRegistry`, or a `() => DelegatedLoopRegistry | Promise<…>`.\n * The bin runs the selected mode, prints the `DelegatedLoopResult` as JSON, and\n * exits 0 on `ok`, 1 on a recorded failure, 2 on a usage/config error.\n *\n * @experimental\n */\n\nimport {\n DELEGATED_LOOP_MODES,\n type DelegatedLoopMode,\n type DelegatedLoopRegistry,\n type DelegatedLoopResult,\n isDelegatedLoopMode,\n runDelegatedLoop,\n} from './loop-runner'\n\n/** @experimental Parsed CLI invocation. */\nexport interface LoopRunnerCliArgs {\n mode: string\n /** Loads the registry — the bin wires this from `--config`; tests inject a stub. */\n loadRegistry: () => Promise<DelegatedLoopRegistry> | DelegatedLoopRegistry\n now?: () => number\n}\n\n/** @experimental */\nexport interface LoopRunnerCliResult {\n exitCode: number\n result?: DelegatedLoopResult\n error?: string\n}\n\n/**\n *\n * Pure CLI core (no process / argv / IO) so it's unit-testable: validate the\n * mode, load the registry, dispatch, map to an exit code (0 ok / 1 failed /\n * 2 usage). Exported for embedding in custom runners + tests.\n *\n * @experimental\n */\nexport async function runLoopRunnerCli(args: LoopRunnerCliArgs): Promise<LoopRunnerCliResult> {\n if (!isDelegatedLoopMode(args.mode)) {\n return {\n exitCode: 2,\n error: `unknown mode '${args.mode}' (expected one of: ${DELEGATED_LOOP_MODES.join(', ')})`,\n }\n }\n let registry: DelegatedLoopRegistry\n try {\n registry = await args.loadRegistry()\n } catch (err) {\n return { exitCode: 2, error: `failed to load registry: ${errMsg(err)}` }\n }\n if (!registry[args.mode]) {\n return {\n exitCode: 2,\n error: `config registers no runner for mode '${args.mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n }\n }\n // runDelegatedLoop throws only on a missing runner (guarded above); a failing\n // engine is captured as { ok: false } → exit 1, not a crash.\n const result = await runDelegatedLoop(args.mode as DelegatedLoopMode, registry, {\n ...(args.now ? { now: args.now } : {}),\n })\n return { exitCode: result.ok ? 0 : 1, result }\n}\n\n/** Parse `--mode X --config Y` from an argv tail (`process.argv.slice(2)`). */\nexport function parseLoopRunnerArgv(argv: string[]): { mode?: string; config?: string } {\n const out: { mode?: string; config?: string } = {}\n for (let i = 0; i < argv.length; i += 1) {\n const a = argv[i]\n if (a === '--mode') out.mode = argv[++i]\n else if (a === '--config') out.config = argv[++i]\n else if (a?.startsWith('--mode=')) out.mode = a.slice('--mode='.length)\n else if (a?.startsWith('--config=')) out.config = a.slice('--config='.length)\n }\n return out\n}\n\n/** Normalize a config module's default export → a registry. */\nfunction resolveRegistry(mod: unknown): DelegatedLoopRegistry {\n const def = (mod as { default?: unknown })?.default ?? mod\n const value = typeof def === 'function' ? (def as () => unknown)() : def\n return value as DelegatedLoopRegistry\n}\n\nfunction errMsg(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n\n/** The argv → IO → exit shell. Kept thin; logic lives in `runLoopRunnerCli`. */\nasync function main(): Promise<void> {\n const { mode, config } = parseLoopRunnerArgv(process.argv.slice(2))\n if (!mode || !config) {\n process.stderr.write(\n 'usage: agent-runtime-loop --mode <mode> --config <module>\\n' +\n ` modes: ${DELEGATED_LOOP_MODES.join(' | ')}\\n` +\n ' config: a JS/TS module default-exporting a DelegatedLoopRegistry (or a factory)\\n',\n )\n process.exit(2)\n }\n const { pathToFileURL } = await import('node:url')\n const { resolve } = await import('node:path')\n const cli = await runLoopRunnerCli({\n mode,\n loadRegistry: async () => resolveRegistry(await import(pathToFileURL(resolve(config)).href)),\n })\n process.stdout.write(`${JSON.stringify(cli.result ?? { error: cli.error }, null, 2)}\\n`)\n if (cli.error) process.stderr.write(`${cli.error}\\n`)\n process.exit(cli.exitCode)\n}\n\n// Run only when executed as the bin — never when imported for the testable\n// core, and never when bundled into a runtime that has no `process.argv`\n// (e.g. Cloudflare Workers, where `process` is a shim without `argv`). Reading\n// `process.argv[1]` directly would throw at module load there; `process.argv?.`\n// keeps the guard a no-op instead of crashing the Worker on startup.\nconst invokedScript = typeof process !== 'undefined' ? process.argv?.[1] : undefined\nif (invokedScript && /loop-runner-bin\\.(js|ts|mjs)$/.test(invokedScript)) {\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B;AAAA,IACjC;AAAA,IACA,cAAc,YAAY,gBAAgB,MAAM,OAAO,cAAc,QAAQ,MAAM,CAAC,EAAE,KAAK;AAAA,EAC7F,CAAC;AACD,UAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,IAAI,UAAU,EAAE,OAAO,IAAI,MAAM,GAAG,MAAM,CAAC,CAAC;AAAA,CAAI;AACvF,MAAI,IAAI,MAAO,SAAQ,OAAO,MAAM,GAAG,IAAI,KAAK;AAAA,CAAI;AACpD,UAAQ,KAAK,IAAI,QAAQ;AAC3B;AAOA,IAAM,gBAAgB,OAAO,YAAY,cAAc,QAAQ,OAAO,CAAC,IAAI;AAC3E,IAAI,iBAAiB,gCAAgC,KAAK,aAAa,GAAG;AACxE,OAAK,KAAK;AACZ;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runLocalHarness
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-7LO5GMAO.js";
|
|
4
4
|
|
|
5
5
|
// src/improvement/agentic-generator.ts
|
|
6
6
|
import { spawnSync } from "child_process";
|
|
@@ -263,4 +263,4 @@ export {
|
|
|
263
263
|
mcpBuildPrompt,
|
|
264
264
|
mcpServeVerifier
|
|
265
265
|
};
|
|
266
|
-
//# sourceMappingURL=chunk-
|
|
266
|
+
//# sourceMappingURL=chunk-VNOOH22O.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/improvement/agentic-generator.ts","../src/improvement/build-prompts.ts","../src/improvement/mcp-serve-verifier.ts"],"sourcesContent":["/**\n *\n * `agenticGenerator` — the full-agentic `CandidateGenerator`: the\n * `shots=N, sandbox=on` setting of the one `improvementDriver`. It runs a real\n * coding harness (claude / codex / opencode) inside the candidate worktree the\n * driver already created, letting the agent read the codebase + the research\n * report and make the change in place. The driver then commits the worktree\n * into a `CodeSurface`.\n *\n * Mechanism: identical to the proven Phase-2.8 in-process executor — spawn the\n * harness as a subprocess with `cwd` = the worktree, on the same filesystem,\n * so edits land in place (no sandbox-mount round-trip). `runLocalHarness` is\n * the verified primitive. The OUTER sandbox is the improvement loop's own\n * execution context; the generator does not nest a second sandbox per\n * candidate (which would reintroduce a host↔sandbox worktree-transport\n * problem that does not need solving here).\n *\n * `maxShots` is the DEPTH dial — a multi-shot verify-in-session loop, NOT the\n * kernel `runLoop`. Each shot runs one full harness session in the (persistent)\n * worktree; between shots the loop refines based on what the last shot produced:\n * - empty tree → \"you changed nothing, make the edits\" → retry\n * - dirty + `verify` fails → feed the verifier's failure into the next shot\n * (the worktree persists, so the harness RESUMES atop its own failing\n * edits with the error in hand — no `--resume` session plumbing needed,\n * and harness-agnostic across claude/codex/opencode)\n * - dirty + `verify` ok (or no verifier configured) → return the candidate\n * A candidate that never verifies within `maxShots` is discarded (`applied:\n * false`), never shipped — if you configured a verifier, a non-passing tree is\n * not a candidate. With no verifier the legacy behavior holds: first dirty shot\n * is the candidate.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport { type LocalHarness, runLocalHarness } from '../mcp/local-harness'\nimport type { CandidateGenerator } from './improvement-driver'\n\n/** Outcome of verifying a candidate worktree. `feedback` (compiler errors,\n * failing test output) is fed into the next shot when `ok` is false. */\nexport interface VerifyResult {\n ok: boolean\n feedback?: string\n}\n\n/** Verifies the edited worktree. Sync or async; throws only on a setup fault\n * (a candidate that fails verification returns `{ok:false}`, it does not\n * throw). */\nexport type Verifier = (worktreePath: string) => Promise<VerifyResult> | VerifyResult\n\nexport interface AgenticGeneratorOptions {\n /** Local coding harness to run in the worktree. Default `claude`. */\n harness?: LocalHarness\n /** Per-shot wall-clock timeout (ms). Default = `runLocalHarness` default (5m). */\n timeoutMs?: number\n /** Build the harness task prompt from the report + findings. Override for\n * domain phrasing; the default turns findings into a concrete coder task. */\n buildPrompt?: (args: { report: unknown; findings: AnalystFinding[] }) => string\n /** Verify the worktree after each dirtying shot. When set, a candidate that\n * fails verification is NOT returned — the failure feeds the next shot\n * (verify-in-session), up to `maxShots`; a candidate that never verifies is\n * discarded (`applied:false`), never shipped. Omitted ⇒ legacy behavior:\n * the first dirty shot is the candidate. See `commandVerifier`. */\n verify?: Verifier\n /** Test seam — inject the harness runner (defaults to `runLocalHarness`). */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the worktree-dirty check (defaults to `git status`). */\n isDirty?: (worktreePath: string) => boolean\n}\n\n/** Full-agentic `CandidateGenerator` (the `shots=N, sandbox=on` setting): run a real coding harness inside the candidate worktree so the agent makes the change in place. */\nexport function agenticGenerator(opts: AgenticGeneratorOptions = {}): CandidateGenerator {\n const harness = opts.harness ?? 'claude'\n const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt\n const run = opts.runHarness ?? runLocalHarness\n const dirty = opts.isDirty ?? worktreeDirty\n const verify = opts.verify\n\n return {\n kind: `agentic:${harness}`,\n async generate({ worktreePath, report, findings, maxShots, signal }) {\n const basePrompt = buildPrompt({ report, findings })\n const shots = Math.max(1, maxShots)\n // Feedback appended to the base prompt for the NEXT shot — empty on shot 0.\n let attemptNote = ''\n\n for (let shot = 0; shot < shots; shot++) {\n if (signal.aborted) break\n await run({\n harness,\n cwd: worktreePath,\n taskPrompt: attemptNote ? `${basePrompt}\\n\\n${attemptNote}` : basePrompt,\n timeoutMs: opts.timeoutMs,\n signal,\n })\n\n // The worktree IS the signal: no edits ⇒ tell the next shot to act.\n if (!dirty(worktreePath)) {\n attemptNote = EMPTY_TREE_NOTE\n continue\n }\n\n // Dirty: with no verifier the diff IS the candidate (we trust the diff,\n // not the harness's stdout). With a verifier the candidate must pass it.\n if (!verify) {\n return { applied: true, summary: summarize(findings) }\n }\n const result = await verify(worktreePath)\n if (result.ok) {\n return { applied: true, summary: summarize(findings) }\n }\n // Dirty but failing — resume next shot atop these edits with the error.\n attemptNote = failureNote(result.feedback)\n }\n\n // Shots exhausted: no verified candidate (or, sans verifier, no edits).\n return { applied: false, summary: '' }\n },\n }\n}\n\n/** Turn the analyst's findings (+ optional report) into a concrete coder task. */\nfunction defaultBuildPrompt(args: { report: unknown; findings: AnalystFinding[] }): string {\n const lines: string[] = [\n 'You are improving this codebase based on an evaluation analysis.',\n 'Make the smallest set of edits that addresses the findings below, then stop.',\n 'Do not change unrelated code. Do not commit — leave changes in the working tree.',\n '',\n 'Findings:',\n ]\n for (const f of args.findings) {\n const where = f.subject ? ` [${f.subject}]` : ''\n lines.push(`- (${f.severity})${where} ${f.claim}`)\n if (f.recommended_action) lines.push(` → ${f.recommended_action}`)\n }\n return lines.join('\\n')\n}\n\nconst EMPTY_TREE_NOTE =\n 'NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.'\n\n/** Next-shot feedback when the worktree is dirty but failed verification. The\n * edits persist on disk, so the harness resumes atop them — tell it to fix in\n * place, not start over. Verifier detail is truncated to keep the prompt bounded. */\nfunction failureNote(feedback?: string): string {\n const detail = feedback?.trim()\n return [\n 'NOTE: your edits are in the working tree but verification FAILED.',\n 'Fix the problem in place — build on your existing edits, do not revert them.',\n detail ? `Verifier output:\\n${truncate(detail, 4000)}` : 'No verifier detail was captured.',\n ].join('\\n')\n}\n\n/** A `Verifier` that runs a command in the worktree: exit 0 ⇒ ok, any other\n * exit ⇒ failed with stdout+stderr as feedback. The common case — verify by\n * `tsc --noEmit`, `pnpm build`, or a test command. A timeout is treated as a\n * FAILED candidate (a change that hangs the build is a bad change); a missing\n * binary or spawn fault throws (a setup bug, not a failed candidate — no\n * silent fallback). */\nexport function commandVerifier(\n command: string,\n args: string[] = [],\n timeoutMs = 300_000,\n): Verifier {\n return (worktreePath: string): VerifyResult => {\n const result = spawnSync(command, args, {\n cwd: worktreePath,\n encoding: 'utf-8',\n timeout: timeoutMs,\n })\n if (result.signal) {\n return {\n ok: false,\n feedback: `verifier '${command}' killed by ${result.signal} (likely timeout after ${timeoutMs}ms)`,\n }\n }\n if (result.error) {\n const code = (result.error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new Error(\n `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n }\n throw new Error(`commandVerifier: '${command}' failed to spawn: ${result.error.message}`)\n }\n if (result.status === 0) return { ok: true }\n const out = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim()\n return { ok: false, feedback: out.length > 0 ? out : `exit ${result.status}` }\n }\n}\n\n/** A one-line summary for the commit message, derived from the findings. */\nfunction summarize(findings: AnalystFinding[]): string {\n if (findings.length === 0) return 'agentic improvement'\n if (findings.length === 1) return `agentic: ${truncate(findings[0]!.claim, 64)}`\n return `agentic: ${findings.length} findings addressed`\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n\n/** Non-empty `git status --porcelain` ⇒ the harness changed the worktree.\n * Fails loud: the worktree is a fresh checkout, so a git error here means\n * something is genuinely broken (git missing, corrupt index, killed mid-run).\n * Folding that into `false` would silently discard a candidate and mask the\n * real failure — forbidden by the no-silent-fallbacks doctrine. */\nfunction worktreeDirty(worktreePath: string): boolean {\n const result = spawnSync('git', ['status', '--porcelain'], {\n cwd: worktreePath,\n encoding: 'utf-8',\n })\n if (result.error) {\n throw new Error(\n `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`,\n )\n }\n if (result.status !== 0) {\n throw new Error(\n `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`,\n )\n }\n return result.stdout.trim().length > 0\n}\n","/**\n * Build-prompt starting points for the two buildable artifact types. There is\n * NO `toolGenerator`/`mcpGenerator` wrapper — the factory is `agenticGenerator`\n * + a verifier (docs/artifact-lifecycle-frontier.md), so a tool or an MCP\n * server is built by composing the pieces directly:\n *\n * // a tool:\n * agenticGenerator({ buildPrompt: toolBuildPrompt, verify: commandVerifier('pnpm', ['test']) })\n * // an MCP server:\n * agenticGenerator({ buildPrompt: mcpBuildPrompt, verify: mcpServeVerifier({ command: 'node', args: ['server.mjs'] }) })\n *\n * These are the only type-specific bit (the phrasing that points the agent at a\n * tool vs. an MCP); the worktree, resume-on-failure loop, and improvement-loop\n * wrapper are shared. MCP is the load-bearing target — it is how a harness\n * acquires tools; raw tools matter where we control the loader.\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\n\ntype FindingsArg = { report: unknown; findings: AnalystFinding[] }\n\nfunction findingLines(findings: AnalystFinding[]): string[] {\n return findings.map((f) => {\n const where = f.subject ? ` [${f.subject}]` : ''\n const action = f.recommended_action ? ` → ${f.recommended_action}` : ''\n return `- (${f.severity})${where} ${f.claim}${action}`\n })\n}\n\n/** Build the starting instruction for a coder agent tasked with implementing a new tool. */\nexport function toolBuildPrompt(args: FindingsArg): string {\n return [\n 'You are building a new TOOL for this codebase to address the gaps below.',\n 'Write the tool as a small, self-contained module PLUS tests that exercise it.',\n 'The tool must compile and its tests must pass — they will be run automatically;',\n 'if verification fails you will get the error and another attempt. Do not commit;',\n 'leave the changes in the working tree.',\n '',\n 'Gaps the tool should close:',\n ...findingLines(args.findings),\n ].join('\\n')\n}\n\n/** Build the starting instruction for a coder agent tasked with implementing a new MCP server. */\nexport function mcpBuildPrompt(args: FindingsArg): string {\n return [\n 'You are building a new MCP SERVER (Model Context Protocol) that exposes',\n 'tool(s) addressing the gaps below, so any harness can mount it.',\n 'Requirements that WILL be checked by booting the server:',\n '- it starts over stdio and answers the MCP `initialize` handshake,',\n '- `tools/list` returns at least one tool with a valid input schema.',\n 'Newline-delimited JSON-RPC 2.0, protocol version 2024-11-05. Include a start',\n 'command (e.g. a package.json `start` script or a clear entrypoint). If the',\n 'boot-and-probe fails you will get the error and another attempt. Do not',\n 'commit; leave the changes in the working tree.',\n '',\n 'Capabilities the server should provide:',\n ...findingLines(args.findings),\n ].join('\\n')\n}\n","/**\n * `mcpServeVerifier` — the intrinsic verifier for a built MCP server: the\n * boot-and-probe checker named in docs/artifact-lifecycle-frontier.md. A\n * generated MCP server is only a candidate if it actually *serves* — so this\n * boots it over stdio (the default local MCP transport) and runs the real\n * handshake: `initialize` → `notifications/initialized` → `tools/list`, and\n * asserts the server answers with at least `minTools` tools.\n *\n * Outcomes follow the `Verifier` contract: a server that fails to start, exits\n * early, errors the handshake, times out, or exposes no tools is a FAILED\n * candidate (`{ok:false}`, fed back into the next generation shot); a missing\n * start binary or spawn fault THROWS (a setup bug, never a silent fallback).\n *\n * Protocol matches the runtime's own stdio MCP server (src/mcp/server.ts):\n * newline-delimited JSON-RPC 2.0, protocol version 2024-11-05.\n */\n\nimport { spawn } from 'node:child_process'\nimport { createInterface } from 'node:readline'\nimport type { Verifier, VerifyResult } from './agentic-generator'\n\nconst PROTOCOL_VERSION = '2024-11-05'\n\nexport interface McpServeSpec {\n /** Command that starts the built MCP server in the worktree (stdio transport). */\n command: string\n args?: string[]\n /** Extra env for the server process (merged over `process.env`). */\n env?: Record<string, string>\n /** Handshake timeout (ms). Default 30s. */\n timeoutMs?: number\n /** Minimum tools the server must expose to pass. Default 1. */\n minTools?: number\n}\n\ninterface JsonRpcResponse {\n jsonrpc?: string\n id?: number | string | null\n result?: unknown\n error?: { code: number; message: string }\n}\n\n/** Build a `Verifier` that boots a generated MCP server over stdio and checks it exposes tools. */\nexport function mcpServeVerifier(spec: McpServeSpec): Verifier {\n const timeoutMs = spec.timeoutMs ?? 30_000\n const minTools = spec.minTools ?? 1\n\n return (worktreePath: string): Promise<VerifyResult> =>\n new Promise<VerifyResult>((resolve, reject) => {\n const child = spawn(spec.command, spec.args ?? [], {\n cwd: worktreePath,\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...process.env, ...spec.env },\n })\n\n const stderr: string[] = []\n let settled = false\n let nextId = 1\n const initId = nextId++\n let listId = -1\n\n const settle = (fn: () => void) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n rl.close()\n child.kill('SIGKILL')\n fn()\n }\n const withStderr = (msg: string) =>\n stderr.length > 0 ? `${msg}\\nstderr:\\n${stderr.join('').slice(-2000)}` : msg\n const pass = () => settle(() => resolve({ ok: true }))\n const failCandidate = (msg: string) =>\n settle(() => resolve({ ok: false, feedback: withStderr(msg) }))\n const setupFault = (err: Error) => settle(() => reject(err))\n\n const send = (msg: Record<string, unknown>): boolean => {\n try {\n child.stdin.write(`${JSON.stringify(msg)}\\n`)\n return true\n } catch (err) {\n // EPIPE: the server died mid-handshake — a failed candidate, not a fault.\n failCandidate(`writing to MCP server stdin failed: ${(err as Error).message}`)\n return false\n }\n }\n\n child.on('error', (err) => {\n const code = (err as NodeJS.ErrnoException).code\n setupFault(\n code === 'ENOENT'\n ? new Error(\n `mcpServeVerifier: '${spec.command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n : new Error(`mcpServeVerifier: '${spec.command}' failed to spawn: ${err.message}`),\n )\n })\n child.on('exit', (code, signal) => {\n // An exit before the handshake completes is a failed candidate (the\n // server crashed on boot); after we settle, our own SIGKILL fires here.\n failCandidate(`MCP server exited (code ${code}, signal ${signal}) before serving`)\n })\n child.stderr.on('data', (d) => stderr.push(String(d)))\n\n const rl = createInterface({ input: child.stdout })\n rl.on('line', (line) => {\n let msg: JsonRpcResponse | undefined\n try {\n msg = JSON.parse(line) as JsonRpcResponse\n } catch {\n return // servers log to stdout too; skip non-JSON lines\n }\n if (!msg || typeof msg !== 'object') return\n\n if (msg.id === initId) {\n if (msg.error) return failCandidate(`initialize errored: ${JSON.stringify(msg.error)}`)\n if (!send({ jsonrpc: '2.0', method: 'notifications/initialized' })) return\n listId = nextId++\n send({ jsonrpc: '2.0', id: listId, method: 'tools/list' })\n return\n }\n if (msg.id === listId) {\n if (msg.error) return failCandidate(`tools/list errored: ${JSON.stringify(msg.error)}`)\n const tools = (msg.result as { tools?: unknown[] } | undefined)?.tools\n if (!Array.isArray(tools)) return failCandidate('tools/list result has no tools array')\n if (tools.length < minTools) {\n return failCandidate(`tools/list returned ${tools.length} tool(s), need >= ${minTools}`)\n }\n return pass()\n }\n })\n\n const timer = setTimeout(\n () => failCandidate(`MCP server did not complete the handshake within ${timeoutMs}ms`),\n timeoutMs,\n )\n\n send({\n jsonrpc: '2.0',\n id: initId,\n method: 'initialize',\n params: {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: { name: 'agent-runtime-mcp-verify', version: '0' },\n },\n })\n })\n}\n"],"mappings":";;;;;AAkCA,SAAS,iBAAiB;AAsCnB,SAAS,iBAAiB,OAAgC,CAAC,GAAuB;AACvF,QAAM,UAAU,KAAK,WAAW;AAChC,QAAM,cAAc,KAAK,eAAe;AACxC,QAAM,MAAM,KAAK,cAAc;AAC/B,QAAM,QAAQ,KAAK,WAAW;AAC9B,QAAM,SAAS,KAAK;AAEpB,SAAO;AAAA,IACL,MAAM,WAAW,OAAO;AAAA,IACxB,MAAM,SAAS,EAAE,cAAc,QAAQ,UAAU,UAAU,OAAO,GAAG;AACnE,YAAM,aAAa,YAAY,EAAE,QAAQ,SAAS,CAAC;AACnD,YAAM,QAAQ,KAAK,IAAI,GAAG,QAAQ;AAElC,UAAI,cAAc;AAElB,eAAS,OAAO,GAAG,OAAO,OAAO,QAAQ;AACvC,YAAI,OAAO,QAAS;AACpB,cAAM,IAAI;AAAA,UACR;AAAA,UACA,KAAK;AAAA,UACL,YAAY,cAAc,GAAG,UAAU;AAAA;AAAA,EAAO,WAAW,KAAK;AAAA,UAC9D,WAAW,KAAK;AAAA,UAChB;AAAA,QACF,CAAC;AAGD,YAAI,CAAC,MAAM,YAAY,GAAG;AACxB,wBAAc;AACd;AAAA,QACF;AAIA,YAAI,CAAC,QAAQ;AACX,iBAAO,EAAE,SAAS,MAAM,SAAS,UAAU,QAAQ,EAAE;AAAA,QACvD;AACA,cAAM,SAAS,MAAM,OAAO,YAAY;AACxC,YAAI,OAAO,IAAI;AACb,iBAAO,EAAE,SAAS,MAAM,SAAS,UAAU,QAAQ,EAAE;AAAA,QACvD;AAEA,sBAAc,YAAY,OAAO,QAAQ;AAAA,MAC3C;AAGA,aAAO,EAAE,SAAS,OAAO,SAAS,GAAG;AAAA,IACvC;AAAA,EACF;AACF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I,QAAQ,QAAQ,aAAa,CAAC;AACzD;AAAA,MACF;AACA,UAAI,IAAI,OAAO,QAAQ;AACrB,YAAI,IAAI,MAAO,QAAO,cAAc,uBAAuB,KAAK,UAAU,IAAI,KAAK,CAAC,EAAE;AACtF,cAAM,QAAS,IAAI,QAA8C;AACjE,YAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,cAAc,sCAAsC;AACtF,YAAI,MAAM,SAAS,UAAU;AAC3B,iBAAO,cAAc,uBAAuB,MAAM,MAAM,qBAAqB,QAAQ,EAAE;AAAA,QACzF;AACA,eAAO,KAAK;AAAA,MACd;AAAA,IACF,CAAC;AAED,UAAM,QAAQ;AAAA,MACZ,MAAM,cAAc,oDAAoD,SAAS,IAAI;AAAA,MACrF;AAAA,IACF;AAEA,SAAK;AAAA,MACH,SAAS;AAAA,MACT,IAAI;AAAA,MACJ,QAAQ;AAAA,MACR,QAAQ;AAAA,QACN,iBAAiB;AAAA,QACjB,cAAc,CAAC;AAAA,QACf,YAAY,EAAE,MAAM,4BAA4B,SAAS,IAAI;AAAA,MAC/D;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACL;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts"],"sourcesContent":["/**\n *\n * Error taxonomy for `@tangle-network/agent-runtime`.\n *\n * Public contract: every error this package throws as part of its consumer-\n * facing API either extends `AgentEvalError` (re-exported here for ergonomic\n * `instanceof` checks at the runtime boundary) or extends one of the\n * runtime-specific subclasses below.\n *\n * Internal invariant guards (`throw new Error('this should never happen')`)\n * remain plain `Error` — they are programmer-mistake assertions, not\n * consumer-catchable contract failures.\n *\n * Subclassing strategy: where a runtime-specific failure maps cleanly to an\n * agent-eval code (validation, config, not_found), we re-use the agent-eval\n * subclass. Runtime-only failure modes (session resume against the wrong\n * backend, backend transport errors) get fresh subclasses that still carry an\n * `AgentEvalErrorCode` so cross-package handlers can pattern-match without\n * importing the runtime.\n *\n * @stable\n */\n\nimport { AgentEvalError } from '@tangle-network/agent-eval'\n\nexport {\n AgentEvalError,\n type AgentEvalErrorCode,\n ConfigError,\n JudgeError,\n NotFoundError,\n ValidationError,\n} from '@tangle-network/agent-eval'\n\n/**\n *\n * Caller asked to resume a session against a backend whose `kind` does not\n * match the session's recorded backend. This is a routing bug — the same\n * session id was reused across two different backend implementations — and\n * is not retryable without picking the right backend.\n *\n * @stable\n */\nexport class SessionMismatchError extends AgentEvalError {\n readonly sessionBackend: string\n readonly requestedBackend: string\n\n constructor(sessionBackend: string, requestedBackend: string, options?: { cause?: unknown }) {\n super(\n 'validation',\n `Cannot resume ${sessionBackend} session with ${requestedBackend} backend`,\n options,\n )\n this.sessionBackend = sessionBackend\n this.requestedBackend = requestedBackend\n }\n}\n\n/**\n *\n * A backend transport call (HTTP, gRPC, sidecar IPC) failed with a non-success\n * status. Distinct from `JudgeError` (which is structural / unrecoverable)\n * because backend failures are sometimes retryable and consumers may want to\n * branch on the upstream status code.\n *\n * @stable\n */\nexport class BackendTransportError extends AgentEvalError {\n readonly backend: string\n readonly status?: number\n /**\n * Truncated upstream response body (≤2 KiB) when available. Diagnostic\n * only — surfaces in `backend_error.error.body` and `final.error.body`\n * so operators can see \"free_tier_limit\", \"invalid_api_key\", etc. without\n * cracking the log line open.\n */\n readonly body?: string\n\n constructor(\n backend: string,\n message: string,\n options?: { cause?: unknown; status?: number; body?: string },\n ) {\n super('config', message, options)\n this.backend = backend\n this.status = options?.status\n this.body = options?.body\n }\n}\n\n/**\n *\n * A runtime-run lifecycle method was called in an order the state machine does\n * not allow: `persist()` before `complete()`, `complete()` twice, etc.\n *\n * @stable\n */\nexport class RuntimeRunStateError extends AgentEvalError {\n constructor(message: string, options?: { cause?: unknown }) {\n super('validation', message, options)\n }\n}\n\n/**\n *\n * The dynamic-loop planner returned an unusable topology move — the LLM emitted\n * no parseable envelope, an unknown `kind`, or a structurally-invalid move\n * (e.g. a fanout with zero tasks). This is a structural failure of the\n * agent-authored topology, not a config mistake: the planner ran but its output\n * cannot drive the kernel. Carries `validation` so cross-package handlers can\n * pattern-match without importing the runtime. Fail loud — never substitute a\n * default move, or the loop silently runs a topology nobody chose.\n *\n * @stable\n */\nexport class PlannerError extends AgentEvalError {\n constructor(message: string, options?: { cause?: unknown }) {\n super('validation', message, options)\n }\n}\n\n/**\n * The analyst loop could not read or run over a round's trace — e.g. an empty round\n * (no iterations to analyze) or a malformed trace projection. Fail loud: a silent empty\n * store would mask a broken capture path and the driver would steer on nothing.\n */\nexport class AnalystError extends AgentEvalError {\n constructor(message: string, options?: { cause?: unknown }) {\n super('validation', message, options)\n }\n}\n"],"mappings":";AAuBA,SAAS,sBAAsB;AAE/B;AAAA,EACE,kBAAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAWA,IAAM,uBAAN,cAAmC,eAAe;AAAA,EAC9C;AAAA,EACA;AAAA,EAET,YAAY,gBAAwB,kBAA0B,SAA+B;AAC3F;AAAA,MACE;AAAA,MACA,iBAAiB,cAAc,iBAAiB,gBAAgB;AAAA,MAChE;AAAA,IACF;AACA,SAAK,iBAAiB;AACtB,SAAK,mBAAmB;AAAA,EAC1B;AACF;AAWO,IAAM,wBAAN,cAAoC,eAAe;AAAA,EAC/C;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA;AAAA,EAET,YACE,SACA,SACA,SACA;AACA,UAAM,UAAU,SAAS,OAAO;AAChC,SAAK,UAAU;AACf,SAAK,SAAS,SAAS;AACvB,SAAK,OAAO,SAAS;AAAA,EACvB;AACF;AASO,IAAM,uBAAN,cAAmC,eAAe;AAAA,EACvD,YAAY,SAAiB,SAA+B;AAC1D,UAAM,cAAc,SAAS,OAAO;AAAA,EACtC;AACF;AAcO,IAAM,eAAN,cAA2B,eAAe;AAAA,EAC/C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,cAAc,SAAS,OAAO;AAAA,EACtC;AACF;AAOO,IAAM,eAAN,cAA2B,eAAe;AAAA,EAC/C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,cAAc,SAAS,OAAO;AAAA,EACtC;AACF;","names":["AgentEvalError"]}
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-4J6RBI3K.js";
|
|
4
4
|
import {
|
|
5
5
|
AnalystError
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-YEJR7IXO.js";
|
|
7
7
|
|
|
8
8
|
// src/analyst-loop/iterations-to-trace-store.ts
|
|
9
9
|
import {
|
|
@@ -579,4 +579,4 @@ export {
|
|
|
579
579
|
iterationsToTraceStore,
|
|
580
580
|
runAnalystLoop
|
|
581
581
|
};
|
|
582
|
-
//# sourceMappingURL=chunk-
|
|
582
|
+
//# sourceMappingURL=chunk-YPA5MLVE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analyst-loop/iterations-to-trace-store.ts","../src/analyst-loop/run-analyst-loop.ts"],"sourcesContent":["/**\n *\n * The read seam that closes the autonomous loop: project a round's `Iteration[]`\n * (each carrying its raw `SandboxEvent[]`) into an in-memory `TraceAnalysisStore`, the\n * read interface the trace analysts query. `runAnalystLoop` has had zero consumers\n * because nothing turned a loop's iterations into a store — this is that bridge.\n *\n * One iteration → one trace. The iteration is the root AGENT span; each `SandboxEvent`\n * becomes a child span (LLM for llm_call events, TOOL for tool events, else SPAN), so an\n * analyst can walk a shot's trace, cluster its errors, and emit findings the driver\n * steers on. Projection is best-effort over the FLAT SandboxEvent shape (no per-event\n * lineage yet — that's the richer-trace gap); it never fabricates — an errored iteration\n * surfaces a real ERROR span carrying the real message.\n *\n * @experimental\n */\n\nimport {\n type DatasetOverview,\n DEFAULT_TRACE_ANALYST_BUDGETS,\n type QueryTracesPage,\n type SearchSpanResult,\n type SearchTraceResult,\n type SpanMatchRecord,\n TRACE_ANALYST_TRUNCATION_MARKER_PREFIX,\n type TraceAnalysisStore,\n type TraceAnalystByteBudgets,\n type TraceAnalystFilters,\n type TraceAnalystSpan,\n type TraceAnalystSpanKind,\n type TraceAnalystTraceSummary,\n type ViewSpansResult,\n type ViewTraceResult,\n} from '@tangle-network/agent-eval'\nimport type { SandboxEvent } from '@tangle-network/sandbox'\nimport { AnalystError } from '../errors'\nimport { extractLlmCallEvent } from '../runtime/sandbox-events'\nimport type { Iteration } from '../runtime/types'\n\n/** ErrorCluster isn't re-exported from the agent-eval root; derive it from the overview. */\ntype ErrorCluster = DatasetOverview['error_clusters'][number]\n\ninterface ProjectedTrace {\n summary: TraceAnalystTraceSummary\n spans: TraceAnalystSpan[]\n /** raw JSONL bytes of this trace's spans — the byte-budget accounting unit. */\n rawBytes: number\n}\n\nconst bytesOf = (v: unknown): number => Buffer.byteLength(JSON.stringify(v) ?? '', 'utf8')\nconst iso = (ms: number): string => new Date(ms).toISOString()\n\n/** Normalize volatile tokens out of a status message so semantically identical failures\n * collapse to one signature (digits, hex/uuids, paths, durations → placeholders). */\nfunction normalizeSignature(message: string): string {\n return message\n .replace(/0x[0-9a-fA-F]+/g, 'HEX')\n .replace(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/g, 'UUID')\n .replace(/(\\/[\\w.-]+){2,}/g, 'PATH')\n .replace(/\\b\\d+(\\.\\d+)?(ms|s|m|h)\\b/g, 'DUR')\n .replace(/\\b\\d+\\b/g, '#')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, 200)\n}\n\nfunction spanKindFor(\n event: SandboxEvent,\n agentRunName: string,\n): {\n kind: TraceAnalystSpanKind\n model: string | null\n tool: string | null\n} {\n const llm = extractLlmCallEvent(event, agentRunName)\n if (llm) return { kind: 'LLM', model: llm.model ?? null, tool: null }\n const type = String(event?.type ?? '')\n if (/tool/i.test(type)) {\n const d = event?.data as { name?: unknown; tool?: unknown } | undefined\n const tool = typeof d?.name === 'string' ? d.name : typeof d?.tool === 'string' ? d.tool : type\n return { kind: 'TOOL', model: null, tool }\n }\n return { kind: 'SPAN', model: null, tool: null }\n}\n\nfunction errorMessageOf(event: SandboxEvent): string | undefined {\n const type = String(event?.type ?? '')\n const d = event?.data as { error?: unknown; message?: unknown } | undefined\n if (/error|fail/i.test(type) || d?.error) {\n const m = d?.error ?? d?.message\n return typeof m === 'string' ? m : `${type} error`\n }\n return undefined\n}\n\n/** Project one iteration → one trace: root AGENT span + a child span per event. */\nfunction projectIteration<Task, Output>(iter: Iteration<Task, Output>): ProjectedTrace {\n const traceId =\n (\n iter.events.find((e) => (e?.data as { sandboxId?: string } | undefined)?.sandboxId)?.data as\n | { sandboxId?: string }\n | undefined\n )?.sandboxId ?? `iter-${iter.index}`\n const start = iso(iter.startedAt)\n const end = iso(iter.endedAt || iter.startedAt)\n const durationMs = Math.max(0, (iter.endedAt || iter.startedAt) - iter.startedAt)\n const rootId = `${traceId}:root`\n const iterErrored = Boolean(iter.error) || iter.verdict?.valid === false\n const spans: TraceAnalystSpan[] = [\n {\n trace_id: traceId,\n span_id: rootId,\n parent_span_id: null,\n name: iter.agentRunName,\n kind: 'AGENT',\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n status: iter.error ? 'ERROR' : 'OK',\n status_message: iter.error?.message,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: null,\n tool_name: null,\n attributes: {\n 'iteration.index': iter.index,\n 'verdict.valid': iter.verdict?.valid,\n 'verdict.score': iter.verdict?.score,\n 'output.preview':\n iter.output === undefined ? undefined : String(iter.output).slice(0, 2000),\n },\n },\n ]\n const models = new Set<string>()\n const tools = new Set<string>()\n iter.events.forEach((event, i) => {\n const { kind, model, tool } = spanKindFor(event, iter.agentRunName)\n if (model) models.add(model)\n if (tool) tools.add(tool)\n const errMsg = errorMessageOf(event)\n spans.push({\n trace_id: traceId,\n span_id: `${traceId}:e${i}`,\n parent_span_id: rootId,\n name: String(event?.type ?? 'event'),\n kind,\n start_time: start,\n end_time: end,\n duration_ms: 0,\n status: errMsg ? 'ERROR' : 'OK',\n status_message: errMsg,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n model_name: model,\n tool_name: tool,\n attributes: (event?.data as Record<string, unknown> | undefined) ?? {},\n })\n })\n const hasErrors = spans.some((s) => s.status === 'ERROR') || iterErrored\n const summary: TraceAnalystTraceSummary = {\n trace_id: traceId,\n service_name: 'agent-runtime',\n agent_name: iter.agentRunName,\n span_count: spans.length,\n has_errors: hasErrors,\n start_time: start,\n end_time: end,\n duration_ms: durationMs,\n raw_jsonl_bytes: bytesOf(spans),\n models: [...models],\n tools: [...tools],\n }\n return { summary, spans, rawBytes: summary.raw_jsonl_bytes }\n}\n\nfunction matchesFilters(t: ProjectedTrace, f?: TraceAnalystFilters): boolean {\n if (!f) return true\n if (f.has_errors !== undefined && t.summary.has_errors !== f.has_errors) return false\n if (f.service_names?.length && !f.service_names.includes(t.summary.service_name ?? ''))\n return false\n if (f.agent_names?.length && !f.agent_names.includes(t.summary.agent_name ?? '')) return false\n if (f.model_names?.length && !f.model_names.some((m) => t.summary.models.includes(m)))\n return false\n if (f.tool_names?.length && !f.tool_names.some((tn) => t.summary.tools.includes(tn))) return false\n if (f.start_time_after && t.summary.start_time < f.start_time_after) return false\n if (f.start_time_before && t.summary.start_time > f.start_time_before) return false\n if (f.regex_pattern && !new RegExp(f.regex_pattern).test(JSON.stringify(t.spans))) return false\n return true\n}\n\nfunction capAttributes(\n attributes: Record<string, unknown>,\n perAttrCap: number,\n): { capped: Record<string, unknown>; truncated: number } {\n let truncated = 0\n const capped: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attributes)) {\n const s = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof s === 'string' && s.length > perAttrCap) {\n truncated += 1\n capped[k] = `${TRACE_ANALYST_TRUNCATION_MARKER_PREFIX} ${s.length}b]${s.slice(0, perAttrCap)}`\n } else {\n capped[k] = v\n }\n }\n return { capped, truncated }\n}\n\n/**\n * Build an in-memory `TraceAnalysisStore` over a loop round's iterations. Fail-loud on an\n * empty round — there is nothing for an analyst to read, and a silent empty store would\n * mask a broken capture path.\n */\nexport function iterationsToTraceStore<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n budgets: TraceAnalystByteBudgets = DEFAULT_TRACE_ANALYST_BUDGETS,\n): TraceAnalysisStore {\n if (iterations.length === 0) {\n throw new AnalystError('iterationsToTraceStore: no iterations to analyze (empty round)')\n }\n const traces = iterations.map((it) => projectIteration(it))\n const byId = new Map(traces.map((t) => [t.summary.trace_id, t]))\n\n const buildClusters = (set: ProjectedTrace[]): ErrorCluster[] => {\n const map = new Map<string, ErrorCluster>()\n for (const t of set) {\n for (const s of t.spans) {\n if (s.status !== 'ERROR' || !s.status_message) continue\n const sig = normalizeSignature(s.status_message)\n const c = map.get(sig) ?? {\n signature: sig,\n status_message_sample: s.status_message,\n span_name: s.name,\n tool_name: s.tool_name,\n trace_count: 0,\n span_count: 0,\n prevalence: 0,\n exemplar_trace_ids: [],\n exemplar_span_ids: [],\n }\n c.span_count += 1\n if (\n !c.exemplar_trace_ids.includes(t.summary.trace_id) &&\n c.exemplar_trace_ids.length < 10\n ) {\n c.exemplar_trace_ids.push(t.summary.trace_id)\n c.trace_count += 1\n }\n if (c.exemplar_span_ids.length < 10) c.exemplar_span_ids.push(s.span_id)\n map.set(sig, c)\n }\n }\n const errorTraces = set.filter((t) => t.summary.has_errors).length || 1\n const clusters = [...map.values()].map((c) => ({\n ...c,\n prevalence: c.trace_count / errorTraces,\n }))\n return clusters.sort((a, b) => b.trace_count - a.trace_count)\n }\n\n return {\n async getOverview(filters?: TraceAnalystFilters): Promise<DatasetOverview> {\n const set = traces.filter((t) => matchesFilters(t, filters))\n const services = new Set<string>()\n const agents = new Set<string>()\n const models = new Set<string>()\n const tools = new Set<string>()\n let errorSpans = 0\n for (const t of set) {\n if (t.summary.service_name) services.add(t.summary.service_name)\n if (t.summary.agent_name) agents.add(t.summary.agent_name)\n for (const m of t.summary.models) models.add(m)\n for (const tn of t.summary.tools) tools.add(tn)\n errorSpans += t.spans.filter((s) => s.status === 'ERROR').length\n }\n const times = set.map((t) => t.summary.start_time).sort()\n return {\n total_traces: set.length,\n raw_jsonl_bytes: set.reduce((n, t) => n + t.rawBytes, 0),\n services: [...services],\n agents: [...agents],\n models: [...models],\n tool_names: [...tools],\n sample_trace_ids: set.slice(0, 20).map((t) => t.summary.trace_id),\n errors: {\n trace_count: set.filter((t) => t.summary.has_errors).length,\n span_count: errorSpans,\n },\n error_clusters: buildClusters(set),\n time_range: times.length ? { earliest: times[0]!, latest: times[times.length - 1]! } : null,\n }\n },\n\n async queryTraces(opts): Promise<QueryTracesPage> {\n const set = traces.filter((t) => matchesFilters(t, opts.filters))\n const offset = opts.offset ?? 0\n const page = set.slice(offset, offset + opts.limit)\n return {\n traces: page.map((t) => t.summary),\n total: set.length,\n has_more: offset + opts.limit < set.length,\n }\n },\n\n async countTraces(filters?: TraceAnalystFilters): Promise<number> {\n return traces.filter((t) => matchesFilters(t, filters)).length\n },\n\n async viewTrace(opts): Promise<ViewTraceResult> {\n const t = byId.get(opts.trace_id)\n if (!t) return { trace_id: opts.trace_id, spans: [] }\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeViewBudget\n const projected = t.spans.map((s) => ({\n ...s,\n attributes: capAttributes(s.attributes, cap).capped,\n }))\n if (bytesOf(projected) > budgets.perCallByteCeiling) {\n const names = new Map<string, number>()\n for (const s of t.spans) names.set(s.name, (names.get(s.name) ?? 0) + 1)\n return {\n trace_id: opts.trace_id,\n oversized: {\n span_count: t.spans.length,\n top_span_names: [...names.entries()].sort((a, b) => b[1] - a[1]).slice(0, 20),\n span_response_bytes_max: Math.max(...t.spans.map((s) => bytesOf(s))),\n error_span_count: t.spans.filter((s) => s.status === 'ERROR').length,\n },\n }\n }\n return { trace_id: opts.trace_id, spans: projected }\n },\n\n async viewSpans(opts): Promise<ViewSpansResult> {\n const t = byId.get(opts.trace_id)\n const cap = opts.per_attribute_byte_cap ?? budgets.perAttributeSpanBudget\n const want = new Set(opts.span_ids)\n const found = (t?.spans ?? []).filter((s) => want.has(s.span_id))\n let truncated = 0\n const spans = found.map((s) => {\n const { capped, truncated: n } = capAttributes(s.attributes, cap)\n truncated += n\n return { ...s, attributes: capped }\n })\n const foundIds = new Set(found.map((s) => s.span_id))\n return {\n trace_id: opts.trace_id,\n spans,\n missing_span_ids: opts.span_ids.filter((id) => !foundIds.has(id)),\n truncated_attribute_count: truncated,\n }\n },\n\n async searchTrace(opts): Promise<SearchTraceResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const hits: SpanMatchRecord[] = []\n for (const s of t?.spans ?? []) {\n for (const hit of searchSpanAttrs(s, opts.regex_pattern, budgets.perMatchTextBudget)) {\n if (hits.length >= max) break\n hits.push(hit)\n }\n }\n return {\n trace_id: opts.trace_id,\n hits,\n total_matches: hits.length,\n has_more: hits.length >= max,\n }\n },\n\n async searchSpan(opts): Promise<SearchSpanResult> {\n const t = byId.get(opts.trace_id)\n const max = opts.max_matches ?? 50\n const span = (t?.spans ?? []).find((s) => s.span_id === opts.span_id)\n const hits = span\n ? searchSpanAttrs(span, opts.regex_pattern, budgets.perMatchTextBudget).slice(0, max)\n : []\n return {\n trace_id: opts.trace_id,\n span_id: opts.span_id,\n hits,\n total_matches: hits.length,\n has_more: false,\n }\n },\n }\n}\n\nfunction searchSpanAttrs(\n span: TraceAnalystSpan,\n pattern: string,\n textCap: number,\n): SpanMatchRecord[] {\n const re = new RegExp(pattern, 'g')\n const hits: SpanMatchRecord[] = []\n for (const [k, v] of Object.entries(span.attributes)) {\n const text = typeof v === 'string' ? v : JSON.stringify(v)\n if (typeof text !== 'string') continue\n re.lastIndex = 0\n const m = re.exec(text)\n if (!m) continue\n const at = m.index\n hits.push({\n trace_id: span.trace_id,\n span_id: span.span_id,\n span_name: span.name,\n span_kind: span.kind,\n attribute_path: `attributes.${k}`,\n matched_text: m[0].slice(0, textCap),\n context_before: text.slice(Math.max(0, at - textCap / 2), at),\n context_after: text.slice(at + m[0].length, at + m[0].length + textCap / 2),\n match_offset: at,\n })\n }\n return hits\n}\n","/**\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":";;;;;;;;AAiBA;AAAA,EAEE;AAAA,EAKA;AAAA,OASK;AAgBP,IAAM,UAAU,CAAC,MAAuB,OAAO,WAAW,KAAK,UAAU,CAAC,KAAK,IAAI,MAAM;AACzF,IAAM,MAAM,CAAC,OAAuB,IAAI,KAAK,EAAE,EAAE,YAAY;AAI7D,SAAS,mBAAmB,SAAyB;AACnD,SAAO,QACJ,QAAQ,mBAAmB,KAAK,EAChC,QAAQ,gFAAgF,MAAM,EAC9F,QAAQ,oBAAoB,MAAM,EAClC,QAAQ,8BAA8B,KAAK,EAC3C,QAAQ,YAAY,GAAG,EACvB,QAAQ,QAA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