@tangle-network/agent-runtime 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +79 -15
  2. package/dist/agent.js +1 -1
  3. package/dist/chunk-GHX7XOJ2.js +433 -0
  4. package/dist/chunk-GHX7XOJ2.js.map +1 -0
  5. package/dist/{chunk-T4OQQEE3.js → chunk-IQS4HI3F.js} +14 -5
  6. package/dist/chunk-IQS4HI3F.js.map +1 -0
  7. package/dist/{chunk-72JQCHOZ.js → chunk-PXUTIMGJ.js} +2318 -237
  8. package/dist/chunk-PXUTIMGJ.js.map +1 -0
  9. package/dist/{chunk-MGFEUYOH.js → chunk-U2VEWKKK.js} +3 -3
  10. package/dist/{chunk-JNPK46YH.js → chunk-VIEDXELL.js} +408 -6
  11. package/dist/chunk-VIEDXELL.js.map +1 -0
  12. package/dist/{chunk-VR4JIC5H.js → chunk-XTEZ3YJ4.js} +2 -2
  13. package/dist/index.d.ts +29 -4
  14. package/dist/index.js +109 -21
  15. package/dist/index.js.map +1 -1
  16. package/dist/kb-gate-CsXpNRk7.d.ts +1145 -0
  17. package/dist/{loop-runner-bin-DEm4roYF.d.ts → loop-runner-bin-Cgn0A-NW.d.ts} +1 -1
  18. package/dist/loop-runner-bin.d.ts +2 -2
  19. package/dist/loop-runner-bin.js +3 -3
  20. package/dist/loops.d.ts +3 -3
  21. package/dist/loops.js +57 -1
  22. package/dist/mcp/bin.js +187 -24
  23. package/dist/mcp/bin.js.map +1 -1
  24. package/dist/mcp/index.d.ts +28 -125
  25. package/dist/mcp/index.js +28 -6
  26. package/dist/mcp/index.js.map +1 -1
  27. package/dist/platform.js +2 -2
  28. package/dist/platform.js.map +1 -1
  29. package/dist/runtime.d.ts +1100 -62
  30. package/dist/runtime.js +57 -1
  31. package/dist/{types-Cbx3dNK5.d.ts → types-BpDfCPUp.d.ts} +1 -1
  32. package/dist/workflow.js +1 -1
  33. package/package.json +7 -6
  34. package/dist/chunk-5YDS7BLC.js +0 -218
  35. package/dist/chunk-5YDS7BLC.js.map +0 -1
  36. package/dist/chunk-72JQCHOZ.js.map +0 -1
  37. package/dist/chunk-JNPK46YH.js.map +0 -1
  38. package/dist/chunk-T4OQQEE3.js.map +0 -1
  39. package/dist/kb-gate-51BlLlVM.d.ts +0 -529
  40. /package/dist/{chunk-MGFEUYOH.js.map → chunk-U2VEWKKK.js.map} +0 -0
  41. /package/dist/{chunk-VR4JIC5H.js.map → chunk-XTEZ3YJ4.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/mcp/delegation-store.ts","../src/mcp/task-queue.ts","../src/mcp/tools/delegate-code.ts","../src/mcp/feedback-store.ts","../src/mcp/tools/delegate-feedback.ts","../src/mcp/tools/delegate-research.ts","../src/mcp/tools/delegation-history.ts","../src/mcp/tools/delegation-status.ts","../src/otel-export.ts"],"sourcesContent":["/**\n * @experimental\n *\n * Persistence port for the MCP delegation queue.\n *\n * `DelegationTaskQueue` keeps its working set in memory (status/history\n * reads stay synchronous) and journals every record mutation through a\n * `DelegationStore`. `DelegationTaskQueue.restore({ store })` is the load\n * path: it reads the full record set once at construction and rehydrates\n * the queue from it. After that the store only sees writes.\n *\n * Records MUST be JSON-safe — `FileDelegationStore` round-trips them\n * through `JSON.stringify`/`JSON.parse`, so a `Date`, `Map`, or function\n * smuggled into `args`/`result` would corrupt the journal.\n */\n\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\nimport { AgentEvalError } from '../errors'\nimport type { DelegationRecord } from './task-queue'\n\n/** @experimental */\nexport interface DelegationStore {\n /**\n * Read every persisted record. Called once, by\n * `DelegationTaskQueue.restore`, before any write. A missing backing\n * file is an empty store; an unparseable one throws\n * `DelegationStateCorruptError`.\n */\n loadAll(): Promise<DelegationRecord[]>\n /** Insert or replace the record keyed by `record.taskId`. */\n upsert(record: DelegationRecord): Promise<void>\n /**\n * Resolve an idempotency key to the taskId that claimed it, if any.\n * The queue serves submit-time dedupe from its rehydrated in-memory\n * index; this read exists for consumers that share a store across\n * processes without holding the full record set.\n */\n lookupIdempotencyKey(key: string): Promise<string | undefined>\n /** Delete the named records — the retention-cap eviction path. */\n remove(taskIds: readonly string[]): Promise<void>\n}\n\n/**\n * The persisted delegation state exists but cannot be parsed into\n * records. Fail loud: silently starting empty over a corrupt journal\n * would erase delegation history and re-run idempotent work. Opt into\n * recovery explicitly via `FileDelegationStoreOptions.recoverCorrupt`\n * (the bin maps `AGENT_RUNTIME_DELEGATION_STATE_RECOVER=1` onto it),\n * which archives the corrupt file and starts fresh.\n *\n * @experimental\n */\nexport class DelegationStateCorruptError extends AgentEvalError {\n constructor(message: string, options?: { cause?: unknown }) {\n super('validation', message, options)\n }\n}\n\n/**\n * A delegation-store read or write failed (filesystem error, store\n * called before `loadAll`, ...). Once the queue observes one, it stops\n * accepting new submissions — accepting work it cannot journal would\n * silently demote durable mode to in-memory mode.\n *\n * @experimental\n */\nexport class DelegationPersistenceError extends AgentEvalError {\n constructor(message: string, options?: { cause?: unknown }) {\n super('config', message, options)\n }\n}\n\n/** @experimental */\nexport class InMemoryDelegationStore implements DelegationStore {\n private readonly records = new Map<string, DelegationRecord>()\n\n async loadAll(): Promise<DelegationRecord[]> {\n return [...this.records.values()].map(cloneRecord)\n }\n\n async upsert(record: DelegationRecord): Promise<void> {\n this.records.set(record.taskId, cloneRecord(record))\n }\n\n async lookupIdempotencyKey(key: string): Promise<string | undefined> {\n for (const record of this.records.values()) {\n if (record.idempotencyKey === key) return record.taskId\n }\n return undefined\n }\n\n async remove(taskIds: readonly string[]): Promise<void> {\n for (const taskId of taskIds) this.records.delete(taskId)\n }\n}\n\n/** @experimental */\nexport interface FileDelegationStoreOptions {\n /** Absolute path of the JSON state file. Parent directories are created on first write. */\n filePath: string\n /**\n * When the state file exists but cannot be parsed, archive it to\n * `<filePath>.corrupt-<timestamp>` and start empty instead of\n * throwing `DelegationStateCorruptError`. Default false.\n */\n recoverCorrupt?: boolean\n}\n\ninterface PersistedDelegationState {\n version: 1\n records: DelegationRecord[]\n}\n\nconst STATE_FORMAT_VERSION = 1\n\n/**\n * JSON-file persistence for the delegation queue. Each write serializes\n * the full record set and lands it atomically (write to a sibling tmp\n * file, then `rename`), so readers never observe a torn file — a crash\n * mid-write leaves the previous snapshot intact. Writes are serialized\n * internally; concurrent `upsert`/`remove` calls cannot interleave.\n *\n * Built for the MCP server's scale (one stdio process, hundreds of\n * records): full-snapshot writes keep the format trivially inspectable\n * and corruption-detectable without a database dependency.\n *\n * @experimental\n */\nexport class FileDelegationStore implements DelegationStore {\n private readonly filePath: string\n private readonly recoverCorrupt: boolean\n private readonly records = new Map<string, DelegationRecord>()\n private loaded = false\n private writeTail: Promise<void> = Promise.resolve()\n private tmpSeq = 0\n\n constructor(options: FileDelegationStoreOptions) {\n this.filePath = options.filePath\n this.recoverCorrupt = options.recoverCorrupt ?? false\n }\n\n async loadAll(): Promise<DelegationRecord[]> {\n let raw: string\n try {\n raw = await readFile(this.filePath, 'utf8')\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n this.loaded = true\n return []\n }\n throw new DelegationPersistenceError(\n `FileDelegationStore: failed to read ${this.filePath}: ${errorMessage(err)}`,\n { cause: err },\n )\n }\n let state: PersistedDelegationState\n try {\n state = parsePersistedState(raw)\n } catch (err) {\n if (!this.recoverCorrupt) {\n throw new DelegationStateCorruptError(\n `FileDelegationStore: state file ${this.filePath} is corrupt (${errorMessage(err)}). ` +\n 'Repair or archive the file, or opt into automatic recovery ' +\n '(recoverCorrupt / AGENT_RUNTIME_DELEGATION_STATE_RECOVER=1) to archive it and start empty.',\n { cause: err },\n )\n }\n const archivePath = `${this.filePath}.corrupt-${Date.now()}`\n await rename(this.filePath, archivePath)\n this.loaded = true\n return []\n }\n this.records.clear()\n for (const record of state.records) this.records.set(record.taskId, record)\n this.loaded = true\n return [...this.records.values()].map(cloneRecord)\n }\n\n async upsert(record: DelegationRecord): Promise<void> {\n this.assertLoaded('upsert')\n this.records.set(record.taskId, cloneRecord(record))\n await this.enqueueWrite()\n }\n\n async lookupIdempotencyKey(key: string): Promise<string | undefined> {\n this.assertLoaded('lookupIdempotencyKey')\n for (const record of this.records.values()) {\n if (record.idempotencyKey === key) return record.taskId\n }\n return undefined\n }\n\n async remove(taskIds: readonly string[]): Promise<void> {\n this.assertLoaded('remove')\n let changed = false\n for (const taskId of taskIds) {\n if (this.records.delete(taskId)) changed = true\n }\n if (changed) await this.enqueueWrite()\n }\n\n private assertLoaded(op: string): void {\n if (this.loaded) return\n // Writing before load would snapshot only the new records and clobber\n // whatever the file already holds.\n throw new DelegationPersistenceError(\n `FileDelegationStore: ${op} called before loadAll() — the on-disk state has not been read yet`,\n )\n }\n\n private enqueueWrite(): Promise<void> {\n const write = this.writeTail.then(() => this.writeSnapshot())\n this.writeTail = write.catch(() => {})\n return write\n }\n\n private async writeSnapshot(): Promise<void> {\n const state: PersistedDelegationState = {\n version: STATE_FORMAT_VERSION,\n records: [...this.records.values()],\n }\n const payload = `${JSON.stringify(state)}\\n`\n this.tmpSeq += 1\n const tmpPath = `${this.filePath}.tmp-${process.pid}-${this.tmpSeq}`\n try {\n await mkdir(dirname(this.filePath), { recursive: true })\n await writeFile(tmpPath, payload, 'utf8')\n await rename(tmpPath, this.filePath)\n } catch (err) {\n throw new DelegationPersistenceError(\n `FileDelegationStore: failed to write ${this.filePath}: ${errorMessage(err)}`,\n { cause: err },\n )\n }\n }\n}\n\nfunction parsePersistedState(raw: string): PersistedDelegationState {\n const parsed: unknown = JSON.parse(raw)\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('top-level value is not an object')\n }\n const state = parsed as Record<string, unknown>\n if (state.version !== STATE_FORMAT_VERSION) {\n throw new Error(`unsupported state version ${JSON.stringify(state.version)}`)\n }\n if (!Array.isArray(state.records)) {\n throw new Error('`records` is not an array')\n }\n for (const record of state.records) {\n if (record === null || typeof record !== 'object') {\n throw new Error('a record entry is not an object')\n }\n const candidate = record as Record<string, unknown>\n if (typeof candidate.taskId !== 'string' || typeof candidate.status !== 'string') {\n throw new Error('a record entry is missing `taskId`/`status`')\n }\n }\n return { version: STATE_FORMAT_VERSION, records: state.records as DelegationRecord[] }\n}\n\nfunction cloneRecord(record: DelegationRecord): DelegationRecord {\n return structuredClone(record)\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err)\n}\n","/**\n * @experimental\n *\n * State machine for async MCP delegations:\n *\n * pending → running → completed | failed\n * ↘ cancelled (from any non-terminal state via cancel())\n *\n * Each `submit` returns a `taskId` immediately and kicks the work off in the\n * background. The work function receives an `AbortSignal` the queue fires\n * when `cancel(taskId)` is called. The queue does NOT supervise runtime\n * timeouts — the underlying `runLoop` driver / sandbox imposes those.\n *\n * Idempotency: callers may supply an `idempotencyKey` (hash of the input).\n * A duplicate `submit` with a known key returns the existing task instead of\n * starting a new one. Mutated input → different key → different task.\n *\n * Durability: the working set lives in memory (reads stay synchronous) and\n * every record mutation is journaled through a `DelegationStore`. The default\n * `InMemoryDelegationStore` keeps today's semantics — a process restart drops\n * all state. Construct via `DelegationTaskQueue.restore({ store })` with a\n * `FileDelegationStore` to reload prior records on startup: terminal records\n * stay queryable, in-flight records either re-attach through the\n * `resumeDelegate` seam (when they carry a `detachedSessionRef`) or fail\n * loud with a driver-restart error so `delegation_status` tells the truth.\n */\n\nimport { ValidationError } from '../errors'\nimport {\n DelegationPersistenceError,\n type DelegationStore,\n InMemoryDelegationStore,\n} from './delegation-store'\nimport type {\n DelegateCodeArgs,\n DelegateResearchArgs,\n DelegateUiAuditArgs,\n DelegationError,\n DelegationFeedbackSnapshot,\n DelegationHistoryArgs,\n DelegationHistoryEntry,\n DelegationProfile,\n DelegationProgress,\n DelegationResultPayload,\n DelegationStatus,\n DelegationStatusResult,\n} from './types'\n\ntype AnyDelegateArgs = DelegateCodeArgs | DelegateResearchArgs | DelegateUiAuditArgs\n\n/**\n * Must be JSON-safe end to end (`args`, `result`, `error`, `feedback`) —\n * persistent stores round-trip records through `JSON.stringify`.\n *\n * @experimental\n */\nexport interface DelegationRecord {\n taskId: string\n profile: DelegationProfile\n namespace?: string\n args: AnyDelegateArgs\n status: DelegationStatus\n progress?: DelegationProgress\n result?: DelegationResultPayload\n error?: DelegationError\n costUsd?: number\n startedAt: string\n completedAt?: string\n /** Sha-prefix hash of the canonical input — used for idempotency lookup. */\n idempotencyKey?: string\n /**\n * Caller-generated deterministic id of a detached run (e.g. the sandbox\n * session id a single-tick driver resumes by). Presence is what makes a\n * restored in-flight record resumable via `resumeDelegate`; without it a\n * restart settles the record as failed.\n */\n detachedSessionRef?: string\n /** Feedback events keyed by this delegation's taskId. */\n feedback: DelegationFeedbackSnapshot[]\n}\n\n/** @experimental */\nexport interface SubmitInput<Args extends AnyDelegateArgs> {\n profile: DelegationProfile\n args: Args\n namespace?: string\n idempotencyKey?: string\n /**\n * Records the detached-run resume key on the new record. The submitted\n * `run` function still executes in-process exactly as without it — the\n * ref only matters after a restart, when `DelegationTaskQueue.restore`\n * hands it to the `resumeDelegate` seam instead of failing the record.\n */\n detachedSessionRef?: string\n /**\n * Runs the underlying delegation. The queue passes a fresh `AbortSignal`\n * and a `report` channel for incremental progress updates. The function\n * MUST resolve with the typed `DelegationResultPayload['output']`; the\n * queue wraps it with the profile tag.\n */\n run: (ctx: DelegationRunContext) => Promise<DelegationResultPayload['output']>\n}\n\n/** @experimental Context handed to a `SubmitInput.run` function. */\nexport interface DelegationRunContext {\n signal: AbortSignal\n report(progress: DelegationProgress): void\n /** The `detachedSessionRef` recorded at submit, when one was supplied. */\n detachedSessionRef?: string\n /**\n * Replace the record's detached-run resume key — the detached dispatch path\n * calls this once the sandbox id is known so the persisted ref names a\n * resolvable box. Ignored after the record settles (a cancel racing the\n * rebind is legitimate; the ref no longer matters then). Throws on an empty\n * ref — erasing the resume key would silently make the record unresumable.\n */\n updateDetachedSessionRef(ref: string): void\n}\n\n/** @experimental */\nexport interface SubmitOutput {\n taskId: string\n /** True when a prior matching `idempotencyKey` returned an existing record. */\n reused: boolean\n}\n\n/**\n * One observation of a detached run, mapped 1:1 from a single-tick driver\n * (e.g. the sandbox SDK's `driveTurn`, which reports\n * completed | running | failed per pass). `running` schedules another tick\n * after `intervalMs`; `completed` / `failed` settle the record.\n *\n * @experimental\n */\nexport type DelegationResumeTick =\n | { state: 'running' }\n | { state: 'completed'; output: DelegationResultPayload['output']; costUsd?: number }\n | { state: 'failed'; error: DelegationError }\n\n/** @experimental */\nexport interface DelegationResumeContext {\n /** Fired by `cancel(taskId)`; the driver should stop the remote run when it can. */\n signal: AbortSignal\n report(progress: DelegationProgress): void\n}\n\n/**\n * Re-attaches restored in-flight records to their detached runs. The queue\n * calls `tick` repeatedly — it never awaits a whole run — so the driver can\n * be a thin wrapper over a one-pass primitive: resolve the run named by\n * `detachedSessionRef`, advance/poll it once, report where it stands. A\n * thrown error settles the record as failed; `failed` ticks are treated as\n * terminal and are not retried.\n *\n * @experimental\n */\nexport interface DelegationResumeDriver {\n tick(\n task: { record: DelegationRecord; detachedSessionRef: string },\n ctx: DelegationResumeContext,\n ): Promise<DelegationResumeTick>\n /** Delay between `running` ticks, in milliseconds. Default 5000. */\n intervalMs?: number\n}\n\n/** @experimental */\nexport interface DelegationTaskQueueOptions {\n /** ID generator override; default `randomTaskId`. */\n generateId?: () => string\n /** Clock override; default `() => new Date().toISOString()`. */\n now?: () => string\n /**\n * Journal for record mutations and the `restore()` load source. Default\n * `InMemoryDelegationStore` — observably identical to an unjournaled\n * queue. Pass a `FileDelegationStore` through\n * `DelegationTaskQueue.restore` for state that survives a restart;\n * constructing with `new` never loads prior state.\n */\n store?: DelegationStore\n /** Resume seam for restored in-flight records that carry a `detachedSessionRef`. */\n resumeDelegate?: DelegationResumeDriver\n /**\n * Maximum number of terminal (completed | failed | cancelled) records\n * retained; the oldest (by `completedAt`) are evicted from memory and\n * store once the cap is exceeded. Default unbounded.\n */\n maxTerminalRecords?: number\n /**\n * Observes the first store failure. After it fires, the queue refuses\n * new submissions and `flush()` rejects with the same error. Default:\n * rethrow on a microtask — an unhandled crash — because silently\n * degrading durable mode to memory-only would lie to the caller.\n */\n onPersistError?: (error: DelegationPersistenceError) => void\n}\n\n/** @experimental */\nexport class DelegationTaskQueue {\n private readonly records = new Map<string, DelegationRecord>()\n private readonly controllers = new Map<string, AbortController>()\n private readonly byIdempotencyKey = new Map<string, string>()\n private readonly generateId: () => string\n private readonly now: () => string\n private readonly store: DelegationStore\n private readonly resumeDelegate?: DelegationResumeDriver\n private readonly maxTerminalRecords: number\n private readonly onPersistError: (error: DelegationPersistenceError) => void\n private persistTail: Promise<void> = Promise.resolve()\n private persistFailure: DelegationPersistenceError | undefined\n\n constructor(options: DelegationTaskQueueOptions = {}) {\n this.generateId = options.generateId ?? randomTaskId\n this.now = options.now ?? (() => new Date().toISOString())\n this.store = options.store ?? new InMemoryDelegationStore()\n this.resumeDelegate = options.resumeDelegate\n if (options.maxTerminalRecords !== undefined) {\n if (!Number.isInteger(options.maxTerminalRecords) || options.maxTerminalRecords < 1) {\n throw new ValidationError(\n `DelegationTaskQueue: maxTerminalRecords must be a positive integer, got ${String(options.maxTerminalRecords)}`,\n )\n }\n }\n this.maxTerminalRecords = options.maxTerminalRecords ?? Number.POSITIVE_INFINITY\n this.onPersistError =\n options.onPersistError ??\n ((error) => {\n queueMicrotask(() => {\n throw error\n })\n })\n }\n\n /**\n * Construct a queue from previously-persisted state. Loads every record\n * from `options.store`, rebuilds the idempotency index (so a re-submitted\n * identical task returns the prior taskId and its terminal state), then:\n *\n * - terminal records stay queryable via `status()` / `history()`\n * - in-flight records with a `detachedSessionRef` re-attach through\n * `options.resumeDelegate` and report `running`\n * - other in-flight records settle as failed — their driver died with\n * the previous process and the result is unrecoverable\n *\n * The retention cap applies to the loaded set as well.\n */\n static async restore(options: DelegationTaskQueueOptions = {}): Promise<DelegationTaskQueue> {\n const queue = new DelegationTaskQueue(options)\n const loaded = await queue.store.loadAll()\n queue.rehydrate(loaded)\n return queue\n }\n\n /**\n * Kick off a delegation in the background. Returns immediately. The\n * `taskId` is queryable via `status` once this method returns. Throws\n * the recorded `DelegationPersistenceError` once the store has failed —\n * the queue does not accept work it cannot journal.\n */\n submit<Args extends AnyDelegateArgs>(input: SubmitInput<Args>): SubmitOutput {\n if (this.persistFailure) throw this.persistFailure\n if (input.idempotencyKey) {\n const existing = this.byIdempotencyKey.get(input.idempotencyKey)\n if (existing && this.records.has(existing)) {\n return { taskId: existing, reused: true }\n }\n }\n const taskId = this.generateId()\n const controller = new AbortController()\n const record: DelegationRecord = {\n taskId,\n profile: input.profile,\n namespace: input.namespace,\n args: input.args,\n status: 'pending',\n startedAt: this.now(),\n feedback: [],\n idempotencyKey: input.idempotencyKey,\n detachedSessionRef: input.detachedSessionRef,\n }\n this.records.set(taskId, record)\n this.controllers.set(taskId, controller)\n if (input.idempotencyKey) this.byIdempotencyKey.set(input.idempotencyKey, taskId)\n this.persist(record)\n\n // Fire-and-forget the run function. Errors flow into the record so the\n // status poll surfaces them; the promise itself is intentionally\n // unobserved by the queue.\n queueMicrotask(() => {\n this.execute(taskId, input, controller)\n })\n\n return { taskId, reused: false }\n }\n\n /**\n * Snapshot the current state of a delegation. Returns `undefined` for\n * unknown ids so callers can distinguish missing from terminal.\n */\n status(taskId: string): DelegationStatusResult | undefined {\n const record = this.records.get(taskId)\n if (!record) return undefined\n return toStatusResult(record)\n }\n\n /**\n * Abort an in-flight delegation. Returns `false` if the task is unknown\n * or already terminal. The underlying `run` function MUST honor the\n * abort signal for the cancel to take effect; the queue marks the\n * record `cancelled` regardless so a misbehaving runner cannot pin the\n * UI on `running` forever.\n */\n cancel(taskId: string): boolean {\n const record = this.records.get(taskId)\n if (!record) return false\n if (isTerminal(record.status)) return false\n const controller = this.controllers.get(taskId)\n controller?.abort()\n record.status = 'cancelled'\n record.completedAt = this.now()\n record.error = { message: 'cancelled by caller', kind: 'CancelledError' }\n this.persist(record)\n this.enforceRetention()\n return true\n }\n\n /**\n * Append a feedback event to the matching delegation. Returns `false`\n * when `ref` does not name a known taskId — the caller should still\n * record the feedback through a different surface (artifact/outcome\n * kinds are not queue-bound).\n */\n attachFeedback(taskId: string, snapshot: DelegationFeedbackSnapshot): boolean {\n const record = this.records.get(taskId)\n if (!record) return false\n record.feedback.push(snapshot)\n this.persist(record)\n return true\n }\n\n /**\n * Query the recorded delegations. Returns entries newest-first (by\n * `startedAt`), truncated to `limit`.\n */\n history(args: DelegationHistoryArgs = {}): DelegationHistoryEntry[] {\n const limit = clampLimit(args.limit)\n const since = args.since ? Date.parse(args.since) : Number.NEGATIVE_INFINITY\n const out: DelegationHistoryEntry[] = []\n for (const record of this.records.values()) {\n if (args.namespace && record.namespace !== args.namespace) continue\n if (args.profile && record.profile !== args.profile) continue\n if (Number.isFinite(since) && Date.parse(record.startedAt) < since) continue\n out.push(toHistoryEntry(record))\n }\n out.sort((a, b) => b.startedAt.localeCompare(a.startedAt))\n return out.slice(0, limit)\n }\n\n /**\n * Await every journal write issued so far. Rejects with the recorded\n * `DelegationPersistenceError` when any of them failed. Call before\n * handing the store's backing file to another process.\n */\n async flush(): Promise<void> {\n await this.persistTail\n if (this.persistFailure) throw this.persistFailure\n }\n\n /** Test-only — number of in-flight (non-terminal) records. */\n inflightCount(): number {\n let n = 0\n for (const record of this.records.values()) {\n if (!isTerminal(record.status)) n += 1\n }\n return n\n }\n\n private async execute<Args extends AnyDelegateArgs>(\n taskId: string,\n input: SubmitInput<Args>,\n controller: AbortController,\n ): Promise<void> {\n const record = this.records.get(taskId)\n if (!record) return\n record.status = 'running'\n this.persist(record)\n try {\n const output = await input.run({\n signal: controller.signal,\n report: (progress) => {\n if (record.status === 'running') {\n record.progress = progress\n this.persist(record)\n }\n },\n ...(record.detachedSessionRef !== undefined\n ? { detachedSessionRef: record.detachedSessionRef }\n : {}),\n updateDetachedSessionRef: (ref) => {\n if (typeof ref !== 'string' || ref.length === 0) {\n throw new ValidationError(\n 'DelegationTaskQueue: updateDetachedSessionRef requires a non-empty ref',\n )\n }\n if (isTerminal(currentStatus(record))) return\n record.detachedSessionRef = ref\n this.persist(record)\n },\n })\n // `cancel()` may have flipped the status to `cancelled` while the\n // run promise was pending. Read the field through a widening\n // helper so the narrowed `'running'` type from the assignment\n // above does not exclude that case at compile time.\n if (currentStatus(record) === 'cancelled') return\n record.status = 'completed'\n record.completedAt = this.now()\n record.result = { profile: input.profile, output } as DelegationResultPayload\n this.persist(record)\n this.enforceRetention()\n } catch (err) {\n if (currentStatus(record) === 'cancelled') return\n record.status = 'failed'\n record.completedAt = this.now()\n record.error = errorToShape(err)\n this.persist(record)\n this.enforceRetention()\n } finally {\n this.controllers.delete(taskId)\n }\n }\n\n private rehydrate(loaded: DelegationRecord[]): void {\n const records = [...loaded].sort((a, b) => a.startedAt.localeCompare(b.startedAt))\n for (const record of records) {\n this.records.set(record.taskId, record)\n if (record.idempotencyKey) this.byIdempotencyKey.set(record.idempotencyKey, record.taskId)\n }\n for (const record of this.records.values()) {\n if (isTerminal(record.status)) continue\n if (record.detachedSessionRef && this.resumeDelegate) {\n record.status = 'running'\n this.persist(record)\n this.startResume(record, record.detachedSessionRef, this.resumeDelegate)\n continue\n }\n record.status = 'failed'\n record.completedAt = this.now()\n record.error = {\n message: record.detachedSessionRef\n ? `delegation driver restarted while the task was in flight; detached session \"${record.detachedSessionRef}\" needs a resumeDelegate to be resumed`\n : 'delegation driver restarted while the task was in flight; the run was not detached and cannot be resumed',\n kind: 'DriverRestartError',\n }\n this.persist(record)\n }\n this.enforceRetention()\n }\n\n private startResume(\n record: DelegationRecord,\n detachedSessionRef: string,\n driver: DelegationResumeDriver,\n ): void {\n const controller = new AbortController()\n this.controllers.set(record.taskId, controller)\n void this.driveResume(record, detachedSessionRef, driver, controller)\n }\n\n private async driveResume(\n record: DelegationRecord,\n detachedSessionRef: string,\n driver: DelegationResumeDriver,\n controller: AbortController,\n ): Promise<void> {\n const intervalMs = driver.intervalMs ?? 5000\n const ctx: DelegationResumeContext = {\n signal: controller.signal,\n report: (progress) => {\n if (currentStatus(record) !== 'running') return\n record.progress = progress\n this.persist(record)\n },\n }\n try {\n while (!controller.signal.aborted && currentStatus(record) === 'running') {\n const tick = await driver.tick({ record: structuredClone(record), detachedSessionRef }, ctx)\n if (currentStatus(record) === 'cancelled') return\n if (tick.state === 'completed') {\n record.status = 'completed'\n record.completedAt = this.now()\n record.result = {\n profile: record.profile,\n output: tick.output,\n } as DelegationResultPayload\n if (tick.costUsd !== undefined) record.costUsd = tick.costUsd\n this.persist(record)\n this.enforceRetention()\n return\n }\n if (tick.state === 'failed') {\n record.status = 'failed'\n record.completedAt = this.now()\n record.error = tick.error\n this.persist(record)\n this.enforceRetention()\n return\n }\n await abortableDelay(intervalMs, controller.signal)\n }\n } catch (err) {\n if (currentStatus(record) === 'cancelled') return\n record.status = 'failed'\n record.completedAt = this.now()\n record.error = errorToShape(err)\n this.persist(record)\n this.enforceRetention()\n } finally {\n this.controllers.delete(record.taskId)\n }\n }\n\n private persist(record: DelegationRecord): void {\n if (this.persistFailure) return\n const snapshot = structuredClone(record)\n this.persistTail = this.persistTail.then(async () => {\n if (this.persistFailure) return\n try {\n await this.store.upsert(snapshot)\n } catch (err) {\n this.failPersistence(err)\n }\n })\n }\n\n private persistRemoval(taskIds: string[]): void {\n if (this.persistFailure || taskIds.length === 0) return\n this.persistTail = this.persistTail.then(async () => {\n if (this.persistFailure) return\n try {\n await this.store.remove(taskIds)\n } catch (err) {\n this.failPersistence(err)\n }\n })\n }\n\n private failPersistence(cause: unknown): void {\n if (this.persistFailure) return\n const error =\n cause instanceof DelegationPersistenceError\n ? cause\n : new DelegationPersistenceError(\n `DelegationTaskQueue: store write failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n )\n this.persistFailure = error\n this.onPersistError(error)\n }\n\n private enforceRetention(): void {\n if (!Number.isFinite(this.maxTerminalRecords)) return\n const terminal: DelegationRecord[] = []\n for (const record of this.records.values()) {\n if (isTerminal(record.status)) terminal.push(record)\n }\n const excess = terminal.length - this.maxTerminalRecords\n if (excess <= 0) return\n terminal.sort((a, b) =>\n (a.completedAt ?? a.startedAt).localeCompare(b.completedAt ?? b.startedAt),\n )\n const evicted = terminal.slice(0, excess)\n for (const record of evicted) {\n this.records.delete(record.taskId)\n if (\n record.idempotencyKey &&\n this.byIdempotencyKey.get(record.idempotencyKey) === record.taskId\n ) {\n this.byIdempotencyKey.delete(record.idempotencyKey)\n }\n }\n this.persistRemoval(evicted.map((record) => record.taskId))\n }\n}\n\nfunction isTerminal(status: DelegationStatus): boolean {\n return status === 'completed' || status === 'failed' || status === 'cancelled'\n}\n\nfunction currentStatus(record: DelegationRecord): DelegationStatus {\n return record.status\n}\n\nfunction clampLimit(raw: number | undefined): number {\n if (!Number.isFinite(raw)) return 50\n const n = Math.trunc(raw as number)\n if (n <= 0) return 50\n return Math.min(n, 500)\n}\n\nfunction abortableDelay(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) {\n resolve()\n return\n }\n const onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n signal.addEventListener('abort', onAbort, { once: true })\n })\n}\n\nfunction toStatusResult(record: DelegationRecord): DelegationStatusResult {\n const out: DelegationStatusResult = {\n taskId: record.taskId,\n profile: record.profile,\n status: record.status,\n startedAt: record.startedAt,\n }\n if (record.progress) out.progress = record.progress\n if (record.result) out.result = record.result\n if (record.error) out.error = record.error\n if (record.costUsd !== undefined) out.costUsd = record.costUsd\n if (record.completedAt) out.completedAt = record.completedAt\n return out\n}\n\nfunction toHistoryEntry(record: DelegationRecord): DelegationHistoryEntry {\n const entry: DelegationHistoryEntry = {\n taskId: record.taskId,\n profile: record.profile,\n args: record.args,\n status: record.status,\n startedAt: record.startedAt,\n }\n if (record.namespace) entry.namespace = record.namespace\n if (record.completedAt) entry.completedAt = record.completedAt\n if (record.costUsd !== undefined) entry.costUsd = record.costUsd\n if (record.feedback.length > 0) entry.feedback = [...record.feedback]\n return entry\n}\n\nfunction errorToShape(err: unknown): DelegationError {\n if (err instanceof Error) {\n return { message: err.message, kind: err.name || 'Error' }\n }\n return { message: String(err), kind: 'NonError' }\n}\n\nfunction randomTaskId(): string {\n // Caller-stable id: `dlg-${timestamp}-${random}`. The timestamp portion\n // makes lexicographic sort match chronological order in history queries\n // even when the system clock skews under the second.\n const t = Date.now().toString(36)\n const r = Math.random().toString(36).slice(2, 10)\n return `dlg-${t}-${r}`\n}\n\n/**\n * Best-effort stable hash for use as `idempotencyKey`. Not cryptographic;\n * collisions only affect dedupe, never correctness.\n *\n * @experimental\n */\nexport function hashIdempotencyInput(value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(canonicalize(value))\n } catch {\n str = String(value)\n }\n // FNV-1a 32-bit\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\nfunction canonicalize(value: unknown): unknown {\n if (value === null || typeof value !== 'object') return value\n if (Array.isArray(value)) return value.map(canonicalize)\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => a.localeCompare(b))\n const out: Record<string, unknown> = {}\n for (const [k, v] of entries) out[k] = canonicalize(v)\n return out\n}\n\n// Re-exports re-used by the feedback-store + handler glue. Kept local so\n// consumers of the queue don't have to import from `./types` separately.\nexport type {\n DelegateCodeArgs,\n DelegateCodeResult,\n DelegateFeedbackArgs,\n DelegateFeedbackResult,\n DelegateResearchArgs,\n DelegateResearchResult,\n DelegateUiAuditArgs,\n DelegateUiAuditConfig,\n DelegateUiAuditResult,\n DelegateUiAuditRoute,\n DelegationError,\n DelegationFeedbackSnapshot,\n DelegationHistoryArgs,\n DelegationHistoryEntry,\n DelegationHistoryResult,\n DelegationProfile,\n DelegationProgress,\n DelegationResultPayload,\n DelegationStatus,\n DelegationStatusArgs,\n DelegationStatusResult,\n UiAuditorDelegationOutput,\n} from './types'\n","/**\n * @experimental\n *\n * `delegate_code` MCP tool — async kickoff. The handler validates the\n * input, computes an idempotency key over the canonical fields, hands\n * the task to the queue, and returns `{ taskId, estimatedDurationMs }`.\n */\n\nimport type { CoderDelegate } from '../delegates'\nimport { formatDetachedSessionRef } from '../detached-turn'\nimport {\n type DelegateCodeArgs,\n type DelegateCodeResult,\n type DelegationTaskQueue,\n hashIdempotencyInput,\n} from '../task-queue'\n\n/** @experimental */\nexport const DELEGATE_CODE_TOOL_NAME = 'delegate_code'\n\n/** @experimental */\nexport const DELEGATE_CODE_DESCRIPTION = [\n 'Delegate a coding task to specialist coder agents that produce a validated patch.',\n '',\n 'Use when: you need code written, fixed, refactored, or extended to satisfy a',\n 'user goal that touches a real repository. The coder runs in an isolated',\n 'sandbox, opens a fresh branch, keeps the diff minimal, runs the supplied',\n 'test + typecheck commands, and emits a unified-diff patch.',\n '',\n 'Returns immediately with a taskId. Poll delegation_status to retrieve the',\n 'patch + validator verdict (typically minutes-to-hours, longer for large',\n 'changes). Identical inputs return the same taskId — safe to retry.',\n '',\n 'When variants > 1, multiple coder harnesses (claude-code, codex, opencode)',\n 'attempt the task in parallel and the highest-scoring patch wins (smallest',\n 'passing diff). Use variants for high-stakes changes; single variant for',\n 'routine ones.',\n '',\n 'Capability scope: the coder cannot modify paths outside repoRoot and cannot',\n 'touch paths in config.forbiddenPaths. The validator hard-fails on a',\n 'forbidden-path violation, diff above config.maxDiffLines, test failure, or',\n 'typecheck failure — none of those make it past the gate.',\n].join('\\n')\n\n/** @experimental */\nexport const DELEGATE_CODE_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n goal: {\n type: 'string',\n description: 'Natural-language description of what the coder must accomplish.',\n },\n repoRoot: {\n type: 'string',\n description: 'Absolute path inside the sandbox where the repo lives.',\n },\n contextHint: {\n type: 'string',\n description: 'Optional free-form context the coder sees in the prompt prelude.',\n },\n variants: {\n type: 'integer',\n minimum: 1,\n maximum: 8,\n description: 'Number of parallel coder harnesses. Default 1.',\n },\n config: {\n type: 'object',\n properties: {\n testCmd: { type: 'string' },\n typecheckCmd: { type: 'string' },\n forbiddenPaths: { type: 'array', items: { type: 'string' } },\n maxDiffLines: { type: 'integer', minimum: 1 },\n },\n additionalProperties: false,\n },\n namespace: {\n type: 'string',\n description: 'Multi-tenant scope (customer-id, workspace-id).',\n },\n },\n required: ['goal', 'repoRoot'],\n additionalProperties: false,\n} as const\n\nconst SINGLE_VARIANT_ESTIMATE_MS = 6 * 60 * 1000 // 6 minutes — single coder\nconst FANOUT_PER_VARIANT_ESTIMATE_MS = 8 * 60 * 1000 // 8 minutes — fanout\n\n/** @experimental */\nexport function validateDelegateCodeArgs(raw: unknown): DelegateCodeArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_code: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const goal = value.goal\n if (typeof goal !== 'string' || goal.trim().length === 0) {\n throw new TypeError('delegate_code: `goal` must be a non-empty string')\n }\n const repoRoot = value.repoRoot\n if (typeof repoRoot !== 'string' || repoRoot.trim().length === 0) {\n throw new TypeError('delegate_code: `repoRoot` must be a non-empty string')\n }\n const args: DelegateCodeArgs = { goal: goal.trim(), repoRoot: repoRoot.trim() }\n if (typeof value.contextHint === 'string') args.contextHint = value.contextHint\n if (value.variants !== undefined) {\n const variants = Number(value.variants)\n if (!Number.isFinite(variants) || variants < 1 || variants > 8) {\n throw new RangeError('delegate_code: `variants` must be an integer in [1, 8]')\n }\n args.variants = Math.trunc(variants)\n }\n if (value.config !== undefined) {\n args.config = validateConfig(value.config)\n }\n if (typeof value.namespace === 'string') args.namespace = value.namespace\n return args\n}\n\nfunction validateConfig(raw: unknown): DelegateCodeArgs['config'] {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_code: `config` must be an object')\n }\n const value = raw as Record<string, unknown>\n const out: NonNullable<DelegateCodeArgs['config']> = {}\n if (value.testCmd !== undefined) {\n if (typeof value.testCmd !== 'string') {\n throw new TypeError('delegate_code: `config.testCmd` must be a string')\n }\n out.testCmd = value.testCmd\n }\n if (value.typecheckCmd !== undefined) {\n if (typeof value.typecheckCmd !== 'string') {\n throw new TypeError('delegate_code: `config.typecheckCmd` must be a string')\n }\n out.typecheckCmd = value.typecheckCmd\n }\n if (value.forbiddenPaths !== undefined) {\n if (!Array.isArray(value.forbiddenPaths)) {\n throw new TypeError('delegate_code: `config.forbiddenPaths` must be a string array')\n }\n out.forbiddenPaths = value.forbiddenPaths.map((entry, i) => {\n if (typeof entry !== 'string') {\n throw new TypeError(`delegate_code: forbiddenPaths[${i}] must be a string`)\n }\n return entry\n })\n }\n if (value.maxDiffLines !== undefined) {\n const n = Number(value.maxDiffLines)\n if (!Number.isFinite(n) || n < 1) {\n throw new RangeError('delegate_code: `config.maxDiffLines` must be a positive integer')\n }\n out.maxDiffLines = Math.trunc(n)\n }\n return out\n}\n\n/** @experimental */\nexport interface DelegateCodeHandlerOptions {\n queue: DelegationTaskQueue\n delegate: CoderDelegate\n /** Override the duration hint. */\n estimateDurationMs?: (args: DelegateCodeArgs) => number\n /**\n * Record a deterministic detached-session resume key on single-variant\n * submissions (derived from the idempotency key, so retried identical\n * inputs name the same logical turn). Enable only when the wired delegate\n * dispatches via sandbox sessions — `createDefaultCoderDelegate` routes\n * onto its `driveTurn` tick path when the ref is present. Fanout\n * (`variants > 1`) never records a ref: one resume key cannot express N\n * sessions + winner selection.\n */\n detachedDispatch?: boolean\n}\n\n/** @experimental */\nexport function createDelegateCodeHandler(\n options: DelegateCodeHandlerOptions,\n): (raw: unknown) => Promise<DelegateCodeResult> {\n const estimateDurationMs = options.estimateDurationMs ?? defaultEstimate\n return async (raw) => {\n const args = validateDelegateCodeArgs(raw)\n const idempotencyKey = hashIdempotencyInput({\n profile: 'coder',\n goal: args.goal,\n repoRoot: args.repoRoot,\n contextHint: args.contextHint,\n variants: args.variants ?? 1,\n config: args.config,\n namespace: args.namespace,\n })\n const detached = options.detachedDispatch === true && (args.variants ?? 1) <= 1\n const submitted = options.queue.submit<DelegateCodeArgs>({\n profile: 'coder',\n args,\n namespace: args.namespace,\n idempotencyKey,\n ...(detached\n ? {\n detachedSessionRef: formatDetachedSessionRef({\n sessionId: `dlg-turn-coder-${idempotencyKey}`,\n }),\n }\n : {}),\n run: async (ctx) => options.delegate(args, ctx),\n })\n return {\n taskId: submitted.taskId,\n estimatedDurationMs: estimateDurationMs(args),\n }\n }\n}\n\nfunction defaultEstimate(args: DelegateCodeArgs): number {\n const variants = Math.max(1, args.variants ?? 1)\n if (variants === 1) return SINGLE_VARIANT_ESTIMATE_MS\n return FANOUT_PER_VARIANT_ESTIMATE_MS\n}\n","/**\n * @experimental\n *\n * Feedback persistence surface for the MCP layer.\n *\n * The substrate cannot import `@tangle-network/agent-knowledge` (it would\n * induce a dependency cycle), so the store is an abstract interface. The\n * default implementation is in-memory; consumers wire their own adapter\n * (a real KbStore-backed sink, an HTTP relay to gtm-agent's knowledge\n * service, etc.) via `createMcpServer({ feedbackStore })`.\n *\n * Feedback events are append-only: every rating is a new event with a\n * fresh id, even when the same delegation is rated multiple times. The\n * caller decides how to roll up scores downstream.\n */\n\nimport type { DelegateFeedbackArgs, DelegationFeedbackSnapshot } from './types'\n\n/** @experimental */\nexport interface FeedbackEvent {\n id: string\n refersTo: DelegateFeedbackArgs['refersTo']\n rating: DelegateFeedbackArgs['rating']\n by: DelegateFeedbackArgs['by']\n capturedAt: string\n namespace?: string\n}\n\n/** @experimental */\nexport interface FeedbackStore {\n /** Append a new event. Never dedupes — every rating is its own event. */\n put(event: FeedbackEvent): Promise<void>\n /**\n * List events filtered by `namespace`. When `namespace` is omitted, list\n * across all namespaces. Returns events in insertion order.\n */\n list(filter?: { namespace?: string; refersToRef?: string }): Promise<FeedbackEvent[]>\n}\n\n/** @experimental */\nexport class InMemoryFeedbackStore implements FeedbackStore {\n private readonly events: FeedbackEvent[] = []\n\n async put(event: FeedbackEvent): Promise<void> {\n this.events.push({ ...event })\n }\n\n async list(filter: { namespace?: string; refersToRef?: string } = {}): Promise<FeedbackEvent[]> {\n let out = this.events\n if (filter.namespace !== undefined) {\n out = out.filter((event) => event.namespace === filter.namespace)\n }\n if (filter.refersToRef !== undefined) {\n out = out.filter((event) => event.refersTo.ref === filter.refersToRef)\n }\n return out.map((event) => ({ ...event }))\n }\n}\n\n/**\n * Project a `FeedbackEvent` down to the snapshot shape carried on\n * `delegation_history` entries.\n *\n * @experimental\n */\nexport function eventToSnapshot(event: FeedbackEvent): DelegationFeedbackSnapshot {\n const snap: DelegationFeedbackSnapshot = {\n id: event.id,\n score: event.rating.score,\n by: event.by,\n notes: event.rating.notes,\n capturedAt: event.capturedAt,\n }\n if (event.rating.label) snap.label = event.rating.label\n return snap\n}\n","/**\n * @experimental\n *\n * `delegate_feedback` MCP tool — synchronous record of agent / user /\n * downstream-judge feedback on a delegation, artifact, or outcome.\n *\n * The store is append-only. Every rating is its own event; no dedupe.\n * When `refersTo.kind === 'delegation'`, the snapshot is also attached\n * to the matching queue record so `delegation_history` surfaces it\n * inline without a join.\n */\n\nimport type { FeedbackStore } from '../feedback-store'\nimport { eventToSnapshot } from '../feedback-store'\nimport type { DelegationTaskQueue } from '../task-queue'\nimport type {\n DelegateFeedbackArgs,\n DelegateFeedbackResult,\n FeedbackRating,\n FeedbackRefersTo,\n} from '../types'\n\n/** @experimental */\nexport const DELEGATE_FEEDBACK_TOOL_NAME = 'delegate_feedback'\n\n/** @experimental */\nexport const DELEGATE_FEEDBACK_DESCRIPTION = [\n 'Record feedback on a delegation, artifact, or outcome. Synchronous — the',\n 'event is durably stored when this call returns.',\n '',\n 'Use when: you (the agent), the user, or a downstream judge has formed an',\n 'opinion about a piece of work and want it persisted for calibration,',\n 'pricing, or future routing. Every call is a new event — multiple ratings',\n 'on the same target are expected and never deduped.',\n '',\n '`refersTo.kind`:',\n ' - \"delegation\": ref is a taskId returned by delegate_code/delegate_research',\n ' - \"artifact\": ref is a URI/path/git-sha — anything you can dereference',\n ' - \"outcome\": ref is a free-form description of a downstream result',\n '',\n '`by`:',\n ' - \"agent\": the agent itself rated the work',\n ' - \"user\": the human user rated it',\n ' - \"downstream-judge\": an automated evaluator emitted the rating',\n '',\n 'When ref names a known taskId, the rating is also attached to the',\n 'delegation record so delegation_history surfaces it inline.',\n].join('\\n')\n\n/** @experimental */\nexport const DELEGATE_FEEDBACK_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n refersTo: {\n type: 'object',\n properties: {\n kind: { type: 'string', enum: ['delegation', 'artifact', 'outcome'] },\n ref: { type: 'string' },\n },\n required: ['kind', 'ref'],\n additionalProperties: false,\n },\n rating: {\n type: 'object',\n properties: {\n score: { type: 'number', minimum: 0, maximum: 1 },\n label: { type: 'string', enum: ['good', 'bad', 'neutral', 'mixed'] },\n notes: { type: 'string' },\n },\n required: ['score', 'notes'],\n additionalProperties: false,\n },\n by: { type: 'string', enum: ['agent', 'user', 'downstream-judge'] },\n capturedAt: { type: 'string' },\n namespace: { type: 'string' },\n },\n required: ['refersTo', 'rating', 'by'],\n additionalProperties: false,\n} as const\n\n/** @experimental */\nexport function validateDelegateFeedbackArgs(raw: unknown): DelegateFeedbackArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const refersTo = validateRefersTo(value.refersTo)\n const rating = validateRating(value.rating)\n const by = value.by\n if (by !== 'agent' && by !== 'user' && by !== 'downstream-judge') {\n throw new TypeError(\n 'delegate_feedback: `by` must be one of \"agent\" | \"user\" | \"downstream-judge\"',\n )\n }\n const args: DelegateFeedbackArgs = { refersTo, rating, by }\n if (value.capturedAt !== undefined) {\n if (typeof value.capturedAt !== 'string' || Number.isNaN(Date.parse(value.capturedAt))) {\n throw new TypeError('delegate_feedback: `capturedAt` must be an ISO datetime')\n }\n args.capturedAt = value.capturedAt\n }\n if (typeof value.namespace === 'string') args.namespace = value.namespace\n return args\n}\n\nfunction validateRefersTo(raw: unknown): FeedbackRefersTo {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: `refersTo` must be an object')\n }\n const value = raw as Record<string, unknown>\n const kind = value.kind\n if (kind !== 'delegation' && kind !== 'artifact' && kind !== 'outcome') {\n throw new TypeError(\n 'delegate_feedback: `refersTo.kind` must be one of \"delegation\" | \"artifact\" | \"outcome\"',\n )\n }\n const ref = value.ref\n if (typeof ref !== 'string' || ref.trim().length === 0) {\n throw new TypeError('delegate_feedback: `refersTo.ref` must be a non-empty string')\n }\n return { kind, ref: ref.trim() }\n}\n\nfunction validateRating(raw: unknown): FeedbackRating {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_feedback: `rating` must be an object')\n }\n const value = raw as Record<string, unknown>\n const score = Number(value.score)\n if (!Number.isFinite(score) || score < 0 || score > 1) {\n throw new RangeError('delegate_feedback: `rating.score` must be a number in [0, 1]')\n }\n const notes = value.notes\n if (typeof notes !== 'string') {\n throw new TypeError('delegate_feedback: `rating.notes` must be a string')\n }\n const rating: FeedbackRating = { score, notes }\n const label = value.label\n if (label !== undefined) {\n if (label !== 'good' && label !== 'bad' && label !== 'neutral' && label !== 'mixed') {\n throw new TypeError(\n 'delegate_feedback: `rating.label` must be one of \"good\" | \"bad\" | \"neutral\" | \"mixed\"',\n )\n }\n rating.label = label\n }\n return rating\n}\n\n/** @experimental */\nexport interface DelegateFeedbackHandlerOptions {\n queue: DelegationTaskQueue\n store: FeedbackStore\n generateId?: () => string\n now?: () => string\n}\n\n/** @experimental */\nexport function createDelegateFeedbackHandler(\n options: DelegateFeedbackHandlerOptions,\n): (raw: unknown) => Promise<DelegateFeedbackResult> {\n const generateId = options.generateId ?? randomFeedbackId\n const now = options.now ?? (() => new Date().toISOString())\n return async (raw) => {\n const args = validateDelegateFeedbackArgs(raw)\n const id = generateId()\n const event = {\n id,\n refersTo: args.refersTo,\n rating: args.rating,\n by: args.by,\n capturedAt: args.capturedAt ?? now(),\n namespace: args.namespace,\n }\n await options.store.put(event)\n if (args.refersTo.kind === 'delegation') {\n options.queue.attachFeedback(args.refersTo.ref, eventToSnapshot(event))\n }\n return { recorded: true, id }\n }\n}\n\nfunction randomFeedbackId(): string {\n const t = Date.now().toString(36)\n const r = Math.random().toString(36).slice(2, 10)\n return `fbk-${t}-${r}`\n}\n","/**\n * @experimental\n *\n * `delegate_research` MCP tool — async kickoff for source-grounded\n * research tasks. Same async semantics as `delegate_code`: returns a\n * taskId immediately, idempotent on canonical inputs.\n *\n * The handler does not import a researcher profile directly — consumers\n * inject a `ResearcherDelegate` via `createMcpServer({ researcherDelegate })`.\n * The substrate cannot depend on `@tangle-network/agent-knowledge`\n * without inducing a dependency cycle.\n */\n\nimport type { ResearcherDelegate } from '../delegates'\nimport { formatDetachedSessionRef } from '../detached-turn'\nimport {\n type DelegateResearchArgs,\n type DelegateResearchResult,\n type DelegationTaskQueue,\n hashIdempotencyInput,\n} from '../task-queue'\nimport type { ResearchSource } from '../types'\n\n/** @experimental */\nexport const DELEGATE_RESEARCH_TOOL_NAME = 'delegate_research'\n\n/** @experimental */\nexport const DELEGATE_RESEARCH_DESCRIPTION = [\n 'Delegate a research question to specialist researcher agents that produce',\n 'source-grounded, evidence-bearing knowledge items.',\n '',\n 'Use when: you need to answer a factual question with external evidence —',\n 'audience research, competitive intelligence, recency-bound web searches,',\n 'corpus / docs lookups. The researcher emits items[] with provenance, a',\n 'citations[] index, and proposedWrites[] you decide whether to persist.',\n '',\n 'Returns immediately with a taskId. Poll delegation_status to retrieve the',\n 'items + verdict. Identical inputs return the same taskId — safe to retry.',\n '',\n 'When variants > 1, multiple researcher harnesses run in parallel and the',\n 'highest-scoring valid output wins (citation density × source diversity ×',\n 'recency match × gap coverage). Use variants when answers might disagree.',\n '',\n 'Multi-tenant isolation: every item carries `namespace`. The validator',\n 'hard-fails when any item is scoped outside `namespace`. Never pass another',\n \"tenant's namespace.\",\n].join('\\n')\n\nconst VALID_SOURCES: readonly ResearchSource[] = ['web', 'corpus', 'twitter', 'github', 'docs']\n\n/** @experimental */\nexport const DELEGATE_RESEARCH_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n question: {\n type: 'string',\n description: 'The research question to answer.',\n },\n namespace: {\n type: 'string',\n description: 'Multi-tenant scope (customer-id, workspace-id). REQUIRED.',\n },\n scope: { type: 'string', description: 'Bound, e.g. \"audience for cpg-founder ICP\".' },\n sources: {\n type: 'array',\n items: { type: 'string', enum: [...VALID_SOURCES] },\n },\n variants: { type: 'integer', minimum: 1, maximum: 8 },\n config: {\n type: 'object',\n properties: {\n recencyWindow: {\n type: 'object',\n properties: {\n since: { type: 'string', description: 'ISO datetime' },\n until: { type: 'string', description: 'ISO datetime' },\n },\n additionalProperties: false,\n },\n maxItems: { type: 'integer', minimum: 1 },\n minConfidence: { type: 'number', minimum: 0, maximum: 1 },\n },\n additionalProperties: false,\n },\n },\n required: ['question', 'namespace'],\n additionalProperties: false,\n} as const\n\nconst SINGLE_VARIANT_ESTIMATE_MS = 4 * 60 * 1000\nconst FANOUT_PER_VARIANT_ESTIMATE_MS = 6 * 60 * 1000\n\n/** @experimental */\nexport function validateDelegateResearchArgs(raw: unknown): DelegateResearchArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_research: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const question = value.question\n if (typeof question !== 'string' || question.trim().length === 0) {\n throw new TypeError('delegate_research: `question` must be a non-empty string')\n }\n const namespace = value.namespace\n if (typeof namespace !== 'string' || namespace.trim().length === 0) {\n throw new TypeError('delegate_research: `namespace` is required')\n }\n const args: DelegateResearchArgs = { question: question.trim(), namespace: namespace.trim() }\n if (typeof value.scope === 'string') args.scope = value.scope\n if (value.sources !== undefined) {\n if (!Array.isArray(value.sources)) {\n throw new TypeError('delegate_research: `sources` must be a string array')\n }\n const sources: ResearchSource[] = value.sources.map((src, i) => {\n if (typeof src !== 'string' || !VALID_SOURCES.includes(src as ResearchSource)) {\n throw new TypeError(\n `delegate_research: sources[${i}] must be one of ${VALID_SOURCES.join('|')}`,\n )\n }\n return src as ResearchSource\n })\n args.sources = sources\n }\n if (value.variants !== undefined) {\n const variants = Number(value.variants)\n if (!Number.isFinite(variants) || variants < 1 || variants > 8) {\n throw new RangeError('delegate_research: `variants` must be an integer in [1, 8]')\n }\n args.variants = Math.trunc(variants)\n }\n if (value.config !== undefined) {\n args.config = validateConfig(value.config)\n }\n return args\n}\n\nfunction validateConfig(raw: unknown): DelegateResearchArgs['config'] {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegate_research: `config` must be an object')\n }\n const value = raw as Record<string, unknown>\n const out: NonNullable<DelegateResearchArgs['config']> = {}\n if (value.recencyWindow !== undefined) {\n if (value.recencyWindow === null || typeof value.recencyWindow !== 'object') {\n throw new TypeError('delegate_research: `config.recencyWindow` must be an object')\n }\n const window = value.recencyWindow as Record<string, unknown>\n const windowOut: NonNullable<NonNullable<DelegateResearchArgs['config']>['recencyWindow']> = {}\n if (window.since !== undefined) {\n if (typeof window.since !== 'string' || Number.isNaN(Date.parse(window.since))) {\n throw new TypeError('delegate_research: `recencyWindow.since` must be an ISO datetime')\n }\n windowOut.since = window.since\n }\n if (window.until !== undefined) {\n if (typeof window.until !== 'string' || Number.isNaN(Date.parse(window.until))) {\n throw new TypeError('delegate_research: `recencyWindow.until` must be an ISO datetime')\n }\n windowOut.until = window.until\n }\n out.recencyWindow = windowOut\n }\n if (value.maxItems !== undefined) {\n const n = Number(value.maxItems)\n if (!Number.isFinite(n) || n < 1) {\n throw new RangeError('delegate_research: `config.maxItems` must be a positive integer')\n }\n out.maxItems = Math.trunc(n)\n }\n if (value.minConfidence !== undefined) {\n const n = Number(value.minConfidence)\n if (!Number.isFinite(n) || n < 0 || n > 1) {\n throw new RangeError('delegate_research: `config.minConfidence` must be in [0, 1]')\n }\n out.minConfidence = n\n }\n return out\n}\n\n/** @experimental */\nexport interface DelegateResearchHandlerOptions {\n queue: DelegationTaskQueue\n delegate: ResearcherDelegate\n estimateDurationMs?: (args: DelegateResearchArgs) => number\n /**\n * Record a deterministic detached-session resume key on single-variant\n * submissions. Same contract as `DelegateCodeHandlerOptions.detachedDispatch`.\n */\n detachedDispatch?: boolean\n}\n\n/** @experimental */\nexport function createDelegateResearchHandler(\n options: DelegateResearchHandlerOptions,\n): (raw: unknown) => Promise<DelegateResearchResult> {\n const estimateDurationMs = options.estimateDurationMs ?? defaultEstimate\n return async (raw) => {\n const args = validateDelegateResearchArgs(raw)\n const idempotencyKey = hashIdempotencyInput({\n profile: 'researcher',\n question: args.question,\n namespace: args.namespace,\n scope: args.scope,\n sources: args.sources,\n variants: args.variants ?? 1,\n config: args.config,\n })\n const detached = options.detachedDispatch === true && (args.variants ?? 1) <= 1\n const submitted = options.queue.submit<DelegateResearchArgs>({\n profile: 'researcher',\n args,\n namespace: args.namespace,\n idempotencyKey,\n ...(detached\n ? {\n detachedSessionRef: formatDetachedSessionRef({\n sessionId: `dlg-turn-research-${idempotencyKey}`,\n }),\n }\n : {}),\n run: async (ctx) => options.delegate(args, ctx),\n })\n return {\n taskId: submitted.taskId,\n estimatedDurationMs: estimateDurationMs(args),\n }\n }\n}\n\nfunction defaultEstimate(args: DelegateResearchArgs): number {\n const variants = Math.max(1, args.variants ?? 1)\n if (variants === 1) return SINGLE_VARIANT_ESTIMATE_MS\n return FANOUT_PER_VARIANT_ESTIMATE_MS\n}\n","/**\n * @experimental\n *\n * `delegation_history` MCP tool — synchronous read of past delegations.\n * The agent uses this for self-introspection — \"have I delegated this\n * kind of task before? did it work?\" — and calibration.\n */\n\nimport type {\n DelegationHistoryArgs,\n DelegationHistoryResult,\n DelegationProfile,\n DelegationTaskQueue,\n} from '../task-queue'\n\n/** @experimental */\nexport const DELEGATION_HISTORY_TOOL_NAME = 'delegation_history'\n\n/** @experimental */\nexport const DELEGATION_HISTORY_DESCRIPTION = [\n 'Read past delegations newest-first. Each entry carries the original',\n 'arguments, current status, cost, and any feedback attached via',\n 'delegate_feedback.',\n '',\n 'Use when: you want to introspect prior decisions — \"have I asked this',\n 'question before?',\n 'did the last patch land?',\n \"what's the historical\",\n 'success rate of coder delegations on this repo?\". Feed the results back',\n 'into your own routing and calibration.',\n '',\n 'Filters: `namespace` (multi-tenant scope), `profile` (\"coder\" | \"researcher\"),',\n '`since` (ISO date — only delegations started at-or-after). `limit` defaults',\n 'to 50, capped at 500.',\n].join('\\n')\n\n/** @experimental */\nexport const DELEGATION_HISTORY_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n namespace: { type: 'string' },\n profile: { type: 'string', enum: ['coder', 'researcher'] },\n since: { type: 'string', description: 'ISO datetime — earliest startedAt to include.' },\n limit: { type: 'integer', minimum: 1, maximum: 500 },\n },\n additionalProperties: false,\n} as const\n\n/** @experimental */\nexport function validateDelegationHistoryArgs(raw: unknown): DelegationHistoryArgs {\n if (raw === undefined || raw === null) return {}\n if (typeof raw !== 'object') {\n throw new TypeError('delegation_history: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const out: DelegationHistoryArgs = {}\n if (value.namespace !== undefined) {\n if (typeof value.namespace !== 'string') {\n throw new TypeError('delegation_history: `namespace` must be a string')\n }\n out.namespace = value.namespace\n }\n if (value.profile !== undefined) {\n if (value.profile !== 'coder' && value.profile !== 'researcher') {\n throw new TypeError('delegation_history: `profile` must be \"coder\" or \"researcher\"')\n }\n out.profile = value.profile as DelegationProfile\n }\n if (value.since !== undefined) {\n if (typeof value.since !== 'string' || Number.isNaN(Date.parse(value.since))) {\n throw new TypeError('delegation_history: `since` must be an ISO datetime')\n }\n out.since = value.since\n }\n if (value.limit !== undefined) {\n const n = Number(value.limit)\n if (!Number.isFinite(n) || n < 1 || n > 500) {\n throw new RangeError('delegation_history: `limit` must be an integer in [1, 500]')\n }\n out.limit = Math.trunc(n)\n }\n return out\n}\n\n/** @experimental */\nexport interface DelegationHistoryHandlerOptions {\n queue: DelegationTaskQueue\n}\n\n/** @experimental */\nexport function createDelegationHistoryHandler(\n options: DelegationHistoryHandlerOptions,\n): (raw: unknown) => Promise<DelegationHistoryResult> {\n return async (raw) => {\n const args = validateDelegationHistoryArgs(raw)\n return { delegations: options.queue.history(args) }\n }\n}\n","/**\n * @experimental\n *\n * `delegation_status` MCP tool — synchronous poll. Returns the current\n * state machine + optional progress + final result (when terminal).\n */\n\nimport { NotFoundError } from '../../errors'\nimport type {\n DelegationStatusArgs,\n DelegationStatusResult,\n DelegationTaskQueue,\n} from '../task-queue'\n\n/** @experimental */\nexport const DELEGATION_STATUS_TOOL_NAME = 'delegation_status'\n\n/** @experimental */\nexport const DELEGATION_STATUS_DESCRIPTION = [\n 'Poll the status of an async delegation. Returns the current state',\n '(pending | running | completed | failed | cancelled), optional progress,',\n 'and the final result when status === \"completed\".',\n '',\n 'Use when: you previously called delegate_code or delegate_research and',\n \"need to know whether the work is done. The agent's right rhythm is to\",\n 'call this every minute or two while waiting; do not busy-poll.',\n '',\n 'For a completed coder task, `result.output` is a CoderOutput with branch,',\n 'patch, test/typecheck results, and diff stats. For a completed research',\n 'task, `result.output` is the items + citations + proposedWrites bundle.',\n '',\n 'Throws NotFoundError when taskId is unknown — never silently returns',\n '`pending` for a typo.',\n].join('\\n')\n\n/** @experimental */\nexport const DELEGATION_STATUS_INPUT_SCHEMA = {\n type: 'object',\n properties: {\n taskId: { type: 'string', description: 'Returned by delegate_code / delegate_research.' },\n },\n required: ['taskId'],\n additionalProperties: false,\n} as const\n\n/** @experimental */\nexport function validateDelegationStatusArgs(raw: unknown): DelegationStatusArgs {\n if (raw === null || typeof raw !== 'object') {\n throw new TypeError('delegation_status: arguments must be an object')\n }\n const value = raw as Record<string, unknown>\n const taskId = value.taskId\n if (typeof taskId !== 'string' || taskId.trim().length === 0) {\n throw new TypeError('delegation_status: `taskId` must be a non-empty string')\n }\n return { taskId: taskId.trim() }\n}\n\n/** @experimental */\nexport interface DelegationStatusHandlerOptions {\n queue: DelegationTaskQueue\n}\n\n/** @experimental */\nexport function createDelegationStatusHandler(\n options: DelegationStatusHandlerOptions,\n): (raw: unknown) => Promise<DelegationStatusResult> {\n return async (raw) => {\n const args = validateDelegationStatusArgs(raw)\n const status = options.queue.status(args.taskId)\n if (!status) {\n throw new NotFoundError(`delegation_status: unknown taskId \"${args.taskId}\"`)\n }\n return status\n }\n}\n","/**\n * OTEL span exporter — streams LoopTraceEvents to an OTLP/HTTP collector.\n *\n * Reads OTEL_EXPORTER_OTLP_ENDPOINT + OTEL_EXPORTER_OTLP_HEADERS from env\n * when no explicit config is given. Keeps the runtime dep-free from\n * @opentelemetry/sdk-trace-base — minimal OTLP/JSON serializer.\n *\n * The exporter accepts both raw OtelSpan objects and LoopTraceEvents\n * (which get converted to OTLP spans automatically).\n */\n\nexport interface OtelExportConfig {\n /** OTLP endpoint. Reads OTEL_EXPORTER_OTLP_ENDPOINT env by default. */\n endpoint?: string\n /** OTLP headers. Reads OTEL_EXPORTER_OTLP_HEADERS env by default. */\n headers?: Record<string, string>\n /** Batch size before flush. Default 64. */\n batchSize?: number\n /** Flush interval ms. Default 5000. */\n flushIntervalMs?: number\n /** Resource attributes stamped on every export. */\n resourceAttributes?: Record<string, string | number | boolean>\n /** Service name. Default 'agent-runtime'. */\n serviceName?: string\n}\n\nexport interface OtelExporter {\n /** Export a span. */\n exportSpan(span: OtelSpan): void\n /** Force flush pending spans. */\n flush(): Promise<void>\n /** Shutdown cleanly. */\n shutdown(): Promise<void>\n}\n\nexport interface OtelSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind?: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes?: OtelAttribute[]\n status?: { code: number; message?: string }\n}\n\nexport interface OtelAttribute {\n key: string\n value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean }\n}\n\ninterface OtlpResourceSpans {\n resource: { attributes: OtelAttribute[] }\n scopeSpans: Array<{ scope: { name: string; version: string }; spans: OtelSpan[] }>\n}\n\ninterface OtlpExport {\n resourceSpans: OtlpResourceSpans[]\n}\n\nconst SCOPE = { name: '@tangle-network/agent-runtime', version: '0.33.0' }\n\n/**\n * Current (non-deprecated) OpenTelemetry GenAI semantic-convention keys.\n * Registry: https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/\n * NB: `gen_ai.system` / `gen_ai.usage.prompt_tokens` / `completion_tokens` are\n * DEPRECATED — do not emit them. We use `provider.name` + `input/output_tokens`.\n */\nconst GEN_AI = {\n operation: 'gen_ai.operation.name',\n agentName: 'gen_ai.agent.name',\n conversationId: 'gen_ai.conversation.id',\n inputTokens: 'gen_ai.usage.input_tokens',\n outputTokens: 'gen_ai.usage.output_tokens',\n} as const\n\n/**\n * Create an OTEL exporter. Returns undefined when no endpoint is configured.\n */\nexport function createOtelExporter(config?: OtelExportConfig): OtelExporter | undefined {\n const resolvedEndpoint =\n config?.endpoint ??\n (typeof process !== 'undefined' ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : undefined)\n if (!resolvedEndpoint) return undefined\n const endpoint: string = resolvedEndpoint\n\n const headers = config?.headers ?? parseHeadersFromEnv()\n const batchSize = config?.batchSize ?? 64\n const flushIntervalMs = config?.flushIntervalMs ?? 5000\n const serviceName = config?.serviceName ?? 'agent-runtime'\n const resourceAttrs = config?.resourceAttributes ?? {}\n\n const pending: OtelSpan[] = []\n let timer: ReturnType<typeof setInterval> | undefined\n let stopped = false\n\n const exporter: OtelExporter = {\n exportSpan(span: OtelSpan): void {\n if (stopped) return\n pending.push(span)\n if (pending.length >= batchSize) {\n void doFlush()\n }\n },\n\n async flush(): Promise<void> {\n await doFlush()\n },\n\n async shutdown(): Promise<void> {\n stopped = true\n if (timer !== undefined) {\n clearInterval(timer)\n timer = undefined\n }\n await doFlush()\n },\n }\n\n timer = setInterval(() => {\n if (pending.length > 0) void doFlush()\n }, flushIntervalMs)\n if (typeof timer === 'object' && 'unref' in timer) {\n ;(timer as NodeJS.Timeout).unref()\n }\n\n async function doFlush(): Promise<void> {\n if (pending.length === 0) return\n const batch = pending.splice(0)\n const body: OtlpExport = {\n resourceSpans: [\n {\n resource: {\n attributes: toAttributes({\n 'service.name': serviceName,\n ...resourceAttrs,\n }),\n },\n scopeSpans: [{ scope: SCOPE, spans: batch }],\n },\n ],\n }\n const url = `${endpoint.replace(/\\/+$/, '')}/v1/traces`\n try {\n await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...headers },\n body: JSON.stringify(body),\n })\n } catch {\n // Best-effort — telemetry export must not crash the runtime.\n }\n }\n\n return exporter\n}\n\n/**\n * Convert a LoopTraceEvent into an OtelSpan for export.\n */\nexport function loopEventToOtelSpan(\n event: {\n kind: string\n runId: string\n timestamp: number\n payload: object\n },\n traceId: string,\n parentSpanId?: string,\n): OtelSpan {\n const spanId = generateSpanId()\n const attrs: Record<string, string | number | boolean> = {\n 'loop.event_kind': event.kind,\n 'loop.run_id': event.runId,\n }\n for (const [k, v] of Object.entries(event.payload)) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n attrs[`loop.${k}`] = v\n }\n }\n const ts = msToNs(event.timestamp)\n return {\n traceId: padTraceId(traceId),\n spanId,\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name: event.kind,\n kind: 1,\n startTimeUnixNano: ts,\n endTimeUnixNano: ts,\n attributes: toAttributes(attrs),\n status: { code: 1 },\n }\n}\n\n/**\n * Build a nested, real-duration OTLP span tree for ONE loop run from its full\n * ordered `LoopTraceEvent` stream. Unlike `loopEventToOtelSpan` (one flat,\n * zero-duration span per event), this reconstructs the topology hierarchy a\n * GenAI trace viewer renders natively:\n *\n * loop (invoke_workflow)\n * └─ loop.round[k] (invoke_workflow) ← tangle.loop.move.{kind,width,rationale}\n * ├─ loop.iteration[i] (invoke_agent) ← gen_ai.agent.name + usage + verdict + placement\n * └─ …\n *\n * Attributes follow the current GenAI semconv (`gen_ai.*`) where they apply and\n * a namespaced `tangle.loop.*` / `tangle.cost.usd` extension for topology /\n * verdict / placement / cost (not yet standardized). Pure: feed it a buffered\n * per-runId event array (e.g. flushed on `loop.ended`) and export the result.\n */\nexport function buildLoopOtelSpans(\n events: ReadonlyArray<{ kind: string; runId: string; timestamp: number; payload: object }>,\n traceId: string,\n rootParentSpanId?: string,\n): OtelSpan[] {\n if (events.length === 0) return []\n const tid = padTraceId(traceId)\n const out: OtelSpan[] = []\n const num = (v: unknown): number | undefined =>\n typeof v === 'number' && Number.isFinite(v) ? v : undefined\n const str = (v: unknown): string | undefined =>\n typeof v === 'string' && v.length > 0 ? v : undefined\n const rec = (v: unknown): Record<string, unknown> =>\n v && typeof v === 'object' ? (v as Record<string, unknown>) : {}\n\n const started = events.find((e) => e.kind === 'loop.started')\n const ended = events.find((e) => e.kind === 'loop.ended')\n const runId = events[0]?.runId ?? ''\n const rootStart = started?.timestamp ?? events[0]!.timestamp\n const rootEnd = ended?.timestamp ?? events[events.length - 1]!.timestamp\n const rootId = generateSpanId()\n\n const make = (\n spanId: string,\n parentSpanId: string | undefined,\n name: string,\n startMs: number,\n endMs: number,\n attrs: Record<string, string | number | boolean>,\n statusCode = 1,\n ): OtelSpan => ({\n traceId: tid,\n spanId,\n parentSpanId: parentSpanId ? padSpanId(parentSpanId) : undefined,\n name,\n kind: 1,\n startTimeUnixNano: msToNs(startMs),\n endTimeUnixNano: msToNs(endMs),\n attributes: toAttributes(attrs),\n status: { code: statusCode },\n })\n\n // root\n const sp = rec(started?.payload)\n const rootAttrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n [GEN_AI.conversationId]: runId,\n 'tangle.loop.driver': str(sp.driver) ?? 'driver',\n }\n if (Array.isArray(sp.agentRunNames) && sp.agentRunNames.length > 0) {\n rootAttrs['tangle.loop.agents'] = sp.agentRunNames.map(String).join(',')\n }\n if (ended) {\n const ep = rec(ended.payload)\n const win = num(ep.winnerIterationIndex)\n if (win !== undefined) rootAttrs['tangle.loop.winner.iteration_index'] = win\n const cost = num(ep.totalCostUsd)\n if (cost !== undefined) rootAttrs['tangle.cost.usd'] = cost\n const dur = num(ep.durationMs)\n if (dur !== undefined) rootAttrs['tangle.loop.duration_ms'] = dur\n const iters = num(ep.iterations)\n if (iters !== undefined) rootAttrs['tangle.loop.iterations'] = iters\n }\n out.push(make(rootId, rootParentSpanId, 'loop', rootStart, rootEnd, rootAttrs))\n\n // rounds + iterations\n const iterStartTs = new Map<number, number>()\n const placementByIdx = new Map<number, Record<string, string>>()\n let currentRoundId: string | undefined\n let pendingRound:\n | { id: string; start: number; attrs: Record<string, string | number | boolean> }\n | undefined\n const flushRound = (endMs: number) => {\n if (!pendingRound) return\n out.push(\n make(pendingRound.id, rootId, 'loop.round', pendingRound.start, endMs, pendingRound.attrs),\n )\n pendingRound = undefined\n }\n\n for (const e of events) {\n const p = rec(e.payload)\n switch (e.kind) {\n case 'loop.plan': {\n flushRound(e.timestamp)\n const id = generateSpanId()\n const roundIdx = num(p.roundIndex) ?? 0\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_workflow',\n 'tangle.loop.round.index': roundIdx,\n 'tangle.loop.move.kind': str(p.moveKind) ?? 'unknown',\n 'tangle.loop.move.round': roundIdx,\n 'tangle.loop.move.width': num(p.plannedCount) ?? 0,\n }\n const r = str(p.rationale)\n if (r) attrs['tangle.loop.move.rationale'] = r\n const parent = num(p.parentIndex)\n if (parent !== undefined) attrs['tangle.loop.move.parent_index'] = parent\n if (Array.isArray(p.childIndices) && p.childIndices.length > 0) {\n attrs['tangle.loop.move.child_indices'] = p.childIndices.map(String).join(',')\n }\n pendingRound = { id, start: e.timestamp, attrs }\n currentRoundId = id\n break\n }\n case 'loop.iteration.started': {\n const idx = num(p.iterationIndex)\n if (idx !== undefined) iterStartTs.set(idx, e.timestamp)\n break\n }\n case 'loop.iteration.dispatch': {\n const idx = num(p.iterationIndex)\n if (idx === undefined) break\n const place: Record<string, string> = {}\n const kind = str(p.placement)\n if (kind) place['tangle.loop.placement.kind'] = kind\n const sid = str(p.sandboxId)\n if (sid) place['tangle.sandbox.id'] = sid\n const fid = str(p.fleetId)\n if (fid) place['tangle.fleet.id'] = fid\n const mid = str(p.machineId)\n if (mid) place['tangle.machine.id'] = mid\n placementByIdx.set(idx, place)\n break\n }\n case 'loop.iteration.ended': {\n const idx = num(p.iterationIndex) ?? 0\n const start = iterStartTs.get(idx) ?? e.timestamp\n const err = str(p.error)\n const attrs: Record<string, string | number | boolean> = {\n [GEN_AI.operation]: 'invoke_agent',\n 'tangle.loop.iteration.index': idx,\n }\n const agent = str(p.agentRunName)\n if (agent) attrs[GEN_AI.agentName] = agent\n const tu = rec(p.tokenUsage)\n const inTok = num(tu.input)\n if (inTok !== undefined) attrs[GEN_AI.inputTokens] = inTok\n const outTok = num(tu.output)\n if (outTok !== undefined) attrs[GEN_AI.outputTokens] = outTok\n const cost = num(p.costUsd)\n if (cost !== undefined) attrs['tangle.cost.usd'] = cost\n const verdict = rec(p.verdict)\n if (typeof verdict.valid === 'boolean') attrs['tangle.loop.verdict.valid'] = verdict.valid\n const score = num(verdict.score)\n if (score !== undefined) attrs['tangle.loop.verdict.score'] = score\n if (err) attrs['tangle.loop.error'] = err\n const gid = num(p.groupId)\n if (gid !== undefined) attrs['tangle.loop.iteration.group_id'] = gid\n const par = num(p.parentIndex)\n if (par !== undefined) attrs['tangle.loop.iteration.parent_index'] = par\n const dur = num(p.durationMs)\n if (dur !== undefined) attrs['tangle.loop.iteration.duration_ms'] = dur\n const preview = str(p.outputPreview)\n if (preview) attrs['tangle.loop.iteration.output_preview'] = preview\n Object.assign(attrs, placementByIdx.get(idx) ?? {})\n out.push(\n make(\n generateSpanId(),\n currentRoundId ?? rootId,\n 'loop.iteration',\n start,\n e.timestamp,\n attrs,\n err ? 2 : 1,\n ),\n )\n break\n }\n case 'loop.decision': {\n if (pendingRound) {\n const dec = str(p.decision)\n if (dec) pendingRound.attrs['tangle.loop.decision'] = dec\n flushRound(e.timestamp)\n }\n currentRoundId = undefined\n break\n }\n }\n }\n flushRound(rootEnd)\n return out\n}\n\nfunction parseHeadersFromEnv(): Record<string, string> {\n if (typeof process === 'undefined') return {}\n const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS\n if (!raw) return {}\n const out: Record<string, string> = {}\n for (const pair of raw.split(',')) {\n const eq = pair.indexOf('=')\n if (eq < 0) continue\n const key = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n if (key) out[key] = value\n }\n return out\n}\n\nfunction toAttributes(record: Record<string, string | number | boolean>): OtelAttribute[] {\n return Object.entries(record).map(([key, value]) => ({\n key,\n value:\n typeof value === 'number'\n ? Number.isInteger(value)\n ? { intValue: value.toString() }\n : { doubleValue: value }\n : typeof value === 'boolean'\n ? { boolValue: value }\n : { stringValue: value },\n }))\n}\n\nfunction msToNs(ms: number): string {\n return (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n}\n\nfunction padSpanId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 16).padEnd(16, '0')\n}\n\nfunction padTraceId(id: string): string {\n const cleaned = id.replace(/-/g, '')\n return cleaned.slice(0, 32).padEnd(32, '0')\n}\n\nfunction generateSpanId(): string {\n const bytes = new Uint8Array(8)\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256)\n }\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('')\n}\n\n// ─── Eval-run ingest (self-improvement provenance) ───────────────────────────\n//\n// Tangle Intelligence has a first-class, non-trace record for self-improvement\n// runs: POST /v1/ingest/eval-runs (\"Mode D\"). Each generation carries a\n// `surfaceHash` (the proposed-change identity) + arbitrary `surface` provenance;\n// a later `gate-decided` event re-emits the same `runId` (idempotent upsert) with\n// a real `gateDecision` + `holdoutLift`, so proposal→verdict is one diffable\n// record. This is how a consumer's RSI loop records WHAT it changed, WHY, from\n// which evidence — the audit trail behind agentic self-improvement.\n\n/** Wire version the eval-runs ingest enforces (X-Tangle-Wire-Version + body). */\nexport const INTELLIGENCE_WIRE_VERSION = '2026-05-26.v1'\n\nexport interface EvalRunGeneration {\n /** 0-based ordinal of this generation within the run (required by ingest). */\n index: number\n /** Identity of the proposed surface change (content-addressed hash). */\n surfaceHash: string\n /** Arbitrary provenance for this generation (rationale, evidence, source). */\n surface?: unknown\n /** Per-scenario results; empty until the generation is measured. */\n cells?: unknown[]\n /** Mean composite score (0 when unmeasured — pair with labels.measured). */\n compositeMean: number\n costUsd: number\n durationMs: number\n}\n\nexport interface EvalRunEvent {\n runId: string\n runDir: string\n /** ISO timestamp. */\n timestamp: string\n status:\n | 'started'\n | 'baseline-complete'\n | 'generation-complete'\n | 'gate-decided'\n | 'finished'\n | 'errored'\n labels?: Record<string, string>\n baseline?: EvalRunGeneration\n generations?: EvalRunGeneration[]\n gateDecision?: 'ship' | 'hold' | 'need_more_work' | 'model_ceiling' | 'arch_ceiling'\n holdoutLift?: number\n totalCostUsd: number\n totalDurationMs: number\n errorMessage?: string\n}\n\nexport interface EvalRunsExportConfig {\n /** Bearer key — tenant is resolved server-side from it. Reads TANGLE_API_KEY. */\n apiKey?: string\n /** Intelligence base. Reads INTELLIGENCE_BASE env, else prod. */\n base?: string\n /** Idempotency-Key header (e.g. the runId) — safe retries + upsert. */\n idempotencyKey?: string\n}\n\nexport interface EvalRunsExportResult {\n ok: boolean\n status: number\n accepted: number\n rejected: Array<{ index: number; reason: string }>\n}\n\nconst DEFAULT_INTELLIGENCE_BASE = 'https://intelligence.tangle.tools'\n\n/**\n * Ship self-improvement eval-run events to Tangle Intelligence. Unlike the\n * best-effort span exporter, this RESOLVES with the ingest verdict (accepted /\n * rejected per event) so a consumer's loop can assert its provenance landed.\n * Throws only on a missing key or network failure.\n */\nexport async function exportEvalRuns(\n events: EvalRunEvent[],\n config?: EvalRunsExportConfig,\n): Promise<EvalRunsExportResult> {\n if (events.length === 0) return { ok: true, status: 0, accepted: 0, rejected: [] }\n const apiKey =\n config?.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n if (!apiKey)\n throw new Error('exportEvalRuns: apiKey required (pass config.apiKey or set TANGLE_API_KEY)')\n const base =\n config?.base ??\n (typeof process !== 'undefined' ? process.env.INTELLIGENCE_BASE : undefined) ??\n DEFAULT_INTELLIGENCE_BASE\n const url = `${base.replace(/\\/+$/, '')}/v1/ingest/eval-runs`\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n authorization: `Bearer ${apiKey}`,\n 'X-Tangle-Wire-Version': INTELLIGENCE_WIRE_VERSION,\n ...(config?.idempotencyKey ? { 'Idempotency-Key': config.idempotencyKey } : {}),\n },\n body: JSON.stringify({ wireVersion: INTELLIGENCE_WIRE_VERSION, events }),\n })\n let parsed: { accepted?: number; rejected?: Array<{ index: number; reason: string }> } = {}\n try {\n parsed = (await res.json()) as typeof parsed\n } catch {\n // non-JSON body (e.g. 5xx HTML) — leave parsed empty\n }\n return {\n ok: res.ok,\n status: res.status,\n accepted: parsed.accepted ?? (res.ok ? events.length : 0),\n rejected: parsed.rejected ?? [],\n }\n}\n"],"mappings":";;;;;;;;;;AAgBA,SAAS,OAAO,UAAU,QAAQ,iBAAiB;AACnD,SAAS,eAAe;AAoCjB,IAAM,8BAAN,cAA0C,eAAe;AAAA,EAC9D,YAAY,SAAiB,SAA+B;AAC1D,UAAM,cAAc,SAAS,OAAO;AAAA,EACtC;AACF;AAUO,IAAM,6BAAN,cAAyC,eAAe;AAAA,EAC7D,YAAY,SAAiB,SAA+B;AAC1D,UAAM,UAAU,SAAS,OAAO;AAAA,EAClC;AACF;AAGO,IAAM,0BAAN,MAAyD;AAAA,EAC7C,UAAU,oBAAI,IAA8B;AAAA,EAE7D,MAAM,UAAuC;AAC3C,WAAO,CAAC,GAAG,KAAK,QAAQ,OAAO,CAAC,EAAE,IAAI,WAAW;AAAA,EACnD;AAAA,EAEA,MAAM,OAAO,QAAyC;AACpD,SAA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AC,EAAE;AACjF,QAAM,SACJ,QAAQ,WAAW,OAAO,YAAY,cAAc,QAAQ,IAAI,iBAAiB;AACnF,MAAI,CAAC;AACH,UAAM,IAAI,MAAM,4EAA4E;AAC9F,QAAM,OACJ,QAAQ,SACP,OAAO,YAAY,cAAc,QAAQ,IAAI,oBAAoB,WAClE;AACF,QAAM,MAAM,GAAG,KAAK,QAAQ,QAAQ,EAAE,CAAC;AACvC,QAAM,MAAM,MAAM,MAAM,KAAK;AAAA,IAC3B,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAU,MAAM;AAAA,MAC/B,yBAAyB;AAAA,MACzB,GAAI,QAAQ,iBAAiB,EAAE,mBAAmB,OAAO,eAAe,IAAI,CAAC;AAAA,IAC/E;AAAA,IACA,MAAM,KAAK,UAAU,EAAE,aAAa,2BAA2B,OAAO,CAAC;AAAA,EACzE,CAAC;AACD,MAAI,SAAqF,CAAC;AAC1F,MAAI;AACF,aAAU,MAAM,IAAI,KAAK;AAAA,EAC3B,QAAQ;AAAA,EAER;AACA,SAAO;AAAA,IACL,IAAI,IAAI;AAAA,IACR,QAAQ,IAAI;AAAA,IACZ,UAAU,OAAO,aAAa,IAAI,KAAK,OAAO,SAAS;AAAA,IACvD,UAAU,OAAO,YAAY,CAAC;AAAA,EAChC;AACF;","names":["SINGLE_VARIANT_ESTIMATE_MS","FANOUT_PER_VARIANT_ESTIMATE_MS","validateConfig","defaultEstimate"]}
@@ -14,7 +14,7 @@ import {
14
14
  DELEGATION_STATUS_DESCRIPTION,
15
15
  DELEGATION_STATUS_INPUT_SCHEMA,
16
16
  DELEGATION_STATUS_TOOL_NAME
17
- } from "./chunk-JNPK46YH.js";
17
+ } from "./chunk-VIEDXELL.js";
18
18
 
19
19
  // src/mcp/openai-tools.ts
20
20
  function buildTool(name, description, parameters) {
@@ -61,4 +61,4 @@ export {
61
61
  mcpToolsForRuntimeMcp,
62
62
  mcpToolsForRuntimeMcpSubset
63
63
  };
64
- //# sourceMappingURL=chunk-VR4JIC5H.js.map
64
+ //# sourceMappingURL=chunk-XTEZ3YJ4.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 { g as AgentBackendInput, h as AgentExecutionBackend, d as OpenAIChatTool, i as OpenAIChatToolChoice, j as AgentBackendContext, R as RuntimeStreamEvent, K as KnowledgeReadinessDecision, k as RunAgentTaskOptions, l as AgentTaskRunResult, m as RunAgentTaskStreamOptions, n as AgentRuntimeEvent, o as AgentTaskStatus, p as RuntimeSessionStore, q as RuntimeSession } from './types-nBMuollC.js';
4
4
  export { r as AgentAdapter, s as AgentKnowledgeProvider, t as AgentRuntimeEventSink, u as AgentTaskContext, v as AgentTaskSpec, B as BackendErrorDetail, w as RuntimeRunHandle, x as RuntimeRunPersistenceAdapter, y as RuntimeRunRow, z as startRuntimeRun } from './types-nBMuollC.js';
5
- export { C as CoderLoopRunnerOptions, D as DELEGATED_LOOP_MODES, a as DelegatedLoopMode, b as DelegatedLoopRegistry, c as DelegatedLoopResult, d as DelegatedLoopRunner, e as DynamicLoopRunnerOptions, L as LoopRunnerCliArgs, f as LoopRunnerCliResult, R as ResearchLoopResult, g as ResearchLoopRunnerOptions, h as RunDelegatedLoopOptions, V as VetoedFact, i as auditLoopRunner, j as coderLoopRunner, k as dynamicLoopRunner, l as isDelegatedLoopMode, p as parseLoopRunnerArgv, r as researchLoopRunner, m as reviewLoopRunner, n as runDelegatedLoop, o as runLoopRunnerCli, s as selfImproveLoopRunner } from './loop-runner-bin-DEm4roYF.js';
5
+ export { C as CoderLoopRunnerOptions, D as DELEGATED_LOOP_MODES, a as DelegatedLoopMode, b as DelegatedLoopRegistry, c as DelegatedLoopResult, d as DelegatedLoopRunner, e as DynamicLoopRunnerOptions, L as LoopRunnerCliArgs, f as LoopRunnerCliResult, R as ResearchLoopResult, g as ResearchLoopRunnerOptions, h as RunDelegatedLoopOptions, V as VetoedFact, i as auditLoopRunner, j as coderLoopRunner, k as dynamicLoopRunner, l as isDelegatedLoopMode, p as parseLoopRunnerArgv, r as researchLoopRunner, m as reviewLoopRunner, n as runDelegatedLoop, o as runLoopRunnerCli, s as selfImproveLoopRunner } from './loop-runner-bin-Cgn0A-NW.js';
6
6
  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-EzfsVUhh.js';
7
7
  import { R as RuntimeHooks } from './runtime-hooks-C7JwKb9E.js';
8
8
  export { b as RuntimeDecisionEvidenceRef, c as RuntimeDecisionKind, d as RuntimeDecisionPoint, e as RuntimeHookContext, f as RuntimeHookErrorContext, a as RuntimeHookEvent, g as RuntimeHookPhase, h as RuntimeHookTarget, i as composeRuntimeHooks, j as defineRuntimeHooks, n as notifyRuntimeDecisionPoint, k as notifyRuntimeHookEvent } from './runtime-hooks-C7JwKb9E.js';
@@ -10,7 +10,7 @@ import '@tangle-network/sandbox';
10
10
  import '@tangle-network/agent-eval/campaign';
11
11
  import '@tangle-network/agent-eval/contract';
12
12
  import './types-p8dWBIXL.js';
13
- import './kb-gate-51BlLlVM.js';
13
+ import './kb-gate-CsXpNRk7.js';
14
14
  import './coder-CVZNGbyg.js';
15
15
  import './substrate-CUgk7F7s.js';
16
16
  import './driver-DYU2sgHr.js';
@@ -1346,6 +1346,12 @@ type ToolLoopEvent = {
1346
1346
  type: 'other';
1347
1347
  event: unknown;
1348
1348
  };
1349
+ /** Why the loop stopped. `completed` = model finished naturally; `stuck-loop` =
1350
+ * ≥3 consecutive identical tool calls (same tool + args); `backstop` = hit the
1351
+ * runaway-backstop cap (200 by default); `deadline` = wall-clock deadlineMs
1352
+ * exceeded; `budget` = maxCostUsd exhausted. Non-`completed` stops are infra /
1353
+ * resource outcomes — eval scoring must distinguish them from capability failure. */
1354
+ type ToolLoopStopReason = 'completed' | 'stuck-loop' | 'backstop' | 'deadline' | 'budget';
1349
1355
  interface ToolLoopResult {
1350
1356
  finalText: string;
1351
1357
  toolResults: Array<{
@@ -1354,6 +1360,8 @@ interface ToolLoopResult {
1354
1360
  outcome: ToolCallOutcome;
1355
1361
  }>;
1356
1362
  turns: number;
1363
+ stopReason: ToolLoopStopReason;
1364
+ /** @deprecated Use `stopReason !== 'completed'` instead. */
1357
1365
  cappedOut: boolean;
1358
1366
  }
1359
1367
  interface RunToolLoopOptions {
@@ -1363,7 +1371,16 @@ interface RunToolLoopOptions {
1363
1371
  streamTurn: (messages: ToolLoopMessage[]) => AsyncIterable<ToolLoopEvent>;
1364
1372
  executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>;
1365
1373
  isExecutableTool: (toolName: string) => boolean;
1374
+ /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow.
1375
+ * For per-workflow limits, use `maxCostUsd` or `deadlineMs` instead. */
1366
1376
  maxToolTurns?: number;
1377
+ /** Wall-clock deadline in ms since epoch (Date.now()-based). When exceeded the
1378
+ * loop stops with stopReason `deadline`. */
1379
+ deadlineMs?: number;
1380
+ /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */
1381
+ maxCostUsd?: number;
1382
+ /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */
1383
+ costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number;
1367
1384
  renderResult?: (label: string, outcome: ToolCallOutcome) => string;
1368
1385
  labelFor?: (call: ToolLoopCall) => string;
1369
1386
  runId?: string;
@@ -1386,6 +1403,7 @@ type StreamToolLoopYield<Raw> = {
1386
1403
  } | {
1387
1404
  kind: 'capped';
1388
1405
  pending: number;
1406
+ stopReason: Exclude<ToolLoopStopReason, 'completed'>;
1389
1407
  };
1390
1408
  interface StreamToolLoopOptions<Raw> {
1391
1409
  systemPrompt: string;
@@ -1396,7 +1414,14 @@ interface StreamToolLoopOptions<Raw> {
1396
1414
  extractToolCall: (event: Raw) => ToolLoopCall | null;
1397
1415
  isExecutableTool: (toolName: string) => boolean;
1398
1416
  executeToolCall: (call: ToolLoopCall) => Promise<ToolCallOutcome>;
1417
+ /** Runaway-backstop cap. Default 200 — set far above any legitimate workflow. */
1399
1418
  maxToolTurns?: number;
1419
+ /** Wall-clock deadline in ms since epoch (Date.now()-based). */
1420
+ deadlineMs?: number;
1421
+ /** Maximum total cost in USD. Requires `costOf` to meter each tool call. */
1422
+ maxCostUsd?: number;
1423
+ /** Return the USD cost of one outcome. Required for `maxCostUsd` to work. */
1424
+ costOf?: (call: ToolLoopCall, outcome: ToolCallOutcome) => number;
1400
1425
  renderResult?: (label: string, outcome: ToolCallOutcome) => string;
1401
1426
  labelFor?: (call: ToolLoopCall) => string;
1402
1427
  runId?: string;
@@ -1405,7 +1430,7 @@ interface StreamToolLoopOptions<Raw> {
1405
1430
  }
1406
1431
  /** Streaming bounded tool loop: yields each raw turn event (the caller maps +
1407
1432
  * telemetries + re-emits it) and each executed `tool_result`; emits one
1408
- * `capped` if it stops at the turn limit with calls still pending. */
1433
+ * `capped` if it stops for any non-completed reason with calls still pending. */
1409
1434
  declare function streamToolLoop<Raw>(opts: StreamToolLoopOptions<Raw>): AsyncGenerator<StreamToolLoopYield<Raw>, void, unknown>;
1410
1435
 
1411
- export { AgentBackendContext, AgentBackendInput, AgentExecutionBackend, AgentRuntimeEvent, AgentTaskRunResult, AgentTaskStatus, type AuthSource, type BackendCallPolicy, BackendTransportError, type ChatStreamEvent, type ChatTurnHooks, type ChatTurnIdentity, type ChatTurnProducer, type ChatTurnResult, type CircuitBreakerConfig, CircuitBreakerState, CircuitOpenError, type Conversation, type ConversationDriveState, type ConversationJournal, type ConversationJournalEntry, type ConversationParticipant, type ConversationPolicy, type ConversationResult, type ConversationStreamEvent, type ConversationTurn, type D1DatabaseLike, type D1StmtLike, DEFAULT_MAX_DEPTH, DEFAULT_ROUTER_BASE_URL, DeadlineExceededError, FORWARD_HEADERS, FileConversationJournal, type ForwardHeaderName, type HaltContext, type HaltPredicate, type HaltReason, type HaltSignal, InMemoryConversationJournal, InMemoryRuntimeSessionStore, type ModelInfo, OpenAIChatTool, OpenAIChatToolChoice, PlannerError, type PropagatedHeaders, type ResolvedChatModel, type RetryBackoff, type RetryableErrorPredicate, type RouterEnv, type RunChatTurnInput, type RunConversationOptions, type RunToolLoopOptions, type RuntimeEventCollector, RuntimeHooks, RuntimeRunStateError, RuntimeSessionStore, RuntimeStreamEvent, type RuntimeStreamEventCollector, type RuntimeTelemetryOptions, type SanitizedKnowledgeReadinessReport, type SqlAdapter, SqlConversationJournal, type StreamToolLoopOptions, type StreamToolLoopYield, type ToolCallOutcome, type ToolLoopCall, type ToolLoopEvent, type ToolLoopMessage, type ToolLoopResult, type TurnOrder, applyRunRecordDefaults, buildForwardHeaders, cleanModelId, computeBackoff, createConversationBackend, createIterableBackend, createOpenAICompatibleBackend, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, d1ToSqlAdapter, decideKnowledgeReadiness, defaultIsRetryable, defineConversation, deriveExecutionId, getModels, handleChatTurn, isDepthExceeded, makePerAttemptSignal, readDepth, readinessServerSentEvent, resolveChatModel, resolveRouterBaseUrl, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runToolLoop, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, sleep, slugifySpeaker, streamToolLoop, turnId, validateChatModelId };
1436
+ export { AgentBackendContext, AgentBackendInput, AgentExecutionBackend, AgentRuntimeEvent, AgentTaskRunResult, AgentTaskStatus, type AuthSource, type BackendCallPolicy, BackendTransportError, type ChatStreamEvent, type ChatTurnHooks, type ChatTurnIdentity, type ChatTurnProducer, type ChatTurnResult, type CircuitBreakerConfig, CircuitBreakerState, CircuitOpenError, type Conversation, type ConversationDriveState, type ConversationJournal, type ConversationJournalEntry, type ConversationParticipant, type ConversationPolicy, type ConversationResult, type ConversationStreamEvent, type ConversationTurn, type D1DatabaseLike, type D1StmtLike, DEFAULT_MAX_DEPTH, DEFAULT_ROUTER_BASE_URL, DeadlineExceededError, FORWARD_HEADERS, FileConversationJournal, type ForwardHeaderName, type HaltContext, type HaltPredicate, type HaltReason, type HaltSignal, InMemoryConversationJournal, InMemoryRuntimeSessionStore, type ModelInfo, OpenAIChatTool, OpenAIChatToolChoice, PlannerError, type PropagatedHeaders, type ResolvedChatModel, type RetryBackoff, type RetryableErrorPredicate, type RouterEnv, type RunChatTurnInput, type RunConversationOptions, type RunToolLoopOptions, type RuntimeEventCollector, RuntimeHooks, RuntimeRunStateError, RuntimeSessionStore, RuntimeStreamEvent, type RuntimeStreamEventCollector, type RuntimeTelemetryOptions, type SanitizedKnowledgeReadinessReport, type SqlAdapter, SqlConversationJournal, type StreamToolLoopOptions, type StreamToolLoopYield, type ToolCallOutcome, type ToolLoopCall, type ToolLoopEvent, type ToolLoopMessage, type ToolLoopResult, type ToolLoopStopReason, type TurnOrder, applyRunRecordDefaults, buildForwardHeaders, cleanModelId, computeBackoff, createConversationBackend, createIterableBackend, createOpenAICompatibleBackend, createRuntimeEventCollector, createRuntimeStreamEventCollector, createSandboxPromptBackend, d1ToSqlAdapter, decideKnowledgeReadiness, defaultIsRetryable, defineConversation, deriveExecutionId, getModels, handleChatTurn, isDepthExceeded, makePerAttemptSignal, readDepth, readinessServerSentEvent, resolveChatModel, resolveRouterBaseUrl, runAgentTask, runAgentTaskStream, runConversation, runConversationStream, runToolLoop, runtimeStreamServerSentEvent, sanitizeAgentRuntimeEvent, sanitizeKnowledgeReadinessReport, sanitizeRuntimeStreamEvent, sleep, slugifySpeaker, streamToolLoop, turnId, validateChatModelId };