oui-spec 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/README.md +1 -1
  2. package/dist/{chunk-4MEYE6XZ.js → chunk-3MISAULT.js} +4 -4
  3. package/dist/chunk-3MISAULT.js.map +1 -0
  4. package/dist/{chunk-2CPOHQGI.cjs → chunk-63T6SSPP.cjs} +27 -6
  5. package/dist/chunk-63T6SSPP.cjs.map +1 -0
  6. package/dist/{chunk-DOJXITEZ.cjs → chunk-DLO56KLG.cjs} +27 -27
  7. package/dist/chunk-DLO56KLG.cjs.map +1 -0
  8. package/dist/{chunk-RZUYWZFK.js → chunk-JRXQLNUL.js} +26 -7
  9. package/dist/chunk-JRXQLNUL.js.map +1 -0
  10. package/dist/core/index.cjs +6 -6
  11. package/dist/core/index.d.cts +5 -5
  12. package/dist/core/index.d.ts +5 -5
  13. package/dist/core/index.js +2 -2
  14. package/dist/index.cjs +44 -36
  15. package/dist/index.d.cts +4 -4
  16. package/dist/index.d.ts +4 -4
  17. package/dist/index.js +2 -2
  18. package/dist/react/index.d.cts +3 -3
  19. package/dist/react/index.d.ts +3 -3
  20. package/dist/spec/index.cjs +40 -32
  21. package/dist/spec/index.d.cts +29 -4
  22. package/dist/spec/index.d.ts +29 -4
  23. package/dist/spec/index.js +1 -1
  24. package/dist/{surface-runtime-BPEtT3LZ.d.ts → surface-runtime-BsRS0EV1.d.ts} +2 -2
  25. package/dist/{surface-runtime-CexHqUn-.d.cts → surface-runtime-bXSSONF4.d.cts} +2 -2
  26. package/dist/transport/index.d.cts +3 -3
  27. package/dist/transport/index.d.ts +3 -3
  28. package/dist/{types-CnlVRPFL.d.cts → types-D4czecOw.d.cts} +5 -3
  29. package/dist/{types-CnlVRPFL.d.ts → types-D4czecOw.d.ts} +5 -3
  30. package/dist/{websocket-DKL9qoO-.d.ts → websocket-BcWDNt_V.d.ts} +1 -1
  31. package/dist/{websocket-HnzPlfk6.d.cts → websocket-EzQq1mxO.d.cts} +1 -1
  32. package/package.json +1 -1
  33. package/spec/OUI-SPEC-v0.1.md +7 -3
  34. package/dist/chunk-2CPOHQGI.cjs.map +0 -1
  35. package/dist/chunk-4MEYE6XZ.js.map +0 -1
  36. package/dist/chunk-DOJXITEZ.cjs.map +0 -1
  37. package/dist/chunk-RZUYWZFK.js.map +0 -1
package/README.md CHANGED
@@ -66,7 +66,7 @@ on the page it just left.
66
66
 
67
67
  Action definitions are heavy (every action's schema: several hundred KB on a
68
68
  studio page), so a client does not send them. It sends an **index**: one entry
69
- per action, with its title, the first sentence of its description, its effect
69
+ per action, with its title, the first sentence of its description (less an opening that repeats the title), its effect
70
70
  and a one-line summary of what it takes. An agent runtime fetches the
71
71
  definition it needs with the runtime's own `oui.describe`, and reads state that
72
72
  did not fit with `oui.read`. This is the index form: pass `form: "index"` to
@@ -1,4 +1,4 @@
1
- import { OUI_RUNTIME_SURFACE, ARGS_HASH_PATTERN, jsonBytes, fitObservations, requiresApproval, surfacesHash, OUI_DESCRIBE_ACTION, OUI_READ_ACTION, atPointer, argsHash, surfaceIndex } from './chunk-RZUYWZFK.js';
1
+ import { OUI_RUNTIME_SURFACE, ARGS_HASH_PATTERN, jsonBytes, fitObservations, requiresApproval, surfacesHash, OUI_DESCRIBE_ACTION, OUI_READ_ACTION, atPointer, argsHash, surfaceIndex } from './chunk-JRXQLNUL.js';
2
2
  import { createWebSocketTransport } from './chunk-R3SGP2UY.js';
3
3
 
4
4
  // src/core/brand.ts
@@ -507,7 +507,7 @@ function createSurfaceRuntime(options = {}) {
507
507
  }
508
508
  }
509
509
  }
510
- const settled = await waitUntilSettled(startedAt);
510
+ const settled = await waitUntilSettled(Date.now());
511
511
  const answered = frame(
512
512
  {
513
513
  requestId: request.requestId,
@@ -906,5 +906,5 @@ function toJsonSafe(value) {
906
906
  }
907
907
 
908
908
  export { createOUI, createSurfaceRuntime, defineSurface };
909
- //# sourceMappingURL=chunk-4MEYE6XZ.js.map
910
- //# sourceMappingURL=chunk-4MEYE6XZ.js.map
909
+ //# sourceMappingURL=chunk-3MISAULT.js.map
910
+ //# sourceMappingURL=chunk-3MISAULT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/brand.ts","../src/core/define-surface.ts","../src/core/create-oui.ts","../src/core/surface-runtime.ts"],"names":["frame"],"mappings":";;;;AA2BO,SAAS,MACd,KAAA,EACuB;AACvB,EAAA,OAAO,KAAA;AACT;;;ACqGO,SAAS,cAId,UAAA,EACwC;AAExC,EAAA,IAAI,UAAA,CAAW,OAAO,mBAAA,EAAqB;AACzC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,UAAU,mBAAmB,CAAA,2DAAA;AAAA,KAC/B;AAAA,EACF;AAGA,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAY;AAClC,EAAA,KAAA,MAAW,MAAA,IAAU,WAAW,OAAA,EAAS;AACvC,IAAA,IAAI,SAAA,CAAU,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,EAAG;AAC5B,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,2BAAA,EAA8B,MAAA,CAAO,EAAE,CAAA,cAAA,EAAiB,WAAW,EAAE,CAAA,CAAA;AAAA,OACvE;AAAA,IACF;AACA,IAAA,SAAA,CAAU,GAAA,CAAI,OAAO,EAAE,CAAA;AAAA,EACzB;AAGA,EAAA,IAAI,WAAW,YAAA,EAAc;AAC3B,IAAA,MAAM,MAAA,uBAAa,GAAA,EAAY;AAC/B,IAAA,KAAA,MAAW,GAAA,IAAO,WAAW,YAAA,EAAc;AACzC,MAAA,IAAI,MAAA,CAAO,GAAA,CAAI,GAAA,CAAI,EAAE,CAAA,EAAG;AACtB,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,CAAA,gCAAA,EAAmC,GAAA,CAAI,EAAE,CAAA,cAAA,EAAiB,WAAW,EAAE,CAAA,CAAA;AAAA,SACzE;AAAA,MACF;AACA,MAAA,MAAA,CAA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OAAA,EAAS,EAAE,CAAC,CAAA;AACzD;AAOA,SAAS,WAAW,KAAA,EAAyB;AAC3C,EAAA,IAAI,KAAA,KAAU,QAAW,OAAO,MAAA;AAChC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB;AACF","file":"chunk-3MISAULT.js","sourcesContent":["/**\n * Nominal branding for values OUI must construct itself.\n *\n * Structural typing means any object with the right shape satisfies an\n * interface. That is how Closure Studio ended up hand-rolling OUI's transport:\n * `SocketLike` was importable, `OUITransport` was a plain interface, so an\n * integrator could satisfy every type without ever calling OUI. The result was\n * a second implementation of the wire — hardcoded namespace, re-declared\n * payload types on the server, and a dead `action:result` mapping alongside the\n * observation channel that already carried results.\n *\n * A unique symbol cannot be produced outside this module. Branding the types\n * OUI owns turns \"you should use our constructor\" into \"you cannot compile\n * without it\".\n */\n\ndeclare const OUI_BRAND: unique symbol;\n\n/** Marks a value as constructed by OUI itself. */\nexport interface OUIBranded<TKind extends string> {\n readonly [OUI_BRAND]: TKind;\n}\n\n/**\n * Attach the brand at runtime. The property does not exist at runtime — the\n * symbol is declare-only — so this is a type-level assertion with no cost.\n */\nexport function brand<TKind extends string, T>(\n value: T,\n): T & OUIBranded<TKind> {\n return value as T & OUIBranded<TKind>;\n}\n","import type {\n OUISurface,\n OUIAction,\n OUIObservation,\n OUIActivation,\n OUIActionPolling,\n JSONSchema,\n OUIEffectKind,\n} from \"../spec/index.js\";\nimport { OUI_RUNTIME_SURFACE } from \"../spec/index-form.js\";\nimport { brand, type OUIBranded } from \"./brand.js\";\n\n/**\n * Configuration for defining an OUI surface with handlers.\n * This is the \"integration file\" an app provides — it declares both\n * the schema (what the agent sees) and the implementation (what executes).\n */\nexport interface SurfaceDefinition<TContext = unknown> {\n id: string;\n name: string;\n description: string;\n version?: string;\n activation?: OUIActivation;\n actions: ActionDefinition<TContext>[];\n observations?: ObservationDefinition[];\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Polling config with an optional resolve handler.\n * The spec's OUIActionPolling is the manifest shape (no functions).\n * The core extends it with the resolve implementation for the runtime.\n */\nexport interface ActionPollingConfig<\n TContext = unknown,\n> extends OUIActionPolling {\n /**\n * Called on each poll interval. Receives the dispatch result from the handler\n * plus the current context. Return { done: true, data } to stop polling,\n * or { done: false, data } to continue.\n */\n resolve?: (\n dispatchResult: unknown,\n context: TContext,\n ) => Promise<{ done: boolean; data: unknown }>;\n}\n\n/**\n * An action definition includes both the schema (for the agent) and\n * the handler (for execution). This is the single source of truth —\n * no separate YAML, no separate listener, no drift possible.\n */\nexport interface ActionDefinition<TContext = unknown> {\n id: string;\n description: string;\n /** Its name as a person reads it, for a confirmation the user approves. */\n title?: string;\n /** What using it does; a `transaction` runs only on the user's approval of the exact request. */\n effect?: OUIEffectKind;\n input: JSONSchema;\n output?: JSONSchema;\n /** Destructive: it runs only on the user's approval of the exact request, unless it only reads. */\n confirm?: boolean;\n async?: boolean;\n\n /**\n * Polling/subscription config for async actions.\n * After the handler returns, the OUI runtime starts polling or subscribing\n * and pushes observation updates until the operation completes.\n * Extends the spec's OUIActionPolling with an optional resolve handler.\n */\n polling?: ActionPollingConfig<TContext>;\n\n usage?: string;\n preconditions?: string;\n estimatedDuration?: string;\n tags?: string[];\n\n /**\n * The handler that executes when the agent invokes this action.\n * Receives typed params and a context object (app-specific state/utilities).\n * Returns a result that the agent sees as the tool output.\n */\n handler: (\n params: Record<string, unknown>,\n context: TContext,\n ) => Promise<ActionHandlerResult>;\n}\n\nexport interface ActionHandlerResult {\n success: boolean;\n data?: unknown;\n error?: { code: string; message: string; details?: unknown };\n /** For async actions: metadata passed to the polling resolver */\n dispatchMeta?: Record<string, unknown>;\n}\n\nexport interface ObservationDefinition {\n id: string;\n description: string;\n schema: JSONSchema;\n /** Function that returns the current observation value */\n getValue?: () => unknown;\n}\n\n/**\n * Define an OUI surface — the single entry point for integrating\n * an application feature with the OUI protocol.\n *\n * This function validates the definition and returns a typed surface\n * object that can be registered with an agent runtime or transport layer.\n *\n * @example\n * ```typescript\n * const mySurface = defineSurface({\n * id: 'my-feature',\n * name: 'My Feature',\n * description: 'Does something cool',\n * actions: [\n * {\n * id: 'do_thing',\n * description: 'Does the thing',\n * input: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },\n * handler: async (params) => {\n * const result = await doTheThing(params.name);\n * return { success: true, data: result };\n * },\n * },\n * ],\n * });\n * ```\n */\nexport function defineSurface<\n TContext = unknown,\n const TId extends string = string,\n>(\n definition: SurfaceDefinition<TContext> & { id: TId },\n): DefinedSurface<TContext> & { id: TId } {\n // The runtime answers this id itself (§7.3.10).\n if (definition.id === OUI_RUNTIME_SURFACE) {\n throw new Error(\n `[OUI] \"${OUI_RUNTIME_SURFACE}\" is the surface runtime's own id: give the surface another`,\n );\n }\n\n // Validate: no duplicate action IDs\n const actionIds = new Set<string>();\n for (const action of definition.actions) {\n if (actionIds.has(action.id)) {\n throw new Error(\n `[OUI] Duplicate action ID \"${action.id}\" in surface \"${definition.id}\"`,\n );\n }\n actionIds.add(action.id);\n }\n\n // Validate: no duplicate observation IDs\n if (definition.observations) {\n const obsIds = new Set<string>();\n for (const obs of definition.observations) {\n if (obsIds.has(obs.id)) {\n throw new Error(\n `[OUI] Duplicate observation ID \"${obs.id}\" in surface \"${definition.id}\"`,\n );\n }\n obsIds.add(obs.id);\n }\n }\n\n return brand<\"surface\", unknown>({\n ...definition,\n\n /** Extract the manifest (schema only, no handlers) for transmission to the agent runtime */\n toManifest(): OUISurface {\n return {\n id: definition.id,\n name: definition.name,\n description: definition.description,\n version: definition.version,\n activation: definition.activation,\n actions: definition.actions.map(actionToManifest),\n observations: definition.observations?.map(obsToManifest),\n metadata: definition.metadata,\n };\n },\n\n /** Execute an action by ID with the given params and context */\n async executeAction(\n actionId: string,\n params: Record<string, unknown>,\n context: TContext,\n ): Promise<ActionHandlerResult> {\n const action = definition.actions.find((a) => a.id === actionId);\n if (!action) {\n return {\n success: false,\n error: {\n code: \"ACTION_NOT_FOUND\",\n message: `Action \"${actionId}\" not found on surface \"${definition.id}\"`,\n },\n };\n }\n try {\n return await action.handler(params, context);\n } catch (err) {\n return {\n success: false,\n error: {\n code: \"ACTION_EXECUTION_ERROR\",\n message: err instanceof Error ? err.message : String(err),\n },\n };\n }\n },\n\n /** Get all action IDs */\n getActionIds(): string[] {\n return definition.actions.map((a) => a.id);\n },\n\n /** Get the polling config for an action (if async) */\n getPollingConfig(actionId: string): OUIActionPolling | undefined {\n const action = definition.actions.find((a) => a.id === actionId);\n return action?.polling;\n },\n }) as DefinedSurface<TContext> & { id: TId };\n}\n\n/** A fully defined surface with both manifest extraction and execution capabilities */\n/**\n * Branded so it can only come from `defineSurface`.\n *\n * Without the brand a plain object literal satisfies this interface\n * structurally, which is how an integrator can assemble a surface that never\n * ran defineSurface's duplicate-id checks and never produced a real manifest.\n */\nexport interface DefinedSurface<TContext = unknown>\n extends SurfaceDefinition<TContext>, OUIBranded<\"surface\"> {\n toManifest(): OUISurface;\n executeAction(\n actionId: string,\n params: Record<string, unknown>,\n context: TContext,\n ): Promise<ActionHandlerResult>;\n getActionIds(): string[];\n /** Get the polling config for an action (if async) */\n getPollingConfig(actionId: string): OUIActionPolling | undefined;\n}\n\n// ─── Internal helpers ────────────────────────────────────────────────────────\n\nfunction actionToManifest<T>(action: ActionDefinition<T>): OUIAction {\n return {\n id: action.id,\n description: action.description,\n ...(action.title !== undefined ? { title: action.title } : {}),\n ...(action.effect !== undefined ? { effect: action.effect } : {}),\n input: action.input,\n output: action.output,\n confirm: action.confirm,\n async: action.async,\n polling: action.polling,\n usage: action.usage,\n preconditions: action.preconditions,\n estimatedDuration: action.estimatedDuration,\n tags: action.tags,\n };\n}\n\nfunction obsToManifest(obs: ObservationDefinition): OUIObservation {\n return {\n id: obs.id,\n description: obs.description,\n schema: obs.schema,\n };\n}\n","/**\n * createOUI — a fixed set of surfaces announced over one socket.\n *\n * For a client whose surfaces come and go (a React app, where a page's\n * surfaces mount with the page), use `createSurfaceRuntime` instead: it keeps\n * the client's own record of what is mounted and answers every request.\n *\n * WHY THIS EXISTS\n *\n * OUI shipped a correct protocol and a correct transport, and its first\n * integrator used neither. studio-ui imported only the `SocketLike` TYPE from\n * oui-spec and rebuilt the wire by hand: a literal map of protocol types to\n * socket names, `oui:` hardcoded so the configurable namespace was unreachable,\n * payload interfaces re-declared on the server, and an `action:result` channel\n * mapped but never sent — duplicating the observation channel that already\n * carries results.\n *\n * Nothing was wrong with the spec. Nothing enforced it. Structural typing meant\n * every hand-rolled piece type-checked, and both ends agreed only by the\n * coincidence of matching string literals. Rename one and the other keeps\n * compiling and silently stops receiving.\n *\n * So the requirements are gated here:\n *\n * OUI owns the wire. The integrator provides a socket; it cannot provide a\n * transport, because `OUITransport` values are branded and only this module\n * brands them.\n *\n * OUI owns the result path. Every dispatch carries a requestId and is\n * answered on OUI's result channel. An integrator cannot add a parallel\n * channel because it cannot construct a transport to add one to.\n *\n * The integrator owns content. Surfaces, action schemas, observation schemas\n * and handlers all arrive through `defineSurface`, whose output is branded —\n * so a plain object shaped like a surface will not compile.\n *\n * Violations fail at compile time with a message naming the offending id.\n */\nimport type { OUITransport, OUITransportConfig } from \"../transport/types.js\";\nimport type { SocketLike } from \"../transport/websocket.js\";\nimport { createWebSocketTransport } from \"../transport/websocket.js\";\nimport type { DefinedSurface } from \"./define-surface.js\";\nimport { brand, type OUIBranded } from \"./brand.js\";\nimport type { OUIConfigError, ValidateSurfaceIds } from \"./validate.js\";\nimport type { OUISurface } from \"../spec/index.js\";\n\n/** A transport OUI constructed. Integrators cannot produce one. */\nexport type OwnedTransport = OUITransport & OUIBranded<\"transport\">;\n\n/** Surface ids as literal types, for the duplicate check. */\ntype SurfaceIds<T extends readonly DefinedSurface<never>[]> = {\n [K in keyof T]: T[K][\"id\"];\n};\n\nexport interface OUIConfig<TSurfaces extends readonly DefinedSurface<never>[]> {\n /**\n * The socket OUI will speak over. The integrator owns the connection —\n * auth, reconnection, lifecycle — and OUI owns what travels on it.\n */\n socket: SocketLike;\n\n /**\n * Surfaces produced by `defineSurface`. A plain object with the same shape\n * will not compile: DefinedSurface is branded.\n */\n surfaces: TSurfaces;\n\n /**\n * Wire configuration. `namespace` defaults to 'oui' and is the supported way\n * to change the event prefix — hardcoding it at the call site is what made\n * this option unreachable in the first integration.\n */\n transport?: Omit<OUITransportConfig, \"namespace\"> & { namespace?: string };\n}\n\n/** A live OUI instance. */\nexport interface OUIInstance {\n /** The transport OUI owns. Exposed for wiring, not for reimplementation. */\n readonly transport: OwnedTransport;\n\n /** Manifests for every registered surface, as the agent sees them. */\n readonly manifests: readonly OUISurface[];\n\n /** Register every surface and connect. */\n start(): Promise<void>;\n\n /**\n * Deregister every surface and detach OUI from the socket. The socket stays\n * connected: the integrator owns it, and other code may share it.\n */\n stop(): void;\n\n /** Look up a registered surface by id. */\n getSurface(id: string): DefinedSurface<never> | undefined;\n}\n\n/**\n * Instantiate OUI.\n *\n * `const` on the type parameter captures surface ids as literal types, which is\n * what allows duplicate detection to name the offending id rather than failing\n * with an unassignable-to-never error.\n */\nexport function createOUI<\n const TSurfaces extends readonly DefinedSurface<never>[],\n>(\n config: OUIConfig<TSurfaces> & ValidateSurfaceIds<SurfaceIds<TSurfaces>>,\n): OUIInstance {\n const {\n socket,\n surfaces,\n transport: transportConfig,\n } = config as OUIConfig<TSurfaces>;\n\n // Defensive, not decorative: the compile-time checks only bind when a caller\n // passes literals. A surface list assembled at runtime, or JS with no types\n // at all, reaches here unchecked.\n if (!socket) {\n throw new Error(\n \"[OUI] createOUI requires a socket. OUI owns the wire; the integrator owns the connection.\",\n );\n }\n if (!Array.isArray(surfaces) || surfaces.length === 0) {\n throw new Error(\"[OUI] createOUI requires at least one surface.\");\n }\n\n const seen = new Set<string>();\n for (const surface of surfaces) {\n if (seen.has(surface.id)) {\n throw new Error(\n `[OUI] Duplicate surface id \"${surface.id}\". Registration is keyed by id, so the second would replace the first.`,\n );\n }\n seen.add(surface.id);\n }\n\n const transport = brand<\"transport\", OUITransport>(\n createWebSocketTransport(socket, transportConfig),\n );\n\n const byId = new Map(surfaces.map((s) => [s.id, s] as const));\n\n return {\n transport,\n manifests: surfaces.map((s) => s.toManifest()),\n\n async start() {\n await transport.connect();\n for (const surface of surfaces) {\n transport.registerSurface(surface.toManifest());\n }\n },\n\n stop() {\n for (const surface of surfaces) {\n transport.deregisterSurface(surface.id);\n }\n transport.dispose();\n },\n\n getSurface(id) {\n return byId.get(id);\n },\n };\n}\n\n/** Re-exported so integrators can name the error type in tests. */\nexport type { OUIConfigError };\n","/**\n * The client-side surface runtime.\n *\n * Holds the surfaces a client has mounted, answers every action request with a\n * result, and produces the snapshot an agent runtime works from.\n *\n * WHY THIS EXISTS\n *\n * The first integration kept no client-side record of what was mounted. Each\n * surface hook registered itself with a server-side registry and listened for\n * dispatches on its own. Three things followed:\n *\n * - The registry was the only record of what the client could do, and it lost\n * entries: a dead socket's cleanup removed a live tab's registration, and the\n * browser never registered again. The agent then had no UI tools at all.\n * - Nothing answered a dispatch. The agent was told an action succeeded before\n * the client had run it, and never saw the page an action led to.\n * - Every hook listened independently, through two paths, so one dispatch ran\n * twice and nothing de-duplicated it.\n *\n * Here the client is the record. `snapshot()` is what the client can do right\n * now, and every request is run once, waited on until the UI settles, and\n * answered with its result and the snapshot after it.\n */\nimport type {\n OUIAction,\n OUIActionRequest,\n OUIActionResult,\n OUIApprovalGrant,\n OUIFit,\n OUIIndexSnapshot,\n OUIResultDelivery,\n OUISurface,\n OUISurfaceIndex,\n OUISurfaceSnapshot,\n OUIObservationSnapshot,\n} from \"../spec/index.js\";\nimport {\n ARGS_HASH_PATTERN,\n argsHash,\n requiresApproval,\n} from \"../spec/approval.js\";\nimport { surfacesHash } from \"../spec/surfaces-hash.js\";\nimport {\n jsonBytes,\n OUI_DESCRIBE_ACTION,\n OUI_READ_ACTION,\n OUI_RUNTIME_SURFACE,\n surfaceIndex,\n} from \"../spec/index-form.js\";\nimport { atPointer, fitObservations } from \"../spec/fit.js\";\nimport type { OUITransport, OUITransportConfig } from \"../transport/types.js\";\nimport {\n createWebSocketTransport,\n type SocketLike,\n} from \"../transport/websocket.js\";\nimport type {\n ActionHandlerResult,\n ActionPollingConfig,\n DefinedSurface,\n} from \"./define-surface.js\";\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\nexport interface SettleOptions {\n /**\n * The UI counts as settled once nothing has mounted, unmounted or changed an\n * observation for this long, and no hold is open. Default 250 ms.\n */\n quietMs?: number;\n /** Give up waiting after this long and answer with `settled: false`. Default 5000 ms. */\n timeoutMs?: number;\n}\n\nexport interface SurfaceRuntimeOptions {\n /** The socket to answer requests on. Can be set or replaced later with `attach`. */\n socket?: SocketLike | null;\n\n /** Wire configuration for the transport the runtime builds on the socket. */\n transport?: OUITransportConfig;\n\n /**\n * Also announce registrations and observations over the transport, for agent\n * runtimes that keep a server-side registry. Default true.\n *\n * An agent runtime that takes the client's snapshot instead (sent with each\n * turn, and returned on every result) has no use for them: set false.\n */\n announce?: boolean;\n\n settle?: SettleOptions;\n\n /** How many answered request ids to remember, for de-duplication. Default 500. */\n dedupeWindow?: number;\n\n /**\n * Decides whether a request that arrived on the socket may run at all. A\n * refused request is neither run nor answered, and is logged.\n *\n * The server should be the only sender of action requests, but a client can\n * also check that a request is one it expects: for example, only while its\n * agent has a turn in progress. Requests passed to `execute` directly are\n * not checked; they come from the application itself.\n */\n accept?: (request: OUIActionRequest) => boolean;\n\n /**\n * What a snapshot and an answer say of the mounted surfaces (§7.3.8):\n * - `\"index\"`: each action as an index entry. The agent runtime fetches a\n * definition when it needs one (`oui.describe`). Use it with an agent\n * runtime that reads the index form.\n * - `\"full\"` (the default until 1.0): each action's whole definition, as\n * every earlier version sent. A page's definitions can outweigh what a\n * frame may carry; then its answers are refused and arrive trimmed.\n */\n form?: \"index\" | \"full\";\n\n /** The most bytes of JSON a frame carries; what does not fit is shortened and said so (§7.3.9). */\n budgets?: {\n /** One answer. Default 480 KB: under the 512 KB a relay commonly caps a frame at. */\n answerBytes?: number;\n /** One snapshot, as sent with a turn. Default 256 KB. */\n snapshotBytes?: number;\n };\n\n /**\n * A request sent again while its answer is on the way is not answered again\n * (§7.3.7): every copy of a large answer queues on the one socket, ahead of\n * the next request's answer. Only once the answer has gone this long without\n * the receiver acknowledging it — lost, or a receiver that does not\n * acknowledge — is a repeat answered again. Default 8000 ms.\n */\n reanswerAfterMs?: number;\n}\n\n// ─── Public types ────────────────────────────────────────────────────────────\n\nexport interface MountedSurface {\n readonly surfaceId: string;\n /** Record an observation value. A no-op once unmounted. */\n pushObservation(observationId: string, value: unknown): void;\n /** Remove this mount. Other mounts of the same surface id are unaffected. */\n unmount(): void;\n}\n\n/** The form a runtime sends its surfaces in (§7.3.8). */\nexport type SurfaceForm = \"full\" | \"index\";\n\nexport interface SurfaceRuntime<F extends SurfaceForm = \"full\"> {\n /**\n * Mount a surface. `getContext` is read when an action runs, so handlers see\n * the latest state rather than the state at mount time.\n *\n * Mounting the same surface id twice is allowed (React StrictMode does it on\n * every mount); the most recent mount serves its actions.\n */\n mount<TContext>(\n surface: DefinedSurface<TContext>,\n getContext: () => TContext,\n ): MountedSurface;\n\n /** Answer requests arriving on this socket (null detaches). */\n attach(socket: SocketLike | null): void;\n\n /** What the client can do right now. */\n snapshot(): F extends \"index\" ? OUIIndexSnapshot : OUISurfaceSnapshot;\n\n /**\n * Run a request once and resolve with its result. A request id seen before\n * resolves with the first result instead of running again.\n */\n execute(request: OUIActionRequest): Promise<OUIActionResult>;\n\n /**\n * Keep the UI unsettled until the returned function is called. For work an\n * action starts that mounting and unmounting cannot show, such as a route's\n * code still loading or a page fetching the data it will display.\n */\n hold(): () => void;\n\n /**\n * Record that the user approved one request, here, through their own\n * confirmation (the agent runtime's approval store answered it to this tab).\n * An action that needs approval — a `transaction`, or a destructive write —\n * runs only on a request whose `approval` matches an unused, unexpired grant\n * for exactly its params. Each grant admits one request.\n */\n grantApproval(grant: OUIApprovalGrant): void;\n\n /** Called whenever the snapshot changes. */\n subscribe(listener: () => void): () => void;\n\n /** Stop polling, detach from the socket and forget every mount. */\n dispose(): void;\n}\n\n// ─── Implementation ──────────────────────────────────────────────────────────\n\ninterface Entry {\n key: number;\n surface: DefinedSurface<unknown>;\n getContext: () => unknown;\n}\n\nconst DEFAULT_QUIET_MS = 250;\nconst DEFAULT_SETTLE_TIMEOUT_MS = 5000;\nconst DEFAULT_DEDUPE_WINDOW = 500;\nconst DEFAULT_REANSWER_AFTER_MS = 8000;\nconst SETTLE_TICK_MS = 50;\nconst DEFAULT_ANSWER_BYTES = 480 * 1024;\nconst DEFAULT_SNAPSHOT_BYTES = 256 * 1024;\n/** What an answer keeps for the page's observations whatever its `data` weighs. */\nconst OBSERVATION_FLOOR_BYTES = 16 * 1024;\n/** Rows `oui.read` returns of a list when the request names no limit. */\nconst DEFAULT_READ_ROWS = 50;\n\nexport function createSurfaceRuntime(\n options: SurfaceRuntimeOptions & { form: \"index\" },\n): SurfaceRuntime<\"index\">;\nexport function createSurfaceRuntime(\n options?: SurfaceRuntimeOptions & { form?: \"full\" },\n): SurfaceRuntime<\"full\">;\nexport function createSurfaceRuntime(\n options: SurfaceRuntimeOptions = {},\n): SurfaceRuntime<SurfaceForm> {\n const announce = options.announce ?? true;\n const quietMs = options.settle?.quietMs ?? DEFAULT_QUIET_MS;\n const settleTimeoutMs =\n options.settle?.timeoutMs ?? DEFAULT_SETTLE_TIMEOUT_MS;\n const dedupeWindow = options.dedupeWindow ?? DEFAULT_DEDUPE_WINDOW;\n const reanswerAfterMs = options.reanswerAfterMs ?? DEFAULT_REANSWER_AFTER_MS;\n const form: SurfaceForm = options.form ?? \"full\";\n const answerBytes = options.budgets?.answerBytes ?? DEFAULT_ANSWER_BYTES;\n const snapshotBytes =\n options.budgets?.snapshotBytes ?? DEFAULT_SNAPSHOT_BYTES;\n // A defined surface never changes, so its manifest and index are made once.\n const manifests = new WeakMap<object, OUISurface>();\n const indexes = new WeakMap<object, OUISurfaceIndex>();\n const manifestOf = (surface: DefinedSurface<unknown>): OUISurface => {\n let manifest = manifests.get(surface);\n if (!manifest)\n manifests.set(\n surface,\n (manifest = toJsonSafe(surface.toManifest()) as OUISurface),\n );\n return manifest;\n };\n const indexOf = (surface: DefinedSurface<unknown>): OUISurfaceIndex => {\n let index = indexes.get(surface);\n if (!index)\n indexes.set(surface, (index = surfaceIndex(manifestOf(surface))));\n return index;\n };\n\n let nextKey = 1;\n const entries: Entry[] = [];\n const observations = new Map<string, Map<string, unknown>>();\n const serializedObservations = new Map<string, string>();\n const holds = new Set<number>();\n let nextHold = 1;\n const results = new Map<string, Promise<OUIActionResult>>();\n const pollers = new Map<string, ReturnType<typeof setInterval>>();\n // How each running poll answers its request if it has to stop early.\n const abandon = new Map<\n string,\n (error: { code: string; message: string }) => void\n >();\n const listeners = new Set<() => void>();\n // Resolves once a request's first result has been handed to the transport.\n const acks = new Map<\n string,\n { promise: Promise<void>; resolve: () => void }\n >();\n function ackFor(requestId: string) {\n let ack = acks.get(requestId);\n if (!ack) {\n let resolve!: () => void;\n const promise = new Promise<void>((r) => (resolve = r));\n ack = { promise, resolve };\n acks.set(requestId, ack);\n }\n return ack;\n }\n function acknowledged(requestId: string): Promise<void> {\n return ackFor(requestId).promise;\n }\n // How each request's first answer is getting to the agent runtime: still\n // being worked out, sent (when), or acknowledged as received. A repeat of the\n // request is answered again only when the answer may have been lost (§7.3.7).\n const delivery = new Map<\n string,\n { state: \"running\" | \"sent\" | \"received\"; at: number }\n >();\n // The surfaces hash each request's first answer reported: an async action's\n // final answer repeats its surfaces only if they changed since then, since\n // the agent runtime waited for that first answer before waiting for this one.\n const answeredHash = new Map<string, string>();\n let lastChangeAt = Date.now();\n // Approvals the user gave in this tab, by approval id, until used or expired.\n const grants = new Map<string, OUIApprovalGrant>();\n\n /**\n * Why a request for an action that needs approval may not run, or null when\n * it may — in which case its grant is used up.\n */\n async function approvalRefusal(\n request: OUIActionRequest,\n ): Promise<string | null> {\n const approval = request.approval;\n if (!approval)\n return \"it needs the user's approval, and the request carries none\";\n let hash: string;\n try {\n hash = await argsHash(request.params ?? {});\n } catch (err) {\n return `its params cannot be checked against an approval: ${err instanceof Error ? err.message : String(err)}`;\n }\n // Checked and used up with no await in between, so one grant admits one request.\n const grant = grants.get(approval.approvalId);\n if (!grant) return \"this tab holds no unused approval for it\";\n if (Date.now() >= grant.expiresAt) {\n grants.delete(approval.approvalId);\n return \"its approval has expired\";\n }\n if (approval.argsHash !== grant.argsHash || hash !== grant.argsHash) {\n return \"its params are not the ones the user approved\";\n }\n grants.delete(approval.approvalId);\n return null;\n }\n\n let socket: SocketLike | null = null;\n let transport: OUITransport | null = null;\n let detachTransport: Array<() => void> = [];\n\n /**\n * `settles: false` for changes that are not the UI reacting to an action,\n * such as an async job's progress: those notify listeners but do not keep\n * an action's result waiting.\n */\n function changed(settles = true) {\n if (settles) lastChangeAt = Date.now();\n for (const l of [...listeners]) l();\n }\n\n function activeFor(surfaceId: string): Entry | undefined {\n for (let i = entries.length - 1; i >= 0; i--) {\n if (entries[i].surface.id === surfaceId) return entries[i];\n }\n return undefined;\n }\n\n /** Active entries, one per surface id, in the order each id was first mounted. */\n function activeEntries(): Entry[] {\n const seen = new Set<string>();\n const out: Entry[] = [];\n for (const e of entries) {\n if (seen.has(e.surface.id)) continue;\n seen.add(e.surface.id);\n out.push(activeFor(e.surface.id)!);\n }\n return out;\n }\n\n function announceSurface(entry: Entry) {\n if (!announce || !transport) return;\n transport.registerSurface(entry.surface.toManifest());\n const obs = observations.get(entry.surface.id);\n if (obs) {\n for (const [observationId, value] of obs) {\n transport.pushObservation({\n surfaceId: entry.surface.id,\n observationId,\n value,\n timestamp: Date.now(),\n });\n }\n }\n }\n\n function announceAll() {\n for (const e of activeEntries()) announceSurface(e);\n }\n\n function setObservation(\n surfaceId: string,\n observationId: string,\n value: unknown,\n settles = true,\n ) {\n const key = `${surfaceId}\\u0000${observationId}`;\n let serialized: string;\n try {\n serialized = JSON.stringify(value) ?? \"undefined\";\n } catch {\n serialized = String(value);\n }\n if (serializedObservations.get(key) === serialized) return;\n serializedObservations.set(key, serialized);\n\n let obs = observations.get(surfaceId);\n if (!obs) {\n obs = new Map();\n observations.set(surfaceId, obs);\n }\n obs.set(observationId, toJsonSafe(value));\n\n if (announce && transport) {\n transport.pushObservation({\n surfaceId,\n observationId,\n value,\n timestamp: Date.now(),\n });\n }\n changed(settles);\n }\n\n function forgetSurface(surfaceId: string) {\n observations.delete(surfaceId);\n for (const key of [...serializedObservations.keys()]) {\n if (key.startsWith(`${surfaceId}\\u0000`))\n serializedObservations.delete(key);\n }\n for (const [key, timer] of pollers) {\n if (key.startsWith(`${surfaceId}\\u0000`)) {\n clearInterval(timer);\n pollers.delete(key);\n // The request still gets its final answer: a poll that stops\n // without one leaves the agent waiting forever.\n abandon.get(key)?.({\n code: \"SURFACE_NOT_MOUNTED\",\n message:\n `Surface \"${surfaceId}\" left the page before its action finished, ` +\n \"so it is no longer being followed. Check what the page shows \" +\n \"before trying again.\",\n });\n abandon.delete(key);\n }\n }\n }\n\n // ─── Polling (async actions) ──────────────────────────────────────────────\n\n /**\n * Polls an async action to completion, publishing progress as an observation\n * and, when it ends, the request's final result (OUI spec §7.3: an async\n * action is acknowledged, then answered once more when it finishes).\n */\n function startPolling(\n requestId: string,\n surfaceId: string,\n actionId: string,\n polling: ActionPollingConfig<unknown>,\n dispatchResult: unknown,\n ) {\n const finish = async (\n success: boolean,\n data: unknown,\n error?: { code: string; message: string },\n ) => {\n // The acknowledgment goes first: a job can finish before the UI settles.\n await acknowledged(requestId);\n answer(\n frame(\n {\n requestId,\n success,\n ...(data !== undefined ? { data: toJsonSafe(data) } : {}),\n ...(error ? { error } : {}),\n interim: false,\n timestamp: Date.now(),\n },\n answeredHash.get(requestId),\n ),\n );\n acks.delete(requestId);\n answeredHash.delete(requestId);\n };\n\n // The observation id is the one surfaces have always published under.\n const observationId = `${surfaceId}:${actionId}:status`;\n const pollerKey = `${surfaceId}\\u0000${actionId}`;\n\n if (polling.subscribe) {\n setObservation(\n surfaceId,\n observationId,\n { status: \"dispatched\", dispatchResult, interim: true },\n false,\n );\n return;\n }\n if (!polling.resolve) {\n setObservation(\n surfaceId,\n observationId,\n { status: \"dispatched\", dispatchResult, interim: false },\n false,\n );\n return;\n }\n\n const existing = pollers.get(pollerKey);\n if (existing) {\n clearInterval(existing);\n pollers.delete(pollerKey);\n abandon.get(pollerKey)?.({\n code: \"SUPERSEDED\",\n message:\n `\"${actionId}\" was started again before this run finished, ` +\n \"so only the newer run is being followed.\",\n });\n abandon.delete(pollerKey);\n }\n\n setObservation(\n surfaceId,\n observationId,\n { status: \"polling\", dispatchResult, interim: true },\n false,\n );\n\n const maxAttempts = polling.maxAttempts ?? Infinity;\n const maxDuration = polling.maxDurationMs ?? Infinity;\n const startedAt = Date.now();\n let attempts = 0;\n\n const timer = setInterval(async () => {\n attempts++;\n if (attempts > maxAttempts || Date.now() - startedAt > maxDuration) {\n clearInterval(timer);\n pollers.delete(pollerKey);\n abandon.delete(pollerKey);\n setObservation(\n surfaceId,\n observationId,\n { status: \"timeout\", dispatchResult, interim: false },\n false,\n );\n void finish(false, undefined, {\n code: \"TIMEOUT\",\n message: `\"${actionId}\" did not finish within its polling limits.`,\n });\n return;\n }\n const entry = activeFor(surfaceId);\n if (!entry) {\n // forgetSurface normally gets here first; answer anyway.\n clearInterval(timer);\n pollers.delete(pollerKey);\n const gone = abandon.get(pollerKey);\n abandon.delete(pollerKey);\n gone?.({\n code: \"SURFACE_NOT_MOUNTED\",\n message:\n `Surface \"${surfaceId}\" left the page before \"${actionId}\" ` +\n \"finished, so it is no longer being followed. Check what the \" +\n \"page shows before trying again.\",\n });\n return;\n }\n // The surface may have remounted without this action (a control that is\n // disabled while its job runs, say). The job is still running, so keep\n // following it with the polling it started with.\n const action = entry.surface.actions.find((a) => a.id === actionId);\n const resolve = action?.polling?.resolve ?? polling.resolve;\n if (!resolve) return;\n try {\n const r = await resolve(dispatchResult, entry.getContext());\n setObservation(\n surfaceId,\n observationId,\n {\n ...(r.data as Record<string, unknown>),\n interim: !r.done,\n },\n false,\n );\n if (r.done) {\n clearInterval(timer);\n pollers.delete(pollerKey);\n abandon.delete(pollerKey);\n void finish(true, r.data);\n }\n } catch (err) {\n // A transient failure is reported, not fatal: keep polling.\n setObservation(\n surfaceId,\n observationId,\n { status: \"poll_error\", error: String(err), interim: true },\n false,\n );\n }\n }, polling.intervalMs);\n\n pollers.set(pollerKey, timer);\n abandon.set(pollerKey, (error) => void finish(false, undefined, error));\n }\n\n // ─── Settling ─────────────────────────────────────────────────────────────\n\n /**\n * Wait until the page has been quiet for `quietMs` since `since`, with no\n * hold open; false when `settleTimeoutMs` passes first.\n *\n * `since` is when the handler RETURNED, not when the request arrived. A\n * handler that awaits its own work — a save, a restore over the network —\n * and only then changes the page returns later than `quietMs` after it\n * started; measured from the start, the page had already \"been quiet\" for\n * the whole of that wait, so the answer was taken at once, before the UI had\n * rendered the change the handler had just made. The result said the\n * restore had worked and the observations beside it still showed the page\n * before it (dev, 2026-10-03).\n */\n async function waitUntilSettled(since: number): Promise<boolean> {\n const deadline = since + settleTimeoutMs;\n for (;;) {\n const now = Date.now();\n const quietFor = now - Math.max(since, lastChangeAt);\n if (holds.size === 0 && quietFor >= quietMs) return true;\n if (now >= deadline) return false;\n await sleep(Math.min(SETTLE_TICK_MS, deadline - now));\n }\n }\n\n // ─── Execution ────────────────────────────────────────────────────────────\n\n async function run(request: OUIActionRequest): Promise<OUIActionResult> {\n const startedAt = Date.now();\n if (request.surfaceId === OUI_RUNTIME_SURFACE)\n return builtin(request, startedAt);\n const entry = activeFor(request.surfaceId);\n\n let result: ActionHandlerResult;\n let interim = false;\n if (!entry) {\n const mounted = activeEntries().map((e) => e.surface.id);\n result = {\n success: false,\n error: {\n code: \"SURFACE_NOT_MOUNTED\",\n message:\n `Surface \"${request.surfaceId}\" is not on screen. ` +\n `Mounted surfaces: ${mounted.length ? mounted.join(\", \") : \"none\"}.`,\n },\n };\n } else {\n const declared = entry.surface.actions.find(\n (a) => a.id === request.actionId,\n );\n const refusal =\n declared && requiresApproval(declared.effect, declared.confirm)\n ? await approvalRefusal(request)\n : null;\n // executeAction turns a thrown handler into ACTION_EXECUTION_ERROR.\n result = refusal\n ? {\n success: false,\n error: {\n code: \"APPROVAL_REQUIRED\",\n message: `\"${request.actionId}\" was not run: ${refusal}.`,\n },\n }\n : await entry.surface.executeAction(\n request.actionId,\n request.params ?? {},\n entry.getContext(),\n );\n if (result.success) {\n const action = entry.surface.actions.find(\n (a) => a.id === request.actionId,\n );\n if (action?.polling) {\n interim = true;\n startPolling(\n request.requestId,\n entry.surface.id,\n action.id,\n action.polling,\n result.data ?? result.dispatchMeta,\n );\n }\n }\n }\n\n // From now: the handler has returned, and what it changed is still to render.\n const settled = await waitUntilSettled(Date.now());\n const answered = frame(\n {\n requestId: request.requestId,\n success: result.success,\n ...(result.data !== undefined ? { data: toJsonSafe(result.data) } : {}),\n ...(result.error\n ? { error: toJsonSafe(result.error) as OUIActionResult[\"error\"] }\n : {}),\n ...(interim ? { interim: true } : {}),\n durationMs: Date.now() - startedAt,\n timestamp: Date.now(),\n settled,\n },\n request.knownSurfaces,\n );\n if (interim) answeredHash.set(request.requestId, answered.surfacesHash!);\n return answered;\n }\n\n /**\n * An outcome as the answer that carries it: with what the page offers, only\n * when the agent runtime does not already hold it (§7.3.4), and the page's\n * observations, all within the answer's byte budget (§7.3.9). The action's\n * own `data` is kept whole unless it alone outweighs the frame; the\n * observations take what is left, and say where they were cut.\n */\n function frame(\n outcome: OUIActionResult,\n knownSurfaces: string | undefined,\n ): OUIActionResult {\n const page = capture();\n const out: OUIActionResult = {\n ...outcome,\n ...(page.surfacesHash !== knownSurfaces\n ? form === \"index\"\n ? { index: page.index }\n : { surfaces: page.surfaces }\n : {}),\n surfacesHash: page.surfacesHash,\n };\n const fit: OUIFit = {};\n // Definitions that alone outweigh the frame are refused and then left out\n // (§7.3.6): the rest is fitted as the answer that will then be sent.\n const carried =\n jsonBytes(out.index ?? out.surfaces) >= answerBytes\n ? { ...out, index: undefined, surfaces: undefined }\n : out;\n const dataLimit =\n answerBytes -\n jsonBytes({ ...carried, data: undefined }) -\n OBSERVATION_FLOOR_BYTES;\n const dataBytes = jsonBytes(out.data);\n if (dataBytes > Math.max(0, dataLimit)) {\n delete out.data;\n fit.data = { bytes: dataBytes, limit: Math.max(0, dataLimit) };\n }\n const fitted = fitObservations(\n page.observations,\n Math.max(\n 0,\n answerBytes -\n jsonBytes(\n out.data === undefined ? { ...carried, data: undefined } : carried,\n ),\n ),\n );\n out.observations = fitted.observations;\n if (fitted.cuts.length) fit.observations = fitted.cuts;\n if (fit.data || fit.observations) out.fit = fit;\n return out;\n }\n\n // ─── The runtime's own actions (§7.3.10) ─────────────────────────────────────\n\n /**\n * `oui.describe` and `oui.read`: answered here, at once. They read what the\n * client holds and change nothing, so there is nothing to settle, and their\n * answer carries their data and the surfaces hash only.\n */\n function builtin(\n request: OUIActionRequest,\n startedAt: number,\n ): OUIActionResult {\n const done = (\n body: Pick<OUIActionResult, \"success\" | \"data\" | \"error\">,\n ): OUIActionResult => ({\n requestId: request.requestId,\n ...body,\n durationMs: Date.now() - startedAt,\n timestamp: Date.now(),\n surfacesHash: capture().surfacesHash,\n settled: true,\n });\n const refuse = (code: string, message: string) =>\n done({ success: false, error: { code, message } });\n const params = request.params ?? {};\n\n if (request.actionId === OUI_DESCRIBE_ACTION) {\n const asked = params.actions;\n if (\n !Array.isArray(asked) ||\n asked.length === 0 ||\n !asked.every(\n (a) =>\n a &&\n typeof a === \"object\" &&\n typeof (a as Record<string, unknown>).surface === \"string\" &&\n typeof (a as Record<string, unknown>).action === \"string\",\n )\n ) {\n return refuse(\n \"INVALID_PARAMS\",\n '\"describe\" takes actions: [{ surface, action }], at least one',\n );\n }\n const definitions: Array<{ surface: string; action: OUIAction }> = [];\n const missing: Array<{ surface: string; action: string }> = [];\n const deferred: Array<{ surface: string; action: string }> = [];\n let bytes = 0;\n for (const { surface, action } of asked as Array<{\n surface: string;\n action: string;\n }>) {\n const entry = activeFor(surface);\n const definition =\n entry &&\n manifestOf(entry.surface).actions.find((a) => a.id === action);\n if (!definition) {\n missing.push({ surface, action });\n continue;\n }\n const size = jsonBytes(definition);\n // One definition always goes, however large: the rest wait for the next request.\n if (\n definitions.length > 0 &&\n bytes + size > answerBytes - OBSERVATION_FLOOR_BYTES\n ) {\n deferred.push({ surface, action });\n continue;\n }\n bytes += size;\n definitions.push({ surface, action: definition });\n }\n return done({\n success: true,\n data: {\n definitions,\n ...(missing.length ? { missing } : {}),\n ...(deferred.length ? { deferred } : {}),\n },\n });\n }\n\n if (request.actionId === OUI_READ_ACTION) {\n const { surface, observation } = params as Record<string, unknown>;\n const path = params.path === undefined ? \"\" : params.path;\n const offset = params.offset === undefined ? 0 : params.offset;\n const limit =\n params.limit === undefined ? DEFAULT_READ_ROWS : params.limit;\n if (\n typeof surface !== \"string\" ||\n typeof observation !== \"string\" ||\n typeof path !== \"string\"\n ) {\n return refuse(\n \"INVALID_PARAMS\",\n '\"read\" takes surface, observation and, to read part of the value, path',\n );\n }\n if (\n !Number.isInteger(offset) ||\n (offset as number) < 0 ||\n !Number.isInteger(limit) ||\n (limit as number) < 1\n ) {\n return refuse(\n \"INVALID_PARAMS\",\n '\"read\" takes offset (0 or more) and limit (1 or more) as whole numbers',\n );\n }\n const values = observations.get(surface);\n if (!values || !values.has(observation)) {\n const known = values ? [...values.keys()] : [];\n return refuse(\n \"NOT_FOUND\",\n values\n ? `Surface \"${surface}\" reports no observation \"${observation}\". It reports: ${known.join(\", \") || \"none\"}.`\n : `Surface \"${surface}\" is not on screen, or reports nothing.`,\n );\n }\n let value: unknown;\n try {\n value = atPointer(values.get(observation), path);\n } catch (err) {\n return refuse(\n \"INVALID_PARAMS\",\n err instanceof Error ? err.message : String(err),\n );\n }\n if (value === undefined) {\n return refuse(\n \"NOT_FOUND\",\n `Nothing is at \"${path}\" in ${surface}.${observation}.`,\n );\n }\n const room = answerBytes - OBSERVATION_FLOOR_BYTES;\n if (Array.isArray(value)) {\n const total = value.length;\n let rows = value.slice(\n offset as number,\n (offset as number) + (limit as number),\n );\n // A page of rows that outweighs the frame is halved until it fits; one row always goes.\n while (rows.length > 1 && jsonBytes(rows) > room)\n rows = rows.slice(0, Math.ceil(rows.length / 2));\n const next = (offset as number) + rows.length;\n return done({\n success: true,\n data: {\n rows,\n total,\n offset,\n ...(next < total ? { more: true, next } : {}),\n },\n });\n }\n const fitted = fitObservations(\n { [surface]: { [observation]: value } },\n room,\n );\n // Cuts are reported relative to the observation, as every other cut is.\n const cuts = fitted.cuts.map((c) => ({ ...c, path: `${path}${c.path}` }));\n return done({\n success: true,\n data: {\n value: fitted.observations[surface][observation],\n ...(cuts.length ? { fit: { observations: cuts } } : {}),\n },\n });\n }\n\n return refuse(\n \"ACTION_NOT_FOUND\",\n `The runtime answers \"${OUI_DESCRIBE_ACTION}\" and \"${OUI_READ_ACTION}\"; it has no \"${request.actionId}\".`,\n );\n }\n\n // ─── Answering ────────────────────────────────────────────────────────────\n\n /**\n * Send an answer, and if the receiving side refuses it, send it again\n * trimmed, saying why (§7.3.6): first without what the page offers, then\n * without the page's observations too, then without the action's data. What\n * the page shows is given up after what it offers: an agent that still sees\n * the page can carry on, and one that does not must stop. An answer that is\n * refused and not sent again leaves the agent waiting until its deadline,\n * then reporting an action that ran as one that did not answer.\n */\n function answer(result: OUIActionResult, onReceived?: () => void) {\n const offered = form === \"index\" ? \"index\" : \"surfaces\";\n const steps: Array<OUIResultDelivery[\"omitted\"]> = [\n [offered],\n [offered, \"observations\"],\n [offered, \"observations\", \"data\"],\n ];\n const send = (frame: OUIActionResult, step: number) => {\n transport?.sendResult(frame, (ack) => {\n if (ack.ok) {\n onReceived?.();\n return;\n }\n const omitted = steps[step];\n if (!omitted) {\n console.warn(\n `[OUI] The answer to ${result.requestId} was refused even trimmed: ${ack.reason}`,\n );\n return;\n }\n console.warn(\n `[OUI] The answer to ${result.requestId} was refused (${ack.reason}); sending it without ${omitted.join(\", \")}`,\n );\n send(trimmed(result, ack.reason, omitted), step + 1);\n });\n };\n send(result, 0);\n }\n\n function execute(request: OUIActionRequest): Promise<OUIActionResult> {\n const seen = results.get(request.requestId);\n if (seen) return seen;\n\n const pending = run(request);\n results.set(request.requestId, pending);\n while (results.size > dedupeWindow) {\n const oldest = results.keys().next().value as string;\n results.delete(oldest);\n delivery.delete(oldest);\n }\n return pending;\n }\n\n // ─── Snapshot ─────────────────────────────────────────────────────────────\n\n /** What is mounted, in the runtime's form, with every observation whole. */\n function capture(): {\n surfaces?: OUISurface[];\n index?: OUISurfaceIndex[];\n observations: OUIObservationSnapshot;\n surfacesHash: string;\n } {\n const active = activeEntries();\n const obs: OUIObservationSnapshot = {};\n for (const e of active) {\n const values = observations.get(e.surface.id);\n if (values && values.size > 0)\n obs[e.surface.id] = Object.fromEntries(values);\n }\n if (form === \"index\") {\n const index = active.map((e) => indexOf(e.surface));\n return { index, observations: obs, surfacesHash: surfacesHash(index) };\n }\n const surfaces = active.map((e) => manifestOf(e.surface));\n return {\n surfaces,\n observations: obs,\n surfacesHash: surfacesHash(surfaces),\n };\n }\n\n function snapshot(): OUISurfaceSnapshot | OUIIndexSnapshot {\n const page = capture();\n const offered =\n form === \"index\" ? { index: page.index! } : { surfaces: page.surfaces! };\n // Definitions that alone outweigh the snapshot cannot be shortened here:\n // the observations are then fitted to the whole budget, not to none of it.\n const offeredBytes = jsonBytes(offered);\n const fitted = fitObservations(\n page.observations,\n offeredBytes >= snapshotBytes\n ? snapshotBytes\n : snapshotBytes - offeredBytes,\n );\n return {\n ...offered,\n observations: fitted.observations,\n surfacesHash: page.surfacesHash,\n ...(fitted.cuts.length ? { fit: { observations: fitted.cuts } } : {}),\n };\n }\n\n // ─── Transport ────────────────────────────────────────────────────────────\n\n function attach(next: SocketLike | null) {\n if (next === socket) return;\n for (const off of detachTransport) off();\n detachTransport = [];\n transport?.dispose();\n transport = null;\n socket = next;\n if (!next) return;\n\n const t = createWebSocketTransport(next, options.transport);\n transport = t;\n\n detachTransport.push(\n t.onAction((request, receipt) => {\n if (options.accept && !options.accept(request)) {\n console.warn(\n `[OUI] Refused a request the client does not accept: ${request.surfaceId}.${request.actionId} (${request.requestId})`,\n );\n receipt?.({\n ok: false,\n reason: \"this client does not accept requests now\",\n });\n return;\n }\n // Received: the sender need not send it again (§7.3.7).\n receipt?.({ ok: true });\n const id = request.requestId;\n const prior = delivery.get(id);\n // A repeat while the answer is being worked out, or is on its way, or\n // has arrived, gets no second copy: copies of a large answer queue on\n // the one socket ahead of the next request's answer.\n if (prior && prior.state !== \"sent\") return;\n if (prior && Date.now() - prior.at < reanswerAfterMs) return;\n if (!prior) delivery.set(id, { state: \"running\", at: Date.now() });\n void execute(request).then((result) => {\n // Answer on whichever transport is live when the result is ready: a\n // reconnect in between keeps the same socket, so this still reaches\n // the runtime that asked.\n if (results.has(id))\n delivery.set(id, { state: \"sent\", at: Date.now() });\n answer(result, () => {\n if (results.has(id))\n delivery.set(id, { state: \"received\", at: Date.now() });\n });\n const ack = ackFor(id);\n ack.resolve();\n // Keep the gate only while a final result may still follow.\n if (!result.interim) acks.delete(id);\n });\n }),\n );\n\n if (announce) {\n // A server-side registry forgets a socket's surfaces when it drops, so\n // every (re)connection announces them again.\n detachTransport.push(\n t.onConnectionChange((connected) => {\n if (connected) announceAll();\n }),\n );\n if (t.connected) announceAll();\n }\n }\n\n if (options.socket) attach(options.socket);\n\n // ─── Mounting ─────────────────────────────────────────────────────────────\n\n function mount<TContext>(\n surface: DefinedSurface<TContext>,\n getContext: () => TContext,\n ): MountedSurface {\n const entry: Entry = {\n key: nextKey++,\n surface: surface as unknown as DefinedSurface<unknown>,\n getContext: getContext as () => unknown,\n };\n entries.push(entry);\n announceSurface(entry);\n changed();\n\n let mounted = true;\n return {\n surfaceId: surface.id,\n pushObservation(observationId, value) {\n // Only the mount serving the surface speaks for it.\n if (!mounted || activeFor(surface.id) !== entry) return;\n setObservation(surface.id, observationId, value);\n },\n unmount() {\n if (!mounted) return;\n mounted = false;\n const i = entries.indexOf(entry);\n if (i >= 0) entries.splice(i, 1);\n const replacement = activeFor(surface.id);\n if (replacement) {\n announceSurface(replacement);\n } else {\n forgetSurface(surface.id);\n if (announce && transport) transport.deregisterSurface(surface.id);\n }\n changed();\n },\n };\n }\n\n return {\n mount,\n attach,\n snapshot: snapshot as SurfaceRuntime<SurfaceForm>[\"snapshot\"],\n execute,\n hold() {\n const id = nextHold++;\n holds.add(id);\n changed();\n let released = false;\n return () => {\n if (released) return;\n released = true;\n holds.delete(id);\n changed();\n };\n },\n grantApproval(grant) {\n if (\n !grant ||\n typeof grant.approvalId !== \"string\" ||\n !grant.approvalId ||\n typeof grant.argsHash !== \"string\" ||\n !ARGS_HASH_PATTERN.test(grant.argsHash) ||\n !Number.isFinite(grant.expiresAt)\n ) {\n throw new Error(\n \"[OUI] grantApproval needs an approvalId, an args hash and an expiry\",\n );\n }\n const now = Date.now();\n for (const [id, g] of grants) if (now >= g.expiresAt) grants.delete(id);\n grants.set(grant.approvalId, { ...grant });\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n dispose() {\n for (const timer of pollers.values()) clearInterval(timer);\n pollers.clear();\n abandon.clear();\n attach(null);\n entries.length = 0;\n observations.clear();\n serializedObservations.clear();\n holds.clear();\n listeners.clear();\n acks.clear();\n answeredHash.clear();\n delivery.clear();\n grants.clear();\n },\n };\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\n/** `result` without the fields `omitted` names, saying so and why (§7.3.6). */\nfunction trimmed(\n result: OUIActionResult,\n reason: string,\n omitted: OUIResultDelivery[\"omitted\"],\n): OUIActionResult {\n const out: OUIActionResult = { ...result };\n for (const field of omitted) delete out[field];\n out.delivery = { trimmed: true, reason, omitted: [...omitted] };\n return out;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Results and observations cross a wire as JSON. A handler returning something\n * that is not (a DOM node, a class instance with cycles) must not take the\n * result down with it.\n */\nfunction toJsonSafe(value: unknown): unknown {\n if (value === undefined) return undefined;\n try {\n return JSON.parse(JSON.stringify(value));\n } catch {\n return String(value);\n }\n}\n"]}
@@ -273,22 +273,41 @@ function summarizeInput(schema) {
273
273
  if (more > 0) parts.push(`+${more} more`);
274
274
  return clip(parts.join(", "), INDEX_INPUT_CHARS);
275
275
  }
276
+ var TITLE_LEAD_IN_CHARS = 32;
277
+ function withoutTitleLeadIn(description, title) {
278
+ const line = description.replace(/\s+/g, " ").trim();
279
+ if (!title) return line;
280
+ const name = title.replace(/\s+/g, " ").trim();
281
+ if (!name) return line;
282
+ let rest;
283
+ if (line.startsWith(`${name}: `)) rest = line.slice(name.length + 2);
284
+ else {
285
+ const quoted = `"${name}": `;
286
+ const at = line.indexOf(quoted);
287
+ if (at >= 0 && at <= TITLE_LEAD_IN_CHARS && !/[.:!?"]/.test(line.slice(0, at)))
288
+ rest = line.slice(at + quoted.length);
289
+ }
290
+ const kept = rest?.trim();
291
+ return kept ? kept : line;
292
+ }
293
+ var DEFINITION_HASH_HEX = 8;
276
294
  function definitionHash(action) {
277
- return fnv1a64(sortedJson(action));
295
+ return fnv1a64(sortedJson(action)).slice(0, DEFINITION_HASH_HEX);
278
296
  }
279
297
  function indexEntry(action) {
280
298
  return {
281
299
  id: action.id,
282
300
  ...action.title ? { title: action.title } : {},
283
- description: firstSentence(action.description),
301
+ description: firstSentence(
302
+ withoutTitleLeadIn(action.description, action.title)
303
+ ),
284
304
  ...action.effect !== void 0 ? { effect: action.effect } : {},
285
305
  ...action.confirm ? { confirm: true } : {},
286
306
  ...action.async ? { async: true } : {},
287
307
  ...action.estimatedDuration ? { estimatedDuration: action.estimatedDuration } : {},
288
308
  ...action.polling?.maxDurationMs !== void 0 ? { maxDurationMs: action.polling.maxDurationMs } : {},
289
309
  input: summarizeInput(action.input),
290
- definitionHash: definitionHash(action),
291
- definitionBytes: jsonBytes(action)
310
+ definitionHash: definitionHash(action)
292
311
  };
293
312
  }
294
313
  function surfaceIndex(surface) {
@@ -429,6 +448,7 @@ function fitObservations(observations, budget) {
429
448
  }
430
449
 
431
450
  exports.ARGS_HASH_PATTERN = ARGS_HASH_PATTERN;
451
+ exports.DEFINITION_HASH_HEX = DEFINITION_HASH_HEX;
432
452
  exports.FIT_LIST_STEPS = FIT_LIST_STEPS;
433
453
  exports.FIT_TEXT_CHARS = FIT_TEXT_CHARS;
434
454
  exports.INDEX_DESCRIPTION_CHARS = INDEX_DESCRIPTION_CHARS;
@@ -459,5 +479,6 @@ exports.summarizeInput = summarizeInput;
459
479
  exports.surfaceIndex = surfaceIndex;
460
480
  exports.surfacesHash = surfacesHash;
461
481
  exports.utf8Length = utf8Length;
462
- //# sourceMappingURL=chunk-2CPOHQGI.cjs.map
463
- //# sourceMappingURL=chunk-2CPOHQGI.cjs.map
482
+ exports.withoutTitleLeadIn = withoutTitleLeadIn;
483
+ //# sourceMappingURL=chunk-63T6SSPP.cjs.map
484
+ //# sourceMappingURL=chunk-63T6SSPP.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/spec/types.ts","../src/spec/approval.ts","../src/spec/surfaces-hash.ts","../src/spec/index-form.ts","../src/spec/fit.ts"],"names":[],"mappings":";;;AAoeO,IAAM,mBAAA,GAAsB;AAAA,EACjC,gBAAA,EAAkB,kBAAA;AAAA,EAClB,kBAAA,EAAoB,oBAAA;AAAA,EACpB,cAAA,EAAgB,gBAAA;AAAA,EAChB,aAAA,EAAe,eAAA;AAAA,EACf,kBAAA,EAAoB;AACtB;;;ACjcO,IAAM,gBAAA,GAA6C;AAAA,EACxD,MAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,K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D","file":"chunk-63T6SSPP.cjs","sourcesContent":["import type { OUIActionApproval, OUIEffectKind } from \"./approval.js\";\n\n/**\n * OUI — Open UI Specification\n *\n * The machine-readable contract for agent-controllable user interfaces.\n * Any UI application that implements this interface can be controlled by\n * any OUI-compatible agent runtime.\n */\n\n/** JSON Schema type (subset used by OUI) */\nexport type JSONSchema = {\n type?: string | string[];\n properties?: Record<string, JSONSchema>;\n items?: JSONSchema;\n required?: string[];\n enum?: (string | number | boolean)[];\n description?: string;\n default?: unknown;\n oneOf?: JSONSchema[];\n anyOf?: JSONSchema[];\n allOf?: JSONSchema[];\n const?: unknown;\n minimum?: number;\n maximum?: number;\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n format?: string;\n additionalProperties?: boolean | JSONSchema;\n title?: string;\n /** Annotations (`x-unit`, `x-rows`, …) a product's contract adds; OUI carries them unread. */\n [annotation: `x-${string}`]: unknown;\n};\n\n/**\n * A Surface is a controllable boundary within an application.\n * It declares what an agent can do (actions), what it can observe (state),\n * and when it's available (activation conditions).\n *\n * Think of it as \"one page\" or \"one feature\" of an application, described\n * in a way that an agent can understand and operate.\n */\nexport interface OUISurface {\n /** Unique identifier for this surface (e.g., 'dataviz-wizard', 'document-editor') */\n id: string;\n\n /** Human-readable name */\n name: string;\n\n /** Description of what this surface does — included in agent context */\n description: string;\n\n /** Version of this surface's contract (semver) */\n version?: string;\n\n /** Actions the agent can invoke on this surface */\n actions: OUIAction[];\n\n /** Observable state the agent can read */\n observations?: OUIObservation[];\n\n /** When this surface is active/available */\n activation?: OUIActivation;\n\n /** Additional metadata for agent context */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Declarative polling configuration for async actions.\n * The OUI runtime in the browser manages the polling lifecycle automatically\n * after the action handler returns its dispatch result.\n */\nexport interface OUIActionPolling {\n /** How often to check (milliseconds) */\n intervalMs: number;\n\n /** Max poll attempts before giving up (optional) */\n maxAttempts?: number;\n\n /** Max total duration before giving up in ms (alternative to maxAttempts) */\n maxDurationMs?: number;\n\n /**\n * Subscribe to a realtime event instead of polling.\n * If provided, the runtime listens for this event instead of using setInterval.\n * More efficient when realtime infrastructure exists.\n */\n subscribe?: {\n /** Event name to listen for */\n event: string;\n /**\n * Filter to match the event. Values prefixed with '$dispatchResult.'\n * are resolved from the handler's return value.\n * Example: { jobId: '$dispatchResult.jobId' }\n */\n filter?: Record<string, unknown>;\n };\n}\n\n/**\n * An Action is a single operation an agent can perform on a surface.\n * Each action becomes a \"tool\" that the LLM can call.\n *\n * The action's handler executes in the UI (or API) and returns a result\n * that the agent sees as the tool's output.\n */\nexport interface OUIAction {\n /** Unique action identifier (becomes the tool name) */\n id: string;\n\n /** Human-readable description — this is what the LLM reads to decide when to use it */\n description: string;\n\n /** The action's name as a person reads it, for a confirmation the user approves. */\n title?: string;\n\n /**\n * What using the action does. A `transaction` runs only on the user's\n * approval of the exact request (see `requiresApproval`). Undeclared counts\n * as a write.\n */\n effect?: OUIEffectKind;\n\n /** JSON Schema for the action's input parameters */\n input: JSONSchema;\n\n /** JSON Schema for the action's return value (optional — agent still gets the result) */\n output?: JSONSchema;\n\n /**\n * Destructive: the action removes or replaces something the person made.\n * Unless its effect only reads, it runs only on the user's approval of the\n * exact request, which the surface runtime checks before it runs.\n */\n confirm?: boolean;\n\n /** If true, the action is async — returns immediately with a job/tracking ID */\n async?: boolean;\n\n /** Declarative polling configuration — runtime manages the polling lifecycle after dispatch */\n polling?: OUIActionPolling;\n\n /** Human-readable hint about when this action is appropriate to use */\n usage?: string;\n\n /**\n * Preconditions that should be met before this action is called.\n * Expressed as a description (for the LLM) not as executable logic.\n */\n preconditions?: string;\n\n /** Estimated duration hint (e.g., \"instant\", \"2-5s\", \"30-120s\") */\n estimatedDuration?: string;\n\n /** Tags for categorization */\n tags?: string[];\n}\n\n/**\n * An Observation is a piece of application state that the agent can read.\n * Observations are pushed to the agent in real-time as the app state changes,\n * giving it situational awareness without needing screenshots.\n */\nexport interface OUIObservation {\n /** Unique identifier for this observation */\n id: string;\n\n /** Description of what this observation represents */\n description: string;\n\n /** JSON Schema for the observation's value */\n schema: JSONSchema;\n\n /** How frequently this observation updates */\n updateFrequency?: \"realtime\" | \"on-change\" | \"polling\";\n}\n\n/**\n * Activation conditions — when a surface is available to the agent.\n * A surface might only be active on a specific page, when certain\n * entities are loaded, or under specific application states.\n */\nexport interface OUIActivation {\n /** URL path(s) where this surface is active */\n routes?: string | string[];\n\n /** Entity type/ID that must be present for this surface to activate */\n entity?: {\n type: string;\n id?: string;\n };\n\n /** Custom predicate description (for documentation, not execution) */\n condition?: string;\n}\n\n// ─── Index form (§7.3.8) ───────────────────────────────────────────────────────\n\n/**\n * One action as a snapshot and an answer carry it: enough to choose it and to\n * know what it takes in outline, without its definition. A page's actions\n * weigh what its whole catalogue weighs (on a studio page, several hundred\n * KB), and an agent runtime that received every definition could neither be\n * sent them in one frame nor give them all to its model. The definition of an\n * action is fetched when it is needed (`oui.describe`, §7.3.10).\n */\nexport interface OUIActionIndexEntry {\n /** The action's id. */\n id: string;\n /** Its name as a person reads it. */\n title?: string;\n /** The first sentence of its description, at most `INDEX_DESCRIPTION_CHARS` characters. */\n description: string;\n effect?: OUIEffectKind;\n confirm?: boolean;\n async?: boolean;\n estimatedDuration?: string;\n /** For an async action: how long its work is followed before it is reported as not finished. */\n maxDurationMs?: number;\n /** What it takes, in one line (`summarizeInput`): \"none\", \"value: number 0–100\", \"clipId, start?, +4 more\". */\n input: string;\n /**\n * A hash of the full definition: a fetched definition is good until this\n * changes. Opaque to a reader, which only compares it with the same action's\n * earlier one: 8 hex digits since 0.8, 16 before.\n */\n definitionHash: string;\n}\n\n/** A surface as a snapshot and an answer carry it in index form: its actions as index entries. */\nexport interface OUISurfaceIndex {\n id: string;\n name: string;\n description: string;\n version?: string;\n /** Observation definitions travel whole: they are small, and say how to read the values that follow. */\n observations?: OUIObservation[];\n index: OUIActionIndexEntry[];\n}\n\n/**\n * One place where a snapshot's or an answer's observations were shortened to\n * fit its byte budget (§7.3.9): a list cut to its first rows, a long text cut,\n * or a value left out. The rest is read with `oui.read` (§7.3.10), by this\n * surface, observation and path.\n */\nexport interface OUIFitCut {\n surface: string;\n observation: string;\n /** JSON Pointer (RFC 6901) into the observation's value; \"\" is the value itself. */\n path: string;\n kind: \"list\" | \"text\" | \"value\";\n /** Rows of a list, characters of a text, bytes of a value. */\n total: number;\n /** How many of them this frame keeps. */\n kept: number;\n}\n\n/** What was shortened or left out to fit a frame's byte budget (§7.3.9). */\nexport interface OUIFit {\n observations?: OUIFitCut[];\n /** The action's `data` was left out: its size, and the most a frame could carry. */\n data?: { bytes: number; limit: number };\n}\n\n// ─── Protocol Types ──────────────────────────────────────────────────────────\n\n/**\n * A request from the agent runtime to execute an action on a surface.\n */\nexport interface OUIActionRequest {\n /** Unique request ID for correlation */\n requestId: string;\n\n /** Which surface this request targets */\n surfaceId: string;\n\n /** Which action to invoke */\n actionId: string;\n\n /** The action's input parameters (validated against the action's input schema) */\n params: Record<string, unknown>;\n\n /** Timestamp of the request */\n timestamp: number;\n\n /**\n * The user's approval this request runs on, for an action that needs one.\n * The surface runtime runs such an action only when this matches a grant\n * the tab received from the user's own confirmation, for exactly `params`.\n */\n approval?: OUIActionApproval;\n\n /**\n * The `surfacesHash` of the surfaces the agent runtime already holds for\n * this client: from its snapshot, or from an earlier result. A client whose\n * surfaces still hash to this answers without `surfaces`, so a result\n * carries the client's surfaces only when they changed (§7.3.4).\n */\n knownSurfaces?: string;\n}\n\n/**\n * Why a client's answer is shorter than the result it produced: the receiving\n * side refused the full answer (too large, or otherwise not accepted), so the\n * client sent it again without the parts named in `omitted`. The action's own\n * outcome — `success`, `error`, and `data` unless omitted — is still the one\n * that happened (§7.3.6).\n */\nexport interface OUIResultDelivery {\n trimmed: true;\n /** What the receiving side said when it refused the full answer. */\n reason: string;\n /** The fields left out of this answer. */\n omitted: Array<\"surfaces\" | \"index\" | \"observations\" | \"data\">;\n}\n\n/**\n * The result of an action execution, returned from the surface to the agent.\n */\nexport interface OUIActionResult {\n /** Correlates to the request */\n requestId: string;\n\n /** Whether the action succeeded */\n success: boolean;\n\n /** The action's return data (if successful) */\n data?: unknown;\n\n /** Error information (if failed) */\n error?: {\n code: string;\n message: string;\n details?: unknown;\n };\n\n /** Progress indicator for interim polling results (0-100) */\n progress?: number;\n\n /** Whether this is an interim update (polling still in progress) or final */\n interim?: boolean;\n\n /** Duration of execution in milliseconds */\n durationMs?: number;\n\n /** Timestamp of the result */\n timestamp: number;\n\n /**\n * The surfaces active on the client once the action's effects settled.\n *\n * An action can change what the agent is able to do next: navigating\n * unmounts one page's surfaces and mounts another's. Without this, the agent\n * would act on the capability set it had before the action, which is the\n * set the action just replaced.\n */\n surfaces?: OUISurface[];\n\n /**\n * The same, in index form (§7.3.8): what a client sends in place of\n * `surfaces` unless it was made to send definitions.\n */\n index?: OUISurfaceIndex[];\n\n /** Latest observation values per surface once the action's effects settled. */\n observations?: OUIObservationSnapshot;\n\n /** What was shortened or left out so this answer fits its byte budget (§7.3.9). */\n fit?: OUIFit;\n\n /**\n * The hash of the client's surfaces once the action's effects settled\n * (`surfacesHash`). Always present from a client that sends it; `surfaces`\n * is then present only when this differs from the request's\n * `knownSurfaces`, and an agent runtime that holds surfaces with this hash\n * keeps using them.\n */\n surfacesHash?: string;\n\n /** Present when this answer was trimmed to be delivered (§7.3.6). */\n delivery?: OUIResultDelivery;\n\n /**\n * False when the client's deadline passed before its UI settled, so\n * `surfaces` and `observations` may still be changing. Absent or true\n * otherwise.\n */\n settled?: boolean;\n}\n\n/** Latest observation values, keyed by surface id and then observation id. */\nexport type OUIObservationSnapshot = Record<string, Record<string, unknown>>;\n\n/**\n * What a client can do right now: the surfaces it has mounted and their latest\n * observation values. A client sends this to its agent runtime (for example,\n * with each turn), and returns it on every action result.\n *\n * This is the full form: every action with its definition. A client made in\n * index form (§7.3.8) sends an `OUIIndexSnapshot` instead.\n */\nexport interface OUISurfaceSnapshot {\n surfaces: OUISurface[];\n observations: OUIObservationSnapshot;\n /**\n * `surfacesHash(surfaces)`: what an agent runtime sends back as a request's\n * `knownSurfaces`, so the client's answer need not repeat surfaces the\n * runtime already holds.\n */\n surfacesHash?: string;\n /** What was shortened so the snapshot fits its byte budget (§7.3.9). */\n fit?: OUIFit;\n}\n\n/** A client's snapshot in index form (§7.3.8): each action as an index entry, not its definition. */\nexport interface OUIIndexSnapshot {\n index: OUISurfaceIndex[];\n observations: OUIObservationSnapshot;\n /** `surfacesHash(index)`. */\n surfacesHash?: string;\n /** What was shortened so the snapshot fits its byte budget (§7.3.9). */\n fit?: OUIFit;\n}\n\n/** A snapshot as an agent runtime receives it: in either form. */\nexport type OUIClientSnapshot = OUISurfaceSnapshot | OUIIndexSnapshot;\n\n/**\n * An observation update pushed from the surface to the agent.\n */\nexport interface OUIObservationUpdate {\n /** Which surface this observation belongs to */\n surfaceId: string;\n\n /** Which observation updated */\n observationId: string;\n\n /** The new value */\n value: unknown;\n\n /** Timestamp of the update */\n timestamp: number;\n}\n\n/**\n * Surface registration event — sent when a surface becomes active.\n */\nexport interface OUISurfaceRegistration {\n /** The full surface manifest */\n surface: OUISurface;\n\n /** Timestamp of registration */\n timestamp: number;\n}\n\n/**\n * Surface deregistration event — sent when a surface becomes inactive.\n */\nexport interface OUISurfaceDeregistration {\n /** Which surface is being deregistered */\n surfaceId: string;\n\n /** Timestamp */\n timestamp: number;\n}\n\n// ─── Transport Protocol Events ───────────────────────────────────────────────\n\n/**\n * All protocol events exchanged between agent runtime and surfaces.\n */\nexport type OUIProtocolEvent =\n | { type: \"surface:register\"; payload: OUISurfaceRegistration }\n | { type: \"surface:deregister\"; payload: OUISurfaceDeregistration }\n | { type: \"action:request\"; payload: OUIActionRequest }\n | { type: \"action:result\"; payload: OUIActionResult }\n | { type: \"observation:update\"; payload: OUIObservationUpdate };\n\n/**\n * Protocol event type strings (for type guards and routing).\n */\nexport const OUI_PROTOCOL_EVENTS = {\n SURFACE_REGISTER: \"surface:register\",\n SURFACE_DEREGISTER: \"surface:deregister\",\n ACTION_REQUEST: \"action:request\",\n ACTION_RESULT: \"action:result\",\n OBSERVATION_UPDATE: \"observation:update\",\n} as const;\n","/**\n * Approvals: an irreversible action runs only on an approval the user gave,\n * bound to the exact request.\n *\n * An agent runtime stops at an action that needs approval and shows the user\n * a confirmation. Its approval store issues a single-use grant when the user\n * confirms, and the request that then reaches the tab carries `approval:\n * { approvalId, argsHash }`. The surface runtime runs the action only when\n * that matches a grant this tab received from the user's own confirmation.\n *\n * Everything that checks a request computes the same args hash: SHA-256 over\n * the RFC 8785 (JCS) canonical JSON of its params, lowercase hex. The\n * published vectors (`oui-spec/approval-vectors.json`) hold every\n * implementation, in any language, to it.\n */\n\n/**\n * What using an action does. One vocabulary for every kind of action, so an\n * action is told apart by what it changes:\n *\n * | Effect | What it changes | Access |\n * |---|---|---|\n * | `view`, `selection`, `navigate`, `open` | What is shown | read |\n * | `edit` | The document, one undo step | write |\n * | `file` | Imports or exports a file | write |\n * | `mutate` | Backend data, through an API operation | write |\n * | `job` | Starts work that outlives the call | write |\n * | `transaction` | An irreversible external act: an order, a payment, a send, a publish | write, approved |\n */\nexport type OUIEffectKind =\n | \"view\"\n | \"selection\"\n | \"navigate\"\n | \"open\"\n | \"edit\"\n | \"file\"\n | \"mutate\"\n | \"job\"\n | \"transaction\";\n\n/** Every effect, in the order of the table above. */\nexport const OUI_EFFECT_KINDS: readonly OUIEffectKind[] = [\n \"view\",\n \"selection\",\n \"navigate\",\n \"open\",\n \"edit\",\n \"file\",\n \"mutate\",\n \"job\",\n \"transaction\",\n];\n\n/** Whether an effect only changes what is shown, or changes something. */\nexport const OUI_EFFECT_ACCESS: Readonly<\n Record<OUIEffectKind, \"read\" | \"write\">\n> = {\n view: \"read\",\n selection: \"read\",\n navigate: \"read\",\n open: \"read\",\n edit: \"write\",\n file: \"write\",\n mutate: \"write\",\n job: \"write\",\n transaction: \"write\",\n};\n\n/** `read` or `write`. An action that declares no effect is a `write`: nothing says it only shows. */\nexport function effectAccess(\n effect: OUIEffectKind | undefined,\n): \"read\" | \"write\" {\n return effect === undefined ? \"write\" : OUI_EFFECT_ACCESS[effect];\n}\n\n/**\n * Whether running an action needs the user's approval of the exact request: a\n * `transaction` always, and a `write` declared destructive. An agent\n * runtime's policy may require it of more; nothing waives these.\n */\nexport function requiresApproval(\n effect: OUIEffectKind | undefined,\n destructive?: boolean,\n): boolean {\n if (effect === \"transaction\") return true;\n return !!destructive && effectAccess(effect) === \"write\";\n}\n\n/** What a request for an approved action carries. */\nexport interface OUIActionApproval {\n approvalId: string;\n /** `argsHash(params)` of the request the user approved. */\n argsHash: string;\n}\n\n/** A grant this tab holds: the user approved this request here. */\nexport interface OUIApprovalGrant extends OUIActionApproval {\n /** Epoch ms after which the grant no longer admits anything. */\n expiresAt: number;\n}\n\n/** An args hash: 64 lowercase hex digits. */\nexport const ARGS_HASH_PATTERN = /^[0-9a-f]{64}$/;\n\n/**\n * The RFC 8785 canonical form of a JSON value:\n * - object members sorted by their names' UTF-16 code units, with no\n * whitespace;\n * - numbers in ECMAScript's shortest round-trip form (`-0` is `0`);\n * - strings escaped as ECMAScript's `JSON.stringify` escapes them.\n *\n * The value must be I-JSON (RFC 7493): anything JSON cannot carry — `NaN`,\n * infinities, `undefined` outside an object member, a bigint, a function, a\n * symbol, a class instance, or a string with a lone surrogate — is refused\n * rather than hashed as something the other end never receives. An object\n * member whose value is `undefined` is left out, as it is on the wire.\n */\nexport function canonicalJson(value: unknown): string {\n return serialize(value, \"$\");\n}\n\n/** SHA-256 of the canonical JSON of a request's params, lowercase hex. Runs wherever WebCrypto does. */\nexport async function argsHash(params: unknown): Promise<string> {\n const canonical = canonicalJson(params);\n const subtle = await webCrypto();\n const digest = await subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(canonical),\n );\n let hex = \"\";\n for (const byte of new Uint8Array(digest))\n hex += byte.toString(16).padStart(2, \"0\");\n return hex;\n}\n\n/**\n * WebCrypto: global in browsers and Node 19+; Node 18 has it only on\n * `node:crypto`, imported here by a specifier bundlers leave alone.\n */\nasync function webCrypto(): Promise<SubtleCrypto> {\n const global = globalThis.crypto?.subtle;\n if (global) return global;\n const nodeCrypto = \"node:crypto\";\n try {\n const mod = (await import(/* @vite-ignore */ nodeCrypto)) as {\n webcrypto?: { subtle?: SubtleCrypto };\n };\n if (mod.webcrypto?.subtle) return mod.webcrypto.subtle;\n } catch {\n // Not Node: fall through to the error below.\n }\n throw new Error(\n \"[OUI] argsHash needs WebCrypto (crypto.subtle), which this runtime does not provide\",\n );\n}\n\nfunction refuse(path: string, what: string): never {\n throw new TypeError(`[OUI] ${path} is not I-JSON: ${what}`);\n}\n\nfunction serialize(value: unknown, path: string): string {\n switch (typeof value) {\n case \"string\":\n return quote(value, path);\n case \"number\":\n if (!Number.isFinite(value)) refuse(path, String(value));\n // ECMAScript's Number-to-string is RFC 8785's number form, and prints -0 as 0.\n return JSON.stringify(value);\n case \"boolean\":\n return value ? \"true\" : \"false\";\n case \"object\": {\n if (value === null) return \"null\";\n if (Array.isArray(value)) {\n return `[${value.map((item, i) => serialize(item, `${path}[${i}]`)).join(\",\")}]`;\n }\n const proto = Object.getPrototypeOf(value);\n if (proto !== Object.prototype && proto !== null) {\n refuse(path, `a ${proto?.constructor?.name ?? \"non-plain\"} object`);\n }\n const record = value as Record<string, unknown>;\n // Default string order compares UTF-16 code units, which is RFC 8785's order.\n const keys = Object.keys(record)\n .filter((k) => record[k] !== undefined)\n .sort();\n return `{${keys\n .map(\n (k) =>\n `${quote(k, `${path} key`)}:${serialize(record[k], `${path}.${k}`)}`,\n )\n .join(\",\")}}`;\n }\n default:\n return refuse(path, typeof value);\n }\n}\n\nfunction quote(text: string, path: string): string {\n // I-JSON strings are well-formed Unicode: a lone surrogate has no UTF-8 form.\n for (let i = 0; i < text.length; i++) {\n const unit = text.charCodeAt(i);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = text.charCodeAt(i + 1);\n if (next >= 0xdc00 && next <= 0xdfff) {\n i++;\n continue;\n }\n refuse(path, `a lone surrogate at ${i}`);\n }\n if (unit >= 0xdc00 && unit <= 0xdfff)\n refuse(path, `a lone surrogate at ${i}`);\n }\n return JSON.stringify(text);\n}\n","/**\n * The identity of a set of surfaces, for an answer that need not repeat them\n * (§7.3.4).\n *\n * A client's surfaces are what an agent may do; every result used to carry\n * them all, so each answer weighed what the page's whole manifest weighs —\n * on a studio page with a hundred and fifty actions, about 265 KB for a click.\n * A relay that caps a frame then drops whole answers, and the agent hears\n * nothing. With this hash the agent runtime says which surfaces it holds\n * (`knownSurfaces`), and the client sends its surfaces only when they differ.\n *\n * The hash is of the surfaces' canonical JSON (object keys sorted), so it does\n * not depend on the order a manifest's fields were written in, and is the\n * same wherever it is computed. It is a 64-bit FNV-1a over the JSON's UTF-16\n * code units, kept as two 32-bit halves: not a security measure — the agent\n * runtime is told the surfaces by the same client that hashes them — but\n * collision-resistant enough that two different capability sets of one page\n * never share one.\n */\nimport type { OUISurface, OUISurfaceIndex } from \"./types.js\";\n\n/** The prefix names the algorithm, so a different one is a different hash rather than a false match. */\nconst PREFIX = \"fnv1a64:\";\n\n/** `surfaces`' hash, as a result's `surfacesHash` and a request's `knownSurfaces` carry it. */\nexport function surfacesHash(\n surfaces: readonly OUISurface[] | readonly OUISurfaceIndex[],\n): string {\n return PREFIX + fnv1a64(sortedJson(surfaces));\n}\n\n/**\n * JSON with every object's keys sorted, and what JSON cannot carry dropped as\n * JSON.stringify drops it. Not approval.ts's `canonicalJson`, which refuses\n * such values on purpose (an approval must hash exactly what crosses the\n * wire): a snapshot is taken on every answer, and must never throw on a\n * manifest that carries, say, an `undefined` in an array.\n */\nexport function sortedJson(value: unknown): string {\n return JSON.stringify(sortKeys(value)) ?? \"null\";\n}\n\nfunction sortKeys(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortKeys);\n if (value && typeof value === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n const member = (value as Record<string, unknown>)[key];\n if (member !== undefined) out[key] = sortKeys(member);\n }\n return out;\n }\n return value;\n}\n\n/**\n * 64-bit FNV-1a (offset 0xcbf29ce484222325, prime 0x100000001b3) in two 32-bit\n * halves, so it runs without BigInt and stays fast on a few hundred KB.\n */\nexport function fnv1a64(text: string): string {\n // The 64-bit offset basis, as high and low 32-bit halves.\n let hi = 0xcbf29ce4;\n let lo = 0x84222325;\n for (let i = 0; i < text.length; i++) {\n lo = (lo ^ text.charCodeAt(i)) >>> 0;\n // Multiply (hi:lo) by the prime 0x00000100_000001b3, keeping 64 bits:\n // lo*0x1b3, and hi*0x1b3 + lo*0x100 carried into the high half.\n const loProduct = lo * 0x1b3;\n const carry = Math.floor(loProduct / 0x100000000);\n const newLo = loProduct >>> 0;\n hi = (Math.imul(hi, 0x1b3) + Math.imul(lo, 0x100) + carry) >>> 0;\n lo = newLo;\n }\n return hex32(hi) + hex32(lo);\n}\n\nfunction hex32(n: number): string {\n return (n >>> 0).toString(16).padStart(8, \"0\");\n}\n","/**\n * The index form of a surface (§7.3.8): each action as one entry that says what\n * it is and what it takes in outline, in place of its definition.\n *\n * Everything here is derived from the action's own definition, by rule, so two\n * clients with the same definition produce the same entry and the same hash.\n */\nimport { fnv1a64, sortedJson } from \"./surfaces-hash.js\";\nimport type {\n JSONSchema,\n OUIAction,\n OUIActionIndexEntry,\n OUISurface,\n OUISurfaceIndex,\n} from \"./types.js\";\n\n/** The longest description an index entry carries. */\nexport const INDEX_DESCRIPTION_CHARS = 160;\n/** The longest input line an index entry carries. */\nexport const INDEX_INPUT_CHARS = 120;\n/** How many of an input's properties its line names before \"+N more\". */\nexport const INDEX_INPUT_PROPERTIES = 6;\n/** How many of an enum's values a line shows before it says how many there are. */\nconst INDEX_ENUM_VALUES = 4;\n\n/** The surface id the runtime itself answers (§7.3.10). No surface may be defined with it. */\nexport const OUI_RUNTIME_SURFACE = \"oui\";\n/** `oui.describe`: the full definitions of the actions asked for. */\nexport const OUI_DESCRIBE_ACTION = \"describe\";\n/** `oui.read`: part of an observation's value, by path, a page of a list at a time. */\nexport const OUI_READ_ACTION = \"read\";\n\n/** The bytes `text` takes as UTF-8, which is what a frame's size limit counts. */\nexport function utf8Length(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (code < 0x80) bytes += 1;\n else if (code < 0x800) bytes += 2;\n else if (code >= 0xd800 && code <= 0xdbff) {\n // A surrogate pair is one code point of four bytes.\n bytes += 4;\n i++;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** The bytes `value` takes as JSON on the wire; 0 for what JSON drops. */\nexport function jsonBytes(value: unknown): number {\n const json = JSON.stringify(value);\n return json === undefined ? 0 : utf8Length(json);\n}\n\n/** `text` cut to `max` characters, ending in \"…\" when it was cut. */\nfunction clip(text: string, max: number): string {\n return text.length <= max ? text : `${text.slice(0, max - 1).trimEnd()}…`;\n}\n\n/** A description's first sentence, on one line, at most `INDEX_DESCRIPTION_CHARS` characters. */\nexport function firstSentence(text: string): string {\n const line = text.replace(/\\s+/g, \" \").trim();\n // A sentence ends at \". \", \"! \" or \"? \": a full stop inside \"0.5\" or \"e.g.\" followed by a letter is not one.\n const end = line.search(/[.!?](?= [A-Z0-9\"'([])/);\n return clip(\n end >= 0 ? line.slice(0, end + 1) : line,\n INDEX_DESCRIPTION_CHARS,\n );\n}\n\nfunction typeOf(schema: JSONSchema): string {\n const t = schema.type;\n return Array.isArray(t) ? t.join(\"|\") : (t ?? \"\");\n}\n\nfunction unitOf(schema: JSONSchema): string {\n const unit = schema[\"x-unit\"];\n return typeof unit === \"string\" && unit ? ` ${unit}` : \"\";\n}\n\n/** The members of a schema's union, when it is one. */\nfunction unionOf(schema: JSONSchema): JSONSchema[] | null {\n const members = schema.oneOf ?? schema.anyOf;\n return members && members.length > 0 ? members : null;\n}\n\n/**\n * The property every member of a union fixes to its own constant, which is\n * what tells the members apart: `effect` in `{ effect: \"glow\", … } | { effect:\n * \"blur\", … }`. Null when the members share no such property.\n */\nexport function discriminatorOf(members: readonly JSONSchema[]): string | null {\n const first = members[0]?.properties;\n if (!first) return null;\n for (const name of Object.keys(first)) {\n const constants = members.map((m) => constantOf(m.properties?.[name]));\n if (\n constants.every((c) => c !== undefined) &&\n new Set(constants).size === members.length\n )\n return name;\n }\n return null;\n}\n\n/** The one value a schema allows, when it allows one. */\nexport function constantOf(\n schema: JSONSchema | undefined,\n): string | number | boolean | undefined {\n if (!schema) return undefined;\n if (\n typeof schema.const === \"string\" ||\n typeof schema.const === \"number\" ||\n typeof schema.const === \"boolean\"\n ) {\n return schema.const;\n }\n return schema.enum?.length === 1 ? schema.enum[0] : undefined;\n}\n\n/** A value's type in a few words: \"number 0–100 px\", \"a|b|c|d|…(12)\", \"list of string\". */\nfunction valueSummary(schema: JSONSchema): string {\n const constant = constantOf(schema);\n if (constant !== undefined && !schema.enum) return JSON.stringify(constant);\n if (schema.enum) {\n const shown = schema.enum.slice(0, INDEX_ENUM_VALUES).map(String).join(\"|\");\n return schema.enum.length > INDEX_ENUM_VALUES\n ? `${shown}|…(${schema.enum.length})`\n : shown;\n }\n const union = unionOf(schema);\n if (union) return `one of ${union.length}`;\n const type = typeOf(schema);\n if (type === \"number\" || type === \"integer\") {\n const { minimum: min, maximum: max } = schema;\n const range =\n min !== undefined && max !== undefined\n ? ` ${min}–${max}`\n : min !== undefined\n ? ` ≥${min}`\n : max !== undefined\n ? ` ≤${max}`\n : \"\";\n return `${type}${range}${unitOf(schema)}`;\n }\n if (type === \"string\")\n return schema.format ? `string(${schema.format})` : \"string\";\n if (type === \"array\")\n return schema.items ? `list of ${valueSummary(schema.items)}` : \"list\";\n if (type === \"object\") {\n const n = Object.keys(schema.properties ?? {}).length;\n return n > 0 ? `object(${n})` : \"object\";\n }\n return type || \"any\";\n}\n\n/**\n * What an action takes, in one line of at most `INDEX_INPUT_CHARS` characters:\n * - \"none\" for an action that takes nothing;\n * - each property with its type, required ones first, optional ones marked\n * \"?\", the first `INDEX_INPUT_PROPERTIES` of them, then \"+N more\";\n * - \"one of N shapes by <property>\" for a union.\n */\nexport function summarizeInput(schema: JSONSchema | undefined): string {\n if (!schema) return \"none\";\n const union = unionOf(schema);\n if (union) {\n const by = discriminatorOf(union);\n return clip(\n `one of ${union.length} shapes${by ? ` by ${by}` : \"\"}`,\n INDEX_INPUT_CHARS,\n );\n }\n const properties = schema.properties ?? {};\n const names = Object.keys(properties);\n if (names.length === 0)\n return typeOf(schema) && typeOf(schema) !== \"object\"\n ? valueSummary(schema)\n : \"none\";\n const required = new Set(schema.required ?? []);\n const ordered = [\n ...names.filter((n) => required.has(n)),\n ...names.filter((n) => !required.has(n)),\n ];\n const shown = ordered.slice(0, INDEX_INPUT_PROPERTIES);\n const more = ordered.length - shown.length;\n const parts = shown.map(\n (n) => `${n}${required.has(n) ? \"\" : \"?\"}: ${valueSummary(properties[n])}`,\n );\n if (more > 0) parts.push(`+${more} more`);\n return clip(parts.join(\", \"), INDEX_INPUT_CHARS);\n}\n\n/** The longest lead-in before a quoted title that is still a lead-in (\"Turn on or off\", \"Choose the face of\"). */\nconst TITLE_LEAD_IN_CHARS = 32;\n\n/**\n * A description without the opening that only repeats the action's title.\n *\n * An entry carries the title beside the description, and descriptions are\n * commonly written to stand alone: `Add artboard: Adds an artboard…`, or, for\n * a control, `Press \"Save\": Saves the project`. In an index that names the\n * title twice for every action, and an index is hundreds of actions. So an\n * opening of the title followed by \": \", or of a short lead-in, the title in\n * double quotes and \": \", is left out: what the entry keeps is what the title\n * does not already say. A description that does not open that way is kept as\n * it is, and one that is only its title is kept too.\n */\nexport function withoutTitleLeadIn(\n description: string,\n title: string | undefined,\n): string {\n const line = description.replace(/\\s+/g, \" \").trim();\n if (!title) return line;\n const name = title.replace(/\\s+/g, \" \").trim();\n if (!name) return line;\n let rest: string | undefined;\n if (line.startsWith(`${name}: `)) rest = line.slice(name.length + 2);\n else {\n const quoted = `\"${name}\": `;\n const at = line.indexOf(quoted);\n // A lead-in is a few words with no sentence in them: \"Press\", \"Type into\", \"Turn on or off\".\n if (\n at >= 0 &&\n at <= TITLE_LEAD_IN_CHARS &&\n !/[.:!?\"]/.test(line.slice(0, at))\n )\n rest = line.slice(at + quoted.length);\n }\n const kept = rest?.trim();\n return kept ? kept : line;\n}\n\n/** The hex digits an entry's `definitionHash` has: 32 bits. */\nexport const DEFINITION_HASH_HEX = 8;\n\n/**\n * The hash of an action's definition, as an index entry's `definitionHash`\n * carries it: the first 32 bits of the 64-bit FNV-1a of its sorted-key JSON.\n *\n * It answers one question, for one action: has this action's definition\n * changed since it was fetched? It is only ever compared with the same\n * action's earlier hash, so 32 bits are enough (a change goes unseen once in\n * 2^32, and costs one stale definition until the next change), and an index of\n * hundreds of actions carries half the digits. The hash of a whole page\n * (`surfacesHash`) is compared across everything on it, and stays 64 bits.\n */\nexport function definitionHash(action: OUIAction): string {\n return fnv1a64(sortedJson(action)).slice(0, DEFINITION_HASH_HEX);\n}\n\n/** An action's index entry (§7.3.8). */\nexport function indexEntry(action: OUIAction): OUIActionIndexEntry {\n return {\n id: action.id,\n ...(action.title ? { title: action.title } : {}),\n description: firstSentence(\n withoutTitleLeadIn(action.description, action.title),\n ),\n ...(action.effect !== undefined ? { effect: action.effect } : {}),\n ...(action.confirm ? { confirm: true } : {}),\n ...(action.async ? { async: true } : {}),\n ...(action.estimatedDuration\n ? { estimatedDuration: action.estimatedDuration }\n : {}),\n ...(action.polling?.maxDurationMs !== undefined\n ? { maxDurationMs: action.polling.maxDurationMs }\n : {}),\n input: summarizeInput(action.input),\n definitionHash: definitionHash(action),\n };\n}\n\n/** A surface in index form (§7.3.8). */\nexport function surfaceIndex(surface: OUISurface): OUISurfaceIndex {\n return {\n id: surface.id,\n name: surface.name,\n description: surface.description,\n ...(surface.version !== undefined ? { version: surface.version } : {}),\n ...(surface.observations ? { observations: surface.observations } : {}),\n index: surface.actions.map(indexEntry),\n };\n}\n","/**\n * Fitting what a client sends to a byte budget (§7.3.9).\n *\n * A frame larger than its receiver accepts is refused whole, and the agent\n * then knows nothing of the page. So the client shortens what it sends before\n * it sends it: the longest lists first, then long texts, then whole values,\n * and it says where it cut, so the rest can be read (`oui.read`, §7.3.10).\n *\n * The cuts are made by rule, in a fixed order, so the same state under the\n * same budget is always shortened the same way.\n */\nimport { jsonBytes } from \"./index-form.js\";\nimport type { OUIFitCut, OUIObservationSnapshot } from \"./types.js\";\n\n/** Rows a list keeps at each step of fitting, until the whole fits. */\nexport const FIT_LIST_STEPS = [200, 50, 20, 5, 0] as const;\n/** Characters a text keeps once lists alone did not make the whole fit. */\nexport const FIT_TEXT_CHARS = 2_000;\n\n/** One step into a JSON Pointer (RFC 6901). */\nexport function pointerStep(pointer: string, key: string | number): string {\n return `${pointer}/${String(key).replace(/~/g, \"~0\").replace(/\\//g, \"~1\")}`;\n}\n\n/** The steps of a JSON Pointer; \"\" is no steps. Throws on a pointer that does not start with \"/\". */\nexport function pointerSteps(pointer: string): string[] {\n if (pointer === \"\") return [];\n if (!pointer.startsWith(\"/\"))\n throw new Error(\n `\"${pointer}\" is not a JSON Pointer: it must be \"\" or start with \"/\"`,\n );\n return pointer\n .slice(1)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n}\n\n/** The value a pointer names inside `value`, or `undefined` when nothing is there. */\nexport function atPointer(value: unknown, pointer: string): unknown {\n let at: unknown = value;\n for (const step of pointerSteps(pointer)) {\n if (Array.isArray(at)) {\n at = /^(0|[1-9]\\d*)$/.test(step) ? at[Number(step)] : undefined;\n } else if (at && typeof at === \"object\") {\n at = Object.prototype.hasOwnProperty.call(at, step)\n ? (at as Record<string, unknown>)[step]\n : undefined;\n } else return undefined;\n if (at === undefined) return undefined;\n }\n return at;\n}\n\ninterface Slot {\n /** The object or array holding the value. */\n holder: Record<string, unknown> | unknown[];\n key: string | number;\n surface: string;\n observation: string;\n path: string;\n}\n\n/** Every array and string inside the observations, each with where it sits. */\nfunction slots(\n observations: OUIObservationSnapshot,\n want: \"list\" | \"text\",\n): Slot[] {\n const found: Slot[] = [];\n const walk = (\n holder: Slot[\"holder\"],\n key: string | number,\n surface: string,\n observation: string,\n path: string,\n ) => {\n const value = (holder as Record<string | number, unknown>)[key];\n if (Array.isArray(value)) {\n if (want === \"list\")\n found.push({ holder, key, surface, observation, path });\n value.forEach((_, i) =>\n walk(value, i, surface, observation, pointerStep(path, i)),\n );\n } else if (value && typeof value === \"object\") {\n for (const k of Object.keys(value))\n walk(\n value as Record<string, unknown>,\n k,\n surface,\n observation,\n pointerStep(path, k),\n );\n } else if (typeof value === \"string\" && want === \"text\") {\n found.push({ holder, key, surface, observation, path });\n }\n };\n for (const surface of Object.keys(observations)) {\n for (const observation of Object.keys(observations[surface])) {\n walk(observations[surface], observation, surface, observation, \"\");\n }\n }\n return found;\n}\n\n/**\n * `observations` within `budget` bytes of JSON, and where they were cut.\n * Returned as they are when they already fit; otherwise a copy is shortened:\n * 1. every list longer than a step of `FIT_LIST_STEPS` is cut to it, a step at\n * a time, until the whole fits;\n * 2. then every text longer than `FIT_TEXT_CHARS` is cut to that;\n * 3. then whole observation values are left out, the largest first.\n */\nexport function fitObservations(\n observations: OUIObservationSnapshot,\n budget: number,\n): { observations: OUIObservationSnapshot; cuts: OUIFitCut[] } {\n if (jsonBytes(observations) <= budget) return { observations, cuts: [] };\n\n const fitted = JSON.parse(\n JSON.stringify(observations),\n ) as OUIObservationSnapshot;\n // One cut per place: a list cut twice is reported once, with its first length.\n const cuts = new Map<string, OUIFitCut>();\n const note = (\n slot: Slot,\n kind: OUIFitCut[\"kind\"],\n total: number,\n kept: number,\n ) => {\n const id = `${slot.surface}\\u0000${slot.observation}\\u0000${slot.path}`;\n const prior = cuts.get(id);\n cuts.set(id, {\n surface: slot.surface,\n observation: slot.observation,\n path: slot.path,\n kind,\n total: prior ? prior.total : total,\n kept,\n });\n };\n const fits = () => jsonBytes(fitted) <= budget;\n\n for (const rows of FIT_LIST_STEPS) {\n for (const slot of slots(fitted, \"list\")) {\n const list = (slot.holder as Record<string | number, unknown>)[\n slot.key\n ] as unknown[];\n if (list.length <= rows) continue;\n note(slot, \"list\", list.length, rows);\n list.length = rows;\n }\n // A cut inside a row that an outer list then dropped is no longer there to read.\n for (const [id, cut] of cuts) {\n if (\n cut.kind === \"list\" &&\n atPointer(fitted[cut.surface]?.[cut.observation], cut.path) ===\n undefined\n )\n cuts.delete(id);\n }\n if (fits()) return { observations: fitted, cuts: [...cuts.values()] };\n }\n\n for (const slot of slots(fitted, \"text\")) {\n const text = (slot.holder as Record<string | number, unknown>)[\n slot.key\n ] as string;\n if (text.length <= FIT_TEXT_CHARS) continue;\n note(slot, \"text\", text.length, FIT_TEXT_CHARS);\n (slot.holder as Record<string | number, unknown>)[slot.key] = text.slice(\n 0,\n FIT_TEXT_CHARS,\n );\n }\n if (fits()) return { observations: fitted, cuts: [...cuts.values()] };\n\n const values = Object.keys(fitted)\n .flatMap((surface) =>\n Object.keys(fitted[surface]).map((observation) => ({\n surface,\n observation,\n bytes: jsonBytes(fitted[surface][observation]),\n })),\n )\n .sort(\n (a, b) =>\n b.bytes - a.bytes ||\n a.surface.localeCompare(b.surface) ||\n a.observation.localeCompare(b.observation),\n );\n for (const { surface, observation, bytes } of values) {\n if (fits()) break;\n for (const [id, cut] of cuts) {\n if (cut.surface === surface && cut.observation === observation)\n cuts.delete(id);\n }\n fitted[surface][observation] = null;\n cuts.set(`${surface}\\u0000${observation}\\u0000`, {\n surface,\n observation,\n path: \"\",\n kind: \"value\",\n total: bytes,\n kept: 0,\n });\n }\n return { observations: fitted, cuts: [...cuts.values()] };\n}\n"]}