@tangle-network/agent-runtime 0.246.0 → 0.247.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/{activation-C6d-NTWk.js → activation-DYqnl8zq.js} +2 -2
  2. package/dist/{activation-C6d-NTWk.js.map → activation-DYqnl8zq.js.map} +1 -1
  3. package/dist/{activation-Df-ae5Uq.d.ts → activation-DizpINK3.d.ts} +2 -2
  4. package/dist/agent.d.ts +2 -2
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-De8pyM57.js → coordination-driver-BV4AAUns.js} +20 -7
  7. package/dist/{coordination-driver-De8pyM57.js.map → coordination-driver-BV4AAUns.js.map} +1 -1
  8. package/dist/{delegate-DE6hNhbD.js → delegate-DQAzB5Xv.js} +2 -2
  9. package/dist/{delegate-DE6hNhbD.js.map → delegate-DQAzB5Xv.js.map} +1 -1
  10. package/dist/durable.d.ts +2 -2
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-s57f-VCR.js → graph-DcBmMLIp.js} +3 -3
  13. package/dist/{graph-s57f-VCR.js.map → graph-DcBmMLIp.js.map} +1 -1
  14. package/dist/{improvement-cycle-BE3gIJwL.js → improvement-cycle-B049YmQ8.js} +3 -3
  15. package/dist/{improvement-cycle-BE3gIJwL.js.map → improvement-cycle-B049YmQ8.js.map} +1 -1
  16. package/dist/{index-CAG31NtK.d.ts → index-DLzlXwr6.d.ts} +11 -6
  17. package/dist/index.d.ts +6 -6
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +7 -5
  20. package/dist/intelligence.js +9 -8
  21. package/dist/intelligence.js.map +1 -1
  22. package/dist/kernel.d.ts +3 -3
  23. package/dist/kernel.js +9 -9
  24. package/dist/{loop-runner-bin-B_oSVrE7.d.ts → loop-runner-bin-HbMECmxT.d.ts} +3 -3
  25. package/dist/{loop-runner-bin-Bp8Mih20.js → loop-runner-bin-iqq1azfy.js} +3 -3
  26. package/dist/{loop-runner-bin-Bp8Mih20.js.map → loop-runner-bin-iqq1azfy.js.map} +1 -1
  27. package/dist/loop-runner-bin.d.ts +1 -1
  28. package/dist/loop-runner-bin.js +1 -1
  29. package/dist/mcp/bin.js +3 -3
  30. package/dist/mcp/index.d.ts +5 -5
  31. package/dist/mcp/index.js +4 -4
  32. package/dist/{openai-tools-B1GMKDjW.d.ts → openai-tools-DvLk_Ddg.d.ts} +2 -2
  33. package/dist/profiles.d.ts +2 -2
  34. package/dist/{provision-supervisor-D0X9KUv-.js → provision-supervisor-BgQx2Avp.js} +4 -4
  35. package/dist/{provision-supervisor-D0X9KUv-.js.map → provision-supervisor-BgQx2Avp.js.map} +1 -1
  36. package/dist/{run-layout-B8-Gqhpg.js → run-layout-hKAJGF4g.js} +6 -1
  37. package/dist/run-layout-hKAJGF4g.js.map +1 -0
  38. package/dist/{runtime-CHbVv5UI.js → runtime-HpTXhB3g.js} +9 -9
  39. package/dist/{runtime-CHbVv5UI.js.map → runtime-HpTXhB3g.js.map} +1 -1
  40. package/dist/{server-DwsC_FyV.js → server-OOE7mXrN.js} +3 -3
  41. package/dist/{server-DwsC_FyV.js.map → server-OOE7mXrN.js.map} +1 -1
  42. package/dist/{stream-agent-turn-DQ-W8mHf.d.ts → stream-agent-turn-CcumM0Bu.d.ts} +2 -2
  43. package/dist/{structural-rollout-DasmuuUp.js → structural-rollout-z1A0okaB.js} +2 -2
  44. package/dist/{structural-rollout-DasmuuUp.js.map → structural-rollout-z1A0okaB.js.map} +1 -1
  45. package/dist/{substrate-DJOnuoa_.d.ts → substrate-CQ0hfewn.d.ts} +2 -2
  46. package/dist/{supervise-o6CzD2Rt.js → supervise-DZEOpzRw.js} +11 -5
  47. package/dist/supervise-DZEOpzRw.js.map +1 -0
  48. package/dist/{supervisor-tGq-TPIv.js → supervisor-BIBWUFUr.js} +165 -48
  49. package/dist/supervisor-BIBWUFUr.js.map +1 -0
  50. package/dist/testing.d.ts +2 -2
  51. package/dist/testing.js +12 -12
  52. package/dist/{top-app-DL-sjv7K.js → top-app-d-bmwO7O.js} +2 -2
  53. package/dist/{top-app-DL-sjv7K.js.map → top-app-d-bmwO7O.js.map} +1 -1
  54. package/dist/tui/bin.js +1 -1
  55. package/dist/tui/index.d.ts +1 -1
  56. package/dist/tui/index.js +2 -2
  57. package/dist/{types-BoEzH8V6.d.ts → types-BUhz284C.d.ts} +23 -10
  58. package/package.json +1 -1
  59. package/dist/run-layout-B8-Gqhpg.js.map +0 -1
  60. package/dist/supervise-o6CzD2Rt.js.map +0 -1
  61. package/dist/supervisor-tGq-TPIv.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"intelligence.js","names":["profileStateDigest","canonicalCandidateDigest","canonicalCandidateDigest"],"sources":["../src/intelligence/delivery.ts","../src/intelligence/effort.ts","../src/intelligence/authored-profile-improvement.ts","../src/intelligence/capability.ts","../src/intelligence/exact-process-candidate.ts","../src/intelligence/profile-activation.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 * @stable\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 * @stable\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","import { assertProposalFindings, type ProposalFinding } from '@tangle-network/agent-eval/analyst'\nimport type { CampaignScenarioIdentity } from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfileImprovementExperimentExecutionInput,\n measuredComparisonFromAgentProfileImprovementExperiment,\n runAgentProfileImprovementExperiment,\n sealAgentProfileImprovementExperiment,\n verifyAgentProfileImprovementExperimentComparison,\n} from '@tangle-network/agent-eval/contract'\nimport type {\n AgentCandidateLineage,\n AgentImprovementProposal,\n AgentImprovementSource,\n AgentProfile,\n AgentProfileImprovementExecutionRef,\n AgentProfileImprovementExperiment,\n AgentProfileImprovementMeasuredComparison,\n AgentProfileImprovementMeasurement,\n AgentProfileImprovementRunReceipt,\n AgentProfileImprovementSuiteInputs,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { agentImprovementSourceSchema } from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { parseExactAgentProfile } from '../candidate-execution/profile'\nimport { assertProfileTrainingIsHeldOut } from '../improvement/candidate-validation'\nimport {\n type AgentProfileImprovementBenchmark,\n createAgentImprovementProposal,\n} from './improvement-cycle'\nimport { agentImprovementProfileDiffs } from './improvement-surfaces'\nimport type { AgentImprovementProfileStateDigest } from './profile-activation'\nimport {\n createProfileImprovementCostLedger,\n profileImprovementMetadata,\n profilePolicyWithBudget,\n profilePreparationAccounting,\n profileStateDigest,\n profileTaskScenarioIdentity,\n sealProfileImprovementBenchmark,\n} from './profile-improvement-experiment'\n\n/** Lineage accepted by the direct candidate path. Optimizer lineage belongs to `improve()`. */\nexport type AuthoredAgentProfileCandidateLineage = Omit<\n AgentCandidateLineage,\n 'source' | 'profileDiffIds'\n> & {\n source: Exclude<AgentCandidateLineage['source'], 'optimizer'>\n /** Runtime derives these from the exact profile change it seals. */\n profileDiffIds?: never\n}\n\n/** Provenance attached while Runtime derives the exact profile diff. */\nexport type AuthoredAgentProfileDiffOptions = NonNullable<\n Parameters<typeof agentImprovementProfileDiffs>[2]\n>\n\n/** Product-owned executor for exact baseline/candidate profile measurement. */\nexport interface AgentProfileCandidateMeasurementExecutor {\n executionRef: AgentProfileImprovementExecutionRef\n measure(\n input: AgentProfileImprovementExperimentExecutionInput & { profile: AgentProfile },\n ): Promise<AgentProfileImprovementRunReceipt>\n}\n\n/**\n * Measure a complete human-authored, imported, or compound profile candidate.\n * No optimizer runs and no optimizer receipt is fabricated.\n */\nexport interface ProposeAuthoredAgentProfileImprovementOptions {\n runId: string\n source: AgentImprovementSource\n profile: AgentProfile\n stateDigest: AgentImprovementProfileStateDigest\n candidateProfile: AgentProfile\n candidateLineage: AuthoredAgentProfileCandidateLineage\n /** Optional source/artifact metadata used on Runtime-derived profile diff steps. */\n diff?: AuthoredAgentProfileDiffOptions\n findings?: readonly ProposalFinding[]\n benchmark: AgentProfileImprovementBenchmark\n executor: AgentProfileCandidateMeasurementExecutor\n /** One customer-approved maximum for the held-out paired measurement. */\n budgetUsd: number\n /** Optional identities used to prove authored/imported development work is held out. */\n developmentScenarios?: readonly CampaignScenarioIdentity[]\n maxConcurrency?: number\n signal?: AbortSignal\n candidate?: AgentProfileImprovementMeasuredComparison['candidate']\n metadata?: AgentProfileImprovementMeasuredComparison['metadata']\n now?: () => Date\n}\n\nexport interface ProposeAuthoredAgentProfileImprovementResult {\n candidateProfile: AgentProfile\n candidateLineage: AgentCandidateLineage\n experiment: AgentProfileImprovementExperiment\n measurements: AgentProfileImprovementMeasurement[]\n proposal: AgentImprovementProposal\n}\n\n/**\n * Put a complete authored/imported profile through the canonical profile\n * experiment and proposal path without invoking `improve()`.\n */\nexport async function proposeAuthoredAgentProfileImprovement(\n options: ProposeAuthoredAgentProfileImprovementOptions,\n): Promise<ProposeAuthoredAgentProfileImprovementResult> {\n const source = agentImprovementSourceSchema.parse(options.source)\n // Validate and seal caller metadata before allocating a cost ledger or\n // invoking the product-owned executor. Reserved provenance fields and forged\n // optimizer receipts must fail closed without spending measurement budget.\n const metadata = profileImprovementMetadata(options.metadata, source)\n const inputLineage = options.candidateLineage as AgentCandidateLineage\n if (inputLineage.source === 'optimizer') {\n throw new Error('authored profile improvement refuses optimizer lineage; use improve()')\n }\n if (Object.hasOwn(inputLineage, 'profileDiffIds')) {\n throw new Error('authored profile improvement derives candidateLineage.profileDiffIds')\n }\n const findings = immutableCandidateValue([\n ...assertProposalFindings(options.findings ?? [], 'authored profile improvement findings'),\n ])\n const costLedger = createProfileImprovementCostLedger(\n options.budgetUsd,\n 'authored profile improvement',\n )\n const preparationStartedAt = performance.now()\n const baselineProfile = parseExactAgentProfile(options.profile, 'authored profile baseline')\n const candidateProfile = parseExactAgentProfile(\n options.candidateProfile,\n 'authored profile candidate',\n )\n const baselineStateDigest = profileStateDigest(\n options.stateDigest,\n source.sourceIdentity,\n baselineProfile,\n )\n if (baselineStateDigest !== source.sourceDigest) {\n throw new Error('authored profile source digest does not match the measured profile state')\n }\n const candidateStateDigest = profileStateDigest(\n options.stateDigest,\n source.sourceIdentity,\n candidateProfile,\n )\n if (candidateStateDigest === baselineStateDigest) {\n throw new Error('authored profile candidate state digest matches the baseline')\n }\n\n const change = agentImprovementProfileDiffs(baselineProfile, candidateProfile, {\n ...options.diff,\n id: options.diff?.id ?? `profile-improvement:${candidateStateDigest}`,\n metadata: {\n ...options.diff?.metadata,\n sourceIdentity: source.sourceIdentity,\n sourceRevision: source.sourceRevision,\n },\n })\n const profileDiffIds = change.map((step) => {\n if (!step.id) throw new Error('authored profile change requires an exact diff id')\n return step.id\n })\n const candidateLineage = immutableCandidateValue<AgentCandidateLineage>({\n ...inputLineage,\n profileDiffIds,\n })\n const policy = profilePolicyWithBudget(\n options.benchmark.policy,\n options.budgetUsd,\n 'authored profile',\n )\n const benchmark = sealProfileImprovementBenchmark({ ...options.benchmark, policy })\n const heldOutDigests = new Set(benchmark.tasks.map((task) => task.scenario.digest))\n assertProfileTrainingIsHeldOut(baselineProfile, heldOutDigests)\n assertProfileTrainingIsHeldOut(candidateProfile, heldOutDigests)\n assertDirectCandidateReleaseWorkIsFresh(benchmark, candidateLineage, options.developmentScenarios)\n const experiment = sealAgentProfileImprovementExperiment({\n kind: 'agent-profile-improvement-experiment',\n digestAlgorithm: 'rfc8785-sha256',\n source,\n executionRef: options.executor.executionRef,\n baseline: { stateDigest: baselineStateDigest },\n candidate: { stateDigest: candidateStateDigest },\n change,\n candidateLineage,\n benchmark,\n policy,\n })\n const profilesByStateDigest = new Map<Sha256Digest, AgentProfile>([\n [baselineStateDigest, baselineProfile],\n [candidateStateDigest, candidateProfile],\n ])\n const preparation = profilePreparationAccounting(costLedger, preparationStartedAt)\n const run = await runAgentProfileImprovementExperiment({\n experiment,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n costLedger,\n ...(options.signal ? { signal: options.signal } : {}),\n execute: async (input) => {\n const measuredProfile = profilesByStateDigest.get(input.stateDigest)\n if (!measuredProfile) {\n throw new Error('authored profile execution requested an unknown profile state')\n }\n return options.executor.measure({ ...input, profile: measuredProfile })\n },\n })\n const evaluation = verifyAgentProfileImprovementExperimentComparison(\n measuredComparisonFromAgentProfileImprovementExperiment({\n experiment,\n measurements: run.measurements,\n runId: options.runId,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n generationsExplored: 0,\n preparation,\n measurement: run.measurement,\n metadata,\n }),\n )\n const proposal = createAgentImprovementProposal({\n runId: options.runId,\n findings,\n evaluation,\n ...(options.now ? { now: options.now } : {}),\n })\n return {\n candidateProfile,\n candidateLineage,\n experiment,\n measurements: run.measurements,\n proposal,\n }\n}\n\nfunction assertDirectCandidateReleaseWorkIsFresh(\n benchmark: AgentProfileImprovementSuiteInputs,\n lineage: AgentCandidateLineage,\n developmentScenarios: readonly CampaignScenarioIdentity[] | undefined,\n): void {\n if (lineage.developmentSplitDigest === benchmark.suite.splitDigest) {\n throw new Error('authored profile development and held-out splits must be disjoint')\n }\n if (!developmentScenarios || developmentScenarios.length === 0) return\n const development = new Set(developmentScenarios.map(canonicalCandidateDigest))\n const reused = benchmark.tasks\n .map(profileTaskScenarioIdentity)\n .filter((scenario) => development.has(canonicalCandidateDigest(scenario)))\n .map((scenario) => scenario.id)\n if (reused.length > 0) {\n throw new Error(\n `authored profile release reuses development scenario(s): [${reused.join(', ')}]`,\n )\n }\n}\n","/**\n * Capability manifest types and conversion from the certified profile wire format.\n * Consumers own binding admission and execution.\n *\n * @stable\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 structural JSON Schema object describing a tool's parameters. */\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 supported by the manifest schema. */\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 consumer resolves the live secret per tenant,\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 * Describes how a capability is backed.\n * Consumers must admit a binding before executing it.\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 // `sqlite` is the only backend a manifest may name: nothing provisions another, and the whole\n // arm is refused at resolve time until it clears the E3 admission bar.\n | { kind: 'memory-store'; provision: 'sqlite'; 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 represented by the manifest schema. */\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 — consumers can fold 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/** Materialized capability surfaces supplied by a consumer-owned executor. */\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 consumer rejected a binding that its executor does not admit.\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 * `composeCertifiedPrompt` folds it before other prompt artifacts.\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 type AgentProfileMeasuredSurface,\n agentImprovementProfileSurfaceDigest,\n agentImprovementTargetProfileDiffs,\n assertProfileImprovementTargetsShareIdentity,\n isAgentProfileMeasuredSurface,\n} from './improvement-surfaces'\n\nexport type AgentImprovementProfileActivationTarget = Omit<\n AgentImprovementActivationTargetPlan,\n 'surface'\n> & {\n surface: AgentImprovementProfileSurface\n}\n\ntype AgentProfileImprovementTransitionTarget = Omit<\n AgentImprovementActivationTargetPlan,\n 'surface'\n> & {\n surface: AgentProfileMeasuredSurface\n}\n\nexport type AgentImprovementProfileTargetState = Omit<\n AgentImprovementActivationTargetState,\n 'surface'\n> & { surface: AgentProfileMeasuredSurface }\n\nexport type AgentImprovementProfileTargetTransition = Omit<\n AgentImprovementActivationTargetTransition,\n 'surface'\n> & { surface: AgentProfileMeasuredSurface }\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 if ('profileTransition' in input) {\n const targets = profileTargets(input.profileTransition.targets)\n assertUniqueProfileTargets(targets)\n const current = readCurrentProfiles(input.currentByIdentity, targets)\n if ('status' in current) return immutableCandidateValue(current)\n return prepareProfileImprovementActivation(input, targets, current)\n }\n const targets = input.targets\n assertUniqueProfileTargets(targets)\n const current = readCurrentProfiles(input.currentByIdentity, targets)\n if ('status' in current) return immutableCandidateValue(current)\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 AgentProfileImprovementTransitionTarget,\n ...AgentProfileImprovementTransitionTarget[],\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 AgentProfileImprovementTransitionTarget[],\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 AgentProfileImprovementTransitionTarget,\n ...AgentProfileImprovementTransitionTarget[],\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: AgentProfileImprovementTransitionTarget\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 AgentProfileImprovementTransitionTarget[],\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): [AgentProfileImprovementTransitionTarget, ...AgentProfileImprovementTransitionTarget[]] {\n if (!targets.every((target) => isAgentProfileMeasuredSurface(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 AgentProfileImprovementTransitionTarget,\n ...AgentProfileImprovementTransitionTarget[],\n ]\n}\n\nfunction assertUniqueProfileTargets(\n targets: readonly AgentProfileImprovementTransitionTarget[],\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 * `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 * @stable\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 * @module\n * @stable\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 AgentProfileCandidateMeasurementExecutor,\n AuthoredAgentProfileCandidateLineage,\n AuthoredAgentProfileDiffOptions,\n ProposeAuthoredAgentProfileImprovementOptions,\n ProposeAuthoredAgentProfileImprovementResult,\n} from './authored-profile-improvement'\nexport { proposeAuthoredAgentProfileImprovement } from './authored-profile-improvement'\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 {\n AppliedIntelligence,\n IntelligenceAgent,\n IntelligenceHookConfig,\n IntelligenceWrapped,\n} from './with-intelligence'\nexport { withIntelligence } from './with-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,WAAW,CAAC;IACxB;IACA,GAAI,MAAM,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM,MAAM,KAAK;IACvD,QAAQ,YAAY,QAAQ,MAAM,aAAa,4BAA4B;GAC7E,CAAC;EACkC;CACrC,SAAS,KAAK;EACZ,OAAO;GACL,WAAW;GACX,WAAW;GACX,OAAO,eAAe,QAAQ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OAAO;GAGvC,IAAI;IACF,MAAM,QAAQ,mBACZ,QAMA,SACA,MAAM,gBACR;IACA,KAAK,MAAM,QAAQ,OAAO,GAAG,WAAW,IAAI;GAC9C,QAAQ,CAER;GACA,OAAO;EACT;EAEA,SAAuB;GACrB,MAAM,UAAU,QAAQ,OAAO,MAAM,SAAS,OAAO,MAAM,QAAQ,OAAO,MAAM,UAAU;GAC1F,MAAM,YAAY,QAAQ,OAAO,UAAU,OAAO,OAAO,SAAS,CAAC;GACnE,MAAM,cAAc,QAAQ,OAAO,YAAY,OAAO,SAAS,SAAS,CAAC;GAEzE,MAAM,YAAsB,CAAC;GAC7B,IAAI,CAAC,WAAW,UAAU,KAAK,QAAQ;GACvC,IAAI,CAAC,aAAa,UAAU,KAAK,UAAU;GAC3C,IAAI,CAAC,SAAS,UAAU,KAAK,MAAM;GAMnC,MAAM,mBAA6B,CAAC;GACpC,IAAI,iBAAiB,iBAAiB,KAAK,kBAAkB;GAE7D,OAAO;IACL,SAAS,OAAO;IAChB;IAGA,kBAAkB,QAAQ,MAAM;IAChC,OAAO;KACL,SAAS;MAAE,OAAO;MAAM,SAAS,CAAC;KAAE;KACpC,WAAW;MACT,OAAO,iBAAiB,WAAW;MACnC,SAAS;KACX;KACA,IAAI;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":["profileStateDigest","canonicalCandidateDigest","canonicalCandidateDigest"],"sources":["../src/intelligence/delivery.ts","../src/intelligence/effort.ts","../src/intelligence/authored-profile-improvement.ts","../src/intelligence/capability.ts","../src/intelligence/exact-process-candidate.ts","../src/intelligence/profile-activation.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 * @stable\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 after the refresh window, or force a pull now. Both join an in-flight pull. */\n refresh(options?: { force?: boolean }): 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 // Bind explicit coordinates and transport; later caller mutation must not redirect this cache.\n const pullOptions = { ...opts }\n const refreshMs = pullOptions.refreshMs ?? defaultRefreshMs\n let certified: CertifiedProfile | null = null\n let lastPullAt: number | undefined\n let inflight: Promise<void> | null = null\n\n async function refresh(options?: { force?: boolean }): Promise<void> {\n // A normal composition also joins a forced refresh instead of returning stale warm guidance.\n if (inflight) return inflight\n if (!options?.force && lastPullAt !== undefined && Date.now() - lastPullAt < refreshMs) return\n inflight = (async () => {\n const outcome = await pullCertified(pullOptions)\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 * @stable\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","import { assertProposalFindings, type ProposalFinding } from '@tangle-network/agent-eval/analyst'\nimport type { CampaignScenarioIdentity } from '@tangle-network/agent-eval/campaign'\nimport {\n type AgentProfileImprovementExperimentExecutionInput,\n measuredComparisonFromAgentProfileImprovementExperiment,\n runAgentProfileImprovementExperiment,\n sealAgentProfileImprovementExperiment,\n verifyAgentProfileImprovementExperimentComparison,\n} from '@tangle-network/agent-eval/contract'\nimport type {\n AgentCandidateLineage,\n AgentImprovementProposal,\n AgentImprovementSource,\n AgentProfile,\n AgentProfileImprovementExecutionRef,\n AgentProfileImprovementExperiment,\n AgentProfileImprovementMeasuredComparison,\n AgentProfileImprovementMeasurement,\n AgentProfileImprovementRunReceipt,\n AgentProfileImprovementSuiteInputs,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport { agentImprovementSourceSchema } from '@tangle-network/agent-interface'\nimport { canonicalCandidateDigest, immutableCandidateValue } from '../candidate-execution/digest'\nimport { parseExactAgentProfile } from '../candidate-execution/profile'\nimport { assertProfileTrainingIsHeldOut } from '../improvement/candidate-validation'\nimport {\n type AgentProfileImprovementBenchmark,\n createAgentImprovementProposal,\n} from './improvement-cycle'\nimport { agentImprovementProfileDiffs } from './improvement-surfaces'\nimport type { AgentImprovementProfileStateDigest } from './profile-activation'\nimport {\n createProfileImprovementCostLedger,\n profileImprovementMetadata,\n profilePolicyWithBudget,\n profilePreparationAccounting,\n profileStateDigest,\n profileTaskScenarioIdentity,\n sealProfileImprovementBenchmark,\n} from './profile-improvement-experiment'\n\n/** Lineage accepted by the direct candidate path. Optimizer lineage belongs to `improve()`. */\nexport type AuthoredAgentProfileCandidateLineage = Omit<\n AgentCandidateLineage,\n 'source' | 'profileDiffIds'\n> & {\n source: Exclude<AgentCandidateLineage['source'], 'optimizer'>\n /** Runtime derives these from the exact profile change it seals. */\n profileDiffIds?: never\n}\n\n/** Provenance attached while Runtime derives the exact profile diff. */\nexport type AuthoredAgentProfileDiffOptions = NonNullable<\n Parameters<typeof agentImprovementProfileDiffs>[2]\n>\n\n/** Product-owned executor for exact baseline/candidate profile measurement. */\nexport interface AgentProfileCandidateMeasurementExecutor {\n executionRef: AgentProfileImprovementExecutionRef\n measure(\n input: AgentProfileImprovementExperimentExecutionInput & { profile: AgentProfile },\n ): Promise<AgentProfileImprovementRunReceipt>\n}\n\n/**\n * Measure a complete human-authored, imported, or compound profile candidate.\n * No optimizer runs and no optimizer receipt is fabricated.\n */\nexport interface ProposeAuthoredAgentProfileImprovementOptions {\n runId: string\n source: AgentImprovementSource\n profile: AgentProfile\n stateDigest: AgentImprovementProfileStateDigest\n candidateProfile: AgentProfile\n candidateLineage: AuthoredAgentProfileCandidateLineage\n /** Optional source/artifact metadata used on Runtime-derived profile diff steps. */\n diff?: AuthoredAgentProfileDiffOptions\n findings?: readonly ProposalFinding[]\n benchmark: AgentProfileImprovementBenchmark\n executor: AgentProfileCandidateMeasurementExecutor\n /** One customer-approved maximum for the held-out paired measurement. */\n budgetUsd: number\n /** Optional identities used to prove authored/imported development work is held out. */\n developmentScenarios?: readonly CampaignScenarioIdentity[]\n maxConcurrency?: number\n signal?: AbortSignal\n candidate?: AgentProfileImprovementMeasuredComparison['candidate']\n metadata?: AgentProfileImprovementMeasuredComparison['metadata']\n now?: () => Date\n}\n\nexport interface ProposeAuthoredAgentProfileImprovementResult {\n candidateProfile: AgentProfile\n candidateLineage: AgentCandidateLineage\n experiment: AgentProfileImprovementExperiment\n measurements: AgentProfileImprovementMeasurement[]\n proposal: AgentImprovementProposal\n}\n\n/**\n * Put a complete authored/imported profile through the canonical profile\n * experiment and proposal path without invoking `improve()`.\n */\nexport async function proposeAuthoredAgentProfileImprovement(\n options: ProposeAuthoredAgentProfileImprovementOptions,\n): Promise<ProposeAuthoredAgentProfileImprovementResult> {\n const source = agentImprovementSourceSchema.parse(options.source)\n // Validate and seal caller metadata before allocating a cost ledger or\n // invoking the product-owned executor. Reserved provenance fields and forged\n // optimizer receipts must fail closed without spending measurement budget.\n const metadata = profileImprovementMetadata(options.metadata, source)\n const inputLineage = options.candidateLineage as AgentCandidateLineage\n if (inputLineage.source === 'optimizer') {\n throw new Error('authored profile improvement refuses optimizer lineage; use improve()')\n }\n if (Object.hasOwn(inputLineage, 'profileDiffIds')) {\n throw new Error('authored profile improvement derives candidateLineage.profileDiffIds')\n }\n const findings = immutableCandidateValue([\n ...assertProposalFindings(options.findings ?? [], 'authored profile improvement findings'),\n ])\n const costLedger = createProfileImprovementCostLedger(\n options.budgetUsd,\n 'authored profile improvement',\n )\n const preparationStartedAt = performance.now()\n const baselineProfile = parseExactAgentProfile(options.profile, 'authored profile baseline')\n const candidateProfile = parseExactAgentProfile(\n options.candidateProfile,\n 'authored profile candidate',\n )\n const baselineStateDigest = profileStateDigest(\n options.stateDigest,\n source.sourceIdentity,\n baselineProfile,\n )\n if (baselineStateDigest !== source.sourceDigest) {\n throw new Error('authored profile source digest does not match the measured profile state')\n }\n const candidateStateDigest = profileStateDigest(\n options.stateDigest,\n source.sourceIdentity,\n candidateProfile,\n )\n if (candidateStateDigest === baselineStateDigest) {\n throw new Error('authored profile candidate state digest matches the baseline')\n }\n\n const change = agentImprovementProfileDiffs(baselineProfile, candidateProfile, {\n ...options.diff,\n id: options.diff?.id ?? `profile-improvement:${candidateStateDigest}`,\n metadata: {\n ...options.diff?.metadata,\n sourceIdentity: source.sourceIdentity,\n sourceRevision: source.sourceRevision,\n },\n })\n const profileDiffIds = change.map((step) => {\n if (!step.id) throw new Error('authored profile change requires an exact diff id')\n return step.id\n })\n const candidateLineage = immutableCandidateValue<AgentCandidateLineage>({\n ...inputLineage,\n profileDiffIds,\n })\n const policy = profilePolicyWithBudget(\n options.benchmark.policy,\n options.budgetUsd,\n 'authored profile',\n )\n const benchmark = sealProfileImprovementBenchmark({ ...options.benchmark, policy })\n const heldOutDigests = new Set(benchmark.tasks.map((task) => task.scenario.digest))\n assertProfileTrainingIsHeldOut(baselineProfile, heldOutDigests)\n assertProfileTrainingIsHeldOut(candidateProfile, heldOutDigests)\n assertDirectCandidateReleaseWorkIsFresh(benchmark, candidateLineage, options.developmentScenarios)\n const experiment = sealAgentProfileImprovementExperiment({\n kind: 'agent-profile-improvement-experiment',\n digestAlgorithm: 'rfc8785-sha256',\n source,\n executionRef: options.executor.executionRef,\n baseline: { stateDigest: baselineStateDigest },\n candidate: { stateDigest: candidateStateDigest },\n change,\n candidateLineage,\n benchmark,\n policy,\n })\n const profilesByStateDigest = new Map<Sha256Digest, AgentProfile>([\n [baselineStateDigest, baselineProfile],\n [candidateStateDigest, candidateProfile],\n ])\n const preparation = profilePreparationAccounting(costLedger, preparationStartedAt)\n const run = await runAgentProfileImprovementExperiment({\n experiment,\n ...(options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency }),\n costLedger,\n ...(options.signal ? { signal: options.signal } : {}),\n execute: async (input) => {\n const measuredProfile = profilesByStateDigest.get(input.stateDigest)\n if (!measuredProfile) {\n throw new Error('authored profile execution requested an unknown profile state')\n }\n return options.executor.measure({ ...input, profile: measuredProfile })\n },\n })\n const evaluation = verifyAgentProfileImprovementExperimentComparison(\n measuredComparisonFromAgentProfileImprovementExperiment({\n experiment,\n measurements: run.measurements,\n runId: options.runId,\n ...(options.candidate ? { candidate: options.candidate } : {}),\n generationsExplored: 0,\n preparation,\n measurement: run.measurement,\n metadata,\n }),\n )\n const proposal = createAgentImprovementProposal({\n runId: options.runId,\n findings,\n evaluation,\n ...(options.now ? { now: options.now } : {}),\n })\n return {\n candidateProfile,\n candidateLineage,\n experiment,\n measurements: run.measurements,\n proposal,\n }\n}\n\nfunction assertDirectCandidateReleaseWorkIsFresh(\n benchmark: AgentProfileImprovementSuiteInputs,\n lineage: AgentCandidateLineage,\n developmentScenarios: readonly CampaignScenarioIdentity[] | undefined,\n): void {\n if (lineage.developmentSplitDigest === benchmark.suite.splitDigest) {\n throw new Error('authored profile development and held-out splits must be disjoint')\n }\n if (!developmentScenarios || developmentScenarios.length === 0) return\n const development = new Set(developmentScenarios.map(canonicalCandidateDigest))\n const reused = benchmark.tasks\n .map(profileTaskScenarioIdentity)\n .filter((scenario) => development.has(canonicalCandidateDigest(scenario)))\n .map((scenario) => scenario.id)\n if (reused.length > 0) {\n throw new Error(\n `authored profile release reuses development scenario(s): [${reused.join(', ')}]`,\n )\n }\n}\n","/**\n * Capability manifest types and conversion from the certified profile wire format.\n * Consumers own binding admission and execution.\n *\n * @stable\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 structural JSON Schema object describing a tool's parameters. */\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 supported by the manifest schema. */\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 consumer resolves the live secret per tenant,\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 * Describes how a capability is backed.\n * Consumers must admit a binding before executing it.\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 // `sqlite` is the only backend a manifest may name: nothing provisions another, and the whole\n // arm is refused at resolve time until it clears the E3 admission bar.\n | { kind: 'memory-store'; provision: 'sqlite'; 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 represented by the manifest schema. */\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 — consumers can fold 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/** Materialized capability surfaces supplied by a consumer-owned executor. */\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 consumer rejected a binding that its executor does not admit.\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 * `composeCertifiedPrompt` folds it before other prompt artifacts.\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 type AgentProfileMeasuredSurface,\n agentImprovementProfileSurfaceDigest,\n agentImprovementTargetProfileDiffs,\n assertProfileImprovementTargetsShareIdentity,\n isAgentProfileMeasuredSurface,\n} from './improvement-surfaces'\n\nexport type AgentImprovementProfileActivationTarget = Omit<\n AgentImprovementActivationTargetPlan,\n 'surface'\n> & {\n surface: AgentImprovementProfileSurface\n}\n\ntype AgentProfileImprovementTransitionTarget = Omit<\n AgentImprovementActivationTargetPlan,\n 'surface'\n> & {\n surface: AgentProfileMeasuredSurface\n}\n\nexport type AgentImprovementProfileTargetState = Omit<\n AgentImprovementActivationTargetState,\n 'surface'\n> & { surface: AgentProfileMeasuredSurface }\n\nexport type AgentImprovementProfileTargetTransition = Omit<\n AgentImprovementActivationTargetTransition,\n 'surface'\n> & { surface: AgentProfileMeasuredSurface }\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 if ('profileTransition' in input) {\n const targets = profileTargets(input.profileTransition.targets)\n assertUniqueProfileTargets(targets)\n const current = readCurrentProfiles(input.currentByIdentity, targets)\n if ('status' in current) return immutableCandidateValue(current)\n return prepareProfileImprovementActivation(input, targets, current)\n }\n const targets = input.targets\n assertUniqueProfileTargets(targets)\n const current = readCurrentProfiles(input.currentByIdentity, targets)\n if ('status' in current) return immutableCandidateValue(current)\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 AgentProfileImprovementTransitionTarget,\n ...AgentProfileImprovementTransitionTarget[],\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 AgentProfileImprovementTransitionTarget[],\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 AgentProfileImprovementTransitionTarget,\n ...AgentProfileImprovementTransitionTarget[],\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: AgentProfileImprovementTransitionTarget\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 AgentProfileImprovementTransitionTarget[],\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): [AgentProfileImprovementTransitionTarget, ...AgentProfileImprovementTransitionTarget[]] {\n if (!targets.every((target) => isAgentProfileMeasuredSurface(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 AgentProfileImprovementTransitionTarget,\n ...AgentProfileImprovementTransitionTarget[],\n ]\n}\n\nfunction assertUniqueProfileTargets(\n targets: readonly AgentProfileImprovementTransitionTarget[],\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 * `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 * @stable\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 * @module\n * @stable\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 AgentProfileCandidateMeasurementExecutor,\n AuthoredAgentProfileCandidateLineage,\n AuthoredAgentProfileDiffOptions,\n ProposeAuthoredAgentProfileImprovementOptions,\n ProposeAuthoredAgentProfileImprovementResult,\n} from './authored-profile-improvement'\nexport { proposeAuthoredAgentProfileImprovement } from './authored-profile-improvement'\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 {\n AppliedIntelligence,\n IntelligenceAgent,\n IntelligenceHookConfig,\n IntelligenceWrapped,\n} from './with-intelligence'\nexport { withIntelligence } from './with-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,IAA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