@tangle-network/agent-runtime 0.106.1 → 0.107.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/{activation-CRjVfOiy.js → activation-Ck5ksFWg.js} +5 -4
- package/dist/{activation-CRjVfOiy.js.map → activation-Ck5ksFWg.js.map} +1 -1
- package/dist/agent.d.ts +2 -2
- package/dist/{analyst-loop-DGdtVENg.js → analyst-loop-C8cGThTW.js} +12 -4
- package/dist/{analyst-loop-DGdtVENg.js.map → analyst-loop-C8cGThTW.js.map} +1 -1
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/analyst-loop.js +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{candidate-execution-DqMbv1rU.js → candidate-execution-BUpR0mSD.js} +4 -4
- package/dist/{candidate-execution-DqMbv1rU.js.map → candidate-execution-BUpR0mSD.js.map} +1 -1
- package/dist/{improvement-adapter-Cr5TBSji.d.ts → improvement-adapter-BaAdfJKT.d.ts} +2 -2
- package/dist/{improvement-cycle-C095kS_g.js → improvement-cycle-Ulvvbg5p.js} +367 -34
- package/dist/improvement-cycle-Ulvvbg5p.js.map +1 -0
- package/dist/{index-DruSKs3Z.d.ts → index-CeawCSEg.d.ts} +2 -2
- package/dist/{index-BGdxAwfO.d.ts → index-D6MwUzvB.d.ts} +7 -7
- package/dist/{index-CbNM40xG.d.ts → index-jmFVBIHo.d.ts} +2 -2
- package/dist/index.d.ts +6 -6
- package/dist/index.js +7 -7
- package/dist/intelligence.d.ts +145 -66
- package/dist/intelligence.js +5 -5
- package/dist/intelligence.js.map +1 -1
- package/dist/{knowledge-Ku-mPP4f.js → knowledge-Dizh_AtL.js} +4 -4
- package/dist/{knowledge-Ku-mPP4f.js.map → knowledge-Dizh_AtL.js.map} +1 -1
- package/dist/knowledge.d.ts +1 -1
- package/dist/knowledge.js +1 -1
- package/dist/{loop-runner-bin-BXsFEUcf.d.ts → loop-runner-bin-BbYG9CeA.d.ts} +3 -3
- package/dist/{loop-runner-bin-CRagyuNb.js → loop-runner-bin-CvdKZkE4.js} +2 -2
- package/dist/{loop-runner-bin-CRagyuNb.js.map → loop-runner-bin-CvdKZkE4.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/loops.d.ts +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/{prepare-B53sPV7M.js → prepare-_WTTffkz.js} +25 -8
- package/dist/prepare-_WTTffkz.js.map +1 -0
- package/dist/primeintellect/index.d.ts +1 -1
- package/dist/{protected-model-port-BLPH5VVv.js → protected-model-port-ZUwVuftA.js} +2 -2
- package/dist/{protected-model-port-BLPH5VVv.js.map → protected-model-port-ZUwVuftA.js.map} +1 -1
- package/dist/{redact-kbIOjfjM.d.ts → redact-C5xOm8cu.d.ts} +23 -3
- package/dist/testing.js +222 -194
- package/dist/testing.js.map +1 -1
- package/dist/{types-Cja5OTGh.d.ts → types-CfGKhIuj.d.ts} +10 -2
- package/dist/{workspace-archive-BosQiotA.js → workspace-archive-CIG1VNCj.js} +2 -2
- package/dist/{workspace-archive-BosQiotA.js.map → workspace-archive-CIG1VNCj.js.map} +1 -1
- package/package.json +6 -6
- package/dist/improvement-cycle-C095kS_g.js.map +0 -1
- package/dist/prepare-B53sPV7M.js.map +0 -1
package/dist/intelligence.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intelligence.js","names":["canonicalCandidateDigest"],"sources":["../src/intelligence/delivery.ts","../src/intelligence/effort.ts","../src/intelligence/capability.ts","../src/intelligence/exact-process-candidate.ts","../src/intelligence/profile-activation.ts","../src/intelligence/resolver.ts","../src/intelligence/with-intelligence.ts","../src/intelligence/index.ts"],"sourcesContent":["/**\n *\n * Tangle Intelligence — the RECEIVE half of the loop (pull-by-default).\n *\n * The sibling Observe path (`./index`) sends run records 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 so an approved\n * improvement actually reaches the running agent. The pull carries three things\n * the plane already composes:\n * - the certified PROMPT surface + prompt-folding artifacts (delivered into the\n * system prompt via {@link composeCertifiedPrompt} — the promoted prompt);\n * - the typed profile DIFFS the plane has promoted, each with its held-out\n * provenance (surfaced as PROPOSALS — never auto-applied at runtime);\n * - the composed `agentProfile` those diffs fold to, for inspection.\n *\n * Pull contract (deployed plane): GET /v1/profiles/:target/composed →\n * { target, generatedAt,\n * promptSurface: {surface,surfaceHash,version,lift}|null,\n * artifacts: { <artifactType>: [{path,content,contentHash,version,lift,promotedAt}] },\n * capabilities: [{id,iface:{surface},binding:{path,content},provenance}],\n * agentProfileDiffs: [{diff, provenance:{version,lift,contentHash,promotedAt}}],\n * agentProfile: AgentProfile|null }\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 * @experimental\n */\n\nimport type {\n AgentImprovementProposal,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { verifyAgentImprovementProposal } from './improvement-cycle'\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 held-out provenance the plane's certify step stamps on a promoted diff.\n * `lift` is the held-out gate lift (e.g. \"+3.1pp\"), never a within-run claim. */\nexport interface DiffProvenance {\n version: number | null\n lift: string | null\n contentHash: string\n promotedAt: string\n}\n\n/**\n * A gate-certified profile diff the plane has already promoted, plus the\n * held-out provenance it carries. This is the previously-DROPPED typed diff the\n * composed endpoint returns; `withIntelligence` deserializes it and surfaces it\n * as a PROPOSAL — a human, or the gated local `improve()` loop, turns a proposal\n * into a shipped profile. It is NEVER auto-applied at runtime.\n */\nexport interface ProposedProfileDiff {\n diff: AgentProfileDiff\n provenance: DiffProvenance\n}\n\n/** The composed endpoint's per-capability summary — the narrow shape on the\n * wire (id + surface + path/content + provenance). Distinct from the richer\n * `CertifiedCapability` the capability resolver lowers a manifest into. */\nexport interface CertifiedCapabilitySummary {\n id: string\n iface: { surface: string }\n binding: { path: string | null; content: string }\n provenance: DiffProvenance\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 /** The typed profile diffs the plane has promoted, each with held-out\n * provenance. Surfaced as proposals; never auto-applied. Empty when none. */\n agentProfileDiffs: ProposedProfileDiff[]\n /** The composed capability summaries the plane returns. Empty when none. */\n capabilities: CertifiedCapabilitySummary[]\n /** The composed profile the promoted diffs fold to, for inspection. `null`\n * when no diffs are promoted. */\n agentProfile: AgentProfile | null\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 request after this many ms. Default 10000. */\n timeoutMs?: number\n}\n\n/** What Runtime knows about a failed proposal submission.\n * `not-sent` means no request began, `rejected` means Intelligence returned a\n * definitive 4xx response, and `unconfirmed` means the caller may safely retry\n * the same immutable proposal. */\nexport type AgentImprovementProposalSubmissionState = 'not-sent' | 'rejected' | 'unconfirmed'\n\n/** Submit a completed measured proposal for product-side review. */\nexport interface SubmitAgentImprovementProposalOptions {\n proposal: AgentImprovementProposal\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 request after this many ms. Default 10000. */\n timeoutMs?: number\n}\n\n/** Typed result for proposal submission. A successful result contains the\n * exact immutable proposal Intelligence recorded. */\nexport type SubmitAgentImprovementProposalOutcome =\n | { succeeded: true; value: AgentImprovementProposal; status: number }\n | {\n succeeded: false\n submission: AgentImprovementProposalSubmissionState\n error: string\n status?: number\n code?: string\n }\n\nconst defaultPlaneRequestTimeoutMs = 10_000\nconst maxPlaneErrorTextLength = 200\n\ntype PlaneRequestOptions = Pick<\n PullCertifiedOptions,\n 'apiKey' | 'baseUrl' | 'fetchImpl' | 'timeoutMs'\n>\n\ninterface PlaneRequestInput extends PlaneRequestOptions {\n path: string\n method?: 'POST'\n headers?: Record<string, string>\n body?: string\n}\n\ntype PlaneRequestResult =\n | { succeeded: true; response: Response }\n | { succeeded: false; attempted: false; error: string }\n | { succeeded: false; attempted: true; error: string }\n\n/** Resolve the ONE Intelligence base URL — the single knob both the send and\n * receive paths derive from. Env fallback: `TANGLE_INTELLIGENCE_URL`. */\nexport function resolveIntelligenceBaseUrl(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/** Make one authenticated request and retain whether the network call began. */\nasync function requestPlane(input: PlaneRequestInput): Promise<PlaneRequestResult> {\n const doFetch = input.fetchImpl ?? (globalThis.fetch as typeof fetch | undefined)\n if (!doFetch) {\n return { succeeded: false, attempted: false, error: 'no fetch implementation available' }\n }\n const apiKey = resolveApiKey(input.apiKey)\n if (!apiKey) {\n return {\n succeeded: false,\n attempted: false,\n error: 'no apiKey (set TANGLE_API_KEY or opts.apiKey)',\n }\n }\n\n try {\n const response = await doFetch(`${resolveIntelligenceBaseUrl(input.baseUrl)}${input.path}`, {\n ...(input.method === undefined ? {} : { method: input.method }),\n headers: {\n authorization: `Bearer ${apiKey}`,\n ...(input.headers ?? {}),\n },\n ...(input.body === undefined ? {} : { body: input.body }),\n signal: AbortSignal.timeout(input.timeoutMs ?? defaultPlaneRequestTimeoutMs),\n })\n return { succeeded: true, response }\n } catch (err) {\n return {\n succeeded: false,\n attempted: true,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : {}\n}\n\nfunction capPlaneErrorText(value: string): string {\n return value.slice(0, maxPlaneErrorTextLength)\n}\n\nfunction toDiffProvenance(value: unknown): DiffProvenance {\n const p = asRecord(value)\n return {\n version: typeof p.version === 'number' ? p.version : null,\n lift: typeof p.lift === 'string' ? p.lift : null,\n contentHash: typeof p.contentHash === 'string' ? p.contentHash : '',\n promotedAt: typeof p.promotedAt === 'string' ? p.promotedAt : '',\n }\n}\n\n/**\n * Deserialize the composed-endpoint response into a `CertifiedProfile`. The\n * previously-dropped `agentProfileDiffs`/`capabilities`/`agentProfile` are read\n * here so they round-trip to the consumer; a plane that has not yet promoted any\n * diffs simply yields empty arrays / a null profile (fail-closed, never a crash).\n */\nexport function normalizeCertifiedProfile(raw: unknown): CertifiedProfile {\n const r = asRecord(raw)\n const promptSurface = r.promptSurface ? (r.promptSurface as CertifiedPromptSurface) : null\n const artifacts = (r.artifacts as Record<string, CertifiedArtifact[]> | undefined) ?? {}\n const agentProfileDiffs: ProposedProfileDiff[] = Array.isArray(r.agentProfileDiffs)\n ? r.agentProfileDiffs.map((entry) => {\n const e = asRecord(entry)\n return { diff: e.diff as AgentProfileDiff, provenance: toDiffProvenance(e.provenance) }\n })\n : []\n const capabilities: CertifiedCapabilitySummary[] = Array.isArray(r.capabilities)\n ? (r.capabilities as CertifiedCapabilitySummary[])\n : []\n return {\n target: typeof r.target === 'string' ? r.target : '',\n generatedAt: typeof r.generatedAt === 'string' ? r.generatedAt : '',\n promptSurface,\n artifacts,\n agentProfileDiffs,\n capabilities,\n agentProfile: (r.agentProfile as AgentProfile | null | undefined) ?? null,\n }\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 request = await requestPlane({\n ...opts,\n path: `/v1/profiles/${encodeURIComponent(opts.target)}/composed`,\n })\n if (!request.succeeded) {\n return {\n succeeded: false,\n error: request.attempted ? `pull request failed: ${request.error}` : request.error,\n }\n }\n const res = request.response\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: normalizeCertifiedProfile(await res.json()) }\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 * Submit a completed Runtime proposal to Intelligence for product-side review.\n * This never runs an experiment, approves a proposal, or applies a candidate.\n * A 4xx response is a confirmed `rejected` request. Network failures, timeouts,\n * 5xx responses, and invalid success responses are `unconfirmed`, so callers\n * can retry the same digest because Intelligence stores proposals idempotently.\n */\nexport async function submitAgentImprovementProposal(\n opts: SubmitAgentImprovementProposalOptions,\n): Promise<SubmitAgentImprovementProposalOutcome> {\n let proposal: AgentImprovementProposal\n try {\n proposal = verifyAgentImprovementProposal(opts.proposal)\n } catch (err) {\n return {\n succeeded: false,\n submission: 'not-sent',\n error: `proposal validation failed: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n\n const request = await requestPlane({\n ...opts,\n path: '/v1/improvements/proposals',\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ proposal }),\n })\n if (!request.succeeded) {\n return {\n succeeded: false,\n submission: request.attempted ? 'unconfirmed' : 'not-sent',\n error: request.attempted\n ? `proposal submission request failed: ${request.error}`\n : request.error,\n }\n }\n const res = request.response\n\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n let code: string | undefined\n let message = capPlaneErrorText(body)\n try {\n const parsed = asRecord(JSON.parse(body))\n if (typeof parsed.error === 'string') code = capPlaneErrorText(parsed.error)\n if (typeof parsed.message === 'string') message = capPlaneErrorText(parsed.message)\n } catch {\n // The response body is optional; the HTTP status still determines the outcome.\n }\n return {\n succeeded: false,\n submission: res.status >= 400 && res.status < 500 ? 'rejected' : 'unconfirmed',\n error: `proposal submission ${res.status}: ${message}`,\n status: res.status,\n ...(code === undefined ? {} : { code }),\n }\n }\n\n try {\n const response = asRecord(await res.json())\n const recorded = verifyAgentImprovementProposal(response.proposal)\n if (recorded.digest !== proposal.digest) {\n return {\n succeeded: false,\n submission: 'unconfirmed',\n error: 'proposal submission returned a different proposal digest',\n status: res.status,\n }\n }\n return { succeeded: true, value: recorded, status: res.status }\n } catch (err) {\n return {\n succeeded: false,\n submission: 'unconfirmed',\n error: `proposal submission response parse failed: ${capPlaneErrorText(\n err instanceof Error ? err.message : String(err),\n )}`,\n status: res.status,\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. Reads only the prompt-folding slice of a profile.\n */\nexport function composeCertifiedPrompt(\n base: string,\n certified: Pick<CertifiedProfile, 'promptSurface' | 'artifacts'> | null,\n): 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/** A cached, self-refreshing source of a target's certified prompt additions —\n * the prompt-only delivery lane for callers that assemble their OWN system\n * prompt (product chat routes) rather than wrapping an agent fn. Same\n * fail-closed semantics as {@link pullCertified}: pulls at most every\n * `refreshMs`, coalesces concurrent pulls, keeps the last-known profile on a\n * failed/404 pull, never throws, never blocks past the pull timeout. */\nexport interface CertifiedPromptSource {\n /** Refresh (window-respecting) then fold the certified additions into a\n * base system prompt. Returns `base` unchanged when nothing is promoted. */\n compose(base: string): Promise<string>\n /** The certified profile currently in effect (`null` = none pulled yet). */\n current(): CertifiedProfile | null\n /** Pull now if the refresh window has elapsed; coalesced and fail-closed. */\n refresh(): Promise<void>\n}\n\n/** Options for {@link createCertifiedPromptSource} — the pull coordinates plus\n * the refresh cadence. */\nexport interface CertifiedPromptSourceOptions extends PullCertifiedOptions {\n /** Min interval between certified-profile pulls. Default 5m. */\n refreshMs?: number\n}\n\n/**\n * Create the cached certified-prompt source — the ONE module-scope-cache +\n * coalesced-refresh + keep-last-known implementation. Product wiring uses this\n * rather than hand-rolling the same lines around `pullCertified`. The\n * `withIntelligence` hook rides this same source for its prompt delivery.\n */\nexport function createCertifiedPromptSource(\n opts: CertifiedPromptSourceOptions,\n): CertifiedPromptSource {\n const refreshMs = opts.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(opts)\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 return {\n refresh,\n current: () => certified,\n async compose(base: string): Promise<string> {\n await refresh()\n return composeCertifiedPrompt(base, certified)\n },\n }\n}\n","/**\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 * @experimental\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 *\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 * @experimental\n */\n\nimport type { AgentProfileMcpServer } from '@tangle-network/agent-interface'\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. `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","import type { TraceStore } from '@tangle-network/agent-eval'\nimport type { CandidateExperimentExecutionInput } from '@tangle-network/agent-eval/contract'\nimport type { CandidateExecutionEvidence } from '@tangle-network/agent-interface'\nimport type { AgentExactProcessResources } from '@tangle-network/agent-interface/environment-provider'\n\nimport type { AgentCandidateExecutionClaimStore } from '../candidate-execution/claim'\nimport { exactProcessProviderAsCandidateExecutor } from '../candidate-execution/exact-process-executor'\nimport type { PrepareAgentCandidateExecutionOptions } from '../candidate-execution/prepare'\nimport {\n type CreateProtectedAgentCandidateModelPortOptions,\n createProtectedAgentCandidateModelPort,\n} from '../candidate-execution/protected-model-port'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateExecutionPorts,\n AgentCandidateExecutorPort,\n AgentCandidateOutputArtifactPort,\n} from '../candidate-execution/types'\nimport { AGENT_CANDIDATE_EXECUTION_SUPPORT } from '../candidate-execution/verify'\nimport type {\n AgentEnvironmentProviderRef,\n AgentEnvironmentProviderRegistry,\n} from '../runtime/environment-provider'\nimport { resolveAgentEnvironmentProvider } from '../runtime/environment-provider'\nimport {\n type AgentCandidateExperimentCellPlacement,\n executeAgentCandidateExperimentCell,\n} from './improvement-cycle'\n\n/** Candidate surfaces implemented by the neutral exact-process executor. */\nexport const exactProcessCandidateExperimentExecutionSupport = Object.freeze({\n outcomes: Object.freeze(['output'] as const),\n outputMediaTypes: Object.freeze(['text/*', 'application/json', '*+json'] as const),\n code: Object.freeze(['disabled'] as const),\n memory: Object.freeze(['disabled'] as const),\n knowledge: true,\n profile: AGENT_CANDIDATE_EXECUTION_SUPPORT.profile,\n isolation: Object.freeze({\n freshEnvironment: true,\n exactProcess: true,\n egress: Object.freeze(['blocked', 'strict'] as const),\n }),\n})\n\nexport interface CreateExactProcessCandidateExperimentExecutorOptions {\n provider: AgentEnvironmentProviderRef\n providerRegistry?: AgentEnvironmentProviderRegistry\n resources: AgentExactProcessResources\n providerOptions?: Record<string, unknown>\n provisionTimeoutMs?: number\n recoveryRetentionMs?: number\n ports: AgentCandidateExecutionPorts\n grader: AgentCandidateBenchmarkGraderPort\n outputArtifacts: AgentCandidateOutputArtifactPort\n traceStore: TraceStore\n claimStore: AgentCandidateExecutionClaimStore\n cleanupTimeoutMs?: number\n resultTimeoutMs?: number\n}\n\n/** Product-owned candidate ports other than protected model access. */\nexport type AgentCandidateExecutionHostPorts = Omit<AgentCandidateExecutionPorts, 'models'>\n\n/**\n * Builds the standard exact-process executor with model access that is scoped,\n * metered, and settled by the caller's grant service.\n */\nexport interface CreateProtectedExactProcessCandidateExperimentExecutorOptions\n extends Omit<CreateExactProcessCandidateExperimentExecutorOptions, 'ports'> {\n hostPorts: AgentCandidateExecutionHostPorts\n model: CreateProtectedAgentCandidateModelPortOptions\n}\n\nexport interface ExactProcessCandidateExperimentExecution\n extends CandidateExperimentExecutionInput {\n executionId: string\n attempt?: number\n executionRoots: AgentCandidateExperimentCellPlacement['executionRoots']\n stagingRoots: AgentCandidateExperimentCellPlacement['stagingRoots']\n preparation?: PrepareAgentCandidateExecutionOptions\n}\n\nexport interface ExactProcessCandidateExperimentExecutor {\n /** Runtime's expired-attempt path reuses this port only to stop and dispose. */\n readonly executor: AgentCandidateExecutorPort\n execute(input: ExactProcessCandidateExperimentExecution): Promise<CandidateExecutionEvidence>\n}\n\n/** Exact-process executor plus the ports required for durable recovery. */\nexport interface ProtectedExactProcessCandidateExperimentExecutor\n extends ExactProcessCandidateExperimentExecutor {\n readonly recoveryPorts: Pick<AgentCandidateExecutionPorts, 'models' | 'memory'>\n}\n\n/** Execute one signed experiment cell through any declared exact-process provider. */\nexport function createExactProcessCandidateExperimentExecutor(\n options: CreateExactProcessCandidateExperimentExecutorOptions,\n): ExactProcessCandidateExperimentExecutor {\n const provider = resolveAgentEnvironmentProvider(options.provider, options.providerRegistry)\n const executor = exactProcessProviderAsCandidateExecutor({\n provider,\n resources: options.resources,\n ...(options.providerOptions ? { providerOptions: options.providerOptions } : {}),\n ...(options.provisionTimeoutMs === undefined\n ? {}\n : { provisionTimeoutMs: options.provisionTimeoutMs }),\n ...(options.recoveryRetentionMs === undefined\n ? {}\n : { recoveryRetentionMs: options.recoveryRetentionMs }),\n })\n return Object.freeze({\n executor,\n async execute(\n input: ExactProcessCandidateExperimentExecution,\n ): Promise<CandidateExecutionEvidence> {\n return await executeAgentCandidateExperimentCell({\n ...input,\n attempt: input.attempt ?? 1,\n executionId: input.executionId,\n executionRoots: input.executionRoots,\n stagingRoots: input.stagingRoots,\n ports: options.ports,\n ...(input.preparation ? { preparation: input.preparation } : {}),\n execution: {\n executor,\n grader: options.grader,\n outputArtifacts: options.outputArtifacts,\n traceStore: options.traceStore,\n claimStore: options.claimStore,\n ...(options.cleanupTimeoutMs === undefined\n ? {}\n : { cleanupTimeoutMs: options.cleanupTimeoutMs }),\n ...(options.resultTimeoutMs === undefined\n ? {}\n : { resultTimeoutMs: options.resultTimeoutMs }),\n },\n })\n },\n })\n}\n\n/** Compose host-owned execution ports with protected model access for one exact-process run. */\nexport function createProtectedExactProcessCandidateExperimentExecutor(\n options: CreateProtectedExactProcessCandidateExperimentExecutorOptions,\n): ProtectedExactProcessCandidateExperimentExecutor {\n const { hostPorts, model, ...exactProcess } = options\n const ports = Object.freeze({\n ...hostPorts,\n models: createProtectedAgentCandidateModelPort(model),\n })\n const execution = createExactProcessCandidateExperimentExecutor({\n ...exactProcess,\n ports,\n })\n return Object.freeze({\n ...execution,\n recoveryPorts: Object.freeze({ models: ports.models, memory: ports.memory }),\n })\n}\n","import type {\n AgentImprovementActivationTargetState,\n AgentImprovementActivationTargetTransition,\n AgentProfile,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { agentProfileImprovementArmSchema } from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport {\n applyExactAgentProfileDiff,\n omitUndefinedObjectFields,\n parseExactAgentProfile,\n} from '../candidate-execution/profile'\nimport type {\n AgentImprovementActivationTargetPlan,\n ProfileImprovementActivationTransitionInput,\n} from './activation'\nimport {\n type AgentImprovementProfileSurface,\n agentImprovementProfileSurfaceDigest,\n agentImprovementTargetProfileDiffs,\n assertProfileImprovementTargetsShareIdentity,\n isAgentImprovementProfileSurface,\n} from './improvement-surfaces'\n\nexport type AgentImprovementProfileActivationTarget = Omit<\n AgentImprovementActivationTargetPlan,\n 'surface'\n> & {\n surface: AgentImprovementProfileSurface\n}\n\nexport type AgentImprovementProfileTargetState = Omit<\n AgentImprovementActivationTargetState,\n 'surface'\n> & { surface: AgentImprovementProfileSurface }\n\nexport type AgentImprovementProfileTargetTransition = Omit<\n AgentImprovementActivationTargetTransition,\n 'surface'\n> & { surface: AgentImprovementProfileSurface }\n\nexport interface AgentImprovementProfileReplacement {\n identity: string\n profile: AgentProfile\n}\n\nexport interface AgentImprovementProfileStateDigestInput {\n identity: string\n profile: AgentProfile\n}\n\n/** Product-defined hash of the complete profile state that actually runs. */\nexport type AgentImprovementProfileStateDigest = (\n input: AgentImprovementProfileStateDigestInput,\n) => Sha256Digest\n\nexport interface AgentImprovementProfileStateResolverInput {\n identity: string\n stateDigest: Sha256Digest\n}\n\n/** Product-owned retained-state lookup used only for an explicit restore. */\nexport type AgentImprovementProfileStateResolver = (\n input: AgentImprovementProfileStateResolverInput,\n) => AgentProfile | undefined\n\nexport type AgentImprovementProfileActivationInput =\n | {\n currentByIdentity: ReadonlyMap<string, AgentProfile>\n targets: readonly [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ]\n }\n | {\n currentByIdentity: ReadonlyMap<string, AgentProfile>\n profileTransition: ProfileImprovementActivationTransitionInput\n stateDigest: AgentImprovementProfileStateDigest\n resolveState?: AgentImprovementProfileStateResolver\n }\n\nexport type AgentImprovementProfileActivationPreparation =\n | {\n status: 'missing'\n identities: readonly string[]\n }\n | {\n status: 'unavailable'\n code: 'PROFILE_STATE_UNAVAILABLE'\n identities: readonly string[]\n requiredStateDigest: Sha256Digest\n }\n | {\n status: 'already-applied' | 'conflict'\n targets: [AgentImprovementProfileTargetState, ...AgentImprovementProfileTargetState[]]\n }\n | {\n status: 'apply'\n replacements: [AgentImprovementProfileReplacement, ...AgentImprovementProfileReplacement[]]\n targets: [\n AgentImprovementProfileTargetTransition,\n ...AgentImprovementProfileTargetTransition[],\n ]\n }\n\ninterface CurrentProfiles {\n identities: string[]\n byIdentity: Map<string, AgentProfile>\n}\n\n/**\n * Compare product-owned profiles with an exact measured transition and prepare\n * all-or-none replacements. The product owns locking, persistence, and retained\n * state; Runtime owns the profile diff semantics and digest checks.\n */\nexport function prepareAgentImprovementProfileActivation(\n input: AgentImprovementProfileActivationInput,\n): AgentImprovementProfileActivationPreparation {\n const targets =\n 'profileTransition' in input ? profileTargets(input.profileTransition.targets) : input.targets\n assertUniqueProfileTargets(targets)\n const current = readCurrentProfiles(input.currentByIdentity, targets)\n if ('status' in current) return immutableCandidateValue(current)\n\n if ('profileTransition' in input) {\n return prepareProfileImprovementActivation(input, targets, current)\n }\n return prepareSurfaceReplacementActivation(targets, current)\n}\n\nfunction prepareSurfaceReplacementActivation(\n targets: readonly [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ],\n currentProfiles: CurrentProfiles,\n): AgentImprovementProfileActivationPreparation {\n const current = targets.map((target) => {\n const profile = currentProfiles.byIdentity.get(target.identity)\n if (!profile) throw new Error(`missing agent profile ${target.identity}`)\n return {\n target,\n currentDigest: agentImprovementProfileSurfaceDigest(profile, target.surface),\n }\n })\n const states = targetStates(current)\n\n if (current.every(({ target, currentDigest }) => currentDigest === target.desiredDigest)) {\n return immutableCandidateValue({ status: 'already-applied', targets: states })\n }\n if (current.some(({ target, currentDigest }) => currentDigest !== target.expectedBaseDigest)) {\n return immutableCandidateValue({ status: 'conflict', targets: states })\n }\n\n const profiles = new Map<string, AgentProfile>()\n for (const identity of currentProfiles.identities) {\n const currentProfile = currentProfiles.byIdentity.get(identity)\n if (!currentProfile) throw new Error(`missing agent profile ${identity}`)\n const profile = targets\n .filter((target) => target.identity === identity)\n .flatMap((target) =>\n agentImprovementTargetProfileDiffs(target, {\n id: `${target.identity}:${target.desiredDigest}`,\n metadata: { identity },\n }),\n )\n .reduce(\n (value, diff) =>\n applyExactAgentProfileDiff(value, diff, `agent profile activation ${identity}`),\n currentProfile,\n )\n profiles.set(identity, immutableCandidateValue(profile))\n }\n\n for (const target of targets) {\n const profile = profiles.get(target.identity)\n if (\n !profile ||\n agentImprovementProfileSurfaceDigest(profile, target.surface) !== target.desiredDigest\n ) {\n throw new Error(\n `agent profile activation did not produce ${target.identity}:${target.surface}`,\n )\n }\n }\n return appliedProfileReplacement(currentProfiles.identities, profiles, targets)\n}\n\nfunction prepareProfileImprovementActivation(\n input: Extract<AgentImprovementProfileActivationInput, { profileTransition: unknown }>,\n targets: readonly [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ],\n currentProfiles: CurrentProfiles,\n): AgentImprovementProfileActivationPreparation {\n const transition = input.profileTransition\n assertProfileTransitionTargets(transition, targets)\n const current = targets.map((target) => {\n const profile = currentProfiles.byIdentity.get(target.identity)\n if (!profile) throw new Error(`missing agent profile ${target.identity}`)\n return {\n target,\n currentDigest: profileStateDigest(input.stateDigest, target.identity, profile),\n }\n })\n const states = targetStates(current)\n\n if (current.every(({ currentDigest }) => currentDigest === transition.desiredStateDigest)) {\n return immutableCandidateValue({ status: 'already-applied', targets: states })\n }\n if (current.some(({ currentDigest }) => currentDigest !== transition.sourceStateDigest)) {\n return immutableCandidateValue({ status: 'conflict', targets: states })\n }\n\n const profiles = new Map<string, AgentProfile>()\n for (const identity of currentProfiles.identities) {\n const currentProfile = currentProfiles.byIdentity.get(identity)\n if (!currentProfile) throw new Error(`missing agent profile ${identity}`)\n const profile =\n transition.operation.kind === 'apply-change'\n ? transition.operation.changes.reduce(\n (value, diff) =>\n applyExactAgentProfileDiff(value, diff, `profile improvement activation ${identity}`),\n currentProfile,\n )\n : restoreProfileState(input.resolveState, identity, transition.desiredStateDigest)\n if (!profile) {\n return immutableCandidateValue({\n status: 'unavailable',\n code: 'PROFILE_STATE_UNAVAILABLE',\n identities: currentProfiles.identities,\n requiredStateDigest: transition.desiredStateDigest,\n })\n }\n const parsed = parseExactAgentProfile(\n omitUndefinedObjectFields(profile, `profile improvement activation ${identity}`),\n `profile improvement activation ${identity}`,\n )\n if (profileStateDigest(input.stateDigest, identity, parsed) !== transition.desiredStateDigest) {\n throw new Error(`profile improvement activation did not produce ${identity}`)\n }\n profiles.set(identity, immutableCandidateValue(parsed))\n }\n\n return appliedProfileReplacement(currentProfiles.identities, profiles, targets)\n}\n\nfunction restoreProfileState(\n resolveState: AgentImprovementProfileStateResolver | undefined,\n identity: string,\n stateDigest: Sha256Digest,\n): AgentProfile | undefined {\n return resolveState?.({ identity, stateDigest })\n}\n\nfunction assertProfileTransitionTargets(\n transition: ProfileImprovementActivationTransitionInput,\n targets: readonly AgentImprovementProfileActivationTarget[],\n): void {\n assertProfileImprovementTargetsShareIdentity(targets)\n const operationDigest = canonicalCandidateDigest(transition.operation)\n if (\n targets.some(\n (target) =>\n target.expectedBaseDigest !== transition.sourceStateDigest ||\n target.desiredDigest !== transition.desiredStateDigest ||\n canonicalCandidateDigest(target.desiredInput) !== operationDigest,\n )\n ) {\n throw new Error('profile improvement targets do not match their transition')\n }\n}\n\nfunction appliedProfileReplacement(\n identities: readonly string[],\n profiles: ReadonlyMap<string, AgentProfile>,\n targets: readonly [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ],\n): AgentImprovementProfileActivationPreparation {\n return immutableCandidateValue({\n status: 'apply',\n replacements: identities.map((identity) => {\n const profile = profiles.get(identity)\n if (!profile) throw new Error(`missing prepared agent profile ${identity}`)\n return { identity, profile }\n }) as [AgentImprovementProfileReplacement, ...AgentImprovementProfileReplacement[]],\n targets: targets.map((target) => ({\n surface: target.surface,\n identity: target.identity,\n beforeDigest: target.expectedBaseDigest,\n afterDigest: target.desiredDigest,\n })) as [AgentImprovementProfileTargetTransition, ...AgentImprovementProfileTargetTransition[]],\n })\n}\n\nfunction targetStates(\n current: readonly {\n target: AgentImprovementProfileActivationTarget\n currentDigest: Sha256Digest\n }[],\n): [AgentImprovementProfileTargetState, ...AgentImprovementProfileTargetState[]] {\n const first = current[0]\n if (!first) throw new Error('agent profile activation requires a target')\n return current.map(({ target, currentDigest }) => ({\n surface: target.surface,\n identity: target.identity,\n currentDigest,\n })) as [AgentImprovementProfileTargetState, ...AgentImprovementProfileTargetState[]]\n}\n\nfunction profileStateDigest(\n stateDigest: AgentImprovementProfileStateDigest,\n identity: string,\n profile: AgentProfile,\n): Sha256Digest {\n return agentProfileImprovementArmSchema.parse({ stateDigest: stateDigest({ identity, profile }) })\n .stateDigest\n}\n\nfunction readCurrentProfiles(\n currentByIdentity: ReadonlyMap<string, AgentProfile>,\n targets: readonly AgentImprovementProfileActivationTarget[],\n): CurrentProfiles | { status: 'missing'; identities: string[] } {\n const identities = [...new Set(targets.map((target) => target.identity))].sort()\n const missing = identities.filter((identity) => !currentByIdentity.has(identity))\n if (missing.length > 0) return { status: 'missing', identities: missing }\n return {\n identities,\n byIdentity: new Map(\n identities.map((identity) => {\n const profile = currentByIdentity.get(identity)\n if (!profile) throw new Error(`missing agent profile ${identity}`)\n const label = `agent profile activation ${identity}`\n return [identity, parseExactAgentProfile(omitUndefinedObjectFields(profile, label), label)]\n }),\n ),\n }\n}\n\nfunction profileTargets(\n targets: readonly AgentImprovementActivationTargetPlan[],\n): [AgentImprovementProfileActivationTarget, ...AgentImprovementProfileActivationTarget[]] {\n if (!targets.every((target) => isAgentImprovementProfileSurface(target.surface))) {\n throw new Error('agent profile activation contains an unsupported surface')\n }\n const first = targets[0]\n if (!first) throw new Error('agent profile activation requires a target')\n return targets as [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ]\n}\n\nfunction assertUniqueProfileTargets(\n targets: readonly AgentImprovementProfileActivationTarget[],\n): void {\n const targetKeys = targets.map((target) => `${target.identity}\\u0000${target.surface}`)\n if (new Set(targetKeys).size !== targetKeys.length) {\n throw new Error('agent profile activation repeats a target')\n }\n}\n","/**\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 * @experimental\n */\n\nimport type { AgentProfileMcpServer } from '@tangle-network/agent-interface'\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 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 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 *\n * `withIntelligence` — the ONE agent-runtime hook that unifies Tangle\n * Intelligence send + receive.\n *\n * It does two things per call, both fail-open:\n * 1. RECEIVE — pull the tenant's certified profile from the deployed plane\n * (cached + refreshed), hand the agent the certified prompt surface to fold\n * (`applied.composePrompt`) and the promoted, gate-certified profile DIFFS\n * as PROPOSALS (`applied.proposals` / `applied.applyProfile`).\n * 2. SEND — serialize a typed {@link RunRecord} for the call through the shipped\n * OTLP builders to the plane's `/v1/otlp` ingest, best-effort.\n *\n * SAFETY — observe + deliver ONLY. This hook NEVER auto-applies a received diff\n * at runtime. A promoted diff is surfaced as a proposal; a human, or the gated\n * local `improve()` loop, turns a proposal into a shipped profile. That\n * preserves the held-out invariant the plane enforces — a runtime that silently\n * folded an un-gated diff into itself would defeat the very gate the diff cleared.\n *\n * import { withIntelligence } from '@tangle-network/agent-runtime/intelligence'\n *\n * export const agent = withIntelligence(\n * async (input, applied) => {\n * const out = await myAgent(input, { systemPrompt: applied.composePrompt(BASE) })\n * applied.record({ success: true, usage: { inferenceUsd: 0.002, intelligenceUsd: 0 } })\n * return out\n * },\n * { project: 'support-agent', target: 'support-agent' },\n * )\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { applyAgentProfileDiff } from '@tangle-network/agent-interface'\nimport {\n type CertifiedProfile,\n composeCertifiedPrompt,\n createCertifiedPromptSource,\n type ProposedProfileDiff,\n} from './delivery'\nimport {\n createIntelligenceClient,\n type IntelligenceConfig,\n type RunRecord,\n type RunReport,\n} from './index'\n\n/** What the hook hands the agent each run. Additive over the prompt-only\n * delivery: `composePrompt` folds the certified prompt surface (as before);\n * `proposals`/`applyProfile` surface the promoted profile DIFFS — never\n * auto-applied; `record` enriches the {@link RunRecord} that is sent. */\nexport interface AppliedIntelligence {\n /** Stable ids shared by the run span and every nested runtime/loop span. */\n runId: string\n traceId: string\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 (the promoted\n * prompt). The consumer opts in by calling it. */\n composePrompt(base: string): string\n /** The promoted, gate-certified profile diffs — surfaced for a human or the\n * gated `improve()` loop. NEVER auto-applied by this hook. Empty when none. */\n proposals: ProposedProfileDiff[]\n /** Fold every proposal into `base` via `applyAgentProfileDiff`, in promotion\n * order, and return the result. The caller invokes this EXPLICITLY (it is the\n * human/gated apply step) — the hook never calls it on the run path. */\n applyProfile(base: AgentProfile): AgentProfile\n /** Enrich the {@link RunRecord} sent for this call — outcome, usage split,\n * model/provider, and the loop event stream. Optional; an un-recorded run\n * still sends input/output with an inference-only zero usage split. */\n record(report: RunReport): void\n}\n\n/** An agent wrapped by {@link withIntelligence}: receives the input plus the\n * intelligence delivered for this run. */\nexport type IntelligenceAgent<I, O> = (input: I, applied: AppliedIntelligence) => Promise<O>\n\n/** `withIntelligence` config = the Observe config plus the pull target, refresh\n * cadence, and a proposals callback. One base URL (`baseUrl` /\n * `TANGLE_INTELLIGENCE_URL`) drives both the send and receive paths. */\nexport interface IntelligenceHookConfig extends IntelligenceConfig {\n /** Pull target. Defaults to `project`. */\n target?: 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 /** Notified when a refresh delivers a NEW set of promoted proposals (by\n * provenance content hash). Surfaces diffs without auto-applying them. */\n onProposals?: (proposals: ProposedProfileDiff[]) => void\n}\n\n/** The wrapped agent — same `(input) => Promise<output>` shape, plus a manual\n * `refresh()` and a `proposals()` accessor for the currently-promoted diffs. */\nexport type IntelligenceWrapped<I, O> = ((input: I) => Promise<O>) & {\n refresh(): Promise<void>\n proposals(): ProposedProfileDiff[]\n /** Flush buffered trace spans before a short-lived process exits. */\n flush(): Promise<void>\n}\n\ninterface RuntimeEventSummary {\n inferenceUsd: number\n inputTokens: number\n outputTokens: number\n model?: string\n sessionId?: string\n success?: boolean\n error?: RunRecord['error']\n}\n\nfunction summarizeRuntimeEvents(\n events: NonNullable<RunReport['runtimeEvents']>,\n): RuntimeEventSummary {\n const summary: RuntimeEventSummary = { inferenceUsd: 0, inputTokens: 0, outputTokens: 0 }\n for (const event of events) {\n if ('session' in event && event.session) summary.sessionId = event.session.id\n if (event.type === 'llm_call') {\n summary.model = event.model\n summary.inferenceUsd += event.costUsd ?? 0\n summary.inputTokens += event.tokensIn ?? 0\n summary.outputTokens += event.tokensOut ?? 0\n } else if (event.type === 'backend_error') {\n summary.success = false\n summary.error = {\n name: event.error?.kind ?? 'BackendError',\n message: event.message,\n ...(event.error?.status !== undefined ? { code: String(event.error.status) } : {}),\n }\n } else if (event.type === 'final') {\n summary.success = event.status === 'completed'\n if (event.error) {\n summary.error = {\n name: event.error.kind,\n message: event.error.message,\n ...(event.error.status !== undefined ? { code: String(event.error.status) } : {}),\n }\n }\n }\n }\n return summary\n}\n\nfunction runError(cause: unknown): NonNullable<RunRecord['error']> {\n if (cause instanceof Error) {\n const code = (cause as Error & { code?: unknown }).code\n return {\n name: cause.name || 'Error',\n message: cause.message,\n ...(typeof code === 'string' || typeof code === 'number' ? { code: String(code) } : {}),\n }\n }\n return { name: 'Error', message: String(cause) }\n}\n\n/**\n * Wrap an agent so it (a) RECEIVES the tenant's certified profile — the prompt\n * surface to fold and the promoted profile diffs as proposals — and (b) SENDS a\n * typed {@link RunRecord} per call to the plane. The pull is cached and refreshed\n * at most every `refreshMs`; a failed pull is fail-closed (the agent runs on its\n * base surface, never breaks because Intelligence is unreachable). The send is\n * best-effort — an export failure never fails the agent's turn — while an error\n * thrown by the agent itself propagates unchanged.\n */\nexport function withIntelligence<I, O>(\n agent: IntelligenceAgent<I, O>,\n config: IntelligenceHookConfig,\n): IntelligenceWrapped<I, O> {\n const client = createIntelligenceClient(config)\n const target = config.target ?? config.project\n const source = createCertifiedPromptSource({\n target,\n ...(config.apiKey !== undefined ? { apiKey: config.apiKey } : {}),\n ...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl } : {}),\n ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),\n ...(config.fetchImpl !== undefined ? { fetchImpl: config.fetchImpl } : {}),\n ...(config.refreshMs !== undefined ? { refreshMs: config.refreshMs } : {}),\n })\n\n const currentProposals = (): ProposedProfileDiff[] => source.current()?.agentProfileDiffs ?? []\n\n // Fire `onProposals` only when the promoted set actually changes (keyed by\n // provenance content hash) — a refresh that re-delivers the same diffs is silent.\n let lastSignal = ''\n function signalProposals(): void {\n const proposals = currentProposals()\n if (proposals.length === 0) return\n const sig = proposals.map((p) => p.provenance.contentHash).join('|')\n if (sig === lastSignal) return\n lastSignal = sig\n config.onProposals?.(proposals)\n }\n\n async function refresh(): Promise<void> {\n await source.refresh()\n signalProposals()\n }\n\n const wrapped = (async (input: I): Promise<O> => {\n const runId = client.freshRunId()\n const traceId = client.freshTraceId()\n const startedAt = Date.now()\n await refresh()\n const certified = source.current()\n const proposals = currentProposals()\n const report: RunReport = {}\n const applied: AppliedIntelligence = {\n runId,\n traceId,\n certified,\n composePrompt: (base: string) => composeCertifiedPrompt(base, certified),\n proposals,\n applyProfile: (base: AgentProfile) =>\n proposals.reduce((profile, p) => applyAgentProfileDiff(profile, p.diff), base),\n record: (r: RunReport) => Object.assign(report, r),\n }\n\n function exportCompleted(output: unknown, caught?: unknown): void {\n const completedAt = Date.now()\n const eventSummary = summarizeRuntimeEvents(report.runtimeEvents ?? [])\n const error = report.error ?? (caught !== undefined ? runError(caught) : eventSummary.error)\n const tokens =\n report.tokens ??\n (eventSummary.inputTokens > 0 || eventSummary.outputTokens > 0\n ? { input: eventSummary.inputTokens, output: eventSummary.outputTokens }\n : undefined)\n const profile = report.profile ?? config.profile\n const record: RunRecord = {\n runId,\n traceId,\n project: config.project,\n target,\n input,\n output,\n outcome: {\n success:\n report.success ??\n (caught !== undefined ? false : (eventSummary.success ?? error === undefined)),\n ...(report.score !== undefined ? { score: report.score } : {}),\n usage: {\n inferenceUsd: report.usage?.inferenceUsd ?? report.costUsd ?? eventSummary.inferenceUsd,\n intelligenceUsd: report.usage?.intelligenceUsd ?? 0,\n },\n },\n timing: { startedAt, completedAt, durationMs: completedAt - startedAt },\n ...((report.model ?? eventSummary.model)\n ? { model: report.model ?? eventSummary.model }\n : {}),\n ...(report.provider !== undefined ? { provider: report.provider } : {}),\n ...(report.loopEvents !== undefined ? { loopEvents: report.loopEvents } : {}),\n ...(report.runtimeEvents !== undefined ? { runtimeEvents: report.runtimeEvents } : {}),\n ...(profile !== undefined ? { profile } : {}),\n ...((report.sessionId ?? eventSummary.sessionId)\n ? { sessionId: report.sessionId ?? eventSummary.sessionId }\n : {}),\n ...((report.harness ?? profile?.harness)\n ? { harness: report.harness ?? profile?.harness }\n : {}),\n ...((report.commitSha ?? config.commitSha)\n ? { commitSha: report.commitSha ?? config.commitSha }\n : {}),\n ...(tokens !== undefined ? { tokens } : {}),\n ...(error !== undefined ? { error } : {}),\n ...(report.candidateExecution !== undefined\n ? { candidateExecution: report.candidateExecution }\n : {}),\n }\n client.exportRunRecord(record)\n }\n\n try {\n const output = await agent(input, applied)\n exportCompleted(output)\n return output\n } catch (cause) {\n exportCompleted(undefined, cause)\n throw cause\n }\n }) as IntelligenceWrapped<I, O>\n\n wrapped.refresh = refresh\n wrapped.proposals = currentProposals\n wrapped.flush = client.flush\n return wrapped\n}\n","/**\n *\n * Tangle Intelligence SDK — trace capture plus reviewable improvement.\n *\n * The client keeps live-agent trace delivery best-effort. The separate\n * improvement-cycle exports analyze completed traces, run a signed baseline\n * versus candidate experiment, bind review to its result, and activate only\n * the exact measured candidate.\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 * @experimental\n */\n\nimport { contentHash } from '@tangle-network/agent-eval'\nimport type { AgentProfile, CandidateExecutionEvidence } from '@tangle-network/agent-interface'\nimport {\n buildLoopOtelSpans,\n buildRuntimeEventOtelSpans,\n createOtelExporter,\n flatOtelSpan,\n type OtelExporter,\n} from '../otel-export'\nimport { type Redactor, resolveRedactor } from '../redact'\nimport type { LoopTraceEvent } from '../runtime/types'\nimport type { RuntimeTelemetryOptions } from '../sanitize'\nimport type { RuntimeStreamEvent } from '../types'\nimport { resolveIntelligenceBaseUrl } from './delivery'\nimport {\n defaultEffortTier,\n type EffortOverrides,\n type EffortSettings,\n type EffortTier,\n isIntelligenceOff,\n resolveEffort,\n} from './effort'\n\nexport type {\n AgentCandidateProfileActivation as CandidateProfileMaterialization,\n AgentImprovementActivation,\n AgentImprovementActivationIntent,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementEvaluation,\n AgentImprovementMeasuredComparison,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n CandidateExecutionEvidence,\n} from '@tangle-network/agent-interface'\nexport { parseAgentCandidateProfileActivation as parseCandidateProfileMaterialization } from '../candidate-execution/profile'\nexport type { Redactor } from '../redact'\nexport { defaultRedactor, resolveRedactor } from '../redact'\nexport type {\n AgentImprovementActivationReconciliation,\n AgentImprovementActivationResultStore,\n AgentImprovementActivationTargetPlan,\n AgentImprovementActivationTransition,\n AgentImprovementActivationTransitionInput,\n AgentProfileImprovementActivationOperation,\n AgentProfileImprovementActivationTargetPlan,\n CreateAgentImprovementActivationResultOptions,\n ExecuteAgentImprovementActivationInput,\n ExecuteAgentImprovementActivationOptions,\n ProfileImprovementActivationTransitionInput,\n SealedCandidateActivationTransitionInput,\n} from './activation'\nexport {\n createAgentImprovementActivationResult,\n executeAgentImprovementActivation,\n verifyAgentImprovementActivationResult,\n} from './activation'\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 AgentImprovementProposalSubmissionState,\n CertifiedArtifact,\n CertifiedCapabilitySummary,\n CertifiedProfile,\n CertifiedPromptSource,\n CertifiedPromptSourceOptions,\n CertifiedPromptSurface,\n DiffProvenance,\n ProposedProfileDiff,\n PullCertifiedOptions,\n PullOutcome,\n SubmitAgentImprovementProposalOptions,\n SubmitAgentImprovementProposalOutcome,\n} from './delivery'\nexport {\n composeCertifiedPrompt,\n createCertifiedPromptSource,\n normalizeCertifiedProfile,\n pullCertified,\n resolveIntelligenceBaseUrl,\n submitAgentImprovementProposal,\n} 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 {\n AgentCandidateExecutionHostPorts,\n CreateExactProcessCandidateExperimentExecutorOptions,\n CreateProtectedExactProcessCandidateExperimentExecutorOptions,\n ExactProcessCandidateExperimentExecution,\n ExactProcessCandidateExperimentExecutor,\n ProtectedExactProcessCandidateExperimentExecutor,\n} from './exact-process-candidate'\nexport {\n createExactProcessCandidateExperimentExecutor,\n createProtectedExactProcessCandidateExperimentExecutor,\n exactProcessCandidateExperimentExecutionSupport,\n} from './exact-process-candidate'\nexport type {\n AgentCandidateExperimentCellPlacement,\n AgentImprovementExperimentMaterial,\n CreateAgentImprovementActivationOptions,\n CreateAgentImprovementProposalOptions,\n ExecuteAgentCandidateExperimentCellOptions,\n ProposeAgentImprovementOptions,\n ProposeAgentImprovementResult,\n ReviewAgentImprovementInput,\n RunAgentCandidateExperimentOptions,\n RunAgentCandidateExperimentResult,\n VerifyCandidateExecutionEvidenceOptions,\n} from './improvement-cycle'\nexport {\n AgentCandidateExperimentCellExecutionError,\n createAgentImprovementActivation,\n createAgentImprovementMeasuredComparison,\n createAgentImprovementProposal,\n executeAgentCandidateExperimentCell,\n proposeAgentImprovement,\n reviewAgentImprovementProposal,\n runAgentCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n verifyAgentImprovementReview,\n verifyCandidateExecutionEvidence,\n} from './improvement-cycle'\nexport type {\n AgentImprovementActivationTargetIdentity,\n AgentImprovementProfileSurface,\n AgentImprovementTargetProfileDiffOptions,\n} from './improvement-surfaces'\nexport {\n AGENT_IMPROVEMENT_PROFILE_SURFACES,\n agentImprovementProfileSurfaceDigest,\n agentImprovementProfileSurfaceInput,\n agentImprovementTargetProfileDiffs,\n buildAgentImprovementActivationTargets,\n isAgentImprovementProfileSurface,\n} from './improvement-surfaces'\nexport type {\n OptimizationActivationReceipt,\n OptimizationReceiptCost,\n} from './optimization-receipt'\nexport {\n createOptimizationActivationReceipt,\n optimizationActivationReceiptFromMetadata,\n} from './optimization-receipt'\nexport type {\n AgentImprovementProfileActivationInput,\n AgentImprovementProfileActivationPreparation,\n AgentImprovementProfileActivationTarget,\n AgentImprovementProfileReplacement,\n AgentImprovementProfileStateDigest,\n AgentImprovementProfileStateDigestInput,\n AgentImprovementProfileStateResolver,\n AgentImprovementProfileStateResolverInput,\n AgentImprovementProfileTargetState,\n AgentImprovementProfileTargetTransition,\n} from './profile-activation'\nexport { prepareAgentImprovementProfileActivation } from './profile-activation'\nexport type { ProvisionedHost, ResolveCtx } from './resolver'\nexport {\n composeCertifiedProfile,\n composeCertifiedProfileFromWire,\n} from './resolver'\nexport type {\n AppliedIntelligence,\n IntelligenceAgent,\n IntelligenceHookConfig,\n IntelligenceWrapped,\n} from './with-intelligence'\nexport { withIntelligence } from './with-intelligence'\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/**\n * The typed record `withIntelligence` sends per call — serialized through the\n * shipped OTLP builders to the plane's `/v1/otlp` ingest. `input`/`output` are\n * redacted on export; the per-class `usage` split carries the billing proof;\n * `loopEvents`, when present, export as the nested loop→round→iteration span\n * tree under the same `traceId`.\n */\nexport interface RunRecord {\n runId: string\n traceId: string\n project: string\n target: string\n input: unknown\n output: unknown\n outcome: {\n success?: boolean\n score?: number\n usage: UsageSplit\n }\n model?: string\n provider?: string\n loopEvents?: LoopTraceEvent[]\n runtimeEvents?: RuntimeStreamEvent[]\n profile?: AgentProfile\n sessionId?: string\n harness?: string\n repository?: string\n commitSha?: string\n timing?: { startedAt: number; completedAt: number; durationMs: number }\n tokens?: {\n input: number\n output: number\n cachedInput?: number\n reasoning?: number\n }\n error?: { name: string; message: string; code?: string }\n /** Exact proposal → review → execution → receipt linkage for candidate runs. */\n candidateExecution?: CandidateExecutionEvidence\n}\n\n/**\n * What an agent reports (via `applied.record`) to enrich the {@link RunRecord}\n * sent for its call. All optional — an un-recorded run still sends input/output\n * with an inference-only zero usage split. `costUsd` without a split is treated\n * as pure inference (the base stream).\n */\nexport interface RunReport {\n success?: boolean\n score?: number\n usage?: Partial<UsageSplit>\n costUsd?: number\n model?: string\n provider?: string\n loopEvents?: LoopTraceEvent[]\n runtimeEvents?: RuntimeStreamEvent[]\n profile?: AgentProfile\n sessionId?: string\n harness?: string\n commitSha?: string\n tokens?: RunRecord['tokens']\n error?: RunRecord['error']\n candidateExecution?: CandidateExecutionEvidence\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 * The ONE Tangle Intelligence base URL — both the send (OTLP `/v1/otlp`) and\n * receive (`/v1/profiles/:target/composed`) paths derive from it. Reads\n * `TANGLE_INTELLIGENCE_URL` when omitted, else `https://intelligence.tangle.tools`.\n * Send is best-effort and only ships when an `apiKey` is present (the tenant\n * key the ingest requires); absent a key, export is a no-op.\n */\n baseUrl?: 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 /** Full canonical profile used for this agent. Exported redacted with a stable hash. */\n profile?: AgentProfile\n /** Commit that produced the running agent, when known. */\n commitSha?: string\n /** Runtime-event payload policy. Tool inputs/results remain off unless explicitly enabled. */\n runtimeTelemetry?: RuntimeTelemetryOptions\n /**\n * Payloads are metadata-only by default: the run span carries a stable hash\n * and UTF-8 byte count, but not the redacted content. Set `full` only when\n * the configured OTLP destination is approved to receive complete redacted\n * inputs, outputs, and profiles.\n */\n payloadAttributes?: 'metadata' | 'full'\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 * `runAgentRounds`/`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 * Send one typed {@link RunRecord} — the run's flat span (input/output/outcome/\n * usage/model/provider, redacted) plus, when `loopEvents` are present, the\n * nested loop topology under the same `traceId`. Reuses the shipped\n * `flatOtelSpan` + `buildLoopOtelSpans` builders (no second builder).\n * Best-effort: export failures are swallowed. Returns the record's `traceId`.\n */\n exportRunRecord(record: RunRecord): string\n /** Mint a fresh run id (`run-<hex>`). */\n freshRunId(): string\n /** Mint a fresh 32-hex trace id. */\n freshTraceId(): 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 freshTraceId(): string {\n return randomHex(32)\n}\n\nfunction freshRunId(): string {\n return `run-${randomHex(16)}`\n}\n\n/** Serialize a redacted value without dropping customer trace content. */\nfunction serializeJson(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\n}\n\nfunction addPayloadAttributes(\n labels: Record<string, string | number | boolean>,\n key: string,\n value: unknown,\n includeFullPayload: boolean,\n): void {\n const serialized = serializeJson(value)\n labels[`${key}_hash`] = contentHash(serialized)\n labels[`${key}_bytes`] = Buffer.byteLength(serialized, 'utf8')\n if (includeFullPayload) labels[key] = serialized\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, the base URL, and\n * the redactor up front; the exporter is built lazily and is `undefined` when no\n * `apiKey` is present (send becomes a no-op — the ingest requires a tenant key,\n * and best-effort export must never spam an unauthenticated plane).\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 includeFullPayload = config.payloadAttributes === 'full'\n const apiKey =\n config.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n // The ONE base URL drives both send and receive; the OTLP ingest lives at\n // `${base}/v1/otlp` and the exporter appends `/v1/traces` → `${base}/v1/otlp/v1/traces`.\n const otlpEndpoint = `${resolveIntelligenceBaseUrl(config.baseUrl)}/v1/otlp`\n\n // Built lazily: a client with no tenant key 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 (!apiKey) return undefined\n exporter = createOtelExporter({\n endpoint: otlpEndpoint,\n headers: { 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 try {\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) {\n addPayloadAttributes(labels, 'tangle.input', redactedInput, includeFullPayload)\n }\n if (redactedOutput !== undefined) {\n addPayloadAttributes(labels, 'tangle.output', redactedOutput, includeFullPayload)\n }\n // Flat span with VERBATIM attribute keys — the plane's session/model/\n // cost readers exact-match `tangle.sessionId` / `gen_ai.request.model`,\n // so the loop-namespacing builder must not be used here.\n ex.exportSpan(\n flatOtelSpan(\n 'tangle.intelligence.run',\n { 'tangle.runId': outcome.runId, ...labels },\n outcome.traceId,\n Date.now(),\n ),\n )\n } catch {\n // Best-effort — telemetry export must never fail the agent's turn.\n }\n }\n\n function exportRunRecord(record: RunRecord): string {\n const ex = getExporter()\n if (!ex) return record.traceId\n try {\n // Clamp the OFF billing invariant on export — the proof holds even if a\n // caller mis-reports an intelligence split at the OFF tier.\n const intelligenceUsd = intelligenceOff ? 0 : record.outcome.usage.intelligenceUsd\n const repository =\n record.repository ?? (config.repo ? `${config.repo.owner}/${config.repo.name}` : undefined)\n const labels: Record<string, string | number | boolean> = {\n project: record.project,\n 'tangle.target': record.target,\n 'tangle.effort.intelligence_off': intelligenceOff,\n 'tangle.usage.inference_usd': record.outcome.usage.inferenceUsd,\n 'tangle.usage.intelligence_usd': intelligenceUsd,\n ...(record.model ? { 'gen_ai.request.model': record.model } : {}),\n ...(record.provider ? { 'provider.name': record.provider } : {}),\n ...(record.sessionId\n ? {\n 'tangle.sessionId': record.sessionId,\n 'gen_ai.conversation.id': record.sessionId,\n }\n : {}),\n ...(record.harness ? { 'tangle.agent.harness': record.harness } : {}),\n ...(repository ? { 'vcs.repository.name': repository } : {}),\n ...(record.commitSha ? { 'vcs.ref.head.revision': record.commitSha } : {}),\n ...(record.timing\n ? {\n 'tangle.started_at_ms': record.timing.startedAt,\n 'tangle.completed_at_ms': record.timing.completedAt,\n 'tangle.duration_ms': record.timing.durationMs,\n }\n : {}),\n ...(record.tokens\n ? {\n 'gen_ai.usage.input_tokens': record.tokens.input,\n 'gen_ai.usage.output_tokens': record.tokens.output,\n ...(record.tokens.cachedInput !== undefined\n ? { 'gen_ai.usage.cache_read_input_tokens': record.tokens.cachedInput }\n : {}),\n ...(record.tokens.reasoning !== undefined\n ? { 'gen_ai.usage.reasoning_tokens': record.tokens.reasoning }\n : {}),\n }\n : {}),\n ...(typeof record.outcome.success === 'boolean'\n ? { 'tangle.outcome.success': record.outcome.success }\n : {}),\n ...(typeof record.outcome.score === 'number'\n ? { 'tangle.outcome.score': record.outcome.score }\n : {}),\n ...(record.error\n ? {\n 'error.type': record.error.code ?? record.error.name,\n 'error.message': serializeJson(redactor(record.error.message)),\n }\n : {}),\n ...(record.runtimeEvents\n ? { 'tangle.runtime.event_count': record.runtimeEvents.length }\n : {}),\n ...(record.candidateExecution\n ? {\n 'tangle.candidate.bundle_digest': record.candidateExecution.receipt.bundleDigest,\n 'tangle.candidate.experiment_digest':\n record.candidateExecution.materializationReceipt.executionPlan.material.runCell\n .experimentDigest,\n 'tangle.candidate.execution_id':\n record.candidateExecution.materializationReceipt.executionPlan.material.executionId,\n 'tangle.candidate.execution_plan_digest':\n record.candidateExecution.receipt.executionPlanDigest,\n 'tangle.candidate.materialization_receipt_digest':\n record.candidateExecution.receipt.materializationReceiptDigest,\n 'tangle.candidate.succeeded':\n record.candidateExecution.receipt.termination.kind === 'exit' &&\n record.candidateExecution.receipt.termination.exitCode === 0 &&\n record.candidateExecution.receipt.benchmarkResult.material.passed,\n 'tangle.candidate.run_receipt_digest': record.candidateExecution.receipt.digest,\n }\n : {}),\n }\n if (record.profile) {\n addPayloadAttributes(\n labels,\n 'tangle.agent.profile',\n redactor(record.profile),\n includeFullPayload,\n )\n if (record.profile.name) labels['gen_ai.agent.name'] = record.profile.name\n }\n const redactedInput = record.input !== undefined ? redactor(record.input) : undefined\n const redactedOutput = record.output !== undefined ? redactor(record.output) : undefined\n if (redactedInput !== undefined) {\n addPayloadAttributes(labels, 'tangle.input', redactedInput, includeFullPayload)\n }\n if (redactedOutput !== undefined) {\n addPayloadAttributes(labels, 'tangle.output', redactedOutput, includeFullPayload)\n }\n const now = Date.now()\n const runSpan = flatOtelSpan(\n 'tangle.intelligence.run',\n { 'tangle.runId': record.runId, ...labels },\n record.traceId,\n record.timing?.startedAt ?? now,\n undefined,\n record.timing?.completedAt ?? now,\n )\n ex.exportSpan(runSpan)\n if (record.runtimeEvents && record.runtimeEvents.length > 0) {\n const spans = buildRuntimeEventOtelSpans(\n record.runtimeEvents,\n record.traceId,\n runSpan.spanId,\n { ...config.runtimeTelemetry, redact: redactor },\n )\n for (const span of spans) ex.exportSpan(span)\n }\n // The loop topology (when present) exports under the SAME traceId, parented\n // under the run span — reusing the shipped builder, never a second one.\n if (record.loopEvents && record.loopEvents.length > 0) {\n const spans = buildLoopOtelSpans(\n record.loopEvents as ReadonlyArray<{\n kind: string\n runId: string\n timestamp: number\n payload: object\n }>,\n record.traceId,\n runSpan.spanId,\n )\n for (const span of spans) ex.exportSpan(span)\n }\n } catch {\n // Best-effort — a send failure must never fail the agent's turn.\n }\n return record.traceId\n }\n\n return {\n project: config.project,\n effort,\n exportRunRecord,\n freshRunId,\n freshTraceId,\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 // Send ships only with a tenant key — the honest \"will export actually\n // land\" signal (the base URL always resolves to the plane default).\n exportConfigured: Boolean(apiKey),\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"],"mappings":";;;;;;;;;;AAmCA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB;AA0HzB,MAAM,+BAA+B;AACrC,MAAM,0BAA0B;;;AAqBhC,SAAgB,2BAA2B,SAAqC;CAC9E,IAAI,SAAS,OAAO,QAAQ,QAAQ,QAAQ,EAAE;CAC9C,IAAI,OAAO,YAAY,eAAe,QAAQ,IAAI,yBAChD,OAAO,QAAQ,IAAI,wBAAwB,QAAQ,QAAQ,EAAE;CAE/D,OAAO;AACT;AAEA,SAAS,cAAc,QAAoC;CACzD,IAAI,QAAQ,OAAO;CACnB,IAAI,OAAO,YAAY,eAAe,QAAQ,IAAI,gBAChD,OAAO,QAAQ,IAAI;CACrB,OAAO;AACT;;AAGA,eAAe,aAAa,OAAuD;CACjF,MAAM,UAAU,MAAM,aAAc,WAAW;CAC/C,IAAI,CAAC,SACH,OAAO;EAAE,WAAW;EAAO,WAAW;EAAO,OAAO;CAAoC;CAE1F,MAAM,SAAS,cAAc,MAAM,MAAM;CACzC,IAAI,CAAC,QACH,OAAO;EACL,WAAW;EACX,WAAW;EACX,OAAO;CACT;CAGF,IAAI;EAUF,OAAO;GAAE,WAAW;GAAM,UAAA,MATH,QAAQ,GAAG,2BAA2B,MAAM,OAAO,IAAI,MAAM,QAAQ;IAC1F,GAAI,MAAM,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,MAAM,OAAO;IAC7D,SAAS;KACP,eAAe,UAAU;KACzB,GAAI,MAAM,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AAI;MAAE,OAAO,UAAU,WAAW;MAAG,SAAS;KAAU;IAC1D;GACF;EACF;EAEA,MAAM,QAAuB;GAC3B,MAAM,KAAK,YAAY;GACvB,IAAI,CAAC,IAAI;GACT,IAAI;IACF,MAAM,GAAG,MAAM;GACjB,QAAQ,CAER;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"intelligence.js","names":["canonicalCandidateDigest"],"sources":["../src/intelligence/delivery.ts","../src/intelligence/effort.ts","../src/intelligence/capability.ts","../src/intelligence/exact-process-candidate.ts","../src/intelligence/profile-activation.ts","../src/intelligence/resolver.ts","../src/intelligence/with-intelligence.ts","../src/intelligence/index.ts"],"sourcesContent":["/**\n *\n * Tangle Intelligence — the RECEIVE half of the loop (pull-by-default).\n *\n * The sibling Observe path (`./index`) sends run records 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 so an approved\n * improvement actually reaches the running agent. The pull carries three things\n * the plane already composes:\n * - the certified PROMPT surface + prompt-folding artifacts (delivered into the\n * system prompt via {@link composeCertifiedPrompt} — the promoted prompt);\n * - the typed profile DIFFS the plane has promoted, each with its held-out\n * provenance (surfaced as PROPOSALS — never auto-applied at runtime);\n * - the composed `agentProfile` those diffs fold to, for inspection.\n *\n * Pull contract (deployed plane): GET /v1/profiles/:target/composed →\n * { target, generatedAt,\n * promptSurface: {surface,surfaceHash,version,lift}|null,\n * artifacts: { <artifactType>: [{path,content,contentHash,version,lift,promotedAt}] },\n * capabilities: [{id,iface:{surface},binding:{path,content},provenance}],\n * agentProfileDiffs: [{diff, provenance:{version,lift,contentHash,promotedAt}}],\n * agentProfile: AgentProfile|null }\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 * @experimental\n */\n\nimport type {\n AgentImprovementProposal,\n AgentProfile,\n AgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport { verifyAgentImprovementProposal } from './improvement-cycle'\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 held-out provenance the plane's certify step stamps on a promoted diff.\n * `lift` is the held-out gate lift (e.g. \"+3.1pp\"), never a within-run claim. */\nexport interface DiffProvenance {\n version: number | null\n lift: string | null\n contentHash: string\n promotedAt: string\n}\n\n/**\n * A gate-certified profile diff the plane has already promoted, plus the\n * held-out provenance it carries. This is the previously-DROPPED typed diff the\n * composed endpoint returns; `withIntelligence` deserializes it and surfaces it\n * as a PROPOSAL — a human, or the gated local `improve()` loop, turns a proposal\n * into a shipped profile. It is NEVER auto-applied at runtime.\n */\nexport interface ProposedProfileDiff {\n diff: AgentProfileDiff\n provenance: DiffProvenance\n}\n\n/** The composed endpoint's per-capability summary — the narrow shape on the\n * wire (id + surface + path/content + provenance). Distinct from the richer\n * `CertifiedCapability` the capability resolver lowers a manifest into. */\nexport interface CertifiedCapabilitySummary {\n id: string\n iface: { surface: string }\n binding: { path: string | null; content: string }\n provenance: DiffProvenance\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 /** The typed profile diffs the plane has promoted, each with held-out\n * provenance. Surfaced as proposals; never auto-applied. Empty when none. */\n agentProfileDiffs: ProposedProfileDiff[]\n /** The composed capability summaries the plane returns. Empty when none. */\n capabilities: CertifiedCapabilitySummary[]\n /** The composed profile the promoted diffs fold to, for inspection. `null`\n * when no diffs are promoted. */\n agentProfile: AgentProfile | null\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 request after this many ms. Default 10000. */\n timeoutMs?: number\n}\n\n/** What Runtime knows about a failed proposal submission.\n * `not-sent` means no request began, `rejected` means Intelligence returned a\n * definitive 4xx response, and `unconfirmed` means the caller may safely retry\n * the same immutable proposal. */\nexport type AgentImprovementProposalSubmissionState = 'not-sent' | 'rejected' | 'unconfirmed'\n\n/** Submit a completed measured proposal for product-side review. */\nexport interface SubmitAgentImprovementProposalOptions {\n proposal: AgentImprovementProposal\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 request after this many ms. Default 10000. */\n timeoutMs?: number\n}\n\n/** Typed result for proposal submission. A successful result contains the\n * exact immutable proposal Intelligence recorded. */\nexport type SubmitAgentImprovementProposalOutcome =\n | { succeeded: true; value: AgentImprovementProposal; status: number }\n | {\n succeeded: false\n submission: AgentImprovementProposalSubmissionState\n error: string\n status?: number\n code?: string\n }\n\nconst defaultPlaneRequestTimeoutMs = 10_000\nconst maxPlaneErrorTextLength = 200\n\ntype PlaneRequestOptions = Pick<\n PullCertifiedOptions,\n 'apiKey' | 'baseUrl' | 'fetchImpl' | 'timeoutMs'\n>\n\ninterface PlaneRequestInput extends PlaneRequestOptions {\n path: string\n method?: 'POST'\n headers?: Record<string, string>\n body?: string\n}\n\ntype PlaneRequestResult =\n | { succeeded: true; response: Response }\n | { succeeded: false; attempted: false; error: string }\n | { succeeded: false; attempted: true; error: string }\n\n/** Resolve the ONE Intelligence base URL — the single knob both the send and\n * receive paths derive from. Env fallback: `TANGLE_INTELLIGENCE_URL`. */\nexport function resolveIntelligenceBaseUrl(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/** Make one authenticated request and retain whether the network call began. */\nasync function requestPlane(input: PlaneRequestInput): Promise<PlaneRequestResult> {\n const doFetch = input.fetchImpl ?? (globalThis.fetch as typeof fetch | undefined)\n if (!doFetch) {\n return { succeeded: false, attempted: false, error: 'no fetch implementation available' }\n }\n const apiKey = resolveApiKey(input.apiKey)\n if (!apiKey) {\n return {\n succeeded: false,\n attempted: false,\n error: 'no apiKey (set TANGLE_API_KEY or opts.apiKey)',\n }\n }\n\n try {\n const response = await doFetch(`${resolveIntelligenceBaseUrl(input.baseUrl)}${input.path}`, {\n ...(input.method === undefined ? {} : { method: input.method }),\n headers: {\n authorization: `Bearer ${apiKey}`,\n ...(input.headers ?? {}),\n },\n ...(input.body === undefined ? {} : { body: input.body }),\n signal: AbortSignal.timeout(input.timeoutMs ?? defaultPlaneRequestTimeoutMs),\n })\n return { succeeded: true, response }\n } catch (err) {\n return {\n succeeded: false,\n attempted: true,\n error: err instanceof Error ? err.message : String(err),\n }\n }\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === 'object' ? (value as Record<string, unknown>) : {}\n}\n\nfunction capPlaneErrorText(value: string): string {\n return value.slice(0, maxPlaneErrorTextLength)\n}\n\nfunction toDiffProvenance(value: unknown): DiffProvenance {\n const p = asRecord(value)\n return {\n version: typeof p.version === 'number' ? p.version : null,\n lift: typeof p.lift === 'string' ? p.lift : null,\n contentHash: typeof p.contentHash === 'string' ? p.contentHash : '',\n promotedAt: typeof p.promotedAt === 'string' ? p.promotedAt : '',\n }\n}\n\n/**\n * Deserialize the composed-endpoint response into a `CertifiedProfile`. The\n * previously-dropped `agentProfileDiffs`/`capabilities`/`agentProfile` are read\n * here so they round-trip to the consumer; a plane that has not yet promoted any\n * diffs simply yields empty arrays / a null profile (fail-closed, never a crash).\n */\nexport function normalizeCertifiedProfile(raw: unknown): CertifiedProfile {\n const r = asRecord(raw)\n const promptSurface = r.promptSurface ? (r.promptSurface as CertifiedPromptSurface) : null\n const artifacts = (r.artifacts as Record<string, CertifiedArtifact[]> | undefined) ?? {}\n const agentProfileDiffs: ProposedProfileDiff[] = Array.isArray(r.agentProfileDiffs)\n ? r.agentProfileDiffs.map((entry) => {\n const e = asRecord(entry)\n return { diff: e.diff as AgentProfileDiff, provenance: toDiffProvenance(e.provenance) }\n })\n : []\n const capabilities: CertifiedCapabilitySummary[] = Array.isArray(r.capabilities)\n ? (r.capabilities as CertifiedCapabilitySummary[])\n : []\n return {\n target: typeof r.target === 'string' ? r.target : '',\n generatedAt: typeof r.generatedAt === 'string' ? r.generatedAt : '',\n promptSurface,\n artifacts,\n agentProfileDiffs,\n capabilities,\n agentProfile: (r.agentProfile as AgentProfile | null | undefined) ?? null,\n }\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 request = await requestPlane({\n ...opts,\n path: `/v1/profiles/${encodeURIComponent(opts.target)}/composed`,\n })\n if (!request.succeeded) {\n return {\n succeeded: false,\n error: request.attempted ? `pull request failed: ${request.error}` : request.error,\n }\n }\n const res = request.response\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: normalizeCertifiedProfile(await res.json()) }\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 * Submit a completed Runtime proposal to Intelligence for product-side review.\n * This never runs an experiment, approves a proposal, or applies a candidate.\n * A 4xx response is a confirmed `rejected` request. Network failures, timeouts,\n * 5xx responses, and invalid success responses are `unconfirmed`, so callers\n * can retry the same digest because Intelligence stores proposals idempotently.\n */\nexport async function submitAgentImprovementProposal(\n opts: SubmitAgentImprovementProposalOptions,\n): Promise<SubmitAgentImprovementProposalOutcome> {\n let proposal: AgentImprovementProposal\n try {\n proposal = verifyAgentImprovementProposal(opts.proposal)\n } catch (err) {\n return {\n succeeded: false,\n submission: 'not-sent',\n error: `proposal validation failed: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n\n const request = await requestPlane({\n ...opts,\n path: '/v1/improvements/proposals',\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ proposal }),\n })\n if (!request.succeeded) {\n return {\n succeeded: false,\n submission: request.attempted ? 'unconfirmed' : 'not-sent',\n error: request.attempted\n ? `proposal submission request failed: ${request.error}`\n : request.error,\n }\n }\n const res = request.response\n\n if (!res.ok) {\n const body = await res.text().catch(() => '')\n let code: string | undefined\n let message = capPlaneErrorText(body)\n try {\n const parsed = asRecord(JSON.parse(body))\n if (typeof parsed.error === 'string') code = capPlaneErrorText(parsed.error)\n if (typeof parsed.message === 'string') message = capPlaneErrorText(parsed.message)\n } catch {\n // The response body is optional; the HTTP status still determines the outcome.\n }\n return {\n succeeded: false,\n submission: res.status >= 400 && res.status < 500 ? 'rejected' : 'unconfirmed',\n error: `proposal submission ${res.status}: ${message}`,\n status: res.status,\n ...(code === undefined ? {} : { code }),\n }\n }\n\n try {\n const response = asRecord(await res.json())\n const recorded = verifyAgentImprovementProposal(response.proposal)\n if (recorded.digest !== proposal.digest) {\n return {\n succeeded: false,\n submission: 'unconfirmed',\n error: 'proposal submission returned a different proposal digest',\n status: res.status,\n }\n }\n return { succeeded: true, value: recorded, status: res.status }\n } catch (err) {\n return {\n succeeded: false,\n submission: 'unconfirmed',\n error: `proposal submission response parse failed: ${capPlaneErrorText(\n err instanceof Error ? err.message : String(err),\n )}`,\n status: res.status,\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. Reads only the prompt-folding slice of a profile.\n */\nexport function composeCertifiedPrompt(\n base: string,\n certified: Pick<CertifiedProfile, 'promptSurface' | 'artifacts'> | null,\n): 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/** A cached, self-refreshing source of a target's certified prompt additions —\n * the prompt-only delivery lane for callers that assemble their OWN system\n * prompt (product chat routes) rather than wrapping an agent fn. Same\n * fail-closed semantics as {@link pullCertified}: pulls at most every\n * `refreshMs`, coalesces concurrent pulls, keeps the last-known profile on a\n * failed/404 pull, never throws, never blocks past the pull timeout. */\nexport interface CertifiedPromptSource {\n /** Refresh (window-respecting) then fold the certified additions into a\n * base system prompt. Returns `base` unchanged when nothing is promoted. */\n compose(base: string): Promise<string>\n /** The certified profile currently in effect (`null` = none pulled yet). */\n current(): CertifiedProfile | null\n /** Pull now if the refresh window has elapsed; coalesced and fail-closed. */\n refresh(): Promise<void>\n}\n\n/** Options for {@link createCertifiedPromptSource} — the pull coordinates plus\n * the refresh cadence. */\nexport interface CertifiedPromptSourceOptions extends PullCertifiedOptions {\n /** Min interval between certified-profile pulls. Default 5m. */\n refreshMs?: number\n}\n\n/**\n * Create the cached certified-prompt source — the ONE module-scope-cache +\n * coalesced-refresh + keep-last-known implementation. Product wiring uses this\n * rather than hand-rolling the same lines around `pullCertified`. The\n * `withIntelligence` hook rides this same source for its prompt delivery.\n */\nexport function createCertifiedPromptSource(\n opts: CertifiedPromptSourceOptions,\n): CertifiedPromptSource {\n const refreshMs = opts.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(opts)\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 return {\n refresh,\n current: () => certified,\n async compose(base: string): Promise<string> {\n await refresh()\n return composeCertifiedPrompt(base, certified)\n },\n }\n}\n","/**\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 * @experimental\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 *\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 * @experimental\n */\n\nimport type { AgentProfileMcpServer } from '@tangle-network/agent-interface'\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. `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","import type { TraceStore } from '@tangle-network/agent-eval'\nimport type { CandidateExperimentExecutionInput } from '@tangle-network/agent-eval/contract'\nimport type { CandidateExecutionEvidence } from '@tangle-network/agent-interface'\nimport type { AgentExactProcessResources } from '@tangle-network/agent-interface/environment-provider'\n\nimport type { AgentCandidateExecutionClaimStore } from '../candidate-execution/claim'\nimport { exactProcessProviderAsCandidateExecutor } from '../candidate-execution/exact-process-executor'\nimport type { PrepareAgentCandidateExecutionOptions } from '../candidate-execution/prepare'\nimport {\n type CreateProtectedAgentCandidateModelPortOptions,\n createProtectedAgentCandidateModelPort,\n} from '../candidate-execution/protected-model-port'\nimport type {\n AgentCandidateBenchmarkGraderPort,\n AgentCandidateExecutionPorts,\n AgentCandidateExecutorPort,\n AgentCandidateOutputArtifactPort,\n} from '../candidate-execution/types'\nimport { AGENT_CANDIDATE_EXECUTION_SUPPORT } from '../candidate-execution/verify'\nimport type {\n AgentEnvironmentProviderRef,\n AgentEnvironmentProviderRegistry,\n} from '../runtime/environment-provider'\nimport { resolveAgentEnvironmentProvider } from '../runtime/environment-provider'\nimport {\n type AgentCandidateExperimentCellPlacement,\n executeAgentCandidateExperimentCell,\n} from './improvement-cycle'\n\n/** Candidate surfaces implemented by the neutral exact-process executor. */\nexport const exactProcessCandidateExperimentExecutionSupport = Object.freeze({\n outcomes: Object.freeze(['output'] as const),\n outputMediaTypes: Object.freeze(['text/*', 'application/json', '*+json'] as const),\n code: Object.freeze(['disabled'] as const),\n memory: Object.freeze(['disabled'] as const),\n knowledge: true,\n profile: AGENT_CANDIDATE_EXECUTION_SUPPORT.profile,\n isolation: Object.freeze({\n freshEnvironment: true,\n exactProcess: true,\n egress: Object.freeze(['blocked', 'strict'] as const),\n }),\n})\n\nexport interface CreateExactProcessCandidateExperimentExecutorOptions {\n provider: AgentEnvironmentProviderRef\n providerRegistry?: AgentEnvironmentProviderRegistry\n resources: AgentExactProcessResources\n providerOptions?: Record<string, unknown>\n provisionTimeoutMs?: number\n recoveryRetentionMs?: number\n ports: AgentCandidateExecutionPorts\n grader: AgentCandidateBenchmarkGraderPort\n outputArtifacts: AgentCandidateOutputArtifactPort\n traceStore: TraceStore\n claimStore: AgentCandidateExecutionClaimStore\n cleanupTimeoutMs?: number\n resultTimeoutMs?: number\n}\n\n/** Product-owned candidate ports other than protected model access. */\nexport type AgentCandidateExecutionHostPorts = Omit<AgentCandidateExecutionPorts, 'models'>\n\n/**\n * Builds the standard exact-process executor with model access that is scoped,\n * metered, and settled by the caller's grant service.\n */\nexport interface CreateProtectedExactProcessCandidateExperimentExecutorOptions\n extends Omit<CreateExactProcessCandidateExperimentExecutorOptions, 'ports'> {\n hostPorts: AgentCandidateExecutionHostPorts\n model: CreateProtectedAgentCandidateModelPortOptions\n}\n\nexport interface ExactProcessCandidateExperimentExecution\n extends CandidateExperimentExecutionInput {\n executionId: string\n attempt?: number\n executionRoots: AgentCandidateExperimentCellPlacement['executionRoots']\n stagingRoots: AgentCandidateExperimentCellPlacement['stagingRoots']\n preparation?: PrepareAgentCandidateExecutionOptions\n}\n\nexport interface ExactProcessCandidateExperimentExecutor {\n /** Runtime's expired-attempt path reuses this port only to stop and dispose. */\n readonly executor: AgentCandidateExecutorPort\n execute(input: ExactProcessCandidateExperimentExecution): Promise<CandidateExecutionEvidence>\n}\n\n/** Exact-process executor plus the ports required for durable recovery. */\nexport interface ProtectedExactProcessCandidateExperimentExecutor\n extends ExactProcessCandidateExperimentExecutor {\n readonly recoveryPorts: Pick<AgentCandidateExecutionPorts, 'models' | 'memory'>\n}\n\n/** Execute one signed experiment cell through any declared exact-process provider. */\nexport function createExactProcessCandidateExperimentExecutor(\n options: CreateExactProcessCandidateExperimentExecutorOptions,\n): ExactProcessCandidateExperimentExecutor {\n const provider = resolveAgentEnvironmentProvider(options.provider, options.providerRegistry)\n const executor = exactProcessProviderAsCandidateExecutor({\n provider,\n resources: options.resources,\n ...(options.providerOptions ? { providerOptions: options.providerOptions } : {}),\n ...(options.provisionTimeoutMs === undefined\n ? {}\n : { provisionTimeoutMs: options.provisionTimeoutMs }),\n ...(options.recoveryRetentionMs === undefined\n ? {}\n : { recoveryRetentionMs: options.recoveryRetentionMs }),\n })\n return Object.freeze({\n executor,\n async execute(\n input: ExactProcessCandidateExperimentExecution,\n ): Promise<CandidateExecutionEvidence> {\n return await executeAgentCandidateExperimentCell({\n ...input,\n attempt: input.attempt ?? 1,\n executionId: input.executionId,\n executionRoots: input.executionRoots,\n stagingRoots: input.stagingRoots,\n ports: options.ports,\n ...(input.preparation ? { preparation: input.preparation } : {}),\n execution: {\n executor,\n grader: options.grader,\n outputArtifacts: options.outputArtifacts,\n traceStore: options.traceStore,\n claimStore: options.claimStore,\n ...(options.cleanupTimeoutMs === undefined\n ? {}\n : { cleanupTimeoutMs: options.cleanupTimeoutMs }),\n ...(options.resultTimeoutMs === undefined\n ? {}\n : { resultTimeoutMs: options.resultTimeoutMs }),\n },\n })\n },\n })\n}\n\n/** Compose host-owned execution ports with protected model access for one exact-process run. */\nexport function createProtectedExactProcessCandidateExperimentExecutor(\n options: CreateProtectedExactProcessCandidateExperimentExecutorOptions,\n): ProtectedExactProcessCandidateExperimentExecutor {\n const { hostPorts, model, ...exactProcess } = options\n const ports = Object.freeze({\n ...hostPorts,\n models: createProtectedAgentCandidateModelPort(model),\n })\n const execution = createExactProcessCandidateExperimentExecutor({\n ...exactProcess,\n ports,\n })\n return Object.freeze({\n ...execution,\n recoveryPorts: Object.freeze({ models: ports.models, memory: ports.memory }),\n })\n}\n","import type {\n AgentImprovementActivationTargetState,\n AgentImprovementActivationTargetTransition,\n AgentProfile,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { agentProfileImprovementArmSchema } from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport {\n applyExactAgentProfileDiff,\n omitUndefinedObjectFields,\n parseExactAgentProfile,\n} from '../candidate-execution/profile'\nimport type {\n AgentImprovementActivationTargetPlan,\n ProfileImprovementActivationTransitionInput,\n} from './activation'\nimport {\n type AgentImprovementProfileSurface,\n agentImprovementProfileSurfaceDigest,\n agentImprovementTargetProfileDiffs,\n assertProfileImprovementTargetsShareIdentity,\n isAgentImprovementProfileSurface,\n} from './improvement-surfaces'\n\nexport type AgentImprovementProfileActivationTarget = Omit<\n AgentImprovementActivationTargetPlan,\n 'surface'\n> & {\n surface: AgentImprovementProfileSurface\n}\n\nexport type AgentImprovementProfileTargetState = Omit<\n AgentImprovementActivationTargetState,\n 'surface'\n> & { surface: AgentImprovementProfileSurface }\n\nexport type AgentImprovementProfileTargetTransition = Omit<\n AgentImprovementActivationTargetTransition,\n 'surface'\n> & { surface: AgentImprovementProfileSurface }\n\nexport interface AgentImprovementProfileReplacement {\n identity: string\n profile: AgentProfile\n}\n\nexport interface AgentImprovementProfileStateDigestInput {\n identity: string\n profile: AgentProfile\n}\n\n/** Product-defined hash of the complete profile state that actually runs. */\nexport type AgentImprovementProfileStateDigest = (\n input: AgentImprovementProfileStateDigestInput,\n) => Sha256Digest\n\nexport interface AgentImprovementProfileStateResolverInput {\n identity: string\n stateDigest: Sha256Digest\n}\n\n/** Product-owned retained-state lookup used only for an explicit restore. */\nexport type AgentImprovementProfileStateResolver = (\n input: AgentImprovementProfileStateResolverInput,\n) => AgentProfile | undefined\n\nexport type AgentImprovementProfileActivationInput =\n | {\n currentByIdentity: ReadonlyMap<string, AgentProfile>\n targets: readonly [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ]\n }\n | {\n currentByIdentity: ReadonlyMap<string, AgentProfile>\n profileTransition: ProfileImprovementActivationTransitionInput\n stateDigest: AgentImprovementProfileStateDigest\n resolveState?: AgentImprovementProfileStateResolver\n }\n\nexport type AgentImprovementProfileActivationPreparation =\n | {\n status: 'missing'\n identities: readonly string[]\n }\n | {\n status: 'unavailable'\n code: 'PROFILE_STATE_UNAVAILABLE'\n identities: readonly string[]\n requiredStateDigest: Sha256Digest\n }\n | {\n status: 'already-applied' | 'conflict'\n targets: [AgentImprovementProfileTargetState, ...AgentImprovementProfileTargetState[]]\n }\n | {\n status: 'apply'\n replacements: [AgentImprovementProfileReplacement, ...AgentImprovementProfileReplacement[]]\n targets: [\n AgentImprovementProfileTargetTransition,\n ...AgentImprovementProfileTargetTransition[],\n ]\n }\n\ninterface CurrentProfiles {\n identities: string[]\n byIdentity: Map<string, AgentProfile>\n}\n\n/**\n * Compare product-owned profiles with an exact measured transition and prepare\n * all-or-none replacements. The product owns locking, persistence, and retained\n * state; Runtime owns the profile diff semantics and digest checks.\n */\nexport function prepareAgentImprovementProfileActivation(\n input: AgentImprovementProfileActivationInput,\n): AgentImprovementProfileActivationPreparation {\n const targets =\n 'profileTransition' in input ? profileTargets(input.profileTransition.targets) : input.targets\n assertUniqueProfileTargets(targets)\n const current = readCurrentProfiles(input.currentByIdentity, targets)\n if ('status' in current) return immutableCandidateValue(current)\n\n if ('profileTransition' in input) {\n return prepareProfileImprovementActivation(input, targets, current)\n }\n return prepareSurfaceReplacementActivation(targets, current)\n}\n\nfunction prepareSurfaceReplacementActivation(\n targets: readonly [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ],\n currentProfiles: CurrentProfiles,\n): AgentImprovementProfileActivationPreparation {\n const current = targets.map((target) => {\n const profile = currentProfiles.byIdentity.get(target.identity)\n if (!profile) throw new Error(`missing agent profile ${target.identity}`)\n return {\n target,\n currentDigest: agentImprovementProfileSurfaceDigest(profile, target.surface),\n }\n })\n const states = targetStates(current)\n\n if (current.every(({ target, currentDigest }) => currentDigest === target.desiredDigest)) {\n return immutableCandidateValue({ status: 'already-applied', targets: states })\n }\n if (current.some(({ target, currentDigest }) => currentDigest !== target.expectedBaseDigest)) {\n return immutableCandidateValue({ status: 'conflict', targets: states })\n }\n\n const profiles = new Map<string, AgentProfile>()\n for (const identity of currentProfiles.identities) {\n const currentProfile = currentProfiles.byIdentity.get(identity)\n if (!currentProfile) throw new Error(`missing agent profile ${identity}`)\n const profile = targets\n .filter((target) => target.identity === identity)\n .flatMap((target) =>\n agentImprovementTargetProfileDiffs(target, {\n id: `${target.identity}:${target.desiredDigest}`,\n metadata: { identity },\n }),\n )\n .reduce(\n (value, diff) =>\n applyExactAgentProfileDiff(value, diff, `agent profile activation ${identity}`),\n currentProfile,\n )\n profiles.set(identity, immutableCandidateValue(profile))\n }\n\n for (const target of targets) {\n const profile = profiles.get(target.identity)\n if (\n !profile ||\n agentImprovementProfileSurfaceDigest(profile, target.surface) !== target.desiredDigest\n ) {\n throw new Error(\n `agent profile activation did not produce ${target.identity}:${target.surface}`,\n )\n }\n }\n return appliedProfileReplacement(currentProfiles.identities, profiles, targets)\n}\n\nfunction prepareProfileImprovementActivation(\n input: Extract<AgentImprovementProfileActivationInput, { profileTransition: unknown }>,\n targets: readonly [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ],\n currentProfiles: CurrentProfiles,\n): AgentImprovementProfileActivationPreparation {\n const transition = input.profileTransition\n assertProfileTransitionTargets(transition, targets)\n const current = targets.map((target) => {\n const profile = currentProfiles.byIdentity.get(target.identity)\n if (!profile) throw new Error(`missing agent profile ${target.identity}`)\n return {\n target,\n currentDigest: profileStateDigest(input.stateDigest, target.identity, profile),\n }\n })\n const states = targetStates(current)\n\n if (current.every(({ currentDigest }) => currentDigest === transition.desiredStateDigest)) {\n return immutableCandidateValue({ status: 'already-applied', targets: states })\n }\n if (current.some(({ currentDigest }) => currentDigest !== transition.sourceStateDigest)) {\n return immutableCandidateValue({ status: 'conflict', targets: states })\n }\n\n const profiles = new Map<string, AgentProfile>()\n for (const identity of currentProfiles.identities) {\n const currentProfile = currentProfiles.byIdentity.get(identity)\n if (!currentProfile) throw new Error(`missing agent profile ${identity}`)\n const profile =\n transition.operation.kind === 'apply-change'\n ? transition.operation.changes.reduce(\n (value, diff) =>\n applyExactAgentProfileDiff(value, diff, `profile improvement activation ${identity}`),\n currentProfile,\n )\n : restoreProfileState(input.resolveState, identity, transition.desiredStateDigest)\n if (!profile) {\n return immutableCandidateValue({\n status: 'unavailable',\n code: 'PROFILE_STATE_UNAVAILABLE',\n identities: currentProfiles.identities,\n requiredStateDigest: transition.desiredStateDigest,\n })\n }\n const parsed = parseExactAgentProfile(\n omitUndefinedObjectFields(profile, `profile improvement activation ${identity}`),\n `profile improvement activation ${identity}`,\n )\n if (profileStateDigest(input.stateDigest, identity, parsed) !== transition.desiredStateDigest) {\n throw new Error(`profile improvement activation did not produce ${identity}`)\n }\n profiles.set(identity, immutableCandidateValue(parsed))\n }\n\n return appliedProfileReplacement(currentProfiles.identities, profiles, targets)\n}\n\nfunction restoreProfileState(\n resolveState: AgentImprovementProfileStateResolver | undefined,\n identity: string,\n stateDigest: Sha256Digest,\n): AgentProfile | undefined {\n return resolveState?.({ identity, stateDigest })\n}\n\nfunction assertProfileTransitionTargets(\n transition: ProfileImprovementActivationTransitionInput,\n targets: readonly AgentImprovementProfileActivationTarget[],\n): void {\n assertProfileImprovementTargetsShareIdentity(targets)\n const operationDigest = canonicalCandidateDigest(transition.operation)\n if (\n targets.some(\n (target) =>\n target.expectedBaseDigest !== transition.sourceStateDigest ||\n target.desiredDigest !== transition.desiredStateDigest ||\n canonicalCandidateDigest(target.desiredInput) !== operationDigest,\n )\n ) {\n throw new Error('profile improvement targets do not match their transition')\n }\n}\n\nfunction appliedProfileReplacement(\n identities: readonly string[],\n profiles: ReadonlyMap<string, AgentProfile>,\n targets: readonly [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ],\n): AgentImprovementProfileActivationPreparation {\n return immutableCandidateValue({\n status: 'apply',\n replacements: identities.map((identity) => {\n const profile = profiles.get(identity)\n if (!profile) throw new Error(`missing prepared agent profile ${identity}`)\n return { identity, profile }\n }) as [AgentImprovementProfileReplacement, ...AgentImprovementProfileReplacement[]],\n targets: targets.map((target) => ({\n surface: target.surface,\n identity: target.identity,\n beforeDigest: target.expectedBaseDigest,\n afterDigest: target.desiredDigest,\n })) as [AgentImprovementProfileTargetTransition, ...AgentImprovementProfileTargetTransition[]],\n })\n}\n\nfunction targetStates(\n current: readonly {\n target: AgentImprovementProfileActivationTarget\n currentDigest: Sha256Digest\n }[],\n): [AgentImprovementProfileTargetState, ...AgentImprovementProfileTargetState[]] {\n const first = current[0]\n if (!first) throw new Error('agent profile activation requires a target')\n return current.map(({ target, currentDigest }) => ({\n surface: target.surface,\n identity: target.identity,\n currentDigest,\n })) as [AgentImprovementProfileTargetState, ...AgentImprovementProfileTargetState[]]\n}\n\nfunction profileStateDigest(\n stateDigest: AgentImprovementProfileStateDigest,\n identity: string,\n profile: AgentProfile,\n): Sha256Digest {\n return agentProfileImprovementArmSchema.parse({ stateDigest: stateDigest({ identity, profile }) })\n .stateDigest\n}\n\nfunction readCurrentProfiles(\n currentByIdentity: ReadonlyMap<string, AgentProfile>,\n targets: readonly AgentImprovementProfileActivationTarget[],\n): CurrentProfiles | { status: 'missing'; identities: string[] } {\n const identities = [...new Set(targets.map((target) => target.identity))].sort()\n const missing = identities.filter((identity) => !currentByIdentity.has(identity))\n if (missing.length > 0) return { status: 'missing', identities: missing }\n return {\n identities,\n byIdentity: new Map(\n identities.map((identity) => {\n const profile = currentByIdentity.get(identity)\n if (!profile) throw new Error(`missing agent profile ${identity}`)\n const label = `agent profile activation ${identity}`\n return [identity, parseExactAgentProfile(omitUndefinedObjectFields(profile, label), label)]\n }),\n ),\n }\n}\n\nfunction profileTargets(\n targets: readonly AgentImprovementActivationTargetPlan[],\n): [AgentImprovementProfileActivationTarget, ...AgentImprovementProfileActivationTarget[]] {\n if (!targets.every((target) => isAgentImprovementProfileSurface(target.surface))) {\n throw new Error('agent profile activation contains an unsupported surface')\n }\n const first = targets[0]\n if (!first) throw new Error('agent profile activation requires a target')\n return targets as [\n AgentImprovementProfileActivationTarget,\n ...AgentImprovementProfileActivationTarget[],\n ]\n}\n\nfunction assertUniqueProfileTargets(\n targets: readonly AgentImprovementProfileActivationTarget[],\n): void {\n const targetKeys = targets.map((target) => `${target.identity}\\u0000${target.surface}`)\n if (new Set(targetKeys).size !== targetKeys.length) {\n throw new Error('agent profile activation repeats a target')\n }\n}\n","/**\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 * @experimental\n */\n\nimport type { AgentProfileMcpServer } from '@tangle-network/agent-interface'\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 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 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 *\n * `withIntelligence` — the ONE agent-runtime hook that unifies Tangle\n * Intelligence send + receive.\n *\n * It does two things per call, both fail-open:\n * 1. RECEIVE — pull the tenant's certified profile from the deployed plane\n * (cached + refreshed), hand the agent the certified prompt surface to fold\n * (`applied.composePrompt`) and the promoted, gate-certified profile DIFFS\n * as PROPOSALS (`applied.proposals` / `applied.applyProfile`).\n * 2. SEND — serialize a typed {@link RunRecord} for the call through the shipped\n * OTLP builders to the plane's `/v1/otlp` ingest, best-effort.\n *\n * SAFETY — observe + deliver ONLY. This hook NEVER auto-applies a received diff\n * at runtime. A promoted diff is surfaced as a proposal; a human, or the gated\n * local `improve()` loop, turns a proposal into a shipped profile. That\n * preserves the held-out invariant the plane enforces — a runtime that silently\n * folded an un-gated diff into itself would defeat the very gate the diff cleared.\n *\n * import { withIntelligence } from '@tangle-network/agent-runtime/intelligence'\n *\n * export const agent = withIntelligence(\n * async (input, applied) => {\n * const out = await myAgent(input, { systemPrompt: applied.composePrompt(BASE) })\n * applied.record({ success: true, usage: { inferenceUsd: 0.002, intelligenceUsd: 0 } })\n * return out\n * },\n * { project: 'support-agent', target: 'support-agent' },\n * )\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { applyAgentProfileDiff } from '@tangle-network/agent-interface'\nimport {\n type CertifiedProfile,\n composeCertifiedPrompt,\n createCertifiedPromptSource,\n type ProposedProfileDiff,\n} from './delivery'\nimport {\n createIntelligenceClient,\n type IntelligenceConfig,\n type RunRecord,\n type RunReport,\n} from './index'\n\n/** What the hook hands the agent each run. Additive over the prompt-only\n * delivery: `composePrompt` folds the certified prompt surface (as before);\n * `proposals`/`applyProfile` surface the promoted profile DIFFS — never\n * auto-applied; `record` enriches the {@link RunRecord} that is sent. */\nexport interface AppliedIntelligence {\n /** Stable ids shared by the run span and every nested runtime/loop span. */\n runId: string\n traceId: string\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 (the promoted\n * prompt). The consumer opts in by calling it. */\n composePrompt(base: string): string\n /** The promoted, gate-certified profile diffs — surfaced for a human or the\n * gated `improve()` loop. NEVER auto-applied by this hook. Empty when none. */\n proposals: ProposedProfileDiff[]\n /** Fold every proposal into `base` via `applyAgentProfileDiff`, in promotion\n * order, and return the result. The caller invokes this EXPLICITLY (it is the\n * human/gated apply step) — the hook never calls it on the run path. */\n applyProfile(base: AgentProfile): AgentProfile\n /** Enrich the {@link RunRecord} sent for this call — outcome, usage split,\n * model/provider, and the loop event stream. Optional; an un-recorded run\n * still sends input/output with an inference-only zero usage split. */\n record(report: RunReport): void\n}\n\n/** An agent wrapped by {@link withIntelligence}: receives the input plus the\n * intelligence delivered for this run. */\nexport type IntelligenceAgent<I, O> = (input: I, applied: AppliedIntelligence) => Promise<O>\n\n/** `withIntelligence` config = the Observe config plus the pull target, refresh\n * cadence, and a proposals callback. One base URL (`baseUrl` /\n * `TANGLE_INTELLIGENCE_URL`) drives both the send and receive paths. */\nexport interface IntelligenceHookConfig extends IntelligenceConfig {\n /** Pull target. Defaults to `project`. */\n target?: 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 /** Notified when a refresh delivers a NEW set of promoted proposals (by\n * provenance content hash). Surfaces diffs without auto-applying them. */\n onProposals?: (proposals: ProposedProfileDiff[]) => void\n}\n\n/** The wrapped agent — same `(input) => Promise<output>` shape, plus a manual\n * `refresh()` and a `proposals()` accessor for the currently-promoted diffs. */\nexport type IntelligenceWrapped<I, O> = ((input: I) => Promise<O>) & {\n refresh(): Promise<void>\n proposals(): ProposedProfileDiff[]\n /** Flush buffered trace spans before a short-lived process exits. */\n flush(): Promise<void>\n}\n\ninterface RuntimeEventSummary {\n inferenceUsd: number\n inputTokens: number\n outputTokens: number\n model?: string\n sessionId?: string\n success?: boolean\n error?: RunRecord['error']\n}\n\nfunction summarizeRuntimeEvents(\n events: NonNullable<RunReport['runtimeEvents']>,\n): RuntimeEventSummary {\n const summary: RuntimeEventSummary = { inferenceUsd: 0, inputTokens: 0, outputTokens: 0 }\n for (const event of events) {\n if ('session' in event && event.session) summary.sessionId = event.session.id\n if (event.type === 'llm_call') {\n summary.model = event.model\n summary.inferenceUsd += event.costUsd ?? 0\n summary.inputTokens += event.tokensIn ?? 0\n summary.outputTokens += event.tokensOut ?? 0\n } else if (event.type === 'backend_error') {\n summary.success = false\n summary.error = {\n name: event.error?.kind ?? 'BackendError',\n message: event.message,\n ...(event.error?.status !== undefined ? { code: String(event.error.status) } : {}),\n }\n } else if (event.type === 'final') {\n summary.success = event.status === 'completed'\n if (event.error) {\n summary.error = {\n name: event.error.kind,\n message: event.error.message,\n ...(event.error.status !== undefined ? { code: String(event.error.status) } : {}),\n }\n }\n }\n }\n return summary\n}\n\nfunction runError(cause: unknown): NonNullable<RunRecord['error']> {\n if (cause instanceof Error) {\n const code = (cause as Error & { code?: unknown }).code\n return {\n name: cause.name || 'Error',\n message: cause.message,\n ...(typeof code === 'string' || typeof code === 'number' ? { code: String(code) } : {}),\n }\n }\n return { name: 'Error', message: String(cause) }\n}\n\n/**\n * Wrap an agent so it (a) RECEIVES the tenant's certified profile — the prompt\n * surface to fold and the promoted profile diffs as proposals — and (b) SENDS a\n * typed {@link RunRecord} per call to the plane. The pull is cached and refreshed\n * at most every `refreshMs`; a failed pull is fail-closed (the agent runs on its\n * base surface, never breaks because Intelligence is unreachable). The send is\n * best-effort — an export failure never fails the agent's turn — while an error\n * thrown by the agent itself propagates unchanged.\n */\nexport function withIntelligence<I, O>(\n agent: IntelligenceAgent<I, O>,\n config: IntelligenceHookConfig,\n): IntelligenceWrapped<I, O> {\n const client = createIntelligenceClient(config)\n const target = config.target ?? config.project\n const source = createCertifiedPromptSource({\n target,\n ...(config.apiKey !== undefined ? { apiKey: config.apiKey } : {}),\n ...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl } : {}),\n ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),\n ...(config.fetchImpl !== undefined ? { fetchImpl: config.fetchImpl } : {}),\n ...(config.refreshMs !== undefined ? { refreshMs: config.refreshMs } : {}),\n })\n\n const currentProposals = (): ProposedProfileDiff[] => source.current()?.agentProfileDiffs ?? []\n\n // Fire `onProposals` only when the promoted set actually changes (keyed by\n // provenance content hash) — a refresh that re-delivers the same diffs is silent.\n let lastSignal = ''\n function signalProposals(): void {\n const proposals = currentProposals()\n if (proposals.length === 0) return\n const sig = proposals.map((p) => p.provenance.contentHash).join('|')\n if (sig === lastSignal) return\n lastSignal = sig\n config.onProposals?.(proposals)\n }\n\n async function refresh(): Promise<void> {\n await source.refresh()\n signalProposals()\n }\n\n const wrapped = (async (input: I): Promise<O> => {\n const runId = client.freshRunId()\n const traceId = client.freshTraceId()\n const startedAt = Date.now()\n await refresh()\n const certified = source.current()\n const proposals = currentProposals()\n const report: RunReport = {}\n const applied: AppliedIntelligence = {\n runId,\n traceId,\n certified,\n composePrompt: (base: string) => composeCertifiedPrompt(base, certified),\n proposals,\n applyProfile: (base: AgentProfile) =>\n proposals.reduce((profile, p) => applyAgentProfileDiff(profile, p.diff), base),\n record: (r: RunReport) => Object.assign(report, r),\n }\n\n function exportCompleted(output: unknown, caught?: unknown): void {\n const completedAt = Date.now()\n const eventSummary = summarizeRuntimeEvents(report.runtimeEvents ?? [])\n const error = report.error ?? (caught !== undefined ? runError(caught) : eventSummary.error)\n const tokens =\n report.tokens ??\n (eventSummary.inputTokens > 0 || eventSummary.outputTokens > 0\n ? { input: eventSummary.inputTokens, output: eventSummary.outputTokens }\n : undefined)\n const profile = report.profile ?? config.profile\n const record: RunRecord = {\n runId,\n traceId,\n project: config.project,\n target,\n input,\n output,\n outcome: {\n success:\n report.success ??\n (caught !== undefined ? false : (eventSummary.success ?? error === undefined)),\n ...(report.score !== undefined ? { score: report.score } : {}),\n usage: {\n inferenceUsd: report.usage?.inferenceUsd ?? report.costUsd ?? eventSummary.inferenceUsd,\n intelligenceUsd: report.usage?.intelligenceUsd ?? 0,\n },\n },\n timing: { startedAt, completedAt, durationMs: completedAt - startedAt },\n ...((report.model ?? eventSummary.model)\n ? { model: report.model ?? eventSummary.model }\n : {}),\n ...(report.provider !== undefined ? { provider: report.provider } : {}),\n ...(report.loopEvents !== undefined ? { loopEvents: report.loopEvents } : {}),\n ...(report.runtimeEvents !== undefined ? { runtimeEvents: report.runtimeEvents } : {}),\n ...(profile !== undefined ? { profile } : {}),\n ...((report.sessionId ?? eventSummary.sessionId)\n ? { sessionId: report.sessionId ?? eventSummary.sessionId }\n : {}),\n ...((report.harness ?? profile?.harness)\n ? { harness: report.harness ?? profile?.harness }\n : {}),\n ...((report.commitSha ?? config.commitSha)\n ? { commitSha: report.commitSha ?? config.commitSha }\n : {}),\n ...(tokens !== undefined ? { tokens } : {}),\n ...(error !== undefined ? { error } : {}),\n ...(report.candidateExecution !== undefined\n ? { candidateExecution: report.candidateExecution }\n : {}),\n }\n client.exportRunRecord(record)\n }\n\n try {\n const output = await agent(input, applied)\n exportCompleted(output)\n return output\n } catch (cause) {\n exportCompleted(undefined, cause)\n throw cause\n }\n }) as IntelligenceWrapped<I, O>\n\n wrapped.refresh = refresh\n wrapped.proposals = currentProposals\n wrapped.flush = client.flush\n return wrapped\n}\n","/**\n *\n * Tangle Intelligence SDK — trace capture plus reviewable improvement.\n *\n * The client keeps live-agent trace delivery best-effort. The separate\n * improvement-cycle exports analyze completed traces, run a signed baseline\n * versus candidate experiment, bind review to its result, and activate only\n * the exact measured candidate.\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 * @experimental\n */\n\nimport { contentHash } from '@tangle-network/agent-eval'\nimport type { AgentProfile, CandidateExecutionEvidence } from '@tangle-network/agent-interface'\nimport {\n buildLoopOtelSpans,\n buildRuntimeEventOtelSpans,\n createOtelExporter,\n flatOtelSpan,\n type OtelExporter,\n} from '../otel-export'\nimport { type Redactor, resolveRedactor } from '../redact'\nimport type { LoopTraceEvent } from '../runtime/types'\nimport type { RuntimeTelemetryOptions } from '../sanitize'\nimport type { RuntimeStreamEvent } from '../types'\nimport { resolveIntelligenceBaseUrl } from './delivery'\nimport {\n defaultEffortTier,\n type EffortOverrides,\n type EffortSettings,\n type EffortTier,\n isIntelligenceOff,\n resolveEffort,\n} from './effort'\n\nexport type {\n AgentCandidateProfileActivation as CandidateProfileMaterialization,\n AgentImprovementActivation,\n AgentImprovementActivationIntent,\n AgentImprovementActivationOutcome,\n AgentImprovementActivationResult,\n AgentImprovementEvaluation,\n AgentImprovementMeasuredComparison,\n AgentImprovementProposal,\n AgentImprovementReview,\n AgentImprovementReviewDecision,\n CandidateExecutionEvidence,\n} from '@tangle-network/agent-interface'\nexport { parseAgentCandidateProfileActivation as parseCandidateProfileMaterialization } from '../candidate-execution/profile'\nexport type { Redactor } from '../redact'\nexport { defaultRedactor, resolveRedactor } from '../redact'\nexport type {\n AgentImprovementActivationReconciliation,\n AgentImprovementActivationResultStore,\n AgentImprovementActivationTargetPlan,\n AgentImprovementActivationTransition,\n AgentImprovementActivationTransitionInput,\n AgentProfileImprovementActivationOperation,\n AgentProfileImprovementActivationTargetPlan,\n CreateAgentImprovementActivationResultOptions,\n ExecuteAgentImprovementActivationInput,\n ExecuteAgentImprovementActivationOptions,\n ProfileImprovementActivationTransitionInput,\n SealedCandidateActivationTransitionInput,\n} from './activation'\nexport {\n createAgentImprovementActivationResult,\n executeAgentImprovementActivation,\n verifyAgentImprovementActivationResult,\n} from './activation'\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 AgentImprovementProposalSubmissionState,\n CertifiedArtifact,\n CertifiedCapabilitySummary,\n CertifiedProfile,\n CertifiedPromptSource,\n CertifiedPromptSourceOptions,\n CertifiedPromptSurface,\n DiffProvenance,\n ProposedProfileDiff,\n PullCertifiedOptions,\n PullOutcome,\n SubmitAgentImprovementProposalOptions,\n SubmitAgentImprovementProposalOutcome,\n} from './delivery'\nexport {\n composeCertifiedPrompt,\n createCertifiedPromptSource,\n normalizeCertifiedProfile,\n pullCertified,\n resolveIntelligenceBaseUrl,\n submitAgentImprovementProposal,\n} 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 {\n AgentCandidateExecutionHostPorts,\n CreateExactProcessCandidateExperimentExecutorOptions,\n CreateProtectedExactProcessCandidateExperimentExecutorOptions,\n ExactProcessCandidateExperimentExecution,\n ExactProcessCandidateExperimentExecutor,\n ProtectedExactProcessCandidateExperimentExecutor,\n} from './exact-process-candidate'\nexport {\n createExactProcessCandidateExperimentExecutor,\n createProtectedExactProcessCandidateExperimentExecutor,\n exactProcessCandidateExperimentExecutionSupport,\n} from './exact-process-candidate'\nexport type {\n AgentCandidateExperimentCellPlacement,\n AgentImprovementAnalysisOptions,\n AgentImprovementExperimentMaterial,\n AgentProfileImprovementBenchmark,\n AgentProfileImprovementExecutor,\n AgentProfileImprovementMethodOptions,\n CreateAgentImprovementActivationOptions,\n CreateAgentImprovementProposalOptions,\n ExecuteAgentCandidateExperimentCellOptions,\n ProposeAgentImprovementOptions,\n ProposeAgentImprovementResult,\n ProposeAgentProfileImprovementOptions,\n ProposeAgentProfileImprovementResult,\n ReviewAgentImprovementInput,\n RunAgentCandidateExperimentOptions,\n RunAgentCandidateExperimentResult,\n VerifyCandidateExecutionEvidenceOptions,\n} from './improvement-cycle'\nexport {\n AgentCandidateExperimentCellExecutionError,\n createAgentImprovementActivation,\n createAgentImprovementMeasuredComparison,\n createAgentImprovementProposal,\n executeAgentCandidateExperimentCell,\n proposeAgentImprovement,\n proposeAgentProfileImprovement,\n reviewAgentImprovementProposal,\n runAgentCandidateExperiment,\n verifyAgentImprovementActivation,\n verifyAgentImprovementProposal,\n verifyAgentImprovementReview,\n verifyCandidateExecutionEvidence,\n} from './improvement-cycle'\nexport type {\n AgentImprovementActivationTargetIdentity,\n AgentImprovementProfileSurface,\n AgentImprovementTargetProfileDiffOptions,\n AgentProfileMeasuredSurface,\n} from './improvement-surfaces'\nexport {\n AGENT_IMPROVEMENT_PROFILE_SURFACES,\n AGENT_PROFILE_MEASURED_SURFACES,\n agentImprovementProfileDiffs,\n agentImprovementProfileSurfaceDigest,\n agentImprovementProfileSurfaceInput,\n agentImprovementTargetProfileDiffs,\n buildAgentImprovementActivationTargets,\n isAgentImprovementProfileSurface,\n isAgentProfileMeasuredSurface,\n} from './improvement-surfaces'\nexport type {\n OptimizationActivationReceipt,\n OptimizationReceiptCost,\n} from './optimization-receipt'\nexport {\n createOptimizationActivationReceipt,\n optimizationActivationReceiptFromMetadata,\n} from './optimization-receipt'\nexport type {\n AgentImprovementProfileActivationInput,\n AgentImprovementProfileActivationPreparation,\n AgentImprovementProfileActivationTarget,\n AgentImprovementProfileReplacement,\n AgentImprovementProfileStateDigest,\n AgentImprovementProfileStateDigestInput,\n AgentImprovementProfileStateResolver,\n AgentImprovementProfileStateResolverInput,\n AgentImprovementProfileTargetState,\n AgentImprovementProfileTargetTransition,\n} from './profile-activation'\nexport { prepareAgentImprovementProfileActivation } from './profile-activation'\nexport type { ProvisionedHost, ResolveCtx } from './resolver'\nexport {\n composeCertifiedProfile,\n composeCertifiedProfileFromWire,\n} from './resolver'\nexport type {\n AppliedIntelligence,\n IntelligenceAgent,\n IntelligenceHookConfig,\n IntelligenceWrapped,\n} from './with-intelligence'\nexport { withIntelligence } from './with-intelligence'\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/**\n * The typed record `withIntelligence` sends per call — serialized through the\n * shipped OTLP builders to the plane's `/v1/otlp` ingest. `input`/`output` are\n * redacted on export; the per-class `usage` split carries the billing proof;\n * `loopEvents`, when present, export as the nested loop→round→iteration span\n * tree under the same `traceId`.\n */\nexport interface RunRecord {\n runId: string\n traceId: string\n project: string\n target: string\n input: unknown\n output: unknown\n outcome: {\n success?: boolean\n score?: number\n usage: UsageSplit\n }\n model?: string\n provider?: string\n loopEvents?: LoopTraceEvent[]\n runtimeEvents?: RuntimeStreamEvent[]\n profile?: AgentProfile\n sessionId?: string\n harness?: string\n repository?: string\n commitSha?: string\n timing?: { startedAt: number; completedAt: number; durationMs: number }\n tokens?: {\n input: number\n output: number\n cachedInput?: number\n reasoning?: number\n }\n error?: { name: string; message: string; code?: string }\n /** Exact proposal → review → execution → receipt linkage for candidate runs. */\n candidateExecution?: CandidateExecutionEvidence\n}\n\n/**\n * What an agent reports (via `applied.record`) to enrich the {@link RunRecord}\n * sent for its call. All optional — an un-recorded run still sends input/output\n * with an inference-only zero usage split. `costUsd` without a split is treated\n * as pure inference (the base stream).\n */\nexport interface RunReport {\n success?: boolean\n score?: number\n usage?: Partial<UsageSplit>\n costUsd?: number\n model?: string\n provider?: string\n loopEvents?: LoopTraceEvent[]\n runtimeEvents?: RuntimeStreamEvent[]\n profile?: AgentProfile\n sessionId?: string\n harness?: string\n commitSha?: string\n tokens?: RunRecord['tokens']\n error?: RunRecord['error']\n candidateExecution?: CandidateExecutionEvidence\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 * The ONE Tangle Intelligence base URL — both the send (OTLP `/v1/otlp`) and\n * receive (`/v1/profiles/:target/composed`) paths derive from it. Reads\n * `TANGLE_INTELLIGENCE_URL` when omitted, else `https://intelligence.tangle.tools`.\n * Send is best-effort and only ships when an `apiKey` is present (the tenant\n * key the ingest requires); absent a key, export is a no-op.\n */\n baseUrl?: 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 /** Full canonical profile used for this agent. Exported redacted with a stable hash. */\n profile?: AgentProfile\n /** Commit that produced the running agent, when known. */\n commitSha?: string\n /** Runtime-event payload policy. Tool inputs/results remain off unless explicitly enabled. */\n runtimeTelemetry?: RuntimeTelemetryOptions\n /**\n * Payloads are metadata-only by default: the run span carries a stable hash\n * and UTF-8 byte count, but not the redacted content. Set `full` only when\n * the configured OTLP destination is approved to receive complete redacted\n * inputs, outputs, and profiles.\n */\n payloadAttributes?: 'metadata' | 'full'\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 * `runAgentRounds`/`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 * Send one typed {@link RunRecord} — the run's flat span (input/output/outcome/\n * usage/model/provider, redacted) plus, when `loopEvents` are present, the\n * nested loop topology under the same `traceId`. Reuses the shipped\n * `flatOtelSpan` + `buildLoopOtelSpans` builders (no second builder).\n * Best-effort: export failures are swallowed. Returns the record's `traceId`.\n */\n exportRunRecord(record: RunRecord): string\n /** Mint a fresh run id (`run-<hex>`). */\n freshRunId(): string\n /** Mint a fresh 32-hex trace id. */\n freshTraceId(): 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 freshTraceId(): string {\n return randomHex(32)\n}\n\nfunction freshRunId(): string {\n return `run-${randomHex(16)}`\n}\n\n/** Serialize a redacted value without dropping customer trace content. */\nfunction serializeJson(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\n}\n\nfunction addPayloadAttributes(\n labels: Record<string, string | number | boolean>,\n key: string,\n value: unknown,\n includeFullPayload: boolean,\n): void {\n const serialized = serializeJson(value)\n labels[`${key}_hash`] = contentHash(serialized)\n labels[`${key}_bytes`] = Buffer.byteLength(serialized, 'utf8')\n if (includeFullPayload) labels[key] = serialized\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, the base URL, and\n * the redactor up front; the exporter is built lazily and is `undefined` when no\n * `apiKey` is present (send becomes a no-op — the ingest requires a tenant key,\n * and best-effort export must never spam an unauthenticated plane).\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 includeFullPayload = config.payloadAttributes === 'full'\n const apiKey =\n config.apiKey ?? (typeof process !== 'undefined' ? process.env.TANGLE_API_KEY : undefined)\n // The ONE base URL drives both send and receive; the OTLP ingest lives at\n // `${base}/v1/otlp` and the exporter appends `/v1/traces` → `${base}/v1/otlp/v1/traces`.\n const otlpEndpoint = `${resolveIntelligenceBaseUrl(config.baseUrl)}/v1/otlp`\n\n // Built lazily: a client with no tenant key 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 (!apiKey) return undefined\n exporter = createOtelExporter({\n endpoint: otlpEndpoint,\n headers: { 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 try {\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) {\n addPayloadAttributes(labels, 'tangle.input', redactedInput, includeFullPayload)\n }\n if (redactedOutput !== undefined) {\n addPayloadAttributes(labels, 'tangle.output', redactedOutput, includeFullPayload)\n }\n // Flat span with VERBATIM attribute keys — the plane's session/model/\n // cost readers exact-match `tangle.sessionId` / `gen_ai.request.model`,\n // so the loop-namespacing builder must not be used here.\n ex.exportSpan(\n flatOtelSpan(\n 'tangle.intelligence.run',\n { 'tangle.runId': outcome.runId, ...labels },\n outcome.traceId,\n Date.now(),\n ),\n )\n } catch {\n // Best-effort — telemetry export must never fail the agent's turn.\n }\n }\n\n function exportRunRecord(record: RunRecord): string {\n const ex = getExporter()\n if (!ex) return record.traceId\n try {\n // Clamp the OFF billing invariant on export — the proof holds even if a\n // caller mis-reports an intelligence split at the OFF tier.\n const intelligenceUsd = intelligenceOff ? 0 : record.outcome.usage.intelligenceUsd\n const repository =\n record.repository ?? (config.repo ? `${config.repo.owner}/${config.repo.name}` : undefined)\n const labels: Record<string, string | number | boolean> = {\n project: record.project,\n 'tangle.target': record.target,\n 'tangle.effort.intelligence_off': intelligenceOff,\n 'tangle.usage.inference_usd': record.outcome.usage.inferenceUsd,\n 'tangle.usage.intelligence_usd': intelligenceUsd,\n ...(record.model ? { 'gen_ai.request.model': record.model } : {}),\n ...(record.provider ? { 'provider.name': record.provider } : {}),\n ...(record.sessionId\n ? {\n 'tangle.sessionId': record.sessionId,\n 'gen_ai.conversation.id': record.sessionId,\n }\n : {}),\n ...(record.harness ? { 'tangle.agent.harness': record.harness } : {}),\n ...(repository ? { 'vcs.repository.name': repository } : {}),\n ...(record.commitSha ? { 'vcs.ref.head.revision': record.commitSha } : {}),\n ...(record.timing\n ? {\n 'tangle.started_at_ms': record.timing.startedAt,\n 'tangle.completed_at_ms': record.timing.completedAt,\n 'tangle.duration_ms': record.timing.durationMs,\n }\n : {}),\n ...(record.tokens\n ? {\n 'gen_ai.usage.input_tokens': record.tokens.input,\n 'gen_ai.usage.output_tokens': record.tokens.output,\n ...(record.tokens.cachedInput !== undefined\n ? { 'gen_ai.usage.cache_read_input_tokens': record.tokens.cachedInput }\n : {}),\n ...(record.tokens.reasoning !== undefined\n ? { 'gen_ai.usage.reasoning_tokens': record.tokens.reasoning }\n : {}),\n }\n : {}),\n ...(typeof record.outcome.success === 'boolean'\n ? { 'tangle.outcome.success': record.outcome.success }\n : {}),\n ...(typeof record.outcome.score === 'number'\n ? { 'tangle.outcome.score': record.outcome.score }\n : {}),\n ...(record.error\n ? {\n 'error.type': record.error.code ?? record.error.name,\n 'error.message': serializeJson(redactor(record.error.message)),\n }\n : {}),\n ...(record.runtimeEvents\n ? { 'tangle.runtime.event_count': record.runtimeEvents.length }\n : {}),\n ...(record.candidateExecution\n ? {\n 'tangle.candidate.bundle_digest': record.candidateExecution.receipt.bundleDigest,\n 'tangle.candidate.experiment_digest':\n record.candidateExecution.materializationReceipt.executionPlan.material.runCell\n .experimentDigest,\n 'tangle.candidate.execution_id':\n record.candidateExecution.materializationReceipt.executionPlan.material.executionId,\n 'tangle.candidate.execution_plan_digest':\n record.candidateExecution.receipt.executionPlanDigest,\n 'tangle.candidate.materialization_receipt_digest':\n record.candidateExecution.receipt.materializationReceiptDigest,\n 'tangle.candidate.succeeded':\n record.candidateExecution.receipt.termination.kind === 'exit' &&\n record.candidateExecution.receipt.termination.exitCode === 0 &&\n record.candidateExecution.receipt.benchmarkResult.material.passed,\n 'tangle.candidate.run_receipt_digest': record.candidateExecution.receipt.digest,\n }\n : {}),\n }\n if (record.profile) {\n addPayloadAttributes(\n labels,\n 'tangle.agent.profile',\n redactor(record.profile),\n includeFullPayload,\n )\n if (record.profile.name) labels['gen_ai.agent.name'] = record.profile.name\n }\n const redactedInput = record.input !== undefined ? redactor(record.input) : undefined\n const redactedOutput = record.output !== undefined ? redactor(record.output) : undefined\n if (redactedInput !== undefined) {\n addPayloadAttributes(labels, 'tangle.input', redactedInput, includeFullPayload)\n }\n if (redactedOutput !== undefined) {\n addPayloadAttributes(labels, 'tangle.output', redactedOutput, includeFullPayload)\n }\n const now = Date.now()\n const runSpan = flatOtelSpan(\n 'tangle.intelligence.run',\n { 'tangle.runId': record.runId, ...labels },\n record.traceId,\n record.timing?.startedAt ?? now,\n undefined,\n record.timing?.completedAt ?? now,\n )\n ex.exportSpan(runSpan)\n if (record.runtimeEvents && record.runtimeEvents.length > 0) {\n const spans = buildRuntimeEventOtelSpans(\n record.runtimeEvents,\n record.traceId,\n runSpan.spanId,\n { ...config.runtimeTelemetry, redact: redactor },\n )\n for (const span of spans) ex.exportSpan(span)\n }\n // The loop topology (when present) exports under the SAME traceId, parented\n // under the run span — reusing the shipped builder, never a second one.\n if (record.loopEvents && record.loopEvents.length > 0) {\n const spans = buildLoopOtelSpans(\n record.loopEvents as ReadonlyArray<{\n kind: string\n runId: string\n timestamp: number\n payload: object\n }>,\n record.traceId,\n runSpan.spanId,\n )\n for (const span of spans) ex.exportSpan(span)\n }\n } catch {\n // Best-effort — a send failure must never fail the agent's turn.\n }\n return record.traceId\n }\n\n return {\n project: config.project,\n effort,\n exportRunRecord,\n freshRunId,\n freshTraceId,\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 // Send ships only with a tenant key — the honest \"will export actually\n // land\" signal (the base URL always resolves to the plane default).\n exportConfigured: Boolean(apiKey),\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"],"mappings":";;;;;;;;;;AAmCA,MAAM,sBAAsB;AAC5B,MAAM,mBAAmB;AA0HzB,MAAM,+BAA+B;AACrC,MAAM,0BAA0B;;;AAqBhC,SAAgB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