@agent-surface/core 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-77YRWAXY.js +915 -0
- package/dist/chunk-77YRWAXY.js.map +1 -0
- package/dist/explain.d.ts +103 -0
- package/dist/explain.js +123 -0
- package/dist/explain.js.map +1 -0
- package/dist/index.d.ts +3 -758
- package/dist/index.js +55 -859
- package/dist/index.js.map +1 -1
- package/dist/registry-DmWUlnta.d.ts +759 -0
- package/package.json +9 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/errors.ts","../src/ids.ts","../src/utils.ts","../src/schema.ts","../src/definition.ts","../src/policy.ts","../src/audit.ts","../src/events.ts","../src/confirmation.ts","../src/internal.ts","../src/invoke.ts","../src/snapshot.ts","../src/registry.ts","../src/toolset.ts"],"sourcesContent":["/** JSON value constraint: every agent-crossing payload MUST be a JsonValue. */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/** A JSON Schema document restricted to the supported subset (docs/03 D19). */\nexport type JsonSchema = Record<string, unknown>;\n\nexport type AgentEnvironment = \"development\" | \"production\" | \"test\";\n\nexport type AgentEffect =\n | \"read\"\n | \"local-state\"\n | \"navigation\"\n | \"server-query\"\n | \"server-mutation\"\n | \"external-side-effect\"\n | \"destructive\";\n\nexport type AgentProcedureEffect =\n | \"server-query\"\n | \"server-mutation\"\n | \"external-side-effect\"\n | \"destructive\";\n\nexport interface AgentConsumer {\n id: string;\n kind: \"embedded\" | \"webmcp\" | \"mcp-bridge\" | \"test\" | \"other\";\n /** Free-form grant strings interpreted by host policies. */\n grants?: string[];\n}\n\nexport interface AgentRouteInfo {\n path: string;\n params?: Record<string, string>;\n}\n\n/**\n * Concurrency group for an action or procedure reference (D25). Not\n * model-visible: it is runtime behavior, not planning information.\n *\n * - `instance` (default) — every action on the registration shares one FIFO\n * queue. Safest: two actions on the same component can never interleave.\n * - `capability` — one queue per capability, so a slow export does not block\n * closing a drawer.\n * - `key` — one queue per author-chosen key, for actions that contend over\n * the same resource across capabilities.\n * - `parallel` — bounded parallelism; `max` is required and must be ≥ 1.\n *\n * `queueDepth` overrides `limits.actionQueueDepth` for this group only.\n */\nexport type AgentConcurrency =\n | { mode: \"instance\"; queueDepth?: number }\n | { mode: \"capability\"; queueDepth?: number }\n | { mode: \"key\"; key: string; queueDepth?: number }\n | { mode: \"parallel\"; max: number; queueDepth?: number };\n\nexport interface AgentSurfaceLimits {\n maxComponentDescription: number; // 500 chars\n maxCapabilityDescription: number; // 300 chars\n maxMetaBytes: number; // 2048\n maxOutputBytes: number; // 32_768\n maxSchemaBytes: number; // 16_384\n maxSchemaDepth: number; // 8\n observationTimeoutMs: number; // 5_000\n actionTimeoutMs: number; // 10_000\n procedureTimeoutMs: number; // 30_000\n actionQueueDepth: number; // 2\n maxConcurrentObservationsPerConsumer: number; // 8 (D24)\n maxConcurrentObservationsTotal: number; // 32 (D24)\n maxQueuedObservationsPerConsumer: number; // 8 (D24)\n dedupeCacheSize: number; // 200 entries\n dedupeCacheTtlMs: number; // 600_000\n tombstoneSize: number; // 100 entries\n tombstoneTtlMs: number; // 300_000\n confirmationTtlMs: number;\n maxPendingConfirmations: number; // 32 (D24; overflow fails RATE_LIMITED, no record) // 120_000\n}\n\nexport const DEFAULT_LIMITS: AgentSurfaceLimits = {\n maxComponentDescription: 500,\n maxCapabilityDescription: 300,\n maxMetaBytes: 2048,\n maxOutputBytes: 32_768,\n maxSchemaBytes: 16_384,\n maxSchemaDepth: 8,\n observationTimeoutMs: 5_000,\n actionTimeoutMs: 10_000,\n procedureTimeoutMs: 30_000,\n actionQueueDepth: 2,\n maxConcurrentObservationsPerConsumer: 8,\n maxConcurrentObservationsTotal: 32,\n maxQueuedObservationsPerConsumer: 8,\n dedupeCacheSize: 200,\n dedupeCacheTtlMs: 600_000,\n tombstoneSize: 100,\n tombstoneTtlMs: 300_000,\n confirmationTtlMs: 120_000,\n maxPendingConfirmations: 32,\n};\n\nexport type Unsubscribe = () => void;\n","import type { JsonValue } from \"./types.js\";\n\n/** The closed agent-facing error enum — one runtime source, cross-validated\n * against spec/error-matrix.json (docs/07 §principles, AS-ERR-001). */\nexport const AGENT_CAPABILITY_ERROR_CODES = [\n \"CAPABILITY_NOT_FOUND\",\n \"CAPABILITY_NOT_AVAILABLE\",\n \"AMBIGUOUS_INSTANCE\",\n \"COMPONENT_UNMOUNTED\",\n \"STALE_CAPABILITY\",\n \"INVOCATION_CONFLICT\",\n \"INVALID_INPUT\",\n \"NOT_AUTHENTICATED\",\n \"NOT_AUTHORIZED\",\n \"PRECONDITION_FAILED\",\n \"CONFIRMATION_REQUIRED\",\n \"CONFIRMATION_INVALID\",\n \"RATE_LIMITED\",\n \"TIMEOUT\",\n \"CANCELLED\",\n \"EXECUTION_FAILED\",\n] as const;\n\nexport type AgentCapabilityErrorCode = (typeof AGENT_CAPABILITY_ERROR_CODES)[number];\n\nexport type AgentErrorRetry =\n | \"no\"\n | \"yes\"\n | \"after-refresh\"\n | \"after-delay\"\n | \"with-confirmation\"\n | \"with-changes\";\n\nexport interface AgentCapabilityErrorPayload {\n code: AgentCapabilityErrorCode;\n /** Agent-safe, imperative, ≤ 300 chars. */\n message: string;\n retry: AgentErrorRetry;\n /** Code-specific, agent-safe, JsonValue only. */\n details?: Record<string, JsonValue>;\n}\n\n/** Thrown form used inside policies/handlers; serialized at the boundary. */\nexport class AgentSurfaceError extends Error {\n readonly payload: AgentCapabilityErrorPayload;\n constructor(payload: AgentCapabilityErrorPayload, opts?: { cause?: unknown }) {\n super(payload.message, opts);\n this.name = \"AgentSurfaceError\";\n this.payload = payload;\n }\n}\n\nexport function isAgentSurfaceError(e: unknown): e is AgentSurfaceError {\n return (\n e instanceof AgentSurfaceError ||\n (typeof e === \"object\" &&\n e !== null &&\n (e as { name?: unknown }).name === \"AgentSurfaceError\" &&\n typeof (e as { payload?: unknown }).payload === \"object\")\n );\n}\n\nexport type AgentSurfaceDefinitionErrorCode =\n | \"INVALID_ID\"\n | \"INVALID_DEFINITION\"\n | \"UNSUPPORTED_SCHEMA\"\n | \"PLANE_VIOLATION\"\n | \"DUPLICATE_CAPABILITY\"\n | \"LIMIT_EXCEEDED\";\n\n/** Structural defects at registration time. Always thrown, never agent-facing. */\nexport class AgentSurfaceDefinitionError extends Error {\n readonly code: AgentSurfaceDefinitionErrorCode;\n constructor(code: AgentSurfaceDefinitionErrorCode, message: string) {\n super(`[${code}] ${message}`);\n this.name = \"AgentSurfaceDefinitionError\";\n this.code = code;\n }\n}\n","/**\n * Canonical ID grammar (docs/01 §identity):\n *\n * capability-id = plane \":\" component-type \".\" capability-name\n * plane = \"view\" | \"domain\"\n * component-type = segment *( \".\" segment )\n * segment = lowercase-letter *( lowercase-letter / digit / \"-\" )\n * capability-name = lowercase-letter *( letter / digit ) ; camelCase, no dots\n * instance-id = 1*( letter / digit / \"-\" / \"_\" )\n *\n * Underscores are reserved for the wire-name encoding (docs/09).\n */\n\nexport const MAX_ID_LENGTH = 128;\n\nconst SEGMENT_RE = /^[a-z][a-z0-9-]*$/;\nconst CAPABILITY_NAME_RE = /^[a-z][A-Za-z0-9]*$/;\nconst INSTANCE_ID_RE = /^[A-Za-z0-9_-]+$/;\n\nexport type AgentPlane = \"view\" | \"domain\";\n\nexport function isValidComponentType(type: string): boolean {\n if (type.length === 0 || type.length > MAX_ID_LENGTH) return false;\n return type.split(\".\").every((seg) => SEGMENT_RE.test(seg));\n}\n\nexport function isValidCapabilityName(name: string): boolean {\n return CAPABILITY_NAME_RE.test(name);\n}\n\nexport function isValidInstanceId(id: string): boolean {\n return id.length > 0 && id.length <= MAX_ID_LENGTH && INSTANCE_ID_RE.test(id);\n}\n\nexport function formatViewCapabilityId(componentType: string, name: string): string {\n return `view:${componentType}.${name}`;\n}\n\nexport function formatDomainCapabilityId(path: string): string {\n return `domain:${path}`;\n}\n\nexport interface ParsedViewCapabilityId {\n plane: \"view\";\n componentType: string;\n name: string;\n}\nexport interface ParsedDomainCapabilityId {\n plane: \"domain\";\n /** Canonical oRPC procedure path — treated as opaque (docs/01). */\n path: string;\n}\nexport type ParsedCapabilityId = ParsedViewCapabilityId | ParsedDomainCapabilityId;\n\n/** Parses a capability id; returns undefined when the grammar is violated. */\nexport function parseCapabilityId(id: string): ParsedCapabilityId | undefined {\n // The signature says `string`, and this is the boundary where that assumption\n // is load-bearing: a caller relaying a malformed request (an adapter whose\n // envelope carried no `capabilityId`) must get a grammar rejection —\n // CAPABILITY_NOT_FOUND — not a TypeError the pipeline reports as an internal\n // defect with retry:\"no\".\n if (typeof id !== \"string\" || id.length > MAX_ID_LENGTH) return undefined;\n if (id.startsWith(\"view:\")) {\n const rest = id.slice(\"view:\".length);\n // The capability name is everything after the LAST dot (docs/01).\n const lastDot = rest.lastIndexOf(\".\");\n if (lastDot <= 0) return undefined;\n const componentType = rest.slice(0, lastDot);\n const name = rest.slice(lastDot + 1);\n if (!isValidComponentType(componentType) || !isValidCapabilityName(name)) {\n return undefined;\n }\n return { plane: \"view\", componentType, name };\n }\n if (id.startsWith(\"domain:\")) {\n const path = id.slice(\"domain:\".length);\n if (path.length === 0) return undefined;\n return { plane: \"domain\", path };\n }\n return undefined;\n}\n\n/* ───────────────────────────── wire names ─────────────────────────────\n * encode(id): \":\" → \"_\" \".\" → \"__\"\n * decode(name): first \"_\" splits the plane (the grammar forbids \"_\" in ids);\n * \"__\" → \".\"\n * Names that would exceed 64 chars are SHORTENED: kept prefix + \"_0_\" + hash\n * of the full id. The marker makes shortening self-evident, so `decodeWireName`\n * can refuse rather than return a plausible wrong id (D30).\n */\n\nexport const MAX_WIRE_NAME_LENGTH = 64;\n\n/**\n * Marks a shortened name. Unreachable in a faithful encoding of a `view:` id\n * (the grammar forbids \"_\", and no segment or capability name may start with a\n * digit). A `domain:` path with a bare \"0\" segment would produce it — decoding\n * such a name is refused rather than guessed, which is the safe direction.\n */\nconst SHORTENED_MARKER = \"_0_\";\n/** Instance disambiguator (docs/09 rule 7); also not decodable by inspection. */\nconst INSTANCE_MARKER = \"_at_\";\n\n/** FNV-1a, base36, extended by re-seeding when more characters are asked for. */\nfunction hash36(input: string, length: number): string {\n let out = \"\";\n for (let round = 0; out.length < length; round++) {\n let hash = (0x811c9dc5 ^ round) >>> 0;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n out += hash.toString(36).padStart(7, \"0\");\n }\n return out.slice(0, length);\n}\n\nfunction rawWireName(id: string, instanceId?: string): string {\n const encoded = id.replace(\":\", \"_\").replaceAll(\".\", \"__\");\n return instanceId ? `${encoded}${INSTANCE_MARKER}${instanceId}` : encoded;\n}\n\nexport function encodeWireName(id: string): string {\n return encodeWireNameForInstance(id);\n}\n\n/**\n * Wire name disambiguated per instance: providers require UNIQUE tool names,\n * so when several live instances expose the same capability the adapter\n * appends `_at_<instanceId>` (docs/09 rule 7 — the id↔name map stays\n * authoritative).\n *\n * The result is ALWAYS ≤ 64 characters (`AS-WIRE-004`) and deterministic for a\n * given `(id, instanceId, level)` (`AS-WIRE-005`). `level` escalates the hash\n * when a catalog would otherwise emit the same name twice — see\n * {@link assignWireNames}, which owns that check; callers with a whole catalog\n * in hand should use it rather than this function directly.\n */\nexport function encodeWireNameForInstance(\n id: string,\n instanceId?: string,\n level = 0,\n): string {\n const raw = rawWireName(id, instanceId);\n // An id carrying its own \"_\" has no faithful encoding — `domain:readState__0`\n // and `domain:readState.0` both produce `domain_readState__0`, and no decoder\n // can separate them. Only reachable on the opaque `domain:` plane (the view\n // grammar forbids \"_\"), and it is what made the codec non-injective. Such ids\n // take the hashed path, which is the existing \"not decodable — consult\n // wireNameMap()\" contract rather than a new one.\n if (level === 0 && raw.length <= MAX_WIRE_NAME_LENGTH && !id.includes(\"_\")) return raw;\n const hashLength = 7 + level * 2;\n const keep = MAX_WIRE_NAME_LENGTH - SHORTENED_MARKER.length - hashLength;\n const hash = hash36(`${id}#${instanceId ?? \"\"}#${level}`, hashLength);\n return `${raw.slice(0, keep)}${SHORTENED_MARKER}${hash}`;\n}\n\nexport interface WireNameEntry {\n /** Canonical capability id. */\n id: string;\n /** Instance disambiguator, when several live instances share the id. */\n instanceId?: string;\n}\n\nexport interface WireNameAssignment {\n /** Emitted names, positionally aligned with the input entries. */\n names: string[];\n /** wireName → canonical id. Authoritative; shortened names are not decodable. */\n byName: ReadonlyMap<string, string>;\n}\n\n/**\n * Assigns wire names to a whole catalog, guaranteeing uniqueness within it\n * (`AS-WIRE-006`). Two distinct entries that collide are BOTH re-encoded at the\n * next hash level, so the outcome depends on the set of entries and not on\n * their order (`AS-WIRE-005`). Escalation is bounded; the last level appends\n * the entry's rank among the colliding keys, which terminates by construction.\n */\nexport function assignWireNames(entries: readonly WireNameEntry[]): WireNameAssignment {\n const keyOf = (e: WireNameEntry): string => `${e.id}#${e.instanceId ?? \"\"}`;\n const level = new Map<string, number>();\n const MAX_LEVEL = 3;\n\n let names = entries.map((e) => encodeWireNameForInstance(e.id, e.instanceId));\n for (let round = 0; round <= MAX_LEVEL; round++) {\n const byName = new Map<string, Set<string>>();\n entries.forEach((entry, i) => {\n const set = byName.get(names[i]!) ?? new Set<string>();\n set.add(keyOf(entry));\n byName.set(names[i]!, set);\n });\n const colliding = new Set<string>();\n for (const [, keys] of byName) {\n if (keys.size > 1) for (const key of keys) colliding.add(key);\n }\n if (colliding.size === 0) break;\n if (round === MAX_LEVEL) {\n // Terminal tie-break: rank within the sorted colliding keys is unique by\n // definition and stable for a given set.\n const ranked = [...colliding].sort();\n names = entries.map((entry, i) => {\n const rank = ranked.indexOf(keyOf(entry));\n if (rank < 0) return names[i]!;\n const suffix = `${SHORTENED_MARKER}${rank}`;\n const base = encodeWireNameForInstance(entry.id, entry.instanceId, MAX_LEVEL);\n return `${base.slice(0, MAX_WIRE_NAME_LENGTH - suffix.length)}${suffix}`;\n });\n break;\n }\n for (const key of colliding) level.set(key, (level.get(key) ?? 0) + 1);\n names = entries.map((entry) =>\n encodeWireNameForInstance(entry.id, entry.instanceId, level.get(keyOf(entry)) ?? 0),\n );\n }\n\n const byName = new Map<string, string>();\n entries.forEach((entry, i) => byName.set(names[i]!, entry.id));\n return { names, byName };\n}\n\n/**\n * Reverses `encodeWireName` for names that were encoded faithfully, and returns\n * `undefined` for every name that was not — shortened names and per-instance\n * names among them (`AS-WIRE-007`: consult `toolset.wireNameMap()` instead).\n * Returning a plausible-but-wrong canonical id would take the audit identity\n * with it, so this refuses anything it cannot re-encode byte-identically.\n *\n * Refusal is decided by what a name *is*, never by a substring it happens to\n * contain. `view:at.a.a` encodes to `view_at__a__a`, where `_at_` is the plane\n * separator meeting a segment named \"at\" — screening for the marker text cost\n * every id with an `at` or `0` segment its own faithful encoding (`AS-ID-004`).\n * Marker-bearing names are still refused, by the two checks that can tell:\n * every underscore run must be exactly two (one \".\"), and the id must re-encode\n * byte-identically.\n */\nexport function decodeWireName(name: string): string | undefined {\n const planeEnd = name.indexOf(\"_\");\n if (planeEnd <= 0) return undefined;\n const plane = name.slice(0, planeEnd);\n if (plane !== \"view\" && plane !== \"domain\") return undefined;\n const rest = name.slice(planeEnd + 1);\n // A longer run is ambiguous, not merely odd: `domain_at____x__a` is the\n // faithful encoding of BOTH `domain:at_._x.a` and `domain:at..x.a`, and\n // re-encoding cannot separate them because both produce it. Domain paths are\n // opaque, so they are the plane where a literal \"_\" can reach the codec.\n if (/_{3,}/.test(rest)) return undefined;\n const path = rest.replaceAll(\"__\", \".\");\n // The same collision in its other shape — an empty segment. `domain:at.at.`\n // shares `domain_at__at__` with `domain:at_` carrying instance `_`. The view\n // grammar already forbids empty segments; domain paths are opaque, so this is\n // where that is caught.\n if (path.split(\".\").some((segment) => segment === \"\")) return undefined;\n const id = `${plane}:${path}`;\n // The codec is injective only for grammar-valid ids with no \"_\" of their own.\n if (id.includes(\"_\") || !parseCapabilityId(id) || encodeWireName(id) !== name) return undefined;\n return id;\n}\n","import type { JsonValue } from \"./types.js\";\n\n/** Deep equality over JsonValue (order-sensitive for arrays, docs/06 rule 2). */\nexport function jsonDeepEqual(a: JsonValue | undefined, b: JsonValue | undefined): boolean {\n if (a === b) return true;\n if (a === undefined || b === undefined) return false;\n if (typeof a !== typeof b || a === null || b === null) return false;\n if (Array.isArray(a) || Array.isArray(b)) {\n return (\n Array.isArray(a) &&\n Array.isArray(b) &&\n a.length === b.length &&\n a.every((v, i) => jsonDeepEqual(v, b[i] as JsonValue))\n );\n }\n if (typeof a === \"object\" && typeof b === \"object\") {\n const ka = Object.keys(a).sort();\n const kb = Object.keys(b).sort();\n return (\n ka.length === kb.length &&\n ka.every(\n (k, i) =>\n k === kb[i] &&\n jsonDeepEqual(\n (a as Record<string, JsonValue>)[k],\n (b as Record<string, JsonValue>)[k],\n ),\n )\n );\n }\n return false;\n}\n\n/** Recursive freeze of plain data (descriptors are deep-frozen JSON). */\nexport function deepFreeze<T>(value: T): T {\n if (value !== null && typeof value === \"object\" && !Object.isFrozen(value)) {\n Object.freeze(value);\n for (const key of Object.keys(value as object)) {\n deepFreeze((value as Record<string, unknown>)[key]);\n }\n }\n return value;\n}\n\n/** Structured clone via JSON semantics (strips undefined, rejects non-JSON). */\nexport function jsonClone<T>(value: T): T {\n return value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T);\n}\n\nexport function isJsonValue(value: unknown, depth = 0): value is JsonValue {\n if (depth > 64) return false;\n if (value === null) return true;\n const t = typeof value;\n if (t === \"string\" || t === \"boolean\") return true;\n if (t === \"number\") return Number.isFinite(value as number);\n if (Array.isArray(value)) return value.every((v) => isJsonValue(v, depth + 1));\n if (t === \"object\") {\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) return false;\n return Object.values(value as object).every(\n (v) => v === undefined || isJsonValue(v, depth + 1),\n );\n }\n return false;\n}\n\nexport function byteLength(value: unknown): number {\n const s = JSON.stringify(value);\n return s === undefined ? 0 : s.length;\n}\n\nconst ALPHABET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\nexport function randomBase62(length: number): string {\n let out = \"\";\n for (let i = 0; i < length; i++) {\n out += ALPHABET[Math.floor(Math.random() * ALPHABET.length)];\n }\n return out;\n}\n\n/** Truncate a string for agent-safe messages/summaries. */\nexport function truncate(s: string, max: number): string {\n return s.length <= max ? s : s.slice(0, Math.max(0, max - 1)) + \"…\";\n}\n\n/**\n * Canonical JSON encoding (docs/18 §correction 1, D21/D22): object keys\n * sorted by UTF-16 code unit, array order significant, `undefined`\n * properties omitted, `-0` encodes as `0`, non-finite numbers are defects.\n */\nexport function canonicalJson(value: JsonValue | undefined): string {\n if (value === undefined || value === null) return \"null\";\n const t = typeof value;\n if (t === \"number\") {\n if (!Number.isFinite(value)) {\n throw new Error(\"canonicalJson: non-finite numbers are not JsonValues\");\n }\n return JSON.stringify(Object.is(value, -0) ? 0 : value);\n }\n if (t === \"string\" || t === \"boolean\") return JSON.stringify(value);\n if (Array.isArray(value)) {\n return `[${value.map((v) => canonicalJson(v ?? null)).join(\",\")}]`;\n }\n const entries = Object.keys(value as Record<string, JsonValue>)\n .sort()\n .filter((k) => (value as Record<string, JsonValue | undefined>)[k] !== undefined)\n .map((k) => `${JSON.stringify(k)}:${canonicalJson((value as Record<string, JsonValue>)[k])}`);\n return `{${entries.join(\",\")}}`;\n}\n\n/** FNV-1a 64-bit over a string, hex-encoded. Non-cryptographic: used for\n * dedupe fingerprints only — confirmation evidence matches exact values,\n * never hash-only (docs/06 rule 2). */\nexport function fnv1a64(input: string): string {\n let hash = 0xcbf29ce484222325n;\n const prime = 0x100000001b3n;\n for (let i = 0; i < input.length; i++) {\n hash ^= BigInt(input.charCodeAt(i));\n hash = (hash * prime) & 0xffffffffffffffffn;\n }\n return hash.toString(16).padStart(16, \"0\");\n}\n","import type { JsonSchema, JsonValue } from \"./types.js\";\nimport { jsonDeepEqual, byteLength } from \"./utils.js\";\n\nexport interface AgentSchemaIssue {\n path: string;\n message: string;\n}\n\n/** Thrown by AgentSchema.parse on invalid input; carries safe, structured issues. */\nexport class AgentSchemaError extends Error {\n readonly issues: AgentSchemaIssue[];\n constructor(issues: AgentSchemaIssue[]) {\n super(issues.map((i) => `${i.path || \"$\"}: ${i.message}`).join(\"; \") || \"Invalid value\");\n this.name = \"AgentSchemaError\";\n this.issues = issues;\n }\n}\n\nexport interface AgentSchema<T> {\n /** Agent-visible JSON Schema (draft 2020-12, restricted subset). */\n readonly jsonSchema: JsonSchema;\n /**\n * Validates and returns a typed value. MUST throw `AgentSchemaError`\n * (with a safe, structured message) on invalid input.\n */\n parse(value: unknown): T;\n}\n\n/** Minimal Standard Schema mirror (https://standardschema.dev). */\nexport interface StandardSchemaV1<I = unknown, O = I> {\n readonly \"~standard\": {\n readonly version: 1;\n readonly vendor: string;\n validate(\n value: unknown,\n ):\n | { value: O; issues?: undefined }\n | { issues: ReadonlyArray<{ message: string; path?: ReadonlyArray<PropertyKey | { key: PropertyKey }> }> }\n | Promise<unknown>;\n readonly types?: { readonly input: I; readonly output: O } | undefined;\n };\n}\n\n/**\n * Wraps any Standard Schema (Zod ≥3.24, Valibot, ArkType) as an AgentSchema.\n * The JSON Schema MUST be supplied explicitly — core does not depend on a\n * converter (docs/03, D20).\n */\nexport function fromStandardSchema<T>(\n schema: StandardSchemaV1<unknown, T>,\n options: { jsonSchema: JsonSchema },\n): AgentSchema<T> {\n return {\n jsonSchema: options.jsonSchema,\n parse(value: unknown): T {\n const result = schema[\"~standard\"].validate(value);\n if (result instanceof Promise) {\n throw new AgentSchemaError([\n { path: \"\", message: \"Async schema validation is not supported in v0.1\" },\n ]);\n }\n if (result.issues) {\n throw new AgentSchemaError(\n result.issues.map((issue) => ({\n path: (issue.path ?? [])\n .map((p) => String(typeof p === \"object\" && p !== null && \"key\" in p ? p.key : p))\n .join(\".\"),\n message: issue.message,\n })),\n );\n }\n return (result as { value: T }).value;\n },\n };\n}\n\n/**\n * Builds an AgentSchema from a raw JSON Schema, validated by the built-in\n * minimal structural validator covering exactly the supported subset.\n */\nexport function fromJsonSchema<T = JsonValue>(schema: JsonSchema): AgentSchema<T> {\n return {\n jsonSchema: schema,\n parse(value: unknown): T {\n const issues = validateValueAgainstSchema(value, schema, schema, \"\");\n if (issues.length > 0) throw new AgentSchemaError(issues);\n return value as T;\n },\n };\n}\n\n/** Convenience for actions with no input / observations of constant shape. */\nexport const emptyObjectSchema: AgentSchema<Record<string, never>> = fromJsonSchema({\n type: \"object\",\n properties: {},\n additionalProperties: false,\n});\n\n/* ─────────────────── D19: supported JSON Schema subset ─────────────────── */\n\nconst ALLOWED_KEYWORDS = new Set([\n \"type\",\n \"enum\",\n \"const\",\n // objects\n \"properties\",\n \"required\",\n \"additionalProperties\",\n // arrays\n \"items\",\n \"minItems\",\n \"maxItems\",\n \"uniqueItems\",\n // strings\n \"minLength\",\n \"maxLength\",\n \"pattern\",\n \"format\",\n // numbers\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n // unions\n \"anyOf\",\n // annotations\n \"description\",\n \"default\",\n \"examples\",\n \"title\",\n \"deprecated\",\n // refs\n \"$defs\",\n \"$ref\",\n // tolerated (converter noise), ignored at validation time\n \"$schema\",\n \"$id\",\n]);\n\nconst REJECTED_KEYWORDS = new Set([\n \"oneOf\",\n \"allOf\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n \"patternProperties\",\n \"dependentRequired\",\n \"dependentSchemas\",\n \"unevaluatedProperties\",\n \"unevaluatedItems\",\n \"prefixItems\",\n \"contains\",\n \"propertyNames\",\n]);\n\nconst ALLOWED_TYPES = new Set([\n \"object\",\n \"array\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\",\n]);\n\nconst ALLOWED_FORMATS = new Set([\"date-time\", \"date\", \"uuid\", \"email\", \"uri\"]);\n\nexport interface SchemaSubsetResult {\n ok: boolean;\n reason?: string;\n}\n\n/**\n * Validates that a JSON Schema document stays inside the D19 subset.\n * Anything outside MUST be rejected at registration with INVALID_DEFINITION /\n * UNSUPPORTED_SCHEMA (docs/03, docs/07).\n */\nexport function validateJsonSchemaDocument(\n schema: JsonSchema,\n limits: { maxSchemaBytes: number; maxSchemaDepth: number },\n): SchemaSubsetResult {\n const size = byteLength(schema);\n if (size > limits.maxSchemaBytes) {\n return { ok: false, reason: `schema serializes to ${size} bytes (max ${limits.maxSchemaBytes})` };\n }\n return walkSchemaDocument(schema, \"\", 0, limits.maxSchemaDepth);\n}\n\nfunction walkSchemaDocument(\n node: unknown,\n path: string,\n depth: number,\n maxDepth: number,\n): SchemaSubsetResult {\n if (depth > maxDepth) {\n return { ok: false, reason: `schema nesting exceeds depth ${maxDepth} at ${path || \"$\"}` };\n }\n if (typeof node === \"boolean\") {\n // Boolean schemas only allowed as additionalProperties (handled by caller).\n return { ok: false, reason: `boolean schema not supported at ${path || \"$\"}` };\n }\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n return { ok: false, reason: `schema must be an object at ${path || \"$\"}` };\n }\n const obj = node as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n if (REJECTED_KEYWORDS.has(key) || !ALLOWED_KEYWORDS.has(key)) {\n return { ok: false, reason: `unsupported keyword \"${key}\" at ${path || \"$\"}` };\n }\n }\n if (\"$ref\" in obj) {\n const ref = obj.$ref;\n if (typeof ref !== \"string\" || !ref.startsWith(\"#/$defs/\")) {\n return { ok: false, reason: `only internal \"#/$defs/...\" refs are supported at ${path || \"$\"}` };\n }\n }\n if (\"type\" in obj) {\n const t = obj.type;\n const types = Array.isArray(t) ? t : [t];\n for (const one of types) {\n if (typeof one !== \"string\" || !ALLOWED_TYPES.has(one)) {\n return { ok: false, reason: `unsupported type \"${String(one)}\" at ${path || \"$\"}` };\n }\n }\n }\n if (\"format\" in obj) {\n const f = obj.format;\n if (typeof f !== \"string\" || !ALLOWED_FORMATS.has(f)) {\n return { ok: false, reason: `unsupported format \"${String(obj.format)}\" at ${path || \"$\"}` };\n }\n }\n if (\"additionalProperties\" in obj && typeof obj.additionalProperties !== \"boolean\") {\n return {\n ok: false,\n reason: `additionalProperties must be a boolean at ${path || \"$\"}`,\n };\n }\n if (\"items\" in obj) {\n if (Array.isArray(obj.items)) {\n return { ok: false, reason: `tuple \"items\" arrays are not supported at ${path || \"$\"}` };\n }\n const r = walkSchemaDocument(obj.items, `${path}.items`, depth + 1, maxDepth);\n if (!r.ok) return r;\n }\n if (\"properties\" in obj) {\n const props = obj.properties;\n if (typeof props !== \"object\" || props === null || Array.isArray(props)) {\n return { ok: false, reason: `properties must be an object at ${path || \"$\"}` };\n }\n for (const [name, sub] of Object.entries(props)) {\n const r = walkSchemaDocument(sub, `${path}.properties.${name}`, depth + 1, maxDepth);\n if (!r.ok) return r;\n }\n }\n if (\"anyOf\" in obj) {\n if (!Array.isArray(obj.anyOf) || obj.anyOf.length === 0) {\n return { ok: false, reason: `anyOf must be a non-empty array at ${path || \"$\"}` };\n }\n for (let i = 0; i < obj.anyOf.length; i++) {\n const r = walkSchemaDocument(obj.anyOf[i], `${path}.anyOf[${i}]`, depth + 1, maxDepth);\n if (!r.ok) return r;\n }\n }\n if (\"$defs\" in obj) {\n const defs = obj.$defs;\n if (typeof defs !== \"object\" || defs === null || Array.isArray(defs)) {\n return { ok: false, reason: `$defs must be an object at ${path || \"$\"}` };\n }\n for (const [name, sub] of Object.entries(defs)) {\n const r = walkSchemaDocument(sub, `${path}.$defs.${name}`, depth + 1, maxDepth);\n if (!r.ok) return r;\n }\n }\n return { ok: true };\n}\n\n/* ─────────────── built-in structural value validator ─────────────── */\n\nconst FORMAT_VALIDATORS: Record<string, (s: string) => boolean> = {\n \"date-time\": (s) => /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/.test(s),\n date: (s) => /^\\d{4}-\\d{2}-\\d{2}$/.test(s),\n uuid: (s) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s),\n email: (s) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s),\n uri: (s) => /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(s),\n};\n\nfunction typeOfValue(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n const t = typeof value;\n if (t === \"number\") return \"number\";\n return t;\n}\n\nfunction matchesType(value: unknown, type: string): boolean {\n switch (type) {\n case \"object\":\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n case \"array\":\n return Array.isArray(value);\n case \"string\":\n return typeof value === \"string\";\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"integer\":\n return typeof value === \"number\" && Number.isInteger(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"null\":\n return value === null;\n default:\n return false;\n }\n}\n\n/**\n * Validates a value against a subset schema. Returns issues (empty = valid).\n * JSON Schema semantics: `default` is annotation-only and never applied.\n */\nexport function validateValueAgainstSchema(\n value: unknown,\n schema: unknown,\n root: JsonSchema,\n path: string,\n): AgentSchemaIssue[] {\n if (typeof schema !== \"object\" || schema === null) return [];\n let node = schema as Record<string, unknown>;\n\n if (typeof node.$ref === \"string\") {\n const ref = node.$ref;\n const defName = ref.slice(\"#/$defs/\".length);\n const defs = root.$defs as Record<string, unknown> | undefined;\n const resolved = defs?.[defName];\n if (typeof resolved !== \"object\" || resolved === null) {\n return [{ path, message: `unresolvable $ref \"${ref}\"` }];\n }\n node = resolved as Record<string, unknown>;\n }\n\n const issues: AgentSchemaIssue[] = [];\n\n if (\"const\" in node) {\n if (!jsonDeepEqual(value as JsonValue, node.const as JsonValue)) {\n issues.push({ path, message: `must equal the constant ${JSON.stringify(node.const)}` });\n return issues;\n }\n }\n\n if (Array.isArray(node.enum)) {\n const ok = node.enum.some((candidate) => jsonDeepEqual(value as JsonValue, candidate as JsonValue));\n if (!ok) {\n issues.push({ path, message: `must be one of ${JSON.stringify(node.enum)}` });\n return issues;\n }\n }\n\n if (Array.isArray(node.anyOf)) {\n const anyOk = node.anyOf.some(\n (branch) => validateValueAgainstSchema(value, branch, root, path).length === 0,\n );\n if (!anyOk) {\n issues.push({ path, message: \"does not match any allowed variant\" });\n return issues;\n }\n }\n\n if (\"type\" in node) {\n const types = Array.isArray(node.type) ? node.type : [node.type];\n const ok = types.some((t) => typeof t === \"string\" && matchesType(value, t));\n if (!ok) {\n issues.push({\n path,\n message: `expected ${types.join(\" | \")}, got ${typeOfValue(value)}`,\n });\n return issues;\n }\n }\n\n if (typeof value === \"string\") {\n if (typeof node.minLength === \"number\" && value.length < node.minLength) {\n issues.push({ path, message: `must be at least ${node.minLength} characters` });\n }\n if (typeof node.maxLength === \"number\" && value.length > node.maxLength) {\n issues.push({ path, message: `must be at most ${node.maxLength} characters` });\n }\n if (typeof node.pattern === \"string\") {\n let re: RegExp | undefined;\n try {\n re = new RegExp(node.pattern);\n } catch {\n // invalid pattern is a schema-document defect; ignore at value time\n }\n if (re && !re.test(value)) {\n issues.push({ path, message: `must match pattern ${node.pattern}` });\n }\n }\n if (typeof node.format === \"string\") {\n const check = FORMAT_VALIDATORS[node.format];\n if (check && !check(value)) {\n issues.push({ path, message: `must be a valid ${node.format}` });\n }\n }\n }\n\n if (typeof value === \"number\") {\n if (typeof node.minimum === \"number\" && value < node.minimum) {\n issues.push({ path, message: `must be >= ${node.minimum}` });\n }\n if (typeof node.maximum === \"number\" && value > node.maximum) {\n issues.push({ path, message: `must be <= ${node.maximum}` });\n }\n if (typeof node.exclusiveMinimum === \"number\" && value <= node.exclusiveMinimum) {\n issues.push({ path, message: `must be > ${node.exclusiveMinimum}` });\n }\n if (typeof node.exclusiveMaximum === \"number\" && value >= node.exclusiveMaximum) {\n issues.push({ path, message: `must be < ${node.exclusiveMaximum}` });\n }\n if (typeof node.multipleOf === \"number\" && node.multipleOf > 0) {\n const quotient = value / node.multipleOf;\n if (Math.abs(quotient - Math.round(quotient)) > 1e-9) {\n issues.push({ path, message: `must be a multiple of ${node.multipleOf}` });\n }\n }\n }\n\n if (Array.isArray(value)) {\n if (typeof node.minItems === \"number\" && value.length < node.minItems) {\n issues.push({ path, message: `must have at least ${node.minItems} items` });\n }\n if (typeof node.maxItems === \"number\" && value.length > node.maxItems) {\n issues.push({ path, message: `must have at most ${node.maxItems} items` });\n }\n if (node.uniqueItems === true) {\n const seen = new Set<string>();\n for (const item of value) {\n const key = JSON.stringify(item);\n if (seen.has(key)) {\n issues.push({ path, message: \"items must be unique\" });\n break;\n }\n seen.add(key);\n }\n }\n if (node.items !== undefined) {\n value.forEach((item, i) => {\n issues.push(...validateValueAgainstSchema(item, node.items, root, `${path}[${i}]`));\n });\n }\n }\n\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n const record = value as Record<string, unknown>;\n const props = (node.properties ?? {}) as Record<string, unknown>;\n if (Array.isArray(node.required)) {\n for (const req of node.required) {\n if (typeof req === \"string\" && record[req] === undefined) {\n issues.push({ path: path ? `${path}.${req}` : req, message: \"is required\" });\n }\n }\n }\n for (const [name, sub] of Object.entries(props)) {\n if (record[name] !== undefined) {\n issues.push(\n ...validateValueAgainstSchema(record[name], sub, root, path ? `${path}.${name}` : name),\n );\n }\n }\n if (node.additionalProperties === false) {\n for (const key of Object.keys(record)) {\n if (!(key in props)) {\n issues.push({\n path: path ? `${path}.${key}` : key,\n message: \"is not an allowed property\",\n });\n }\n }\n }\n }\n\n return issues;\n}\n","import type {\n AgentConcurrency,\n AgentConsumer,\n AgentProcedureEffect,\n AgentSurfaceLimits,\n JsonSchema,\n JsonValue,\n} from \"./types.js\";\nimport type { AgentSchema } from \"./schema.js\";\nimport { validateJsonSchemaDocument } from \"./schema.js\";\nimport type { AgentPolicy } from \"./policy.js\";\nimport { AgentSurfaceDefinitionError } from \"./errors.js\";\nimport {\n isValidCapabilityName,\n isValidComponentType,\n isValidInstanceId,\n formatViewCapabilityId,\n MAX_ID_LENGTH,\n} from \"./ids.js\";\nimport { byteLength, isJsonValue } from \"./utils.js\";\n\n/* ───────────────────────── handler contexts ───────────────────────── */\n\nexport interface AgentReadContext {\n capabilityId: string;\n registrationId: string;\n consumer: AgentConsumer;\n /** Host context (user, tenant, env…) from RegistryOptions.context(). */\n host: Readonly<Record<string, unknown>>;\n}\n\nexport interface AgentActionContext extends AgentReadContext {\n invocationId: string;\n /** Aborted on timeout, external cancellation, or unmount. Cooperative. */\n signal: AbortSignal;\n /** Present iff this invocation carries approved confirmation evidence. */\n confirmation?: { id: string; approvedAt: string };\n}\n\nexport interface PreconditionFailure {\n message: string; // agent-safe\n details?: Record<string, JsonValue>; // agent-safe\n}\n\n/* ───────────────────────── capability definitions ───────────────────────── */\n\nexport interface AgentObservationDefinition<TOut extends JsonValue> {\n /** Agent-visible description, ≤ 300 chars. */\n description: string;\n output: AgentSchema<TOut>;\n /**\n * Reads current semantic state. MUST be side-effect free. SHOULD be\n * synchronous; MAY return a promise (subject to observation timeout).\n */\n read(ctx: AgentReadContext): TOut | Promise<TOut>;\n /** Availability predicate, re-evaluated at snapshot and at invocation. */\n when?: () => boolean;\n unavailableReason?: string | (() => string);\n policies?: AgentPolicy[];\n meta?: Record<string, JsonValue>;\n timeoutMs?: number;\n}\n\nexport interface AgentActionDefinition<\n TIn extends JsonValue,\n TOut extends JsonValue | void = void,\n> {\n description: string;\n input: AgentSchema<TIn>;\n output?: AgentSchema<Exclude<TOut, void>>;\n /** View actions MUST be \"local-state\" | \"navigation\" (plane rule, docs/01). */\n effect: \"local-state\" | \"navigation\";\n idempotent?: boolean; // default false\n reversible?: boolean; // default true\n confirmation?: \"never\" | \"optional\" | \"required\"; // default \"never\"\n audit?: \"none\" | \"metadata\" | \"full\"; // default \"metadata\"\n when?: () => boolean;\n unavailableReason?: string | (() => string);\n /**\n * Input-aware validation beyond the schema. Return void to pass; return\n * (or throw) a PreconditionFailure to fail with PRECONDITION_FAILED.\n */\n precondition?(input: TIn, ctx: AgentReadContext): void | PreconditionFailure;\n /**\n * TOut is inferred from `output` only (NoInfer): the schema is the source\n * of truth and the handler's return is checked against it.\n */\n execute(input: TIn, ctx: AgentActionContext): NoInfer<TOut> | Promise<NoInfer<TOut>>;\n policies?: AgentPolicy[];\n meta?: Record<string, JsonValue>;\n timeoutMs?: number;\n /** Concurrency group (D25). Default `{mode:\"instance\"}` — serialize with\n * every other action on this component instance. */\n concurrency?: AgentConcurrency;\n}\n\n/** Identity helpers that fix generics for record-literal authoring. */\nexport function observation<TOut extends JsonValue>(\n def: AgentObservationDefinition<TOut>,\n): AgentObservationDefinition<TOut> {\n return def;\n}\nexport function action<TIn extends JsonValue, TOut extends JsonValue | void = void>(\n def: AgentActionDefinition<TIn, TOut>,\n): AgentActionDefinition<TIn, TOut> {\n return def;\n}\nexport function defineAgentComponent(def: AgentComponentDefinition): AgentComponentDefinition {\n return def;\n}\n\n/* ───────────────────────── procedure references ─────────────────────────\n * Bindings are constructed by @agent-surface/orpc (docs/05); core only\n * consumes this structural shape (zero-dependency rule, docs/02).\n */\n\nexport interface ProcedureCallInfo {\n invocationId: string;\n consumer: AgentConsumer;\n signal: AbortSignal;\n confirmation?: { id: string; approvedAt: string };\n}\n\nexport interface AgentProcedureExecutor {\n execute(req: {\n path: string;\n input: JsonValue; // effective, validated input\n info: ProcedureCallInfo;\n }): Promise<JsonValue>;\n /** Known exposed procedure paths (manifest), used for suffix-collision lint. */\n paths?: ReadonlyArray<string>;\n}\n\nexport interface AgentProcedureRefDescriptor {\n readonly id: string; // \"domain:devices.disable\"\n readonly path: string; // \"devices.disable\"\n readonly description: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly effect: AgentProcedureEffect;\n /** Server-declared flag the client must respect (approval required). */\n readonly requiresApproval?: boolean;\n}\n\nexport interface AgentProcedureBindingRuntimeConfig {\n when?: () => boolean;\n unavailableReason?: string | (() => string);\n /** UI-derived inputs, evaluated at EXECUTION time (docs/05 rule 4). */\n bind?: () => Record<string, JsonValue>;\n overridableFields?: ReadonlyArray<string>;\n /** Escalate (never lower) the manifest's confirmation requirement. */\n confirmation?: \"optional\" | \"required\";\n policies?: AgentPolicy[];\n /** Contextual description appended to the manifest description. */\n describe?: () => string;\n meta?: Record<string, JsonValue>;\n /** Concurrency group (D25). Default: one group per procedure identity per\n * referencing registration — conservative, and it never couples a domain\n * call to unrelated view actions. */\n concurrency?: AgentConcurrency;\n}\n\nexport interface AgentProcedureBinding<TIn extends object = object, TOut = unknown> {\n readonly kind: \"procedure-binding\";\n readonly ref: AgentProcedureRefDescriptor;\n readonly config: AgentProcedureBindingRuntimeConfig;\n /** Keys produced by bind(), captured at binding creation. */\n readonly boundKeys: ReadonlyArray<string>;\n /** Bound keys the agent may NOT supply (bound minus overridable). */\n readonly lockedKeys: ReadonlyArray<string>;\n /** Agent-facing (reduced) input schema per D7 rule 1. */\n readonly reducedInputSchema: JsonSchema;\n /** Optional link to the owning view component. */\n contextLink?: { type: string; instanceId: string };\n /** Phantom fields carrying the generics (never read at runtime). */\n readonly __types?: { input: TIn; output: TOut };\n}\n\n/* ───────────────────────── component definition ───────────────────────── */\n\nexport interface AgentComponentDefinition {\n /** Component type, e.g. \"devices.table\". MUST match the id grammar. */\n type: string;\n /** Distinguishes simultaneous mounts. Defaults to \"default\". Data-derived. */\n instanceId?: string;\n /** Agent-visible description, ≤ 500 chars. Required, non-empty. */\n description: string;\n /** Optional containment link for hierarchy-aware consumers. */\n parent?: { type: string; instanceId?: string };\n /** Agent-visible metadata. JsonValue, ≤ 2 kB serialized. */\n meta?: Record<string, JsonValue>;\n /** Internal metadata for policies/audit sinks. NEVER serialized. */\n internal?: Record<string, unknown>;\n /** Policies applied to every capability of this component. */\n policies?: AgentPolicy[];\n /** Registrant trust label; default \"first-party\". */\n origin?: string;\n /** Snapshot ordering/budget priority; higher survives budgets longer. */\n priority?: number;\n /** Master switch; false ⇒ all capabilities visible-disabled. */\n enabled?: boolean;\n\n observations?: Record<string, AgentObservationDefinition<any>>;\n actions?: Record<string, AgentActionDefinition<any, any>>;\n /** Domain references; normally added via @agent-surface/orpc. */\n procedures?: AgentProcedureBinding<any, any>[];\n}\n\n/* ───────────────────────── definition validation ───────────────────────── */\n\nconst COMPONENT_KEYS = new Set([\n \"type\",\n \"instanceId\",\n \"description\",\n \"parent\",\n \"meta\",\n \"internal\",\n \"policies\",\n \"origin\",\n \"priority\",\n \"enabled\",\n \"observations\",\n \"actions\",\n \"procedures\",\n]);\n\nconst OBSERVATION_KEYS = new Set([\n \"description\",\n \"output\",\n \"read\",\n \"when\",\n \"unavailableReason\",\n \"policies\",\n \"meta\",\n \"timeoutMs\",\n]);\n\nconst ACTION_KEYS = new Set([\n \"description\",\n \"input\",\n \"output\",\n \"effect\",\n \"idempotent\",\n \"reversible\",\n \"confirmation\",\n \"audit\",\n \"when\",\n \"unavailableReason\",\n \"precondition\",\n \"execute\",\n \"policies\",\n \"meta\",\n \"timeoutMs\",\n \"concurrency\",\n]);\n\nconst VIEW_EFFECTS = new Set([\"local-state\", \"navigation\"]);\nconst SERVER_EFFECTS = new Set([\n \"server-query\",\n \"server-mutation\",\n \"external-side-effect\",\n \"destructive\",\n]);\n\nfunction fail(code: ConstructorParameters<typeof AgentSurfaceDefinitionError>[0], message: string): never {\n throw new AgentSurfaceDefinitionError(code, message);\n}\n\nfunction checkMeta(meta: unknown, where: string, limits: AgentSurfaceLimits): void {\n if (meta === undefined) return;\n if (!isJsonValue(meta) || typeof meta !== \"object\" || Array.isArray(meta)) {\n fail(\"INVALID_DEFINITION\", `${where}: meta must be a JsonValue record`);\n }\n if (byteLength(meta) > limits.maxMetaBytes) {\n fail(\"LIMIT_EXCEEDED\", `${where}: meta exceeds ${limits.maxMetaBytes} bytes`);\n }\n}\n\n/** D25: the group shape is closed and `parallel` must be explicitly bounded —\n * an unbounded group would be the one place the runtime stops being bounded. */\nfunction checkConcurrency(concurrency: AgentConcurrency | undefined, where: string): void {\n if (concurrency === undefined) return;\n if (typeof concurrency !== \"object\" || concurrency === null) {\n fail(\"INVALID_DEFINITION\", `${where}: concurrency must be an object`);\n }\n const { mode } = concurrency;\n if (![\"instance\", \"capability\", \"key\", \"parallel\"].includes(mode)) {\n fail(\"INVALID_DEFINITION\", `${where}: invalid concurrency mode \"${String(mode)}\"`);\n }\n if (mode === \"key\" && (typeof concurrency.key !== \"string\" || concurrency.key.length === 0)) {\n fail(\"INVALID_DEFINITION\", `${where}: concurrency mode \"key\" requires a non-empty key`);\n }\n if (\n mode === \"parallel\" &&\n (typeof concurrency.max !== \"number\" || !Number.isInteger(concurrency.max) || concurrency.max < 1)\n ) {\n fail(\n \"INVALID_DEFINITION\",\n `${where}: concurrency mode \"parallel\" requires an integer max ≥ 1 (unbounded parallelism is not offered)`,\n );\n }\n const depth = concurrency.queueDepth;\n if (depth !== undefined && (!Number.isInteger(depth) || depth < 0)) {\n fail(\"INVALID_DEFINITION\", `${where}: concurrency queueDepth must be a non-negative integer`);\n }\n}\n\nfunction checkSchema(schema: AgentSchema<any> | undefined, where: string, limits: AgentSurfaceLimits): void {\n if (schema === undefined) return;\n if (typeof schema !== \"object\" || schema === null || typeof schema.parse !== \"function\" || typeof schema.jsonSchema !== \"object\") {\n fail(\"INVALID_DEFINITION\", `${where}: expected an AgentSchema ({ jsonSchema, parse })`);\n }\n const result = validateJsonSchemaDocument(schema.jsonSchema, limits);\n if (!result.ok) fail(\"UNSUPPORTED_SCHEMA\", `${where}: ${result.reason}`);\n}\n\n/**\n * Validates a component definition structurally. Throws\n * AgentSurfaceDefinitionError in every environment — structural defects are\n * deterministic code bugs (docs/03 §registry).\n */\nexport function validateComponentDefinition(\n def: AgentComponentDefinition,\n limits: AgentSurfaceLimits,\n opts: { hasProcedureExecutor: boolean },\n): void {\n if (typeof def !== \"object\" || def === null) {\n fail(\"INVALID_DEFINITION\", \"definition must be an object\");\n }\n for (const key of Object.keys(def)) {\n if (!COMPONENT_KEYS.has(key)) {\n fail(\"INVALID_DEFINITION\", `unknown definition field \"${key}\"`);\n }\n }\n if (typeof def.type !== \"string\" || !isValidComponentType(def.type)) {\n fail(\"INVALID_ID\", `invalid component type \"${String(def.type)}\"`);\n }\n const instanceId = def.instanceId ?? \"default\";\n if (!isValidInstanceId(instanceId)) {\n fail(\"INVALID_ID\", `invalid instanceId \"${instanceId}\" for component \"${def.type}\"`);\n }\n if (typeof def.description !== \"string\" || def.description.trim().length === 0) {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": description is required and must be non-empty`);\n }\n if (def.description.length > limits.maxComponentDescription) {\n fail(\n \"LIMIT_EXCEEDED\",\n `component \"${def.type}\": description exceeds ${limits.maxComponentDescription} chars`,\n );\n }\n if (def.parent !== undefined) {\n if (\n typeof def.parent !== \"object\" ||\n def.parent === null ||\n typeof def.parent.type !== \"string\" ||\n !isValidComponentType(def.parent.type) ||\n (def.parent.instanceId !== undefined && !isValidInstanceId(def.parent.instanceId))\n ) {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": invalid parent link`);\n }\n }\n checkMeta(def.meta, `component \"${def.type}\"`, limits);\n if (def.priority !== undefined && typeof def.priority !== \"number\") {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": priority must be a number`);\n }\n if (def.origin !== undefined && typeof def.origin !== \"string\") {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": origin must be a string`);\n }\n\n const seenNames = new Set<string>();\n const checkName = (name: string, kind: string): void => {\n if (!isValidCapabilityName(name)) {\n fail(\"INVALID_ID\", `component \"${def.type}\": invalid ${kind} name \"${name}\"`);\n }\n const capabilityId = formatViewCapabilityId(def.type, name);\n if (capabilityId.length > MAX_ID_LENGTH) {\n fail(\"INVALID_ID\", `capability id \"${capabilityId}\" exceeds ${MAX_ID_LENGTH} chars`);\n }\n if (seenNames.has(name)) {\n fail(\"DUPLICATE_CAPABILITY\", `component \"${def.type}\": duplicate capability name \"${name}\"`);\n }\n seenNames.add(name);\n };\n\n for (const [name, obs] of Object.entries(def.observations ?? {})) {\n checkName(name, \"observation\");\n const where = `observation \"${def.type}.${name}\"`;\n for (const key of Object.keys(obs)) {\n if (!OBSERVATION_KEYS.has(key)) fail(\"INVALID_DEFINITION\", `${where}: unknown field \"${key}\"`);\n }\n if (typeof obs.description !== \"string\" || obs.description.trim().length === 0) {\n fail(\"INVALID_DEFINITION\", `${where}: description is required`);\n }\n if (obs.description.length > limits.maxCapabilityDescription) {\n fail(\"LIMIT_EXCEEDED\", `${where}: description exceeds ${limits.maxCapabilityDescription} chars`);\n }\n if (typeof obs.read !== \"function\") fail(\"INVALID_DEFINITION\", `${where}: read() is required`);\n checkSchema(obs.output, `${where} output`, limits);\n if (obs.output === undefined) fail(\"INVALID_DEFINITION\", `${where}: output schema is required`);\n checkMeta(obs.meta, where, limits);\n }\n\n for (const [name, act] of Object.entries(def.actions ?? {})) {\n checkName(name, \"action\");\n const where = `action \"${def.type}.${name}\"`;\n for (const key of Object.keys(act)) {\n if (!ACTION_KEYS.has(key)) fail(\"INVALID_DEFINITION\", `${where}: unknown field \"${key}\"`);\n }\n if (typeof act.description !== \"string\" || act.description.trim().length === 0) {\n fail(\"INVALID_DEFINITION\", `${where}: description is required`);\n }\n if (act.description.length > limits.maxCapabilityDescription) {\n fail(\"LIMIT_EXCEEDED\", `${where}: description exceeds ${limits.maxCapabilityDescription} chars`);\n }\n if (typeof act.execute !== \"function\") fail(\"INVALID_DEFINITION\", `${where}: execute() is required`);\n if (!VIEW_EFFECTS.has(act.effect as string)) {\n if (SERVER_EFFECTS.has(act.effect as string)) {\n fail(\n \"PLANE_VIOLATION\",\n `${where}: view actions cannot declare server effect \"${act.effect}\" — define an oRPC procedure and reference it (docs/05)`,\n );\n }\n fail(\"INVALID_DEFINITION\", `${where}: effect must be \"local-state\" or \"navigation\"`);\n }\n if (act.confirmation !== undefined && ![\"never\", \"optional\", \"required\"].includes(act.confirmation)) {\n fail(\"INVALID_DEFINITION\", `${where}: invalid confirmation \"${act.confirmation}\"`);\n }\n if (act.audit !== undefined && ![\"none\", \"metadata\", \"full\"].includes(act.audit)) {\n fail(\"INVALID_DEFINITION\", `${where}: invalid audit level \"${act.audit}\"`);\n }\n if (act.input === undefined) fail(\"INVALID_DEFINITION\", `${where}: input schema is required`);\n checkSchema(act.input, `${where} input`, limits);\n checkSchema(act.output, `${where} output`, limits);\n checkMeta(act.meta, where, limits);\n checkConcurrency(act.concurrency, where);\n }\n\n const procedures = def.procedures ?? [];\n if (procedures.length > 0 && !opts.hasProcedureExecutor) {\n fail(\n \"PLANE_VIOLATION\",\n `component \"${def.type}\": procedure bindings require an installed procedure executor (registry.setProcedureExecutor)`,\n );\n }\n for (const binding of procedures) {\n if (typeof binding !== \"object\" || binding === null || binding.kind !== \"procedure-binding\") {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": invalid procedure binding`);\n }\n const ref = binding.ref;\n if (\n typeof ref !== \"object\" ||\n ref === null ||\n typeof ref.path !== \"string\" ||\n ref.path.length === 0 ||\n typeof ref.id !== \"string\" ||\n ref.id !== `domain:${ref.path}` ||\n typeof ref.description !== \"string\"\n ) {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": procedure binding has an invalid ref`);\n }\n if (!SERVER_EFFECTS.has(ref.effect as string)) {\n fail(\n \"PLANE_VIOLATION\",\n `procedure \"${ref.path}\": effect must be one of server-query | server-mutation | external-side-effect | destructive`,\n );\n }\n if (typeof binding.reducedInputSchema !== \"object\" || binding.reducedInputSchema === null) {\n fail(\"INVALID_DEFINITION\", `procedure \"${ref.path}\": missing reduced input schema`);\n }\n if (binding.config.confirmation !== undefined && ![\"optional\", \"required\"].includes(binding.config.confirmation)) {\n fail(\"INVALID_DEFINITION\", `procedure \"${ref.path}\": invalid confirmation escalation`);\n }\n checkMeta(binding.config.meta, `procedure \"${ref.path}\"`, limits);\n checkConcurrency(binding.config.concurrency, `procedure \"${ref.path}\"`);\n }\n}\n","import type {\n AgentConsumer,\n AgentEffect,\n AgentEnvironment,\n JsonValue,\n} from \"./types.js\";\nimport { AgentSurfaceError } from \"./errors.js\";\nimport type { AgentInvocationResult } from \"./invocation-types.js\";\nimport type { AuditSink } from \"./audit.js\";\n\nexport type DiscoveryDecision =\n | { decision: \"expose\" }\n | { decision: \"disable\"; reason: string } // visible-disabled\n | { decision: \"hide\" }; // absent from snapshot\n\nexport interface AgentPolicyContext {\n capabilityId: string;\n plane: \"view\" | \"domain\";\n kind: \"observation\" | \"action\" | \"procedure\";\n effect: AgentEffect;\n registrationId: string;\n consumer: AgentConsumer;\n host: Readonly<Record<string, unknown>>; // RegistryOptions.context()\n meta: {\n component?: Record<string, JsonValue>;\n capability?: Record<string, JsonValue>;\n };\n internal: Readonly<Record<string, unknown>>; // never serialized\n /** Registry environment (additive convenience for built-ins). */\n environment: AgentEnvironment;\n /** Registry's injectable clock — built-ins MUST use this, never Date.now(). */\n now(): number;\n}\n\n/** Phase-4 context: no agent input is available here, by construction (D21). */\nexport type AgentAuthorizationContext = AgentPolicyContext;\n\n/** Phase-6 context: only the validated effective input is visible (D21). */\nexport interface AgentInvocationPolicyContext extends AgentAuthorizationContext {\n invocationId: string;\n effectiveInput: JsonValue;\n}\n\nexport interface AgentPolicy {\n name: string;\n /**\n * Discovery-time filter. MUST be synchronous, cheap, side-effect free.\n * Advisory: hides/disables in catalogs. Default when absent: expose.\n */\n onDiscovery?(ctx: AgentPolicyContext): DiscoveryDecision;\n /**\n * Pre-input authority gate (pipeline phase 4): authn/authz/tenant/\n * environment/input-independent rate. MAY be async. Onion order; call\n * next() to proceed. Throw AgentSurfaceError to deny.\n */\n onAuthorize?(\n ctx: AgentAuthorizationContext,\n next: () => Promise<AgentInvocationResult>,\n ): Promise<AgentInvocationResult>;\n /**\n * Post-input invocation gate (pipeline phase 6). Receives ONLY the\n * validated effective input — never raw agent input (D21).\n */\n onInvoke?(\n ctx: AgentInvocationPolicyContext,\n next: () => Promise<AgentInvocationResult>,\n ): Promise<AgentInvocationResult>;\n}\n\n/**\n * Marker read by the invocation pipeline: policies carrying it escalate the\n * capability's confirmation requirement (docs/06 requireConfirmation).\n */\nexport const CONFIRMATION_ESCALATION: unique symbol = Symbol(\"agent-surface.confirmation-escalation\");\n\nexport interface ConfirmationEscalation {\n /** Evaluated at phase 6 over the validated effective input (D21). */\n if?: (ctx: AgentPolicyContext & { effectiveInput: JsonValue }) => boolean;\n summary?: (effectiveInput: JsonValue) => string;\n}\n\nexport type AgentPolicyWithEscalation = AgentPolicy & {\n [CONFIRMATION_ESCALATION]?: ConfirmationEscalation;\n};\n\n/** Most-restrictive-wins composition of discovery decisions (docs/06). */\nexport function evaluateDiscovery(\n policies: ReadonlyArray<AgentPolicy>,\n ctx: AgentPolicyContext,\n): DiscoveryDecision {\n let disable: { decision: \"disable\"; reason: string } | undefined;\n for (const policy of policies) {\n if (!policy.onDiscovery) continue;\n let decision: DiscoveryDecision;\n try {\n decision = policy.onDiscovery(ctx);\n } catch {\n // A throwing discovery policy is a defect; fail closed.\n return { decision: \"hide\" };\n }\n if (decision.decision === \"hide\") return decision;\n if (decision.decision === \"disable\" && !disable) disable = decision;\n }\n return disable ?? { decision: \"expose\" };\n}\n\n/** Onion composition of onAuthorize handlers (registry outermost, phase 4). */\nexport function composeAuthorizeChain(\n policies: ReadonlyArray<AgentPolicy>,\n ctx: AgentAuthorizationContext,\n core: () => Promise<AgentInvocationResult>,\n): Promise<AgentInvocationResult> {\n let index = -1;\n const dispatch = (i: number): Promise<AgentInvocationResult> => {\n if (i <= index) {\n return Promise.reject(new Error(\"policy next() called multiple times\"));\n }\n index = i;\n const policy = policies[i];\n if (!policy) return core();\n if (!policy.onAuthorize) return dispatch(i + 1);\n return policy.onAuthorize(ctx, () => dispatch(i + 1));\n };\n return dispatch(0);\n}\n\n/** Onion composition of onInvoke handlers (registry outermost, phase 6). */\nexport function composeInvokeChain(\n policies: ReadonlyArray<AgentPolicy>,\n ctx: AgentInvocationPolicyContext,\n core: () => Promise<AgentInvocationResult>,\n): Promise<AgentInvocationResult> {\n let index = -1;\n const dispatch = (i: number): Promise<AgentInvocationResult> => {\n if (i <= index) {\n return Promise.reject(new Error(\"policy next() called multiple times\"));\n }\n index = i;\n const policy = policies[i];\n if (!policy) return core();\n if (!policy.onInvoke) return dispatch(i + 1);\n return policy.onInvoke(ctx, () => dispatch(i + 1));\n };\n return dispatch(0);\n}\n\n/* ───────────────────────── built-in policies ─────────────────────────\n * Authority hides, state discloses (D11/D12): authz-style built-ins hide at\n * discovery and fail typed at invocation.\n */\n\n/** Requires ctx.host[key] (default \"user\"). Fails NOT_AUTHENTICATED; hides. */\nexport function authenticated(opts?: { key?: string }): AgentPolicy {\n const key = opts?.key ?? \"user\";\n return {\n name: \"authenticated\",\n onDiscovery(ctx) {\n return ctx.host[key] ? { decision: \"expose\" } : { decision: \"hide\" };\n },\n async onAuthorize(ctx, next) {\n if (!ctx.host[key]) {\n throw new AgentSurfaceError({\n code: \"NOT_AUTHENTICATED\",\n message: \"Sign-in is required before this capability can be used. Ask the user to sign in.\",\n retry: \"no\",\n });\n }\n return next();\n },\n };\n}\n\n/** Delegates to a host authorizer. Fails NOT_AUTHORIZED; hides at discovery. */\nexport function hasPermission(\n permission: string,\n check: (host: Record<string, unknown>, permission: string) => boolean,\n): AgentPolicy {\n return {\n name: `has-permission(${permission})`,\n onDiscovery(ctx) {\n return check({ ...ctx.host }, permission) ? { decision: \"expose\" } : { decision: \"hide\" };\n },\n async onAuthorize(ctx, next) {\n if (!check({ ...ctx.host }, permission)) {\n throw new AgentSurfaceError({\n code: \"NOT_AUTHORIZED\",\n message: \"The current user is not authorized to use this capability.\",\n retry: \"no\",\n details: { origin: \"client\" },\n });\n }\n return next();\n },\n };\n}\n\n/** Tenant boundary: hides unless current(host) === expected(ctx). */\nexport function tenantBoundary(opts: {\n current: (host: Record<string, unknown>) => string | undefined;\n expected: (ctx: AgentPolicyContext) => string | undefined;\n}): AgentPolicy {\n const matches = (ctx: AgentPolicyContext): boolean => {\n const current = opts.current({ ...ctx.host });\n const expected = opts.expected(ctx);\n return expected === undefined || current === expected;\n };\n return {\n name: \"tenant-boundary\",\n onDiscovery(ctx) {\n return matches(ctx) ? { decision: \"expose\" } : { decision: \"hide\" };\n },\n async onAuthorize(ctx, next) {\n if (!matches(ctx)) {\n throw new AgentSurfaceError({\n code: \"NOT_AUTHORIZED\",\n message: \"This capability belongs to a different tenant.\",\n retry: \"no\",\n details: { origin: \"client\" },\n });\n }\n return next();\n },\n };\n}\n\n/** Restricts to environments. Others: hidden. */\nexport function environment(allowed: AgentEnvironment[]): AgentPolicy {\n return {\n name: \"environment\",\n onDiscovery(ctx) {\n return allowed.includes(ctx.environment) ? { decision: \"expose\" } : { decision: \"hide\" };\n },\n async onAuthorize(ctx, next) {\n if (!allowed.includes(ctx.environment)) {\n throw new AgentSurfaceError({\n code: \"CAPABILITY_NOT_FOUND\",\n message: \"This capability does not exist in the current surface.\",\n retry: \"after-refresh\",\n });\n }\n return next();\n },\n };\n}\n\n/**\n * Token bucket per (consumer, capability). Advisory, input-independent —\n * runs pre-input (phase 4). Author input-aware rate policies as onInvoke.\n * Fails RATE_LIMITED. Uses the injectable clock (AS-POLICY-001).\n */\nexport function rateLimit(opts: { limit: number; windowMs: number }): AgentPolicy {\n const hits = new Map<string, number[]>();\n return {\n name: \"rate-limit\",\n async onAuthorize(ctx, next) {\n const key = `${ctx.consumer.kind}:${ctx.consumer.id} ${ctx.capabilityId}`;\n const now = ctx.now();\n const windowStart = now - opts.windowMs;\n const list = (hits.get(key) ?? []).filter((t) => t > windowStart);\n if (list.length >= opts.limit) {\n const retryAfterMs = Math.max(0, (list[0] ?? now) + opts.windowMs - now);\n throw new AgentSurfaceError({\n code: \"RATE_LIMITED\",\n message: \"Too many calls to this capability. Wait before retrying.\",\n retry: \"after-delay\",\n details: { reason: \"rate\", retryAfterMs },\n });\n }\n list.push(now);\n hits.set(key, list);\n return next();\n },\n };\n}\n\n/** Escalates confirmation to \"required\" (optionally conditionally).\n * Predicates run at phase 6 over the validated effective input (D21). */\nexport function requireConfirmation(opts?: {\n if?: (ctx: AgentPolicyContext & { effectiveInput: JsonValue }) => boolean;\n summary?: (effectiveInput: JsonValue) => string;\n}): AgentPolicy {\n const policy: AgentPolicyWithEscalation = {\n name: \"require-confirmation\",\n };\n policy[CONFIRMATION_ESCALATION] = { if: opts?.if, summary: opts?.summary };\n return policy;\n}\n\n/** Forwards invocation events to a sink at the given detail level.\n * Runs at phase 6 (onInvoke): its enrichment sees the effective input. */\nexport function audit(sink?: AuditSink, level: \"metadata\" | \"full\" = \"metadata\"): AgentPolicy {\n return {\n name: \"audit\",\n async onInvoke(ctx, next) {\n const startedAt = ctx.now();\n sink?.record({\n at: new Date(startedAt).toISOString(),\n type: \"invocation-started\",\n capabilityId: ctx.capabilityId,\n registrationId: ctx.registrationId,\n invocationId: ctx.invocationId,\n consumerId: ctx.consumer.id,\n ...(level === \"full\" ? { payload: { input: ctx.effectiveInput } } : {}),\n });\n const result = await next();\n sink?.record({\n at: new Date(ctx.now()).toISOString(),\n type: \"invocation-settled\",\n capabilityId: ctx.capabilityId,\n registrationId: ctx.registrationId,\n invocationId: ctx.invocationId,\n consumerId: ctx.consumer.id,\n status: result.status,\n ...(result.status === \"error\" ? { code: result.error.code } : {}),\n durationMs: ctx.now() - startedAt,\n ...(level === \"full\" && result.status === \"ok\" && result.output !== undefined\n ? { payload: { output: result.output } }\n : {}),\n });\n return result;\n },\n };\n}\n","import type { JsonValue } from \"./types.js\";\nimport type { AgentCapabilityErrorCode } from \"./errors.js\";\n\nexport interface AuditEvent {\n at: string; // ISO-8601\n type:\n | \"registration\"\n | \"unregistration\"\n | \"registration-rejected\"\n | \"invocation-started\"\n | \"invocation-settled\"\n | \"confirmation-requested\"\n | \"confirmation-approved\"\n | \"confirmation-denied\"\n | \"confirmation-expired\"\n | \"confirmation-consumed\"\n | \"late-settlement\"\n | \"collision-suspected\";\n capabilityId?: string;\n registrationId?: string;\n invocationId?: string;\n consumerId?: string;\n status?: \"ok\" | \"error\";\n code?: AgentCapabilityErrorCode;\n durationMs?: number;\n /** Time spent waiting for a concurrency slot (docs/06 §audit; distinct\n * from execution — §7.1 observability). Settled invocations only. */\n queueWaitMs?: number;\n /** Time spent inside the handler/executor guards, excluding queue wait. */\n executionMs?: number;\n /** Present only for capabilities with audit: \"full\"; size-capped. */\n payload?: { input?: JsonValue; output?: JsonValue };\n}\n\nexport interface AuditSink {\n /** MUST NOT throw; MUST be non-blocking. */\n record(event: AuditEvent): void;\n}\n\nexport function memoryAuditSink(opts?: {\n capacity?: number;\n}): AuditSink & { events(): AuditEvent[] } {\n const capacity = opts?.capacity ?? 1000;\n const buffer: AuditEvent[] = [];\n return {\n record(event) {\n buffer.push(event);\n if (buffer.length > capacity) buffer.splice(0, buffer.length - capacity);\n },\n events() {\n return [...buffer];\n },\n };\n}\n\nexport function consoleAuditSink(): AuditSink {\n return {\n record(event) {\n // eslint-disable-next-line no-console\n console.debug(\"[agent-surface audit]\", event.type, event);\n },\n };\n}\n\n/** Sinks MUST NOT break the registry: exceptions are swallowed (and logged). */\nexport function safeRecord(sink: AuditSink | undefined, event: AuditEvent): void {\n if (!sink) return;\n try {\n sink.record(event);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[agent-surface] audit sink threw\", err);\n }\n}\n","import type { AgentCapabilityErrorCode } from \"./errors.js\";\n\nexport type AgentSurfaceEvent =\n | { type: \"surface-changed\"; surfaceVersion: string } // coalesced per microtask\n | {\n type: \"component-registered\";\n registrationId: string;\n componentType: string;\n instanceId: string;\n }\n | {\n type: \"component-unregistered\";\n registrationId: string;\n componentType: string;\n instanceId: string;\n }\n | {\n type: \"component-rejected\";\n componentType: string;\n instanceId: string;\n reason: \"duplicate\" | \"guard\";\n }\n | {\n type: \"availability-changed\";\n registrationId: string;\n capabilityId: string;\n available: boolean;\n }\n | { type: \"collision-suspected\"; viewCapabilityId: string; domainProcedureId: string }\n | { type: \"invocation-started\"; invocationId: string; capabilityId: string; consumerId: string }\n | {\n type: \"invocation-settled\";\n invocationId: string;\n capabilityId: string;\n status: \"ok\" | \"error\";\n code?: AgentCapabilityErrorCode;\n durationMs: number;\n }\n | {\n type: \"confirmation-requested\";\n confirmationId: string;\n capabilityId: string;\n expiresAt: string;\n }\n | {\n type: \"confirmation-resolved\";\n confirmationId: string;\n outcome: \"approved\" | \"denied\" | \"expired\";\n };\n\n/**\n * Ordered, non-re-entrant event dispatcher (D17): events queue in mutation\n * order and drain one at a time; events emitted from listeners join the queue\n * and are delivered after the current event finishes; listener exceptions are\n * isolated and reported.\n */\nexport class EventDispatcher {\n private listeners = new Set<(event: AgentSurfaceEvent) => void>();\n private queue: AgentSurfaceEvent[] = [];\n private draining = false;\n\n constructor(private reportError: (err: unknown) => void) {}\n\n subscribe(listener: (event: AgentSurfaceEvent) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n emit(event: AgentSurfaceEvent): void {\n this.queue.push(event);\n if (this.draining) return;\n this.draining = true;\n try {\n let next: AgentSurfaceEvent | undefined;\n while ((next = this.queue.shift()) !== undefined) {\n for (const listener of [...this.listeners]) {\n try {\n listener(next);\n } catch (err) {\n this.reportError(err);\n }\n }\n }\n } finally {\n this.draining = false;\n }\n }\n\n clear(): void {\n this.listeners.clear();\n this.queue.length = 0;\n }\n}\n","import type { AgentEffect, JsonValue, Unsubscribe } from \"./types.js\";\nimport { jsonDeepEqual, randomBase62 } from \"./utils.js\";\nimport type { AgentSurfaceEvent } from \"./events.js\";\nimport type { AuditEvent } from \"./audit.js\";\n\nexport interface PendingConfirmation {\n confirmationId: string; // \"cnf_\" + random\n capabilityId: string;\n registrationId: string;\n /** Normalized consumer identity `kind:id` (D22). */\n consumerKey: string;\n /** Effect of the operation being approved. */\n effect: AgentEffect;\n /** Human-readable summary composed from description + effective input. */\n summary: string;\n /** The exact effective input (bound + agent-supplied) being approved. */\n input: JsonValue;\n requestedAt: string;\n expiresAt: string; // default TTL 120 s\n}\n\nexport interface ConfirmationController {\n /** Pending requests, for host UI rendering. */\n pending(): PendingConfirmation[];\n resolve(confirmationId: string, resolution: { approved: boolean; reason?: string }): void;\n /** Resolves when the given confirmation settles (approved/denied/expired). */\n waitFor(\n confirmationId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<\"approved\" | \"denied\" | \"expired\">;\n subscribe(listener: (pending: PendingConfirmation[]) => void): Unsubscribe;\n /** Test hook: force-expire a record as if its TTL elapsed (docs/08). */\n forceExpire(confirmationId: string): void;\n}\n\ntype RecordState = \"pending\" | \"approved\" | \"denied\" | \"expired\" | \"consumed\";\n\ninterface ConfirmationRecord extends PendingConfirmation {\n state: RecordState;\n /** Canonical request digest (D21): {surfaceId, registrationId,\n * capabilityId, consumerKey, effectiveInput, effect}. */\n digest: string;\n approvedAt?: string;\n denyReason?: string;\n timer?: ReturnType<typeof setTimeout>;\n waiters: Array<(outcome: \"approved\" | \"denied\" | \"expired\") => void>;\n}\n\nexport type ConsumeResult =\n | { ok: true; approvedAt: string }\n | { ok: false; kind: \"pending-again\"; record: PendingConfirmation }\n | { ok: false; kind: \"invalid\"; reason: \"expired\" | \"denied\" | \"consumed\" | \"mismatch\" };\n\nconst MAX_RETAINED_RESOLVED = 200;\n\nexport class ConfirmationStore {\n private records = new Map<string, ConfirmationRecord>();\n private listeners = new Set<(pending: PendingConfirmation[]) => void>();\n\n constructor(\n private readonly opts: {\n ttlMs: number;\n maxPending: number;\n now: () => number;\n emit: (event: AgentSurfaceEvent) => void;\n audit: (event: Omit<AuditEvent, \"at\">) => void;\n },\n ) {}\n\n /** Creates (or re-uses a matching pending) confirmation record.\n * Returns \"overflow\" when the bounded pending store is full (D24):\n * the caller fails RATE_LIMITED and no record is created. */\n request(request: {\n capabilityId: string;\n registrationId: string;\n consumerKey: string;\n effect: AgentEffect;\n input: JsonValue;\n summary: string;\n digest: string;\n }): PendingConfirmation | \"overflow\" {\n for (const record of this.records.values()) {\n if (record.state === \"pending\" && record.digest === request.digest) {\n return this.view(record);\n }\n }\n if (this.pendingCount() >= this.opts.maxPending) return \"overflow\";\n const now = this.opts.now();\n const record: ConfirmationRecord = {\n confirmationId: `cnf_${randomBase62(12)}`,\n capabilityId: request.capabilityId,\n registrationId: request.registrationId,\n consumerKey: request.consumerKey,\n effect: request.effect,\n summary: request.summary,\n input: request.input,\n digest: request.digest,\n requestedAt: new Date(now).toISOString(),\n expiresAt: new Date(now + this.opts.ttlMs).toISOString(),\n state: \"pending\",\n waiters: [],\n };\n record.timer = setTimeout(() => this.expire(record.confirmationId), this.opts.ttlMs);\n this.records.set(record.confirmationId, record);\n this.trim();\n this.opts.emit({\n type: \"confirmation-requested\",\n confirmationId: record.confirmationId,\n capabilityId: record.capabilityId,\n expiresAt: record.expiresAt,\n });\n this.opts.audit({\n type: \"confirmation-requested\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n invocationId: undefined,\n });\n this.notify();\n return this.view(record);\n }\n\n private pendingCount(): number {\n let count = 0;\n for (const record of this.records.values()) {\n if (record.state === \"pending\") count += 1;\n }\n return count;\n }\n\n resolve(confirmationId: string, resolution: { approved: boolean; reason?: string }): void {\n const record = this.records.get(confirmationId);\n if (!record || record.state !== \"pending\") return;\n if (record.timer) clearTimeout(record.timer);\n if (resolution.approved) {\n record.state = \"approved\";\n record.approvedAt = new Date(this.opts.now()).toISOString();\n this.opts.emit({ type: \"confirmation-resolved\", confirmationId, outcome: \"approved\" });\n this.opts.audit({\n type: \"confirmation-approved\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n });\n this.settleWaiters(record, \"approved\");\n } else {\n record.state = \"denied\";\n record.denyReason = resolution.reason;\n this.opts.emit({ type: \"confirmation-resolved\", confirmationId, outcome: \"denied\" });\n this.opts.audit({\n type: \"confirmation-denied\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n });\n this.settleWaiters(record, \"denied\");\n }\n this.notify();\n }\n\n expire(confirmationId: string): void {\n const record = this.records.get(confirmationId);\n if (!record || record.state !== \"pending\") return;\n if (record.timer) clearTimeout(record.timer);\n record.state = \"expired\";\n record.expiresAt = new Date(this.opts.now()).toISOString();\n this.opts.emit({ type: \"confirmation-resolved\", confirmationId, outcome: \"expired\" });\n this.opts.audit({\n type: \"confirmation-expired\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n });\n this.settleWaiters(record, \"expired\");\n this.notify();\n }\n\n /** Evidence validation + single-use consumption (docs/06 rules 2–5).\n * Matching is digest-first AND exact-value on the effective input —\n * never hash-only (AS-CONFIRM-002). */\n consume(evidence: {\n confirmationId: string;\n digest: string;\n input: JsonValue;\n }): ConsumeResult {\n const record = this.records.get(evidence.confirmationId);\n if (!record) return { ok: false, kind: \"invalid\", reason: \"mismatch\" };\n const matches =\n record.digest === evidence.digest && jsonDeepEqual(record.input, evidence.input);\n switch (record.state) {\n case \"pending\":\n return matches\n ? { ok: false, kind: \"pending-again\", record: this.view(record) }\n : { ok: false, kind: \"invalid\", reason: \"mismatch\" };\n case \"denied\":\n return { ok: false, kind: \"invalid\", reason: \"denied\" };\n case \"expired\":\n return { ok: false, kind: \"invalid\", reason: \"expired\" };\n case \"consumed\":\n return { ok: false, kind: \"invalid\", reason: \"consumed\" };\n case \"approved\": {\n if (Date.parse(record.expiresAt) < this.opts.now()) {\n record.state = \"expired\";\n return { ok: false, kind: \"invalid\", reason: \"expired\" };\n }\n if (!matches) return { ok: false, kind: \"invalid\", reason: \"mismatch\" };\n record.state = \"consumed\"; // atomic single use\n this.opts.audit({\n type: \"confirmation-consumed\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n });\n return { ok: true, approvedAt: record.approvedAt ?? record.requestedAt };\n }\n }\n }\n\n pending(): PendingConfirmation[] {\n return [...this.records.values()]\n .filter((r) => r.state === \"pending\")\n .map((r) => this.view(r));\n }\n\n waitFor(\n confirmationId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<\"approved\" | \"denied\" | \"expired\"> {\n const record = this.records.get(confirmationId);\n if (!record) return Promise.resolve(\"expired\");\n if (record.state === \"approved\" || record.state === \"consumed\") return Promise.resolve(\"approved\");\n if (record.state === \"denied\") return Promise.resolve(\"denied\");\n if (record.state === \"expired\") return Promise.resolve(\"expired\");\n return new Promise((resolvePromise) => {\n const waiter = (outcome: \"approved\" | \"denied\" | \"expired\"): void => resolvePromise(outcome);\n record.waiters.push(waiter);\n opts?.signal?.addEventListener(\n \"abort\",\n () => {\n const i = record.waiters.indexOf(waiter);\n if (i >= 0) record.waiters.splice(i, 1);\n resolvePromise(\"expired\");\n },\n { once: true },\n );\n });\n }\n\n subscribe(listener: (pending: PendingConfirmation[]) => void): Unsubscribe {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Expires every pending record (dispose path). */\n disposeAll(): void {\n for (const record of [...this.records.values()]) {\n if (record.state === \"pending\") this.expire(record.confirmationId);\n }\n this.listeners.clear();\n }\n\n controller(): ConfirmationController {\n return {\n pending: () => this.pending(),\n resolve: (id, resolution) => this.resolve(id, resolution),\n waitFor: (id, opts) => this.waitFor(id, opts),\n subscribe: (listener) => this.subscribe(listener),\n forceExpire: (id) => this.expire(id),\n };\n }\n\n private view(record: ConfirmationRecord): PendingConfirmation {\n return {\n confirmationId: record.confirmationId,\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerKey: record.consumerKey,\n effect: record.effect,\n summary: record.summary,\n input: record.input,\n requestedAt: record.requestedAt,\n expiresAt: record.expiresAt,\n };\n }\n\n private settleWaiters(\n record: ConfirmationRecord,\n outcome: \"approved\" | \"denied\" | \"expired\",\n ): void {\n const waiters = record.waiters.splice(0);\n for (const waiter of waiters) waiter(outcome);\n }\n\n private notify(): void {\n const snapshot = this.pending();\n for (const listener of [...this.listeners]) {\n try {\n listener(snapshot);\n } catch {\n // listener errors must not corrupt the store\n }\n }\n }\n\n private trim(): void {\n const resolved = [...this.records.values()].filter((r) => r.state !== \"pending\");\n if (resolved.length <= MAX_RETAINED_RESOLVED) return;\n for (const record of resolved.slice(0, resolved.length - MAX_RETAINED_RESOLVED)) {\n this.records.delete(record.confirmationId);\n }\n }\n}\n","import type {\n AgentConcurrency,\n AgentConsumer,\n AgentEnvironment,\n AgentProcedureEffect,\n AgentRouteInfo,\n AgentSurfaceLimits,\n JsonSchema,\n JsonValue,\n} from \"./types.js\";\nimport type {\n AgentComponentDefinition,\n AgentProcedureBinding,\n AgentProcedureExecutor,\n} from \"./definition.js\";\nimport type { AgentSchema } from \"./schema.js\";\nimport type { AgentPolicy, AgentPolicyContext } from \"./policy.js\";\nimport type { AgentCapabilityErrorPayload } from \"./errors.js\";\nimport type { AgentSurfaceEvent, EventDispatcher } from \"./events.js\";\nimport type { AuditEvent, AuditSink } from \"./audit.js\";\nimport type { ConfirmationStore } from \"./confirmation.js\";\nimport type { AgentInvocationResult } from \"./invocation-types.js\";\nimport { formatViewCapabilityId } from \"./ids.js\";\nimport { jsonClone } from \"./utils.js\";\n\nexport type ConfirmationLevel = \"never\" | \"optional\" | \"required\";\nexport type AuditLevel = \"none\" | \"metadata\" | \"full\";\n\nexport interface ObservationRuntime {\n kind: \"observation\";\n name: string;\n capabilityId: string;\n description: string;\n outputSchema: AgentSchema<any>;\n jsonSchema: JsonSchema;\n meta?: Record<string, JsonValue>;\n timeoutMs?: number;\n policies: AgentPolicy[];\n auditLevel: AuditLevel;\n}\n\nexport interface ActionRuntime {\n kind: \"action\";\n name: string;\n capabilityId: string;\n description: string;\n inputSchema: AgentSchema<any>;\n inputJsonSchema: JsonSchema;\n outputSchema?: AgentSchema<any>;\n outputJsonSchema?: JsonSchema;\n effect: \"local-state\" | \"navigation\";\n idempotent: boolean;\n reversible: boolean;\n confirmation: ConfirmationLevel;\n auditLevel: AuditLevel;\n meta?: Record<string, JsonValue>;\n timeoutMs?: number;\n policies: AgentPolicy[];\n concurrency?: AgentConcurrency;\n}\n\nexport interface ProcedureRuntime {\n kind: \"procedure\";\n binding: AgentProcedureBinding;\n capabilityId: string; // \"domain:\" + path\n path: string;\n effect: AgentProcedureEffect;\n requiresApproval: boolean;\n baseDescription: string;\n fullInputSchema: JsonSchema;\n reducedInputSchema: JsonSchema;\n outputJsonSchema?: JsonSchema;\n boundKeys: string[];\n lockedKeys: string[];\n overridableKeys: Set<string>;\n confirmationFloor: ConfirmationLevel;\n idempotent: boolean;\n auditLevel: AuditLevel;\n meta?: Record<string, JsonValue>;\n policies: AgentPolicy[];\n contextLink?: { type: string; instanceId: string };\n concurrency?: AgentConcurrency;\n}\n\nexport interface InFlightEntry {\n /**\n * Owner unregistered. Default: aborts the handler signal and settles\n * COMPONENT_UNMOUNTED (first settle wins, D16). Navigation-effect entries\n * only abort the signal — the invocation settles on handler settlement,\n * timeout, or external cancel (D23).\n */\n onUnregister(): void;\n /** Registry disposed: always aborts and settles CANCELLED. */\n onDispose(): void;\n}\n\nexport interface InternalRegistration {\n id: string;\n key: string; // `${type}\\u0000${instanceId}`\n type: string;\n instanceId: string;\n description: string;\n parent?: { type: string; instanceId: string };\n meta?: Record<string, JsonValue>;\n internal: Readonly<Record<string, unknown>>;\n origin: string;\n priority: number;\n /** Live definition object: handlers/when are read through it (D3). */\n definition: AgentComponentDefinition;\n componentPolicies: AgentPolicy[];\n observations: Map<string, ObservationRuntime>;\n actions: Map<string, ActionRuntime>;\n procedures: ProcedureRuntime[];\n /** Procedure-only registrations never appear in snapshot.components. */\n procedureOnly: boolean;\n status: \"active\" | \"unregistered\";\n enabled: boolean;\n availabilityOverrides: Map<string, { available: boolean; reason?: string }>;\n inFlight: Set<InFlightEntry>;\n /**\n * Concurrency groups (D25), created lazily and deleted when they fall idle,\n * so the map is bounded by the number of *currently contended* groups rather\n * than by the number of capabilities ever invoked.\n */\n concurrencyGroups: Map<string, ConcurrencyGroup>;\n}\n\n/** One FIFO admission group. `max` is 1 for every mode except `parallel`. */\nexport interface ConcurrencyGroup {\n running: number;\n max: number;\n depth: number;\n waiting: Array<() => void>;\n}\n\nexport interface Tombstone {\n registrationId: string;\n type: string;\n instanceId: string;\n capabilityIds: Set<string>;\n expiresAt: number;\n}\n\n/** Dedupe entries carry the request fingerprint (D22): join/return only on\n * a match; a mismatch fails INVOCATION_CONFLICT without touching the entry. */\nexport type DedupeEntry =\n | { kind: \"inflight\"; fingerprint: string; promise: Promise<AgentInvocationResult> }\n | { kind: \"terminal\"; fingerprint: string; result: AgentInvocationResult; expiresAt: number };\n\n/** Bounded observation admission state (D24). `waiting` is arrival-ordered;\n * a release wakes the first waiter whose consumer is under its cap. */\nexport interface ObservationAdmission {\n total: number;\n perConsumer: Map<string, number>;\n waiting: Array<{ consumerKey: string; admit: (admitted: boolean) => void }>;\n}\n\nexport interface RegistryInternals {\n environment: AgentEnvironment;\n limits: AgentSurfaceLimits;\n surfaceId: string;\n version: number;\n registrations: Map<string, InternalRegistration>;\n byKey: Map<string, string>;\n tombstones: Map<string, Tombstone>;\n /** Keyed by `${consumerKey} ${invocationId}` (D22). */\n dedupe: Map<string, DedupeEntry>;\n observationAdmission: ObservationAdmission;\n dispatcher: EventDispatcher;\n confirmations: ConfirmationStore;\n executor: AgentProcedureExecutor | undefined;\n disposed: boolean;\n registryPolicies: AgentPolicy[];\n auditSink: AuditSink | undefined;\n contextFn: (() => Record<string, unknown>) | undefined;\n routeFn: (() => AgentRouteInfo | undefined) | undefined;\n now: () => number;\n bumpVersion(): void;\n emit(event: AgentSurfaceEvent): void;\n recordAudit(event: Omit<AuditEvent, \"at\">): void;\n host(): Record<string, unknown>;\n devWarn(...args: unknown[]): void;\n devError(...args: unknown[]): void;\n}\n\n/**\n * Internal seam, deliberately not part of `AgentSurfaceRegistry`: the registry\n * attaches its environment-gated dev logger here so a same-package adapter can\n * report a repair it performed without either widening the public interface or\n * inventing a second environment gate. Symbol-keyed and non-enumerable, so it\n * stays invisible to spreads, `Object.keys`, and serialization.\n */\nexport const DEV_WARN: unique symbol = Symbol(\"agent-surface.dev-warn\");\n\nexport interface DevWarnCarrier {\n [DEV_WARN]?: (...args: unknown[]) => void;\n}\n\n/** Marker for defects that must throw out of invoke() in development. */\nexport class DevDefectError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AgentSurfaceDevDefectError\";\n }\n}\n\nexport function componentKey(type: string, instanceId: string): string {\n return `${type}\\u0000${instanceId}`;\n}\n\nconst CONFIRMATION_RANK: Record<ConfirmationLevel, number> = {\n never: 0,\n optional: 1,\n required: 2,\n};\n\nexport function maxConfirmation(...levels: ConfirmationLevel[]): ConfirmationLevel {\n return levels.reduce((acc, l) => (CONFIRMATION_RANK[l] > CONFIRMATION_RANK[acc] ? l : acc), \"never\");\n}\n\nexport function defaultConfirmationFor(effect: AgentProcedureEffect): ConfirmationLevel {\n switch (effect) {\n case \"server-query\":\n return \"never\";\n case \"server-mutation\":\n return \"optional\";\n case \"external-side-effect\":\n case \"destructive\":\n return \"required\";\n }\n}\n\nexport function defaultAuditFor(effect: AgentProcedureEffect): AuditLevel {\n return effect === \"external-side-effect\" || effect === \"destructive\" ? \"full\" : \"metadata\";\n}\n\nlet registrationCounter = 0;\nexport function nextRegistrationId(random: () => string): string {\n registrationCounter += 1;\n return `reg_${registrationCounter.toString(36).padStart(4, \"0\")}${random()}`;\n}\n\n/** Copies the structural descriptor out of a definition (frozen per D2). */\nexport function normalizeRegistration(\n def: AgentComponentDefinition,\n id: string,\n): InternalRegistration {\n const instanceId = def.instanceId ?? \"default\";\n const observations = new Map<string, ObservationRuntime>();\n for (const [name, obs] of Object.entries(def.observations ?? {})) {\n observations.set(name, {\n kind: \"observation\",\n name,\n capabilityId: formatViewCapabilityId(def.type, name),\n description: obs.description,\n outputSchema: obs.output,\n jsonSchema: jsonClone(obs.output.jsonSchema),\n meta: obs.meta ? jsonClone(obs.meta) : undefined,\n timeoutMs: obs.timeoutMs,\n policies: [...(obs.policies ?? [])],\n auditLevel: \"none\",\n });\n }\n const actions = new Map<string, ActionRuntime>();\n for (const [name, act] of Object.entries(def.actions ?? {})) {\n actions.set(name, {\n kind: \"action\",\n name,\n capabilityId: formatViewCapabilityId(def.type, name),\n description: act.description,\n inputSchema: act.input,\n inputJsonSchema: jsonClone(act.input.jsonSchema),\n outputSchema: act.output,\n outputJsonSchema: act.output ? jsonClone(act.output.jsonSchema) : undefined,\n effect: act.effect,\n idempotent: act.idempotent ?? false,\n reversible: act.reversible ?? true,\n confirmation: act.confirmation ?? \"never\",\n auditLevel: act.audit ?? \"metadata\",\n meta: act.meta ? jsonClone(act.meta) : undefined,\n timeoutMs: act.timeoutMs,\n policies: [...(act.policies ?? [])],\n concurrency: act.concurrency,\n });\n }\n const hasView = observations.size > 0 || actions.size > 0;\n const procedures: ProcedureRuntime[] = (def.procedures ?? []).map((binding) => {\n const boundKeys = [...binding.boundKeys];\n const overridable = new Set(binding.config.overridableFields ?? []);\n const lockedKeys = binding.lockedKeys\n ? [...binding.lockedKeys]\n : boundKeys.filter((k) => !overridable.has(k));\n const effect = binding.ref.effect;\n return {\n kind: \"procedure\",\n binding,\n capabilityId: binding.ref.id,\n path: binding.ref.path,\n effect,\n requiresApproval: binding.ref.requiresApproval === true,\n baseDescription: binding.ref.description,\n fullInputSchema: jsonClone(binding.ref.inputSchema),\n reducedInputSchema: jsonClone(binding.reducedInputSchema),\n outputJsonSchema: binding.ref.outputSchema ? jsonClone(binding.ref.outputSchema) : undefined,\n boundKeys,\n lockedKeys,\n overridableKeys: overridable,\n confirmationFloor: maxConfirmation(\n defaultConfirmationFor(effect),\n binding.config.confirmation ?? \"never\",\n binding.ref.requiresApproval === true ? \"required\" : \"never\",\n ),\n idempotent: effect === \"server-query\",\n auditLevel: defaultAuditFor(effect),\n meta: binding.config.meta ? jsonClone(binding.config.meta) : undefined,\n policies: [...(binding.config.policies ?? [])],\n contextLink:\n binding.contextLink ?? (hasView ? { type: def.type, instanceId } : undefined),\n concurrency: binding.config.concurrency,\n };\n });\n\n return {\n id,\n key: componentKey(def.type, instanceId),\n type: def.type,\n instanceId,\n description: def.description,\n parent: def.parent\n ? { type: def.parent.type, instanceId: def.parent.instanceId ?? \"default\" }\n : undefined,\n meta: def.meta ? jsonClone(def.meta) : undefined,\n internal: Object.freeze({ ...(def.internal ?? {}) }),\n origin: def.origin ?? \"first-party\",\n priority: def.priority ?? 0,\n definition: def,\n componentPolicies: [...(def.policies ?? [])],\n observations,\n actions,\n procedures,\n procedureOnly: !hasView && procedures.length > 0,\n status: \"active\",\n enabled: def.enabled !== false,\n availabilityOverrides: new Map(),\n inFlight: new Set(),\n concurrencyGroups: new Map(),\n };\n}\n\n/**\n * Resolve the concurrency group for a capability (D25). Actions default to\n * `{mode:\"instance\"}` — one queue for the whole registration, so unrelated\n * actions on one component cannot interleave. Procedure references default to\n * one group per procedure identity per referencing registration: conservative\n * for repeat calls of the same domain operation, and never coupled to view\n * actions that happen to live on the same component.\n */\nexport function concurrencyGroupFor(\n cap: ActionRuntime | ProcedureRuntime,\n limits: AgentSurfaceLimits,\n): { key: string; max: number; depth: number } {\n const declared: AgentConcurrency | undefined =\n cap.kind === \"action\" ? cap.concurrency : cap.concurrency;\n const fallbackDepth = limits.actionQueueDepth;\n if (declared === undefined) {\n return cap.kind === \"action\"\n ? { key: \"instance\", max: 1, depth: fallbackDepth }\n : { key: `proc:${cap.capabilityId}`, max: 1, depth: fallbackDepth };\n }\n const depth = declared.queueDepth ?? fallbackDepth;\n switch (declared.mode) {\n case \"instance\":\n return { key: \"instance\", max: 1, depth };\n case \"capability\":\n return { key: `cap:${cap.capabilityId}`, max: 1, depth };\n case \"key\":\n return { key: `key:${declared.key}`, max: 1, depth };\n case \"parallel\":\n return { key: `par:${cap.capabilityId}`, max: declared.max, depth };\n }\n}\n\nexport type CapabilityRuntime = ObservationRuntime | ActionRuntime | ProcedureRuntime;\n\n/** Live `when`/`unavailableReason` lookup through the definition (D3). */\nfunction liveAvailabilityHooks(\n reg: InternalRegistration,\n cap: CapabilityRuntime,\n): { when?: () => boolean; unavailableReason?: string | (() => string) } {\n if (cap.kind === \"observation\") {\n const live = reg.definition.observations?.[cap.name];\n return { when: live?.when, unavailableReason: live?.unavailableReason };\n }\n if (cap.kind === \"action\") {\n const live = reg.definition.actions?.[cap.name];\n return { when: live?.when, unavailableReason: live?.unavailableReason };\n }\n return { when: cap.binding.config.when, unavailableReason: cap.binding.config.unavailableReason };\n}\n\nexport interface Availability {\n available: boolean;\n reason?: string;\n}\n\n/** Availability formula from docs/03 §availability (policies applied separately). */\nexport function computeAvailability(\n internals: RegistryInternals,\n reg: InternalRegistration,\n cap: CapabilityRuntime,\n): Availability {\n if (reg.status !== \"active\") {\n return { available: false, reason: \"component-unregistered\" };\n }\n if (!reg.enabled) {\n return { available: false, reason: \"component-disabled\" };\n }\n const overrideKey = cap.kind === \"procedure\" ? cap.path : cap.name;\n const override =\n reg.availabilityOverrides.get(overrideKey) ?? reg.availabilityOverrides.get(cap.capabilityId);\n if (override && override.available === false) {\n return { available: false, reason: override.reason ?? \"unavailable\" };\n }\n const hooks = liveAvailabilityHooks(reg, cap);\n if (hooks.when) {\n let result: boolean;\n try {\n result = hooks.when() !== false;\n } catch (err) {\n internals.devWarn(\n `[agent-surface] when() threw for ${cap.capabilityId}; treating as unavailable`,\n err,\n );\n return { available: false, reason: \"when-error\" };\n }\n if (!result) {\n let reason = \"Currently unavailable\";\n const ur = hooks.unavailableReason;\n try {\n if (typeof ur === \"function\") reason = ur();\n else if (typeof ur === \"string\") reason = ur;\n } catch {\n /* keep fallback reason */\n }\n return { available: false, reason };\n }\n }\n return { available: true };\n}\n\nexport function policiesFor(\n internals: RegistryInternals,\n reg: InternalRegistration,\n cap: CapabilityRuntime,\n): AgentPolicy[] {\n return [...internals.registryPolicies, ...reg.componentPolicies, ...cap.policies];\n}\n\nexport function buildPolicyContext(\n internals: RegistryInternals,\n reg: InternalRegistration,\n cap: CapabilityRuntime,\n consumer: AgentConsumer,\n host: Record<string, unknown>,\n): AgentPolicyContext {\n return {\n capabilityId: cap.capabilityId,\n plane: cap.kind === \"procedure\" ? \"domain\" : \"view\",\n kind: cap.kind,\n effect: cap.kind === \"observation\" ? \"read\" : cap.effect,\n registrationId: reg.id,\n consumer,\n host,\n meta: { component: reg.meta, capability: cap.meta },\n internal: reg.internal,\n environment: internals.environment,\n now: () => internals.now(),\n };\n}\n\n/** Runtime-normalized consumer identity (D22): the invocation namespace. */\nexport function consumerKeyOf(consumer: AgentConsumer): string {\n return `${consumer.kind}:${consumer.id}`;\n}\n\nexport function pruneTombstones(internals: RegistryInternals): void {\n const now = internals.now();\n for (const [id, tomb] of internals.tombstones) {\n if (tomb.expiresAt <= now) internals.tombstones.delete(id);\n }\n while (internals.tombstones.size > internals.limits.tombstoneSize) {\n const oldest = internals.tombstones.keys().next().value;\n if (oldest === undefined) break;\n internals.tombstones.delete(oldest);\n }\n}\n\nexport function addTombstone(internals: RegistryInternals, reg: InternalRegistration): void {\n const capabilityIds = new Set<string>();\n for (const obs of reg.observations.values()) capabilityIds.add(obs.capabilityId);\n for (const act of reg.actions.values()) capabilityIds.add(act.capabilityId);\n for (const proc of reg.procedures) capabilityIds.add(proc.capabilityId);\n internals.tombstones.set(reg.id, {\n registrationId: reg.id,\n type: reg.type,\n instanceId: reg.instanceId,\n capabilityIds,\n expiresAt: internals.now() + internals.limits.tombstoneTtlMs,\n });\n pruneTombstones(internals);\n}\n","import type { AgentConsumer, JsonValue } from \"./types.js\";\nimport type {\n AgentInvocation,\n AgentInvocationResult,\n InvokeOptions,\n} from \"./invocation-types.js\";\nimport type {\n ActionRuntime,\n CapabilityRuntime,\n InFlightEntry,\n InternalRegistration,\n ObservationRuntime,\n ProcedureRuntime,\n RegistryInternals,\n} from \"./internal.js\";\nimport {\n DevDefectError,\n buildPolicyContext,\n computeAvailability,\n concurrencyGroupFor,\n consumerKeyOf,\n maxConfirmation,\n policiesFor,\n} from \"./internal.js\";\nimport type { AgentCapabilityErrorPayload } from \"./errors.js\";\nimport { AgentSurfaceError, isAgentSurfaceError } from \"./errors.js\";\nimport { parseCapabilityId } from \"./ids.js\";\nimport { AgentSchemaError, fromJsonSchema } from \"./schema.js\";\nimport {\n CONFIRMATION_ESCALATION,\n composeAuthorizeChain,\n composeInvokeChain,\n evaluateDiscovery,\n type AgentInvocationPolicyContext,\n type AgentPolicyWithEscalation,\n type ConfirmationEscalation,\n} from \"./policy.js\";\nimport type { AgentActionContext, AgentReadContext } from \"./definition.js\";\nimport { canonicalJson, fnv1a64, isJsonValue, randomBase62, truncate } from \"./utils.js\";\n\nconst DEFAULT_CONSUMER: AgentConsumer = { id: \"anonymous\", kind: \"embedded\" };\n\n/* ─────────────────────── error payload constructors ─────────────────────── */\n\nfunction notFound(): AgentCapabilityErrorPayload {\n return {\n code: \"CAPABILITY_NOT_FOUND\",\n message:\n \"This capability does not exist in the current surface. Refresh the surface catalog before the next step.\",\n retry: \"after-refresh\",\n };\n}\n\nfunction notAvailable(reason: string | undefined): AgentCapabilityErrorPayload {\n return {\n code: \"CAPABILITY_NOT_AVAILABLE\",\n message: `This capability exists but is currently unavailable${reason ? `: ${reason}` : \"\"}. Perform the enabling step first, then refresh.`,\n retry: \"after-refresh\",\n ...(reason !== undefined ? { details: { reason } } : {}),\n };\n}\n\nfunction unmounted(phase: \"resolve\" | \"mid-flight\"): AgentCapabilityErrorPayload {\n return {\n code: \"COMPONENT_UNMOUNTED\",\n message:\n phase === \"mid-flight\"\n ? \"The owning view unmounted while this capability was executing. Verify state before repeating a non-idempotent action.\"\n : \"The owning view is no longer mounted. Refresh the surface catalog.\",\n retry: \"after-refresh\",\n details: { phase },\n };\n}\n\nfunction stale(\n reason: \"registration-replaced\" | \"surface-reloaded\" | \"surface-version-mismatch\",\n liveRegistrationId?: string,\n): AgentCapabilityErrorPayload {\n return {\n code: \"STALE_CAPABILITY\",\n message:\n \"The invocation references a superseded surface snapshot. Refresh the catalog and re-resolve the target.\",\n retry: \"after-refresh\",\n details: { reason, ...(liveRegistrationId ? { liveRegistrationId } : {}) },\n };\n}\n\nfunction invocationConflict(): AgentCapabilityErrorPayload {\n // Agent-visible details MUST NOT expose the prior request (docs/07).\n return {\n code: \"INVOCATION_CONFLICT\",\n message:\n \"This invocation id was already used for a different request. Use a fresh invocation id if the new request is intentional.\",\n retry: \"with-changes\",\n details: { reason: \"id-reused-with-different-request\" },\n };\n}\n\nfunction queueFull(retryAfterMs: number): AgentCapabilityErrorPayload {\n return {\n code: \"RATE_LIMITED\",\n message: \"The queue for this capability is full. Retry shortly.\",\n retry: \"after-delay\",\n details: { reason: \"queue-full\", retryAfterMs },\n };\n}\n\nfunction cancelled(message: string): AgentCapabilityErrorPayload {\n return { code: \"CANCELLED\", message, retry: \"yes\" };\n}\n\nfunction executionFailed(\n reason: \"handler-error\" | \"output-invalid\" | \"output-too-large\" | \"transport\",\n opts?: { transient?: boolean },\n): AgentCapabilityErrorPayload {\n const messages: Record<string, string> = {\n \"handler-error\": \"The capability failed to execute.\",\n \"output-invalid\": \"The capability produced an invalid output.\",\n \"output-too-large\": \"The capability produced an output exceeding the size limit.\",\n transport: \"The server call failed.\",\n };\n return {\n code: \"EXECUTION_FAILED\",\n message: messages[reason] ?? \"The capability failed to execute.\",\n retry: opts?.transient ? \"after-delay\" : \"no\",\n details: {\n reason,\n ...(opts?.transient ? { transient: true, retryAfterMs: 1000 } : {}),\n },\n };\n}\n\n/* ──────────────── phase 1: consumer-scoped dedupe + conflict (D22) ──────────────── */\n\n/** Fingerprint of the request AS ISSUED (docs/18 §correction 2). */\nfunction requestFingerprint(request: AgentInvocation): string {\n return fnv1a64(\n canonicalJson({\n capabilityId: request.capabilityId,\n registrationId: request.registrationId ?? null,\n instanceId: request.instanceId ?? null,\n surfaceVersion: request.surfaceVersion ?? null,\n input: request.input ?? null,\n confirmationId: request.confirmationId ?? null,\n }),\n );\n}\n\nexport function performInvoke(\n internals: RegistryInternals,\n request: AgentInvocation,\n options?: InvokeOptions,\n): Promise<AgentInvocationResult> {\n if (internals.disposed) {\n throw new Error(\"invoke() called on a disposed registry\");\n }\n const invocationId = request.invocationId ?? `inv_${randomBase62(12)}`;\n const consumer = options?.consumer ?? DEFAULT_CONSUMER;\n const consumerKey = consumerKeyOf(consumer);\n const fingerprint = requestFingerprint(request);\n const dedupeKey = `${consumerKey} ${invocationId}`;\n\n pruneDedupe(internals);\n const existing = internals.dedupe.get(dedupeKey);\n if (existing) {\n if (existing.kind === \"inflight\") {\n if (existing.fingerprint === fingerprint) return existing.promise; // join, don't re-execute\n return Promise.resolve(conflictResult(internals, request, invocationId, consumer));\n }\n if (existing.expiresAt > internals.now()) {\n if (existing.fingerprint === fingerprint) return Promise.resolve(existing.result);\n return Promise.resolve(conflictResult(internals, request, invocationId, consumer));\n }\n internals.dedupe.delete(dedupeKey); // expired key: a new attempt (bounded window)\n }\n\n const promise = runPipeline(internals, request, invocationId, consumer, consumerKey, options);\n internals.dedupe.set(dedupeKey, { kind: \"inflight\", fingerprint, promise });\n promise.then(\n (result) => {\n // Terminal = ok and every error except CONFIRMATION_REQUIRED / RATE_LIMITED\n // (expected-retry outcomes; INVOCATION_CONFLICT never reaches here).\n const terminal =\n result.status === \"ok\" ||\n (result.error.code !== \"CONFIRMATION_REQUIRED\" && result.error.code !== \"RATE_LIMITED\");\n if (terminal) {\n internals.dedupe.set(dedupeKey, {\n kind: \"terminal\",\n fingerprint,\n result,\n expiresAt: internals.now() + internals.limits.dedupeCacheTtlMs,\n });\n pruneDedupe(internals);\n } else {\n internals.dedupe.delete(dedupeKey);\n }\n },\n () => {\n internals.dedupe.delete(dedupeKey);\n },\n );\n return promise;\n}\n\n/** Fail-closed conflict envelope: emitted through events/audit, never cached. */\nfunction conflictResult(\n internals: RegistryInternals,\n request: AgentInvocation,\n invocationId: string,\n consumer: AgentConsumer,\n): AgentInvocationResult {\n internals.emit({\n type: \"invocation-started\",\n invocationId,\n capabilityId: request.capabilityId,\n consumerId: consumer.id,\n });\n const error = invocationConflict();\n const result: AgentInvocationResult = {\n status: \"error\",\n invocationId,\n capabilityId: request.capabilityId,\n error,\n surfaceVersion: String(internals.version),\n };\n internals.emit({\n type: \"invocation-settled\",\n invocationId,\n capabilityId: request.capabilityId,\n status: \"error\",\n code: error.code,\n durationMs: 0,\n });\n internals.recordAudit({\n type: \"invocation-settled\",\n capabilityId: request.capabilityId,\n invocationId,\n consumerId: consumerKeyOf(consumer),\n status: \"error\",\n code: error.code,\n durationMs: 0,\n });\n return result;\n}\n\nfunction pruneDedupe(internals: RegistryInternals): void {\n const now = internals.now();\n for (const [id, entry] of internals.dedupe) {\n if (entry.kind === \"terminal\" && entry.expiresAt <= now) internals.dedupe.delete(id);\n }\n while (internals.dedupe.size > internals.limits.dedupeCacheSize) {\n const oldest = internals.dedupe.keys().next().value;\n if (oldest === undefined) break;\n const entry = internals.dedupe.get(oldest);\n if (entry?.kind === \"inflight\") break; // never evict in-flight joins\n internals.dedupe.delete(oldest);\n }\n}\n\n/* ───────────────────────────── the 10 phases ───────────────────────────── */\n\ninterface ResolvedTarget {\n reg: InternalRegistration;\n cap: CapabilityRuntime;\n}\n\nasync function runPipeline(\n internals: RegistryInternals,\n request: AgentInvocation,\n invocationId: string,\n consumer: AgentConsumer,\n consumerKey: string,\n options?: InvokeOptions,\n): Promise<AgentInvocationResult> {\n const startVersion = internals.version;\n const startedAt = internals.now();\n internals.emit({\n type: \"invocation-started\",\n invocationId,\n capabilityId: request.capabilityId,\n consumerId: consumer.id,\n });\n\n let resolvedAuditLevel: \"none\" | \"metadata\" | \"full\" = \"metadata\";\n let resolvedRegistrationId: string | undefined;\n let inputForAudit: JsonValue | undefined;\n let outputForAudit: JsonValue | undefined;\n // §7.1 observability: queue wait and execution duration are distinct.\n let queueWaitMsForAudit: number | undefined;\n let executionMsForAudit: number | undefined;\n\n const finalize = (\n body:\n | { status: \"ok\"; output?: JsonValue }\n | { status: \"error\"; error: AgentCapabilityErrorPayload },\n ): AgentInvocationResult => {\n const surfaceVersion = String(internals.version);\n const surfaceChanged = internals.version !== startVersion ? true : undefined;\n const result: AgentInvocationResult =\n body.status === \"ok\"\n ? {\n status: \"ok\",\n invocationId,\n capabilityId: request.capabilityId,\n ...(body.output !== undefined ? { output: body.output } : {}),\n surfaceVersion,\n ...(surfaceChanged ? { surfaceChanged } : {}),\n }\n : {\n status: \"error\",\n invocationId,\n capabilityId: request.capabilityId,\n error: body.error,\n surfaceVersion,\n ...(surfaceChanged ? { surfaceChanged } : {}),\n };\n const durationMs = internals.now() - startedAt;\n internals.emit({\n type: \"invocation-settled\",\n invocationId,\n capabilityId: request.capabilityId,\n status: result.status,\n ...(result.status === \"error\" ? { code: result.error.code } : {}),\n durationMs,\n });\n if (resolvedAuditLevel !== \"none\") {\n internals.recordAudit({\n type: \"invocation-settled\",\n capabilityId: request.capabilityId,\n registrationId: resolvedRegistrationId,\n invocationId,\n consumerId: consumerKey,\n status: result.status,\n ...(result.status === \"error\" ? { code: result.error.code } : {}),\n durationMs,\n ...(queueWaitMsForAudit !== undefined ? { queueWaitMs: queueWaitMsForAudit } : {}),\n ...(executionMsForAudit !== undefined ? { executionMs: executionMsForAudit } : {}),\n ...(resolvedAuditLevel === \"full\"\n ? {\n payload: {\n ...(inputForAudit !== undefined ? { input: inputForAudit } : {}),\n ...(outputForAudit !== undefined ? { output: outputForAudit } : {}),\n },\n }\n : {}),\n });\n }\n return result;\n };\n\n try {\n /* phase 2 — resolve + staleness tokens */\n const resolved = resolveTarget(internals, request);\n if (\"error\" in resolved) return finalize({ status: \"error\", error: resolved.error });\n const { reg, cap } = resolved;\n resolvedRegistrationId = reg.id;\n resolvedAuditLevel = cap.auditLevel;\n\n // surfaceVersion is enforced only for dangerous effects (docs/03 §versioning).\n if (\n request.surfaceVersion !== undefined &&\n request.surfaceVersion !== String(internals.version) &&\n cap.kind === \"procedure\" &&\n (cap.effect === \"destructive\" || cap.effect === \"external-side-effect\")\n ) {\n return finalize({ status: \"error\", error: stale(\"surface-version-mismatch\") });\n }\n\n if (resolvedAuditLevel !== \"none\") {\n internals.recordAudit({\n type: \"invocation-started\",\n capabilityId: cap.capabilityId,\n registrationId: reg.id,\n invocationId,\n consumerId: consumerKey,\n });\n }\n\n /* phase 3 — availability (re-evaluated, never trusted from discovery) */\n const availability = computeAvailability(internals, reg, cap);\n if (!availability.available) {\n return finalize({ status: \"error\", error: notAvailable(availability.reason) });\n }\n\n /* phase 4 — pre-input authority. The onDiscovery re-run covers pure\n discovery policies (hide ⇒ NOT_FOUND, disable ⇒ NOT_AVAILABLE);\n onAuthorize gates run onion-style with NO agent input in scope (D21). */\n const host = internals.host();\n const chain = policiesFor(internals, reg, cap);\n const policyCtx = buildPolicyContext(internals, reg, cap, consumer, host);\n const discovery = evaluateDiscovery(\n chain.filter((p) => !p.onAuthorize && !p.onInvoke),\n policyCtx,\n );\n if (discovery.decision === \"hide\") {\n // Indistinguishable from nonexistence for this consumer (requirement 12).\n return finalize({ status: \"error\", error: notFound() });\n }\n if (discovery.decision === \"disable\") {\n return finalize({ status: \"error\", error: notAvailable(discovery.reason) });\n }\n const escalations = chain\n .map((p) => (p as AgentPolicyWithEscalation)[CONFIRMATION_ESCALATION])\n .filter((e): e is ConfirmationEscalation => e !== undefined);\n\n const core = (): Promise<AgentInvocationResult> =>\n executeCore(internals, {\n request,\n invocationId,\n consumer,\n consumerKey,\n host,\n reg,\n cap,\n chain,\n policyCtx,\n escalations,\n options,\n finalize,\n setAuditPayload: (input, output) => {\n if (input !== undefined) inputForAudit = input;\n if (output !== undefined) outputForAudit = output;\n },\n setTimings: (timings) => {\n if (timings.queueWaitMs !== undefined) queueWaitMsForAudit = timings.queueWaitMs;\n if (timings.executionMs !== undefined) executionMsForAudit = timings.executionMs;\n },\n });\n\n try {\n return await composeAuthorizeChain(chain, policyCtx, core);\n } catch (err) {\n if (isAgentSurfaceError(err)) {\n return finalize({ status: \"error\", error: err.payload });\n }\n throw err;\n }\n } catch (err) {\n if (err instanceof DevDefectError) throw err; // dev probes throw out of invoke()\n if (isAgentSurfaceError(err)) {\n return finalize({ status: \"error\", error: err.payload });\n }\n internals.devError(\"[agent-surface] invocation pipeline failure\", err);\n return finalize({ status: \"error\", error: executionFailed(\"handler-error\") });\n }\n}\n\n/* ───────────────────────────── resolution ───────────────────────────── */\n\nfunction resolveTarget(\n internals: RegistryInternals,\n request: AgentInvocation,\n): ResolvedTarget | { error: AgentCapabilityErrorPayload } {\n const parsed = parseCapabilityId(request.capabilityId);\n if (!parsed) return { error: notFound() };\n\n interface Candidate {\n reg: InternalRegistration;\n cap: CapabilityRuntime;\n }\n let candidates: Candidate[] = [];\n\n if (parsed.plane === \"view\") {\n for (const reg of internals.registrations.values()) {\n if (reg.status !== \"active\" || reg.type !== parsed.componentType) continue;\n const cap: ObservationRuntime | ActionRuntime | undefined =\n reg.observations.get(parsed.name) ?? reg.actions.get(parsed.name);\n if (cap) candidates.push({ reg, cap });\n }\n } else {\n for (const reg of internals.registrations.values()) {\n if (reg.status !== \"active\") continue;\n for (const proc of reg.procedures) {\n if (proc.path === parsed.path) candidates.push({ reg, cap: proc });\n }\n }\n }\n\n if (request.instanceId !== undefined) {\n candidates = candidates.filter((c) => c.reg.instanceId === request.instanceId);\n }\n candidates.sort((a, b) =>\n a.reg.instanceId < b.reg.instanceId ? -1 : a.reg.instanceId > b.reg.instanceId ? 1 : 0,\n );\n\n if (request.registrationId !== undefined) {\n const live = candidates.find((c) => c.reg.id === request.registrationId);\n if (live) return live;\n // Tombstones are TTL-bound: an expired one no longer proves recency.\n const tombstone = internals.tombstones.get(request.registrationId);\n const tombstoned = tombstone !== undefined && tombstone.expiresAt > internals.now();\n if (candidates.length > 0) {\n const reason = tombstoned\n ? (\"registration-replaced\" as const)\n : (\"surface-reloaded\" as const);\n return { error: stale(reason, candidates[0]?.reg.id) };\n }\n if (tombstoned) {\n return { error: unmounted(\"resolve\") };\n }\n return { error: notFound() };\n }\n\n if (candidates.length === 0) {\n for (const tomb of internals.tombstones.values()) {\n if (tomb.expiresAt <= internals.now()) continue;\n if (tomb.capabilityIds.has(request.capabilityId)) {\n return { error: unmounted(\"resolve\") };\n }\n }\n return { error: notFound() };\n }\n if (candidates.length > 1) {\n const instances: JsonValue = candidates.map((c) => {\n const entry: Record<string, JsonValue> = {\n instanceId: c.reg.instanceId,\n registrationId: c.reg.id,\n };\n if (c.cap.kind === \"procedure\") {\n if (c.cap.contextLink) entry.context = { ...c.cap.contextLink };\n } else {\n entry.description = c.reg.description;\n }\n return entry;\n });\n return {\n error: {\n code: \"AMBIGUOUS_INSTANCE\",\n message:\n \"More than one live instance matches this capability. Re-issue the call with an explicit instanceId or registrationId.\",\n retry: \"with-changes\",\n details: { instances },\n },\n };\n }\n return candidates[0] as Candidate;\n}\n\n/* ───────────────────────── phases 5–10 per kind ───────────────────────── */\n\ninterface CoreArgs {\n request: AgentInvocation;\n invocationId: string;\n consumer: AgentConsumer;\n consumerKey: string;\n host: Record<string, unknown>;\n reg: InternalRegistration;\n cap: CapabilityRuntime;\n chain: ReadonlyArray<AgentPolicyWithEscalation>;\n policyCtx: ReturnType<typeof buildPolicyContext>;\n escalations: ConfirmationEscalation[];\n options: InvokeOptions | undefined;\n finalize: (\n body:\n | { status: \"ok\"; output?: JsonValue }\n | { status: \"error\"; error: AgentCapabilityErrorPayload },\n ) => AgentInvocationResult;\n setAuditPayload: (input?: JsonValue, output?: JsonValue) => void;\n setTimings: (timings: { queueWaitMs?: number; executionMs?: number }) => void;\n}\n\nasync function executeCore(\n internals: RegistryInternals,\n args: CoreArgs,\n): Promise<AgentInvocationResult> {\n const { cap } = args;\n if (cap.kind === \"observation\") return executeObservation(internals, args, cap);\n if (cap.kind === \"action\") return executeAction(internals, args, cap);\n return executeProcedure(internals, args, cap);\n}\n\n/** Phase 6: onInvoke onion over the validated effective input (D21). */\nfunction runInvokePolicies(\n args: CoreArgs,\n effectiveInput: JsonValue,\n downstream: () => Promise<AgentInvocationResult>,\n): Promise<AgentInvocationResult> {\n const invokeCtx: AgentInvocationPolicyContext = {\n ...args.policyCtx,\n invocationId: args.invocationId,\n effectiveInput,\n };\n return composeInvokeChain(args.chain, invokeCtx, downstream);\n}\n\nasync function executeObservation(\n internals: RegistryInternals,\n args: CoreArgs,\n cap: ObservationRuntime,\n): Promise<AgentInvocationResult> {\n // Observations skip input parsing, confirmation, and the action queue;\n // their effective input is vacuously {} for phase-6 policies.\n const { reg, invocationId, consumer, consumerKey, host, options, finalize } = args;\n const readCtx: AgentReadContext = {\n capabilityId: cap.capabilityId,\n registrationId: reg.id,\n consumer,\n host,\n };\n const run = async (): Promise<AgentInvocationResult> => {\n /* phase 8 — bounded observation admission (D24) */\n const queueStart = internals.now();\n const slot = await acquireObservationSlot(internals, consumerKey);\n args.setTimings({ queueWaitMs: internals.now() - queueStart });\n if (slot === \"overflow\") {\n return finalize({ status: \"error\", error: queueFull(250) });\n }\n if (slot === \"cancelled\") {\n return finalize({\n status: \"error\",\n error: { ...cancelled(\"The registry was disposed.\"), retry: \"no\" },\n });\n }\n try {\n const timeoutMs =\n options?.timeoutMs ?? cap.timeoutMs ?? internals.limits.observationTimeoutMs;\n const executeStart = internals.now();\n const outcome = await executeWithGuards(internals, reg, {\n invocationId,\n capabilityId: cap.capabilityId,\n timeoutMs,\n externalSignal: options?.signal,\n idempotent: true,\n run: () => {\n const live = reg.definition.observations?.[cap.name];\n if (!live) throw new Error(\"observation handler missing\");\n return live.read(readCtx);\n },\n });\n args.setTimings({ executionMs: internals.now() - executeStart });\n if (!outcome.ok) return finalize({ status: \"error\", error: outcome.payload });\n const output = settleOutput(internals, outcome.value, cap.outputSchema);\n if (\"error\" in output) return finalize({ status: \"error\", error: output.error });\n return finalize({ status: \"ok\", output: output.value });\n } finally {\n releaseObservationSlot(internals, consumerKey);\n }\n };\n return runInvokePolicies(args, {}, run);\n}\n\nasync function executeAction(\n internals: RegistryInternals,\n args: CoreArgs,\n cap: ActionRuntime,\n): Promise<AgentInvocationResult> {\n const { request, reg, invocationId, consumer, host, options, finalize } = args;\n\n /* phase 5 — validated effective input */\n let parsedInput: JsonValue;\n try {\n parsedInput = cap.inputSchema.parse(request.input) as JsonValue;\n } catch (err) {\n return finalize({ status: \"error\", error: invalidInput(err) });\n }\n args.setAuditPayload(parsedInput, undefined);\n\n const readCtx: AgentReadContext = {\n capabilityId: cap.capabilityId,\n registrationId: reg.id,\n consumer,\n host,\n };\n\n const run = async (): Promise<AgentInvocationResult> => {\n /* phase 6 (tail) — confirmation decision over the effective input */\n const confirmation = gateConfirmation(internals, {\n ...args,\n effectiveInput: parsedInput,\n declared: cap.confirmation,\n description: cap.description,\n effect: cap.effect,\n });\n if (\"error\" in confirmation) return finalize({ status: \"error\", error: confirmation.error });\n\n /* phase 7 — precondition */\n const livePrecondition = reg.definition.actions?.[cap.name]?.precondition;\n if (livePrecondition) {\n try {\n const failure = livePrecondition(parsedInput, readCtx);\n if (failure && typeof failure.message === \"string\") {\n return finalize({\n status: \"error\",\n error: preconditionFailed(failure.message, failure.details),\n });\n }\n } catch (err) {\n if (isAgentSurfaceError(err)) return finalize({ status: \"error\", error: err.payload });\n if (\n !(err instanceof Error) &&\n typeof err === \"object\" &&\n err !== null &&\n typeof (err as { message?: unknown }).message === \"string\"\n ) {\n const failure = err as { message: string; details?: Record<string, JsonValue> };\n return finalize({\n status: \"error\",\n error: preconditionFailed(failure.message, failure.details),\n });\n }\n internals.devError(`[agent-surface] precondition threw for ${cap.capabilityId}`, err);\n return finalize({ status: \"error\", error: executionFailed(\"handler-error\") });\n }\n }\n\n /* phase 8 — concurrency: per-group admission, default per instance (D13/D25) */\n const queueStart = internals.now();\n const slot = await acquireActionSlot(internals, reg, cap);\n args.setTimings({ queueWaitMs: internals.now() - queueStart });\n if (slot === \"overflow\") {\n return finalize({ status: \"error\", error: queueFull(250) });\n }\n\n try {\n /* phase 9 — execute; navigation actions settle on handler settlement (D23) */\n const timeoutMs = options?.timeoutMs ?? cap.timeoutMs ?? internals.limits.actionTimeoutMs;\n const executeStart = internals.now();\n const outcome = await executeWithGuards(internals, reg, {\n invocationId,\n capabilityId: cap.capabilityId,\n timeoutMs,\n externalSignal: options?.signal,\n idempotent: cap.idempotent,\n navigationSettlement: cap.effect === \"navigation\",\n run: (signal) => {\n const live = reg.definition.actions?.[cap.name];\n if (!live) throw new Error(\"action handler missing\");\n const actionCtx: AgentActionContext = {\n ...readCtx,\n invocationId,\n signal,\n ...(confirmation.evidence ? { confirmation: confirmation.evidence } : {}),\n };\n return live.execute(parsedInput, actionCtx);\n },\n });\n args.setTimings({ executionMs: internals.now() - executeStart });\n if (!outcome.ok) return finalize({ status: \"error\", error: outcome.payload });\n\n /* phase 10 — settle */\n const output = settleOutput(internals, outcome.value, cap.outputSchema);\n if (\"error\" in output) return finalize({ status: \"error\", error: output.error });\n args.setAuditPayload(undefined, output.value);\n return finalize({ status: \"ok\", output: output.value });\n } finally {\n releaseActionSlot(internals, reg, cap);\n }\n };\n return runInvokePolicies(args, parsedInput, run);\n}\n\nasync function executeProcedure(\n internals: RegistryInternals,\n args: CoreArgs,\n cap: ProcedureRuntime,\n): Promise<AgentInvocationResult> {\n const { request, reg, invocationId, consumer, options, finalize } = args;\n\n /* phase 5 — validated effective input:\n locked-field rejection → reduced parse → bind → merge → full-schema parse */\n const agentInput = (request.input ?? {}) as Record<string, JsonValue>;\n if (typeof agentInput !== \"object\" || agentInput === null || Array.isArray(agentInput)) {\n return finalize({\n status: \"error\",\n error: invalidInput(new AgentSchemaError([{ path: \"\", message: \"input must be an object\" }])),\n });\n }\n const suppliedLocked = Object.keys(agentInput).filter((k) => cap.lockedKeys.includes(k));\n if (suppliedLocked.length > 0) {\n return finalize({\n status: \"error\",\n error: {\n code: \"INVALID_INPUT\",\n message:\n \"Some fields are bound to the application's UI state and cannot be supplied by the agent. Omit them and retry.\",\n retry: \"with-changes\",\n details: { lockedFields: suppliedLocked },\n },\n });\n }\n try {\n fromJsonSchema(cap.reducedInputSchema).parse(agentInput);\n } catch (err) {\n return finalize({ status: \"error\", error: invalidInput(err) });\n }\n\n // bind() runs at EXECUTION time on live UI state (docs/05 rule 4).\n let bound: Record<string, JsonValue> = {};\n const bind = cap.binding.config.bind;\n if (bind) {\n try {\n bound = bind() ?? {};\n } catch (err) {\n internals.devWarn(`[agent-surface] bind() threw for ${cap.capabilityId}`, err);\n return finalize({ status: \"error\", error: bindingFailed() });\n }\n }\n\n const effective: Record<string, JsonValue> = {};\n for (const [key, value] of Object.entries(agentInput)) {\n if (!cap.lockedKeys.includes(key)) effective[key] = value;\n }\n for (const key of cap.boundKeys) {\n const agentSupplied = cap.overridableKeys.has(key) && agentInput[key] !== undefined;\n if (!agentSupplied && bound[key] !== undefined) effective[key] = bound[key] as JsonValue;\n }\n\n // Merged object is validated against the FULL original schema (docs/05 rule 5):\n // the agent's part already validated, so a failure here is a binding bug.\n try {\n fromJsonSchema(cap.fullInputSchema).parse(effective);\n } catch (err) {\n internals.devWarn(\n `[agent-surface] merged input for ${cap.capabilityId} failed full-schema validation`,\n err,\n );\n return finalize({ status: \"error\", error: bindingFailed() });\n }\n args.setAuditPayload(effective, undefined);\n\n const run = async (): Promise<AgentInvocationResult> => {\n /* phase 6 (tail) — confirmation decision over the effective input */\n const confirmation = gateConfirmation(internals, {\n ...args,\n effectiveInput: effective,\n declared: cap.confirmationFloor,\n description: cap.baseDescription,\n effect: cap.effect,\n });\n if (\"error\" in confirmation) return finalize({ status: \"error\", error: confirmation.error });\n\n /* phase 8 — concurrency: one group per procedure identity by default (D25) */\n const queueStart = internals.now();\n const slot = await acquireActionSlot(internals, reg, cap);\n args.setTimings({ queueWaitMs: internals.now() - queueStart });\n if (slot === \"overflow\") {\n return finalize({ status: \"error\", error: queueFull(250) });\n }\n\n try {\n /* phase 9 — forward to the executor (the server re-validates everything) */\n const executor = internals.executor;\n if (!executor) {\n return finalize({ status: \"error\", error: executionFailed(\"transport\") });\n }\n const timeoutMs = options?.timeoutMs ?? internals.limits.procedureTimeoutMs;\n const executeStart = internals.now();\n const outcome = await executeWithGuards(internals, reg, {\n invocationId,\n capabilityId: cap.capabilityId,\n timeoutMs,\n externalSignal: options?.signal,\n idempotent: cap.idempotent,\n run: (signal) =>\n executor.execute({\n path: cap.path,\n input: effective,\n info: {\n invocationId,\n consumer,\n signal,\n ...(confirmation.evidence ? { confirmation: confirmation.evidence } : {}),\n },\n }),\n procedureErrors: true,\n });\n args.setTimings({ executionMs: internals.now() - executeStart });\n if (!outcome.ok) return finalize({ status: \"error\", error: outcome.payload });\n\n /* phase 10 — settle */\n const output = settleOutput(\n internals,\n outcome.value,\n cap.outputJsonSchema ? fromJsonSchema(cap.outputJsonSchema) : undefined,\n );\n if (\"error\" in output) return finalize({ status: \"error\", error: output.error });\n args.setAuditPayload(undefined, output.value);\n return finalize({ status: \"ok\", output: output.value });\n } finally {\n releaseActionSlot(internals, reg, cap);\n }\n };\n return runInvokePolicies(args, effective, run);\n}\n\n/* ───────────────────── confirmation gate (docs/06, D21) ───────────────────── */\n\nfunction gateConfirmation(\n internals: RegistryInternals,\n args: CoreArgs & {\n effectiveInput: JsonValue;\n declared: \"never\" | \"optional\" | \"required\";\n description: string;\n effect: string;\n },\n):\n | { evidence?: { id: string; approvedAt: string } }\n | { error: AgentCapabilityErrorPayload } {\n const { request, reg, cap, consumerKey, escalations, effectiveInput, declared } = args;\n\n const activeEscalations = escalations.filter((e) => {\n if (!e.if) return true;\n try {\n return e.if({ ...args.policyCtx, effectiveInput });\n } catch {\n return true; // fail closed: a broken condition still confirms\n }\n });\n const effective = maxConfirmation(declared, activeEscalations.length > 0 ? \"required\" : \"never\");\n if (effective !== \"required\") return {};\n\n const summaryComposer = activeEscalations.find((e) => e.summary)?.summary;\n let summary: string;\n try {\n summary = summaryComposer\n ? summaryComposer(effectiveInput)\n : `${args.description} — input: ${JSON.stringify(effectiveInput)}`;\n } catch {\n summary = args.description;\n }\n summary = truncate(summary, 300);\n\n // Canonical request digest (D21): what the user approves is exactly what\n // executes. The canonical string itself is the digest — comparison stays\n // exact-value, never hash-only.\n const digest = canonicalJson({\n surfaceId: internals.surfaceId,\n registrationId: reg.id,\n capabilityId: cap.capabilityId,\n consumerKey,\n effectiveInput,\n effect: args.effect,\n });\n\n if (request.confirmationId) {\n const consumed = internals.confirmations.consume({\n confirmationId: request.confirmationId,\n digest,\n input: effectiveInput,\n });\n if (consumed.ok) {\n return { evidence: { id: request.confirmationId, approvedAt: consumed.approvedAt } };\n }\n if (consumed.kind === \"pending-again\") {\n return { error: confirmationRequired(consumed.record, args.effect) };\n }\n return {\n error: {\n code: \"CONFIRMATION_INVALID\",\n message:\n consumed.reason === \"denied\"\n ? \"The user declined this action. Do not retry; respect the decision.\"\n : consumed.reason === \"expired\"\n ? \"The confirmation expired. Request a fresh confirmation.\"\n : consumed.reason === \"consumed\"\n ? \"This confirmation was already used. Request a fresh confirmation if the action is still needed.\"\n : \"The confirmation does not match this exact invocation.\",\n retry: consumed.reason === \"expired\" ? \"with-confirmation\" : \"no\",\n details: { reason: consumed.reason },\n },\n };\n }\n\n const record = internals.confirmations.request({\n capabilityId: cap.capabilityId,\n registrationId: reg.id,\n consumerKey,\n effect: args.policyCtx.effect,\n input: effectiveInput,\n summary,\n digest,\n });\n if (record === \"overflow\") {\n // Bounded pending store (D24): fail closed, no record created.\n return { error: queueFull(1000) };\n }\n return { error: confirmationRequired(record, args.effect) };\n}\n\nfunction confirmationRequired(\n record: { confirmationId: string; summary: string; expiresAt: string },\n effect: string,\n): AgentCapabilityErrorPayload {\n return {\n code: \"CONFIRMATION_REQUIRED\",\n message:\n \"User approval is required for this action. Wait for the user to resolve the confirmation, then retry with the confirmationId.\",\n retry: \"with-confirmation\",\n details: {\n confirmationId: record.confirmationId,\n summary: record.summary,\n expiresAt: record.expiresAt,\n effect,\n origin: \"client\",\n },\n };\n}\n\n/* ───────────────────── shared input/output helpers ───────────────────── */\n\nfunction invalidInput(err: unknown): AgentCapabilityErrorPayload {\n const issues =\n err instanceof AgentSchemaError\n ? err.issues.map((i) => ({ path: i.path, message: i.message }))\n : [{ path: \"\", message: \"Input failed schema validation\" }];\n return {\n code: \"INVALID_INPUT\",\n message: \"The input does not match the capability's schema. Fix the listed issues and retry.\",\n retry: \"with-changes\",\n details: { issues },\n };\n}\n\nfunction preconditionFailed(\n message: string,\n details?: Record<string, JsonValue>,\n): AgentCapabilityErrorPayload {\n return {\n code: \"PRECONDITION_FAILED\",\n message: truncate(message, 300),\n retry: \"with-changes\",\n ...(details ? { details } : {}),\n };\n}\n\nfunction bindingFailed(): AgentCapabilityErrorPayload {\n return {\n code: \"PRECONDITION_FAILED\",\n message:\n \"The UI-derived input binding could not be evaluated. Refresh the surface and check availability before retrying.\",\n retry: \"after-refresh\",\n details: { reason: \"binding-failed\" },\n };\n}\n\nfunction settleOutput(\n internals: RegistryInternals,\n value: unknown,\n schema: { parse(v: unknown): unknown } | undefined,\n): { value?: JsonValue } | { error: AgentCapabilityErrorPayload } {\n if (value === undefined) return {};\n let parsed: unknown = value;\n if (schema) {\n try {\n parsed = schema.parse(value);\n } catch (err) {\n internals.devError(\"[agent-surface] output failed schema validation\", err);\n return { error: executionFailed(\"output-invalid\") };\n }\n }\n if (!isJsonValue(parsed)) {\n if (internals.environment !== \"production\") {\n throw new DevDefectError(\n \"capability output is not a JsonValue (functions, symbols, bigints, Dates, or cycles are defects — docs/03 §serialization)\",\n );\n }\n return { error: executionFailed(\"output-invalid\") };\n }\n let serialized: string;\n try {\n serialized = JSON.stringify(parsed);\n } catch {\n if (internals.environment !== \"production\") {\n throw new DevDefectError(\"capability output cannot be serialized to JSON\");\n }\n return { error: executionFailed(\"output-invalid\") };\n }\n if (serialized.length > internals.limits.maxOutputBytes) {\n return { error: executionFailed(\"output-too-large\") };\n }\n return { value: parsed as JsonValue };\n}\n\n/* ─────────────── execution guards: timeout/abort/unmount (D16/D23) ─────────────── */\n\ntype ExecutionOutcome =\n | { ok: true; value: unknown }\n | { ok: false; payload: AgentCapabilityErrorPayload };\n\nfunction executeWithGuards(\n internals: RegistryInternals,\n reg: InternalRegistration,\n opts: {\n invocationId: string;\n capabilityId: string;\n timeoutMs: number;\n externalSignal: AbortSignal | undefined;\n idempotent: boolean;\n run: (signal: AbortSignal) => unknown;\n procedureErrors?: boolean;\n /** D23: unregistration aborts the signal but never settles the invocation. */\n navigationSettlement?: boolean;\n },\n): Promise<ExecutionOutcome> {\n return new Promise((resolve) => {\n const controller = new AbortController();\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const entry: InFlightEntry = {\n onUnregister() {\n controller.abort();\n if (!opts.navigationSettlement) {\n finish({ ok: false, payload: unmounted(\"mid-flight\") });\n }\n // Navigation invocations settle on handler settlement/timeout/cancel\n // only — a committed transition must not be overwritten (AS-NAV-001).\n },\n onDispose() {\n controller.abort();\n finish({\n ok: false,\n payload: { code: \"CANCELLED\", message: \"The registry was disposed.\", retry: \"no\" },\n });\n },\n };\n\n const onExternalAbort = (): void => {\n controller.abort();\n finish({\n ok: false,\n payload: cancelled(\"The invocation was cancelled by the host.\"),\n });\n };\n\n const finish = (outcome: ExecutionOutcome): boolean => {\n if (settled) return false;\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n reg.inFlight.delete(entry);\n opts.externalSignal?.removeEventListener(\"abort\", onExternalAbort);\n resolve(outcome);\n return true;\n };\n\n const lateSettlement = (): void => {\n internals.recordAudit({\n type: \"late-settlement\",\n capabilityId: opts.capabilityId,\n registrationId: reg.id,\n invocationId: opts.invocationId,\n });\n };\n\n const handlerError = (err: unknown): ExecutionOutcome => {\n if (isAgentSurfaceError(err)) return { ok: false, payload: err.payload };\n // D23: a navigation handler rejecting after its signal was aborted\n // abandoned the transition — that is a cancellation, not a failure.\n if (opts.navigationSettlement && controller.signal.aborted) {\n return { ok: false, payload: cancelled(\"The navigation was abandoned after its owner unmounted.\") };\n }\n internals.devError(`[agent-surface] handler failed for ${opts.capabilityId}`, err);\n return {\n ok: false,\n payload: executionFailed(opts.procedureErrors ? \"transport\" : \"handler-error\", {\n transient:\n opts.procedureErrors === true &&\n typeof err === \"object\" &&\n err !== null &&\n (err as { transient?: unknown }).transient === true,\n }),\n };\n };\n\n // The pipeline is async: the registration may have died (or the registry\n // been disposed) between resolution and execution. Re-check here.\n if (internals.disposed) {\n resolve({\n ok: false,\n payload: { code: \"CANCELLED\", message: \"The registry was disposed.\", retry: \"no\" },\n });\n return;\n }\n if (reg.status !== \"active\") {\n resolve({ ok: false, payload: unmounted(\"mid-flight\") });\n return;\n }\n if (opts.externalSignal?.aborted) {\n resolve({\n ok: false,\n payload: cancelled(\"The invocation was cancelled by the host.\"),\n });\n return;\n }\n opts.externalSignal?.addEventListener(\"abort\", onExternalAbort, { once: true });\n\n timer = setTimeout(() => {\n controller.abort();\n finish({\n ok: false,\n payload: {\n code: \"TIMEOUT\",\n message: opts.idempotent\n ? \"The capability timed out. It is idempotent; retrying with a new invocationId is safe.\"\n : \"The capability timed out and side effects may or may not have occurred. Verify state with an observation before repeating.\",\n retry: opts.idempotent ? \"yes\" : \"no\",\n details: { timeoutMs: opts.timeoutMs, idempotent: opts.idempotent },\n },\n });\n }, opts.timeoutMs);\n\n reg.inFlight.add(entry);\n\n let returned: unknown;\n try {\n returned = opts.run(controller.signal);\n } catch (err) {\n finish(handlerError(err));\n return;\n }\n\n if (\n returned !== null &&\n (typeof returned === \"object\" || typeof returned === \"function\") &&\n typeof (returned as PromiseLike<unknown>).then === \"function\"\n ) {\n (returned as Promise<unknown>).then(\n (value) => {\n if (!finish({ ok: true, value })) lateSettlement();\n },\n (err) => {\n if (!finish(handlerError(err))) lateSettlement();\n },\n );\n } else {\n // Synchronous completion settles before any unmount abort (D16).\n finish({ ok: true, value: returned });\n }\n });\n}\n\n/* ─────────────── action serialization per component instance (D13) ─────────────── */\n\nasync function acquireActionSlot(\n internals: RegistryInternals,\n reg: InternalRegistration,\n cap: ActionRuntime | ProcedureRuntime,\n): Promise<\"ok\" | \"overflow\"> {\n const { key, max, depth } = concurrencyGroupFor(cap, internals.limits);\n let group = reg.concurrencyGroups.get(key);\n if (!group) {\n group = { running: 0, max, depth, waiting: [] };\n reg.concurrencyGroups.set(key, group);\n }\n if (group.running < group.max) {\n group.running += 1;\n return \"ok\";\n }\n if (group.waiting.length >= group.depth) {\n // Nothing was reserved, so an idle group must not linger in the map.\n if (group.running === 0 && group.waiting.length === 0) reg.concurrencyGroups.delete(key);\n return \"overflow\";\n }\n await new Promise<void>((resolve) => group.waiting.push(resolve));\n return \"ok\"; // the releasing invocation hands the slot over\n}\n\nfunction releaseActionSlot(\n internals: RegistryInternals,\n reg: InternalRegistration,\n cap: ActionRuntime | ProcedureRuntime,\n): void {\n const { key } = concurrencyGroupFor(cap, internals.limits);\n const group = reg.concurrencyGroups.get(key);\n if (!group) return;\n const next = group.waiting.shift();\n // A handed-over slot stays counted: `running` never dips between the two.\n if (!next) group.running -= 1;\n else next();\n if (group.running === 0 && group.waiting.length === 0) reg.concurrencyGroups.delete(key);\n}\n\n/* ─────────────── bounded observation admission per consumer (D24) ─────────────── */\n\nfunction acquireObservationSlot(\n internals: RegistryInternals,\n consumerKey: string,\n): Promise<\"ok\" | \"overflow\" | \"cancelled\"> {\n const adm = internals.observationAdmission;\n const perCap = internals.limits.maxConcurrentObservationsPerConsumer;\n const totalCap = internals.limits.maxConcurrentObservationsTotal;\n const held = adm.perConsumer.get(consumerKey) ?? 0;\n if (held < perCap && adm.total < totalCap) {\n adm.perConsumer.set(consumerKey, held + 1);\n adm.total += 1;\n return Promise.resolve(\"ok\");\n }\n let queued = 0;\n for (const waiter of adm.waiting) {\n if (waiter.consumerKey === consumerKey) queued += 1;\n }\n if (queued >= internals.limits.maxQueuedObservationsPerConsumer) {\n return Promise.resolve(\"overflow\");\n }\n return new Promise((resolve) => {\n adm.waiting.push({\n consumerKey,\n admit: (admitted) => resolve(admitted ? \"ok\" : \"cancelled\"),\n });\n });\n}\n\nfunction releaseObservationSlot(internals: RegistryInternals, consumerKey: string): void {\n const adm = internals.observationAdmission;\n adm.total = Math.max(0, adm.total - 1);\n const held = adm.perConsumer.get(consumerKey) ?? 0;\n if (held <= 1) adm.perConsumer.delete(consumerKey);\n else adm.perConsumer.set(consumerKey, held - 1);\n\n // Wake the first arrival-ordered waiter whose consumer is under its cap:\n // FIFO within a consumer, no cross-consumer starvation (AS-OBS-002).\n const perCap = internals.limits.maxConcurrentObservationsPerConsumer;\n const totalCap = internals.limits.maxConcurrentObservationsTotal;\n for (let i = 0; i < adm.waiting.length; i++) {\n const waiter = adm.waiting[i];\n if (!waiter) continue;\n const waiterHeld = adm.perConsumer.get(waiter.consumerKey) ?? 0;\n if (waiterHeld < perCap && adm.total < totalCap) {\n adm.waiting.splice(i, 1);\n adm.perConsumer.set(waiter.consumerKey, waiterHeld + 1);\n adm.total += 1;\n waiter.admit(true);\n return;\n }\n }\n}\n\n/** Dispose path: drain queued observation waiters as cancelled (leak-free). */\nexport function drainObservationQueues(internals: RegistryInternals): void {\n const adm = internals.observationAdmission;\n const waiting = adm.waiting.splice(0);\n for (const waiter of waiting) waiter.admit(false);\n}\n","import type {\n AgentConsumer,\n AgentProcedureEffect,\n AgentRouteInfo,\n JsonSchema,\n JsonValue,\n} from \"./types.js\";\nimport type { RegistryInternals, InternalRegistration, ConfirmationLevel } from \"./internal.js\";\nimport {\n buildPolicyContext,\n computeAvailability,\n policiesFor,\n} from \"./internal.js\";\nimport { evaluateDiscovery } from \"./policy.js\";\nimport { byteLength, deepFreeze } from \"./utils.js\";\n\nexport interface SnapshotContext {\n consumer?: AgentConsumer; // default: {\"id\":\"anonymous\",\"kind\":\"embedded\"}\n /** Component-type prefixes to include, e.g. [\"devices\"]. Default: all. */\n scope?: string[];\n /** Include visible-disabled capabilities. Default true. */\n includeUnavailable?: boolean;\n /** [Experimental] Truncation budget. */\n budget?: { maxComponents?: number; maxBytes?: number };\n}\n\nexport interface AgentSurfaceSnapshot {\n surfaceId: string;\n surfaceVersion: string;\n capturedAt: string; // ISO-8601\n route?: AgentRouteInfo;\n components: AgentComponentDescriptor[];\n /** Domain references, top-level (planes are not nested into each other). */\n procedures: AgentProcedureDescriptor[];\n /** [Experimental] Present iff a budget truncated the snapshot. */\n truncated?: { droppedComponents: number };\n /**\n * [Experimental] Present iff a configured scope floor refused part of a\n * requested scope (D27) — set by the adapter, never by `snapshot()`, which\n * has no floor to intersect against. Empty `components` alongside this marker\n * means the request fell outside the floor, not that the surface is empty.\n */\n scopeRejected?: { prefixes: string[] };\n}\n\nexport interface AgentComponentDescriptor {\n type: string;\n instanceId: string;\n registrationId: string;\n description: string;\n parent?: { type: string; instanceId: string };\n meta?: Record<string, JsonValue>;\n observations: AgentObservationDescriptor[];\n actions: AgentActionDescriptor[];\n}\n\nexport interface AgentObservationDescriptor {\n capabilityId: string; // \"view:devices.table.readState\"\n name: string; // \"readState\"\n description: string;\n outputSchema: JsonSchema;\n available: boolean;\n unavailableReason?: string;\n meta?: Record<string, JsonValue>;\n}\n\nexport interface AgentActionDescriptor {\n capabilityId: string;\n name: string;\n description: string;\n inputSchema: JsonSchema;\n outputSchema?: JsonSchema;\n effect: \"local-state\" | \"navigation\";\n idempotent: boolean;\n reversible: boolean;\n confirmation: \"never\" | \"optional\" | \"required\";\n available: boolean;\n unavailableReason?: string;\n meta?: Record<string, JsonValue>;\n}\n\nexport interface AgentProcedureDescriptor {\n procedureId: string; // \"domain:devices.disable\"\n /**\n * The manifest description. Stable across snapshots — the contextual\n * `describe()` output is `contextualNote` and is never folded in here (D28).\n */\n description: string;\n /** Volatile: this snapshot's contextual `describe()` output, if any. */\n contextualNote?: string;\n /** Agent-facing (reduced) input schema per binding rule 1 (docs/05). */\n inputSchema: JsonSchema;\n outputSchema?: JsonSchema;\n effect: AgentProcedureEffect;\n confirmation: ConfirmationLevel; // max(manifest, reference)\n available: boolean;\n unavailableReason?: string;\n boundFields: Array<{ path: string; locked: boolean; source: \"ui-state\" }>;\n /** The registration that contributed this reference (staleness token). */\n registrationId: string;\n /** Optional link to the owning view component. */\n context?: { type: string; instanceId: string };\n meta?: Record<string, JsonValue>;\n}\n\nexport type AgentCapabilityDescriptorUnion =\n | AgentObservationDescriptor\n | AgentActionDescriptor\n | AgentProcedureDescriptor;\n\nconst DEFAULT_CONSUMER: AgentConsumer = { id: \"anonymous\", kind: \"embedded\" };\n\nfunction matchesScope(type: string, scope: string[] | undefined): boolean {\n if (!scope || scope.length === 0) return true;\n return scope.some((prefix) => type === prefix || type.startsWith(`${prefix}.`));\n}\n\nfunction sortRegistrations(regs: InternalRegistration[]): InternalRegistration[] {\n return regs.sort((a, b) => {\n if (a.priority !== b.priority) return b.priority - a.priority;\n if (a.type !== b.type) return a.type < b.type ? -1 : 1;\n return a.instanceId < b.instanceId ? -1 : a.instanceId > b.instanceId ? 1 : 0;\n });\n}\n\n/**\n * Synchronous, side-effect-free catalog projection (docs/03 §snapshot, D5):\n * never runs read() handlers, never awaits, never serializes `internal`.\n */\nexport function createSnapshot(\n internals: RegistryInternals,\n ctx?: SnapshotContext,\n): AgentSurfaceSnapshot {\n const consumer = ctx?.consumer ?? DEFAULT_CONSUMER;\n const includeUnavailable = ctx?.includeUnavailable ?? true;\n const host = internals.host();\n\n const regs = sortRegistrations(\n [...internals.registrations.values()].filter((r) => r.status === \"active\"),\n );\n\n const components: AgentComponentDescriptor[] = [];\n const componentPriority: number[] = [];\n const procedures: AgentProcedureDescriptor[] = [];\n\n for (const reg of regs) {\n const inScopeForComponents = matchesScope(reg.type, ctx?.scope);\n\n if (!reg.procedureOnly && inScopeForComponents) {\n const observations: AgentObservationDescriptor[] = [];\n const actions: AgentActionDescriptor[] = [];\n let definedCount = 0;\n let hiddenCount = 0;\n\n for (const obs of reg.observations.values()) {\n definedCount += 1;\n const chain = policiesFor(internals, reg, obs);\n const policyCtx = buildPolicyContext(internals, reg, obs, consumer, host);\n const decision = evaluateDiscovery(chain, policyCtx);\n if (decision.decision === \"hide\") {\n hiddenCount += 1;\n continue;\n }\n const availability = computeAvailability(internals, reg, obs);\n const available = availability.available && decision.decision === \"expose\";\n const reason =\n decision.decision === \"disable\" ? decision.reason : availability.reason;\n if (!available && !includeUnavailable) continue;\n observations.push({\n capabilityId: obs.capabilityId,\n name: obs.name,\n description: obs.description,\n outputSchema: obs.jsonSchema,\n available,\n ...(available ? {} : { unavailableReason: reason }),\n ...(obs.meta ? { meta: obs.meta } : {}),\n });\n }\n\n for (const act of reg.actions.values()) {\n definedCount += 1;\n const chain = policiesFor(internals, reg, act);\n const policyCtx = buildPolicyContext(internals, reg, act, consumer, host);\n const decision = evaluateDiscovery(chain, policyCtx);\n if (decision.decision === \"hide\") {\n hiddenCount += 1;\n continue;\n }\n const availability = computeAvailability(internals, reg, act);\n const available = availability.available && decision.decision === \"expose\";\n const reason =\n decision.decision === \"disable\" ? decision.reason : availability.reason;\n if (!available && !includeUnavailable) continue;\n actions.push({\n capabilityId: act.capabilityId,\n name: act.name,\n description: act.description,\n inputSchema: act.inputJsonSchema,\n ...(act.outputJsonSchema ? { outputSchema: act.outputJsonSchema } : {}),\n effect: act.effect,\n idempotent: act.idempotent,\n reversible: act.reversible,\n confirmation: act.confirmation,\n available,\n ...(available ? {} : { unavailableReason: reason }),\n ...(act.meta ? { meta: act.meta } : {}),\n });\n }\n\n // Deny-by-default: a component whose every capability is policy-hidden\n // is itself hidden (existence is information, docs/06).\n const allHidden = definedCount > 0 && hiddenCount === definedCount;\n if (!allHidden) {\n components.push({\n type: reg.type,\n instanceId: reg.instanceId,\n registrationId: reg.id,\n description: reg.description,\n ...(reg.parent ? { parent: reg.parent } : {}),\n ...(reg.meta ? { meta: reg.meta } : {}),\n observations,\n actions,\n });\n componentPriority.push(reg.priority);\n }\n }\n\n for (const proc of reg.procedures) {\n const scopeMatch = proc.contextLink\n ? matchesScope(proc.contextLink.type, ctx?.scope)\n : matchesScope(proc.path, ctx?.scope);\n if (!scopeMatch) continue;\n const chain = policiesFor(internals, reg, proc);\n const policyCtx = buildPolicyContext(internals, reg, proc, consumer, host);\n const decision = evaluateDiscovery(chain, policyCtx);\n if (decision.decision === \"hide\") continue;\n const availability = computeAvailability(internals, reg, proc);\n const available = availability.available && decision.decision === \"expose\";\n const reason = decision.decision === \"disable\" ? decision.reason : availability.reason;\n if (!available && !includeUnavailable) continue;\n // D28: the stable description and the volatile note are kept apart here,\n // and merged back only for hosts that have not migrated yet.\n let contextualNote: string | undefined;\n const describe = proc.binding.config.describe;\n if (describe) {\n try {\n const contextual = describe();\n if (contextual) contextualNote = contextual;\n } catch {\n /* describe() must not break the snapshot */\n }\n }\n procedures.push({\n procedureId: proc.capabilityId,\n // Never merged with `contextualNote` (D28): the manifest text is the\n // stable half, and folding volatile text in is what churned the\n // provider's cached prompt prefix.\n description: proc.baseDescription,\n ...(contextualNote !== undefined ? { contextualNote } : {}),\n inputSchema: proc.reducedInputSchema,\n ...(proc.outputJsonSchema ? { outputSchema: proc.outputJsonSchema } : {}),\n effect: proc.effect,\n confirmation: proc.confirmationFloor,\n available,\n ...(available ? {} : { unavailableReason: reason }),\n boundFields: proc.boundKeys.map((path) => ({\n path,\n locked: proc.lockedKeys.includes(path),\n source: \"ui-state\" as const,\n })),\n registrationId: reg.id,\n ...(proc.contextLink ? { context: proc.contextLink } : {}),\n ...(proc.meta ? { meta: proc.meta } : {}),\n });\n }\n }\n\n // Budgets (Experimental): drop lowest-priority components first, loudly.\n let dropped = 0;\n const budget = ctx?.budget;\n if (budget?.maxComponents !== undefined && components.length > budget.maxComponents) {\n dropped += components.length - budget.maxComponents;\n dropLowestPriority(components, componentPriority, components.length - budget.maxComponents);\n }\n if (budget?.maxBytes !== undefined) {\n while (components.length > 0 && byteLength(components) > budget.maxBytes) {\n dropLowestPriority(components, componentPriority, 1);\n dropped += 1;\n }\n }\n\n const snapshot: AgentSurfaceSnapshot = {\n surfaceId: internals.surfaceId,\n surfaceVersion: String(internals.version),\n capturedAt: new Date(internals.now()).toISOString(),\n ...(internals.routeFn?.() ? { route: internals.routeFn() } : {}),\n components,\n procedures,\n ...(dropped > 0 ? { truncated: { droppedComponents: dropped } } : {}),\n };\n return deepFreeze(snapshot);\n}\n\nfunction dropLowestPriority(\n components: AgentComponentDescriptor[],\n priorities: number[],\n count: number,\n): void {\n for (let n = 0; n < count && components.length > 0; n++) {\n let lowestIndex = 0;\n for (let i = 1; i < priorities.length; i++) {\n if ((priorities[i] ?? 0) <= (priorities[lowestIndex] ?? 0)) lowestIndex = i;\n }\n components.splice(lowestIndex, 1);\n priorities.splice(lowestIndex, 1);\n }\n}\n","import type {\n AgentEnvironment,\n AgentRouteInfo,\n AgentSurfaceLimits,\n} from \"./types.js\";\nimport { DEFAULT_LIMITS, type Unsubscribe } from \"./types.js\";\nimport type {\n AgentComponentDefinition,\n AgentProcedureExecutor,\n} from \"./definition.js\";\nimport { validateComponentDefinition } from \"./definition.js\";\nimport type { AgentPolicy } from \"./policy.js\";\nimport type { AuditSink, AuditEvent } from \"./audit.js\";\nimport { consoleAuditSink, memoryAuditSink, safeRecord } from \"./audit.js\";\nimport { EventDispatcher, type AgentSurfaceEvent } from \"./events.js\";\nimport { ConfirmationStore, type ConfirmationController } from \"./confirmation.js\";\nimport type { AgentInvocation, AgentInvocationResult, InvokeOptions } from \"./invocation-types.js\";\nimport { drainObservationQueues, performInvoke } from \"./invoke.js\";\nimport { createSnapshot, type AgentSurfaceSnapshot, type SnapshotContext } from \"./snapshot.js\";\nimport {\n DEV_WARN,\n addTombstone,\n componentKey,\n nextRegistrationId,\n normalizeRegistration,\n type InternalRegistration,\n type RegistryInternals,\n} from \"./internal.js\";\nimport { AgentSurfaceDefinitionError } from \"./errors.js\";\nimport { formatViewCapabilityId } from \"./ids.js\";\nimport { randomBase62 } from \"./utils.js\";\n\nexport interface RegistrationCandidate {\n definition: AgentComponentDefinition; // includes origin (default \"first-party\")\n stack?: string; // dev-mode capture for diagnostics\n}\n\nexport interface RegistryOptions {\n /** \"development\" | \"production\" | \"test\". Default: \"production\". */\n environment?: AgentEnvironment;\n /** Host context provider. MUST be synchronous and cheap. */\n context?: () => Record<string, unknown>;\n /** Global policies, outermost layer of every chain. */\n policies?: AgentPolicy[];\n /** Audit sink; default: bounded in-memory sink (+ console in development). */\n audit?: AuditSink;\n /** Guard invoked before accepting a registration (trust filtering, docs/06). */\n onRegister?: (candidate: RegistrationCandidate) => \"accept\" | \"reject\";\n /** Collision handling for duplicate (type, instanceId). Default \"reject\". */\n onDuplicateInstance?: \"reject\" | \"replace\";\n /** Suffix-collision diagnostics vs known domain ids. Default \"warn\". */\n duplicateSuffixPolicy?: \"off\" | \"warn\" | \"error\";\n /** Route descriptor for snapshots (host wires its router here). */\n route?: () => AgentRouteInfo | undefined;\n limits?: Partial<AgentSurfaceLimits>;\n /** Injectable clock (docs/08 determinism); default Date.now. */\n now?: () => number;\n}\n\nexport interface AgentRegistrationHandle {\n readonly registrationId: string; // \"reg_\" + monotonic + random\n readonly status: \"active\" | \"rejected\" | \"unregistered\";\n /** Push dynamic updates; only these fields are updatable (D2). */\n update(patch: {\n enabled?: boolean;\n availability?: Record<string, { available: boolean; reason?: string }>;\n }): void;\n /** Bumps the surface version without changing anything. */\n invalidate(): void;\n unregister(): void;\n}\n\nexport interface AgentSurfaceRegistry {\n readonly surfaceId: string; // \"srf_\" + random, per instance\n register(definition: AgentComponentDefinition): AgentRegistrationHandle;\n snapshot(context?: SnapshotContext): AgentSurfaceSnapshot; // synchronous\n invoke(request: AgentInvocation, options?: InvokeOptions): Promise<AgentInvocationResult>;\n subscribe(listener: (event: AgentSurfaceEvent) => void): Unsubscribe;\n confirmations: ConfirmationController;\n /** Register a domain-procedure executor (installed by @agent-surface/orpc). */\n setProcedureExecutor(executor: AgentProcedureExecutor | undefined): void;\n getVersion(): string;\n /** Tears down: aborts in-flight invocations (CANCELLED), clears listeners. */\n dispose(): void;\n}\n\nexport function createAgentSurfaceRegistry(options?: RegistryOptions): AgentSurfaceRegistry {\n const environment = options?.environment ?? \"production\";\n const limits: AgentSurfaceLimits = { ...DEFAULT_LIMITS, ...(options?.limits ?? {}) };\n const now = options?.now ?? (() => Date.now());\n const auditSink: AuditSink =\n options?.audit ??\n (environment === \"development\"\n ? combineSinks(memoryAuditSink(), consoleAuditSink())\n : memoryAuditSink());\n\n let surfaceChangedScheduled = false;\n\n const dispatcher = new EventDispatcher((err) => {\n if (environment === \"development\") {\n // eslint-disable-next-line no-console\n console.error(\"[agent-surface] event listener threw\", err);\n }\n });\n\n const internals: RegistryInternals = {\n environment,\n limits,\n surfaceId: `srf_${randomBase62(22)}`,\n version: 0,\n registrations: new Map(),\n byKey: new Map(),\n tombstones: new Map(),\n dedupe: new Map(),\n observationAdmission: { total: 0, perConsumer: new Map(), waiting: [] },\n dispatcher,\n confirmations: undefined as unknown as ConfirmationStore, // set below\n executor: undefined,\n disposed: false,\n registryPolicies: [...(options?.policies ?? [])],\n auditSink,\n contextFn: options?.context,\n routeFn: options?.route,\n now,\n bumpVersion() {\n internals.version += 1;\n if (!surfaceChangedScheduled) {\n surfaceChangedScheduled = true;\n queueMicrotask(() => {\n surfaceChangedScheduled = false;\n if (internals.disposed) return;\n internals.emit({ type: \"surface-changed\", surfaceVersion: String(internals.version) });\n });\n }\n },\n emit(event) {\n dispatcher.emit(event);\n },\n recordAudit(event: Omit<AuditEvent, \"at\">) {\n safeRecord(auditSink, { at: new Date(now()).toISOString(), ...event });\n },\n host() {\n try {\n return internals.contextFn?.() ?? {};\n } catch (err) {\n internals.devWarn(\"[agent-surface] RegistryOptions.context() threw\", err);\n return {};\n }\n },\n devWarn(...args) {\n if (environment === \"development\") {\n // eslint-disable-next-line no-console\n console.warn(...args);\n }\n },\n devError(...args) {\n if (environment === \"development\") {\n // eslint-disable-next-line no-console\n console.error(...args);\n }\n },\n };\n\n internals.confirmations = new ConfirmationStore({\n ttlMs: limits.confirmationTtlMs,\n maxPending: limits.maxPendingConfirmations,\n now,\n emit: (event) => internals.emit(event),\n audit: (event) => internals.recordAudit(event),\n });\n\n const onDuplicateInstance = options?.onDuplicateInstance ?? \"reject\";\n const duplicateSuffixPolicy = options?.duplicateSuffixPolicy ?? \"warn\";\n\n function deadHandle(): AgentRegistrationHandle {\n const id = nextRegistrationId(() => randomBase62(6));\n return {\n registrationId: id,\n status: \"rejected\",\n update() {\n internals.devWarn(\"[agent-surface] update() called on a rejected registration handle\");\n },\n invalidate() {\n internals.devWarn(\"[agent-surface] invalidate() called on a rejected registration handle\");\n },\n unregister() {\n /* no-op */\n },\n };\n }\n\n function unregisterInternal(reg: InternalRegistration): void {\n if (reg.status !== \"active\") return;\n reg.status = \"unregistered\";\n internals.registrations.delete(reg.id);\n if (internals.byKey.get(reg.key) === reg.id) internals.byKey.delete(reg.key);\n addTombstone(internals, reg);\n // Abort in-flight invocations: non-navigation ones settle\n // COMPONENT_UNMOUNTED unless the handler already settled (first settle\n // wins, D16); navigation ones only lose their signal and settle on\n // handler settlement (D23).\n for (const entry of [...reg.inFlight]) {\n entry.onUnregister();\n }\n internals.bumpVersion();\n internals.emit({\n type: \"component-unregistered\",\n registrationId: reg.id,\n componentType: reg.type,\n instanceId: reg.instanceId,\n });\n internals.recordAudit({\n type: \"unregistration\",\n registrationId: reg.id,\n capabilityId: undefined,\n });\n }\n\n function checkSuffixCollisions(def: AgentComponentDefinition): void {\n if (duplicateSuffixPolicy === \"off\") return;\n const paths = internals.executor?.paths;\n if (!paths || paths.length === 0) return;\n const names = [\n ...Object.keys(def.observations ?? {}),\n ...Object.keys(def.actions ?? {}),\n ];\n for (const name of names) {\n const candidatePath = `${def.type}.${name}`;\n if (paths.includes(candidatePath)) {\n const viewCapabilityId = formatViewCapabilityId(def.type, name);\n const domainProcedureId = `domain:${candidatePath}`;\n if (duplicateSuffixPolicy === \"error\") {\n throw new AgentSurfaceDefinitionError(\n \"PLANE_VIOLATION\",\n `view capability \"${viewCapabilityId}\" collides with domain procedure \"${domainProcedureId}\" — reference the procedure instead of redefining it (docs/05)`,\n );\n }\n internals.devWarn(\n `[agent-surface] suspicious suffix collision: \"${viewCapabilityId}\" vs \"${domainProcedureId}\"`,\n );\n internals.emit({ type: \"collision-suspected\", viewCapabilityId, domainProcedureId });\n internals.recordAudit({\n type: \"collision-suspected\",\n capabilityId: viewCapabilityId,\n });\n }\n }\n }\n\n const registry: AgentSurfaceRegistry = {\n surfaceId: internals.surfaceId,\n\n register(definition: AgentComponentDefinition): AgentRegistrationHandle {\n if (internals.disposed) throw new Error(\"register() called on a disposed registry\");\n\n // Structural defects throw in EVERY environment (docs/03 §registry, D4).\n validateComponentDefinition(definition, limits, {\n hasProcedureExecutor: internals.executor !== undefined,\n });\n checkSuffixCollisions(definition);\n\n const instanceId = definition.instanceId ?? \"default\";\n\n // Runtime conditions produce dead handles, never throws (D4).\n if (options?.onRegister) {\n let verdict: \"accept\" | \"reject\" = \"accept\";\n try {\n verdict = options.onRegister({\n definition,\n ...(environment === \"development\" ? { stack: new Error().stack } : {}),\n });\n } catch (err) {\n internals.devError(\"[agent-surface] onRegister guard threw; rejecting\", err);\n verdict = \"reject\";\n }\n if (verdict === \"reject\") {\n internals.emit({\n type: \"component-rejected\",\n componentType: definition.type,\n instanceId,\n reason: \"guard\",\n });\n internals.recordAudit({ type: \"registration-rejected\" });\n internals.devError(\n `[agent-surface] registration of \"${definition.type}\" (${instanceId}) rejected by guard`,\n );\n return deadHandle();\n }\n }\n\n const key = componentKey(definition.type, instanceId);\n const existingId = internals.byKey.get(key);\n if (existingId !== undefined) {\n if (onDuplicateInstance === \"reject\") {\n internals.emit({\n type: \"component-rejected\",\n componentType: definition.type,\n instanceId,\n reason: \"duplicate\",\n });\n internals.recordAudit({ type: \"registration-rejected\" });\n internals.devError(\n `[agent-surface] duplicate registration of \"${definition.type}\" (${instanceId}); first-wins (onDuplicateInstance: \"reject\")`,\n );\n return deadHandle();\n }\n const existing = internals.registrations.get(existingId);\n if (existing) unregisterInternal(existing);\n }\n\n const reg = normalizeRegistration(definition, nextRegistrationId(() => randomBase62(6)));\n internals.registrations.set(reg.id, reg);\n internals.byKey.set(reg.key, reg.id);\n internals.bumpVersion();\n internals.emit({\n type: \"component-registered\",\n registrationId: reg.id,\n componentType: reg.type,\n instanceId: reg.instanceId,\n });\n internals.recordAudit({ type: \"registration\", registrationId: reg.id });\n\n return {\n get registrationId() {\n return reg.id;\n },\n get status() {\n return reg.status === \"active\" ? (\"active\" as const) : (\"unregistered\" as const);\n },\n update(patch) {\n if (reg.status !== \"active\") {\n internals.devWarn(\n `[agent-surface] update() called after unregistration of \"${reg.type}\"`,\n );\n return;\n }\n let changed = false;\n if (patch.enabled !== undefined && patch.enabled !== reg.enabled) {\n reg.enabled = patch.enabled;\n changed = true;\n }\n if (patch.availability) {\n for (const [name, value] of Object.entries(patch.availability)) {\n const prev = reg.availabilityOverrides.get(name);\n if (!prev || prev.available !== value.available || prev.reason !== value.reason) {\n reg.availabilityOverrides.set(name, {\n available: value.available,\n ...(value.reason !== undefined ? { reason: value.reason } : {}),\n });\n changed = true;\n const capabilityId =\n reg.observations.get(name)?.capabilityId ??\n reg.actions.get(name)?.capabilityId ??\n reg.procedures.find((p) => p.path === name)?.capabilityId ??\n name;\n internals.emit({\n type: \"availability-changed\",\n registrationId: reg.id,\n capabilityId,\n available: value.available,\n });\n }\n }\n }\n if (changed) internals.bumpVersion();\n },\n invalidate() {\n if (reg.status !== \"active\") return;\n internals.bumpVersion();\n },\n unregister() {\n unregisterInternal(reg);\n },\n };\n },\n\n snapshot(context?: SnapshotContext): AgentSurfaceSnapshot {\n if (internals.disposed) throw new Error(\"snapshot() called on a disposed registry\");\n return createSnapshot(internals, context);\n },\n\n invoke(request, invokeOptions) {\n return performInvoke(internals, request, invokeOptions);\n },\n\n subscribe(listener) {\n return dispatcher.subscribe(listener);\n },\n\n confirmations: internals.confirmations.controller(),\n\n setProcedureExecutor(executor) {\n internals.executor = executor;\n },\n\n getVersion() {\n return String(internals.version);\n },\n\n dispose() {\n if (internals.disposed) return;\n for (const reg of [...internals.registrations.values()]) {\n for (const entry of [...reg.inFlight]) {\n entry.onDispose();\n }\n reg.status = \"unregistered\";\n }\n drainObservationQueues(internals);\n internals.registrations.clear();\n internals.byKey.clear();\n internals.confirmations.disposeAll();\n internals.disposed = true;\n dispatcher.clear();\n },\n };\n\n // Internal seam (DEV_WARN): adapters in this package report dev-mode repairs\n // through the registry's own environment gate rather than a second one.\n Object.defineProperty(registry, DEV_WARN, {\n value: (...args: unknown[]) => internals.devWarn(...args),\n enumerable: false,\n });\n\n return registry;\n}\n\nfunction combineSinks(...sinks: AuditSink[]): AuditSink {\n return {\n record(event) {\n for (const sink of sinks) safeRecord(sink, event);\n },\n };\n}\n","import type { AgentConsumer, JsonSchema, JsonValue, Unsubscribe } from \"./types.js\";\nimport type { AgentSurfaceRegistry } from \"./registry.js\";\nimport type { AgentInvocationResult } from \"./invocation-types.js\";\nimport type { AgentCapabilityErrorPayload } from \"./errors.js\";\nimport type {\n AgentActionDescriptor,\n AgentObservationDescriptor,\n AgentProcedureDescriptor,\n AgentSurfaceSnapshot,\n} from \"./snapshot.js\";\nimport { DEV_WARN, type DevWarnCarrier } from \"./internal.js\";\nimport { assignWireNames, type WireNameEntry } from \"./ids.js\";\nimport { randomBase62 } from \"./utils.js\";\n\nexport interface AgentToolsetOptions {\n consumer: AgentConsumer;\n /**\n * \"direct\": one tool per capability — provider-native input typing, catalog\n * size linear in the surface. \"meta\": three fixed tools with lazy discovery —\n * constant tool-block size, one extra round trip before the first act.\n *\n * [Experimental] applies to \"meta\" only (D29): the three verbs' envelope may\n * change in any release — 0.6 typed `surface_act.input` and started enforcing\n * the verb schemas (D32). \"direct\" is Draft, like the rest of the API.\n *\n * Default \"direct\"; see the selection guide in docs/09 §choosing-a-mode.\n */\n mode?: \"direct\" | \"meta\";\n /**\n * Loop topology (D26). Sets the confirmation-mode default: \"embedded\" →\n * \"wait\", \"remote\" → \"two-phase\". One of `topology` or `confirmations`\n * MUST be provided — there is no ambiguous global default.\n */\n topology?: \"embedded\" | \"remote\";\n /**\n * \"wait\": on CONFIRMATION_REQUIRED, await user resolution (up to TTL) and\n * auto-retry, so the model sees one tool call → one final result.\n * \"two-phase\": surface CONFIRMATION_REQUIRED to the model, which retries.\n * Overrides the topology default (a remote loop opting into \"wait\" owns\n * its transport-timeout story, docs/09 §confirmation-topology).\n */\n confirmations?: \"wait\" | \"two-phase\";\n /**\n * Component-type prefixes this consumer may discover. D27: this is a\n * **floor** — in \"meta\" mode a model-supplied `scope` can only narrow it\n * further, never widen it. Not an authority boundary: `invoke` does not\n * check scope in either mode (docs/09 §scope-is-discovery-only).\n */\n scope?: string[];\n /**\n * [Experimental] Snapshot truncation budget for `surface_discover`.\n * \"meta\" mode only — there the `truncated` marker rides in the payload the\n * model reads. In \"direct\" mode a budget would silently drop tools with no\n * signal to anyone, so it is rejected rather than half-honored.\n */\n budget?: { maxComponents?: number; maxBytes?: number };\n}\n\nexport interface AgentTool {\n /** Wire-safe name (docs/09 §wire-names), ≤ 64 chars, unique in this catalog. */\n name: string;\n /**\n * Plane + effect + confirmation prefix, then the authored description.\n * Contains NO live state (D28), so it is safe in a provider tool block with\n * prompt-prefix caching across steps.\n */\n description: string;\n inputSchema: JsonSchema;\n /**\n * Volatile: re-derived on every snapshot. Hosts render this OUTSIDE the tool\n * block (e.g. a trailing system message) so availability stays honest without\n * invalidating the cached prefix (D28).\n */\n state: {\n available: boolean;\n unavailableReason?: string;\n /** Live text contributed by a contextual binding's `describe()`. */\n note?: string;\n };\n execute(input: JsonValue, call: { toolCallId?: string }): Promise<AgentInvocationResult>;\n}\n\nexport interface AgentToolset {\n tools(): AgentTool[]; // recomputed per surface version\n /**\n * wireName → canonical capability id, for the catalog `tools()` last built.\n * Authoritative: shortened names are not decodable by string surgery, so a\n * host MUST consult this rather than reversing names itself (D30). Empty in\n * \"meta\" mode, whose three tool names are not capability ids.\n */\n wireNameMap(): ReadonlyMap<string, string>;\n /** Fires when tools() would return a different catalog. */\n subscribe(listener: (tools: AgentTool[]) => void): Unsubscribe;\n dispose(): void;\n}\n\ninterface CatalogEntry {\n capabilityId: string;\n /**\n * Omitted when the target is not uniquely resolvable from the snapshot, so\n * the registry's own resolver decides (AMBIGUOUS_INSTANCE / not-found /\n * unmounted). Never send a placeholder: an empty string reads as \"this exact\n * registration\", which resolves to STALE_CAPABILITY and sends the agent into\n * a refresh loop against an unchanged surface (AS-ADAPTER-003).\n */\n registrationId?: string;\n instanceId?: string;\n surfaceVersion: string;\n kind: \"observation\" | \"action\" | \"procedure\";\n}\n\nconst EMPTY_INPUT_SCHEMA: JsonSchema = {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n};\n\n/* ───────────────────────── meta-mode verb schemas ─────────────────────────\n * Module-level constants: the three verbs are the same bytes for every toolset\n * and every mount, which is the property AS-META-005 and D28 pin.\n */\n\nconst META_DISCOVER_SCHEMA: JsonSchema = {\n type: \"object\",\n properties: {\n scope: {\n type: \"array\",\n items: { type: \"string\" },\n // No enum: valid tokens are live component types, and inlining them\n // would make this tool block churn on every mount — the churn\n // AS-META-005 and D28 exist to prevent.\n description:\n 'Component-type prefixes to narrow the result, e.g. [\"devices.table\"], taken from `components[].type` of an earlier call — omit on the first. Narrows only: prefixes outside this host\\'s configured scope match nothing and come back in `scopeRejected`.',\n },\n },\n additionalProperties: false,\n};\n\nconst META_READ_SCHEMA: JsonSchema = {\n type: \"object\",\n properties: {\n capabilityId: {\n type: \"string\",\n description:\n \"Observation id, verbatim from `observations[].capabilityId` in a discover result.\",\n },\n instanceId: {\n type: \"string\",\n description:\n \"Only when several components share a type: `components[].instanceId` picks one.\",\n },\n },\n required: [\"capabilityId\"],\n additionalProperties: false,\n};\n\nconst META_ACT_SCHEMA: JsonSchema = {\n type: \"object\",\n properties: {\n capabilityId: {\n type: \"string\",\n description: \"Action `capabilityId` or `procedureId`, verbatim from a discover result.\",\n },\n instanceId: {\n type: \"string\",\n description:\n \"Only when several components share a type: `components[].instanceId` picks one.\",\n },\n // Typed, and not merely described: an untyped property is the one position\n // a provider's constrained decoder cannot constrain, so the model falls\n // back to its prior — a JSON-encoded string, the shape\n // `function_call.arguments` carries — and sorts the rest of the capability's\n // arguments into the sibling modifiers below. `type: \"object\"` costs\n // nothing in practice: direct mode already passes `act.inputSchema`\n // straight through as the tool schema, and providers require that to be an\n // object schema at the top level. No `additionalProperties` here — the\n // capability's own schema governs what goes inside.\n input: {\n type: \"object\",\n description:\n \"Arguments matching that capability's `inputSchema`, as a JSON object — not a JSON-encoded string. Everything the capability declares goes in here, never beside it.\",\n },\n invocationId: {\n type: \"string\",\n description:\n \"Reuse a previous call's id to retry without executing twice; required when resuming after CONFIRMATION_REQUIRED.\",\n },\n confirmationId: {\n type: \"string\",\n description:\n \"The id returned with CONFIRMATION_REQUIRED, sent back after the user approves.\",\n },\n surfaceVersion: {\n type: \"string\",\n description:\n \"The `surfaceVersion` you planned against. Send it for destructive or externally-visible calls: a surface that moved underneath the plan then fails instead of executing. Omitted, the call binds to what is live now.\",\n },\n },\n required: [\"capabilityId\"],\n additionalProperties: false,\n};\n\n/**\n * Stable properties of the capability — plane, effect, confirmation. Never\n * availability: that is a property of the moment, and folding it in here is\n * what made the tool block churn between steps (D28).\n */\nfunction describePrefix(\n plane: \"view\" | \"domain\",\n effect: string,\n confirmation: \"never\" | \"optional\" | \"required\",\n): string {\n const parts = [plane, effect];\n if (confirmation === \"required\") parts.push(\"requires confirmation\");\n return `[${parts.join(\" · \")}]`;\n}\n\nfunction availabilityState(descriptor: {\n available: boolean;\n unavailableReason?: string;\n contextualNote?: string;\n}): AgentTool[\"state\"] {\n return {\n available: descriptor.available,\n ...(descriptor.unavailableReason !== undefined\n ? { unavailableReason: descriptor.unavailableReason }\n : {}),\n ...(descriptor.contextualNote !== undefined ? { note: descriptor.contextualNote } : {}),\n };\n}\n\nexport function createAgentToolset(\n registry: AgentSurfaceRegistry,\n options: AgentToolsetOptions,\n): AgentToolset {\n const mode = options.mode ?? \"direct\";\n if (options.confirmations === undefined && options.topology === undefined) {\n // D26: no ambiguous global default — programmer misuse, every environment.\n throw new Error(\n \"createAgentToolset: declare a topology ('embedded' | 'remote') or an explicit confirmations mode ('wait' | 'two-phase'). Embedded loops default to 'wait', remote loops to 'two-phase' (docs/09 §confirmation-topology).\",\n );\n }\n if (options.budget !== undefined && mode !== \"meta\") {\n // No silent no-op: in direct mode a budget would drop tools from the\n // catalog with no `truncated` marker anywhere the host or model can see.\n throw new Error(\n \"createAgentToolset: `budget` applies to mode 'meta' only — in 'direct' mode it would silently drop tools. Pass a `scope` to bound a direct catalog instead (docs/09 §meta-tools-mode).\",\n );\n }\n const confirmationsMode =\n options.confirmations ?? (options.topology === \"remote\" ? \"two-phase\" : \"wait\");\n // Dev diagnostics ride the registry's own environment gate (DEV_WARN); a\n // registry built elsewhere (a test double) simply carries none.\n const devWarn = (registry as unknown as DevWarnCarrier)[DEV_WARN] ?? ((): void => {});\n const listeners = new Set<(tools: AgentTool[]) => void>();\n const pendingWaits = new Set<AbortController>();\n let disposed = false;\n let cachedVersion: string | undefined;\n let cachedTools: AgentTool[] | undefined;\n let cachedWireNames: ReadonlyMap<string, string> = new Map();\n let cachedSignature: string | undefined;\n\n /** Wait for a confirmation, abortable by dispose (AS-TOPO-003, D26).\n * The disposed guard covers the window where dispose lands between the\n * CONFIRMATION_REQUIRED result and this wait's registration. */\n async function waitForConfirmation(confirmationId: string): Promise<void> {\n if (disposed) return;\n const controller = new AbortController();\n pendingWaits.add(controller);\n try {\n await registry.confirmations.waitFor(confirmationId, { signal: controller.signal });\n } finally {\n pendingWaits.delete(controller);\n }\n }\n\n async function invokeThroughSurface(\n entry: CatalogEntry,\n input: JsonValue | undefined,\n toolCallId: string | undefined,\n overrides?: { invocationId?: string; confirmationId?: string },\n ): Promise<AgentInvocationResult> {\n const invocationId = overrides?.invocationId ?? toolCallId ?? `inv_${randomBase62(12)}`;\n const base = {\n invocationId,\n capabilityId: entry.capabilityId,\n ...(entry.instanceId !== undefined ? { instanceId: entry.instanceId } : {}),\n ...(entry.registrationId !== undefined ? { registrationId: entry.registrationId } : {}),\n surfaceVersion: entry.surfaceVersion,\n ...(input !== undefined ? { input } : {}),\n ...(overrides?.confirmationId !== undefined\n ? { confirmationId: overrides.confirmationId }\n : {}),\n };\n let result = await registry.invoke(base, { consumer: options.consumer });\n if (\n confirmationsMode === \"wait\" &&\n result.status === \"error\" &&\n result.error.code === \"CONFIRMATION_REQUIRED\"\n ) {\n const confirmationId = result.error.details?.confirmationId;\n if (typeof confirmationId === \"string\") {\n await waitForConfirmation(confirmationId);\n // Deterministic shutdown: a dispose mid-wait returns the pending\n // CONFIRMATION_REQUIRED result as-is (D26).\n if (disposed) return result;\n // Retry reuses the SAME invocationId + confirmationId (docs/03 D14):\n // CONFIRMATION_REQUIRED was not cached as terminal, so this executes.\n result = await registry.invoke(\n { ...base, confirmationId },\n { consumer: options.consumer },\n );\n }\n }\n return result;\n }\n\n function buildDirectTools(): { tools: AgentTool[]; wireNames: ReadonlyMap<string, string> } {\n const snapshot = registry.snapshot({\n consumer: options.consumer,\n ...(options.scope ? { scope: options.scope } : {}),\n includeUnavailable: true,\n });\n\n interface PendingTool {\n wire: WireNameEntry;\n entry: CatalogEntry;\n prefix: string;\n description: string;\n inputSchema: JsonSchema;\n state: AgentTool[\"state\"];\n }\n const pending: PendingTool[] = [];\n\n const push = (\n capabilityId: string,\n kind: CatalogEntry[\"kind\"],\n registrationId: string,\n instanceId: string | undefined,\n prefix: string,\n description: string,\n inputSchema: JsonSchema,\n state: AgentTool[\"state\"],\n nameSuffix?: string,\n ): void => {\n const suffix = nameSuffix ?? instanceId;\n pending.push({\n // Providers require unique tool names: multi-instance capabilities\n // are disambiguated with an `_at_<instance>` suffix (docs/09).\n wire: { id: capabilityId, ...(suffix !== undefined ? { instanceId: suffix } : {}) },\n entry: {\n capabilityId,\n registrationId,\n ...(instanceId !== undefined ? { instanceId } : {}),\n surfaceVersion: snapshot.surfaceVersion,\n kind,\n },\n prefix,\n description,\n inputSchema,\n state,\n });\n };\n\n // One pre-pass instead of a filter() per component: at 300 mounted\n // components the quadratic version cost ~90k comparisons per projection.\n const typeCounts = new Map<string, number>();\n for (const component of snapshot.components) {\n typeCounts.set(component.type, (typeCounts.get(component.type) ?? 0) + 1);\n }\n\n for (const component of snapshot.components) {\n const multiInstance = (typeCounts.get(component.type) ?? 0) > 1;\n const instanceId = multiInstance ? component.instanceId : undefined;\n for (const obs of component.observations) {\n push(\n obs.capabilityId,\n \"observation\",\n component.registrationId,\n instanceId,\n describePrefix(\"view\", \"read\", \"never\"),\n obs.description,\n EMPTY_INPUT_SCHEMA,\n availabilityState(obs),\n );\n }\n for (const act of component.actions) {\n push(\n act.capabilityId,\n \"action\",\n component.registrationId,\n instanceId,\n describePrefix(\"view\", act.effect, act.confirmation),\n act.description,\n act.inputSchema,\n availabilityState(act),\n );\n }\n }\n const procedureCounts = new Map<string, number>();\n for (const proc of snapshot.procedures) {\n procedureCounts.set(proc.procedureId, (procedureCounts.get(proc.procedureId) ?? 0) + 1);\n }\n for (const proc of snapshot.procedures) {\n const needsSuffix = (procedureCounts.get(proc.procedureId) ?? 0) > 1;\n push(\n proc.procedureId,\n \"procedure\",\n proc.registrationId,\n undefined,\n describePrefix(\"domain\", proc.effect, proc.confirmation),\n // The stable half only: a contextual note travels in `state.note`.\n proc.description,\n proc.inputSchema,\n availabilityState(proc),\n needsSuffix\n ? (proc.context?.instanceId ?? proc.registrationId.replace(/[^A-Za-z0-9_-]/g, \"\"))\n : undefined,\n );\n }\n\n // Uniqueness is a catalog property, not a per-name one (AS-WIRE-006).\n const assignment = assignWireNames(pending.map((p) => p.wire));\n const tools = pending.map((p, i) => ({\n name: assignment.names[i]!,\n description: `${p.prefix} ${p.description}`,\n inputSchema: p.inputSchema,\n state: p.state,\n execute: (input: JsonValue, call: { toolCallId?: string }) =>\n invokeThroughSurface(p.entry, input, call.toolCallId),\n }));\n return { tools, wireNames: assignment.byName };\n }\n\n /**\n * A meta verb rejecting its own envelope, before the registry sees anything.\n * The error branch needs an identity: the caller's `capabilityId` when it\n * supplied one, else the verb's own meta id — mirroring `surface_discover`'s\n * ok result, and what hosts already fall back to for audit identity when a\n * meta call names no target.\n */\n function envelopeFailure(\n metaCapabilityId: string,\n capabilityId: JsonValue | undefined,\n error: AgentCapabilityErrorPayload,\n toolCallId: string | undefined,\n ): AgentInvocationResult {\n return {\n status: \"error\",\n invocationId: toolCallId ?? `inv_${randomBase62(12)}`,\n capabilityId:\n typeof capabilityId === \"string\" && capabilityId.length > 0\n ? capabilityId\n : metaCapabilityId,\n error,\n surfaceVersion: registry.getVersion(),\n };\n }\n\n function buildMetaTools(): AgentTool[] {\n const snapshotFor = (): AgentSurfaceSnapshot =>\n registry.snapshot({\n consumer: options.consumer,\n ...(options.scope ? { scope: options.scope } : {}),\n });\n // The three verbs are always callable; per-capability availability lives in\n // the `surface_discover` payload, where the model actually reads it.\n const verbs: Array<Omit<AgentTool, \"state\">> = [\n {\n name: \"surface_discover\",\n description:\n \"[meta] Discover the current agent surface: components, capabilities, procedures, availability, schemas.\",\n inputSchema: META_DISCOVER_SCHEMA,\n async execute(input, call) {\n const invalid = validateEnvelope(\"surface_discover\", META_DISCOVER_SCHEMA, input);\n if (invalid) {\n return envelopeFailure(\"meta:surface.discover\", undefined, invalid, call.toolCallId);\n }\n const requested = (input as { scope?: string[] } | undefined)?.scope;\n // D27: the configured scope is a floor; a model-supplied scope narrows.\n const effective = intersectScope(options.scope, requested);\n const snapshot = registry.snapshot({\n consumer: options.consumer,\n ...(effective.scope ? { scope: effective.scope } : {}),\n ...(options.budget ? { budget: options.budget } : {}),\n });\n // Disjoint request: honored as \"nothing\", never widened to the floor.\n // The refusal is marked for the same reason budget truncation is —\n // an unexplained blank payload reads as \"the surface is empty\", which\n // is the one conclusion the model must not draw here (AS-META-006).\n const projected: AgentSurfaceSnapshot = {\n ...snapshot,\n // A disjoint request is snapshotted unscoped, so any `truncated`\n // count belongs to a surface this payload does not contain. Keeping\n // it would claim a budget dropped what scope did.\n ...(effective.empty\n ? { components: [], procedures: [], truncated: undefined }\n : {}),\n ...(effective.rejected.length > 0\n ? { scopeRejected: { prefixes: effective.rejected } }\n : {}),\n };\n return {\n status: \"ok\",\n invocationId: `inv_${randomBase62(12)}`,\n capabilityId: \"meta:surface.discover\",\n output: JSON.parse(JSON.stringify(projected)) as JsonValue,\n surfaceVersion: snapshot.surfaceVersion,\n };\n },\n },\n {\n name: \"surface_read\",\n description: \"[meta] Invoke an observation by capabilityId and return its output.\",\n inputSchema: META_READ_SCHEMA,\n async execute(input, call) {\n const req = (input ?? {}) as { capabilityId: string; instanceId?: string };\n const invalid = validateEnvelope(\"surface_read\", META_READ_SCHEMA, input);\n if (invalid) {\n return envelopeFailure(\"meta:surface.read\", req.capabilityId, invalid, call.toolCallId);\n }\n const snapshot = snapshotFor();\n const { registrationId } = findTarget(snapshot, req.capabilityId, req.instanceId);\n return invokeThroughSurface(\n {\n capabilityId: req.capabilityId,\n // Unresolved → let the registry answer (AS-ADAPTER-003).\n ...(registrationId !== undefined ? { registrationId } : {}),\n ...(req.instanceId !== undefined ? { instanceId: req.instanceId } : {}),\n surfaceVersion: snapshot.surfaceVersion,\n kind: \"observation\",\n },\n undefined,\n call.toolCallId,\n );\n },\n },\n {\n name: \"surface_act\",\n description:\n \"[meta] Invoke an action or procedure by capabilityId. Echo the surfaceVersion you discovered so a surface that changed underneath a destructive plan is rejected rather than executed.\",\n inputSchema: META_ACT_SCHEMA,\n async execute(input, call) {\n const req = (input ?? {}) as {\n capabilityId: string;\n instanceId?: string;\n input?: JsonValue;\n invocationId?: string;\n confirmationId?: string;\n surfaceVersion?: string;\n };\n // `input` is exempt from the type check: the shim below owns it, and\n // recovering a stringified object beats rejecting it (AS-META-008).\n const invalid = validateEnvelope(\"surface_act\", META_ACT_SCHEMA, input, [\"input\"]);\n if (invalid) {\n return envelopeFailure(\"meta:surface.act\", req.capabilityId, invalid, call.toolCallId);\n }\n const snapshot = snapshotFor();\n const { registrationId, inputSchema } = findTarget(\n snapshot,\n req.capabilityId,\n req.instanceId,\n );\n let actInput = req.input;\n const parsed = parseStringifiedObject(actInput, inputSchema);\n if (parsed !== undefined) {\n actInput = parsed;\n // Never silent: a repaired call is indistinguishable from a\n // well-formed one downstream, which would hide exactly the\n // regression this shim exists to absorb.\n devWarn(\n `[agent-surface] surface_act got \\`input\\` as a JSON-encoded string for \"${req.capabilityId}\" and parsed it; the provider is not honoring the tool schema.`,\n );\n }\n // One execution path with direct mode: same resolution, same\n // staleness binding, same wait-mode confirmation retry (D26). A\n // direct tool carries the version of the catalog it was built from;\n // the equivalent here is the version the model discovered, so it is\n // taken from the caller when supplied (AS-META-004).\n return invokeThroughSurface(\n {\n capabilityId: req.capabilityId,\n ...(registrationId !== undefined ? { registrationId } : {}),\n ...(req.instanceId !== undefined ? { instanceId: req.instanceId } : {}),\n surfaceVersion: req.surfaceVersion ?? snapshot.surfaceVersion,\n kind: \"action\",\n },\n actInput,\n call.toolCallId,\n {\n ...(req.invocationId !== undefined ? { invocationId: req.invocationId } : {}),\n ...(req.confirmationId !== undefined ? { confirmationId: req.confirmationId } : {}),\n },\n );\n },\n },\n ];\n return verbs.map((verb) => ({ ...verb, state: { available: true } }));\n }\n\n function computeTools(): AgentTool[] {\n if (mode === \"meta\") {\n cachedTools ??= buildMetaTools();\n return cachedTools;\n }\n const version = registry.getVersion();\n if (cachedTools && cachedVersion === version) return cachedTools;\n const built = buildDirectTools();\n cachedTools = built.tools;\n cachedWireNames = built.wireNames;\n cachedVersion = version;\n return cachedTools;\n }\n\n /**\n * Includes `state`: the definitions are byte-identical across an\n * availability flip, so a host that re-renders its state block on\n * `subscribe` would otherwise never hear about it.\n */\n function signatureOf(tools: AgentTool[]): string {\n return JSON.stringify(\n tools.map((t) => [t.name, t.description, t.inputSchema, t.state]),\n );\n }\n\n const unsubscribe = registry.subscribe((event) => {\n if (disposed || event.type !== \"surface-changed\") return;\n cachedVersion = undefined;\n // Meta mode: the three-tool catalog is constant by construction, so\n // tools() can never differ and listeners are never called. Agents notice\n // surface changes by re-running surface_discover and comparing\n // surfaceVersion (docs/09 §meta-tools-mode).\n if (mode === \"meta\") return;\n const tools = computeTools();\n const signature = signatureOf(tools);\n if (signature === cachedSignature) return;\n cachedSignature = signature;\n for (const listener of [...listeners]) {\n try {\n listener(tools);\n } catch {\n /* listener isolation */\n }\n }\n });\n\n return {\n tools() {\n const tools = computeTools();\n cachedSignature ??= signatureOf(tools);\n return tools;\n },\n wireNameMap() {\n if (mode === \"meta\") return new Map();\n computeTools();\n return cachedWireNames;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n unsubscribe();\n listeners.clear();\n // Settle in-flight wait-mode waits deterministically (D26).\n for (const controller of [...pendingWaits]) controller.abort();\n pendingWaits.clear();\n },\n };\n}\n\n/**\n * D27 — the adapter-configured scope is a floor, not a default. A model-supplied\n * scope may narrow it (`[\"devices\"]` → `[\"devices.table\"]`), never widen it\n * (`[]` or `[\"admin\"]` cannot reach past the floor). Prefix lists intersect\n * pairwise: the more specific prefix wins when one extends the other, and a\n * pair that shares no prefix contributes nothing. An empty result means the\n * request was entirely outside the floor — reported as an empty surface rather\n * than silently falling back to the floor itself.\n *\n * `rejected` names the requested prefixes the floor admitted nothing for, in\n * request order. It carries the whole request when the two are disjoint, and a\n * subset when only part of the request was out of bounds; both are cases where\n * the model asked for something and got silence back (AS-META-006). A prefix\n * broader than the floor is *not* rejected: it contributed the floor's own\n * narrower prefix, which is the narrowing D27 describes.\n */\nfunction intersectScope(\n floor: string[] | undefined,\n requested: string[] | undefined,\n): { scope?: string[]; empty: boolean; rejected: string[] } {\n const hasFloor = floor !== undefined && floor.length > 0;\n // `[]` is \"everything\" to matchesScope — treat it as \"unspecified\", so an\n // empty array cannot be used to widen past the floor.\n if (requested === undefined || requested.length === 0) {\n return hasFloor ? { scope: floor, empty: false, rejected: [] } : { empty: false, rejected: [] };\n }\n if (!hasFloor) return { scope: requested, empty: false, rejected: [] };\n const out = new Set<string>();\n const rejected: string[] = [];\n for (const r of requested) {\n let admitted = false;\n for (const f of floor) {\n if (r === f || r.startsWith(`${f}.`)) {\n out.add(r);\n admitted = true;\n } else if (f.startsWith(`${r}.`)) {\n out.add(f);\n admitted = true;\n }\n }\n // Deduped: a repeated prefix is one refusal, not one per occurrence.\n if (!admitted && !rejected.includes(r)) rejected.push(r);\n }\n return out.size > 0\n ? { scope: [...out], empty: false, rejected }\n : { empty: true, rejected };\n}\n\ninterface ResolvedTarget {\n /**\n * Omitted unless the pair resolves to exactly one live registration — see\n * {@link CatalogEntry.registrationId} for why a placeholder is worse.\n */\n registrationId?: string;\n /**\n * The target's declared agent-facing input schema, under the same\n * one-match condition. Read only to decide whether a stringified `input`\n * may be repaired; the registry remains the validator.\n */\n inputSchema?: JsonSchema;\n}\n\nfunction findTarget(\n snapshot: AgentSurfaceSnapshot,\n capabilityId: string,\n instanceId: string | undefined,\n): ResolvedTarget {\n const matches: ResolvedTarget[] = [];\n for (const component of snapshot.components) {\n if (instanceId !== undefined && component.instanceId !== instanceId) continue;\n const all: Array<AgentObservationDescriptor | AgentActionDescriptor> = [\n ...component.observations,\n ...component.actions,\n ];\n const hit = all.find((c) => c.capabilityId === capabilityId);\n // Observations carry no input schema, so the field stays absent for them.\n if (hit) {\n matches.push({\n registrationId: component.registrationId,\n ...(\"inputSchema\" in hit ? { inputSchema: hit.inputSchema } : {}),\n });\n }\n }\n for (const proc of snapshot.procedures as AgentProcedureDescriptor[]) {\n if (proc.procedureId === capabilityId) {\n matches.push({ registrationId: proc.registrationId, inputSchema: proc.inputSchema });\n }\n }\n return matches.length === 1 ? matches[0]! : {};\n}\n\n/* ─────────────────────── meta-verb envelope checking ───────────────────────\n * The three verbs declare `required` and `additionalProperties: false`, and\n * nothing enforced either: a provider that compiles the tool schema into a\n * sampling grammar makes most of this unreachable, and one that does not hands\n * the envelope through verbatim. The consequences were asymmetric — a missing\n * `capabilityId` reached `parseCapabilityId` as `undefined` and came back as\n * EXECUTION_FAILED {retry:\"no\"}, reporting a caller error as an internal defect\n * and telling the model to stop rather than fix its call. Checked against each\n * verb's OWN schema, so the declaration and the check cannot drift.\n */\n\n/** A type alias, not an interface: `details` is a `JsonValue` bag, and only\n * the alias carries the implicit index signature that makes it assignable. */\ntype EnvelopeIssue = { path: string; message: string };\n\nfunction validateEnvelope(\n verb: string,\n schema: JsonSchema,\n raw: JsonValue | undefined,\n /** Properties this must not type-check; their owner handles the value. */\n exempt: readonly string[] = [],\n): AgentCapabilityErrorPayload | undefined {\n // `null` is how some providers spell \"no arguments\" — read as `{}`, so a\n // no-argument verb keeps working and a required key is still reported as\n // missing rather than as a malformed envelope.\n if (raw !== undefined && raw !== null && (typeof raw !== \"object\" || Array.isArray(raw))) {\n return envelopeError(verb, [\n { path: \"\", message: `\\`${verb}\\` takes a JSON object of arguments.` },\n ]);\n }\n const properties = (schema.properties ?? {}) as Record<string, JsonSchema>;\n const known = Object.keys(properties);\n const required = (schema.required ?? []) as string[];\n const req = (raw ?? {}) as Record<string, JsonValue | undefined>;\n const issues: EnvelopeIssue[] = [];\n\n for (const key of required) {\n if (req[key] === undefined) issues.push({ path: key, message: `\\`${key}\\` is required.` });\n }\n for (const [key, value] of Object.entries(req)) {\n if (value === undefined) continue;\n if (!known.includes(key)) {\n if (schema.additionalProperties === false) {\n issues.push({\n path: key,\n // The high-value half is the pointer back at `input`: it turns the\n // dead end of a hoisted capability argument into a one-retry\n // recovery. A verb without an `input` has nowhere to point.\n message: `Unknown top-level property. \\`${verb}\\` accepts only ${known.join(\", \")}.${\n known.includes(\"input\")\n ? \" An argument the capability declares belongs inside `input`.\"\n : \"\"\n }`,\n });\n }\n continue;\n }\n if (exempt.includes(key)) continue;\n const issue = checkDeclaredType(key, properties[key]!, value);\n if (issue) issues.push(issue);\n }\n return issues.length > 0 ? envelopeError(verb, issues) : undefined;\n}\n\nfunction checkDeclaredType(\n key: string,\n property: JsonSchema,\n value: JsonValue,\n): EnvelopeIssue | undefined {\n if (property.type === \"string\" && (typeof value !== \"string\" || value.length === 0)) {\n return { path: key, message: `\\`${key}\\` must be a non-empty string.` };\n }\n if (property.type === \"array\") {\n if (!Array.isArray(value)) return { path: key, message: `\\`${key}\\` must be an array.` };\n const items = property.items as JsonSchema | undefined;\n if (items?.type === \"string\" && !value.every((item) => typeof item === \"string\")) {\n return { path: key, message: `\\`${key}\\` must be an array of strings.` };\n }\n }\n return undefined;\n}\n\nfunction envelopeError(verb: string, issues: EnvelopeIssue[]): AgentCapabilityErrorPayload {\n return {\n code: \"INVALID_INPUT\",\n // Names the envelope, not the capability: pointing the model at the\n // capability's schema when the wrapper is what is wrong sends it to fix\n // something that is already correct.\n message: `The \\`${verb}\\` call is malformed — the fault is in the tool's own arguments, not the capability's input. Fix the listed issues and retry.`,\n retry: \"with-changes\",\n details: { issues },\n };\n}\n\n/**\n * Recovers the one malformation an untyped `input` property invited: the\n * arguments arriving as a JSON-encoded string, the shape the dominant\n * function-calling convention (`function_call.arguments`) carries nested call\n * arguments in. Typing the property fixes providers that honor the schema\n * during generation; this covers the ones that do not.\n *\n * Deliberately narrow: only when the target's own schema declares an object,\n * and only when the string parses to a plain object. A capability that\n * genuinely declares a string input must never have its argument parsed out\n * from under it. Anything else passes through untouched, to the registry's\n * validator, which owns the verdict.\n */\nfunction parseStringifiedObject(\n value: JsonValue | undefined,\n targetSchema: JsonSchema | undefined,\n): JsonValue | undefined {\n if (typeof value !== \"string\" || targetSchema?.type !== \"object\") return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return parsed as JsonValue;\n}\n"],"mappings":";AAmFO,IAAM,iBAAqC;AAAA,EAChD,yBAAyB;AAAA,EACzB,0BAA0B;AAAA,EAC1B,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,sBAAsB;AAAA,EACtB,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,sCAAsC;AAAA,EACtC,gCAAgC;AAAA,EAChC,kCAAkC;AAAA,EAClC,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,yBAAyB;AAC3B;;;ACnGO,IAAM,+BAA+B;AAAA,EAC1C;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CAAiC;AAAA,EACxE;AACA,MAAI,SAAS,SAAS,SAAS;AAC7B,QAAI,CAAC,MAAM,QAAQ,KAAK,EAAG,QAAO,EAAE,MAAM,KAAK,SAAS,KAAK,GAAG,uBAAuB;AACvF,UAAM,QAAQ,SAAS;AACvB,QAAI,OAAO,SAAS,YAAY,CAAC,MAAM,MAAM,CAAC,SAAS,OAAO,SAAS,QAAQ,GAAG;AAChF,aAAO,EAAE,MAAM,KAAK,SAAS,KAAK,GAAG,kCAAkC;AAAA,IACzE;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,cAAc,MAAc,QAAsD;AACzF,SAAO;AAAA,IACL,MAAM;AAAA;AAAA;AAAA;AAAA,IAIN,SAAS,SAAS,IAAI;AAAA,IACtB,OAAO;AAAA,IACP,SAAS,EAAE,OAAO;AAAA,EACpB;AACF;AAeA,SAAS,uBACP,OACA,cACuB;AACvB,MAAI,OAAO,UAAU,YAAY,cAAc,SAAS,SAAU,QAAO;AACzE,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,KAAK;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,EAAG,QAAO;AACnF,SAAO;AACT;","names":["byName","record","DEFAULT_CONSUMER","environment"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/schema.ts","../src/definition.ts","../src/audit.ts","../src/events.ts","../src/confirmation.ts","../src/invoke.ts","../src/registry.ts","../src/toolset.ts"],"sourcesContent":["/** JSON value constraint: every agent-crossing payload MUST be a JsonValue. */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/** A JSON Schema document restricted to the supported subset (docs/03 D19). */\nexport type JsonSchema = Record<string, unknown>;\n\nexport type AgentEnvironment = \"development\" | \"production\" | \"test\";\n\nexport type AgentEffect =\n | \"read\"\n | \"local-state\"\n | \"navigation\"\n | \"server-query\"\n | \"server-mutation\"\n | \"external-side-effect\"\n | \"destructive\";\n\nexport type AgentProcedureEffect =\n | \"server-query\"\n | \"server-mutation\"\n | \"external-side-effect\"\n | \"destructive\";\n\nexport interface AgentConsumer {\n id: string;\n kind: \"embedded\" | \"webmcp\" | \"mcp-bridge\" | \"test\" | \"other\";\n /** Free-form grant strings interpreted by host policies. */\n grants?: string[];\n}\n\nexport interface AgentRouteInfo {\n path: string;\n params?: Record<string, string>;\n}\n\n/**\n * Concurrency group for an action or procedure reference (D25). Not\n * model-visible: it is runtime behavior, not planning information.\n *\n * - `instance` (default) — every action on the registration shares one FIFO\n * queue. Safest: two actions on the same component can never interleave.\n * - `capability` — one queue per capability, so a slow export does not block\n * closing a drawer.\n * - `key` — one queue per author-chosen key, for actions that contend over\n * the same resource across capabilities.\n * - `parallel` — bounded parallelism; `max` is required and must be ≥ 1.\n *\n * `queueDepth` overrides `limits.actionQueueDepth` for this group only.\n */\nexport type AgentConcurrency =\n | { mode: \"instance\"; queueDepth?: number }\n | { mode: \"capability\"; queueDepth?: number }\n | { mode: \"key\"; key: string; queueDepth?: number }\n | { mode: \"parallel\"; max: number; queueDepth?: number };\n\nexport interface AgentSurfaceLimits {\n maxComponentDescription: number; // 500 chars\n maxCapabilityDescription: number; // 300 chars\n maxMetaBytes: number; // 2048\n maxOutputBytes: number; // 32_768\n maxSchemaBytes: number; // 16_384\n maxSchemaDepth: number; // 8\n observationTimeoutMs: number; // 5_000\n actionTimeoutMs: number; // 10_000\n procedureTimeoutMs: number; // 30_000\n actionQueueDepth: number; // 2\n maxConcurrentObservationsPerConsumer: number; // 8 (D24)\n maxConcurrentObservationsTotal: number; // 32 (D24)\n maxQueuedObservationsPerConsumer: number; // 8 (D24)\n dedupeCacheSize: number; // 200 entries\n dedupeCacheTtlMs: number; // 600_000\n tombstoneSize: number; // 100 entries\n tombstoneTtlMs: number; // 300_000\n confirmationTtlMs: number;\n maxPendingConfirmations: number; // 32 (D24; overflow fails RATE_LIMITED, no record) // 120_000\n}\n\nexport const DEFAULT_LIMITS: AgentSurfaceLimits = {\n maxComponentDescription: 500,\n maxCapabilityDescription: 300,\n maxMetaBytes: 2048,\n maxOutputBytes: 32_768,\n maxSchemaBytes: 16_384,\n maxSchemaDepth: 8,\n observationTimeoutMs: 5_000,\n actionTimeoutMs: 10_000,\n procedureTimeoutMs: 30_000,\n actionQueueDepth: 2,\n maxConcurrentObservationsPerConsumer: 8,\n maxConcurrentObservationsTotal: 32,\n maxQueuedObservationsPerConsumer: 8,\n dedupeCacheSize: 200,\n dedupeCacheTtlMs: 600_000,\n tombstoneSize: 100,\n tombstoneTtlMs: 300_000,\n confirmationTtlMs: 120_000,\n maxPendingConfirmations: 32,\n};\n\nexport type Unsubscribe = () => void;\n","import type { JsonSchema, JsonValue } from \"./types.js\";\nimport { jsonDeepEqual, byteLength } from \"./utils.js\";\n\nexport interface AgentSchemaIssue {\n path: string;\n message: string;\n}\n\n/** Thrown by AgentSchema.parse on invalid input; carries safe, structured issues. */\nexport class AgentSchemaError extends Error {\n readonly issues: AgentSchemaIssue[];\n constructor(issues: AgentSchemaIssue[]) {\n super(issues.map((i) => `${i.path || \"$\"}: ${i.message}`).join(\"; \") || \"Invalid value\");\n this.name = \"AgentSchemaError\";\n this.issues = issues;\n }\n}\n\nexport interface AgentSchema<T> {\n /** Agent-visible JSON Schema (draft 2020-12, restricted subset). */\n readonly jsonSchema: JsonSchema;\n /**\n * Validates and returns a typed value. MUST throw `AgentSchemaError`\n * (with a safe, structured message) on invalid input.\n */\n parse(value: unknown): T;\n}\n\n/** Minimal Standard Schema mirror (https://standardschema.dev). */\nexport interface StandardSchemaV1<I = unknown, O = I> {\n readonly \"~standard\": {\n readonly version: 1;\n readonly vendor: string;\n validate(\n value: unknown,\n ):\n | { value: O; issues?: undefined }\n | { issues: ReadonlyArray<{ message: string; path?: ReadonlyArray<PropertyKey | { key: PropertyKey }> }> }\n | Promise<unknown>;\n readonly types?: { readonly input: I; readonly output: O } | undefined;\n };\n}\n\n/**\n * Wraps any Standard Schema (Zod ≥3.24, Valibot, ArkType) as an AgentSchema.\n * The JSON Schema MUST be supplied explicitly — core does not depend on a\n * converter (docs/03, D20).\n */\nexport function fromStandardSchema<T>(\n schema: StandardSchemaV1<unknown, T>,\n options: { jsonSchema: JsonSchema },\n): AgentSchema<T> {\n return {\n jsonSchema: options.jsonSchema,\n parse(value: unknown): T {\n const result = schema[\"~standard\"].validate(value);\n if (result instanceof Promise) {\n throw new AgentSchemaError([\n { path: \"\", message: \"Async schema validation is not supported in v0.1\" },\n ]);\n }\n if (result.issues) {\n throw new AgentSchemaError(\n result.issues.map((issue) => ({\n path: (issue.path ?? [])\n .map((p) => String(typeof p === \"object\" && p !== null && \"key\" in p ? p.key : p))\n .join(\".\"),\n message: issue.message,\n })),\n );\n }\n return (result as { value: T }).value;\n },\n };\n}\n\n/**\n * Builds an AgentSchema from a raw JSON Schema, validated by the built-in\n * minimal structural validator covering exactly the supported subset.\n */\nexport function fromJsonSchema<T = JsonValue>(schema: JsonSchema): AgentSchema<T> {\n return {\n jsonSchema: schema,\n parse(value: unknown): T {\n const issues = validateValueAgainstSchema(value, schema, schema, \"\");\n if (issues.length > 0) throw new AgentSchemaError(issues);\n return value as T;\n },\n };\n}\n\n/** Convenience for actions with no input / observations of constant shape. */\nexport const emptyObjectSchema: AgentSchema<Record<string, never>> = fromJsonSchema({\n type: \"object\",\n properties: {},\n additionalProperties: false,\n});\n\n/* ─────────────────── D19: supported JSON Schema subset ─────────────────── */\n\nconst ALLOWED_KEYWORDS = new Set([\n \"type\",\n \"enum\",\n \"const\",\n // objects\n \"properties\",\n \"required\",\n \"additionalProperties\",\n // arrays\n \"items\",\n \"minItems\",\n \"maxItems\",\n \"uniqueItems\",\n // strings\n \"minLength\",\n \"maxLength\",\n \"pattern\",\n \"format\",\n // numbers\n \"minimum\",\n \"maximum\",\n \"exclusiveMinimum\",\n \"exclusiveMaximum\",\n \"multipleOf\",\n // unions\n \"anyOf\",\n // annotations\n \"description\",\n \"default\",\n \"examples\",\n \"title\",\n \"deprecated\",\n // refs\n \"$defs\",\n \"$ref\",\n // tolerated (converter noise), ignored at validation time\n \"$schema\",\n \"$id\",\n]);\n\nconst REJECTED_KEYWORDS = new Set([\n \"oneOf\",\n \"allOf\",\n \"not\",\n \"if\",\n \"then\",\n \"else\",\n \"patternProperties\",\n \"dependentRequired\",\n \"dependentSchemas\",\n \"unevaluatedProperties\",\n \"unevaluatedItems\",\n \"prefixItems\",\n \"contains\",\n \"propertyNames\",\n]);\n\nconst ALLOWED_TYPES = new Set([\n \"object\",\n \"array\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"null\",\n]);\n\nconst ALLOWED_FORMATS = new Set([\"date-time\", \"date\", \"uuid\", \"email\", \"uri\"]);\n\nexport interface SchemaSubsetResult {\n ok: boolean;\n reason?: string;\n}\n\n/**\n * Validates that a JSON Schema document stays inside the D19 subset.\n * Anything outside MUST be rejected at registration with INVALID_DEFINITION /\n * UNSUPPORTED_SCHEMA (docs/03, docs/07).\n */\nexport function validateJsonSchemaDocument(\n schema: JsonSchema,\n limits: { maxSchemaBytes: number; maxSchemaDepth: number },\n): SchemaSubsetResult {\n const size = byteLength(schema);\n if (size > limits.maxSchemaBytes) {\n return { ok: false, reason: `schema serializes to ${size} bytes (max ${limits.maxSchemaBytes})` };\n }\n return walkSchemaDocument(schema, \"\", 0, limits.maxSchemaDepth);\n}\n\nfunction walkSchemaDocument(\n node: unknown,\n path: string,\n depth: number,\n maxDepth: number,\n): SchemaSubsetResult {\n if (depth > maxDepth) {\n return { ok: false, reason: `schema nesting exceeds depth ${maxDepth} at ${path || \"$\"}` };\n }\n if (typeof node === \"boolean\") {\n // Boolean schemas only allowed as additionalProperties (handled by caller).\n return { ok: false, reason: `boolean schema not supported at ${path || \"$\"}` };\n }\n if (typeof node !== \"object\" || node === null || Array.isArray(node)) {\n return { ok: false, reason: `schema must be an object at ${path || \"$\"}` };\n }\n const obj = node as Record<string, unknown>;\n for (const key of Object.keys(obj)) {\n if (REJECTED_KEYWORDS.has(key) || !ALLOWED_KEYWORDS.has(key)) {\n return { ok: false, reason: `unsupported keyword \"${key}\" at ${path || \"$\"}` };\n }\n }\n if (\"$ref\" in obj) {\n const ref = obj.$ref;\n if (typeof ref !== \"string\" || !ref.startsWith(\"#/$defs/\")) {\n return { ok: false, reason: `only internal \"#/$defs/...\" refs are supported at ${path || \"$\"}` };\n }\n }\n if (\"type\" in obj) {\n const t = obj.type;\n const types = Array.isArray(t) ? t : [t];\n for (const one of types) {\n if (typeof one !== \"string\" || !ALLOWED_TYPES.has(one)) {\n return { ok: false, reason: `unsupported type \"${String(one)}\" at ${path || \"$\"}` };\n }\n }\n }\n if (\"format\" in obj) {\n const f = obj.format;\n if (typeof f !== \"string\" || !ALLOWED_FORMATS.has(f)) {\n return { ok: false, reason: `unsupported format \"${String(obj.format)}\" at ${path || \"$\"}` };\n }\n }\n if (\"additionalProperties\" in obj && typeof obj.additionalProperties !== \"boolean\") {\n return {\n ok: false,\n reason: `additionalProperties must be a boolean at ${path || \"$\"}`,\n };\n }\n if (\"items\" in obj) {\n if (Array.isArray(obj.items)) {\n return { ok: false, reason: `tuple \"items\" arrays are not supported at ${path || \"$\"}` };\n }\n const r = walkSchemaDocument(obj.items, `${path}.items`, depth + 1, maxDepth);\n if (!r.ok) return r;\n }\n if (\"properties\" in obj) {\n const props = obj.properties;\n if (typeof props !== \"object\" || props === null || Array.isArray(props)) {\n return { ok: false, reason: `properties must be an object at ${path || \"$\"}` };\n }\n for (const [name, sub] of Object.entries(props)) {\n const r = walkSchemaDocument(sub, `${path}.properties.${name}`, depth + 1, maxDepth);\n if (!r.ok) return r;\n }\n }\n if (\"anyOf\" in obj) {\n if (!Array.isArray(obj.anyOf) || obj.anyOf.length === 0) {\n return { ok: false, reason: `anyOf must be a non-empty array at ${path || \"$\"}` };\n }\n for (let i = 0; i < obj.anyOf.length; i++) {\n const r = walkSchemaDocument(obj.anyOf[i], `${path}.anyOf[${i}]`, depth + 1, maxDepth);\n if (!r.ok) return r;\n }\n }\n if (\"$defs\" in obj) {\n const defs = obj.$defs;\n if (typeof defs !== \"object\" || defs === null || Array.isArray(defs)) {\n return { ok: false, reason: `$defs must be an object at ${path || \"$\"}` };\n }\n for (const [name, sub] of Object.entries(defs)) {\n const r = walkSchemaDocument(sub, `${path}.$defs.${name}`, depth + 1, maxDepth);\n if (!r.ok) return r;\n }\n }\n return { ok: true };\n}\n\n/* ─────────────── built-in structural value validator ─────────────── */\n\nconst FORMAT_VALIDATORS: Record<string, (s: string) => boolean> = {\n \"date-time\": (s) => /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/.test(s),\n date: (s) => /^\\d{4}-\\d{2}-\\d{2}$/.test(s),\n uuid: (s) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s),\n email: (s) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s),\n uri: (s) => /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(s),\n};\n\nfunction typeOfValue(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n const t = typeof value;\n if (t === \"number\") return \"number\";\n return t;\n}\n\nfunction matchesType(value: unknown, type: string): boolean {\n switch (type) {\n case \"object\":\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n case \"array\":\n return Array.isArray(value);\n case \"string\":\n return typeof value === \"string\";\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"integer\":\n return typeof value === \"number\" && Number.isInteger(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"null\":\n return value === null;\n default:\n return false;\n }\n}\n\n/**\n * Validates a value against a subset schema. Returns issues (empty = valid).\n * JSON Schema semantics: `default` is annotation-only and never applied.\n */\nexport function validateValueAgainstSchema(\n value: unknown,\n schema: unknown,\n root: JsonSchema,\n path: string,\n): AgentSchemaIssue[] {\n if (typeof schema !== \"object\" || schema === null) return [];\n let node = schema as Record<string, unknown>;\n\n if (typeof node.$ref === \"string\") {\n const ref = node.$ref;\n const defName = ref.slice(\"#/$defs/\".length);\n const defs = root.$defs as Record<string, unknown> | undefined;\n const resolved = defs?.[defName];\n if (typeof resolved !== \"object\" || resolved === null) {\n return [{ path, message: `unresolvable $ref \"${ref}\"` }];\n }\n node = resolved as Record<string, unknown>;\n }\n\n const issues: AgentSchemaIssue[] = [];\n\n if (\"const\" in node) {\n if (!jsonDeepEqual(value as JsonValue, node.const as JsonValue)) {\n issues.push({ path, message: `must equal the constant ${JSON.stringify(node.const)}` });\n return issues;\n }\n }\n\n if (Array.isArray(node.enum)) {\n const ok = node.enum.some((candidate) => jsonDeepEqual(value as JsonValue, candidate as JsonValue));\n if (!ok) {\n issues.push({ path, message: `must be one of ${JSON.stringify(node.enum)}` });\n return issues;\n }\n }\n\n if (Array.isArray(node.anyOf)) {\n const anyOk = node.anyOf.some(\n (branch) => validateValueAgainstSchema(value, branch, root, path).length === 0,\n );\n if (!anyOk) {\n issues.push({ path, message: \"does not match any allowed variant\" });\n return issues;\n }\n }\n\n if (\"type\" in node) {\n const types = Array.isArray(node.type) ? node.type : [node.type];\n const ok = types.some((t) => typeof t === \"string\" && matchesType(value, t));\n if (!ok) {\n issues.push({\n path,\n message: `expected ${types.join(\" | \")}, got ${typeOfValue(value)}`,\n });\n return issues;\n }\n }\n\n if (typeof value === \"string\") {\n if (typeof node.minLength === \"number\" && value.length < node.minLength) {\n issues.push({ path, message: `must be at least ${node.minLength} characters` });\n }\n if (typeof node.maxLength === \"number\" && value.length > node.maxLength) {\n issues.push({ path, message: `must be at most ${node.maxLength} characters` });\n }\n if (typeof node.pattern === \"string\") {\n let re: RegExp | undefined;\n try {\n re = new RegExp(node.pattern);\n } catch {\n // invalid pattern is a schema-document defect; ignore at value time\n }\n if (re && !re.test(value)) {\n issues.push({ path, message: `must match pattern ${node.pattern}` });\n }\n }\n if (typeof node.format === \"string\") {\n const check = FORMAT_VALIDATORS[node.format];\n if (check && !check(value)) {\n issues.push({ path, message: `must be a valid ${node.format}` });\n }\n }\n }\n\n if (typeof value === \"number\") {\n if (typeof node.minimum === \"number\" && value < node.minimum) {\n issues.push({ path, message: `must be >= ${node.minimum}` });\n }\n if (typeof node.maximum === \"number\" && value > node.maximum) {\n issues.push({ path, message: `must be <= ${node.maximum}` });\n }\n if (typeof node.exclusiveMinimum === \"number\" && value <= node.exclusiveMinimum) {\n issues.push({ path, message: `must be > ${node.exclusiveMinimum}` });\n }\n if (typeof node.exclusiveMaximum === \"number\" && value >= node.exclusiveMaximum) {\n issues.push({ path, message: `must be < ${node.exclusiveMaximum}` });\n }\n if (typeof node.multipleOf === \"number\" && node.multipleOf > 0) {\n const quotient = value / node.multipleOf;\n if (Math.abs(quotient - Math.round(quotient)) > 1e-9) {\n issues.push({ path, message: `must be a multiple of ${node.multipleOf}` });\n }\n }\n }\n\n if (Array.isArray(value)) {\n if (typeof node.minItems === \"number\" && value.length < node.minItems) {\n issues.push({ path, message: `must have at least ${node.minItems} items` });\n }\n if (typeof node.maxItems === \"number\" && value.length > node.maxItems) {\n issues.push({ path, message: `must have at most ${node.maxItems} items` });\n }\n if (node.uniqueItems === true) {\n const seen = new Set<string>();\n for (const item of value) {\n const key = JSON.stringify(item);\n if (seen.has(key)) {\n issues.push({ path, message: \"items must be unique\" });\n break;\n }\n seen.add(key);\n }\n }\n if (node.items !== undefined) {\n value.forEach((item, i) => {\n issues.push(...validateValueAgainstSchema(item, node.items, root, `${path}[${i}]`));\n });\n }\n }\n\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n const record = value as Record<string, unknown>;\n const props = (node.properties ?? {}) as Record<string, unknown>;\n if (Array.isArray(node.required)) {\n for (const req of node.required) {\n if (typeof req === \"string\" && record[req] === undefined) {\n issues.push({ path: path ? `${path}.${req}` : req, message: \"is required\" });\n }\n }\n }\n for (const [name, sub] of Object.entries(props)) {\n if (record[name] !== undefined) {\n issues.push(\n ...validateValueAgainstSchema(record[name], sub, root, path ? `${path}.${name}` : name),\n );\n }\n }\n if (node.additionalProperties === false) {\n for (const key of Object.keys(record)) {\n if (!(key in props)) {\n issues.push({\n path: path ? `${path}.${key}` : key,\n message: \"is not an allowed property\",\n });\n }\n }\n }\n }\n\n return issues;\n}\n","import type {\n AgentConcurrency,\n AgentConsumer,\n AgentProcedureEffect,\n AgentSurfaceLimits,\n JsonSchema,\n JsonValue,\n} from \"./types.js\";\nimport type { AgentSchema } from \"./schema.js\";\nimport { validateJsonSchemaDocument } from \"./schema.js\";\nimport type { AgentPolicy } from \"./policy.js\";\nimport { AgentSurfaceDefinitionError } from \"./errors.js\";\nimport {\n isValidCapabilityName,\n isValidComponentType,\n isValidInstanceId,\n formatViewCapabilityId,\n MAX_ID_LENGTH,\n} from \"./ids.js\";\nimport { byteLength, isJsonValue } from \"./utils.js\";\n\n/* ───────────────────────── handler contexts ───────────────────────── */\n\nexport interface AgentReadContext {\n capabilityId: string;\n registrationId: string;\n consumer: AgentConsumer;\n /** Host context (user, tenant, env…) from RegistryOptions.context(). */\n host: Readonly<Record<string, unknown>>;\n}\n\nexport interface AgentActionContext extends AgentReadContext {\n invocationId: string;\n /** Aborted on timeout, external cancellation, or unmount. Cooperative. */\n signal: AbortSignal;\n /** Present iff this invocation carries approved confirmation evidence. */\n confirmation?: { id: string; approvedAt: string };\n}\n\nexport interface PreconditionFailure {\n message: string; // agent-safe\n details?: Record<string, JsonValue>; // agent-safe\n}\n\n/* ───────────────────────── capability definitions ───────────────────────── */\n\nexport interface AgentObservationDefinition<TOut extends JsonValue> {\n /** Agent-visible description, ≤ 300 chars. */\n description: string;\n output: AgentSchema<TOut>;\n /**\n * Reads current semantic state. MUST be side-effect free. SHOULD be\n * synchronous; MAY return a promise (subject to observation timeout).\n */\n read(ctx: AgentReadContext): TOut | Promise<TOut>;\n /** Availability predicate, re-evaluated at snapshot and at invocation. */\n when?: () => boolean;\n unavailableReason?: string | (() => string);\n policies?: AgentPolicy[];\n meta?: Record<string, JsonValue>;\n timeoutMs?: number;\n}\n\nexport interface AgentActionDefinition<\n TIn extends JsonValue,\n TOut extends JsonValue | void = void,\n> {\n description: string;\n input: AgentSchema<TIn>;\n output?: AgentSchema<Exclude<TOut, void>>;\n /** View actions MUST be \"local-state\" | \"navigation\" (plane rule, docs/01). */\n effect: \"local-state\" | \"navigation\";\n idempotent?: boolean; // default false\n reversible?: boolean; // default true\n confirmation?: \"never\" | \"optional\" | \"required\"; // default \"never\"\n audit?: \"none\" | \"metadata\" | \"full\"; // default \"metadata\"\n when?: () => boolean;\n unavailableReason?: string | (() => string);\n /**\n * Input-aware validation beyond the schema. Return void to pass; return\n * (or throw) a PreconditionFailure to fail with PRECONDITION_FAILED.\n */\n precondition?(input: TIn, ctx: AgentReadContext): void | PreconditionFailure;\n /**\n * TOut is inferred from `output` only (NoInfer): the schema is the source\n * of truth and the handler's return is checked against it.\n */\n execute(input: TIn, ctx: AgentActionContext): NoInfer<TOut> | Promise<NoInfer<TOut>>;\n policies?: AgentPolicy[];\n meta?: Record<string, JsonValue>;\n timeoutMs?: number;\n /** Concurrency group (D25). Default `{mode:\"instance\"}` — serialize with\n * every other action on this component instance. */\n concurrency?: AgentConcurrency;\n}\n\n/** Identity helpers that fix generics for record-literal authoring. */\nexport function observation<TOut extends JsonValue>(\n def: AgentObservationDefinition<TOut>,\n): AgentObservationDefinition<TOut> {\n return def;\n}\nexport function action<TIn extends JsonValue, TOut extends JsonValue | void = void>(\n def: AgentActionDefinition<TIn, TOut>,\n): AgentActionDefinition<TIn, TOut> {\n return def;\n}\nexport function defineAgentComponent(def: AgentComponentDefinition): AgentComponentDefinition {\n return def;\n}\n\n/* ───────────────────────── procedure references ─────────────────────────\n * Bindings are constructed by @agent-surface/orpc (docs/05); core only\n * consumes this structural shape (zero-dependency rule, docs/02).\n */\n\nexport interface ProcedureCallInfo {\n invocationId: string;\n consumer: AgentConsumer;\n signal: AbortSignal;\n confirmation?: { id: string; approvedAt: string };\n}\n\nexport interface AgentProcedureExecutor {\n execute(req: {\n path: string;\n input: JsonValue; // effective, validated input\n info: ProcedureCallInfo;\n }): Promise<JsonValue>;\n /** Known exposed procedure paths (manifest), used for suffix-collision lint. */\n paths?: ReadonlyArray<string>;\n}\n\nexport interface AgentProcedureRefDescriptor {\n readonly id: string; // \"domain:devices.disable\"\n readonly path: string; // \"devices.disable\"\n readonly description: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly effect: AgentProcedureEffect;\n /** Server-declared flag the client must respect (approval required). */\n readonly requiresApproval?: boolean;\n}\n\nexport interface AgentProcedureBindingRuntimeConfig {\n when?: () => boolean;\n unavailableReason?: string | (() => string);\n /** UI-derived inputs, evaluated at EXECUTION time (docs/05 rule 4). */\n bind?: () => Record<string, JsonValue>;\n overridableFields?: ReadonlyArray<string>;\n /** Escalate (never lower) the manifest's confirmation requirement. */\n confirmation?: \"optional\" | \"required\";\n policies?: AgentPolicy[];\n /** Contextual description appended to the manifest description. */\n describe?: () => string;\n meta?: Record<string, JsonValue>;\n /** Concurrency group (D25). Default: one group per procedure identity per\n * referencing registration — conservative, and it never couples a domain\n * call to unrelated view actions. */\n concurrency?: AgentConcurrency;\n}\n\nexport interface AgentProcedureBinding<TIn extends object = object, TOut = unknown> {\n readonly kind: \"procedure-binding\";\n readonly ref: AgentProcedureRefDescriptor;\n readonly config: AgentProcedureBindingRuntimeConfig;\n /** Keys produced by bind(), captured at binding creation. */\n readonly boundKeys: ReadonlyArray<string>;\n /** Bound keys the agent may NOT supply (bound minus overridable). */\n readonly lockedKeys: ReadonlyArray<string>;\n /** Agent-facing (reduced) input schema per D7 rule 1. */\n readonly reducedInputSchema: JsonSchema;\n /** Optional link to the owning view component. */\n contextLink?: { type: string; instanceId: string };\n /** Phantom fields carrying the generics (never read at runtime). */\n readonly __types?: { input: TIn; output: TOut };\n}\n\n/* ───────────────────────── component definition ───────────────────────── */\n\nexport interface AgentComponentDefinition {\n /** Component type, e.g. \"devices.table\". MUST match the id grammar. */\n type: string;\n /** Distinguishes simultaneous mounts. Defaults to \"default\". Data-derived. */\n instanceId?: string;\n /** Agent-visible description, ≤ 500 chars. Required, non-empty. */\n description: string;\n /** Optional containment link for hierarchy-aware consumers. */\n parent?: { type: string; instanceId?: string };\n /** Agent-visible metadata. JsonValue, ≤ 2 kB serialized. */\n meta?: Record<string, JsonValue>;\n /** Internal metadata for policies/audit sinks. NEVER serialized. */\n internal?: Record<string, unknown>;\n /** Policies applied to every capability of this component. */\n policies?: AgentPolicy[];\n /** Registrant trust label; default \"first-party\". */\n origin?: string;\n /** Snapshot ordering/budget priority; higher survives budgets longer. */\n priority?: number;\n /** Master switch; false ⇒ all capabilities visible-disabled. */\n enabled?: boolean;\n\n observations?: Record<string, AgentObservationDefinition<any>>;\n actions?: Record<string, AgentActionDefinition<any, any>>;\n /** Domain references; normally added via @agent-surface/orpc. */\n procedures?: AgentProcedureBinding<any, any>[];\n}\n\n/* ───────────────────────── definition validation ───────────────────────── */\n\nconst COMPONENT_KEYS = new Set([\n \"type\",\n \"instanceId\",\n \"description\",\n \"parent\",\n \"meta\",\n \"internal\",\n \"policies\",\n \"origin\",\n \"priority\",\n \"enabled\",\n \"observations\",\n \"actions\",\n \"procedures\",\n]);\n\nconst OBSERVATION_KEYS = new Set([\n \"description\",\n \"output\",\n \"read\",\n \"when\",\n \"unavailableReason\",\n \"policies\",\n \"meta\",\n \"timeoutMs\",\n]);\n\nconst ACTION_KEYS = new Set([\n \"description\",\n \"input\",\n \"output\",\n \"effect\",\n \"idempotent\",\n \"reversible\",\n \"confirmation\",\n \"audit\",\n \"when\",\n \"unavailableReason\",\n \"precondition\",\n \"execute\",\n \"policies\",\n \"meta\",\n \"timeoutMs\",\n \"concurrency\",\n]);\n\nconst VIEW_EFFECTS = new Set([\"local-state\", \"navigation\"]);\nconst SERVER_EFFECTS = new Set([\n \"server-query\",\n \"server-mutation\",\n \"external-side-effect\",\n \"destructive\",\n]);\n\nfunction fail(code: ConstructorParameters<typeof AgentSurfaceDefinitionError>[0], message: string): never {\n throw new AgentSurfaceDefinitionError(code, message);\n}\n\nfunction checkMeta(meta: unknown, where: string, limits: AgentSurfaceLimits): void {\n if (meta === undefined) return;\n if (!isJsonValue(meta) || typeof meta !== \"object\" || Array.isArray(meta)) {\n fail(\"INVALID_DEFINITION\", `${where}: meta must be a JsonValue record`);\n }\n if (byteLength(meta) > limits.maxMetaBytes) {\n fail(\"LIMIT_EXCEEDED\", `${where}: meta exceeds ${limits.maxMetaBytes} bytes`);\n }\n}\n\n/** D25: the group shape is closed and `parallel` must be explicitly bounded —\n * an unbounded group would be the one place the runtime stops being bounded. */\nfunction checkConcurrency(concurrency: AgentConcurrency | undefined, where: string): void {\n if (concurrency === undefined) return;\n if (typeof concurrency !== \"object\" || concurrency === null) {\n fail(\"INVALID_DEFINITION\", `${where}: concurrency must be an object`);\n }\n const { mode } = concurrency;\n if (![\"instance\", \"capability\", \"key\", \"parallel\"].includes(mode)) {\n fail(\"INVALID_DEFINITION\", `${where}: invalid concurrency mode \"${String(mode)}\"`);\n }\n if (mode === \"key\" && (typeof concurrency.key !== \"string\" || concurrency.key.length === 0)) {\n fail(\"INVALID_DEFINITION\", `${where}: concurrency mode \"key\" requires a non-empty key`);\n }\n if (\n mode === \"parallel\" &&\n (typeof concurrency.max !== \"number\" || !Number.isInteger(concurrency.max) || concurrency.max < 1)\n ) {\n fail(\n \"INVALID_DEFINITION\",\n `${where}: concurrency mode \"parallel\" requires an integer max ≥ 1 (unbounded parallelism is not offered)`,\n );\n }\n const depth = concurrency.queueDepth;\n if (depth !== undefined && (!Number.isInteger(depth) || depth < 0)) {\n fail(\"INVALID_DEFINITION\", `${where}: concurrency queueDepth must be a non-negative integer`);\n }\n}\n\nfunction checkSchema(schema: AgentSchema<any> | undefined, where: string, limits: AgentSurfaceLimits): void {\n if (schema === undefined) return;\n if (typeof schema !== \"object\" || schema === null || typeof schema.parse !== \"function\" || typeof schema.jsonSchema !== \"object\") {\n fail(\"INVALID_DEFINITION\", `${where}: expected an AgentSchema ({ jsonSchema, parse })`);\n }\n const result = validateJsonSchemaDocument(schema.jsonSchema, limits);\n if (!result.ok) fail(\"UNSUPPORTED_SCHEMA\", `${where}: ${result.reason}`);\n}\n\n/**\n * Validates a component definition structurally. Throws\n * AgentSurfaceDefinitionError in every environment — structural defects are\n * deterministic code bugs (docs/03 §registry).\n */\nexport function validateComponentDefinition(\n def: AgentComponentDefinition,\n limits: AgentSurfaceLimits,\n opts: { hasProcedureExecutor: boolean },\n): void {\n if (typeof def !== \"object\" || def === null) {\n fail(\"INVALID_DEFINITION\", \"definition must be an object\");\n }\n for (const key of Object.keys(def)) {\n if (!COMPONENT_KEYS.has(key)) {\n fail(\"INVALID_DEFINITION\", `unknown definition field \"${key}\"`);\n }\n }\n if (typeof def.type !== \"string\" || !isValidComponentType(def.type)) {\n fail(\"INVALID_ID\", `invalid component type \"${String(def.type)}\"`);\n }\n const instanceId = def.instanceId ?? \"default\";\n if (!isValidInstanceId(instanceId)) {\n fail(\"INVALID_ID\", `invalid instanceId \"${instanceId}\" for component \"${def.type}\"`);\n }\n if (typeof def.description !== \"string\" || def.description.trim().length === 0) {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": description is required and must be non-empty`);\n }\n if (def.description.length > limits.maxComponentDescription) {\n fail(\n \"LIMIT_EXCEEDED\",\n `component \"${def.type}\": description exceeds ${limits.maxComponentDescription} chars`,\n );\n }\n if (def.parent !== undefined) {\n if (\n typeof def.parent !== \"object\" ||\n def.parent === null ||\n typeof def.parent.type !== \"string\" ||\n !isValidComponentType(def.parent.type) ||\n (def.parent.instanceId !== undefined && !isValidInstanceId(def.parent.instanceId))\n ) {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": invalid parent link`);\n }\n }\n checkMeta(def.meta, `component \"${def.type}\"`, limits);\n if (def.priority !== undefined && typeof def.priority !== \"number\") {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": priority must be a number`);\n }\n if (def.origin !== undefined && typeof def.origin !== \"string\") {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": origin must be a string`);\n }\n\n const seenNames = new Set<string>();\n const checkName = (name: string, kind: string): void => {\n if (!isValidCapabilityName(name)) {\n fail(\"INVALID_ID\", `component \"${def.type}\": invalid ${kind} name \"${name}\"`);\n }\n const capabilityId = formatViewCapabilityId(def.type, name);\n if (capabilityId.length > MAX_ID_LENGTH) {\n fail(\"INVALID_ID\", `capability id \"${capabilityId}\" exceeds ${MAX_ID_LENGTH} chars`);\n }\n if (seenNames.has(name)) {\n fail(\"DUPLICATE_CAPABILITY\", `component \"${def.type}\": duplicate capability name \"${name}\"`);\n }\n seenNames.add(name);\n };\n\n for (const [name, obs] of Object.entries(def.observations ?? {})) {\n checkName(name, \"observation\");\n const where = `observation \"${def.type}.${name}\"`;\n for (const key of Object.keys(obs)) {\n if (!OBSERVATION_KEYS.has(key)) fail(\"INVALID_DEFINITION\", `${where}: unknown field \"${key}\"`);\n }\n if (typeof obs.description !== \"string\" || obs.description.trim().length === 0) {\n fail(\"INVALID_DEFINITION\", `${where}: description is required`);\n }\n if (obs.description.length > limits.maxCapabilityDescription) {\n fail(\"LIMIT_EXCEEDED\", `${where}: description exceeds ${limits.maxCapabilityDescription} chars`);\n }\n if (typeof obs.read !== \"function\") fail(\"INVALID_DEFINITION\", `${where}: read() is required`);\n checkSchema(obs.output, `${where} output`, limits);\n if (obs.output === undefined) fail(\"INVALID_DEFINITION\", `${where}: output schema is required`);\n checkMeta(obs.meta, where, limits);\n }\n\n for (const [name, act] of Object.entries(def.actions ?? {})) {\n checkName(name, \"action\");\n const where = `action \"${def.type}.${name}\"`;\n for (const key of Object.keys(act)) {\n if (!ACTION_KEYS.has(key)) fail(\"INVALID_DEFINITION\", `${where}: unknown field \"${key}\"`);\n }\n if (typeof act.description !== \"string\" || act.description.trim().length === 0) {\n fail(\"INVALID_DEFINITION\", `${where}: description is required`);\n }\n if (act.description.length > limits.maxCapabilityDescription) {\n fail(\"LIMIT_EXCEEDED\", `${where}: description exceeds ${limits.maxCapabilityDescription} chars`);\n }\n if (typeof act.execute !== \"function\") fail(\"INVALID_DEFINITION\", `${where}: execute() is required`);\n if (!VIEW_EFFECTS.has(act.effect as string)) {\n if (SERVER_EFFECTS.has(act.effect as string)) {\n fail(\n \"PLANE_VIOLATION\",\n `${where}: view actions cannot declare server effect \"${act.effect}\" — define an oRPC procedure and reference it (docs/05)`,\n );\n }\n fail(\"INVALID_DEFINITION\", `${where}: effect must be \"local-state\" or \"navigation\"`);\n }\n if (act.confirmation !== undefined && ![\"never\", \"optional\", \"required\"].includes(act.confirmation)) {\n fail(\"INVALID_DEFINITION\", `${where}: invalid confirmation \"${act.confirmation}\"`);\n }\n if (act.audit !== undefined && ![\"none\", \"metadata\", \"full\"].includes(act.audit)) {\n fail(\"INVALID_DEFINITION\", `${where}: invalid audit level \"${act.audit}\"`);\n }\n if (act.input === undefined) fail(\"INVALID_DEFINITION\", `${where}: input schema is required`);\n checkSchema(act.input, `${where} input`, limits);\n checkSchema(act.output, `${where} output`, limits);\n checkMeta(act.meta, where, limits);\n checkConcurrency(act.concurrency, where);\n }\n\n const procedures = def.procedures ?? [];\n if (procedures.length > 0 && !opts.hasProcedureExecutor) {\n fail(\n \"PLANE_VIOLATION\",\n `component \"${def.type}\": procedure bindings require an installed procedure executor (registry.setProcedureExecutor)`,\n );\n }\n for (const binding of procedures) {\n if (typeof binding !== \"object\" || binding === null || binding.kind !== \"procedure-binding\") {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": invalid procedure binding`);\n }\n const ref = binding.ref;\n if (\n typeof ref !== \"object\" ||\n ref === null ||\n typeof ref.path !== \"string\" ||\n ref.path.length === 0 ||\n typeof ref.id !== \"string\" ||\n ref.id !== `domain:${ref.path}` ||\n typeof ref.description !== \"string\"\n ) {\n fail(\"INVALID_DEFINITION\", `component \"${def.type}\": procedure binding has an invalid ref`);\n }\n if (!SERVER_EFFECTS.has(ref.effect as string)) {\n fail(\n \"PLANE_VIOLATION\",\n `procedure \"${ref.path}\": effect must be one of server-query | server-mutation | external-side-effect | destructive`,\n );\n }\n if (typeof binding.reducedInputSchema !== \"object\" || binding.reducedInputSchema === null) {\n fail(\"INVALID_DEFINITION\", `procedure \"${ref.path}\": missing reduced input schema`);\n }\n if (binding.config.confirmation !== undefined && ![\"optional\", \"required\"].includes(binding.config.confirmation)) {\n fail(\"INVALID_DEFINITION\", `procedure \"${ref.path}\": invalid confirmation escalation`);\n }\n checkMeta(binding.config.meta, `procedure \"${ref.path}\"`, limits);\n checkConcurrency(binding.config.concurrency, `procedure \"${ref.path}\"`);\n }\n}\n","import type { JsonValue } from \"./types.js\";\nimport type { AgentCapabilityErrorCode } from \"./errors.js\";\n\nexport interface AuditEvent {\n at: string; // ISO-8601\n type:\n | \"registration\"\n | \"unregistration\"\n | \"registration-rejected\"\n | \"invocation-started\"\n | \"invocation-settled\"\n | \"confirmation-requested\"\n | \"confirmation-approved\"\n | \"confirmation-denied\"\n | \"confirmation-expired\"\n | \"confirmation-consumed\"\n | \"late-settlement\"\n | \"collision-suspected\";\n capabilityId?: string;\n registrationId?: string;\n invocationId?: string;\n consumerId?: string;\n status?: \"ok\" | \"error\";\n code?: AgentCapabilityErrorCode;\n durationMs?: number;\n /** Time spent waiting for a concurrency slot (docs/06 §audit; distinct\n * from execution — §7.1 observability). Settled invocations only. */\n queueWaitMs?: number;\n /** Time spent inside the handler/executor guards, excluding queue wait. */\n executionMs?: number;\n /** Present only for capabilities with audit: \"full\"; size-capped. */\n payload?: { input?: JsonValue; output?: JsonValue };\n}\n\nexport interface AuditSink {\n /** MUST NOT throw; MUST be non-blocking. */\n record(event: AuditEvent): void;\n}\n\nexport function memoryAuditSink(opts?: {\n capacity?: number;\n}): AuditSink & { events(): AuditEvent[] } {\n const capacity = opts?.capacity ?? 1000;\n const buffer: AuditEvent[] = [];\n return {\n record(event) {\n buffer.push(event);\n if (buffer.length > capacity) buffer.splice(0, buffer.length - capacity);\n },\n events() {\n return [...buffer];\n },\n };\n}\n\nexport function consoleAuditSink(): AuditSink {\n return {\n record(event) {\n // eslint-disable-next-line no-console\n console.debug(\"[agent-surface audit]\", event.type, event);\n },\n };\n}\n\n/** Sinks MUST NOT break the registry: exceptions are swallowed (and logged). */\nexport function safeRecord(sink: AuditSink | undefined, event: AuditEvent): void {\n if (!sink) return;\n try {\n sink.record(event);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[agent-surface] audit sink threw\", err);\n }\n}\n","import type { AgentCapabilityErrorCode } from \"./errors.js\";\n\nexport type AgentSurfaceEvent =\n | { type: \"surface-changed\"; surfaceVersion: string } // coalesced per microtask\n | {\n type: \"component-registered\";\n registrationId: string;\n componentType: string;\n instanceId: string;\n }\n | {\n type: \"component-unregistered\";\n registrationId: string;\n componentType: string;\n instanceId: string;\n }\n | {\n type: \"component-rejected\";\n componentType: string;\n instanceId: string;\n reason: \"duplicate\" | \"guard\";\n }\n | {\n type: \"availability-changed\";\n registrationId: string;\n capabilityId: string;\n available: boolean;\n }\n | { type: \"collision-suspected\"; viewCapabilityId: string; domainProcedureId: string }\n | { type: \"invocation-started\"; invocationId: string; capabilityId: string; consumerId: string }\n | {\n type: \"invocation-settled\";\n invocationId: string;\n capabilityId: string;\n status: \"ok\" | \"error\";\n code?: AgentCapabilityErrorCode;\n durationMs: number;\n }\n | {\n type: \"confirmation-requested\";\n confirmationId: string;\n capabilityId: string;\n expiresAt: string;\n }\n | {\n type: \"confirmation-resolved\";\n confirmationId: string;\n outcome: \"approved\" | \"denied\" | \"expired\";\n };\n\n/**\n * Ordered, non-re-entrant event dispatcher (D17): events queue in mutation\n * order and drain one at a time; events emitted from listeners join the queue\n * and are delivered after the current event finishes; listener exceptions are\n * isolated and reported.\n */\nexport class EventDispatcher {\n private listeners = new Set<(event: AgentSurfaceEvent) => void>();\n private queue: AgentSurfaceEvent[] = [];\n private draining = false;\n\n constructor(private reportError: (err: unknown) => void) {}\n\n subscribe(listener: (event: AgentSurfaceEvent) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n emit(event: AgentSurfaceEvent): void {\n this.queue.push(event);\n if (this.draining) return;\n this.draining = true;\n try {\n let next: AgentSurfaceEvent | undefined;\n while ((next = this.queue.shift()) !== undefined) {\n for (const listener of [...this.listeners]) {\n try {\n listener(next);\n } catch (err) {\n this.reportError(err);\n }\n }\n }\n } finally {\n this.draining = false;\n }\n }\n\n clear(): void {\n this.listeners.clear();\n this.queue.length = 0;\n }\n}\n","import type { AgentEffect, JsonValue, Unsubscribe } from \"./types.js\";\nimport { jsonDeepEqual, randomBase62 } from \"./utils.js\";\nimport type { AgentSurfaceEvent } from \"./events.js\";\nimport type { AuditEvent } from \"./audit.js\";\n\nexport interface PendingConfirmation {\n confirmationId: string; // \"cnf_\" + random\n capabilityId: string;\n registrationId: string;\n /** Normalized consumer identity `kind:id` (D22). */\n consumerKey: string;\n /** Effect of the operation being approved. */\n effect: AgentEffect;\n /** Human-readable summary composed from description + effective input. */\n summary: string;\n /** The exact effective input (bound + agent-supplied) being approved. */\n input: JsonValue;\n requestedAt: string;\n expiresAt: string; // default TTL 120 s\n}\n\nexport interface ConfirmationController {\n /** Pending requests, for host UI rendering. */\n pending(): PendingConfirmation[];\n resolve(confirmationId: string, resolution: { approved: boolean; reason?: string }): void;\n /** Resolves when the given confirmation settles (approved/denied/expired). */\n waitFor(\n confirmationId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<\"approved\" | \"denied\" | \"expired\">;\n subscribe(listener: (pending: PendingConfirmation[]) => void): Unsubscribe;\n /** Test hook: force-expire a record as if its TTL elapsed (docs/08). */\n forceExpire(confirmationId: string): void;\n}\n\ntype RecordState = \"pending\" | \"approved\" | \"denied\" | \"expired\" | \"consumed\";\n\ninterface ConfirmationRecord extends PendingConfirmation {\n state: RecordState;\n /** Canonical request digest (D21): {surfaceId, registrationId,\n * capabilityId, consumerKey, effectiveInput, effect}. */\n digest: string;\n approvedAt?: string;\n denyReason?: string;\n timer?: ReturnType<typeof setTimeout>;\n waiters: Array<(outcome: \"approved\" | \"denied\" | \"expired\") => void>;\n}\n\nexport type ConsumeResult =\n | { ok: true; approvedAt: string }\n | { ok: false; kind: \"pending-again\"; record: PendingConfirmation }\n | { ok: false; kind: \"invalid\"; reason: \"expired\" | \"denied\" | \"consumed\" | \"mismatch\" };\n\nconst MAX_RETAINED_RESOLVED = 200;\n\nexport class ConfirmationStore {\n private records = new Map<string, ConfirmationRecord>();\n private listeners = new Set<(pending: PendingConfirmation[]) => void>();\n\n constructor(\n private readonly opts: {\n ttlMs: number;\n maxPending: number;\n now: () => number;\n emit: (event: AgentSurfaceEvent) => void;\n audit: (event: Omit<AuditEvent, \"at\">) => void;\n },\n ) {}\n\n /** Creates (or re-uses a matching pending) confirmation record.\n * Returns \"overflow\" when the bounded pending store is full (D24):\n * the caller fails RATE_LIMITED and no record is created. */\n request(request: {\n capabilityId: string;\n registrationId: string;\n consumerKey: string;\n effect: AgentEffect;\n input: JsonValue;\n summary: string;\n digest: string;\n }): PendingConfirmation | \"overflow\" {\n for (const record of this.records.values()) {\n if (record.state === \"pending\" && record.digest === request.digest) {\n return this.view(record);\n }\n }\n if (this.pendingCount() >= this.opts.maxPending) return \"overflow\";\n const now = this.opts.now();\n const record: ConfirmationRecord = {\n confirmationId: `cnf_${randomBase62(12)}`,\n capabilityId: request.capabilityId,\n registrationId: request.registrationId,\n consumerKey: request.consumerKey,\n effect: request.effect,\n summary: request.summary,\n input: request.input,\n digest: request.digest,\n requestedAt: new Date(now).toISOString(),\n expiresAt: new Date(now + this.opts.ttlMs).toISOString(),\n state: \"pending\",\n waiters: [],\n };\n record.timer = setTimeout(() => this.expire(record.confirmationId), this.opts.ttlMs);\n this.records.set(record.confirmationId, record);\n this.trim();\n this.opts.emit({\n type: \"confirmation-requested\",\n confirmationId: record.confirmationId,\n capabilityId: record.capabilityId,\n expiresAt: record.expiresAt,\n });\n this.opts.audit({\n type: \"confirmation-requested\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n invocationId: undefined,\n });\n this.notify();\n return this.view(record);\n }\n\n private pendingCount(): number {\n let count = 0;\n for (const record of this.records.values()) {\n if (record.state === \"pending\") count += 1;\n }\n return count;\n }\n\n resolve(confirmationId: string, resolution: { approved: boolean; reason?: string }): void {\n const record = this.records.get(confirmationId);\n if (!record || record.state !== \"pending\") return;\n if (record.timer) clearTimeout(record.timer);\n if (resolution.approved) {\n record.state = \"approved\";\n record.approvedAt = new Date(this.opts.now()).toISOString();\n this.opts.emit({ type: \"confirmation-resolved\", confirmationId, outcome: \"approved\" });\n this.opts.audit({\n type: \"confirmation-approved\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n });\n this.settleWaiters(record, \"approved\");\n } else {\n record.state = \"denied\";\n record.denyReason = resolution.reason;\n this.opts.emit({ type: \"confirmation-resolved\", confirmationId, outcome: \"denied\" });\n this.opts.audit({\n type: \"confirmation-denied\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n });\n this.settleWaiters(record, \"denied\");\n }\n this.notify();\n }\n\n expire(confirmationId: string): void {\n const record = this.records.get(confirmationId);\n if (!record || record.state !== \"pending\") return;\n if (record.timer) clearTimeout(record.timer);\n record.state = \"expired\";\n record.expiresAt = new Date(this.opts.now()).toISOString();\n this.opts.emit({ type: \"confirmation-resolved\", confirmationId, outcome: \"expired\" });\n this.opts.audit({\n type: \"confirmation-expired\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n });\n this.settleWaiters(record, \"expired\");\n this.notify();\n }\n\n /** Evidence validation + single-use consumption (docs/06 rules 2–5).\n * Matching is digest-first AND exact-value on the effective input —\n * never hash-only (AS-CONFIRM-002). */\n consume(evidence: {\n confirmationId: string;\n digest: string;\n input: JsonValue;\n }): ConsumeResult {\n const record = this.records.get(evidence.confirmationId);\n if (!record) return { ok: false, kind: \"invalid\", reason: \"mismatch\" };\n const matches =\n record.digest === evidence.digest && jsonDeepEqual(record.input, evidence.input);\n switch (record.state) {\n case \"pending\":\n return matches\n ? { ok: false, kind: \"pending-again\", record: this.view(record) }\n : { ok: false, kind: \"invalid\", reason: \"mismatch\" };\n case \"denied\":\n return { ok: false, kind: \"invalid\", reason: \"denied\" };\n case \"expired\":\n return { ok: false, kind: \"invalid\", reason: \"expired\" };\n case \"consumed\":\n return { ok: false, kind: \"invalid\", reason: \"consumed\" };\n case \"approved\": {\n if (Date.parse(record.expiresAt) < this.opts.now()) {\n record.state = \"expired\";\n return { ok: false, kind: \"invalid\", reason: \"expired\" };\n }\n if (!matches) return { ok: false, kind: \"invalid\", reason: \"mismatch\" };\n record.state = \"consumed\"; // atomic single use\n this.opts.audit({\n type: \"confirmation-consumed\",\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerId: record.consumerKey,\n });\n return { ok: true, approvedAt: record.approvedAt ?? record.requestedAt };\n }\n }\n }\n\n pending(): PendingConfirmation[] {\n return [...this.records.values()]\n .filter((r) => r.state === \"pending\")\n .map((r) => this.view(r));\n }\n\n waitFor(\n confirmationId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<\"approved\" | \"denied\" | \"expired\"> {\n const record = this.records.get(confirmationId);\n if (!record) return Promise.resolve(\"expired\");\n if (record.state === \"approved\" || record.state === \"consumed\") return Promise.resolve(\"approved\");\n if (record.state === \"denied\") return Promise.resolve(\"denied\");\n if (record.state === \"expired\") return Promise.resolve(\"expired\");\n return new Promise((resolvePromise) => {\n const waiter = (outcome: \"approved\" | \"denied\" | \"expired\"): void => resolvePromise(outcome);\n record.waiters.push(waiter);\n opts?.signal?.addEventListener(\n \"abort\",\n () => {\n const i = record.waiters.indexOf(waiter);\n if (i >= 0) record.waiters.splice(i, 1);\n resolvePromise(\"expired\");\n },\n { once: true },\n );\n });\n }\n\n subscribe(listener: (pending: PendingConfirmation[]) => void): Unsubscribe {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n /** Expires every pending record (dispose path). */\n disposeAll(): void {\n for (const record of [...this.records.values()]) {\n if (record.state === \"pending\") this.expire(record.confirmationId);\n }\n this.listeners.clear();\n }\n\n controller(): ConfirmationController {\n return {\n pending: () => this.pending(),\n resolve: (id, resolution) => this.resolve(id, resolution),\n waitFor: (id, opts) => this.waitFor(id, opts),\n subscribe: (listener) => this.subscribe(listener),\n forceExpire: (id) => this.expire(id),\n };\n }\n\n private view(record: ConfirmationRecord): PendingConfirmation {\n return {\n confirmationId: record.confirmationId,\n capabilityId: record.capabilityId,\n registrationId: record.registrationId,\n consumerKey: record.consumerKey,\n effect: record.effect,\n summary: record.summary,\n input: record.input,\n requestedAt: record.requestedAt,\n expiresAt: record.expiresAt,\n };\n }\n\n private settleWaiters(\n record: ConfirmationRecord,\n outcome: \"approved\" | \"denied\" | \"expired\",\n ): void {\n const waiters = record.waiters.splice(0);\n for (const waiter of waiters) waiter(outcome);\n }\n\n private notify(): void {\n const snapshot = this.pending();\n for (const listener of [...this.listeners]) {\n try {\n listener(snapshot);\n } catch {\n // listener errors must not corrupt the store\n }\n }\n }\n\n private trim(): void {\n const resolved = [...this.records.values()].filter((r) => r.state !== \"pending\");\n if (resolved.length <= MAX_RETAINED_RESOLVED) return;\n for (const record of resolved.slice(0, resolved.length - MAX_RETAINED_RESOLVED)) {\n this.records.delete(record.confirmationId);\n }\n }\n}\n","import type { AgentConsumer, JsonValue } from \"./types.js\";\nimport type {\n AgentInvocation,\n AgentInvocationResult,\n InvokeOptions,\n} from \"./invocation-types.js\";\nimport type {\n ActionRuntime,\n CapabilityRuntime,\n InFlightEntry,\n InternalRegistration,\n ObservationRuntime,\n ProcedureRuntime,\n RegistryInternals,\n} from \"./internal.js\";\nimport {\n DevDefectError,\n buildPolicyContext,\n computeAvailability,\n concurrencyGroupFor,\n consumerKeyOf,\n maxConfirmation,\n policiesFor,\n} from \"./internal.js\";\nimport type { AgentCapabilityErrorPayload } from \"./errors.js\";\nimport { AgentSurfaceError, isAgentSurfaceError } from \"./errors.js\";\nimport { parseCapabilityId } from \"./ids.js\";\nimport { AgentSchemaError, fromJsonSchema } from \"./schema.js\";\nimport {\n CONFIRMATION_ESCALATION,\n composeAuthorizeChain,\n composeInvokeChain,\n evaluateDiscovery,\n type AgentInvocationPolicyContext,\n type AgentPolicyWithEscalation,\n type ConfirmationEscalation,\n} from \"./policy.js\";\nimport type { AgentActionContext, AgentReadContext } from \"./definition.js\";\nimport { canonicalJson, fnv1a64, isJsonValue, randomBase62, truncate } from \"./utils.js\";\n\nconst DEFAULT_CONSUMER: AgentConsumer = { id: \"anonymous\", kind: \"embedded\" };\n\n/* ─────────────────────── error payload constructors ─────────────────────── */\n\nfunction notFound(): AgentCapabilityErrorPayload {\n return {\n code: \"CAPABILITY_NOT_FOUND\",\n message:\n \"This capability does not exist in the current surface. Refresh the surface catalog before the next step.\",\n retry: \"after-refresh\",\n };\n}\n\nfunction notAvailable(reason: string | undefined): AgentCapabilityErrorPayload {\n return {\n code: \"CAPABILITY_NOT_AVAILABLE\",\n message: `This capability exists but is currently unavailable${reason ? `: ${reason}` : \"\"}. Perform the enabling step first, then refresh.`,\n retry: \"after-refresh\",\n ...(reason !== undefined ? { details: { reason } } : {}),\n };\n}\n\nfunction unmounted(phase: \"resolve\" | \"mid-flight\"): AgentCapabilityErrorPayload {\n return {\n code: \"COMPONENT_UNMOUNTED\",\n message:\n phase === \"mid-flight\"\n ? \"The owning view unmounted while this capability was executing. Verify state before repeating a non-idempotent action.\"\n : \"The owning view is no longer mounted. Refresh the surface catalog.\",\n retry: \"after-refresh\",\n details: { phase },\n };\n}\n\nfunction stale(\n reason: \"registration-replaced\" | \"surface-reloaded\" | \"surface-version-mismatch\",\n liveRegistrationId?: string,\n): AgentCapabilityErrorPayload {\n return {\n code: \"STALE_CAPABILITY\",\n message:\n \"The invocation references a superseded surface snapshot. Refresh the catalog and re-resolve the target.\",\n retry: \"after-refresh\",\n details: { reason, ...(liveRegistrationId ? { liveRegistrationId } : {}) },\n };\n}\n\nfunction invocationConflict(): AgentCapabilityErrorPayload {\n // Agent-visible details MUST NOT expose the prior request (docs/07).\n return {\n code: \"INVOCATION_CONFLICT\",\n message:\n \"This invocation id was already used for a different request. Use a fresh invocation id if the new request is intentional.\",\n retry: \"with-changes\",\n details: { reason: \"id-reused-with-different-request\" },\n };\n}\n\nfunction queueFull(retryAfterMs: number): AgentCapabilityErrorPayload {\n return {\n code: \"RATE_LIMITED\",\n message: \"The queue for this capability is full. Retry shortly.\",\n retry: \"after-delay\",\n details: { reason: \"queue-full\", retryAfterMs },\n };\n}\n\nfunction cancelled(message: string): AgentCapabilityErrorPayload {\n return { code: \"CANCELLED\", message, retry: \"yes\" };\n}\n\nfunction executionFailed(\n reason: \"handler-error\" | \"output-invalid\" | \"output-too-large\" | \"transport\",\n opts?: { transient?: boolean },\n): AgentCapabilityErrorPayload {\n const messages: Record<string, string> = {\n \"handler-error\": \"The capability failed to execute.\",\n \"output-invalid\": \"The capability produced an invalid output.\",\n \"output-too-large\": \"The capability produced an output exceeding the size limit.\",\n transport: \"The server call failed.\",\n };\n return {\n code: \"EXECUTION_FAILED\",\n message: messages[reason] ?? \"The capability failed to execute.\",\n retry: opts?.transient ? \"after-delay\" : \"no\",\n details: {\n reason,\n ...(opts?.transient ? { transient: true, retryAfterMs: 1000 } : {}),\n },\n };\n}\n\n/* ──────────────── phase 1: consumer-scoped dedupe + conflict (D22) ──────────────── */\n\n/** Fingerprint of the request AS ISSUED (docs/18 §correction 2). */\nfunction requestFingerprint(request: AgentInvocation): string {\n return fnv1a64(\n canonicalJson({\n capabilityId: request.capabilityId,\n registrationId: request.registrationId ?? null,\n instanceId: request.instanceId ?? null,\n surfaceVersion: request.surfaceVersion ?? null,\n input: request.input ?? null,\n confirmationId: request.confirmationId ?? null,\n }),\n );\n}\n\nexport function performInvoke(\n internals: RegistryInternals,\n request: AgentInvocation,\n options?: InvokeOptions,\n): Promise<AgentInvocationResult> {\n if (internals.disposed) {\n throw new Error(\"invoke() called on a disposed registry\");\n }\n const invocationId = request.invocationId ?? `inv_${randomBase62(12)}`;\n const consumer = options?.consumer ?? DEFAULT_CONSUMER;\n const consumerKey = consumerKeyOf(consumer);\n const fingerprint = requestFingerprint(request);\n const dedupeKey = `${consumerKey} ${invocationId}`;\n\n pruneDedupe(internals);\n const existing = internals.dedupe.get(dedupeKey);\n if (existing) {\n if (existing.kind === \"inflight\") {\n if (existing.fingerprint === fingerprint) return existing.promise; // join, don't re-execute\n return Promise.resolve(conflictResult(internals, request, invocationId, consumer));\n }\n if (existing.expiresAt > internals.now()) {\n if (existing.fingerprint === fingerprint) return Promise.resolve(existing.result);\n return Promise.resolve(conflictResult(internals, request, invocationId, consumer));\n }\n internals.dedupe.delete(dedupeKey); // expired key: a new attempt (bounded window)\n }\n\n const promise = runPipeline(internals, request, invocationId, consumer, consumerKey, options);\n internals.dedupe.set(dedupeKey, { kind: \"inflight\", fingerprint, promise });\n promise.then(\n (result) => {\n // Terminal = ok and every error except CONFIRMATION_REQUIRED / RATE_LIMITED\n // (expected-retry outcomes; INVOCATION_CONFLICT never reaches here).\n const terminal =\n result.status === \"ok\" ||\n (result.error.code !== \"CONFIRMATION_REQUIRED\" && result.error.code !== \"RATE_LIMITED\");\n if (terminal) {\n internals.dedupe.set(dedupeKey, {\n kind: \"terminal\",\n fingerprint,\n result,\n expiresAt: internals.now() + internals.limits.dedupeCacheTtlMs,\n });\n pruneDedupe(internals);\n } else {\n internals.dedupe.delete(dedupeKey);\n }\n },\n () => {\n internals.dedupe.delete(dedupeKey);\n },\n );\n return promise;\n}\n\n/** Fail-closed conflict envelope: emitted through events/audit, never cached. */\nfunction conflictResult(\n internals: RegistryInternals,\n request: AgentInvocation,\n invocationId: string,\n consumer: AgentConsumer,\n): AgentInvocationResult {\n internals.emit({\n type: \"invocation-started\",\n invocationId,\n capabilityId: request.capabilityId,\n consumerId: consumer.id,\n });\n const error = invocationConflict();\n const result: AgentInvocationResult = {\n status: \"error\",\n invocationId,\n capabilityId: request.capabilityId,\n error,\n surfaceVersion: String(internals.version),\n };\n internals.emit({\n type: \"invocation-settled\",\n invocationId,\n capabilityId: request.capabilityId,\n status: \"error\",\n code: error.code,\n durationMs: 0,\n });\n internals.recordAudit({\n type: \"invocation-settled\",\n capabilityId: request.capabilityId,\n invocationId,\n consumerId: consumerKeyOf(consumer),\n status: \"error\",\n code: error.code,\n durationMs: 0,\n });\n return result;\n}\n\nfunction pruneDedupe(internals: RegistryInternals): void {\n const now = internals.now();\n for (const [id, entry] of internals.dedupe) {\n if (entry.kind === \"terminal\" && entry.expiresAt <= now) internals.dedupe.delete(id);\n }\n while (internals.dedupe.size > internals.limits.dedupeCacheSize) {\n const oldest = internals.dedupe.keys().next().value;\n if (oldest === undefined) break;\n const entry = internals.dedupe.get(oldest);\n if (entry?.kind === \"inflight\") break; // never evict in-flight joins\n internals.dedupe.delete(oldest);\n }\n}\n\n/* ───────────────────────────── the 10 phases ───────────────────────────── */\n\ninterface ResolvedTarget {\n reg: InternalRegistration;\n cap: CapabilityRuntime;\n}\n\nasync function runPipeline(\n internals: RegistryInternals,\n request: AgentInvocation,\n invocationId: string,\n consumer: AgentConsumer,\n consumerKey: string,\n options?: InvokeOptions,\n): Promise<AgentInvocationResult> {\n const startVersion = internals.version;\n const startedAt = internals.now();\n internals.emit({\n type: \"invocation-started\",\n invocationId,\n capabilityId: request.capabilityId,\n consumerId: consumer.id,\n });\n\n let resolvedAuditLevel: \"none\" | \"metadata\" | \"full\" = \"metadata\";\n let resolvedRegistrationId: string | undefined;\n let inputForAudit: JsonValue | undefined;\n let outputForAudit: JsonValue | undefined;\n // §7.1 observability: queue wait and execution duration are distinct.\n let queueWaitMsForAudit: number | undefined;\n let executionMsForAudit: number | undefined;\n\n const finalize = (\n body:\n | { status: \"ok\"; output?: JsonValue }\n | { status: \"error\"; error: AgentCapabilityErrorPayload },\n ): AgentInvocationResult => {\n const surfaceVersion = String(internals.version);\n const surfaceChanged = internals.version !== startVersion ? true : undefined;\n const result: AgentInvocationResult =\n body.status === \"ok\"\n ? {\n status: \"ok\",\n invocationId,\n capabilityId: request.capabilityId,\n ...(body.output !== undefined ? { output: body.output } : {}),\n surfaceVersion,\n ...(surfaceChanged ? { surfaceChanged } : {}),\n }\n : {\n status: \"error\",\n invocationId,\n capabilityId: request.capabilityId,\n error: body.error,\n surfaceVersion,\n ...(surfaceChanged ? { surfaceChanged } : {}),\n };\n const durationMs = internals.now() - startedAt;\n internals.emit({\n type: \"invocation-settled\",\n invocationId,\n capabilityId: request.capabilityId,\n status: result.status,\n ...(result.status === \"error\" ? { code: result.error.code } : {}),\n durationMs,\n });\n if (resolvedAuditLevel !== \"none\") {\n internals.recordAudit({\n type: \"invocation-settled\",\n capabilityId: request.capabilityId,\n registrationId: resolvedRegistrationId,\n invocationId,\n consumerId: consumerKey,\n status: result.status,\n ...(result.status === \"error\" ? { code: result.error.code } : {}),\n durationMs,\n ...(queueWaitMsForAudit !== undefined ? { queueWaitMs: queueWaitMsForAudit } : {}),\n ...(executionMsForAudit !== undefined ? { executionMs: executionMsForAudit } : {}),\n ...(resolvedAuditLevel === \"full\"\n ? {\n payload: {\n ...(inputForAudit !== undefined ? { input: inputForAudit } : {}),\n ...(outputForAudit !== undefined ? { output: outputForAudit } : {}),\n },\n }\n : {}),\n });\n }\n return result;\n };\n\n try {\n /* phase 2 — resolve + staleness tokens */\n const resolved = resolveTarget(internals, request);\n if (\"error\" in resolved) return finalize({ status: \"error\", error: resolved.error });\n const { reg, cap } = resolved;\n resolvedRegistrationId = reg.id;\n resolvedAuditLevel = cap.auditLevel;\n\n // surfaceVersion is enforced only for dangerous effects (docs/03 §versioning).\n if (\n request.surfaceVersion !== undefined &&\n request.surfaceVersion !== String(internals.version) &&\n cap.kind === \"procedure\" &&\n (cap.effect === \"destructive\" || cap.effect === \"external-side-effect\")\n ) {\n return finalize({ status: \"error\", error: stale(\"surface-version-mismatch\") });\n }\n\n if (resolvedAuditLevel !== \"none\") {\n internals.recordAudit({\n type: \"invocation-started\",\n capabilityId: cap.capabilityId,\n registrationId: reg.id,\n invocationId,\n consumerId: consumerKey,\n });\n }\n\n /* phase 3 — availability (re-evaluated, never trusted from discovery) */\n const availability = computeAvailability(internals, reg, cap);\n if (!availability.available) {\n return finalize({ status: \"error\", error: notAvailable(availability.reason) });\n }\n\n /* phase 4 — pre-input authority. The onDiscovery re-run covers pure\n discovery policies (hide ⇒ NOT_FOUND, disable ⇒ NOT_AVAILABLE);\n onAuthorize gates run onion-style with NO agent input in scope (D21). */\n const host = internals.host();\n const chain = policiesFor(internals, reg, cap);\n const policyCtx = buildPolicyContext(internals, reg, cap, consumer, host);\n const discovery = evaluateDiscovery(\n chain.filter((p) => !p.onAuthorize && !p.onInvoke),\n policyCtx,\n );\n if (discovery.decision === \"hide\") {\n // Indistinguishable from nonexistence for this consumer (requirement 12).\n return finalize({ status: \"error\", error: notFound() });\n }\n if (discovery.decision === \"disable\") {\n return finalize({ status: \"error\", error: notAvailable(discovery.reason) });\n }\n const escalations = chain\n .map((p) => (p as AgentPolicyWithEscalation)[CONFIRMATION_ESCALATION])\n .filter((e): e is ConfirmationEscalation => e !== undefined);\n\n const core = (): Promise<AgentInvocationResult> =>\n executeCore(internals, {\n request,\n invocationId,\n consumer,\n consumerKey,\n host,\n reg,\n cap,\n chain,\n policyCtx,\n escalations,\n options,\n finalize,\n setAuditPayload: (input, output) => {\n if (input !== undefined) inputForAudit = input;\n if (output !== undefined) outputForAudit = output;\n },\n setTimings: (timings) => {\n if (timings.queueWaitMs !== undefined) queueWaitMsForAudit = timings.queueWaitMs;\n if (timings.executionMs !== undefined) executionMsForAudit = timings.executionMs;\n },\n });\n\n try {\n return await composeAuthorizeChain(chain, policyCtx, core);\n } catch (err) {\n if (isAgentSurfaceError(err)) {\n return finalize({ status: \"error\", error: err.payload });\n }\n throw err;\n }\n } catch (err) {\n if (err instanceof DevDefectError) throw err; // dev probes throw out of invoke()\n if (isAgentSurfaceError(err)) {\n return finalize({ status: \"error\", error: err.payload });\n }\n internals.devError(\"[agent-surface] invocation pipeline failure\", err);\n return finalize({ status: \"error\", error: executionFailed(\"handler-error\") });\n }\n}\n\n/* ───────────────────────────── resolution ───────────────────────────── */\n\nfunction resolveTarget(\n internals: RegistryInternals,\n request: AgentInvocation,\n): ResolvedTarget | { error: AgentCapabilityErrorPayload } {\n const parsed = parseCapabilityId(request.capabilityId);\n if (!parsed) return { error: notFound() };\n\n interface Candidate {\n reg: InternalRegistration;\n cap: CapabilityRuntime;\n }\n let candidates: Candidate[] = [];\n\n if (parsed.plane === \"view\") {\n for (const reg of internals.registrations.values()) {\n if (reg.status !== \"active\" || reg.type !== parsed.componentType) continue;\n const cap: ObservationRuntime | ActionRuntime | undefined =\n reg.observations.get(parsed.name) ?? reg.actions.get(parsed.name);\n if (cap) candidates.push({ reg, cap });\n }\n } else {\n for (const reg of internals.registrations.values()) {\n if (reg.status !== \"active\") continue;\n for (const proc of reg.procedures) {\n if (proc.path === parsed.path) candidates.push({ reg, cap: proc });\n }\n }\n }\n\n if (request.instanceId !== undefined) {\n candidates = candidates.filter((c) => c.reg.instanceId === request.instanceId);\n }\n candidates.sort((a, b) =>\n a.reg.instanceId < b.reg.instanceId ? -1 : a.reg.instanceId > b.reg.instanceId ? 1 : 0,\n );\n\n if (request.registrationId !== undefined) {\n const live = candidates.find((c) => c.reg.id === request.registrationId);\n if (live) return live;\n // Tombstones are TTL-bound: an expired one no longer proves recency.\n const tombstone = internals.tombstones.get(request.registrationId);\n const tombstoned = tombstone !== undefined && tombstone.expiresAt > internals.now();\n if (candidates.length > 0) {\n const reason = tombstoned\n ? (\"registration-replaced\" as const)\n : (\"surface-reloaded\" as const);\n return { error: stale(reason, candidates[0]?.reg.id) };\n }\n if (tombstoned) {\n return { error: unmounted(\"resolve\") };\n }\n return { error: notFound() };\n }\n\n if (candidates.length === 0) {\n for (const tomb of internals.tombstones.values()) {\n if (tomb.expiresAt <= internals.now()) continue;\n if (tomb.capabilityIds.has(request.capabilityId)) {\n return { error: unmounted(\"resolve\") };\n }\n }\n return { error: notFound() };\n }\n if (candidates.length > 1) {\n const instances: JsonValue = candidates.map((c) => {\n const entry: Record<string, JsonValue> = {\n instanceId: c.reg.instanceId,\n registrationId: c.reg.id,\n };\n if (c.cap.kind === \"procedure\") {\n if (c.cap.contextLink) entry.context = { ...c.cap.contextLink };\n } else {\n entry.description = c.reg.description;\n }\n return entry;\n });\n return {\n error: {\n code: \"AMBIGUOUS_INSTANCE\",\n message:\n \"More than one live instance matches this capability. Re-issue the call with an explicit instanceId or registrationId.\",\n retry: \"with-changes\",\n details: { instances },\n },\n };\n }\n return candidates[0] as Candidate;\n}\n\n/* ───────────────────────── phases 5–10 per kind ───────────────────────── */\n\ninterface CoreArgs {\n request: AgentInvocation;\n invocationId: string;\n consumer: AgentConsumer;\n consumerKey: string;\n host: Record<string, unknown>;\n reg: InternalRegistration;\n cap: CapabilityRuntime;\n chain: ReadonlyArray<AgentPolicyWithEscalation>;\n policyCtx: ReturnType<typeof buildPolicyContext>;\n escalations: ConfirmationEscalation[];\n options: InvokeOptions | undefined;\n finalize: (\n body:\n | { status: \"ok\"; output?: JsonValue }\n | { status: \"error\"; error: AgentCapabilityErrorPayload },\n ) => AgentInvocationResult;\n setAuditPayload: (input?: JsonValue, output?: JsonValue) => void;\n setTimings: (timings: { queueWaitMs?: number; executionMs?: number }) => void;\n}\n\nasync function executeCore(\n internals: RegistryInternals,\n args: CoreArgs,\n): Promise<AgentInvocationResult> {\n const { cap } = args;\n if (cap.kind === \"observation\") return executeObservation(internals, args, cap);\n if (cap.kind === \"action\") return executeAction(internals, args, cap);\n return executeProcedure(internals, args, cap);\n}\n\n/** Phase 6: onInvoke onion over the validated effective input (D21). */\nfunction runInvokePolicies(\n args: CoreArgs,\n effectiveInput: JsonValue,\n downstream: () => Promise<AgentInvocationResult>,\n): Promise<AgentInvocationResult> {\n const invokeCtx: AgentInvocationPolicyContext = {\n ...args.policyCtx,\n invocationId: args.invocationId,\n effectiveInput,\n };\n return composeInvokeChain(args.chain, invokeCtx, downstream);\n}\n\nasync function executeObservation(\n internals: RegistryInternals,\n args: CoreArgs,\n cap: ObservationRuntime,\n): Promise<AgentInvocationResult> {\n // Observations skip input parsing, confirmation, and the action queue;\n // their effective input is vacuously {} for phase-6 policies.\n const { reg, invocationId, consumer, consumerKey, host, options, finalize } = args;\n const readCtx: AgentReadContext = {\n capabilityId: cap.capabilityId,\n registrationId: reg.id,\n consumer,\n host,\n };\n const run = async (): Promise<AgentInvocationResult> => {\n /* phase 8 — bounded observation admission (D24) */\n const queueStart = internals.now();\n const slot = await acquireObservationSlot(internals, consumerKey);\n args.setTimings({ queueWaitMs: internals.now() - queueStart });\n if (slot === \"overflow\") {\n return finalize({ status: \"error\", error: queueFull(250) });\n }\n if (slot === \"cancelled\") {\n return finalize({\n status: \"error\",\n error: { ...cancelled(\"The registry was disposed.\"), retry: \"no\" },\n });\n }\n try {\n const timeoutMs =\n options?.timeoutMs ?? cap.timeoutMs ?? internals.limits.observationTimeoutMs;\n const executeStart = internals.now();\n const outcome = await executeWithGuards(internals, reg, {\n invocationId,\n capabilityId: cap.capabilityId,\n timeoutMs,\n externalSignal: options?.signal,\n idempotent: true,\n run: () => {\n const live = reg.definition.observations?.[cap.name];\n if (!live) throw new Error(\"observation handler missing\");\n return live.read(readCtx);\n },\n });\n args.setTimings({ executionMs: internals.now() - executeStart });\n if (!outcome.ok) return finalize({ status: \"error\", error: outcome.payload });\n const output = settleOutput(internals, outcome.value, cap.outputSchema);\n if (\"error\" in output) return finalize({ status: \"error\", error: output.error });\n return finalize({ status: \"ok\", output: output.value });\n } finally {\n releaseObservationSlot(internals, consumerKey);\n }\n };\n return runInvokePolicies(args, {}, run);\n}\n\nasync function executeAction(\n internals: RegistryInternals,\n args: CoreArgs,\n cap: ActionRuntime,\n): Promise<AgentInvocationResult> {\n const { request, reg, invocationId, consumer, host, options, finalize } = args;\n\n /* phase 5 — validated effective input */\n let parsedInput: JsonValue;\n try {\n parsedInput = cap.inputSchema.parse(request.input) as JsonValue;\n } catch (err) {\n return finalize({ status: \"error\", error: invalidInput(err) });\n }\n args.setAuditPayload(parsedInput, undefined);\n\n const readCtx: AgentReadContext = {\n capabilityId: cap.capabilityId,\n registrationId: reg.id,\n consumer,\n host,\n };\n\n const run = async (): Promise<AgentInvocationResult> => {\n /* phase 6 (tail) — confirmation decision over the effective input */\n const confirmation = gateConfirmation(internals, {\n ...args,\n effectiveInput: parsedInput,\n declared: cap.confirmation,\n description: cap.description,\n effect: cap.effect,\n });\n if (\"error\" in confirmation) return finalize({ status: \"error\", error: confirmation.error });\n\n /* phase 7 — precondition */\n const livePrecondition = reg.definition.actions?.[cap.name]?.precondition;\n if (livePrecondition) {\n try {\n const failure = livePrecondition(parsedInput, readCtx);\n if (failure && typeof failure.message === \"string\") {\n return finalize({\n status: \"error\",\n error: preconditionFailed(failure.message, failure.details),\n });\n }\n } catch (err) {\n if (isAgentSurfaceError(err)) return finalize({ status: \"error\", error: err.payload });\n if (\n !(err instanceof Error) &&\n typeof err === \"object\" &&\n err !== null &&\n typeof (err as { message?: unknown }).message === \"string\"\n ) {\n const failure = err as { message: string; details?: Record<string, JsonValue> };\n return finalize({\n status: \"error\",\n error: preconditionFailed(failure.message, failure.details),\n });\n }\n internals.devError(`[agent-surface] precondition threw for ${cap.capabilityId}`, err);\n return finalize({ status: \"error\", error: executionFailed(\"handler-error\") });\n }\n }\n\n /* phase 8 — concurrency: per-group admission, default per instance (D13/D25) */\n const queueStart = internals.now();\n const slot = await acquireActionSlot(internals, reg, cap);\n args.setTimings({ queueWaitMs: internals.now() - queueStart });\n if (slot === \"overflow\") {\n return finalize({ status: \"error\", error: queueFull(250) });\n }\n\n try {\n /* phase 9 — execute; navigation actions settle on handler settlement (D23) */\n const timeoutMs = options?.timeoutMs ?? cap.timeoutMs ?? internals.limits.actionTimeoutMs;\n const executeStart = internals.now();\n const outcome = await executeWithGuards(internals, reg, {\n invocationId,\n capabilityId: cap.capabilityId,\n timeoutMs,\n externalSignal: options?.signal,\n idempotent: cap.idempotent,\n navigationSettlement: cap.effect === \"navigation\",\n run: (signal) => {\n const live = reg.definition.actions?.[cap.name];\n if (!live) throw new Error(\"action handler missing\");\n const actionCtx: AgentActionContext = {\n ...readCtx,\n invocationId,\n signal,\n ...(confirmation.evidence ? { confirmation: confirmation.evidence } : {}),\n };\n return live.execute(parsedInput, actionCtx);\n },\n });\n args.setTimings({ executionMs: internals.now() - executeStart });\n if (!outcome.ok) return finalize({ status: \"error\", error: outcome.payload });\n\n /* phase 10 — settle */\n const output = settleOutput(internals, outcome.value, cap.outputSchema);\n if (\"error\" in output) return finalize({ status: \"error\", error: output.error });\n args.setAuditPayload(undefined, output.value);\n return finalize({ status: \"ok\", output: output.value });\n } finally {\n releaseActionSlot(internals, reg, cap);\n }\n };\n return runInvokePolicies(args, parsedInput, run);\n}\n\nasync function executeProcedure(\n internals: RegistryInternals,\n args: CoreArgs,\n cap: ProcedureRuntime,\n): Promise<AgentInvocationResult> {\n const { request, reg, invocationId, consumer, options, finalize } = args;\n\n /* phase 5 — validated effective input:\n locked-field rejection → reduced parse → bind → merge → full-schema parse */\n const agentInput = (request.input ?? {}) as Record<string, JsonValue>;\n if (typeof agentInput !== \"object\" || agentInput === null || Array.isArray(agentInput)) {\n return finalize({\n status: \"error\",\n error: invalidInput(new AgentSchemaError([{ path: \"\", message: \"input must be an object\" }])),\n });\n }\n const suppliedLocked = Object.keys(agentInput).filter((k) => cap.lockedKeys.includes(k));\n if (suppliedLocked.length > 0) {\n return finalize({\n status: \"error\",\n error: {\n code: \"INVALID_INPUT\",\n message:\n \"Some fields are bound to the application's UI state and cannot be supplied by the agent. Omit them and retry.\",\n retry: \"with-changes\",\n details: { lockedFields: suppliedLocked },\n },\n });\n }\n try {\n fromJsonSchema(cap.reducedInputSchema).parse(agentInput);\n } catch (err) {\n return finalize({ status: \"error\", error: invalidInput(err) });\n }\n\n // bind() runs at EXECUTION time on live UI state (docs/05 rule 4).\n let bound: Record<string, JsonValue> = {};\n const bind = cap.binding.config.bind;\n if (bind) {\n try {\n bound = bind() ?? {};\n } catch (err) {\n internals.devWarn(`[agent-surface] bind() threw for ${cap.capabilityId}`, err);\n return finalize({ status: \"error\", error: bindingFailed() });\n }\n }\n\n const effective: Record<string, JsonValue> = {};\n for (const [key, value] of Object.entries(agentInput)) {\n if (!cap.lockedKeys.includes(key)) effective[key] = value;\n }\n for (const key of cap.boundKeys) {\n const agentSupplied = cap.overridableKeys.has(key) && agentInput[key] !== undefined;\n if (!agentSupplied && bound[key] !== undefined) effective[key] = bound[key] as JsonValue;\n }\n\n // Merged object is validated against the FULL original schema (docs/05 rule 5):\n // the agent's part already validated, so a failure here is a binding bug.\n try {\n fromJsonSchema(cap.fullInputSchema).parse(effective);\n } catch (err) {\n internals.devWarn(\n `[agent-surface] merged input for ${cap.capabilityId} failed full-schema validation`,\n err,\n );\n return finalize({ status: \"error\", error: bindingFailed() });\n }\n args.setAuditPayload(effective, undefined);\n\n const run = async (): Promise<AgentInvocationResult> => {\n /* phase 6 (tail) — confirmation decision over the effective input */\n const confirmation = gateConfirmation(internals, {\n ...args,\n effectiveInput: effective,\n declared: cap.confirmationFloor,\n description: cap.baseDescription,\n effect: cap.effect,\n });\n if (\"error\" in confirmation) return finalize({ status: \"error\", error: confirmation.error });\n\n /* phase 8 — concurrency: one group per procedure identity by default (D25) */\n const queueStart = internals.now();\n const slot = await acquireActionSlot(internals, reg, cap);\n args.setTimings({ queueWaitMs: internals.now() - queueStart });\n if (slot === \"overflow\") {\n return finalize({ status: \"error\", error: queueFull(250) });\n }\n\n try {\n /* phase 9 — forward to the executor (the server re-validates everything) */\n const executor = internals.executor;\n if (!executor) {\n return finalize({ status: \"error\", error: executionFailed(\"transport\") });\n }\n const timeoutMs = options?.timeoutMs ?? internals.limits.procedureTimeoutMs;\n const executeStart = internals.now();\n const outcome = await executeWithGuards(internals, reg, {\n invocationId,\n capabilityId: cap.capabilityId,\n timeoutMs,\n externalSignal: options?.signal,\n idempotent: cap.idempotent,\n run: (signal) =>\n executor.execute({\n path: cap.path,\n input: effective,\n info: {\n invocationId,\n consumer,\n signal,\n ...(confirmation.evidence ? { confirmation: confirmation.evidence } : {}),\n },\n }),\n procedureErrors: true,\n });\n args.setTimings({ executionMs: internals.now() - executeStart });\n if (!outcome.ok) return finalize({ status: \"error\", error: outcome.payload });\n\n /* phase 10 — settle */\n const output = settleOutput(\n internals,\n outcome.value,\n cap.outputJsonSchema ? fromJsonSchema(cap.outputJsonSchema) : undefined,\n );\n if (\"error\" in output) return finalize({ status: \"error\", error: output.error });\n args.setAuditPayload(undefined, output.value);\n return finalize({ status: \"ok\", output: output.value });\n } finally {\n releaseActionSlot(internals, reg, cap);\n }\n };\n return runInvokePolicies(args, effective, run);\n}\n\n/* ───────────────────── confirmation gate (docs/06, D21) ───────────────────── */\n\nfunction gateConfirmation(\n internals: RegistryInternals,\n args: CoreArgs & {\n effectiveInput: JsonValue;\n declared: \"never\" | \"optional\" | \"required\";\n description: string;\n effect: string;\n },\n):\n | { evidence?: { id: string; approvedAt: string } }\n | { error: AgentCapabilityErrorPayload } {\n const { request, reg, cap, consumerKey, escalations, effectiveInput, declared } = args;\n\n const activeEscalations = escalations.filter((e) => {\n if (!e.if) return true;\n try {\n return e.if({ ...args.policyCtx, effectiveInput });\n } catch {\n return true; // fail closed: a broken condition still confirms\n }\n });\n const effective = maxConfirmation(declared, activeEscalations.length > 0 ? \"required\" : \"never\");\n if (effective !== \"required\") return {};\n\n const summaryComposer = activeEscalations.find((e) => e.summary)?.summary;\n let summary: string;\n try {\n summary = summaryComposer\n ? summaryComposer(effectiveInput)\n : `${args.description} — input: ${JSON.stringify(effectiveInput)}`;\n } catch {\n summary = args.description;\n }\n summary = truncate(summary, 300);\n\n // Canonical request digest (D21): what the user approves is exactly what\n // executes. The canonical string itself is the digest — comparison stays\n // exact-value, never hash-only.\n const digest = canonicalJson({\n surfaceId: internals.surfaceId,\n registrationId: reg.id,\n capabilityId: cap.capabilityId,\n consumerKey,\n effectiveInput,\n effect: args.effect,\n });\n\n if (request.confirmationId) {\n const consumed = internals.confirmations.consume({\n confirmationId: request.confirmationId,\n digest,\n input: effectiveInput,\n });\n if (consumed.ok) {\n return { evidence: { id: request.confirmationId, approvedAt: consumed.approvedAt } };\n }\n if (consumed.kind === \"pending-again\") {\n return { error: confirmationRequired(consumed.record, args.effect) };\n }\n return {\n error: {\n code: \"CONFIRMATION_INVALID\",\n message:\n consumed.reason === \"denied\"\n ? \"The user declined this action. Do not retry; respect the decision.\"\n : consumed.reason === \"expired\"\n ? \"The confirmation expired. Request a fresh confirmation.\"\n : consumed.reason === \"consumed\"\n ? \"This confirmation was already used. Request a fresh confirmation if the action is still needed.\"\n : \"The confirmation does not match this exact invocation.\",\n retry: consumed.reason === \"expired\" ? \"with-confirmation\" : \"no\",\n details: { reason: consumed.reason },\n },\n };\n }\n\n const record = internals.confirmations.request({\n capabilityId: cap.capabilityId,\n registrationId: reg.id,\n consumerKey,\n effect: args.policyCtx.effect,\n input: effectiveInput,\n summary,\n digest,\n });\n if (record === \"overflow\") {\n // Bounded pending store (D24): fail closed, no record created.\n return { error: queueFull(1000) };\n }\n return { error: confirmationRequired(record, args.effect) };\n}\n\nfunction confirmationRequired(\n record: { confirmationId: string; summary: string; expiresAt: string },\n effect: string,\n): AgentCapabilityErrorPayload {\n return {\n code: \"CONFIRMATION_REQUIRED\",\n message:\n \"User approval is required for this action. Wait for the user to resolve the confirmation, then retry with the confirmationId.\",\n retry: \"with-confirmation\",\n details: {\n confirmationId: record.confirmationId,\n summary: record.summary,\n expiresAt: record.expiresAt,\n effect,\n origin: \"client\",\n },\n };\n}\n\n/* ───────────────────── shared input/output helpers ───────────────────── */\n\nfunction invalidInput(err: unknown): AgentCapabilityErrorPayload {\n const issues =\n err instanceof AgentSchemaError\n ? err.issues.map((i) => ({ path: i.path, message: i.message }))\n : [{ path: \"\", message: \"Input failed schema validation\" }];\n return {\n code: \"INVALID_INPUT\",\n message: \"The input does not match the capability's schema. Fix the listed issues and retry.\",\n retry: \"with-changes\",\n details: { issues },\n };\n}\n\nfunction preconditionFailed(\n message: string,\n details?: Record<string, JsonValue>,\n): AgentCapabilityErrorPayload {\n return {\n code: \"PRECONDITION_FAILED\",\n message: truncate(message, 300),\n retry: \"with-changes\",\n ...(details ? { details } : {}),\n };\n}\n\nfunction bindingFailed(): AgentCapabilityErrorPayload {\n return {\n code: \"PRECONDITION_FAILED\",\n message:\n \"The UI-derived input binding could not be evaluated. Refresh the surface and check availability before retrying.\",\n retry: \"after-refresh\",\n details: { reason: \"binding-failed\" },\n };\n}\n\nfunction settleOutput(\n internals: RegistryInternals,\n value: unknown,\n schema: { parse(v: unknown): unknown } | undefined,\n): { value?: JsonValue } | { error: AgentCapabilityErrorPayload } {\n if (value === undefined) return {};\n let parsed: unknown = value;\n if (schema) {\n try {\n parsed = schema.parse(value);\n } catch (err) {\n internals.devError(\"[agent-surface] output failed schema validation\", err);\n return { error: executionFailed(\"output-invalid\") };\n }\n }\n if (!isJsonValue(parsed)) {\n if (internals.environment !== \"production\") {\n throw new DevDefectError(\n \"capability output is not a JsonValue (functions, symbols, bigints, Dates, or cycles are defects — docs/03 §serialization)\",\n );\n }\n return { error: executionFailed(\"output-invalid\") };\n }\n let serialized: string;\n try {\n serialized = JSON.stringify(parsed);\n } catch {\n if (internals.environment !== \"production\") {\n throw new DevDefectError(\"capability output cannot be serialized to JSON\");\n }\n return { error: executionFailed(\"output-invalid\") };\n }\n if (serialized.length > internals.limits.maxOutputBytes) {\n return { error: executionFailed(\"output-too-large\") };\n }\n return { value: parsed as JsonValue };\n}\n\n/* ─────────────── execution guards: timeout/abort/unmount (D16/D23) ─────────────── */\n\ntype ExecutionOutcome =\n | { ok: true; value: unknown }\n | { ok: false; payload: AgentCapabilityErrorPayload };\n\nfunction executeWithGuards(\n internals: RegistryInternals,\n reg: InternalRegistration,\n opts: {\n invocationId: string;\n capabilityId: string;\n timeoutMs: number;\n externalSignal: AbortSignal | undefined;\n idempotent: boolean;\n run: (signal: AbortSignal) => unknown;\n procedureErrors?: boolean;\n /** D23: unregistration aborts the signal but never settles the invocation. */\n navigationSettlement?: boolean;\n },\n): Promise<ExecutionOutcome> {\n return new Promise((resolve) => {\n const controller = new AbortController();\n let settled = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const entry: InFlightEntry = {\n onUnregister() {\n controller.abort();\n if (!opts.navigationSettlement) {\n finish({ ok: false, payload: unmounted(\"mid-flight\") });\n }\n // Navigation invocations settle on handler settlement/timeout/cancel\n // only — a committed transition must not be overwritten (AS-NAV-001).\n },\n onDispose() {\n controller.abort();\n finish({\n ok: false,\n payload: { code: \"CANCELLED\", message: \"The registry was disposed.\", retry: \"no\" },\n });\n },\n };\n\n const onExternalAbort = (): void => {\n controller.abort();\n finish({\n ok: false,\n payload: cancelled(\"The invocation was cancelled by the host.\"),\n });\n };\n\n const finish = (outcome: ExecutionOutcome): boolean => {\n if (settled) return false;\n settled = true;\n if (timer !== undefined) clearTimeout(timer);\n reg.inFlight.delete(entry);\n opts.externalSignal?.removeEventListener(\"abort\", onExternalAbort);\n resolve(outcome);\n return true;\n };\n\n const lateSettlement = (): void => {\n internals.recordAudit({\n type: \"late-settlement\",\n capabilityId: opts.capabilityId,\n registrationId: reg.id,\n invocationId: opts.invocationId,\n });\n };\n\n const handlerError = (err: unknown): ExecutionOutcome => {\n if (isAgentSurfaceError(err)) return { ok: false, payload: err.payload };\n // D23: a navigation handler rejecting after its signal was aborted\n // abandoned the transition — that is a cancellation, not a failure.\n if (opts.navigationSettlement && controller.signal.aborted) {\n return { ok: false, payload: cancelled(\"The navigation was abandoned after its owner unmounted.\") };\n }\n internals.devError(`[agent-surface] handler failed for ${opts.capabilityId}`, err);\n return {\n ok: false,\n payload: executionFailed(opts.procedureErrors ? \"transport\" : \"handler-error\", {\n transient:\n opts.procedureErrors === true &&\n typeof err === \"object\" &&\n err !== null &&\n (err as { transient?: unknown }).transient === true,\n }),\n };\n };\n\n // The pipeline is async: the registration may have died (or the registry\n // been disposed) between resolution and execution. Re-check here.\n if (internals.disposed) {\n resolve({\n ok: false,\n payload: { code: \"CANCELLED\", message: \"The registry was disposed.\", retry: \"no\" },\n });\n return;\n }\n if (reg.status !== \"active\") {\n resolve({ ok: false, payload: unmounted(\"mid-flight\") });\n return;\n }\n if (opts.externalSignal?.aborted) {\n resolve({\n ok: false,\n payload: cancelled(\"The invocation was cancelled by the host.\"),\n });\n return;\n }\n opts.externalSignal?.addEventListener(\"abort\", onExternalAbort, { once: true });\n\n timer = setTimeout(() => {\n controller.abort();\n finish({\n ok: false,\n payload: {\n code: \"TIMEOUT\",\n message: opts.idempotent\n ? \"The capability timed out. It is idempotent; retrying with a new invocationId is safe.\"\n : \"The capability timed out and side effects may or may not have occurred. Verify state with an observation before repeating.\",\n retry: opts.idempotent ? \"yes\" : \"no\",\n details: { timeoutMs: opts.timeoutMs, idempotent: opts.idempotent },\n },\n });\n }, opts.timeoutMs);\n\n reg.inFlight.add(entry);\n\n let returned: unknown;\n try {\n returned = opts.run(controller.signal);\n } catch (err) {\n finish(handlerError(err));\n return;\n }\n\n if (\n returned !== null &&\n (typeof returned === \"object\" || typeof returned === \"function\") &&\n typeof (returned as PromiseLike<unknown>).then === \"function\"\n ) {\n (returned as Promise<unknown>).then(\n (value) => {\n if (!finish({ ok: true, value })) lateSettlement();\n },\n (err) => {\n if (!finish(handlerError(err))) lateSettlement();\n },\n );\n } else {\n // Synchronous completion settles before any unmount abort (D16).\n finish({ ok: true, value: returned });\n }\n });\n}\n\n/* ─────────────── action serialization per component instance (D13) ─────────────── */\n\nasync function acquireActionSlot(\n internals: RegistryInternals,\n reg: InternalRegistration,\n cap: ActionRuntime | ProcedureRuntime,\n): Promise<\"ok\" | \"overflow\"> {\n const { key, max, depth } = concurrencyGroupFor(cap, internals.limits);\n let group = reg.concurrencyGroups.get(key);\n if (!group) {\n group = { running: 0, max, depth, waiting: [] };\n reg.concurrencyGroups.set(key, group);\n }\n if (group.running < group.max) {\n group.running += 1;\n return \"ok\";\n }\n if (group.waiting.length >= group.depth) {\n // Nothing was reserved, so an idle group must not linger in the map.\n if (group.running === 0 && group.waiting.length === 0) reg.concurrencyGroups.delete(key);\n return \"overflow\";\n }\n await new Promise<void>((resolve) => group.waiting.push(resolve));\n return \"ok\"; // the releasing invocation hands the slot over\n}\n\nfunction releaseActionSlot(\n internals: RegistryInternals,\n reg: InternalRegistration,\n cap: ActionRuntime | ProcedureRuntime,\n): void {\n const { key } = concurrencyGroupFor(cap, internals.limits);\n const group = reg.concurrencyGroups.get(key);\n if (!group) return;\n const next = group.waiting.shift();\n // A handed-over slot stays counted: `running` never dips between the two.\n if (!next) group.running -= 1;\n else next();\n if (group.running === 0 && group.waiting.length === 0) reg.concurrencyGroups.delete(key);\n}\n\n/* ─────────────── bounded observation admission per consumer (D24) ─────────────── */\n\nfunction acquireObservationSlot(\n internals: RegistryInternals,\n consumerKey: string,\n): Promise<\"ok\" | \"overflow\" | \"cancelled\"> {\n const adm = internals.observationAdmission;\n const perCap = internals.limits.maxConcurrentObservationsPerConsumer;\n const totalCap = internals.limits.maxConcurrentObservationsTotal;\n const held = adm.perConsumer.get(consumerKey) ?? 0;\n if (held < perCap && adm.total < totalCap) {\n adm.perConsumer.set(consumerKey, held + 1);\n adm.total += 1;\n return Promise.resolve(\"ok\");\n }\n let queued = 0;\n for (const waiter of adm.waiting) {\n if (waiter.consumerKey === consumerKey) queued += 1;\n }\n if (queued >= internals.limits.maxQueuedObservationsPerConsumer) {\n return Promise.resolve(\"overflow\");\n }\n return new Promise((resolve) => {\n adm.waiting.push({\n consumerKey,\n admit: (admitted) => resolve(admitted ? \"ok\" : \"cancelled\"),\n });\n });\n}\n\nfunction releaseObservationSlot(internals: RegistryInternals, consumerKey: string): void {\n const adm = internals.observationAdmission;\n adm.total = Math.max(0, adm.total - 1);\n const held = adm.perConsumer.get(consumerKey) ?? 0;\n if (held <= 1) adm.perConsumer.delete(consumerKey);\n else adm.perConsumer.set(consumerKey, held - 1);\n\n // Wake the first arrival-ordered waiter whose consumer is under its cap:\n // FIFO within a consumer, no cross-consumer starvation (AS-OBS-002).\n const perCap = internals.limits.maxConcurrentObservationsPerConsumer;\n const totalCap = internals.limits.maxConcurrentObservationsTotal;\n for (let i = 0; i < adm.waiting.length; i++) {\n const waiter = adm.waiting[i];\n if (!waiter) continue;\n const waiterHeld = adm.perConsumer.get(waiter.consumerKey) ?? 0;\n if (waiterHeld < perCap && adm.total < totalCap) {\n adm.waiting.splice(i, 1);\n adm.perConsumer.set(waiter.consumerKey, waiterHeld + 1);\n adm.total += 1;\n waiter.admit(true);\n return;\n }\n }\n}\n\n/** Dispose path: drain queued observation waiters as cancelled (leak-free). */\nexport function drainObservationQueues(internals: RegistryInternals): void {\n const adm = internals.observationAdmission;\n const waiting = adm.waiting.splice(0);\n for (const waiter of waiting) waiter.admit(false);\n}\n","import type {\n AgentEnvironment,\n AgentRouteInfo,\n AgentSurfaceLimits,\n} from \"./types.js\";\nimport { DEFAULT_LIMITS, type Unsubscribe } from \"./types.js\";\nimport type {\n AgentComponentDefinition,\n AgentProcedureExecutor,\n} from \"./definition.js\";\nimport { validateComponentDefinition } from \"./definition.js\";\nimport type { AgentPolicy } from \"./policy.js\";\nimport type { AuditSink, AuditEvent } from \"./audit.js\";\nimport { consoleAuditSink, memoryAuditSink, safeRecord } from \"./audit.js\";\nimport { EventDispatcher, type AgentSurfaceEvent } from \"./events.js\";\nimport { ConfirmationStore, type ConfirmationController } from \"./confirmation.js\";\nimport type { AgentInvocation, AgentInvocationResult, InvokeOptions } from \"./invocation-types.js\";\nimport { drainObservationQueues, performInvoke } from \"./invoke.js\";\nimport { createSnapshot, type AgentSurfaceSnapshot, type SnapshotContext } from \"./snapshot.js\";\nimport {\n DEV_WARN,\n INTERNALS,\n addTombstone,\n componentKey,\n nextRegistrationId,\n normalizeRegistration,\n type InternalRegistration,\n type RegistryInternals,\n} from \"./internal.js\";\nimport { AgentSurfaceDefinitionError } from \"./errors.js\";\nimport { formatViewCapabilityId } from \"./ids.js\";\nimport { randomBase62 } from \"./utils.js\";\n\nexport interface RegistrationCandidate {\n definition: AgentComponentDefinition; // includes origin (default \"first-party\")\n stack?: string; // dev-mode capture for diagnostics\n}\n\nexport interface RegistryOptions {\n /** \"development\" | \"production\" | \"test\". Default: \"production\". */\n environment?: AgentEnvironment;\n /** Host context provider. MUST be synchronous and cheap. */\n context?: () => Record<string, unknown>;\n /** Global policies, outermost layer of every chain. */\n policies?: AgentPolicy[];\n /** Audit sink; default: bounded in-memory sink (+ console in development). */\n audit?: AuditSink;\n /** Guard invoked before accepting a registration (trust filtering, docs/06). */\n onRegister?: (candidate: RegistrationCandidate) => \"accept\" | \"reject\";\n /** Collision handling for duplicate (type, instanceId). Default \"reject\". */\n onDuplicateInstance?: \"reject\" | \"replace\";\n /** Suffix-collision diagnostics vs known domain ids. Default \"warn\". */\n duplicateSuffixPolicy?: \"off\" | \"warn\" | \"error\";\n /** Route descriptor for snapshots (host wires its router here). */\n route?: () => AgentRouteInfo | undefined;\n limits?: Partial<AgentSurfaceLimits>;\n /** Injectable clock (docs/08 determinism); default Date.now. */\n now?: () => number;\n}\n\nexport interface AgentRegistrationHandle {\n readonly registrationId: string; // \"reg_\" + monotonic + random\n readonly status: \"active\" | \"rejected\" | \"unregistered\";\n /** Push dynamic updates; only these fields are updatable (D2). */\n update(patch: {\n enabled?: boolean;\n availability?: Record<string, { available: boolean; reason?: string }>;\n }): void;\n /** Bumps the surface version without changing anything. */\n invalidate(): void;\n unregister(): void;\n}\n\nexport interface AgentSurfaceRegistry {\n readonly surfaceId: string; // \"srf_\" + random, per instance\n register(definition: AgentComponentDefinition): AgentRegistrationHandle;\n snapshot(context?: SnapshotContext): AgentSurfaceSnapshot; // synchronous\n invoke(request: AgentInvocation, options?: InvokeOptions): Promise<AgentInvocationResult>;\n subscribe(listener: (event: AgentSurfaceEvent) => void): Unsubscribe;\n confirmations: ConfirmationController;\n /** Register a domain-procedure executor (installed by @agent-surface/orpc). */\n setProcedureExecutor(executor: AgentProcedureExecutor | undefined): void;\n getVersion(): string;\n /** Tears down: aborts in-flight invocations (CANCELLED), clears listeners. */\n dispose(): void;\n}\n\nexport function createAgentSurfaceRegistry(options?: RegistryOptions): AgentSurfaceRegistry {\n const environment = options?.environment ?? \"production\";\n const limits: AgentSurfaceLimits = { ...DEFAULT_LIMITS, ...(options?.limits ?? {}) };\n const now = options?.now ?? (() => Date.now());\n const auditSink: AuditSink =\n options?.audit ??\n (environment === \"development\"\n ? combineSinks(memoryAuditSink(), consoleAuditSink())\n : memoryAuditSink());\n\n let surfaceChangedScheduled = false;\n\n const dispatcher = new EventDispatcher((err) => {\n if (environment === \"development\") {\n // eslint-disable-next-line no-console\n console.error(\"[agent-surface] event listener threw\", err);\n }\n });\n\n const internals: RegistryInternals = {\n environment,\n limits,\n surfaceId: `srf_${randomBase62(22)}`,\n version: 0,\n registrations: new Map(),\n byKey: new Map(),\n tombstones: new Map(),\n dedupe: new Map(),\n observationAdmission: { total: 0, perConsumer: new Map(), waiting: [] },\n dispatcher,\n confirmations: undefined as unknown as ConfirmationStore, // set below\n executor: undefined,\n disposed: false,\n registryPolicies: [...(options?.policies ?? [])],\n auditSink,\n contextFn: options?.context,\n routeFn: options?.route,\n now,\n bumpVersion() {\n internals.version += 1;\n if (!surfaceChangedScheduled) {\n surfaceChangedScheduled = true;\n queueMicrotask(() => {\n surfaceChangedScheduled = false;\n if (internals.disposed) return;\n internals.emit({ type: \"surface-changed\", surfaceVersion: String(internals.version) });\n });\n }\n },\n emit(event) {\n dispatcher.emit(event);\n },\n recordAudit(event: Omit<AuditEvent, \"at\">) {\n safeRecord(auditSink, { at: new Date(now()).toISOString(), ...event });\n },\n host() {\n try {\n return internals.contextFn?.() ?? {};\n } catch (err) {\n internals.devWarn(\"[agent-surface] RegistryOptions.context() threw\", err);\n return {};\n }\n },\n devWarn(...args) {\n if (environment === \"development\") {\n // eslint-disable-next-line no-console\n console.warn(...args);\n }\n },\n devError(...args) {\n if (environment === \"development\") {\n // eslint-disable-next-line no-console\n console.error(...args);\n }\n },\n };\n\n internals.confirmations = new ConfirmationStore({\n ttlMs: limits.confirmationTtlMs,\n maxPending: limits.maxPendingConfirmations,\n now,\n emit: (event) => internals.emit(event),\n audit: (event) => internals.recordAudit(event),\n });\n\n const onDuplicateInstance = options?.onDuplicateInstance ?? \"reject\";\n const duplicateSuffixPolicy = options?.duplicateSuffixPolicy ?? \"warn\";\n\n function deadHandle(): AgentRegistrationHandle {\n const id = nextRegistrationId(() => randomBase62(6));\n return {\n registrationId: id,\n status: \"rejected\",\n update() {\n internals.devWarn(\"[agent-surface] update() called on a rejected registration handle\");\n },\n invalidate() {\n internals.devWarn(\"[agent-surface] invalidate() called on a rejected registration handle\");\n },\n unregister() {\n /* no-op */\n },\n };\n }\n\n function unregisterInternal(reg: InternalRegistration): void {\n if (reg.status !== \"active\") return;\n reg.status = \"unregistered\";\n internals.registrations.delete(reg.id);\n if (internals.byKey.get(reg.key) === reg.id) internals.byKey.delete(reg.key);\n addTombstone(internals, reg);\n // Abort in-flight invocations: non-navigation ones settle\n // COMPONENT_UNMOUNTED unless the handler already settled (first settle\n // wins, D16); navigation ones only lose their signal and settle on\n // handler settlement (D23).\n for (const entry of [...reg.inFlight]) {\n entry.onUnregister();\n }\n internals.bumpVersion();\n internals.emit({\n type: \"component-unregistered\",\n registrationId: reg.id,\n componentType: reg.type,\n instanceId: reg.instanceId,\n });\n internals.recordAudit({\n type: \"unregistration\",\n registrationId: reg.id,\n capabilityId: undefined,\n });\n }\n\n function checkSuffixCollisions(def: AgentComponentDefinition): void {\n if (duplicateSuffixPolicy === \"off\") return;\n const paths = internals.executor?.paths;\n if (!paths || paths.length === 0) return;\n const names = [\n ...Object.keys(def.observations ?? {}),\n ...Object.keys(def.actions ?? {}),\n ];\n for (const name of names) {\n const candidatePath = `${def.type}.${name}`;\n if (paths.includes(candidatePath)) {\n const viewCapabilityId = formatViewCapabilityId(def.type, name);\n const domainProcedureId = `domain:${candidatePath}`;\n if (duplicateSuffixPolicy === \"error\") {\n throw new AgentSurfaceDefinitionError(\n \"PLANE_VIOLATION\",\n `view capability \"${viewCapabilityId}\" collides with domain procedure \"${domainProcedureId}\" — reference the procedure instead of redefining it (docs/05)`,\n );\n }\n internals.devWarn(\n `[agent-surface] suspicious suffix collision: \"${viewCapabilityId}\" vs \"${domainProcedureId}\"`,\n );\n internals.emit({ type: \"collision-suspected\", viewCapabilityId, domainProcedureId });\n internals.recordAudit({\n type: \"collision-suspected\",\n capabilityId: viewCapabilityId,\n });\n }\n }\n }\n\n const registry: AgentSurfaceRegistry = {\n surfaceId: internals.surfaceId,\n\n register(definition: AgentComponentDefinition): AgentRegistrationHandle {\n if (internals.disposed) throw new Error(\"register() called on a disposed registry\");\n\n // Structural defects throw in EVERY environment (docs/03 §registry, D4).\n validateComponentDefinition(definition, limits, {\n hasProcedureExecutor: internals.executor !== undefined,\n });\n checkSuffixCollisions(definition);\n\n const instanceId = definition.instanceId ?? \"default\";\n\n // Runtime conditions produce dead handles, never throws (D4).\n if (options?.onRegister) {\n let verdict: \"accept\" | \"reject\" = \"accept\";\n try {\n verdict = options.onRegister({\n definition,\n ...(environment === \"development\" ? { stack: new Error().stack } : {}),\n });\n } catch (err) {\n internals.devError(\"[agent-surface] onRegister guard threw; rejecting\", err);\n verdict = \"reject\";\n }\n if (verdict === \"reject\") {\n internals.emit({\n type: \"component-rejected\",\n componentType: definition.type,\n instanceId,\n reason: \"guard\",\n });\n internals.recordAudit({ type: \"registration-rejected\" });\n internals.devError(\n `[agent-surface] registration of \"${definition.type}\" (${instanceId}) rejected by guard`,\n );\n return deadHandle();\n }\n }\n\n const key = componentKey(definition.type, instanceId);\n const existingId = internals.byKey.get(key);\n if (existingId !== undefined) {\n if (onDuplicateInstance === \"reject\") {\n internals.emit({\n type: \"component-rejected\",\n componentType: definition.type,\n instanceId,\n reason: \"duplicate\",\n });\n internals.recordAudit({ type: \"registration-rejected\" });\n internals.devError(\n `[agent-surface] duplicate registration of \"${definition.type}\" (${instanceId}); first-wins (onDuplicateInstance: \"reject\")`,\n );\n return deadHandle();\n }\n const existing = internals.registrations.get(existingId);\n if (existing) unregisterInternal(existing);\n }\n\n const reg = normalizeRegistration(definition, nextRegistrationId(() => randomBase62(6)));\n internals.registrations.set(reg.id, reg);\n internals.byKey.set(reg.key, reg.id);\n internals.bumpVersion();\n internals.emit({\n type: \"component-registered\",\n registrationId: reg.id,\n componentType: reg.type,\n instanceId: reg.instanceId,\n });\n internals.recordAudit({ type: \"registration\", registrationId: reg.id });\n\n return {\n get registrationId() {\n return reg.id;\n },\n get status() {\n return reg.status === \"active\" ? (\"active\" as const) : (\"unregistered\" as const);\n },\n update(patch) {\n if (reg.status !== \"active\") {\n internals.devWarn(\n `[agent-surface] update() called after unregistration of \"${reg.type}\"`,\n );\n return;\n }\n let changed = false;\n if (patch.enabled !== undefined && patch.enabled !== reg.enabled) {\n reg.enabled = patch.enabled;\n changed = true;\n }\n if (patch.availability) {\n for (const [name, value] of Object.entries(patch.availability)) {\n const prev = reg.availabilityOverrides.get(name);\n if (!prev || prev.available !== value.available || prev.reason !== value.reason) {\n reg.availabilityOverrides.set(name, {\n available: value.available,\n ...(value.reason !== undefined ? { reason: value.reason } : {}),\n });\n changed = true;\n const capabilityId =\n reg.observations.get(name)?.capabilityId ??\n reg.actions.get(name)?.capabilityId ??\n reg.procedures.find((p) => p.path === name)?.capabilityId ??\n name;\n internals.emit({\n type: \"availability-changed\",\n registrationId: reg.id,\n capabilityId,\n available: value.available,\n });\n }\n }\n }\n if (changed) internals.bumpVersion();\n },\n invalidate() {\n if (reg.status !== \"active\") return;\n internals.bumpVersion();\n },\n unregister() {\n unregisterInternal(reg);\n },\n };\n },\n\n snapshot(context?: SnapshotContext): AgentSurfaceSnapshot {\n if (internals.disposed) throw new Error(\"snapshot() called on a disposed registry\");\n return createSnapshot(internals, context);\n },\n\n invoke(request, invokeOptions) {\n return performInvoke(internals, request, invokeOptions);\n },\n\n subscribe(listener) {\n return dispatcher.subscribe(listener);\n },\n\n confirmations: internals.confirmations.controller(),\n\n setProcedureExecutor(executor) {\n internals.executor = executor;\n },\n\n getVersion() {\n return String(internals.version);\n },\n\n dispose() {\n if (internals.disposed) return;\n for (const reg of [...internals.registrations.values()]) {\n for (const entry of [...reg.inFlight]) {\n entry.onDispose();\n }\n reg.status = \"unregistered\";\n }\n drainObservationQueues(internals);\n internals.registrations.clear();\n internals.byKey.clear();\n internals.confirmations.disposeAll();\n internals.disposed = true;\n dispatcher.clear();\n },\n };\n\n // Internal seam (DEV_WARN): adapters in this package report dev-mode repairs\n // through the registry's own environment gate rather than a second one.\n Object.defineProperty(registry, DEV_WARN, {\n value: (...args: unknown[]) => internals.devWarn(...args),\n enumerable: false,\n });\n\n // Internal seam (INTERNALS): read only by `@agent-surface/core/explain`, a\n // separate entry so the developer projection cannot be reached from the\n // package root that adapters import (docs/06 §explain-is-not-agent-facing).\n Object.defineProperty(registry, INTERNALS, {\n value: internals,\n enumerable: false,\n });\n\n return registry;\n}\n\nfunction combineSinks(...sinks: AuditSink[]): AuditSink {\n return {\n record(event) {\n for (const sink of sinks) safeRecord(sink, event);\n },\n };\n}\n","import type { AgentConsumer, JsonSchema, JsonValue, Unsubscribe } from \"./types.js\";\nimport type { AgentSurfaceRegistry } from \"./registry.js\";\nimport type { AgentInvocationResult } from \"./invocation-types.js\";\nimport type { AgentCapabilityErrorPayload } from \"./errors.js\";\nimport type {\n AgentActionDescriptor,\n AgentObservationDescriptor,\n AgentProcedureDescriptor,\n AgentSurfaceSnapshot,\n} from \"./snapshot.js\";\nimport { DEV_WARN, type DevWarnCarrier } from \"./internal.js\";\nimport { assignWireNames, type WireNameEntry } from \"./ids.js\";\nimport { randomBase62 } from \"./utils.js\";\n\nexport interface AgentToolsetOptions {\n consumer: AgentConsumer;\n /**\n * \"direct\": one tool per capability — provider-native input typing, catalog\n * size linear in the surface. \"meta\": three fixed tools with lazy discovery —\n * constant tool-block size, one extra round trip before the first act.\n *\n * [Experimental] applies to \"meta\" only (D29): the three verbs' envelope may\n * change in any release — 0.6 typed `surface_act.input` and started enforcing\n * the verb schemas (D32). \"direct\" is Draft, like the rest of the API.\n *\n * Default \"direct\"; see the selection guide in docs/09 §choosing-a-mode.\n */\n mode?: \"direct\" | \"meta\";\n /**\n * Loop topology (D26). Sets the confirmation-mode default: \"embedded\" →\n * \"wait\", \"remote\" → \"two-phase\". One of `topology` or `confirmations`\n * MUST be provided — there is no ambiguous global default.\n */\n topology?: \"embedded\" | \"remote\";\n /**\n * \"wait\": on CONFIRMATION_REQUIRED, await user resolution (up to TTL) and\n * auto-retry, so the model sees one tool call → one final result.\n * \"two-phase\": surface CONFIRMATION_REQUIRED to the model, which retries.\n * Overrides the topology default (a remote loop opting into \"wait\" owns\n * its transport-timeout story, docs/09 §confirmation-topology).\n */\n confirmations?: \"wait\" | \"two-phase\";\n /**\n * Component-type prefixes this consumer may discover. D27: this is a\n * **floor** — in \"meta\" mode a model-supplied `scope` can only narrow it\n * further, never widen it. Not an authority boundary: `invoke` does not\n * check scope in either mode (docs/09 §scope-is-discovery-only).\n */\n scope?: string[];\n /**\n * [Experimental] Snapshot truncation budget for `surface_discover`.\n * \"meta\" mode only — there the `truncated` marker rides in the payload the\n * model reads. In \"direct\" mode a budget would silently drop tools with no\n * signal to anyone, so it is rejected rather than half-honored.\n */\n budget?: { maxComponents?: number; maxBytes?: number };\n}\n\nexport interface AgentTool {\n /** Wire-safe name (docs/09 §wire-names), ≤ 64 chars, unique in this catalog. */\n name: string;\n /**\n * Plane + effect + confirmation prefix, then the authored description.\n * Contains NO live state (D28), so it is safe in a provider tool block with\n * prompt-prefix caching across steps.\n */\n description: string;\n inputSchema: JsonSchema;\n /**\n * Volatile: re-derived on every snapshot. Hosts render this OUTSIDE the tool\n * block (e.g. a trailing system message) so availability stays honest without\n * invalidating the cached prefix (D28).\n */\n state: {\n available: boolean;\n unavailableReason?: string;\n /** Live text contributed by a contextual binding's `describe()`. */\n note?: string;\n };\n execute(input: JsonValue, call: { toolCallId?: string }): Promise<AgentInvocationResult>;\n}\n\nexport interface AgentToolset {\n tools(): AgentTool[]; // recomputed per surface version\n /**\n * wireName → canonical capability id, for the catalog `tools()` last built.\n * Authoritative: shortened names are not decodable by string surgery, so a\n * host MUST consult this rather than reversing names itself (D30). Empty in\n * \"meta\" mode, whose three tool names are not capability ids.\n */\n wireNameMap(): ReadonlyMap<string, string>;\n /** Fires when tools() would return a different catalog. */\n subscribe(listener: (tools: AgentTool[]) => void): Unsubscribe;\n dispose(): void;\n}\n\ninterface CatalogEntry {\n capabilityId: string;\n /**\n * Omitted when the target is not uniquely resolvable from the snapshot, so\n * the registry's own resolver decides (AMBIGUOUS_INSTANCE / not-found /\n * unmounted). Never send a placeholder: an empty string reads as \"this exact\n * registration\", which resolves to STALE_CAPABILITY and sends the agent into\n * a refresh loop against an unchanged surface (AS-ADAPTER-003).\n */\n registrationId?: string;\n instanceId?: string;\n surfaceVersion: string;\n kind: \"observation\" | \"action\" | \"procedure\";\n}\n\nconst EMPTY_INPUT_SCHEMA: JsonSchema = {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n};\n\n/* ───────────────────────── meta-mode verb schemas ─────────────────────────\n * Module-level constants: the three verbs are the same bytes for every toolset\n * and every mount, which is the property AS-META-005 and D28 pin.\n */\n\nconst META_DISCOVER_SCHEMA: JsonSchema = {\n type: \"object\",\n properties: {\n scope: {\n type: \"array\",\n items: { type: \"string\" },\n // No enum: valid tokens are live component types, and inlining them\n // would make this tool block churn on every mount — the churn\n // AS-META-005 and D28 exist to prevent.\n description:\n 'Component-type prefixes to narrow the result, e.g. [\"devices.table\"], taken from `components[].type` of an earlier call — omit on the first. Narrows only: prefixes outside this host\\'s configured scope match nothing and come back in `scopeRejected`.',\n },\n },\n additionalProperties: false,\n};\n\nconst META_READ_SCHEMA: JsonSchema = {\n type: \"object\",\n properties: {\n capabilityId: {\n type: \"string\",\n description:\n \"Observation id, verbatim from `observations[].capabilityId` in a discover result.\",\n },\n instanceId: {\n type: \"string\",\n description:\n \"Only when several components share a type: `components[].instanceId` picks one.\",\n },\n },\n required: [\"capabilityId\"],\n additionalProperties: false,\n};\n\nconst META_ACT_SCHEMA: JsonSchema = {\n type: \"object\",\n properties: {\n capabilityId: {\n type: \"string\",\n description: \"Action `capabilityId` or `procedureId`, verbatim from a discover result.\",\n },\n instanceId: {\n type: \"string\",\n description:\n \"Only when several components share a type: `components[].instanceId` picks one.\",\n },\n // Typed, and not merely described: an untyped property is the one position\n // a provider's constrained decoder cannot constrain, so the model falls\n // back to its prior — a JSON-encoded string, the shape\n // `function_call.arguments` carries — and sorts the rest of the capability's\n // arguments into the sibling modifiers below. `type: \"object\"` costs\n // nothing in practice: direct mode already passes `act.inputSchema`\n // straight through as the tool schema, and providers require that to be an\n // object schema at the top level. No `additionalProperties` here — the\n // capability's own schema governs what goes inside.\n input: {\n type: \"object\",\n description:\n \"Arguments matching that capability's `inputSchema`, as a JSON object — not a JSON-encoded string. Everything the capability declares goes in here, never beside it.\",\n },\n invocationId: {\n type: \"string\",\n description:\n \"Reuse a previous call's id to retry without executing twice; required when resuming after CONFIRMATION_REQUIRED.\",\n },\n confirmationId: {\n type: \"string\",\n description:\n \"The id returned with CONFIRMATION_REQUIRED, sent back after the user approves.\",\n },\n surfaceVersion: {\n type: \"string\",\n description:\n \"The `surfaceVersion` you planned against. Send it for destructive or externally-visible calls: a surface that moved underneath the plan then fails instead of executing. Omitted, the call binds to what is live now.\",\n },\n },\n required: [\"capabilityId\"],\n additionalProperties: false,\n};\n\n/**\n * Stable properties of the capability — plane, effect, confirmation. Never\n * availability: that is a property of the moment, and folding it in here is\n * what made the tool block churn between steps (D28).\n */\nfunction describePrefix(\n plane: \"view\" | \"domain\",\n effect: string,\n confirmation: \"never\" | \"optional\" | \"required\",\n): string {\n const parts = [plane, effect];\n if (confirmation === \"required\") parts.push(\"requires confirmation\");\n return `[${parts.join(\" · \")}]`;\n}\n\nfunction availabilityState(descriptor: {\n available: boolean;\n unavailableReason?: string;\n contextualNote?: string;\n}): AgentTool[\"state\"] {\n return {\n available: descriptor.available,\n ...(descriptor.unavailableReason !== undefined\n ? { unavailableReason: descriptor.unavailableReason }\n : {}),\n ...(descriptor.contextualNote !== undefined ? { note: descriptor.contextualNote } : {}),\n };\n}\n\nexport function createAgentToolset(\n registry: AgentSurfaceRegistry,\n options: AgentToolsetOptions,\n): AgentToolset {\n const mode = options.mode ?? \"direct\";\n if (options.confirmations === undefined && options.topology === undefined) {\n // D26: no ambiguous global default — programmer misuse, every environment.\n throw new Error(\n \"createAgentToolset: declare a topology ('embedded' | 'remote') or an explicit confirmations mode ('wait' | 'two-phase'). Embedded loops default to 'wait', remote loops to 'two-phase' (docs/09 §confirmation-topology).\",\n );\n }\n if (options.budget !== undefined && mode !== \"meta\") {\n // No silent no-op: in direct mode a budget would drop tools from the\n // catalog with no `truncated` marker anywhere the host or model can see.\n throw new Error(\n \"createAgentToolset: `budget` applies to mode 'meta' only — in 'direct' mode it would silently drop tools. Pass a `scope` to bound a direct catalog instead (docs/09 §meta-tools-mode).\",\n );\n }\n const confirmationsMode =\n options.confirmations ?? (options.topology === \"remote\" ? \"two-phase\" : \"wait\");\n // Dev diagnostics ride the registry's own environment gate (DEV_WARN); a\n // registry built elsewhere (a test double) simply carries none.\n const devWarn = (registry as unknown as DevWarnCarrier)[DEV_WARN] ?? ((): void => {});\n const listeners = new Set<(tools: AgentTool[]) => void>();\n const pendingWaits = new Set<AbortController>();\n let disposed = false;\n let cachedVersion: string | undefined;\n let cachedTools: AgentTool[] | undefined;\n let cachedWireNames: ReadonlyMap<string, string> = new Map();\n let cachedSignature: string | undefined;\n\n /** Wait for a confirmation, abortable by dispose (AS-TOPO-003, D26).\n * The disposed guard covers the window where dispose lands between the\n * CONFIRMATION_REQUIRED result and this wait's registration. */\n async function waitForConfirmation(confirmationId: string): Promise<void> {\n if (disposed) return;\n const controller = new AbortController();\n pendingWaits.add(controller);\n try {\n await registry.confirmations.waitFor(confirmationId, { signal: controller.signal });\n } finally {\n pendingWaits.delete(controller);\n }\n }\n\n async function invokeThroughSurface(\n entry: CatalogEntry,\n input: JsonValue | undefined,\n toolCallId: string | undefined,\n overrides?: { invocationId?: string; confirmationId?: string },\n ): Promise<AgentInvocationResult> {\n const invocationId = overrides?.invocationId ?? toolCallId ?? `inv_${randomBase62(12)}`;\n const base = {\n invocationId,\n capabilityId: entry.capabilityId,\n ...(entry.instanceId !== undefined ? { instanceId: entry.instanceId } : {}),\n ...(entry.registrationId !== undefined ? { registrationId: entry.registrationId } : {}),\n surfaceVersion: entry.surfaceVersion,\n ...(input !== undefined ? { input } : {}),\n ...(overrides?.confirmationId !== undefined\n ? { confirmationId: overrides.confirmationId }\n : {}),\n };\n let result = await registry.invoke(base, { consumer: options.consumer });\n if (\n confirmationsMode === \"wait\" &&\n result.status === \"error\" &&\n result.error.code === \"CONFIRMATION_REQUIRED\"\n ) {\n const confirmationId = result.error.details?.confirmationId;\n if (typeof confirmationId === \"string\") {\n await waitForConfirmation(confirmationId);\n // Deterministic shutdown: a dispose mid-wait returns the pending\n // CONFIRMATION_REQUIRED result as-is (D26).\n if (disposed) return result;\n // Retry reuses the SAME invocationId + confirmationId (docs/03 D14):\n // CONFIRMATION_REQUIRED was not cached as terminal, so this executes.\n result = await registry.invoke(\n { ...base, confirmationId },\n { consumer: options.consumer },\n );\n }\n }\n return result;\n }\n\n function buildDirectTools(): { tools: AgentTool[]; wireNames: ReadonlyMap<string, string> } {\n const snapshot = registry.snapshot({\n consumer: options.consumer,\n ...(options.scope ? { scope: options.scope } : {}),\n includeUnavailable: true,\n });\n\n interface PendingTool {\n wire: WireNameEntry;\n entry: CatalogEntry;\n prefix: string;\n description: string;\n inputSchema: JsonSchema;\n state: AgentTool[\"state\"];\n }\n const pending: PendingTool[] = [];\n\n const push = (\n capabilityId: string,\n kind: CatalogEntry[\"kind\"],\n registrationId: string,\n instanceId: string | undefined,\n prefix: string,\n description: string,\n inputSchema: JsonSchema,\n state: AgentTool[\"state\"],\n nameSuffix?: string,\n ): void => {\n const suffix = nameSuffix ?? instanceId;\n pending.push({\n // Providers require unique tool names: multi-instance capabilities\n // are disambiguated with an `_at_<instance>` suffix (docs/09).\n wire: { id: capabilityId, ...(suffix !== undefined ? { instanceId: suffix } : {}) },\n entry: {\n capabilityId,\n registrationId,\n ...(instanceId !== undefined ? { instanceId } : {}),\n surfaceVersion: snapshot.surfaceVersion,\n kind,\n },\n prefix,\n description,\n inputSchema,\n state,\n });\n };\n\n // One pre-pass instead of a filter() per component: at 300 mounted\n // components the quadratic version cost ~90k comparisons per projection.\n const typeCounts = new Map<string, number>();\n for (const component of snapshot.components) {\n typeCounts.set(component.type, (typeCounts.get(component.type) ?? 0) + 1);\n }\n\n for (const component of snapshot.components) {\n const multiInstance = (typeCounts.get(component.type) ?? 0) > 1;\n const instanceId = multiInstance ? component.instanceId : undefined;\n for (const obs of component.observations) {\n push(\n obs.capabilityId,\n \"observation\",\n component.registrationId,\n instanceId,\n describePrefix(\"view\", \"read\", \"never\"),\n obs.description,\n EMPTY_INPUT_SCHEMA,\n availabilityState(obs),\n );\n }\n for (const act of component.actions) {\n push(\n act.capabilityId,\n \"action\",\n component.registrationId,\n instanceId,\n describePrefix(\"view\", act.effect, act.confirmation),\n act.description,\n act.inputSchema,\n availabilityState(act),\n );\n }\n }\n const procedureCounts = new Map<string, number>();\n for (const proc of snapshot.procedures) {\n procedureCounts.set(proc.procedureId, (procedureCounts.get(proc.procedureId) ?? 0) + 1);\n }\n for (const proc of snapshot.procedures) {\n const needsSuffix = (procedureCounts.get(proc.procedureId) ?? 0) > 1;\n push(\n proc.procedureId,\n \"procedure\",\n proc.registrationId,\n undefined,\n describePrefix(\"domain\", proc.effect, proc.confirmation),\n // The stable half only: a contextual note travels in `state.note`.\n proc.description,\n proc.inputSchema,\n availabilityState(proc),\n needsSuffix\n ? (proc.context?.instanceId ?? proc.registrationId.replace(/[^A-Za-z0-9_-]/g, \"\"))\n : undefined,\n );\n }\n\n // Uniqueness is a catalog property, not a per-name one (AS-WIRE-006).\n const assignment = assignWireNames(pending.map((p) => p.wire));\n const tools = pending.map((p, i) => ({\n name: assignment.names[i]!,\n description: `${p.prefix} ${p.description}`,\n inputSchema: p.inputSchema,\n state: p.state,\n execute: (input: JsonValue, call: { toolCallId?: string }) =>\n invokeThroughSurface(p.entry, input, call.toolCallId),\n }));\n return { tools, wireNames: assignment.byName };\n }\n\n /**\n * A meta verb rejecting its own envelope, before the registry sees anything.\n * The error branch needs an identity: the caller's `capabilityId` when it\n * supplied one, else the verb's own meta id — mirroring `surface_discover`'s\n * ok result, and what hosts already fall back to for audit identity when a\n * meta call names no target.\n */\n function envelopeFailure(\n metaCapabilityId: string,\n capabilityId: JsonValue | undefined,\n error: AgentCapabilityErrorPayload,\n toolCallId: string | undefined,\n ): AgentInvocationResult {\n return {\n status: \"error\",\n invocationId: toolCallId ?? `inv_${randomBase62(12)}`,\n capabilityId:\n typeof capabilityId === \"string\" && capabilityId.length > 0\n ? capabilityId\n : metaCapabilityId,\n error,\n surfaceVersion: registry.getVersion(),\n };\n }\n\n function buildMetaTools(): AgentTool[] {\n const snapshotFor = (): AgentSurfaceSnapshot =>\n registry.snapshot({\n consumer: options.consumer,\n ...(options.scope ? { scope: options.scope } : {}),\n });\n // The three verbs are always callable; per-capability availability lives in\n // the `surface_discover` payload, where the model actually reads it.\n const verbs: Array<Omit<AgentTool, \"state\">> = [\n {\n name: \"surface_discover\",\n description:\n \"[meta] Discover the current agent surface: components, capabilities, procedures, availability, schemas.\",\n inputSchema: META_DISCOVER_SCHEMA,\n async execute(input, call) {\n const invalid = validateEnvelope(\"surface_discover\", META_DISCOVER_SCHEMA, input);\n if (invalid) {\n return envelopeFailure(\"meta:surface.discover\", undefined, invalid, call.toolCallId);\n }\n const requested = (input as { scope?: string[] } | undefined)?.scope;\n // D27: the configured scope is a floor; a model-supplied scope narrows.\n const effective = intersectScope(options.scope, requested);\n const snapshot = registry.snapshot({\n consumer: options.consumer,\n ...(effective.scope ? { scope: effective.scope } : {}),\n ...(options.budget ? { budget: options.budget } : {}),\n });\n // Disjoint request: honored as \"nothing\", never widened to the floor.\n // The refusal is marked for the same reason budget truncation is —\n // an unexplained blank payload reads as \"the surface is empty\", which\n // is the one conclusion the model must not draw here (AS-META-006).\n const projected: AgentSurfaceSnapshot = {\n ...snapshot,\n // A disjoint request is snapshotted unscoped, so any `truncated`\n // count belongs to a surface this payload does not contain. Keeping\n // it would claim a budget dropped what scope did.\n ...(effective.empty\n ? { components: [], procedures: [], truncated: undefined }\n : {}),\n ...(effective.rejected.length > 0\n ? { scopeRejected: { prefixes: effective.rejected } }\n : {}),\n };\n return {\n status: \"ok\",\n invocationId: `inv_${randomBase62(12)}`,\n capabilityId: \"meta:surface.discover\",\n output: JSON.parse(JSON.stringify(projected)) as JsonValue,\n surfaceVersion: snapshot.surfaceVersion,\n };\n },\n },\n {\n name: \"surface_read\",\n description: \"[meta] Invoke an observation by capabilityId and return its output.\",\n inputSchema: META_READ_SCHEMA,\n async execute(input, call) {\n const req = (input ?? {}) as { capabilityId: string; instanceId?: string };\n const invalid = validateEnvelope(\"surface_read\", META_READ_SCHEMA, input);\n if (invalid) {\n return envelopeFailure(\"meta:surface.read\", req.capabilityId, invalid, call.toolCallId);\n }\n const snapshot = snapshotFor();\n const { registrationId } = findTarget(snapshot, req.capabilityId, req.instanceId);\n return invokeThroughSurface(\n {\n capabilityId: req.capabilityId,\n // Unresolved → let the registry answer (AS-ADAPTER-003).\n ...(registrationId !== undefined ? { registrationId } : {}),\n ...(req.instanceId !== undefined ? { instanceId: req.instanceId } : {}),\n surfaceVersion: snapshot.surfaceVersion,\n kind: \"observation\",\n },\n undefined,\n call.toolCallId,\n );\n },\n },\n {\n name: \"surface_act\",\n description:\n \"[meta] Invoke an action or procedure by capabilityId. Echo the surfaceVersion you discovered so a surface that changed underneath a destructive plan is rejected rather than executed.\",\n inputSchema: META_ACT_SCHEMA,\n async execute(input, call) {\n const req = (input ?? {}) as {\n capabilityId: string;\n instanceId?: string;\n input?: JsonValue;\n invocationId?: string;\n confirmationId?: string;\n surfaceVersion?: string;\n };\n // `input` is exempt from the type check: the shim below owns it, and\n // recovering a stringified object beats rejecting it (AS-META-008).\n const invalid = validateEnvelope(\"surface_act\", META_ACT_SCHEMA, input, [\"input\"]);\n if (invalid) {\n return envelopeFailure(\"meta:surface.act\", req.capabilityId, invalid, call.toolCallId);\n }\n const snapshot = snapshotFor();\n const { registrationId, inputSchema } = findTarget(\n snapshot,\n req.capabilityId,\n req.instanceId,\n );\n let actInput = req.input;\n const parsed = parseStringifiedObject(actInput, inputSchema);\n if (parsed !== undefined) {\n actInput = parsed;\n // Never silent: a repaired call is indistinguishable from a\n // well-formed one downstream, which would hide exactly the\n // regression this shim exists to absorb.\n devWarn(\n `[agent-surface] surface_act got \\`input\\` as a JSON-encoded string for \"${req.capabilityId}\" and parsed it; the provider is not honoring the tool schema.`,\n );\n }\n // One execution path with direct mode: same resolution, same\n // staleness binding, same wait-mode confirmation retry (D26). A\n // direct tool carries the version of the catalog it was built from;\n // the equivalent here is the version the model discovered, so it is\n // taken from the caller when supplied (AS-META-004).\n return invokeThroughSurface(\n {\n capabilityId: req.capabilityId,\n ...(registrationId !== undefined ? { registrationId } : {}),\n ...(req.instanceId !== undefined ? { instanceId: req.instanceId } : {}),\n surfaceVersion: req.surfaceVersion ?? snapshot.surfaceVersion,\n kind: \"action\",\n },\n actInput,\n call.toolCallId,\n {\n ...(req.invocationId !== undefined ? { invocationId: req.invocationId } : {}),\n ...(req.confirmationId !== undefined ? { confirmationId: req.confirmationId } : {}),\n },\n );\n },\n },\n ];\n return verbs.map((verb) => ({ ...verb, state: { available: true } }));\n }\n\n function computeTools(): AgentTool[] {\n if (mode === \"meta\") {\n cachedTools ??= buildMetaTools();\n return cachedTools;\n }\n const version = registry.getVersion();\n if (cachedTools && cachedVersion === version) return cachedTools;\n const built = buildDirectTools();\n cachedTools = built.tools;\n cachedWireNames = built.wireNames;\n cachedVersion = version;\n return cachedTools;\n }\n\n /**\n * Includes `state`: the definitions are byte-identical across an\n * availability flip, so a host that re-renders its state block on\n * `subscribe` would otherwise never hear about it.\n */\n function signatureOf(tools: AgentTool[]): string {\n return JSON.stringify(\n tools.map((t) => [t.name, t.description, t.inputSchema, t.state]),\n );\n }\n\n const unsubscribe = registry.subscribe((event) => {\n if (disposed || event.type !== \"surface-changed\") return;\n cachedVersion = undefined;\n // Meta mode: the three-tool catalog is constant by construction, so\n // tools() can never differ and listeners are never called. Agents notice\n // surface changes by re-running surface_discover and comparing\n // surfaceVersion (docs/09 §meta-tools-mode).\n if (mode === \"meta\") return;\n const tools = computeTools();\n const signature = signatureOf(tools);\n if (signature === cachedSignature) return;\n cachedSignature = signature;\n for (const listener of [...listeners]) {\n try {\n listener(tools);\n } catch {\n /* listener isolation */\n }\n }\n });\n\n return {\n tools() {\n const tools = computeTools();\n cachedSignature ??= signatureOf(tools);\n return tools;\n },\n wireNameMap() {\n if (mode === \"meta\") return new Map();\n computeTools();\n return cachedWireNames;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n disposed = true;\n unsubscribe();\n listeners.clear();\n // Settle in-flight wait-mode waits deterministically (D26).\n for (const controller of [...pendingWaits]) controller.abort();\n pendingWaits.clear();\n },\n };\n}\n\n/**\n * D27 — the adapter-configured scope is a floor, not a default. A model-supplied\n * scope may narrow it (`[\"devices\"]` → `[\"devices.table\"]`), never widen it\n * (`[]` or `[\"admin\"]` cannot reach past the floor). Prefix lists intersect\n * pairwise: the more specific prefix wins when one extends the other, and a\n * pair that shares no prefix contributes nothing. An empty result means the\n * request was entirely outside the floor — reported as an empty surface rather\n * than silently falling back to the floor itself.\n *\n * `rejected` names the requested prefixes the floor admitted nothing for, in\n * request order. It carries the whole request when the two are disjoint, and a\n * subset when only part of the request was out of bounds; both are cases where\n * the model asked for something and got silence back (AS-META-006). A prefix\n * broader than the floor is *not* rejected: it contributed the floor's own\n * narrower prefix, which is the narrowing D27 describes.\n */\nfunction intersectScope(\n floor: string[] | undefined,\n requested: string[] | undefined,\n): { scope?: string[]; empty: boolean; rejected: string[] } {\n const hasFloor = floor !== undefined && floor.length > 0;\n // `[]` is \"everything\" to matchesScope — treat it as \"unspecified\", so an\n // empty array cannot be used to widen past the floor.\n if (requested === undefined || requested.length === 0) {\n return hasFloor ? { scope: floor, empty: false, rejected: [] } : { empty: false, rejected: [] };\n }\n if (!hasFloor) return { scope: requested, empty: false, rejected: [] };\n const out = new Set<string>();\n const rejected: string[] = [];\n for (const r of requested) {\n let admitted = false;\n for (const f of floor) {\n if (r === f || r.startsWith(`${f}.`)) {\n out.add(r);\n admitted = true;\n } else if (f.startsWith(`${r}.`)) {\n out.add(f);\n admitted = true;\n }\n }\n // Deduped: a repeated prefix is one refusal, not one per occurrence.\n if (!admitted && !rejected.includes(r)) rejected.push(r);\n }\n return out.size > 0\n ? { scope: [...out], empty: false, rejected }\n : { empty: true, rejected };\n}\n\ninterface ResolvedTarget {\n /**\n * Omitted unless the pair resolves to exactly one live registration — see\n * {@link CatalogEntry.registrationId} for why a placeholder is worse.\n */\n registrationId?: string;\n /**\n * The target's declared agent-facing input schema, under the same\n * one-match condition. Read only to decide whether a stringified `input`\n * may be repaired; the registry remains the validator.\n */\n inputSchema?: JsonSchema;\n}\n\nfunction findTarget(\n snapshot: AgentSurfaceSnapshot,\n capabilityId: string,\n instanceId: string | undefined,\n): ResolvedTarget {\n const matches: ResolvedTarget[] = [];\n for (const component of snapshot.components) {\n if (instanceId !== undefined && component.instanceId !== instanceId) continue;\n const all: Array<AgentObservationDescriptor | AgentActionDescriptor> = [\n ...component.observations,\n ...component.actions,\n ];\n const hit = all.find((c) => c.capabilityId === capabilityId);\n // Observations carry no input schema, so the field stays absent for them.\n if (hit) {\n matches.push({\n registrationId: component.registrationId,\n ...(\"inputSchema\" in hit ? { inputSchema: hit.inputSchema } : {}),\n });\n }\n }\n for (const proc of snapshot.procedures as AgentProcedureDescriptor[]) {\n if (proc.procedureId === capabilityId) {\n matches.push({ registrationId: proc.registrationId, inputSchema: proc.inputSchema });\n }\n }\n return matches.length === 1 ? matches[0]! : {};\n}\n\n/* ─────────────────────── meta-verb envelope checking ───────────────────────\n * The three verbs declare `required` and `additionalProperties: false`, and\n * nothing enforced either: a provider that compiles the tool schema into a\n * sampling grammar makes most of this unreachable, and one that does not hands\n * the envelope through verbatim. The consequences were asymmetric — a missing\n * `capabilityId` reached `parseCapabilityId` as `undefined` and came back as\n * EXECUTION_FAILED {retry:\"no\"}, reporting a caller error as an internal defect\n * and telling the model to stop rather than fix its call. Checked against each\n * verb's OWN schema, so the declaration and the check cannot drift.\n */\n\n/** A type alias, not an interface: `details` is a `JsonValue` bag, and only\n * the alias carries the implicit index signature that makes it assignable. */\ntype EnvelopeIssue = { path: string; message: string };\n\nfunction validateEnvelope(\n verb: string,\n schema: JsonSchema,\n raw: JsonValue | undefined,\n /** Properties this must not type-check; their owner handles the value. */\n exempt: readonly string[] = [],\n): AgentCapabilityErrorPayload | undefined {\n // `null` is how some providers spell \"no arguments\" — read as `{}`, so a\n // no-argument verb keeps working and a required key is still reported as\n // missing rather than as a malformed envelope.\n if (raw !== undefined && raw !== null && (typeof raw !== \"object\" || Array.isArray(raw))) {\n return envelopeError(verb, [\n { path: \"\", message: `\\`${verb}\\` takes a JSON object of arguments.` },\n ]);\n }\n const properties = (schema.properties ?? {}) as Record<string, JsonSchema>;\n const known = Object.keys(properties);\n const required = (schema.required ?? []) as string[];\n const req = (raw ?? {}) as Record<string, JsonValue | undefined>;\n const issues: EnvelopeIssue[] = [];\n\n for (const key of required) {\n if (req[key] === undefined) issues.push({ path: key, message: `\\`${key}\\` is required.` });\n }\n for (const [key, value] of Object.entries(req)) {\n if (value === undefined) continue;\n if (!known.includes(key)) {\n if (schema.additionalProperties === false) {\n issues.push({\n path: key,\n // The high-value half is the pointer back at `input`: it turns the\n // dead end of a hoisted capability argument into a one-retry\n // recovery. A verb without an `input` has nowhere to point.\n message: `Unknown top-level property. \\`${verb}\\` accepts only ${known.join(\", \")}.${\n known.includes(\"input\")\n ? \" An argument the capability declares belongs inside `input`.\"\n : \"\"\n }`,\n });\n }\n continue;\n }\n if (exempt.includes(key)) continue;\n const issue = checkDeclaredType(key, properties[key]!, value);\n if (issue) issues.push(issue);\n }\n return issues.length > 0 ? envelopeError(verb, issues) : undefined;\n}\n\nfunction checkDeclaredType(\n key: string,\n property: JsonSchema,\n value: JsonValue,\n): EnvelopeIssue | undefined {\n if (property.type === \"string\" && (typeof value !== \"string\" || value.length === 0)) {\n return { path: key, message: `\\`${key}\\` must be a non-empty string.` };\n }\n if (property.type === \"array\") {\n if (!Array.isArray(value)) return { path: key, message: `\\`${key}\\` must be an array.` };\n const items = property.items as JsonSchema | undefined;\n if (items?.type === \"string\" && !value.every((item) => typeof item === \"string\")) {\n return { path: key, message: `\\`${key}\\` must be an array of strings.` };\n }\n }\n return undefined;\n}\n\nfunction envelopeError(verb: string, issues: EnvelopeIssue[]): AgentCapabilityErrorPayload {\n return {\n code: \"INVALID_INPUT\",\n // Names the envelope, not the capability: pointing the model at the\n // capability's schema when the wrapper is what is wrong sends it to fix\n // something that is already correct.\n message: `The \\`${verb}\\` call is malformed — the fault is in the tool's own arguments, not the capability's input. Fix the listed issues and retry.`,\n retry: \"with-changes\",\n details: { issues },\n };\n}\n\n/**\n * Recovers the one malformation an untyped `input` property invited: the\n * arguments arriving as a JSON-encoded string, the shape the dominant\n * function-calling convention (`function_call.arguments`) carries nested call\n * arguments in. Typing the property fixes providers that honor the schema\n * during generation; this covers the ones that do not.\n *\n * Deliberately narrow: only when the target's own schema declares an object,\n * and only when the string parses to a plain object. A capability that\n * genuinely declares a string input must never have its argument parsed out\n * from under it. Anything else passes through untouched, to the registry's\n * validator, which owns the verdict.\n */\nfunction parseStringifiedObject(\n value: JsonValue | undefined,\n targetSchema: JsonSchema | undefined,\n): JsonValue | undefined {\n if (typeof value !== \"string\" || targetSchema?.type !== \"object\") return undefined;\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return parsed as JsonValue;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmFO,IAAM,iBAAqC;AAAA,EAChD,yBAAyB;AAAA,EACzB,0BAA0B;AAAA,EAC1B,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,sBAAsB;AAAA,EACtB,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,sCAAsC;AAAA,EACtC,gCAAgC;AAAA,EAChC,kCAAkC;AAAA,EAClC,iBAAiB;AAAA,EACjB,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,yBAAyB;AAC3B;;;AC9FO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EACjC;AAAA,EACT,YAAY,QAA4B;AACtC,UAAM,OAAO,IAAI,CAAC,MAAM,GAAG,EAAE,QAAQ,GAAG,KAAK,EAAE,OAAO,EAAE,EAAE,KAAK,IAAI,KAAK,eAAe;AACvF,SAAK,OAAO;AACZ,SAAK,SAAS;AAAA,EAChB;AACF;AAgCO,SAAS,mBACd,QACA,SACgB;AAChB,SAAO;AAAA,IACL,YAAY,QAAQ;AAAA,IACpB,MAAM,OAAmB;AACvB,YAAM,SAAS,OAAO,WAAW,EAAE,SAAS,KAAK;AACjD,UAAI,kBAAkB,SAAS;AAC7B,cAAM,IAAI,iBAAiB;AAAA,UACzB,EAAE,MAAM,IAAI,SAAS,mDAAmD;AAAA,QAC1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