@agent-surface/core 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,49 +1,22 @@
1
- # @agent-surface/core
1
+ # `@agent-surface/core`
2
2
 
3
- Framework-agnostic core of [agent-surface](https://github.com/Wiseair-srl/agent-surface): a registry for declaring an explicit, semantic, typed, policy-governed *agent surface* over a frontend — and nothing more. If a component or capability is not explicitly annotated, it does not exist for the agent.
4
-
5
- Zero runtime dependencies. Provides: canonical capability ids, the `AgentSchema` layer (Standard Schema + built-in JSON Schema subset validator), component/capability definitions, the registry (registration lifecycle, availability, versioning, staleness), synchronous snapshots, the 10-phase invocation pipeline, composable policies, single-use confirmation evidence, audit sinks, and a provider-neutral toolset projection for embedded agent loops.
6
-
7
- Docs: https://agent-surface-docs.vercel.app
8
-
9
- ## Install
10
-
11
- ```bash
12
- pnpm add @agent-surface/core
13
- ```
14
-
15
- ## Use
3
+ Framework-neutral contracts, registry, policy, confirmation, invocation and exposure gateway.
16
4
 
17
5
  ```ts
18
- import {
19
- createAgentSurfaceRegistry,
20
- defineAgentComponent,
21
- observation,
22
- action,
23
- fromStandardSchema,
24
- createAgentToolset,
25
- } from "@agent-surface/core";
26
-
27
- const registry = createAgentSurfaceRegistry({
28
- environment: import.meta.env.DEV ? "development" : "production",
29
- context: () => ({ user: authStore.user }),
6
+ const contract = defineAgentComponentContract({
7
+ type: "devices.table",
8
+ description: "Device table",
9
+ observations: { readState: observationContract({ description: "State", output }) },
10
+ actions: { selectRows: actionContract({ description: "Select", input, effect: "local-state" }) },
30
11
  });
31
12
 
32
- registry.register(
33
- defineAgentComponent({
34
- type: "devices.table",
35
- description: "Table of the devices visible on the current page",
36
- observations: { readState: observation({ /* … */ }) },
37
- actions: { selectRows: action({ /* … */ }) },
38
- }),
39
- );
40
-
41
- const toolset = createAgentToolset(registry, {
42
- consumer: { id: "copilot", kind: "embedded" },
43
- topology: "embedded", // required (D26): embedded → confirmations "wait",
44
- }); // remote → "two-phase". No global default.
13
+ const registry = createAgentSurfaceRegistry({ authority });
14
+ registry.register(contract.bind({
15
+ observations: { readState: { read } },
16
+ actions: { selectRows: { execute } },
17
+ }));
45
18
  ```
46
19
 
47
- React apps should use [`@agent-surface/react`](https://www.npmjs.com/package/@agent-surface/react) instead of calling `register` directly. Full specification: [docs](https://github.com/Wiseair-srl/agent-surface/tree/main/docs).
20
+ The compiler authority is mandatory. Raw/unknown/stale/changed registrations fail closed. Use `createAgentExposureGateway(authority)` at final provider/MCP assembly.
48
21
 
49
- MIT © Wiseair S.r.l.
22
+ See [Core API](../../docs/03-core-api.md).
package/dist/explain.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { D as DiscoveryDecision, A as AgentRouteInfo, a as AgentConsumer, b as AgentSurfaceRegistry, S as SnapshotContext } from './registry-XD1QsGQ4.js';
2
- export { m as matchesScope } from './registry-XD1QsGQ4.js';
1
+ import { D as DiscoveryDecision, A as AgentRouteInfo, a as AgentConsumer, b as AgentSurfaceRegistry, S as SnapshotContext } from './registry-QvbeJMRD.js';
2
+ export { m as matchesScope } from './registry-QvbeJMRD.js';
3
3
 
4
4
  /**
5
5
  * `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-XD1QsGQ4.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, n as AgentComponentDefinition, o as AgentComponentDescriptor, p as AgentConcurrency, q as AgentEffect, r as AgentEnvironment, s as AgentErrorRetry, t as AgentInvocation, u as AgentInvocationPolicyContext, v as AgentObservationDefinition, w as AgentObservationDescriptor, x as AgentPolicy, y as AgentPolicyContext, z as AgentProcedureBinding, B as AgentProcedureBindingRuntimeConfig, C as AgentProcedureDescriptor, E as AgentProcedureEffect, F as AgentProcedureExecutor, G as AgentProcedureRefDescriptor, H as AgentReadContext, I as AgentRegistrationHandle, A as AgentRouteInfo, K as AgentSchema, L as AgentSchemaError, M as AgentSchemaIssue, N as AgentSurfaceDefinitionError, O as AgentSurfaceDefinitionErrorCode, P as AgentSurfaceError, Q as AgentSurfaceEvent, R as AgentSurfaceLimits, T as AgentSurfaceSnapshot, V as AuditEvent, W as AuditSink, X as CONFIRMATION_ESCALATION, Y as ConfirmationController, Z as ConfirmationEscalation, _ as DEFAULT_LIMITS, D as DiscoveryDecision, $ as InvokeOptions, a0 as PendingConfirmation, a1 as PreconditionFailure, a2 as ProcedureCallInfo, a3 as RegistrationCandidate, a4 as RegistryOptions, S as SnapshotContext, a5 as StandardSchemaV1, a6 as action, a7 as audit, a8 as authenticated, a9 as composeInvokeChain, aa as consoleAuditSink, ab as createAgentSurfaceRegistry, ac as defineAgentComponent, ad as emptyObjectSchema, ae as environment, af as evaluateDiscovery, ag as fromJsonSchema, ah as fromStandardSchema, ai as hasPermission, aj as isAgentSurfaceError, ak as memoryAuditSink, al as observation, am as rateLimit, an as requireConfirmation, ao as tenantBoundary, ap as validateComponentDefinition, aq as validateJsonSchemaDocument, ar as validateValueAgainstSchema } from './registry-XD1QsGQ4.js';
1
+ import { J as JsonSchema, c as JsonValue, d as AgentInvocationResult, U as Unsubscribe, a as AgentConsumer, b as AgentSurfaceRegistry } from './registry-QvbeJMRD.js';
2
+ export { e as AGENT_CAPABILITY_ERROR_CODES, f as AgentActionContext, g as AgentActionContract, h as AgentActionDefinition, i as AgentActionDescriptor, j as AgentAuthorizationContext, k as AgentCapabilityDescriptorUnion, l as AgentCapabilityErrorCode, n as AgentCapabilityErrorPayload, o as AgentComponentContract, p as AgentComponentContractDefinition, q as AgentComponentDefinition, r as AgentComponentDescriptor, s as AgentComponentRuntimeBindings, t as AgentConcurrency, u as AgentEffect, v as AgentEnvironment, w as AgentErrorRetry, x as AgentExposureGateway, y as AgentInvocation, z as AgentInvocationPolicyContext, B as AgentObservationContract, C as AgentObservationDefinition, E as AgentObservationDescriptor, F as AgentPolicy, G as AgentPolicyContext, H as AgentProcedureBinding, I as AgentProcedureBindingRuntimeConfig, K as AgentProcedureContract, L as AgentProcedureContractDefinition, M as AgentProcedureDescriptor, N as AgentProcedureEffect, O as AgentProcedureExecutor, P as AgentProcedureRefDescriptor, Q as AgentReadContext, R as AgentRegistrationHandle, A as AgentRouteInfo, T as AgentSchema, V as AgentSchemaError, W as AgentSchemaIssue, X as AgentSurfaceDefinitionError, Y as AgentSurfaceDefinitionErrorCode, Z as AgentSurfaceError, _ as AgentSurfaceEvent, $ as AgentSurfaceLimits, a0 as AgentSurfaceSnapshot, a1 as AuditEvent, a2 as AuditSink, a3 as CAPABILITY_CONTRACT_FORMAT_VERSION, a4 as CONFIRMATION_ESCALATION, a5 as CapabilityAuthority, a6 as CapabilityContractEntry, a7 as CapabilityContractKind, a8 as CapabilityContractManifest, a9 as CapabilityPolicyAttachment, aa as CompiledExternalAgentTool, ab as ConfirmationController, ac as ConfirmationEscalation, ad as DEFAULT_LIMITS, D as DiscoveryDecision, ae as ExternalAgentToolContract, af as ExternalAgentToolContractDefinition, ag as ExternalCapabilityContractDigest, ah as InvokeOptions, ai as PendingConfirmation, aj as PreconditionFailure, ak as ProcedureCallInfo, al as RegistrationCandidate, am as RegistryOptions, S as SnapshotContext, an as StandardSchemaV1, ao as action, ap as actionContract, aq as assertDefinitionAuthorized, ar as audit, as as authenticated, at as authorizeAgentProcedureBinding, au as composeInvokeChain, av as consoleAuditSink, aw as createAgentExposureGateway, ax as createAgentSurfaceRegistry, ay as createCapabilityAuthority, az as defineAgentComponent, aA as defineAgentComponentContract, aB as defineAgentProcedureContract, aC as defineExternalAgentToolContract, aD as deriveAgentComponentBinding, aE as emptyObjectSchema, aF as environment, aG as evaluateDiscovery, aH as fromJsonSchema, aI as fromStandardSchema, aJ as hasPermission, aK as isAgentSurfaceError, aL as memoryAuditSink, aM as observation, aN as observationContract, aO as rateLimit, aP as requireConfirmation, aQ as tenantBoundary, aR as validateComponentDefinition, aS as validateJsonSchemaDocument, aT as validateValueAgainstSchema } from './registry-QvbeJMRD.js';
3
3
 
4
4
  /**
5
5
  * Canonical ID grammar (docs/01 §identity):
package/dist/index.js CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  consumerKeyOf,
24
24
  createSnapshot,
25
25
  decodeWireName,
26
+ deepFreeze,
26
27
  encodeWireName,
27
28
  encodeWireNameForInstance,
28
29
  environment,
@@ -1945,8 +1946,521 @@ function drainObservationQueues(internals) {
1945
1946
  for (const waiter of waiting) waiter.admit(false);
1946
1947
  }
1947
1948
 
1949
+ // src/sha256.ts
1950
+ var K = new Uint32Array([
1951
+ 1116352408,
1952
+ 1899447441,
1953
+ 3049323471,
1954
+ 3921009573,
1955
+ 961987163,
1956
+ 1508970993,
1957
+ 2453635748,
1958
+ 2870763221,
1959
+ 3624381080,
1960
+ 310598401,
1961
+ 607225278,
1962
+ 1426881987,
1963
+ 1925078388,
1964
+ 2162078206,
1965
+ 2614888103,
1966
+ 3248222580,
1967
+ 3835390401,
1968
+ 4022224774,
1969
+ 264347078,
1970
+ 604807628,
1971
+ 770255983,
1972
+ 1249150122,
1973
+ 1555081692,
1974
+ 1996064986,
1975
+ 2554220882,
1976
+ 2821834349,
1977
+ 2952996808,
1978
+ 3210313671,
1979
+ 3336571891,
1980
+ 3584528711,
1981
+ 113926993,
1982
+ 338241895,
1983
+ 666307205,
1984
+ 773529912,
1985
+ 1294757372,
1986
+ 1396182291,
1987
+ 1695183700,
1988
+ 1986661051,
1989
+ 2177026350,
1990
+ 2456956037,
1991
+ 2730485921,
1992
+ 2820302411,
1993
+ 3259730800,
1994
+ 3345764771,
1995
+ 3516065817,
1996
+ 3600352804,
1997
+ 4094571909,
1998
+ 275423344,
1999
+ 430227734,
2000
+ 506948616,
2001
+ 659060556,
2002
+ 883997877,
2003
+ 958139571,
2004
+ 1322822218,
2005
+ 1537002063,
2006
+ 1747873779,
2007
+ 1955562222,
2008
+ 2024104815,
2009
+ 2227730452,
2010
+ 2361852424,
2011
+ 2428436474,
2012
+ 2756734187,
2013
+ 3204031479,
2014
+ 3329325298
2015
+ ]);
2016
+ function rotateRight(value, shift) {
2017
+ return value >>> shift | value << 32 - shift;
2018
+ }
2019
+ function sha256(input) {
2020
+ const bytes = new TextEncoder().encode(input);
2021
+ const paddedLength = Math.ceil((bytes.length + 9) / 64) * 64;
2022
+ const padded = new Uint8Array(paddedLength);
2023
+ padded.set(bytes);
2024
+ padded[bytes.length] = 128;
2025
+ const bitLength = bytes.length * 8;
2026
+ const view = new DataView(padded.buffer);
2027
+ view.setUint32(paddedLength - 8, Math.floor(bitLength / 4294967296));
2028
+ view.setUint32(paddedLength - 4, bitLength >>> 0);
2029
+ const hash = new Uint32Array([
2030
+ 1779033703,
2031
+ 3144134277,
2032
+ 1013904242,
2033
+ 2773480762,
2034
+ 1359893119,
2035
+ 2600822924,
2036
+ 528734635,
2037
+ 1541459225
2038
+ ]);
2039
+ const words = new Uint32Array(64);
2040
+ for (let offset = 0; offset < paddedLength; offset += 64) {
2041
+ for (let index = 0; index < 16; index += 1) {
2042
+ words[index] = view.getUint32(offset + index * 4);
2043
+ }
2044
+ for (let index = 16; index < 64; index += 1) {
2045
+ const a2 = words[index - 15];
2046
+ const b2 = words[index - 2];
2047
+ const sigma0 = rotateRight(a2, 7) ^ rotateRight(a2, 18) ^ a2 >>> 3;
2048
+ const sigma1 = rotateRight(b2, 17) ^ rotateRight(b2, 19) ^ b2 >>> 10;
2049
+ words[index] = words[index - 16] + sigma0 + words[index - 7] + sigma1 >>> 0;
2050
+ }
2051
+ let [a, b, c, d, e, f, g, h] = hash;
2052
+ for (let index = 0; index < 64; index += 1) {
2053
+ const sum1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25);
2054
+ const choice = e & f ^ ~e & g;
2055
+ const temp1 = h + sum1 + choice + K[index] + words[index] >>> 0;
2056
+ const sum0 = rotateRight(a, 2) ^ rotateRight(a, 13) ^ rotateRight(a, 22);
2057
+ const majority = a & b ^ a & c ^ b & c;
2058
+ const temp2 = sum0 + majority >>> 0;
2059
+ h = g;
2060
+ g = f;
2061
+ f = e;
2062
+ e = d + temp1 >>> 0;
2063
+ d = c;
2064
+ c = b;
2065
+ b = a;
2066
+ a = temp1 + temp2 >>> 0;
2067
+ }
2068
+ hash[0] = hash[0] + a >>> 0;
2069
+ hash[1] = hash[1] + b >>> 0;
2070
+ hash[2] = hash[2] + c >>> 0;
2071
+ hash[3] = hash[3] + d >>> 0;
2072
+ hash[4] = hash[4] + e >>> 0;
2073
+ hash[5] = hash[5] + f >>> 0;
2074
+ hash[6] = hash[6] + g >>> 0;
2075
+ hash[7] = hash[7] + h >>> 0;
2076
+ }
2077
+ return [...hash].map((value) => value.toString(16).padStart(8, "0")).join("");
2078
+ }
2079
+
2080
+ // src/contract.ts
2081
+ var CAPABILITY_CONTRACT_FORMAT_VERSION = 4;
2082
+ var authorityStates = /* @__PURE__ */ new WeakMap();
2083
+ var componentBindingProofs = /* @__PURE__ */ new WeakMap();
2084
+ var capabilityContractProofs = /* @__PURE__ */ new WeakMap();
2085
+ var externalToolProofs = /* @__PURE__ */ new WeakMap();
2086
+ var unsafeAuthorityTestMode = false;
2087
+ function isUnsafeAuthorityTestMode() {
2088
+ return unsafeAuthorityTestMode;
2089
+ }
2090
+ function observationContract(contract) {
2091
+ return contract;
2092
+ }
2093
+ function actionContract(contract) {
2094
+ return contract;
2095
+ }
2096
+ function defineAgentComponentContract(definition, compiled) {
2097
+ const contract = {
2098
+ ...definition,
2099
+ kind: "agent-component-contract",
2100
+ bind(bindings) {
2101
+ const observations = {};
2102
+ for (const [name, authored] of Object.entries(definition.observations ?? {})) {
2103
+ const runtime = bindings.observations?.[name];
2104
+ if (!runtime?.read) {
2105
+ throw new AgentSurfaceDefinitionError(
2106
+ "INVALID_DEFINITION",
2107
+ `contract "${definition.type}" observation "${name}" has no runtime binding`
2108
+ );
2109
+ }
2110
+ observations[name] = {
2111
+ description: authored.description,
2112
+ output: authored.output,
2113
+ read: runtime.read,
2114
+ ...authored.meta ? { meta: authored.meta } : {},
2115
+ ...authored.timeoutMs !== void 0 ? { timeoutMs: authored.timeoutMs } : {},
2116
+ ...runtime.when ? { when: runtime.when } : {},
2117
+ ...runtime.unavailableReason ? { unavailableReason: runtime.unavailableReason } : {},
2118
+ ...runtime.policies ? { policies: runtime.policies } : {}
2119
+ };
2120
+ }
2121
+ const actions = {};
2122
+ for (const [name, authored] of Object.entries(definition.actions ?? {})) {
2123
+ const runtime = bindings.actions?.[name];
2124
+ if (!runtime?.execute) {
2125
+ throw new AgentSurfaceDefinitionError(
2126
+ "INVALID_DEFINITION",
2127
+ `contract "${definition.type}" action "${name}" has no runtime binding`
2128
+ );
2129
+ }
2130
+ actions[name] = {
2131
+ description: authored.description,
2132
+ input: authored.input,
2133
+ ...authored.output ? { output: authored.output } : {},
2134
+ effect: authored.effect,
2135
+ execute: runtime.execute,
2136
+ ...authored.idempotent !== void 0 ? { idempotent: authored.idempotent } : {},
2137
+ ...authored.reversible !== void 0 ? { reversible: authored.reversible } : {},
2138
+ ...authored.confirmation !== void 0 ? { confirmation: authored.confirmation } : {},
2139
+ ...authored.audit !== void 0 ? { audit: authored.audit } : {},
2140
+ ...authored.meta ? { meta: authored.meta } : {},
2141
+ ...authored.timeoutMs !== void 0 ? { timeoutMs: authored.timeoutMs } : {},
2142
+ ...authored.concurrency ? { concurrency: authored.concurrency } : {},
2143
+ ...runtime.when ? { when: runtime.when } : {},
2144
+ ...runtime.unavailableReason ? { unavailableReason: runtime.unavailableReason } : {},
2145
+ ...runtime.precondition ? { precondition: runtime.precondition } : {},
2146
+ ...runtime.policies ? { policies: runtime.policies } : {}
2147
+ };
2148
+ }
2149
+ const bound = {
2150
+ type: definition.type,
2151
+ description: definition.description,
2152
+ ...bindings.instanceId !== void 0 ? { instanceId: bindings.instanceId } : {},
2153
+ ...bindings.parent ? { parent: bindings.parent } : {},
2154
+ ...definition.meta ? { meta: definition.meta } : {},
2155
+ ...bindings.internal ? { internal: bindings.internal } : {},
2156
+ ...bindings.policies ? { policies: bindings.policies } : {},
2157
+ ...definition.origin ? { origin: definition.origin } : {},
2158
+ ...definition.priority !== void 0 ? { priority: definition.priority } : {},
2159
+ ...bindings.enabled !== void 0 ? { enabled: bindings.enabled } : {},
2160
+ ...Object.keys(observations).length > 0 ? { observations } : {},
2161
+ ...Object.keys(actions).length > 0 ? { actions } : {},
2162
+ ...bindings.procedures ? { procedures: bindings.procedures } : {}
2163
+ };
2164
+ if (compiled) componentBindingProofs.set(bound, compiled);
2165
+ return bound;
2166
+ }
2167
+ };
2168
+ return contract;
2169
+ }
2170
+ function defineAgentProcedureContract(definition, compiled) {
2171
+ const contract = {
2172
+ kind: "agent-procedure-contract",
2173
+ definition
2174
+ };
2175
+ if (compiled) capabilityContractProofs.set(contract, compiled);
2176
+ return contract;
2177
+ }
2178
+ function defineExternalAgentToolContract(definition, compiled) {
2179
+ const contract = {
2180
+ kind: "external-agent-tool-contract",
2181
+ definition,
2182
+ bind(binding) {
2183
+ if (!compiled) {
2184
+ throw new AgentSurfaceDefinitionError(
2185
+ "INVALID_DEFINITION",
2186
+ `external contract "${definition.id}" has no compiler provenance`
2187
+ );
2188
+ }
2189
+ const tool = {
2190
+ name: definition.id,
2191
+ description: definition.description,
2192
+ inputSchema: definition.input.jsonSchema,
2193
+ execute: binding.execute
2194
+ };
2195
+ externalToolProofs.set(tool, compiled);
2196
+ return tool;
2197
+ }
2198
+ };
2199
+ if (compiled) capabilityContractProofs.set(contract, compiled);
2200
+ return contract;
2201
+ }
2202
+ function deriveAgentComponentBinding(source, derived) {
2203
+ const proof = componentBindingProofs.get(source);
2204
+ if (proof) componentBindingProofs.set(derived, proof);
2205
+ return derived;
2206
+ }
2207
+ function authorizeAgentProcedureBinding(contract, definition) {
2208
+ const token = capabilityContractProofs.get(contract);
2209
+ if (token) {
2210
+ componentBindingProofs.set(definition, {
2211
+ manifestHash: token.manifestHash,
2212
+ declarationId: token.declarationId,
2213
+ capabilities: { [token.capabilityId]: token }
2214
+ });
2215
+ }
2216
+ return definition;
2217
+ }
2218
+ function manifestIndex(manifest) {
2219
+ if (manifest.formatVersion !== CAPABILITY_CONTRACT_FORMAT_VERSION || manifest.completeness?.status !== "proven" || typeof manifest.hash !== "string" || manifest.hash.length === 0) {
2220
+ throw new AgentSurfaceDefinitionError("INVALID_DEFINITION", "invalid compiled capability manifest");
2221
+ }
2222
+ const index = /* @__PURE__ */ new Map();
2223
+ for (const entry of manifest.capabilities) {
2224
+ const { contractHash, targets: _targets, ...contract } = entry;
2225
+ if (sha256(canonicalContractJson(contract)) !== contractHash) {
2226
+ throw new AgentSurfaceDefinitionError(
2227
+ "INVALID_DEFINITION",
2228
+ `compiled contract hash is invalid for "${entry.capabilityId}"`
2229
+ );
2230
+ }
2231
+ const key = `${entry.declarationId}\0${entry.capabilityId}`;
2232
+ if (index.has(key)) {
2233
+ throw new AgentSurfaceDefinitionError(
2234
+ "DUPLICATE_CAPABILITY",
2235
+ `duplicate compiled declaration "${entry.declarationId}" for "${entry.capabilityId}"`
2236
+ );
2237
+ }
2238
+ index.set(key, entry);
2239
+ }
2240
+ const { hash, ...payload } = manifest;
2241
+ if (sha256(canonicalContractJson(payload)) !== hash) {
2242
+ throw new AgentSurfaceDefinitionError("INVALID_DEFINITION", "compiled manifest hash is invalid");
2243
+ }
2244
+ return index;
2245
+ }
2246
+ function canonicalContractValue(value) {
2247
+ if (value === null) return "null";
2248
+ if (value === void 0) return "null";
2249
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
2250
+ if (typeof value === "number") {
2251
+ if (!Number.isFinite(value)) throw new Error("contract contains a non-finite number");
2252
+ return JSON.stringify(Object.is(value, -0) ? 0 : value);
2253
+ }
2254
+ if (Array.isArray(value)) return `[${value.map(canonicalContractValue).join(",")}]`;
2255
+ const record = value;
2256
+ return `{${Object.keys(record).sort().filter((key) => record[key] !== void 0).map((key) => `${JSON.stringify(key)}:${canonicalContractValue(record[key])}`).join(",")}}`;
2257
+ }
2258
+ function canonicalContractJson(value) {
2259
+ return `${canonicalContractValue(value)}
2260
+ `;
2261
+ }
2262
+ function createCapabilityAuthority(manifest) {
2263
+ const snapshot = deepFreeze(
2264
+ JSON.parse(JSON.stringify(manifest))
2265
+ );
2266
+ const authority = Object.freeze({ manifest: snapshot });
2267
+ authorityStates.set(authority, { manifest: snapshot, index: manifestIndex(snapshot) });
2268
+ return authority;
2269
+ }
2270
+ function authorityState(authority) {
2271
+ const state = authorityStates.get(authority);
2272
+ if (!state) {
2273
+ throw new AgentSurfaceDefinitionError(
2274
+ "INVALID_DEFINITION",
2275
+ "invalid capability authority: use compiler-generated authority"
2276
+ );
2277
+ }
2278
+ return state;
2279
+ }
2280
+ function assertCapabilityAuthority(authority) {
2281
+ authorityState(authority);
2282
+ }
2283
+ function assertToken(token, manifest, index) {
2284
+ if (token.manifestHash !== manifest.hash) {
2285
+ throw new AgentSurfaceDefinitionError(
2286
+ "INVALID_DEFINITION",
2287
+ `stale compiler token for "${token.capabilityId}": manifest hash mismatch`
2288
+ );
2289
+ }
2290
+ const declared = index.get(`${token.declarationId}\0${token.capabilityId}`);
2291
+ if (!declared) {
2292
+ throw new AgentSurfaceDefinitionError(
2293
+ "INVALID_DEFINITION",
2294
+ `unknown compiled declaration "${token.declarationId}" for "${token.capabilityId}"`
2295
+ );
2296
+ }
2297
+ if (declared.contractHash !== token.contractHash) {
2298
+ throw new AgentSurfaceDefinitionError(
2299
+ "INVALID_DEFINITION",
2300
+ `compiled contract hash mismatch for "${token.capabilityId}"`
2301
+ );
2302
+ }
2303
+ }
2304
+ var CONFIRMATION_RANK = { never: 0, optional: 1, required: 2 };
2305
+ function effectiveProcedureConfirmation(binding) {
2306
+ if (binding.ref.requiresApproval || binding.config.confirmation === "required") return "required";
2307
+ return binding.config.confirmation ?? "never";
2308
+ }
2309
+ function runtimeCapabilities(definition) {
2310
+ const sharedPolicies = definition.policies ?? [];
2311
+ return [
2312
+ ...Object.entries(definition.observations ?? {}).map(([name, observation2]) => ({
2313
+ capabilityId: `view:${definition.type}.${name}`,
2314
+ kind: "observation",
2315
+ description: observation2.description,
2316
+ effect: "read",
2317
+ outputSchema: observation2.output.jsonSchema,
2318
+ policies: [...sharedPolicies, ...observation2.policies ?? []]
2319
+ })),
2320
+ ...Object.entries(definition.actions ?? {}).map(([name, action2]) => ({
2321
+ capabilityId: `view:${definition.type}.${name}`,
2322
+ kind: "action",
2323
+ description: action2.description,
2324
+ effect: action2.effect,
2325
+ inputSchema: action2.input.jsonSchema,
2326
+ ...action2.output ? { outputSchema: action2.output.jsonSchema } : {},
2327
+ confirmation: action2.confirmation ?? "never",
2328
+ policies: [...sharedPolicies, ...action2.policies ?? []]
2329
+ })),
2330
+ ...(definition.procedures ?? []).map((binding) => ({
2331
+ capabilityId: binding.ref.id,
2332
+ kind: "procedure",
2333
+ description: binding.ref.description,
2334
+ effect: binding.ref.effect,
2335
+ inputSchema: binding.ref.inputSchema,
2336
+ ...binding.ref.outputSchema ? { outputSchema: binding.ref.outputSchema } : {},
2337
+ confirmation: effectiveProcedureConfirmation(binding),
2338
+ policies: [...sharedPolicies, ...binding.config.policies ?? []]
2339
+ }))
2340
+ ];
2341
+ }
2342
+ function assertPolicyCoverage(declared, runtime, capabilityId) {
2343
+ for (const attachment of declared ?? []) {
2344
+ const policy = runtime.find((candidate) => candidate.name === attachment.name);
2345
+ const phaseImplemented = !attachment.phase || attachment.phase === "discovery" && typeof policy?.onDiscovery === "function" || attachment.phase === "authorize" && typeof policy?.onAuthorize === "function" || attachment.phase === "invoke" && typeof policy?.onInvoke === "function";
2346
+ if (!policy || !phaseImplemented) {
2347
+ throw new AgentSurfaceDefinitionError(
2348
+ "INVALID_DEFINITION",
2349
+ `capability "${capabilityId}" omits required policy "${attachment.name}"${attachment.phase ? ` at ${attachment.phase}` : ""}`
2350
+ );
2351
+ }
2352
+ }
2353
+ }
2354
+ function assertRuntimeMatchesContract(runtime, declared) {
2355
+ const mismatch = (field) => {
2356
+ throw new AgentSurfaceDefinitionError(
2357
+ "INVALID_DEFINITION",
2358
+ `runtime ${field} mismatch for "${runtime.capabilityId}"`
2359
+ );
2360
+ };
2361
+ if (declared.kind !== runtime.kind) mismatch("kind");
2362
+ if (declared.description !== runtime.description) mismatch("description");
2363
+ if (declared.effect !== runtime.effect) mismatch("effect");
2364
+ if (!jsonDeepEqual(declared.inputSchema, runtime.inputSchema)) {
2365
+ mismatch("input schema");
2366
+ }
2367
+ if (!jsonDeepEqual(declared.outputSchema, runtime.outputSchema)) {
2368
+ mismatch("output schema");
2369
+ }
2370
+ const declaredConfirmation = declared.confirmation ?? "never";
2371
+ const runtimeConfirmation = runtime.confirmation ?? "never";
2372
+ if (CONFIRMATION_RANK[runtimeConfirmation] < CONFIRMATION_RANK[declaredConfirmation]) {
2373
+ mismatch("confirmation");
2374
+ }
2375
+ assertPolicyCoverage(declared.policies, runtime.policies, runtime.capabilityId);
2376
+ }
2377
+ function assertDefinitionAuthorized(definition, authority) {
2378
+ const state = authorityState(authority);
2379
+ const provenance = componentBindingProofs.get(definition);
2380
+ if (!provenance) {
2381
+ throw new AgentSurfaceDefinitionError(
2382
+ "INVALID_DEFINITION",
2383
+ `raw registration "${definition.type}" rejected: bind a compiler-generated contract`
2384
+ );
2385
+ }
2386
+ if (provenance.manifestHash !== state.manifest.hash) {
2387
+ throw new AgentSurfaceDefinitionError(
2388
+ "INVALID_DEFINITION",
2389
+ `stale contract "${provenance.declarationId}": manifest hash mismatch`
2390
+ );
2391
+ }
2392
+ const capabilities = runtimeCapabilities(definition);
2393
+ const expected = capabilities.map((capability) => capability.capabilityId);
2394
+ for (const capability of capabilities) {
2395
+ const capabilityId = capability.capabilityId;
2396
+ const token = provenance.capabilities[capabilityId];
2397
+ if (!token) {
2398
+ throw new AgentSurfaceDefinitionError(
2399
+ "INVALID_DEFINITION",
2400
+ `capability "${capabilityId}" is absent from compiled contract "${provenance.declarationId}"`
2401
+ );
2402
+ }
2403
+ assertToken(token, state.manifest, state.index);
2404
+ const declared = state.index.get(`${token.declarationId}\0${token.capabilityId}`);
2405
+ assertRuntimeMatchesContract(capability, declared);
2406
+ }
2407
+ for (const capabilityId of Object.keys(provenance.capabilities)) {
2408
+ if (!expected.includes(capabilityId)) {
2409
+ throw new AgentSurfaceDefinitionError(
2410
+ "INVALID_DEFINITION",
2411
+ `binding for "${provenance.declarationId}" omits compiled capability "${capabilityId}"`
2412
+ );
2413
+ }
2414
+ }
2415
+ }
2416
+ function createAgentExposureGateway(authority) {
2417
+ const state = authorityState(authority);
2418
+ return {
2419
+ expose(tools) {
2420
+ return tools.map((tool) => {
2421
+ const token = externalToolProofs.get(tool);
2422
+ if (!token) {
2423
+ throw new AgentSurfaceDefinitionError(
2424
+ "INVALID_DEFINITION",
2425
+ `raw provider tool "${tool.name}" rejected by compiled exposure gateway`
2426
+ );
2427
+ }
2428
+ assertToken(token, state.manifest, state.index);
2429
+ const declared = state.index.get(`${token.declarationId}\0${token.capabilityId}`);
2430
+ if (declared.kind !== "external") {
2431
+ throw new AgentSurfaceDefinitionError(
2432
+ "INVALID_DEFINITION",
2433
+ `runtime kind mismatch for "${tool.name}"`
2434
+ );
2435
+ }
2436
+ if (declared.capabilityId !== tool.name || declared.description !== tool.description) {
2437
+ throw new AgentSurfaceDefinitionError(
2438
+ "INVALID_DEFINITION",
2439
+ `runtime external tool mismatch for "${tool.name}"`
2440
+ );
2441
+ }
2442
+ if (!jsonDeepEqual(declared.inputSchema, tool.inputSchema)) {
2443
+ throw new AgentSurfaceDefinitionError(
2444
+ "INVALID_DEFINITION",
2445
+ `runtime input schema mismatch for "${tool.name}"`
2446
+ );
2447
+ }
2448
+ return tool;
2449
+ });
2450
+ }
2451
+ };
2452
+ }
2453
+
1948
2454
  // src/registry.ts
1949
2455
  function createAgentSurfaceRegistry(options) {
2456
+ const unsafeTestMode = isUnsafeAuthorityTestMode();
2457
+ if (!options?.authority && !unsafeTestMode) {
2458
+ throw new AgentSurfaceDefinitionError(
2459
+ "INVALID_DEFINITION",
2460
+ "createAgentSurfaceRegistry requires a compiler-generated capability authority"
2461
+ );
2462
+ }
2463
+ if (options?.authority) assertCapabilityAuthority(options.authority);
1950
2464
  const environment2 = options?.environment ?? "production";
1951
2465
  const limits = { ...DEFAULT_LIMITS, ...options?.limits ?? {} };
1952
2466
  const now = options?.now ?? (() => Date.now());
@@ -2093,6 +2607,10 @@ function createAgentSurfaceRegistry(options) {
2093
2607
  surfaceId: internals.surfaceId,
2094
2608
  register(definition) {
2095
2609
  if (internals.disposed) throw new Error("register() called on a disposed registry");
2610
+ if (options?.authority) assertDefinitionAuthorized(definition, options.authority);
2611
+ else if (!unsafeTestMode) {
2612
+ throw new AgentSurfaceDefinitionError("INVALID_DEFINITION", "capability authority unavailable");
2613
+ }
2096
2614
  validateComponentDefinition(definition, limits, {
2097
2615
  hasProcedureExecutor: internals.executor !== void 0
2098
2616
  });
@@ -2781,20 +3299,30 @@ export {
2781
3299
  AgentSchemaError,
2782
3300
  AgentSurfaceDefinitionError,
2783
3301
  AgentSurfaceError,
3302
+ CAPABILITY_CONTRACT_FORMAT_VERSION,
2784
3303
  CONFIRMATION_ESCALATION,
2785
3304
  DEFAULT_LIMITS,
2786
3305
  MAX_ID_LENGTH,
2787
3306
  MAX_WIRE_NAME_LENGTH,
2788
3307
  action,
3308
+ actionContract,
3309
+ assertDefinitionAuthorized,
2789
3310
  assignWireNames,
2790
3311
  audit,
2791
3312
  authenticated,
3313
+ authorizeAgentProcedureBinding,
2792
3314
  composeInvokeChain,
2793
3315
  consoleAuditSink,
3316
+ createAgentExposureGateway,
2794
3317
  createAgentSurfaceRegistry,
2795
3318
  createAgentToolset,
3319
+ createCapabilityAuthority,
2796
3320
  decodeWireName,
2797
3321
  defineAgentComponent,
3322
+ defineAgentComponentContract,
3323
+ defineAgentProcedureContract,
3324
+ defineExternalAgentToolContract,
3325
+ deriveAgentComponentBinding,
2798
3326
  emptyObjectSchema,
2799
3327
  encodeWireName,
2800
3328
  encodeWireNameForInstance,
@@ -2812,6 +3340,7 @@ export {
2812
3340
  jsonDeepEqual,
2813
3341
  memoryAuditSink,
2814
3342
  observation,
3343
+ observationContract,
2815
3344
  parseCapabilityId,
2816
3345
  rateLimit,
2817
3346
  requireConfirmation,