@tangle-network/agent-runtime 0.33.0 → 0.34.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 CHANGED
@@ -86,7 +86,7 @@ sandbox ──── AgentProfile (substrate type), Sandbox.create, expo
86
86
  (provides the harness execution surface)
87
87
  ```
88
88
 
89
- Self-improving products consume all four. See [`agent-stack-adoption` skill](https://github.com/drewstone/dotfiles/blob/main/claude/skills/agent-stack-adoption/SKILL.md) for the end-to-end 10-phase adoption runbook.
89
+ Self-improving products consume all four. This package ships a self-contained adoption skill at [`skills/agent-runtime-adoption/SKILL.md`](./skills/agent-runtime-adoption/SKILL.md) driven loops, topology drivers (refine / fanout-vote / dynamic), the `loopDispatch` campaign bridge, MCP delegation, and identity-gated `optimizePrompt`; it needs only this package + `@tangle-network/agent-eval`. For the end-to-end self-improving pipeline (trace sink → analyst loop → scorecard → production loop → CI), see the broader `agent-eval-adoption` / `agent-stack-adoption` skills.
90
90
 
91
91
  ## Examples
92
92
 
@@ -42,6 +42,10 @@ function createDynamicDriver(options) {
42
42
  },
43
43
  decide() {
44
44
  return pending?.kind === "stop" ? "done" : "continue";
45
+ },
46
+ describePlan() {
47
+ if (!pending) return void 0;
48
+ return pending.rationale !== void 0 ? { kind: pending.kind, rationale: pending.rationale } : { kind: pending.kind };
45
49
  }
46
50
  };
47
51
  }
@@ -281,6 +285,12 @@ function safeJson(value) {
281
285
  }
282
286
  }
283
287
 
288
+ // src/loops/report-usage.ts
289
+ function reportLoopUsage(cost, result, source = "loop") {
290
+ cost.observe(result.costUsd, source);
291
+ cost.observeTokens({ input: result.tokenUsage.input, output: result.tokenUsage.output });
292
+ }
293
+
284
294
  // src/loops/run-loop.ts
285
295
  var DEFAULT_MAX_ITERATIONS = 10;
286
296
  var DEFAULT_MAX_CONCURRENCY = 4;
@@ -302,6 +312,7 @@ async function runLoop(options) {
302
312
  const loopStart = now();
303
313
  const driverName = options.driver.name ?? "driver";
304
314
  const iterations = [];
315
+ let round = 0;
305
316
  await emitTrace(options.ctx.traceEmitter, {
306
317
  kind: "loop.started",
307
318
  runId,
@@ -323,6 +334,19 @@ async function runLoop(options) {
323
334
  while (iterations.length < maxIterations) {
324
335
  if (controller.signal.aborted) throwAbort();
325
336
  const planned = await options.driver.plan(options.task, iterations);
337
+ const planDesc = options.driver.describePlan?.();
338
+ await emitTrace(options.ctx.traceEmitter, {
339
+ kind: "loop.plan",
340
+ runId,
341
+ timestamp: now(),
342
+ payload: {
343
+ roundIndex: round,
344
+ plannedCount: planned.length,
345
+ moveKind: planDesc?.kind ?? (planned.length === 0 ? "stop" : planned.length === 1 ? "refine" : "fanout"),
346
+ rationale: planDesc?.rationale
347
+ }
348
+ });
349
+ round += 1;
326
350
  if (planned.length === 0) break;
327
351
  const remaining = maxIterations - iterations.length;
328
352
  const slice = planned.slice(0, remaining);
@@ -477,7 +501,8 @@ async function executeIteration(args) {
477
501
  verdict: slot.verdict,
478
502
  error: slot.error?.message,
479
503
  costUsd: slot.costUsd,
480
- durationMs: slot.endedAt - slot.startedAt
504
+ durationMs: slot.endedAt - slot.startedAt,
505
+ tokenUsage: slot.tokenUsage.input || slot.tokenUsage.output ? { ...slot.tokenUsage } : void 0
481
506
  }
482
507
  });
483
508
  }
@@ -658,12 +683,6 @@ function hashJson(value) {
658
683
  return (h >>> 0).toString(16).padStart(8, "0");
659
684
  }
660
685
 
661
- // src/loops/report-usage.ts
662
- function reportLoopUsage(cost, result, source = "loop") {
663
- cost.observe(result.costUsd, source);
664
- cost.observeTokens({ input: result.tokenUsage.input, output: result.tokenUsage.output });
665
- }
666
-
667
686
  // src/loops/loop-dispatch.ts
668
687
  function campaignTraceToLoopEmitter(trace) {
669
688
  return {
@@ -704,9 +723,9 @@ export {
704
723
  createRefineDriver,
705
724
  refineWinnerIndex,
706
725
  createSandboxPlanner,
707
- runLoop,
708
726
  reportLoopUsage,
727
+ runLoop,
709
728
  loopDispatch,
710
729
  loopCampaignDispatch
711
730
  };
712
- //# sourceMappingURL=chunk-GLTUUKTN.js.map
731
+ //# sourceMappingURL=chunk-7KS6UEHB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/loops/drivers/dynamic.ts","../src/loops/drivers/refine.ts","../src/loops/drivers/sandbox-planner.ts","../src/loops/report-usage.ts","../src/loops/run-loop.ts","../src/loops/loop-dispatch.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Dynamic driver — the agent authors the loop topology at runtime.\n *\n * Where `refine` and `fanout-vote` encode a fixed shape as a pure function of\n * history, this driver delegates the per-round shape to an injected\n * `TopologyPlanner`. Each round the planner inspects the task + iteration\n * history and emits one `TopologyMove`:\n * - `refine` → one task next round (optionally rewritten from the prior attempt)\n * - `fanout` → N tasks next round (the kernel round-robins `agentRuns`, so a\n * 2-harness fanout dispatches branch 0 to harness A and branch 1 to harness B)\n * - `stop` → terminate; the kernel selects the winner across all iterations\n *\n * The planner is the brain; this driver is the structure. It maps moves onto\n * the kernel's `plan`/`decide` contract, enforces the iteration + fanout caps,\n * and fails loud on a malformed move. The planner is injected exactly like\n * `refine`'s `refineTask` and `fanout-vote`'s `selector` — so a test can drive\n * a deterministic policy through the real kernel, and production can wire it to\n * an LLM via `createSandboxPlanner`.\n *\n * Topology is orthogonal to harness: the planner never names a backend. Which\n * harness runs a branch is decided by the `AgentRunSpec` the kernel round-robins\n * to, so one dynamic driver works across claude-code, codex, opencode, pi —\n * including fanning a single round across several at once.\n */\n\nimport { PlannerError, ValidationError } from '../../errors'\nimport type { Driver, Iteration } from '../types'\n\n/** Terminal once `decide` returns `'done'` (a kernel terminal decision). */\nexport type DynamicDecision = 'continue' | 'done'\n\n/**\n * One topology decision for the next round. `fanout` carries explicit tasks\n * rather than a count so the planner can issue heterogeneous branches (a\n * different sub-task per harness); pass N copies of one task for a homogeneous\n * fanout that relies on `agentRuns` diversity instead.\n *\n * @experimental\n */\nexport type TopologyMove<Task> =\n | { kind: 'refine'; task: Task; rationale?: string }\n | { kind: 'fanout'; tasks: Task[]; rationale?: string }\n | { kind: 'stop'; rationale?: string }\n\n/** @experimental */\nexport interface PlannerContext<Task, Output> {\n /** The root task the loop was invoked with — stable across rounds. */\n task: Task\n /** Every iteration so far, in dispatch order, with outputs + verdicts. */\n history: ReadonlyArray<Iteration<Task, Output>>\n /** `history.length` — iterations already spent. */\n iterationsSpent: number\n /** Iterations left before the driver's `maxIterations` cap forces a stop. */\n iterationsRemaining: number\n}\n\n/**\n * Chooses the next topology move from the task + history. Sync or async; an\n * async planner is where an LLM call goes (see `createSandboxPlanner`).\n *\n * @experimental\n */\nexport type TopologyPlanner<Task, Output> = (\n ctx: PlannerContext<Task, Output>,\n) => TopologyMove<Task> | Promise<TopologyMove<Task>>\n\n/** @experimental */\nexport interface CreateDynamicDriverOptions<Task, Output> {\n /** The agent-authored topology policy. Invoked once per round in `plan`. */\n planner: TopologyPlanner<Task, Output>\n /**\n * Hard safety cap on total iterations. When reached, the driver stops before\n * consulting the planner. Default 8. Set the kernel's `runLoop`\n * `maxIterations >= ` this so the driver's cap governs and the loop closes on\n * a clean `'done'` rather than a truncated `'continue'`.\n */\n maxIterations?: number\n /** Max branches a single `fanout` move may dispatch. Default 4. */\n maxFanout?: number\n /** Stable identifier surfaced in trace events. Default `'dynamic'`. */\n name?: string\n}\n\n/** @experimental */\nexport function createDynamicDriver<Task, Output>(\n options: CreateDynamicDriverOptions<Task, Output>,\n): Driver<Task, Output, DynamicDecision> {\n if (typeof options.planner !== 'function') {\n throw new ValidationError('createDynamicDriver: planner must be a function')\n }\n const maxIterations = options.maxIterations ?? 8\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('createDynamicDriver: maxIterations must be > 0')\n }\n const maxFanout = options.maxFanout ?? 4\n if (!Number.isFinite(maxFanout) || maxFanout < 1) {\n throw new ValidationError('createDynamicDriver: maxFanout must be >= 1')\n }\n\n // The kernel calls plan(), runs the batch, then calls decide() — strictly\n // sequential, one driver instance per loop. Caching the move the planner\n // chose this round lets decide() report terminality without re-invoking the\n // planner (which would double every LLM call).\n let pending: TopologyMove<Task> | undefined\n\n return {\n name: options.name ?? 'dynamic',\n async plan(task, history) {\n if (history.length >= maxIterations) {\n pending = { kind: 'stop', rationale: `maxIterations (${maxIterations}) reached` }\n return []\n }\n const move = await options.planner({\n task,\n history,\n iterationsSpent: history.length,\n iterationsRemaining: maxIterations - history.length,\n })\n pending = validateMove(move, maxFanout)\n switch (pending.kind) {\n case 'refine':\n return [pending.task]\n case 'fanout':\n return pending.tasks\n case 'stop':\n return []\n }\n },\n decide() {\n // pending is set by the plan() call that immediately precedes every\n // decide(). Only a `stop` move terminates; refine/fanout keep looping so\n // plan() — and thus the planner — runs again next round.\n return pending?.kind === 'stop' ? 'done' : 'continue'\n },\n describePlan() {\n // Surface the move the planner just chose (kind + rationale) so the\n // kernel's loop.plan trace event carries the agent's intent, not just the\n // inferred fan-width. `pending` is the move set by the preceding plan().\n if (!pending) return undefined\n return pending.rationale !== undefined\n ? { kind: pending.kind, rationale: pending.rationale }\n : { kind: pending.kind }\n },\n }\n}\n\nfunction validateMove<Task>(move: TopologyMove<Task>, maxFanout: number): TopologyMove<Task> {\n if (!move || typeof move !== 'object' || typeof (move as { kind?: unknown }).kind !== 'string') {\n throw new PlannerError(`dynamic planner returned a non-move value: ${describe(move)}`)\n }\n switch (move.kind) {\n case 'refine':\n return move\n case 'stop':\n return move\n case 'fanout': {\n if (!Array.isArray(move.tasks) || move.tasks.length === 0) {\n throw new PlannerError('dynamic planner fanout move must carry a non-empty tasks[]')\n }\n if (move.tasks.length <= maxFanout) return move\n // Clamp rather than reject — over-fanning is a budget concern, not a\n // structural error. The clamp is recorded in the rationale for traces.\n return {\n kind: 'fanout',\n tasks: move.tasks.slice(0, maxFanout),\n rationale: `${move.rationale ?? ''} [clamped ${move.tasks.length}→${maxFanout}]`.trim(),\n }\n }\n default:\n throw new PlannerError(\n `dynamic planner returned unknown move kind: ${describe((move as { kind: unknown }).kind)}`,\n )\n }\n}\n\nfunction describe(value: unknown): string {\n try {\n return JSON.stringify(value) ?? String(value)\n } catch {\n return String(value)\n }\n}\n\n/**\n * Compact, planner-friendly view of iteration history — what an LLM planner\n * needs to choose the next move without the raw event streams. Output is\n * truncated so a long run's prompt stays bounded.\n *\n * @experimental\n */\nexport function summarizeHistory<Task, Output>(\n history: ReadonlyArray<Iteration<Task, Output>>,\n opts: { maxOutputChars?: number } = {},\n): Array<{\n index: number\n agentRunName: string\n valid?: boolean\n score?: number\n error?: string\n output?: string\n}> {\n const maxOutputChars = opts.maxOutputChars ?? 600\n return history.map((iter) => {\n const row: {\n index: number\n agentRunName: string\n valid?: boolean\n score?: number\n error?: string\n output?: string\n } = { index: iter.index, agentRunName: iter.agentRunName }\n if (iter.verdict) {\n row.valid = iter.verdict.valid\n if (typeof iter.verdict.score === 'number') row.score = iter.verdict.score\n }\n if (iter.error) row.error = iter.error.message\n if (iter.output !== undefined) {\n const serialized = describe(iter.output)\n row.output =\n serialized.length > maxOutputChars ? `${serialized.slice(0, maxOutputChars)}…` : serialized\n }\n return row\n })\n}\n","/**\n * @experimental\n *\n * Refine driver — single task per iteration, validator-gated.\n *\n * `plan` returns `[task]` (possibly transformed via `refineTask`) until the\n * prior verdict is valid OR the local cap is hit, then `[]`.\n * `decide` returns `'stop'` once the latest verdict is valid OR the cap is\n * reached. The kernel's `maxIterations` is an orthogonal safety cap;\n * whichever is lower wins.\n */\n\nimport { ValidationError } from '../../errors'\nimport type { DefaultVerdict, Driver, Iteration } from '../types'\n\nexport type RefineDecision = 'continue' | 'stop'\n\n/** @experimental */\nexport interface CreateRefineDriverOptions<Task> {\n /** Hard cap on iterations. Default 5. */\n maxIterations?: number\n /**\n * Optional task transform applied each round based on the prior verdict.\n * When omitted, the same task is replayed and the agent is expected to\n * inspect the sandbox session state for prior attempts.\n */\n refineTask?: (task: Task, prior: DefaultVerdict) => Task\n /** Stable identifier surfaced in trace events. Default `'refine'`. */\n name?: string\n}\n\n/** @experimental */\nexport function createRefineDriver<Task, Output>(\n options: CreateRefineDriverOptions<Task> = {},\n): Driver<Task, Output, RefineDecision> {\n const maxIterations = options.maxIterations ?? 5\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('createRefineDriver: maxIterations must be > 0')\n }\n const refineTask = options.refineTask\n return {\n name: options.name ?? 'refine',\n async plan(task, history) {\n if (history.length >= maxIterations) return []\n if (history.length === 0) return [task]\n const prior = history.at(-1)\n if (!prior) return [task]\n if (prior.verdict?.valid === true) return []\n // Worker error: replay the same task so the agent can self-correct.\n // The driver has no signal beyond `verdict`; only the validator\n // controls \"good enough\".\n if (!refineTask || !prior.verdict) return [prior.task]\n return [refineTask(prior.task, prior.verdict)]\n },\n decide(history) {\n const last = history.at(-1)\n if (!last) return 'continue'\n if (last.verdict?.valid === true) return 'stop'\n if (history.length >= maxIterations) return 'stop'\n return 'continue'\n },\n }\n}\n\n/**\n * Test helper: select the last-valid iteration (or the last attempt if\n * none passed). Mirrors the kernel's default selector ordering for refine\n * topologies — the most recent successful attempt wins.\n *\n * @experimental\n */\nexport function refineWinnerIndex<Task, Output>(\n iterations: ReadonlyArray<Iteration<Task, Output>>,\n): number | undefined {\n for (let i = iterations.length - 1; i >= 0; i -= 1) {\n if (iterations[i]?.verdict?.valid) return i\n }\n return iterations.length > 0 ? iterations.length - 1 : undefined\n}\n","/**\n * @experimental\n *\n * `createSandboxPlanner` — wire the dynamic driver's `TopologyPlanner` to a\n * real agent. Each round it spins a sandbox on `profile`, streams a prompt that\n * carries the history summary, and decodes the agent's chosen `TopologyMove`\n * from a JSON envelope it emits. This is the \"agent authors its own loop\n * topology\" path: the planner profile can be any harness (claude-code, codex,\n * opencode, pi) — its only job is to read what happened and emit the next move.\n *\n * The planner profile is deliberately distinct from the worker `agentRuns`: a\n * cheap fast model can steer topology while expensive workers do the labor, and\n * the planner never names which harness runs a branch — the kernel's\n * `agentRuns` round-robin decides that.\n *\n * Envelope contract the agent must emit (fenced ```json or a structured\n * `result`/`final` event payload):\n * { \"kind\": \"refine\" | \"fanout\" | \"stop\",\n * \"tasks\"?: [ <task>, ... ], // decoded via `decodeTask`\n * \"n\"?: number, // fanout shorthand: N copies of the root task\n * \"rationale\"?: string }\n *\n * A missing / unparseable / unknown-kind envelope throws `PlannerError` — the\n * loop never silently runs a topology the agent did not choose.\n */\n\nimport type {\n AgentProfile,\n CreateSandboxOptions,\n SandboxEvent,\n} from '@tangle-network/sandbox'\nimport { PlannerError, ValidationError } from '../../errors'\nimport type { AgentRunSpec, LoopSandboxClient } from '../types'\nimport type { PlannerContext, TopologyMove, TopologyPlanner } from './dynamic'\nimport { summarizeHistory } from './dynamic'\n\n/** Raw, pre-decode envelope an agent emits to choose the next move. */\nexport interface TopologyMoveEnvelope {\n kind: string\n tasks?: unknown[]\n n?: number\n rationale?: string\n}\n\n/** @experimental */\nexport interface CreateSandboxPlannerOptions<Task, Output> {\n /** Sandbox client — the planner calls `.create()` once per round. */\n client: LoopSandboxClient\n /** The planner agent. Steers topology; does not run the work. */\n profile: AgentProfile\n /**\n * Decode one raw task from the envelope's `tasks[]` into a domain `Task`.\n * Required because `Task` is opaque to this module — only the caller knows\n * its shape. Throw to reject a malformed task; the error surfaces as a\n * `PlannerError`.\n */\n decodeTask: (raw: unknown, ctx: PlannerContext<Task, Output>) => Task\n /** Override the default prompt (history summary + envelope contract). */\n buildPrompt?: (ctx: PlannerContext<Task, Output>) => string\n /** Override envelope extraction from the event stream. */\n parseEnvelope?: (events: SandboxEvent[]) => TopologyMoveEnvelope | undefined\n /** Sandbox overrides for the planner sandbox (timeouts, env, etc.). */\n sandboxOverrides?: AgentRunSpec<Task>['sandboxOverrides']\n /** Cancellation for the planner's own LLM call. */\n signal?: AbortSignal\n}\n\n/** @experimental */\nexport function createSandboxPlanner<Task, Output>(\n opts: CreateSandboxPlannerOptions<Task, Output>,\n): TopologyPlanner<Task, Output> {\n if (!opts.client || typeof opts.client.create !== 'function') {\n throw new ValidationError('createSandboxPlanner: client.create is required')\n }\n if (typeof opts.decodeTask !== 'function') {\n throw new ValidationError('createSandboxPlanner: decodeTask is required')\n }\n const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt\n const parseEnvelope = opts.parseEnvelope ?? defaultParseEnvelope\n\n return async (ctx) => {\n const box = await opts.client.create(buildSandboxOptions(opts.profile, opts.sandboxOverrides))\n const events: SandboxEvent[] = []\n for await (const event of box.streamPrompt(buildPrompt(ctx), { signal: opts.signal })) {\n events.push(event)\n }\n const envelope = parseEnvelope(events)\n if (!envelope) {\n throw new PlannerError('sandbox planner emitted no parseable topology-move envelope')\n }\n return envelopeToMove(envelope, ctx, opts.decodeTask)\n }\n}\n\nfunction envelopeToMove<Task, Output>(\n envelope: TopologyMoveEnvelope,\n ctx: PlannerContext<Task, Output>,\n decodeTask: (raw: unknown, ctx: PlannerContext<Task, Output>) => Task,\n): TopologyMove<Task> {\n const kind = String(envelope.kind ?? '').toLowerCase()\n const rationale = typeof envelope.rationale === 'string' ? envelope.rationale : undefined\n if (kind === 'stop') {\n return { kind: 'stop', rationale }\n }\n if (kind === 'refine') {\n const raw = Array.isArray(envelope.tasks) ? envelope.tasks[0] : undefined\n // No new task → replay the root task; the worker self-corrects from its\n // own prior attempt in sandbox state, mirroring the refine driver default.\n const task = raw === undefined ? ctx.task : decodeTaskGuarded(decodeTask, raw, ctx)\n return { kind: 'refine', task, rationale }\n }\n if (kind === 'fanout') {\n const tasks = resolveFanoutTasks(envelope, ctx, decodeTask)\n return { kind: 'fanout', tasks, rationale }\n }\n throw new PlannerError(`sandbox planner emitted unknown move kind: ${JSON.stringify(envelope.kind)}`)\n}\n\nfunction resolveFanoutTasks<Task, Output>(\n envelope: TopologyMoveEnvelope,\n ctx: PlannerContext<Task, Output>,\n decodeTask: (raw: unknown, ctx: PlannerContext<Task, Output>) => Task,\n): Task[] {\n if (Array.isArray(envelope.tasks) && envelope.tasks.length > 0) {\n return envelope.tasks.map((raw) => decodeTaskGuarded(decodeTask, raw, ctx))\n }\n // `n` shorthand: N copies of the root task, leaning on `agentRuns` diversity.\n if (typeof envelope.n === 'number' && Number.isFinite(envelope.n) && envelope.n >= 1) {\n return Array.from({ length: Math.floor(envelope.n) }, () => ctx.task)\n }\n throw new PlannerError('sandbox planner fanout envelope needs a non-empty tasks[] or n >= 1')\n}\n\nfunction decodeTaskGuarded<Task, Output>(\n decodeTask: (raw: unknown, ctx: PlannerContext<Task, Output>) => Task,\n raw: unknown,\n ctx: PlannerContext<Task, Output>,\n): Task {\n try {\n return decodeTask(raw, ctx)\n } catch (err) {\n throw new PlannerError(`sandbox planner decodeTask rejected ${JSON.stringify(raw)}`, {\n cause: err,\n })\n }\n}\n\nfunction buildSandboxOptions(\n profile: AgentProfile,\n overrides: AgentRunSpec<unknown>['sandboxOverrides'],\n): CreateSandboxOptions {\n const base = overrides ?? {}\n const overrideBackend = base.backend\n const explicitType = profile.metadata?.backendType\n type BackendType = NonNullable<CreateSandboxOptions['backend']>['type']\n return {\n ...base,\n backend: {\n type: (overrideBackend?.type ?? explicitType ?? 'opencode') as BackendType,\n profile,\n ...(overrideBackend?.model ? { model: overrideBackend.model } : {}),\n ...(overrideBackend?.server ? { server: overrideBackend.server } : {}),\n },\n }\n}\n\nfunction defaultBuildPrompt<Task, Output>(ctx: PlannerContext<Task, Output>): string {\n const summary = summarizeHistory(ctx.history)\n return [\n 'You are the loop planner. You do not do the work — you decide the topology of the next round.',\n '',\n `Root task:\\n${safeJson(ctx.task)}`,\n '',\n `Iterations spent: ${ctx.iterationsSpent}. Remaining before the hard cap: ${ctx.iterationsRemaining}.`,\n '',\n ctx.history.length === 0\n ? 'No attempts yet.'\n : `Attempts so far (index, agent, verdict, output):\\n${safeJson(summary)}`,\n '',\n 'Choose ONE move and emit it as a fenced JSON block:',\n ' - {\"kind\":\"refine\",\"tasks\":[<task>],\"rationale\":\"...\"} — one more attempt; omit tasks to replay the root task.',\n ' - {\"kind\":\"fanout\",\"tasks\":[<task>,<task>],\"rationale\":\"...\"} — N parallel branches (or \"n\": N for N copies of the root task).',\n ' - {\"kind\":\"stop\",\"rationale\":\"...\"} — a valid result exists or further attempts will not help.',\n '',\n 'Stop as soon as an attempt is valid. Prefer refine when an attempt is close; fan out when attempts disagree or the approach is uncertain.',\n 'Emit ONLY the JSON block.',\n ].join('\\n')\n}\n\nfunction defaultParseEnvelope(events: SandboxEvent[]): TopologyMoveEnvelope | undefined {\n // Structured payload on a terminal event wins — sandbox SDKs lift emitted\n // JSON onto data.result / data.output / data of a result|final event.\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const type = String(event.type ?? '')\n const data = isRecord(event.data) ? event.data : undefined\n if (!data) continue\n if (type === 'result' || type === 'final' || type === 'planner.move') {\n const direct = coerceEnvelope(data.result ?? data.output ?? data)\n if (direct) return direct\n }\n }\n // Fall back to a fenced JSON block in the most recent text delta.\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n if (!event) continue\n const data = isRecord(event.data) ? event.data : undefined\n if (!data) continue\n const text = pickString(data.text) ?? pickString(data.delta) ?? pickString(data.content)\n if (!text) continue\n const fenced = extractFencedJson(text)\n const coerced = coerceEnvelope(fenced)\n if (coerced) return coerced\n }\n return undefined\n}\n\nfunction coerceEnvelope(value: unknown): TopologyMoveEnvelope | undefined {\n if (!isRecord(value)) return undefined\n if (typeof value.kind !== 'string' || value.kind.length === 0) return undefined\n const out: TopologyMoveEnvelope = { kind: value.kind }\n if (Array.isArray(value.tasks)) out.tasks = value.tasks\n if (typeof value.n === 'number') out.n = value.n\n if (typeof value.rationale === 'string') out.rationale = value.rationale\n return out\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction pickString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nfunction extractFencedJson(text: string): unknown | undefined {\n const match = text.match(/```(?:json)?\\s*([\\s\\S]*?)```/i)\n const body = (match?.[1] ?? text).trim()\n if (!body) return undefined\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n\nfunction safeJson(value: unknown): string {\n try {\n return JSON.stringify(value, null, 2) ?? String(value)\n } catch {\n return String(value)\n }\n}\n","/**\n * Bridge a finished `runLoop` into an agent-eval campaign / profile-matrix\n * dispatch.\n *\n * `runProfileMatrix` (and `runCampaign`) run the backend-integrity guard over\n * the token usage a dispatch reports through `ctx.cost`. A dispatch that wraps\n * `runLoop` must forward the loop's cost AND token usage, or the guard reads\n * the run as a stub and throws. `reportLoopUsage` is that one line:\n *\n * const dispatch: ProfileDispatchFn<S, A> = async (profile, scenario, ctx) => {\n * const result = await runLoop({ ...optsFor(profile, scenario), ctx: loopCtx })\n * reportLoopUsage(ctx, result)\n * return result.winner?.output as A\n * }\n *\n * Typed structurally against the campaign `DispatchContext.cost` so this module\n * stays free of an agent-eval import — it works with any cost meter exposing\n * `observe` + `observeTokens`.\n */\n\nimport type { LoopResult } from './types'\n\n/** The slice of an agent-eval campaign `DispatchContext.cost` this needs. */\nexport interface UsageSink {\n observe(amountUsd: number, source: string): void\n observeTokens(usage: { input: number; output: number }): void\n}\n\n/**\n * Forward a `LoopResult`'s aggregated cost + token usage into a campaign cost\n * meter so the backend-integrity guard sees real LLM activity. `source`\n * defaults to `'loop'`.\n */\nexport function reportLoopUsage<Task, Output, Decision>(\n cost: UsageSink,\n result: Pick<LoopResult<Task, Output, Decision>, 'costUsd' | 'tokenUsage'>,\n source = 'loop',\n): void {\n cost.observe(result.costUsd, source)\n cost.observeTokens({ input: result.tokenUsage.input, output: result.tokenUsage.output })\n}\n","/**\n * @experimental\n *\n * `runLoop` — the topology-agnostic kernel built atop the sandbox SDK.\n *\n * Each iteration:\n * 1. `driver.plan(task, history)` → N tasks (1 = refine, N = fanout, 0 = stop)\n * 2. For each task (parallel, bounded by `maxConcurrency`):\n * a. round-robin an `AgentRunSpec` from `agentRuns`\n * b. `sandboxClient.create({ backend: { profile }, ...overrides })`\n * c. emit `loop.iteration.dispatch` with the placement\n * (`{ sibling, sandboxId }` or `{ fleet, fleetId, machineId, sandboxId }`)\n * d. iterate `box.streamPrompt(taskToPrompt(task))` and collect events\n * 3. `output.parse(events)` → typed `Output`\n * 4. `validator?.validate(output)` → `DefaultVerdict`\n * 5. Append `Iteration` to history; emit `loop.iteration.ended`\n * 6. `driver.decide(history)` → if terminal, return result + winner\n *\n * The kernel owns: iteration accounting, per-iteration timing, error\n * capture, abort propagation, concurrency cap, cost aggregation, and trace\n * emission. The kernel does NOT own: what the agent runs (sandbox SDK +\n * profile), how outputs are decoded (output adapter), how outputs are\n * scored (validator), or topology (driver).\n */\n\nimport type {\n AgentProfile,\n CreateSandboxOptions,\n SandboxEvent,\n SandboxInstance,\n} from '@tangle-network/sandbox'\nimport { ValidationError } from '../errors'\nimport type { RuntimeStreamEvent } from '../types'\nimport type {\n AgentRunSpec,\n Driver,\n ExecCtx,\n Iteration,\n LoopResult,\n LoopSandboxClient,\n LoopSandboxPlacement,\n LoopTraceEmitter,\n LoopTraceEvent,\n LoopWinner,\n OutputAdapter,\n Validator,\n} from './types'\n\nconst DEFAULT_MAX_ITERATIONS = 10\nconst DEFAULT_MAX_CONCURRENCY = 4\n\n/** @experimental */\nexport interface RunLoopOptions<Task, Output, Decision> {\n driver: Driver<Task, Output, Decision>\n /**\n * Single agent spec — every iteration uses this profile. Mutually\n * exclusive with `agentRuns`.\n */\n agentRun?: AgentRunSpec<Task>\n /**\n * Multiple specs for heterogeneous fanout. The kernel round-robins\n * through them when the driver plans N tasks. Mutually exclusive with\n * `agentRun`.\n */\n agentRuns?: AgentRunSpec<Task>[]\n output: OutputAdapter<Output>\n validator?: Validator<Output>\n task: Task\n ctx: ExecCtx\n /** Default 10. Hard cap on total iterations across all `plan()` rounds. */\n maxIterations?: number\n /** Default 4. In-flight worker cap within a single `plan()` batch. */\n maxConcurrency?: number\n /**\n * Pre-allocated id for trace correlation. Default = `loop-${random}`.\n * Surfaces as `runId` on every emitted `LoopTraceEvent`.\n */\n runId?: string\n /**\n * Clock override; default `Date.now`. Deterministic tests pass a\n * monotonic counter to stabilize iteration timing fields.\n */\n now?: () => number\n /**\n * Override the default winner selector (highest-valid-score, ties broken\n * by earliest iteration).\n */\n selectWinner?: (iterations: Iteration<Task, Output>[]) => LoopWinner<Task, Output> | undefined\n}\n\n/** @experimental */\nexport async function runLoop<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n): Promise<LoopResult<Task, Output, Decision>> {\n const specs = resolveAgentRuns(options)\n const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS\n if (!Number.isFinite(maxIterations) || maxIterations <= 0) {\n throw new ValidationError('runLoop: maxIterations must be > 0')\n }\n const maxConcurrency = options.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY\n if (!Number.isFinite(maxConcurrency) || maxConcurrency <= 0) {\n throw new ValidationError('runLoop: maxConcurrency must be > 0')\n }\n if (!options.ctx?.sandboxClient || typeof options.ctx.sandboxClient.create !== 'function') {\n throw new ValidationError('runLoop: ctx.sandboxClient.create is required')\n }\n const now = options.now ?? Date.now\n const runId = options.runId ?? `loop-${randomSuffix()}`\n const loopStart = now()\n const driverName = options.driver.name ?? 'driver'\n const iterations: Iteration<Task, Output>[] = []\n let round = 0\n\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.started',\n runId,\n timestamp: now(),\n payload: {\n driver: driverName,\n agentRunNames: specs.map((spec) => spec.name ?? spec.profile.name ?? 'agent'),\n maxIterations,\n maxConcurrency,\n },\n })\n\n const controller = new AbortController()\n const onOuterAbort = () => controller.abort()\n if (options.ctx.signal) {\n if (options.ctx.signal.aborted) controller.abort()\n else options.ctx.signal.addEventListener('abort', onOuterAbort, { once: true })\n }\n\n try {\n while (iterations.length < maxIterations) {\n if (controller.signal.aborted) throwAbort()\n const planned = await options.driver.plan(options.task, iterations)\n const planDesc = options.driver.describePlan?.()\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.plan',\n runId,\n timestamp: now(),\n payload: {\n roundIndex: round,\n plannedCount: planned.length,\n moveKind:\n planDesc?.kind ??\n (planned.length === 0 ? 'stop' : planned.length === 1 ? 'refine' : 'fanout'),\n rationale: planDesc?.rationale,\n },\n })\n round += 1\n if (planned.length === 0) break\n\n const remaining = maxIterations - iterations.length\n const slice = planned.slice(0, remaining)\n const baseIndex = iterations.length\n // Reserve slots up front so concurrent workers may mutate by index.\n for (let i = 0; i < slice.length; i += 1) {\n const spec = specs[(baseIndex + i) % specs.length]!\n iterations.push({\n index: baseIndex + i,\n task: slice[i] as Task,\n agentRunName: spec.name ?? spec.profile.name ?? 'agent',\n events: [],\n startedAt: now(),\n endedAt: 0,\n costUsd: 0,\n tokenUsage: { input: 0, output: 0 },\n })\n }\n\n await runBatch({\n slice,\n baseIndex,\n iterations,\n specs,\n output: options.output,\n validator: options.validator,\n maxConcurrency,\n signal: controller.signal,\n ctx: options.ctx,\n runId,\n now,\n })\n\n if (controller.signal.aborted) throwAbort()\n\n const decision = await options.driver.decide(iterations)\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: serializeDecision(decision), historyLength: iterations.length },\n })\n if (isTerminalDecision(decision)) {\n return finalize({\n options,\n decision,\n iterations,\n startMs: loopStart,\n now,\n runId,\n })\n }\n }\n\n if (iterations.length >= maxIterations) {\n // Cap reached without a terminal decision — ask the driver one more time\n // for its final state, then close out.\n const decision = await options.driver.decide(iterations)\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: serializeDecision(decision), historyLength: iterations.length },\n })\n return finalize({ options, decision, iterations, startMs: loopStart, now, runId })\n }\n // `plan()` returned `[]` before `decide()` reached a terminal state.\n const decision = await options.driver.decide(iterations)\n await emitTrace(options.ctx.traceEmitter, {\n kind: 'loop.decision',\n runId,\n timestamp: now(),\n payload: { decision: serializeDecision(decision), historyLength: iterations.length },\n })\n return finalize({ options, decision, iterations, startMs: loopStart, now, runId })\n } finally {\n if (options.ctx.signal) options.ctx.signal.removeEventListener('abort', onOuterAbort)\n }\n}\n\ninterface RunBatchArgs<Task, Output> {\n slice: Task[]\n baseIndex: number\n iterations: Iteration<Task, Output>[]\n specs: AgentRunSpec<Task>[]\n output: OutputAdapter<Output>\n validator: Validator<Output> | undefined\n maxConcurrency: number\n signal: AbortSignal\n ctx: ExecCtx\n runId: string\n now: () => number\n}\n\nasync function runBatch<Task, Output>(args: RunBatchArgs<Task, Output>) {\n const queue = args.slice.map((task, offset) => ({ task, index: args.baseIndex + offset }))\n const inflight = new Set<Promise<void>>()\n while (queue.length > 0 || inflight.size > 0) {\n while (inflight.size < args.maxConcurrency && queue.length > 0) {\n const item = queue.shift()!\n const p = executeIteration({ ...args, item }).finally(() => inflight.delete(p))\n inflight.add(p)\n }\n if (inflight.size === 0) break\n await Promise.race(inflight)\n }\n}\n\ninterface ExecuteIterationArgs<Task, Output> extends RunBatchArgs<Task, Output> {\n item: { task: Task; index: number }\n}\n\nasync function executeIteration<Task, Output>(args: ExecuteIterationArgs<Task, Output>) {\n const slot = args.iterations[args.item.index]\n if (!slot)\n throw new ValidationError(`runLoop: missing iteration slot at index ${args.item.index}`)\n const spec = args.specs[args.item.index % args.specs.length]\n if (!spec) throw new ValidationError('runLoop: no AgentRunSpec available for iteration')\n slot.startedAt = args.now()\n slot.agentRunName = spec.name ?? spec.profile.name ?? 'agent'\n\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.started',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n taskHash: hashJson(args.item.task),\n },\n })\n\n try {\n const box = await createSandboxForSpec(args.ctx.sandboxClient, spec, args.signal)\n const placement = describePlacementSafe(args.ctx.sandboxClient, box)\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.dispatch',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n placement: placement.kind,\n sandboxId: placement.sandboxId,\n fleetId: placement.fleetId,\n machineId: placement.machineId,\n },\n })\n const message = spec.taskToPrompt(args.item.task)\n const events: SandboxEvent[] = []\n for await (const event of box.streamPrompt(message, { signal: args.signal })) {\n events.push(event)\n const llmCall = extractLlmCallEvent(event, slot.agentRunName)\n if (llmCall) {\n slot.costUsd += llmCall.costUsd ?? 0\n slot.tokenUsage.input += llmCall.tokensIn ?? 0\n slot.tokenUsage.output += llmCall.tokensOut ?? 0\n args.ctx.runHandle?.observe(llmCall)\n }\n }\n slot.events = events\n slot.output = args.output.parse(events)\n if (args.validator) {\n slot.verdict = await args.validator.validate(slot.output, {\n iteration: args.item.index,\n signal: args.signal,\n traceEmitter: args.ctx.traceEmitter,\n })\n }\n } catch (err) {\n slot.error = err instanceof Error ? err : new Error(String(err))\n } finally {\n slot.endedAt = args.now()\n await emitTrace(args.ctx.traceEmitter, {\n kind: 'loop.iteration.ended',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n iterationIndex: args.item.index,\n agentRunName: slot.agentRunName,\n outputHash: slot.output !== undefined ? hashJson(slot.output) : undefined,\n verdict: slot.verdict,\n error: slot.error?.message,\n costUsd: slot.costUsd,\n durationMs: slot.endedAt - slot.startedAt,\n tokenUsage:\n slot.tokenUsage.input || slot.tokenUsage.output ? { ...slot.tokenUsage } : undefined,\n },\n })\n }\n}\n\nfunction describePlacementSafe(\n client: LoopSandboxClient,\n box: SandboxInstance,\n): LoopSandboxPlacement {\n if (typeof client.describePlacement === 'function') {\n try {\n const result = client.describePlacement(box)\n if (\n result &&\n typeof result === 'object' &&\n (result.kind === 'sibling' || result.kind === 'fleet')\n ) {\n return {\n kind: result.kind,\n sandboxId: result.sandboxId ?? readSandboxId(box),\n fleetId: result.fleetId,\n machineId: result.machineId,\n }\n }\n } catch {\n // Adapter bug must not corrupt the iteration; fall through to default.\n }\n }\n return { kind: 'sibling', sandboxId: readSandboxId(box) }\n}\n\nfunction readSandboxId(box: SandboxInstance): string | undefined {\n const raw = (box as unknown as { id?: unknown }).id\n return typeof raw === 'string' && raw.length > 0 ? raw : undefined\n}\n\nasync function createSandboxForSpec<Task>(\n client: LoopSandboxClient,\n spec: AgentRunSpec<Task>,\n signal: AbortSignal,\n): Promise<SandboxInstance> {\n const overrides = spec.sandboxOverrides ?? {}\n const overrideBackend = overrides.backend\n const opts: CreateSandboxOptions = {\n ...overrides,\n backend: {\n type: overrideBackend?.type ?? inferBackendType(spec.profile),\n profile: spec.profile satisfies AgentProfile,\n ...(overrideBackend?.model ? { model: overrideBackend.model } : {}),\n ...(overrideBackend?.server ? { server: overrideBackend.server } : {}),\n },\n }\n // Cooperative cancellation: if the abort signal fires while .create is\n // pending, the promise itself is not abortable but the inflight prompt is.\n if (signal.aborted) throwAbort()\n return client.create(opts)\n}\n\nfunction inferBackendType(\n profile: AgentProfile,\n): CreateSandboxOptions['backend'] extends infer B\n ? B extends { type: infer T }\n ? T\n : never\n : never {\n // The sandbox SDK accepts profile-driven backend selection by name. When the\n // profile has no explicit hint we fall through to the SDK's default\n // ('opencode' on the platform side). Returning a literal here would lie\n // about provenance — let the SDK pick.\n type BackendType = NonNullable<CreateSandboxOptions['backend']>['type']\n const explicit = profile.metadata?.backendType\n if (typeof explicit === 'string') return explicit as BackendType\n return 'opencode' as BackendType\n}\n\ninterface FinalizeArgs<Task, Output, Decision> {\n options: RunLoopOptions<Task, Output, Decision>\n decision: Decision\n iterations: Iteration<Task, Output>[]\n startMs: number\n now: () => number\n runId: string\n}\n\nfunction finalize<Task, Output, Decision>(\n args: FinalizeArgs<Task, Output, Decision>,\n): LoopResult<Task, Output, Decision> {\n const winner = (args.options.selectWinner ?? defaultSelectWinner)(args.iterations)\n const costUsd = args.iterations.reduce((sum, iter) => sum + (iter.costUsd || 0), 0)\n const tokenUsage = args.iterations.reduce(\n (acc, iter) => {\n acc.input += iter.tokenUsage?.input ?? 0\n acc.output += iter.tokenUsage?.output ?? 0\n return acc\n },\n { input: 0, output: 0 },\n )\n const result: LoopResult<Task, Output, Decision> = {\n decision: args.decision,\n iterations: args.iterations,\n winner,\n durationMs: args.now() - args.startMs,\n costUsd,\n tokenUsage,\n }\n void emitTrace(args.options.ctx.traceEmitter, {\n kind: 'loop.ended',\n runId: args.runId,\n timestamp: args.now(),\n payload: {\n winnerIterationIndex: winner?.iterationIndex,\n totalCostUsd: costUsd,\n durationMs: result.durationMs,\n iterations: args.iterations.length,\n },\n })\n return result\n}\n\nfunction defaultSelectWinner<Task, Output>(\n iterations: Iteration<Task, Output>[],\n): LoopWinner<Task, Output> | undefined {\n const candidates = iterations.filter((iter) => iter.output !== undefined && !iter.error)\n if (candidates.length === 0) return undefined\n const valid = candidates.filter((iter) => iter.verdict?.valid === true)\n const pool = valid.length > 0 ? valid : candidates\n const sorted = [...pool].sort(\n (a, b) => (b.verdict?.score ?? 0) - (a.verdict?.score ?? 0) || a.index - b.index,\n )\n const top = sorted[0]\n if (!top || top.output === undefined) return undefined\n return {\n task: top.task,\n output: top.output,\n verdict: top.verdict,\n iterationIndex: top.index,\n agentRunName: top.agentRunName,\n }\n}\n\nfunction resolveAgentRuns<Task, Output, Decision>(\n options: RunLoopOptions<Task, Output, Decision>,\n): AgentRunSpec<Task>[] {\n if (options.agentRun && options.agentRuns) {\n throw new ValidationError('runLoop: pass exactly one of `agentRun` or `agentRuns`')\n }\n if (options.agentRun) return [options.agentRun]\n if (options.agentRuns && options.agentRuns.length > 0) return options.agentRuns\n throw new ValidationError('runLoop: `agentRun` or non-empty `agentRuns` is required')\n}\n\nfunction isTerminalDecision(decision: unknown): boolean {\n return (\n decision === 'stop' || decision === 'pick-winner' || decision === 'fail' || decision === 'done'\n )\n}\n\nfunction serializeDecision(decision: unknown): string {\n if (typeof decision === 'string') return decision\n if (decision === null || decision === undefined) return 'null'\n try {\n return JSON.stringify(decision)\n } catch {\n return String(decision)\n }\n}\n\nasync function emitTrace(\n emitter: LoopTraceEmitter | undefined,\n event: LoopTraceEvent,\n): Promise<void> {\n if (!emitter) return\n await emitter.emit(event)\n}\n\nfunction randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n\nfunction throwAbort(): never {\n const err = new Error('aborted')\n err.name = 'AbortError'\n throw err\n}\n\n/**\n * Extract a `RuntimeStreamEvent`-shaped `llm_call` from a sandbox event when\n * the event carries usage/cost data. Returns `undefined` for non-cost events\n * so the kernel can iterate the full stream without branching.\n *\n * Sandbox SDK emits a polymorphic `SandboxEvent = { type, data, id? }`. The\n * canonical cost-carrying types observed in the wild:\n * - `llm_call` — `data: { model, tokensIn, tokensOut, costUsd, ... }`\n * - `message.completed` / `result` — `data: { usage: { inputTokens,\n * outputTokens, totalCostUsd? } }`\n * - `cost.usage` — same shape under a dedicated type\n *\n * Numeric coercion is strict: `Number.isFinite` gates every accumulator\n * write so a sentinel `NaN` from a misbehaving backend cannot poison the\n * ledger.\n */\nfunction extractLlmCallEvent(\n event: SandboxEvent,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n if (!event || typeof event !== 'object') return undefined\n const type = String(event.type ?? '')\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n\n if (type === 'llm_call' || type === 'cost.usage' || type === 'usage') {\n return buildLlmCall(data, agentRunName)\n }\n if (type === 'message.completed' || type === 'result' || type === 'final') {\n const usage = data.usage as Record<string, unknown> | undefined\n if (!usage || typeof usage !== 'object') return undefined\n return buildLlmCall({ ...usage, model: data.model ?? usage.model }, agentRunName)\n }\n return undefined\n}\n\nfunction buildLlmCall(\n data: Record<string, unknown>,\n agentRunName: string,\n): (RuntimeStreamEvent & { type: 'llm_call' }) | undefined {\n const tokensIn = pickFiniteNumber(data, ['tokensIn', 'inputTokens', 'prompt_tokens'])\n const tokensOut = pickFiniteNumber(data, ['tokensOut', 'outputTokens', 'completion_tokens'])\n const costUsd = pickFiniteNumber(data, ['costUsd', 'totalCostUsd', 'cost_usd', 'cost'])\n if (tokensIn === undefined && tokensOut === undefined && costUsd === undefined) {\n return undefined\n }\n const model = typeof data.model === 'string' && data.model.length > 0 ? data.model : agentRunName\n const event: RuntimeStreamEvent & { type: 'llm_call' } = {\n type: 'llm_call',\n model,\n }\n if (tokensIn !== undefined) event.tokensIn = tokensIn\n if (tokensOut !== undefined) event.tokensOut = tokensOut\n if (costUsd !== undefined) event.costUsd = costUsd\n return event\n}\n\nfunction pickFiniteNumber(data: Record<string, unknown>, keys: string[]): number | undefined {\n for (const key of keys) {\n const value = data[key]\n if (typeof value === 'number' && Number.isFinite(value)) return value\n }\n return undefined\n}\n\n/**\n * Stable hash for the trace payload. Not cryptographic — only used so\n * downstream eval pipelines can group iterations whose task / output is the\n * same. Bare structural hash; non-JSON values stringify via their `toString`.\n */\nfunction hashJson(value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n // FNV-1a 32-bit — branch-free, dependency-free, good enough for grouping.\n let h = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n h ^= str.charCodeAt(i)\n h = Math.imul(h, 0x01000193)\n }\n return (h >>> 0).toString(16).padStart(8, '0')\n}\n","/**\n * `loopDispatch` — turn `runLoop` into an agent-eval campaign dispatch.\n *\n * Without this adapter a consumer wiring `runLoop` into `runProfileMatrix` /\n * `runCampaign` has to, by hand, every time: (a) build an `ExecCtx` with a\n * sandbox client, (b) adapt the campaign `DispatchContext.trace` into a\n * `LoopTraceEmitter` (or lose all loop trace correlation), and (c) remember to\n * forward the loop's cost + tokens via `ctx.cost` (forgetting it yields a\n * `{0,0}` cell the backend-integrity guard reads as a stub). Three foot-guns,\n * the third silent. The fleet's products skipped (c) and fell back to a\n * `workerRecords[]` side-channel — the exact anti-pattern the substrate exists\n * to kill.\n *\n * `loopDispatch` collapses all three into one typed call:\n *\n * const dispatch = loopDispatch({\n * sandboxClient,\n * toLoopOptions: (scenario, profile) => ({ driver, agentRun, output, validator, task }),\n * })\n * await runProfileMatrix({ profiles, scenarios, dispatch, judges, commitSha })\n *\n * Usage is reported automatically; trace events are forwarded automatically;\n * the ctx is built automatically. The seam becomes impossible to mis-wire.\n *\n * Typed structurally against the campaign `DispatchContext` (imported type-only\n * from `@tangle-network/agent-eval/campaign`) — a downward dependency, never an\n * inversion.\n */\n\n// agent-eval's AgentProfile (the eval-harness unit of variation, `model: string`)\n// — NOT sandbox's AgentProfile. ProfileDispatchFn is keyed on the former.\nimport type { AgentProfile } from '@tangle-network/agent-eval'\nimport type {\n CampaignTraceWriter,\n DispatchContext,\n DispatchFn,\n ProfileDispatchFn,\n Scenario,\n} from '@tangle-network/agent-eval/campaign'\nimport { reportLoopUsage } from './report-usage'\nimport { type RunLoopOptions, runLoop } from './run-loop'\nimport type { LoopResult, LoopSandboxClient, LoopTraceEmitter } from './types'\n\n/** runLoop options minus the `ctx` (loopDispatch builds the ctx). */\nexport type LoopOptionsForDispatch<Task, Output, Decision> = Omit<\n RunLoopOptions<Task, Output, Decision>,\n 'ctx'\n>\n\nexport interface LoopDispatchOptions<Task, Output, Decision, TScenario extends Scenario, TArtifact> {\n /** Sandbox client used for every cell's `runLoop`. Supplied once. */\n sandboxClient: LoopSandboxClient\n /** Build the per-cell runLoop options from the scenario (+ profile, when\n * used with `runProfileMatrix`). */\n toLoopOptions: (\n scenario: TScenario,\n profile: AgentProfile,\n ) => LoopOptionsForDispatch<Task, Output, Decision>\n /** Map the finished loop to the artifact the judges score. Default:\n * `result.winner?.output`. A loop with no winner yields `undefined` (judges\n * skip the cell) — but the loop's token usage is STILL reported, so the\n * integrity guard sees real activity. */\n toArtifact?: (result: LoopResult<Task, Output, Decision>) => TArtifact\n /** Forward `loop.*` trace events into the campaign's scoped trace so loop\n * spans correlate with the cell. Default true. */\n forwardTrace?: boolean\n /** Cost-meter source label for the loop's spend. Default `'loop'`. */\n costSource?: string\n}\n\n/** Bridge a campaign `DispatchContext.trace` to a `LoopTraceEmitter` so every\n * `loop.*` event lands as a span under the cell's scoped trace. */\nfunction campaignTraceToLoopEmitter(trace: CampaignTraceWriter): LoopTraceEmitter {\n return {\n emit(event) {\n trace\n .span(event.kind, { runId: event.runId, timestamp: event.timestamp, ...event.payload })\n .end()\n },\n }\n}\n\nasync function runLoopForCell<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n scenario: TScenario,\n profile: AgentProfile,\n ctx: DispatchContext,\n): Promise<TArtifact> {\n const loopOptions = opts.toLoopOptions(scenario, profile)\n const result = await runLoop<Task, Output, Decision>({\n ...loopOptions,\n ctx: {\n sandboxClient: opts.sandboxClient,\n signal: ctx.signal,\n traceEmitter:\n opts.forwardTrace === false ? undefined : campaignTraceToLoopEmitter(ctx.trace),\n },\n })\n reportLoopUsage(ctx.cost, result, opts.costSource ?? 'loop')\n const toArtifact =\n opts.toArtifact ?? ((r: LoopResult<Task, Output, Decision>) => r.winner?.output as TArtifact)\n return toArtifact(result)\n}\n\n/**\n * Adapter for `runProfileMatrix` (profile is an axis). Returns a\n * `ProfileDispatchFn` that runs `runLoop` per (profile, scenario) cell and\n * reports usage automatically.\n */\nexport function loopDispatch<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>,\n): ProfileDispatchFn<TScenario, TArtifact> {\n return (profile, scenario, ctx) => runLoopForCell(opts, scenario, profile, ctx)\n}\n\n/**\n * Adapter for `runCampaign` (no profile axis). `toLoopOptions` receives only\n * the scenario; the `profile` passed to the shared core is a stable sentinel\n * so a single `runLoop` config is reused across cells.\n */\nexport function loopCampaignDispatch<Task, Output, Decision, TScenario extends Scenario, TArtifact>(\n opts: Omit<LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact>, 'toLoopOptions'> & {\n toLoopOptions: (scenario: TScenario) => LoopOptionsForDispatch<Task, Output, Decision>\n },\n): DispatchFn<TScenario, TArtifact> {\n const profileSentinel = { id: 'loop-campaign', model: 'n/a@loop-campaign' } as AgentProfile\n const profiled: LoopDispatchOptions<Task, Output, Decision, TScenario, TArtifact> = {\n ...opts,\n toLoopOptions: (scenario) => opts.toLoopOptions(scenario),\n }\n return (scenario, ctx) => runLoopForCell(profiled, scenario, profileSentinel, ctx)\n}\n"],"mappings":";;;;;;AAsFO,SAAS,oBACd,SACuC;AACvC,MAAI,OAAO,QAAQ,YAAY,YAAY;AACzC,UAAM,IAAI,gBAAgB,iDAAiD;AAAA,EAC7E;AACA,QAAM,gBAAgB,QAAQ,iBAAiB;AAC/C,MAAI,CAAC,OAAO,SAAS,aAAa,KAAK,iBAAiB,GAAG;AACzD,UAAM,IAAI,gBAAgB,gDAAgD;AAAA,EAC5E;AACA,QAAM,YAAY,QAAQ,aAAa;AACvC,MAAI,CAAC,OAAO,SAAS,SAAS,KAAK,YAAY,GAAG;AAChD,UAAM,IAAI,gBAAgB,6CAA6C;AAAA,EACzE;AAMA,MAAI;AAEJ,SAAO;AAAA,IACL,MAAM,QAAQ,QAAQ;AAAA,IACtB,MAAM,KAAK,MAAM,SAAS;AACxB,UAAI,QAAQ,UAAU,eAAe;AACnC,kBAAU,EAAE,MAAM,QAAQ,WAAW,kBAAkB,aAAa,YAAY;AAChF,eAAO,CAAC;AAAA,MACV;AACA,YAAM,OAAO,MAAM,QAAQ,QAAQ;AAAA,QACjC;AAAA,QACA;AAAA,QACA,iBAAiB,QAAQ;AAAA,QACzB,qBAAqB,gBAAgB,QAAQ;AAAA,MAC/C,CAAC;AACD,gBAAU,aAAa,MAAM,SAAS;AACtC,cAAQ,QAAQ,MAAM;AAAA,QACpB,KAAK;AACH,iBAAO,CAAC,QAAQ,IAAI;AAAA,QACtB,KAAK;AACH,iBAAO,QAAQ;AAAA,QACjB,KAAK;AACH,iBAAO,CAAC;AAAA,MACZ;AAAA,IACF;AAAA,IACA,SAAS;AAIP,aAAO,SAAS,SAAS,SAAS,SAAS;AAAA,IAC7C;AAAA,IACA,e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AK,cAAc,QAAQ;AAAA,EAC1D;AACA,SAAO,CAAC,UAAU,QAAQ,eAAe,UAAU,UAAU,iBAAiB,GAAG;AACnF;","names":["decision"]}
@@ -58,7 +58,14 @@ function mcpToolsForRuntimeMcpSubset(names) {
58
58
  }
59
59
 
60
60
  // src/otel-export.ts
61
- var SCOPE = { name: "@tangle-network/agent-runtime", version: "0.23.0" };
61
+ var SCOPE = { name: "@tangle-network/agent-runtime", version: "0.33.0" };
62
+ var GEN_AI = {
63
+ operation: "gen_ai.operation.name",
64
+ agentName: "gen_ai.agent.name",
65
+ conversationId: "gen_ai.conversation.id",
66
+ inputTokens: "gen_ai.usage.input_tokens",
67
+ outputTokens: "gen_ai.usage.output_tokens"
68
+ };
62
69
  function createOtelExporter(config) {
63
70
  const resolvedEndpoint = config?.endpoint ?? (typeof process !== "undefined" ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : void 0);
64
71
  if (!resolvedEndpoint) return void 0;
@@ -150,6 +157,148 @@ function loopEventToOtelSpan(event, traceId, parentSpanId) {
150
157
  status: { code: 1 }
151
158
  };
152
159
  }
160
+ function buildLoopOtelSpans(events, traceId, rootParentSpanId) {
161
+ if (events.length === 0) return [];
162
+ const tid = padTraceId(traceId);
163
+ const out = [];
164
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
165
+ const str = (v) => typeof v === "string" && v.length > 0 ? v : void 0;
166
+ const rec = (v) => v && typeof v === "object" ? v : {};
167
+ const started = events.find((e) => e.kind === "loop.started");
168
+ const ended = events.find((e) => e.kind === "loop.ended");
169
+ const runId = events[0]?.runId ?? "";
170
+ const rootStart = started?.timestamp ?? events[0].timestamp;
171
+ const rootEnd = ended?.timestamp ?? events[events.length - 1].timestamp;
172
+ const rootId = generateSpanId();
173
+ const make = (spanId, parentSpanId, name, startMs, endMs, attrs, statusCode = 1) => ({
174
+ traceId: tid,
175
+ spanId,
176
+ parentSpanId: parentSpanId ? padSpanId(parentSpanId) : void 0,
177
+ name,
178
+ kind: 1,
179
+ startTimeUnixNano: msToNs(startMs),
180
+ endTimeUnixNano: msToNs(endMs),
181
+ attributes: toAttributes(attrs),
182
+ status: { code: statusCode }
183
+ });
184
+ const sp = rec(started?.payload);
185
+ const rootAttrs = {
186
+ [GEN_AI.operation]: "invoke_workflow",
187
+ [GEN_AI.conversationId]: runId,
188
+ "tangle.loop.driver": str(sp.driver) ?? "driver"
189
+ };
190
+ if (Array.isArray(sp.agentRunNames) && sp.agentRunNames.length > 0) {
191
+ rootAttrs["tangle.loop.agents"] = sp.agentRunNames.map(String).join(",");
192
+ }
193
+ if (ended) {
194
+ const ep = rec(ended.payload);
195
+ const win = num(ep.winnerIterationIndex);
196
+ if (win !== void 0) rootAttrs["tangle.loop.winner.iteration_index"] = win;
197
+ const cost = num(ep.totalCostUsd);
198
+ if (cost !== void 0) rootAttrs["tangle.cost.usd"] = cost;
199
+ const iters = num(ep.iterations);
200
+ if (iters !== void 0) rootAttrs["tangle.loop.iterations"] = iters;
201
+ }
202
+ out.push(make(rootId, rootParentSpanId, "loop", rootStart, rootEnd, rootAttrs));
203
+ const iterStartTs = /* @__PURE__ */ new Map();
204
+ const placementByIdx = /* @__PURE__ */ new Map();
205
+ let currentRoundId;
206
+ let pendingRound;
207
+ const flushRound = (endMs) => {
208
+ if (!pendingRound) return;
209
+ out.push(
210
+ make(pendingRound.id, rootId, "loop.round", pendingRound.start, endMs, pendingRound.attrs)
211
+ );
212
+ pendingRound = void 0;
213
+ };
214
+ for (const e of events) {
215
+ const p = rec(e.payload);
216
+ switch (e.kind) {
217
+ case "loop.plan": {
218
+ flushRound(e.timestamp);
219
+ const id = generateSpanId();
220
+ const attrs = {
221
+ [GEN_AI.operation]: "invoke_workflow",
222
+ "tangle.loop.round.index": num(p.roundIndex) ?? 0,
223
+ "tangle.loop.move.kind": str(p.moveKind) ?? "unknown",
224
+ "tangle.loop.move.width": num(p.plannedCount) ?? 0
225
+ };
226
+ const r = str(p.rationale);
227
+ if (r) attrs["tangle.loop.move.rationale"] = r;
228
+ pendingRound = { id, start: e.timestamp, attrs };
229
+ currentRoundId = id;
230
+ break;
231
+ }
232
+ case "loop.iteration.started": {
233
+ const idx = num(p.iterationIndex);
234
+ if (idx !== void 0) iterStartTs.set(idx, e.timestamp);
235
+ break;
236
+ }
237
+ case "loop.iteration.dispatch": {
238
+ const idx = num(p.iterationIndex);
239
+ if (idx === void 0) break;
240
+ const place = {};
241
+ const kind = str(p.placement);
242
+ if (kind) place["tangle.loop.placement.kind"] = kind;
243
+ const sid = str(p.sandboxId);
244
+ if (sid) place["tangle.sandbox.id"] = sid;
245
+ const fid = str(p.fleetId);
246
+ if (fid) place["tangle.fleet.id"] = fid;
247
+ const mid = str(p.machineId);
248
+ if (mid) place["tangle.machine.id"] = mid;
249
+ placementByIdx.set(idx, place);
250
+ break;
251
+ }
252
+ case "loop.iteration.ended": {
253
+ const idx = num(p.iterationIndex) ?? 0;
254
+ const start = iterStartTs.get(idx) ?? e.timestamp;
255
+ const err = str(p.error);
256
+ const attrs = {
257
+ [GEN_AI.operation]: "invoke_agent",
258
+ "tangle.loop.iteration.index": idx
259
+ };
260
+ const agent = str(p.agentRunName);
261
+ if (agent) attrs[GEN_AI.agentName] = agent;
262
+ const tu = rec(p.tokenUsage);
263
+ const inTok = num(tu.input);
264
+ if (inTok !== void 0) attrs[GEN_AI.inputTokens] = inTok;
265
+ const outTok = num(tu.output);
266
+ if (outTok !== void 0) attrs[GEN_AI.outputTokens] = outTok;
267
+ const cost = num(p.costUsd);
268
+ if (cost !== void 0) attrs["tangle.cost.usd"] = cost;
269
+ const verdict = rec(p.verdict);
270
+ if (typeof verdict.valid === "boolean") attrs["tangle.loop.verdict.valid"] = verdict.valid;
271
+ const score = num(verdict.score);
272
+ if (score !== void 0) attrs["tangle.loop.verdict.score"] = score;
273
+ if (err) attrs["tangle.loop.error"] = err;
274
+ Object.assign(attrs, placementByIdx.get(idx) ?? {});
275
+ out.push(
276
+ make(
277
+ generateSpanId(),
278
+ currentRoundId ?? rootId,
279
+ "loop.iteration",
280
+ start,
281
+ e.timestamp,
282
+ attrs,
283
+ err ? 2 : 1
284
+ )
285
+ );
286
+ break;
287
+ }
288
+ case "loop.decision": {
289
+ if (pendingRound) {
290
+ const dec = str(p.decision);
291
+ if (dec) pendingRound.attrs["tangle.loop.decision"] = dec;
292
+ flushRound(e.timestamp);
293
+ }
294
+ currentRoundId = void 0;
295
+ break;
296
+ }
297
+ }
298
+ }
299
+ flushRound(rootEnd);
300
+ return out;
301
+ }
153
302
  function parseHeadersFromEnv() {
154
303
  if (typeof process === "undefined") return {};
155
304
  const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS;
@@ -227,7 +376,8 @@ export {
227
376
  mcpToolsForRuntimeMcpSubset,
228
377
  createOtelExporter,
229
378
  loopEventToOtelSpan,
379
+ buildLoopOtelSpans,
230
380
  INTELLIGENCE_WIRE_VERSION,
231
381
  exportEvalRuns
232
382
  };
233
- //# sourceMappingURL=chunk-RO7K6JNF.js.map
383
+ //# sourceMappingURL=chunk-Q4ZDSLBD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/openai-tools.ts","../src/otel-export.ts"],"sourcesContent":["/**\n * @experimental\n *\n * OpenAI Chat Completions `tools[]` projection of the 5 agent-runtime MCP\n * delegation tools.\n *\n * Use when configuring `createOpenAICompatibleBackend({ tools: ... })` so the\n * model can call `delegate_code`, `delegate_research`, `delegate_feedback`,\n * `delegation_status`, and `delegation_history` through the OpenAI-compat\n * transport (tcloud, OpenRouter, OpenAI direct, cli-bridge). The runtime\n * surfaces tool calls as `tool_call` stream events — execution is the\n * caller's responsibility (typically the parent sandbox runtime's MCP\n * mount).\n *\n * Sandbox-SDK callers do NOT need this helper: the sandbox runtime mounts\n * MCP servers natively and the in-sandbox harness discovers tools via the\n * runtime, not via an OpenAI tools array.\n *\n * Tool name + description + JSON-schema are pulled from the canonical\n * `DELEGATE_*` constants exported by `./tools/*` so the projection cannot\n * drift from the server's own validators.\n */\n\nimport type { OpenAIChatTool } from '../types'\nimport {\n DELEGATE_CODE_DESCRIPTION,\n DELEGATE_CODE_INPUT_SCHEMA,\n DELEGATE_CODE_TOOL_NAME,\n} from './tools/delegate-code'\nimport {\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA,\n DELEGATE_FEEDBACK_TOOL_NAME,\n} from './tools/delegate-feedback'\nimport {\n DELEGATE_RESEARCH_DESCRIPTION,\n DELEGATE_RESEARCH_INPUT_SCHEMA,\n DELEGATE_RESEARCH_TOOL_NAME,\n} from './tools/delegate-research'\nimport {\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA,\n DELEGATION_HISTORY_TOOL_NAME,\n} from './tools/delegation-history'\nimport {\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA,\n DELEGATION_STATUS_TOOL_NAME,\n} from './tools/delegation-status'\n\nfunction buildTool(\n name: string,\n description: string,\n parameters: Readonly<Record<string, unknown>>,\n): OpenAIChatTool {\n // `parameters` arrives as a deeply-readonly `as const` literal. The\n // OpenAI-compat backend JSON-serializes the body so a shallow copy\n // into a plain object is sufficient — and shields callers that mutate\n // the returned descriptor from corrupting the source constant.\n return {\n type: 'function',\n function: { name, description, parameters: { ...parameters } },\n }\n}\n\n/**\n * @experimental\n *\n * Returns the 5 delegation tools projected into OpenAI Chat Completions\n * `tools[]` shape. The order is stable: `delegate_code`,\n * `delegate_research`, `delegate_feedback`, `delegation_status`,\n * `delegation_history`.\n */\nexport function mcpToolsForRuntimeMcp(): OpenAIChatTool[] {\n return [\n buildTool(\n DELEGATE_CODE_TOOL_NAME,\n DELEGATE_CODE_DESCRIPTION,\n DELEGATE_CODE_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATE_RESEARCH_TOOL_NAME,\n DELEGATE_RESEARCH_DESCRIPTION,\n DELEGATE_RESEARCH_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATE_FEEDBACK_TOOL_NAME,\n DELEGATE_FEEDBACK_DESCRIPTION,\n DELEGATE_FEEDBACK_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_STATUS_TOOL_NAME,\n DELEGATION_STATUS_DESCRIPTION,\n DELEGATION_STATUS_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n buildTool(\n DELEGATION_HISTORY_TOOL_NAME,\n DELEGATION_HISTORY_DESCRIPTION,\n DELEGATION_HISTORY_INPUT_SCHEMA as Readonly<Record<string, unknown>>,\n ),\n ]\n}\n\n/**\n * @experimental\n *\n * Subset filter — return only the projected tools whose `function.name`\n * appears in `names`. Useful for curated mounts (e.g. only the queue-bound\n * delegation tools, omitting `delegate_feedback`). Unknown names are\n * silently ignored; pass an empty array to get an empty result.\n */\nexport function mcpToolsForRuntimeMcpSubset(names: ReadonlyArray<string>): OpenAIChatTool[] {\n const allowed = new Set(names)\n return mcpToolsForRuntimeMcp().filter((tool) => allowed.has(tool.function.name))\n}\n","/**\n * OTEL span exporter — streams LoopTraceEvents to an OTLP/HTTP collector.\n *\n * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env\n * when no explicit config is given. Keeps the runtime dep-free from\n * @opentelemetry/sdk-trace-base — minimal OTLP/JSON serializer.\n *\n * The exporter accepts both raw OtelSpan objects and LoopTraceEvents\n * (which get converted to OTLP spans automatically).\n */\n\nexport interface OtelExportConfig {\n /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */\n endpoint?: string\n /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */\n headers?: Record<string, string>\n /** Batch size before flush. Default 64. */\n batchSize?: number\n /** Flush interval ms. Default 5000. */\n flushIntervalMs?: number\n /** Resource attributes stamped on every export. */\n resourceAttributes?: Record<string, string | number | boolean>\n /** Service name. Default 'agent-runtime'. */\n serviceName?: string\n}\n\nexport interface OtelExporter {\n /** Export a span. */\n exportSpan(span: OtelSpan): void\n /** Force flush pending spans. */\n flush(): Promise<void>\n /** Shutdown cleanly. */\n shutdown(): Promise<void>\n}\n\nexport interface OtelSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind?: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes?: OtelAttribute[]\n status?: { code: number; message?: string }\n}\n\nexport interface OtelAttribute {\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n}\n\ninterface OtlpResourceSpans {\n resource: { attributes: OtelAttribute[] }\n scopeSpans: Array<{ scope: { name: string; version: string }; spans: OtelSpan[] }>\n}\n\ninterface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\n\nconst SCOPE = { name: '@tangle-network/agent-runtime', version: '0.33.0' }\n\n/**\n * Current (non-deprecated) OpenTelemetry GenAI semantic-convention keys.\n * Registry: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/\n * NB: `gen_ai.system` / `gen_ai.usage.prompt_tokens` / `completion_tokens` are\n * DEPRECATED — do not emit them. We use `provider.name` + `input/output_tokens`.\n */\nconst GEN_AI = {\n operation: 'gen_ai.operation.name',\n agentName: 'gen_ai.agent.name',\n conversationId: 'gen_ai.conversation.id',\n inputTokens: 'gen_ai.usage.input_tokens',\n outputTokens: 'gen_ai.usage.output_tokens',\n} as const\n\n/**\n * Create an OTEL exporter. Returns undefined when no endpoint is configured.\n */\nexport function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined {\n const resolvedEndpoint =\n config?.endpoint ??\n (typeof process !== 'undefined' ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : undefined)\n if (!resolvedEndpoint) return undefined\n const endpoint: string = resolvedEndpoint\n\n const headers = config?.headers ?? parseHeadersFromEnv()\n const batchSize = config?.batchSize ?? 64\n const flushIntervalMs = config?.flushIntervalMs ?? 5000\n const serviceName = config?.serviceName ?? 'agent-runtime'\n const resourceAttrs = config?.resourceAttributes ?? {}\n\n const pending: OtelSpan[] = []\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n const exporter: OtelExporter = {\n exportSpan(span: OtelSpan): void {\n if (stopped) return\n pending.push(span)\n if (pending.length >= batchSize) {\n void doFlush()\n }\n },\n\n async flush(): Promise<void> {\n await doFlush()\n },\n\n async shutdown(): Promise<void> {\n stopped = true\n if (timer !== undefined) {\n clearInterval(timer)\n timer = undefined\n }\n await doFlush()\n },\n }\n\n timer = setInterval(() => {\n if (pending.length > 0) void doFlush()\n }, flushIntervalMs)\n if (typeof timer === 'object' && 'unref' in timer) {\n ;(timer as NodeJS.Timeout).unref()\n }\n\n async function doFlush(): Promise<void> {\n if (pending.length === 0) return\n const batch = pending.splice(0)\n const body: OtlpExport = {\n resourceSpans: [\n {\n resource: {\n attributes: toAttributes({\n 'service.name': serviceName,\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: SCOPE, spans: batch }],\n },\n ],\n }\n const url = `${endpoint.replace(/\\/+$/, '')}/v1/traces`\n try {\n await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...headers },\n body: JSON.stringify(body),\n })\n } catch {\n // Best-effort — telemetry export must not crash the runtime.\n }\n }\n\n return exporter\n}\n\n/**\n * Convert a LoopTraceEvent into an OtelSpan for export.\n */\nexport function loopEventToOtelSpan(\n event: {\n kind: string\n runId: string\n timestamp: number\n payload: object\n },\n traceId: string,\n parentSpanId?: string,\n): OtelSpan {\n const spanId = generateSpanId()\n const attrs: Record<string, string | number | boolean> = {\n 'loop.event_kind': event.kind,\n 'loop.run_id': event.runId,\n }\n for (const [k, v] of Object.entries(event.payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n attrs[`loop.${k}`] = v\n }\n }\n const ts = msToNs(event.timestamp)\n return {\n traceId: padTraceId(traceId),\n spanId,\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name: event.kind,\n kind: 1,\n startTimeUnixNano: ts,\n endTimeUnixNano: ts,\n attributes: toAttributes(attrs),\n status: { code: 1 },\n }\n}\n\n/**\n * Build a nested, real-duration OTLP span tree for ONE loop run from its full\n * ordered `LoopTraceEvent` stream. Unlike `loopEventToOtelSpan` (one flat,\n * zero-duration span per event), this reconstructs the topology hierarchy a\n * GenAI trace viewer renders natively:\n *\n * loop (invoke_workflow)\n * └─ loop.round[k] (invoke_workflow) ← tangle.loop.move.{kind,width,rationale}\n * ├─ loop.iteration[i] (invoke_agent) ← gen_ai.agent.name + usage + verdict + placement\n * └─ …\n *\n * Attributes follow the current GenAI semconv (`gen_ai.*`) where they apply and\n * a namespaced `tangle.loop.*` / `tangle.cost.usd` extension for topology /\n * verdict / placement / cost (not yet standardized). Pure: feed it a buffered\n * per-runId event array (e.g. flushed on `loop.ended`) and export the result.\n */\nexport function buildLoopOtelSpans(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n traceId: string,\n rootParentSpanId?: string,\n): OtelSpan[] {\n if (events.length === 0) return []\n const tid = padTraceId(traceId)\n const out: OtelSpan[] = []\n const num = (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) ? v : undefined\n const str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined\n const rec = (v: unknown): Record<string, unknown> =>\n v && typeof v === 'object' ? (v as Record<string, unknown>) : {}\n\n const started = events.find((e) => e.kind === 'loop.started')\n const ended = events.find((e) => e.kind === 'loop.ended')\n const runId = events[0]?.runId ?? ''\n const rootStart = started?.timestamp ?? events[0]!.timestamp\n const rootEnd = ended?.timestamp ?? events[events.length - 1]!.timestamp\n const rootId = generateSpanId()\n\n const make = (\n spanId: string,\n parentSpanId: string | undefined,\n name: string,\n startMs: number,\n endMs: number,\n attrs: Record<string, string | number | boolean>,\n statusCode = 1,\n ): OtelSpan => ({\n traceId: tid,\n spanId,\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name,\n kind: 1,\n startTimeUnixNano: msToNs(startMs),\n endTimeUnixNano: msToNs(endMs),\n attributes: toAttributes(attrs),\n status: { code: statusCode },\n })\n\n // root\n const sp = rec(started?.payload)\n const rootAttrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n [GEN_AI.conversationId]: runId,\n 'tangle.loop.driver': str(sp.driver) ?? 'driver',\n }\n if (Array.isArray(sp.agentRunNames) && sp.agentRunNames.length > 0) {\n rootAttrs['tangle.loop.agents'] = sp.agentRunNames.map(String).join(',')\n }\n if (ended) {\n const ep = rec(ended.payload)\n const win = num(ep.winnerIterationIndex)\n if (win !== undefined) rootAttrs['tangle.loop.winner.iteration_index'] = win\n const cost = num(ep.totalCostUsd)\n if (cost !== undefined) rootAttrs['tangle.cost.usd'] = cost\n const iters = num(ep.iterations)\n if (iters !== undefined) rootAttrs['tangle.loop.iterations'] = iters\n }\n out.push(make(rootId, rootParentSpanId, 'loop', rootStart, rootEnd, rootAttrs))\n\n // rounds + iterations\n const iterStartTs = new Map<number, number>()\n const placementByIdx = new Map<number, Record<string, string>>()\n let currentRoundId: string | undefined\n let pendingRound:\n | { id: string; start: number; attrs: Record<string, string | number | boolean> }\n | undefined\n const flushRound = (endMs: number) => {\n if (!pendingRound) return\n out.push(\n make(pendingRound.id, rootId, 'loop.round', pendingRound.start, endMs, pendingRound.attrs),\n )\n pendingRound = undefined\n }\n\n for (const e of events) {\n const p = rec(e.payload)\n switch (e.kind) {\n case 'loop.plan': {\n flushRound(e.timestamp)\n const id = generateSpanId()\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n 'tangle.loop.round.index': num(p.roundIndex) ?? 0,\n 'tangle.loop.move.kind': str(p.moveKind) ?? 'unknown',\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 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 Object.assign(attrs, placementByIdx.get(idx) ?? {})\n out.push(\n make(\n generateSpanId(),\n currentRoundId ?? rootId,\n 'loop.iteration',\n start,\n e.timestamp,\n attrs,\n err ? 2 : 1,\n ),\n )\n break\n }\n case 'loop.decision': {\n if (pendingRound) {\n const dec = str(p.decision)\n if (dec) pendingRound.attrs['tangle.loop.decision'] = dec\n flushRound(e.timestamp)\n }\n currentRoundId = undefined\n break\n }\n }\n }\n flushRound(rootEnd)\n return out\n}\n\nfunction parseHeadersFromEnv(): Record<string, string> {\n if (typeof process === 'undefined') return {}\n const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(',')) {\n const eq = pair.indexOf('=')\n if (eq < 0) continue\n const key = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n if (key) out[key] = value\n }\n return out\n}\n\nfunction toAttributes(record: Record<string, string | number | boolean>): OtelAttribute[] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\nfunction msToNs(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n\nfunction padSpanId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 16).padEnd(16, '0')\n}\n\nfunction padTraceId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 32).padEnd(32, '0')\n}\n\nfunction generateSpanId(): string {\n const bytes = new Uint8Array(8)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── Eval-run ingest (self-improvement provenance) ───────────────────────────\n//\n// Tangle Intelligence has a first-class, non-trace record for self-improvement\n// runs: POST /v1/ingest/eval-runs (\"Mode D\"). Each generation carries a\n// `surfaceHash` (the proposed-change identity) + arbitrary `surface` provenance;\n// a later `gate-decided` event re-emits the same `runId` (idempotent upsert) with\n// a real `gateDecision` + `holdoutLift`, so proposal→verdict is one diffable\n// record. This is how a consumer's RSI loop records WHAT it changed, WHY, from\n// which evidence — the audit trail behind agentic self-improvement.\n\n/** Wire version the eval-runs ingest enforces (X-Tangle-Wire-Version + body). */\nexport const INTELLIGENCE_WIRE_VERSION = '2026-05-26.v1'\n\nexport interface EvalRunGeneration {\n /** 0-based ordinal of this generation within the run (required by ingest). */\n index: number\n /** Identity of the proposed surface change (content-addressed hash). */\n surfaceHash: string\n /** Arbitrary provenance for this generation (rationale, evidence, source). */\n surface?: unknown\n /** Per-scenario results; empty until the generation is measured. */\n cells?: unknown[]\n /** Mean composite score (0 when unmeasured — pair with labels.measured). */\n compositeMean: number\n costUsd: number\n durationMs: number\n}\n\nexport interface EvalRunEvent {\n runId: string\n runDir: string\n /** ISO timestamp. */\n timestamp: string\n status:\n | 'started'\n | 'baseline-complete'\n | 'generation-complete'\n | 'gate-decided'\n | 'finished'\n | 'errored'\n labels?: Record<string, string>\n baseline?: EvalRunGeneration\n generations?: EvalRunGeneration[]\n gateDecision?: 'ship' | 'hold' | 'need_more_work' | 'model_ceiling' | 'arch_ceiling'\n holdoutLift?: number\n totalCostUsd: number\n totalDurationMs: number\n errorMessage?: string\n}\n\nexport interface EvalRunsExportConfig {\n /** Bearer key — tenant is resolved server-side from it. Reads TANGLE_API_KEY. */\n apiKey?: string\n /** Intelligence base. Reads INTELLIGENCE_BASE env, else prod. */\n base?: string\n /** Idempotency-Key header (e.g. the runId) — safe retries + upsert. */\n idempotencyKey?: string\n}\n\nexport interface EvalRunsExportResult {\n ok: boolean\n status: number\n accepted: number\n rejected: Array<{ index: number; reason: string }>\n}\n\nconst DEFAULT_INTELLIGENCE_BASE = 'https://intelligence.tangle.tools'\n\n/**\n * Ship self-improvement eval-run events to Tangle Intelligence. Unlike the\n * best-effort span exporter, this RESOLVES with the ingest verdict (accepted /\n * rejected per event) so a consumer's loop can assert its provenance landed.\n * Throws only on a missing key or network failure.\n */\nexport async function exportEvalRuns(\n events: EvalRunEvent[],\n config?: EvalRunsExportConfig,\n): Promise<EvalRunsExportResult> {\n if (events.length === 0) return { ok: true, status: 0, accepted: 0, rejected: [] }\n const apiKey =\n config?.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n if (!apiKey)\n throw new Error('exportEvalRuns: apiKey required (pass config.apiKey or set TANGLE_API_KEY)')\n const base =\n config?.base ??\n (typeof process !== 'undefined' ? process.env.INTELLIGENCE_BASE : undefined) ??\n DEFAULT_INTELLIGENCE_BASE\n const url = `${base.replace(/\\/+$/, '')}/v1/ingest/eval-runs`\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${apiKey}`,\n 'X-Tangle-Wire-Version': INTELLIGENCE_WIRE_VERSION,\n ...(config?.idempotencyKey ? { 'Idempotency-Key': config.idempotencyKey } : {}),\n },\n body: JSON.stringify({ wireVersion: INTELLIGENCE_WIRE_VERSION, events }),\n })\n let parsed: { accepted?: number; rejected?: Array<{ index: number; reason: string }> } = {}\n try {\n parsed = (await res.json()) as typeof parsed\n } catch {\n // non-JSON body (e.g. 5xx HTML) — leave parsed empty\n }\n return {\n ok: res.ok,\n status: res.status,\n accepted: parsed.accepted ?? (res.ok ? events.length : 0),\n rejected: parsed.rejected ?? [],\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAkDA,SAAS,UACP,MACA,aACA,YACgB;AAKhB,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU,EAAE,MAAM,aAAa,YAAY,EAAE,GAAG,WAAW,EAAE;AAAA,EAC/D;AACF;AAUO,SAAS,wBAA0C;AACxD,SAAO;AAAA,IACL;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAUO,SAAS,4BAA4B,OAAgD;AAC1F,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AC;AACH,UAAM,IAAI,MAAM,4EAA4E;AAC9F,QAAM,OACJ,QAAQ,SACP,OAAO,YAAY,cAAc,QAAQ,IAAI,oBAAoB,WAClE;AACF,QAAM,MAAM,GAAG,KAAK,QAAQ,QAAQ,EAAE,CAAC;AACvC,QAAM,MAAM,MAAM,MAAM,KAAK;AAAA,IAC3B,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,MAAM;AAAA,MAC/B,yBAAyB;AAAA,MACzB,GAAI,QAAQ,iBAAiB,EAAE,mBAAmB,OAAO,eAAe,IAAI,CAAC;AAAA,IAC/E;AAAA,IACA,MAAM,KAAK,UAAU,EAAE,aAAa,2BAA2B,OAAO,CAAC;AAAA,EACzE,CAAC;AACD,MAAI,SAAqF,CAAC;AAC1F,MAAI;AACF,aAAU,MAAM,IAAI,KAAK;AAAA,EAC3B,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,QAAQ,IAAI;AAAA,IACZ,UAAU,OAAO,aAAa,IAAI,KAAK,OAAO,SAAS;AAAA,IACvD,UAAU,OAAO,YAAY,CAAC;AAAA,EAChC;AACF;","names":[]}
@@ -27,7 +27,7 @@ import {
27
27
  } from "./chunk-GLR25NG7.js";
28
28
  import {
29
29
  runLoop
30
- } from "./chunk-GLTUUKTN.js";
30
+ } from "./chunk-7KS6UEHB.js";
31
31
  import {
32
32
  coderProfile,
33
33
  multiHarnessCoderFanout
@@ -712,4 +712,4 @@ export {
712
712
  createMcpServer,
713
713
  createInProcessTransport
714
714
  };
715
- //# sourceMappingURL=chunk-AAJVQRPL.js.map
715
+ //# sourceMappingURL=chunk-VVHX5RKE.js.map
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { AgentEvalError, KnowledgeReadinessReport, RunRecord, ControlEvalResult,
2
2
  export { AgentEvalError, AgentEvalErrorCode, ConfigError, ControlBudget, ControlDecision, ControlEvalResult, ControlRunResult, ControlStep, DataAcquisitionPlan, JudgeError, KnowledgeReadinessReport, KnowledgeRequirement, NotFoundError, RunRecord, ValidationError } from '@tangle-network/agent-eval';
3
3
  import { a as AgentBackendInput, b as AgentExecutionBackend, O as OpenAIChatTool, c as OpenAIChatToolChoice, d as AgentBackendContext, R as RuntimeStreamEvent, K as KnowledgeReadinessDecision, e as RunAgentTaskOptions, f as AgentTaskRunResult, g as RunAgentTaskStreamOptions, h as AgentRuntimeEvent, i as AgentTaskStatus, j as RuntimeSessionStore, k as RuntimeSession } from './types-CsCCryln.js';
4
4
  export { l as AgentAdapter, m as AgentKnowledgeProvider, n as AgentRuntimeEventSink, o as AgentTaskContext, A as AgentTaskSpec, B as BackendErrorDetail } from './types-CsCCryln.js';
5
- export { E as EvalRunEvent, b as EvalRunGeneration, c as EvalRunsExportConfig, d as EvalRunsExportResult, I as INTELLIGENCE_WIRE_VERSION, e as OtelAttribute, f as OtelExportConfig, O as OtelExporter, g as OtelSpan, h as createOtelExporter, i as exportEvalRuns, l as loopEventToOtelSpan, m as mcpToolsForRuntimeMcp, a as mcpToolsForRuntimeMcpSubset } from './otel-export-CsgwKFq8.js';
5
+ export { E as EvalRunEvent, b as EvalRunGeneration, c as EvalRunsExportConfig, d as EvalRunsExportResult, I as INTELLIGENCE_WIRE_VERSION, e as OtelAttribute, f as OtelExportConfig, O as OtelExporter, g as OtelSpan, h as buildLoopOtelSpans, i as createOtelExporter, j as exportEvalRuns, l as loopEventToOtelSpan, m as mcpToolsForRuntimeMcp, a as mcpToolsForRuntimeMcpSubset } from './otel-export-xgf4J6bo.js';
6
6
  export { R as RuntimeRunHandle, a as RuntimeRunPersistenceAdapter, b as RuntimeRunRow, s as startRuntimeRun } from './runtime-run-B8VIiOhI.js';
7
7
 
8
8
  /**
package/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  INTELLIGENCE_WIRE_VERSION,
3
+ buildLoopOtelSpans,
3
4
  createOtelExporter,
4
5
  exportEvalRuns,
5
6
  loopEventToOtelSpan,
6
7
  mcpToolsForRuntimeMcp,
7
8
  mcpToolsForRuntimeMcpSubset
8
- } from "./chunk-RO7K6JNF.js";
9
+ } from "./chunk-Q4ZDSLBD.js";
9
10
  import "./chunk-HSX6PFZR.js";
10
11
  import {
11
12
  AgentEvalError,
@@ -2729,6 +2730,7 @@ export {
2729
2730
  ValidationError,
2730
2731
  applyRunRecordDefaults,
2731
2732
  buildForwardHeaders,
2733
+ buildLoopOtelSpans,
2732
2734
  cleanModelId,
2733
2735
  computeBackoff,
2734
2736
  createConversationBackend,