@agent-surface/core 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,102 +1,5 @@
1
- /** JSON value constraint: every agent-crossing payload MUST be a JsonValue. */
2
- type JsonValue = string | number | boolean | null | JsonValue[] | {
3
- [key: string]: JsonValue;
4
- };
5
- /** A JSON Schema document restricted to the supported subset (docs/03 D19). */
6
- type JsonSchema = Record<string, unknown>;
7
- type AgentEnvironment = "development" | "production" | "test";
8
- type AgentEffect = "read" | "local-state" | "navigation" | "server-query" | "server-mutation" | "external-side-effect" | "destructive";
9
- type AgentProcedureEffect = "server-query" | "server-mutation" | "external-side-effect" | "destructive";
10
- interface AgentConsumer {
11
- id: string;
12
- kind: "embedded" | "webmcp" | "mcp-bridge" | "test" | "other";
13
- /** Free-form grant strings interpreted by host policies. */
14
- grants?: string[];
15
- }
16
- interface AgentRouteInfo {
17
- path: string;
18
- params?: Record<string, string>;
19
- }
20
- /**
21
- * Concurrency group for an action or procedure reference (D25). Not
22
- * model-visible: it is runtime behavior, not planning information.
23
- *
24
- * - `instance` (default) — every action on the registration shares one FIFO
25
- * queue. Safest: two actions on the same component can never interleave.
26
- * - `capability` — one queue per capability, so a slow export does not block
27
- * closing a drawer.
28
- * - `key` — one queue per author-chosen key, for actions that contend over
29
- * the same resource across capabilities.
30
- * - `parallel` — bounded parallelism; `max` is required and must be ≥ 1.
31
- *
32
- * `queueDepth` overrides `limits.actionQueueDepth` for this group only.
33
- */
34
- type AgentConcurrency = {
35
- mode: "instance";
36
- queueDepth?: number;
37
- } | {
38
- mode: "capability";
39
- queueDepth?: number;
40
- } | {
41
- mode: "key";
42
- key: string;
43
- queueDepth?: number;
44
- } | {
45
- mode: "parallel";
46
- max: number;
47
- queueDepth?: number;
48
- };
49
- interface AgentSurfaceLimits {
50
- maxComponentDescription: number;
51
- maxCapabilityDescription: number;
52
- maxMetaBytes: number;
53
- maxOutputBytes: number;
54
- maxSchemaBytes: number;
55
- maxSchemaDepth: number;
56
- observationTimeoutMs: number;
57
- actionTimeoutMs: number;
58
- procedureTimeoutMs: number;
59
- actionQueueDepth: number;
60
- maxConcurrentObservationsPerConsumer: number;
61
- maxConcurrentObservationsTotal: number;
62
- maxQueuedObservationsPerConsumer: number;
63
- dedupeCacheSize: number;
64
- dedupeCacheTtlMs: number;
65
- tombstoneSize: number;
66
- tombstoneTtlMs: number;
67
- confirmationTtlMs: number;
68
- maxPendingConfirmations: number;
69
- }
70
- declare const DEFAULT_LIMITS: AgentSurfaceLimits;
71
- type Unsubscribe = () => void;
72
-
73
- /** The closed agent-facing error enum — one runtime source, cross-validated
74
- * against spec/error-matrix.json (docs/07 §principles, AS-ERR-001). */
75
- declare const AGENT_CAPABILITY_ERROR_CODES: readonly ["CAPABILITY_NOT_FOUND", "CAPABILITY_NOT_AVAILABLE", "AMBIGUOUS_INSTANCE", "COMPONENT_UNMOUNTED", "STALE_CAPABILITY", "INVOCATION_CONFLICT", "INVALID_INPUT", "NOT_AUTHENTICATED", "NOT_AUTHORIZED", "PRECONDITION_FAILED", "CONFIRMATION_REQUIRED", "CONFIRMATION_INVALID", "RATE_LIMITED", "TIMEOUT", "CANCELLED", "EXECUTION_FAILED"];
76
- type AgentCapabilityErrorCode = (typeof AGENT_CAPABILITY_ERROR_CODES)[number];
77
- type AgentErrorRetry = "no" | "yes" | "after-refresh" | "after-delay" | "with-confirmation" | "with-changes";
78
- interface AgentCapabilityErrorPayload {
79
- code: AgentCapabilityErrorCode;
80
- /** Agent-safe, imperative, ≤ 300 chars. */
81
- message: string;
82
- retry: AgentErrorRetry;
83
- /** Code-specific, agent-safe, JsonValue only. */
84
- details?: Record<string, JsonValue>;
85
- }
86
- /** Thrown form used inside policies/handlers; serialized at the boundary. */
87
- declare class AgentSurfaceError extends Error {
88
- readonly payload: AgentCapabilityErrorPayload;
89
- constructor(payload: AgentCapabilityErrorPayload, opts?: {
90
- cause?: unknown;
91
- });
92
- }
93
- declare function isAgentSurfaceError(e: unknown): e is AgentSurfaceError;
94
- type AgentSurfaceDefinitionErrorCode = "INVALID_ID" | "INVALID_DEFINITION" | "UNSUPPORTED_SCHEMA" | "PLANE_VIOLATION" | "DUPLICATE_CAPABILITY" | "LIMIT_EXCEEDED";
95
- /** Structural defects at registration time. Always thrown, never agent-facing. */
96
- declare class AgentSurfaceDefinitionError extends Error {
97
- readonly code: AgentSurfaceDefinitionErrorCode;
98
- constructor(code: AgentSurfaceDefinitionErrorCode, message: string);
99
- }
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';
100
3
 
101
4
  /**
102
5
  * Canonical ID grammar (docs/01 §identity):
@@ -182,664 +85,6 @@ declare function assignWireNames(entries: readonly WireNameEntry[]): WireNameAss
182
85
  */
183
86
  declare function decodeWireName(name: string): string | undefined;
184
87
 
185
- interface AgentSchemaIssue {
186
- path: string;
187
- message: string;
188
- }
189
- /** Thrown by AgentSchema.parse on invalid input; carries safe, structured issues. */
190
- declare class AgentSchemaError extends Error {
191
- readonly issues: AgentSchemaIssue[];
192
- constructor(issues: AgentSchemaIssue[]);
193
- }
194
- interface AgentSchema<T> {
195
- /** Agent-visible JSON Schema (draft 2020-12, restricted subset). */
196
- readonly jsonSchema: JsonSchema;
197
- /**
198
- * Validates and returns a typed value. MUST throw `AgentSchemaError`
199
- * (with a safe, structured message) on invalid input.
200
- */
201
- parse(value: unknown): T;
202
- }
203
- /** Minimal Standard Schema mirror (https://standardschema.dev). */
204
- interface StandardSchemaV1<I = unknown, O = I> {
205
- readonly "~standard": {
206
- readonly version: 1;
207
- readonly vendor: string;
208
- validate(value: unknown): {
209
- value: O;
210
- issues?: undefined;
211
- } | {
212
- issues: ReadonlyArray<{
213
- message: string;
214
- path?: ReadonlyArray<PropertyKey | {
215
- key: PropertyKey;
216
- }>;
217
- }>;
218
- } | Promise<unknown>;
219
- readonly types?: {
220
- readonly input: I;
221
- readonly output: O;
222
- } | undefined;
223
- };
224
- }
225
- /**
226
- * Wraps any Standard Schema (Zod ≥3.24, Valibot, ArkType) as an AgentSchema.
227
- * The JSON Schema MUST be supplied explicitly — core does not depend on a
228
- * converter (docs/03, D20).
229
- */
230
- declare function fromStandardSchema<T>(schema: StandardSchemaV1<unknown, T>, options: {
231
- jsonSchema: JsonSchema;
232
- }): AgentSchema<T>;
233
- /**
234
- * Builds an AgentSchema from a raw JSON Schema, validated by the built-in
235
- * minimal structural validator covering exactly the supported subset.
236
- */
237
- declare function fromJsonSchema<T = JsonValue>(schema: JsonSchema): AgentSchema<T>;
238
- /** Convenience for actions with no input / observations of constant shape. */
239
- declare const emptyObjectSchema: AgentSchema<Record<string, never>>;
240
- interface SchemaSubsetResult {
241
- ok: boolean;
242
- reason?: string;
243
- }
244
- /**
245
- * Validates that a JSON Schema document stays inside the D19 subset.
246
- * Anything outside MUST be rejected at registration with INVALID_DEFINITION /
247
- * UNSUPPORTED_SCHEMA (docs/03, docs/07).
248
- */
249
- declare function validateJsonSchemaDocument(schema: JsonSchema, limits: {
250
- maxSchemaBytes: number;
251
- maxSchemaDepth: number;
252
- }): SchemaSubsetResult;
253
- /**
254
- * Validates a value against a subset schema. Returns issues (empty = valid).
255
- * JSON Schema semantics: `default` is annotation-only and never applied.
256
- */
257
- declare function validateValueAgainstSchema(value: unknown, schema: unknown, root: JsonSchema, path: string): AgentSchemaIssue[];
258
-
259
- interface AgentInvocation {
260
- /** Idempotency key. Adapters SHOULD pass their tool-call id. Generated if absent. */
261
- invocationId?: string;
262
- capabilityId: string;
263
- /** Required when >1 live instance of the target component exists. */
264
- instanceId?: string;
265
- /** Staleness token from discovery. Adapters SHOULD always send it. */
266
- registrationId?: string;
267
- /** Version hint; enforced only for destructive/external effects. */
268
- surfaceVersion?: string;
269
- input?: JsonValue;
270
- /** Evidence from a resolved confirmation (docs/06). */
271
- confirmationId?: string;
272
- }
273
- interface InvokeOptions {
274
- consumer?: AgentConsumer;
275
- signal?: AbortSignal;
276
- timeoutMs?: number;
277
- }
278
- type AgentInvocationResult = {
279
- status: "ok";
280
- invocationId: string;
281
- capabilityId: string;
282
- output?: JsonValue;
283
- surfaceVersion: string;
284
- /** Set when the surface changed during execution. */
285
- surfaceChanged?: boolean;
286
- } | {
287
- status: "error";
288
- invocationId: string;
289
- capabilityId: string;
290
- error: AgentCapabilityErrorPayload;
291
- surfaceVersion: string;
292
- surfaceChanged?: boolean;
293
- };
294
-
295
- interface AuditEvent {
296
- at: string;
297
- type: "registration" | "unregistration" | "registration-rejected" | "invocation-started" | "invocation-settled" | "confirmation-requested" | "confirmation-approved" | "confirmation-denied" | "confirmation-expired" | "confirmation-consumed" | "late-settlement" | "collision-suspected";
298
- capabilityId?: string;
299
- registrationId?: string;
300
- invocationId?: string;
301
- consumerId?: string;
302
- status?: "ok" | "error";
303
- code?: AgentCapabilityErrorCode;
304
- durationMs?: number;
305
- /** Time spent waiting for a concurrency slot (docs/06 §audit; distinct
306
- * from execution — §7.1 observability). Settled invocations only. */
307
- queueWaitMs?: number;
308
- /** Time spent inside the handler/executor guards, excluding queue wait. */
309
- executionMs?: number;
310
- /** Present only for capabilities with audit: "full"; size-capped. */
311
- payload?: {
312
- input?: JsonValue;
313
- output?: JsonValue;
314
- };
315
- }
316
- interface AuditSink {
317
- /** MUST NOT throw; MUST be non-blocking. */
318
- record(event: AuditEvent): void;
319
- }
320
- declare function memoryAuditSink(opts?: {
321
- capacity?: number;
322
- }): AuditSink & {
323
- events(): AuditEvent[];
324
- };
325
- declare function consoleAuditSink(): AuditSink;
326
-
327
- type DiscoveryDecision = {
328
- decision: "expose";
329
- } | {
330
- decision: "disable";
331
- reason: string;
332
- } | {
333
- decision: "hide";
334
- };
335
- interface AgentPolicyContext {
336
- capabilityId: string;
337
- plane: "view" | "domain";
338
- kind: "observation" | "action" | "procedure";
339
- effect: AgentEffect;
340
- registrationId: string;
341
- consumer: AgentConsumer;
342
- host: Readonly<Record<string, unknown>>;
343
- meta: {
344
- component?: Record<string, JsonValue>;
345
- capability?: Record<string, JsonValue>;
346
- };
347
- internal: Readonly<Record<string, unknown>>;
348
- /** Registry environment (additive convenience for built-ins). */
349
- environment: AgentEnvironment;
350
- /** Registry's injectable clock — built-ins MUST use this, never Date.now(). */
351
- now(): number;
352
- }
353
- /** Phase-4 context: no agent input is available here, by construction (D21). */
354
- type AgentAuthorizationContext = AgentPolicyContext;
355
- /** Phase-6 context: only the validated effective input is visible (D21). */
356
- interface AgentInvocationPolicyContext extends AgentAuthorizationContext {
357
- invocationId: string;
358
- effectiveInput: JsonValue;
359
- }
360
- interface AgentPolicy {
361
- name: string;
362
- /**
363
- * Discovery-time filter. MUST be synchronous, cheap, side-effect free.
364
- * Advisory: hides/disables in catalogs. Default when absent: expose.
365
- */
366
- onDiscovery?(ctx: AgentPolicyContext): DiscoveryDecision;
367
- /**
368
- * Pre-input authority gate (pipeline phase 4): authn/authz/tenant/
369
- * environment/input-independent rate. MAY be async. Onion order; call
370
- * next() to proceed. Throw AgentSurfaceError to deny.
371
- */
372
- onAuthorize?(ctx: AgentAuthorizationContext, next: () => Promise<AgentInvocationResult>): Promise<AgentInvocationResult>;
373
- /**
374
- * Post-input invocation gate (pipeline phase 6). Receives ONLY the
375
- * validated effective input — never raw agent input (D21).
376
- */
377
- onInvoke?(ctx: AgentInvocationPolicyContext, next: () => Promise<AgentInvocationResult>): Promise<AgentInvocationResult>;
378
- }
379
- /**
380
- * Marker read by the invocation pipeline: policies carrying it escalate the
381
- * capability's confirmation requirement (docs/06 requireConfirmation).
382
- */
383
- declare const CONFIRMATION_ESCALATION: unique symbol;
384
- interface ConfirmationEscalation {
385
- /** Evaluated at phase 6 over the validated effective input (D21). */
386
- if?: (ctx: AgentPolicyContext & {
387
- effectiveInput: JsonValue;
388
- }) => boolean;
389
- summary?: (effectiveInput: JsonValue) => string;
390
- }
391
- /** Most-restrictive-wins composition of discovery decisions (docs/06). */
392
- declare function evaluateDiscovery(policies: ReadonlyArray<AgentPolicy>, ctx: AgentPolicyContext): DiscoveryDecision;
393
- /** Onion composition of onInvoke handlers (registry outermost, phase 6). */
394
- declare function composeInvokeChain(policies: ReadonlyArray<AgentPolicy>, ctx: AgentInvocationPolicyContext, core: () => Promise<AgentInvocationResult>): Promise<AgentInvocationResult>;
395
- /** Requires ctx.host[key] (default "user"). Fails NOT_AUTHENTICATED; hides. */
396
- declare function authenticated(opts?: {
397
- key?: string;
398
- }): AgentPolicy;
399
- /** Delegates to a host authorizer. Fails NOT_AUTHORIZED; hides at discovery. */
400
- declare function hasPermission(permission: string, check: (host: Record<string, unknown>, permission: string) => boolean): AgentPolicy;
401
- /** Tenant boundary: hides unless current(host) === expected(ctx). */
402
- declare function tenantBoundary(opts: {
403
- current: (host: Record<string, unknown>) => string | undefined;
404
- expected: (ctx: AgentPolicyContext) => string | undefined;
405
- }): AgentPolicy;
406
- /** Restricts to environments. Others: hidden. */
407
- declare function environment(allowed: AgentEnvironment[]): AgentPolicy;
408
- /**
409
- * Token bucket per (consumer, capability). Advisory, input-independent —
410
- * runs pre-input (phase 4). Author input-aware rate policies as onInvoke.
411
- * Fails RATE_LIMITED. Uses the injectable clock (AS-POLICY-001).
412
- */
413
- declare function rateLimit(opts: {
414
- limit: number;
415
- windowMs: number;
416
- }): AgentPolicy;
417
- /** Escalates confirmation to "required" (optionally conditionally).
418
- * Predicates run at phase 6 over the validated effective input (D21). */
419
- declare function requireConfirmation(opts?: {
420
- if?: (ctx: AgentPolicyContext & {
421
- effectiveInput: JsonValue;
422
- }) => boolean;
423
- summary?: (effectiveInput: JsonValue) => string;
424
- }): AgentPolicy;
425
- /** Forwards invocation events to a sink at the given detail level.
426
- * Runs at phase 6 (onInvoke): its enrichment sees the effective input. */
427
- declare function audit(sink?: AuditSink, level?: "metadata" | "full"): AgentPolicy;
428
-
429
- interface AgentReadContext {
430
- capabilityId: string;
431
- registrationId: string;
432
- consumer: AgentConsumer;
433
- /** Host context (user, tenant, env…) from RegistryOptions.context(). */
434
- host: Readonly<Record<string, unknown>>;
435
- }
436
- interface AgentActionContext extends AgentReadContext {
437
- invocationId: string;
438
- /** Aborted on timeout, external cancellation, or unmount. Cooperative. */
439
- signal: AbortSignal;
440
- /** Present iff this invocation carries approved confirmation evidence. */
441
- confirmation?: {
442
- id: string;
443
- approvedAt: string;
444
- };
445
- }
446
- interface PreconditionFailure {
447
- message: string;
448
- details?: Record<string, JsonValue>;
449
- }
450
- interface AgentObservationDefinition<TOut extends JsonValue> {
451
- /** Agent-visible description, ≤ 300 chars. */
452
- description: string;
453
- output: AgentSchema<TOut>;
454
- /**
455
- * Reads current semantic state. MUST be side-effect free. SHOULD be
456
- * synchronous; MAY return a promise (subject to observation timeout).
457
- */
458
- read(ctx: AgentReadContext): TOut | Promise<TOut>;
459
- /** Availability predicate, re-evaluated at snapshot and at invocation. */
460
- when?: () => boolean;
461
- unavailableReason?: string | (() => string);
462
- policies?: AgentPolicy[];
463
- meta?: Record<string, JsonValue>;
464
- timeoutMs?: number;
465
- }
466
- interface AgentActionDefinition<TIn extends JsonValue, TOut extends JsonValue | void = void> {
467
- description: string;
468
- input: AgentSchema<TIn>;
469
- output?: AgentSchema<Exclude<TOut, void>>;
470
- /** View actions MUST be "local-state" | "navigation" (plane rule, docs/01). */
471
- effect: "local-state" | "navigation";
472
- idempotent?: boolean;
473
- reversible?: boolean;
474
- confirmation?: "never" | "optional" | "required";
475
- audit?: "none" | "metadata" | "full";
476
- when?: () => boolean;
477
- unavailableReason?: string | (() => string);
478
- /**
479
- * Input-aware validation beyond the schema. Return void to pass; return
480
- * (or throw) a PreconditionFailure to fail with PRECONDITION_FAILED.
481
- */
482
- precondition?(input: TIn, ctx: AgentReadContext): void | PreconditionFailure;
483
- /**
484
- * TOut is inferred from `output` only (NoInfer): the schema is the source
485
- * of truth and the handler's return is checked against it.
486
- */
487
- execute(input: TIn, ctx: AgentActionContext): NoInfer<TOut> | Promise<NoInfer<TOut>>;
488
- policies?: AgentPolicy[];
489
- meta?: Record<string, JsonValue>;
490
- timeoutMs?: number;
491
- /** Concurrency group (D25). Default `{mode:"instance"}` — serialize with
492
- * every other action on this component instance. */
493
- concurrency?: AgentConcurrency;
494
- }
495
- /** Identity helpers that fix generics for record-literal authoring. */
496
- declare function observation<TOut extends JsonValue>(def: AgentObservationDefinition<TOut>): AgentObservationDefinition<TOut>;
497
- declare function action<TIn extends JsonValue, TOut extends JsonValue | void = void>(def: AgentActionDefinition<TIn, TOut>): AgentActionDefinition<TIn, TOut>;
498
- declare function defineAgentComponent(def: AgentComponentDefinition): AgentComponentDefinition;
499
- interface ProcedureCallInfo {
500
- invocationId: string;
501
- consumer: AgentConsumer;
502
- signal: AbortSignal;
503
- confirmation?: {
504
- id: string;
505
- approvedAt: string;
506
- };
507
- }
508
- interface AgentProcedureExecutor {
509
- execute(req: {
510
- path: string;
511
- input: JsonValue;
512
- info: ProcedureCallInfo;
513
- }): Promise<JsonValue>;
514
- /** Known exposed procedure paths (manifest), used for suffix-collision lint. */
515
- paths?: ReadonlyArray<string>;
516
- }
517
- interface AgentProcedureRefDescriptor {
518
- readonly id: string;
519
- readonly path: string;
520
- readonly description: string;
521
- readonly inputSchema: JsonSchema;
522
- readonly outputSchema?: JsonSchema;
523
- readonly effect: AgentProcedureEffect;
524
- /** Server-declared flag the client must respect (approval required). */
525
- readonly requiresApproval?: boolean;
526
- }
527
- interface AgentProcedureBindingRuntimeConfig {
528
- when?: () => boolean;
529
- unavailableReason?: string | (() => string);
530
- /** UI-derived inputs, evaluated at EXECUTION time (docs/05 rule 4). */
531
- bind?: () => Record<string, JsonValue>;
532
- overridableFields?: ReadonlyArray<string>;
533
- /** Escalate (never lower) the manifest's confirmation requirement. */
534
- confirmation?: "optional" | "required";
535
- policies?: AgentPolicy[];
536
- /** Contextual description appended to the manifest description. */
537
- describe?: () => string;
538
- meta?: Record<string, JsonValue>;
539
- /** Concurrency group (D25). Default: one group per procedure identity per
540
- * referencing registration — conservative, and it never couples a domain
541
- * call to unrelated view actions. */
542
- concurrency?: AgentConcurrency;
543
- }
544
- interface AgentProcedureBinding<TIn extends object = object, TOut = unknown> {
545
- readonly kind: "procedure-binding";
546
- readonly ref: AgentProcedureRefDescriptor;
547
- readonly config: AgentProcedureBindingRuntimeConfig;
548
- /** Keys produced by bind(), captured at binding creation. */
549
- readonly boundKeys: ReadonlyArray<string>;
550
- /** Bound keys the agent may NOT supply (bound minus overridable). */
551
- readonly lockedKeys: ReadonlyArray<string>;
552
- /** Agent-facing (reduced) input schema per D7 rule 1. */
553
- readonly reducedInputSchema: JsonSchema;
554
- /** Optional link to the owning view component. */
555
- contextLink?: {
556
- type: string;
557
- instanceId: string;
558
- };
559
- /** Phantom fields carrying the generics (never read at runtime). */
560
- readonly __types?: {
561
- input: TIn;
562
- output: TOut;
563
- };
564
- }
565
- interface AgentComponentDefinition {
566
- /** Component type, e.g. "devices.table". MUST match the id grammar. */
567
- type: string;
568
- /** Distinguishes simultaneous mounts. Defaults to "default". Data-derived. */
569
- instanceId?: string;
570
- /** Agent-visible description, ≤ 500 chars. Required, non-empty. */
571
- description: string;
572
- /** Optional containment link for hierarchy-aware consumers. */
573
- parent?: {
574
- type: string;
575
- instanceId?: string;
576
- };
577
- /** Agent-visible metadata. JsonValue, ≤ 2 kB serialized. */
578
- meta?: Record<string, JsonValue>;
579
- /** Internal metadata for policies/audit sinks. NEVER serialized. */
580
- internal?: Record<string, unknown>;
581
- /** Policies applied to every capability of this component. */
582
- policies?: AgentPolicy[];
583
- /** Registrant trust label; default "first-party". */
584
- origin?: string;
585
- /** Snapshot ordering/budget priority; higher survives budgets longer. */
586
- priority?: number;
587
- /** Master switch; false ⇒ all capabilities visible-disabled. */
588
- enabled?: boolean;
589
- observations?: Record<string, AgentObservationDefinition<any>>;
590
- actions?: Record<string, AgentActionDefinition<any, any>>;
591
- /** Domain references; normally added via @agent-surface/orpc. */
592
- procedures?: AgentProcedureBinding<any, any>[];
593
- }
594
- /**
595
- * Validates a component definition structurally. Throws
596
- * AgentSurfaceDefinitionError in every environment — structural defects are
597
- * deterministic code bugs (docs/03 §registry).
598
- */
599
- declare function validateComponentDefinition(def: AgentComponentDefinition, limits: AgentSurfaceLimits, opts: {
600
- hasProcedureExecutor: boolean;
601
- }): void;
602
-
603
- type AgentSurfaceEvent = {
604
- type: "surface-changed";
605
- surfaceVersion: string;
606
- } | {
607
- type: "component-registered";
608
- registrationId: string;
609
- componentType: string;
610
- instanceId: string;
611
- } | {
612
- type: "component-unregistered";
613
- registrationId: string;
614
- componentType: string;
615
- instanceId: string;
616
- } | {
617
- type: "component-rejected";
618
- componentType: string;
619
- instanceId: string;
620
- reason: "duplicate" | "guard";
621
- } | {
622
- type: "availability-changed";
623
- registrationId: string;
624
- capabilityId: string;
625
- available: boolean;
626
- } | {
627
- type: "collision-suspected";
628
- viewCapabilityId: string;
629
- domainProcedureId: string;
630
- } | {
631
- type: "invocation-started";
632
- invocationId: string;
633
- capabilityId: string;
634
- consumerId: string;
635
- } | {
636
- type: "invocation-settled";
637
- invocationId: string;
638
- capabilityId: string;
639
- status: "ok" | "error";
640
- code?: AgentCapabilityErrorCode;
641
- durationMs: number;
642
- } | {
643
- type: "confirmation-requested";
644
- confirmationId: string;
645
- capabilityId: string;
646
- expiresAt: string;
647
- } | {
648
- type: "confirmation-resolved";
649
- confirmationId: string;
650
- outcome: "approved" | "denied" | "expired";
651
- };
652
-
653
- interface PendingConfirmation {
654
- confirmationId: string;
655
- capabilityId: string;
656
- registrationId: string;
657
- /** Normalized consumer identity `kind:id` (D22). */
658
- consumerKey: string;
659
- /** Effect of the operation being approved. */
660
- effect: AgentEffect;
661
- /** Human-readable summary composed from description + effective input. */
662
- summary: string;
663
- /** The exact effective input (bound + agent-supplied) being approved. */
664
- input: JsonValue;
665
- requestedAt: string;
666
- expiresAt: string;
667
- }
668
- interface ConfirmationController {
669
- /** Pending requests, for host UI rendering. */
670
- pending(): PendingConfirmation[];
671
- resolve(confirmationId: string, resolution: {
672
- approved: boolean;
673
- reason?: string;
674
- }): void;
675
- /** Resolves when the given confirmation settles (approved/denied/expired). */
676
- waitFor(confirmationId: string, opts?: {
677
- signal?: AbortSignal;
678
- }): Promise<"approved" | "denied" | "expired">;
679
- subscribe(listener: (pending: PendingConfirmation[]) => void): Unsubscribe;
680
- /** Test hook: force-expire a record as if its TTL elapsed (docs/08). */
681
- forceExpire(confirmationId: string): void;
682
- }
683
-
684
- type ConfirmationLevel = "never" | "optional" | "required";
685
-
686
- interface SnapshotContext {
687
- consumer?: AgentConsumer;
688
- /** Component-type prefixes to include, e.g. ["devices"]. Default: all. */
689
- scope?: string[];
690
- /** Include visible-disabled capabilities. Default true. */
691
- includeUnavailable?: boolean;
692
- /** [Experimental] Truncation budget. */
693
- budget?: {
694
- maxComponents?: number;
695
- maxBytes?: number;
696
- };
697
- }
698
- interface AgentSurfaceSnapshot {
699
- surfaceId: string;
700
- surfaceVersion: string;
701
- capturedAt: string;
702
- route?: AgentRouteInfo;
703
- components: AgentComponentDescriptor[];
704
- /** Domain references, top-level (planes are not nested into each other). */
705
- procedures: AgentProcedureDescriptor[];
706
- /** [Experimental] Present iff a budget truncated the snapshot. */
707
- truncated?: {
708
- droppedComponents: number;
709
- };
710
- /**
711
- * [Experimental] Present iff a configured scope floor refused part of a
712
- * requested scope (D27) — set by the adapter, never by `snapshot()`, which
713
- * has no floor to intersect against. Empty `components` alongside this marker
714
- * means the request fell outside the floor, not that the surface is empty.
715
- */
716
- scopeRejected?: {
717
- prefixes: string[];
718
- };
719
- }
720
- interface AgentComponentDescriptor {
721
- type: string;
722
- instanceId: string;
723
- registrationId: string;
724
- description: string;
725
- parent?: {
726
- type: string;
727
- instanceId: string;
728
- };
729
- meta?: Record<string, JsonValue>;
730
- observations: AgentObservationDescriptor[];
731
- actions: AgentActionDescriptor[];
732
- }
733
- interface AgentObservationDescriptor {
734
- capabilityId: string;
735
- name: string;
736
- description: string;
737
- outputSchema: JsonSchema;
738
- available: boolean;
739
- unavailableReason?: string;
740
- meta?: Record<string, JsonValue>;
741
- }
742
- interface AgentActionDescriptor {
743
- capabilityId: string;
744
- name: string;
745
- description: string;
746
- inputSchema: JsonSchema;
747
- outputSchema?: JsonSchema;
748
- effect: "local-state" | "navigation";
749
- idempotent: boolean;
750
- reversible: boolean;
751
- confirmation: "never" | "optional" | "required";
752
- available: boolean;
753
- unavailableReason?: string;
754
- meta?: Record<string, JsonValue>;
755
- }
756
- interface AgentProcedureDescriptor {
757
- procedureId: string;
758
- /**
759
- * The manifest description. Stable across snapshots — the contextual
760
- * `describe()` output is `contextualNote` and is never folded in here (D28).
761
- */
762
- description: string;
763
- /** Volatile: this snapshot's contextual `describe()` output, if any. */
764
- contextualNote?: string;
765
- /** Agent-facing (reduced) input schema per binding rule 1 (docs/05). */
766
- inputSchema: JsonSchema;
767
- outputSchema?: JsonSchema;
768
- effect: AgentProcedureEffect;
769
- confirmation: ConfirmationLevel;
770
- available: boolean;
771
- unavailableReason?: string;
772
- boundFields: Array<{
773
- path: string;
774
- locked: boolean;
775
- source: "ui-state";
776
- }>;
777
- /** The registration that contributed this reference (staleness token). */
778
- registrationId: string;
779
- /** Optional link to the owning view component. */
780
- context?: {
781
- type: string;
782
- instanceId: string;
783
- };
784
- meta?: Record<string, JsonValue>;
785
- }
786
- type AgentCapabilityDescriptorUnion = AgentObservationDescriptor | AgentActionDescriptor | AgentProcedureDescriptor;
787
-
788
- interface RegistrationCandidate {
789
- definition: AgentComponentDefinition;
790
- stack?: string;
791
- }
792
- interface RegistryOptions {
793
- /** "development" | "production" | "test". Default: "production". */
794
- environment?: AgentEnvironment;
795
- /** Host context provider. MUST be synchronous and cheap. */
796
- context?: () => Record<string, unknown>;
797
- /** Global policies, outermost layer of every chain. */
798
- policies?: AgentPolicy[];
799
- /** Audit sink; default: bounded in-memory sink (+ console in development). */
800
- audit?: AuditSink;
801
- /** Guard invoked before accepting a registration (trust filtering, docs/06). */
802
- onRegister?: (candidate: RegistrationCandidate) => "accept" | "reject";
803
- /** Collision handling for duplicate (type, instanceId). Default "reject". */
804
- onDuplicateInstance?: "reject" | "replace";
805
- /** Suffix-collision diagnostics vs known domain ids. Default "warn". */
806
- duplicateSuffixPolicy?: "off" | "warn" | "error";
807
- /** Route descriptor for snapshots (host wires its router here). */
808
- route?: () => AgentRouteInfo | undefined;
809
- limits?: Partial<AgentSurfaceLimits>;
810
- /** Injectable clock (docs/08 determinism); default Date.now. */
811
- now?: () => number;
812
- }
813
- interface AgentRegistrationHandle {
814
- readonly registrationId: string;
815
- readonly status: "active" | "rejected" | "unregistered";
816
- /** Push dynamic updates; only these fields are updatable (D2). */
817
- update(patch: {
818
- enabled?: boolean;
819
- availability?: Record<string, {
820
- available: boolean;
821
- reason?: string;
822
- }>;
823
- }): void;
824
- /** Bumps the surface version without changing anything. */
825
- invalidate(): void;
826
- unregister(): void;
827
- }
828
- interface AgentSurfaceRegistry {
829
- readonly surfaceId: string;
830
- register(definition: AgentComponentDefinition): AgentRegistrationHandle;
831
- snapshot(context?: SnapshotContext): AgentSurfaceSnapshot;
832
- invoke(request: AgentInvocation, options?: InvokeOptions): Promise<AgentInvocationResult>;
833
- subscribe(listener: (event: AgentSurfaceEvent) => void): Unsubscribe;
834
- confirmations: ConfirmationController;
835
- /** Register a domain-procedure executor (installed by @agent-surface/orpc). */
836
- setProcedureExecutor(executor: AgentProcedureExecutor | undefined): void;
837
- getVersion(): string;
838
- /** Tears down: aborts in-flight invocations (CANCELLED), clears listeners. */
839
- dispose(): void;
840
- }
841
- declare function createAgentSurfaceRegistry(options?: RegistryOptions): AgentSurfaceRegistry;
842
-
843
88
  interface AgentToolsetOptions {
844
89
  consumer: AgentConsumer;
845
90
  /**
@@ -929,4 +174,4 @@ declare function createAgentToolset(registry: AgentSurfaceRegistry, options: Age
929
174
  /** Deep equality over JsonValue (order-sensitive for arrays, docs/06 rule 2). */
930
175
  declare function jsonDeepEqual(a: JsonValue | undefined, b: JsonValue | undefined): boolean;
931
176
 
932
- export { AGENT_CAPABILITY_ERROR_CODES, type AgentActionContext, type AgentActionDefinition, type AgentActionDescriptor, type AgentAuthorizationContext, type AgentCapabilityDescriptorUnion, type AgentCapabilityErrorCode, type AgentCapabilityErrorPayload, type AgentComponentDefinition, type AgentComponentDescriptor, type AgentConcurrency, type AgentConsumer, type AgentEffect, type AgentEnvironment, type AgentErrorRetry, type AgentInvocation, type AgentInvocationPolicyContext, type AgentInvocationResult, type AgentObservationDefinition, type AgentObservationDescriptor, type AgentPlane, type AgentPolicy, type AgentPolicyContext, type AgentProcedureBinding, type AgentProcedureBindingRuntimeConfig, type AgentProcedureDescriptor, type AgentProcedureEffect, type AgentProcedureExecutor, type AgentProcedureRefDescriptor, type AgentReadContext, type AgentRegistrationHandle, type AgentRouteInfo, type AgentSchema, AgentSchemaError, type AgentSchemaIssue, AgentSurfaceDefinitionError, type AgentSurfaceDefinitionErrorCode, AgentSurfaceError, type AgentSurfaceEvent, type AgentSurfaceLimits, type AgentSurfaceRegistry, type AgentSurfaceSnapshot, type AgentTool, type AgentToolset, type AgentToolsetOptions, type AuditEvent, type AuditSink, CONFIRMATION_ESCALATION, type ConfirmationController, type ConfirmationEscalation, DEFAULT_LIMITS, type DiscoveryDecision, type InvokeOptions, type JsonSchema, type JsonValue, MAX_ID_LENGTH, MAX_WIRE_NAME_LENGTH, type ParsedCapabilityId, type PendingConfirmation, type PreconditionFailure, type ProcedureCallInfo, type RegistrationCandidate, type RegistryOptions, type SnapshotContext, type StandardSchemaV1, type Unsubscribe, type WireNameAssignment, type WireNameEntry, action, assignWireNames, audit, authenticated, composeInvokeChain, consoleAuditSink, createAgentSurfaceRegistry, createAgentToolset, decodeWireName, defineAgentComponent, emptyObjectSchema, encodeWireName, encodeWireNameForInstance, environment, evaluateDiscovery, formatDomainCapabilityId, formatViewCapabilityId, fromJsonSchema, fromStandardSchema, hasPermission, isAgentSurfaceError, isValidCapabilityName, isValidComponentType, isValidInstanceId, jsonDeepEqual, memoryAuditSink, observation, parseCapabilityId, rateLimit, requireConfirmation, tenantBoundary, validateComponentDefinition, validateJsonSchemaDocument, validateValueAgainstSchema };
177
+ export { AgentConsumer, AgentInvocationResult, type AgentPlane, AgentSurfaceRegistry, type AgentTool, type AgentToolset, type AgentToolsetOptions, JsonSchema, JsonValue, MAX_ID_LENGTH, MAX_WIRE_NAME_LENGTH, type ParsedCapabilityId, Unsubscribe, type WireNameAssignment, type WireNameEntry, assignWireNames, createAgentToolset, decodeWireName, encodeWireName, encodeWireNameForInstance, formatDomainCapabilityId, formatViewCapabilityId, isValidCapabilityName, isValidComponentType, isValidInstanceId, jsonDeepEqual, parseCapabilityId };