@tangle-network/agent-runtime 0.52.0 → 0.53.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent.d.ts +2 -2
- package/dist/agent.js +2 -2
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/{chunk-7SP2OVYZ.js → chunk-5M2WDWBI.js} +3 -3
- package/dist/{chunk-4JI4BCBI.js → chunk-AYRQZRDV.js} +2 -2
- package/dist/{chunk-BERLUBAP.js → chunk-FO4DCM7R.js} +2 -2
- package/dist/{chunk-7JITYN6T.js → chunk-JFIYKDXF.js} +17 -2
- package/dist/chunk-JFIYKDXF.js.map +1 -0
- package/dist/{chunk-COAVO6QB.js → chunk-K5M3SHEU.js} +3 -3
- package/dist/{chunk-2OU7ZQPD.js → chunk-K6WP7PYW.js} +42 -57
- package/dist/chunk-K6WP7PYW.js.map +1 -0
- package/dist/{chunk-V2K35HF2.js → chunk-P4QNEXFC.js} +2 -2
- package/dist/{coder-_YCf3BAK.d.ts → coder-LKm3Mczw.d.ts} +1 -1
- package/dist/{delegation-profile-1GbW5yA3.d.ts → delegation-profile-Bvfro2m1.d.ts} +28 -2
- package/dist/{driver-DLI1io57.d.ts → driver-B2RKkVJW.d.ts} +1 -1
- package/dist/index.d.ts +7 -7
- package/dist/index.js +7 -5
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +475 -5
- package/dist/intelligence.js +547 -3
- package/dist/intelligence.js.map +1 -1
- package/dist/{kb-gate-CHAyt4aI.d.ts → kb-gate-CKfykcYQ.d.ts} +2 -2
- package/dist/{loop-runner-bin-DFUNgpeK.d.ts → loop-runner-bin-D4Ir7b00.d.ts} +4 -4
- package/dist/loop-runner-bin.d.ts +5 -5
- package/dist/loop-runner-bin.js +3 -3
- package/dist/loops.d.ts +6 -5
- package/dist/loops.js +1 -1
- package/dist/mcp/bin.js +4 -4
- package/dist/mcp/index.d.ts +7 -7
- package/dist/mcp/index.js +6 -6
- package/dist/{openai-tools-D4HLDWgw.d.ts → openai-tools-CKfR3EMh.d.ts} +1 -1
- package/dist/profiles.d.ts +2 -2
- package/dist/router-client-B0Qi1NiN.d.ts +120 -0
- package/dist/{run-loop-BIineL1T.d.ts → run-loop-DgVhucoR.d.ts} +1 -1
- package/dist/runtime.d.ts +16 -119
- package/dist/runtime.js +1 -1
- package/dist/{types-5MGt5KTY.d.ts → types-CNDJCL_0.d.ts} +1 -1
- package/dist/{types-BEQsBhOE.d.ts → types-CklkW4Eh.d.ts} +2 -1
- package/dist/workflow.d.ts +2 -2
- package/dist/workflow.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2OU7ZQPD.js.map +0 -1
- package/dist/chunk-7JITYN6T.js.map +0 -1
- /package/dist/{chunk-7SP2OVYZ.js.map → chunk-5M2WDWBI.js.map} +0 -0
- /package/dist/{chunk-4JI4BCBI.js.map → chunk-AYRQZRDV.js.map} +0 -0
- /package/dist/{chunk-BERLUBAP.js.map → chunk-FO4DCM7R.js.map} +0 -0
- /package/dist/{chunk-COAVO6QB.js.map → chunk-K5M3SHEU.js.map} +0 -0
- /package/dist/{chunk-V2K35HF2.js.map → chunk-P4QNEXFC.js.map} +0 -0
package/dist/intelligence.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/intelligence/effort.ts","../src/intelligence/redact.ts","../src/intelligence/delivery.ts","../src/intelligence/index.ts"],"sourcesContent":["/**\n * @experimental\n *\n * EffortPolicy — pure data, no execution. Resolves a named tier into a flat\n * settings object the Intelligence wrapper reads to decide WHICH intelligence\n * spawns are admitted. The composer never runs anything; it only describes the\n * shape of intelligence a tier permits.\n *\n * The billing boundary lives one layer above this (the wrapper tags trace usage\n * by class). What this module owns is the single law the OFF tier rests on:\n * `'off'` ⇒ every intelligence knob OFF (analysts:false, corpus:'off',\n * fanout:1, loops:false, intelligenceBudgetUsd:0). At OFF the wrapper runs the\n * agent as pure passthrough and only intelligence-class usage can prove to be\n * zero — there is nothing to spawn.\n */\n\n/** The named effort tiers, lowest to highest. `'off'` is the honest floor\n * below `'eco'`: intelligence fully off, telemetry still best-effort. */\nexport type EffortTier = 'off' | 'eco' | 'standard' | 'thorough' | 'max'\n\n/** Corpus access an intelligence tier permits. `'off'` reads and writes\n * nothing; `'read'` consults the cross-run corpus without contributing;\n * `'read-write'` both consults and accumulates. */\nexport type CorpusAccess = 'off' | 'read' | 'read-write'\n\n/**\n * The flat, resolved settings a tier compiles to. Every field is individually\n * overridable through `resolveEffort`. Pure data — read by the wrapper, never\n * self-executing.\n */\nexport interface EffortSettings {\n /** Whether trace-derived analyst diagnosis may spawn. `false` ⇒ no analyst. */\n analysts: boolean\n /** Cross-run corpus access this tier permits. */\n corpus: CorpusAccess\n /** Parallel candidate width. `1` ⇒ single-shot, no breadth. */\n fanout: number\n /** Whether multi-step improvement loops (refine / fanout-vote) may run. */\n loops: boolean\n /**\n * Ceiling, in USD, for INTELLIGENCE-class spawns only (analysts, corpus,\n * loops) — NOT base inference. `0` refuses every intelligence spawn; `null`\n * means uncapped (the spend lands on the Pareto receipt). Base-stream\n * inference is billed on its own channel and is never constrained here.\n */\n intelligenceBudgetUsd: number | null\n}\n\n/** Per-field overrides applied on top of a tier preset. Any subset of the\n * resolved settings; each provided field wins over the preset. */\nexport type EffortOverrides = Partial<EffortSettings>\n\nconst presets: Readonly<Record<EffortTier, Readonly<EffortSettings>>> = {\n off: {\n analysts: false,\n corpus: 'off',\n fanout: 1,\n loops: false,\n intelligenceBudgetUsd: 0,\n },\n eco: {\n analysts: true,\n corpus: 'read',\n fanout: 1,\n loops: false,\n intelligenceBudgetUsd: 0.25,\n },\n standard: {\n analysts: true,\n corpus: 'read-write',\n fanout: 3,\n loops: true,\n intelligenceBudgetUsd: 2,\n },\n thorough: {\n analysts: true,\n corpus: 'read-write',\n fanout: 5,\n loops: true,\n intelligenceBudgetUsd: 10,\n },\n max: {\n analysts: true,\n corpus: 'read-write',\n fanout: 8,\n loops: true,\n intelligenceBudgetUsd: null,\n },\n}\n\n/** The default tier when a client declares no effort. `'standard'` turns\n * intelligence on with sensible knobs; opt down to `'off'`/`'eco'` or up to\n * `'thorough'`/`'max'`. */\nexport const defaultEffortTier: EffortTier = 'standard'\n\n/**\n * Compile a named tier (plus optional per-field overrides) into the flat\n * `EffortSettings` the wrapper reads. Pure: same inputs → same object, no I/O,\n * no execution. Fails loud on an unknown tier rather than silently defaulting —\n * a typo'd tier must not quietly grant or deny intelligence.\n *\n * Invariant preserved for the billing floor: `resolveEffort('off')` always\n * yields `intelligenceBudgetUsd: 0` with every intelligence knob off UNLESS the\n * caller explicitly overrides a field — overriding off is an opt-in the caller\n * owns, not a default the composer leaks.\n */\nexport function resolveEffort(tier: EffortTier, overrides?: EffortOverrides): EffortSettings {\n const preset = presets[tier]\n if (!preset) {\n throw new Error(\n `resolveEffort: unknown effort tier ${JSON.stringify(tier)} (expected one of ${(\n Object.keys(presets) as EffortTier[]\n )\n .map((t) => `'${t}'`)\n .join(', ')})`,\n )\n }\n return { ...preset, ...(overrides ?? {}) }\n}\n\n/**\n * True when these settings admit NO intelligence spawn — the passthrough\n * predicate the wrapper branches on. Every intelligence axis must be off:\n * analysts disabled, corpus off, no breadth, no loops, and a zero intelligence\n * budget. A caller who overrides any one of these back on is no longer at the\n * OFF floor and the wrapper treats them as an intelligence-enabled run.\n */\nexport function isIntelligenceOff(settings: EffortSettings): boolean {\n return (\n settings.analysts === false &&\n settings.corpus === 'off' &&\n settings.fanout <= 1 &&\n settings.loops === false &&\n settings.intelligenceBudgetUsd === 0\n )\n}\n","/**\n * @experimental\n *\n * Redaction for Intelligence trace export. The trace carries the customer's\n * real input/output; before any of it leaves the process it passes through a\n * `Redactor`. The default scrubs the obvious leak classes (API keys, bearer\n * tokens, emails, private keys) from strings and walks nested objects/arrays,\n * but a customer with domain-specific PII supplies their own `redact` hook.\n *\n * This is intentionally narrower than `src/sanitize.ts` (which redacts the\n * runtime's *event envelope* field-by-field): here the value is opaque\n * customer payload, so the scrub is value-shaped, not schema-shaped.\n */\n\n/** A redactor maps an arbitrary trace value to a safe-to-export value. Pure;\n * must not throw on cyclic input (the default tolerates cycles). */\nexport type Redactor = (value: unknown) => unknown\n\nconst redactedMarker = '[redacted]'\n\n/** Secret-bearing key names: when an object key matches, its value is fully\n * replaced regardless of the value's own content. Lowercased compare. */\nconst secretKeyPattern =\n /(api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(id|token)|cookie|bearer)/i\n\n/** In-value secret/PII patterns scrubbed from any string, regardless of key. */\nconst valuePatterns: ReadonlyArray<RegExp> = [\n // Bearer tokens.\n /\\bBearer\\s+[A-Za-z0-9._\\-+/=]{8,}/gi,\n // Provider-style API keys (sk-..., sk-tan-..., pk_live_..., ghp_...).\n /\\b(?:sk|pk|rk|ak)[-_][A-Za-z0-9_-]{12,}/g,\n /\\bgh[pousr]_[A-Za-z0-9]{20,}/g,\n // AWS access key ids.\n /\\bAKIA[0-9A-Z]{16}\\b/g,\n // PEM private-key blocks.\n /-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,\n // Email addresses.\n /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n]\n\n/** Scrub a single string of in-value secret/PII patterns. */\nfunction scrubString(input: string): string {\n let out = input\n for (const pattern of valuePatterns) {\n out = out.replace(pattern, redactedMarker)\n }\n return out\n}\n\n/**\n * The built-in redactor. Walks objects and arrays; replaces values under\n * secret-bearing keys wholesale; scrubs in-value patterns from every string.\n * Cycle-safe (a seen-set short-circuits self-referential payloads to\n * `'[circular]'`), depth-bounded, and total — never throws on customer input.\n */\nexport function defaultRedactor(value: unknown): unknown {\n return walk(value, new WeakSet(), 0)\n}\n\nconst maxDepth = 32\n\nfunction walk(value: unknown, seen: WeakSet<object>, depth: number): unknown {\n if (depth > maxDepth) return '[truncated]'\n if (typeof value === 'string') return scrubString(value)\n if (value === null || typeof value !== 'object') return value\n if (seen.has(value)) return '[circular]'\n seen.add(value)\n\n if (Array.isArray(value)) {\n return value.map((item) => walk(item, seen, depth + 1))\n }\n\n const out: Record<string, unknown> = {}\n for (const [key, v] of Object.entries(value as Record<string, unknown>)) {\n if (secretKeyPattern.test(key)) {\n out[key] = redactedMarker\n continue\n }\n out[key] = walk(v, seen, depth + 1)\n }\n return out\n}\n\n/**\n * Resolve the redactor a client uses. A caller-supplied hook replaces the\n * default entirely (the customer owns their PII rules); absent one, the\n * built-in `defaultRedactor` runs. Returning `false` is the explicit opt-out —\n * NO redaction, for a caller who has already sanitized upstream and wants raw\n * fidelity. Opt-out is loud (an explicit `false`), never a silent default.\n */\nexport function resolveRedactor(redact: Redactor | false | undefined): Redactor {\n if (redact === false) return (value) => value\n return redact ?? defaultRedactor\n}\n","/**\n * @experimental\n *\n * Tangle Intelligence — the DELIVERY half of the loop (pull-by-default).\n *\n * The sibling Observe layer (`./index`) sends traces UP to the plane. This\n * module pulls certified artifacts DOWN: it reads the tenant's promoted,\n * gate-certified profile from the deployed Intelligence plane and folds it into\n * the running agent's prompt — so an approved improvement actually reaches the\n * agent. This is \"shipping intelligence to people's agents\", pull-by-default;\n * the push/Gated-PR opt-in composes on top of this.\n *\n * Pull contract (deployed plane): GET /v1/profiles/:target/composed →\n * { target, generatedAt, promptSurface: {surface,surfaceHash,version,lift}|null,\n * artifacts: { <artifactType>: [{path,content,contentHash,version,lift,promotedAt}] } }\n * Auth: Bearer <apiKey> (the one TANGLE_API_KEY shared by router + sandbox +\n * intelligence), resolved to a tenant by platform-api's key-verify S2S contract.\n *\n * import { withCertifiedDelivery } from '@tangle-network/agent-runtime/intelligence'\n *\n * export const agent = withCertifiedDelivery(\n * async (input, applied) => myAgent(input, { systemPrompt: applied.composePrompt(BASE) }),\n * { project: 'support-agent', target: 'support-agent' },\n * )\n */\n\nimport { createIntelligenceClient, type IntelligenceConfig } from './index'\n\nconst defaultPlaneBaseUrl = 'https://intelligence.tangle.tools'\nconst defaultRefreshMs = 300_000\n\n/** A promoted, certified artifact (one entry in the composed profile). */\nexport interface CertifiedArtifact {\n path: string | null\n content: string\n contentHash: string\n version: number | null\n /** Held-out gate lift attached at certification, e.g. \"+3.1pp\" — never a\n * within-run claim. `null` when the promotion carried no lift record. */\n lift: string | null\n promotedAt: string\n}\n\n/** The active promoted prompt surface for a target. */\nexport interface CertifiedPromptSurface {\n surface: string\n surfaceHash: string\n version: number | null\n lift: string | null\n}\n\n/** The composed certified profile — exactly the shape the plane's\n * `GET /v1/profiles/:target/composed` returns. */\nexport interface CertifiedProfile {\n target: string\n generatedAt: string\n promptSurface: CertifiedPromptSurface | null\n artifacts: Record<string, CertifiedArtifact[]>\n}\n\n/** Typed outcome for the pull — inspect `succeeded` before `value`. A 404\n * (nothing promoted yet) is a normal, non-error `succeeded: false`. */\nexport type PullOutcome =\n | { succeeded: true; value: CertifiedProfile }\n | { succeeded: false; error: string; status?: number }\n\nexport interface PullCertifiedOptions {\n /** The agent target certified artifacts are promoted under. */\n target: string\n /** Bearer key. Defaults to `process.env.TANGLE_API_KEY`. */\n apiKey?: string\n /** Plane base URL. Defaults to `process.env.TANGLE_INTELLIGENCE_URL` then\n * `https://intelligence.tangle.tools`. */\n baseUrl?: string\n /** fetch impl (tests / non-global-fetch runtimes). Defaults to global fetch. */\n fetchImpl?: typeof fetch\n}\n\nfunction resolvePlaneBaseUrl(baseUrl: string | undefined): string {\n if (baseUrl) return baseUrl.replace(/\\/+$/, '')\n if (typeof process !== 'undefined' && process.env.TANGLE_INTELLIGENCE_URL) {\n return process.env.TANGLE_INTELLIGENCE_URL.replace(/\\/+$/, '')\n }\n return defaultPlaneBaseUrl\n}\n\nfunction resolveApiKey(apiKey: string | undefined): string {\n if (apiKey) return apiKey\n if (typeof process !== 'undefined' && process.env.TANGLE_API_KEY)\n return process.env.TANGLE_API_KEY\n return ''\n}\n\n/**\n * Pull the certified composed profile for a target. Fail-closed: a network\n * error or a non-2xx returns a typed `succeeded: false` (never throws), so a\n * caller can run on its base surface when Intelligence is unreachable. A 404 is\n * the normal \"nothing promoted yet\" signal, carried as `status: 404`.\n */\nexport async function pullCertified(opts: PullCertifiedOptions): Promise<PullOutcome> {\n const doFetch = opts.fetchImpl ?? (globalThis.fetch as typeof fetch | undefined)\n if (!doFetch) return { succeeded: false, error: 'no fetch implementation available' }\n const apiKey = resolveApiKey(opts.apiKey)\n if (!apiKey) return { succeeded: false, error: 'no apiKey (set TANGLE_API_KEY or opts.apiKey)' }\n const baseUrl = resolvePlaneBaseUrl(opts.baseUrl)\n const url = `${baseUrl}/v1/profiles/${encodeURIComponent(opts.target)}/composed`\n let res: Response\n try {\n res = await doFetch(url, { headers: { authorization: `Bearer ${apiKey}` } })\n } catch (err) {\n return {\n succeeded: false,\n error: `pull request failed: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (res.status === 404) {\n return {\n succeeded: false,\n error: 'no certified artifacts promoted for target yet',\n status: 404,\n }\n }\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n return {\n succeeded: false,\n error: `pull ${res.status}: ${body.slice(0, 200)}`,\n status: res.status,\n }\n }\n try {\n return { succeeded: true, value: (await res.json()) as CertifiedProfile }\n } catch (err) {\n return {\n succeeded: false,\n error: `pull response parse failed: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n}\n\n/**\n * Fold the certified prompt surface (and any certified `prompt-surface` /\n * `skill` artifacts) into a base system prompt under a marked section, so the\n * deployed agent prompt == base + the gate-certified additions. Order is stable\n * (prompt surface first, then artifacts by type then path) so the same profile\n * renders byte-identically each call. Returns `base` unchanged when there is no\n * usable certified content.\n */\nexport function composeCertifiedPrompt(base: string, certified: CertifiedProfile | null): string {\n if (!certified) return base\n const parts: string[] = []\n if (certified.promptSurface?.surface.trim()) parts.push(certified.promptSurface.surface.trim())\n for (const type of Object.keys(certified.artifacts).sort()) {\n if (type !== 'prompt-surface' && type !== 'skill') continue\n const bucket = certified.artifacts[type] ?? []\n for (const a of [...bucket].sort((x, y) => (x.path ?? '').localeCompare(y.path ?? ''))) {\n if (a.content.trim()) parts.push(a.content.trim())\n }\n }\n if (parts.length === 0) return base\n return `${base.trim()}\\n\\n## Certified guidance (Tangle Intelligence)\\n\\n${parts.join('\\n\\n')}`\n}\n\n/** What the delivery wrapper hands the agent each run. */\nexport interface AppliedIntelligence {\n /** The certified profile in effect (null when none promoted / pull failed —\n * fail-closed: the agent runs on its base surface). */\n certified: CertifiedProfile | null\n /** Fold the certified prompt surface into a base system prompt. */\n composePrompt(base: string): string\n}\n\n/** An agent wrapped by {@link withCertifiedDelivery}: receives the input plus\n * the certified intelligence delivered for this run. */\nexport type DeliveredAgent<I, O> = (input: I, applied: AppliedIntelligence) => Promise<O>\n\n/** Delivery config = the Observe config plus the pull target + refresh cadence. */\nexport interface DeliveryConfig extends IntelligenceConfig {\n /** Pull target. Defaults to `project`. */\n target?: string\n /** Plane base URL for the pull (NOT the OTLP `endpoint`). Defaults to\n * `TANGLE_INTELLIGENCE_URL` then `https://intelligence.tangle.tools`. */\n baseUrl?: string\n /** Min interval between certified-profile pulls. Default 5m. */\n refreshMs?: number\n /** fetch impl for the pull (tests). Defaults to global fetch. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Wrap an agent so it (a) Observes each run via the shipped Observe client and\n * (b) RECEIVES the tenant's certified artifacts pulled from the deployed plane.\n * The certified profile is cached and refreshed at most every `refreshMs`; a\n * failed pull is fail-closed — the agent runs on its base surface and never\n * breaks because Intelligence is unreachable. When the plane promotes a new\n * gate-certified surface, the next refresh delivers it to the running agent.\n */\nexport function withCertifiedDelivery<I, O>(\n agent: DeliveredAgent<I, O>,\n config: DeliveryConfig,\n): ((input: I) => Promise<O>) & { refresh(): Promise<void> } {\n const client = createIntelligenceClient(config)\n const target = config.target ?? config.project\n const refreshMs = config.refreshMs ?? defaultRefreshMs\n let certified: CertifiedProfile | null = null\n let lastPullAt = 0\n let inflight: Promise<void> | null = null\n\n async function refresh(): Promise<void> {\n if (Date.now() - lastPullAt < refreshMs) return\n if (inflight) return inflight\n inflight = (async () => {\n const outcome = await pullCertified({\n target,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n fetchImpl: config.fetchImpl,\n })\n lastPullAt = Date.now()\n // Only replace the cache on a real pull; a 404/error keeps the last-known\n // certified profile (or null) — fail-closed, never wipe a good surface.\n if (outcome.succeeded) certified = outcome.value\n })()\n try {\n await inflight\n } finally {\n inflight = null\n }\n }\n\n const wrapped = (async (input: I): Promise<O> => {\n await refresh()\n const applied: AppliedIntelligence = {\n certified,\n composePrompt: (base: string) => composeCertifiedPrompt(base, certified),\n }\n return client.traceRun(\n { input, labels: { 'tangle.certified_version': certified?.promptSurface?.version ?? -1 } },\n async (trace) => {\n const out = await agent(input, applied)\n trace.recordOutput(out)\n return out\n },\n )\n }) as ((input: I) => Promise<O>) & { refresh(): Promise<void> }\n wrapped.refresh = refresh\n return wrapped\n}\n","/**\n * @experimental\n *\n * Tangle Intelligence SDK — the Observe + Mode-0 product layer.\n *\n * A thin, best-effort wrapper over the shipped trace-export substrate\n * (`createOtelExporter` in `../otel-export`). It does exactly two things in\n * this slice:\n *\n * 1. OBSERVE — wrap a generic agent and export one trace span per call to\n * Tangle Intelligence, swallowing every export failure so a live agent\n * never fails because Intelligence is down.\n * 2. MODE 0 / OFF — at `effort: 'off'`, run the agent as PURE PASSTHROUGH\n * (zero intelligence spawns) with best-effort telemetry still on. The\n * exported trace tags usage by class `{ inferenceUsd, intelligenceUsd }`,\n * and at OFF `intelligenceUsd` is provably `0` — the mechanism that proves\n * an OFF customer paid inference-only.\n *\n * Behavior-changing intelligence (analyst steer, candidate promotion, loops)\n * is a LATER phase and is NOT built here. This wrapper only Observes and passes\n * through; there is no abort path, so the only fail-soft surface is the\n * telemetry export.\n */\n\nimport { createOtelExporter, loopEventToOtelSpan, type OtelExporter } from '../otel-export'\nimport {\n defaultEffortTier,\n type EffortOverrides,\n type EffortSettings,\n type EffortTier,\n isIntelligenceOff,\n resolveEffort,\n} from './effort'\nimport { type Redactor, resolveRedactor } from './redact'\n\nexport type {\n AppliedIntelligence,\n CertifiedArtifact,\n CertifiedProfile,\n CertifiedPromptSurface,\n DeliveredAgent,\n DeliveryConfig,\n PullCertifiedOptions,\n PullOutcome,\n} from './delivery'\nexport { composeCertifiedPrompt, pullCertified, withCertifiedDelivery } from './delivery'\nexport type {\n CorpusAccess,\n EffortOverrides,\n EffortSettings,\n EffortTier,\n} from './effort'\nexport {\n defaultEffortTier,\n isIntelligenceOff,\n resolveEffort,\n} from './effort'\nexport type { Redactor } from './redact'\nexport { defaultRedactor, resolveRedactor } from './redact'\n\n/** Usage class for billing. Base-stream tokens bill `'inference'`; every\n * intelligence spawn (analyst, corpus, loop) bills `'intelligence'`. The\n * billing line falls on the spawn line. */\nexport type UsageClass = 'inference' | 'intelligence'\n\n/**\n * The per-class cost split carried by every trace and outcome. `off` ⇒\n * `intelligenceUsd: 0` by construction — there is no intelligence spawn to\n * bill. This is a classification on the trace, NOT a budget-pool split.\n */\nexport interface UsageSplit {\n /** Base-stream (model) spend in USD. */\n inferenceUsd: number\n /** Intelligence-spawn spend in USD. Provably `0` at the OFF tier. */\n intelligenceUsd: number\n}\n\n/** Repo coordinates a product may declare for the (later) Gated-PR mode. The\n * Observe slice only records their PRESENCE for `doctor()`; it never touches\n * the repo. */\nexport interface RepoConfig {\n owner: string\n name: string\n baseBranch: string\n}\n\n/** Client configuration. `project` + `apiKey` are the Observe minimum; the\n * rest tune effort, endpoint, redaction, and (for `doctor()` readiness)\n * declare the surfaces/checks/repo a later PR mode would need. */\nexport interface IntelligenceConfig {\n /** Stable project id — the tenant dimension every trace is tagged with. */\n project: string\n /** Bearer key for the Intelligence ingest. Reads `TANGLE_API_KEY` when omitted. */\n apiKey?: string\n /** Effort tier (default `'standard'`) plus optional per-field overrides. */\n effort?: EffortTier | { tier: EffortTier; overrides?: EffortOverrides }\n /**\n * OTLP ingest base. The underlying exporter appends `/v1/traces`, so point\n * this at the OTLP route (e.g. `https://intelligence.tangle.tools/v1/otlp`).\n * Reads `INTELLIGENCE_OTLP_ENDPOINT` then `OTEL_EXPORTER_OTLP_ENDPOINT` when\n * omitted; absent all three, export is a no-op (best-effort by construction).\n */\n endpoint?: string\n /**\n * Redaction hook run over every exported input/output. A function replaces\n * the default scrubber; `false` opts out entirely (raw fidelity, caller has\n * sanitized upstream); omitted ⇒ the built-in `defaultRedactor`.\n */\n redact?: Redactor | false\n /** Mutable surfaces a later PR mode would edit. Recorded for `doctor()` only. */\n surfaces?: string[]\n /** Verification checks a later PR mode would gate on. Recorded for `doctor()` only. */\n checks?: string[]\n /** Repo access a later PR mode would need. Recorded for `doctor()` only. */\n repo?: RepoConfig\n}\n\n/** Metadata describing one traced run. `runId`/`traceId` default to fresh ids. */\nexport interface TraceMeta {\n /** The run's input — exported through the redactor. */\n input?: unknown\n /** Stable run id. Defaults to a fresh id. */\n runId?: string\n /** 32-hex trace id. Defaults to a fresh id. */\n traceId?: string\n /** Model id, when known — stamped on the span. */\n model?: string\n /** Provider name, when known — stamped on the span. */\n provider?: string\n /** Arbitrary extra labels (string/number/boolean) stamped on the span. */\n labels?: Record<string, string | number | boolean>\n}\n\n/**\n * The trace handle a `traceRun` body records into. `recordOutput` captures the\n * agent's result (redacted on export); `recordOutcome` captures the scored\n * outcome + the `{ inferenceUsd, intelligenceUsd }` split. Both are optional —\n * an un-recorded run still exports a span with whatever was set.\n */\nexport interface TraceHandle {\n /** Capture the run's output. Exported through the redactor. */\n recordOutput(output: unknown): void\n /**\n * Capture the run's outcome. `usage` defaults to inference-only\n * (`intelligenceUsd: 0`) — the OFF baseline; an intelligence-enabled run\n * fills `intelligenceUsd` itself. `costUsd`, when given without a split, is\n * treated as pure inference.\n */\n recordOutcome(outcome: {\n success?: boolean\n score?: number\n costUsd?: number\n usage?: Partial<UsageSplit>\n }): void\n}\n\n/** The resolved outcome of one traced run, surfaced on the export span and\n * available to the caller for downstream billing assertions. */\nexport interface TraceOutcome {\n runId: string\n traceId: string\n project: string\n /** The resolved effort settings this run executed under. */\n effort: EffortSettings\n /** True when this run ran as pure passthrough (the OFF floor). */\n intelligenceOff: boolean\n success?: boolean\n score?: number\n /** Per-class billing split. `intelligenceUsd` is `0` at the OFF tier. */\n usage: UsageSplit\n}\n\n/** The Observe-mode Intelligence client. */\nexport interface IntelligenceClient {\n /** The resolved project id. */\n readonly project: string\n /** The resolved effort settings. */\n readonly effort: EffortSettings\n /**\n * Run `fn` under a trace, export one span best-effort, and return whatever\n * `fn` returns. Telemetry-export failures are swallowed; an error THROWN by\n * `fn` propagates to the caller (the agent's own failures are not masked).\n */\n traceRun<T>(meta: TraceMeta, fn: (trace: TraceHandle) => Promise<T>): Promise<T>\n /**\n * Network-free readiness report: which adoption modes are reachable given\n * this config. Observe is always reachable; Recommend needs outcomes; PR\n * needs checks + surfaces + repo.\n */\n doctor(): DoctorReport\n /** Flush any pending export spans. Best-effort; resolves even if export fails. */\n flush(): Promise<void>\n}\n\n/** One mode's readiness verdict. */\nexport interface ModeReadiness {\n ready: boolean\n /** Inputs this mode still needs, when not ready. Empty when ready. */\n missing: string[]\n}\n\n/** The `doctor()` readiness report — Mode-readiness without any network call. */\nexport interface DoctorReport {\n project: string\n effort: EffortSettings\n /** True when an OTLP endpoint is configured (export will actually ship). */\n exportConfigured: boolean\n modes: {\n observe: ModeReadiness\n recommend: ModeReadiness\n pr: ModeReadiness\n }\n}\n\nfunction resolveEffortConfig(effort: IntelligenceConfig['effort']): EffortSettings {\n if (effort === undefined) return resolveEffort(defaultEffortTier)\n if (typeof effort === 'string') return resolveEffort(effort)\n return resolveEffort(effort.tier, effort.overrides)\n}\n\nfunction resolveEndpoint(endpoint: string | undefined): string | undefined {\n if (endpoint) return endpoint\n if (typeof process === 'undefined') return undefined\n return process.env.INTELLIGENCE_OTLP_ENDPOINT ?? process.env.OTEL_EXPORTER_OTLP_ENDPOINT\n}\n\nfunction freshTraceId(): string {\n return randomHex(32)\n}\n\nfunction freshRunId(): string {\n return `run-${randomHex(16)}`\n}\n\n/** Serialize a redacted value to a bounded string for a span attribute.\n * `loopEventToOtelSpan` only stamps string/number/boolean payload fields, so a\n * structured input/output must be flattened here. Bounded to keep span\n * attributes small; the full payload is the consumer's own store, not the span. */\nconst previewMaxChars = 4096\nfunction previewJson(value: unknown): string {\n let s: string\n if (typeof value === 'string') s = value\n else {\n try {\n s = JSON.stringify(value) ?? String(value)\n } catch {\n s = String(value)\n }\n }\n return s.length > previewMaxChars ? `${s.slice(0, previewMaxChars)}…[truncated]` : s\n}\n\nfunction randomHex(chars: number): string {\n const bytes = new Uint8Array(Math.ceil(chars / 2))\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < bytes.length; 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 .slice(0, chars)\n}\n\n/**\n * Create an Observe-mode Intelligence client. Resolves effort, endpoint, and\n * redactor up front; the exporter is built lazily and is `undefined` when no\n * endpoint is configured (export becomes a no-op — best-effort by\n * construction).\n */\nexport function createIntelligenceClient(config: IntelligenceConfig): IntelligenceClient {\n if (!config.project) {\n throw new Error('createIntelligenceClient: `project` is required')\n }\n const effort = resolveEffortConfig(config.effort)\n const intelligenceOff = isIntelligenceOff(effort)\n const redactor = resolveRedactor(config.redact)\n const apiKey =\n config.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n const endpoint = resolveEndpoint(config.endpoint)\n\n // Built lazily: a client with no endpoint never allocates an exporter timer.\n let exporter: OtelExporter | undefined\n let exporterResolved = false\n function getExporter(): OtelExporter | undefined {\n if (exporterResolved) return exporter\n exporterResolved = true\n if (!endpoint) return undefined\n exporter = createOtelExporter({\n endpoint,\n headers: apiKey ? { authorization: `Bearer ${apiKey}` } : {},\n serviceName: config.project,\n resourceAttributes: { 'tangle.project': config.project },\n })\n return exporter\n }\n\n function exportTrace(meta: TraceMeta, outcome: TraceOutcome, output: unknown): void {\n const ex = getExporter()\n if (!ex) return\n const labels: Record<string, string | number | boolean> = {\n project: config.project,\n 'tangle.effort.intelligence_off': outcome.intelligenceOff,\n 'tangle.usage.inference_usd': outcome.usage.inferenceUsd,\n 'tangle.usage.intelligence_usd': outcome.usage.intelligenceUsd,\n ...(meta.model ? { 'gen_ai.request.model': meta.model } : {}),\n ...(meta.provider ? { 'provider.name': meta.provider } : {}),\n ...(typeof outcome.success === 'boolean'\n ? { 'tangle.outcome.success': outcome.success }\n : {}),\n ...(typeof outcome.score === 'number' ? { 'tangle.outcome.score': outcome.score } : {}),\n ...(meta.labels ?? {}),\n }\n const redactedInput = meta.input !== undefined ? redactor(meta.input) : undefined\n const redactedOutput = output !== undefined ? redactor(output) : undefined\n if (redactedInput !== undefined) labels['tangle.input'] = previewJson(redactedInput)\n if (redactedOutput !== undefined) labels['tangle.output'] = previewJson(redactedOutput)\n try {\n ex.exportSpan(\n loopEventToOtelSpan(\n {\n kind: 'tangle.intelligence.run',\n runId: outcome.runId,\n timestamp: Date.now(),\n payload: labels,\n },\n outcome.traceId,\n ),\n )\n } catch {\n // Best-effort — telemetry export must never fail the agent's turn.\n }\n }\n\n return {\n project: config.project,\n effort,\n\n async traceRun<T>(meta: TraceMeta, fn: (trace: TraceHandle) => Promise<T>): Promise<T> {\n const runId = meta.runId ?? freshRunId()\n const traceId = meta.traceId ?? freshTraceId()\n let recordedOutput: unknown\n // Default split: inference-only. At OFF this is provably the whole bill.\n const usage: UsageSplit = { inferenceUsd: 0, intelligenceUsd: 0 }\n let success: boolean | undefined\n let score: number | undefined\n\n const trace: TraceHandle = {\n recordOutput(output: unknown): void {\n recordedOutput = output\n },\n recordOutcome(outcome): void {\n if (typeof outcome.success === 'boolean') success = outcome.success\n if (typeof outcome.score === 'number') score = outcome.score\n if (outcome.usage) {\n if (typeof outcome.usage.inferenceUsd === 'number') {\n usage.inferenceUsd = outcome.usage.inferenceUsd\n }\n if (typeof outcome.usage.intelligenceUsd === 'number') {\n usage.intelligenceUsd = outcome.usage.intelligenceUsd\n }\n } else if (typeof outcome.costUsd === 'number') {\n // A bare cost with no split is pure inference (the base stream).\n usage.inferenceUsd = outcome.costUsd\n }\n },\n }\n\n // The OFF floor is a HARD invariant, not a default: no intelligence spawn\n // can occur in this Observe slice, so intelligence-class spend is zero.\n // We clamp on export rather than trust the caller, so the billing proof\n // holds even if a caller mis-records an outcome at OFF.\n const result = await fn(trace)\n if (intelligenceOff) usage.intelligenceUsd = 0\n\n const outcome: TraceOutcome = {\n runId,\n traceId,\n project: config.project,\n effort,\n intelligenceOff,\n ...(success !== undefined ? { success } : {}),\n ...(score !== undefined ? { score } : {}),\n usage,\n }\n exportTrace(meta, outcome, recordedOutput)\n return result\n },\n\n doctor(): DoctorReport {\n const hasRepo = Boolean(config.repo?.owner && config.repo?.name && config.repo?.baseBranch)\n const hasChecks = Boolean(config.checks && config.checks.length > 0)\n const hasSurfaces = Boolean(config.surfaces && config.surfaces.length > 0)\n\n const prMissing: string[] = []\n if (!hasChecks) prMissing.push('checks')\n if (!hasSurfaces) prMissing.push('surfaces')\n if (!hasRepo) prMissing.push('repo')\n\n // Recommend needs real outcomes to cluster. In the Observe slice the only\n // outcome source is `recordOutcome`; we can't introspect future calls, so\n // readiness reflects that outcome capture is WIRED (the API exists),\n // gated on the client emitting them — surfaced as the honest dependency.\n const recommendMissing: string[] = []\n if (intelligenceOff) recommendMissing.push('effort above off')\n\n return {\n project: config.project,\n effort,\n exportConfigured: Boolean(endpoint),\n modes: {\n observe: { ready: true, missing: [] },\n recommend: {\n ready: recommendMissing.length === 0,\n missing: recommendMissing,\n },\n pr: { ready: prMissing.length === 0, missing: prMissing },\n },\n }\n },\n\n async flush(): Promise<void> {\n const ex = getExporter()\n if (!ex) return\n try {\n await ex.flush()\n } catch {\n // Best-effort — a flush failure must not surface to the caller.\n }\n },\n }\n}\n\n/** A generic agent: one async input → output. The shape `withTangleIntelligence`\n * preserves exactly. */\nexport type Agent<TInput, TOutput> = (input: TInput) => Promise<TOutput>\n\n/** Either a built client or the config to build one. */\nexport type ClientOrConfig = IntelligenceClient | IntelligenceConfig\n\nfunction isClient(value: ClientOrConfig): value is IntelligenceClient {\n return typeof (value as IntelligenceClient).traceRun === 'function'\n}\n\n/**\n * Wrap a generic `agent` with best-effort Observe-mode tracing, returning the\n * SAME shape. Each call runs the agent under a trace and exports one span; an\n * export failure is swallowed (the live agent never fails because Intelligence\n * is down) but an error from the agent itself propagates unchanged.\n *\n * At `effort: 'off'` this is pure passthrough plus best-effort telemetry —\n * zero intelligence spawns, `intelligenceUsd: 0` on the trace.\n */\nexport function withTangleIntelligence<TInput, TOutput>(\n agent: Agent<TInput, TOutput>,\n clientOrConfig: ClientOrConfig,\n): Agent<TInput, TOutput> {\n const client = isClient(clientOrConfig)\n ? clientOrConfig\n : createIntelligenceClient(clientOrConfig)\n\n return async (input: TInput): Promise<TOutput> => {\n return client.traceRun({ input }, async (trace) => {\n const output = await agent(input)\n trace.recordOutput(output)\n return output\n })\n }\n}\n"],"mappings":";;;;;;;AAoDA,IAAM,UAAkE;AAAA,EACtE,KAAK;AAAA,IACH,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AAAA,EACA,KAAK;AAAA,IACH,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AAAA,EACA,UAAU;AAAA,IACR,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AAAA,EACA,UAAU;AAAA,IACR,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AAAA,EACA,KAAK;AAAA,IACH,UAAU;A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ACF;AASA,SAAS,SAAS,OAAoD;AACpE,SAAO,OAAQ,MAA6B,aAAa;AAC3D;AAWO,SAAS,uBACd,OACA,gBACwB;AACxB,QAAM,SAAS,SAAS,cAAc,IAClC,iBACA,yBAAyB,cAAc;AAE3C,SAAO,OAAO,UAAoC;AAChD,WAAO,OAAO,SAAS,EAAE,MAAM,GAAG,OAAO,UAAU;AACjD,YAAM,SAAS,MAAM,MAAM,KAAK;AAChC,YAAM,aAAa,MAAM;AACzB,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":["outcome"]}
|
|
1
|
+
{"version":3,"sources":["../src/intelligence/effort.ts","../src/intelligence/redact.ts","../src/intelligence/capability.ts","../src/intelligence/delivery.ts","../src/intelligence/resolver.ts","../src/intelligence/index.ts"],"sourcesContent":["/**\n * @experimental\n *\n * EffortPolicy — pure data, no execution. Resolves a named tier into a flat\n * settings object the Intelligence wrapper reads to decide WHICH intelligence\n * spawns are admitted. The composer never runs anything; it only describes the\n * shape of intelligence a tier permits.\n *\n * The billing boundary lives one layer above this (the wrapper tags trace usage\n * by class). What this module owns is the single law the OFF tier rests on:\n * `'off'` ⇒ every intelligence knob OFF (analysts:false, corpus:'off',\n * fanout:1, loops:false, intelligenceBudgetUsd:0). At OFF the wrapper runs the\n * agent as pure passthrough and only intelligence-class usage can prove to be\n * zero — there is nothing to spawn.\n */\n\n/** The named effort tiers, lowest to highest. `'off'` is the honest floor\n * below `'eco'`: intelligence fully off, telemetry still best-effort. */\nexport type EffortTier = 'off' | 'eco' | 'standard' | 'thorough' | 'max'\n\n/** Corpus access an intelligence tier permits. `'off'` reads and writes\n * nothing; `'read'` consults the cross-run corpus without contributing;\n * `'read-write'` both consults and accumulates. */\nexport type CorpusAccess = 'off' | 'read' | 'read-write'\n\n/**\n * The flat, resolved settings a tier compiles to. Every field is individually\n * overridable through `resolveEffort`. Pure data — read by the wrapper, never\n * self-executing.\n */\nexport interface EffortSettings {\n /** Whether trace-derived analyst diagnosis may spawn. `false` ⇒ no analyst. */\n analysts: boolean\n /** Cross-run corpus access this tier permits. */\n corpus: CorpusAccess\n /** Parallel candidate width. `1` ⇒ single-shot, no breadth. */\n fanout: number\n /** Whether multi-step improvement loops (refine / fanout-vote) may run. */\n loops: boolean\n /**\n * Ceiling, in USD, for INTELLIGENCE-class spawns only (analysts, corpus,\n * loops) — NOT base inference. `0` refuses every intelligence spawn; `null`\n * means uncapped (the spend lands on the Pareto receipt). Base-stream\n * inference is billed on its own channel and is never constrained here.\n */\n intelligenceBudgetUsd: number | null\n}\n\n/** Per-field overrides applied on top of a tier preset. Any subset of the\n * resolved settings; each provided field wins over the preset. */\nexport type EffortOverrides = Partial<EffortSettings>\n\nconst presets: Readonly<Record<EffortTier, Readonly<EffortSettings>>> = {\n off: {\n analysts: false,\n corpus: 'off',\n fanout: 1,\n loops: false,\n intelligenceBudgetUsd: 0,\n },\n eco: {\n analysts: true,\n corpus: 'read',\n fanout: 1,\n loops: false,\n intelligenceBudgetUsd: 0.25,\n },\n standard: {\n analysts: true,\n corpus: 'read-write',\n fanout: 3,\n loops: true,\n intelligenceBudgetUsd: 2,\n },\n thorough: {\n analysts: true,\n corpus: 'read-write',\n fanout: 5,\n loops: true,\n intelligenceBudgetUsd: 10,\n },\n max: {\n analysts: true,\n corpus: 'read-write',\n fanout: 8,\n loops: true,\n intelligenceBudgetUsd: null,\n },\n}\n\n/** The default tier when a client declares no effort. `'standard'` turns\n * intelligence on with sensible knobs; opt down to `'off'`/`'eco'` or up to\n * `'thorough'`/`'max'`. */\nexport const defaultEffortTier: EffortTier = 'standard'\n\n/**\n * Compile a named tier (plus optional per-field overrides) into the flat\n * `EffortSettings` the wrapper reads. Pure: same inputs → same object, no I/O,\n * no execution. Fails loud on an unknown tier rather than silently defaulting —\n * a typo'd tier must not quietly grant or deny intelligence.\n *\n * Invariant preserved for the billing floor: `resolveEffort('off')` always\n * yields `intelligenceBudgetUsd: 0` with every intelligence knob off UNLESS the\n * caller explicitly overrides a field — overriding off is an opt-in the caller\n * owns, not a default the composer leaks.\n */\nexport function resolveEffort(tier: EffortTier, overrides?: EffortOverrides): EffortSettings {\n const preset = presets[tier]\n if (!preset) {\n throw new Error(\n `resolveEffort: unknown effort tier ${JSON.stringify(tier)} (expected one of ${(\n Object.keys(presets) as EffortTier[]\n )\n .map((t) => `'${t}'`)\n .join(', ')})`,\n )\n }\n return { ...preset, ...(overrides ?? {}) }\n}\n\n/**\n * True when these settings admit NO intelligence spawn — the passthrough\n * predicate the wrapper branches on. Every intelligence axis must be off:\n * analysts disabled, corpus off, no breadth, no loops, and a zero intelligence\n * budget. A caller who overrides any one of these back on is no longer at the\n * OFF floor and the wrapper treats them as an intelligence-enabled run.\n */\nexport function isIntelligenceOff(settings: EffortSettings): boolean {\n return (\n settings.analysts === false &&\n settings.corpus === 'off' &&\n settings.fanout <= 1 &&\n settings.loops === false &&\n settings.intelligenceBudgetUsd === 0\n )\n}\n\n/**\n * The run-config overrides an `EffortSettings` compiles to — the bridge between the\n * pure effort policy and the orchestration entrypoints (`runPersonified` / the\n * improvement cycle). This is ONLY data: it never constructs an analyst or runs a\n * loop. The caller reads these flags to decide WHAT to pass:\n *\n * - `withAnalyst: false` ⇒ DO NOT construct/pass a `ScopeAnalyst` to `runPersonified`\n * (the dormant empty-findings path runs; the base agent still works). This is the\n * PRODUCT fail-closed at `off`/`eco` — \"don't construct the analyst\" — distinct from\n * the EXPERIMENT fail-closed inside `createScopeAnalyst` (\"hard abort\"), which stays\n * untouched. Degrade, never throw.\n * - `fanout` ⇒ the `ShapeBudget.fanout` width to pass (`1` at `off`, the tier's breadth\n * otherwise). Overrides the personify default fanout.\n * - `withLoops: false` ⇒ the improvement cycle is a no-op for this run (no refine /\n * fanout-vote multi-step loop spawns).\n * - `intelligenceBudgetUsd` ⇒ the intelligence-class spend ceiling carried through for\n * the billing clamp (passed verbatim; `0` refuses every intelligence spawn).\n */\nexport interface EffortOverridesCompiled {\n /** Construct + pass a `ScopeAnalyst`? `false` ⇒ omit it (degrade to the base agent). */\n withAnalyst: boolean\n /** `ShapeBudget.fanout` width to pass to `runPersonified`. */\n fanout: number\n /** Run the multi-step improvement cycle, or no-op it for this run? */\n withLoops: boolean\n /** Intelligence-class spend ceiling. `0` refuses every intelligence spawn; `null` uncapped. */\n intelligenceBudgetUsd: number | null\n}\n\n/**\n * Compile resolved `EffortSettings` into the orchestration overrides above. Pure: same\n * input → same object, no I/O, no execution, no construction. It is the single place that\n * maps the effort axes onto the run-config knobs, so no `if (effort)` leaks into the\n * supervise kernel — the kernel stays effort-blind, the caller reads these flags once.\n *\n * `off`/`eco` (`analysts: false`) compile to `withAnalyst: false` ⇒ the caller omits the\n * analyst and the run degrades to the dormant base agent rather than throwing. `fanout: 1`\n * (no breadth) at `off`; `withLoops: false` no-ops the improvement cycle. `standard`+\n * compile to `withAnalyst: true`, the tier's `fanout`, and `withLoops: true`.\n */\nexport function compileEffort(settings: EffortSettings): EffortOverridesCompiled {\n return {\n withAnalyst: settings.analysts,\n fanout: settings.fanout,\n withLoops: settings.loops,\n intelligenceBudgetUsd: settings.intelligenceBudgetUsd,\n }\n}\n","/**\n * @experimental\n *\n * Redaction for Intelligence trace export. The trace carries the customer's\n * real input/output; before any of it leaves the process it passes through a\n * `Redactor`. The default scrubs the obvious leak classes (API keys, bearer\n * tokens, emails, private keys) from strings and walks nested objects/arrays,\n * but a customer with domain-specific PII supplies their own `redact` hook.\n *\n * This is intentionally narrower than `src/sanitize.ts` (which redacts the\n * runtime's *event envelope* field-by-field): here the value is opaque\n * customer payload, so the scrub is value-shaped, not schema-shaped.\n */\n\n/** A redactor maps an arbitrary trace value to a safe-to-export value. Pure;\n * must not throw on cyclic input (the default tolerates cycles). */\nexport type Redactor = (value: unknown) => unknown\n\nconst redactedMarker = '[redacted]'\n\n/** Secret-bearing key names: when an object key matches, its value is fully\n * replaced regardless of the value's own content. Lowercased compare. */\nconst secretKeyPattern =\n /(api[-_]?key|secret|token|password|passwd|authorization|auth|private[-_]?key|credential|access[-_]?key|client[-_]?secret|session[-_]?(id|token)|cookie|bearer)/i\n\n/** In-value secret/PII patterns scrubbed from any string, regardless of key. */\nconst valuePatterns: ReadonlyArray<RegExp> = [\n // Bearer tokens.\n /\\bBearer\\s+[A-Za-z0-9._\\-+/=]{8,}/gi,\n // Provider-style API keys (sk-..., sk-tan-..., pk_live_..., ghp_...).\n /\\b(?:sk|pk|rk|ak)[-_][A-Za-z0-9_-]{12,}/g,\n /\\bgh[pousr]_[A-Za-z0-9]{20,}/g,\n // AWS access key ids.\n /\\bAKIA[0-9A-Z]{16}\\b/g,\n // PEM private-key blocks.\n /-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,\n // Email addresses.\n /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g,\n]\n\n/** Scrub a single string of in-value secret/PII patterns. */\nfunction scrubString(input: string): string {\n let out = input\n for (const pattern of valuePatterns) {\n out = out.replace(pattern, redactedMarker)\n }\n return out\n}\n\n/**\n * The built-in redactor. Walks objects and arrays; replaces values under\n * secret-bearing keys wholesale; scrubs in-value patterns from every string.\n * Cycle-safe (a seen-set short-circuits self-referential payloads to\n * `'[circular]'`), depth-bounded, and total — never throws on customer input.\n */\nexport function defaultRedactor(value: unknown): unknown {\n return walk(value, new WeakSet(), 0)\n}\n\nconst maxDepth = 32\n\nfunction walk(value: unknown, seen: WeakSet<object>, depth: number): unknown {\n if (depth > maxDepth) return '[truncated]'\n if (typeof value === 'string') return scrubString(value)\n if (value === null || typeof value !== 'object') return value\n if (seen.has(value)) return '[circular]'\n seen.add(value)\n\n if (Array.isArray(value)) {\n return value.map((item) => walk(item, seen, depth + 1))\n }\n\n const out: Record<string, unknown> = {}\n for (const [key, v] of Object.entries(value as Record<string, unknown>)) {\n if (secretKeyPattern.test(key)) {\n out[key] = redactedMarker\n continue\n }\n out[key] = walk(v, seen, depth + 1)\n }\n return out\n}\n\n/**\n * Resolve the redactor a client uses. A caller-supplied hook replaces the\n * default entirely (the customer owns their PII rules); absent one, the\n * built-in `defaultRedactor` runs. Returning `false` is the explicit opt-out —\n * NO redaction, for a caller who has already sanitized upstream and wants raw\n * fidelity. Opt-out is loud (an explicit `false`), never a silent default.\n */\nexport function resolveRedactor(redact: Redactor | false | undefined): Redactor {\n if (redact === false) return (value) => value\n return redact ?? defaultRedactor\n}\n","/**\n * @experimental\n *\n * The Capability-Delivery Manifest — the unified, future-proof structure for\n * delivering ONE certified unit of agent power = `{ interface, binding }`.\n *\n * The law that makes it future-proof: **interfaces are closed; bindings are\n * open.** The interface is the only thing the agent and the certify lane ever\n * reason about (a tool / an MCP toolset / a prompt-context / a retrieval surface\n * / a hook / a subagent). The binding is a tagged union over runtime kinds that\n * the resolver collapses (inline / file / http / sandbox-code / mcp-stdio /\n * mcp-remote / process-on-infra / rag-index / memory-store / wasm / a2a). A new\n * runtime kind = one new binding arm + one resolver case; nothing else moves.\n *\n * This module owns the manifest TYPES and the lowering of TODAY's wire\n * (`CertifiedProfile`) into a `CapabilityManifest`. The resolver — the single\n * place that knows binding kinds and produces a uniform `ResolvedSurface` — lives\n * in `./resolver`. The shipped prompt-only path (`composeCertifiedPrompt` in\n * `./delivery`) is preserved verbatim: a prompt is a `Capability{ surface:\n * 'context', binding:{ kind:'inline' } }`, so the existing\n * `pullCertified → composeCertifiedPrompt → fail-closed` lane is a strict subset.\n *\n * Layering: this depends DOWN on `@tangle-network/sandbox` (the SDK\n * `AgentProfileMcpServer` shape the mcp binding lowers to) and on the runtime's\n * own `ToolSpec`. It never imports agent-eval and never reaches upward.\n */\n\nimport type { AgentProfileMcpServer } from '@tangle-network/sandbox'\nimport type { ToolSpec } from '../runtime/router-client'\nimport type { CertifiedArtifact, CertifiedProfile, CertifiedPromptSurface } from './delivery'\n\n// ── AXIS 1 — INTERFACE (CLOSED) ────────────────────────────────────────────────\n\n/** A JSON Schema object describing a tool's parameters. Kept structural — the\n * resolver forwards it verbatim into a `ToolSpec` / MCP `tools/list` check. */\nexport type JsonSchema = Record<string, unknown>\n\n/**\n * What the agent consumes. CLOSED — a new runtime kind NEVER extends this. Each\n * arm maps slot-for-slot onto `AgentProfile` + the host `RouterToolsSeam`.\n */\nexport type CapabilityInterface =\n | {\n surface: 'tool'\n name: string\n description?: string\n parameters: JsonSchema\n returns?: JsonSchema\n }\n | { surface: 'mcp'; serverName: string; toolset?: string[] }\n | { surface: 'context'; kind: 'prompt-surface' | 'skill' | 'instructions'; name: string }\n | { surface: 'retrieval'; name: string; description?: string; topK?: number }\n | { surface: 'hook'; event: string; matcher?: string }\n | { surface: 'subagent'; name: string; description?: string }\n\n/** Every interface surface tag — the closed set the resolver fans into slots. */\nexport type CapabilitySurface = CapabilityInterface['surface']\n\n// ── Content + credential REFERENCES (resolved lazily per-tenant) ────────────────\n\n/**\n * Where a capability's bytes live. A leaked manifest carries no live secret and\n * no inlined blob: `github`/`blob` are pointers resolved at provision time.\n */\nexport type ContentRef =\n | { kind: 'inline'; content: string }\n | { kind: 'github'; repository?: string; path: string; ref?: string }\n | { kind: 'blob'; uri: string; sha256: string; bytes?: number }\n\n/** A named secret a binding requires — declared, never carried. */\nexport interface CredentialRef {\n key: string\n}\n\n/**\n * How a binding authenticates at resolve time. Declared as a REQUIREMENT in the\n * manifest; the live secret is resolved per-tenant by the resolver context,\n * never inlined here.\n */\nexport type CapabilityAuth =\n | { mode: 'none' }\n | { mode: 'tangle-key' }\n | { mode: 'hub-connection'; providerId: string; scopes?: string[] }\n | { mode: 'secret-ref'; key: string }\n\n// ── AXIS 2 — BINDING (OPEN tagged union) ────────────────────────────────────────\n\n/**\n * The host a `process-on-infra` binding provisions before its inner binding.\n * Reuses `createExecutor`'s backend-as-data vocabulary — no new runtime invented.\n * `image` is the sandbox image tag; `warm`/`idleTtlMs`/`costTag` meter standing\n * cost; `ports` are the inner server's listen ports the host must expose.\n */\nexport interface HostSpec {\n backend: 'sandbox' | 'router' | 'cli'\n image?: string\n ports?: number[]\n warm?: boolean\n idleTtlMs?: number\n costTag?: string\n}\n\n/**\n * How a capability is backed. OPEN tagged union — THE extension point. All arms\n * are typed even when the resolver does not yet admit them; an un-admitted arm\n * throws {@link CapabilityNotAdmittedError} at resolve, never silently no-ops.\n */\nexport type DeliveryBinding =\n // FILE class — deliver = write bytes (the shipped path).\n | { kind: 'inline'; content: ContentRef }\n | { kind: 'file'; path: string; content: ContentRef; executable?: boolean }\n // TOOL-CODE class — deliver = code the agent calls.\n | { kind: 'http'; url: string; method?: string; auth?: CapabilityAuth }\n | { kind: 'sandbox-code'; entry: string; code: ContentRef; runtime?: string; harness?: string }\n // PROCESS class — deliver = a running server. STRICT discriminated union over\n // the SDK's flat `AgentProfileMcpServer.transport` vocabulary.\n | {\n kind: 'mcp-stdio'\n command: string\n args?: string[]\n env?: Record<string, string>\n cwd?: string\n }\n | { kind: 'mcp-remote'; url: string; transport: 'http' | 'sse'; headers?: Record<string, string> }\n // COMPOSED — a binding whose host must itself be provisioned. RECURSIVE.\n // \"a certified MCP hosted in a sandbox\" === this. Resolve depth-first: host\n // before inner.\n | { kind: 'process-on-infra'; host: HostSpec; inner: DeliveryBinding }\n // INFRA class — deliver = a provisioned store + a connection (standing cost).\n | { kind: 'rag-index'; index: ContentRef; embedModel: string; topK?: number }\n | { kind: 'memory-store'; provision: 'sqlite' | 'neo4j' | 'vector'; seed?: ContentRef }\n // EXTENSION POINTS — future arms, additive and agent-invisible.\n | { kind: 'wasm'; module: ContentRef; exports: string[] }\n | { kind: 'a2a'; endpoint: string; card: ContentRef; auth?: CapabilityAuth }\n\n/** Every binding kind — the open set the resolver dispatches over. */\nexport type DeliveryBindingKind = DeliveryBinding['kind']\n\n// ── Provenance + the manifest ───────────────────────────────────────────────────\n\n/**\n * The certify lane's held-out lift travelling WITH delivery. The shipped\n * `CertifiedArtifact` envelope minus its content (which moves into the binding\n * arm): `version`/`contentHash`/`lift` are stamped by the promote step, never\n * the author.\n *\n * `sourcePath` is the artifact's ORIGINAL path (including `null`). It is the\n * byte-stable fold sort key — the resolver folds context artifacts in\n * `composeCertifiedPrompt` order, which sorts by `path ?? ''`, so a `null` path\n * is load-bearing and MUST round-trip exactly. It is distinct from a context\n * `iface.name` (display only): collapsing the two flips the fold order for a\n * mix of null-path and non-null-path artifacts.\n */\nexport interface CertProvenance {\n contentHash: string\n version: number | null\n lift: string | null\n promotedAt: string\n sourcePath: string | null\n}\n\n/** One certified unit of agent power. */\nexport interface CertifiedCapability {\n id: string\n iface: CapabilityInterface\n binding: DeliveryBinding\n auth: CapabilityAuth\n provenance: CertProvenance\n}\n\n/**\n * The strict generalization of `CertifiedProfile`. `promptSurface` is kept\n * during the migration window (the shipped pull lane still emits it); new\n * capabilities live in `capabilities`.\n */\nexport interface CapabilityManifest {\n target: string\n generatedAt: string\n promptSurface: CertifiedPromptSurface | null\n capabilities: CertifiedCapability[]\n}\n\n// ── The resolved surface — one shape, both seams ────────────────────────────────\n\n/** One retrieval handle. The agent never learns vector vs graph vs index. */\nexport interface ResolvedRetrieval {\n name: string\n retrieve(query: string, k?: number): Promise<Array<{ text: string; score?: number }>>\n}\n\n/** One resolved hook — event + the command/matcher the seam folds into\n * `AgentProfile.hooks`. */\nexport interface ResolvedHook {\n event: string\n command: string\n matcher?: string\n}\n\n/** One resolved subagent — folded into `AgentProfile.subagents`. */\nexport interface ResolvedSubagent {\n name: string\n description?: string\n prompt?: string\n}\n\n/**\n * What `composeCertifiedProfile` produces. Every binding fans into the same\n * slots, consumed identically by the in-process seam (`RouterToolsSeam.{tools,\n * executeToolCall}` + folded prompt) and the sandbox seam (`AgentProfile`).\n * `dispose()` tears provisioned hosts down in REVERSE dependency order.\n */\nexport interface ResolvedSurface {\n /** Host-side tool defs → `RouterToolsSeam.tools` / agent-app `extraTools`. */\n tools: ToolSpec[]\n /** Host-side dispatch for a resolved tool. Throws when `name` is unknown so a\n * mis-dispatch is loud, never a silent empty string. */\n execute(name: string, args: Record<string, unknown>, task: unknown): Promise<string>\n /** Sandbox-side tool delivery → `AgentProfile.mcp` / in-proc `createMcpEnvironment`. */\n mcpConnections: Record<string, AgentProfileMcpServer>\n /** Prompt-context additions, byte-stable-ordered → folded system prompt. */\n promptAdditions: string[]\n /** Workspace files → `AgentProfile.resources.files`. */\n files: Array<{ path: string; content: string; executable?: boolean }>\n /** Uniform retrieval handles. */\n retrieval: ResolvedRetrieval[]\n /** Hooks → `AgentProfile.hooks`. */\n hooks: ResolvedHook[]\n /** Subagents → `AgentProfile.subagents`. */\n subagents: ResolvedSubagent[]\n /** The folded system prompt — base + the byte-stable prompt additions, exactly\n * as `composeCertifiedPrompt` renders the inline/context capabilities. */\n systemPrompt: string\n /** Tear down provisioned hosts (reverse dependency order). */\n dispose(): Promise<void>\n}\n\n// ── Errors ──────────────────────────────────────────────────────────────────────\n\n/**\n * A binding kind whose resolver case is typed but not yet admitted (rag-index,\n * memory-store, wasm, a2a). Thrown by the resolver — NEVER faked into a working\n * surface. The TYPE arms exist so the union is closed against the spec; the\n * resolver grows them later behind their lifecycle + admission gate.\n */\nexport class CapabilityNotAdmittedError extends Error {\n readonly kind: DeliveryBindingKind\n readonly capabilityId: string\n constructor(kind: DeliveryBindingKind, capabilityId: string, reason: string) {\n super(`capability '${capabilityId}': binding '${kind}' not admitted — ${reason}`)\n this.name = 'CapabilityNotAdmittedError'\n this.kind = kind\n this.capabilityId = capabilityId\n }\n}\n\n// ── Lowering today's wire (`CertifiedProfile`) → `CapabilityManifest` ───────────\n\nconst provenanceFromArtifact = (a: CertifiedArtifact): CertProvenance => ({\n contentHash: a.contentHash,\n version: a.version,\n lift: a.lift,\n promotedAt: a.promotedAt,\n sourcePath: a.path,\n})\n\nconst contextKindForType = (type: string): 'prompt-surface' | 'skill' | 'instructions' =>\n type === 'prompt-surface' || type === 'skill' ? type : 'instructions'\n\n/**\n * Heuristic shape-inference for a non-context artifact. The plane stores\n * `artifactType` as a free string today, so a tool/mcp-shaped artifact arrives\n * as opaque content. We infer the narrowest binding that is always-valid:\n * - a parseable OpenAI-tool JSON (`{ name, parameters, url? }`) → an `http`\n * tool when it carries a `url`, else an inline `tool` definition;\n * - a parseable MCP-server JSON (`{ command }` or `{ url, transport }`) → the\n * matching strict mcp binding;\n * - anything else → `context`/inline (the fail-safe — the bytes still reach the\n * agent as prompt context, never dropped).\n */\nfunction inferCapability(type: string, a: CertifiedArtifactWithIndex): CertifiedCapability {\n const id = `${type}:${a.path ?? a.index}`\n const provenance = provenanceFromArtifact(a)\n const parsed = tryParseJson(a.content)\n\n if (parsed && typeof parsed === 'object') {\n const obj = parsed as Record<string, unknown>\n if (typeof obj.command === 'string') {\n return {\n id,\n iface: { surface: 'mcp', serverName: String(obj.name ?? type) },\n binding: {\n kind: 'mcp-stdio',\n command: obj.command,\n ...(Array.isArray(obj.args) ? { args: obj.args.map(String) } : {}),\n ...(isStringRecord(obj.env) ? { env: obj.env } : {}),\n ...(typeof obj.cwd === 'string' ? { cwd: obj.cwd } : {}),\n },\n auth: { mode: 'none' },\n provenance,\n }\n }\n if (typeof obj.url === 'string' && (obj.transport === 'http' || obj.transport === 'sse')) {\n return {\n id,\n iface: { surface: 'mcp', serverName: String(obj.name ?? type) },\n binding: {\n kind: 'mcp-remote',\n url: obj.url,\n transport: obj.transport,\n ...(isStringRecord(obj.headers) ? { headers: obj.headers } : {}),\n },\n auth: { mode: 'none' },\n provenance,\n }\n }\n if (typeof obj.name === 'string' && isJsonSchema(obj.parameters)) {\n const iface: CapabilityInterface = {\n surface: 'tool',\n name: obj.name,\n ...(typeof obj.description === 'string' ? { description: obj.description } : {}),\n parameters: obj.parameters,\n }\n if (typeof obj.url === 'string') {\n return {\n id,\n iface,\n binding: {\n kind: 'http',\n url: obj.url,\n ...(typeof obj.method === 'string' ? { method: obj.method } : {}),\n },\n auth: { mode: 'none' },\n provenance,\n }\n }\n return {\n id,\n iface,\n binding: { kind: 'inline', content: { kind: 'inline', content: a.content } },\n auth: { mode: 'none' },\n provenance,\n }\n }\n }\n\n return {\n id,\n iface: { surface: 'context', kind: 'instructions', name: a.path ?? type },\n binding: { kind: 'inline', content: { kind: 'inline', content: a.content } },\n auth: { mode: 'none' },\n provenance,\n }\n}\n\ntype CertifiedArtifactWithIndex = CertifiedArtifact & { index: number }\n\n/**\n * Lower the EXISTING plane wire (`CertifiedProfile`) into a `CapabilityManifest`.\n * `prompt-surface`/`skill` artifacts → `context`/inline capabilities (the\n * shipped fold, generalized); any other artifact type → best-effort binding\n * inference (see {@link inferCapability}). `promptSurface` is carried through so\n * the resolver folds it first, exactly as `composeCertifiedPrompt` does today.\n * This delivers the spine against today's wire before the plane changes.\n */\nexport function manifestFromProfile(profile: CertifiedProfile): CapabilityManifest {\n const capabilities: CertifiedCapability[] = []\n for (const type of Object.keys(profile.artifacts).sort()) {\n const bucket = profile.artifacts[type] ?? []\n const sorted = [...bucket]\n .map((a, index) => ({ ...a, index }))\n .sort((x, y) => (x.path ?? '').localeCompare(y.path ?? ''))\n for (const a of sorted) {\n if (type === 'prompt-surface' || type === 'skill') {\n capabilities.push({\n id: `${type}:${a.path ?? a.index}`,\n iface: { surface: 'context', kind: contextKindForType(type), name: a.path ?? type },\n binding: { kind: 'inline', content: { kind: 'inline', content: a.content } },\n auth: { mode: 'none' },\n provenance: provenanceFromArtifact(a),\n })\n } else {\n capabilities.push(inferCapability(type, a))\n }\n }\n }\n return {\n target: profile.target,\n generatedAt: profile.generatedAt,\n promptSurface: profile.promptSurface,\n capabilities,\n }\n}\n\nfunction tryParseJson(s: string): unknown {\n try {\n return JSON.parse(s)\n } catch {\n return undefined\n }\n}\n\nfunction isStringRecord(v: unknown): v is Record<string, string> {\n return (\n typeof v === 'object' &&\n v !== null &&\n !Array.isArray(v) &&\n Object.values(v as Record<string, unknown>).every((x) => typeof x === 'string')\n )\n}\n\nfunction isJsonSchema(v: unknown): v is JsonSchema {\n return typeof v === 'object' && v !== null && !Array.isArray(v)\n}\n","/**\n * @experimental\n *\n * Tangle Intelligence — the DELIVERY half of the loop (pull-by-default).\n *\n * The sibling Observe layer (`./index`) sends traces UP to the plane. This\n * module pulls certified artifacts DOWN: it reads the tenant's promoted,\n * gate-certified profile from the deployed Intelligence plane and folds it into\n * the running agent's prompt — so an approved improvement actually reaches the\n * agent. This is \"shipping intelligence to people's agents\", pull-by-default;\n * the push/Gated-PR opt-in composes on top of this.\n *\n * Pull contract (deployed plane): GET /v1/profiles/:target/composed →\n * { target, generatedAt, promptSurface: {surface,surfaceHash,version,lift}|null,\n * artifacts: { <artifactType>: [{path,content,contentHash,version,lift,promotedAt}] } }\n * Auth: Bearer <apiKey> (the one TANGLE_API_KEY shared by router + sandbox +\n * intelligence), resolved to a tenant by platform-api's key-verify S2S contract.\n *\n * import { withCertifiedDelivery } from '@tangle-network/agent-runtime/intelligence'\n *\n * export const agent = withCertifiedDelivery(\n * async (input, applied) => myAgent(input, { systemPrompt: applied.composePrompt(BASE) }),\n * { project: 'support-agent', target: 'support-agent' },\n * )\n */\n\nimport { createIntelligenceClient, type IntelligenceConfig } from './index'\n\nconst defaultPlaneBaseUrl = 'https://intelligence.tangle.tools'\nconst defaultRefreshMs = 300_000\n\n/** A promoted, certified artifact (one entry in the composed profile). */\nexport interface CertifiedArtifact {\n path: string | null\n content: string\n contentHash: string\n version: number | null\n /** Held-out gate lift attached at certification, e.g. \"+3.1pp\" — never a\n * within-run claim. `null` when the promotion carried no lift record. */\n lift: string | null\n promotedAt: string\n}\n\n/** The active promoted prompt surface for a target. */\nexport interface CertifiedPromptSurface {\n surface: string\n surfaceHash: string\n version: number | null\n lift: string | null\n}\n\n/** The composed certified profile — exactly the shape the plane's\n * `GET /v1/profiles/:target/composed` returns. */\nexport interface CertifiedProfile {\n target: string\n generatedAt: string\n promptSurface: CertifiedPromptSurface | null\n artifacts: Record<string, CertifiedArtifact[]>\n}\n\n/** Typed outcome for the pull — inspect `succeeded` before `value`. A 404\n * (nothing promoted yet) is a normal, non-error `succeeded: false`. */\nexport type PullOutcome =\n | { succeeded: true; value: CertifiedProfile }\n | { succeeded: false; error: string; status?: number }\n\nexport interface PullCertifiedOptions {\n /** The agent target certified artifacts are promoted under. */\n target: string\n /** Bearer key. Defaults to `process.env.TANGLE_API_KEY`. */\n apiKey?: string\n /** Plane base URL. Defaults to `process.env.TANGLE_INTELLIGENCE_URL` then\n * `https://intelligence.tangle.tools`. */\n baseUrl?: string\n /** fetch impl (tests / non-global-fetch runtimes). Defaults to global fetch. */\n fetchImpl?: typeof fetch\n /** Abort the pull after this many ms so a hung plane never blocks the caller.\n * Default 10000. The timeout surfaces as a normal fail-closed `succeeded:\n * false` (the agent runs on its base surface). */\n timeoutMs?: number\n}\n\nconst defaultPullTimeoutMs = 10_000\n\nfunction resolvePlaneBaseUrl(baseUrl: string | undefined): string {\n if (baseUrl) return baseUrl.replace(/\\/+$/, '')\n if (typeof process !== 'undefined' && process.env.TANGLE_INTELLIGENCE_URL) {\n return process.env.TANGLE_INTELLIGENCE_URL.replace(/\\/+$/, '')\n }\n return defaultPlaneBaseUrl\n}\n\nfunction resolveApiKey(apiKey: string | undefined): string {\n if (apiKey) return apiKey\n if (typeof process !== 'undefined' && process.env.TANGLE_API_KEY)\n return process.env.TANGLE_API_KEY\n return ''\n}\n\n/**\n * Pull the certified composed profile for a target. Fail-closed: a network\n * error or a non-2xx returns a typed `succeeded: false` (never throws), so a\n * caller can run on its base surface when Intelligence is unreachable. A 404 is\n * the normal \"nothing promoted yet\" signal, carried as `status: 404`.\n */\nexport async function pullCertified(opts: PullCertifiedOptions): Promise<PullOutcome> {\n const doFetch = opts.fetchImpl ?? (globalThis.fetch as typeof fetch | undefined)\n if (!doFetch) return { succeeded: false, error: 'no fetch implementation available' }\n const apiKey = resolveApiKey(opts.apiKey)\n if (!apiKey) return { succeeded: false, error: 'no apiKey (set TANGLE_API_KEY or opts.apiKey)' }\n const baseUrl = resolvePlaneBaseUrl(opts.baseUrl)\n const url = `${baseUrl}/v1/profiles/${encodeURIComponent(opts.target)}/composed`\n let res: Response\n try {\n res = await doFetch(url, {\n headers: { authorization: `Bearer ${apiKey}` },\n signal: AbortSignal.timeout(opts.timeoutMs ?? defaultPullTimeoutMs),\n })\n } catch (err) {\n return {\n succeeded: false,\n error: `pull request failed: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (res.status === 404) {\n return {\n succeeded: false,\n error: 'no certified artifacts promoted for target yet',\n status: 404,\n }\n }\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n return {\n succeeded: false,\n error: `pull ${res.status}: ${body.slice(0, 200)}`,\n status: res.status,\n }\n }\n try {\n return { succeeded: true, value: (await res.json()) as CertifiedProfile }\n } catch (err) {\n return {\n succeeded: false,\n error: `pull response parse failed: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n}\n\n/** Artifact-type buckets that fold into the system prompt, in fold order. A\n * certified `context` capability whose content is free text (`instructions`)\n * is delivered here so it actually reaches the agent — never bucketed into a\n * type the fold then silently skips. The resolver reuses this exact set so its\n * `promptAdditions` slot matches the folded prompt byte-for-byte. */\nexport const promptFoldTypes = ['prompt-surface', 'skill', 'instructions'] as const\n\n/**\n * Fold the certified prompt surface (and any certified prompt-folding artifacts:\n * `prompt-surface` / `skill` / `instructions`) into a base system prompt under a\n * marked section, so the deployed agent prompt == base + the gate-certified\n * additions. Order is stable (prompt surface first, then artifact buckets in\n * `promptFoldTypes` order, then by path within a bucket) so the same profile\n * renders byte-identically each call. Returns `base` unchanged when there is no\n * usable certified content.\n */\nexport function composeCertifiedPrompt(base: string, certified: CertifiedProfile | null): string {\n if (!certified) return base\n const parts: string[] = []\n if (certified.promptSurface?.surface.trim()) parts.push(certified.promptSurface.surface.trim())\n for (const type of promptFoldTypes) {\n const bucket = certified.artifacts[type] ?? []\n for (const a of [...bucket].sort((x, y) => (x.path ?? '').localeCompare(y.path ?? ''))) {\n if (a.content.trim()) parts.push(a.content.trim())\n }\n }\n if (parts.length === 0) return base\n return `${base.trim()}\\n\\n## Certified guidance (Tangle Intelligence)\\n\\n${parts.join('\\n\\n')}`\n}\n\n/** What the delivery wrapper hands the agent each run. */\nexport interface AppliedIntelligence {\n /** The certified profile in effect (null when none promoted / pull failed —\n * fail-closed: the agent runs on its base surface). */\n certified: CertifiedProfile | null\n /** Fold the certified prompt surface into a base system prompt. */\n composePrompt(base: string): string\n}\n\n/** An agent wrapped by {@link withCertifiedDelivery}: receives the input plus\n * the certified intelligence delivered for this run. */\nexport type DeliveredAgent<I, O> = (input: I, applied: AppliedIntelligence) => Promise<O>\n\n/** Delivery config = the Observe config plus the pull target + refresh cadence. */\nexport interface DeliveryConfig extends IntelligenceConfig {\n /** Pull target. Defaults to `project`. */\n target?: string\n /** Plane base URL for the pull (NOT the OTLP `endpoint`). Defaults to\n * `TANGLE_INTELLIGENCE_URL` then `https://intelligence.tangle.tools`. */\n baseUrl?: string\n /** Min interval between certified-profile pulls. Default 5m. */\n refreshMs?: number\n /** Per-pull timeout in ms (fail-closed on a hung plane). Default 10000. */\n timeoutMs?: number\n /** fetch impl for the pull (tests). Defaults to global fetch. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Wrap an agent so it (a) Observes each run via the shipped Observe client and\n * (b) RECEIVES the tenant's certified artifacts pulled from the deployed plane.\n * The certified profile is cached and refreshed at most every `refreshMs`; a\n * failed pull is fail-closed — the agent runs on its base surface and never\n * breaks because Intelligence is unreachable. When the plane promotes a new\n * gate-certified surface, the next refresh delivers it to the running agent.\n */\nexport function withCertifiedDelivery<I, O>(\n agent: DeliveredAgent<I, O>,\n config: DeliveryConfig,\n): ((input: I) => Promise<O>) & { refresh(): Promise<void> } {\n const client = createIntelligenceClient(config)\n const target = config.target ?? config.project\n const refreshMs = config.refreshMs ?? defaultRefreshMs\n let certified: CertifiedProfile | null = null\n let lastPullAt = 0\n let inflight: Promise<void> | null = null\n\n async function refresh(): Promise<void> {\n if (Date.now() - lastPullAt < refreshMs) return\n if (inflight) return inflight\n inflight = (async () => {\n const outcome = await pullCertified({\n target,\n apiKey: config.apiKey,\n baseUrl: config.baseUrl,\n timeoutMs: config.timeoutMs,\n fetchImpl: config.fetchImpl,\n })\n lastPullAt = Date.now()\n // Only replace the cache on a real pull; a 404/error keeps the last-known\n // certified profile (or null) — fail-closed, never wipe a good surface.\n if (outcome.succeeded) certified = outcome.value\n })()\n try {\n await inflight\n } finally {\n inflight = null\n }\n }\n\n const wrapped = (async (input: I): Promise<O> => {\n await refresh()\n const applied: AppliedIntelligence = {\n certified,\n composePrompt: (base: string) => composeCertifiedPrompt(base, certified),\n }\n return client.traceRun(\n { input, labels: { 'tangle.certified_version': certified?.promptSurface?.version ?? -1 } },\n async (trace) => {\n const out = await agent(input, applied)\n trace.recordOutput(out)\n return out\n },\n )\n }) as ((input: I) => Promise<O>) & { refresh(): Promise<void> }\n wrapped.refresh = refresh\n return wrapped\n}\n","/**\n * @experimental\n *\n * The capability resolver — the ONLY place that knows binding kinds. It lowers a\n * `CapabilityManifest` into a uniform `ResolvedSurface` consumed identically by\n * the in-process seam (`RouterToolsSeam.{tools, executeToolCall}` + a folded\n * prompt) and the sandbox seam (`AgentProfile`).\n *\n * The spine (zero new infra) resolves inline/file, mcp-stdio/mcp-remote, and\n * http tools for BOTH seams, reusing shipped primitives:\n * - inline/context → `composeCertifiedPrompt` (delivery.ts) — byte-stable order;\n * - http → a `ToolSpec` + a host-side fetch `execute`;\n * - mcp-stdio/remote → an `AgentProfileMcpServer` (the strict union widens to\n * the SDK's flat shape — an always-valid lowering).\n *\n * The ladder rungs that need infra are INJECTED capabilities of the resolve\n * context (`runSandboxCode`, `provisionHost`), so the substrate-free caller wires\n * only what it can host — a binding that needs an absent provider throws loudly,\n * it is NEVER faked into a working surface. The not-yet-admitted arms (rag-index,\n * memory-store, wasm, a2a) throw {@link CapabilityNotAdmittedError}.\n *\n * Fail-closed by construction (mirroring `pullCertified`): a `null` manifest\n * returns the base surface only; a per-capability resolve failure DROPS that\n * capability (never a half-wired tool); a post-resolve drift check drops any tool\n * whose live names diverge from the certified interface.\n */\n\nimport type { AgentProfileMcpServer } from '@tangle-network/sandbox'\nimport type { ToolSpec } from '../runtime/router-client'\nimport {\n type CapabilityAuth,\n type CapabilityManifest,\n CapabilityNotAdmittedError,\n type CertifiedCapability,\n type ContentRef,\n type DeliveryBinding,\n type HostSpec,\n manifestFromProfile,\n type ResolvedHook,\n type ResolvedRetrieval,\n type ResolvedSubagent,\n type ResolvedSurface,\n} from './capability'\nimport type { CertifiedArtifact, CertifiedProfile } from './delivery'\nimport { composeCertifiedPrompt, promptFoldTypes } from './delivery'\n\n/** A live, provisioned host the resolver tore up for a `process-on-infra` arm.\n * `teardown()` runs at `dispose()` in reverse provisioning order. */\nexport interface ProvisionedHost {\n /** Lower the inner binding's mcp connection now that the host is up; the URL/\n * command points at the host. Absent when the host serves a non-mcp inner. */\n mcpConnection?: AgentProfileMcpServer\n teardown(): Promise<void>\n}\n\n/**\n * Per-call, per-tenant context the resolver reads. Everything that touches the\n * network, a secret, or an infra provisioner is INJECTED so the manifest carries\n * no live secret and the substrate-free caller wires only what it can host.\n */\nexport interface ResolveCtx {\n /** Stable tenant id — namespaces billing + teardown (`tenant#target`). */\n tenant?: string\n /** fetch impl for http tools. Defaults to global fetch; absent ⇒ http tools fail loud. */\n fetchImpl?: typeof fetch\n /**\n * Resolve a declared credential to a live secret for THIS tenant. Returns a\n * typed outcome — inspect `succeeded` before `value`. Absent ⇒ a binding that\n * declares non-`none` auth fails loud (never a request with no credential).\n */\n resolveSecret?: (\n auth: CapabilityAuth,\n tenant: string | undefined,\n ) => Promise<{ succeeded: true; value: string } | { succeeded: false; error: string }>\n /**\n * Run a `sandbox-code` body per call. Injected by the host that owns a sandbox\n * client (the spine does not import the sandbox executor). Absent ⇒\n * `sandbox-code` bindings fail loud.\n */\n runSandboxCode?: (\n code: ContentRef,\n entry: string,\n args: Record<string, unknown>,\n task: unknown,\n ) => Promise<string>\n /**\n * Provision a host for a `process-on-infra` binding, then serve the inner\n * binding inside it. Injected by the host that owns `createExecutor`. Absent ⇒\n * `process-on-infra` bindings fail loud. The provider resolves the inner\n * binding INSIDE the host and returns the connection + a teardown.\n */\n provisionHost?: (\n host: HostSpec,\n inner: DeliveryBinding,\n costTag: string,\n ) => Promise<ProvisionedHost>\n /**\n * Drift probe: return the LIVE tool names a resolved surface exposes for a\n * given capability id (a `tools/list` over an mcp connection, the agent's\n * actual registered tool names for a host tool). When present, the post-resolve\n * drift check drops any tool/mcp whose live names diverge from the certified\n * interface — the only callable surfaces are gate-blessed ones. Absent ⇒ the\n * check enforces only the host-side executor↔spec parity (no live probe).\n */\n probeLiveToolNames?: (capabilityId: string) => Promise<string[]>\n /**\n * Observe a DROPPED capability — a per-capability resolve failure that is\n * fail-closed (the capability is omitted, never half-wired). The drop is the\n * contract; this surfaces the diagnostic so it is never silently erased. NOT\n * called for {@link CapabilityNotAdmittedError} (that rethrows — a manifest\n * carrying an un-admitted binding kind is a hard error, not a soft drop).\n */\n onDrop?: (capabilityId: string, error: Error) => void\n}\n\n/** Internal accumulator the resolver fills, then folds into a `ResolvedSurface`. */\ninterface SurfaceAccumulator {\n tools: ToolSpec[]\n executors: Map<string, (args: Record<string, unknown>, task: unknown) => Promise<string>>\n mcpConnections: Record<string, AgentProfileMcpServer>\n contextArtifacts: Record<string, CertifiedArtifact[]>\n files: Array<{ path: string; content: string; executable?: boolean }>\n retrieval: ResolvedRetrieval[]\n hooks: ResolvedHook[]\n subagents: ResolvedSubagent[]\n teardowns: Array<() => Promise<void>>\n /** Tool name → the capability id that certified it (drift probe key). */\n toolCapabilityId: Map<string, string>\n /** Mcp server name → the capability id + its certified tool names (drift). */\n mcpCapability: Map<string, { capabilityId: string; certifiedNames: string[] }>\n}\n\nfunction emptyAccumulator(): SurfaceAccumulator {\n return {\n tools: [],\n executors: new Map(),\n mcpConnections: {},\n contextArtifacts: {},\n files: [],\n retrieval: [],\n hooks: [],\n subagents: [],\n teardowns: [],\n toolCapabilityId: new Map(),\n mcpCapability: new Map(),\n }\n}\n\n/**\n * Compose a certified profile into a uniform `ResolvedSurface`. Additive over\n * `composeCertifiedPrompt`: the inline/context fold is delegated to\n * `composeCertifiedPrompt` so the byte-stable ordering (prompt surface first,\n * then type alphabetic, then path locale-compare) is reused EXACTLY — the\n * prompt-only path is a strict subset of this.\n *\n * Fail-closed: a `null` manifest returns the base surface only.\n */\nexport async function composeCertifiedProfile(\n base: { systemPrompt: string },\n manifest: CapabilityManifest | null,\n ctx: ResolveCtx = {},\n): Promise<ResolvedSurface> {\n if (!manifest || manifest.capabilities.length === 0) {\n return baseSurface(base.systemPrompt, manifest?.promptSurface ?? null)\n }\n\n const acc = emptyAccumulator()\n for (const cap of manifest.capabilities) {\n try {\n await resolveCapability(cap, ctx, acc)\n } catch (err) {\n // An un-admitted binding kind is a hard error (the manifest is malformed\n // for this resolver); any other per-capability failure is a fail-closed\n // drop — the diagnostic is surfaced via `onDrop`, never erased.\n if (err instanceof CapabilityNotAdmittedError) throw err\n ctx.onDrop?.(cap.id, err instanceof Error ? err : new Error(String(err)))\n }\n }\n\n await driftDropTools(acc, ctx)\n\n const promptAdditions = collectPromptAdditions(manifest.promptSurface, acc.contextArtifacts)\n const systemPrompt = composeCertifiedPrompt(base.systemPrompt, {\n target: manifest.target,\n generatedAt: manifest.generatedAt,\n promptSurface: manifest.promptSurface,\n artifacts: acc.contextArtifacts,\n })\n\n const teardowns = acc.teardowns\n return {\n tools: acc.tools,\n async execute(name, args, task): Promise<string> {\n const fn = acc.executors.get(name)\n if (!fn) throw new Error(`composeCertifiedProfile.execute: unknown tool '${name}'`)\n return fn(args, task)\n },\n mcpConnections: acc.mcpConnections,\n promptAdditions,\n files: acc.files,\n retrieval: acc.retrieval,\n hooks: acc.hooks,\n subagents: acc.subagents,\n systemPrompt,\n async dispose(): Promise<void> {\n // Reverse dependency order: a host provisioned before its inner is torn\n // down after the inner's teardown ran.\n for (let i = teardowns.length - 1; i >= 0; i -= 1) {\n const teardown = teardowns[i]\n if (teardown) await teardown()\n }\n },\n }\n}\n\nfunction baseSurface(\n systemPrompt: string,\n promptSurface: CapabilityManifest['promptSurface'],\n): ResolvedSurface {\n const folded = composeCertifiedPrompt(systemPrompt, {\n target: '',\n generatedAt: '',\n promptSurface,\n artifacts: {},\n })\n return {\n tools: [],\n async execute(name): Promise<string> {\n throw new Error(`composeCertifiedProfile.execute: unknown tool '${name}'`)\n },\n mcpConnections: {},\n promptAdditions: collectPromptAdditions(promptSurface, {}),\n files: [],\n retrieval: [],\n hooks: [],\n subagents: [],\n systemPrompt: folded,\n async dispose(): Promise<void> {},\n }\n}\n\n/** The byte-stable prompt additions a viewer/debugger can inspect — the same\n * parts `composeCertifiedPrompt` joins into the folded prompt, in the same fold\n * order (`promptFoldTypes`). */\nfunction collectPromptAdditions(\n promptSurface: CapabilityManifest['promptSurface'],\n contextArtifacts: Record<string, CertifiedArtifact[]>,\n): string[] {\n const parts: string[] = []\n if (promptSurface?.surface.trim()) parts.push(promptSurface.surface.trim())\n for (const type of promptFoldTypes) {\n const bucket = contextArtifacts[type] ?? []\n for (const a of [...bucket].sort((x, y) => (x.path ?? '').localeCompare(y.path ?? ''))) {\n if (a.content.trim()) parts.push(a.content.trim())\n }\n }\n return parts\n}\n\nasync function resolveCapability(\n cap: CertifiedCapability,\n ctx: ResolveCtx,\n acc: SurfaceAccumulator,\n): Promise<void> {\n await resolveBinding(cap, cap.binding, ctx, acc)\n}\n\nasync function resolveBinding(\n cap: CertifiedCapability,\n binding: DeliveryBinding,\n ctx: ResolveCtx,\n acc: SurfaceAccumulator,\n): Promise<void> {\n switch (binding.kind) {\n case 'inline':\n resolveInline(cap, binding, acc)\n return\n case 'file':\n resolveFile(cap, binding, acc)\n return\n case 'http':\n resolveHttp(cap, binding, ctx, acc)\n return\n case 'mcp-stdio':\n case 'mcp-remote':\n resolveMcp(cap, binding, acc)\n return\n case 'sandbox-code':\n resolveSandboxCode(cap, binding, ctx, acc)\n return\n case 'process-on-infra':\n await resolveProcessOnInfra(cap, binding, ctx, acc, new Set())\n return\n case 'rag-index':\n throw new CapabilityNotAdmittedError(\n binding.kind,\n cap.id,\n 'rag retrieval lift must clear the E3 score-superiority admission bar before a store is trusted (memory/e3-certified-memory-verdict)',\n )\n case 'memory-store':\n throw new CapabilityNotAdmittedError(\n binding.kind,\n cap.id,\n 'memory-store admission is gated on the E3 score-superiority bar (memory/e3-certified-memory-verdict)',\n )\n case 'wasm':\n throw new CapabilityNotAdmittedError(\n binding.kind,\n cap.id,\n 'wasm is an extension-point arm, not yet admitted',\n )\n case 'a2a':\n throw new CapabilityNotAdmittedError(\n binding.kind,\n cap.id,\n 'a2a is an extension-point arm, not yet admitted',\n )\n }\n}\n\n/** inline → a context artifact (prompt-surface/skill folded) or an inline tool\n * def. Context capabilities feed the byte-stable prompt fold; an inline `tool`\n * interface registers a host-side tool whose body is the inlined JSON spec. */\nfunction resolveInline(\n cap: CertifiedCapability,\n binding: Extract<DeliveryBinding, { kind: 'inline' }>,\n acc: SurfaceAccumulator,\n): void {\n const content = inlineContent(cap, binding.content)\n if (cap.iface.surface === 'context') {\n pushContextArtifact(acc, cap, content)\n return\n }\n if (cap.iface.surface === 'tool') {\n registerInlineTool(cap, content, acc)\n return\n }\n // Any other surface delivered inline folds as prompt context (the fail-safe —\n // the bytes still reach the agent, never silently dropped).\n pushContextArtifact(acc, cap, content)\n}\n\n/** An inline `tool` interface registers a host-side `ToolSpec` whose body is the\n * static inlined content (a fixed response / canned handler). Its `execute`\n * returns the content verbatim — the agent calls it like any other tool. */\nfunction registerInlineTool(\n cap: CertifiedCapability,\n content: string,\n acc: SurfaceAccumulator,\n): void {\n if (cap.iface.surface !== 'tool') return\n const iface = cap.iface\n acc.tools.push({\n type: 'function',\n function: {\n name: iface.name,\n ...(iface.description ? { description: iface.description } : {}),\n parameters: iface.parameters,\n },\n })\n acc.toolCapabilityId.set(iface.name, cap.id)\n acc.executors.set(iface.name, async () => content)\n}\n\n/** file → a workspace file mount (+ a prompt fold when the file is context). */\nfunction resolveFile(\n cap: CertifiedCapability,\n binding: Extract<DeliveryBinding, { kind: 'file' }>,\n acc: SurfaceAccumulator,\n): void {\n const content = inlineContent(cap, binding.content)\n acc.files.push({\n path: binding.path,\n content,\n ...(binding.executable ? { executable: true } : {}),\n })\n if (cap.iface.surface === 'context') pushContextArtifact(acc, cap, content)\n}\n\n/** mcp-stdio/mcp-remote → an `AgentProfileMcpServer`. The strict discriminated\n * union widens to the SDK's flat shape — an always-valid lowering, no translation. */\nfunction resolveMcp(\n cap: CertifiedCapability,\n binding: Extract<DeliveryBinding, { kind: 'mcp-stdio' | 'mcp-remote' }>,\n acc: SurfaceAccumulator,\n): void {\n const serverName = cap.iface.surface === 'mcp' ? cap.iface.serverName : cap.id\n acc.mcpConnections[serverName] = mcpServerFromBinding(binding, cap)\n acc.mcpCapability.set(serverName, {\n capabilityId: cap.id,\n certifiedNames: cap.iface.surface === 'mcp' ? (cap.iface.toolset ?? []) : [],\n })\n}\n\nfunction mcpServerFromBinding(\n binding: Extract<DeliveryBinding, { kind: 'mcp-stdio' | 'mcp-remote' }>,\n cap: CertifiedCapability,\n): AgentProfileMcpServer {\n const metadata: Record<string, unknown> = { capabilityId: cap.id }\n if (cap.iface.surface === 'mcp' && cap.iface.toolset) metadata.tools = cap.iface.toolset\n if (binding.kind === 'mcp-stdio') {\n return {\n transport: 'stdio',\n command: binding.command,\n ...(binding.args ? { args: binding.args } : {}),\n ...(binding.env ? { env: binding.env } : {}),\n ...(binding.cwd ? { cwd: binding.cwd } : {}),\n enabled: true,\n metadata,\n }\n }\n return {\n transport: binding.transport,\n url: binding.url,\n ...(binding.headers ? { headers: binding.headers } : {}),\n enabled: true,\n metadata,\n }\n}\n\n/** http → a `ToolSpec` + a host-side fetch `execute`. THE host seam: an http\n * tool is callable in-process, never injected into a sandbox profile. */\nfunction resolveHttp(\n cap: CertifiedCapability,\n binding: Extract<DeliveryBinding, { kind: 'http' }>,\n ctx: ResolveCtx,\n acc: SurfaceAccumulator,\n): void {\n if (cap.iface.surface !== 'tool') {\n throw new Error(`capability '${cap.id}': http binding requires a 'tool' interface`)\n }\n const iface = cap.iface\n acc.tools.push({\n type: 'function',\n function: {\n name: iface.name,\n ...(iface.description ? { description: iface.description } : {}),\n parameters: iface.parameters,\n },\n })\n acc.toolCapabilityId.set(iface.name, cap.id)\n const method = binding.method ?? 'POST'\n const auth = binding.auth ?? cap.auth\n acc.executors.set(iface.name, async (args) => {\n const doFetch = ctx.fetchImpl ?? (globalThis.fetch as typeof fetch | undefined)\n if (!doFetch) throw new Error(`capability '${cap.id}': no fetch implementation for http tool`)\n const headers: Record<string, string> = { 'content-type': 'application/json' }\n if (auth.mode !== 'none') {\n if (!ctx.resolveSecret) {\n throw new Error(\n `capability '${cap.id}': http auth '${auth.mode}' requires ResolveCtx.resolveSecret`,\n )\n }\n const secret = await ctx.resolveSecret(auth, ctx.tenant)\n if (!secret.succeeded) {\n throw new Error(`capability '${cap.id}': secret resolution failed — ${secret.error}`)\n }\n headers.authorization = `Bearer ${secret.value}`\n }\n const res = await doFetch(binding.url, {\n method,\n headers,\n ...(method === 'GET' ? {} : { body: JSON.stringify(args) }),\n })\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n throw new Error(`capability '${cap.id}': http ${res.status}: ${body.slice(0, 200)}`)\n }\n return res.text()\n })\n}\n\n/** sandbox-code → a host-side tool whose body runs per-call in a box, via the\n * injected `runSandboxCode` (the host owns the sandbox client). */\nfunction resolveSandboxCode(\n cap: CertifiedCapability,\n binding: Extract<DeliveryBinding, { kind: 'sandbox-code' }>,\n ctx: ResolveCtx,\n acc: SurfaceAccumulator,\n): void {\n if (cap.iface.surface !== 'tool') {\n throw new Error(`capability '${cap.id}': sandbox-code binding requires a 'tool' interface`)\n }\n const iface = cap.iface\n acc.tools.push({\n type: 'function',\n function: {\n name: iface.name,\n ...(iface.description ? { description: iface.description } : {}),\n parameters: iface.parameters,\n },\n })\n acc.toolCapabilityId.set(iface.name, cap.id)\n acc.executors.set(iface.name, async (args, task) => {\n if (!ctx.runSandboxCode) {\n throw new Error(\n `capability '${cap.id}': sandbox-code binding requires ResolveCtx.runSandboxCode`,\n )\n }\n return ctx.runSandboxCode(binding.code, binding.entry, args, task)\n })\n}\n\n/**\n * process-on-infra → provision the host FIRST (depth-first), then resolve the\n * inner binding inside it. The injected `provisionHost` owns `createExecutor`;\n * this resolver wires the returned connection + teardown (reverse dep order) and\n * the cost tag. A `visited` set guards against a self-referential host cycle.\n */\nasync function resolveProcessOnInfra(\n cap: CertifiedCapability,\n binding: Extract<DeliveryBinding, { kind: 'process-on-infra' }>,\n ctx: ResolveCtx,\n acc: SurfaceAccumulator,\n visited: Set<DeliveryBinding>,\n): Promise<void> {\n if (visited.has(binding)) {\n throw new Error(`capability '${cap.id}': process-on-infra cycle detected`)\n }\n visited.add(binding)\n if (!ctx.provisionHost) {\n throw new Error(\n `capability '${cap.id}': process-on-infra binding requires ResolveCtx.provisionHost`,\n )\n }\n if (binding.inner.kind === 'process-on-infra') {\n // Nested provisioning: provision the OUTER host, then recurse the inner\n // process-on-infra inside the same provisioner contract (host before inner).\n const outer = await ctx.provisionHost(\n binding.host,\n binding.inner,\n hostCostTag(cap, binding.host),\n )\n acc.teardowns.push(() => outer.teardown())\n await resolveProcessOnInfra(cap, binding.inner, ctx, acc, visited)\n return\n }\n const provisioned = await ctx.provisionHost(\n binding.host,\n binding.inner,\n hostCostTag(cap, binding.host),\n )\n acc.teardowns.push(() => provisioned.teardown())\n if (provisioned.mcpConnection) {\n const serverName = cap.iface.surface === 'mcp' ? cap.iface.serverName : cap.id\n acc.mcpConnections[serverName] = provisioned.mcpConnection\n acc.mcpCapability.set(serverName, {\n capabilityId: cap.id,\n certifiedNames: cap.iface.surface === 'mcp' ? (cap.iface.toolset ?? []) : [],\n })\n }\n}\n\nfunction hostCostTag(cap: CertifiedCapability, host: HostSpec): string {\n return host.costTag ?? `capability/${cap.id}`\n}\n\n/**\n * Post-resolve drift check (fail-closed): a resolved surface's LIVE tool names\n * must equal the certified interface — mismatch → drop. The only callable tools\n * are gate-blessed ones. Two enforcement layers:\n * 1. host-side parity — every registered tool keeps a matching executor and\n * vice-versa (a half-wired tool, e.g. one whose provision failed, is\n * removed rather than exposed);\n * 2. live-name equality (when `ctx.probeLiveToolNames` is wired) — for each\n * host tool the live name must contain the certified name; for each mcp\n * server the live `tools/list` must equal the certified `toolset`.\n * A drop removes BOTH the tool spec and its executor (host) or the connection\n * (mcp); a capability that lost its drift check never reaches the agent.\n */\nasync function driftDropTools(acc: SurfaceAccumulator, ctx: ResolveCtx): Promise<void> {\n // Layer 1 — host-side executor↔spec parity.\n const specNames = new Set(acc.tools.map((t) => t.function.name))\n for (const name of acc.executors.keys()) {\n if (!specNames.has(name)) acc.executors.delete(name)\n }\n acc.tools = acc.tools.filter((t) => acc.executors.has(t.function.name))\n\n if (!ctx.probeLiveToolNames) return\n\n // Layer 2 — live-name equality per capability.\n const droppedTools = new Set<string>()\n for (const tool of acc.tools) {\n const capId = acc.toolCapabilityId.get(tool.function.name)\n if (!capId) continue\n const live = await ctx.probeLiveToolNames(capId)\n if (!live.includes(tool.function.name)) droppedTools.add(tool.function.name)\n }\n for (const name of droppedTools) {\n acc.executors.delete(name)\n }\n acc.tools = acc.tools.filter((t) => !droppedTools.has(t.function.name))\n\n for (const [serverName, info] of acc.mcpCapability) {\n if (info.certifiedNames.length === 0) continue\n const live = await ctx.probeLiveToolNames(info.capabilityId)\n if (!setsEqual(new Set(live), new Set(info.certifiedNames))) {\n delete acc.mcpConnections[serverName]\n acc.mcpCapability.delete(serverName)\n }\n }\n}\n\nfunction setsEqual(a: Set<string>, b: Set<string>): boolean {\n if (a.size !== b.size) return false\n for (const x of a) if (!b.has(x)) return false\n return true\n}\n\nfunction inlineContent(cap: CertifiedCapability, ref: ContentRef): string {\n if (ref.kind === 'inline') return ref.content\n // github/blob refs are pointers the spine does not fetch — a binding that\n // declares one without an inline body cannot be folded into a prompt or file\n // here. Fail loud so the caller wires a fetcher rather than shipping an empty\n // capability.\n throw new Error(\n `capability '${cap.id}': content ref '${ref.kind}' is not inline — wire a content fetcher to resolve it`,\n )\n}\n\nfunction pushContextArtifact(\n acc: SurfaceAccumulator,\n cap: CertifiedCapability,\n content: string,\n): void {\n const type = contextArtifactType(cap)\n const bucket = acc.contextArtifacts[type] ?? []\n acc.contextArtifacts[type] = bucket\n bucket.push({\n path: contextArtifactPath(cap),\n content,\n contentHash: cap.provenance.contentHash,\n version: cap.provenance.version,\n lift: cap.provenance.lift,\n promotedAt: cap.provenance.promotedAt,\n })\n}\n\n/** Map a context capability onto the artifact-type bucket `composeCertifiedPrompt`\n * folds. The `prompt-surface`/`skill`/`instructions` buckets all fold into the\n * prompt (see `promptFoldTypes`), so context bytes always reach the agent; a\n * non-context surface lowered here as the fail-safe folds as `instructions`. */\nfunction contextArtifactType(cap: CertifiedCapability): string {\n if (cap.iface.surface === 'context') {\n return cap.iface.kind === 'instructions' ? 'instructions' : cap.iface.kind\n }\n return 'instructions'\n}\n\n/** The artifact's byte-stable fold sort key — the ORIGINAL source path,\n * including `null`, round-tripped through provenance. The resolver folds in\n * `composeCertifiedPrompt` order (sort by `path ?? ''`), so `null` is\n * load-bearing and must survive the manifest→resolve→fold trip unchanged. This\n * is deliberately NOT `iface.name` (display only) — conflating the two flips\n * the fold order against the gate-certified reference. */\nfunction contextArtifactPath(cap: CertifiedCapability): string | null {\n return cap.provenance.sourcePath\n}\n\n/** Lower a plane `CertifiedProfile` straight into a `ResolvedSurface` via\n * `manifestFromProfile` — the convenience the shipped pull lane calls when it\n * already holds a `CertifiedProfile` (today's wire) rather than a manifest. */\nexport async function composeCertifiedProfileFromWire(\n base: { systemPrompt: string },\n profile: CertifiedProfile | null,\n ctx: ResolveCtx = {},\n): Promise<ResolvedSurface> {\n if (!profile) return composeCertifiedProfile(base, null, ctx)\n return composeCertifiedProfile(base, manifestFromProfile(profile), ctx)\n}\n","/**\n * @experimental\n *\n * Tangle Intelligence SDK — the Observe + Mode-0 product layer.\n *\n * A thin, best-effort wrapper over the shipped trace-export substrate\n * (`createOtelExporter` in `../otel-export`). It does exactly two things in\n * this slice:\n *\n * 1. OBSERVE — wrap a generic agent and export one trace span per call to\n * Tangle Intelligence, swallowing every export failure so a live agent\n * never fails because Intelligence is down.\n * 2. MODE 0 / OFF — at `effort: 'off'`, run the agent as PURE PASSTHROUGH\n * (zero intelligence spawns) with best-effort telemetry still on. The\n * exported trace tags usage by class `{ inferenceUsd, intelligenceUsd }`,\n * and at OFF `intelligenceUsd` is provably `0` — the mechanism that proves\n * an OFF customer paid inference-only.\n *\n * Behavior-changing intelligence (analyst steer, candidate promotion, loops)\n * is a LATER phase and is NOT built here. This wrapper only Observes and passes\n * through; there is no abort path, so the only fail-soft surface is the\n * telemetry export.\n */\n\nimport {\n buildLoopOtelSpans,\n createOtelExporter,\n loopEventToOtelSpan,\n type OtelExporter,\n} from '../otel-export'\nimport type { LoopTraceEvent } from '../runtime/types'\nimport {\n defaultEffortTier,\n type EffortOverrides,\n type EffortSettings,\n type EffortTier,\n isIntelligenceOff,\n resolveEffort,\n} from './effort'\nimport { type Redactor, resolveRedactor } from './redact'\n\nexport type {\n CapabilityAuth,\n CapabilityInterface,\n CapabilityManifest,\n CapabilitySurface,\n CertifiedCapability,\n CertProvenance,\n ContentRef,\n CredentialRef,\n DeliveryBinding,\n DeliveryBindingKind,\n HostSpec,\n JsonSchema,\n ResolvedHook,\n ResolvedRetrieval,\n ResolvedSubagent,\n ResolvedSurface,\n} from './capability'\nexport { CapabilityNotAdmittedError, manifestFromProfile } from './capability'\nexport type {\n AppliedIntelligence,\n CertifiedArtifact,\n CertifiedProfile,\n CertifiedPromptSurface,\n DeliveredAgent,\n DeliveryConfig,\n PullCertifiedOptions,\n PullOutcome,\n} from './delivery'\nexport { composeCertifiedPrompt, pullCertified, withCertifiedDelivery } from './delivery'\nexport type {\n CorpusAccess,\n EffortOverrides,\n EffortOverridesCompiled,\n EffortSettings,\n EffortTier,\n} from './effort'\nexport {\n compileEffort,\n defaultEffortTier,\n isIntelligenceOff,\n resolveEffort,\n} from './effort'\nexport type { Redactor } from './redact'\nexport { defaultRedactor, resolveRedactor } from './redact'\nexport type { ProvisionedHost, ResolveCtx } from './resolver'\nexport {\n composeCertifiedProfile,\n composeCertifiedProfileFromWire,\n} from './resolver'\n\n/** Usage class for billing. Base-stream tokens bill `'inference'`; every\n * intelligence spawn (analyst, corpus, loop) bills `'intelligence'`. The\n * billing line falls on the spawn line. */\nexport type UsageClass = 'inference' | 'intelligence'\n\n/**\n * The per-class cost split carried by every trace and outcome. `off` ⇒\n * `intelligenceUsd: 0` by construction — there is no intelligence spawn to\n * bill. This is a classification on the trace, NOT a budget-pool split.\n */\nexport interface UsageSplit {\n /** Base-stream (model) spend in USD. */\n inferenceUsd: number\n /** Intelligence-spawn spend in USD. Provably `0` at the OFF tier. */\n intelligenceUsd: number\n}\n\n/** Repo coordinates a product may declare for the (later) Gated-PR mode. The\n * Observe slice only records their PRESENCE for `doctor()`; it never touches\n * the repo. */\nexport interface RepoConfig {\n owner: string\n name: string\n baseBranch: string\n}\n\n/** Client configuration. `project` + `apiKey` are the Observe minimum; the\n * rest tune effort, endpoint, redaction, and (for `doctor()` readiness)\n * declare the surfaces/checks/repo a later PR mode would need. */\nexport interface IntelligenceConfig {\n /** Stable project id — the tenant dimension every trace is tagged with. */\n project: string\n /** Bearer key for the Intelligence ingest. Reads `TANGLE_API_KEY` when omitted. */\n apiKey?: string\n /** Effort tier (default `'standard'`) plus optional per-field overrides. */\n effort?: EffortTier | { tier: EffortTier; overrides?: EffortOverrides }\n /**\n * OTLP ingest base. The underlying exporter appends `/v1/traces`, so point\n * this at the OTLP route (e.g. `https://intelligence.tangle.tools/v1/otlp`).\n * Reads `INTELLIGENCE_OTLP_ENDPOINT` then `OTEL_EXPORTER_OTLP_ENDPOINT` when\n * omitted; absent all three, export is a no-op (best-effort by construction).\n */\n endpoint?: string\n /**\n * Redaction hook run over every exported input/output. A function replaces\n * the default scrubber; `false` opts out entirely (raw fidelity, caller has\n * sanitized upstream); omitted ⇒ the built-in `defaultRedactor`.\n */\n redact?: Redactor | false\n /** Mutable surfaces a later PR mode would edit. Recorded for `doctor()` only. */\n surfaces?: string[]\n /** Verification checks a later PR mode would gate on. Recorded for `doctor()` only. */\n checks?: string[]\n /** Repo access a later PR mode would need. Recorded for `doctor()` only. */\n repo?: RepoConfig\n}\n\n/** Metadata describing one traced run. `runId`/`traceId` default to fresh ids. */\nexport interface TraceMeta {\n /** The run's input — exported through the redactor. */\n input?: unknown\n /** Stable run id. Defaults to a fresh id. */\n runId?: string\n /** 32-hex trace id. Defaults to a fresh id. */\n traceId?: string\n /** Model id, when known — stamped on the span. */\n model?: string\n /** Provider name, when known — stamped on the span. */\n provider?: string\n /** Arbitrary extra labels (string/number/boolean) stamped on the span. */\n labels?: Record<string, string | number | boolean>\n}\n\n/**\n * The trace handle a `traceRun` body records into. `recordOutput` captures the\n * agent's result (redacted on export); `recordOutcome` captures the scored\n * outcome + the `{ inferenceUsd, intelligenceUsd }` split. Both are optional —\n * an un-recorded run still exports a span with whatever was set.\n */\nexport interface TraceHandle {\n /** Capture the run's output. Exported through the redactor. */\n recordOutput(output: unknown): void\n /**\n * Capture the run's outcome. `usage` defaults to inference-only\n * (`intelligenceUsd: 0`) — the OFF baseline; an intelligence-enabled run\n * fills `intelligenceUsd` itself. `costUsd`, when given without a split, is\n * treated as pure inference.\n */\n recordOutcome(outcome: {\n success?: boolean\n score?: number\n costUsd?: number\n usage?: Partial<UsageSplit>\n }): void\n}\n\n/** Metadata for {@link IntelligenceClient.recordTrace}. */\nexport interface RecordTraceMeta {\n /** 32-hex trace id to anchor every span to. Defaults to a fresh id. */\n traceId?: string\n /** Span id of an enclosing span the loop root should parent under (e.g. a\n * `traceRun` span). Omitted ⇒ the loop root is the trace root. */\n rootParentSpanId?: string\n}\n\n/** The resolved outcome of one traced run, surfaced on the export span and\n * available to the caller for downstream billing assertions. */\nexport interface TraceOutcome {\n runId: string\n traceId: string\n project: string\n /** The resolved effort settings this run executed under. */\n effort: EffortSettings\n /** True when this run ran as pure passthrough (the OFF floor). */\n intelligenceOff: boolean\n success?: boolean\n score?: number\n /** Per-class billing split. `intelligenceUsd` is `0` at the OFF tier. */\n usage: UsageSplit\n}\n\n/** The Observe-mode Intelligence client. */\nexport interface IntelligenceClient {\n /** The resolved project id. */\n readonly project: string\n /** The resolved effort settings. */\n readonly effort: EffortSettings\n /**\n * Run `fn` under a trace, export one span best-effort, and return whatever\n * `fn` returns. Telemetry-export failures are swallowed; an error THROWN by\n * `fn` propagates to the caller (the agent's own failures are not masked).\n */\n traceRun<T>(meta: TraceMeta, fn: (trace: TraceHandle) => Promise<T>): Promise<T>\n /**\n * Export a run's full loop topology — the ordered `LoopTraceEvent` stream a\n * `runLoop`/`Supervisor` run emits — as a nested OTLP span tree (loop → round →\n * iteration) into ONE trace. Reuses the shipped `buildLoopOtelSpans` builder\n * (NO second span builder), so the topology a viewer renders matches the\n * kernel's. `traceId` defaults to a fresh id; `rootParentSpanId` parents the\n * loop root under an enclosing span (e.g. a `traceRun` span) when given.\n * Best-effort: export failures are swallowed. Returns the resolved `traceId`.\n */\n recordTrace(events: ReadonlyArray<LoopTraceEvent>, meta?: RecordTraceMeta): string\n /**\n * Network-free readiness report: which adoption modes are reachable given\n * this config. Observe is always reachable; Recommend needs outcomes; PR\n * needs checks + surfaces + repo.\n */\n doctor(): DoctorReport\n /** Flush any pending export spans. Best-effort; resolves even if export fails. */\n flush(): Promise<void>\n}\n\n/** One mode's readiness verdict. */\nexport interface ModeReadiness {\n ready: boolean\n /** Inputs this mode still needs, when not ready. Empty when ready. */\n missing: string[]\n}\n\n/** The `doctor()` readiness report — Mode-readiness without any network call. */\nexport interface DoctorReport {\n project: string\n effort: EffortSettings\n /** True when an OTLP endpoint is configured (export will actually ship). */\n exportConfigured: boolean\n modes: {\n observe: ModeReadiness\n recommend: ModeReadiness\n pr: ModeReadiness\n }\n}\n\nfunction resolveEffortConfig(effort: IntelligenceConfig['effort']): EffortSettings {\n if (effort === undefined) return resolveEffort(defaultEffortTier)\n if (typeof effort === 'string') return resolveEffort(effort)\n return resolveEffort(effort.tier, effort.overrides)\n}\n\nfunction resolveEndpoint(endpoint: string | undefined): string | undefined {\n if (endpoint) return endpoint\n if (typeof process === 'undefined') return undefined\n return process.env.INTELLIGENCE_OTLP_ENDPOINT ?? process.env.OTEL_EXPORTER_OTLP_ENDPOINT\n}\n\nfunction freshTraceId(): string {\n return randomHex(32)\n}\n\nfunction freshRunId(): string {\n return `run-${randomHex(16)}`\n}\n\n/** Serialize a redacted value to a bounded string for a span attribute.\n * `loopEventToOtelSpan` only stamps string/number/boolean payload fields, so a\n * structured input/output must be flattened here. Bounded to keep span\n * attributes small; the full payload is the consumer's own store, not the span. */\nconst previewMaxChars = 4096\nfunction previewJson(value: unknown): string {\n let s: string\n if (typeof value === 'string') s = value\n else {\n try {\n s = JSON.stringify(value) ?? String(value)\n } catch {\n s = String(value)\n }\n }\n return s.length > previewMaxChars ? `${s.slice(0, previewMaxChars)}…[truncated]` : s\n}\n\nfunction randomHex(chars: number): string {\n const bytes = new Uint8Array(Math.ceil(chars / 2))\n if (typeof globalThis.crypto?.getRandomValues === 'function') {\n globalThis.crypto.getRandomValues(bytes)\n } else {\n for (let i = 0; i < bytes.length; 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 .slice(0, chars)\n}\n\n/**\n * Create an Observe-mode Intelligence client. Resolves effort, endpoint, and\n * redactor up front; the exporter is built lazily and is `undefined` when no\n * endpoint is configured (export becomes a no-op — best-effort by\n * construction).\n */\nexport function createIntelligenceClient(config: IntelligenceConfig): IntelligenceClient {\n if (!config.project) {\n throw new Error('createIntelligenceClient: `project` is required')\n }\n const effort = resolveEffortConfig(config.effort)\n const intelligenceOff = isIntelligenceOff(effort)\n const redactor = resolveRedactor(config.redact)\n const apiKey =\n config.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n const endpoint = resolveEndpoint(config.endpoint)\n\n // Built lazily: a client with no endpoint never allocates an exporter timer.\n let exporter: OtelExporter | undefined\n let exporterResolved = false\n function getExporter(): OtelExporter | undefined {\n if (exporterResolved) return exporter\n exporterResolved = true\n if (!endpoint) return undefined\n exporter = createOtelExporter({\n endpoint,\n headers: apiKey ? { authorization: `Bearer ${apiKey}` } : {},\n serviceName: config.project,\n resourceAttributes: { 'tangle.project': config.project },\n })\n return exporter\n }\n\n function exportTrace(meta: TraceMeta, outcome: TraceOutcome, output: unknown): void {\n const ex = getExporter()\n if (!ex) return\n const labels: Record<string, string | number | boolean> = {\n project: config.project,\n 'tangle.effort.intelligence_off': outcome.intelligenceOff,\n 'tangle.usage.inference_usd': outcome.usage.inferenceUsd,\n 'tangle.usage.intelligence_usd': outcome.usage.intelligenceUsd,\n ...(meta.model ? { 'gen_ai.request.model': meta.model } : {}),\n ...(meta.provider ? { 'provider.name': meta.provider } : {}),\n ...(typeof outcome.success === 'boolean'\n ? { 'tangle.outcome.success': outcome.success }\n : {}),\n ...(typeof outcome.score === 'number' ? { 'tangle.outcome.score': outcome.score } : {}),\n ...(meta.labels ?? {}),\n }\n const redactedInput = meta.input !== undefined ? redactor(meta.input) : undefined\n const redactedOutput = output !== undefined ? redactor(output) : undefined\n if (redactedInput !== undefined) labels['tangle.input'] = previewJson(redactedInput)\n if (redactedOutput !== undefined) labels['tangle.output'] = previewJson(redactedOutput)\n try {\n ex.exportSpan(\n loopEventToOtelSpan(\n {\n kind: 'tangle.intelligence.run',\n runId: outcome.runId,\n timestamp: Date.now(),\n payload: labels,\n },\n outcome.traceId,\n ),\n )\n } catch {\n // Best-effort — telemetry export must never fail the agent's turn.\n }\n }\n\n return {\n project: config.project,\n effort,\n\n async traceRun<T>(meta: TraceMeta, fn: (trace: TraceHandle) => Promise<T>): Promise<T> {\n const runId = meta.runId ?? freshRunId()\n const traceId = meta.traceId ?? freshTraceId()\n let recordedOutput: unknown\n // Default split: inference-only. At OFF this is provably the whole bill.\n const usage: UsageSplit = { inferenceUsd: 0, intelligenceUsd: 0 }\n let success: boolean | undefined\n let score: number | undefined\n\n const trace: TraceHandle = {\n recordOutput(output: unknown): void {\n recordedOutput = output\n },\n recordOutcome(outcome): void {\n if (typeof outcome.success === 'boolean') success = outcome.success\n if (typeof outcome.score === 'number') score = outcome.score\n if (outcome.usage) {\n if (typeof outcome.usage.inferenceUsd === 'number') {\n usage.inferenceUsd = outcome.usage.inferenceUsd\n }\n if (typeof outcome.usage.intelligenceUsd === 'number') {\n usage.intelligenceUsd = outcome.usage.intelligenceUsd\n }\n } else if (typeof outcome.costUsd === 'number') {\n // A bare cost with no split is pure inference (the base stream).\n usage.inferenceUsd = outcome.costUsd\n }\n },\n }\n\n // The OFF floor is a HARD invariant, not a default: no intelligence spawn\n // can occur in this Observe slice, so intelligence-class spend is zero.\n // We clamp on export rather than trust the caller, so the billing proof\n // holds even if a caller mis-records an outcome at OFF.\n const result = await fn(trace)\n if (intelligenceOff) usage.intelligenceUsd = 0\n\n const outcome: TraceOutcome = {\n runId,\n traceId,\n project: config.project,\n effort,\n intelligenceOff,\n ...(success !== undefined ? { success } : {}),\n ...(score !== undefined ? { score } : {}),\n usage,\n }\n exportTrace(meta, outcome, recordedOutput)\n return result\n },\n\n recordTrace(events: ReadonlyArray<LoopTraceEvent>, meta?: RecordTraceMeta): string {\n const traceId = meta?.traceId ?? freshTraceId()\n const ex = getExporter()\n if (!ex || events.length === 0) return traceId\n // Reuse the shipped topology builder — loop → round → iteration span tree —\n // so the structure matches the kernel's, never a second parallel builder.\n try {\n const spans = buildLoopOtelSpans(\n events as ReadonlyArray<{\n kind: string\n runId: string\n timestamp: number\n payload: object\n }>,\n traceId,\n meta?.rootParentSpanId,\n )\n for (const span of spans) ex.exportSpan(span)\n } catch {\n // Best-effort — a trace export must never fail the caller's run.\n }\n return traceId\n },\n\n doctor(): DoctorReport {\n const hasRepo = Boolean(config.repo?.owner && config.repo?.name && config.repo?.baseBranch)\n const hasChecks = Boolean(config.checks && config.checks.length > 0)\n const hasSurfaces = Boolean(config.surfaces && config.surfaces.length > 0)\n\n const prMissing: string[] = []\n if (!hasChecks) prMissing.push('checks')\n if (!hasSurfaces) prMissing.push('surfaces')\n if (!hasRepo) prMissing.push('repo')\n\n // Recommend needs real outcomes to cluster. In the Observe slice the only\n // outcome source is `recordOutcome`; we can't introspect future calls, so\n // readiness reflects that outcome capture is WIRED (the API exists),\n // gated on the client emitting them — surfaced as the honest dependency.\n const recommendMissing: string[] = []\n if (intelligenceOff) recommendMissing.push('effort above off')\n\n return {\n project: config.project,\n effort,\n exportConfigured: Boolean(endpoint),\n modes: {\n observe: { ready: true, missing: [] },\n recommend: {\n ready: recommendMissing.length === 0,\n missing: recommendMissing,\n },\n pr: { ready: prMissing.length === 0, missing: prMissing },\n },\n }\n },\n\n async flush(): Promise<void> {\n const ex = getExporter()\n if (!ex) return\n try {\n await ex.flush()\n } catch {\n // Best-effort — a flush failure must not surface to the caller.\n }\n },\n }\n}\n\n/** A generic agent: one async input → output. The shape `withTangleIntelligence`\n * preserves exactly. */\nexport type Agent<TInput, TOutput> = (input: TInput) => Promise<TOutput>\n\n/** Either a built client or the config to build one. */\nexport type ClientOrConfig = IntelligenceClient | IntelligenceConfig\n\nfunction isClient(value: ClientOrConfig): value is IntelligenceClient {\n return typeof (value as IntelligenceClient).traceRun === 'function'\n}\n\n/**\n * Wrap a generic `agent` with best-effort Observe-mode tracing, returning the\n * SAME shape. Each call runs the agent under a trace and exports one span; an\n * export failure is swallowed (the live agent never fails because Intelligence\n * is down) but an error from the agent itself propagates unchanged.\n *\n * At `effort: 'off'` this is pure passthrough plus best-effort telemetry —\n * zero intelligence spawns, `intelligenceUsd: 0` on the trace.\n */\nexport function withTangleIntelligence<TInput, TOutput>(\n agent: Agent<TInput, TOutput>,\n clientOrConfig: ClientOrConfig,\n): Agent<TInput, TOutput> {\n const client = isClient(clientOrConfig)\n ? clientOrConfig\n : createIntelligenceClient(clientOrConfig)\n\n return async (input: TInput): Promise<TOutput> => {\n return client.traceRun({ input }, async (trace) => {\n const output = await agent(input)\n trace.recordOutput(output)\n return output\n })\n }\n}\n"],"mappings":";;;;;;;;AAoDA,IAAM,UAAkE;AAAA,EACtE,KAAK;AAAA,IACH,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AAAA,EACA,KAAK;AAAA,IACH,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AAAA,EACA,UAAU;AAAA,IACR,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AAAA,EACA,UAAU;AAAA,IACR,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AAAA,EACA,KAAK;AAAA,IACH,UAAU;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,uBAAuB;AAAA,EACzB;AACF;AAKO,IAAM,oBAAgC;AAatC,SAAS,cAAc,MAAkB,WAA6C;AAC3F,QAAM,SAAS,QAAQ,IAAI;AAC3B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR,sCAAsC,KAAK,UAAU,IAAI,CAAC,qBACxD,OAAO,KAAK,OAAO,EAElB,IAAI,CAAC,MAAM,IAAI,CAAC,GAAG,EACnB,KAAK,IAAI,CAAC;AAAA,IACf;AAAA,EACF;AACA,SAAO,EAAE,GAAG,QAAQ,GAAI,aAAa,CAAC,EAAG;AAC3C;AASO,SAAS,kBAAkB,UAAmC;AACnE,SACE,SAAS,aAAa,SACtB,SAAS,WAAW,SACpB,SAAS,UAAU,KACnB,SAAS,UAAU,SACnB,SAAS,0BAA0B;AAEvC;AA0CO,SAAS,cAAc,UAAmD;AAC/E,SAAO;AAA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,cAAc;AAE3C,SAAO,OAAO,UAAoC;AAChD,WAAO,OAAO,SAAS,EAAE,MAAM,GAAG,OAAO,UAAU;AACjD,YAAM,SAAS,MAAM,MAAM,KAAK;AAChC,YAAM,aAAa,MAAM;AACzB,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;","names":["outcome"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as CoderOutput, b as CoderTask } from './coder-
|
|
2
|
-
import {
|
|
1
|
+
import { C as CoderOutput, b as CoderTask } from './coder-LKm3Mczw.js';
|
|
2
|
+
import { g as LoopTraceEmitter, e as LoopTraceEvent, S as SandboxClient, A as AgentRunSpec } from './types-CklkW4Eh.js';
|
|
3
3
|
import { SandboxEvent, SandboxInstance } from '@tangle-network/sandbox';
|
|
4
4
|
import { AgentEvalError } from '@tangle-network/agent-eval';
|
|
5
5
|
import { a as UiLens, U as UiFinding } from './substrate-CUgk7F7s.js';
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { Scenario } from '@tangle-network/agent-eval/campaign';
|
|
2
2
|
import { SelfImproveOptions, SelfImproveResult } from '@tangle-network/agent-eval/contract';
|
|
3
3
|
import { R as RunAnalystLoopOpts, a as RunAnalystLoopResult } from './types-p8dWBIXL.js';
|
|
4
|
-
import { D as DelegateCodeArgs, C as CoderReviewer, a as CoderWinnerSelection, F as FactCandidate, b as CreateKbGateOptions } from './kb-gate-
|
|
5
|
-
import { C as CoderOutput } from './coder-
|
|
6
|
-
import { S as SandboxClient, O as OutputAdapter, V as Validator, A as AgentRunSpec, b as LoopResult } from './types-
|
|
7
|
-
import { T as TopologyPlanner, C as CreateDriverOptions, D as DriverDecision } from './driver-
|
|
4
|
+
import { D as DelegateCodeArgs, C as CoderReviewer, a as CoderWinnerSelection, F as FactCandidate, b as CreateKbGateOptions } from './kb-gate-CKfykcYQ.js';
|
|
5
|
+
import { C as CoderOutput } from './coder-LKm3Mczw.js';
|
|
6
|
+
import { S as SandboxClient, O as OutputAdapter, V as Validator, A as AgentRunSpec, b as LoopResult } from './types-CklkW4Eh.js';
|
|
7
|
+
import { T as TopologyPlanner, C as CreateDriverOptions, D as DriverDecision } from './driver-B2RKkVJW.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* @experimental
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
export { L as LoopRunnerCliArgs, f as LoopRunnerCliResult, p as parseLoopRunnerArgv, o as runLoopRunnerCli } from './loop-runner-bin-
|
|
2
|
+
export { L as LoopRunnerCliArgs, f as LoopRunnerCliResult, p as parseLoopRunnerArgv, o as runLoopRunnerCli } from './loop-runner-bin-D4Ir7b00.js';
|
|
3
3
|
import '@tangle-network/agent-eval/campaign';
|
|
4
4
|
import '@tangle-network/agent-eval/contract';
|
|
5
5
|
import './types-p8dWBIXL.js';
|
|
6
6
|
import '@tangle-network/agent-eval';
|
|
7
|
-
import './kb-gate-
|
|
8
|
-
import './coder-
|
|
7
|
+
import './kb-gate-CKfykcYQ.js';
|
|
8
|
+
import './coder-LKm3Mczw.js';
|
|
9
9
|
import '@tangle-network/sandbox';
|
|
10
|
-
import './types-
|
|
10
|
+
import './types-CklkW4Eh.js';
|
|
11
11
|
import './runtime-hooks-C7JwKb9E.js';
|
|
12
12
|
import './substrate-CUgk7F7s.js';
|
|
13
|
-
import './driver-
|
|
13
|
+
import './driver-B2RKkVJW.js';
|
package/dist/loop-runner-bin.js
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
import {
|
|
3
3
|
parseLoopRunnerArgv,
|
|
4
4
|
runLoopRunnerCli
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-K5M3SHEU.js";
|
|
6
6
|
import "./chunk-FNMGYYSS.js";
|
|
7
|
-
import "./chunk-
|
|
7
|
+
import "./chunk-AYRQZRDV.js";
|
|
8
8
|
import "./chunk-KADIJAD4.js";
|
|
9
9
|
import "./chunk-HNUXAZIJ.js";
|
|
10
10
|
import "./chunk-G3RGMA7C.js";
|
|
11
|
-
import "./chunk-
|
|
11
|
+
import "./chunk-K6WP7PYW.js";
|
|
12
12
|
import "./chunk-GSUO5QS6.js";
|
|
13
13
|
import "./chunk-DGUM43GV.js";
|
|
14
14
|
export {
|
package/dist/loops.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
export { AgentProfile, CreateSandboxOptions, SandboxEvent, SandboxInstance } from '@tangle-network/sandbox';
|
|
2
|
-
export { AgenticOptions, AgenticRunResult, AgenticSurface, AgenticTask, AgenticTool, AnytimeReport, AnytimeStrategySummary, AnytimeTaskCurve, ArtifactHandle, AssertTraceDerivedFindings, AuditIntentInput, AuditIntentOptions, AuthorStrategyOptions, AuthoredStrategy, BenchmarkCell, BenchmarkConfig, BenchmarkLift, BenchmarkReport, BenchmarkStrategySummary, BenchmarkTaskRow, BridgeSeam, BudgetPool, BudgetReadout, ChampionPick, ChampionPolicy, CheckpointCapableBox, CliSeam, CombinatorShape, Corpus, CorpusFilter, CorpusRecord, CreateScopeAnalystOptions, CriuCapableClient, DefinePersona, DefinePersonaInput, Deliverable, Environment, EqualKArm, EqualKOnCost, EqualKOnCostOptions, EqualKVerdict, EvolutionArchiveNode, EvolutionAuthor, EvolutionBandInfo, EvolutionCandidate, EvolutionGeneration, EvolutionReport, ExecutorConfig, Fanout, FanoutOptions, FanoutSynthesis, FileCorpus, FileResultBlobStore, FileSpawnJournal, FlatWidenGate, ForkCapableBox, GitWorkspaceOptions, HarvestCorpusOptions, HarvestFailure, HarvestReport, InMemoryCorpus, InMemoryResultBlobStore, InMemorySpawnJournal, IntentAudit, LoopDispatchOptions, LoopOptionsForDispatch, LoopShape, LoopUntil, LoopUntilSpec, LoopUntilState, McpEndpoint, McpEnvironmentOptions, Observation, ObserveInput, ObserveOptions, OpenSandboxRunOptions, Outcome, Panel, PanelJudge, PanelSpec, PanelVerdict, Persona, PersonaContext, PersonaExecutors, Pipeline, PipelineStage, PromotionGateOptions, PromotionVerdict, RegistryAnalyzeProjection, RenderCorpusToInstructions, RenderCorpusToInstructionsOptions, ReservationTicket,
|
|
3
|
-
export { A as AnalyzeInput, a as CompletionAnalyst, b as CompletionEvidence, c as CompletionPolicy, d as CompletionVerdict, C as CreateDriverOptions, D as DriverDecision, P as PlannerContext, e as TopologyMove, T as TopologyPlanner, f as completionAuthorizes, g as createDriver, h as deterministicCompletion, r as renderAnalyses, s as sentinelCompletion, i as stopSentinel } from './driver-
|
|
4
|
-
export { R as
|
|
5
|
-
export {
|
|
6
|
-
export { A as
|
|
2
|
+
export { AgenticOptions, AgenticRunResult, AgenticSurface, AgenticTask, AgenticTool, AnytimeReport, AnytimeStrategySummary, AnytimeTaskCurve, ArtifactHandle, AssertTraceDerivedFindings, AuditIntentInput, AuditIntentOptions, AuthorStrategyOptions, AuthoredStrategy, BenchmarkCell, BenchmarkConfig, BenchmarkLift, BenchmarkReport, BenchmarkStrategySummary, BenchmarkTaskRow, BridgeSeam, BudgetPool, BudgetReadout, ChampionPick, ChampionPolicy, CheckpointCapableBox, CliSeam, CombinatorShape, Corpus, CorpusFilter, CorpusRecord, CreateScopeAnalystOptions, CriuCapableClient, DefinePersona, DefinePersonaInput, Deliverable, Environment, EqualKArm, EqualKOnCost, EqualKOnCostOptions, EqualKVerdict, EvolutionArchiveNode, EvolutionAuthor, EvolutionBandInfo, EvolutionCandidate, EvolutionGeneration, EvolutionReport, ExecutorConfig, Fanout, FanoutOptions, FanoutSynthesis, FileCorpus, FileResultBlobStore, FileSpawnJournal, FlatWidenGate, ForkCapableBox, GitWorkspaceOptions, HarvestCorpusOptions, HarvestFailure, HarvestReport, InMemoryCorpus, InMemoryResultBlobStore, InMemorySpawnJournal, IntentAudit, LoopDispatchOptions, LoopOptionsForDispatch, LoopShape, LoopUntil, LoopUntilSpec, LoopUntilState, McpEndpoint, McpEnvironmentOptions, Observation, ObserveInput, ObserveOptions, OpenSandboxRunOptions, Outcome, Panel, PanelJudge, PanelSpec, PanelVerdict, Persona, PersonaContext, PersonaExecutors, Pipeline, PipelineStage, PromotionGateOptions, PromotionVerdict, RegistryAnalyzeProjection, RenderCorpusToInstructions, RenderCorpusToInstructionsOptions, ReservationTicket, RouterSeam, RouterToolsSeam, RunAgenticOptions, RunPersonified, RunPersonifiedOptions, SandboxCapabilities, SandboxLineage, SandboxLineageHandle, SandboxRun, SandboxSeam, ScopeAnalyst, ScopeAnalyzeInput, ScopeWidenGate, SessionCapableBox, ShapeBudget, ShapeContext, ShapeRegistry, Shell, ShotPersona, ShotSpec, SteerContext, Strategy, StrategyCtx, StrategyEvolutionConfig, StrategyResult, SurfaceScore, TrajectoryNode, TrajectoryReport, TrajectoryReportFn, TrajectoryReportOptions, TurnResult, UsageSink, VerifierEnvironmentOptions, Verify, VerifySpec, WaterfallCollector, WaterfallReport, WaterfallSpan, Widen, WidenDecision, WidenLineage, WidenSpec, Workspace, WorkspaceCommit, acquireSandbox, adaptiveRefine, anytimeReport, assertStrategyContract, assertTraceDerivedFindings, auditIntent, authorStrategy, breadthDriver, buildSteerContext, builtinShapes, contentAddress, createBudgetPool, createExecutor, createExecutorRegistry, createMcpEnvironment, createRootHandle, createSandboxLineage, createScope, createScopeAnalyst, createShapeRegistry, createSupervisor, createVerifierEnvironment, createWaterfallCollector, defaultAnalystInstruction, defaultAuditorInstruction, definePersona, defineStrategy, depthDriver, discriminatingMeans, equalKOnCost, extractLlmCallEvent, fanout, flatWidenGate, gitWorkspace, harvestCorpus, inlineSandboxClient, jjWorkspace, localShell, loopDispatch, loopUntil, mapSandboxEvent, materializeTreeView, observe, openSandboxRun, panel, pickChampion, pipeline, printBenchmarkReport, probeSandboxCapabilities, promotionGate, refine, registerShape, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderReport, replaySpawnTree, reportLoopUsage, runAgentic, runBenchmark, runPersonified, runStrategyEvolution, sample, sampleThenRefine, selectChampion, settledToIteration, spendFromUsageEvents, strategyAuthorContract, trajectoryReport, verify, widen } from './runtime.js';
|
|
3
|
+
export { A as AnalyzeInput, a as CompletionAnalyst, b as CompletionEvidence, c as CompletionPolicy, d as CompletionVerdict, C as CreateDriverOptions, D as DriverDecision, P as PlannerContext, e as TopologyMove, T as TopologyPlanner, f as completionAuthorizes, g as createDriver, h as deterministicCompletion, r as renderAnalyses, s as sentinelCompletion, i as stopSentinel } from './driver-B2RKkVJW.js';
|
|
4
|
+
export { R as RouterChatResult, a as RouterChatToolsResult, b as RouterConfig, c as RouterToolCall, d as RouterToolLoopResult, T as ToolSpec, r as routerChatWithTools, e as routerChatWithUsage, f as routerToolLoop } from './router-client-B0Qi1NiN.js';
|
|
5
|
+
export { R as RunLoopOptions, c as createSandboxForSpec, d as defaultSelectWinner, r as runLoop } from './run-loop-DgVhucoR.js';
|
|
6
|
+
export { A as Agent, d as AgentSpec, B as Budget, j as Executor, k as ExecutorContext, h as ExecutorFactory, E as ExecutorRegistry, l as ExecutorResult, H as Handle, N as NodeId, m as NodeSnapshot, n as NodeStatus, o as Restart, R as ResultBlobStore, e as RootHandle, p as RootSignal, q as Runtime, S as Scope, c as Settled, b as SpawnEvent, a as SpawnJournal, r as SpawnOpts, g as Spend, f as SupervisedResult, i as Supervisor, s as SupervisorOpts, T as TreeView, U as UsageEvent, W as WidenGate } from './types-CNDJCL_0.js';
|
|
7
|
+
export { A as AgentRunSpec, D as Driver, E as ExecCtx, I as Iteration, F as LoopDecisionPayload, G as LoopEndedPayload, H as LoopIterationDispatchPayload, J as LoopIterationEndedPayload, M as LoopIterationStartedPayload, a as LoopLineageOptions, N as LoopPlanDescription, P as LoopPlanPayload, b as LoopResult, f as LoopSandboxPlacement, Q as LoopStartedPayload, T as LoopTeardownFailedPayload, d as LoopTokenUsage, g as LoopTraceEmitter, e as LoopTraceEvent, L as LoopWinner, O as OutputAdapter, S as SandboxClient, U as ValidationCtx, V as Validator } from './types-CklkW4Eh.js';
|
|
7
8
|
export { DefaultVerdict } from '@tangle-network/agent-eval';
|
|
8
9
|
import './runtime-hooks-C7JwKb9E.js';
|
|
9
10
|
import '@tangle-network/agent-eval/campaign';
|
package/dist/loops.js
CHANGED
package/dist/mcp/bin.js
CHANGED
|
@@ -4,12 +4,12 @@ import {
|
|
|
4
4
|
createPropagatingTraceEmitter,
|
|
5
5
|
detectExecutor,
|
|
6
6
|
readTraceContextFromEnv
|
|
7
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-5M2WDWBI.js";
|
|
8
8
|
import "../chunk-WIR4HOOJ.js";
|
|
9
9
|
import {
|
|
10
10
|
DelegationTaskQueue,
|
|
11
11
|
FileDelegationStore
|
|
12
|
-
} from "../chunk-
|
|
12
|
+
} from "../chunk-FO4DCM7R.js";
|
|
13
13
|
import {
|
|
14
14
|
coderTaskFromArgs,
|
|
15
15
|
composeLoopTraceEmitters,
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
parseDetachedSessionRef,
|
|
21
21
|
runDetachedTurn,
|
|
22
22
|
settleDetachedCoderTurn
|
|
23
|
-
} from "../chunk-
|
|
23
|
+
} from "../chunk-AYRQZRDV.js";
|
|
24
24
|
import {
|
|
25
25
|
coderProfile
|
|
26
26
|
} from "../chunk-KADIJAD4.js";
|
|
@@ -28,7 +28,7 @@ import "../chunk-GLR25NG7.js";
|
|
|
28
28
|
import "../chunk-G3RGMA7C.js";
|
|
29
29
|
import {
|
|
30
30
|
runLoop
|
|
31
|
-
} from "../chunk-
|
|
31
|
+
} from "../chunk-K6WP7PYW.js";
|
|
32
32
|
import "../chunk-GSUO5QS6.js";
|
|
33
33
|
import "../chunk-DGUM43GV.js";
|
|
34
34
|
|
package/dist/mcp/index.d.ts
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
import { S as SandboxClient,
|
|
2
|
-
import { c as FleetHandle, d as DelegationExecutor, e as DelegateFeedbackArgs, f as DelegationFeedbackSnapshot, g as DelegationTaskQueue, h as CoderDelegate, R as ResearcherDelegate, U as UiAuditorDelegate, T as TraceContext, D as DelegateCodeArgs, i as DelegateCodeResult, j as DelegateFeedbackResult, k as ResearchSource, l as DelegateResearchArgs, m as DelegateResearchResult, n as DelegateUiAuditArgs, o as DelegateUiAuditResult, p as DelegationHistoryResult, q as DelegationHistoryArgs, r as DelegationStatusResult, s as DelegationStatusArgs } from '../kb-gate-
|
|
3
|
-
export { t as CappedDelegationTrace, u as CoderReview, C as CoderReviewer, a as CoderWinnerSelection, v as CreateDefaultCoderDelegateOptions, b as CreateKbGateOptions, w as DELEGATION_TRACE_MAX_BYTES, x as DELEGATION_TRACE_MAX_SPANS, y as DelegateCodeConfig, z as DelegateResearchConfig, A as DelegateRunCtx, B as DelegateUiAuditConfig, E as DelegateUiAuditRoute, G as DelegationError, H as DelegationHistoryEntry, I as DelegationPersistenceError, J as DelegationProfile, K as DelegationProgress, L as DelegationRecord, M as DelegationResultPayload, N as DelegationResumeContext, O as DelegationResumeDriver, P as DelegationResumeTick, Q as DelegationRunContext, S as DelegationStateCorruptError, V as DelegationStatus, W as DelegationStore, X as DelegationTaskQueueOptions, Y as DelegationTraceCaps, Z as DelegationTraceCollector, _ as DelegationTraceSpan, $ as DetachedSessionRefParts, a0 as DetachedTurn, a1 as DriveTurnCapableBox, a2 as DriveTurnResumeDriverOptions, a3 as DriveTurnTick, F as FactCandidate, a4 as FactJudge, a5 as FactJudgeVerdict, a6 as FeedbackRating, a7 as FeedbackRefersTo, a8 as FileDelegationStore, a9 as FileDelegationStoreOptions, aa as FleetWorkspaceExecutorOptions, ab as InMemoryDelegationStore, ac as KbGateResult, ad as ResearchOutputShape, ae as RunDetachedTurnOptions, af as SettleDetachedCoderTurnOptions, ag as SiblingSandboxExecutorOptions, ah as SubmitInput, ai as SubmitOutput, aj as UiAuditorDelegationOutput, ak as buildDelegationTraceSpans, al as capDelegationTrace, am as coderTaskFromArgs, an as composeLoopTraceEmitters, ao as createDefaultCoderDelegate, ap as createDelegationTraceCollector, aq as createDriveTurnResumeDriver, ar as createFleetWorkspaceExecutor, as as createKbGate, at as createPropagatingTraceEmitter, au as createSiblingSandboxExecutor, av as detachedTurnEvents, aw as formatDetachedSessionRef, ax as hashIdempotencyInput, ay as parseDetachedSessionRef, az as readTraceContextFromEnv, aA as runDetachedTurn, aB as settleDetachedCoderTurn, aC as traceContextToEnv } from '../kb-gate-
|
|
4
|
-
export { B as BuildDelegationMcpServerOptions, C as ComposeProductionAgentProfileOptions, D as DELEGATION_MCP_SERVER_KEY, b as buildDelegationMcpServer, c as composeProductionAgentProfile } from '../delegation-profile-
|
|
1
|
+
import { S as SandboxClient, f as LoopSandboxPlacement } from '../types-CklkW4Eh.js';
|
|
2
|
+
import { c as FleetHandle, d as DelegationExecutor, e as DelegateFeedbackArgs, f as DelegationFeedbackSnapshot, g as DelegationTaskQueue, h as CoderDelegate, R as ResearcherDelegate, U as UiAuditorDelegate, T as TraceContext, D as DelegateCodeArgs, i as DelegateCodeResult, j as DelegateFeedbackResult, k as ResearchSource, l as DelegateResearchArgs, m as DelegateResearchResult, n as DelegateUiAuditArgs, o as DelegateUiAuditResult, p as DelegationHistoryResult, q as DelegationHistoryArgs, r as DelegationStatusResult, s as DelegationStatusArgs } from '../kb-gate-CKfykcYQ.js';
|
|
3
|
+
export { t as CappedDelegationTrace, u as CoderReview, C as CoderReviewer, a as CoderWinnerSelection, v as CreateDefaultCoderDelegateOptions, b as CreateKbGateOptions, w as DELEGATION_TRACE_MAX_BYTES, x as DELEGATION_TRACE_MAX_SPANS, y as DelegateCodeConfig, z as DelegateResearchConfig, A as DelegateRunCtx, B as DelegateUiAuditConfig, E as DelegateUiAuditRoute, G as DelegationError, H as DelegationHistoryEntry, I as DelegationPersistenceError, J as DelegationProfile, K as DelegationProgress, L as DelegationRecord, M as DelegationResultPayload, N as DelegationResumeContext, O as DelegationResumeDriver, P as DelegationResumeTick, Q as DelegationRunContext, S as DelegationStateCorruptError, V as DelegationStatus, W as DelegationStore, X as DelegationTaskQueueOptions, Y as DelegationTraceCaps, Z as DelegationTraceCollector, _ as DelegationTraceSpan, $ as DetachedSessionRefParts, a0 as DetachedTurn, a1 as DriveTurnCapableBox, a2 as DriveTurnResumeDriverOptions, a3 as DriveTurnTick, F as FactCandidate, a4 as FactJudge, a5 as FactJudgeVerdict, a6 as FeedbackRating, a7 as FeedbackRefersTo, a8 as FileDelegationStore, a9 as FileDelegationStoreOptions, aa as FleetWorkspaceExecutorOptions, ab as InMemoryDelegationStore, ac as KbGateResult, ad as ResearchOutputShape, ae as RunDetachedTurnOptions, af as SettleDetachedCoderTurnOptions, ag as SiblingSandboxExecutorOptions, ah as SubmitInput, ai as SubmitOutput, aj as UiAuditorDelegationOutput, ak as buildDelegationTraceSpans, al as capDelegationTrace, am as coderTaskFromArgs, an as composeLoopTraceEmitters, ao as createDefaultCoderDelegate, ap as createDelegationTraceCollector, aq as createDriveTurnResumeDriver, ar as createFleetWorkspaceExecutor, as as createKbGate, at as createPropagatingTraceEmitter, au as createSiblingSandboxExecutor, av as detachedTurnEvents, aw as formatDetachedSessionRef, ax as hashIdempotencyInput, ay as parseDetachedSessionRef, az as readTraceContextFromEnv, aA as runDetachedTurn, aB as settleDetachedCoderTurn, aC as traceContextToEnv } from '../kb-gate-CKfykcYQ.js';
|
|
4
|
+
export { B as BuildDelegationMcpServerOptions, C as ComposeProductionAgentProfileOptions, D as DELEGATION_MCP_SERVER_KEY, b as buildDelegationMcpServer, c as composeProductionAgentProfile } from '../delegation-profile-Bvfro2m1.js';
|
|
5
5
|
import { L as LocalHarness, r as runLocalHarness } from '../local-harness-KrdFTY5R.js';
|
|
6
6
|
export { a as LocalHarnessResult, R as RunLocalHarnessOptions } from '../local-harness-KrdFTY5R.js';
|
|
7
|
-
export { m as mcpToolsForRuntimeMcp, a as mcpToolsForRuntimeMcpSubset } from '../openai-tools-
|
|
7
|
+
export { m as mcpToolsForRuntimeMcp, a as mcpToolsForRuntimeMcpSubset } from '../openai-tools-CKfR3EMh.js';
|
|
8
8
|
import { AnalystFinding } from '@tangle-network/agent-eval';
|
|
9
|
-
import { S as Scope, R as ResultBlobStore, A as Agent, B as Budget } from '../types-
|
|
9
|
+
import { S as Scope, R as ResultBlobStore, A as Agent, B as Budget } from '../types-CNDJCL_0.js';
|
|
10
10
|
import { a as UiLens } from '../substrate-CUgk7F7s.js';
|
|
11
11
|
import '@tangle-network/sandbox';
|
|
12
12
|
import '../runtime-hooks-C7JwKb9E.js';
|
|
13
|
-
import '../coder-
|
|
13
|
+
import '../coder-LKm3Mczw.js';
|
|
14
14
|
import 'node:child_process';
|
|
15
15
|
|
|
16
16
|
/**
|