@deepseek-ai/dsh-session-store 0.0.0-stage → 0.2.3-alpha.4

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.
@@ -0,0 +1,345 @@
1
+ /**
2
+ * Capability-independent tool history for request projection: the tool
3
+ * declarations in force for a Session and the developer-message updates that
4
+ * record historical additions. `Session.toolHistory()` evaluates
5
+ * {@link toolHistoryStateDefinition} over the Session's data and asks
6
+ * {@link snapshotToolHistory} for the snapshot.
7
+ *
8
+ * States are plain data that survives `JSON.stringify` and `JSON.parse`
9
+ * unchanged. Each distinct tool definition is kept once in `pool`; every other
10
+ * field refers to a definition by its index in that array. `advanceToolHistory`
11
+ * forks a plain copy of a state and `transitions.apply` updates that copy in
12
+ * place; freezing the snapshot belongs to the reader.
13
+ *
14
+ * @module @deepseek-ai/dsh-session-store/tool-history
15
+ */
16
+
17
+ import type { MessageId, ToolHistory, ToolSchema } from '@deepseek-ai/dsh-llm'
18
+ import type { SessionEvent, SessionSeq } from '@deepseek-ai/dsh-session'
19
+ import type { SessionStateDefinition } from '@deepseek-ai/dsh-session-data'
20
+
21
+ /** Newest-first immutable chain of committed headers, each recording its tool list as pool indexes; one node per `request/header` event. */
22
+ interface HeaderLink {
23
+ readonly seq: SessionSeq
24
+ readonly tools: readonly number[]
25
+ readonly prev: HeaderLink | undefined
26
+ }
27
+
28
+ /** One developer-message update recorded by pool indexes: its durable message id and the definitions it adds. */
29
+ interface StoredUpdate {
30
+ readonly messageId: MessageId
31
+ readonly additions: readonly number[]
32
+ }
33
+
34
+ /** Baseline tool indexes of the current declaration series and the updates recorded since it started, in log order. */
35
+ interface SeriesHistory {
36
+ readonly tools: readonly number[]
37
+ readonly updates: readonly StoredUpdate[]
38
+ }
39
+
40
+ /**
41
+ * One state of the tool-history fold: plain data with no methods and no
42
+ * Map/Set, so `JSON.parse(JSON.stringify(state))` is the same state a fold
43
+ * would produce. A state returned to a reader is never modified again;
44
+ * transitions write only to a fresh copy.
45
+ */
46
+ export interface ToolHistoryState {
47
+ /** Every distinct tool definition seen so far, stored once, as received; the same JSON text always maps to the same index. */
48
+ pool: readonly ToolSchema[]
49
+ /** Committed headers, newest first; additions may reference any earlier header by sequence number. */
50
+ headers: HeaderLink | undefined
51
+ /** Definitions retained in the current declaration series, including removed tools,
52
+ * recorded as tool name to the pool index of its latest declaration. */
53
+ declared: Record<string, number>
54
+ /** Pool indexes of the active definitions from the latest request header. */
55
+ active: readonly number[]
56
+ /** Active names reconstructed from the baseline and recorded updates. */
57
+ available: string[]
58
+ /** Header that starts the current declaration series; absent before the first header. */
59
+ baselineSeq: SessionSeq | undefined
60
+ /** Baseline and resolved updates of the current series, recorded by pool indexes. */
61
+ history: SeriesHistory
62
+ }
63
+
64
+ /**
65
+ * Read a committed header by sequence number.
66
+ * @param head - newest node of the header chain.
67
+ * @param seq - sequence number the developer message referenced.
68
+ * @returns the header's node, or undefined when no committed header has that sequence number.
69
+ */
70
+ function headerAt(head: HeaderLink | undefined, seq: SessionSeq): HeaderLink | undefined {
71
+ // Links are ordered newest first, so the walk ends at the first header older than the reference.
72
+ for (let node = head; node !== undefined && node.seq >= seq; node = node.prev) {
73
+ if (node.seq === seq) return node
74
+ }
75
+ return undefined
76
+ }
77
+
78
+ /** Content index of one pool array: the JSON text of every definition and the reverse lookup used while interning. */
79
+ interface PoolIndex {
80
+ readonly texts: readonly string[]
81
+ readonly ids: ReadonlyMap<string, number>
82
+ }
83
+
84
+ /** Content indexes of pool arrays, built on first use. A cache only: losing it costs time, never behavior. */
85
+ const poolIndexes = new WeakMap<readonly ToolSchema[], PoolIndex>()
86
+
87
+ /**
88
+ * Get the content index of a pool, deriving it from the definitions when absent.
89
+ * @param pool - a state's pool.
90
+ * @returns the JSON text of each pooled definition and the text-to-index lookup.
91
+ */
92
+ function indexOfPool(pool: readonly ToolSchema[]): PoolIndex {
93
+ let index = poolIndexes.get(pool)
94
+ if (index === undefined) {
95
+ const texts = pool.map(tool => JSON.stringify(tool))
96
+ index = { texts, ids: new Map(texts.map((text, id) => [text, id])) }
97
+ poolIndexes.set(pool, index)
98
+ }
99
+ return index
100
+ }
101
+
102
+ /** Result of pooling one header's declared tools. */
103
+ interface InternedTools {
104
+ readonly pool: readonly ToolSchema[]
105
+ readonly ids: readonly number[]
106
+ readonly texts: readonly string[]
107
+ }
108
+
109
+ /**
110
+ * Store definitions that are not in the pool yet and return the pool indexes of the whole list.
111
+ * @param pool - the pool before this header.
112
+ * @param tools - definitions declared by the header, in declaration order.
113
+ * @returns the pool, extended if a definition is new; one index and one JSON text per declared tool.
114
+ */
115
+ function internTools(pool: readonly ToolSchema[], tools: readonly ToolSchema[]): InternedTools {
116
+ let index = indexOfPool(pool)
117
+ let extended: ToolSchema[] | undefined
118
+ const texts: string[] = []
119
+ const ids = tools.map((tool) => {
120
+ const text = JSON.stringify(tool)
121
+ texts.push(text)
122
+ let id = index.ids.get(text)
123
+ if (id === undefined) {
124
+ id = (extended ?? pool).length
125
+ extended ??= [...pool]
126
+ extended.push(tool)
127
+ index = { texts: [...index.texts, text], ids: new Map(index.ids).set(text, id) }
128
+ poolIndexes.set(extended, index)
129
+ }
130
+ return id
131
+ })
132
+ return { pool: extended ?? pool, ids, texts }
133
+ }
134
+
135
+ /**
136
+ * Create an empty name-to-index record without a prototype, so any tool name is a plain key.
137
+ * @returns the record.
138
+ */
139
+ function emptyDeclarations(): Record<string, number> {
140
+ return Object.create(null) as Record<string, number>
141
+ }
142
+
143
+ /**
144
+ * Copy a declarations record before a transition adds to it.
145
+ * @param declared - the record published by the previous state.
146
+ * @returns a new record with the same entries.
147
+ */
148
+ function copyDeclarations(declared: Record<string, number>): Record<string, number> {
149
+ return Object.assign(emptyDeclarations(), declared)
150
+ }
151
+
152
+ /**
153
+ * Record which pool definition each declared tool name currently means.
154
+ * @param tools - declared definitions in order; a repeated name keeps its last declaration.
155
+ * @param ids - pool indexes of `tools`, one per entry.
156
+ * @returns a name-to-index record without a prototype.
157
+ */
158
+ function declarationsOf(tools: readonly ToolSchema[], ids: readonly number[]): Record<string, number> {
159
+ const declared = emptyDeclarations()
160
+ tools.forEach((tool, position) => { declared[tool.name] = ids[position] as number })
161
+ return declared
162
+ }
163
+
164
+ /**
165
+ * Read one pooled definition by index.
166
+ * @param pool - a state's pool.
167
+ * @param id - an index produced by interning.
168
+ * @returns the definition stored at that index.
169
+ */
170
+ function definitionAt(pool: readonly ToolSchema[], id: number): ToolSchema {
171
+ const tool = pool[id]
172
+ /* v8 ignore next -- indexes come from interning the same pool. */
173
+ if (tool === undefined) throw new Error(`tool history state: no definition at pool index ${id}`)
174
+ return tool
175
+ }
176
+
177
+ /**
178
+ * Turn pool indexes into the definitions a reader receives.
179
+ * @param pool - the state's pool.
180
+ * @param ids - indexes into that pool.
181
+ * @returns the definitions in the same order.
182
+ */
183
+ function lookupTools(pool: readonly ToolSchema[], ids: readonly number[]): readonly ToolSchema[] {
184
+ return ids.map(id => definitionAt(pool, id))
185
+ }
186
+
187
+ /** Materialized series histories, keyed by the state's `history` object; a cache only, never part of a state. */
188
+ const historyViews = new WeakMap<SeriesHistory, ToolHistory>()
189
+ /** Materialized fallback views, keyed by the active index list; a cache only, never part of a state. */
190
+ const fallbackViews = new WeakMap<readonly number[], ToolHistory>()
191
+
192
+ /** Signatures of the two operations below; `ThisType` gives their bodies the state as `this`. */
193
+ type Transition = {
194
+ apply(event: SessionEvent<'request/header' | 'developer/message'>): void
195
+ snapshot(): ToolHistory
196
+ } & ThisType<ToolHistoryState>
197
+
198
+ /** Folds committed headers and developer messages independently of model capability. */
199
+ const transitions = {
200
+ /**
201
+ * Consume the next committed event in log order.
202
+ * @param event - a session event, including inherited events during restoration.
203
+ */
204
+ apply(event: SessionEvent<'request/header' | 'developer/message'>): void {
205
+ if (event.type === 'request/header') {
206
+ const tools = event.data.header.tools ?? []
207
+ const interned = internTools(this.pool, tools)
208
+ this.pool = interned.pool
209
+ this.headers = { seq: event.seq, tools: interned.ids, prev: this.headers }
210
+ // A retained name cannot acquire a different definition without losing
211
+ // prefix reuse; an unchanged restored name is re-offered by its recorded addition.
212
+ const pooled = indexOfPool(this.pool).texts
213
+ const redeclared = tools.some((tool, position) => {
214
+ // A state read back from JSON has an ordinary prototype, so only own names record declarations.
215
+ const before = Object.hasOwn(this.declared, tool.name) ? this.declared[tool.name] : undefined
216
+ return before !== undefined && pooled[before] !== interned.texts[position]
217
+ })
218
+ if (this.baselineSeq === undefined || event.data.reason === 'series' || event.data.startsSeries || redeclared) {
219
+ this.baselineSeq = event.seq
220
+ this.declared = declarationsOf(tools, interned.ids)
221
+ this.history = { tools: interned.ids, updates: [] }
222
+ this.available = [...new Set(tools.map(tool => tool.name))]
223
+ }
224
+ this.active = interned.ids
225
+ } else {
226
+ const { message, headerSeq } = event.data
227
+ const declaredBy = headerSeq === undefined ? undefined : headerAt(this.headers, headerSeq)
228
+ const additions = message.content.flatMap((block) => {
229
+ if (block.type !== 'tool-addition') return []
230
+ const id = declaredBy?.tools.find(id => definitionAt(this.pool, id).name === block.toolName)
231
+ if (id === undefined) throw new Error(`tool history: missing definition for ${block.toolName}`)
232
+ return [id]
233
+ })
234
+ // The fields published by earlier states stay untouched: this message writes to copies.
235
+ if (additions.length > 0) {
236
+ this.declared = copyDeclarations(this.declared)
237
+ for (const id of additions) this.declared[definitionAt(this.pool, id).name] = id
238
+ }
239
+ this.available = [...this.available]
240
+ for (const block of message.content) {
241
+ if (block.type === 'tool-addition' && !this.available.includes(block.toolName)) this.available.push(block.toolName)
242
+ else if (block.type === 'tool-removal') this.available = this.available.filter(name => name !== block.toolName)
243
+ }
244
+ this.history = {
245
+ tools: this.history.tools,
246
+ updates: [...this.history.updates, { messageId: message.id, additions }],
247
+ }
248
+ }
249
+ },
250
+
251
+ /**
252
+ * Read a snapshot; later transitions do not mutate the returned object.
253
+ * @returns initial declarations and historically resolved additions for the current series.
254
+ */
255
+ snapshot(): ToolHistory {
256
+ const activeNames = this.active.map(id => definitionAt(this.pool, id).name)
257
+ // Sessions written before tool-update emission have headers without matching updates.
258
+ if (activeNames.length !== this.available.length || activeNames.some(name => !this.available.includes(name))) {
259
+ let view = fallbackViews.get(this.active)
260
+ if (view === undefined) {
261
+ view = { tools: lookupTools(this.pool, this.active), updates: [] }
262
+ fallbackViews.set(this.active, view)
263
+ }
264
+ return view
265
+ }
266
+ let view = historyViews.get(this.history)
267
+ if (view === undefined) {
268
+ view = {
269
+ tools: lookupTools(this.pool, this.history.tools),
270
+ updates: this.history.updates.map(update => ({ messageId: update.messageId, additions: lookupTools(this.pool, update.additions) })),
271
+ }
272
+ historyViews.set(this.history, view)
273
+ }
274
+ return view
275
+ },
276
+ } satisfies Transition
277
+
278
+ /**
279
+ * Create the state before any event.
280
+ * @returns an empty fold with no header, an empty pool and an empty history.
281
+ */
282
+ function createToolHistoryState(): ToolHistoryState {
283
+ return {
284
+ pool: [],
285
+ headers: undefined,
286
+ declared: emptyDeclarations(),
287
+ active: [],
288
+ available: [],
289
+ baselineSeq: undefined,
290
+ history: { tools: [], updates: [] },
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Copy a state so that one transition can update the copy in place.
296
+ * @param state - the published state being advanced.
297
+ * @returns a plain state sharing every field the transition does not replace.
298
+ */
299
+ function fork(state: ToolHistoryState): ToolHistoryState {
300
+ return {
301
+ pool: state.pool,
302
+ headers: state.headers,
303
+ declared: state.declared,
304
+ active: state.active,
305
+ available: state.available,
306
+ baselineSeq: state.baselineSeq,
307
+ history: state.history,
308
+ }
309
+ }
310
+
311
+ /**
312
+ * Advance the fold by one committed event.
313
+ * @param state - state covering all prior events.
314
+ * @param event - the next committed event.
315
+ * @returns the next state, or `state` itself for an event type the fold does not read.
316
+ * @throws Error when a developer message adds a tool that the committed header it references did not declare.
317
+ */
318
+ export function advanceToolHistory(state: ToolHistoryState, event: SessionEvent): ToolHistoryState {
319
+ if (event.type !== 'request/header' && event.type !== 'developer/message') return state
320
+ const next = fork(state)
321
+ transitions.apply.call(next, event)
322
+ return next
323
+ }
324
+
325
+ /**
326
+ * Read the tool history a state implies; freezing the result is the caller's job.
327
+ * @param state - a state returned by {@link advanceToolHistory} or by the definition's `init`, also after a JSON round trip.
328
+ * @returns the series history while its baseline and updates account for every active declaration,
329
+ * otherwise the complete active declarations with no updates. Definitions are the pool's objects.
330
+ */
331
+ export function snapshotToolHistory(state: ToolHistoryState): ToolHistory {
332
+ return transitions.snapshot.call(state)
333
+ }
334
+
335
+ /**
336
+ * State definition that `Session.toolHistory()` reads: the active tool
337
+ * declarations of the current series with the additions recorded by developer
338
+ * messages, or the complete active declarations alone while the latest header
339
+ * lacks its update record. Before the first header the history is empty.
340
+ */
341
+ export const toolHistoryStateDefinition = {
342
+ key: 'toolHistory',
343
+ init: createToolHistoryState,
344
+ apply: advanceToolHistory,
345
+ } satisfies SessionStateDefinition<'toolHistory', ToolHistoryState>
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Complete session log validation without constructing a Session.
3
+ * @module @deepseek-ai/dsh-session-store/validation
4
+ */
5
+
6
+ import { checkSessionLog, SessionLogOffset } from '@deepseek-ai/dsh-session'
7
+ import type { SessionEvent, SessionHeader, SessionMessageProjection, SessionSeedEventState, SurfaceTransitionValidator } from '@deepseek-ai/dsh-session'
8
+ import { SurfaceManager } from './surface.ts'
9
+
10
+ /**
11
+ * Admit one validated event through the surface transition.
12
+ * @param event - validated event at `index`, not yet in the log `surface` reads.
13
+ * @param index - position in the log being replayed.
14
+ * @param surface - incremental surface validator carrying the message interpreters.
15
+ * @throws `invalid seed event at index <index>: …` when the surface rejects the event.
16
+ */
17
+ function replaySurfaceEvent(event: SessionEvent, index: number, surface: SurfaceTransitionValidator): void {
18
+ // Replay accepts events incrementally through the same transition as a live
19
+ // append and a full-log fold. The candidate is planned before it enters
20
+ // `log`, so a failure cannot partially mutate the surface.
21
+ try {
22
+ surface.validateNext(event)
23
+ } catch (error: unknown) {
24
+ throw new Error(`invalid seed event at index ${index}: ${error instanceof Error ? error.message : 'invalid surface metadata'}`)
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Replay validated events through the surface in order and push each accepted event into `log`, which `surface` reads.
30
+ * Each event passes the surface transition before it enters `log`.
31
+ * @param events - events accepted by `checkSessionLog`.
32
+ * @param log - empty log that `surface` was constructed over.
33
+ * @param surface - incremental surface validator carrying the message interpreters.
34
+ * @throws on the first invalid surface transition; `log` then holds the accepted prefix.
35
+ */
36
+ export function replaySurfaceEvents(
37
+ events: readonly SessionEvent[],
38
+ log: SessionEvent[],
39
+ surface: SurfaceManager,
40
+ ): void {
41
+ for (const [index, event] of events.entries()) {
42
+ replaySurfaceEvent(event, index, surface)
43
+ log.push(event)
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Validate a header and event log without constructing a Session. It runs the
49
+ * two stages Session construction runs: first the structural checks on the
50
+ * header, event envelopes, sequences, and inherited cut, then surface replay
51
+ * in event order. Because the stages do not interleave, a log with several
52
+ * invalid points can report a different first error than an interleaved
53
+ * per-event check.
54
+ * Without `eventState` the checks use the borrowed seed mode: events and header
55
+ * are copied before validation. With it they validate and deeply freeze
56
+ * `header` in place and leave events uncopied.
57
+ * Embedded Assistant streams are not replayed.
58
+ * @param header - header whose `id` is the Session identity.
59
+ * @param events - seed events; omitted means no seed.
60
+ * @param inheritedEventCount - exact fork-inherited prefix length; required when `header.isSeeded`.
61
+ * @param eventState - aliasing state of adopted events; omitted for borrowed events.
62
+ * @param projections - message interpreters for plugin-owned events.
63
+ * @throws on the first invalid header field, event envelope, sequence, or inherited cut, then on the first invalid surface transition.
64
+ */
65
+ export function validateSessionLog(
66
+ header: SessionHeader,
67
+ events?: readonly SessionEvent[],
68
+ inheritedEventCount?: SessionLogOffset,
69
+ eventState?: SessionSeedEventState,
70
+ projections: readonly SessionMessageProjection[] = [],
71
+ ): void {
72
+ const checked = checkSessionLog(header.id, header, events, inheritedEventCount, eventState ?? 'snapshot')
73
+ const log: SessionEvent[] = []
74
+ replaySurfaceEvents(checked.events, log, new SurfaceManager(log, SessionLogOffset(0), projections))
75
+ }