@hasna-internal/kai-session 0.1.1-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,999 @@
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 @hasna-internal/kai-session
7
+ */
8
+ import { Service } from '@deepseek-ai/cordis';
9
+ import { isAbsolute } from 'node:path';
10
+ import { deepFreeze } from '@hasna-internal/kai-llm';
11
+ import { scopeOf, scopeTarget } from '@hasna-internal/kai-scope';
12
+ import { SESSION_FORMAT_VERSION, SessionId } from "./types.js";
13
+ import { snapshotJsonValue } from "./json.js";
14
+ import { deriveEventMessage, SurfaceManager } from "./surface.js";
15
+ import { foldRequestHeader } from "./request-header.js";
16
+ export * from "./types.js";
17
+ export { SessionPreparation } from "./preparation.js";
18
+ export { isJsonValue, snapshotJsonValue } from "./json.js";
19
+ export { interruptedTurnClosers, TOOL_NOT_STARTED, TOOL_OUTCOME_UNKNOWN } from "./repair.js";
20
+ export { decodeStorageRecord, packChunkRuns } from "./chunk-rows.js";
21
+ export { deriveEventMessage, foldSurface, isAppendSurfaceEvent, isReplacementSurfaceEvent, isSurfaceEvent, isSurfaceEligibleType } from "./surface.js";
22
+ export { canonicalHeader, foldRequestHeader, headerEquals } from "./request-header.js";
23
+ export { KNOWN_SESSION_EVENT_TYPES } from "./known-event-types.js";
24
+ /** Validate and freeze one detached creation header in place. */
25
+ function validateSessionHeader(id, input) {
26
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) {
27
+ throw new Error('session header is not a plain JSON record');
28
+ }
29
+ const record = input;
30
+ if (record.version !== SESSION_FORMAT_VERSION) {
31
+ throw new Error(`session header version must be ${SESSION_FORMAT_VERSION}, got ${String(record.version)}`);
32
+ }
33
+ if (record.id !== id) {
34
+ throw new Error(`session header id "${String(record.id)}" does not match session id "${id}"`);
35
+ }
36
+ if (typeof record.createdAt !== 'number'
37
+ || !Number.isSafeInteger(record.createdAt)
38
+ || record.createdAt < 0) {
39
+ throw new Error('session header createdAt must be a non-negative safe integer');
40
+ }
41
+ if (record.cwd !== undefined) {
42
+ if (typeof record.cwd !== 'string')
43
+ throw new Error('session header cwd must be a string');
44
+ if (!isAbsolute(record.cwd)) {
45
+ throw new Error(`session header cwd must be an absolute path, got "${record.cwd}"`);
46
+ }
47
+ }
48
+ if (record.parentSession !== undefined && typeof record.parentSession !== 'string') {
49
+ throw new Error('session header parentSession must be a string');
50
+ }
51
+ if (record.seedLength !== undefined
52
+ && (typeof record.seedLength !== 'number' || !Number.isSafeInteger(record.seedLength) || record.seedLength < 0)) {
53
+ throw new Error('session header seedLength must be a non-negative safe integer');
54
+ }
55
+ if (record.origin !== undefined && record.origin !== 'subagent') {
56
+ throw new Error('session header origin must be "subagent"');
57
+ }
58
+ if (record.delegationDepth !== undefined
59
+ && (typeof record.delegationDepth !== 'number' || !Number.isSafeInteger(record.delegationDepth) || record.delegationDepth < 0)) {
60
+ throw new Error('session header delegationDepth must be a non-negative safe integer');
61
+ }
62
+ if (record.agentPreset !== undefined && typeof record.agentPreset !== 'string') {
63
+ throw new Error('session header agentPreset must be a string');
64
+ }
65
+ return deepFreeze(record);
66
+ }
67
+ /** Validate and freeze one exclusively owned persistence header in place. */
68
+ function validateRestoredSessionHeader(id, input) {
69
+ if (input !== null && typeof input === 'object' && !Array.isArray(input)) {
70
+ const prototype = Reflect.getPrototypeOf(input);
71
+ if (prototype !== Object.prototype && prototype !== null) {
72
+ throw new Error('session header is not a plain JSON record');
73
+ }
74
+ }
75
+ return validateSessionHeader(id, input);
76
+ }
77
+ /** Detach, validate, and freeze the creation metadata published by a session. */
78
+ function snapshotSessionHeader(id, source) {
79
+ const input = source === undefined
80
+ ? { version: SESSION_FORMAT_VERSION, id, createdAt: Date.now() }
81
+ : source;
82
+ const snapshot = snapshotJsonValue(input);
83
+ if (snapshot === undefined)
84
+ throw new Error('session header is not losslessly JSON-serializable');
85
+ return validateSessionHeader(id, snapshot);
86
+ }
87
+ /**
88
+ * Validate an exclusively owned event and deeply freeze its identified message
89
+ * without copying the event. The caller transfers an object graph that no
90
+ * producer retains and that shares no mutable children with another event.
91
+ * Use {@link snapshotSessionEvent} when exclusive ownership is not guaranteed.
92
+ * @param event - exclusively owned event imported across a trusted boundary.
93
+ * @returns the same event object with a validated, deeply frozen message.
94
+ */
95
+ export function adoptSessionEvent(event) {
96
+ assertMessageEventShape(event, `session event at seq ${event.seq}`);
97
+ switch (event.type) {
98
+ case 'user/message':
99
+ deepFreeze(event.data);
100
+ break;
101
+ case 'assistant/message':
102
+ case 'tool/result':
103
+ deepFreeze(event.data.message);
104
+ break;
105
+ default:
106
+ // SessionEventMap is merge-extensible; plugin-owned events carry no core message.
107
+ break;
108
+ }
109
+ return event;
110
+ }
111
+ /**
112
+ * Detach one event while preserving deep immutability for its identified message.
113
+ * @param event - event imported across a query or persistence boundary.
114
+ * @returns a detached event snapshot with a validated, deeply frozen message.
115
+ */
116
+ export function snapshotSessionEvent(event) {
117
+ return adoptSessionEvent(structuredClone(event));
118
+ }
119
+ /** Deep-freeze one acyclic JSON tree without consuming the JavaScript call stack. */
120
+ function freezeRestoredObject(value) {
121
+ const pending = [value];
122
+ while (pending.length > 0) {
123
+ // The non-empty check proves an object remains to visit.
124
+ // oxlint-disable-next-line typescript/no-non-null-assertion
125
+ const current = pending.pop();
126
+ Object.freeze(current);
127
+ for (const key in current) {
128
+ const child = current[key];
129
+ if (child !== null && typeof child === 'object')
130
+ pending.push(child);
131
+ }
132
+ }
133
+ return value;
134
+ }
135
+ /** Validate the fixed event envelope after one-pass JSON materialization. */
136
+ function assertSessionEventEnvelope(value, index) {
137
+ const event = value;
138
+ if (event['type'] === 'request/header-delta') {
139
+ throw new Error(`seed event at index ${index} uses unsupported legacy request/header-delta format`);
140
+ }
141
+ for (const key in event) {
142
+ switch (key) {
143
+ case 'type':
144
+ case 'seq':
145
+ case 'time':
146
+ case 'data':
147
+ case 'surfaceOp':
148
+ case 'sourceEventSeqs':
149
+ case 'ignorable':
150
+ break;
151
+ default:
152
+ throw new Error(`seed event at index ${index} has an invalid event envelope`);
153
+ }
154
+ }
155
+ const type = event['type'];
156
+ const seq = event['seq'];
157
+ const time = event['time'];
158
+ if (typeof type !== 'string'
159
+ || typeof seq !== 'number' || !Number.isSafeInteger(seq) || seq < 0
160
+ || typeof time !== 'number' || !Number.isSafeInteger(time)
161
+ || event['data'] === undefined
162
+ || (event['ignorable'] !== undefined && event['ignorable'] !== true)) {
163
+ throw new Error(`seed event at index ${index} has an invalid event envelope`);
164
+ }
165
+ switch (type) {
166
+ case 'request/header':
167
+ case 'user/message':
168
+ case 'assistant/message':
169
+ case 'tool/result':
170
+ assertCurrentLlmShape(event, index);
171
+ break;
172
+ }
173
+ }
174
+ /** Reject obsolete request headers and malformed messages at the seed/load boundary. */
175
+ function assertCurrentLlmShape(event, index) {
176
+ const data = event['data'];
177
+ const record = typeof data === 'object' && data !== null
178
+ ? data
179
+ : undefined;
180
+ if (event['type'] === 'request/header') {
181
+ const header = record?.['header'];
182
+ const headerRecord = typeof header === 'object' && header !== null && !Array.isArray(header)
183
+ ? header
184
+ : undefined;
185
+ const config = headerRecord?.['config'];
186
+ if (!hasProviderModel(config))
187
+ throw new Error(`seed request/header at index ${index} lacks provider/model`);
188
+ const configRecord = config;
189
+ const reasoningEffort = configRecord['reasoningEffort'];
190
+ if (reasoningEffort !== undefined
191
+ && (typeof reasoningEffort !== 'string' || reasoningEffort.length === 0)) {
192
+ throw new Error(`seed request/header at index ${index} has an invalid reasoningEffort`);
193
+ }
194
+ assertAdapterDefaults(headerRecord?.['adapterDefaults'], configRecord, index);
195
+ }
196
+ const type = event['type'];
197
+ if (type !== 'user/message' && type !== 'assistant/message'
198
+ && type !== 'tool/result')
199
+ return;
200
+ assertMessageEventShape(event, `seed ${type} at index ${index}`);
201
+ }
202
+ const allowedAdapterKeys = new Set(['reasoningEffort', 'maxTokens']);
203
+ /** Validate adapter-default markers imported from a durable request header. */
204
+ function assertAdapterDefaults(value, config, index) {
205
+ if (value === undefined)
206
+ return;
207
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
208
+ throw new Error(`seed request/header at index ${index} has invalid adapterDefaults`);
209
+ }
210
+ const defaults = value;
211
+ if (Object.keys(defaults).some(key => !allowedAdapterKeys.has(key))
212
+ || Object.values(defaults).some(marker => marker !== true)
213
+ || defaults['reasoningEffort'] === true && config['reasoningEffort'] === undefined
214
+ || defaults['maxTokens'] === true && config['maxTokens'] === undefined) {
215
+ throw new Error(`seed request/header at index ${index} has invalid adapterDefaults`);
216
+ }
217
+ }
218
+ /** Validate only the event-specific invariants needed to safely replay a message. */
219
+ function assertMessageEventShape(event, subject) {
220
+ const type = event['type'];
221
+ if (type !== 'user/message' && type !== 'assistant/message'
222
+ && type !== 'tool/result')
223
+ return;
224
+ const data = event['data'];
225
+ const record = typeof data === 'object' && data !== null
226
+ ? data
227
+ : undefined;
228
+ const message = type === 'user/message' ? record : record?.['message'];
229
+ if (typeof message !== 'object' || message === null
230
+ || typeof message['id'] !== 'string'
231
+ || message['id'] === '') {
232
+ throw new Error(`${subject} lacks an identified message`);
233
+ }
234
+ const messageRecord = message;
235
+ const expectedRole = type === 'assistant/message' ? 'assistant' : 'user';
236
+ if (messageRecord['role'] !== expectedRole) {
237
+ throw new Error(`${subject} message must have role "${expectedRole}"`);
238
+ }
239
+ const source = messageRecord['source'];
240
+ if (typeof source !== 'object' || source === null
241
+ || typeof source['kind'] !== 'string'
242
+ || source['kind'] === '') {
243
+ throw new Error(`${subject} message has invalid source`);
244
+ }
245
+ if (!Array.isArray(messageRecord['content'])) {
246
+ throw new Error(`${subject} message has invalid content`);
247
+ }
248
+ const sourceRecord = source;
249
+ if (type === 'assistant/message') {
250
+ if (sourceRecord['kind'] !== 'model' || !hasProviderModel(sourceRecord)) {
251
+ throw new Error(`${subject} message must have model source`);
252
+ }
253
+ return;
254
+ }
255
+ if (type !== 'tool/result')
256
+ return;
257
+ if (sourceRecord['kind'] !== 'tool'
258
+ || typeof sourceRecord['callId'] !== 'string'
259
+ || sourceRecord['callId'] === '') {
260
+ throw new Error(`${subject} message must have tool source`);
261
+ }
262
+ const content = messageRecord['content'];
263
+ const block = content[0];
264
+ if (content.length !== 1 || typeof block !== 'object' || block === null
265
+ || block['type'] !== 'tool-result'
266
+ || !Array.isArray(block['content'])) {
267
+ throw new Error(`${subject} message must contain one tool-result block`);
268
+ }
269
+ if (block['toolCallId'] !== sourceRecord['callId']) {
270
+ throw new Error(`${subject} message has mismatched tool call ids`);
271
+ }
272
+ }
273
+ /** Whether an unknown value carries the current provider/model pair. */
274
+ function hasProviderModel(value) {
275
+ if (typeof value !== 'object' || value === null)
276
+ return false;
277
+ const pair = value;
278
+ return typeof pair['provider'] === 'string' && pair['provider'].length > 0
279
+ && typeof pair['model'] === 'string' && pair['model'].length > 0;
280
+ }
281
+ /** Reject request-header vocabulary removed with the legacy delta codec. */
282
+ function assertSupportedRequestHeader(type, data, location) {
283
+ if (type === 'request/header-delta') {
284
+ throw new Error(`${location} uses unsupported legacy request/header-delta format`);
285
+ }
286
+ if (type === 'request/header'
287
+ && data !== null && typeof data === 'object' && !Array.isArray(data)
288
+ && data['reason'] === 'fallback') {
289
+ throw new Error(`${location} uses unsupported legacy request/header reason "fallback"`);
290
+ }
291
+ }
292
+ /** Resolve one listener snapshot, including Cordis's internal dispatch checks. */
293
+ function collectSessionCallbacks(ctx, args) {
294
+ return [...ctx.events.dispatch('emit', args)];
295
+ }
296
+ /** Invoke one resolved observe-only listener snapshot with per-listener containment. */
297
+ function invokeContainedSessionObservers(ctx, name, id, args, callbacks) {
298
+ for (const callback of callbacks) {
299
+ try {
300
+ const returned = callback(...args);
301
+ void Promise.resolve(returned).catch((error) => {
302
+ ctx.logger.warn(`session "${id}": ${name} listener rejected: ${String(error)}`);
303
+ });
304
+ }
305
+ catch (error) {
306
+ ctx.logger.warn(`session "${id}": ${name} listener threw: ${String(error)}`);
307
+ }
308
+ }
309
+ }
310
+ /** Store attachment for the append path; module-private to keep Session store-agnostic publicly. */
311
+ const attachments = new WeakMap();
312
+ /**
313
+ * An event-sourced session: an append-only log of {@link SessionEvent}s.
314
+ *
315
+ * Plain class (not a Service) — create live instances via
316
+ * `ctx.sessions.create()` and detached instances via {@link create}.
317
+ * Seeding with an existing event log replays/forks a session.
318
+ * @typert object
319
+ */
320
+ export class Session {
321
+ log = [];
322
+ /** Single incremental owner of surface acceptance and projection state. */
323
+ surfaceManager = new SurfaceManager(this.log);
324
+ /** The ordered surface over this session's event log. */
325
+ get surface() {
326
+ return this.surfaceManager;
327
+ }
328
+ /**
329
+ * Detached, deep-frozen creation metadata (format version, cwd, lineage,
330
+ * seed boundary). Supplied by the store via `ctx.sessions.create()`. When a
331
+ * `Session` is created without a store-owned header, a minimal header is
332
+ * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
333
+ * `session.header` is always present. Kept out of the event log — it is a
334
+ * storage concern, not replayable conversation state.
335
+ */
336
+ header;
337
+ /** The session identity, derived from its durable header's single copy. */
338
+ get id() {
339
+ return this.header.id;
340
+ }
341
+ /**
342
+ * The first seq appended IN THIS PROCESS: the length of the constructor
343
+ * seed (0 without one). Events with smaller seq values entered through
344
+ * construction — replay, fork, or resume — and were never published on the
345
+ * `session/event` firehose (constructor seeds do not emit), so consumers
346
+ * that replay the log as a publication substitute (telemetry adoption)
347
+ * start here. Distinct from `header.seedLength`, the DURABLE fork-lineage
348
+ * boundary: a resumed session's constructor seed is its full stored log,
349
+ * while its header keeps the original fork value — this field is the
350
+ * in-process construction fact.
351
+ *
352
+ * Not persisted itself: a seeded session projects it into the log as the
353
+ * `session/end-seed` event, which is what a consumer reading STORED history
354
+ * reads. Locate the LAST such event, not necessarily one at this seq — a
355
+ * seed already ending in one is not re-marked, so reopening an untouched
356
+ * session leaves that event at a smaller seq than `firstLiveSeq`. Prefer
357
+ * this field in-process: it is exact before the marker reaches storage.
358
+ *
359
+ * When this lifecycle appends the marker, it occupies this seq before the
360
+ * store attaches and therefore does not publish either. Otherwise this seq
361
+ * holds an ordinary published write.
362
+ */
363
+ firstLiveSeq;
364
+ /**
365
+ * Create a detached session by validating and snapshotting borrowed seed
366
+ * events and storage metadata.
367
+ * @param id - session identity.
368
+ * @param seed - optional borrowed replay or fork events.
369
+ * @param header - optional borrowed storage metadata.
370
+ * @returns a detached session.
371
+ */
372
+ static create(id, seed, header) {
373
+ return new Session(id, seed, header);
374
+ }
375
+ /**
376
+ * Restore a detached session by taking ownership of fresh persistence values.
377
+ * The storage format, event envelopes, sequence continuity, surface transitions,
378
+ * and header fields are validated before the restored objects are frozen.
379
+ * @param id - restored session identity.
380
+ * @param seed - fresh detached events whose ownership is transferred.
381
+ * @param header - fresh detached metadata whose ownership is transferred.
382
+ * @returns a restored detached session.
383
+ */
384
+ static fromRestore(id, seed, header) {
385
+ return new Session(id, seed, header, 'restore');
386
+ }
387
+ constructor(id, seed, header, mode = 'snapshot') {
388
+ const restoredHeader = mode === 'restore'
389
+ ? validateRestoredSessionHeader(id, header)
390
+ : undefined;
391
+ if (seed !== undefined) {
392
+ // Validate the seed to the SAME invariants `append` enforces, so a
393
+ // replay/fork (`ctx.sessions.create(id, { seed })`) cannot construct a
394
+ // live log that no persistence backend could store: each event's `data`
395
+ // must be JSON-serializable, and `seq` must be contiguous from 0 (the
396
+ // `seq = log.length` contract the whole system relies on). Without this,
397
+ // a bad seed would surface only later as a backend rejection or a silent
398
+ // divergence between the live log and disk.
399
+ for (const [index, source] of seed.entries()) {
400
+ // The seed is a persistence/replay boundary: validate and detach the
401
+ // complete event in one lossless-JSON pass.
402
+ const snapshot = mode === 'restore' ? source : snapshotJsonValue(source);
403
+ if (snapshot === undefined) {
404
+ throw new Error(`seed event at index ${index} is not losslessly JSON-serializable`);
405
+ }
406
+ assertSessionEventEnvelope(snapshot, index);
407
+ assertSupportedRequestHeader(snapshot.type, snapshot.data, `seed event at index ${index}`);
408
+ if (snapshot.seq !== index) {
409
+ throw new Error(`seed event at index ${index} has seq ${snapshot.seq} (expected ${index}); seed must be contiguous from 0`);
410
+ }
411
+ // A seed is accepted incrementally through the same transition as a
412
+ // live append and a full-log fold. The candidate is planned before it
413
+ // enters `log`, so a failure cannot partially mutate the surface.
414
+ try {
415
+ this.surfaceManager.validateNext(snapshot);
416
+ }
417
+ catch (error) {
418
+ throw new Error(`invalid seed event at index ${index}: ${error instanceof Error ? error.message : 'invalid surface metadata'}`);
419
+ }
420
+ this.log.push(mode === 'restore' ? freezeRestoredObject(snapshot) : deepFreeze(snapshot));
421
+ }
422
+ }
423
+ this.firstLiveSeq = this.log.length;
424
+ this.header = restoredHeader ?? snapshotSessionHeader(id, header);
425
+ // Appended here so the marker is already in `events` when a backend
426
+ // captures the creation seed: no load-time write. Re-marking is skipped
427
+ // because a cold session is resumed on first touch, so repeatedly opening
428
+ // one must not grow its log per open.
429
+ if (seed !== undefined && this.log.at(-1)?.type !== 'session/end-seed') {
430
+ this.append('session/end-seed', {});
431
+ }
432
+ }
433
+ /** Cached immutable public snapshot of the private append-only log. */
434
+ eventsSnapshot;
435
+ /**
436
+ * An immutable snapshot of the append-only event log. The snapshot is reused
437
+ * until the next append; a previously returned array does not grow later.
438
+ * Events and their nested data are deep-frozen at acceptance, so neither a
439
+ * cast nor ordinary JavaScript can rewrite durable history.
440
+ */
441
+ get events() {
442
+ this.eventsSnapshot ??= Object.freeze([...this.log]);
443
+ return this.eventsSnapshot;
444
+ }
445
+ /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
446
+ get seq() {
447
+ return this.log.length;
448
+ }
449
+ /**
450
+ * Append one typed event to the log and synchronously notify observers via
451
+ * the store-owned, module-private publication hooks. The hot path never blocks
452
+ * on I/O — persistence plugins buffer asynchronously. Once the event enters
453
+ * the log, the append is committed: observer failures are logged and
454
+ * contained per listener, so they do not change the return value or prevent
455
+ * later listeners from observing the same accepted event.
456
+ *
457
+ * @param type - The event type (key of {@link SessionEventMap}).
458
+ * @param data - The event payload; must be JSON-serializable.
459
+ * @param opts - Surface metadata: `surfaceOp` controls how the event enters
460
+ * the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier
461
+ * events this one derives from. REQUIRED for
462
+ * {@link SurfaceEventType} events (every message-producing event must
463
+ * declare how it joins the surface, the sole source of derived model
464
+ * history) and
465
+ * rejected by the compiler for non-surface types like `turn/start` or
466
+ * `assistant/chunk`.
467
+ * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
468
+ * `data` that entered the log, so reading `event.data` back sees the logged
469
+ * value, never the caller's still-mutable input.
470
+ * @throws if `data` or surface metadata is not losslessly JSON-serializable
471
+ * (BigInt, function, symbol, undefined, negative zero, non-finite number,
472
+ * circular reference, sparse array, or an exotic object such as
473
+ * Map/Set/Date/class instance), or when the candidate violates the
474
+ * canonical surface contract (marker shape and eligibility, unique
475
+ * earlier source-event references, positional replacement validity, and complete
476
+ * shadowed-node coverage). One recursive pass reads, validates, and
477
+ * copies each nested value once, so a stateful getter cannot supply one value
478
+ * to validation and another to storage. The event log is the durable source
479
+ * of truth, so a bad event fails at the append site rather than later during
480
+ * a backend flush. A synchronous internal dispatch validation failure or an
481
+ * append reentered while this acceptance/publication boundary is open also
482
+ * rejects before the log changes.
483
+ */
484
+ append(type, data, ...opts) {
485
+ const surfaceOpts = opts[0];
486
+ const surfaceMetadata = {
487
+ ...surfaceOpts?.sourceEventSeqs === undefined ? {} : { sourceEventSeqs: surfaceOpts.sourceEventSeqs },
488
+ ...surfaceOpts?.surfaceOp === undefined ? {} : { surfaceOp: surfaceOpts.surfaceOp },
489
+ };
490
+ const dataSnapshot = snapshotJsonValue(data);
491
+ if (dataSnapshot === undefined) {
492
+ throw new Error(`session event "${type}" carries non-JSON-serializable data`);
493
+ }
494
+ assertSupportedRequestHeader(type, dataSnapshot, `session event "${type}"`);
495
+ const surfaceMetadataSnapshot = snapshotJsonValue(surfaceMetadata);
496
+ if (surfaceMetadataSnapshot === undefined) {
497
+ throw new Error(`session event "${type}" carries non-JSON-serializable surface metadata`);
498
+ }
499
+ const entry = attachments.get(this);
500
+ if (entry?.appending) {
501
+ throw new Error('session append cannot reenter while another append is being published');
502
+ }
503
+ const event = deepFreeze({
504
+ type,
505
+ seq: this.log.length,
506
+ time: Date.now(),
507
+ data: dataSnapshot,
508
+ ...surfaceMetadataSnapshot,
509
+ });
510
+ this.surfaceManager.validateNext(event);
511
+ if (entry !== undefined)
512
+ entry.appending = true;
513
+ try {
514
+ let callbacks;
515
+ const callbackArgs = [this, event];
516
+ if (entry !== undefined) {
517
+ callbacks = collectSessionCallbacks(entry.emitCtx, [entry.carrier, 'session/event', ...callbackArgs]);
518
+ }
519
+ this.log.push(event);
520
+ this.eventsSnapshot = undefined;
521
+ if (callbacks !== undefined && entry !== undefined) {
522
+ invokeContainedSessionObservers(entry.emitCtx, 'session/event', entry.id, callbackArgs, callbacks);
523
+ }
524
+ return event;
525
+ }
526
+ finally {
527
+ if (entry !== undefined) {
528
+ entry.appending = false;
529
+ if (entry.detachRequested && !entry.announcing)
530
+ entry.detach();
531
+ }
532
+ }
533
+ }
534
+ /** Cached fold of the request-header events — see {@link requestHeader}. */
535
+ headerFold;
536
+ /** Log position (events consumed) the header fold has reached. */
537
+ headerFoldSeq = 0;
538
+ /**
539
+ * The {@link EpochHeader} in force after the log's last header event — the
540
+ * header the NEXT request will be compared against — or undefined before
541
+ * the first `request/header` snapshot. The live, incrementally-maintained
542
+ * form of `foldRequestHeader(session.events)`: each header event is folded
543
+ * once, when first seen, so a per-step read costs O(new events).
544
+ * @returns the folded header, or undefined when no header event exists yet.
545
+ */
546
+ requestHeader() {
547
+ if (this.headerFoldSeq < this.log.length) {
548
+ // Frozen on update: the fold is session state exposed by reference — a
549
+ // consumer mutating it in place (instead of building a replacement)
550
+ // would desync every later comparison against the log, so mutation
551
+ // throws instead.
552
+ this.headerFold = deepFreeze(foldRequestHeader(this.log.slice(this.headerFoldSeq), this.headerFold));
553
+ this.headerFoldSeq = this.log.length;
554
+ }
555
+ return this.headerFold;
556
+ }
557
+ /** Cached fold of `request/context` events. */
558
+ contextFold;
559
+ contextFoldSeq = 0;
560
+ /**
561
+ * Return the latest resolved route metadata, or `undefined` before the first
562
+ * `request/context` event. Each event is folded once.
563
+ * @returns the latest immutable route metadata.
564
+ */
565
+ requestContext() {
566
+ if (this.contextFoldSeq < this.log.length) {
567
+ for (const event of this.log.slice(this.contextFoldSeq)) {
568
+ if (event.type === 'request/context')
569
+ this.contextFold = deepFreeze({ ...event.data });
570
+ }
571
+ this.contextFoldSeq = this.log.length;
572
+ }
573
+ return this.contextFold;
574
+ }
575
+ /** The derived-message cache: frozen projections, extended per unseen node. */
576
+ derived = [];
577
+ /** Surface position (nodes projected) the cache has reached. */
578
+ derivedNodes = 0;
579
+ /** {@link SurfaceManager.replaceGeneration} the cache was built under. */
580
+ derivedGeneration = 0;
581
+ /**
582
+ * Derive the LLM message history by walking the ordered sequences of
583
+ * message-producing events maintained by `surfaceOp` markers. The
584
+ * surface is the single source of derived history: every message-producing
585
+ * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
586
+ * turn boundary) is correctly absent, and a compaction `replace` deletes the
587
+ * shadowed nodes from the derivation. The projection rules are
588
+ * {@link deriveEventMessage}, folded per node.
589
+ *
590
+ * CACHED: each surface node is projected exactly once, when first seen — a
591
+ * call costs O(new nodes), and a surface rewrite (a `replace`;
592
+ * {@link SessionSurface.replaceGeneration}) rebuilds. The returned array is
593
+ * a fresh snapshot per call (later appends never grow an array a caller
594
+ * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
595
+ * Their content reuses the already frozen durable event data, so the cache
596
+ * needs no second deep clone and consumers still cannot mutate the log.
597
+ * @returns a fresh array of the shared, frozen derived history.
598
+ */
599
+ deriveMessages() {
600
+ const surface = this.surface;
601
+ const nodes = surface.nodes;
602
+ const generation = surface.replaceGeneration;
603
+ if (generation !== this.derivedGeneration) {
604
+ this.derived = [];
605
+ this.derivedNodes = 0;
606
+ this.derivedGeneration = generation;
607
+ }
608
+ for (const seq of nodes.slice(this.derivedNodes)) {
609
+ // Surface sequences are built from this.log — seq is always a valid
610
+ // index by construction. The non-null assertion expresses that invariant.
611
+ // oxlint-disable-next-line typescript/no-non-null-assertion
612
+ const msg = this.deriveEventMessage(this.log[seq]);
613
+ // A surface node is one of the five message-producing types, but an
614
+ // empty-content assistant/message (a max-tokens step that hosts only
615
+ // usage) derives to null and must not enter the transcript.
616
+ if (msg)
617
+ this.derived.push(msg);
618
+ }
619
+ this.derivedNodes = nodes.length;
620
+ return [...this.derived];
621
+ }
622
+ /**
623
+ * Instance face of the pure per-node `deriveEventMessage` export from
624
+ * `surface.ts`.
625
+ * @param event - the event to project.
626
+ * @returns the derived message, or null when the event produces none.
627
+ */
628
+ deriveEventMessage(event) {
629
+ return deriveEventMessage(event);
630
+ }
631
+ }
632
+ /** Typed error for session fork rejections. */
633
+ export class SessionForkError extends Error {
634
+ code;
635
+ constructor(message, code) {
636
+ super(message);
637
+ this.code = code;
638
+ this.name = 'SessionForkError';
639
+ }
640
+ }
641
+ /**
642
+ * In-memory session store (`ctx.sessions`).
643
+ *
644
+ * Persistence is intentionally not implemented here — persistence plugins
645
+ * subscribe to `session/event` and flush on `session/flush` / dispose.
646
+ */
647
+ export class SessionStore extends Service {
648
+ store = new Map();
649
+ counter = 0;
650
+ constructor(ctx) {
651
+ super(ctx, 'sessions');
652
+ ctx.inject(['typert'], (typeCtx) => {
653
+ typeCtx.typert.lookups.register('session', {
654
+ parameter: 'session',
655
+ wire: 'sessionId',
656
+ hostTypeSymbol: '@hasna-internal/kai-session#Session',
657
+ wireTypeSymbol: '@hasna-internal/kai-session/types#SessionId',
658
+ resolve: sessionId => this.get(sessionId),
659
+ });
660
+ });
661
+ }
662
+ /**
663
+ * Create a session owned by the calling fiber: disposing that fiber stops
664
+ * event notification and removes the session from the store. `options.seed`
665
+ * populates the session with a copy of those events (replay/fork);
666
+ * `options.meta` attaches creation metadata (validated absolute `cwd`, seed
667
+ * and parent lineage, and delegation depth) as the immutable
668
+ * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
669
+ *
670
+ * For an agent whose session must be torn down IN ORDER with its loop (so the
671
+ * loop's final events are published before the store attachment ends), do NOT use this
672
+ * — fold the session lifecycle into the agent's own effect via
673
+ * {@link prepare} + {@link enter} + {@link announce} (see
674
+ * `dsh-agent-loop`'s creation transaction).
675
+ *
676
+ * @param id - the session id; omitted, the store mints `session-<n>`.
677
+ * @param options - seed events and/or creation metadata for the header.
678
+ * @returns the live session, already entered and announced.
679
+ * @throws if a session with `id` already exists, metadata is not a plain
680
+ * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
681
+ * non-absolute path (storage backends key directories off it).
682
+ */
683
+ create(id, options) {
684
+ const session = this.prepare(id, options);
685
+ // Single effect owned by the calling fiber. Yield the detach BEFORE
686
+ // announcing so a throwing `session/created` listener rolls the attach back
687
+ // (the generator effect disposes already-yielded disposers on a throw)
688
+ // instead of leaking the store entry and its publication hooks.
689
+ this.ctx.effect(function* () {
690
+ yield this.enter(session);
691
+ this.announce(session);
692
+ }.bind(this), 'sessions.create()');
693
+ return session;
694
+ }
695
+ /**
696
+ * Build a session WITHOUT entering it into the store — validate the id/cwd and
697
+ * construct the {@link Session} (with its immutable {@link SessionHeader}).
698
+ * Pairs with {@link enter} + {@link announce}: a caller that owns a composite
699
+ * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
700
+ * effect so a fiber unload tears the session + agent down as a single ORDERED
701
+ * chain rather than as racing sibling effects — which would remove the publication hooks
702
+ * before the driver's closing events commit, dropping them.
703
+ *
704
+ * @param id - the session id; omitted, the store mints `session-<n>`.
705
+ * @param options - seed events and/or creation metadata for the header. With
706
+ * `seedSource: 'persistence'`, metadata and events must be fresh detached
707
+ * graphs whose ownership transfers to this call: they are validated and
708
+ * frozen in place through {@link Session.fromRestore}, so the caller must
709
+ * retain no mutable aliases.
710
+ * @returns the constructed session, NOT yet in the store.
711
+ * @throws if a session with `id` already exists, metadata is not a plain
712
+ * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
713
+ * non-absolute path.
714
+ */
715
+ prepare(id, options) {
716
+ let sessionId;
717
+ if (id === undefined) {
718
+ do
719
+ sessionId = SessionId(`session-${++this.counter}`);
720
+ while (this.store.has(sessionId));
721
+ }
722
+ else {
723
+ sessionId = SessionId(id);
724
+ }
725
+ if (this.store.has(sessionId))
726
+ throw new Error(`session "${sessionId}" already exists`);
727
+ if (options?.seedSource === 'persistence') {
728
+ return Session.fromRestore(sessionId, options.seed, options.meta);
729
+ }
730
+ const seed = options?.seed;
731
+ const meta = options?.meta;
732
+ const header = {
733
+ version: SESSION_FORMAT_VERSION,
734
+ id: sessionId,
735
+ createdAt: meta?.createdAt ?? Date.now(),
736
+ ...meta?.cwd === undefined ? {} : { cwd: meta.cwd },
737
+ ...meta?.parentSession === undefined ? {} : { parentSession: meta.parentSession },
738
+ ...meta?.seedLength === undefined ? {} : { seedLength: meta.seedLength },
739
+ ...meta?.origin === undefined ? {} : { origin: meta.origin },
740
+ ...meta?.delegationDepth === undefined ? {} : { delegationDepth: meta.delegationDepth },
741
+ ...meta?.agentPreset === undefined ? {} : { agentPreset: meta.agentPreset },
742
+ };
743
+ return Session.create(sessionId, seed, header);
744
+ }
745
+ /**
746
+ * Enter a {@link prepare}d session into the store: install the module-private
747
+ * append publication hooks and add it to the store. Returns the DETACH
748
+ * disposer (hooks + store removal). Does NOT emit `session/created` —
749
+ * the caller yields this disposer inside its effect and THEN calls
750
+ * {@link announce}, so a throwing `session/created` listener rolls the attach
751
+ * back instead of leaking it.
752
+ *
753
+ * Re-checks the id for a duplicate: `prepare` and `enter` are public
754
+ * cross-package primitives and a caller may interleave arbitrary work (or
755
+ * another create) between them, so a stale prepared session must NOT overwrite
756
+ * a live store entry of the same id — its detach disposer would later delete
757
+ * the REAL session. The {@link create} convenience and the agent factory call
758
+ * the two back-to-back so they never trip this, but the public API cannot
759
+ * assume that.
760
+ *
761
+ * @param session - a {@link prepare}d session not yet in the store.
762
+ * @returns the detach disposer (publication hooks + store removal). When called from
763
+ * a synchronous `session/created` listener, removal and disposal wait until
764
+ * that creation dispatch unwinds.
765
+ * @throws if a session with this id is already in the store.
766
+ */
767
+ enter(session) {
768
+ const id = session.id;
769
+ const carrier = scopeTarget(session, scopeOf(this.ctx));
770
+ // This is the authoritative collision boundary after arbitrary unpublished
771
+ // preparation. Only one exact same-id transaction can publish.
772
+ if (this.store.has(id))
773
+ throw new Error(`session "${id}" already exists`);
774
+ if (attachments.has(session))
775
+ throw new Error(`session "${id}" is already attached to a store`);
776
+ const entry = {
777
+ id,
778
+ session,
779
+ carrier,
780
+ emitCtx: this.ctx,
781
+ announced: false,
782
+ announcing: false,
783
+ appending: false,
784
+ detachRequested: false,
785
+ detach: () => { this.detachEntered(entry); },
786
+ };
787
+ this.store.set(id, entry);
788
+ attachments.set(session, entry);
789
+ let entered = true;
790
+ const detach = () => {
791
+ if (!entered)
792
+ return;
793
+ entered = false;
794
+ // A lifecycle listener may own the advanced detach capability. Keep the
795
+ // entry and its publication hooks live until synchronous creation or append
796
+ // publication unwinds, then publish the paired disposal edge.
797
+ if (entry.announcing || entry.appending) {
798
+ entry.detachRequested = true;
799
+ return;
800
+ }
801
+ entry.detach();
802
+ };
803
+ return detach;
804
+ }
805
+ /** Remove one exact entered session and emit its paired disposal when announced. */
806
+ detachEntered(entry) {
807
+ entry.detachRequested = false;
808
+ // A stale capability cannot remove observers or storage belonging to a
809
+ // later same-id lifecycle.
810
+ /* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */
811
+ if (this.store.get(entry.id) !== entry)
812
+ return;
813
+ this.store.delete(entry.id);
814
+ attachments.delete(entry.session);
815
+ if (entry.announced)
816
+ this.emitDisposed(entry);
817
+ }
818
+ /** Emit `session/created` exactly once for an {@link enter}ed session (with
819
+ * the carrier {@link enter} captured). Separate from {@link enter} so the
820
+ * caller can yield the detach disposer first (rollback safety — see
821
+ * {@link enter}).
822
+ * @param session - the entered session to announce to listeners.
823
+ * @throws if the session is not live or its announcement already began,
824
+ * including a reentrant call from a creation listener. */
825
+ announce(session) {
826
+ const entry = this.liveEntryFor(session);
827
+ if (entry.announced || entry.announcing) {
828
+ throw new Error(`session "${entry.id}" was already announced`);
829
+ }
830
+ // Mark before emit: Cordis emit may deliver to earlier listeners and then
831
+ // throw. Rollback must still pair that partial creation with disposal, and
832
+ // a listener cannot recursively create a second lifecycle edge.
833
+ entry.announced = true;
834
+ const callbackArgs = [session];
835
+ entry.announcing = true;
836
+ try {
837
+ const callbacks = collectSessionCallbacks(this.ctx, [entry.carrier, 'session/created', session]);
838
+ for (const callback of callbacks) {
839
+ // Synchronous throws intentionally propagate and veto publication; the
840
+ // yielded detach then emits the paired disposal edge. An async function
841
+ // is nevertheless assignable to a void listener, so observe its returned
842
+ // promise: rejection is too late to roll back and must be logged instead
843
+ // of becoming unhandled.
844
+ const returned = callback(...callbackArgs);
845
+ void Promise.resolve(returned).catch((error) => {
846
+ this.ctx.logger.warn(`session "${entry.id}": session/created listener rejected: ${String(error)}`);
847
+ });
848
+ }
849
+ }
850
+ finally {
851
+ entry.announcing = false;
852
+ if (entry.detachRequested && !entry.appending)
853
+ entry.detach();
854
+ }
855
+ }
856
+ /** Emit the paired teardown notification with per-listener containment. */
857
+ emitDisposed(entry) {
858
+ const callbackArgs = [entry.session];
859
+ try {
860
+ const callbacks = collectSessionCallbacks(this.ctx, [entry.carrier, 'session/disposed', entry.session]);
861
+ invokeContainedSessionObservers(this.ctx, 'session/disposed', entry.id, callbackArgs, callbacks);
862
+ }
863
+ catch (error) {
864
+ this.ctx.logger.warn(`session "${entry.id}": session/disposed dispatch threw: ${String(error)}`);
865
+ }
866
+ }
867
+ /**
868
+ * Dispatch the awaited `session/flush` durability checkpoint for `session`,
869
+ * with the carrier captured at {@link enter}. THE flush entry point: the
870
+ * store owns the carrier, so callers (the checkpoint policy's per-request
871
+ * barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers
872
+ * that flush themselves before reading storage) must come through here
873
+ * rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner,
874
+ * one spelling, and the scoped-dispatch invariant can pin it.
875
+ * @param session - the session whose buffered events must reach durable storage.
876
+ * @returns whether at least one durability listener participated, after every
877
+ * listener has settled successfully.
878
+ * @throws the first registered listener failure after every listener settles.
879
+ */
880
+ async flush(session) {
881
+ const { carrier } = this.liveEntryFor(session);
882
+ const callbackArgs = [session];
883
+ const callbacks = collectSessionCallbacks(this.ctx, [carrier, 'session/flush', session]);
884
+ const results = await Promise.allSettled(callbacks.map((callback) => {
885
+ try {
886
+ return callback(...callbackArgs);
887
+ }
888
+ catch (error) {
889
+ // Preserve the listener's exact rejection value; flush is a caller-owned
890
+ // failure boundary, and Cordis listeners may throw arbitrary values.
891
+ // oxlint-disable-next-line typescript/prefer-promise-reject-errors
892
+ return Promise.reject(error);
893
+ }
894
+ }));
895
+ const failure = results.find((result) => result.status === 'rejected');
896
+ if (failure !== undefined)
897
+ throw failure.reason;
898
+ return callbacks.length > 0;
899
+ }
900
+ /** Return the exact live entry; detached/prepared objects reject. */
901
+ liveEntryFor(session) {
902
+ const entry = attachments.get(session);
903
+ if (entry === undefined || this.store.get(entry.id) !== entry) {
904
+ throw new Error(`session "${session.id}" is not live in this store`);
905
+ }
906
+ return entry;
907
+ }
908
+ /**
909
+ * Look up a live session.
910
+ * @param id - the session id to look up.
911
+ * @returns the session, or undefined when no live session has that id.
912
+ */
913
+ get(id) {
914
+ return this.store.get(id)?.session;
915
+ }
916
+ /**
917
+ * All live sessions, in creation order.
918
+ * @returns a fresh array; mutating it does not affect the store.
919
+ */
920
+ list() {
921
+ return [...this.store.values()].map(entry => entry.session);
922
+ }
923
+ /**
924
+ * Create a live child session from a stable prefix of a live source.
925
+ * `boundary` is an inclusive source event seq; omitted means the source's
926
+ * current last event. The selected slice may end with a between-turn event
927
+ * but must not end inside an open turn.
928
+ *
929
+ * @param source - Live source session object or id.
930
+ * @param boundary - Inclusive source event seq to fork through; omitted means
931
+ * the source's current last event, and omitted on an empty source forks an
932
+ * empty child.
933
+ * @param childSessionId - Optional child session id; omitted delegates to
934
+ * `SessionStore`'s id policy.
935
+ * @returns The created live child session.
936
+ */
937
+ fork(source, boundary, childSessionId) {
938
+ if (childSessionId !== undefined && this.get(childSessionId) !== undefined) {
939
+ throw new SessionForkError(`session "${childSessionId}" already exists`, 'SESSION_ALREADY_EXISTS');
940
+ }
941
+ const liveSource = this._resolveForkSource(source);
942
+ const seed = this._forkSeed(liveSource, boundary);
943
+ return this.create(childSessionId, {
944
+ seed,
945
+ meta: {
946
+ ...liveSource.header.cwd !== undefined ? { cwd: liveSource.header.cwd } : {},
947
+ parentSession: liveSource.id,
948
+ seedLength: seed.length,
949
+ },
950
+ });
951
+ }
952
+ _forkSeed(session, requestedBoundary) {
953
+ const events = session.events;
954
+ const lastEvent = events.at(-1);
955
+ let boundary;
956
+ if (requestedBoundary !== undefined) {
957
+ boundary = requestedBoundary;
958
+ }
959
+ else {
960
+ if (lastEvent === undefined)
961
+ return [];
962
+ boundary = lastEvent.seq;
963
+ }
964
+ if (!Number.isSafeInteger(boundary) || boundary < 0) {
965
+ throw new SessionForkError(`fork boundary for session "${session.id}" must be a non-negative safe integer, got ${String(boundary)}`, 'INVALID_BOUNDARY');
966
+ }
967
+ if (boundary >= events.length) {
968
+ const lastSeq = events.at(-1)?.seq;
969
+ throw new SessionForkError(`fork boundary ${boundary} does not exist in session "${session.id}" (last seq: ${lastSeq ?? 'none'})`, 'INVALID_BOUNDARY');
970
+ }
971
+ const boundaryEvent = events[boundary];
972
+ if (boundaryEvent === undefined || boundaryEvent.seq !== boundary) {
973
+ throw new SessionForkError(`fork boundary ${boundary} does not match a contiguous event seq in session "${session.id}"`, 'INVALID_BOUNDARY');
974
+ }
975
+ const lastTurnBoundary = events.slice(0, boundary + 1)
976
+ .findLast(event => event.type === 'turn/start' || event.type === 'turn/end');
977
+ if (lastTurnBoundary?.type === 'turn/start') {
978
+ throw new SessionForkError(`fork boundary ${boundary} in session "${session.id}" ends inside open turn ${lastTurnBoundary.data.turn}`, 'OPEN_TURN');
979
+ }
980
+ return events.slice(0, boundary + 1);
981
+ }
982
+ _resolveForkSource(source) {
983
+ if (typeof source === 'string') {
984
+ const session = this.get(source);
985
+ if (session === undefined)
986
+ throw new SessionForkError(`session "${source}" not found`, 'SESSION_NOT_FOUND');
987
+ return session;
988
+ }
989
+ const live = this.get(source.id);
990
+ if (live === undefined) {
991
+ throw new SessionForkError(`session "${source.id}" not found`, 'SESSION_NOT_FOUND');
992
+ }
993
+ if (live !== source)
994
+ throw new SessionForkError(`session "${source.id}" is not the live store instance`, 'SESSION_NOT_LIVE');
995
+ return source;
996
+ }
997
+ }
998
+ export default SessionStore;
999
+ //# sourceMappingURL=index.js.map