oui-spec 0.4.1 → 0.6.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 (48) hide show
  1. package/README.md +41 -8
  2. package/dist/{chunk-DCVVTP3V.cjs → chunk-5UUJ3F7C.cjs} +53 -16
  3. package/dist/chunk-5UUJ3F7C.cjs.map +1 -0
  4. package/dist/{chunk-GDB56ZQZ.cjs → chunk-AFNWLRKV.cjs} +126 -15
  5. package/dist/chunk-AFNWLRKV.cjs.map +1 -0
  6. package/dist/chunk-B2EFZMGY.js +159 -0
  7. package/dist/chunk-B2EFZMGY.js.map +1 -0
  8. package/dist/chunk-LDECTDPU.cjs +169 -0
  9. package/dist/chunk-LDECTDPU.cjs.map +1 -0
  10. package/dist/{chunk-F3WKIRAU.js → chunk-R3SGP2UY.js} +53 -16
  11. package/dist/chunk-R3SGP2UY.js.map +1 -0
  12. package/dist/{chunk-UQLG55ST.js → chunk-VQETSIY5.js} +124 -13
  13. package/dist/chunk-VQETSIY5.js.map +1 -0
  14. package/dist/core/index.cjs +7 -7
  15. package/dist/core/index.d.cts +5 -5
  16. package/dist/core/index.d.ts +5 -5
  17. package/dist/core/index.js +3 -3
  18. package/dist/index.cjs +40 -8
  19. package/dist/index.d.cts +4 -3
  20. package/dist/index.d.ts +4 -3
  21. package/dist/index.js +3 -3
  22. package/dist/react/index.d.cts +3 -3
  23. package/dist/react/index.d.ts +3 -3
  24. package/dist/spec/index.cjs +34 -2
  25. package/dist/spec/index.d.cts +22 -272
  26. package/dist/spec/index.d.ts +22 -272
  27. package/dist/spec/index.js +1 -1
  28. package/dist/{surface-runtime-BzIKgL_I.d.cts → surface-runtime-CSZ9UtBO.d.cts} +23 -2
  29. package/dist/{surface-runtime-DeByfbKg.d.ts → surface-runtime-D5nINY4b.d.ts} +23 -2
  30. package/dist/transport/index.cjs +2 -2
  31. package/dist/transport/index.d.cts +3 -3
  32. package/dist/transport/index.d.ts +3 -3
  33. package/dist/transport/index.js +1 -1
  34. package/dist/types-CmJb1BQ8.d.cts +403 -0
  35. package/dist/types-CmJb1BQ8.d.ts +403 -0
  36. package/dist/{websocket-YfWILdZ4.d.cts → websocket-Ce3tDSsJ.d.ts} +26 -7
  37. package/dist/{websocket-c5tIUWY5.d.ts → websocket-Ds2Rh_jL.d.cts} +26 -7
  38. package/package.json +4 -3
  39. package/spec/OUI-SPEC-v0.1.md +63 -7
  40. package/spec/approval-vectors.json +88 -0
  41. package/dist/chunk-BMCL2K74.js +0 -12
  42. package/dist/chunk-BMCL2K74.js.map +0 -1
  43. package/dist/chunk-DCVVTP3V.cjs.map +0 -1
  44. package/dist/chunk-F3WKIRAU.js.map +0 -1
  45. package/dist/chunk-GDB56ZQZ.cjs.map +0 -1
  46. package/dist/chunk-UQLG55ST.js.map +0 -1
  47. package/dist/chunk-ZKM4XWAB.cjs +0 -14
  48. package/dist/chunk-ZKM4XWAB.cjs.map +0 -1
@@ -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":["createWebSocketTransport","argsHash","requiresApproval","surfacesHash","ARGS_HASH_PATTERN"],"mappings":";;;;;;AA2BO,SAAS,MACd,KAAA,EACuB;AACvB,EAAA,OAAO,KAAA;AACT;;;ACoGO,SAAS,cAId,UAAA,EACwC;AAExC,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;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AAA,IAAS,OAAA,EAAS,OAAO,GAAA,CAAI,KAAK,CAAA;AAC7C,EAAA,GAAA,CAAI,QAAA,GAAW,EAAE,OAAA,EAAS,IAAA,EAAM,QAAQ,OAAA,EAAS,CAAC,GAAG,OAAO,CAAA,EAAE;AAC9D,EAAA,OAAO,GAAA;AACT;AAEA,SAAS,MAAM,EAAA,EAA2B;AACxC,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,YAAY,UAAA,CAAW,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-AFNWLRKV.cjs","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 { 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 // 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 OUIActionRequest,\n OUIActionResult,\n OUIApprovalGrant,\n OUIResultDelivery,\n OUISurface,\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 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 * 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\nexport interface SurfaceRuntime {\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(): 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;\n\nexport function createSurfaceRuntime(\n options: SurfaceRuntimeOptions = {},\n): SurfaceRuntime {\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\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 const snap = snapshot();\n const known = answeredHash.get(requestId);\n answer({\n requestId,\n success,\n ...(data !== undefined ? { data: toJsonSafe(data) } : {}),\n ...(error ? { error } : {}),\n interim: false,\n timestamp: Date.now(),\n ...(snap.surfacesHash !== known ? { surfaces: snap.surfaces } : {}),\n observations: snap.observations,\n surfacesHash: snap.surfacesHash,\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 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 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 const settled = await waitUntilSettled(startedAt);\n const snap = snapshot();\n if (interim) answeredHash.set(request.requestId, snap.surfacesHash!);\n\n return {\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 // Only what the agent runtime does not already hold (§7.3.4).\n ...(snap.surfacesHash !== request.knownSurfaces\n ? { surfaces: snap.surfaces }\n : {}),\n observations: snap.observations,\n surfacesHash: snap.surfacesHash,\n settled,\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 the page's surfaces and\n * observations, then without the action's data too. 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 steps: Array<OUIResultDelivery[\"omitted\"]> = [\n [\"surfaces\", \"observations\"],\n [\"surfaces\", \"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 function snapshot(): OUISurfaceSnapshot {\n const surfaces: OUISurface[] = [];\n const obs: OUIObservationSnapshot = {};\n for (const e of activeEntries()) {\n surfaces.push(e.surface.toManifest());\n const values = observations.get(e.surface.id);\n if (values && values.size > 0)\n obs[e.surface.id] = Object.fromEntries(values);\n }\n return {\n surfaces,\n observations: obs,\n surfacesHash: surfacesHash(surfaces),\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,\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"]}
@@ -0,0 +1,159 @@
1
+ // src/spec/types.ts
2
+ var OUI_PROTOCOL_EVENTS = {
3
+ SURFACE_REGISTER: "surface:register",
4
+ SURFACE_DEREGISTER: "surface:deregister",
5
+ ACTION_REQUEST: "action:request",
6
+ ACTION_RESULT: "action:result",
7
+ OBSERVATION_UPDATE: "observation:update"
8
+ };
9
+
10
+ // src/spec/approval.ts
11
+ var OUI_EFFECT_KINDS = [
12
+ "view",
13
+ "selection",
14
+ "navigate",
15
+ "open",
16
+ "edit",
17
+ "file",
18
+ "mutate",
19
+ "job",
20
+ "transaction"
21
+ ];
22
+ var OUI_EFFECT_ACCESS = {
23
+ view: "read",
24
+ selection: "read",
25
+ navigate: "read",
26
+ open: "read",
27
+ edit: "write",
28
+ file: "write",
29
+ mutate: "write",
30
+ job: "write",
31
+ transaction: "write"
32
+ };
33
+ function effectAccess(effect) {
34
+ return effect === void 0 ? "write" : OUI_EFFECT_ACCESS[effect];
35
+ }
36
+ function requiresApproval(effect, destructive) {
37
+ if (effect === "transaction") return true;
38
+ return !!destructive && effectAccess(effect) === "write";
39
+ }
40
+ var ARGS_HASH_PATTERN = /^[0-9a-f]{64}$/;
41
+ function canonicalJson(value) {
42
+ return serialize(value, "$");
43
+ }
44
+ async function argsHash(params) {
45
+ const canonical = canonicalJson(params);
46
+ const subtle = await webCrypto();
47
+ const digest = await subtle.digest(
48
+ "SHA-256",
49
+ new TextEncoder().encode(canonical)
50
+ );
51
+ let hex = "";
52
+ for (const byte of new Uint8Array(digest))
53
+ hex += byte.toString(16).padStart(2, "0");
54
+ return hex;
55
+ }
56
+ async function webCrypto() {
57
+ const global = globalThis.crypto?.subtle;
58
+ if (global) return global;
59
+ const nodeCrypto = "node:crypto";
60
+ try {
61
+ const mod = await import(
62
+ /* @vite-ignore */
63
+ nodeCrypto
64
+ );
65
+ if (mod.webcrypto?.subtle) return mod.webcrypto.subtle;
66
+ } catch {
67
+ }
68
+ throw new Error(
69
+ "[OUI] argsHash needs WebCrypto (crypto.subtle), which this runtime does not provide"
70
+ );
71
+ }
72
+ function refuse(path, what) {
73
+ throw new TypeError(`[OUI] ${path} is not I-JSON: ${what}`);
74
+ }
75
+ function serialize(value, path) {
76
+ switch (typeof value) {
77
+ case "string":
78
+ return quote(value, path);
79
+ case "number":
80
+ if (!Number.isFinite(value)) refuse(path, String(value));
81
+ return JSON.stringify(value);
82
+ case "boolean":
83
+ return value ? "true" : "false";
84
+ case "object": {
85
+ if (value === null) return "null";
86
+ if (Array.isArray(value)) {
87
+ return `[${value.map((item, i) => serialize(item, `${path}[${i}]`)).join(",")}]`;
88
+ }
89
+ const proto = Object.getPrototypeOf(value);
90
+ if (proto !== Object.prototype && proto !== null) {
91
+ refuse(path, `a ${proto?.constructor?.name ?? "non-plain"} object`);
92
+ }
93
+ const record = value;
94
+ const keys = Object.keys(record).filter((k) => record[k] !== void 0).sort();
95
+ return `{${keys.map(
96
+ (k) => `${quote(k, `${path} key`)}:${serialize(record[k], `${path}.${k}`)}`
97
+ ).join(",")}}`;
98
+ }
99
+ default:
100
+ return refuse(path, typeof value);
101
+ }
102
+ }
103
+ function quote(text, path) {
104
+ for (let i = 0; i < text.length; i++) {
105
+ const unit = text.charCodeAt(i);
106
+ if (unit >= 55296 && unit <= 56319) {
107
+ const next = text.charCodeAt(i + 1);
108
+ if (next >= 56320 && next <= 57343) {
109
+ i++;
110
+ continue;
111
+ }
112
+ refuse(path, `a lone surrogate at ${i}`);
113
+ }
114
+ if (unit >= 56320 && unit <= 57343)
115
+ refuse(path, `a lone surrogate at ${i}`);
116
+ }
117
+ return JSON.stringify(text);
118
+ }
119
+
120
+ // src/spec/surfaces-hash.ts
121
+ var PREFIX = "fnv1a64:";
122
+ function surfacesHash(surfaces) {
123
+ return PREFIX + fnv1a64(sortedJson(surfaces));
124
+ }
125
+ function sortedJson(value) {
126
+ return JSON.stringify(sortKeys(value)) ?? "null";
127
+ }
128
+ function sortKeys(value) {
129
+ if (Array.isArray(value)) return value.map(sortKeys);
130
+ if (value && typeof value === "object") {
131
+ const out = {};
132
+ for (const key of Object.keys(value).sort()) {
133
+ const member = value[key];
134
+ if (member !== void 0) out[key] = sortKeys(member);
135
+ }
136
+ return out;
137
+ }
138
+ return value;
139
+ }
140
+ function fnv1a64(text) {
141
+ let hi = 3421674724;
142
+ let lo = 2216829733;
143
+ for (let i = 0; i < text.length; i++) {
144
+ lo = (lo ^ text.charCodeAt(i)) >>> 0;
145
+ const loProduct = lo * 435;
146
+ const carry = Math.floor(loProduct / 4294967296);
147
+ const newLo = loProduct >>> 0;
148
+ hi = Math.imul(hi, 435) + Math.imul(lo, 256) + carry >>> 0;
149
+ lo = newLo;
150
+ }
151
+ return hex32(hi) + hex32(lo);
152
+ }
153
+ function hex32(n) {
154
+ return (n >>> 0).toString(16).padStart(8, "0");
155
+ }
156
+
157
+ export { ARGS_HASH_PATTERN, OUI_EFFECT_ACCESS, OUI_EFFECT_KINDS, OUI_PROTOCOL_EVENTS, argsHash, canonicalJson, effectAccess, requiresApproval, surfacesHash };
158
+ //# sourceMappingURL=chunk-B2EFZMGY.js.map
159
+ //# sourceMappingURL=chunk-B2EFZMGY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/spec/types.ts","../src/spec/approval.ts","../src/spec/surfaces-hash.ts"],"names":[],"mappings":";AAiYO,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;;;AC9VO,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,KAAA;AAAA,EACA;AACF;AAGO,IAAM,iBAAA,GAET;AAAA,EACF,IAAA,EAAM,MAAA;AAAA,EACN,SAAA,EAAW,MAAA;AAAA,EACX,QAAA,EAAU,MAAA;AAAA,EACV,IAAA,EAAM,MAAA;AAAA,EACN,IAAA,EAAM,OAAA;AAAA,EACN,IAAA,EAAM,OAAA;AAAA,EACN,MAAA,EAAQ,OAAA;AAAA,EACR,GAAA,EAAK,OAAA;AAAA,EACL,WAAA,EAAa;AACf;AAGO,SAAS,aACd,MAAA,EACkB;AAClB,EAAA,OAAO,MAAA,KAAW,MAAA,GAAY,OAAA,GAAU,iBAAA,CAAkB,MAAM,CAAA;AAClE;AAOO,SAAS,gBAAA,CACd,QACA,WAAA,EACS;AACT,EAAA,IAAI,MAAA,KAAW,eAAe,OAAO,IAAA;AACrC,EAAA,OAAO,CAAC,CAAC,WAAA,IAAe,YAAA,CAAa,MAAM,CAAA,KAAM,OAAA;AACnD;AAgBO,IAAM,iBAAA,GAAoB;AAe1B,SAAS,cAAc,KAAA,EAAwB;AACpD,EAAA,OAAO,SAAA,CAAU,OAAO,GAAG,CAAA;AAC7B;AAGA,eAAsB,SAAS,MAAA,EAAkC;AAC/D,EA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AAmB;AAChC,EAAA,OAAA,CAAQ,MAAM,CAAA,EAAG,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAA;AAC/C","file":"chunk-B2EFZMGY.js","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};\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// ─── 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\" | \"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 /** Latest observation values per surface once the action's effects settled. */\n observations?: OUIObservationSnapshot;\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 */\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}\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 } 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(surfaces: readonly OUISurface[]): 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 */\nfunction 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"]}
@@ -0,0 +1,169 @@
1
+ 'use strict';
2
+
3
+ // src/spec/types.ts
4
+ var OUI_PROTOCOL_EVENTS = {
5
+ SURFACE_REGISTER: "surface:register",
6
+ SURFACE_DEREGISTER: "surface:deregister",
7
+ ACTION_REQUEST: "action:request",
8
+ ACTION_RESULT: "action:result",
9
+ OBSERVATION_UPDATE: "observation:update"
10
+ };
11
+
12
+ // src/spec/approval.ts
13
+ var OUI_EFFECT_KINDS = [
14
+ "view",
15
+ "selection",
16
+ "navigate",
17
+ "open",
18
+ "edit",
19
+ "file",
20
+ "mutate",
21
+ "job",
22
+ "transaction"
23
+ ];
24
+ var OUI_EFFECT_ACCESS = {
25
+ view: "read",
26
+ selection: "read",
27
+ navigate: "read",
28
+ open: "read",
29
+ edit: "write",
30
+ file: "write",
31
+ mutate: "write",
32
+ job: "write",
33
+ transaction: "write"
34
+ };
35
+ function effectAccess(effect) {
36
+ return effect === void 0 ? "write" : OUI_EFFECT_ACCESS[effect];
37
+ }
38
+ function requiresApproval(effect, destructive) {
39
+ if (effect === "transaction") return true;
40
+ return !!destructive && effectAccess(effect) === "write";
41
+ }
42
+ var ARGS_HASH_PATTERN = /^[0-9a-f]{64}$/;
43
+ function canonicalJson(value) {
44
+ return serialize(value, "$");
45
+ }
46
+ async function argsHash(params) {
47
+ const canonical = canonicalJson(params);
48
+ const subtle = await webCrypto();
49
+ const digest = await subtle.digest(
50
+ "SHA-256",
51
+ new TextEncoder().encode(canonical)
52
+ );
53
+ let hex = "";
54
+ for (const byte of new Uint8Array(digest))
55
+ hex += byte.toString(16).padStart(2, "0");
56
+ return hex;
57
+ }
58
+ async function webCrypto() {
59
+ const global = globalThis.crypto?.subtle;
60
+ if (global) return global;
61
+ const nodeCrypto = "node:crypto";
62
+ try {
63
+ const mod = await import(
64
+ /* @vite-ignore */
65
+ nodeCrypto
66
+ );
67
+ if (mod.webcrypto?.subtle) return mod.webcrypto.subtle;
68
+ } catch {
69
+ }
70
+ throw new Error(
71
+ "[OUI] argsHash needs WebCrypto (crypto.subtle), which this runtime does not provide"
72
+ );
73
+ }
74
+ function refuse(path, what) {
75
+ throw new TypeError(`[OUI] ${path} is not I-JSON: ${what}`);
76
+ }
77
+ function serialize(value, path) {
78
+ switch (typeof value) {
79
+ case "string":
80
+ return quote(value, path);
81
+ case "number":
82
+ if (!Number.isFinite(value)) refuse(path, String(value));
83
+ return JSON.stringify(value);
84
+ case "boolean":
85
+ return value ? "true" : "false";
86
+ case "object": {
87
+ if (value === null) return "null";
88
+ if (Array.isArray(value)) {
89
+ return `[${value.map((item, i) => serialize(item, `${path}[${i}]`)).join(",")}]`;
90
+ }
91
+ const proto = Object.getPrototypeOf(value);
92
+ if (proto !== Object.prototype && proto !== null) {
93
+ refuse(path, `a ${proto?.constructor?.name ?? "non-plain"} object`);
94
+ }
95
+ const record = value;
96
+ const keys = Object.keys(record).filter((k) => record[k] !== void 0).sort();
97
+ return `{${keys.map(
98
+ (k) => `${quote(k, `${path} key`)}:${serialize(record[k], `${path}.${k}`)}`
99
+ ).join(",")}}`;
100
+ }
101
+ default:
102
+ return refuse(path, typeof value);
103
+ }
104
+ }
105
+ function quote(text, path) {
106
+ for (let i = 0; i < text.length; i++) {
107
+ const unit = text.charCodeAt(i);
108
+ if (unit >= 55296 && unit <= 56319) {
109
+ const next = text.charCodeAt(i + 1);
110
+ if (next >= 56320 && next <= 57343) {
111
+ i++;
112
+ continue;
113
+ }
114
+ refuse(path, `a lone surrogate at ${i}`);
115
+ }
116
+ if (unit >= 56320 && unit <= 57343)
117
+ refuse(path, `a lone surrogate at ${i}`);
118
+ }
119
+ return JSON.stringify(text);
120
+ }
121
+
122
+ // src/spec/surfaces-hash.ts
123
+ var PREFIX = "fnv1a64:";
124
+ function surfacesHash(surfaces) {
125
+ return PREFIX + fnv1a64(sortedJson(surfaces));
126
+ }
127
+ function sortedJson(value) {
128
+ return JSON.stringify(sortKeys(value)) ?? "null";
129
+ }
130
+ function sortKeys(value) {
131
+ if (Array.isArray(value)) return value.map(sortKeys);
132
+ if (value && typeof value === "object") {
133
+ const out = {};
134
+ for (const key of Object.keys(value).sort()) {
135
+ const member = value[key];
136
+ if (member !== void 0) out[key] = sortKeys(member);
137
+ }
138
+ return out;
139
+ }
140
+ return value;
141
+ }
142
+ function fnv1a64(text) {
143
+ let hi = 3421674724;
144
+ let lo = 2216829733;
145
+ for (let i = 0; i < text.length; i++) {
146
+ lo = (lo ^ text.charCodeAt(i)) >>> 0;
147
+ const loProduct = lo * 435;
148
+ const carry = Math.floor(loProduct / 4294967296);
149
+ const newLo = loProduct >>> 0;
150
+ hi = Math.imul(hi, 435) + Math.imul(lo, 256) + carry >>> 0;
151
+ lo = newLo;
152
+ }
153
+ return hex32(hi) + hex32(lo);
154
+ }
155
+ function hex32(n) {
156
+ return (n >>> 0).toString(16).padStart(8, "0");
157
+ }
158
+
159
+ exports.ARGS_HASH_PATTERN = ARGS_HASH_PATTERN;
160
+ exports.OUI_EFFECT_ACCESS = OUI_EFFECT_ACCESS;
161
+ exports.OUI_EFFECT_KINDS = OUI_EFFECT_KINDS;
162
+ exports.OUI_PROTOCOL_EVENTS = OUI_PROTOCOL_EVENTS;
163
+ exports.argsHash = argsHash;
164
+ exports.canonicalJson = canonicalJson;
165
+ exports.effectAccess = effectAccess;
166
+ exports.requiresApproval = requiresApproval;
167
+ exports.surfacesHash = surfacesHash;
168
+ //# sourceMappingURL=chunk-LDECTDPU.cjs.map
169
+ //# sourceMappingURL=chunk-LDECTDPU.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/spec/types.ts","../src/spec/approval.ts","../src/spec/surfaces-hash.ts"],"names":[],"mappings":";;;AAiYO,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;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AG,CAAA;AACrD,MAAA,IAAI,WAAW,MAAA,EAAW,GAAA,CAAI,GAAG,CAAA,GAAI,SAAS,MAAM,CAAA;AAAA,IACtD;AACA,IAAA,OAAO,GAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT;AAMO,SAAS,QAAQ,IAAA,EAAsB;AAE5C,EAAA,IAAI,EAAA,GAAK,UAAA;AACT,EAAA,IAAI,EAAA,GAAK,UAAA;AACT,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,QAAQ,CAAA,EAAA,EAAK;AACpC,IAAA,EAAA,GAAA,CAAM,EAAA,GAAK,IAAA,CAAK,UAAA,CAAW,CAAC,CAAA,MAAO,CAAA;AAGnC,IAAA,MAAM,YAAY,EAAA,GAAK,GAAA;AACvB,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,SAAA,GAAY,UAAW,CAAA;AAChD,IAAA,MAAM,QAAQ,SAAA,KAAc,CAAA;AAC5B,IAAA,EAAA,GAAM,IAAA,CAAK,IAAA,CAAK,EAAA,EAAI,GAAK,CAAA,GAAI,KAAK,IAAA,CAAK,EAAA,EAAI,GAAK,CAAA,GAAI,KAAA,KAAW,CAAA;AAC/D,IAAA,EAAA,GAAK,KAAA;AAAA,EACP;AACA,EAAA,OAAO,KAAA,CAAM,EAAE,CAAA,GAAI,KAAA,CAAM,EAAE,CAAA;AAC7B;AAEA,SAAS,MAAM,CAAA,EAAmB;AAChC,EAAA,OAAA,CAAQ,MAAM,CAAA,EAAG,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAA;AAC/C","file":"chunk-LDECTDPU.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};\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// ─── 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\" | \"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 /** Latest observation values per surface once the action's effects settled. */\n observations?: OUIObservationSnapshot;\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 */\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}\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 } 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(surfaces: readonly OUISurface[]): 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 */\nfunction 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"]}