experimental-a2 0.13.0 → 0.14.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 (99) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/{actor-DJi3RsNu.d.ts → actor-BfQSE0KC.d.ts} +4 -4
  3. package/dist/{actor-DJi3RsNu.d.ts.map → actor-BfQSE0KC.d.ts.map} +1 -1
  4. package/dist/actor-client.d.ts +1 -1
  5. package/dist/actor-client.js +1 -1
  6. package/dist/actor-react.d.ts +3 -3
  7. package/dist/actor-react.js +2 -2
  8. package/dist/{actor-shared-DI7J5upy.js → actor-shared-B5tJfzt-.js} +2 -2
  9. package/dist/{actor-shared-DI7J5upy.js.map → actor-shared-B5tJfzt-.js.map} +1 -1
  10. package/dist/actor.d.ts +1 -1
  11. package/dist/actor.js +3 -3
  12. package/dist/ai-Cai-lCbj.d.ts +580 -0
  13. package/dist/ai-Cai-lCbj.d.ts.map +1 -0
  14. package/dist/ai-control-CcD4hh3y.js +119 -0
  15. package/dist/ai-control-CcD4hh3y.js.map +1 -0
  16. package/dist/ai-server.d.ts +6 -6
  17. package/dist/ai-server.d.ts.map +1 -1
  18. package/dist/ai-server.js +1014 -501
  19. package/dist/ai-server.js.map +1 -1
  20. package/dist/ai.d.ts +2 -365
  21. package/dist/ai.js +801 -80
  22. package/dist/ai.js.map +1 -1
  23. package/dist/{client-P_NNNRM-.d.ts → client-BAEABRZB.d.ts} +2 -2
  24. package/dist/{client-P_NNNRM-.d.ts.map → client-BAEABRZB.d.ts.map} +1 -1
  25. package/dist/{client-Bf6uSEAk.js → client-BYzHjkwU.js} +21 -6
  26. package/dist/client-BYzHjkwU.js.map +1 -0
  27. package/dist/client.d.ts +1 -1
  28. package/dist/client.js +1 -1
  29. package/dist/{contract-48bUMgcL.js → contract-CKRg_E4q.js} +3 -26
  30. package/dist/contract-CKRg_E4q.js.map +1 -0
  31. package/dist/index.d.ts +2 -2
  32. package/dist/index.js +1 -1
  33. package/dist/react.d.ts +2 -2
  34. package/dist/react.js +1 -1
  35. package/dist/{reducer-DJKWm3cp.d.ts → reducer-BcS9VDKC.d.ts} +4 -1
  36. package/dist/{reducer-DJKWm3cp.d.ts.map → reducer-BcS9VDKC.d.ts.map} +1 -1
  37. package/dist/reducer-DEMjEY_O.js +29 -0
  38. package/dist/reducer-DEMjEY_O.js.map +1 -0
  39. package/dist/scheduler-qstash.d.ts +2 -2
  40. package/dist/scheduler-qstash.js +1 -1
  41. package/dist/scheduler-vercel.d.ts +2 -2
  42. package/dist/scheduler-vercel.js +1 -1
  43. package/dist/{server-DjZZa1wr.d.ts → server-Bp5Nd1pF.d.ts} +3 -3
  44. package/dist/{server-DjZZa1wr.d.ts.map → server-Bp5Nd1pF.d.ts.map} +1 -1
  45. package/dist/{server-BeNADlCI.js → server-CjJSGcF7.js} +4 -3
  46. package/dist/server-CjJSGcF7.js.map +1 -0
  47. package/dist/server.d.ts +3 -3
  48. package/dist/server.js +1 -1
  49. package/dist/{store-DtDOWLSn.d.ts → store-D_yhNdPz.d.ts} +7 -2
  50. package/dist/{store-DtDOWLSn.d.ts.map → store-D_yhNdPz.d.ts.map} +1 -1
  51. package/dist/store-N8PXxDAS.js.map +1 -1
  52. package/dist/store-memory.d.ts +1 -1
  53. package/dist/store-postgres.d.ts +1 -1
  54. package/dist/store-postgres.js +19 -0
  55. package/dist/store-postgres.js.map +1 -1
  56. package/dist/store-redis-http.d.ts +1 -1
  57. package/dist/store-redis-http.js +1 -1
  58. package/dist/{store-redis-notify-BUCyXOn0.js → store-redis-notify-D2EI6gwX.js} +27 -2
  59. package/dist/store-redis-notify-D2EI6gwX.js.map +1 -0
  60. package/dist/store-redis.d.ts +1 -1
  61. package/dist/store-redis.js +1 -1
  62. package/dist/store-sqlite.d.ts +1 -1
  63. package/docs/guides/06-ai-agents.mdx +265 -62
  64. package/docs/reference/01-api.mdx +122 -27
  65. package/examples/playground/app/agent/[agentId]/agent-client.tsx +118 -21
  66. package/examples/playground/app/agent/[agentId]/agent-queue.tsx +289 -0
  67. package/examples/playground/app/agent/compaction-settings.test.ts +22 -6
  68. package/examples/playground/app/agent/model.ts +11 -2
  69. package/examples/playground/app/agent/server.ts +8 -2
  70. package/examples/playground/app/chat/[chatId]/chat-client.tsx +3 -13
  71. package/examples/playground/app/chat/model.ts +2 -2
  72. package/examples/playground/app/chat/server.ts +24 -17
  73. package/examples/playground/app/globals.css +179 -0
  74. package/examples/playground/package.json +1 -1
  75. package/package.json +1 -1
  76. package/src/ai-client-state.ts +185 -0
  77. package/src/ai-control-server.ts +829 -0
  78. package/src/ai-control-state.ts +152 -0
  79. package/src/ai-control.ts +139 -0
  80. package/src/ai-coordinator.ts +99 -32
  81. package/src/ai-progress-batches.ts +68 -0
  82. package/src/ai-projector.ts +76 -15
  83. package/src/ai-sdk-step.ts +0 -1
  84. package/src/ai-server.ts +381 -608
  85. package/src/ai.ts +553 -108
  86. package/src/client.ts +31 -9
  87. package/src/licenses/Apache-2.0.txt +55 -0
  88. package/src/parse-partial-json.ts +441 -0
  89. package/src/reducer.ts +6 -0
  90. package/src/server.ts +8 -4
  91. package/src/store-postgres.ts +27 -0
  92. package/src/store-redis-core.ts +53 -1
  93. package/src/store-redis-notify.ts +1 -0
  94. package/src/store.ts +6 -0
  95. package/dist/ai.d.ts.map +0 -1
  96. package/dist/client-Bf6uSEAk.js.map +0 -1
  97. package/dist/contract-48bUMgcL.js.map +0 -1
  98. package/dist/server-BeNADlCI.js.map +0 -1
  99. package/dist/store-redis-notify-BUCyXOn0.js.map +0 -1
package/src/client.ts CHANGED
@@ -30,7 +30,7 @@ import type {
30
30
  PresencePatch,
31
31
  WithPresence,
32
32
  } from './contract.ts'
33
- import type { Reducer } from './reducer.ts'
33
+ import { clientStateProjection, type Reducer } from './reducer.ts'
34
34
  import { validateSync } from './validate.ts'
35
35
  import {
36
36
  errorFromWire,
@@ -1434,7 +1434,7 @@ export function createClient<
1434
1434
  .filter((p) => p.acked)
1435
1435
  .map((p) => p.acked!)
1436
1436
  .toSorted((a, b) => a.index - b.index)
1437
- const maxKnown = acked.at(-1)?.index ?? stateIndex
1437
+ const maxKnown = Math.max(stateIndex, acked.at(-1)?.index ?? stateIndex)
1438
1438
  const unacked = pending
1439
1439
  .filter((p) => !p.acked)
1440
1440
  .map(
@@ -1479,10 +1479,25 @@ export function createClient<
1479
1479
  const buildSnapshot = (): SessionSnapshot<D, S, P> => {
1480
1480
  const overlay = overlayEvents()
1481
1481
  let state = foldedState
1482
- for (const event of overlay) state = reducer.fold(state, event)
1482
+ for (const event of overlay) {
1483
+ if (event.index > stateIndex) state = reducer.fold(state, event)
1484
+ }
1485
+ const displayedOverlay = overlay.filter((event) => {
1486
+ if (event.index > stateIndex) return true
1487
+ let low = 0
1488
+ let high = serverEvents.length - 1
1489
+ while (low <= high) {
1490
+ const middle = Math.floor((low + high) / 2)
1491
+ const observed = serverEvents[middle]!
1492
+ if (observed.index === event.index) return observed.id !== event.id
1493
+ if (observed.index < event.index) low = middle + 1
1494
+ else high = middle - 1
1495
+ }
1496
+ return true
1497
+ })
1483
1498
  return {
1484
- state,
1485
- events: [...serverEvents, ...overlay],
1499
+ state: reducer[clientStateProjection]?.(state) ?? state,
1500
+ events: [...serverEvents, ...displayedOverlay],
1486
1501
  index: stateIndex,
1487
1502
  history: historyState(),
1488
1503
  connection: connection(),
@@ -1837,6 +1852,12 @@ export function createClient<
1837
1852
  const entry = pending.find((p) => p.id === event.id)
1838
1853
  if (entry) entry.acked = event // stream retires it at its index
1839
1854
  }
1855
+ pending = pending.filter(
1856
+ (entry) =>
1857
+ entry.acked === undefined ||
1858
+ entry.acked.index >
1859
+ Math.min(stateIndex, streamIndex ?? stateIndex),
1860
+ )
1840
1861
  if ((acked.at(-1)?.index ?? 0) > (streamIndex ?? stateIndex))
1841
1862
  refreshIdleStream()
1842
1863
  notify()
@@ -2219,14 +2240,15 @@ export function createClient<
2219
2240
  return
2220
2241
  }
2221
2242
 
2222
- // The server fold subsumes everything observed through the old
2223
- // state index. Keep later optimistic work overlaid, retiring acked
2224
- // entries the new state index proves are already durable.
2243
+ // State hydration does not subsume delivery: unobserved ACKs still
2244
+ // keep an idle stream catching up even when their state is covered.
2225
2245
  stateIndex = nextIndex
2226
2246
  foldedState = next.initialState
2227
2247
  mergeServerEvents(next.initialEvents, stateIndex)
2228
2248
  pending = pending.filter(
2229
- (entry) => !entry.acked || entry.acked.index > stateIndex,
2249
+ (entry) =>
2250
+ !entry.acked ||
2251
+ entry.acked.index > Math.min(stateIndex, streamIndex ?? stateIndex),
2230
2252
  )
2231
2253
  if (confirmWatchers.some((watcher) => watcher.index <= stateIndex)) {
2232
2254
  const due = confirmWatchers.filter(
@@ -0,0 +1,55 @@
1
+ Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
16
+
17
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
18
+
19
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
20
+
21
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
22
+
23
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
24
+
25
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
26
+
27
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
28
+
29
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
30
+
31
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
32
+
33
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
34
+
35
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
36
+
37
+ You must give any other recipients of the Work or Derivative Works a copy of this License; and
38
+
39
+ You must cause any modified files to carry prominent notices stating that You changed the files; and
40
+
41
+ You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
42
+
43
+ If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,441 @@
1
+ /*!
2
+ * Adapted from AI SDK 7.0.58, packages/ai/src/util/fix-json.ts.
3
+ * Source: https://github.com/vercel/ai, packages/ai/src/util/fix-json.ts.
4
+ * Modified to expose a synchronous partial parser with strict TypeScript types.
5
+ * Also preserves positive exponents in unfinished containers.
6
+ * Copyright 2023 Vercel, Inc.
7
+ * @license Apache-2.0. See src/licenses/Apache-2.0.txt.
8
+ */
9
+
10
+ export function parsePartialJSON(text: string | undefined): unknown {
11
+ if (text === undefined || text.trim() === '') return undefined
12
+ try {
13
+ return JSON.parse(text) as unknown
14
+ } catch {
15
+ try {
16
+ return JSON.parse(repairPartialJSON(text)) as unknown
17
+ } catch {
18
+ return undefined
19
+ }
20
+ }
21
+ }
22
+
23
+ type State =
24
+ | 'ROOT'
25
+ | 'FINISH'
26
+ | 'INSIDE_STRING'
27
+ | 'INSIDE_STRING_ESCAPE'
28
+ | 'INSIDE_STRING_UNICODE_ESCAPE'
29
+ | 'INSIDE_LITERAL'
30
+ | 'INSIDE_NUMBER'
31
+ | 'INSIDE_OBJECT_START'
32
+ | 'INSIDE_OBJECT_KEY'
33
+ | 'INSIDE_OBJECT_AFTER_KEY'
34
+ | 'INSIDE_OBJECT_BEFORE_VALUE'
35
+ | 'INSIDE_OBJECT_AFTER_VALUE'
36
+ | 'INSIDE_OBJECT_AFTER_COMMA'
37
+ | 'INSIDE_ARRAY_START'
38
+ | 'INSIDE_ARRAY_AFTER_VALUE'
39
+ | 'INSIDE_ARRAY_AFTER_COMMA'
40
+
41
+ const isHexDigit = (char: string): boolean =>
42
+ (char >= '0' && char <= '9') ||
43
+ (char >= 'A' && char <= 'F') ||
44
+ (char >= 'a' && char <= 'f')
45
+
46
+ function repairPartialJSON(input: string): string {
47
+ const stack: State[] = ['ROOT']
48
+ let lastValidIndex = -1
49
+ let literalStart: number | null = null
50
+ let unicodeEscapeDigits = 0
51
+
52
+ function processValueStart(char: string, i: number, swapState: State) {
53
+ {
54
+ switch (char) {
55
+ case '"': {
56
+ lastValidIndex = i
57
+ stack.pop()
58
+ stack.push(swapState)
59
+ stack.push('INSIDE_STRING')
60
+ break
61
+ }
62
+
63
+ case 'f':
64
+ case 't':
65
+ case 'n': {
66
+ lastValidIndex = i
67
+ literalStart = i
68
+ stack.pop()
69
+ stack.push(swapState)
70
+ stack.push('INSIDE_LITERAL')
71
+ break
72
+ }
73
+
74
+ case '-': {
75
+ stack.pop()
76
+ stack.push(swapState)
77
+ stack.push('INSIDE_NUMBER')
78
+ break
79
+ }
80
+ case '0':
81
+ case '1':
82
+ case '2':
83
+ case '3':
84
+ case '4':
85
+ case '5':
86
+ case '6':
87
+ case '7':
88
+ case '8':
89
+ case '9': {
90
+ lastValidIndex = i
91
+ stack.pop()
92
+ stack.push(swapState)
93
+ stack.push('INSIDE_NUMBER')
94
+ break
95
+ }
96
+
97
+ case '{': {
98
+ lastValidIndex = i
99
+ stack.pop()
100
+ stack.push(swapState)
101
+ stack.push('INSIDE_OBJECT_START')
102
+ break
103
+ }
104
+
105
+ case '[': {
106
+ lastValidIndex = i
107
+ stack.pop()
108
+ stack.push(swapState)
109
+ stack.push('INSIDE_ARRAY_START')
110
+ break
111
+ }
112
+ }
113
+ }
114
+ }
115
+
116
+ function processAfterObjectValue(char: string, i: number) {
117
+ switch (char) {
118
+ case ',': {
119
+ stack.pop()
120
+ stack.push('INSIDE_OBJECT_AFTER_COMMA')
121
+ break
122
+ }
123
+ case '}': {
124
+ lastValidIndex = i
125
+ stack.pop()
126
+ break
127
+ }
128
+ }
129
+ }
130
+
131
+ function processAfterArrayValue(char: string, i: number) {
132
+ switch (char) {
133
+ case ',': {
134
+ stack.pop()
135
+ stack.push('INSIDE_ARRAY_AFTER_COMMA')
136
+ break
137
+ }
138
+ case ']': {
139
+ lastValidIndex = i
140
+ stack.pop()
141
+ break
142
+ }
143
+ }
144
+ }
145
+
146
+ for (let i = 0; i < input.length; i++) {
147
+ const char = input[i]!
148
+ const currentState = stack[stack.length - 1]
149
+
150
+ switch (currentState) {
151
+ case 'ROOT':
152
+ processValueStart(char, i, 'FINISH')
153
+ break
154
+
155
+ case 'INSIDE_OBJECT_START': {
156
+ switch (char) {
157
+ case '"': {
158
+ stack.pop()
159
+ stack.push('INSIDE_OBJECT_KEY')
160
+ break
161
+ }
162
+ case '}': {
163
+ lastValidIndex = i
164
+ stack.pop()
165
+ break
166
+ }
167
+ }
168
+ break
169
+ }
170
+
171
+ case 'INSIDE_OBJECT_AFTER_COMMA': {
172
+ switch (char) {
173
+ case '"': {
174
+ stack.pop()
175
+ stack.push('INSIDE_OBJECT_KEY')
176
+ break
177
+ }
178
+ }
179
+ break
180
+ }
181
+
182
+ case 'INSIDE_OBJECT_KEY': {
183
+ switch (char) {
184
+ case '"': {
185
+ stack.pop()
186
+ stack.push('INSIDE_OBJECT_AFTER_KEY')
187
+ break
188
+ }
189
+ }
190
+ break
191
+ }
192
+
193
+ case 'INSIDE_OBJECT_AFTER_KEY': {
194
+ switch (char) {
195
+ case ':': {
196
+ stack.pop()
197
+ stack.push('INSIDE_OBJECT_BEFORE_VALUE')
198
+
199
+ break
200
+ }
201
+ }
202
+ break
203
+ }
204
+
205
+ case 'INSIDE_OBJECT_BEFORE_VALUE': {
206
+ processValueStart(char, i, 'INSIDE_OBJECT_AFTER_VALUE')
207
+ break
208
+ }
209
+
210
+ case 'INSIDE_OBJECT_AFTER_VALUE': {
211
+ processAfterObjectValue(char, i)
212
+ break
213
+ }
214
+
215
+ case 'INSIDE_STRING': {
216
+ switch (char) {
217
+ case '"': {
218
+ stack.pop()
219
+ lastValidIndex = i
220
+ break
221
+ }
222
+
223
+ case '\\': {
224
+ stack.push('INSIDE_STRING_ESCAPE')
225
+ break
226
+ }
227
+
228
+ default: {
229
+ lastValidIndex = i
230
+ }
231
+ }
232
+
233
+ break
234
+ }
235
+
236
+ case 'INSIDE_ARRAY_START': {
237
+ switch (char) {
238
+ case ']': {
239
+ lastValidIndex = i
240
+ stack.pop()
241
+ break
242
+ }
243
+
244
+ default: {
245
+ lastValidIndex = i
246
+ processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE')
247
+ break
248
+ }
249
+ }
250
+ break
251
+ }
252
+
253
+ case 'INSIDE_ARRAY_AFTER_VALUE': {
254
+ switch (char) {
255
+ case ',': {
256
+ stack.pop()
257
+ stack.push('INSIDE_ARRAY_AFTER_COMMA')
258
+ break
259
+ }
260
+
261
+ case ']': {
262
+ lastValidIndex = i
263
+ stack.pop()
264
+ break
265
+ }
266
+
267
+ default: {
268
+ lastValidIndex = i
269
+ break
270
+ }
271
+ }
272
+
273
+ break
274
+ }
275
+
276
+ case 'INSIDE_ARRAY_AFTER_COMMA': {
277
+ processValueStart(char, i, 'INSIDE_ARRAY_AFTER_VALUE')
278
+ break
279
+ }
280
+
281
+ case 'INSIDE_STRING_ESCAPE': {
282
+ stack.pop()
283
+
284
+ if (char === 'u') {
285
+ unicodeEscapeDigits = 0
286
+ stack.push('INSIDE_STRING_UNICODE_ESCAPE')
287
+ } else {
288
+ lastValidIndex = i
289
+ }
290
+
291
+ break
292
+ }
293
+
294
+ case 'INSIDE_STRING_UNICODE_ESCAPE': {
295
+ if (isHexDigit(char)) {
296
+ unicodeEscapeDigits++
297
+
298
+ if (unicodeEscapeDigits === 4) {
299
+ stack.pop()
300
+ lastValidIndex = i
301
+ }
302
+ }
303
+
304
+ break
305
+ }
306
+
307
+ case 'INSIDE_NUMBER': {
308
+ switch (char) {
309
+ case '0':
310
+ case '1':
311
+ case '2':
312
+ case '3':
313
+ case '4':
314
+ case '5':
315
+ case '6':
316
+ case '7':
317
+ case '8':
318
+ case '9': {
319
+ lastValidIndex = i
320
+ break
321
+ }
322
+
323
+ case 'e':
324
+ case 'E':
325
+ case '-':
326
+ case '+':
327
+ case '.': {
328
+ break
329
+ }
330
+
331
+ case ',': {
332
+ stack.pop()
333
+
334
+ if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {
335
+ processAfterArrayValue(char, i)
336
+ }
337
+
338
+ if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {
339
+ processAfterObjectValue(char, i)
340
+ }
341
+
342
+ break
343
+ }
344
+
345
+ case '}': {
346
+ stack.pop()
347
+
348
+ if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {
349
+ processAfterObjectValue(char, i)
350
+ }
351
+
352
+ break
353
+ }
354
+
355
+ case ']': {
356
+ stack.pop()
357
+
358
+ if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {
359
+ processAfterArrayValue(char, i)
360
+ }
361
+
362
+ break
363
+ }
364
+
365
+ default: {
366
+ stack.pop()
367
+ break
368
+ }
369
+ }
370
+
371
+ break
372
+ }
373
+
374
+ case 'INSIDE_LITERAL': {
375
+ const partialLiteral = input.substring(literalStart!, i + 1)
376
+
377
+ if (
378
+ !'false'.startsWith(partialLiteral) &&
379
+ !'true'.startsWith(partialLiteral) &&
380
+ !'null'.startsWith(partialLiteral)
381
+ ) {
382
+ stack.pop()
383
+
384
+ if (stack[stack.length - 1] === 'INSIDE_OBJECT_AFTER_VALUE') {
385
+ processAfterObjectValue(char, i)
386
+ } else if (stack[stack.length - 1] === 'INSIDE_ARRAY_AFTER_VALUE') {
387
+ processAfterArrayValue(char, i)
388
+ }
389
+ } else {
390
+ lastValidIndex = i
391
+ }
392
+
393
+ break
394
+ }
395
+ }
396
+ }
397
+
398
+ let result = input.slice(0, lastValidIndex + 1)
399
+
400
+ for (let i = stack.length - 1; i >= 0; i--) {
401
+ const state = stack[i]
402
+
403
+ switch (state) {
404
+ case 'INSIDE_STRING': {
405
+ result += '"'
406
+ break
407
+ }
408
+
409
+ case 'INSIDE_OBJECT_KEY':
410
+ case 'INSIDE_OBJECT_AFTER_KEY':
411
+ case 'INSIDE_OBJECT_AFTER_COMMA':
412
+ case 'INSIDE_OBJECT_START':
413
+ case 'INSIDE_OBJECT_BEFORE_VALUE':
414
+ case 'INSIDE_OBJECT_AFTER_VALUE': {
415
+ result += '}'
416
+ break
417
+ }
418
+
419
+ case 'INSIDE_ARRAY_START':
420
+ case 'INSIDE_ARRAY_AFTER_COMMA':
421
+ case 'INSIDE_ARRAY_AFTER_VALUE': {
422
+ result += ']'
423
+ break
424
+ }
425
+
426
+ case 'INSIDE_LITERAL': {
427
+ const partialLiteral = input.substring(literalStart!, input.length)
428
+
429
+ if ('true'.startsWith(partialLiteral)) {
430
+ result += 'true'.slice(partialLiteral.length)
431
+ } else if ('false'.startsWith(partialLiteral)) {
432
+ result += 'false'.slice(partialLiteral.length)
433
+ } else if ('null'.startsWith(partialLiteral)) {
434
+ result += 'null'.slice(partialLiteral.length)
435
+ }
436
+ }
437
+ }
438
+ }
439
+
440
+ return result
441
+ }
package/src/reducer.ts CHANGED
@@ -2,6 +2,10 @@ import type { ContractEvent, EventDefs, PresenceDefs } from './contract.ts'
2
2
  import type { StandardSchemaV1 } from './standard-schema.ts'
3
3
  import { validateSync } from './validate.ts'
4
4
 
5
+ export const clientStateProjection: unique symbol = Symbol(
6
+ 'a2.clientStateProjection',
7
+ )
8
+
5
9
  /**
6
10
  * A pure fold over a session's events — `(state, event) => state` —
7
11
  * derived from a contract via `contract.reducer(options).fold(fn)`.
@@ -29,6 +33,8 @@ export type Reducer<
29
33
  readonly presence: Readonly<P>
30
34
  readonly fold: (state: S, event: ContractEvent<D>) => S
31
35
  readonly initialState: S
36
+ /** Internal read-side projection. Never used as a fold input or persisted. */
37
+ readonly [clientStateProjection]?: (state: S) => S
32
38
  /**
33
39
  * When present: `initialState` was validated against it at
34
40
  * definition, and any cached fold a2 rehydrates (server snapshots,
package/src/server.ts CHANGED
@@ -944,7 +944,7 @@ export function createServer<
944
944
  const readHistory = async (
945
945
  sessionId: string,
946
946
  bounds?: { gte?: number; lte?: number },
947
- ): Promise<StoredEvent[]> => {
947
+ ): Promise<Event[]> => {
948
948
  const gte = bounds?.gte
949
949
  const lte = bounds?.lte
950
950
  assertHistoryIndex('gte', gte)
@@ -967,7 +967,9 @@ export function createServer<
967
967
  : { afterIndex: Math.max(0, gte - 1) }),
968
968
  ...(lte === undefined ? {} : { throughIndex: lte }),
969
969
  }
970
- const rows = await store.read(nsId(sessionId), readOptions)
970
+ const rows = await (store.readHistory
971
+ ? store.readHistory(nsId(sessionId), readOptions)
972
+ : store.read(nsId(sessionId), readOptions))
971
973
  return rows.filter(
972
974
  (row) =>
973
975
  (gte === undefined || row.index >= gte) &&
@@ -2001,6 +2003,7 @@ export function createServer<
2001
2003
  close(): Promise<void>
2002
2004
  }> => {
2003
2005
  let hub = abortHubs.get(ns)
2006
+ const created = hub === undefined
2004
2007
  if (!hub) hub = createAbortHub(store, ns, trigger.index)
2005
2008
  const activeTypes = new Set<string>()
2006
2009
  for (const active of hub.subscriptions) {
@@ -2022,8 +2025,9 @@ export function createServer<
2022
2025
  }
2023
2026
  hub.subscriptions.add(subscription)
2024
2027
  const needsCatchup =
2025
- trigger.index < hub.startAfter ||
2026
- [...subscription.types].some((type) => !activeTypes.has(type))
2028
+ !created &&
2029
+ (trigger.index < hub.startAfter ||
2030
+ [...subscription.types].some((type) => !activeTypes.has(type)))
2027
2031
  if (needsCatchup) {
2028
2032
  const earlier = await store.read(ns, { afterIndex: trigger.index })
2029
2033
  hub.startAfter = Math.min(hub.startAfter, trigger.index)
@@ -760,6 +760,33 @@ export function postgres(options: PostgresStoreOptions = {}): PostgresStore {
760
760
  })
761
761
  },
762
762
 
763
+ async readHistory(sessionId, opts) {
764
+ return wrap(async () => {
765
+ if (
766
+ opts?.throughIndex !== undefined &&
767
+ opts.throughIndex <= (opts.afterIndex ?? 0)
768
+ )
769
+ return []
770
+ const c = await client()
771
+ const conditions = ['session_id = $1']
772
+ const params: unknown[] = [sessionId]
773
+ if (opts?.afterIndex !== undefined) {
774
+ params.push(opts.afterIndex)
775
+ conditions.push(`idx > $${params.length}`)
776
+ }
777
+ if (opts?.throughIndex !== undefined) {
778
+ params.push(opts.throughIndex)
779
+ conditions.push(`idx <= $${params.length}`)
780
+ }
781
+ const { rows } = await c.query(
782
+ `select session_id, idx, event_id, event_type, payload, created_at
783
+ from a2_events where ${conditions.join(' and ')} order by idx`,
784
+ params,
785
+ )
786
+ return rows.map(toEvent)
787
+ })
788
+ },
789
+
763
790
  async claimAvailable({
764
791
  sessionId,
765
792
  holder,