@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.
package/src/index.ts ADDED
@@ -0,0 +1,773 @@
1
+ /**
2
+ * Event-sourced session service: append-only session log, in-memory store, and
3
+ * the derived LLM message history. Persistence is a plugin concern (subscribe
4
+ * to `session/event`, drain on `session/flush`).
5
+ *
6
+ * @module @deepseek-ai/dsh-session-store
7
+ */
8
+
9
+ import { Context, Service } from '@deepseek-ai/cordis'
10
+ import { deepFreeze, snapshotJsonValue } from '@deepseek-ai/dsh-util-values'
11
+ import { scopeOf, scopeTarget } from '@deepseek-ai/dsh-scope'
12
+ import type { Scoped } from '@deepseek-ai/dsh-scope'
13
+ import type { Message, ToolHistory } from '@deepseek-ai/dsh-llm'
14
+ import {
15
+ needsInheritedSeedMarker,
16
+ SessionLogOffset,
17
+ SessionSeq,
18
+ validateSessionEventData,
19
+ } from '@deepseek-ai/dsh-session'
20
+ import type {
21
+ EpochHeader,
22
+ PluginRecord,
23
+ PluginRecordMap,
24
+ PluginRecordType,
25
+ RequestContext,
26
+ SessionEvent,
27
+ SessionEventInput,
28
+ SessionEventMap,
29
+ SessionEventType,
30
+ SessionConstructionOptions,
31
+ SessionHeader,
32
+ SessionId,
33
+ SessionMessageProjection,
34
+ SessionSurface,
35
+ SurfaceEventType,
36
+ SurfaceIntent,
37
+ } from '@deepseek-ai/dsh-session'
38
+ import type { Session as SessionInterface, SessionStore as SessionStoreInterface } from '@deepseek-ai/dsh-session'
39
+ import type { ReadonlySessionData, SessionData } from '@deepseek-ai/dsh-session-data'
40
+ import { SurfaceManager } from './surface.ts'
41
+ import { requestContextStateDefinition, requestHeaderStateDefinition } from './request-header.ts'
42
+ import { snapshotToolHistory, toolHistoryStateDefinition } from './tool-history.ts'
43
+ import { replaySurfaceEvents } from './validation.ts'
44
+
45
+ export { SessionPreparation } from './preparation.ts'
46
+ export type { SessionPreparationOptions } from './preparation.ts'
47
+ export { foldSurface } from './surface.ts'
48
+ export { canonicalHeader, headerEquals } from './request-header.ts'
49
+ export { validateSessionLog } from './validation.ts'
50
+
51
+ type SessionCallback = (...args: unknown[]) => unknown
52
+
53
+ /** Resolve one listener snapshot, including Cordis's internal dispatch checks. */
54
+ function collectSessionCallbacks(ctx: Context, args: unknown[]): SessionCallback[] {
55
+ return [...ctx.events.dispatch('emit', args)] as SessionCallback[]
56
+ }
57
+
58
+ /** Invoke one resolved observe-only listener snapshot with per-listener containment. */
59
+ function invokeContainedSessionObservers(
60
+ ctx: Context,
61
+ name: 'session/event' | 'session/disposed',
62
+ id: SessionId,
63
+ args: unknown[],
64
+ callbacks: SessionCallback[],
65
+ ): void {
66
+ for (const callback of callbacks) {
67
+ try {
68
+ const returned: unknown = callback(...args)
69
+ void Promise.resolve(returned).catch((error: unknown) => {
70
+ ctx.logger.warn(`session "${id}": ${name} listener rejected: ${String(error)}`)
71
+ })
72
+ } catch (error: unknown) {
73
+ ctx.logger.warn(`session "${id}": ${name} listener threw: ${String(error)}`)
74
+ }
75
+ }
76
+ }
77
+
78
+ /** All mutable lifecycle state for one exact store entry. */
79
+ interface SessionEntry {
80
+ readonly id: SessionId
81
+ readonly session: SessionInterface
82
+ readonly carrier: Scoped<SessionInterface>
83
+ readonly emitCtx: Context
84
+ announcement: 'pending' | 'dispatching' | 'complete' | 'failed'
85
+ appending: boolean
86
+ detachRequested: boolean
87
+ detach(): void
88
+ }
89
+
90
+ /** Store-owned Sessions retain a null entry while unentered; absent keys are independent. */
91
+ const attachments = new WeakMap<SessionInterface, SessionEntry | null>()
92
+
93
+ /**
94
+ * Grammar of a {@link PluginRecordType}: `plugin:` followed by
95
+ * slash-separated segments of lowercase letters, digits, `.`, `_`, and `-`,
96
+ * each segment starting with a letter or digit.
97
+ */
98
+ const PLUGIN_RECORD_TYPE = /^plugin:[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/u
99
+
100
+ /**
101
+ * Whether one event type name follows the plugin record grammar.
102
+ * @param type - an event type name.
103
+ * @returns whether the name is a {@link PluginRecordType}.
104
+ */
105
+ function isPluginRecordType(type: string): type is PluginRecordType {
106
+ return PLUGIN_RECORD_TYPE.test(type)
107
+ }
108
+
109
+ /**
110
+ * Type one constructed plugin record as a log event after checking its type
111
+ * against the plugin record grammar. A restored Session already holds events
112
+ * whose types are outside `SessionEventMap` when they are marked ignorable;
113
+ * a plugin record is such an event.
114
+ * @param value - the frozen record envelope built by {@link Session}.
115
+ * @throws when the record type is outside the plugin record grammar.
116
+ */
117
+ function assertPluginRecordEvent(value: unknown): asserts value is SessionEvent {
118
+ const { type } = value as { readonly type: string }
119
+ if (!isPluginRecordType(type)) {
120
+ throw new Error(`plugin record type "${type}" must be "plugin:" followed by lowercase slash-separated segments`)
121
+ }
122
+ }
123
+
124
+ /** Module-private access to {@link Session}'s record commit, assigned once by its static block. */
125
+ let commitPluginRecord: (session: Session, type: PluginRecordType, data: unknown) => SessionSeq
126
+
127
+ /**
128
+ * Append one experimental plugin record: an event marked `ignorable` whose
129
+ * type is declared in {@link PluginRecordMap}, outside {@link SessionEventMap}.
130
+ * The plugin record catalog lists it separately from released event schemas.
131
+ * A reader that does not recognize the type retains and skips the record, which never
132
+ * enters the model-visible surface, and fork and resume carry it with the rest
133
+ * of the log. A Session format migration retains records on a best-effort
134
+ * basis, so a record holds plugin-owned state that its owner can lose without
135
+ * changing how the rest of the log is interpreted.
136
+ *
137
+ * Only production source under `packages/experimental/` may call this
138
+ * function; the `verify-plugin-record-callers` gate rejects any other
139
+ * production caller in this repository. Read records back with
140
+ * {@link pluginRecordOf}.
141
+ * @param session - the Session whose log receives the record.
142
+ * @param type - declared record name: `plugin:` followed by slash-separated
143
+ * segments of lowercase letters, digits, `.`, `_`, and `-`, each starting
144
+ * with a letter or digit.
145
+ * @param data - JSON payload, snapshotted before it enters the log.
146
+ * @returns the sequence number of the committed record.
147
+ * @throws when a store-owned Session is unentered or its creation announcement
148
+ * has not completed, when `type` is outside
149
+ * that grammar, when `data` is not losslessly
150
+ * JSON-serializable, or when the call reenters another append's publication;
151
+ * a rejected record does not change the log.
152
+ */
153
+ export function appendPluginRecord<K extends Extract<keyof PluginRecordMap, PluginRecordType>>(
154
+ session: SessionInterface,
155
+ type: K,
156
+ data: NoInfer<PluginRecordMap[K]>,
157
+ ): SessionSeq {
158
+ return commitPluginRecord(session as Session, type, data)
159
+ }
160
+
161
+ /**
162
+ * Read one committed event as a plugin record. The V3-to-V4 format edge also
163
+ * renames each unknown ignorable V3 event into the `plugin:` namespace, so an
164
+ * owner names its records under its own package name and validates `data`.
165
+ * @param event - any committed Session event, live or restored.
166
+ * @returns the record, or undefined when the event is not an ignorable event
167
+ * whose type follows the plugin record grammar.
168
+ */
169
+ export function pluginRecordOf(event: SessionEvent): PluginRecord | undefined {
170
+ const type: string = event.type
171
+ if (event.ignorable !== true || !isPluginRecordType(type)) return undefined
172
+ return { type, seq: event.seq, time: event.time, data: event.data }
173
+ }
174
+
175
+ /** Copy live append inputs before sequence assignment. */
176
+ function snapshotAppend(
177
+ type: SessionEventType,
178
+ data: SessionEventMap[SessionEventType] | undefined,
179
+ opts: SurfaceIntent | undefined,
180
+ subject: string,
181
+ ) {
182
+ const surfaceOp = opts?.surfaceOp
183
+ const sourceEventSeqs = opts?.sourceEventSeqs
184
+ const dataSnapshot = snapshotJsonValue(data)
185
+ if (dataSnapshot === undefined) throw new Error(`${subject} carries non-JSON-serializable data`)
186
+ const surface = snapshotJsonValue({
187
+ ...sourceEventSeqs === undefined ? {} : { sourceEventSeqs },
188
+ ...surfaceOp === undefined ? {} : { surfaceOp },
189
+ })
190
+ if (surface === undefined) throw new Error(`${subject} carries non-JSON-serializable surface metadata`)
191
+ return { type, data: dataSnapshot, surface }
192
+ }
193
+
194
+ /** Construct and validate one live event from detached inputs. */
195
+ function createAppendEvent(snapshot: ReturnType<typeof snapshotAppend>, seq: SessionSeq): SessionEvent {
196
+ const { type, data, surface } = snapshot
197
+ const event = deepFreeze({ type, seq, time: Date.now(), data, ...surface } as SessionEvent)
198
+ validateSessionEventData(event, `session event "${type}" at seq ${seq}`)
199
+ return event
200
+ }
201
+
202
+ /**
203
+ * An event-sourced session: an append-only log of {@link SessionEvent}s.
204
+ *
205
+ * Plain class (not a Service) — instances are constructed over session data,
206
+ * and plugins reach live instances through `ctx.sessions`.
207
+ */
208
+ export class Session implements SessionInterface {
209
+ /**
210
+ * Surface-accepted references to the data's events, read by the surface and
211
+ * the incremental folds. Transitional: it holds the same event objects as the
212
+ * data's log, and every append pushes to both.
213
+ */
214
+ private log: SessionEvent[] = []
215
+ /** The data this Session was constructed from; every append and event read goes through it. */
216
+ private readonly data: SessionData
217
+ private batchPublication: SessionEvent | undefined
218
+ /** Single incremental owner of surface acceptance and projection state. */
219
+ private readonly surfaceManager: SurfaceManager
220
+
221
+ get surface(): SessionSurface {
222
+ return this.surfaceManager
223
+ }
224
+
225
+ readonly header: SessionHeader
226
+
227
+ readonly inheritedEventCount: SessionLogOffset
228
+
229
+ get id(): SessionId {
230
+ return this.header.id
231
+ }
232
+
233
+ readonly firstLiveSeq: SessionLogOffset
234
+
235
+ readonly firstLifecycleSeq: SessionLogOffset
236
+
237
+ /**
238
+ * Construct a detached Session over data that no other Session was
239
+ * constructed from: replay its events through the surface and append the
240
+ * marker that `mode` requires. Appends go through the data.
241
+ * @param data - writable data whose header, events, and inherited cut are validated.
242
+ * @param options.mode - `create` for new data, `restore` for opened stored data.
243
+ * @param options.projections - pure interpreters for plugin-owned message changes.
244
+ * @returns a detached session.
245
+ * @throws when an event fails surface replay or requires a missing message interpreter.
246
+ */
247
+ static fromData(
248
+ data: SessionData,
249
+ options: SessionConstructionOptions & { readonly projections?: readonly SessionMessageProjection[] },
250
+ ): Session {
251
+ return new Session(data, options.mode, options.projections)
252
+ }
253
+
254
+ private constructor(
255
+ data: SessionData,
256
+ mode: 'create' | 'restore',
257
+ projections: readonly SessionMessageProjection[] = [],
258
+ ) {
259
+ this.data = data
260
+ this.surfaceManager = new SurfaceManager(this.log, SessionLogOffset(0), projections)
261
+ replaySurfaceEvents(data.snapshotEvents(), this.log, this.surfaceManager)
262
+ this.firstLiveSeq = SessionLogOffset(this.log.length)
263
+ this.header = data.header
264
+ const inheritedEventCount = data.inheritedEventCount
265
+ this.inheritedEventCount = inheritedEventCount
266
+ this.firstLifecycleSeq = mode === 'create' && this.header.isSeeded ? inheritedEventCount : this.firstLiveSeq
267
+ // A fresh seeded child always owns one tagged marker at its inherited cut,
268
+ // even when the copied prefix already ends in an ancestor marker. Restore
269
+ // retains that durable marker and appends only the ordinary resume marker,
270
+ // also to an empty stored log. A creation without fork lineage marks the
271
+ // end of non-empty data; empty data, from an empty seed or from none,
272
+ // stays empty.
273
+ if (mode === 'create' && needsInheritedSeedMarker(this.header, this.log, inheritedEventCount)) {
274
+ this.append('session/end-seed', { inherited: true })
275
+ } else if ((mode === 'restore' || (!this.header.isSeeded && !data.isEmpty)) && this.log.at(-1)?.type !== 'session/end-seed') {
276
+ this.append('session/end-seed', {})
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Return the immutable event stored at one exact sequence number.
282
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
283
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
284
+ * @param seq - event sequence number.
285
+ * @returns the accepted event, or undefined when the log does not contain it.
286
+ */
287
+ eventAt(seq: SessionSeq): SessionEvent | undefined {
288
+ return this.data.eventAt(seq)
289
+ }
290
+
291
+ /**
292
+ * Materialize an immutable snapshot of a half-open event sequence range.
293
+ * A full current snapshot is reused until the next append; every previously
294
+ * returned snapshot remains stable after later appends.
295
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
296
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
297
+ * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
298
+ * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
299
+ * @returns a frozen array of the selected deeply frozen events.
300
+ */
301
+ snapshotEvents(
302
+ fromSeq: SessionLogOffset = SessionLogOffset(0),
303
+ toSeqExclusive: SessionLogOffset = this.seq,
304
+ ): readonly SessionEvent[] {
305
+ return this.data.snapshotEvents(fromSeq, toSeqExclusive)
306
+ }
307
+
308
+ /**
309
+ * Read an immutable snapshot of a half-open event sequence range.
310
+ * The range is captured when the call starts; later appends do not change the result.
311
+ * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
312
+ * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
313
+ * @returns a frozen array of the selected deeply frozen events.
314
+ */
315
+ readEvents(
316
+ fromSeq: SessionLogOffset = SessionLogOffset(0),
317
+ toSeqExclusive: SessionLogOffset = this.seq,
318
+ ): Promise<readonly SessionEvent[]> {
319
+ return this.data.readEvents(fromSeq, toSeqExclusive)
320
+ }
321
+
322
+ /**
323
+ * Return the read-only view of this Session's data: the same object on every
324
+ * call, sharing the log and seeing later appends.
325
+ * @returns the data's view.
326
+ */
327
+ readonlyView(): ReadonlySessionData {
328
+ return this.data.readonlyView()
329
+ }
330
+
331
+ /**
332
+ * Return this Session's events after its fork-inherited prefix.
333
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
334
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
335
+ * @returns a fresh array containing child-owned events in log order.
336
+ */
337
+ ownEvents(): readonly SessionEvent[] {
338
+ // oxlint-disable-next-line typescript/no-deprecated -- Deprecated reader delegates to the deprecated range read.
339
+ return this.snapshotEvents(this.inheritedEventCount)
340
+ }
341
+
342
+ isOwnSeq(seq: SessionSeq): boolean {
343
+ return seq >= this.inheritedEventCount && seq < this.seq
344
+ }
345
+
346
+ get seq(): SessionLogOffset {
347
+ return this.data.seq
348
+ }
349
+
350
+ get currentBatchPublication(): SessionEvent | undefined {
351
+ return this.batchPublication
352
+ }
353
+
354
+ append(inputs: readonly SessionEventInput[]): readonly SessionEvent[]
355
+
356
+ append<T extends SessionEventType>(
357
+ type: T,
358
+ data: SessionEventMap[T],
359
+ ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent<T>] : []
360
+ ): SessionEvent<T>
361
+ append(
362
+ type: SessionEventType | readonly SessionEventInput[],
363
+ data?: SessionEventMap[SessionEventType],
364
+ ...opts: [opts?: SurfaceIntent]
365
+ ): SessionEvent | readonly SessionEvent[] {
366
+ if (typeof type !== 'string') return this.#appendEvents(type)
367
+ this.publicationEntry()
368
+ const snapshot = snapshotAppend(type, data, opts[0], `session event "${type}"`)
369
+ // Payload getters can detach the Session while the snapshots are read.
370
+ const entry = this.publicationEntry()
371
+ const event = createAppendEvent(snapshot, SessionSeq(this.log.length))
372
+ this.commit(event, entry)
373
+ return event
374
+ }
375
+
376
+ /**
377
+ * Validate and publish consecutive events together. Observers see the complete log.
378
+ * @param inputs - event payloads and surface intents in commit order.
379
+ * @returns immutable committed events in the same order.
380
+ * @throws before changing the log if any candidate or synchronous dispatch validation fails.
381
+ */
382
+ #appendEvents(inputs: readonly SessionEventInput[]): readonly SessionEvent[] {
383
+ this.publicationEntry()
384
+ if (inputs.length === 0) return []
385
+ const snapshots = Array.from({ length: inputs.length }, (_, index) => {
386
+ const input = inputs.at(index)
387
+ if (input === undefined) throw new Error(`session batch has an empty member at index ${index}`)
388
+ const [type, data, surfaceOpts] = input
389
+ return snapshotAppend(type, data, surfaceOpts, `session batch member ${index} ("${type}")`)
390
+ })
391
+ // Payload getters may append to or detach the Session.
392
+ const entry = this.publicationEntry()
393
+ const startSeq = this.log.length
394
+ const events = snapshots.map((snapshot, index) => createAppendEvent(snapshot, SessionSeq(startSeq + index)))
395
+ const acceptSurface = this.surfaceManager.prepareBatch(events)
396
+ if (entry !== undefined) entry.appending = true
397
+ try {
398
+ const publications = entry === undefined ? [] : events.map((event) => {
399
+ const args: unknown[] = [this, event]
400
+ const callbacks = collectSessionCallbacks(entry.emitCtx, [entry.carrier, 'session/event', ...args])
401
+ return { event, args, callbacks }
402
+ })
403
+ for (const event of events) this.log.push(event)
404
+ this.data.append(events)
405
+ acceptSurface()
406
+ if (entry !== undefined) {
407
+ for (const { event, args, callbacks } of publications) {
408
+ this.batchPublication = event
409
+ invokeContainedSessionObservers(entry.emitCtx, 'session/event', entry.id, args, callbacks)
410
+ }
411
+ }
412
+ } finally {
413
+ this.batchPublication = undefined
414
+ if (entry !== undefined) {
415
+ entry.appending = false
416
+ if (entry.detachRequested) entry.detach()
417
+ }
418
+ }
419
+ return events
420
+ }
421
+
422
+ static {
423
+ commitPluginRecord = (session, type, data) => session.#appendRecord(type, data)
424
+ }
425
+
426
+ /**
427
+ * Commit one plugin record; {@link appendPluginRecord} is the only caller.
428
+ * @param type - record type, checked against the plugin record grammar.
429
+ * @param data - JSON payload, snapshotted before it enters the log.
430
+ * @returns the record's sequence number.
431
+ */
432
+ #appendRecord(type: PluginRecordType, data: unknown): SessionSeq {
433
+ this.publicationEntry()
434
+ const dataSnapshot = snapshotJsonValue(data)
435
+ if (dataSnapshot === undefined) {
436
+ throw new Error(`plugin record "${type}" carries non-JSON-serializable data`)
437
+ }
438
+ const entry = this.publicationEntry()
439
+ const record: unknown = deepFreeze({
440
+ type,
441
+ seq: SessionSeq(this.log.length),
442
+ time: Date.now(),
443
+ data: dataSnapshot,
444
+ ignorable: true,
445
+ })
446
+ assertPluginRecordEvent(record)
447
+ this.commit(record, entry)
448
+ return record.seq
449
+ }
450
+
451
+ /**
452
+ * Require announced membership for store-owned Sessions and refuse reentrant publication.
453
+ * @returns the current store attachment, or undefined for an independent Session.
454
+ */
455
+ private publicationEntry(): SessionEntry | undefined {
456
+ const entry = attachments.get(this)
457
+ if (entry === null) {
458
+ throw new Error(`session "${this.id}" cannot append outside a SessionStore`)
459
+ }
460
+ if (entry !== undefined && entry.announcement !== 'complete') {
461
+ throw new Error(`session "${this.id}" cannot append before session/created completes`)
462
+ }
463
+ if (entry?.appending) {
464
+ throw new Error('session append cannot reenter while another append is being published')
465
+ }
466
+ return entry
467
+ }
468
+
469
+ /**
470
+ * Accept one frozen candidate at the next sequence number, enter it into the
471
+ * log, and notify `session/event` observers with per-listener containment.
472
+ * @param event - the candidate built at the current log length.
473
+ * @param entry - the attachment read before the candidate was built.
474
+ */
475
+ private commit(event: SessionEvent, entry: SessionEntry | undefined): void {
476
+ this.surfaceManager.validateNext(event)
477
+
478
+ if (entry !== undefined) entry.appending = true
479
+ try {
480
+ const callbackArgs: unknown[] = [this, event]
481
+ const callbacks = entry === undefined
482
+ ? undefined
483
+ : collectSessionCallbacks(entry.emitCtx, [entry.carrier, 'session/event', ...callbackArgs])
484
+ this.log.push(event)
485
+ this.data.append([event])
486
+ if (entry !== undefined && callbacks !== undefined) {
487
+ invokeContainedSessionObservers(entry.emitCtx, 'session/event', entry.id, callbackArgs, callbacks)
488
+ }
489
+ } finally {
490
+ if (entry !== undefined) {
491
+ entry.appending = false
492
+ if (entry.detachRequested && entry.announcement !== 'dispatching') entry.detach()
493
+ }
494
+ }
495
+ }
496
+
497
+ /** Header {@link requestHeader} froze last; the same object is not frozen again. */
498
+ private frozenHeader: EpochHeader | undefined
499
+
500
+ /**
501
+ * The {@link EpochHeader} in force after the log's last header event — the
502
+ * header the NEXT request will be compared against — or undefined before
503
+ * the first `request/header` snapshot. Read by evaluating
504
+ * `requestHeaderStateDefinition` over this Session's data, so each header
505
+ * event is folded once.
506
+ * @returns the immutable header, or undefined when no header event exists yet.
507
+ */
508
+ requestHeader(): EpochHeader | undefined {
509
+ const header = this.data.evaluateState(requestHeaderStateDefinition) ?? undefined
510
+ // Frozen before it is returned: the header is session state exposed by
511
+ // reference — a consumer mutating it in place (instead of building a
512
+ // replacement) would desync every later comparison against the log, so
513
+ // mutation throws instead.
514
+ if (header !== undefined && header !== this.frozenHeader) this.frozenHeader = deepFreeze(header)
515
+ return header
516
+ }
517
+
518
+ /** Route metadata {@link requestContext} froze last; the same object is not frozen again. */
519
+ private frozenContext: RequestContext | undefined
520
+
521
+ /**
522
+ * Return the latest resolved route metadata, or `undefined` before the first
523
+ * `request/context` event. Read by evaluating `requestContextStateDefinition`
524
+ * over this Session's data, so each event is folded once.
525
+ * @returns the latest immutable route metadata.
526
+ */
527
+ requestContext(): RequestContext | undefined {
528
+ const context = this.data.evaluateState(requestContextStateDefinition) ?? undefined
529
+ if (context !== undefined && context !== this.frozenContext) this.frozenContext = deepFreeze(context)
530
+ return context
531
+ }
532
+
533
+ /** Tool history {@link toolHistory} froze last; the same object is not frozen again. */
534
+ private frozenToolHistory: ToolHistory | undefined
535
+
536
+ /**
537
+ * Return the capability-independent tool history for request projection.
538
+ * Read by evaluating `toolHistoryStateDefinition` over this Session's data,
539
+ * so each committed header and developer message is folded once.
540
+ * @returns the immutable snapshot: the current series' active declarations
541
+ * with the historical additions recorded by developer messages, or the
542
+ * complete active declarations alone while the latest header lacks its
543
+ * update record.
544
+ */
545
+ toolHistory(): ToolHistory {
546
+ const snapshot = snapshotToolHistory(this.data.evaluateState(toolHistoryStateDefinition))
547
+ if (snapshot !== this.frozenToolHistory) this.frozenToolHistory = deepFreeze(snapshot)
548
+ return snapshot
549
+ }
550
+
551
+ /** The derived-message cache: frozen projections, extended per unseen node. */
552
+ private derived: Message[] = []
553
+ /** Surface position (nodes projected) the cache has reached. */
554
+ private derivedNodes = 0
555
+ /** {@link SurfaceManager.contentGeneration} the cache was built under. */
556
+ private derivedGeneration = 0
557
+
558
+ deriveMessages(): Message[] {
559
+ const surface = this.surface
560
+ const nodes = surface.nodes
561
+ const generation = surface.contentGeneration
562
+ if (generation !== this.derivedGeneration) {
563
+ this.derived = []
564
+ this.derivedNodes = 0
565
+ this.derivedGeneration = generation
566
+ }
567
+ for (const seq of nodes.slice(this.derivedNodes)) {
568
+ // Surface sequences are built from this.log — seq is always a valid
569
+ // index by construction. The non-null assertion expresses that invariant.
570
+ // oxlint-disable-next-line typescript/no-non-null-assertion
571
+ const msg = this.deriveEventMessage(this.log[seq]!)
572
+ // A surface node is one of the five message-producing types, but an
573
+ // empty-content assistant/message (a max-tokens step that hosts only
574
+ // usage) derives to null and must not enter the transcript.
575
+ if (msg) this.derived.push(msg)
576
+ }
577
+ this.derivedNodes = nodes.length
578
+ return [...this.derived]
579
+ }
580
+
581
+ deriveEventMessage(event: SessionEvent): Message | null {
582
+ return this.surfaceManager.deriveEventMessage(event)
583
+ }
584
+ }
585
+
586
+ /**
587
+ * In-memory session store (`ctx.sessions`).
588
+ *
589
+ * Persistence is intentionally not implemented here — the agent lifecycle
590
+ * attaches a session-log writer to each published session's write handle;
591
+ * a session published outside that lifecycle persists nothing.
592
+ */
593
+ export class SessionStore extends Service implements SessionStoreInterface {
594
+ private store = new Map<SessionId, SessionEntry>()
595
+ private readonly projections: SessionMessageProjection[] = []
596
+
597
+ get messageProjections(): readonly SessionMessageProjection[] {
598
+ return this.projections
599
+ }
600
+
601
+ registerMessageProjection(projection: SessionMessageProjection): () => Promise<void> {
602
+ if (this.projections.some(item => item.type === projection.type)) {
603
+ throw new Error(`session message projection "${projection.type}" is already registered`)
604
+ }
605
+ return this.ctx.effect(() => {
606
+ this.projections.push(projection)
607
+ return () => { this.projections.splice(this.projections.indexOf(projection), 1) }
608
+ }, 'sessions.registerMessageProjection()')
609
+ }
610
+
611
+ constructor(ctx: Context) {
612
+ super(ctx, 'sessions')
613
+ ctx.inject(['typert'], (typeCtx) => {
614
+ typeCtx.typert.lookups.register('session', {
615
+ parameter: 'session',
616
+ wire: 'sessionId',
617
+ resource: 'session',
618
+ hostTypeSymbol: '@deepseek-ai/dsh-session#Session',
619
+ wireTypeSymbol: '@deepseek-ai/dsh-session/types#SessionId',
620
+ resolve: sessionId => this.get(sessionId),
621
+ })
622
+ })
623
+ }
624
+
625
+ /**
626
+ * Construct a store-owned, unentered Session from data that no other Session
627
+ * was constructed from, with the store's message interpreters. Pairs with
628
+ * {@link enter} + {@link announce}.
629
+ * @param data - writable data; the caller still owns it when this throws.
630
+ * @param options.mode - `create` for new data, `restore` for opened stored data.
631
+ * @returns the store-owned session, not yet entered and read-only until announced.
632
+ * @throws if a session with the data's id already exists or surface replay fails.
633
+ */
634
+ prepare(data: SessionData, options: SessionConstructionOptions): Session {
635
+ const id = data.header.id
636
+ if (this.store.has(id)) throw new Error(`session "${id}" already exists`)
637
+ const session = Session.fromData(data, { mode: options.mode, projections: this.projections })
638
+ attachments.set(session, null)
639
+ return session
640
+ }
641
+
642
+ enter(session: SessionInterface): () => void {
643
+ const id = session.id
644
+ const carrier = scopeTarget(session, scopeOf(this.ctx))
645
+ // This is the authoritative collision boundary after arbitrary unpublished
646
+ // preparation. Only one exact same-id transaction can publish.
647
+ if (this.store.has(id)) throw new Error(`session "${id}" already exists`)
648
+ if (attachments.get(session) != null) throw new Error(`session "${id}" is already attached to a store`)
649
+ const entry: SessionEntry = {
650
+ id,
651
+ session,
652
+ carrier,
653
+ emitCtx: this.ctx,
654
+ announcement: 'pending',
655
+ appending: false,
656
+ detachRequested: false,
657
+ detach: () => { this.detachEntered(entry) },
658
+ }
659
+ this.store.set(id, entry)
660
+ attachments.set(session, entry)
661
+ let entered = true
662
+ const detach = (): void => {
663
+ if (!entered) return
664
+ entered = false
665
+ // A lifecycle listener may own the advanced detach capability. Keep the
666
+ // entry and its publication hooks live until synchronous creation or append
667
+ // publication unwinds, then publish the paired disposal edge.
668
+ if (entry.announcement === 'dispatching' || entry.appending) {
669
+ entry.detachRequested = true
670
+ return
671
+ }
672
+ entry.detach()
673
+ }
674
+ return detach
675
+ }
676
+
677
+ /** Remove one exact entered session and emit its paired disposal when announced. */
678
+ private detachEntered(entry: SessionEntry): void {
679
+ entry.detachRequested = false
680
+ // A stale capability cannot remove observers or storage belonging to a
681
+ // later same-id lifecycle.
682
+ /* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */
683
+ if (this.store.get(entry.id) !== entry) return
684
+ this.store.delete(entry.id)
685
+ attachments.set(entry.session, null)
686
+ if (entry.announcement !== 'pending') this.emitDisposed(entry)
687
+ }
688
+
689
+ announce(session: SessionInterface): void {
690
+ const entry = this.liveEntryFor(session)
691
+ if (entry.announcement !== 'pending') {
692
+ throw new Error(`session "${entry.id}" was already announced`)
693
+ }
694
+ // Partial creation dispatch still requires disposal on rollback; listeners
695
+ // cannot recursively begin another announcement.
696
+ const callbackArgs: unknown[] = [session]
697
+ entry.announcement = 'dispatching'
698
+ try {
699
+ const callbacks = collectSessionCallbacks(this.ctx, [entry.carrier, 'session/created', session])
700
+ for (const callback of callbacks) {
701
+ // Synchronous throws intentionally propagate and veto publication; the
702
+ // yielded detach then emits the paired disposal edge. An async function
703
+ // is nevertheless assignable to a void listener, so observe its returned
704
+ // promise: rejection is too late to roll back and must be logged instead
705
+ // of becoming unhandled.
706
+ const returned: unknown = callback(...callbackArgs)
707
+ void Promise.resolve(returned).catch((error: unknown) => {
708
+ this.ctx.logger.warn(`session "${entry.id}": session/created listener rejected: ${String(error)}`)
709
+ })
710
+ }
711
+ entry.announcement = 'complete'
712
+ } catch (error: unknown) {
713
+ entry.announcement = 'failed'
714
+ throw error
715
+ } finally {
716
+ if (entry.detachRequested) entry.detach()
717
+ }
718
+ }
719
+
720
+ /** Emit the paired teardown notification with per-listener containment. */
721
+ private emitDisposed(entry: SessionEntry): void {
722
+ const callbackArgs: unknown[] = [entry.session]
723
+ try {
724
+ const callbacks = collectSessionCallbacks(this.ctx, [entry.carrier, 'session/disposed', entry.session])
725
+ invokeContainedSessionObservers(this.ctx, 'session/disposed', entry.id, callbackArgs, callbacks)
726
+ } catch (error: unknown) {
727
+ // `emit()` aggregates listener failures; name their messages. Any other
728
+ // thrown value keeps its own text so the containment log never throws.
729
+ /* v8 ignore next -- the dispatch contract throws AggregateError */
730
+ const members = error instanceof AggregateError ? ` [${error.errors.map(String).join('; ')}]` : ''
731
+ this.ctx.logger.warn(`session "${entry.id}": session/disposed dispatch threw: ${String(error)}${members}`)
732
+ }
733
+ }
734
+
735
+ async flush(session: SessionInterface): Promise<boolean> {
736
+ const { carrier } = this.liveEntryFor(session)
737
+ const callbackArgs: unknown[] = [session]
738
+ const callbacks = collectSessionCallbacks(this.ctx, [carrier, 'session/flush', session])
739
+ const results = await Promise.allSettled(callbacks.map((callback) => {
740
+ try {
741
+ return callback(...callbackArgs)
742
+ } catch (error: unknown) {
743
+ // Preserve the listener's exact rejection value; flush is a caller-owned
744
+ // failure boundary, and Cordis listeners may throw arbitrary values.
745
+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors
746
+ return Promise.reject(error)
747
+ }
748
+ }))
749
+ const failure = results.find((result): result is PromiseRejectedResult => result.status === 'rejected')
750
+ if (failure !== undefined) throw failure.reason
751
+ return callbacks.length > 0
752
+ }
753
+
754
+ /** Return the exact live entry; detached/prepared objects reject. */
755
+ private liveEntryFor(session: SessionInterface): SessionEntry {
756
+ const entry = attachments.get(session)
757
+ if (entry == null || this.store.get(entry.id) !== entry) {
758
+ throw new Error(`session "${session.id}" is not live in this store`)
759
+ }
760
+ return entry
761
+ }
762
+
763
+ get(id: SessionId): SessionInterface | undefined {
764
+ return this.store.get(id)?.session
765
+ }
766
+
767
+ list(): SessionInterface[] {
768
+ return [...this.store.values()].map(entry => entry.session)
769
+ }
770
+
771
+ }
772
+
773
+ export default SessionStore