@agent-surface/core 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/explain.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { D as DiscoveryDecision, A as AgentRouteInfo, a as AgentConsumer, b as AgentSurfaceRegistry, S as SnapshotContext } from './registry-DmWUlnta.js';
1
+ import { D as DiscoveryDecision, A as AgentRouteInfo, a as AgentConsumer, b as AgentSurfaceRegistry, S as SnapshotContext } from './registry-BSwS05Xq.js';
2
2
 
3
3
  /**
4
4
  * `explainSurface()` — the developer projection.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { J as JsonSchema, c as JsonValue, d as AgentInvocationResult, U as Unsubscribe, a as AgentConsumer, b as AgentSurfaceRegistry } from './registry-DmWUlnta.js';
2
- export { e as AGENT_CAPABILITY_ERROR_CODES, f as AgentActionContext, g as AgentActionDefinition, h as AgentActionDescriptor, i as AgentAuthorizationContext, j as AgentCapabilityDescriptorUnion, k as AgentCapabilityErrorCode, l as AgentCapabilityErrorPayload, m as AgentComponentDefinition, n as AgentComponentDescriptor, o as AgentConcurrency, p as AgentEffect, q as AgentEnvironment, r as AgentErrorRetry, s as AgentInvocation, t as AgentInvocationPolicyContext, u as AgentObservationDefinition, v as AgentObservationDescriptor, w as AgentPolicy, x as AgentPolicyContext, y as AgentProcedureBinding, z as AgentProcedureBindingRuntimeConfig, B as AgentProcedureDescriptor, C as AgentProcedureEffect, E as AgentProcedureExecutor, F as AgentProcedureRefDescriptor, G as AgentReadContext, H as AgentRegistrationHandle, A as AgentRouteInfo, I as AgentSchema, K as AgentSchemaError, L as AgentSchemaIssue, M as AgentSurfaceDefinitionError, N as AgentSurfaceDefinitionErrorCode, O as AgentSurfaceError, P as AgentSurfaceEvent, Q as AgentSurfaceLimits, R as AgentSurfaceSnapshot, T as AuditEvent, V as AuditSink, W as CONFIRMATION_ESCALATION, X as ConfirmationController, Y as ConfirmationEscalation, Z as DEFAULT_LIMITS, D as DiscoveryDecision, _ as InvokeOptions, $ as PendingConfirmation, a0 as PreconditionFailure, a1 as ProcedureCallInfo, a2 as RegistrationCandidate, a3 as RegistryOptions, S as SnapshotContext, a4 as StandardSchemaV1, a5 as action, a6 as audit, a7 as authenticated, a8 as composeInvokeChain, a9 as consoleAuditSink, aa as createAgentSurfaceRegistry, ab as defineAgentComponent, ac as emptyObjectSchema, ad as environment, ae as evaluateDiscovery, af as fromJsonSchema, ag as fromStandardSchema, ah as hasPermission, ai as isAgentSurfaceError, aj as memoryAuditSink, ak as observation, al as rateLimit, am as requireConfirmation, an as tenantBoundary, ao as validateComponentDefinition, ap as validateJsonSchemaDocument, aq as validateValueAgainstSchema } from './registry-DmWUlnta.js';
1
+ import { J as JsonSchema, c as JsonValue, d as AgentInvocationResult, U as Unsubscribe, a as AgentConsumer, b as AgentSurfaceRegistry } from './registry-BSwS05Xq.js';
2
+ export { e as AGENT_CAPABILITY_ERROR_CODES, f as AgentActionContext, g as AgentActionDefinition, h as AgentActionDescriptor, i as AgentAuthorizationContext, j as AgentCapabilityDescriptorUnion, k as AgentCapabilityErrorCode, l as AgentCapabilityErrorPayload, m as AgentComponentDefinition, n as AgentComponentDescriptor, o as AgentConcurrency, p as AgentEffect, q as AgentEnvironment, r as AgentErrorRetry, s as AgentInvocation, t as AgentInvocationPolicyContext, u as AgentObservationDefinition, v as AgentObservationDescriptor, w as AgentPolicy, x as AgentPolicyContext, y as AgentProcedureBinding, z as AgentProcedureBindingRuntimeConfig, B as AgentProcedureDescriptor, C as AgentProcedureEffect, E as AgentProcedureExecutor, F as AgentProcedureRefDescriptor, G as AgentReadContext, H as AgentRegistrationHandle, A as AgentRouteInfo, I as AgentSchema, K as AgentSchemaError, L as AgentSchemaIssue, M as AgentSurfaceDefinitionError, N as AgentSurfaceDefinitionErrorCode, O as AgentSurfaceError, P as AgentSurfaceEvent, Q as AgentSurfaceLimits, R as AgentSurfaceSnapshot, T as AuditEvent, V as AuditSink, W as CONFIRMATION_ESCALATION, X as ConfirmationController, Y as ConfirmationEscalation, Z as DEFAULT_LIMITS, D as DiscoveryDecision, _ as InvokeOptions, $ as PendingConfirmation, a0 as PreconditionFailure, a1 as ProcedureCallInfo, a2 as RegistrationCandidate, a3 as RegistryOptions, S as SnapshotContext, a4 as StandardSchemaV1, a5 as action, a6 as audit, a7 as authenticated, a8 as composeInvokeChain, a9 as consoleAuditSink, aa as createAgentSurfaceRegistry, ab as defineAgentComponent, ac as emptyObjectSchema, ad as environment, ae as evaluateDiscovery, af as fromJsonSchema, ag as fromStandardSchema, ah as hasPermission, ai as isAgentSurfaceError, aj as memoryAuditSink, ak as observation, al as rateLimit, am as requireConfirmation, an as tenantBoundary, ao as validateComponentDefinition, ap as validateJsonSchemaDocument, aq as validateValueAgainstSchema } from './registry-BSwS05Xq.js';
3
3
 
4
4
  /**
5
5
  * Canonical ID grammar (docs/01 §identity):
package/dist/index.js CHANGED
@@ -705,10 +705,15 @@ function memoryAuditSink(opts) {
705
705
  function consoleAuditSink() {
706
706
  return {
707
707
  record(event) {
708
- console.debug("[agent-surface audit]", event.type, event);
708
+ if (isNodeLike()) console.error("[agent-surface audit]", event.type, event);
709
+ else console.debug("[agent-surface audit]", event.type, event);
709
710
  }
710
711
  };
711
712
  }
713
+ function isNodeLike() {
714
+ const proc = globalThis.process;
715
+ return typeof proc?.versions?.node === "string";
716
+ }
712
717
  function safeRecord(sink, event) {
713
718
  if (!sink) return;
714
719
  try {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
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,WA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AAA,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":["record","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\n/**\n * Development-time visibility, on the *diagnostic* stream.\n *\n * `console.debug` is the browser's verbose channel — the right home for a\n * per-event trace nobody explicitly asked to see. Node has no such channel:\n * there, `console.debug` is an alias of `console.log` and writes to **stdout**,\n * which is the stream a host that mounts this registry renders *its own output*\n * into. One registration is then enough to make `agent-surface inspect --json`\n * emit something no JSON parser accepts (AS-CLI-004), and a config deriving\n * `environment` from `import.meta.env.PROD` gets this sink under vite-node\n * without doing anything unusual.\n *\n * An audit trail is a diagnostic, not program output, so under Node it goes to\n * stderr. `console.error` rather than `process.stderr.write`: core stays\n * runtime-neutral, and a host that already intercepts the console keeps seeing\n * these events.\n */\nexport function consoleAuditSink(): AuditSink {\n return {\n record(event) {\n // eslint-disable-next-line no-console\n if (isNodeLike()) console.error(\"[agent-surface audit]\", event.type, event);\n // eslint-disable-next-line no-console\n else console.debug(\"[agent-surface audit]\", event.type, event);\n },\n };\n}\n\n/**\n * Node, not a bundler's `process` shim — only the real thing reports\n * `versions.node`. Read off `globalThis` so `core` needs no Node types.\n */\nfunction isNodeLike(): boolean {\n const proc = (globalThis as { process?: { versions?: { node?: unknown } } }).process;\n return typeof proc?.versions?.node === \"string\";\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,IAC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AAS,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":["record","environment"]}
@@ -238,6 +238,23 @@ declare function memoryAuditSink(opts?: {
238
238
  }): AuditSink & {
239
239
  events(): AuditEvent[];
240
240
  };
241
+ /**
242
+ * Development-time visibility, on the *diagnostic* stream.
243
+ *
244
+ * `console.debug` is the browser's verbose channel — the right home for a
245
+ * per-event trace nobody explicitly asked to see. Node has no such channel:
246
+ * there, `console.debug` is an alias of `console.log` and writes to **stdout**,
247
+ * which is the stream a host that mounts this registry renders *its own output*
248
+ * into. One registration is then enough to make `agent-surface inspect --json`
249
+ * emit something no JSON parser accepts (AS-CLI-004), and a config deriving
250
+ * `environment` from `import.meta.env.PROD` gets this sink under vite-node
251
+ * without doing anything unusual.
252
+ *
253
+ * An audit trail is a diagnostic, not program output, so under Node it goes to
254
+ * stderr. `console.error` rather than `process.stderr.write`: core stays
255
+ * runtime-neutral, and a host that already intercepts the console keeps seeing
256
+ * these events.
257
+ */
241
258
  declare function consoleAuditSink(): AuditSink;
242
259
 
243
260
  type DiscoveryDecision = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-surface/core",
3
- "version": "0.9.0",
3
+ "version": "0.9.1",
4
4
  "description": "Framework-agnostic registry, types, policies, errors, snapshot, invocation for frontend agent surfaces",
5
5
  "license": "MIT",
6
6
  "type": "module",