experimental-a2 0.2.0 → 0.4.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 (92) hide show
  1. package/CHANGELOG.md +169 -0
  2. package/dist/ai-B4YhEnfw.d.ts +333 -0
  3. package/dist/ai-server.d.ts +48 -9
  4. package/dist/ai-server.js +121 -49
  5. package/dist/ai.d.ts +2 -303
  6. package/dist/ai.js +231 -86
  7. package/dist/cli-B3VuxoDe.js +597 -0
  8. package/dist/cli-bin.d.ts +1 -0
  9. package/dist/cli-bin.js +5 -0
  10. package/dist/cli.d.ts +19 -0
  11. package/dist/cli.js +2 -0
  12. package/dist/client-BrfDXQ8A.d.ts +155 -0
  13. package/dist/client-Bt4tAKi9.js +798 -0
  14. package/dist/client.d.ts +2 -90
  15. package/dist/client.js +1 -409
  16. package/dist/{contract-CG_adnu_.js → contract-48bUMgcL.js} +10 -2
  17. package/dist/{contract-C_3dIIEU.d.ts → contract-jIfaR085.d.ts} +62 -8
  18. package/dist/devtools-J_jZ2vQf.d.ts +151 -0
  19. package/dist/devtools-kJJaORn-.js +338 -0
  20. package/dist/devtools-server.browser.js +1 -1
  21. package/dist/devtools-server.d.ts +2 -2
  22. package/dist/devtools-server.js +224 -43
  23. package/dist/devtools.d.ts +2 -0
  24. package/dist/devtools.js +2 -0
  25. package/dist/{errors-BJRMd-h6.js → errors-BQuJpe82.js} +4 -4
  26. package/dist/{errors-xL_JTXsY.d.ts → errors-W6nwJ-fm.d.ts} +1 -1
  27. package/dist/http.d.ts +71 -13
  28. package/dist/http.js +302 -41
  29. package/dist/{idempotent-replay-BMyHrP0L.js → idempotent-replay-DuqEkYA7.js} +2 -2
  30. package/dist/index.d.ts +5 -5
  31. package/dist/index.js +2 -2
  32. package/dist/{inspection-E7qbD0Xj.js → inspection-DaxB5jM2.js} +2 -1
  33. package/dist/internal-aEotMzu_.js +209 -0
  34. package/dist/otel.d.ts +1 -1
  35. package/dist/platform-B4TnJtWu.js +32 -0
  36. package/dist/react.d.ts +37 -14
  37. package/dist/react.js +26 -15
  38. package/dist/scheduler-qstash.d.ts +78 -0
  39. package/dist/scheduler-qstash.js +499 -0
  40. package/dist/scheduler-task-BpzhPnRS.js +54 -0
  41. package/dist/{recovery-vercel.d.ts → scheduler-vercel.d.ts} +17 -24
  42. package/dist/scheduler-vercel.js +226 -0
  43. package/dist/server-CcNnFnoW.js +1405 -0
  44. package/dist/server-YtPq7hjw.d.ts +260 -0
  45. package/dist/server.d.ts +4 -155
  46. package/dist/server.js +2 -2
  47. package/dist/{log-ldf5g8Cx.d.ts → store-C3sNAaBT.d.ts} +111 -35
  48. package/dist/{log-yJbXUf72.js → store-N8PXxDAS.js} +1 -1
  49. package/dist/store-codec-DTG0Ftek.js +8 -0
  50. package/dist/store-memory.d.ts +11 -0
  51. package/dist/{log-memory.js → store-memory.js} +127 -24
  52. package/dist/{log-polling-6COoN60V.js → store-polling-DgrrAE3d.js} +7 -6
  53. package/dist/{log-postgres.d.ts → store-postgres.d.ts} +6 -6
  54. package/dist/{log-postgres.js → store-postgres.js} +158 -24
  55. package/dist/{log-redis.js → store-redis-core-DWqx3F47.js} +294 -156
  56. package/dist/store-redis-http.d.ts +21 -0
  57. package/dist/store-redis-http.js +70 -0
  58. package/dist/store-redis.d.ts +37 -0
  59. package/dist/store-redis.js +298 -0
  60. package/dist/{log-sqlite.d.ts → store-sqlite.d.ts} +6 -6
  61. package/dist/{log-sqlite.js → store-sqlite.js} +116 -22
  62. package/dist/{telemetry-Cso0qyHQ.d.ts → telemetry-BjYHTfh2.d.ts} +1 -1
  63. package/dist/testing.browser.d.ts +1 -0
  64. package/dist/testing.browser.js +4 -0
  65. package/dist/testing.d.ts +31 -0
  66. package/dist/testing.js +101 -0
  67. package/dist/wire-DCUZBUlT.js +222 -0
  68. package/docs/01-quickstart.mdx +4 -5
  69. package/docs/concepts/01-contracts.mdx +21 -17
  70. package/docs/concepts/02-handlers.mdx +7 -7
  71. package/docs/concepts/03-durability.mdx +26 -29
  72. package/docs/concepts/04-state.mdx +18 -21
  73. package/docs/guides/01-timers.mdx +154 -54
  74. package/docs/guides/02-cancellation.mdx +30 -4
  75. package/docs/guides/03-react.mdx +20 -21
  76. package/docs/guides/04-local-first.mdx +1 -1
  77. package/docs/guides/05-production.mdx +321 -60
  78. package/docs/guides/06-ai-agents.mdx +249 -49
  79. package/docs/guides/07-devtools.mdx +137 -12
  80. package/docs/guides/08-application-data.mdx +1 -1
  81. package/docs/guides/09-presence.mdx +284 -0
  82. package/docs/guides/10-transports.mdx +131 -0
  83. package/docs/index.mdx +22 -46
  84. package/docs/reference/01-api.mdx +751 -102
  85. package/docs/reference/02-errors.mdx +10 -5
  86. package/package.json +23 -6
  87. package/dist/internal-D6wNxTck.js +0 -36
  88. package/dist/log-memory.d.ts +0 -11
  89. package/dist/log-redis.d.ts +0 -31
  90. package/dist/recovery-vercel.js +0 -119
  91. package/dist/server-DJgD2YWP.js +0 -877
  92. package/dist/wire-BVsgR8o9.js +0 -62
@@ -0,0 +1,226 @@
1
+ import { f as classifySchedulerSendFailure, t as DRAIN_TIMINGS, u as assertSchedulerTargets, v as serverInternals } from "./internal-aEotMzu_.js";
2
+ import { n as deliverSchedulerAppend } from "./server-CcNnFnoW.js";
3
+ import { t as retryableLazy } from "./retryable-lazy-DZWmHpii.js";
4
+ import { n as SYSTEM_CLOCK } from "./store-N8PXxDAS.js";
5
+ import { t as normalizeSchedulerTask } from "./scheduler-task-BpzhPnRS.js";
6
+ import { createHash } from "node:crypto";
7
+ //#region src/scheduler-vercel.ts
8
+ /**
9
+ * experimental-a2/scheduler-vercel — queue-backed scheduler over Vercel Queues.
10
+ *
11
+ * `vercelQueues()` returns an `A2Scheduler` (a2-implementation.md §9):
12
+ *
13
+ * - drain tasks round the requested watchdog time up to a one-second slot.
14
+ * One message per `(topic, contract, session, dueAt)` coalesces appends,
15
+ * claim renewals and racing callbacks. `DuplicateMessageError` is
16
+ * success because that due-time slot is already durable.
17
+ * - append tasks hash their stable task id with the topic for provider
18
+ * deduplication. Their six-day maximum delay leaves a full day for
19
+ * delivery and retries inside the provider's seven-day retention.
20
+ * They target the publishing deployment unless explicitly configured
21
+ * as deploymentless. Drain tasks always remain deployment-scoped.
22
+ * - `handler(...servers)` is the delivery route: look up the server for
23
+ * the contract named in the message and drain it. Settled drains ack;
24
+ * contention arms a later watchdog before acking; handler failure keeps
25
+ * the current message and redelivers with backoff.
26
+ *
27
+ * `@vercel/queue` is an optional peer dependency, imported lazily. The
28
+ * `transport` option is the injection seam — tests run a real little
29
+ * in-memory queue through the same interface.
30
+ */
31
+ /**
32
+ * The "not settled yet" signal for a stalled handler — an expected state,
33
+ * not a transport failure. The default transport classifies it in
34
+ * `@vercel/queue`'s `retry` option and reschedules the delivery quietly
35
+ * (`{ afterSeconds }` → visibility change → 200 response, no error log)
36
+ * instead of letting it surface as a thrown 500. Busy deliveries use a
37
+ * fresh watchdog instead. Custom transports should treat this class the
38
+ * same way when their protocol has a polite reschedule.
39
+ */
40
+ var DrainUnsettled = class extends Error {};
41
+ /** Vercel Queues rejects shorter visibility changes. */
42
+ const MIN_VISIBILITY_SECONDS = 30;
43
+ /** Vercel Queues' maximum message retention and delivery delay. */
44
+ const MAX_RETENTION_SECONDS = 604800;
45
+ /** Leave the final retention day for delivery and retries. */
46
+ const MAX_DELAY_SECONDS = 518400;
47
+ const TOPIC_PATTERN = /^[A-Za-z0-9_-]+$/;
48
+ const RETRYABLE_HTTP_CLIENT_STATUSES = /* @__PURE__ */ new Set([
49
+ 408,
50
+ 409,
51
+ 425,
52
+ 429
53
+ ]);
54
+ /** The SDK's send path maps these statuses to name-only error instances. */
55
+ const TERMINAL_VERCEL_SEND_ERROR_NAMES = /* @__PURE__ */ new Set([
56
+ "BadRequestError",
57
+ "UnauthorizedError",
58
+ "ForbiddenError"
59
+ ]);
60
+ const recordOf = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
61
+ const httpStatusOf = (error) => {
62
+ try {
63
+ const record = recordOf(error);
64
+ if (!record) return void 0;
65
+ const response = recordOf(record["response"]);
66
+ const statuses = [
67
+ record["status"],
68
+ record["statusCode"],
69
+ response?.["status"]
70
+ ].filter((value) => typeof value === "number" && Number.isInteger(value) && value >= 100 && value <= 599);
71
+ const [status] = statuses;
72
+ if (status === void 0) return void 0;
73
+ return statuses.every((candidate) => candidate === status) ? status : void 0;
74
+ } catch {
75
+ return;
76
+ }
77
+ };
78
+ const errorNameOf = (error) => {
79
+ try {
80
+ const name = recordOf(error)?.["name"];
81
+ return typeof name === "string" ? name : void 0;
82
+ } catch {
83
+ return;
84
+ }
85
+ };
86
+ const classifyVercelSendFailure = (error) => {
87
+ const status = httpStatusOf(error);
88
+ const terminal = status === void 0 ? TERMINAL_VERCEL_SEND_ERROR_NAMES.has(errorNameOf(error) ?? "") : status >= 400 && status < 500 && !RETRYABLE_HTTP_CLIENT_STATUSES.has(status);
89
+ return classifySchedulerSendFailure(error, terminal ? "terminal" : "retryable");
90
+ };
91
+ const digestId = (parts) => `a2_${createHash("sha256").update(JSON.stringify(parts)).digest("hex")}`;
92
+ /** Base of the unsettled redelivery backoff, doubled per delivery. */
93
+ const UNSETTLED_BACKOFF_BASE_SECONDS = 5;
94
+ /** Redelivery backoff for retry states: base, 2×, 4×… bounded. */
95
+ const unsettledBackoffSeconds = (deliveryCount) => Math.min(Math.max(UNSETTLED_BACKOFF_BASE_SECONDS * 2 ** Math.max(deliveryCount - 1, 0), MIN_VISIBILITY_SECONDS), 60);
96
+ const vercelQueueTransport = async () => {
97
+ const queue = await import("@vercel/queue").catch(() => {
98
+ throw classifySchedulerSendFailure(/* @__PURE__ */ new Error("experimental-a2/scheduler-vercel needs the '@vercel/queue' package (optional peer dependency) — install it, or inject a transport"), "terminal");
99
+ });
100
+ const deploymentClient = new queue.QueueClient();
101
+ const deploymentlessClient = new queue.QueueClient({ deploymentId: null });
102
+ return {
103
+ send: (topic, message, options, routing) => {
104
+ const deployment = routing?.deployment ?? "deployment";
105
+ const body = {
106
+ ...message,
107
+ _a2Vercel: {
108
+ version: 1,
109
+ deployment
110
+ }
111
+ };
112
+ return (deployment === "deploymentless" ? deploymentlessClient : deploymentClient).send(topic, body, options);
113
+ },
114
+ handleCallback: (handler) => {
115
+ const callbackOptions = {
116
+ visibilityTimeoutSeconds: MIN_VISIBILITY_SECONDS,
117
+ retry: (error, metadata) => error instanceof DrainUnsettled ? { afterSeconds: unsettledBackoffSeconds(metadata.deliveryCount) } : void 0
118
+ };
119
+ const deploymentHandler = deploymentClient.handleCallback(handler, callbackOptions);
120
+ const deploymentlessHandler = deploymentlessClient.handleCallback(handler, callbackOptions);
121
+ return async (req) => {
122
+ let delivered;
123
+ try {
124
+ delivered = await req.clone().json();
125
+ } catch {
126
+ return deploymentlessHandler(req);
127
+ }
128
+ const metadata = recordOf(recordOf(delivered)?.["_a2Vercel"]);
129
+ return (metadata?.["version"] === 1 ? metadata["deployment"] : void 0) === "deployment" ? deploymentHandler(req) : deploymentlessHandler(req);
130
+ };
131
+ },
132
+ isDuplicate: (error) => error instanceof queue.DuplicateMessageError
133
+ };
134
+ };
135
+ function vercelQueues(options = {}) {
136
+ const topic = options.topic ?? "a2";
137
+ if (typeof topic !== "string" || !TOPIC_PATTERN.test(topic)) throw new TypeError("vercelQueues() topic must match [A-Za-z0-9_-]+");
138
+ const scheduledAppends = options.scheduledAppends ?? "deployment";
139
+ if (scheduledAppends !== "deployment" && scheduledAppends !== "deploymentless") throw new TypeError("vercelQueues() scheduledAppends must be 'deployment' or 'deploymentless'");
140
+ const clock = options.clock ?? SYSTEM_CLOCK;
141
+ const transport = retryableLazy(() => options.transport ? Promise.resolve(options.transport) : vercelQueueTransport()).get;
142
+ const sendTask = async (task) => {
143
+ const nowMs = clock.now().getTime();
144
+ const requestedDueAt = task.dueAt;
145
+ if (!Number.isFinite(requestedDueAt)) throw classifySchedulerSendFailure(/* @__PURE__ */ new TypeError("vercel scheduler dueAt must be a finite number"), "terminal");
146
+ const dueAt = requestedDueAt <= nowMs ? Math.floor(nowMs / 1e3) * 1e3 : Math.ceil(requestedDueAt / 1e3) * 1e3;
147
+ const deliveryTargetAt = task.kind === "append" ? requestedDueAt : dueAt;
148
+ const deliveryDelaySeconds = Math.max(0, Math.ceil((deliveryTargetAt - nowMs) / 1e3));
149
+ if (deliveryDelaySeconds > MAX_DELAY_SECONDS) throw classifySchedulerSendFailure(/* @__PURE__ */ new RangeError("vercelQueues() tasks cannot be delayed more than 6 days"), "terminal");
150
+ const deployment = task.kind === "append" ? scheduledAppends : "deployment";
151
+ const message = {
152
+ ...task,
153
+ dueAt
154
+ };
155
+ const idempotencyKey = task.kind === "drain" ? digestId([
156
+ "a2:scheduler-vercel:drain:v1",
157
+ topic,
158
+ task.contract,
159
+ task.sessionId,
160
+ String(dueAt)
161
+ ]) : digestId([
162
+ "a2:scheduler-vercel:append:v1",
163
+ topic,
164
+ task.id
165
+ ]);
166
+ const t = await transport();
167
+ try {
168
+ await t.send(topic, message, {
169
+ delaySeconds: deliveryDelaySeconds,
170
+ idempotencyKey,
171
+ retentionSeconds: MAX_RETENTION_SECONDS
172
+ }, { deployment });
173
+ } catch (err) {
174
+ if (t.isDuplicate(err)) return;
175
+ throw classifyVercelSendFailure(err);
176
+ }
177
+ };
178
+ const successorDueAt = (message) => {
179
+ const minimumDueAt = clock.now().getTime() + DRAIN_TIMINGS.claimTtlMs + DRAIN_TIMINGS.watchdogGraceMs;
180
+ const beats = Math.max(1, Math.ceil((minimumDueAt - message.dueAt) / DRAIN_TIMINGS.claimHeartbeatMs));
181
+ return message.dueAt + beats * DRAIN_TIMINGS.claimHeartbeatMs;
182
+ };
183
+ return {
184
+ async schedule(task) {
185
+ await sendTask(task);
186
+ },
187
+ handler(...servers) {
188
+ assertSchedulerTargets(servers, { allowStructural: true });
189
+ const byContract = /* @__PURE__ */ new Map();
190
+ for (const server of servers) byContract.set(server.contract.name, server);
191
+ return async (req) => {
192
+ return (await transport()).handleCallback(async (delivered) => {
193
+ const task = normalizeSchedulerTask(delivered);
194
+ if (!task) throw new TypeError("a2 scheduler received an invalid task");
195
+ const server = byContract.get(task.contract);
196
+ if (!server) throw new Error(`a2 scheduler: no server for contract '${task.contract}' — pass it to schedulerHandler(...)`);
197
+ const internals = serverInternals.get(server);
198
+ if (task.kind === "append") {
199
+ await deliverSchedulerAppend(server, task);
200
+ return;
201
+ }
202
+ const nextDueAt = successorDueAt(task);
203
+ const result = internals ? await internals.schedulerDrain(task.sessionId, { watchdogDueAt: nextDueAt }) : {
204
+ ...await server.drain(task.sessionId),
205
+ outcome: "unknown"
206
+ };
207
+ if (result.settled) return;
208
+ if (result.outcome === "busy") {
209
+ if (result.schedulerArm) await result.schedulerArm;
210
+ else await sendTask({
211
+ version: 1,
212
+ kind: "drain",
213
+ contract: task.contract,
214
+ sessionId: task.sessionId,
215
+ dueAt: nextDueAt
216
+ });
217
+ return;
218
+ }
219
+ throw new DrainUnsettled(`a2 scheduler: session '${task.sessionId}' of '${task.contract}' not settled yet (${result.outcome}) — rescheduled for redelivery`);
220
+ })(req);
221
+ };
222
+ }
223
+ };
224
+ }
225
+ //#endregion
226
+ export { DrainUnsettled, vercelQueues };