@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/lib/index.js ADDED
@@ -0,0 +1,1371 @@
1
+ import { Service } from "@deepseek-ai/cordis";
2
+ import { deepFreeze, snapshotJsonValue } from "@deepseek-ai/dsh-util-values";
3
+ import { scopeOf, scopeTarget } from "@deepseek-ai/dsh-scope";
4
+ import { MESSAGE_PROJECTION_EVENT_TYPES, SessionLogOffset, SessionSeq, assertSourceEventReferences, checkSessionLog, deriveEventMessage, needsInheritedSeedMarker, validateSessionEventData, validateSurfaceMetadata } from "@deepseek-ai/dsh-session";
5
+ import { callConfigEquals } from "@deepseek-ai/dsh-llm";
6
+ //#region lib/types/surface.js
7
+ /**
8
+ * The surface fold: replays `surfaceOp` markers and message projections over a
9
+ * session event log, as one complete pass ({@link foldSurface}) or
10
+ * incrementally behind `session.surface` ({@link SurfaceManager}).
11
+ *
12
+ * @module @deepseek-ai/dsh-session-store/surface
13
+ */
14
+ /** Whether a payload field is a JSON object rather than an array or scalar. */
15
+ function isRecord(value) {
16
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17
+ }
18
+ /** Create an empty surface fold state. */
19
+ function createFoldState() {
20
+ return {
21
+ nodes: [],
22
+ replaceGeneration: 0,
23
+ contentGeneration: 0,
24
+ projectedMessages: /* @__PURE__ */ new Map(),
25
+ projections: /* @__PURE__ */ new Set()
26
+ };
27
+ }
28
+ /** Resolve tool additions against their immutable historical request header. */
29
+ function assertDeveloperHeader(event, read) {
30
+ if (event.type !== "developer/message") return;
31
+ validateSessionEventData(event, `developer/message at seq ${event.seq}`);
32
+ if (event.data.headerSeq === void 0) return;
33
+ const headerSeq = event.data.headerSeq;
34
+ const headerEvent = read(headerSeq);
35
+ if (headerSeq >= event.seq || headerEvent?.type !== "request/header") throw new Error("developer/message headerSeq must reference an earlier request/header");
36
+ for (const block of event.data.message.content) {
37
+ if (block.type !== "tool-addition") continue;
38
+ const definitions = headerEvent.data.header.tools?.filter((tool) => tool.name === block.toolName) ?? [];
39
+ if (definitions.length !== 1) throw new Error(`developer/message tool-addition "${block.toolName}" must name exactly one tool in headerSeq ${headerSeq}`);
40
+ const definition = definitions[0];
41
+ if (typeof definition.description !== "string" || !isRecord(definition.parameters)) throw new Error(`developer/message tool-addition "${block.toolName}" requires a complete tool definition in headerSeq ${headerSeq}`);
42
+ if (Object.hasOwn(definition, "deferLoading") && definition.deferLoading !== true) throw new Error("developer/message referenced tool deferLoading must be true when present");
43
+ }
44
+ }
45
+ /** Locate one replacement range without mutating the current fold state. */
46
+ function replacementRange(state, op) {
47
+ const startIdx = state.nodes.indexOf(op.startSeq);
48
+ if (startIdx === -1) throw new Error(`surface replace: start seq ${op.startSeq} not found in surface`);
49
+ const endIdx = state.nodes.indexOf(op.endSeq);
50
+ if (endIdx === -1) throw new Error(`surface replace: end seq ${op.endSeq} not found in surface`);
51
+ if (startIdx > endIdx) throw new Error(`surface replace: start seq ${op.startSeq} (index ${startIdx}) is after end seq ${op.endSeq} (index ${endIdx})`);
52
+ return {
53
+ startIdx,
54
+ endIdx,
55
+ shadowedSeqs: state.nodes.slice(startIdx, endIdx + 1)
56
+ };
57
+ }
58
+ /**
59
+ * Deep structural equality over the session-event JSON value domain
60
+ * (null/boolean/number/string, arrays, plain objects). Replaces
61
+ * `node:util`'s isDeepStrictEqual to keep this module browser-safe.
62
+ */
63
+ function isDeepEqualJson(a, b) {
64
+ if (a === b) return true;
65
+ if (Array.isArray(a) || Array.isArray(b)) {
66
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
67
+ return a.every((item, i) => isDeepEqualJson(item, b[i]));
68
+ }
69
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
70
+ const aKeys = Object.keys(a);
71
+ const bRecord = b;
72
+ if (aKeys.length !== Object.keys(b).length) return false;
73
+ return aKeys.every((key) => Object.hasOwn(b, key) && isDeepEqualJson(a[key], bRecord[key]));
74
+ }
75
+ /** Restrict a tool-result replacement to one current result's content. */
76
+ function assertToolResultRewrite(event, shadowedSeqs, read) {
77
+ if (event.type !== "tool/result") return;
78
+ if (shadowedSeqs.length !== 1) throw new Error("tool/result surface replacement must rewrite exactly one current node");
79
+ for (const originalSeq of shadowedSeqs) {
80
+ const original = read(originalSeq);
81
+ if (original?.type !== "tool/result") throw new Error("tool/result surface replacement must target a current tool/result");
82
+ const originalRest = { ...original.data };
83
+ const replacementRest = { ...event.data };
84
+ originalRest["message"] = {
85
+ ...original.data.message,
86
+ content: null
87
+ };
88
+ replacementRest["message"] = {
89
+ ...event.data.message,
90
+ content: null
91
+ };
92
+ if (!isDeepEqualJson(originalRest, replacementRest)) throw new Error("tool/result surface replacement may change only content");
93
+ }
94
+ }
95
+ /**
96
+ * Protect the system prompt at surface node 0. A replacement covering node 0
97
+ * while that node is a `system/message` must itself be a `system/message` over
98
+ * exactly that node; later system nodes carry no protection and a compaction
99
+ * range may shadow them.
100
+ */
101
+ function assertSystemHeadRewrite(event, state, startIdx, shadowedSeqs, read) {
102
+ if (startIdx !== 0) return;
103
+ if (read(state.nodes[0])?.type !== "system/message") return;
104
+ if (event.type !== "system/message" || shadowedSeqs.length !== 1) throw new Error("surface replace: node 0 holds the system prompt and may be rewritten only by a system/message over exactly that node");
105
+ }
106
+ /** Validate one event at its replay boundary and prepare its atomic fold transition. */
107
+ function planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projections, candidates) {
108
+ if (event.seq !== expectedSeq) throw new Error(`session event seq ${event.seq} is not contiguous; expected ${expectedSeq}`);
109
+ const surfaceOp = validateSurfaceMetadata(event);
110
+ const read = (seq) => {
111
+ const index = seq - baseSeq;
112
+ return index < events.length ? events[index] : candidates?.[index - events.length];
113
+ };
114
+ assertDeveloperHeader(event, read);
115
+ const projection = projections.find((item) => item.type === event.type);
116
+ if (projection !== void 0) {
117
+ let projectionEvents;
118
+ return {
119
+ kind: "project",
120
+ projection,
121
+ messages: projection.project(event, {
122
+ nodes: state.nodes,
123
+ get events() {
124
+ return candidates === void 0 ? events : projectionEvents ??= [...events, ...candidates];
125
+ },
126
+ baseSeq,
127
+ messages: state.projectedMessages
128
+ })
129
+ };
130
+ }
131
+ if (MESSAGE_PROJECTION_EVENT_TYPES.has(event.type)) throw new Error(`session event "${event.type}" requires a message projection; load its owning plugin or supply its projection definition`);
132
+ if (surfaceOp === void 0) return;
133
+ if (surfaceOp === "append") return {
134
+ kind: "append",
135
+ seq: event.seq
136
+ };
137
+ const range = replacementRange(state, surfaceOp);
138
+ assertSourceEventReferences(event, range.shadowedSeqs);
139
+ assertToolResultRewrite(event, range.shadowedSeqs, read);
140
+ assertSystemHeadRewrite(event, state, range.startIdx, range.shadowedSeqs, read);
141
+ return {
142
+ kind: "replace",
143
+ seq: event.seq,
144
+ start: surfaceOp.startSeq,
145
+ end: surfaceOp.endSeq,
146
+ ...range
147
+ };
148
+ }
149
+ /** Apply one event and return replacement metadata only when one occurred. */
150
+ function applySurfaceEvent(state, event, expectedSeq, events, baseSeq, projections) {
151
+ return applySurfacePlan(state, planSurfaceEvent(state, event, expectedSeq, events, baseSeq, projections));
152
+ }
153
+ /** Commit one previously validated surface transition. */
154
+ function applySurfacePlan(state, plan) {
155
+ if (plan?.kind === "append") state.nodes.push(plan.seq);
156
+ else if (plan?.kind === "replace") {
157
+ state.nodes.splice(plan.startIdx, plan.endIdx - plan.startIdx + 1, plan.seq);
158
+ state.replaceGeneration += 1;
159
+ state.contentGeneration += 1;
160
+ } else if (plan?.kind === "project") {
161
+ for (const [seq, message] of plan.messages) state.projectedMessages.set(seq, message);
162
+ state.projections.add(plan.projection);
163
+ state.contentGeneration += 1;
164
+ }
165
+ if (plan?.kind !== "replace") return;
166
+ return {
167
+ seq: plan.seq,
168
+ start: plan.start,
169
+ end: plan.end,
170
+ shadowedSeqs: plan.shadowedSeqs
171
+ };
172
+ }
173
+ /**
174
+ * Replay a complete session log through the canonical surface fold.
175
+ * @param events - session events in contiguous seq order.
176
+ * @param projections - pure interpreters for plugin-owned message changes; required definitions must be supplied.
177
+ * @returns detached current sequences and replacement history.
178
+ * @throws when an interpreter is missing or an event violates its projection, surface metadata, source attribution, or replacement rules.
179
+ */
180
+ function foldSurface(events, projections = []) {
181
+ const state = createFoldState();
182
+ const replacements = [];
183
+ for (const [index, event] of events.entries()) {
184
+ const replacement = applySurfaceEvent(state, event, SessionSeq(index), events, SessionLogOffset(0), projections);
185
+ if (replacement !== void 0) replacements.push(replacement);
186
+ }
187
+ return {
188
+ nodes: [...state.nodes],
189
+ replacements,
190
+ projectedMessages: new Map(state.projectedMessages)
191
+ };
192
+ }
193
+ /** Incremental ordered surface view and append-boundary validator. */
194
+ var SurfaceManager = class {
195
+ log;
196
+ baseSeq;
197
+ projections;
198
+ /** Shared transition state; replacement history is not retained. */
199
+ _state = createFoldState();
200
+ /** Last processed absolute seq. */
201
+ _lastProcessedSeq;
202
+ /** Candidate already validated by `validateNext`, pending exact log admission. */
203
+ _pendingPlan;
204
+ /**
205
+ * @param log - Contiguous complete log or loaded event window.
206
+ * @param baseSeq - Absolute sequence of the window's first event.
207
+ * @param projections - live borrowed definitions; removing a used definition invalidates further reads.
208
+ */
209
+ constructor(log, baseSeq = SessionLogOffset(0), projections = []) {
210
+ this.log = log;
211
+ this.baseSeq = baseSeq;
212
+ this.projections = projections;
213
+ this._lastProcessedSeq = baseSeq === 0 ? -1 : SessionSeq(baseSeq - 1);
214
+ }
215
+ /**
216
+ * Validate the next candidate without mutating the committed surface.
217
+ * @param event - candidate event that has not entered the log yet.
218
+ */
219
+ validateNext(event) {
220
+ this._assertProjections();
221
+ if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();
222
+ const expectedSeq = SessionSeq(this.baseSeq + this.log.length);
223
+ this._pendingPlan = {
224
+ event,
225
+ expectedSeq,
226
+ plan: planSurfaceEvent(this._state, event, expectedSeq, this.log, this.baseSeq, this.projections)
227
+ };
228
+ }
229
+ /**
230
+ * Validate consecutive candidates against an isolated surface fold.
231
+ * @param events - candidates immediately following the committed log.
232
+ * @returns a callback adopting the validated fold after all candidates enter the log.
233
+ */
234
+ prepareBatch(events) {
235
+ this._assertProjections();
236
+ if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();
237
+ const lastProcessedSeq = SessionSeq(this.baseSeq + this.log.length + events.length - 1);
238
+ if (events.every((event) => (event.surfaceOp === void 0 || event.surfaceOp === "append") && !this.projections.some((projection) => projection.type === event.type))) {
239
+ const plans = events.map((event, index) => planSurfaceEvent(this._state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events));
240
+ return () => {
241
+ for (const plan of plans) applySurfacePlan(this._state, plan);
242
+ this._lastProcessedSeq = lastProcessedSeq;
243
+ this._pendingPlan = void 0;
244
+ };
245
+ }
246
+ const state = {
247
+ ...this._state,
248
+ nodes: [...this._state.nodes],
249
+ projectedMessages: new Map(this._state.projectedMessages),
250
+ projections: new Set(this._state.projections)
251
+ };
252
+ const plans = events.map((event, index) => {
253
+ const plan = planSurfaceEvent(state, event, SessionSeq(this.baseSeq + this.log.length + index), this.log, this.baseSeq, this.projections, events);
254
+ applySurfacePlan(state, plan);
255
+ return plan;
256
+ });
257
+ return () => {
258
+ for (const plan of plans) applySurfacePlan(this._state, plan);
259
+ this._lastProcessedSeq = lastProcessedSeq;
260
+ this._pendingPlan = void 0;
261
+ };
262
+ }
263
+ /** Monotonic count of folded positional replacements. */
264
+ get replaceGeneration() {
265
+ this._assertProjections();
266
+ if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();
267
+ return this._state.replaceGeneration;
268
+ }
269
+ /** Monotonic count of committed changes to existing model-visible content. */
270
+ get contentGeneration() {
271
+ this._assertProjections();
272
+ if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();
273
+ return this._state.contentGeneration;
274
+ }
275
+ /**
276
+ * Project one message with every committed message projection applied.
277
+ * @param event - message-producing or log-only event.
278
+ * @returns its immutable projected message, or null when it produces none.
279
+ */
280
+ deriveEventMessage(event) {
281
+ this._assertProjections();
282
+ if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();
283
+ return deriveEventMessage(event, this._state.projectedMessages);
284
+ }
285
+ /** Surface event sequences in model-visible order. */
286
+ get nodes() {
287
+ this._assertProjections();
288
+ if (this._lastProcessedSeq < this.baseSeq + this.log.length - 1) this._processDelta();
289
+ return this._state.nodes;
290
+ }
291
+ /** System nodes in surface order, including nodes whose content array is empty; scans current nodes on each read. */
292
+ get systemNodes() {
293
+ const systems = [];
294
+ for (const seq of this.nodes) {
295
+ const event = this.log[seq - this.baseSeq];
296
+ if (event?.type === "system/message") systems.push({
297
+ seq,
298
+ isEmpty: event.data.message.content.length === 0
299
+ });
300
+ }
301
+ return systems;
302
+ }
303
+ /** Fold events appended since the previous access. */
304
+ _processDelta() {
305
+ const tailSeq = this.baseSeq + this.log.length - 1;
306
+ for (let seq = this._lastProcessedSeq + 1; seq <= tailSeq; seq++) {
307
+ const index = seq - this.baseSeq;
308
+ const event = this.log[index];
309
+ const pending = this._pendingPlan;
310
+ if (pending?.event === event && pending.expectedSeq === seq) applySurfacePlan(this._state, pending.plan);
311
+ else applySurfaceEvent(this._state, event, SessionSeq(seq), this.log, this.baseSeq, this.projections);
312
+ if (pending !== void 0 && pending.expectedSeq <= seq) this._pendingPlan = void 0;
313
+ this._lastProcessedSeq = SessionSeq(seq);
314
+ }
315
+ }
316
+ /** Cached messages cannot outlive the definitions that interpreted their log. */
317
+ _assertProjections() {
318
+ const candidate = this._pendingPlan;
319
+ const pending = candidate !== void 0 && this.log[candidate.expectedSeq - this.baseSeq] === candidate.event ? candidate.plan : void 0;
320
+ const required = pending?.kind === "project" ? [...this._state.projections, pending.projection] : this._state.projections;
321
+ for (const projection of required) if (!this.projections.includes(projection)) throw new Error(`session message projection "${projection.type}" was removed or replaced; restore the session with its owning plugin`);
322
+ }
323
+ };
324
+ //#endregion
325
+ //#region lib/types/request-header.js
326
+ /**
327
+ * Request-header reconstruction utilities over full `request/header` session
328
+ * events. Anyone holding a session log reconstructs the {@link EpochHeader}
329
+ * any request was built under by taking the latest canonical snapshot; the
330
+ * loop uses the same equality helper to avoid logging unchanged headers. The
331
+ * route metadata of `request/context` events is reconstructed the same way.
332
+ *
333
+ * @module @deepseek-ai/dsh-session-store/request-header
334
+ */
335
+ /**
336
+ * Normalize a header to canonical form: an empty tool list becomes an absent
337
+ * field, matching how requests are built. Logging, folding, and comparison use
338
+ * this one representation.
339
+ * @param header - the header to normalize (not mutated).
340
+ * @returns the canonical header.
341
+ */
342
+ function canonicalHeader(header) {
343
+ const adapterDefaults = header.adapterDefaults;
344
+ return {
345
+ config: header.config,
346
+ ...adapterDefaults?.reasoningEffort === true || adapterDefaults?.maxTokens === true ? { adapterDefaults } : {},
347
+ ...header.tools !== void 0 && header.tools.length > 0 ? { tools: header.tools } : {}
348
+ };
349
+ }
350
+ /** Canonical JSON equality for tool schemas assembled through the same path. */
351
+ function sameSchema(a, b) {
352
+ return JSON.stringify(a) === JSON.stringify(b);
353
+ }
354
+ /**
355
+ * Field-wise equality over canonical headers. Tool schemas compare in order.
356
+ * @param a - one canonical header.
357
+ * @param b - the other.
358
+ * @returns whether config, adapter defaults, and tools all match.
359
+ */
360
+ function headerEquals(a, b) {
361
+ if (!callConfigEquals(a.config, b.config) || a.adapterDefaults?.reasoningEffort !== b.adapterDefaults?.reasoningEffort || a.adapterDefaults?.maxTokens !== b.adapterDefaults?.maxTokens) return false;
362
+ const at = a.tools ?? [];
363
+ const bt = b.tools ?? [];
364
+ return at.length === bt.length && at.every((tool, i) => sameSchema(tool, bt[i]));
365
+ }
366
+ /** Request-header transition: a `request/header` event yields its canonical header; any other event returns `state` itself. */
367
+ function applyRequestHeader(state, event) {
368
+ return event.type === "request/header" ? canonicalHeader(event.data.header) : state;
369
+ }
370
+ /** Request-context transition: a `request/context` event yields a copy of its route metadata; any other event returns `state` itself. */
371
+ function applyRequestContext(state, event) {
372
+ return event.type === "request/context" ? { ...event.data } : state;
373
+ }
374
+ /**
375
+ * State definition that `Session.requestHeader()` reads: the canonical
376
+ * {@link EpochHeader} of the latest `request/header` event, or `null` before
377
+ * the first one.
378
+ */
379
+ const requestHeaderStateDefinition = {
380
+ key: "requestHeader",
381
+ init: () => null,
382
+ apply: applyRequestHeader
383
+ };
384
+ /**
385
+ * State definition that `Session.requestContext()` reads: a copy of the latest
386
+ * `request/context` event's route metadata, or `null` before the first one.
387
+ */
388
+ const requestContextStateDefinition = {
389
+ key: "requestContext",
390
+ init: () => null,
391
+ apply: applyRequestContext
392
+ };
393
+ //#endregion
394
+ //#region lib/types/tool-history.js
395
+ /**
396
+ * Capability-independent tool history for request projection: the tool
397
+ * declarations in force for a Session and the developer-message updates that
398
+ * record historical additions. `Session.toolHistory()` evaluates
399
+ * {@link toolHistoryStateDefinition} over the Session's data and asks
400
+ * {@link snapshotToolHistory} for the snapshot.
401
+ *
402
+ * States are plain data that survives `JSON.stringify` and `JSON.parse`
403
+ * unchanged. Each distinct tool definition is kept once in `pool`; every other
404
+ * field refers to a definition by its index in that array. `advanceToolHistory`
405
+ * forks a plain copy of a state and `transitions.apply` updates that copy in
406
+ * place; freezing the snapshot belongs to the reader.
407
+ *
408
+ * @module @deepseek-ai/dsh-session-store/tool-history
409
+ */
410
+ /**
411
+ * Read a committed header by sequence number.
412
+ * @param head - newest node of the header chain.
413
+ * @param seq - sequence number the developer message referenced.
414
+ * @returns the header's node, or undefined when no committed header has that sequence number.
415
+ */
416
+ function headerAt(head, seq) {
417
+ for (let node = head; node !== void 0 && node.seq >= seq; node = node.prev) if (node.seq === seq) return node;
418
+ }
419
+ /** Content indexes of pool arrays, built on first use. A cache only: losing it costs time, never behavior. */
420
+ const poolIndexes = /* @__PURE__ */ new WeakMap();
421
+ /**
422
+ * Get the content index of a pool, deriving it from the definitions when absent.
423
+ * @param pool - a state's pool.
424
+ * @returns the JSON text of each pooled definition and the text-to-index lookup.
425
+ */
426
+ function indexOfPool(pool) {
427
+ let index = poolIndexes.get(pool);
428
+ if (index === void 0) {
429
+ const texts = pool.map((tool) => JSON.stringify(tool));
430
+ index = {
431
+ texts,
432
+ ids: new Map(texts.map((text, id) => [text, id]))
433
+ };
434
+ poolIndexes.set(pool, index);
435
+ }
436
+ return index;
437
+ }
438
+ /**
439
+ * Store definitions that are not in the pool yet and return the pool indexes of the whole list.
440
+ * @param pool - the pool before this header.
441
+ * @param tools - definitions declared by the header, in declaration order.
442
+ * @returns the pool, extended if a definition is new; one index and one JSON text per declared tool.
443
+ */
444
+ function internTools(pool, tools) {
445
+ let index = indexOfPool(pool);
446
+ let extended;
447
+ const texts = [];
448
+ const ids = tools.map((tool) => {
449
+ const text = JSON.stringify(tool);
450
+ texts.push(text);
451
+ let id = index.ids.get(text);
452
+ if (id === void 0) {
453
+ id = (extended ?? pool).length;
454
+ extended ??= [...pool];
455
+ extended.push(tool);
456
+ index = {
457
+ texts: [...index.texts, text],
458
+ ids: new Map(index.ids).set(text, id)
459
+ };
460
+ poolIndexes.set(extended, index);
461
+ }
462
+ return id;
463
+ });
464
+ return {
465
+ pool: extended ?? pool,
466
+ ids,
467
+ texts
468
+ };
469
+ }
470
+ /**
471
+ * Create an empty name-to-index record without a prototype, so any tool name is a plain key.
472
+ * @returns the record.
473
+ */
474
+ function emptyDeclarations() {
475
+ return Object.create(null);
476
+ }
477
+ /**
478
+ * Copy a declarations record before a transition adds to it.
479
+ * @param declared - the record published by the previous state.
480
+ * @returns a new record with the same entries.
481
+ */
482
+ function copyDeclarations(declared) {
483
+ return Object.assign(emptyDeclarations(), declared);
484
+ }
485
+ /**
486
+ * Record which pool definition each declared tool name currently means.
487
+ * @param tools - declared definitions in order; a repeated name keeps its last declaration.
488
+ * @param ids - pool indexes of `tools`, one per entry.
489
+ * @returns a name-to-index record without a prototype.
490
+ */
491
+ function declarationsOf(tools, ids) {
492
+ const declared = emptyDeclarations();
493
+ tools.forEach((tool, position) => {
494
+ declared[tool.name] = ids[position];
495
+ });
496
+ return declared;
497
+ }
498
+ /**
499
+ * Read one pooled definition by index.
500
+ * @param pool - a state's pool.
501
+ * @param id - an index produced by interning.
502
+ * @returns the definition stored at that index.
503
+ */
504
+ function definitionAt(pool, id) {
505
+ const tool = pool[id];
506
+ /* v8 ignore next -- indexes come from interning the same pool. */
507
+ if (tool === void 0) throw new Error(`tool history state: no definition at pool index ${id}`);
508
+ return tool;
509
+ }
510
+ /**
511
+ * Turn pool indexes into the definitions a reader receives.
512
+ * @param pool - the state's pool.
513
+ * @param ids - indexes into that pool.
514
+ * @returns the definitions in the same order.
515
+ */
516
+ function lookupTools(pool, ids) {
517
+ return ids.map((id) => definitionAt(pool, id));
518
+ }
519
+ /** Materialized series histories, keyed by the state's `history` object; a cache only, never part of a state. */
520
+ const historyViews = /* @__PURE__ */ new WeakMap();
521
+ /** Materialized fallback views, keyed by the active index list; a cache only, never part of a state. */
522
+ const fallbackViews = /* @__PURE__ */ new WeakMap();
523
+ /** Folds committed headers and developer messages independently of model capability. */
524
+ const transitions = {
525
+ /**
526
+ * Consume the next committed event in log order.
527
+ * @param event - a session event, including inherited events during restoration.
528
+ */
529
+ apply(event) {
530
+ if (event.type === "request/header") {
531
+ const tools = event.data.header.tools ?? [];
532
+ const interned = internTools(this.pool, tools);
533
+ this.pool = interned.pool;
534
+ this.headers = {
535
+ seq: event.seq,
536
+ tools: interned.ids,
537
+ prev: this.headers
538
+ };
539
+ const pooled = indexOfPool(this.pool).texts;
540
+ const redeclared = tools.some((tool, position) => {
541
+ const before = Object.hasOwn(this.declared, tool.name) ? this.declared[tool.name] : void 0;
542
+ return before !== void 0 && pooled[before] !== interned.texts[position];
543
+ });
544
+ if (this.baselineSeq === void 0 || event.data.reason === "series" || event.data.startsSeries || redeclared) {
545
+ this.baselineSeq = event.seq;
546
+ this.declared = declarationsOf(tools, interned.ids);
547
+ this.history = {
548
+ tools: interned.ids,
549
+ updates: []
550
+ };
551
+ this.available = [...new Set(tools.map((tool) => tool.name))];
552
+ }
553
+ this.active = interned.ids;
554
+ } else {
555
+ const { message, headerSeq } = event.data;
556
+ const declaredBy = headerSeq === void 0 ? void 0 : headerAt(this.headers, headerSeq);
557
+ const additions = message.content.flatMap((block) => {
558
+ if (block.type !== "tool-addition") return [];
559
+ const id = declaredBy?.tools.find((id) => definitionAt(this.pool, id).name === block.toolName);
560
+ if (id === void 0) throw new Error(`tool history: missing definition for ${block.toolName}`);
561
+ return [id];
562
+ });
563
+ if (additions.length > 0) {
564
+ this.declared = copyDeclarations(this.declared);
565
+ for (const id of additions) this.declared[definitionAt(this.pool, id).name] = id;
566
+ }
567
+ this.available = [...this.available];
568
+ for (const block of message.content) if (block.type === "tool-addition" && !this.available.includes(block.toolName)) this.available.push(block.toolName);
569
+ else if (block.type === "tool-removal") this.available = this.available.filter((name) => name !== block.toolName);
570
+ this.history = {
571
+ tools: this.history.tools,
572
+ updates: [...this.history.updates, {
573
+ messageId: message.id,
574
+ additions
575
+ }]
576
+ };
577
+ }
578
+ },
579
+ /**
580
+ * Read a snapshot; later transitions do not mutate the returned object.
581
+ * @returns initial declarations and historically resolved additions for the current series.
582
+ */
583
+ snapshot() {
584
+ const activeNames = this.active.map((id) => definitionAt(this.pool, id).name);
585
+ if (activeNames.length !== this.available.length || activeNames.some((name) => !this.available.includes(name))) {
586
+ let view = fallbackViews.get(this.active);
587
+ if (view === void 0) {
588
+ view = {
589
+ tools: lookupTools(this.pool, this.active),
590
+ updates: []
591
+ };
592
+ fallbackViews.set(this.active, view);
593
+ }
594
+ return view;
595
+ }
596
+ let view = historyViews.get(this.history);
597
+ if (view === void 0) {
598
+ view = {
599
+ tools: lookupTools(this.pool, this.history.tools),
600
+ updates: this.history.updates.map((update) => ({
601
+ messageId: update.messageId,
602
+ additions: lookupTools(this.pool, update.additions)
603
+ }))
604
+ };
605
+ historyViews.set(this.history, view);
606
+ }
607
+ return view;
608
+ }
609
+ };
610
+ /**
611
+ * Create the state before any event.
612
+ * @returns an empty fold with no header, an empty pool and an empty history.
613
+ */
614
+ function createToolHistoryState() {
615
+ return {
616
+ pool: [],
617
+ headers: void 0,
618
+ declared: emptyDeclarations(),
619
+ active: [],
620
+ available: [],
621
+ baselineSeq: void 0,
622
+ history: {
623
+ tools: [],
624
+ updates: []
625
+ }
626
+ };
627
+ }
628
+ /**
629
+ * Copy a state so that one transition can update the copy in place.
630
+ * @param state - the published state being advanced.
631
+ * @returns a plain state sharing every field the transition does not replace.
632
+ */
633
+ function fork(state) {
634
+ return {
635
+ pool: state.pool,
636
+ headers: state.headers,
637
+ declared: state.declared,
638
+ active: state.active,
639
+ available: state.available,
640
+ baselineSeq: state.baselineSeq,
641
+ history: state.history
642
+ };
643
+ }
644
+ /**
645
+ * Advance the fold by one committed event.
646
+ * @param state - state covering all prior events.
647
+ * @param event - the next committed event.
648
+ * @returns the next state, or `state` itself for an event type the fold does not read.
649
+ * @throws Error when a developer message adds a tool that the committed header it references did not declare.
650
+ */
651
+ function advanceToolHistory(state, event) {
652
+ if (event.type !== "request/header" && event.type !== "developer/message") return state;
653
+ const next = fork(state);
654
+ transitions.apply.call(next, event);
655
+ return next;
656
+ }
657
+ /**
658
+ * Read the tool history a state implies; freezing the result is the caller's job.
659
+ * @param state - a state returned by {@link advanceToolHistory} or by the definition's `init`, also after a JSON round trip.
660
+ * @returns the series history while its baseline and updates account for every active declaration,
661
+ * otherwise the complete active declarations with no updates. Definitions are the pool's objects.
662
+ */
663
+ function snapshotToolHistory(state) {
664
+ return transitions.snapshot.call(state);
665
+ }
666
+ /**
667
+ * State definition that `Session.toolHistory()` reads: the active tool
668
+ * declarations of the current series with the additions recorded by developer
669
+ * messages, or the complete active declarations alone while the latest header
670
+ * lacks its update record. Before the first header the history is empty.
671
+ */
672
+ const toolHistoryStateDefinition = {
673
+ key: "toolHistory",
674
+ init: createToolHistoryState,
675
+ apply: advanceToolHistory
676
+ };
677
+ //#endregion
678
+ //#region lib/types/validation.js
679
+ /**
680
+ * Complete session log validation without constructing a Session.
681
+ * @module @deepseek-ai/dsh-session-store/validation
682
+ */
683
+ /**
684
+ * Admit one validated event through the surface transition.
685
+ * @param event - validated event at `index`, not yet in the log `surface` reads.
686
+ * @param index - position in the log being replayed.
687
+ * @param surface - incremental surface validator carrying the message interpreters.
688
+ * @throws `invalid seed event at index <index>: …` when the surface rejects the event.
689
+ */
690
+ function replaySurfaceEvent(event, index, surface) {
691
+ try {
692
+ surface.validateNext(event);
693
+ } catch (error) {
694
+ throw new Error(`invalid seed event at index ${index}: ${error instanceof Error ? error.message : "invalid surface metadata"}`);
695
+ }
696
+ }
697
+ /**
698
+ * Replay validated events through the surface in order and push each accepted event into `log`, which `surface` reads.
699
+ * Each event passes the surface transition before it enters `log`.
700
+ * @param events - events accepted by `checkSessionLog`.
701
+ * @param log - empty log that `surface` was constructed over.
702
+ * @param surface - incremental surface validator carrying the message interpreters.
703
+ * @throws on the first invalid surface transition; `log` then holds the accepted prefix.
704
+ */
705
+ function replaySurfaceEvents(events, log, surface) {
706
+ for (const [index, event] of events.entries()) {
707
+ replaySurfaceEvent(event, index, surface);
708
+ log.push(event);
709
+ }
710
+ }
711
+ /**
712
+ * Validate a header and event log without constructing a Session. It runs the
713
+ * two stages Session construction runs: first the structural checks on the
714
+ * header, event envelopes, sequences, and inherited cut, then surface replay
715
+ * in event order. Because the stages do not interleave, a log with several
716
+ * invalid points can report a different first error than an interleaved
717
+ * per-event check.
718
+ * Without `eventState` the checks use the borrowed seed mode: events and header
719
+ * are copied before validation. With it they validate and deeply freeze
720
+ * `header` in place and leave events uncopied.
721
+ * Embedded Assistant streams are not replayed.
722
+ * @param header - header whose `id` is the Session identity.
723
+ * @param events - seed events; omitted means no seed.
724
+ * @param inheritedEventCount - exact fork-inherited prefix length; required when `header.isSeeded`.
725
+ * @param eventState - aliasing state of adopted events; omitted for borrowed events.
726
+ * @param projections - message interpreters for plugin-owned events.
727
+ * @throws on the first invalid header field, event envelope, sequence, or inherited cut, then on the first invalid surface transition.
728
+ */
729
+ function validateSessionLog(header, events, inheritedEventCount, eventState, projections = []) {
730
+ const checked = checkSessionLog(header.id, header, events, inheritedEventCount, eventState ?? "snapshot");
731
+ const log = [];
732
+ replaySurfaceEvents(checked.events, log, new SurfaceManager(log, SessionLogOffset(0), projections));
733
+ }
734
+ //#endregion
735
+ //#region lib/types/preparation.js
736
+ /**
737
+ * Ownership of one unpublished Session before registry publication.
738
+ * @module @deepseek-ai/dsh-session-store/preparation
739
+ */
740
+ /**
741
+ * One exact unpublished Session and the provider state that keeps it usable.
742
+ * Disposal is synchronous and idempotent. Providers decide whether release
743
+ * returns the Session to a cache or discards it; publication may consume that
744
+ * state before disposal, making the callback a no-op.
745
+ */
746
+ var SessionPreparation = class SessionPreparation {
747
+ options;
748
+ released = false;
749
+ /** The exact Session to use for setup and publication. */
750
+ session;
751
+ constructor(session, options) {
752
+ this.options = options;
753
+ this.session = session;
754
+ }
755
+ /**
756
+ * Wrap an unpublished Session in one preparation lifetime.
757
+ * @param session - exact unpublished Session.
758
+ * @param options - optional provider release behavior.
759
+ * @returns a preparation disposed after publication or rollback.
760
+ */
761
+ static create(session, options) {
762
+ return new SessionPreparation(session, options ?? {});
763
+ }
764
+ /** Release provider state once when this preparation leaves its caller. */
765
+ [Symbol.dispose]() {
766
+ if (this.released) return;
767
+ this.released = true;
768
+ this.options.release?.();
769
+ }
770
+ };
771
+ //#endregion
772
+ //#region lib/types/index.js
773
+ /**
774
+ * Event-sourced session service: append-only session log, in-memory store, and
775
+ * the derived LLM message history. Persistence is a plugin concern (subscribe
776
+ * to `session/event`, drain on `session/flush`).
777
+ *
778
+ * @module @deepseek-ai/dsh-session-store
779
+ */
780
+ /** Resolve one listener snapshot, including Cordis's internal dispatch checks. */
781
+ function collectSessionCallbacks(ctx, args) {
782
+ return [...ctx.events.dispatch("emit", args)];
783
+ }
784
+ /** Invoke one resolved observe-only listener snapshot with per-listener containment. */
785
+ function invokeContainedSessionObservers(ctx, name, id, args, callbacks) {
786
+ for (const callback of callbacks) try {
787
+ const returned = callback(...args);
788
+ Promise.resolve(returned).catch((error) => {
789
+ ctx.logger.warn(`session "${id}": ${name} listener rejected: ${String(error)}`);
790
+ });
791
+ } catch (error) {
792
+ ctx.logger.warn(`session "${id}": ${name} listener threw: ${String(error)}`);
793
+ }
794
+ }
795
+ /** Store-owned Sessions retain a null entry while unentered; absent keys are independent. */
796
+ const attachments = /* @__PURE__ */ new WeakMap();
797
+ /**
798
+ * Grammar of a {@link PluginRecordType}: `plugin:` followed by
799
+ * slash-separated segments of lowercase letters, digits, `.`, `_`, and `-`,
800
+ * each segment starting with a letter or digit.
801
+ */
802
+ const PLUGIN_RECORD_TYPE = /^plugin:[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/u;
803
+ /**
804
+ * Whether one event type name follows the plugin record grammar.
805
+ * @param type - an event type name.
806
+ * @returns whether the name is a {@link PluginRecordType}.
807
+ */
808
+ function isPluginRecordType(type) {
809
+ return PLUGIN_RECORD_TYPE.test(type);
810
+ }
811
+ /**
812
+ * Type one constructed plugin record as a log event after checking its type
813
+ * against the plugin record grammar. A restored Session already holds events
814
+ * whose types are outside `SessionEventMap` when they are marked ignorable;
815
+ * a plugin record is such an event.
816
+ * @param value - the frozen record envelope built by {@link Session}.
817
+ * @throws when the record type is outside the plugin record grammar.
818
+ */
819
+ function assertPluginRecordEvent(value) {
820
+ const { type } = value;
821
+ if (!isPluginRecordType(type)) throw new Error(`plugin record type "${type}" must be "plugin:" followed by lowercase slash-separated segments`);
822
+ }
823
+ /** Module-private access to {@link Session}'s record commit, assigned once by its static block. */
824
+ let commitPluginRecord;
825
+ /**
826
+ * Append one experimental plugin record: an event marked `ignorable` whose
827
+ * type is declared in {@link PluginRecordMap}, outside {@link SessionEventMap}.
828
+ * The plugin record catalog lists it separately from released event schemas.
829
+ * A reader that does not recognize the type retains and skips the record, which never
830
+ * enters the model-visible surface, and fork and resume carry it with the rest
831
+ * of the log. A Session format migration retains records on a best-effort
832
+ * basis, so a record holds plugin-owned state that its owner can lose without
833
+ * changing how the rest of the log is interpreted.
834
+ *
835
+ * Only production source under `packages/experimental/` may call this
836
+ * function; the `verify-plugin-record-callers` gate rejects any other
837
+ * production caller in this repository. Read records back with
838
+ * {@link pluginRecordOf}.
839
+ * @param session - the Session whose log receives the record.
840
+ * @param type - declared record name: `plugin:` followed by slash-separated
841
+ * segments of lowercase letters, digits, `.`, `_`, and `-`, each starting
842
+ * with a letter or digit.
843
+ * @param data - JSON payload, snapshotted before it enters the log.
844
+ * @returns the sequence number of the committed record.
845
+ * @throws when a store-owned Session is unentered or its creation announcement
846
+ * has not completed, when `type` is outside
847
+ * that grammar, when `data` is not losslessly
848
+ * JSON-serializable, or when the call reenters another append's publication;
849
+ * a rejected record does not change the log.
850
+ */
851
+ function appendPluginRecord(session, type, data) {
852
+ return commitPluginRecord(session, type, data);
853
+ }
854
+ /**
855
+ * Read one committed event as a plugin record. The V3-to-V4 format edge also
856
+ * renames each unknown ignorable V3 event into the `plugin:` namespace, so an
857
+ * owner names its records under its own package name and validates `data`.
858
+ * @param event - any committed Session event, live or restored.
859
+ * @returns the record, or undefined when the event is not an ignorable event
860
+ * whose type follows the plugin record grammar.
861
+ */
862
+ function pluginRecordOf(event) {
863
+ const type = event.type;
864
+ if (event.ignorable !== true || !isPluginRecordType(type)) return void 0;
865
+ return {
866
+ type,
867
+ seq: event.seq,
868
+ time: event.time,
869
+ data: event.data
870
+ };
871
+ }
872
+ /** Copy live append inputs before sequence assignment. */
873
+ function snapshotAppend(type, data, opts, subject) {
874
+ const surfaceOp = opts?.surfaceOp;
875
+ const sourceEventSeqs = opts?.sourceEventSeqs;
876
+ const dataSnapshot = snapshotJsonValue(data);
877
+ if (dataSnapshot === void 0) throw new Error(`${subject} carries non-JSON-serializable data`);
878
+ const surface = snapshotJsonValue({
879
+ ...sourceEventSeqs === void 0 ? {} : { sourceEventSeqs },
880
+ ...surfaceOp === void 0 ? {} : { surfaceOp }
881
+ });
882
+ if (surface === void 0) throw new Error(`${subject} carries non-JSON-serializable surface metadata`);
883
+ return {
884
+ type,
885
+ data: dataSnapshot,
886
+ surface
887
+ };
888
+ }
889
+ /** Construct and validate one live event from detached inputs. */
890
+ function createAppendEvent(snapshot, seq) {
891
+ const { type, data, surface } = snapshot;
892
+ const event = deepFreeze({
893
+ type,
894
+ seq,
895
+ time: Date.now(),
896
+ data,
897
+ ...surface
898
+ });
899
+ validateSessionEventData(event, `session event "${type}" at seq ${seq}`);
900
+ return event;
901
+ }
902
+ /**
903
+ * An event-sourced session: an append-only log of {@link SessionEvent}s.
904
+ *
905
+ * Plain class (not a Service) — instances are constructed over session data,
906
+ * and plugins reach live instances through `ctx.sessions`.
907
+ */
908
+ var Session = class Session {
909
+ /**
910
+ * Surface-accepted references to the data's events, read by the surface and
911
+ * the incremental folds. Transitional: it holds the same event objects as the
912
+ * data's log, and every append pushes to both.
913
+ */
914
+ log = [];
915
+ /** The data this Session was constructed from; every append and event read goes through it. */
916
+ data;
917
+ batchPublication;
918
+ /** Single incremental owner of surface acceptance and projection state. */
919
+ surfaceManager;
920
+ get surface() {
921
+ return this.surfaceManager;
922
+ }
923
+ header;
924
+ inheritedEventCount;
925
+ get id() {
926
+ return this.header.id;
927
+ }
928
+ firstLiveSeq;
929
+ firstLifecycleSeq;
930
+ /**
931
+ * Construct a detached Session over data that no other Session was
932
+ * constructed from: replay its events through the surface and append the
933
+ * marker that `mode` requires. Appends go through the data.
934
+ * @param data - writable data whose header, events, and inherited cut are validated.
935
+ * @param options.mode - `create` for new data, `restore` for opened stored data.
936
+ * @param options.projections - pure interpreters for plugin-owned message changes.
937
+ * @returns a detached session.
938
+ * @throws when an event fails surface replay or requires a missing message interpreter.
939
+ */
940
+ static fromData(data, options) {
941
+ return new Session(data, options.mode, options.projections);
942
+ }
943
+ constructor(data, mode, projections = []) {
944
+ this.data = data;
945
+ this.surfaceManager = new SurfaceManager(this.log, SessionLogOffset(0), projections);
946
+ replaySurfaceEvents(data.snapshotEvents(), this.log, this.surfaceManager);
947
+ this.firstLiveSeq = SessionLogOffset(this.log.length);
948
+ this.header = data.header;
949
+ const inheritedEventCount = data.inheritedEventCount;
950
+ this.inheritedEventCount = inheritedEventCount;
951
+ this.firstLifecycleSeq = mode === "create" && this.header.isSeeded ? inheritedEventCount : this.firstLiveSeq;
952
+ if (mode === "create" && needsInheritedSeedMarker(this.header, this.log, inheritedEventCount)) this.append("session/end-seed", { inherited: true });
953
+ else if ((mode === "restore" || !this.header.isSeeded && !data.isEmpty) && this.log.at(-1)?.type !== "session/end-seed") this.append("session/end-seed", {});
954
+ }
955
+ /**
956
+ * Return the immutable event stored at one exact sequence number.
957
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
958
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
959
+ * @param seq - event sequence number.
960
+ * @returns the accepted event, or undefined when the log does not contain it.
961
+ */
962
+ eventAt(seq) {
963
+ return this.data.eventAt(seq);
964
+ }
965
+ /**
966
+ * Materialize an immutable snapshot of a half-open event sequence range.
967
+ * A full current snapshot is reused until the next append; every previously
968
+ * returned snapshot remains stable after later appends.
969
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
970
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
971
+ * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
972
+ * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
973
+ * @returns a frozen array of the selected deeply frozen events.
974
+ */
975
+ snapshotEvents(fromSeq = SessionLogOffset(0), toSeqExclusive = this.seq) {
976
+ return this.data.snapshotEvents(fromSeq, toSeqExclusive);
977
+ }
978
+ /**
979
+ * Read an immutable snapshot of a half-open event sequence range.
980
+ * The range is captured when the call starts; later appends do not change the result.
981
+ * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
982
+ * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
983
+ * @returns a frozen array of the selected deeply frozen events.
984
+ */
985
+ readEvents(fromSeq = SessionLogOffset(0), toSeqExclusive = this.seq) {
986
+ return this.data.readEvents(fromSeq, toSeqExclusive);
987
+ }
988
+ /**
989
+ * Return the read-only view of this Session's data: the same object on every
990
+ * call, sharing the log and seeing later appends.
991
+ * @returns the data's view.
992
+ */
993
+ readonlyView() {
994
+ return this.data.readonlyView();
995
+ }
996
+ /**
997
+ * Return this Session's events after its fork-inherited prefix.
998
+ * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
999
+ * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
1000
+ * @returns a fresh array containing child-owned events in log order.
1001
+ */
1002
+ ownEvents() {
1003
+ return this.snapshotEvents(this.inheritedEventCount);
1004
+ }
1005
+ isOwnSeq(seq) {
1006
+ return seq >= this.inheritedEventCount && seq < this.seq;
1007
+ }
1008
+ get seq() {
1009
+ return this.data.seq;
1010
+ }
1011
+ get currentBatchPublication() {
1012
+ return this.batchPublication;
1013
+ }
1014
+ append(type, data, ...opts) {
1015
+ if (typeof type !== "string") return this.#appendEvents(type);
1016
+ this.publicationEntry();
1017
+ const snapshot = snapshotAppend(type, data, opts[0], `session event "${type}"`);
1018
+ const entry = this.publicationEntry();
1019
+ const event = createAppendEvent(snapshot, SessionSeq(this.log.length));
1020
+ this.commit(event, entry);
1021
+ return event;
1022
+ }
1023
+ /**
1024
+ * Validate and publish consecutive events together. Observers see the complete log.
1025
+ * @param inputs - event payloads and surface intents in commit order.
1026
+ * @returns immutable committed events in the same order.
1027
+ * @throws before changing the log if any candidate or synchronous dispatch validation fails.
1028
+ */
1029
+ #appendEvents(inputs) {
1030
+ this.publicationEntry();
1031
+ if (inputs.length === 0) return [];
1032
+ const snapshots = Array.from({ length: inputs.length }, (_, index) => {
1033
+ const input = inputs.at(index);
1034
+ if (input === void 0) throw new Error(`session batch has an empty member at index ${index}`);
1035
+ const [type, data, surfaceOpts] = input;
1036
+ return snapshotAppend(type, data, surfaceOpts, `session batch member ${index} ("${type}")`);
1037
+ });
1038
+ const entry = this.publicationEntry();
1039
+ const startSeq = this.log.length;
1040
+ const events = snapshots.map((snapshot, index) => createAppendEvent(snapshot, SessionSeq(startSeq + index)));
1041
+ const acceptSurface = this.surfaceManager.prepareBatch(events);
1042
+ if (entry !== void 0) entry.appending = true;
1043
+ try {
1044
+ const publications = entry === void 0 ? [] : events.map((event) => {
1045
+ const args = [this, event];
1046
+ return {
1047
+ event,
1048
+ args,
1049
+ callbacks: collectSessionCallbacks(entry.emitCtx, [
1050
+ entry.carrier,
1051
+ "session/event",
1052
+ ...args
1053
+ ])
1054
+ };
1055
+ });
1056
+ for (const event of events) this.log.push(event);
1057
+ this.data.append(events);
1058
+ acceptSurface();
1059
+ if (entry !== void 0) for (const { event, args, callbacks } of publications) {
1060
+ this.batchPublication = event;
1061
+ invokeContainedSessionObservers(entry.emitCtx, "session/event", entry.id, args, callbacks);
1062
+ }
1063
+ } finally {
1064
+ this.batchPublication = void 0;
1065
+ if (entry !== void 0) {
1066
+ entry.appending = false;
1067
+ if (entry.detachRequested) entry.detach();
1068
+ }
1069
+ }
1070
+ return events;
1071
+ }
1072
+ static {
1073
+ commitPluginRecord = (session, type, data) => session.#appendRecord(type, data);
1074
+ }
1075
+ /**
1076
+ * Commit one plugin record; {@link appendPluginRecord} is the only caller.
1077
+ * @param type - record type, checked against the plugin record grammar.
1078
+ * @param data - JSON payload, snapshotted before it enters the log.
1079
+ * @returns the record's sequence number.
1080
+ */
1081
+ #appendRecord(type, data) {
1082
+ this.publicationEntry();
1083
+ const dataSnapshot = snapshotJsonValue(data);
1084
+ if (dataSnapshot === void 0) throw new Error(`plugin record "${type}" carries non-JSON-serializable data`);
1085
+ const entry = this.publicationEntry();
1086
+ const record = deepFreeze({
1087
+ type,
1088
+ seq: SessionSeq(this.log.length),
1089
+ time: Date.now(),
1090
+ data: dataSnapshot,
1091
+ ignorable: true
1092
+ });
1093
+ assertPluginRecordEvent(record);
1094
+ this.commit(record, entry);
1095
+ return record.seq;
1096
+ }
1097
+ /**
1098
+ * Require announced membership for store-owned Sessions and refuse reentrant publication.
1099
+ * @returns the current store attachment, or undefined for an independent Session.
1100
+ */
1101
+ publicationEntry() {
1102
+ const entry = attachments.get(this);
1103
+ if (entry === null) throw new Error(`session "${this.id}" cannot append outside a SessionStore`);
1104
+ if (entry !== void 0 && entry.announcement !== "complete") throw new Error(`session "${this.id}" cannot append before session/created completes`);
1105
+ if (entry?.appending) throw new Error("session append cannot reenter while another append is being published");
1106
+ return entry;
1107
+ }
1108
+ /**
1109
+ * Accept one frozen candidate at the next sequence number, enter it into the
1110
+ * log, and notify `session/event` observers with per-listener containment.
1111
+ * @param event - the candidate built at the current log length.
1112
+ * @param entry - the attachment read before the candidate was built.
1113
+ */
1114
+ commit(event, entry) {
1115
+ this.surfaceManager.validateNext(event);
1116
+ if (entry !== void 0) entry.appending = true;
1117
+ try {
1118
+ const callbackArgs = [this, event];
1119
+ const callbacks = entry === void 0 ? void 0 : collectSessionCallbacks(entry.emitCtx, [
1120
+ entry.carrier,
1121
+ "session/event",
1122
+ ...callbackArgs
1123
+ ]);
1124
+ this.log.push(event);
1125
+ this.data.append([event]);
1126
+ if (entry !== void 0 && callbacks !== void 0) invokeContainedSessionObservers(entry.emitCtx, "session/event", entry.id, callbackArgs, callbacks);
1127
+ } finally {
1128
+ if (entry !== void 0) {
1129
+ entry.appending = false;
1130
+ if (entry.detachRequested && entry.announcement !== "dispatching") entry.detach();
1131
+ }
1132
+ }
1133
+ }
1134
+ /** Header {@link requestHeader} froze last; the same object is not frozen again. */
1135
+ frozenHeader;
1136
+ /**
1137
+ * The {@link EpochHeader} in force after the log's last header event — the
1138
+ * header the NEXT request will be compared against — or undefined before
1139
+ * the first `request/header` snapshot. Read by evaluating
1140
+ * `requestHeaderStateDefinition` over this Session's data, so each header
1141
+ * event is folded once.
1142
+ * @returns the immutable header, or undefined when no header event exists yet.
1143
+ */
1144
+ requestHeader() {
1145
+ const header = this.data.evaluateState(requestHeaderStateDefinition) ?? void 0;
1146
+ if (header !== void 0 && header !== this.frozenHeader) this.frozenHeader = deepFreeze(header);
1147
+ return header;
1148
+ }
1149
+ /** Route metadata {@link requestContext} froze last; the same object is not frozen again. */
1150
+ frozenContext;
1151
+ /**
1152
+ * Return the latest resolved route metadata, or `undefined` before the first
1153
+ * `request/context` event. Read by evaluating `requestContextStateDefinition`
1154
+ * over this Session's data, so each event is folded once.
1155
+ * @returns the latest immutable route metadata.
1156
+ */
1157
+ requestContext() {
1158
+ const context = this.data.evaluateState(requestContextStateDefinition) ?? void 0;
1159
+ if (context !== void 0 && context !== this.frozenContext) this.frozenContext = deepFreeze(context);
1160
+ return context;
1161
+ }
1162
+ /** Tool history {@link toolHistory} froze last; the same object is not frozen again. */
1163
+ frozenToolHistory;
1164
+ /**
1165
+ * Return the capability-independent tool history for request projection.
1166
+ * Read by evaluating `toolHistoryStateDefinition` over this Session's data,
1167
+ * so each committed header and developer message is folded once.
1168
+ * @returns the immutable snapshot: the current series' active declarations
1169
+ * with the historical additions recorded by developer messages, or the
1170
+ * complete active declarations alone while the latest header lacks its
1171
+ * update record.
1172
+ */
1173
+ toolHistory() {
1174
+ const snapshot = snapshotToolHistory(this.data.evaluateState(toolHistoryStateDefinition));
1175
+ if (snapshot !== this.frozenToolHistory) this.frozenToolHistory = deepFreeze(snapshot);
1176
+ return snapshot;
1177
+ }
1178
+ /** The derived-message cache: frozen projections, extended per unseen node. */
1179
+ derived = [];
1180
+ /** Surface position (nodes projected) the cache has reached. */
1181
+ derivedNodes = 0;
1182
+ /** {@link SurfaceManager.contentGeneration} the cache was built under. */
1183
+ derivedGeneration = 0;
1184
+ deriveMessages() {
1185
+ const surface = this.surface;
1186
+ const nodes = surface.nodes;
1187
+ const generation = surface.contentGeneration;
1188
+ if (generation !== this.derivedGeneration) {
1189
+ this.derived = [];
1190
+ this.derivedNodes = 0;
1191
+ this.derivedGeneration = generation;
1192
+ }
1193
+ for (const seq of nodes.slice(this.derivedNodes)) {
1194
+ const msg = this.deriveEventMessage(this.log[seq]);
1195
+ if (msg) this.derived.push(msg);
1196
+ }
1197
+ this.derivedNodes = nodes.length;
1198
+ return [...this.derived];
1199
+ }
1200
+ deriveEventMessage(event) {
1201
+ return this.surfaceManager.deriveEventMessage(event);
1202
+ }
1203
+ };
1204
+ /**
1205
+ * In-memory session store (`ctx.sessions`).
1206
+ *
1207
+ * Persistence is intentionally not implemented here — the agent lifecycle
1208
+ * attaches a session-log writer to each published session's write handle;
1209
+ * a session published outside that lifecycle persists nothing.
1210
+ */
1211
+ var SessionStore = class extends Service {
1212
+ store = /* @__PURE__ */ new Map();
1213
+ projections = [];
1214
+ get messageProjections() {
1215
+ return this.projections;
1216
+ }
1217
+ registerMessageProjection(projection) {
1218
+ if (this.projections.some((item) => item.type === projection.type)) throw new Error(`session message projection "${projection.type}" is already registered`);
1219
+ return this.ctx.effect(() => {
1220
+ this.projections.push(projection);
1221
+ return () => {
1222
+ this.projections.splice(this.projections.indexOf(projection), 1);
1223
+ };
1224
+ }, "sessions.registerMessageProjection()");
1225
+ }
1226
+ constructor(ctx) {
1227
+ super(ctx, "sessions");
1228
+ ctx.inject(["typert"], (typeCtx) => {
1229
+ typeCtx.typert.lookups.register("session", {
1230
+ parameter: "session",
1231
+ wire: "sessionId",
1232
+ resource: "session",
1233
+ hostTypeSymbol: "@deepseek-ai/dsh-session#Session",
1234
+ wireTypeSymbol: "@deepseek-ai/dsh-session/types#SessionId",
1235
+ resolve: (sessionId) => this.get(sessionId)
1236
+ });
1237
+ });
1238
+ }
1239
+ /**
1240
+ * Construct a store-owned, unentered Session from data that no other Session
1241
+ * was constructed from, with the store's message interpreters. Pairs with
1242
+ * {@link enter} + {@link announce}.
1243
+ * @param data - writable data; the caller still owns it when this throws.
1244
+ * @param options.mode - `create` for new data, `restore` for opened stored data.
1245
+ * @returns the store-owned session, not yet entered and read-only until announced.
1246
+ * @throws if a session with the data's id already exists or surface replay fails.
1247
+ */
1248
+ prepare(data, options) {
1249
+ const id = data.header.id;
1250
+ if (this.store.has(id)) throw new Error(`session "${id}" already exists`);
1251
+ const session = Session.fromData(data, {
1252
+ mode: options.mode,
1253
+ projections: this.projections
1254
+ });
1255
+ attachments.set(session, null);
1256
+ return session;
1257
+ }
1258
+ enter(session) {
1259
+ const id = session.id;
1260
+ const carrier = scopeTarget(session, scopeOf(this.ctx));
1261
+ if (this.store.has(id)) throw new Error(`session "${id}" already exists`);
1262
+ if (attachments.get(session) != null) throw new Error(`session "${id}" is already attached to a store`);
1263
+ const entry = {
1264
+ id,
1265
+ session,
1266
+ carrier,
1267
+ emitCtx: this.ctx,
1268
+ announcement: "pending",
1269
+ appending: false,
1270
+ detachRequested: false,
1271
+ detach: () => {
1272
+ this.detachEntered(entry);
1273
+ }
1274
+ };
1275
+ this.store.set(id, entry);
1276
+ attachments.set(session, entry);
1277
+ let entered = true;
1278
+ const detach = () => {
1279
+ if (!entered) return;
1280
+ entered = false;
1281
+ if (entry.announcement === "dispatching" || entry.appending) {
1282
+ entry.detachRequested = true;
1283
+ return;
1284
+ }
1285
+ entry.detach();
1286
+ };
1287
+ return detach;
1288
+ }
1289
+ /** Remove one exact entered session and emit its paired disposal when announced. */
1290
+ detachEntered(entry) {
1291
+ entry.detachRequested = false;
1292
+ /* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */
1293
+ if (this.store.get(entry.id) !== entry) return;
1294
+ this.store.delete(entry.id);
1295
+ attachments.set(entry.session, null);
1296
+ if (entry.announcement !== "pending") this.emitDisposed(entry);
1297
+ }
1298
+ announce(session) {
1299
+ const entry = this.liveEntryFor(session);
1300
+ if (entry.announcement !== "pending") throw new Error(`session "${entry.id}" was already announced`);
1301
+ const callbackArgs = [session];
1302
+ entry.announcement = "dispatching";
1303
+ try {
1304
+ const callbacks = collectSessionCallbacks(this.ctx, [
1305
+ entry.carrier,
1306
+ "session/created",
1307
+ session
1308
+ ]);
1309
+ for (const callback of callbacks) {
1310
+ const returned = callback(...callbackArgs);
1311
+ Promise.resolve(returned).catch((error) => {
1312
+ this.ctx.logger.warn(`session "${entry.id}": session/created listener rejected: ${String(error)}`);
1313
+ });
1314
+ }
1315
+ entry.announcement = "complete";
1316
+ } catch (error) {
1317
+ entry.announcement = "failed";
1318
+ throw error;
1319
+ } finally {
1320
+ if (entry.detachRequested) entry.detach();
1321
+ }
1322
+ }
1323
+ /** Emit the paired teardown notification with per-listener containment. */
1324
+ emitDisposed(entry) {
1325
+ const callbackArgs = [entry.session];
1326
+ try {
1327
+ const callbacks = collectSessionCallbacks(this.ctx, [
1328
+ entry.carrier,
1329
+ "session/disposed",
1330
+ entry.session
1331
+ ]);
1332
+ invokeContainedSessionObservers(this.ctx, "session/disposed", entry.id, callbackArgs, callbacks);
1333
+ } catch (error) {
1334
+ /* v8 ignore next -- the dispatch contract throws AggregateError */
1335
+ const members = error instanceof AggregateError ? ` [${error.errors.map(String).join("; ")}]` : "";
1336
+ this.ctx.logger.warn(`session "${entry.id}": session/disposed dispatch threw: ${String(error)}${members}`);
1337
+ }
1338
+ }
1339
+ async flush(session) {
1340
+ const { carrier } = this.liveEntryFor(session);
1341
+ const callbackArgs = [session];
1342
+ const callbacks = collectSessionCallbacks(this.ctx, [
1343
+ carrier,
1344
+ "session/flush",
1345
+ session
1346
+ ]);
1347
+ const failure = (await Promise.allSettled(callbacks.map((callback) => {
1348
+ try {
1349
+ return callback(...callbackArgs);
1350
+ } catch (error) {
1351
+ return Promise.reject(error);
1352
+ }
1353
+ }))).find((result) => result.status === "rejected");
1354
+ if (failure !== void 0) throw failure.reason;
1355
+ return callbacks.length > 0;
1356
+ }
1357
+ /** Return the exact live entry; detached/prepared objects reject. */
1358
+ liveEntryFor(session) {
1359
+ const entry = attachments.get(session);
1360
+ if (entry == null || this.store.get(entry.id) !== entry) throw new Error(`session "${session.id}" is not live in this store`);
1361
+ return entry;
1362
+ }
1363
+ get(id) {
1364
+ return this.store.get(id)?.session;
1365
+ }
1366
+ list() {
1367
+ return [...this.store.values()].map((entry) => entry.session);
1368
+ }
1369
+ };
1370
+ //#endregion
1371
+ export { Session, SessionPreparation, SessionStore, SessionStore as default, appendPluginRecord, canonicalHeader, foldSurface, headerEquals, pluginRecordOf, validateSessionLog };