@hasna-internal/kai-session-query 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.
package/lib/index.js ADDED
@@ -0,0 +1,969 @@
1
+ import { Service } from "@deepseek-ai/cordis";
2
+ import { Session, foldSurface, isSurfaceEvent, snapshotSessionEvent } from "@hasna-internal/kai-session";
3
+ import { foldSessionTitle } from "@hasna-internal/kai-session-title";
4
+ import { HarnessError } from "@hasna-internal/kai-llm";
5
+ //#region lib/types/config.js
6
+ /** Public configuration and typed failures for the combined session-query service. */
7
+ /** Default maximum `before`/`after` raw-event window. */
8
+ const SESSION_QUERY_READ_WINDOW_MAX = 50;
9
+ /** Default maximum number of concurrent persisted-log inspections in one batch read. */
10
+ const SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY = 4;
11
+ /** Typed session-query failure whose `code` is one closed taxonomy member. */
12
+ var SessionQueryError = class extends HarnessError {
13
+ constructor(message, code, options) {
14
+ super(message, code, options);
15
+ }
16
+ };
17
+ //#endregion
18
+ //#region lib/types/sources.js
19
+ /** Shared immutable-header checks for logical session source observers. */
20
+ /**
21
+ * Reject incompatible observations of one logical session source.
22
+ * @param a - first live, listed, or loaded header observation.
23
+ * @param b - second header observation expected to identify the same source.
24
+ */
25
+ function assertSessionHeadersCompatible(a, b) {
26
+ if (a.version !== b.version || a.id !== b.id || a.createdAt !== b.createdAt || a.cwd !== b.cwd || a.parentSession !== b.parentSession || a.seedLength !== b.seedLength || (a.delegationDepth ?? 0) !== (b.delegationDepth ?? 0)) throw new SessionQueryError(`session source headers conflict for session "${a.id}"`, "SESSION_QUERY_SOURCE_CONFLICT");
27
+ }
28
+ //#endregion
29
+ //#region lib/types/corpus.js
30
+ /** Live/persisted logical-corpus resolution for session-query. */
31
+ /** Resolves a live-preferred corpus against the persistence service mounted now. */
32
+ var SessionCorpus = class {
33
+ _ctx;
34
+ _persistedInspectConcurrency;
35
+ _persistence;
36
+ _optionalPersistenceFiber;
37
+ constructor(_ctx, _persistedInspectConcurrency) {
38
+ this._ctx = _ctx;
39
+ this._persistedInspectConcurrency = _persistedInspectConcurrency;
40
+ this._optionalPersistenceFiber = _ctx.inject(["sessionPersistence"], (childCtx) => {
41
+ const service = childCtx.sessionPersistence;
42
+ this._persistence = service;
43
+ childCtx.effect(() => () => {
44
+ /* v8 ignore next -- a stale optional-service disposer cannot clear a replacement */
45
+ if (this._persistence === service) this._persistence = void 0;
46
+ }, "sessionQuery.persistenceBinding");
47
+ });
48
+ _ctx.effect(() => {
49
+ return () => this._optionalPersistenceFiber.dispose();
50
+ }, "sessionQuery.optionalPersistence");
51
+ }
52
+ /**
53
+ * List the complete logical corpus with live precedence and cloned headers.
54
+ * @param signal - optional cancellation for persistence listing.
55
+ * @returns records in deterministic newest-first order.
56
+ */
57
+ async listSessions(signal) {
58
+ signal?.throwIfAborted();
59
+ const persistence = this._persistence;
60
+ const persisted = persistence === void 0 ? [] : await listPersisted(persistence, signal);
61
+ signal?.throwIfAborted();
62
+ const records = /* @__PURE__ */ new Map();
63
+ for (const header of persisted) records.set(header.id, {
64
+ header: structuredClone(header),
65
+ live: false,
66
+ persisted: true
67
+ });
68
+ for (const session of this._ctx.sessions.list()) {
69
+ const durable = records.get(session.id);
70
+ if (durable !== void 0) assertSessionHeadersCompatible(session.header, durable.header);
71
+ records.set(session.id, {
72
+ header: structuredClone(session.header),
73
+ live: true,
74
+ persisted: durable !== void 0
75
+ });
76
+ }
77
+ return [...records.values()].sort(compareSessions);
78
+ }
79
+ /**
80
+ * Load one logical source, preferring a detached live snapshot.
81
+ *
82
+ * A known live target never consults persistence, so an optional backend's
83
+ * failure cannot make current in-memory history unreadable.
84
+ * @param sessionId - session to resolve.
85
+ * @param signal - optional cancellation for persisted source resolution.
86
+ * @returns detached live-preferred header and events.
87
+ */
88
+ async load(sessionId, signal) {
89
+ signal?.throwIfAborted();
90
+ const live = this._ctx.sessions.get(sessionId);
91
+ if (live !== void 0) {
92
+ const snapshot = snapshotLive(live);
93
+ signal?.throwIfAborted();
94
+ return snapshot;
95
+ }
96
+ const persistence = this._persistence;
97
+ if (persistence === void 0) throw notFound(sessionId);
98
+ const listed = (await listPersisted(persistence, signal)).find((header) => header.id === sessionId);
99
+ signal?.throwIfAborted();
100
+ if (listed === void 0) throw notFound(sessionId);
101
+ const loaded = await inspectPersisted(persistence, sessionId, signal);
102
+ signal?.throwIfAborted();
103
+ const attached = this._ctx.sessions.get(sessionId);
104
+ if (attached !== void 0) {
105
+ const snapshot = snapshotLive(attached);
106
+ signal?.throwIfAborted();
107
+ return snapshot;
108
+ }
109
+ assertSessionHeadersCompatible(loaded.meta, listed);
110
+ const snapshot = {
111
+ header: structuredClone(loaded.meta),
112
+ events: loaded.events.map((event) => structuredClone(event))
113
+ };
114
+ signal?.throwIfAborted();
115
+ return snapshot;
116
+ }
117
+ /**
118
+ * Project unique logical sources immediately from one persistence listing.
119
+ *
120
+ * The synchronous projector runs before a persisted worker claims its next id.
121
+ * Full logs are borrowed only for that call and never retained by the batch.
122
+ * @param sessionIds - sessions to resolve in first-occurrence order.
123
+ * @param project - synchronous fold that owns/clones every retained value.
124
+ * @param signal - cancellation shared by listing and every persisted inspection.
125
+ * @returns one fulfilled or rejected projected result per unique requested id.
126
+ */
127
+ async projectMany(sessionIds, project, signal) {
128
+ const ids = [...new Set(sessionIds)];
129
+ signal?.throwIfAborted();
130
+ const resolved = /* @__PURE__ */ new Map();
131
+ const unresolved = [];
132
+ for (const id of ids) {
133
+ const session = this._ctx.sessions.get(id);
134
+ if (session === void 0) unresolved.push(id);
135
+ else resolved.set(id, projectSource(id, sourceLive(session), project, signal));
136
+ }
137
+ if (unresolved.length === 0) return orderedResults(ids, resolved);
138
+ const persistence = this._persistence;
139
+ if (persistence === void 0) {
140
+ for (const sessionId of unresolved) resolved.set(sessionId, {
141
+ sessionId,
142
+ status: "rejected",
143
+ reason: notFound(sessionId)
144
+ });
145
+ return orderedResults(ids, resolved);
146
+ }
147
+ let persisted;
148
+ try {
149
+ persisted = await listPersisted(persistence, signal);
150
+ signal?.throwIfAborted();
151
+ } catch (error) {
152
+ if (signal?.aborted) signal.throwIfAborted();
153
+ for (const sessionId of unresolved) resolved.set(sessionId, {
154
+ sessionId,
155
+ status: "rejected",
156
+ reason: error
157
+ });
158
+ return orderedResults(ids, resolved);
159
+ }
160
+ const persistedById = new Map(persisted.map((header) => [header.id, header]));
161
+ const resolvePersisted = async (sessionId) => {
162
+ const listed = persistedById.get(sessionId);
163
+ if (listed === void 0) {
164
+ const attached = this._ctx.sessions.get(sessionId);
165
+ resolved.set(sessionId, attached === void 0 ? {
166
+ sessionId,
167
+ status: "rejected",
168
+ reason: notFound(sessionId)
169
+ } : projectSource(sessionId, sourceLive(attached), project, signal));
170
+ return;
171
+ }
172
+ try {
173
+ signal?.throwIfAborted();
174
+ const loaded = await inspectPersisted(persistence, sessionId, signal);
175
+ signal?.throwIfAborted();
176
+ const attached = this._ctx.sessions.get(sessionId);
177
+ if (attached !== void 0) {
178
+ resolved.set(sessionId, projectSource(sessionId, sourceLive(attached), project, signal));
179
+ return;
180
+ }
181
+ assertSessionHeadersCompatible(loaded.meta, listed);
182
+ resolved.set(sessionId, projectSource(sessionId, {
183
+ header: loaded.meta,
184
+ events: loaded.events
185
+ }, project, signal));
186
+ } catch (error) {
187
+ if (signal?.aborted) signal.throwIfAborted();
188
+ resolved.set(sessionId, {
189
+ sessionId,
190
+ status: "rejected",
191
+ reason: error
192
+ });
193
+ }
194
+ };
195
+ let cursor = 0;
196
+ const worker = async () => {
197
+ for (;;) {
198
+ signal?.throwIfAborted();
199
+ const index = cursor;
200
+ if (index >= unresolved.length) return;
201
+ cursor += 1;
202
+ await resolvePersisted(unresolved[index]);
203
+ }
204
+ };
205
+ const workerCount = Math.min(this._persistedInspectConcurrency, unresolved.length);
206
+ const settlements = await Promise.allSettled(Array.from({ length: workerCount }, () => worker()));
207
+ if (signal?.aborted) signal.throwIfAborted();
208
+ /* v8 ignore start -- per-id failures settle inside resolvePersisted; workers reject only on abort above */
209
+ for (const settlement of settlements) if (settlement.status === "rejected") throw settlement.reason;
210
+ /* v8 ignore stop */
211
+ signal?.throwIfAborted();
212
+ return orderedResults(ids, resolved);
213
+ }
214
+ };
215
+ function projectSource(sessionId, source, project, signal) {
216
+ try {
217
+ signal?.throwIfAborted();
218
+ const value = project(source);
219
+ signal?.throwIfAborted();
220
+ return {
221
+ sessionId,
222
+ status: "fulfilled",
223
+ value
224
+ };
225
+ } catch (reason) {
226
+ /* v8 ignore next -- the synchronous projector has no external cancellation yield */
227
+ if (signal?.aborted) signal.throwIfAborted();
228
+ return {
229
+ sessionId,
230
+ status: "rejected",
231
+ reason
232
+ };
233
+ }
234
+ }
235
+ function sourceLive(session) {
236
+ return {
237
+ header: session.header,
238
+ events: session.events
239
+ };
240
+ }
241
+ function orderedResults(ids, resolved) {
242
+ return ids.map((sessionId) => resolved.get(sessionId));
243
+ }
244
+ async function listPersisted(persistence, signal) {
245
+ try {
246
+ return await persistence.list(signal);
247
+ } catch (error) {
248
+ if (signal?.aborted) signal.throwIfAborted();
249
+ throw new SessionQueryError(`session persistence listing failed: ${errorMessage(error)}`, "SESSION_QUERY_PERSISTENCE_FAILED", { cause: error });
250
+ }
251
+ }
252
+ async function inspectPersisted(persistence, sessionId, signal) {
253
+ try {
254
+ return await persistence.inspect(sessionId, signal);
255
+ } catch (error) {
256
+ if (signal?.aborted) signal.throwIfAborted();
257
+ if (error instanceof Error && error.name === "SessionPersistenceCorruptionError") throw new SessionQueryError(`stored session "${sessionId}" is corrupt: ${errorMessage(error)}`, "SESSION_QUERY_CORRUPT_SESSION", { cause: error });
258
+ throw new SessionQueryError(`failed to inspect session "${sessionId}": ${errorMessage(error)}`, "SESSION_QUERY_PERSISTENCE_FAILED", { cause: error });
259
+ }
260
+ }
261
+ function snapshotLive(session) {
262
+ return {
263
+ header: structuredClone(session.header),
264
+ events: session.events.map((event) => structuredClone(event))
265
+ };
266
+ }
267
+ function compareSessions(a, b) {
268
+ return b.header.createdAt - a.header.createdAt || a.header.id.localeCompare(b.header.id);
269
+ }
270
+ function notFound(sessionId) {
271
+ return new SessionQueryError(`session "${sessionId}" not found`, "SESSION_QUERY_SESSION_NOT_FOUND");
272
+ }
273
+ function errorMessage(error) {
274
+ return error instanceof Error ? error.message : "unknown error";
275
+ }
276
+ //#endregion
277
+ //#region lib/types/extraction.js
278
+ /** First-party semantic text extraction for session-query consumers. */
279
+ /**
280
+ * Extract searchable semantic text from one first-party session event.
281
+ *
282
+ * Structural boundaries, raw stream chunks, request envelopes, and unknown
283
+ * declaration-merged events contribute no text.
284
+ * @param event - event to inspect.
285
+ * @returns newline-joined semantic text, or an empty string when non-searchable.
286
+ */
287
+ function extractSessionEventText(event) {
288
+ switch (event.type) {
289
+ case "user/message": return contentText(event.data.content);
290
+ case "assistant/message": return contentText(event.data.message.content);
291
+ case "tool/call": return joinText([event.data.name, event.data.arguments]);
292
+ case "tool/result": return joinText([
293
+ contentText(event.data.message.content),
294
+ event.data.error?.name ?? "",
295
+ event.data.error?.code ?? ""
296
+ ]);
297
+ case "todo/write": return joinText(event.data.todos.flatMap((todo) => [todo.status, todo.content]));
298
+ case "turn/end": return turnEndText(event.data.reason);
299
+ case "turn/start":
300
+ case "step/start":
301
+ case "step/end":
302
+ case "assistant/chunk":
303
+ case "request/header": return "";
304
+ default: return "";
305
+ }
306
+ }
307
+ function turnEndText(reason) {
308
+ switch (reason.kind) {
309
+ case "error": return joinText(["error", reason.error.message]);
310
+ case "aborted": return "aborted";
311
+ case "max-tokens":
312
+ case "interrupted": return reason.kind;
313
+ case "completed": return "";
314
+ default: return "";
315
+ }
316
+ }
317
+ function contentText(content) {
318
+ return joinText(content.flatMap(blockText));
319
+ }
320
+ function blockText(block) {
321
+ switch (block.type) {
322
+ case "text": return [block.text];
323
+ case "reasoning": return [];
324
+ case "tool-call": return [block.name, block.arguments];
325
+ case "tool-result": return block.content.flatMap(blockText);
326
+ default: return [];
327
+ }
328
+ }
329
+ function joinText(parts) {
330
+ return parts.map((part) => part.trim()).filter(Boolean).join("\n");
331
+ }
332
+ //#endregion
333
+ //#region lib/types/documents.js
334
+ /** Shared event metadata and semantic-document projection. */
335
+ /**
336
+ * Project a raw log into lightweight surface-aware event records.
337
+ * @param sessionId - session that owns the log.
338
+ * @param events - complete contiguous raw event log.
339
+ * @returns one record per event in ascending seq order.
340
+ */
341
+ function buildSessionEventRecords(sessionId, events) {
342
+ const surfaceBySeq = classifySurface(events);
343
+ return events.map((event) => ({
344
+ sessionId,
345
+ seq: event.seq,
346
+ type: event.type,
347
+ time: event.time,
348
+ surface: surfaceBySeq.get(event.seq) ?? "log-only"
349
+ }));
350
+ }
351
+ /**
352
+ * Build first-party semantic documents for one complete raw event log.
353
+ * @param sessionId - session that owns the log.
354
+ * @param events - complete contiguous raw event log.
355
+ * @returns searchable documents in ascending seq order; structural events are omitted.
356
+ */
357
+ function buildSessionEventSearchDocuments(sessionId, events) {
358
+ const surfaceBySeq = classifySurface(events);
359
+ const documents = [];
360
+ for (const event of events) {
361
+ const text = extractSessionEventText(event);
362
+ if (text.length === 0) continue;
363
+ documents.push({
364
+ sessionId,
365
+ seq: event.seq,
366
+ type: event.type,
367
+ time: event.time,
368
+ surface: surfaceBySeq.get(event.seq) ?? "log-only",
369
+ text
370
+ });
371
+ }
372
+ return documents;
373
+ }
374
+ function classifySurface(events) {
375
+ let folded;
376
+ try {
377
+ folded = foldSurface(events);
378
+ } catch (error) {
379
+ throw new SessionQueryError(
380
+ /* v8 ignore next -- foldSurface throws Error instances */
381
+ `invalid session surface: ${error instanceof Error ? error.message : "unknown error"}`,
382
+ "SESSION_QUERY_INVALID_SURFACE",
383
+ { cause: error }
384
+ );
385
+ }
386
+ const result = /* @__PURE__ */ new Map();
387
+ for (const seq of folded.nodes) result.set(seq, "current");
388
+ for (const replacement of folded.replacements) for (const seq of replacement.shadowedSeqs) result.set(seq, "shadowed");
389
+ return result;
390
+ }
391
+ //#endregion
392
+ //#region lib/types/filters.js
393
+ /** Pure provider-independent predicates for logical sessions and event text. */
394
+ /**
395
+ * Apply ANDed logical-session filters while preserving input order.
396
+ * @param records - detached logical-session records to inspect.
397
+ * @param filters - clauses whose list values are ORed within each clause.
398
+ * @returns records accepted by every clause.
399
+ */
400
+ function filterSessionResults(records, filters = []) {
401
+ const predicates = filters.map(sessionPredicate);
402
+ return records.filter((record) => predicates.every((predicate) => predicate(record)));
403
+ }
404
+ /**
405
+ * Apply ANDed event filters to extracted semantic documents.
406
+ * @param documents - semantic documents produced by {@link buildSessionEventSearchDocuments}.
407
+ * @param filters - metadata and literal-text predicates.
408
+ * @returns documents accepted by every clause, in input order.
409
+ */
410
+ function filterSessionEventDocuments(documents, filters = []) {
411
+ const predicates = filters.map(eventPredicate);
412
+ return documents.filter((document) => predicates.every((predicate) => predicate(document)));
413
+ }
414
+ /**
415
+ * Copy and validate logical-session filters before an asynchronous boundary.
416
+ * @param filters - caller-owned clauses to materialize.
417
+ * @returns detached validated clauses.
418
+ */
419
+ function materializeSessionResultFilters(filters) {
420
+ assertArray(filters);
421
+ return filters.map((filter) => {
422
+ switch (filter.kind) {
423
+ case "id": return {
424
+ kind: filter.kind,
425
+ values: copyStrings(filter.kind, filter.values)
426
+ };
427
+ case "cwd": return {
428
+ kind: filter.kind,
429
+ values: copyNullableStrings(filter.kind, filter.values)
430
+ };
431
+ case "created-at": return copyRange(filter.kind, filter);
432
+ case "parent": return {
433
+ kind: filter.kind,
434
+ values: copyNullableStrings(filter.kind, filter.values)
435
+ };
436
+ case "availability": {
437
+ const values = copyStrings(filter.kind, filter.values);
438
+ assertAllowedValues(filter.kind, values, ["live", "persisted"]);
439
+ return {
440
+ kind: filter.kind,
441
+ values
442
+ };
443
+ }
444
+ default: return unknownFilter(filter);
445
+ }
446
+ });
447
+ }
448
+ /**
449
+ * Copy and validate event filters before an asynchronous boundary.
450
+ * @param filters - caller-owned clauses to materialize.
451
+ * @returns detached validated clauses.
452
+ */
453
+ function materializeSessionEventResultFilters(filters) {
454
+ assertArray(filters);
455
+ return filters.map((filter) => {
456
+ switch (filter.kind) {
457
+ case "seq":
458
+ case "time": return copyRange(filter.kind, filter);
459
+ case "type": return {
460
+ kind: filter.kind,
461
+ values: copyStrings(filter.kind, filter.values)
462
+ };
463
+ case "surface": {
464
+ const values = copyStrings(filter.kind, filter.values);
465
+ assertAllowedValues(filter.kind, values, [
466
+ "current",
467
+ "shadowed",
468
+ "log-only"
469
+ ]);
470
+ return {
471
+ kind: filter.kind,
472
+ values
473
+ };
474
+ }
475
+ case "text":
476
+ if (typeof filter.text !== "string") throw invalidFilter("text filter text must be a string");
477
+ return {
478
+ kind: filter.kind,
479
+ text: filter.text
480
+ };
481
+ default: return unknownFilter(filter);
482
+ }
483
+ });
484
+ }
485
+ /**
486
+ * Compile a literal case-insensitive, whitespace-flexible semantic-text match.
487
+ * @param text - caller-provided literal text.
488
+ * @returns Unicode-aware regular expression safe from regex injection.
489
+ */
490
+ function compileSessionTextFilter(text) {
491
+ const trimmed = text.trim();
492
+ if (trimmed.length === 0) throw new SessionQueryError("session text filter must contain non-whitespace text", "SESSION_QUERY_INVALID_FILTER");
493
+ const pattern = trimmed.split(/\s+/u).map((part) => part.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")).join("\\s+");
494
+ return new RegExp(pattern, "iu");
495
+ }
496
+ function sessionPredicate(filter) {
497
+ switch (filter.kind) {
498
+ case "id": return (record) => filter.values.includes(record.header.id);
499
+ case "cwd": return (record) => filter.values.includes(record.header.cwd ?? null);
500
+ case "created-at": {
501
+ const range = validateRange(filter.kind, filter);
502
+ return (record) => matchesRange(record.header.createdAt, range);
503
+ }
504
+ case "parent": return (record) => filter.values.includes(record.header.parentSession ?? null);
505
+ case "availability":
506
+ assertAllowedValues(filter.kind, filter.values, ["live", "persisted"]);
507
+ return (record) => filter.values.some((value) => value === "live" ? record.live : record.persisted);
508
+ default: return unknownFilter(filter);
509
+ }
510
+ }
511
+ function eventPredicate(filter) {
512
+ switch (filter.kind) {
513
+ case "seq": {
514
+ const range = validateRange(filter.kind, filter);
515
+ return (document) => matchesRange(document.seq, range);
516
+ }
517
+ case "time": {
518
+ const range = validateRange(filter.kind, filter);
519
+ return (document) => matchesRange(document.time, range);
520
+ }
521
+ case "type": return (document) => filter.values.includes(document.type);
522
+ case "surface":
523
+ assertAllowedValues(filter.kind, filter.values, [
524
+ "current",
525
+ "shadowed",
526
+ "log-only"
527
+ ]);
528
+ return (document) => filter.values.includes(document.surface);
529
+ case "text": {
530
+ const pattern = compileSessionTextFilter(filter.text);
531
+ return (document) => pattern.test(document.text);
532
+ }
533
+ default: return unknownFilter(filter);
534
+ }
535
+ }
536
+ function copyStrings(name, values) {
537
+ if (!isRuntimeArray(values) || values.some((value) => typeof value !== "string")) throw invalidFilter(`${name} filter values must be an array of strings`);
538
+ return [...values];
539
+ }
540
+ function assertArray(value) {
541
+ if (!Array.isArray(value)) throw invalidFilter("filters must be an array");
542
+ }
543
+ function copyNullableStrings(name, values) {
544
+ if (!isRuntimeArray(values) || values.some((value) => value !== null && typeof value !== "string")) throw invalidFilter(`${name} filter values must be an array of strings or null`);
545
+ return [...values];
546
+ }
547
+ function copyRange(kind, range) {
548
+ const copy = {
549
+ kind,
550
+ ...range.from === void 0 ? {} : { from: range.from },
551
+ ...range.to === void 0 ? {} : { to: range.to }
552
+ };
553
+ validateRange(kind, copy);
554
+ return copy;
555
+ }
556
+ function unknownFilter(filter) {
557
+ const kind = filter.kind;
558
+ throw invalidFilter(`unknown filter kind ${typeof kind === "string" ? `"${kind}"` : "(missing)"}`);
559
+ }
560
+ function assertAllowedValues(name, values, allowed) {
561
+ for (const value of values) if (!allowed.includes(value)) throw new SessionQueryError(`session ${name} filter contains unknown value "${value}"`, "SESSION_QUERY_INVALID_FILTER");
562
+ }
563
+ function validateRange(name, range) {
564
+ if (range.from !== void 0 && !Number.isFinite(range.from)) throw invalidRange(name, "from must be finite");
565
+ if (range.to !== void 0 && !Number.isFinite(range.to)) throw invalidRange(name, "to must be finite");
566
+ if (range.from !== void 0 && range.to !== void 0 && range.from > range.to) throw invalidRange(name, "from must be less than or equal to to");
567
+ return range;
568
+ }
569
+ function matchesRange(value, range) {
570
+ return (range.from === void 0 || value >= range.from) && (range.to === void 0 || value <= range.to);
571
+ }
572
+ function invalidRange(name, detail) {
573
+ return invalidFilter(`${name} filter ${detail}`);
574
+ }
575
+ function invalidFilter(detail) {
576
+ return new SessionQueryError(`session ${detail}`, "SESSION_QUERY_INVALID_FILTER");
577
+ }
578
+ function isRuntimeArray(value) {
579
+ return Array.isArray(value);
580
+ }
581
+ //#endregion
582
+ //#region lib/types/tracing.js
583
+ /** One-shot session-lineage and event-relationship tracing helpers. */
584
+ /**
585
+ * Classify a raw event log with one canonical surface fold.
586
+ * @param sessionId - owner of the event log.
587
+ * @param events - detached raw event log.
588
+ * @returns lightweight records in ascending log order.
589
+ */
590
+ function eventRecords(sessionId, events) {
591
+ return analyzeEventLog(sessionId, events).records;
592
+ }
593
+ /**
594
+ * Fold and return the current model surface after validating the whole log.
595
+ * @param sessionId - owner used in query diagnostics.
596
+ * @param events - detached raw event log from one corpus observation.
597
+ * @returns detached current surface events in folded order.
598
+ */
599
+ function currentSurfaceEvents(sessionId, events) {
600
+ return analyzeEventLog(sessionId, events).currentSeqs.map((seq) => {
601
+ const event = events[seq];
602
+ /* v8 ignore next 6 -- analyzeEventLog validated contiguous seqs and foldSurface returned only surface-event seqs. */
603
+ if (event === void 0 || event.seq !== seq || !isSurfaceEvent(event)) throw new SessionQueryError(`invalid session surface: current node ${seq} is not a surface event`, "SESSION_QUERY_INVALID_SURFACE");
604
+ return snapshotSessionEvent(event);
605
+ });
606
+ }
607
+ /**
608
+ * Trace one target after one canonical surface fold and whole-log validation.
609
+ * @param sessionId - owner of the event log.
610
+ * @param events - detached raw event log.
611
+ * @param seq - target event seq.
612
+ * @returns direct surface replacements and relationships to cited source events.
613
+ */
614
+ function traceEvent(sessionId, events, seq) {
615
+ const target = events[seq];
616
+ if (target === void 0 || target.seq !== seq) throw new SessionQueryError(`session "${sessionId}" has no event at seq ${seq}`, "SESSION_QUERY_EVENT_NOT_FOUND");
617
+ const analysis = analyzeEventLog(sessionId, events);
618
+ const replacementChain = [];
619
+ let replacement = analysis.replacedBy.get(seq);
620
+ while (replacement !== void 0) {
621
+ replacementChain.push(replacement);
622
+ replacement = analysis.replacedBy.get(replacement);
623
+ }
624
+ const derivedEventSeqs = [];
625
+ for (const event of events) {
626
+ if (event.seq <= seq) continue;
627
+ if (eventSources(event).includes(seq)) derivedEventSeqs.push(event.seq);
628
+ }
629
+ const targetRecord = analysis.records[seq];
630
+ const replacedBy = analysis.replacedBy.get(seq);
631
+ return {
632
+ target: targetRecord,
633
+ ...replacedBy === void 0 ? {} : { replacedBy },
634
+ replacementChain,
635
+ replacedEventSeqs: analysis.replacedEventSeqs.get(seq) ?? [],
636
+ sourceEventSeqs: [...eventSources(target)],
637
+ derivedEventSeqs
638
+ };
639
+ }
640
+ /**
641
+ * Trace one target's known ancestry and recursively known descendants.
642
+ * @param records - complete logical corpus from one observation.
643
+ * @param sessionId - target session id.
644
+ * @returns complete or explicitly partial lineage.
645
+ */
646
+ function traceSession(records, sessionId) {
647
+ const byId = new Map(records.map((record) => [record.header.id, record]));
648
+ const target = byId.get(sessionId);
649
+ if (target === void 0) throw new SessionQueryError(`session "${sessionId}" not found`, "SESSION_QUERY_SESSION_NOT_FOUND");
650
+ const ancestors = [];
651
+ const ancestrySeen = new Set([sessionId]);
652
+ let unresolvedParentId;
653
+ let parentId = target.header.parentSession;
654
+ while (parentId !== void 0) {
655
+ if (ancestrySeen.has(parentId)) throw new SessionQueryError(`session lineage contains a cycle at "${parentId}"`, "SESSION_QUERY_INVALID_LINEAGE");
656
+ ancestrySeen.add(parentId);
657
+ const parent = byId.get(parentId);
658
+ if (parent === void 0) {
659
+ unresolvedParentId = parentId;
660
+ break;
661
+ }
662
+ ancestors.push(parent);
663
+ parentId = parent.header.parentSession;
664
+ }
665
+ const childrenByParent = /* @__PURE__ */ new Map();
666
+ for (const record of records) {
667
+ const parent = record.header.parentSession;
668
+ if (parent === void 0) continue;
669
+ const children = childrenByParent.get(parent) ?? [];
670
+ children.push(record);
671
+ childrenByParent.set(parent, children);
672
+ }
673
+ for (const children of childrenByParent.values()) children.sort((a, b) => a.header.createdAt - b.header.createdAt || a.header.id.localeCompare(b.header.id));
674
+ const descendants = buildDescendants(childrenByParent, sessionId);
675
+ const common = {
676
+ target: cloneRecord(target),
677
+ ancestors: ancestors.map(cloneRecord),
678
+ descendants
679
+ };
680
+ if (unresolvedParentId !== void 0) return {
681
+ ...common,
682
+ complete: false,
683
+ unresolvedParentId
684
+ };
685
+ return {
686
+ ...common,
687
+ complete: true,
688
+ root: cloneRecord(ancestors.at(-1) ?? target)
689
+ };
690
+ }
691
+ function analyzeEventLog(sessionId, events) {
692
+ let folded;
693
+ try {
694
+ folded = foldSurface(events);
695
+ } catch (error) {
696
+ throw new SessionQueryError(
697
+ /* v8 ignore next -- foldSurface throws Error instances */
698
+ `invalid session surface: ${error instanceof Error ? error.message : "unknown error"}`,
699
+ "SESSION_QUERY_INVALID_SURFACE",
700
+ { cause: error }
701
+ );
702
+ }
703
+ const current = new Set(folded.nodes);
704
+ const replacedBy = /* @__PURE__ */ new Map();
705
+ const replacedEventSeqs = /* @__PURE__ */ new Map();
706
+ for (const replacement of folded.replacements) {
707
+ const removed = replacement.shadowedSeqs;
708
+ replacedEventSeqs.set(replacement.seq, removed);
709
+ for (const removedSeq of removed) replacedBy.set(removedSeq, replacement.seq);
710
+ }
711
+ return {
712
+ records: events.map((event) => ({
713
+ sessionId,
714
+ seq: event.seq,
715
+ type: event.type,
716
+ time: event.time,
717
+ surface: current.has(event.seq) ? "current" : replacedBy.has(event.seq) ? "shadowed" : "log-only"
718
+ })),
719
+ replacedBy,
720
+ replacedEventSeqs,
721
+ currentSeqs: [...folded.nodes]
722
+ };
723
+ }
724
+ function eventSources(event) {
725
+ return event.sourceEventSeqs ?? [];
726
+ }
727
+ function buildDescendants(childrenByParent, sessionId) {
728
+ const descendants = [];
729
+ const stack = [{
730
+ sessionId,
731
+ descendants
732
+ }];
733
+ while (stack.length > 0) {
734
+ const frame = stack.pop();
735
+ const nodes = [];
736
+ for (const child of childrenByParent.get(frame.sessionId) ?? []) {
737
+ const node = {
738
+ session: cloneRecord(child),
739
+ descendants: []
740
+ };
741
+ nodes.push(node);
742
+ frame.descendants.push(node);
743
+ }
744
+ for (let index = nodes.length - 1; index >= 0; index -= 1) {
745
+ const node = nodes[index];
746
+ stack.push({
747
+ sessionId: node.session.header.id,
748
+ descendants: node.descendants
749
+ });
750
+ }
751
+ }
752
+ return descendants;
753
+ }
754
+ function cloneRecord(record) {
755
+ return {
756
+ ...record,
757
+ header: structuredClone(record.header)
758
+ };
759
+ }
760
+ //#endregion
761
+ //#region lib/types/cursor.js
762
+ /** Opaque cursor identity for session-search pagination. */
763
+ /**
764
+ * Brand an encoded provider cursor for the public search contract.
765
+ * @param value - opaque encoded cursor value.
766
+ * @returns the same runtime string with session-search cursor identity.
767
+ */
768
+ function SessionSearchCursor(value) {
769
+ return value;
770
+ }
771
+ //#endregion
772
+ //#region lib/types/index.js
773
+ /**
774
+ * Service Definition for combined session-history reads, traces, filters, and full-text search.
775
+ *
776
+ * @module @hasna-internal/kai-session-query
777
+ */
778
+ /**
779
+ * Unified live-preferred session query service.
780
+ *
781
+ * Exact reads, filters, and traces are backend-independent concrete behavior.
782
+ * A backend implements full-text observation, reconciliation, ranking, cursor
783
+ * generations, and query execution on the same `ctx.sessionQuery` service.
784
+ */
785
+ var SessionQueryEngine = class extends Service {
786
+ static inject = ["sessions"];
787
+ _readWindowMax;
788
+ _corpus;
789
+ constructor(ctx, config = {}) {
790
+ super(ctx, "sessionQuery");
791
+ this._readWindowMax = config.readWindowMax ?? 50;
792
+ if (!Number.isInteger(this._readWindowMax) || this._readWindowMax < 0) throw new SessionQueryError("session-query: readWindowMax must be a non-negative integer", "SESSION_QUERY_INVALID_CONFIG");
793
+ const persistedInspectConcurrency = config.persistedInspectConcurrency ?? 4;
794
+ if (!Number.isSafeInteger(persistedInspectConcurrency) || persistedInspectConcurrency < 1) throw new SessionQueryError("session-query: persistedInspectConcurrency must be a positive safe integer", "SESSION_QUERY_INVALID_CONFIG");
795
+ this._corpus = new SessionCorpus(ctx, persistedInspectConcurrency);
796
+ }
797
+ /**
798
+ * List the complete logical corpus using live-preferred records.
799
+ * @param signal - optional cancellation for persistence listing.
800
+ * @returns deterministic newest-first cloned session records.
801
+ */
802
+ listSessions(signal) {
803
+ return this._corpus.listSessions(signal);
804
+ }
805
+ /**
806
+ * Read and replay-validate one complete logical session log without making it live.
807
+ * @param sessionId - live or persisted session id to read.
808
+ * @returns cloned header and complete raw event log from one observation.
809
+ * @throws when persistence, header compatibility, or replay validation fails.
810
+ */
811
+ async readSession(sessionId) {
812
+ const loaded = await this._corpus.load(sessionId);
813
+ Session.create(sessionId, loaded.events, loaded.header);
814
+ return {
815
+ session: structuredClone(loaded.header),
816
+ events: loaded.events.map(snapshotSessionEvent)
817
+ };
818
+ }
819
+ /**
820
+ * Filter the complete logical corpus with provider-independent predicates.
821
+ * @param filters - ANDed session metadata and availability clauses.
822
+ * @param signal - optional cancellation for persistence listing.
823
+ * @returns matching cloned records in deterministic newest-first order.
824
+ */
825
+ async filterSessions(filters, signal) {
826
+ const ownedFilters = materializeSessionResultFilters(filters);
827
+ return this._filterSessions(ownedFilters, signal);
828
+ }
829
+ /**
830
+ * Fold the latest log-backed title from one live-preferred logical session.
831
+ * @param sessionId - live or persisted session id to read.
832
+ * @param signal - optional cancellation for source resolution and title folding.
833
+ * @returns latest title snapshot, or `undefined` when the log has no title event.
834
+ */
835
+ async readTitle(sessionId, signal) {
836
+ return (await this.readTitleSnapshot(sessionId, signal)).title;
837
+ }
838
+ /**
839
+ * Fold the latest title and return its source header from one corpus observation.
840
+ * @param sessionId - live or persisted session id to read.
841
+ * @param signal - optional cancellation for source resolution and title folding.
842
+ * @returns cloned source header and optional latest title snapshot.
843
+ */
844
+ async readTitleSnapshot(sessionId, signal) {
845
+ const result = (await this.readTitleSnapshots([sessionId], signal))[0];
846
+ if (result.status === "rejected") throw result.reason;
847
+ return result.value;
848
+ }
849
+ /**
850
+ * Fold titles for unique sessions from one cancellable corpus observation.
851
+ *
852
+ * Results preserve first-occurrence input order. Operational failures stay
853
+ * isolated per session, while cancellation rejects the complete operation.
854
+ * @param sessionIds - live or persisted session ids to observe.
855
+ * @param signal - optional cancellation shared by all source reads.
856
+ * @returns one fulfilled or rejected result per unique requested id.
857
+ */
858
+ async readTitleSnapshots(sessionIds, signal) {
859
+ return this._corpus.projectMany(sessionIds, (source) => {
860
+ const title = foldSessionTitle(source.events);
861
+ return {
862
+ session: structuredClone(source.header),
863
+ ...title === void 0 ? {} : { title }
864
+ };
865
+ }, signal);
866
+ }
867
+ /**
868
+ * List lightweight raw-log event records for one logical session.
869
+ * @param sessionId - live-preferred session id to read.
870
+ * @returns event records in ascending seq order.
871
+ */
872
+ async listEvents(sessionId) {
873
+ return eventRecords(sessionId, (await this._corpus.load(sessionId)).events);
874
+ }
875
+ /**
876
+ * Scan first-party semantic event documents with provider-independent filters.
877
+ * @param sessionId - live-preferred session id to scan.
878
+ * @param filters - ANDed metadata and literal-text predicates.
879
+ * @returns matching semantic documents in ascending seq order.
880
+ */
881
+ async filterEvents(sessionId, filters) {
882
+ const ownedFilters = materializeSessionEventResultFilters(filters);
883
+ return this._filterEvents(sessionId, ownedFilters);
884
+ }
885
+ async _filterSessions(filters, signal) {
886
+ return filterSessionResults(await this._corpus.listSessions(signal), filters);
887
+ }
888
+ async _filterEvents(sessionId, filters) {
889
+ return filterSessionEventDocuments(buildSessionEventSearchDocuments(sessionId, (await this._corpus.load(sessionId)).events), filters);
890
+ }
891
+ /**
892
+ * Read one session's complete current model surface from one corpus observation.
893
+ * @param sessionId - live-preferred session id to read.
894
+ * @returns cloned header, current surface, and the last sequence number included in the raw-log capture.
895
+ * @throws when source resolution fails or the session surface is invalid.
896
+ */
897
+ async readSurface(sessionId) {
898
+ const loaded = await this._corpus.load(sessionId);
899
+ return {
900
+ session: structuredClone(loaded.header),
901
+ capturedThroughSeq: loaded.events.at(-1)?.seq ?? null,
902
+ events: currentSurfaceEvents(sessionId, loaded.events)
903
+ };
904
+ }
905
+ /**
906
+ * Trace known ancestry and descendants from one corpus observation.
907
+ * @param sessionId - logical session id to trace.
908
+ * @param signal - optional cancellation for persistence listing.
909
+ * @returns a complete lineage or the first parent that could not be resolved.
910
+ * @throws when corpus resolution fails, the target is absent, or its known ancestry cycles.
911
+ */
912
+ async traceSession(sessionId, signal) {
913
+ const records = await this._corpus.listSessions(signal);
914
+ signal?.throwIfAborted();
915
+ return traceSession(records, sessionId);
916
+ }
917
+ /**
918
+ * Trace one event's direct positional replacements and cited source events.
919
+ * @param request - target session id and event seq.
920
+ * @param signal - optional cancellation for persisted source resolution.
921
+ * @returns source header, direct links, and the target's positional replacement chain.
922
+ * @throws when source resolution fails, the target is absent, or surface/source-event validation fails.
923
+ */
924
+ async traceEvent(request, signal) {
925
+ const loaded = await this._corpus.load(request.sessionId, signal);
926
+ signal?.throwIfAborted();
927
+ return {
928
+ session: loaded.header,
929
+ ...traceEvent(request.sessionId, loaded.events, request.seq)
930
+ };
931
+ }
932
+ /**
933
+ * Read one full event plus a bounded raw-log context window.
934
+ * @param request - target session/seq and context sizes.
935
+ * @param signal - optional cancellation for persisted source resolution.
936
+ * @returns cloned target and neighboring events.
937
+ */
938
+ async readEvent(request, signal) {
939
+ const before = this._readWindow("before", request.before);
940
+ const after = this._readWindow("after", request.after);
941
+ const sessionId = request.sessionId;
942
+ const seq = request.seq;
943
+ return this._readEvent(sessionId, seq, before, after, signal);
944
+ }
945
+ async _readEvent(sessionId, seq, before, after, signal) {
946
+ const loaded = await this._corpus.load(sessionId, signal);
947
+ signal?.throwIfAborted();
948
+ const target = loaded.events[seq];
949
+ if (target === void 0 || target.seq !== seq) throw new SessionQueryError(`session "${sessionId}" has no event at seq ${seq}`, "SESSION_QUERY_EVENT_NOT_FOUND");
950
+ const startSeq = Math.max(0, seq - before);
951
+ const endSeq = Math.min(loaded.events.length - 1, seq + after);
952
+ const targetSnapshot = snapshotSessionEvent(target);
953
+ const events = loaded.events.slice(startSeq, endSeq + 1).map((event) => event === target ? targetSnapshot : snapshotSessionEvent(event));
954
+ return {
955
+ session: structuredClone(loaded.header),
956
+ target: targetSnapshot,
957
+ events,
958
+ startSeq,
959
+ endSeq
960
+ };
961
+ }
962
+ _readWindow(name, value) {
963
+ if (value === void 0) return 0;
964
+ if (!Number.isInteger(value) || value < 0 || value > this._readWindowMax) throw new SessionQueryError(`${name} must be an integer between 0 and ${this._readWindowMax}`, "SESSION_QUERY_INVALID_WINDOW");
965
+ return value;
966
+ }
967
+ };
968
+ //#endregion
969
+ export { SESSION_QUERY_DEFAULT_PERSISTED_INSPECT_CONCURRENCY, SESSION_QUERY_READ_WINDOW_MAX, SessionQueryEngine, SessionQueryEngine as default, SessionQueryError, SessionSearchCursor, assertSessionHeadersCompatible, buildSessionEventRecords, buildSessionEventSearchDocuments, compileSessionTextFilter, extractSessionEventText, filterSessionEventDocuments, filterSessionResults, materializeSessionEventResultFilters, materializeSessionResultFilters };