experimental-a2 0.10.0 → 0.12.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 (121) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/actor-DJi3RsNu.d.ts +310 -0
  3. package/dist/actor-DJi3RsNu.d.ts.map +1 -0
  4. package/dist/actor-client.d.ts +13 -4
  5. package/dist/actor-client.d.ts.map +1 -1
  6. package/dist/actor-client.js +63 -7
  7. package/dist/actor-client.js.map +1 -1
  8. package/dist/actor-react.d.ts +5 -4
  9. package/dist/actor-react.d.ts.map +1 -1
  10. package/dist/actor-react.js +16 -2
  11. package/dist/actor-react.js.map +1 -1
  12. package/dist/actor.d.ts +2 -176
  13. package/dist/actor.js +13 -2
  14. package/dist/actor.js.map +1 -1
  15. package/dist/ai-server.d.ts +1 -1
  16. package/dist/ai-server.js +2 -2
  17. package/dist/ai.d.ts +1 -1
  18. package/dist/ai.js +1 -1
  19. package/dist/client-Bf6uSEAk.js +1342 -0
  20. package/dist/client-Bf6uSEAk.js.map +1 -0
  21. package/dist/client-P_NNNRM-.d.ts +243 -0
  22. package/dist/client-P_NNNRM-.d.ts.map +1 -0
  23. package/dist/client.d.ts +2 -208
  24. package/dist/client.js +2 -1206
  25. package/dist/errors-DCk6ch5n.js.map +1 -1
  26. package/dist/errors-DvhSXnxk.d.ts +28 -0
  27. package/dist/errors-DvhSXnxk.d.ts.map +1 -0
  28. package/dist/index.d.ts +3 -35
  29. package/dist/{internal-DRXJ56EI.js → internal-Dq2qYxou.js} +2 -2
  30. package/dist/{internal-DRXJ56EI.js.map → internal-Dq2qYxou.js.map} +1 -1
  31. package/dist/platform-B4TnJtWu.js +34 -0
  32. package/dist/platform-B4TnJtWu.js.map +1 -0
  33. package/dist/react.d.ts +3 -1
  34. package/dist/react.d.ts.map +1 -1
  35. package/dist/react.js +2 -1
  36. package/dist/react.js.map +1 -1
  37. package/dist/scheduler-qstash.d.ts +2 -2
  38. package/dist/scheduler-qstash.js +3 -2
  39. package/dist/scheduler-qstash.js.map +1 -1
  40. package/dist/scheduler-vercel.d.ts +2 -2
  41. package/dist/scheduler-vercel.js +2 -2
  42. package/dist/{server-DlLyvaSH.js → server-BeNADlCI.js} +171 -65
  43. package/dist/server-BeNADlCI.js.map +1 -0
  44. package/dist/{server-DgCrSuhB.d.ts → server-DjZZa1wr.d.ts} +9 -3
  45. package/dist/{server-DgCrSuhB.d.ts.map → server-DjZZa1wr.d.ts.map} +1 -1
  46. package/dist/server.d.ts +3 -3
  47. package/dist/server.js +2 -2
  48. package/dist/{store-DGHeBtIQ.d.ts → store-DtDOWLSn.d.ts} +4 -5
  49. package/dist/{store-DGHeBtIQ.d.ts.map → store-DtDOWLSn.d.ts.map} +1 -1
  50. package/dist/store-N8PXxDAS.js.map +1 -1
  51. package/dist/store-memory.d.ts +1 -1
  52. package/dist/store-memory.js +1 -1
  53. package/dist/{store-polling-6DW7F1DT.js → store-polling-CmxUbV93.js} +56 -7
  54. package/dist/store-polling-CmxUbV93.js.map +1 -0
  55. package/dist/store-postgres.d.ts +6 -4
  56. package/dist/store-postgres.d.ts.map +1 -1
  57. package/dist/store-postgres.js +701 -53
  58. package/dist/store-postgres.js.map +1 -1
  59. package/dist/store-presence-polling-C7-XZyW9.js +94 -0
  60. package/dist/store-presence-polling-C7-XZyW9.js.map +1 -0
  61. package/dist/store-redis-http.d.ts +2 -2
  62. package/dist/store-redis-http.d.ts.map +1 -1
  63. package/dist/store-redis-http.js +184 -38
  64. package/dist/store-redis-http.js.map +1 -1
  65. package/dist/{store-redis-core-z-ykbyMg.js → store-redis-notify-BUCyXOn0.js} +491 -27
  66. package/dist/store-redis-notify-BUCyXOn0.js.map +1 -0
  67. package/dist/store-redis.d.ts +5 -13
  68. package/dist/store-redis.d.ts.map +1 -1
  69. package/dist/store-redis.js +27 -271
  70. package/dist/store-redis.js.map +1 -1
  71. package/dist/store-sqlite.d.ts +1 -1
  72. package/dist/store-sqlite.js +1 -1
  73. package/dist/{wire--yji6mO3.js → wire-BO5wWCb1.js} +18 -16
  74. package/dist/wire-BO5wWCb1.js.map +1 -0
  75. package/docs/actors/04-routes.mdx +40 -8
  76. package/docs/guides/03-react.mdx +52 -10
  77. package/docs/guides/05-production.mdx +54 -5
  78. package/docs/guides/09-presence.mdx +12 -7
  79. package/docs/guides/10-transports.mdx +15 -2
  80. package/docs/reference/01-api.mdx +124 -17
  81. package/docs/reference/02-errors.mdx +45 -11
  82. package/examples/playground/package.json +1 -1
  83. package/package.json +1 -1
  84. package/src/actor-client.ts +114 -14
  85. package/src/actor-react.ts +18 -3
  86. package/src/actor.ts +16 -1
  87. package/src/client-errors.ts +51 -0
  88. package/src/client.ts +253 -96
  89. package/src/errors.ts +4 -9
  90. package/src/index.ts +1 -1
  91. package/src/internal.ts +1 -1
  92. package/src/postgres-notification-scope.ts +134 -0
  93. package/src/postgres-notifications.ts +244 -0
  94. package/src/postgres-pool.ts +65 -0
  95. package/src/postgres-resources.ts +185 -0
  96. package/src/presence-recovery.ts +120 -0
  97. package/src/react.ts +3 -0
  98. package/src/redis-http-subscriptions.ts +199 -0
  99. package/src/server.ts +160 -22
  100. package/src/session-socket.ts +25 -7
  101. package/src/sse.ts +17 -0
  102. package/src/store-polling.ts +32 -12
  103. package/src/store-postgres.ts +292 -75
  104. package/src/store-presence-polling.ts +125 -0
  105. package/src/store-redis-core.ts +37 -30
  106. package/src/store-redis-http.ts +51 -45
  107. package/src/store-redis-notify.ts +464 -0
  108. package/src/store-redis.ts +9 -364
  109. package/src/store.ts +3 -4
  110. package/src/stream-activity.ts +32 -0
  111. package/src/wire.ts +39 -15
  112. package/dist/actor-shared-USo5MyuF.d.ts +0 -136
  113. package/dist/actor-shared-USo5MyuF.d.ts.map +0 -1
  114. package/dist/actor.d.ts.map +0 -1
  115. package/dist/client.d.ts.map +0 -1
  116. package/dist/client.js.map +0 -1
  117. package/dist/index.d.ts.map +0 -1
  118. package/dist/server-DlLyvaSH.js.map +0 -1
  119. package/dist/store-polling-6DW7F1DT.js.map +0 -1
  120. package/dist/store-redis-core-z-ykbyMg.js.map +0 -1
  121. package/dist/wire--yji6mO3.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"actor-react.js","names":[],"sources":["../src/actor-react.ts"],"sourcesContent":["'use client'\n/**\n * experimental-a2/actor/react — use an actor from React: live state\n * plus typed calls, one hook. A thin wrapper: the state pump follows\n * the SSE that `handle.fetch` serves (frontier resume, reconnection,\n * heartbeat watchdog — both ends library code), and `call` is\n * `createActorClient`'s typed surface (the framework-agnostic\n * primitive for everything that isn't React).\n *\n * ```tsx\n * // server component\n * const initial = await vault.actor(id).state()\n * // client component — typed by the server module, erased at build\n * const { state, call, connection } = useActor<typeof vault>({\n * api: `/vault/${id}`, // your route: auth, then handle.fetch\n * id,\n * initial,\n * })\n * await call.withdraw({ amount: 60 }) // ActorRefusedError on refusal\n * ```\n *\n * The fold is library code (last write wins over state commits), so no\n * reducers, schemas, or contracts appear in browser code. Live, not\n * optimistic: handlers are server code deciding against serialized\n * fresh state, so a local guess would be wrong exactly when the actor\n * matters. On a view-projected mount, pass the projected shape as the\n * second type argument — `useActor<typeof vault, PublicVault>` — and\n * `initial`, `state`, and call answers all carry it.\n */\n\nimport { ACTOR_STATE_EVENT, openPresenceDefs } from './actor-shared.ts'\nimport type { ActorPresenceMap, ActorPresenceValues } from './actor-shared.ts'\nimport {\n createActorClient,\n type ActorClientCall,\n type ActorStateOf,\n type AnyActorDefinition,\n} from './actor-client.ts'\nimport { createClient } from './client.ts'\nimport type { A2Client, Connection } from './client.ts'\nimport type { ContractEvent, EventDefs, PresenceDefs } from './contract.ts'\nimport type { Reducer } from './reducer.ts'\nimport { useSession } from './react.ts'\n\n/** The server-to-client handoff: `await def.actor(id).state()`. */\nexport type ActorSnapshot<S> = { state: S; index: number }\n\nexport type UseActorOptions<View> = {\n /** The route whose handler delegates to `handle.fetch` for this instance. */\n api: string\n /** The instance id. */\n id: string\n /** The server-rendered fold — the stream resumes after `index`. */\n initial: ActorSnapshot<View>\n /** This client's presence identity — required to call `setPresence`. */\n participant?: string\n}\n\n/** The definition's presence vocabulary, `never` when undeclared. */\ntype PresenceOf<D extends AnyActorDefinition> = D extends {\n protocol?: infer P\n}\n ? NonNullable<P> extends { presence: infer Values extends object }\n ? Values\n : never\n : never\n\nexport type UseActorResult<D extends AnyActorDefinition, View> = {\n /** The actor's state, live: every commit streams in and replaces it. */\n state: View\n /** The stream frontier. */\n index: number\n connection: Connection\n /** Typed calls over POST — the response is the answer. */\n call: ActorClientCall<D, View>\n /** The state-commit feed this browser has observed. */\n events: ContractEvent<EventDefs>[]\n /**\n * The replicated presence map: participant → field → latest value.\n * Peer-authored — render values like user input. Empty (and\n * `setPresence` untyped-callable-with-nothing) when the protocol\n * declares no presence.\n */\n presence: ActorPresenceMap<PresenceOf<D>>\n /**\n * Announce this client's presence fields (throttled, resent on\n * reconnect; `null` clears a field). Requires `participant`.\n */\n setPresence: (values: ActorPresenceValues<PresenceOf<D>>) => void\n}\n\n/**\n * The follower fold, untyped on purpose: the state type comes from the\n * caller's `initial` handoff, and the fold never inspects state.\n * `initialState` is never rendered — `initial` is required, so every\n * session hydrates before it connects.\n */\nconst followerReducer: Reducer<EventDefs, unknown, PresenceDefs> = {\n name: 'a2.actor.follower.v1',\n events: {},\n // The open vocabulary ('*' catch-all): the browser cannot know a\n // server-defined field list, so the server stays the authority and\n // the protocol types honest callers at compile time.\n presence: openPresenceDefs,\n fold: (state, event) =>\n event.type === ACTOR_STATE_EVENT\n ? (event.payload as { state: unknown }).state\n : state,\n initialState: undefined,\n stateSchema: undefined,\n}\n\nconst clients = new Map<string, A2Client<EventDefs, unknown, PresenceDefs>>()\n\n/** Use one actor instance: live state plus typed calls. No provider. */\nexport function useActor<D extends AnyActorDefinition, View = ActorStateOf<D>>(\n options: UseActorOptions<View>,\n): UseActorResult<D, View> {\n const { api } = options\n let client = clients.get(api)\n if (!client) {\n client = createClient({ reducer: followerReducer, api })\n clients.set(api, client)\n }\n const session = useSession(client, options.id, {\n hydrate: options.initial,\n ...(options.participant === undefined\n ? {}\n : { participant: options.participant }),\n })\n const { call } = createActorClient<D, View>({ api })\n return {\n state: session.state as View,\n index: session.index,\n connection: session.connection,\n call,\n events: session.events,\n presence: session.presence as ActorPresenceMap<PresenceOf<D>>,\n setPresence: session.setPresence as (\n values: ActorPresenceValues<PresenceOf<D>>,\n ) => void,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,MAAM,kBAA6D;CACjE,MAAM;CACN,QAAQ,CAAC;CAIT,UAAU;CACV,OAAO,OAAO,UACZ,MAAM,SAAA,mBACD,MAAM,QAA+B,QACtC;CACN,cAAc,KAAA;CACd,aAAa,KAAA;AACf;AAEA,MAAM,0BAAU,IAAI,IAAwD;;AAG5E,SAAgB,SACd,SACyB;CACzB,MAAM,EAAE,QAAQ;CAChB,IAAI,SAAS,QAAQ,IAAI,GAAG;CAC5B,IAAI,CAAC,QAAQ;EACX,SAAS,aAAa;GAAE,SAAS;GAAiB;EAAI,CAAC;EACvD,QAAQ,IAAI,KAAK,MAAM;CACzB;CACA,MAAM,UAAU,WAAW,QAAQ,QAAQ,IAAI;EAC7C,SAAS,QAAQ;EACjB,GAAI,QAAQ,gBAAgB,KAAA,IACxB,CAAC,IACD,EAAE,aAAa,QAAQ,YAAY;CACzC,CAAC;CACD,MAAM,EAAE,SAAS,kBAA2B,EAAE,IAAI,CAAC;CACnD,OAAO;EACL,OAAO,QAAQ;EACf,OAAO,QAAQ;EACf,YAAY,QAAQ;EACpB;EACA,QAAQ,QAAQ;EAChB,UAAU,QAAQ;EAClB,aAAa,QAAQ;CAGvB;AACF"}
1
+ {"version":3,"file":"actor-react.js","names":[],"sources":["../src/actor-react.ts"],"sourcesContent":["'use client'\n/**\n * experimental-a2/actor/react — use an actor from React: live state\n * plus typed calls, one hook. A thin wrapper: the state pump follows\n * the SSE that `handle.fetch` serves (frontier resume, reconnection,\n * heartbeat watchdog — both ends library code), and `call` is\n * `createActorClient`'s typed surface (the framework-agnostic\n * primitive for everything that isn't React).\n *\n * ```tsx\n * // server component\n * const initial = await vault.actor(id).state()\n * // client component — typed by the server module, erased at build\n * const { state, call, connection } = useActor<typeof vault>({\n * api: `/vault/${id}`, // your route: auth, then handle.fetch\n * id,\n * initial,\n * })\n * await call.withdraw({ amount: 60 }) // ActorRefusedError on refusal\n * ```\n *\n * The fold is library code (last write wins over state commits), so no\n * reducers, schemas, or contracts appear in browser code. Live, not\n * optimistic: handlers are server code deciding against serialized\n * fresh state, so a local guess would be wrong exactly when the actor\n * matters. On a view-projected mount, pass the projected shape as the\n * second type argument — `useActor<typeof vault, PublicVault>` — and\n * `initial`, `state`, and call answers all carry it.\n */\n\nimport { ACTOR_STATE_EVENT, openPresenceDefs } from './actor-shared.ts'\nimport type { ActorPresenceMap, ActorPresenceValues } from './actor-shared.ts'\nimport {\n createActorClient,\n type ActorClientCall,\n type ActorStateOf,\n type AnyActorDefinition,\n} from './actor-client.ts'\nimport { createClient } from './client.ts'\nimport type { A2Client, Connection } from './client.ts'\nimport type { ContractEvent, EventDefs, PresenceDefs } from './contract.ts'\nimport type { Reducer } from './reducer.ts'\nimport { useSession } from './react.ts'\nimport { useMemo } from 'react'\n\n/** The server-to-client handoff: `await def.actor(id).state()`. */\nexport type ActorSnapshot<S> = { state: S; index: number }\n\nexport type UseActorOptions<View> = {\n /** The route whose handler delegates to `handle.fetch` for this instance. */\n api: string\n /** The instance id. */\n id: string\n /** The server-rendered fold — the stream resumes after `index`. */\n initial: ActorSnapshot<View>\n /** This client's presence identity — required to call `setPresence`. */\n participant?: string\n}\n\n/** The definition's presence vocabulary, `never` when undeclared. */\ntype PresenceOf<D extends AnyActorDefinition> = D extends {\n protocol?: infer P\n}\n ? NonNullable<P> extends { presence: infer Values extends object }\n ? Values\n : never\n : never\n\nexport type UseActorResult<D extends AnyActorDefinition, View> = {\n /** The live view, advanced by call answers, refreshes, and stream commits. */\n state: View\n /** The latest adopted state index. */\n index: number\n connection: Connection\n /** Typed calls over POST — the response is the answer. */\n call: ActorClientCall<D, View>\n refresh: () => Promise<ActorSnapshot<View>>\n /** The state-commit feed this browser has observed. */\n events: ContractEvent<EventDefs>[]\n /**\n * The replicated presence map: participant → field → latest value.\n * Peer-authored — render values like user input. Empty (and\n * `setPresence` untyped-callable-with-nothing) when the protocol\n * declares no presence.\n */\n presence: ActorPresenceMap<PresenceOf<D>>\n /**\n * Announce this client's presence fields (throttled, resent on\n * reconnect; `null` clears a field). Requires `participant`.\n */\n setPresence: (values: ActorPresenceValues<PresenceOf<D>>) => void\n}\n\n/**\n * The follower fold, untyped on purpose: the state type comes from the\n * caller's `initial` handoff, and the fold never inspects state.\n * `initialState` is never rendered — `initial` is required, so every\n * session hydrates before it connects.\n */\nconst followerReducer: Reducer<EventDefs, unknown, PresenceDefs> = {\n name: 'a2.actor.follower.v1',\n events: {},\n // The open vocabulary ('*' catch-all): the browser cannot know a\n // server-defined field list, so the server stays the authority and\n // the protocol types honest callers at compile time.\n presence: openPresenceDefs,\n fold: (state, event) =>\n event.type === ACTOR_STATE_EVENT\n ? (event.payload as { state: unknown }).state\n : state,\n initialState: undefined,\n stateSchema: undefined,\n}\n\nconst clients = new Map<string, A2Client<EventDefs, unknown, PresenceDefs>>()\n\n/** Use one actor instance: live state plus typed calls. No provider. */\nexport function useActor<D extends AnyActorDefinition, View = ActorStateOf<D>>(\n options: UseActorOptions<View>,\n): UseActorResult<D, View> {\n const { api } = options\n let client = clients.get(api)\n if (!client) {\n client = createClient({ reducer: followerReducer, api })\n clients.set(api, client)\n }\n const session = useSession(client, options.id, {\n hydrate: options.initial,\n ...(options.participant === undefined\n ? {}\n : { participant: options.participant }),\n })\n const { call, state: refresh } = useMemo(\n () =>\n createActorClient<D, View>({\n api,\n onSnapshot: ({ state, index }) => {\n client.session(options.id, {\n initialState: state,\n initialIndex: index,\n })\n },\n }),\n [api, client, options.id],\n )\n return {\n state: session.state as View,\n index: session.index,\n connection: session.connection,\n call,\n refresh,\n events: session.events,\n presence: session.presence as ActorPresenceMap<PresenceOf<D>>,\n setPresence: session.setPresence as (\n values: ActorPresenceValues<PresenceOf<D>>,\n ) => void,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmGA,MAAM,kBAA6D;CACjE,MAAM;CACN,QAAQ,CAAC;CAIT,UAAU;CACV,OAAO,OAAO,UACZ,MAAM,SAAA,mBACD,MAAM,QAA+B,QACtC;CACN,cAAc,KAAA;CACd,aAAa,KAAA;AACf;AAEA,MAAM,0BAAU,IAAI,IAAwD;;AAG5E,SAAgB,SACd,SACyB;CACzB,MAAM,EAAE,QAAQ;CAChB,IAAI,SAAS,QAAQ,IAAI,GAAG;CAC5B,IAAI,CAAC,QAAQ;EACX,SAAS,aAAa;GAAE,SAAS;GAAiB;EAAI,CAAC;EACvD,QAAQ,IAAI,KAAK,MAAM;CACzB;CACA,MAAM,UAAU,WAAW,QAAQ,QAAQ,IAAI;EAC7C,SAAS,QAAQ;EACjB,GAAI,QAAQ,gBAAgB,KAAA,IACxB,CAAC,IACD,EAAE,aAAa,QAAQ,YAAY;CACzC,CAAC;CACD,MAAM,EAAE,MAAM,OAAO,YAAY,cAE7B,kBAA2B;EACzB;EACA,aAAa,EAAE,OAAO,YAAY;GAChC,OAAO,QAAQ,QAAQ,IAAI;IACzB,cAAc;IACd,cAAc;GAChB,CAAC;EACH;CACF,CAAC,GACH;EAAC;EAAK;EAAQ,QAAQ;CAAE,CAC1B;CACA,OAAO;EACL,OAAO,QAAQ;EACf,OAAO,QAAQ;EACf,YAAY,QAAQ;EACpB;EACA;EACA,QAAQ,QAAQ;EAChB,UAAU,QAAQ;EAClB,aAAa,QAAQ;CAGvB;AACF"}
package/dist/actor.d.ts CHANGED
@@ -1,176 +1,2 @@
1
- import { i as Contract, s as EventDefs, t as Reducer } from "./reducer-DJKWm3cp.js";
2
- import { t as A2Store } from "./store-DGHeBtIQ.js";
3
- import { m as Session, n as A2Server, t as A2Scheduler } from "./server-DgCrSuhB.js";
4
- import { i as A2Telemetry } from "./telemetry-CpeclqB2.js";
5
- import { a as ActorPresenceOf, c as ActorRefusedError, d as ActorSend, i as ActorPresenceMap, l as ActorScheduleOptions, n as ActorConcurrentContext, o as ActorPresenceValues, r as ActorContext, s as ActorProtocol, t as ActorClientEventDefs, u as ActorScheduleSend } from "./actor-shared-USo5MyuF.js";
6
- //#region src/actor.d.ts
7
- /**
8
- * One event's handler: ordinary server code. Serial by default — read
9
- * `ctx.state`, perform I/O, mutate `ctx.state`, one atomic commit at
10
- * return. `{ concurrent: true, handle }` opts the handler out of the
11
- * lane for slow I/O: state becomes a snapshot read and mutations
12
- * happen by sending events. The input is typed by the protocol; the
13
- * wire hands handlers parsed JSON, so a wire-exposed event guards its
14
- * input in its first line (`schema.parse(input)` if you like schemas —
15
- * userland either way).
16
- */
17
- type ActorHandler<D extends ActorProtocol, K extends keyof D["events"]> = ((ctx: ActorContext<D>, input: D["events"][K]) => void | Promise<void>) | {
18
- concurrent: true;
19
- handle: (ctx: ActorConcurrentContext<D>, input: D["events"][K]) => void | Promise<void>;
20
- };
21
- /**
22
- * Mark a handler concurrent — off the lane, in parallel with the lane
23
- * and with other concurrent handlers, `ctx.state()` a snapshot read.
24
- * Sugar for the structural `{ concurrent: true, handle }` form:
25
- *
26
- * ```ts
27
- * handlers: {
28
- * transfer: concurrent(async (ctx, input) => {
29
- * await bank.transfer(input, { idempotencyKey: input.ref })
30
- * ctx.send.settle({ ref: input.ref })
31
- * }),
32
- * }
33
- * ```
34
- */
35
- declare function concurrent<Ctx, I>(handle: (ctx: Ctx, input: I) => void | Promise<void>): {
36
- concurrent: true;
37
- handle: (ctx: Ctx, input: I) => void | Promise<void>;
38
- };
39
- type ActorOptions<D extends ActorProtocol> = {
40
- /** Identity — prefixes storage keys; one contract per actor definition. */
41
- name: string;
42
- /** The initial state — checked against the protocol, a plain JSON tree. */
43
- state: D["state"];
44
- /**
45
- * One handler per declared event — completeness and payload shapes
46
- * are compile-checked against the protocol.
47
- */
48
- handlers: { [K in keyof D["events"]]: ActorHandler<D, K>; };
49
- store?: A2Store;
50
- scheduler?: A2Scheduler;
51
- telemetry?: A2Telemetry;
52
- } & ([ActorPresenceOf<D>] extends [never] ? {
53
- presence?: never;
54
- } : {
55
- /**
56
- * The wire bit for the protocol's `presence` vocabulary — types
57
- * erase, so the runtime needs one value to arm the presence
58
- * lanes (frames on GET, envelopes on POST). Required exactly
59
- * when the protocol declares `presence`; the vocabulary itself
60
- * is typed there. Values are validated to the JSON floor and
61
- * pass through `authorize` as `{ type: 'presence' }` operations;
62
- * meaning stays with your renderers — treat values as user
63
- * input.
64
- */
65
- presence: true;
66
- });
67
- /**
68
- * One HTTP operation `handle.fetch` is about to serve — the actor
69
- * mirror of core's `A2Operation`. `authorize` sees it before any
70
- * write or subscription; returning `false` answers 403.
71
- */
72
- type ActorOperation = {
73
- readonly type: "stream";
74
- readonly id: string;
75
- readonly startAfter: number;
76
- } | {
77
- readonly type: "call";
78
- readonly id: string;
79
- readonly event: string;
80
- readonly input: unknown;
81
- readonly messageId?: string;
82
- } | {
83
- readonly type: "presence";
84
- readonly id: string;
85
- readonly participant: string;
86
- readonly values: Readonly<Record<string, unknown>>;
87
- };
88
- type ActorFetchOptions<D extends ActorProtocol> = {
89
- /** Per-operation policy — authentication happened in your route. */
90
- authorize?: (operation: ActorOperation) => boolean | Promise<boolean>;
91
- /**
92
- * Request-time projection: what this mount's audience sees. Applied
93
- * to every state frame on the stream AND to call answers (the two
94
- * untrusted lanes must agree, or the call lane leaks what the
95
- * stream hides). The definition stays audience-agnostic — different
96
- * routes project the same actor differently, and per-viewer views
97
- * are just closures over the route's auth. Output is held to the
98
- * JSON-tree floor like everything else. Transport-agnostic: applied
99
- * at frame emission, so any wire the door speaks emits projected
100
- * frames. Absent, the full state ships (the trusted default).
101
- */
102
- view?: (state: D["state"]) => unknown;
103
- };
104
- type ActorSendOptions = {
105
- /** Explicit message id — makes retries of this send idempotent. */
106
- id?: string;
107
- };
108
- type ActorCallOptions = ActorSendOptions & {
109
- /** How long to await the answer before rejecting the wait (default 30s). */
110
- timeoutMs?: number;
111
- };
112
- type ActorCallResult<S> = {
113
- /** The actor's state after this message was processed. */
114
- state: S;
115
- /** Log index of the state commit that answered this message. */
116
- index: number;
117
- };
118
- type CallMethod<D extends ActorProtocol, K extends keyof D["events"]> = {} extends D["events"][K] ? (input?: D["events"][K], options?: ActorCallOptions) => Promise<ActorCallResult<D["state"]>> : (input: D["events"][K], options?: ActorCallOptions) => Promise<ActorCallResult<D["state"]>>;
119
- type SendMethod<D extends ActorProtocol, K extends keyof D["events"]> = {} extends D["events"][K] ? (input?: D["events"][K], options?: ActorSendOptions) => Promise<{
120
- id: string;
121
- index: number;
122
- }> : (input: D["events"][K], options?: ActorSendOptions) => Promise<{
123
- id: string;
124
- index: number;
125
- }>;
126
- /** One instance: typed calls and sends, reads, the managed door, the escape hatch. */
127
- type ActorHandle<D extends ActorProtocol> = {
128
- readonly id: string;
129
- /**
130
- * Send the event and await its answer: the state after the handler
131
- * ran, or a rejection with `ActorRefusedError`. Serial events only —
132
- * concurrent handlers produce no answer to await; `send` them.
133
- */
134
- readonly call: { readonly [K in keyof D["events"]]: CallMethod<D, K>; };
135
- /** Cast: validate, append the event durably, return without waiting. */
136
- readonly send: { readonly [K in keyof D["events"]]: SendMethod<D, K>; };
137
- /** Snapshot read — never queues behind pending messages. */
138
- readonly state: () => Promise<ActorCallResult<D["state"]>>;
139
- /**
140
- * The managed door — the actor mirror of `server.fetch`, bound to
141
- * this instance. GET streams the state plane (`a2.actor.state`
142
- * commits only, `?index` resume, heartbeat, deadline rotation);
143
- * POST is the call lane `createActorClient` speaks (`{ event,
144
- * input, messageId? }` → the answer, 409 for a refusal). Your route
145
- * authenticates and picks the instance; `authorize` sees every
146
- * operation. Custom endpoints are route code around this call.
147
- */
148
- readonly fetch: (request: Request, options?: ActorFetchOptions<D>) => Promise<Response>;
149
- /** Escape hatch: the raw A2 session (history, stream, schedule). */
150
- readonly session: Session<EventDefs>;
151
- };
152
- type ActorDefinition<D extends ActorProtocol> = {
153
- readonly name: string;
154
- /**
155
- * Type-only carrier of the protocol, so clients deriving from
156
- * `typeof def` can see the vocabularies (`experimental-a2/actor/react`
157
- * types `presence` from it). Never a runtime value.
158
- */
159
- readonly protocol?: D;
160
- /** The assembled contract — declared events plus the reserved a2.actor.* pair. */
161
- readonly contract: Contract<EventDefs>;
162
- /** The underlying A2 server — `server.fetch` mounts the full session wire. */
163
- readonly server: A2Server<EventDefs>;
164
- /** The state fold — same identity as the client's follower fold. */
165
- readonly reducer: Reducer<ActorClientEventDefs<D["state"]>, D["state"]>;
166
- actor(id: string): ActorHandle<D>;
167
- };
168
- /**
169
- * Define and serve an actor over its protocol: a named, durable
170
- * instance-per-id with serialized state handlers, concurrent I/O
171
- * handlers, and typed self-sends.
172
- */
173
- declare function actor<D extends ActorProtocol>(options: ActorOptions<D>): ActorDefinition<D>;
174
- //#endregion
175
- export { ActorCallOptions, ActorCallResult, type ActorConcurrentContext, type ActorContext, ActorDefinition, ActorFetchOptions, ActorHandle, ActorHandler, ActorOperation, ActorOptions, type ActorPresenceMap, type ActorPresenceOf, type ActorPresenceValues, type ActorProtocol, ActorRefusedError, type ActorScheduleOptions, type ActorScheduleSend, type ActorSend, ActorSendOptions, actor, concurrent };
176
- //# sourceMappingURL=actor.d.ts.map
1
+ import { _ as ActorProtocol, a as ActorHandle, b as ActorScheduleSend, c as ActorOptions, d as concurrent, f as ActorConcurrentContext, g as ActorPresenceValues, h as ActorPresenceOf, i as ActorFetchOptions, l as ActorSendOptions, m as ActorPresenceMap, n as ActorCallResult, o as ActorHandler, p as ActorContext, r as ActorDefinition, s as ActorOperation, t as ActorCallOptions, u as actor, v as ActorRefusedError, x as ActorSend, y as ActorScheduleOptions } from "./actor-DJi3RsNu.js";
2
+ export { ActorCallOptions, ActorCallResult, type ActorConcurrentContext, type ActorContext, ActorDefinition, ActorFetchOptions, ActorHandle, ActorHandler, ActorOperation, ActorOptions, type ActorPresenceMap, type ActorPresenceOf, type ActorPresenceValues, type ActorProtocol, ActorRefusedError, type ActorScheduleOptions, type ActorScheduleSend, type ActorSend, ActorSendOptions, actor, concurrent };
package/dist/actor.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as contract } from "./contract-48bUMgcL.js";
2
2
  import { n as NonRetriableError, t as A2Error } from "./errors-DCk6ch5n.js";
3
- import { a as parsePresenceSibling, i as sseResponse, r as setServerFetchHooks, t as createServer } from "./server-DlLyvaSH.js";
3
+ import { a as sseResponse, i as setServerFetchHooks, o as parsePresenceSibling, t as createServer } from "./server-BeNADlCI.js";
4
4
  import { a as actorFailedSchema, c as isJsonTree, i as ActorRefusedError, l as openPresenceDefs, n as ACTOR_LANE, o as actorReducer, r as ACTOR_STATE_EVENT, s as actorStateSchema, t as ACTOR_FAILED_EVENT } from "./actor-shared-DI7J5upy.js";
5
5
  //#region src/actor.ts
6
6
  /**
@@ -324,6 +324,17 @@ function actor(options) {
324
324
  const authorized = async (operation) => await fetchOptions?.authorize?.(Object.freeze(operation)) !== false;
325
325
  if (request.method === "GET") {
326
326
  const url = new URL(request.url);
327
+ if (url.searchParams.has("snapshot")) {
328
+ if (!await authorized({
329
+ type: "state",
330
+ id
331
+ })) return forbidden();
332
+ const result = await readState();
333
+ return Response.json({
334
+ state: fetchOptions?.view ? applyView(fetchOptions.view, result.state) : result.state,
335
+ index: result.index
336
+ }, { headers: { "cache-control": "private, no-store" } });
337
+ }
327
338
  const raw = Number(url.searchParams.get("index"));
328
339
  const startAfter = Number.isSafeInteger(raw) && raw >= 0 ? raw : 0;
329
340
  if (!await authorized({
@@ -387,7 +398,7 @@ function actor(options) {
387
398
  return Response.json(fetchOptions?.view ? {
388
399
  state: applyView(fetchOptions.view, result.state),
389
400
  index: result.index
390
- } : result);
401
+ } : result, { headers: { "cache-control": "private, no-store" } });
391
402
  } catch (error) {
392
403
  if (error instanceof ActorRefusedError) return Response.json({
393
404
  error: error.message,
package/dist/actor.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"actor.js","names":["contract","createContract"],"sources":["../src/actor.ts"],"sourcesContent":["/**\n * experimental-a2/actor — durable actors over the log. Server-only\n * (handlers are server code); the browser condition resolves to a\n * throwing stub, and the browser surfaces are experimental-a2/actor/client\n * and experimental-a2/actor/react.\n *\n * An actor is defined over a protocol — its state shape and event\n * vocabulary, as types — and one complete `handlers` bag:\n *\n * ```ts\n * interface Counter {\n * state: { count: number }\n * events: { increment: object; add: { by: number } }\n * }\n * const counter = actor<Counter>({\n * name: 'counter',\n * state: { count: 0 },\n * handlers: {\n * increment: (ctx) => {\n * ctx.state.count++\n * },\n * add: (ctx, input) => {\n * ctx.state.count += input.by\n * },\n * },\n * })\n * ```\n *\n * Handlers are serial by default: one at a time per instance (a lane —\n * the state's write lock), `ctx.state` a mutable draft committed\n * atomically with completion. A handler holding slow I/O opts out of\n * the lane with `{ concurrent: true, handle }`: it runs in parallel,\n * reads state as a snapshot, and mutates by sending events whose\n * serial handlers decide against fresh state. `ctx.send.eventName(...)`\n * is typed by the protocol and buffered — committed atomically with\n * the handler's completion, so a reserve and its trigger can never\n * half-happen.\n *\n * A thrown `NonRetriableError` is an answer (settled, delivered to a\n * waiting caller); any other error retries like every A2 handler\n * failure; a crash re-runs against the same pre-state. Everything\n * compiles to contract + reducer + laned handlers + returned events —\n * no new store operations, no new wire.\n */\n\n// oxlint-disable no-await-in-loop -- a call awaits its answer: drain, read\n// the tail, repeat until the message settles. Sequential by nature.\n\nimport {\n ACTOR_FAILED_EVENT,\n ACTOR_LANE,\n ACTOR_STATE_EVENT,\n ActorRefusedError,\n actorFailedSchema,\n actorReducer,\n actorStateSchema,\n isJsonTree,\n openPresenceDefs,\n} from './actor-shared.ts'\nimport type {\n ActorClientEventDefs,\n ActorConcurrentContext,\n ActorContext,\n ActorFailedPayload,\n ActorPresenceOf,\n ActorProtocol,\n ActorScheduleOptions,\n ActorScheduleSend,\n ActorSend,\n ActorStatePayload,\n} from './actor-shared.ts'\nimport { parsePresenceSibling } from './push-envelope.ts'\nimport type { ParsedPushPresence } from './push-envelope.ts'\nimport { contract as createContract } from './contract.ts'\nimport type { PresencePatch, PresenceSnapshot } from './contract.ts'\nimport type { Contract, EventDefs } from './contract.ts'\nimport type { Reducer } from './reducer.ts'\nimport { A2Error, NonRetriableError } from './errors.ts'\nimport { createServer } from './server.ts'\nimport { setServerFetchHooks } from './server-fetch.ts'\nimport { sseResponse } from './sse.ts'\nimport type { A2Scheduler, A2Server, HandlerEntry, Session } from './server.ts'\nimport type { A2Store } from './store.ts'\nimport type { StandardSchemaV1 } from './standard-schema.ts'\nimport type { A2Telemetry } from './telemetry.ts'\n\nexport type {\n ActorConcurrentContext,\n ActorContext,\n ActorPresenceMap,\n ActorPresenceOf,\n ActorPresenceValues,\n ActorProtocol,\n ActorScheduleOptions,\n ActorScheduleSend,\n ActorSend,\n} from './actor-shared.ts'\nexport { ActorRefusedError } from './actor-shared.ts'\n\n/**\n * One event's handler: ordinary server code. Serial by default — read\n * `ctx.state`, perform I/O, mutate `ctx.state`, one atomic commit at\n * return. `{ concurrent: true, handle }` opts the handler out of the\n * lane for slow I/O: state becomes a snapshot read and mutations\n * happen by sending events. The input is typed by the protocol; the\n * wire hands handlers parsed JSON, so a wire-exposed event guards its\n * input in its first line (`schema.parse(input)` if you like schemas —\n * userland either way).\n */\nexport type ActorHandler<D extends ActorProtocol, K extends keyof D['events']> =\n | ((ctx: ActorContext<D>, input: D['events'][K]) => void | Promise<void>)\n | {\n concurrent: true\n handle: (\n ctx: ActorConcurrentContext<D>,\n input: D['events'][K],\n ) => void | Promise<void>\n }\n\n/**\n * Mark a handler concurrent — off the lane, in parallel with the lane\n * and with other concurrent handlers, `ctx.state()` a snapshot read.\n * Sugar for the structural `{ concurrent: true, handle }` form:\n *\n * ```ts\n * handlers: {\n * transfer: concurrent(async (ctx, input) => {\n * await bank.transfer(input, { idempotencyKey: input.ref })\n * ctx.send.settle({ ref: input.ref })\n * }),\n * }\n * ```\n */\nexport function concurrent<Ctx, I>(\n handle: (ctx: Ctx, input: I) => void | Promise<void>,\n): { concurrent: true; handle: (ctx: Ctx, input: I) => void | Promise<void> } {\n return { concurrent: true, handle }\n}\n\nexport type ActorOptions<D extends ActorProtocol> = {\n /** Identity — prefixes storage keys; one contract per actor definition. */\n name: string\n /** The initial state — checked against the protocol, a plain JSON tree. */\n state: D['state']\n /**\n * One handler per declared event — completeness and payload shapes\n * are compile-checked against the protocol.\n */\n handlers: { [K in keyof D['events']]: ActorHandler<D, K> }\n store?: A2Store\n scheduler?: A2Scheduler\n telemetry?: A2Telemetry\n} & ([ActorPresenceOf<D>] extends [never]\n ? { presence?: never }\n : {\n /**\n * The wire bit for the protocol's `presence` vocabulary — types\n * erase, so the runtime needs one value to arm the presence\n * lanes (frames on GET, envelopes on POST). Required exactly\n * when the protocol declares `presence`; the vocabulary itself\n * is typed there. Values are validated to the JSON floor and\n * pass through `authorize` as `{ type: 'presence' }` operations;\n * meaning stays with your renderers — treat values as user\n * input.\n */\n presence: true\n })\n\n/**\n * One HTTP operation `handle.fetch` is about to serve — the actor\n * mirror of core's `A2Operation`. `authorize` sees it before any\n * write or subscription; returning `false` answers 403.\n */\nexport type ActorOperation =\n | {\n readonly type: 'stream'\n readonly id: string\n readonly startAfter: number\n }\n | {\n readonly type: 'call'\n readonly id: string\n readonly event: string\n readonly input: unknown\n readonly messageId?: string\n }\n | {\n readonly type: 'presence'\n readonly id: string\n readonly participant: string\n readonly values: Readonly<Record<string, unknown>>\n }\n\nexport type ActorFetchOptions<D extends ActorProtocol> = {\n /** Per-operation policy — authentication happened in your route. */\n authorize?: (operation: ActorOperation) => boolean | Promise<boolean>\n /**\n * Request-time projection: what this mount's audience sees. Applied\n * to every state frame on the stream AND to call answers (the two\n * untrusted lanes must agree, or the call lane leaks what the\n * stream hides). The definition stays audience-agnostic — different\n * routes project the same actor differently, and per-viewer views\n * are just closures over the route's auth. Output is held to the\n * JSON-tree floor like everything else. Transport-agnostic: applied\n * at frame emission, so any wire the door speaks emits projected\n * frames. Absent, the full state ships (the trusted default).\n */\n view?: (state: D['state']) => unknown\n}\n\nexport type ActorSendOptions = {\n /** Explicit message id — makes retries of this send idempotent. */\n id?: string\n}\n\nexport type ActorCallOptions = ActorSendOptions & {\n /** How long to await the answer before rejecting the wait (default 30s). */\n timeoutMs?: number\n}\n\nexport type ActorCallResult<S> = {\n /** The actor's state after this message was processed. */\n state: S\n /** Log index of the state commit that answered this message. */\n index: number\n}\n\ntype CallMethod<\n D extends ActorProtocol,\n K extends keyof D['events'],\n> = {} extends D['events'][K]\n ? (\n input?: D['events'][K],\n options?: ActorCallOptions,\n ) => Promise<ActorCallResult<D['state']>>\n : (\n input: D['events'][K],\n options?: ActorCallOptions,\n ) => Promise<ActorCallResult<D['state']>>\n\ntype SendMethod<\n D extends ActorProtocol,\n K extends keyof D['events'],\n> = {} extends D['events'][K]\n ? (\n input?: D['events'][K],\n options?: ActorSendOptions,\n ) => Promise<{ id: string; index: number }>\n : (\n input: D['events'][K],\n options?: ActorSendOptions,\n ) => Promise<{ id: string; index: number }>\n\n/** One instance: typed calls and sends, reads, the managed door, the escape hatch. */\nexport type ActorHandle<D extends ActorProtocol> = {\n readonly id: string\n /**\n * Send the event and await its answer: the state after the handler\n * ran, or a rejection with `ActorRefusedError`. Serial events only —\n * concurrent handlers produce no answer to await; `send` them.\n */\n readonly call: { readonly [K in keyof D['events']]: CallMethod<D, K> }\n /** Cast: validate, append the event durably, return without waiting. */\n readonly send: { readonly [K in keyof D['events']]: SendMethod<D, K> }\n /** Snapshot read — never queues behind pending messages. */\n readonly state: () => Promise<ActorCallResult<D['state']>>\n /**\n * The managed door — the actor mirror of `server.fetch`, bound to\n * this instance. GET streams the state plane (`a2.actor.state`\n * commits only, `?index` resume, heartbeat, deadline rotation);\n * POST is the call lane `createActorClient` speaks (`{ event,\n * input, messageId? }` → the answer, 409 for a refusal). Your route\n * authenticates and picks the instance; `authorize` sees every\n * operation. Custom endpoints are route code around this call.\n */\n readonly fetch: (\n request: Request,\n options?: ActorFetchOptions<D>,\n ) => Promise<Response>\n /** Escape hatch: the raw A2 session (history, stream, schedule). */\n readonly session: Session<EventDefs>\n}\n\nexport type ActorDefinition<D extends ActorProtocol> = {\n readonly name: string\n /**\n * Type-only carrier of the protocol, so clients deriving from\n * `typeof def` can see the vocabularies (`experimental-a2/actor/react`\n * types `presence` from it). Never a runtime value.\n */\n readonly protocol?: D\n /** The assembled contract — declared events plus the reserved a2.actor.* pair. */\n readonly contract: Contract<EventDefs>\n /** The underlying A2 server — `server.fetch` mounts the full session wire. */\n readonly server: A2Server<EventDefs>\n /** The state fold — same identity as the client's follower fold. */\n readonly reducer: Reducer<ActorClientEventDefs<D['state']>, D['state']>\n actor(id: string): ActorHandle<D>\n}\n\n// Object-mechanics names, not surface names: events live in their own\n// bags, so nothing else is reserved.\nconst UNSAFE_EVENT_NAMES = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst forbidden = (): Response =>\n Response.json({ error: 'the operation is not authorized' }, { status: 403 })\n\nconst CALL_TIMEOUT_MS = 30_000\nconst CALL_POLL_MS = 25\n\n/** Declared events accept any JSON tree; `undefined` normalizes to `{}`. */\nconst jsonInputSchema: StandardSchemaV1<unknown> = {\n '~standard': {\n version: 1,\n vendor: 'a2',\n validate(value) {\n if (value === undefined || value === null) return { value: {} }\n if (!isJsonTree(value)) {\n return {\n issues: [{ message: 'event input must be a plain JSON tree' }],\n }\n }\n return { value }\n },\n },\n}\n\nconst describeError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms))\n\ntype NormalizedHandler<D extends ActorProtocol> =\n | {\n kind: 'serial'\n handle: (ctx: ActorContext<D>, input: unknown) => void | Promise<void>\n }\n | {\n kind: 'concurrent'\n handle: (\n ctx: ActorConcurrentContext<D>,\n input: unknown,\n ) => void | Promise<void>\n }\n\n/**\n * Define and serve an actor over its protocol: a named, durable\n * instance-per-id with serialized state handlers, concurrent I/O\n * handlers, and typed self-sends.\n */\nexport function actor<D extends ActorProtocol>(\n options: ActorOptions<D>,\n): ActorDefinition<D> {\n const { name } = options\n\n const handlersByEvent = new Map<string, NormalizedHandler<D>>()\n const events: Record<string, StandardSchemaV1> = {\n [ACTOR_STATE_EVENT]: actorStateSchema(),\n [ACTOR_FAILED_EVENT]: actorFailedSchema,\n }\n for (const [eventName, def] of Object.entries(\n options.handlers as Record<string, ActorHandler<D, keyof D['events']>>,\n )) {\n if (UNSAFE_EVENT_NAMES.has(eventName)) {\n throw new TypeError(\n `actor '${name}': '${eventName}' collides with object plumbing and cannot name an event`,\n )\n }\n if (eventName.startsWith('a2.')) {\n throw new TypeError(\n `actor '${name}': event names starting with 'a2.' are reserved`,\n )\n }\n handlersByEvent.set(\n eventName,\n typeof def === 'function'\n ? {\n kind: 'serial',\n handle: def as (\n ctx: ActorContext<D>,\n input: unknown,\n ) => void | Promise<void>,\n }\n : {\n kind: 'concurrent',\n handle: def.handle as (\n ctx: ActorConcurrentContext<D>,\n input: unknown,\n ) => void | Promise<void>,\n },\n )\n events[eventName] = jsonInputSchema\n }\n\n const reducer = actorReducer({ name, state: options.state })\n // The server's contract carries every event type; the reducer only\n // folds state commits. Same fold, same identity — the widening is a\n // typing formality.\n const serverReducer = reducer as unknown as Reducer<EventDefs, D['state']>\n\n // The typed durable-timer surface: immediate handoff to the\n // configured scheduler through the handler session, so timer\n // identity is scoped to the triggering message and re-runs address\n // the same timer (core §6). Not buffered — see ActorScheduleSend.\n const makeSchedule = (\n schedule: (\n name: string,\n timing: { delay?: string; at?: Date },\n event: { type: string; payload: unknown },\n ) => Promise<void>,\n ): ActorScheduleSend<D['events']> => {\n const surface: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(surface, eventName, {\n value: (input: unknown, scheduleOptions: ActorScheduleOptions) => {\n const { name: taskName, ...timing } = scheduleOptions\n return schedule(taskName ?? eventName, timing, {\n type: eventName,\n payload: input ?? {},\n })\n },\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n return surface as ActorScheduleSend<D['events']>\n }\n\n // The typed self-send surface: per-invocation buffers behind one\n // shared method record shape. defineProperty so event names like\n // 'constructor'-adjacent identifiers can never touch prototypes.\n const makeSend = (\n buffer: { type: string; payload: unknown }[],\n ): ActorSend<D['events']> => {\n const send: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(send, eventName, {\n value: (input?: unknown) => {\n buffer.push({ type: eventName, payload: input ?? {} })\n },\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n return send as ActorSend<D['events']>\n }\n\n const handlers: Record<string, HandlerEntry<EventDefs>> = {}\n for (const [eventName, def] of handlersByEvent) {\n if (def.kind === 'concurrent') {\n // No lane: concurrent handlers run in parallel — with the lane\n // and with each other. They cannot write state (no draft to\n // commit), so no serialization is needed for correctness; slow\n // I/O lives here without blocking the actor.\n handlers[eventName] = async (ctx) => {\n const sends: { type: string; payload: unknown }[] = []\n try {\n await def.handle(\n {\n id: ctx.event.id,\n attempt: ctx.attempt,\n signal: ctx.signal,\n send: makeSend(sends),\n schedule: makeSchedule((taskName, timing, event) =>\n ctx.session.schedule(\n taskName,\n timing as Parameters<typeof ctx.session.schedule>[1],\n event,\n ),\n ),\n state: async () => {\n const { state, index } = await ctx.session.state(\n serverReducer,\n { through: 'latest' },\n )\n return { state, index }\n },\n },\n ctx.event.payload,\n )\n } catch (error) {\n if (!(error instanceof NonRetriableError)) throw error\n // A terminal failure is recorded for audit; nothing awaits a\n // concurrent handler, so the marker is history, not an\n // answer. Buffered sends are discarded — refusals are total,\n // so compensate by completing (send then return), never by\n // throwing.\n const payload: ActorFailedPayload = {\n message: ctx.event.id,\n event: eventName,\n error: describeError(error),\n }\n return { type: ACTOR_FAILED_EVENT, payload }\n }\n // Sends commit atomically with settlement; re-runs converge on\n // the same deterministic message ids.\n return sends\n }\n continue\n }\n handlers[eventName] = {\n // One lane for every serial handler of one instance: the next\n // message starts only after the previous one completed, and\n // completion commits the state event atomically —\n // read-modify-write on `ctx.state` is safe by exclusion, not by\n // liveness.\n lane: ACTOR_LANE,\n handler: async (ctx) => {\n // Explicitly 'latest', not the event-relative default: prior\n // lane messages commit *after* this message was appended, so\n // their state commits carry higher indexes than the trigger —\n // an event-relative read would miss them and lose updates.\n // 'latest' is deterministic here because the lane makes this\n // attempt the only possible writer while it runs.\n const { state } = await ctx.session.state(serverReducer, {\n through: 'latest',\n })\n const draft = structuredClone(state)\n const sends: { type: string; payload: unknown }[] = []\n try {\n await def.handle(\n {\n state: draft,\n id: ctx.event.id,\n attempt: ctx.attempt,\n signal: ctx.signal,\n send: makeSend(sends),\n schedule: makeSchedule((taskName, timing, event) =>\n ctx.session.schedule(\n taskName,\n timing as Parameters<typeof ctx.session.schedule>[1],\n event,\n ),\n ),\n },\n ctx.event.payload,\n )\n } catch (error) {\n // A NonRetriableError is an answer: settle the message,\n // record the refusal, deliver it to the waiting caller —\n // no retry, no failure budget spent (buffered sends are\n // discarded with the draft: refusals are total). Every\n // other throw is an ordinary A2 handler failure: rethrown\n // into core's retry machinery (backoff, ten-failure\n // budget, dead letter) — including surrendered lease\n // aborts, which core recognizes by identity.\n if (!(error instanceof NonRetriableError)) throw error\n const payload: ActorFailedPayload = {\n message: ctx.event.id,\n event: eventName,\n error: describeError(error),\n }\n return { type: ACTOR_FAILED_EVENT, payload }\n }\n // One returned batch: buffered sends plus the state commit —\n // committed atomically with completion, so a reserve and its\n // trigger can never half-happen. The state event stays the\n // outcome marker a waiting call resolves on. (Unconditional\n // for now; a dirty check is a compatible later optimization.)\n const payload: ActorStatePayload<D['state']> = {\n state: draft,\n event: eventName,\n message: ctx.event.id,\n }\n return [...sends, { type: ACTOR_STATE_EVENT, payload }]\n },\n }\n }\n\n const presenceEnabled = (options as { presence?: unknown }).presence === true\n // The '*' catch-all arms an open server-side vocabulary: the\n // protocol types field names at compile time, the floor validates\n // every value, and `authorize` sees every set. See openPresenceDefs.\n const contract = presenceEnabled\n ? createContract({ name, events, presence: openPresenceDefs })\n : createContract({ name, events })\n const server = createServer({\n contract,\n handlers,\n ...(options.store ? { store: options.store } : {}),\n ...(options.scheduler ? { scheduler: options.scheduler } : {}),\n ...(options.telemetry ? { telemetry: options.telemetry } : {}),\n })\n // Single-writer discipline on the underlying session wire too: if an\n // application mounts `def.server.fetch`, browsers may push declared\n // events, never authored state or failure records.\n setServerFetchHooks(server, {\n validateIngress: ({ events: pushed }) => {\n for (const event of pushed) {\n if (event.type.startsWith('a2.actor.')) {\n throw new TypeError(\n `'${event.type}' is reserved — only a handler's completion can author it`,\n )\n }\n }\n },\n })\n\n const makeHandle = (id: string): ActorHandle<D> => {\n const session = server.session(id)\n\n const sendEvent = async (\n eventName: string,\n input: unknown,\n sendOptions?: ActorSendOptions,\n ): Promise<{ id: string; index: number }> => {\n const [message] = await session.append({\n type: eventName,\n payload: input ?? {},\n ...(sendOptions?.id ? { id: sendOptions.id } : {}),\n })\n if (!message) throw new Error('append returned no event')\n return { id: message.id, index: message.index }\n }\n\n const callEvent = async (\n eventName: string,\n input: unknown,\n callOptions?: ActorCallOptions,\n ): Promise<ActorCallResult<D['state']>> => {\n if (handlersByEvent.get(eventName)?.kind === 'concurrent') {\n throw new TypeError(\n `actor '${name}': '${eventName}' is concurrent — it produces no answer to await; send it instead`,\n )\n }\n const message = await sendEvent(eventName, input, callOptions)\n const deadline = Date.now() + (callOptions?.timeoutMs ?? CALL_TIMEOUT_MS)\n let cursor = message.index + 1\n for (;;) {\n // Drain participates in processing (usually answering inline in\n // this invocation); claims arbitrate if another process runs.\n await server.drain(id)\n const tail = await session.history({ gte: cursor })\n for (const event of tail) {\n if (event.type === ACTOR_STATE_EVENT) {\n const payload = event.payload as ActorStatePayload<D['state']>\n if (payload.message === message.id) {\n return { state: payload.state, index: event.index }\n }\n }\n if (event.type === ACTOR_FAILED_EVENT) {\n const payload = event.payload as ActorFailedPayload\n if (payload.message === message.id) {\n throw new ActorRefusedError(eventName, message.id, payload.error)\n }\n }\n }\n const last = tail[tail.length - 1]\n if (last) cursor = last.index + 1\n if (Date.now() >= deadline) {\n throw new Error(\n `actor '${name}': timed out waiting for '${eventName}' (message ${message.id})`,\n )\n }\n await sleep(CALL_POLL_MS)\n }\n }\n\n const readState = async (): Promise<ActorCallResult<D['state']>> => {\n const { state, index } = await session.state(serverReducer)\n return { state, index }\n }\n\n const applyView = (\n view: (state: D['state']) => unknown,\n state: D['state'],\n ): unknown => {\n const viewed = view(state)\n if (!isJsonTree(viewed)) {\n throw new TypeError(\n `actor '${name}': the view returned a value that is not a plain JSON tree`,\n )\n }\n return viewed\n }\n\n const streamStates = async function* (\n startAfter: number,\n view?: (state: D['state']) => unknown,\n ) {\n // With presence armed, the session interleaves presence items\n // (snapshot, then patches) between log events. They are\n // ephemeral audience data, not actor state: they pass through\n // untouched — views project state, never peers — and they never\n // advance the resume frontier.\n const source: AsyncIterable<\n | Awaited<ReturnType<typeof session.history>>[number]\n | PresencePatch\n | PresenceSnapshot\n > = presenceEnabled\n ? (\n session as unknown as {\n stream(options: {\n startAfter: number\n presence: true\n }): AsyncIterable<PresencePatch | PresenceSnapshot>\n }\n ).stream({ startAfter, presence: true })\n : session.stream({ startAfter })\n for await (const item of source) {\n if (!('type' in item)) {\n yield item\n continue\n }\n const event = item\n // The state plane only: subscribers see what the actor is,\n // never other callers' inputs. Refusals answer only their\n // caller (the POST 409); the full mailbox stays server-side.\n if (event.type !== ACTOR_STATE_EVENT) continue\n if (!view) {\n yield event\n continue\n }\n const payload = event.payload as ActorStatePayload<D['state']>\n yield {\n ...event,\n payload: { ...payload, state: applyView(view, payload.state) },\n }\n }\n }\n\n // The managed door — the actor mirror of `server.fetch`: GET is\n // the state-plane SSE (`a2.actor.state` commits only, `?index`\n // resume), POST is the call lane (`{ event, input, messageId? }`\n // → the answer, 409 for a refusal). Authentication happens in the\n // surrounding route; per-operation policy in `authorize`.\n const handleFetch = async (\n request: Request,\n fetchOptions?: ActorFetchOptions<D>,\n ): Promise<Response> => {\n const authorized = async (operation: ActorOperation): Promise<boolean> =>\n (await fetchOptions?.authorize?.(Object.freeze(operation))) !== false\n\n if (request.method === 'GET') {\n const url = new URL(request.url)\n const raw = Number(url.searchParams.get('index'))\n const startAfter = Number.isSafeInteger(raw) && raw >= 0 ? raw : 0\n if (!(await authorized({ type: 'stream', id, startAfter }))) {\n return forbidden()\n }\n return sseResponse(streamStates(startAfter, fetchOptions?.view))\n }\n if (request.method !== 'POST') {\n return new Response(null, {\n status: 405,\n headers: { allow: 'GET, POST' },\n })\n }\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return Response.json({ error: 'invalid JSON body' }, { status: 400 })\n }\n const record =\n typeof body === 'object' && body !== null\n ? (body as Record<string, unknown>)\n : {}\n if ('presence' in record) {\n // A presence envelope — what the follower client's\n // `setPresence` posts. Events never ride this lane: writes to\n // the actor are calls.\n if (!presenceEnabled) {\n return Response.json(\n { error: `actor '${name}' declares no presence` },\n { status: 400 },\n )\n }\n const pushedEvents = record['events']\n if (\n pushedEvents !== undefined &&\n (!Array.isArray(pushedEvents) || pushedEvents.length > 0)\n ) {\n return Response.json(\n { error: 'the actor wire takes calls, not event pushes' },\n { status: 400 },\n )\n }\n let patch: ParsedPushPresence\n try {\n const parsed = parsePresenceSibling(record['presence'])\n if (!parsed) throw new TypeError('presence must be an object')\n patch = parsed\n } catch (error) {\n return Response.json({ error: describeError(error) }, { status: 400 })\n }\n if (\n !(await authorized({\n type: 'presence',\n id,\n participant: patch.participant,\n values: patch.values,\n }))\n ) {\n return forbidden()\n }\n try {\n await (\n session as unknown as {\n setPresence(patch: ParsedPushPresence): Promise<void>\n }\n ).setPresence(patch)\n } catch (error) {\n if (\n error instanceof A2Error &&\n (error.code === 'INVALID_PAYLOAD' ||\n error.code === 'UNKNOWN_PRESENCE_FIELD')\n ) {\n return Response.json({ error: error.message }, { status: 400 })\n }\n throw error\n }\n return Response.json([])\n }\n const eventName = record['event']\n if (\n typeof eventName !== 'string' ||\n handlersByEvent.get(eventName)?.kind !== 'serial'\n ) {\n return Response.json({ error: 'unknown event' }, { status: 400 })\n }\n const messageId = record['messageId']\n if (messageId !== undefined && typeof messageId !== 'string') {\n return Response.json({ error: 'invalid messageId' }, { status: 400 })\n }\n const input = record['input']\n if (\n !(await authorized({\n type: 'call',\n id,\n event: eventName,\n input,\n ...(messageId === undefined ? {} : { messageId }),\n }))\n ) {\n return forbidden()\n }\n try {\n const result = await callEvent(\n eventName,\n input,\n messageId === undefined ? undefined : { id: messageId },\n )\n return Response.json(\n fetchOptions?.view\n ? {\n state: applyView(fetchOptions.view, result.state),\n index: result.index,\n }\n : result,\n )\n } catch (error) {\n if (error instanceof ActorRefusedError) {\n return Response.json(\n {\n error: error.message,\n event: error.event,\n messageId: error.messageId,\n },\n { status: 409 },\n )\n }\n if (\n error instanceof A2Error &&\n (error.code === 'INVALID_PAYLOAD' ||\n error.code === 'UNKNOWN_EVENT_TYPE')\n ) {\n return Response.json({ error: error.message }, { status: 400 })\n }\n throw error\n }\n }\n\n const call: Record<string, unknown> = {}\n const send: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(call, eventName, {\n value: (input?: unknown, callOptions?: ActorCallOptions) =>\n callEvent(eventName, input, callOptions),\n enumerable: true,\n configurable: true,\n writable: false,\n })\n Object.defineProperty(send, eventName, {\n value: (input?: unknown, sendOptions?: ActorSendOptions) =>\n sendEvent(eventName, input, sendOptions),\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n const handle: ActorHandle<D> = {\n id,\n session,\n call: call as ActorHandle<D>['call'],\n send: send as ActorHandle<D>['send'],\n state: readState,\n fetch: handleFetch,\n }\n return handle\n }\n\n return {\n name,\n contract,\n server,\n reducer,\n actor: makeHandle,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;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AAM,QAAQ,GAAG,EAAE,QAAQ,IAAI,CAAC;IAEhE,MAAM;GACR;EACF;EAEA,MAAM,OAAgC,CAAC;EACvC,MAAM,OAAgC,CAAC;EACvC,KAAK,MAAM,aAAa,gBAAgB,KAAK,GAAG;GAC9C,OAAO,eAAe,MAAM,WAAW;IACrC,QAAQ,OAAiB,gBACvB,UAAU,WAAW,OAAO,WAAW;IACzC,YAAY;IACZ,cAAc;IACd,UAAU;GACZ,CAAC;GACD,OAAO,eAAe,MAAM,WAAW;IACrC,QAAQ,OAAiB,gBACvB,UAAU,WAAW,OAAO,WAAW;IACzC,YAAY;IACZ,cAAc;IACd,UAAU;GACZ,CAAC;EACH;EAUA,OAAO;GAPL;GACA;GACM;GACA;GACN,OAAO;GACP,OAAO;EAEG;CACd;CAEA,OAAO;EACL;EACA,UAAA;EACA;EACA;EACA,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"actor.js","names":["contract","createContract"],"sources":["../src/actor.ts"],"sourcesContent":["/**\n * experimental-a2/actor — durable actors over the log. Server-only\n * (handlers are server code); the browser condition resolves to a\n * throwing stub, and the browser surfaces are experimental-a2/actor/client\n * and experimental-a2/actor/react.\n *\n * An actor is defined over a protocol — its state shape and event\n * vocabulary, as types — and one complete `handlers` bag:\n *\n * ```ts\n * interface Counter {\n * state: { count: number }\n * events: { increment: object; add: { by: number } }\n * }\n * const counter = actor<Counter>({\n * name: 'counter',\n * state: { count: 0 },\n * handlers: {\n * increment: (ctx) => {\n * ctx.state.count++\n * },\n * add: (ctx, input) => {\n * ctx.state.count += input.by\n * },\n * },\n * })\n * ```\n *\n * Handlers are serial by default: one at a time per instance (a lane —\n * the state's write lock), `ctx.state` a mutable draft committed\n * atomically with completion. A handler holding slow I/O opts out of\n * the lane with `{ concurrent: true, handle }`: it runs in parallel,\n * reads state as a snapshot, and mutates by sending events whose\n * serial handlers decide against fresh state. `ctx.send.eventName(...)`\n * is typed by the protocol and buffered — committed atomically with\n * the handler's completion, so a reserve and its trigger can never\n * half-happen.\n *\n * A thrown `NonRetriableError` is an answer (settled, delivered to a\n * waiting caller); any other error retries like every A2 handler\n * failure; a crash re-runs against the same pre-state. Everything\n * compiles to contract + reducer + laned handlers + returned events —\n * no new store operations, no new wire.\n */\n\n// oxlint-disable no-await-in-loop -- a call awaits its answer: drain, read\n// the tail, repeat until the message settles. Sequential by nature.\n\nimport {\n ACTOR_FAILED_EVENT,\n ACTOR_LANE,\n ACTOR_STATE_EVENT,\n ActorRefusedError,\n actorFailedSchema,\n actorReducer,\n actorStateSchema,\n isJsonTree,\n openPresenceDefs,\n} from './actor-shared.ts'\nimport type {\n ActorClientEventDefs,\n ActorConcurrentContext,\n ActorContext,\n ActorFailedPayload,\n ActorPresenceOf,\n ActorProtocol,\n ActorScheduleOptions,\n ActorScheduleSend,\n ActorSend,\n ActorStatePayload,\n} from './actor-shared.ts'\nimport { parsePresenceSibling } from './push-envelope.ts'\nimport type { ParsedPushPresence } from './push-envelope.ts'\nimport { contract as createContract } from './contract.ts'\nimport type { PresencePatch, PresenceSnapshot } from './contract.ts'\nimport type { Contract, EventDefs } from './contract.ts'\nimport type { Reducer } from './reducer.ts'\nimport { A2Error, NonRetriableError } from './errors.ts'\nimport { createServer } from './server.ts'\nimport { setServerFetchHooks } from './server-fetch.ts'\nimport { sseResponse } from './sse.ts'\nimport type { A2Scheduler, A2Server, HandlerEntry, Session } from './server.ts'\nimport type { A2Store } from './store.ts'\nimport type { StandardSchemaV1 } from './standard-schema.ts'\nimport type { A2Telemetry } from './telemetry.ts'\n\nexport type {\n ActorConcurrentContext,\n ActorContext,\n ActorPresenceMap,\n ActorPresenceOf,\n ActorPresenceValues,\n ActorProtocol,\n ActorScheduleOptions,\n ActorScheduleSend,\n ActorSend,\n} from './actor-shared.ts'\nexport { ActorRefusedError } from './actor-shared.ts'\n\n/**\n * One event's handler: ordinary server code. Serial by default — read\n * `ctx.state`, perform I/O, mutate `ctx.state`, one atomic commit at\n * return. `{ concurrent: true, handle }` opts the handler out of the\n * lane for slow I/O: state becomes a snapshot read and mutations\n * happen by sending events. The input is typed by the protocol; the\n * wire hands handlers parsed JSON, so a wire-exposed event guards its\n * input in its first line (`schema.parse(input)` if you like schemas —\n * userland either way).\n */\nexport type ActorHandler<D extends ActorProtocol, K extends keyof D['events']> =\n | ((ctx: ActorContext<D>, input: D['events'][K]) => void | Promise<void>)\n | {\n concurrent: true\n handle: (\n ctx: ActorConcurrentContext<D>,\n input: D['events'][K],\n ) => void | Promise<void>\n }\n\n/**\n * Mark a handler concurrent — off the lane, in parallel with the lane\n * and with other concurrent handlers, `ctx.state()` a snapshot read.\n * Sugar for the structural `{ concurrent: true, handle }` form:\n *\n * ```ts\n * handlers: {\n * transfer: concurrent(async (ctx, input) => {\n * await bank.transfer(input, { idempotencyKey: input.ref })\n * ctx.send.settle({ ref: input.ref })\n * }),\n * }\n * ```\n */\nexport function concurrent<Ctx, I>(\n handle: (ctx: Ctx, input: I) => void | Promise<void>,\n): { concurrent: true; handle: (ctx: Ctx, input: I) => void | Promise<void> } {\n return { concurrent: true, handle }\n}\n\nexport type ActorOptions<D extends ActorProtocol> = {\n /** Identity — prefixes storage keys; one contract per actor definition. */\n name: string\n /** The initial state — checked against the protocol, a plain JSON tree. */\n state: D['state']\n /**\n * One handler per declared event — completeness and payload shapes\n * are compile-checked against the protocol.\n */\n handlers: { [K in keyof D['events']]: ActorHandler<D, K> }\n store?: A2Store\n scheduler?: A2Scheduler\n telemetry?: A2Telemetry\n} & ([ActorPresenceOf<D>] extends [never]\n ? { presence?: never }\n : {\n /**\n * The wire bit for the protocol's `presence` vocabulary — types\n * erase, so the runtime needs one value to arm the presence\n * lanes (frames on GET, envelopes on POST). Required exactly\n * when the protocol declares `presence`; the vocabulary itself\n * is typed there. Values are validated to the JSON floor and\n * pass through `authorize` as `{ type: 'presence' }` operations;\n * meaning stays with your renderers — treat values as user\n * input.\n */\n presence: true\n })\n\n/**\n * One HTTP operation `handle.fetch` is about to serve — the actor\n * mirror of core's `A2Operation`. `authorize` sees it before any\n * read, write, or subscription; returning `false` answers 403.\n */\nexport type ActorOperation =\n | { readonly type: 'state'; readonly id: string }\n | {\n readonly type: 'stream'\n readonly id: string\n readonly startAfter: number\n }\n | {\n readonly type: 'call'\n readonly id: string\n readonly event: string\n readonly input: unknown\n readonly messageId?: string\n }\n | {\n readonly type: 'presence'\n readonly id: string\n readonly participant: string\n readonly values: Readonly<Record<string, unknown>>\n }\n\nexport type ActorFetchOptions<D extends ActorProtocol> = {\n /** Per-operation policy — authentication happened in your route. */\n authorize?: (operation: ActorOperation) => boolean | Promise<boolean>\n /**\n * Request-time projection: what this mount's audience sees. Applied\n * to every state frame on the stream AND to call answers (the two\n * untrusted lanes must agree, or the call lane leaks what the\n * stream hides). The definition stays audience-agnostic — different\n * routes project the same actor differently, and per-viewer views\n * are just closures over the route's auth. Output is held to the\n * JSON-tree floor like everything else. Transport-agnostic: applied\n * at frame emission, so any wire the door speaks emits projected\n * frames. Absent, the full state ships (the trusted default).\n */\n view?: (state: D['state']) => unknown\n}\n\nexport type ActorSendOptions = {\n /** Explicit message id — makes retries of this send idempotent. */\n id?: string\n}\n\nexport type ActorCallOptions = ActorSendOptions & {\n /** How long to await the answer before rejecting the wait (default 30s). */\n timeoutMs?: number\n}\n\nexport type ActorCallResult<S> = {\n /** The actor's state after this message was processed. */\n state: S\n /** Log index of the state commit that answered this message. */\n index: number\n}\n\ntype CallMethod<\n D extends ActorProtocol,\n K extends keyof D['events'],\n> = {} extends D['events'][K]\n ? (\n input?: D['events'][K],\n options?: ActorCallOptions,\n ) => Promise<ActorCallResult<D['state']>>\n : (\n input: D['events'][K],\n options?: ActorCallOptions,\n ) => Promise<ActorCallResult<D['state']>>\n\ntype SendMethod<\n D extends ActorProtocol,\n K extends keyof D['events'],\n> = {} extends D['events'][K]\n ? (\n input?: D['events'][K],\n options?: ActorSendOptions,\n ) => Promise<{ id: string; index: number }>\n : (\n input: D['events'][K],\n options?: ActorSendOptions,\n ) => Promise<{ id: string; index: number }>\n\n/** One instance: typed calls and sends, reads, the managed door, the escape hatch. */\nexport type ActorHandle<D extends ActorProtocol> = {\n readonly id: string\n /**\n * Send the event and await its answer: the state after the handler\n * ran, or a rejection with `ActorRefusedError`. Serial events only —\n * concurrent handlers produce no answer to await; `send` them.\n */\n readonly call: { readonly [K in keyof D['events']]: CallMethod<D, K> }\n /** Cast: validate, append the event durably, return without waiting. */\n readonly send: { readonly [K in keyof D['events']]: SendMethod<D, K> }\n /** Snapshot read — never queues behind pending messages. */\n readonly state: () => Promise<ActorCallResult<D['state']>>\n /**\n * The managed door — the actor mirror of `server.fetch`, bound to\n * this instance. GET streams the state plane (`a2.actor.state`\n * commits only, `?index` resume, heartbeat, deadline rotation);\n * POST is the call lane `createActorClient` speaks (`{ event,\n * input, messageId? }` → the answer, 409 for a refusal). Your route\n * authenticates and picks the instance; `authorize` sees every\n * operation. Custom endpoints are route code around this call.\n */\n readonly fetch: (\n request: Request,\n options?: ActorFetchOptions<D>,\n ) => Promise<Response>\n /** Escape hatch: the raw A2 session (history, stream, schedule). */\n readonly session: Session<EventDefs>\n}\n\nexport type ActorDefinition<D extends ActorProtocol> = {\n readonly name: string\n /**\n * Type-only carrier of the protocol, so clients deriving from\n * `typeof def` can see the vocabularies (`experimental-a2/actor/react`\n * types `presence` from it). Never a runtime value.\n */\n readonly protocol?: D\n /** The assembled contract — declared events plus the reserved a2.actor.* pair. */\n readonly contract: Contract<EventDefs>\n /** The underlying A2 server — `server.fetch` mounts the full session wire. */\n readonly server: A2Server<EventDefs>\n /** The state fold — same identity as the client's follower fold. */\n readonly reducer: Reducer<ActorClientEventDefs<D['state']>, D['state']>\n actor(id: string): ActorHandle<D>\n}\n\n// Object-mechanics names, not surface names: events live in their own\n// bags, so nothing else is reserved.\nconst UNSAFE_EVENT_NAMES = new Set(['__proto__', 'constructor', 'prototype'])\n\nconst forbidden = (): Response =>\n Response.json({ error: 'the operation is not authorized' }, { status: 403 })\n\nconst CALL_TIMEOUT_MS = 30_000\nconst CALL_POLL_MS = 25\n\n/** Declared events accept any JSON tree; `undefined` normalizes to `{}`. */\nconst jsonInputSchema: StandardSchemaV1<unknown> = {\n '~standard': {\n version: 1,\n vendor: 'a2',\n validate(value) {\n if (value === undefined || value === null) return { value: {} }\n if (!isJsonTree(value)) {\n return {\n issues: [{ message: 'event input must be a plain JSON tree' }],\n }\n }\n return { value }\n },\n },\n}\n\nconst describeError = (error: unknown): string =>\n error instanceof Error ? error.message : String(error)\n\nconst sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms))\n\ntype NormalizedHandler<D extends ActorProtocol> =\n | {\n kind: 'serial'\n handle: (ctx: ActorContext<D>, input: unknown) => void | Promise<void>\n }\n | {\n kind: 'concurrent'\n handle: (\n ctx: ActorConcurrentContext<D>,\n input: unknown,\n ) => void | Promise<void>\n }\n\n/**\n * Define and serve an actor over its protocol: a named, durable\n * instance-per-id with serialized state handlers, concurrent I/O\n * handlers, and typed self-sends.\n */\nexport function actor<D extends ActorProtocol>(\n options: ActorOptions<D>,\n): ActorDefinition<D> {\n const { name } = options\n\n const handlersByEvent = new Map<string, NormalizedHandler<D>>()\n const events: Record<string, StandardSchemaV1> = {\n [ACTOR_STATE_EVENT]: actorStateSchema(),\n [ACTOR_FAILED_EVENT]: actorFailedSchema,\n }\n for (const [eventName, def] of Object.entries(\n options.handlers as Record<string, ActorHandler<D, keyof D['events']>>,\n )) {\n if (UNSAFE_EVENT_NAMES.has(eventName)) {\n throw new TypeError(\n `actor '${name}': '${eventName}' collides with object plumbing and cannot name an event`,\n )\n }\n if (eventName.startsWith('a2.')) {\n throw new TypeError(\n `actor '${name}': event names starting with 'a2.' are reserved`,\n )\n }\n handlersByEvent.set(\n eventName,\n typeof def === 'function'\n ? {\n kind: 'serial',\n handle: def as (\n ctx: ActorContext<D>,\n input: unknown,\n ) => void | Promise<void>,\n }\n : {\n kind: 'concurrent',\n handle: def.handle as (\n ctx: ActorConcurrentContext<D>,\n input: unknown,\n ) => void | Promise<void>,\n },\n )\n events[eventName] = jsonInputSchema\n }\n\n const reducer = actorReducer({ name, state: options.state })\n // The server's contract carries every event type; the reducer only\n // folds state commits. Same fold, same identity — the widening is a\n // typing formality.\n const serverReducer = reducer as unknown as Reducer<EventDefs, D['state']>\n\n // The typed durable-timer surface: immediate handoff to the\n // configured scheduler through the handler session, so timer\n // identity is scoped to the triggering message and re-runs address\n // the same timer (core §6). Not buffered — see ActorScheduleSend.\n const makeSchedule = (\n schedule: (\n name: string,\n timing: { delay?: string; at?: Date },\n event: { type: string; payload: unknown },\n ) => Promise<void>,\n ): ActorScheduleSend<D['events']> => {\n const surface: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(surface, eventName, {\n value: (input: unknown, scheduleOptions: ActorScheduleOptions) => {\n const { name: taskName, ...timing } = scheduleOptions\n return schedule(taskName ?? eventName, timing, {\n type: eventName,\n payload: input ?? {},\n })\n },\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n return surface as ActorScheduleSend<D['events']>\n }\n\n // The typed self-send surface: per-invocation buffers behind one\n // shared method record shape. defineProperty so event names like\n // 'constructor'-adjacent identifiers can never touch prototypes.\n const makeSend = (\n buffer: { type: string; payload: unknown }[],\n ): ActorSend<D['events']> => {\n const send: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(send, eventName, {\n value: (input?: unknown) => {\n buffer.push({ type: eventName, payload: input ?? {} })\n },\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n return send as ActorSend<D['events']>\n }\n\n const handlers: Record<string, HandlerEntry<EventDefs>> = {}\n for (const [eventName, def] of handlersByEvent) {\n if (def.kind === 'concurrent') {\n // No lane: concurrent handlers run in parallel — with the lane\n // and with each other. They cannot write state (no draft to\n // commit), so no serialization is needed for correctness; slow\n // I/O lives here without blocking the actor.\n handlers[eventName] = async (ctx) => {\n const sends: { type: string; payload: unknown }[] = []\n try {\n await def.handle(\n {\n id: ctx.event.id,\n attempt: ctx.attempt,\n signal: ctx.signal,\n send: makeSend(sends),\n schedule: makeSchedule((taskName, timing, event) =>\n ctx.session.schedule(\n taskName,\n timing as Parameters<typeof ctx.session.schedule>[1],\n event,\n ),\n ),\n state: async () => {\n const { state, index } = await ctx.session.state(\n serverReducer,\n { through: 'latest' },\n )\n return { state, index }\n },\n },\n ctx.event.payload,\n )\n } catch (error) {\n if (!(error instanceof NonRetriableError)) throw error\n // A terminal failure is recorded for audit; nothing awaits a\n // concurrent handler, so the marker is history, not an\n // answer. Buffered sends are discarded — refusals are total,\n // so compensate by completing (send then return), never by\n // throwing.\n const payload: ActorFailedPayload = {\n message: ctx.event.id,\n event: eventName,\n error: describeError(error),\n }\n return { type: ACTOR_FAILED_EVENT, payload }\n }\n // Sends commit atomically with settlement; re-runs converge on\n // the same deterministic message ids.\n return sends\n }\n continue\n }\n handlers[eventName] = {\n // One lane for every serial handler of one instance: the next\n // message starts only after the previous one completed, and\n // completion commits the state event atomically —\n // read-modify-write on `ctx.state` is safe by exclusion, not by\n // liveness.\n lane: ACTOR_LANE,\n handler: async (ctx) => {\n // Explicitly 'latest', not the event-relative default: prior\n // lane messages commit *after* this message was appended, so\n // their state commits carry higher indexes than the trigger —\n // an event-relative read would miss them and lose updates.\n // 'latest' is deterministic here because the lane makes this\n // attempt the only possible writer while it runs.\n const { state } = await ctx.session.state(serverReducer, {\n through: 'latest',\n })\n const draft = structuredClone(state)\n const sends: { type: string; payload: unknown }[] = []\n try {\n await def.handle(\n {\n state: draft,\n id: ctx.event.id,\n attempt: ctx.attempt,\n signal: ctx.signal,\n send: makeSend(sends),\n schedule: makeSchedule((taskName, timing, event) =>\n ctx.session.schedule(\n taskName,\n timing as Parameters<typeof ctx.session.schedule>[1],\n event,\n ),\n ),\n },\n ctx.event.payload,\n )\n } catch (error) {\n // A NonRetriableError is an answer: settle the message,\n // record the refusal, deliver it to the waiting caller —\n // no retry, no failure budget spent (buffered sends are\n // discarded with the draft: refusals are total). Every\n // other throw is an ordinary A2 handler failure: rethrown\n // into core's retry machinery (backoff, ten-failure\n // budget, dead letter) — including surrendered lease\n // aborts, which core recognizes by identity.\n if (!(error instanceof NonRetriableError)) throw error\n const payload: ActorFailedPayload = {\n message: ctx.event.id,\n event: eventName,\n error: describeError(error),\n }\n return { type: ACTOR_FAILED_EVENT, payload }\n }\n // One returned batch: buffered sends plus the state commit —\n // committed atomically with completion, so a reserve and its\n // trigger can never half-happen. The state event stays the\n // outcome marker a waiting call resolves on. (Unconditional\n // for now; a dirty check is a compatible later optimization.)\n const payload: ActorStatePayload<D['state']> = {\n state: draft,\n event: eventName,\n message: ctx.event.id,\n }\n return [...sends, { type: ACTOR_STATE_EVENT, payload }]\n },\n }\n }\n\n const presenceEnabled = (options as { presence?: unknown }).presence === true\n // The '*' catch-all arms an open server-side vocabulary: the\n // protocol types field names at compile time, the floor validates\n // every value, and `authorize` sees every set. See openPresenceDefs.\n const contract = presenceEnabled\n ? createContract({ name, events, presence: openPresenceDefs })\n : createContract({ name, events })\n const server = createServer({\n contract,\n handlers,\n ...(options.store ? { store: options.store } : {}),\n ...(options.scheduler ? { scheduler: options.scheduler } : {}),\n ...(options.telemetry ? { telemetry: options.telemetry } : {}),\n })\n // Single-writer discipline on the underlying session wire too: if an\n // application mounts `def.server.fetch`, browsers may push declared\n // events, never authored state or failure records.\n setServerFetchHooks(server, {\n validateIngress: ({ events: pushed }) => {\n for (const event of pushed) {\n if (event.type.startsWith('a2.actor.')) {\n throw new TypeError(\n `'${event.type}' is reserved — only a handler's completion can author it`,\n )\n }\n }\n },\n })\n\n const makeHandle = (id: string): ActorHandle<D> => {\n const session = server.session(id)\n\n const sendEvent = async (\n eventName: string,\n input: unknown,\n sendOptions?: ActorSendOptions,\n ): Promise<{ id: string; index: number }> => {\n const [message] = await session.append({\n type: eventName,\n payload: input ?? {},\n ...(sendOptions?.id ? { id: sendOptions.id } : {}),\n })\n if (!message) throw new Error('append returned no event')\n return { id: message.id, index: message.index }\n }\n\n const callEvent = async (\n eventName: string,\n input: unknown,\n callOptions?: ActorCallOptions,\n ): Promise<ActorCallResult<D['state']>> => {\n if (handlersByEvent.get(eventName)?.kind === 'concurrent') {\n throw new TypeError(\n `actor '${name}': '${eventName}' is concurrent — it produces no answer to await; send it instead`,\n )\n }\n const message = await sendEvent(eventName, input, callOptions)\n const deadline = Date.now() + (callOptions?.timeoutMs ?? CALL_TIMEOUT_MS)\n let cursor = message.index + 1\n for (;;) {\n // Drain participates in processing (usually answering inline in\n // this invocation); claims arbitrate if another process runs.\n await server.drain(id)\n const tail = await session.history({ gte: cursor })\n for (const event of tail) {\n if (event.type === ACTOR_STATE_EVENT) {\n const payload = event.payload as ActorStatePayload<D['state']>\n if (payload.message === message.id) {\n return { state: payload.state, index: event.index }\n }\n }\n if (event.type === ACTOR_FAILED_EVENT) {\n const payload = event.payload as ActorFailedPayload\n if (payload.message === message.id) {\n throw new ActorRefusedError(eventName, message.id, payload.error)\n }\n }\n }\n const last = tail[tail.length - 1]\n if (last) cursor = last.index + 1\n if (Date.now() >= deadline) {\n throw new Error(\n `actor '${name}': timed out waiting for '${eventName}' (message ${message.id})`,\n )\n }\n await sleep(CALL_POLL_MS)\n }\n }\n\n const readState = async (): Promise<ActorCallResult<D['state']>> => {\n const { state, index } = await session.state(serverReducer)\n return { state, index }\n }\n\n const applyView = (\n view: (state: D['state']) => unknown,\n state: D['state'],\n ): unknown => {\n const viewed = view(state)\n if (!isJsonTree(viewed)) {\n throw new TypeError(\n `actor '${name}': the view returned a value that is not a plain JSON tree`,\n )\n }\n return viewed\n }\n\n const streamStates = async function* (\n startAfter: number,\n view?: (state: D['state']) => unknown,\n ) {\n // With presence armed, the session interleaves presence items\n // (snapshot, then patches) between log events. They are\n // ephemeral audience data, not actor state: they pass through\n // untouched — views project state, never peers — and they never\n // advance the resume frontier.\n const source: AsyncIterable<\n | Awaited<ReturnType<typeof session.history>>[number]\n | PresencePatch\n | PresenceSnapshot\n > = presenceEnabled\n ? (\n session as unknown as {\n stream(options: {\n startAfter: number\n presence: true\n }): AsyncIterable<PresencePatch | PresenceSnapshot>\n }\n ).stream({ startAfter, presence: true })\n : session.stream({ startAfter })\n for await (const item of source) {\n if (!('type' in item)) {\n yield item\n continue\n }\n const event = item\n // The state plane only: subscribers see what the actor is,\n // never other callers' inputs. Refusals answer only their\n // caller (the POST 409); the full mailbox stays server-side.\n if (event.type !== ACTOR_STATE_EVENT) continue\n if (!view) {\n yield event\n continue\n }\n const payload = event.payload as ActorStatePayload<D['state']>\n yield {\n ...event,\n payload: { ...payload, state: applyView(view, payload.state) },\n }\n }\n }\n\n // The managed door — the actor mirror of `server.fetch`: GET is\n // the state-plane SSE (`a2.actor.state` commits only, `?index`\n // resume), POST is the call lane (`{ event, input, messageId? }`\n // → the answer, 409 for a refusal). Authentication happens in the\n // surrounding route; per-operation policy in `authorize`.\n const handleFetch = async (\n request: Request,\n fetchOptions?: ActorFetchOptions<D>,\n ): Promise<Response> => {\n const authorized = async (operation: ActorOperation): Promise<boolean> =>\n (await fetchOptions?.authorize?.(Object.freeze(operation))) !== false\n\n if (request.method === 'GET') {\n const url = new URL(request.url)\n if (url.searchParams.has('snapshot')) {\n if (!(await authorized({ type: 'state', id }))) return forbidden()\n const result = await readState()\n return Response.json(\n {\n state: fetchOptions?.view\n ? applyView(fetchOptions.view, result.state)\n : result.state,\n index: result.index,\n },\n { headers: { 'cache-control': 'private, no-store' } },\n )\n }\n const raw = Number(url.searchParams.get('index'))\n const startAfter = Number.isSafeInteger(raw) && raw >= 0 ? raw : 0\n if (!(await authorized({ type: 'stream', id, startAfter }))) {\n return forbidden()\n }\n return sseResponse(streamStates(startAfter, fetchOptions?.view))\n }\n if (request.method !== 'POST') {\n return new Response(null, {\n status: 405,\n headers: { allow: 'GET, POST' },\n })\n }\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return Response.json({ error: 'invalid JSON body' }, { status: 400 })\n }\n const record =\n typeof body === 'object' && body !== null\n ? (body as Record<string, unknown>)\n : {}\n if ('presence' in record) {\n // A presence envelope — what the follower client's\n // `setPresence` posts. Events never ride this lane: writes to\n // the actor are calls.\n if (!presenceEnabled) {\n return Response.json(\n { error: `actor '${name}' declares no presence` },\n { status: 400 },\n )\n }\n const pushedEvents = record['events']\n if (\n pushedEvents !== undefined &&\n (!Array.isArray(pushedEvents) || pushedEvents.length > 0)\n ) {\n return Response.json(\n { error: 'the actor wire takes calls, not event pushes' },\n { status: 400 },\n )\n }\n let patch: ParsedPushPresence\n try {\n const parsed = parsePresenceSibling(record['presence'])\n if (!parsed) throw new TypeError('presence must be an object')\n patch = parsed\n } catch (error) {\n return Response.json({ error: describeError(error) }, { status: 400 })\n }\n if (\n !(await authorized({\n type: 'presence',\n id,\n participant: patch.participant,\n values: patch.values,\n }))\n ) {\n return forbidden()\n }\n try {\n await (\n session as unknown as {\n setPresence(patch: ParsedPushPresence): Promise<void>\n }\n ).setPresence(patch)\n } catch (error) {\n if (\n error instanceof A2Error &&\n (error.code === 'INVALID_PAYLOAD' ||\n error.code === 'UNKNOWN_PRESENCE_FIELD')\n ) {\n return Response.json({ error: error.message }, { status: 400 })\n }\n throw error\n }\n return Response.json([])\n }\n const eventName = record['event']\n if (\n typeof eventName !== 'string' ||\n handlersByEvent.get(eventName)?.kind !== 'serial'\n ) {\n return Response.json({ error: 'unknown event' }, { status: 400 })\n }\n const messageId = record['messageId']\n if (messageId !== undefined && typeof messageId !== 'string') {\n return Response.json({ error: 'invalid messageId' }, { status: 400 })\n }\n const input = record['input']\n if (\n !(await authorized({\n type: 'call',\n id,\n event: eventName,\n input,\n ...(messageId === undefined ? {} : { messageId }),\n }))\n ) {\n return forbidden()\n }\n try {\n const result = await callEvent(\n eventName,\n input,\n messageId === undefined ? undefined : { id: messageId },\n )\n return Response.json(\n fetchOptions?.view\n ? {\n state: applyView(fetchOptions.view, result.state),\n index: result.index,\n }\n : result,\n { headers: { 'cache-control': 'private, no-store' } },\n )\n } catch (error) {\n if (error instanceof ActorRefusedError) {\n return Response.json(\n {\n error: error.message,\n event: error.event,\n messageId: error.messageId,\n },\n { status: 409 },\n )\n }\n if (\n error instanceof A2Error &&\n (error.code === 'INVALID_PAYLOAD' ||\n error.code === 'UNKNOWN_EVENT_TYPE')\n ) {\n return Response.json({ error: error.message }, { status: 400 })\n }\n throw error\n }\n }\n\n const call: Record<string, unknown> = {}\n const send: Record<string, unknown> = {}\n for (const eventName of handlersByEvent.keys()) {\n Object.defineProperty(call, eventName, {\n value: (input?: unknown, callOptions?: ActorCallOptions) =>\n callEvent(eventName, input, callOptions),\n enumerable: true,\n configurable: true,\n writable: false,\n })\n Object.defineProperty(send, eventName, {\n value: (input?: unknown, sendOptions?: ActorSendOptions) =>\n sendEvent(eventName, input, sendOptions),\n enumerable: true,\n configurable: true,\n writable: false,\n })\n }\n\n const handle: ActorHandle<D> = {\n id,\n session,\n call: call as ActorHandle<D>['call'],\n send: send as ActorHandle<D>['send'],\n state: readState,\n fetch: handleFetch,\n }\n return handle\n }\n\n return {\n name,\n contract,\n server,\n reducer,\n actor: makeHandle,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqIA,SAAgB,WACd,QAC4E;CAC5E,OAAO;EAAE,YAAY;EAAM;CAAO;AACpC;AAsKA,MAAM,qCAAqB,IAAI,IAAI;CAAC;CAAa;CAAe;AAAW,CAAC;AAE5E,MAAM,kBACJ,SAAS,KAAK,EAAE,OAAO,kCAAkC,GAAG,EAAE,QAAQ,IAAI,CAAC;AAE7E,MAAM,kBAAkB;AACxB,MAAM,eAAe;;AAGrB,MAAM,kBAA6C,EACjD,aAAa;CACX,SAAS;CACT,QAAQ;CACR,SAAS,OAAO;EACd,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,EAAE,OAAO,CAAC,EAAE;EAC9D,IAAI,CAAC,WAAW,KAAK,GACnB,OAAO,EACL,QAAQ,CAAC,EAAE,SAAS,wCAAw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AAO,eAAe,MAAM,WAAW;IACrC,QAAQ,OAAiB,gBACvB,UAAU,WAAW,OAAO,WAAW;IACzC,YAAY;IACZ,cAAc;IACd,UAAU;GACZ,CAAC;GACD,OAAO,eAAe,MAAM,WAAW;IACrC,QAAQ,OAAiB,gBACvB,UAAU,WAAW,OAAO,WAAW;IACzC,YAAY;IACZ,cAAc;IACd,UAAU;GACZ,CAAC;EACH;EAUA,OAAO;GAPL;GACA;GACM;GACA;GACN,OAAO;GACP,OAAO;EAEG;CACd;CAEA,OAAO;EACL;EACA,UAAA;EACA;EACA;EACA,OAAO;CACT;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { a as ContractEvent, s as EventDefs } from "./reducer-DJKWm3cp.js";
2
- import { n as A2Server, p as ServerOptions } from "./server-DgCrSuhB.js";
2
+ import { n as A2Server, p as ServerOptions } from "./server-DjZZa1wr.js";
3
3
  import { AIEventDefs, AIState, AgentDefinition, AgentToolContext, AgentToolEventDefs } from "./ai.js";
4
4
  import { Instructions, LanguageModel, TextStreamPart, ToolSet, ToolSet as ToolSet$1, UIMessage, UIMessageChunk, streamText } from "ai";
5
5
  //#region src/ai-sdk-step.d.ts
package/dist/ai-server.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { t as A2Error } from "./errors-DCk6ch5n.js";
2
- import { f as consumeSchedulerSendFailure, p as installAmbientToolScopeStorage } from "./internal-DRXJ56EI.js";
3
- import { r as setServerFetchHooks, t as createServer } from "./server-DlLyvaSH.js";
2
+ import { f as consumeSchedulerSendFailure, p as installAmbientToolScopeStorage } from "./internal-Dq2qYxou.js";
3
+ import { i as setServerFetchHooks, t as createServer } from "./server-BeNADlCI.js";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  import { convertToModelMessages, stepCountIs, streamText, toUIMessageStream } from "ai";
6
6
  //#region src/ai-sdk-step.ts
package/dist/ai.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { h as StandardSchemaV1, i as Contract, r as AppendInput, s as EventDefs, t as Reducer } from "./reducer-DJKWm3cp.js";
2
- import { s as HandlerContext } from "./server-DgCrSuhB.js";
2
+ import { s as HandlerContext } from "./server-DjZZa1wr.js";
3
3
  import { FinishReason, JSONValue, LanguageModelUsage, UIMessage, UIMessageChunk } from "ai";
4
4
  //#region src/ai.d.ts
5
5
  type AgentStatus = "idle" | "generating" | "waiting" | "failed" | "closed";
package/dist/ai.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { n as validateSync, t as assertSyncSchema } from "./validate-XKT4FSNn.js";
2
2
  import { t as contract } from "./contract-48bUMgcL.js";
3
- import { l as ambientToolScopeStorage } from "./internal-DRXJ56EI.js";
3
+ import { l as ambientToolScopeStorage } from "./internal-Dq2qYxou.js";
4
4
  //#region src/ai-projector.ts
5
5
  const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6
6
  const cloneMessage = (messageId, base) => structuredClone(base ?? {