@wrongstack/core 0.302.0 → 0.302.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.
Files changed (42) hide show
  1. package/dist/agent-status-tracker.d.ts +6 -2
  2. package/dist/chronicle/index.js +1836 -1645
  3. package/dist/chronicle/metrics-store.d.ts +14 -0
  4. package/dist/chronicle/project-server-protocol.d.ts +13 -0
  5. package/dist/chronicle/project-server.js +1759 -1583
  6. package/dist/chronicle/rollup-adapter.d.ts +2 -0
  7. package/dist/chronicle/sqlite-journal.d.ts +59 -0
  8. package/dist/coordination/index.js +790 -248
  9. package/dist/coordination/mail-tools.d.ts +2 -2
  10. package/dist/core/continue-intent.d.ts +2 -0
  11. package/dist/core/conversation-state.d.ts +5 -0
  12. package/dist/core/index.js +120 -19
  13. package/dist/defaults/index.js +927 -373
  14. package/dist/execution/index.js +27 -10
  15. package/dist/index.d.ts +3 -1
  16. package/dist/index.js +8762 -6780
  17. package/dist/infrastructure/index.js +722 -672
  18. package/dist/kernel/events/memory-events.d.ts +62 -0
  19. package/dist/plugin/index.js +2154 -1979
  20. package/dist/session-catalog/client.d.ts +62 -0
  21. package/dist/session-catalog/endpoint.d.ts +6 -0
  22. package/dist/session-catalog/index.d.ts +6 -0
  23. package/dist/session-catalog/index.js +1978 -0
  24. package/dist/session-catalog/project-server.d.ts +3 -0
  25. package/dist/session-catalog/project-server.js +1838 -0
  26. package/dist/session-catalog/protocol.d.ts +275 -0
  27. package/dist/session-catalog/registry.d.ts +59 -0
  28. package/dist/session-catalog/store.d.ts +55 -0
  29. package/dist/storage/index.d.ts +42 -38
  30. package/dist/storage/index.js +14279 -13393
  31. package/dist/storage/session-event-bridge.d.ts +2 -2
  32. package/dist/storage/session-store.d.ts +6 -0
  33. package/dist/tools/index.js +8 -2
  34. package/dist/types/context-evidence.d.ts +2 -0
  35. package/dist/types/messages.d.ts +8 -0
  36. package/dist/types/session.d.ts +19 -0
  37. package/dist/utils/context-evidence.d.ts +13 -1
  38. package/dist/utils/index.js +26 -2
  39. package/instructions/system-lite.md +11 -2
  40. package/instructions/system-pro.md +14 -0
  41. package/instructions/system.md +14 -0
  42. package/package.json +7 -3
@@ -0,0 +1,1978 @@
1
+ // src/session-catalog/client.ts
2
+ import { spawn } from "node:child_process";
3
+ import * as fs2 from "node:fs";
4
+ import * as net from "node:net";
5
+ import * as path2 from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ // src/session-catalog/endpoint.ts
9
+ import { createHash } from "node:crypto";
10
+ import * as fs from "node:fs";
11
+ import * as os from "node:os";
12
+ import * as path from "node:path";
13
+
14
+ // src/utils/socket-path.ts
15
+ import {
16
+ assertUnixSocketPathWithinLimit,
17
+ checkUnixSocketPath,
18
+ unixSocketPathLimit
19
+ } from "@wrongstack/persistence";
20
+
21
+ // src/session-catalog/protocol.ts
22
+ var SESSION_CATALOG_PROTOCOL_VERSION = 1;
23
+ var SESSION_CATALOG_MAX_FRAME_CHARS = 4 * 1024 * 1024;
24
+ var SESSION_CATALOG_DEFAULT_LEASE_MS = 3e4;
25
+ var SESSION_CATALOG_DEFAULT_RESERVATION_MS = 15e3;
26
+ var SESSION_CATALOG_MAX_AGENTS = 128;
27
+ function encodeSessionCatalogMessage(message) {
28
+ return `${JSON.stringify(message)}
29
+ `;
30
+ }
31
+
32
+ // src/session-catalog/endpoint.ts
33
+ var SESSION_CATALOG_METADATA_FILE = ".session-catalog-server.json";
34
+ function normalizedPath(value) {
35
+ const resolved = path.resolve(value);
36
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
37
+ }
38
+ function sessionCatalogProjectServerKey(projectDir) {
39
+ return createHash("sha256").update(normalizedPath(projectDir)).digest("hex").slice(0, 24);
40
+ }
41
+ function sessionCatalogProjectServerEndpoint(projectDir) {
42
+ const key = sessionCatalogProjectServerKey(projectDir);
43
+ if (process.platform === "win32") {
44
+ return `\\\\.\\pipe\\wrongstack-session-catalog-v${SESSION_CATALOG_PROTOCOL_VERSION}-${key}`;
45
+ }
46
+ return path.join(os.tmpdir(), `wssc-v${SESSION_CATALOG_PROTOCOL_VERSION}`, `${key}.sock`);
47
+ }
48
+ function sessionCatalogProjectServerMetadataPath(projectDir) {
49
+ return path.join(projectDir, SESSION_CATALOG_METADATA_FILE);
50
+ }
51
+ function ensureSessionCatalogSocketDirectory(endpoint) {
52
+ if (process.platform === "win32") return;
53
+ assertUnixSocketPathWithinLimit(endpoint, "session-catalog");
54
+ fs.mkdirSync(path.dirname(endpoint), { recursive: true, mode: 448 });
55
+ }
56
+
57
+ // src/session-catalog/client.ts
58
+ var CONNECT_TIMEOUT_MS = 750;
59
+ var START_TIMEOUT_MS = 1e4;
60
+ var CALL_TIMEOUT_MS = 3e4;
61
+ var MAX_PENDING_REQUESTS = 1024;
62
+ var MAX_EVENT_LISTENERS = 64;
63
+ function locateServer(moduleUrl, exists) {
64
+ for (const candidate of [
65
+ "./project-server.js",
66
+ "../session-catalog/project-server.js",
67
+ "./session-catalog/project-server.js",
68
+ "../../dist/session-catalog/project-server.js"
69
+ ]) {
70
+ try {
71
+ const url = new URL(candidate, moduleUrl);
72
+ if (url.protocol === "file:" && exists(fileURLToPath(url))) return url;
73
+ } catch {
74
+ }
75
+ }
76
+ return null;
77
+ }
78
+ function resolveSessionCatalogDaemonAvailability(moduleUrl = import.meta.url, exists = fs2.existsSync) {
79
+ if (process.env["WRONGSTACK_SESSION_CATALOG_INLINE"] || process.env["WRONGSTACK_SESSION_CATALOG_SERVER"] === "0")
80
+ return { kind: "inline-requested" };
81
+ const url = locateServer(moduleUrl, exists);
82
+ return url ? { kind: "available", url } : { kind: "missing-build" };
83
+ }
84
+ function resolveSessionCatalogProjectServerUrl(moduleUrl = import.meta.url, exists = fs2.existsSync) {
85
+ const availability = resolveSessionCatalogDaemonAvailability(moduleUrl, exists);
86
+ return availability.kind === "available" ? availability.url : null;
87
+ }
88
+ function normalize(value) {
89
+ const resolved = path2.resolve(value);
90
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
91
+ }
92
+ function delay(ms) {
93
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
94
+ }
95
+ var SessionCatalogProjectClient = class {
96
+ constructor(options) {
97
+ this.options = options;
98
+ this.endpoint = sessionCatalogProjectServerEndpoint(options.projectDir);
99
+ }
100
+ options;
101
+ endpoint;
102
+ socket = null;
103
+ info = null;
104
+ buffer = "";
105
+ connecting = null;
106
+ connectResolve = null;
107
+ connectReject = null;
108
+ authToken;
109
+ nextId = 1;
110
+ pending = /* @__PURE__ */ new Map();
111
+ eventListeners = /* @__PURE__ */ new Set();
112
+ reconnectTimer;
113
+ explicitlyClosed = false;
114
+ async call(op, args, options = {}) {
115
+ await this.ensureConnected(true);
116
+ return this.request({ type: "request", op, args }, options.timeoutMs ?? CALL_TIMEOUT_MS);
117
+ }
118
+ /**
119
+ * Call an already-running project daemon without starting one.
120
+ *
121
+ * Cross-project discovery must use this path: observing another project is
122
+ * never sufficient authority to wake that project's IPC owner.
123
+ */
124
+ async callExisting(op, args, options = {}) {
125
+ await this.ensureConnected(false);
126
+ return this.request({ type: "request", op, args }, options.timeoutMs ?? CALL_TIMEOUT_MS);
127
+ }
128
+ ping() {
129
+ return this.call("ping", {}, { timeoutMs: 3e3 });
130
+ }
131
+ async subscribe(listener) {
132
+ if (!this.eventListeners.has(listener) && this.eventListeners.size >= MAX_EVENT_LISTENERS) {
133
+ throw new Error(`Session Catalog listener limit reached (${MAX_EVENT_LISTENERS})`);
134
+ }
135
+ this.explicitlyClosed = false;
136
+ this.eventListeners.add(listener);
137
+ try {
138
+ await this.call("subscribe", {});
139
+ } catch (error) {
140
+ this.eventListeners.delete(listener);
141
+ throw error;
142
+ }
143
+ return async () => {
144
+ this.eventListeners.delete(listener);
145
+ if (this.eventListeners.size === 0)
146
+ await this.callExisting("unsubscribe", {}).catch(() => void 0);
147
+ };
148
+ }
149
+ async shutdown(reason) {
150
+ try {
151
+ await this.ensureConnected(false);
152
+ } catch {
153
+ return { stopped: false };
154
+ }
155
+ const result = await this.request({ type: "shutdown", ...reason !== void 0 ? { reason } : {} }, 5e3).catch(
156
+ () => ({ stopped: false })
157
+ );
158
+ if (result.stopped) {
159
+ const metadataPath = sessionCatalogProjectServerMetadataPath(this.options.projectDir);
160
+ const deadline = Date.now() + 5e3;
161
+ while (fs2.existsSync(metadataPath) && Date.now() < deadline) await delay(20);
162
+ if (result.pid && result.pid !== process.pid) {
163
+ while (Date.now() < deadline) {
164
+ try {
165
+ process.kill(result.pid, 0);
166
+ await delay(20);
167
+ } catch {
168
+ break;
169
+ }
170
+ }
171
+ }
172
+ }
173
+ return result;
174
+ }
175
+ async close() {
176
+ this.explicitlyClosed = true;
177
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
178
+ this.reconnectTimer = void 0;
179
+ const socket = this.socket;
180
+ this.socket = null;
181
+ this.info = null;
182
+ if (socket && !socket.destroyed)
183
+ await new Promise((resolve5) => {
184
+ socket.once("close", resolve5);
185
+ socket.end();
186
+ });
187
+ }
188
+ async ensureConnected(spawnIfMissing) {
189
+ if (this.socket && !this.socket.destroyed && this.info) return;
190
+ if (this.connecting) return this.connecting;
191
+ this.connecting = this.connectWithElection(spawnIfMissing).finally(() => {
192
+ this.connecting = null;
193
+ });
194
+ return this.connecting;
195
+ }
196
+ async connectWithElection(spawnIfMissing) {
197
+ const deadline = Date.now() + (spawnIfMissing ? START_TIMEOUT_MS : CONNECT_TIMEOUT_MS);
198
+ let spawned = false;
199
+ let lastError = new Error("Session Catalog project server unavailable");
200
+ while (Date.now() < deadline) {
201
+ try {
202
+ await this.connectOnce();
203
+ return;
204
+ } catch (error) {
205
+ lastError = error;
206
+ }
207
+ if (!spawnIfMissing) break;
208
+ if (!spawned) {
209
+ this.spawnDetached();
210
+ spawned = true;
211
+ }
212
+ await delay(75);
213
+ }
214
+ throw lastError;
215
+ }
216
+ connectOnce() {
217
+ this.socket?.destroy();
218
+ this.socket = null;
219
+ this.info = null;
220
+ this.authToken = void 0;
221
+ this.buffer = "";
222
+ return new Promise((resolve5, reject) => {
223
+ const socket = net.createConnection(this.endpoint);
224
+ this.socket = socket;
225
+ socket.setEncoding("utf8");
226
+ const timer = setTimeout(() => {
227
+ reject(new Error("Session Catalog handshake timed out"));
228
+ socket.destroy();
229
+ }, CONNECT_TIMEOUT_MS);
230
+ timer.unref?.();
231
+ this.connectResolve = () => {
232
+ clearTimeout(timer);
233
+ this.connectResolve = null;
234
+ this.connectReject = null;
235
+ resolve5();
236
+ };
237
+ this.connectReject = (error) => {
238
+ clearTimeout(timer);
239
+ this.connectResolve = null;
240
+ this.connectReject = null;
241
+ reject(error);
242
+ };
243
+ socket.on("data", (chunk) => this.onData(socket, chunk));
244
+ socket.on("error", (error) => {
245
+ if (!this.info) this.connectReject?.(error);
246
+ });
247
+ socket.on("close", () => this.onClose(socket));
248
+ });
249
+ }
250
+ currentAuthToken() {
251
+ if (this.authToken === void 0) {
252
+ try {
253
+ const parsed = JSON.parse(
254
+ fs2.readFileSync(sessionCatalogProjectServerMetadataPath(this.options.projectDir), "utf8")
255
+ );
256
+ if (typeof parsed.authToken === "string" && parsed.authToken)
257
+ this.authToken = parsed.authToken;
258
+ } catch {
259
+ }
260
+ }
261
+ return this.authToken;
262
+ }
263
+ request(message, timeoutMs) {
264
+ const socket = this.socket;
265
+ if (!socket || socket.destroyed)
266
+ return Promise.reject(new Error("Session Catalog connection is unavailable"));
267
+ const id = this.nextId++;
268
+ if (this.pending.size >= MAX_PENDING_REQUESTS) {
269
+ return Promise.reject(
270
+ new Error(`Session Catalog pending request limit reached (${MAX_PENDING_REQUESTS})`)
271
+ );
272
+ }
273
+ const encoded = encodeSessionCatalogMessage({
274
+ ...message,
275
+ id,
276
+ authToken: this.currentAuthToken()
277
+ });
278
+ if (encoded.length > SESSION_CATALOG_MAX_FRAME_CHARS)
279
+ return Promise.reject(new Error("Session Catalog request exceeded frame limit"));
280
+ return new Promise((resolve5, reject) => {
281
+ const timer = setTimeout(() => {
282
+ const pending = this.pending.get(id);
283
+ if (!pending) return;
284
+ this.pending.delete(id);
285
+ pending.reject(
286
+ new Error(
287
+ `Session Catalog ${message.type === "request" ? message.op : message.type} timed out`
288
+ )
289
+ );
290
+ }, timeoutMs);
291
+ timer.unref?.();
292
+ this.pending.set(id, { resolve: resolve5, reject, timer });
293
+ socket.write(encoded);
294
+ });
295
+ }
296
+ onData(socket, chunk) {
297
+ if (socket !== this.socket) return;
298
+ this.buffer += chunk;
299
+ if (this.buffer.length > SESSION_CATALOG_MAX_FRAME_CHARS) {
300
+ socket.destroy(new Error("Session Catalog response exceeded frame limit"));
301
+ return;
302
+ }
303
+ while (true) {
304
+ const newline = this.buffer.indexOf("\n");
305
+ if (newline < 0) return;
306
+ const line = this.buffer.slice(0, newline);
307
+ this.buffer = this.buffer.slice(newline + 1);
308
+ if (!line) continue;
309
+ try {
310
+ this.onMessage(JSON.parse(line));
311
+ } catch {
312
+ socket.destroy(new Error("Invalid Session Catalog response"));
313
+ return;
314
+ }
315
+ }
316
+ }
317
+ onMessage(message) {
318
+ if (message.type === "hello") {
319
+ if (message.protocolVersion !== SESSION_CATALOG_PROTOCOL_VERSION) {
320
+ this.connectReject?.(
321
+ new Error(
322
+ `Session Catalog protocol mismatch: client=${SESSION_CATALOG_PROTOCOL_VERSION}, server=${message.protocolVersion}`
323
+ )
324
+ );
325
+ this.socket?.destroy();
326
+ return;
327
+ }
328
+ if (normalize(message.projectDir) !== normalize(this.options.projectDir) || normalize(message.projectRoot) !== normalize(this.options.projectRoot)) {
329
+ this.connectReject?.(new Error("Session Catalog project identity mismatch"));
330
+ this.socket?.destroy();
331
+ return;
332
+ }
333
+ this.info = message;
334
+ this.connectResolve?.();
335
+ return;
336
+ }
337
+ if (message.type === "event") {
338
+ for (const listener of this.eventListeners) {
339
+ try {
340
+ listener(message.event);
341
+ } catch {
342
+ }
343
+ }
344
+ return;
345
+ }
346
+ const pending = this.pending.get(message.id);
347
+ if (!pending) return;
348
+ this.pending.delete(message.id);
349
+ clearTimeout(pending.timer);
350
+ if (message.ok) pending.resolve(message.result);
351
+ else {
352
+ const error = new Error(message.error);
353
+ if (message.errorName) error.name = message.errorName;
354
+ pending.reject(error);
355
+ }
356
+ }
357
+ onClose(socket) {
358
+ if (socket !== this.socket) return;
359
+ this.socket = null;
360
+ this.info = null;
361
+ this.authToken = void 0;
362
+ const error = new Error("Session Catalog connection closed");
363
+ this.connectReject?.(error);
364
+ this.connectResolve = null;
365
+ this.connectReject = null;
366
+ for (const pending of this.pending.values()) {
367
+ clearTimeout(pending.timer);
368
+ pending.reject(error);
369
+ }
370
+ this.pending.clear();
371
+ this.scheduleSubscriptionReconnect();
372
+ }
373
+ scheduleSubscriptionReconnect() {
374
+ if (this.explicitlyClosed || this.eventListeners.size === 0 || this.reconnectTimer) return;
375
+ this.reconnectTimer = setTimeout(() => {
376
+ this.reconnectTimer = void 0;
377
+ void this.call("subscribe", {}).catch(() => this.scheduleSubscriptionReconnect());
378
+ }, 250);
379
+ this.reconnectTimer.unref?.();
380
+ }
381
+ spawnDetached() {
382
+ const url = resolveSessionCatalogProjectServerUrl();
383
+ if (!url) throw new Error("Built Session Catalog project server is unavailable");
384
+ const child = spawn(
385
+ process.execPath,
386
+ [
387
+ fileURLToPath(url),
388
+ "--project-dir",
389
+ this.options.projectDir,
390
+ "--project-root",
391
+ this.options.projectRoot
392
+ ],
393
+ { detached: true, stdio: "ignore", windowsHide: true, env: process.env }
394
+ );
395
+ child.unref();
396
+ }
397
+ };
398
+
399
+ // src/session-catalog/registry.ts
400
+ import { randomUUID } from "node:crypto";
401
+ import * as fs3 from "node:fs/promises";
402
+ import * as path3 from "node:path";
403
+ var HEARTBEAT_INTERVAL_MS = 5e3;
404
+ var AGENT_WRITE_THROTTLE_MS = 300;
405
+ var MAX_PROJECT_CLIENTS = 128;
406
+ var MAX_GLOBAL_ROOTS = 16;
407
+ var ProjectSessionRegistry = class {
408
+ constructor(globalRoot) {
409
+ this.globalRoot = globalRoot;
410
+ }
411
+ globalRoot;
412
+ instanceId = randomUUID();
413
+ clients = /* @__PURE__ */ new Map();
414
+ current;
415
+ heartbeatTimer;
416
+ agentRevision = 0;
417
+ pendingAgents;
418
+ agentTimer;
419
+ lastAgentWriteAt = 0;
420
+ bindingKey(projectDir) {
421
+ const resolved = path3.resolve(projectDir);
422
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
423
+ }
424
+ async closeBinding(binding) {
425
+ if (this.current?.binding === binding) return;
426
+ const key = this.bindingKey(binding.projectDir);
427
+ if (this.clients.get(key) === binding) this.clients.delete(key);
428
+ await binding.client.close();
429
+ }
430
+ binding(projectSlug, projectRoot) {
431
+ const projectDir = path3.join(this.globalRoot, "projects", projectSlug);
432
+ const key = this.bindingKey(projectDir);
433
+ let binding = this.clients.get(key);
434
+ if (!binding) {
435
+ if (this.clients.size >= MAX_PROJECT_CLIENTS) {
436
+ const oldest = [...this.clients.entries()].find(
437
+ ([, candidate]) => candidate !== this.current?.binding
438
+ );
439
+ if (oldest) {
440
+ this.clients.delete(oldest[0]);
441
+ void oldest[1].client.close();
442
+ }
443
+ }
444
+ binding = {
445
+ projectDir,
446
+ projectRoot: path3.resolve(projectRoot),
447
+ client: new SessionCatalogProjectClient({ projectDir, projectRoot })
448
+ };
449
+ this.clients.set(key, binding);
450
+ } else {
451
+ this.clients.delete(key);
452
+ this.clients.set(key, binding);
453
+ }
454
+ return binding;
455
+ }
456
+ fullEntry(entry) {
457
+ const agents = entry.agents ?? [];
458
+ return {
459
+ ...entry,
460
+ status: agents.some((agent) => agent.status !== "idle") ? "active" : "idle",
461
+ lastHeartbeatAt: (/* @__PURE__ */ new Date()).toISOString(),
462
+ agentCount: agents.length,
463
+ agents
464
+ };
465
+ }
466
+ async register(entry) {
467
+ const full = this.fullEntry(entry);
468
+ if (this.current?.entry.sessionId === full.sessionId && this.current.entry.pid === full.pid) {
469
+ this.current.entry = full;
470
+ this.current.credential = await this.current.binding.client.call("heartbeat", {
471
+ credential: this.current.credential,
472
+ status: full.status
473
+ });
474
+ return;
475
+ }
476
+ const nextBinding = this.binding(full.projectSlug, full.projectRoot);
477
+ let nextCredential;
478
+ try {
479
+ nextCredential = await nextBinding.client.call("claim_new", {
480
+ entry: full,
481
+ ownerInstanceId: this.instanceId
482
+ });
483
+ } catch (error) {
484
+ await this.closeBinding(nextBinding).catch(() => void 0);
485
+ throw error;
486
+ }
487
+ const previous = this.current;
488
+ this.current = { binding: nextBinding, credential: nextCredential, entry: full };
489
+ this.agentRevision = 0;
490
+ this.cancelAgentTimer();
491
+ this.startHeartbeat();
492
+ if (previous) {
493
+ await previous.binding.client.call("release", { credential: previous.credential }).catch(() => void 0);
494
+ if (previous.binding !== nextBinding) await this.closeBinding(previous.binding);
495
+ }
496
+ }
497
+ /** Reserve before transcript hydration; activation swaps ownership only after the writer opened. */
498
+ async reserveResume(target) {
499
+ const binding = this.binding(target.projectSlug, target.projectRoot);
500
+ let reservation;
501
+ try {
502
+ reservation = await binding.client.call("reserve_resume", {
503
+ targetSessionId: target.sessionId,
504
+ requesterInstanceId: this.instanceId,
505
+ ...this.current ? { currentSessionId: this.current.entry.sessionId } : {}
506
+ });
507
+ } catch (error) {
508
+ await this.closeBinding(binding).catch(() => void 0);
509
+ throw error;
510
+ }
511
+ let settled = false;
512
+ return {
513
+ reservation,
514
+ activate: async (registration) => {
515
+ if (settled) throw new Error("Resume reservation is already settled");
516
+ const entry = this.fullEntry(registration);
517
+ const credential = await binding.client.call("activate_reservation", {
518
+ reservation,
519
+ entry
520
+ });
521
+ const previous = this.current;
522
+ this.current = { binding, credential, entry };
523
+ settled = true;
524
+ this.agentRevision = 0;
525
+ this.cancelAgentTimer();
526
+ this.startHeartbeat();
527
+ if (previous) {
528
+ await previous.binding.client.call("release", { credential: previous.credential }).catch(() => void 0);
529
+ if (previous.binding !== binding) await this.closeBinding(previous.binding);
530
+ }
531
+ },
532
+ cancel: async () => {
533
+ if (settled) return;
534
+ settled = true;
535
+ try {
536
+ await binding.client.call("cancel_reservation", {
537
+ reservationId: reservation.reservationId,
538
+ requesterInstanceId: this.instanceId
539
+ }).catch(() => void 0);
540
+ } finally {
541
+ await this.closeBinding(binding).catch(() => void 0);
542
+ }
543
+ }
544
+ };
545
+ }
546
+ async updateAgents(agents) {
547
+ if (!this.current) return;
548
+ this.pendingAgents = agents;
549
+ this.current.entry = {
550
+ ...this.current.entry,
551
+ agents,
552
+ agentCount: agents.length,
553
+ status: agents.some((agent) => agent.status !== "idle") ? "active" : "idle",
554
+ lastHeartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
555
+ };
556
+ const elapsed = Date.now() - this.lastAgentWriteAt;
557
+ if (!this.agentTimer && elapsed >= AGENT_WRITE_THROTTLE_MS) {
558
+ await this.flushAgents();
559
+ return;
560
+ }
561
+ if (!this.agentTimer) {
562
+ this.agentTimer = setTimeout(
563
+ () => {
564
+ this.agentTimer = void 0;
565
+ void this.flushAgents();
566
+ },
567
+ Math.max(0, AGENT_WRITE_THROTTLE_MS - elapsed)
568
+ );
569
+ this.agentTimer.unref?.();
570
+ }
571
+ }
572
+ async flushAgents() {
573
+ const agents = this.pendingAgents;
574
+ const current = this.current;
575
+ if (!agents || !current) return;
576
+ this.pendingAgents = void 0;
577
+ this.lastAgentWriteAt = Date.now();
578
+ const revision = ++this.agentRevision;
579
+ await current.binding.client.call("publish_agents", {
580
+ credential: current.credential,
581
+ revision,
582
+ agents
583
+ });
584
+ }
585
+ async markClosing() {
586
+ this.stopHeartbeat();
587
+ this.cancelAgentTimer();
588
+ if (this.current)
589
+ await this.current.binding.client.call("mark_closing", {
590
+ credential: this.current.credential
591
+ });
592
+ }
593
+ async unregister() {
594
+ this.stopHeartbeat();
595
+ this.cancelAgentTimer();
596
+ const current = this.current;
597
+ this.current = void 0;
598
+ if (current) {
599
+ try {
600
+ await current.binding.client.call("release", { credential: current.credential });
601
+ } finally {
602
+ await this.closeBinding(current.binding);
603
+ }
604
+ }
605
+ }
606
+ async list() {
607
+ const projectsDir = path3.join(this.globalRoot, "projects");
608
+ let directories = [];
609
+ try {
610
+ directories = (await fs3.readdir(projectsDir, { withFileTypes: true })).filter((entry) => entry.isDirectory()).slice(0, 1e3).map((entry) => entry.name);
611
+ } catch {
612
+ return [];
613
+ }
614
+ const snapshots = await Promise.all(
615
+ directories.map(async (slug) => {
616
+ const projectDir = path3.join(projectsDir, slug);
617
+ let client;
618
+ try {
619
+ const metadata = JSON.parse(
620
+ await fs3.readFile(sessionCatalogProjectServerMetadataPath(projectDir), "utf8")
621
+ );
622
+ if (typeof metadata.projectRoot !== "string" || !metadata.projectRoot) return [];
623
+ client = new SessionCatalogProjectClient({
624
+ projectDir,
625
+ projectRoot: metadata.projectRoot
626
+ });
627
+ return await client.callExisting("list_live", {});
628
+ } catch {
629
+ return [];
630
+ } finally {
631
+ await client?.close().catch(() => void 0);
632
+ }
633
+ })
634
+ );
635
+ return snapshots.flat();
636
+ }
637
+ async listByProject(projectSlug) {
638
+ const current = this.current;
639
+ if (current && path3.basename(current.binding.projectDir) === projectSlug) {
640
+ return current.binding.client.call("list_live", {}).catch(() => []);
641
+ }
642
+ const projectDir = path3.join(this.globalRoot, "projects", projectSlug);
643
+ let client;
644
+ try {
645
+ const metadata = JSON.parse(
646
+ await fs3.readFile(sessionCatalogProjectServerMetadataPath(projectDir), "utf8")
647
+ );
648
+ if (typeof metadata.projectRoot !== "string") return [];
649
+ client = new SessionCatalogProjectClient({ projectDir, projectRoot: metadata.projectRoot });
650
+ return await client.callExisting("list_live", {}).catch(() => []);
651
+ } catch {
652
+ return [];
653
+ } finally {
654
+ await client?.close().catch(() => void 0);
655
+ }
656
+ }
657
+ async get(sessionId) {
658
+ return (await this.list()).find((entry) => entry.sessionId === sessionId);
659
+ }
660
+ subscribeProject(projectSlug, projectRoot, listener) {
661
+ const binding = this.binding(projectSlug, projectRoot);
662
+ return binding.client.subscribe(listener).then((unsubscribe) => async () => {
663
+ await unsubscribe();
664
+ await this.closeBinding(binding);
665
+ });
666
+ }
667
+ get registryPath() {
668
+ return path3.join(this.globalRoot, "projects");
669
+ }
670
+ async dispose() {
671
+ await this.unregister().catch(() => void 0);
672
+ await Promise.all([...this.clients.values()].map((binding) => binding.client.close()));
673
+ this.clients.clear();
674
+ }
675
+ /** Whether this facade currently owns a live session lease. */
676
+ ownsSession() {
677
+ return this.current !== void 0;
678
+ }
679
+ startHeartbeat() {
680
+ this.stopHeartbeat();
681
+ this.heartbeatTimer = setInterval(() => {
682
+ void this.heartbeat();
683
+ }, HEARTBEAT_INTERVAL_MS);
684
+ this.heartbeatTimer.unref?.();
685
+ }
686
+ stopHeartbeat() {
687
+ if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
688
+ this.heartbeatTimer = void 0;
689
+ }
690
+ cancelAgentTimer() {
691
+ if (this.agentTimer) clearTimeout(this.agentTimer);
692
+ this.agentTimer = void 0;
693
+ this.pendingAgents = void 0;
694
+ }
695
+ async heartbeat() {
696
+ const current = this.current;
697
+ if (!current) return;
698
+ try {
699
+ const credential = await current.binding.client.call("heartbeat", {
700
+ credential: current.credential,
701
+ status: current.entry.status
702
+ });
703
+ if (this.current === current) current.credential = credential;
704
+ } catch {
705
+ }
706
+ }
707
+ };
708
+ var registries = /* @__PURE__ */ new Map();
709
+ var lastRegistryKey;
710
+ function getProjectSessionRegistry(globalRoot) {
711
+ const key = globalRoot !== void 0 ? path3.resolve(globalRoot) : lastRegistryKey;
712
+ if (!key)
713
+ throw new Error("SessionRegistry not initialized. Call getSessionRegistry(globalRoot) first.");
714
+ let registry = registries.get(key);
715
+ if (!registry) {
716
+ if (registries.size >= MAX_GLOBAL_ROOTS) {
717
+ const idle = [...registries.entries()].find(([, candidate]) => !candidate.ownsSession());
718
+ if (!idle)
719
+ throw new Error(`Session Registry global-root limit reached (${MAX_GLOBAL_ROOTS})`);
720
+ registries.delete(idle[0]);
721
+ void idle[1].dispose();
722
+ }
723
+ registry = new ProjectSessionRegistry(key);
724
+ registries.set(key, registry);
725
+ } else {
726
+ registries.delete(key);
727
+ registries.set(key, registry);
728
+ }
729
+ lastRegistryKey = key;
730
+ return registry;
731
+ }
732
+ function hasProjectSessionRegistry(globalRoot) {
733
+ if (globalRoot === void 0) return registries.size > 0;
734
+ return registries.has(path3.resolve(globalRoot));
735
+ }
736
+
737
+ // src/session-catalog/store.ts
738
+ import { createHash as createHash2, randomBytes, randomUUID as randomUUID2, timingSafeEqual } from "node:crypto";
739
+ import * as fs4 from "node:fs";
740
+ import * as path4 from "node:path";
741
+
742
+ // src/coordination/sqlite-mailbox-schema.ts
743
+ import { createRequire } from "node:module";
744
+
745
+ // src/utils/sqlite-warning.ts
746
+ var SQLITE_EXPERIMENTAL_WARNING_RE = /sqlite is an experimental feature/i;
747
+ function isSqliteExperimentalWarning(warning, rest) {
748
+ const message = typeof warning === "string" ? warning : warning instanceof Error ? warning.message : "";
749
+ const typeOrOptions = rest[0];
750
+ const warningType = typeof warning === "string" ? typeof typeOrOptions === "string" ? typeOrOptions : typeof typeOrOptions === "object" && typeOrOptions !== null && "type" in typeOrOptions && typeof typeOrOptions.type === "string" ? typeOrOptions.type : "" : warning instanceof Error ? warning.name : "";
751
+ const warningCode = typeof warning === "string" ? typeof typeOrOptions === "object" && typeOrOptions !== null && "code" in typeOrOptions && typeof typeOrOptions.code === "string" ? typeOrOptions.code : typeof rest[1] === "string" ? rest[1] : "" : warning instanceof Error && "code" in warning && typeof warning.code === "string" ? warning.code : "";
752
+ return SQLITE_EXPERIMENTAL_WARNING_RE.test(message) && (warningType === "ExperimentalWarning" || warningCode === "ExperimentalWarning");
753
+ }
754
+ function withSqliteExperimentalWarningSuppressed(run) {
755
+ const originalEmitWarning = process.emitWarning;
756
+ const forwardWarning = originalEmitWarning.bind(process);
757
+ process.emitWarning = ((warning, ...rest) => {
758
+ if (isSqliteExperimentalWarning(warning, rest)) return;
759
+ forwardWarning(warning, ...rest);
760
+ });
761
+ try {
762
+ return run();
763
+ } finally {
764
+ process.emitWarning = originalEmitWarning;
765
+ }
766
+ }
767
+
768
+ // src/coordination/sqlite-mailbox-schema.ts
769
+ var DatabaseSyncCtor;
770
+ function loadDatabaseSync() {
771
+ if (DatabaseSyncCtor) return DatabaseSyncCtor;
772
+ return withSqliteExperimentalWarningSuppressed(() => {
773
+ const require2 = createRequire(import.meta.url);
774
+ DatabaseSyncCtor = require2("node:sqlite").DatabaseSync;
775
+ return DatabaseSyncCtor;
776
+ });
777
+ }
778
+
779
+ // src/security/secret-scrubber.ts
780
+ var PATTERNS = [
781
+ // Anchored at the start where possible so partial matches inside larger
782
+ // strings don't trigger false positives.
783
+ {
784
+ type: "anthropic_key",
785
+ regex: /(?<![A-Za-z0-9])sk-ant-api\d+-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9])/g,
786
+ anchor: "sk-ant-"
787
+ },
788
+ { type: "openai_key", regex: /(?<![A-Za-z0-9])sk-(?:proj-)?[A-Za-z0-9_-]{20,}(?![A-Za-z0-9])/g, anchor: "sk-" },
789
+ { type: "github_pat", regex: /(?<![A-Za-z0-9])ghp_[A-Za-z0-9]{36,}(?![A-Za-z0-9])/g, anchor: "ghp_" },
790
+ { type: "github_pat_v2", regex: /(?<![A-Za-z0-9])github_pat_[A-Za-z0-9_]{50,}(?![A-Za-z0-9])/g, anchor: "github_pat_" },
791
+ { type: "aws_access_key", regex: /(?<![A-Za-z0-9])AKIA[0-9A-Z]{16}(?![A-Za-z0-9])/g, anchor: "AKIA" },
792
+ { type: "gcp_key", regex: /(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{35}(?![A-Za-z0-9])/g, anchor: "AIza" },
793
+ { type: "slack_token", regex: /(?<![A-Za-z0-9-])xox[abpos]-[A-Za-z0-9-]{10,}(?![A-Za-z0-9-])/g, anchor: "xox" },
794
+ {
795
+ type: "stripe_key",
796
+ regex: /(?<![A-Za-z0-9])sk_(?:live|test)_[A-Za-z0-9]{24,}(?![A-Za-z0-9])/g,
797
+ anchor: "sk_"
798
+ },
799
+ {
800
+ type: "twilio_sid",
801
+ regex: /(?<![A-Za-z0-9])AC[a-f0-9]{32}(?![A-Za-z0-9])/g,
802
+ anchor: "AC"
803
+ },
804
+ {
805
+ type: "telegram_bot_token",
806
+ // Telegram tokens are of the form bot<digits>:<alphanum> in URL paths
807
+ regex: /\/bot\d+:[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
808
+ anchor: "/bot"
809
+ },
810
+ {
811
+ type: "jwt",
812
+ // Anchored: look for literal "eyJ" which is unambiguous for JWT header
813
+ regex: /(?<![A-Za-z0-9/+=])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}(?![A-Za-z0-9/+=])/g,
814
+ anchor: "eyJ"
815
+ },
816
+ {
817
+ type: "private_key",
818
+ // Anchored: start must be BEGIN, end must be END with no extra dashes after END
819
+ regex: /(?:^|\n)-----BEGIN (?:RSA|EC|OPENSSH|DSA|PGP)? ?PRIVATE KEY-----[\s\S]*?-----END[^-]*-----(?:\n|$)/g,
820
+ anchor: "-----BEGIN"
821
+ },
822
+ { type: "mongodb_uri", regex: /mongodb(?:\+srv)?:\/\/[^\s"'`]+/g, anchor: "mongodb" },
823
+ { type: "postgres_uri", regex: /postgres(?:ql)?:\/\/[^\s"'`]+/g, anchor: "postgres" },
824
+ { type: "mysql_uri", regex: /mysql:\/\/[^\s"'`]+/g, anchor: "mysql://" },
825
+ { type: "redis_uri", regex: /redis:\/\/[^\s"'`]+/g, anchor: "redis://" },
826
+ // AI/ML provider keys — modern LLM services with well-known prefixes
827
+ {
828
+ type: "huggingface_token",
829
+ // HuggingFace tokens: hf_ followed by 34 alphanumeric chars
830
+ regex: /(?<![A-Za-z0-9])hf_[A-Za-z0-9]{34}(?![A-Za-z0-9])/g,
831
+ anchor: "hf_"
832
+ },
833
+ {
834
+ type: "replicate_token",
835
+ // Replicate tokens: r8_ followed by 40+ alphanumeric chars
836
+ regex: /(?<![A-Za-z0-9])r8_[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
837
+ anchor: "r8_"
838
+ },
839
+ {
840
+ type: "perplexity_key",
841
+ // Perplexity API keys: pplx- followed by 40+ alphanumeric chars
842
+ regex: /(?<![A-Za-z0-9])pplx-[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
843
+ anchor: "pplx-"
844
+ },
845
+ {
846
+ type: "groq_key",
847
+ // Groq API keys: gsk_ followed by 40+ alphanumeric chars
848
+ regex: /(?<![A-Za-z0-9])gsk_[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
849
+ anchor: "gsk_"
850
+ },
851
+ {
852
+ type: "bearer_token",
853
+ // Anchored with alternation instead of negative lookahead — avoids V8
854
+ // backtracking risk on adversarial input. Bounded at 512 chars.
855
+ // Min 12 chars: some OAuth providers issue shorter-lived tokens (< 20
856
+ // chars). A 12-char base64 string has ~71 bits of entropy — above the
857
+ // threshold where random strings are unlikely to produce false matches.
858
+ // The trailing boundary is a NON-consuming lookahead: two adjacent bearer
859
+ // tokens sharing a single delimiter (`Bearer a… Bearer b…`) must both be
860
+ // redacted. A consuming trailing delimiter would eat the separator the
861
+ // next match needs for its leading anchor, leaking the second token.
862
+ regex: /(?:^|[^A-Za-z0-9_.~+/-])Bearer\s+[A-Za-z0-9._~+/-]{12,512}=*(?=$|[^A-Za-z0-9_.~+/-])/g,
863
+ anchor: "Bearer"
864
+ },
865
+ {
866
+ type: "high_entropy_env",
867
+ // Anchored with alternation instead of lookbehind to avoid backtracking.
868
+ // Value bounded at 512 chars.
869
+ // The trailing boundary is a NON-consuming lookahead so two secrets
870
+ // separated by a single delimiter (one space OR one newline, e.g.
871
+ // `printenv` / `.env` dumps: `API_KEY=… \n SESSION_TOKEN=…`) are BOTH
872
+ // redacted. A consuming trailing `\s` would swallow the separator the
873
+ // next match needs for its leading anchor, so every other secret would
874
+ // leak in plaintext.
875
+ // The leading delimiter is CAPTURED (group 1) and re-emitted by the
876
+ // replacement so the separator between adjacent secrets is preserved
877
+ // rather than collapsed. Capture groups are therefore: 1=leading
878
+ // delimiter, 2=key name, 3=value.
879
+ regex: /(^|\s)([A-Z_]{4,}(?:KEY|TOKEN|SECRET|PASSWORD|PWD))\s*[:=]\s*['"]?([A-Za-z0-9_/+=-]{20,512})['"]?(?=\s|$)/g,
880
+ anchor: ["KEY", "TOKEN", "SECRET", "PASSWORD", "PWD"]
881
+ },
882
+ // ── Ported from packages/plugins credential-patterns.ts (WS-034) ─────────
883
+ // The plugin runtime carried 37 patterns while this scrubber — the one that
884
+ // guards session JSONL, chronicle, HQ broadcast, WebUI events and the auth
885
+ // audit — carried 22. The plugin side already had a parity test; it just did
886
+ // not cover core. Most consequential: WrongStack mints `gho_` tokens itself
887
+ // in the Copilot OAuth flow, and `gh[ousr]_` was absent here.
888
+ {
889
+ type: "github_oauth_token",
890
+ regex: /(?<![A-Za-z0-9])gh[ousr]_[A-Za-z0-9]{36,}(?![A-Za-z0-9])/g,
891
+ anchor: ["gho_", "ghu_", "ghs_", "ghr_"]
892
+ },
893
+ {
894
+ type: "gitlab_pat",
895
+ regex: /(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
896
+ anchor: "glpat-"
897
+ },
898
+ {
899
+ type: "gitlab_runner_token",
900
+ regex: /(?<![A-Za-z0-9])glrt-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
901
+ anchor: "glrt-"
902
+ },
903
+ {
904
+ type: "npm_token",
905
+ regex: /(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g,
906
+ anchor: "npm_"
907
+ },
908
+ {
909
+ type: "slack_app_token",
910
+ regex: /(?<![A-Za-z0-9-])xapp-\d-[A-Za-z0-9-]{10,}(?![A-Za-z0-9-])/g,
911
+ anchor: "xapp-"
912
+ },
913
+ {
914
+ type: "slack_webhook",
915
+ regex: /https:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9_-]+\/B[A-Za-z0-9_-]+\/[A-Za-z0-9]{16,}/g,
916
+ anchor: "hooks.slack.com"
917
+ },
918
+ {
919
+ type: "sendgrid_key",
920
+ regex: /(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
921
+ anchor: "SG."
922
+ },
923
+ {
924
+ type: "digitalocean_token",
925
+ regex: /(?<![A-Za-z0-9])dop_v1_[a-f0-9]{64}(?![A-Za-z0-9])/g,
926
+ anchor: "dop_v1_"
927
+ },
928
+ {
929
+ type: "doppler_token",
930
+ regex: /(?<![A-Za-z0-9])dp\.(?:pt|st|sa|scim|audit)\.[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
931
+ anchor: "dp."
932
+ },
933
+ {
934
+ type: "shopify_token",
935
+ regex: /(?<![A-Za-z0-9])shp(?:at|ca|pa|ss)_[a-fA-F0-9]{32}(?![A-Za-z0-9])/g,
936
+ anchor: "shp"
937
+ },
938
+ {
939
+ type: "docker_pat",
940
+ regex: /(?<![A-Za-z0-9])dckr_pat_[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
941
+ anchor: "dckr_pat_"
942
+ },
943
+ {
944
+ type: "linear_key",
945
+ regex: /(?<![A-Za-z0-9])lin_api_[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
946
+ anchor: "lin_api_"
947
+ },
948
+ {
949
+ type: "atlassian_token",
950
+ regex: /(?<![A-Za-z0-9])ATATT3[A-Za-z0-9_\-=]{40,}(?![A-Za-z0-9_\-=])/g,
951
+ anchor: "ATATT3"
952
+ },
953
+ {
954
+ type: "square_token",
955
+ regex: /(?<![A-Za-z0-9])(?:sq0(?:atp|csp)-|EAAA)[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
956
+ anchor: ["sq0atp-", "sq0csp-", "EAAA"]
957
+ },
958
+ {
959
+ type: "google_oauth_client_secret",
960
+ regex: /(?<![A-Za-z0-9_-])GOCSPX-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
961
+ anchor: "GOCSPX-"
962
+ }
963
+ ];
964
+ var SIMPLE_PATTERNS = PATTERNS.filter((p) => p.type !== "high_entropy_env");
965
+ var COMBINED_REGEX = new RegExp(SIMPLE_PATTERNS.map((p) => `(${p.regex.source})`).join("|"), "g");
966
+ var HIGH_ENTROPY_REGEX = PATTERNS.find((p) => p.type === "high_entropy_env").regex;
967
+ var COMBINED_REPLACEMENTS = SIMPLE_PATTERNS.map((p) => `[REDACTED:${p.type}]`);
968
+ var SCRUB_CHUNK_BYTES = 64 * 1024;
969
+ var SCRUB_OVERLAP_BYTES = 1024;
970
+ var PATTERN_ANCHORS = [
971
+ ...new Set(
972
+ PATTERNS.flatMap(
973
+ (pattern) => typeof pattern.anchor === "string" ? [pattern.anchor] : [...pattern.anchor]
974
+ )
975
+ )
976
+ ];
977
+ var JSON_KEY_ANCHORS = [
978
+ '"apiKey"',
979
+ '"api_key"',
980
+ '"token"',
981
+ '"secret"',
982
+ '"password"',
983
+ '"authorization"',
984
+ '"bearer"',
985
+ '"private_key"',
986
+ '"access_token"',
987
+ '"refresh_token"',
988
+ '"client_secret"'
989
+ ];
990
+ var ALL_ANCHORS = [...PATTERN_ANCHORS, ...JSON_KEY_ANCHORS];
991
+ function hasCredentialAnchors(text) {
992
+ for (const anchor of ALL_ANCHORS) {
993
+ if (text.includes(anchor)) return true;
994
+ }
995
+ return false;
996
+ }
997
+ var DefaultSecretScrubber = class {
998
+ scrub(text) {
999
+ if (!text) return text;
1000
+ if (!hasCredentialAnchors(text)) return text;
1001
+ if (text.length <= SCRUB_CHUNK_BYTES) {
1002
+ return this.scrubOne(text);
1003
+ }
1004
+ const out = [];
1005
+ let i = 0;
1006
+ while (i < text.length) {
1007
+ let end = Math.min(i + SCRUB_CHUNK_BYTES, text.length);
1008
+ if (end < text.length) {
1009
+ const limit = Math.min(end + SCRUB_OVERLAP_BYTES, text.length);
1010
+ let safe = -1;
1011
+ for (let j = end; j < limit; j++) {
1012
+ const ch = text.charCodeAt(j);
1013
+ if (ch === 32 || ch === 9 || ch === 10 || ch === 13) {
1014
+ safe = j;
1015
+ break;
1016
+ }
1017
+ }
1018
+ end = safe === -1 ? end : safe + 1;
1019
+ }
1020
+ out.push(this.scrubOne(text.slice(i, end)));
1021
+ i = end;
1022
+ }
1023
+ return out.join("");
1024
+ }
1025
+ scrubOne(text) {
1026
+ if (!hasCredentialAnchors(text)) return text;
1027
+ let out = text.replace(
1028
+ COMBINED_REGEX,
1029
+ (match, ...groups) => {
1030
+ const idx = groups.findIndex((g) => g !== void 0);
1031
+ if (idx < 0) return match;
1032
+ const replacement = COMBINED_REPLACEMENTS[idx];
1033
+ return replacement !== void 0 ? replacement : match;
1034
+ }
1035
+ );
1036
+ out = out.replace(HIGH_ENTROPY_REGEX, (_match, lead, key, _value) => {
1037
+ return `${lead}${key}=[REDACTED:high_entropy_env]`;
1038
+ });
1039
+ return out;
1040
+ }
1041
+ /**
1042
+ * Recursively scrub every string value in an object/array graph. Secrets can
1043
+ * appear under any key — a URL query param, an `authorization` header, an
1044
+ * arbitrarily-named nested field — so we don't gate recursion on key names.
1045
+ * The per-string `scrub()` fast-path (anchor pre-scan) keeps this cheap: any
1046
+ * value without a credential anchor returns immediately without regex work.
1047
+ */
1048
+ scrubObject(obj) {
1049
+ const seen = /* @__PURE__ */ new WeakSet();
1050
+ const visit = (v) => {
1051
+ if (typeof v === "string") return this.scrub(v);
1052
+ if (v === null || typeof v !== "object") return v;
1053
+ if (seen.has(v)) return v;
1054
+ seen.add(v);
1055
+ if (Array.isArray(v)) return v.map(visit);
1056
+ const out = {};
1057
+ for (const [k, val] of Object.entries(v)) {
1058
+ out[k] = visit(val);
1059
+ }
1060
+ return out;
1061
+ };
1062
+ return visit(obj);
1063
+ }
1064
+ };
1065
+
1066
+ // src/utils/atomic-write.ts
1067
+ import {
1068
+ createPersistencePrimitives
1069
+ } from "@wrongstack/persistence";
1070
+
1071
+ // src/types/errors.ts
1072
+ var ERROR_CODES = {
1073
+ // Provider
1074
+ PROVIDER_RATE_LIMITED: "PROVIDER_RATE_LIMITED",
1075
+ PROVIDER_AUTH_FAILED: "PROVIDER_AUTH_FAILED",
1076
+ PROVIDER_OVERLOADED: "PROVIDER_OVERLOADED",
1077
+ PROVIDER_INVALID_REQUEST: "PROVIDER_INVALID_REQUEST",
1078
+ PROVIDER_SERVER_ERROR: "PROVIDER_SERVER_ERROR",
1079
+ PROVIDER_NETWORK_ERROR: "PROVIDER_NETWORK_ERROR",
1080
+ PROVIDER_CONTEXT_OVERFLOW: "PROVIDER_CONTEXT_OVERFLOW",
1081
+ // Tool
1082
+ TOOL_NOT_FOUND: "TOOL_NOT_FOUND",
1083
+ TOOL_PERMISSION_DENIED: "TOOL_PERMISSION_DENIED",
1084
+ TOOL_EXECUTION_FAILED: "TOOL_EXECUTION_FAILED",
1085
+ TOOL_TIMEOUT: "TOOL_TIMEOUT",
1086
+ TOOL_INPUT_INVALID: "TOOL_INPUT_INVALID",
1087
+ // Config
1088
+ CONFIG_INVALID: "CONFIG_INVALID",
1089
+ CONFIG_NOT_FOUND: "CONFIG_NOT_FOUND",
1090
+ CONFIG_PARSE_FAILED: "CONFIG_PARSE_FAILED",
1091
+ CONFIG_MIGRATION_NEEDED: "CONFIG_MIGRATION_NEEDED",
1092
+ // Plugin
1093
+ PLUGIN_LOAD_FAILED: "PLUGIN_LOAD_FAILED",
1094
+ PLUGIN_API_MISMATCH: "PLUGIN_API_MISMATCH",
1095
+ PLUGIN_MISSING_DEPENDENCY: "PLUGIN_MISSING_DEPENDENCY",
1096
+ // Agent
1097
+ AGENT_ITERATION_LIMIT: "AGENT_ITERATION_LIMIT",
1098
+ AGENT_CONTEXT_OVERFLOW: "AGENT_CONTEXT_OVERFLOW",
1099
+ AGENT_ABORTED: "AGENT_ABORTED",
1100
+ AGENT_RUN_FAILED: "AGENT_RUN_FAILED",
1101
+ // Session
1102
+ SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
1103
+ SESSION_CORRUPTED: "SESSION_CORRUPTED",
1104
+ SESSION_WRITE_FAILED: "SESSION_WRITE_FAILED",
1105
+ // Container / Registry
1106
+ CONTAINER_TOKEN_ALREADY_BOUND: "CONTAINER_TOKEN_ALREADY_BOUND",
1107
+ CONTAINER_TOKEN_NOT_BOUND: "CONTAINER_TOKEN_NOT_BOUND",
1108
+ CONTAINER_CIRCULAR_DEPENDENCY: "CONTAINER_CIRCULAR_DEPENDENCY",
1109
+ REGISTRY_DUPLICATE: "REGISTRY_DUPLICATE",
1110
+ REGISTRY_NOT_FOUND: "REGISTRY_NOT_FOUND",
1111
+ REGISTRY_INVALID: "REGISTRY_INVALID",
1112
+ // File system
1113
+ FS_READ_FAILED: "FS_READ_FAILED",
1114
+ FS_WRITE_FAILED: "FS_WRITE_FAILED",
1115
+ FS_MKDIR_FAILED: "FS_MKDIR_FAILED",
1116
+ FS_DELETE_FAILED: "FS_DELETE_FAILED",
1117
+ FS_ATOMIC_WRITE_FAILED: "FS_ATOMIC_WRITE_FAILED",
1118
+ // SDD (Spec-Driven Development)
1119
+ SDD_VALIDATION_FAILED: "SDD_VALIDATION_FAILED",
1120
+ SDD_PARSE_FAILED: "SDD_PARSE_FAILED",
1121
+ SDD_INVALID_STATE: "SDD_INVALID_STATE",
1122
+ SDD_NOT_READY: "SDD_NOT_READY",
1123
+ // General
1124
+ VALIDATION_ERROR: "VALIDATION_ERROR",
1125
+ PARSE_FAILED: "PARSE_FAILED",
1126
+ UNKNOWN: "UNKNOWN"
1127
+ };
1128
+ var WrongStackError = class extends Error {
1129
+ code;
1130
+ subsystem;
1131
+ severity;
1132
+ recoverable;
1133
+ context;
1134
+ constructor(opts) {
1135
+ super(opts.message, { cause: opts.cause });
1136
+ this.name = "WrongStackError";
1137
+ this.code = opts.code;
1138
+ this.subsystem = opts.subsystem;
1139
+ this.severity = opts.severity ?? "error";
1140
+ this.recoverable = opts.recoverable ?? false;
1141
+ this.context = opts.context;
1142
+ }
1143
+ /**
1144
+ * Render a one-line user-facing description.
1145
+ * Subclasses should override for domain-specific formatting.
1146
+ */
1147
+ describe() {
1148
+ const ctx = this.context ? ` ${formatContext(this.context)}` : "";
1149
+ return `${this.code}: ${this.message}${ctx}`;
1150
+ }
1151
+ };
1152
+ function formatContext(ctx) {
1153
+ const parts = Object.entries(ctx).filter(([, v]) => v !== void 0).slice(0, 3).map(([k, v]) => `${k}=${String(v)}`);
1154
+ return parts.length > 0 ? `[${parts.join(" ")}]` : "";
1155
+ }
1156
+ var FsError = class extends WrongStackError {
1157
+ path;
1158
+ constructor(opts) {
1159
+ super({
1160
+ message: opts.message,
1161
+ code: opts.code,
1162
+ subsystem: "fs",
1163
+ severity: "error",
1164
+ recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,
1165
+ context: { path: opts.path, ...opts.context },
1166
+ cause: opts.cause
1167
+ });
1168
+ this.name = "FsError";
1169
+ this.path = opts.path;
1170
+ }
1171
+ };
1172
+
1173
+ // src/utils/atomic-write.ts
1174
+ var primitives = createPersistencePrimitives({
1175
+ createLockTimeoutError: ({ targetPath, timeoutMs }) => new FsError({
1176
+ message: `Timed out waiting for file lock: ${targetPath}`,
1177
+ code: "FS_ATOMIC_WRITE_FAILED",
1178
+ path: targetPath,
1179
+ context: { timeoutMs }
1180
+ })
1181
+ });
1182
+ var atomicWrite = primitives.atomicWrite;
1183
+ var atomicReplaceWithWriter = primitives.atomicReplaceWithWriter;
1184
+ var ensureDir = primitives.ensureDir;
1185
+ var withFileLock = primitives.withFileLock;
1186
+
1187
+ // src/utils/pid.ts
1188
+ function isPidAlive(pid) {
1189
+ if (!Number.isInteger(pid) || pid <= 0) return false;
1190
+ if (pid === process.pid) return true;
1191
+ try {
1192
+ process.kill(pid, 0);
1193
+ return true;
1194
+ } catch (err) {
1195
+ const code = err.code;
1196
+ if (code === "EPERM") return true;
1197
+ return false;
1198
+ }
1199
+ }
1200
+
1201
+ // src/session-catalog/store.ts
1202
+ var SCHEMA_VERSION = 1;
1203
+ var MAX_LEASE_MS = 12e4;
1204
+ var MAX_RESERVATION_MS = 6e4;
1205
+ var MAX_MAINTENANCE_MS = 5 * 6e4;
1206
+ var MAX_PAGE = 1e3;
1207
+ function hashSecret(secret) {
1208
+ return createHash2("sha256").update(secret).digest("hex");
1209
+ }
1210
+ function secretMatches(secret, expectedHex) {
1211
+ const actual = Buffer.from(hashSecret(secret), "hex");
1212
+ const expected = Buffer.from(expectedHex, "hex");
1213
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
1214
+ }
1215
+ function boundedMs(value, fallback, max) {
1216
+ return Math.min(max, Math.max(1e3, Number.isFinite(value) ? Math.floor(value) : fallback));
1217
+ }
1218
+ function parseJson(value) {
1219
+ return JSON.parse(value);
1220
+ }
1221
+ function conflict(message) {
1222
+ const error = new Error(message);
1223
+ error.name = "SessionOwnershipConflictError";
1224
+ return error;
1225
+ }
1226
+ function assertId(value, label = "session id") {
1227
+ if (!value || value.length > 256 || value.includes("\\") || value.startsWith("/") || value.includes("..")) {
1228
+ throw new TypeError(`Invalid ${label}`);
1229
+ }
1230
+ }
1231
+ function boundPresenceValue(value, depth) {
1232
+ if (typeof value === "string") {
1233
+ return value.length <= 6e3 ? value : `${value.slice(0, 5988)}\u2026[truncated]`;
1234
+ }
1235
+ if (value === null || typeof value !== "object") return value;
1236
+ if (depth >= 8) return "[truncated depth]";
1237
+ if (Array.isArray(value)) {
1238
+ return value.slice(0, 64).map((item) => boundPresenceValue(item, depth + 1));
1239
+ }
1240
+ const result = {};
1241
+ for (const [key, item] of Object.entries(value).slice(0, 64)) {
1242
+ result[key] = boundPresenceValue(item, depth + 1);
1243
+ }
1244
+ return result;
1245
+ }
1246
+ var SessionCatalogStore = class {
1247
+ constructor(projectDir) {
1248
+ this.projectDir = projectDir;
1249
+ this.sessionsDir = path4.join(projectDir, "sessions");
1250
+ fs4.mkdirSync(this.sessionsDir, { recursive: true, mode: 448 });
1251
+ this.databasePath = path4.join(this.sessionsDir, "catalog.sqlite");
1252
+ const Database = loadDatabaseSync();
1253
+ this.db = new Database(this.databasePath);
1254
+ try {
1255
+ this.configureDatabase();
1256
+ this.initialize();
1257
+ } catch (error) {
1258
+ const message = error instanceof Error ? error.message : String(error);
1259
+ if (!/SQLITE_CORRUPT|SQLITE_NOTADB|database disk image is malformed|file is not a database/i.test(
1260
+ message
1261
+ )) {
1262
+ this.db.close();
1263
+ throw error;
1264
+ }
1265
+ this.db.close();
1266
+ const quarantine = `${this.databasePath}.corrupt-${Date.now()}`;
1267
+ try {
1268
+ fs4.renameSync(this.databasePath, quarantine);
1269
+ } catch {
1270
+ }
1271
+ for (const suffix of ["-wal", "-shm"]) {
1272
+ try {
1273
+ fs4.renameSync(`${this.databasePath}${suffix}`, `${quarantine}${suffix}`);
1274
+ } catch {
1275
+ }
1276
+ }
1277
+ this.db = new Database(this.databasePath);
1278
+ this.configureDatabase();
1279
+ this.initialize();
1280
+ }
1281
+ this.reapExpired();
1282
+ const rowCount = Number(
1283
+ this.db.prepare("SELECT COUNT(*) AS count FROM sessions").get().count
1284
+ );
1285
+ if (rowCount === 0 && this.walkFiles(this.sessionsDir, ".jsonl").some((file) => !file.endsWith("_index.jsonl"))) {
1286
+ this.rebuildCatalog();
1287
+ }
1288
+ }
1289
+ projectDir;
1290
+ databasePath;
1291
+ sessionsDir;
1292
+ db;
1293
+ scrubber = new DefaultSecretScrubber();
1294
+ configureDatabase() {
1295
+ this.db.exec(
1296
+ "PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000; PRAGMA synchronous=NORMAL;"
1297
+ );
1298
+ }
1299
+ close() {
1300
+ this.db.close();
1301
+ }
1302
+ initialize() {
1303
+ this.db.exec(`
1304
+ CREATE TABLE IF NOT EXISTS catalog_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
1305
+ CREATE TABLE IF NOT EXISTS sessions (
1306
+ session_id TEXT PRIMARY KEY,
1307
+ transcript_relative_path TEXT NOT NULL,
1308
+ summary_relative_path TEXT NOT NULL,
1309
+ summary_json TEXT NOT NULL,
1310
+ transcript_size INTEGER NOT NULL DEFAULT 0,
1311
+ transcript_mtime_ms REAL NOT NULL DEFAULT 0,
1312
+ summary_revision INTEGER NOT NULL DEFAULT 1,
1313
+ indexed_at TEXT NOT NULL,
1314
+ damaged INTEGER NOT NULL DEFAULT 0
1315
+ );
1316
+ CREATE TABLE IF NOT EXISTS session_leases (
1317
+ session_id TEXT PRIMARY KEY,
1318
+ lease_id TEXT NOT NULL UNIQUE,
1319
+ lease_secret_hash TEXT NOT NULL,
1320
+ owner_instance_id TEXT NOT NULL,
1321
+ owner_pid INTEGER NOT NULL,
1322
+ owner_started_at TEXT NOT NULL,
1323
+ entry_json TEXT NOT NULL,
1324
+ agent_revision INTEGER NOT NULL DEFAULT 0,
1325
+ status TEXT NOT NULL,
1326
+ last_heartbeat_at INTEGER NOT NULL,
1327
+ lease_expires_at INTEGER NOT NULL
1328
+ );
1329
+ CREATE TABLE IF NOT EXISTS resume_reservations (
1330
+ reservation_id TEXT PRIMARY KEY,
1331
+ target_session_id TEXT NOT NULL UNIQUE,
1332
+ requester_instance_id TEXT NOT NULL,
1333
+ current_session_id TEXT,
1334
+ created_at INTEGER NOT NULL,
1335
+ expires_at INTEGER NOT NULL
1336
+ );
1337
+ CREATE TABLE IF NOT EXISTS maintenance_leases (
1338
+ session_id TEXT PRIMARY KEY,
1339
+ operation TEXT NOT NULL,
1340
+ holder_id TEXT NOT NULL,
1341
+ lease_id TEXT NOT NULL UNIQUE,
1342
+ acquired_at INTEGER NOT NULL,
1343
+ expires_at INTEGER NOT NULL
1344
+ );
1345
+ CREATE INDEX IF NOT EXISTS idx_sessions_activity ON sessions(indexed_at DESC);
1346
+ CREATE INDEX IF NOT EXISTS idx_leases_expiry ON session_leases(lease_expires_at);
1347
+ CREATE INDEX IF NOT EXISTS idx_reservations_expiry ON resume_reservations(expires_at);
1348
+ CREATE INDEX IF NOT EXISTS idx_maintenance_expiry ON maintenance_leases(expires_at);
1349
+ `);
1350
+ this.db.prepare("INSERT INTO catalog_meta(key,value) VALUES (?,?) ON CONFLICT(key) DO NOTHING").run("schema_version", String(SCHEMA_VERSION));
1351
+ this.db.prepare("INSERT INTO catalog_meta(key,value) VALUES (?,?) ON CONFLICT(key) DO NOTHING").run("generation", "0");
1352
+ const row = this.db.prepare("SELECT value FROM catalog_meta WHERE key=?").get("schema_version");
1353
+ if (Number(row.value) !== SCHEMA_VERSION)
1354
+ throw new Error(`Unsupported session catalog schema ${row.value}`);
1355
+ }
1356
+ transaction(run) {
1357
+ this.db.exec("BEGIN IMMEDIATE");
1358
+ try {
1359
+ const result = run();
1360
+ this.db.exec("COMMIT");
1361
+ return result;
1362
+ } catch (error) {
1363
+ this.db.exec("ROLLBACK");
1364
+ throw error;
1365
+ }
1366
+ }
1367
+ bumpGeneration() {
1368
+ this.db.prepare("UPDATE catalog_meta SET value=CAST(value AS INTEGER)+1 WHERE key='generation'").run();
1369
+ return this.generation();
1370
+ }
1371
+ generation() {
1372
+ const row = this.db.prepare("SELECT value FROM catalog_meta WHERE key='generation'").get();
1373
+ return Number(row.value) || 0;
1374
+ }
1375
+ reapExpired(now = Date.now()) {
1376
+ this.db.prepare("DELETE FROM resume_reservations WHERE expires_at<=?").run(now);
1377
+ this.db.prepare("DELETE FROM maintenance_leases WHERE expires_at<=?").run(now);
1378
+ const rows = this.db.prepare("SELECT * FROM session_leases WHERE lease_expires_at<=?").all(now);
1379
+ for (const row of rows) {
1380
+ if (!isPidAlive(row.owner_pid)) {
1381
+ this.db.prepare("DELETE FROM session_leases WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
1382
+ } else if (row.status !== "lost") {
1383
+ this.db.prepare("UPDATE session_leases SET status='lost' WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
1384
+ }
1385
+ }
1386
+ }
1387
+ maintenanceExists(sessionId) {
1388
+ return Boolean(
1389
+ this.db.prepare("SELECT 1 AS yes FROM maintenance_leases WHERE session_id=? AND expires_at>?").get(sessionId, Date.now())
1390
+ );
1391
+ }
1392
+ leaseRow(sessionId) {
1393
+ return this.db.prepare("SELECT * FROM session_leases WHERE session_id=?").get(sessionId);
1394
+ }
1395
+ verifyCredential(credential) {
1396
+ assertId(credential.sessionId);
1397
+ const row = this.leaseRow(credential.sessionId);
1398
+ if (!row || row.lease_id !== credential.leaseId || row.owner_instance_id !== credential.ownerInstanceId || !secretMatches(credential.leaseSecret, row.lease_secret_hash)) {
1399
+ throw conflict(`Session ${credential.sessionId} lease proof is invalid or no longer owned`);
1400
+ }
1401
+ return row;
1402
+ }
1403
+ createLease(entry, ownerInstanceId, leaseMs) {
1404
+ assertId(entry.sessionId);
1405
+ if (!ownerInstanceId || ownerInstanceId.length > 256)
1406
+ throw new TypeError("Invalid owner instance id");
1407
+ if (!Number.isSafeInteger(entry.pid) || entry.pid <= 0)
1408
+ throw new TypeError("Invalid owner pid");
1409
+ const now = Date.now();
1410
+ const leaseId = randomUUID2();
1411
+ const leaseSecret = randomBytes(32).toString("hex");
1412
+ const expiresAt = now + boundedMs(leaseMs, SESSION_CATALOG_DEFAULT_LEASE_MS, MAX_LEASE_MS);
1413
+ this.db.prepare(`INSERT INTO session_leases(
1414
+ session_id,lease_id,lease_secret_hash,owner_instance_id,owner_pid,owner_started_at,
1415
+ entry_json,agent_revision,status,last_heartbeat_at,lease_expires_at
1416
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?)`).run(
1417
+ entry.sessionId,
1418
+ leaseId,
1419
+ hashSecret(leaseSecret),
1420
+ ownerInstanceId,
1421
+ entry.pid,
1422
+ entry.startedAt,
1423
+ JSON.stringify(entry),
1424
+ 0,
1425
+ entry.status,
1426
+ now,
1427
+ expiresAt
1428
+ );
1429
+ return { sessionId: entry.sessionId, leaseId, leaseSecret, ownerInstanceId, expiresAt };
1430
+ }
1431
+ claimNew(entry, ownerInstanceId, leaseMs) {
1432
+ return this.transaction(() => {
1433
+ this.reapExpired();
1434
+ const existing = this.leaseRow(entry.sessionId);
1435
+ if (existing)
1436
+ throw conflict(
1437
+ `Session ${entry.sessionId} is already open in another running wstack (pid ${existing.owner_pid}).`
1438
+ );
1439
+ if (this.maintenanceExists(entry.sessionId))
1440
+ throw conflict(`Session ${entry.sessionId} is under maintenance`);
1441
+ const reserved = this.db.prepare(
1442
+ "SELECT 1 AS yes FROM resume_reservations WHERE target_session_id=? AND expires_at>?"
1443
+ ).get(entry.sessionId, Date.now());
1444
+ if (reserved) throw conflict(`Session ${entry.sessionId} is reserved for resume`);
1445
+ const credential = this.createLease(entry, ownerInstanceId, leaseMs);
1446
+ this.bumpGeneration();
1447
+ return credential;
1448
+ });
1449
+ }
1450
+ reconnectLease(credential) {
1451
+ return this.transaction(() => {
1452
+ const row = this.verifyCredential(credential);
1453
+ if (row.owner_pid !== process.pid && !isPidAlive(row.owner_pid))
1454
+ throw conflict(`Session ${credential.sessionId} owner process is no longer alive`);
1455
+ const expiresAt = Date.now() + SESSION_CATALOG_DEFAULT_LEASE_MS;
1456
+ this.db.prepare(
1457
+ "UPDATE session_leases SET lease_expires_at=?,last_heartbeat_at=?,status=? WHERE session_id=? AND lease_id=?"
1458
+ ).run(
1459
+ expiresAt,
1460
+ Date.now(),
1461
+ row.status === "lost" ? "idle" : row.status,
1462
+ row.session_id,
1463
+ row.lease_id
1464
+ );
1465
+ return { ...credential, expiresAt };
1466
+ });
1467
+ }
1468
+ reserveResume(targetSessionId, requesterInstanceId, currentSessionId, reservationMs) {
1469
+ assertId(targetSessionId);
1470
+ return this.transaction(() => {
1471
+ this.reapExpired();
1472
+ const live = this.leaseRow(targetSessionId);
1473
+ if (live)
1474
+ throw conflict(
1475
+ `Session ${targetSessionId} is already open in another running wstack (pid ${live.owner_pid}).`
1476
+ );
1477
+ if (this.maintenanceExists(targetSessionId))
1478
+ throw conflict(`Session ${targetSessionId} is under maintenance`);
1479
+ const catalog = this.db.prepare("SELECT 1 AS yes FROM sessions WHERE session_id=?").get(targetSessionId);
1480
+ if (!catalog && !fs4.existsSync(this.containedPath(`${targetSessionId}.jsonl`)))
1481
+ throw new Error(`Session not found: ${targetSessionId}`);
1482
+ const reservationId = randomUUID2();
1483
+ const now = Date.now();
1484
+ const expiresAt = now + boundedMs(reservationMs, SESSION_CATALOG_DEFAULT_RESERVATION_MS, MAX_RESERVATION_MS);
1485
+ try {
1486
+ this.db.prepare(
1487
+ "INSERT INTO resume_reservations(reservation_id,target_session_id,requester_instance_id,current_session_id,created_at,expires_at) VALUES (?,?,?,?,?,?)"
1488
+ ).run(
1489
+ reservationId,
1490
+ targetSessionId,
1491
+ requesterInstanceId,
1492
+ currentSessionId ?? null,
1493
+ now,
1494
+ expiresAt
1495
+ );
1496
+ } catch {
1497
+ throw conflict(`Session ${targetSessionId} is already reserved for resume`);
1498
+ }
1499
+ this.bumpGeneration();
1500
+ return { reservationId, targetSessionId, requesterInstanceId, expiresAt };
1501
+ });
1502
+ }
1503
+ activateReservation(reservation, entry, leaseMs) {
1504
+ return this.transaction(() => {
1505
+ this.reapExpired();
1506
+ const row = this.db.prepare("SELECT * FROM resume_reservations WHERE reservation_id=?").get(reservation.reservationId);
1507
+ if (!row || row.target_session_id !== reservation.targetSessionId || row.requester_instance_id !== reservation.requesterInstanceId || row.expires_at <= Date.now())
1508
+ throw conflict("Resume reservation expired or is not owned by this requester");
1509
+ if (entry.sessionId !== row.target_session_id)
1510
+ throw new TypeError("Reservation target and session entry differ");
1511
+ if (this.leaseRow(entry.sessionId) || this.maintenanceExists(entry.sessionId))
1512
+ throw conflict(`Session ${entry.sessionId} can no longer be activated`);
1513
+ const credential = this.createLease(entry, reservation.requesterInstanceId, leaseMs);
1514
+ this.db.prepare("DELETE FROM resume_reservations WHERE reservation_id=?").run(row.reservation_id);
1515
+ this.bumpGeneration();
1516
+ return credential;
1517
+ });
1518
+ }
1519
+ cancelReservation(reservationId, requesterInstanceId) {
1520
+ this.db.prepare("DELETE FROM resume_reservations WHERE reservation_id=? AND requester_instance_id=?").run(reservationId, requesterInstanceId);
1521
+ }
1522
+ heartbeat(credential, status) {
1523
+ return this.transaction(() => {
1524
+ const row = this.verifyCredential(credential);
1525
+ const expiresAt = Date.now() + SESSION_CATALOG_DEFAULT_LEASE_MS;
1526
+ const nextStatus = status ?? (row.status === "closing" ? "closing" : row.status === "lost" ? "idle" : row.status);
1527
+ const entry = parseJson(row.entry_json);
1528
+ entry.status = nextStatus;
1529
+ entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
1530
+ this.db.prepare(
1531
+ "UPDATE session_leases SET status=?,entry_json=?,last_heartbeat_at=?,lease_expires_at=? WHERE session_id=? AND lease_id=?"
1532
+ ).run(
1533
+ nextStatus,
1534
+ JSON.stringify(entry),
1535
+ Date.now(),
1536
+ expiresAt,
1537
+ row.session_id,
1538
+ row.lease_id
1539
+ );
1540
+ return { ...credential, expiresAt };
1541
+ });
1542
+ }
1543
+ publishAgents(credential, revision, agents) {
1544
+ if (!Number.isSafeInteger(revision) || revision < 0)
1545
+ throw new TypeError("Invalid presence revision");
1546
+ if (!Array.isArray(agents) || agents.length > SESSION_CATALOG_MAX_AGENTS)
1547
+ throw new TypeError(`Agent snapshot exceeds ${SESSION_CATALOG_MAX_AGENTS} agents`);
1548
+ const boundedAgents = boundPresenceValue(
1549
+ this.scrubber.scrubObject(agents),
1550
+ 0
1551
+ );
1552
+ const encoded = JSON.stringify(boundedAgents);
1553
+ if (encoded.length > 1024 * 1024) throw new TypeError("Agent snapshot exceeds 1 MiB");
1554
+ return this.transaction(() => {
1555
+ const row = this.verifyCredential(credential);
1556
+ if (revision <= row.agent_revision) return { accepted: false, revision: row.agent_revision };
1557
+ const entry = parseJson(row.entry_json);
1558
+ entry.agents = boundedAgents;
1559
+ entry.agentCount = boundedAgents.length;
1560
+ entry.status = boundedAgents.some((agent) => agent.status !== "idle") ? "active" : "idle";
1561
+ entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
1562
+ this.db.prepare(
1563
+ "UPDATE session_leases SET entry_json=?,agent_revision=?,status=?,last_heartbeat_at=? WHERE session_id=? AND lease_id=?"
1564
+ ).run(
1565
+ JSON.stringify(entry),
1566
+ revision,
1567
+ entry.status,
1568
+ Date.now(),
1569
+ row.session_id,
1570
+ row.lease_id
1571
+ );
1572
+ this.bumpGeneration();
1573
+ return { accepted: true, revision };
1574
+ });
1575
+ }
1576
+ markClosing(credential) {
1577
+ const row = this.verifyCredential(credential);
1578
+ const entry = parseJson(row.entry_json);
1579
+ entry.status = "closing";
1580
+ entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
1581
+ this.db.prepare(
1582
+ "UPDATE session_leases SET status='closing',entry_json=?,last_heartbeat_at=? WHERE session_id=? AND lease_id=?"
1583
+ ).run(JSON.stringify(entry), Date.now(), row.session_id, row.lease_id);
1584
+ this.bumpGeneration();
1585
+ }
1586
+ release(credential) {
1587
+ this.transaction(() => {
1588
+ const row = this.verifyCredential(credential);
1589
+ this.db.prepare("DELETE FROM session_leases WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
1590
+ this.bumpGeneration();
1591
+ });
1592
+ }
1593
+ listLive() {
1594
+ this.reapExpired();
1595
+ return this.db.prepare(
1596
+ "SELECT entry_json,status,last_heartbeat_at FROM session_leases ORDER BY last_heartbeat_at DESC"
1597
+ ).all().map((row) => ({
1598
+ ...parseJson(row.entry_json),
1599
+ status: row.status,
1600
+ lastHeartbeatAt: new Date(row.last_heartbeat_at).toISOString()
1601
+ }));
1602
+ }
1603
+ getLive(sessionId) {
1604
+ return this.listLive().find((entry) => entry.sessionId === sessionId) ?? null;
1605
+ }
1606
+ containedPath(relative2) {
1607
+ assertId(relative2.replace(/\.(jsonl|summary\.json)$/, ""), "session path");
1608
+ const root = path4.resolve(this.sessionsDir);
1609
+ const candidate = path4.resolve(root, relative2);
1610
+ const prefix = `${root}${path4.sep}`;
1611
+ if (candidate !== root && !(process.platform === "win32" ? candidate.toLowerCase().startsWith(prefix.toLowerCase()) : candidate.startsWith(prefix)))
1612
+ throw new TypeError("Session path escapes sessions directory");
1613
+ return candidate;
1614
+ }
1615
+ upsertSummary(summary, transcriptRelativePath = `${summary.id}.jsonl`, summaryRelativePath = `${summary.id}.summary.json`) {
1616
+ assertId(summary.id);
1617
+ summary = this.scrubber.scrubObject(summary);
1618
+ const normalizedTranscript = transcriptRelativePath.replaceAll("\\", "/");
1619
+ const normalizedSummary = summaryRelativePath.replaceAll("\\", "/");
1620
+ if (normalizedTranscript !== `${summary.id}.jsonl` || normalizedSummary !== `${summary.id}.summary.json`) {
1621
+ throw new TypeError("Session catalog paths must match the canonical session identity");
1622
+ }
1623
+ transcriptRelativePath = normalizedTranscript;
1624
+ summaryRelativePath = normalizedSummary;
1625
+ const transcript = this.containedPath(transcriptRelativePath);
1626
+ const stat = fs4.existsSync(transcript) ? fs4.statSync(transcript) : void 0;
1627
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1628
+ return this.transaction(() => {
1629
+ const prior = this.db.prepare("SELECT summary_revision FROM sessions WHERE session_id=?").get(summary.id);
1630
+ const revision = (prior?.summary_revision ?? 0) + 1;
1631
+ this.db.prepare(`INSERT INTO sessions(session_id,transcript_relative_path,summary_relative_path,summary_json,transcript_size,transcript_mtime_ms,summary_revision,indexed_at,damaged)
1632
+ VALUES (?,?,?,?,?,?,?,?,0) ON CONFLICT(session_id) DO UPDATE SET transcript_relative_path=excluded.transcript_relative_path,summary_relative_path=excluded.summary_relative_path,summary_json=excluded.summary_json,transcript_size=excluded.transcript_size,transcript_mtime_ms=excluded.transcript_mtime_ms,summary_revision=excluded.summary_revision,indexed_at=excluded.indexed_at,damaged=0`).run(
1633
+ summary.id,
1634
+ transcriptRelativePath,
1635
+ summaryRelativePath,
1636
+ JSON.stringify(summary),
1637
+ stat?.size ?? 0,
1638
+ stat?.mtimeMs ?? 0,
1639
+ revision,
1640
+ now
1641
+ );
1642
+ this.bumpGeneration();
1643
+ return {
1644
+ ...summary,
1645
+ transcriptRelativePath,
1646
+ summaryRelativePath,
1647
+ transcriptSize: stat?.size ?? 0,
1648
+ transcriptMtimeMs: stat?.mtimeMs ?? 0,
1649
+ summaryRevision: revision,
1650
+ indexedAt: now,
1651
+ damaged: false
1652
+ };
1653
+ });
1654
+ }
1655
+ catalogRecord(row) {
1656
+ return {
1657
+ ...parseJson(row.summary_json),
1658
+ transcriptRelativePath: row.transcript_relative_path,
1659
+ summaryRelativePath: row.summary_relative_path,
1660
+ transcriptSize: row.transcript_size,
1661
+ transcriptMtimeMs: row.transcript_mtime_ms,
1662
+ summaryRevision: row.summary_revision,
1663
+ indexedAt: row.indexed_at,
1664
+ damaged: row.damaged !== 0
1665
+ };
1666
+ }
1667
+ listCatalog(limit = 100, search) {
1668
+ const bounded = Math.min(MAX_PAGE, Math.max(1, Math.floor(limit)));
1669
+ const rows = search?.trim() ? this.db.prepare(
1670
+ "SELECT * FROM sessions WHERE session_id LIKE ? OR json_extract(summary_json,'$.title') LIKE ? OR json_extract(summary_json,'$.name') LIKE ? ORDER BY COALESCE(json_extract(summary_json,'$.lastActivityAt'),json_extract(summary_json,'$.startedAt')) DESC LIMIT ?"
1671
+ ).all(`%${search.trim()}%`, `%${search.trim()}%`, `%${search.trim()}%`, bounded) : this.db.prepare(
1672
+ "SELECT * FROM sessions ORDER BY COALESCE(json_extract(summary_json,'$.lastActivityAt'),json_extract(summary_json,'$.startedAt')) DESC LIMIT ?"
1673
+ ).all(bounded);
1674
+ return rows.map((row) => this.catalogRecord(row));
1675
+ }
1676
+ getSummary(sessionId) {
1677
+ const row = this.db.prepare("SELECT * FROM sessions WHERE session_id=?").get(sessionId);
1678
+ return row ? this.catalogRecord(row) : null;
1679
+ }
1680
+ resolveId(query) {
1681
+ const normalized = query.trim();
1682
+ if (!normalized) throw new Error("Session not found: (empty query)");
1683
+ if (this.getSummary(normalized)) return normalized;
1684
+ const rows = this.db.prepare(
1685
+ "SELECT session_id FROM sessions WHERE session_id LIKE ? OR session_id LIKE ? LIMIT 3"
1686
+ ).all(`%/${normalized}`, `${normalized}%`);
1687
+ const ids = [...new Set(rows.map((row) => row.session_id))];
1688
+ if (ids.length === 1) return ids[0];
1689
+ if (ids.length === 0) throw new Error(`Session not found: ${query}`);
1690
+ throw new Error(`Ambiguous session id "${query}": ${ids.join(", ")}`);
1691
+ }
1692
+ async rename(sessionId, name) {
1693
+ const current = this.getSummary(this.resolveId(sessionId));
1694
+ if (!current) throw new Error(`Session not found: ${sessionId}`);
1695
+ const trimmed = name.trim();
1696
+ const summary = { ...current };
1697
+ for (const key of [
1698
+ "transcriptRelativePath",
1699
+ "summaryRelativePath",
1700
+ "transcriptSize",
1701
+ "transcriptMtimeMs",
1702
+ "summaryRevision",
1703
+ "indexedAt",
1704
+ "damaged"
1705
+ ])
1706
+ delete summary[key];
1707
+ const previous = { ...summary };
1708
+ if (trimmed) summary.name = this.scrubber.scrub(trimmed).slice(0, 500);
1709
+ else delete summary.name;
1710
+ const summaryPath = this.containedPath(current.summaryRelativePath);
1711
+ fs4.mkdirSync(path4.dirname(summaryPath), { recursive: true, mode: 448 });
1712
+ await atomicWrite(summaryPath, `${JSON.stringify(summary)}
1713
+ `, { mode: 384 });
1714
+ try {
1715
+ return this.upsertSummary(
1716
+ summary,
1717
+ current.transcriptRelativePath,
1718
+ current.summaryRelativePath
1719
+ );
1720
+ } catch (error) {
1721
+ await atomicWrite(summaryPath, `${JSON.stringify(previous)}
1722
+ `, { mode: 384 }).catch(
1723
+ () => void 0
1724
+ );
1725
+ throw error;
1726
+ }
1727
+ }
1728
+ acquireMaintenance(sessionId, operation, holderId, leaseMs) {
1729
+ assertId(sessionId);
1730
+ return this.transaction(() => {
1731
+ this.reapExpired();
1732
+ if (this.leaseRow(sessionId)) throw conflict(`Session ${sessionId} is live`);
1733
+ const reservation = this.db.prepare(
1734
+ "SELECT 1 AS yes FROM resume_reservations WHERE target_session_id=? AND expires_at>?"
1735
+ ).get(sessionId, Date.now());
1736
+ if (reservation) throw conflict(`Session ${sessionId} is reserved for resume`);
1737
+ const leaseId = randomUUID2();
1738
+ const now = Date.now();
1739
+ const expiresAt = now + boundedMs(leaseMs, 6e4, MAX_MAINTENANCE_MS);
1740
+ try {
1741
+ this.db.prepare(
1742
+ "INSERT INTO maintenance_leases(session_id,operation,holder_id,lease_id,acquired_at,expires_at) VALUES (?,?,?,?,?,?)"
1743
+ ).run(sessionId, operation, holderId, leaseId, now, expiresAt);
1744
+ } catch {
1745
+ throw conflict(`Session ${sessionId} already has maintenance in progress`);
1746
+ }
1747
+ return { sessionId, operation, holderId, leaseId, expiresAt };
1748
+ });
1749
+ }
1750
+ releaseMaintenance(lease) {
1751
+ this.db.prepare("DELETE FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=?").run(lease.sessionId, lease.leaseId, lease.holderId);
1752
+ }
1753
+ delete(sessionId, lease) {
1754
+ const row = this.db.prepare(
1755
+ "SELECT * FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=? AND operation=? AND expires_at>?"
1756
+ ).get(sessionId, lease.leaseId, lease.holderId, lease.operation, Date.now());
1757
+ if (!row || lease.operation !== "delete")
1758
+ throw conflict("A valid delete maintenance lease is required");
1759
+ const record = this.getSummary(sessionId);
1760
+ if (!record) throw new Error(`Session not found: ${sessionId}`);
1761
+ const transcript = this.containedPath(record.transcriptRelativePath);
1762
+ const artifacts = [
1763
+ transcript,
1764
+ this.containedPath(record.summaryRelativePath),
1765
+ this.containedPath(`${sessionId}.plan.json`),
1766
+ this.containedPath(`${sessionId}.tasks.json`),
1767
+ this.containedPath(`${sessionId}.todos.json`),
1768
+ path4.join(path4.dirname(transcript), path4.basename(sessionId))
1769
+ ];
1770
+ const trashRoot = path4.join(this.sessionsDir, "_trash", lease.leaseId);
1771
+ fs4.mkdirSync(trashRoot, { recursive: true, mode: 448 });
1772
+ const moved = [];
1773
+ try {
1774
+ artifacts.forEach((artifact, index) => {
1775
+ if (!fs4.existsSync(artifact)) return;
1776
+ const target = path4.join(trashRoot, `${index}-${path4.basename(artifact)}`);
1777
+ fs4.renameSync(artifact, target);
1778
+ moved.push({ from: artifact, to: target });
1779
+ });
1780
+ this.transaction(() => {
1781
+ const current = this.db.prepare(
1782
+ "SELECT 1 AS yes FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=? AND operation=? AND expires_at>?"
1783
+ ).get(sessionId, lease.leaseId, lease.holderId, "delete", Date.now());
1784
+ if (!current) throw conflict("Delete maintenance lease expired while staging artifacts");
1785
+ this.db.prepare("DELETE FROM sessions WHERE session_id=?").run(sessionId);
1786
+ this.db.prepare("DELETE FROM maintenance_leases WHERE session_id=?").run(sessionId);
1787
+ this.bumpGeneration();
1788
+ });
1789
+ } catch (error) {
1790
+ for (const item of moved.reverse()) {
1791
+ try {
1792
+ fs4.mkdirSync(path4.dirname(item.from), { recursive: true, mode: 448 });
1793
+ fs4.renameSync(item.to, item.from);
1794
+ } catch {
1795
+ }
1796
+ }
1797
+ throw error;
1798
+ }
1799
+ try {
1800
+ fs4.rmSync(trashRoot, { recursive: true, force: true });
1801
+ const trashParent = path4.dirname(trashRoot);
1802
+ if (fs4.readdirSync(trashParent).length === 0) fs4.rmdirSync(trashParent);
1803
+ } catch {
1804
+ }
1805
+ }
1806
+ prune(maxAgeDays, holderId) {
1807
+ if (!Number.isFinite(maxAgeDays) || maxAgeDays < 0) throw new TypeError("Invalid prune age");
1808
+ const cutoff = Date.now() - maxAgeDays * 864e5;
1809
+ const candidates = this.db.prepare("SELECT session_id FROM sessions WHERE transcript_mtime_ms<?").all(cutoff);
1810
+ let deleted = 0;
1811
+ for (const { session_id: id } of candidates) {
1812
+ try {
1813
+ const lease = this.acquireMaintenance(id, "delete", holderId);
1814
+ this.delete(id, lease);
1815
+ deleted++;
1816
+ } catch (error) {
1817
+ if (error.name !== "SessionOwnershipConflictError") throw error;
1818
+ }
1819
+ }
1820
+ return deleted;
1821
+ }
1822
+ rebuildCatalog() {
1823
+ const summaries = this.walkFiles(this.sessionsDir, ".summary.json");
1824
+ const transcripts = this.walkFiles(this.sessionsDir, ".jsonl").filter(
1825
+ (file) => !file.endsWith("_index.jsonl")
1826
+ );
1827
+ const ids = /* @__PURE__ */ new Set();
1828
+ for (const file of [...summaries, ...transcripts]) {
1829
+ const relative2 = path4.relative(this.sessionsDir, file).replaceAll("\\", "/");
1830
+ ids.add(relative2.replace(/\.summary\.json$|\.jsonl$/, ""));
1831
+ }
1832
+ let indexed = 0;
1833
+ let damaged = 0;
1834
+ this.transaction(() => {
1835
+ this.db.prepare("DELETE FROM sessions").run();
1836
+ for (const id of ids) {
1837
+ try {
1838
+ const summaryFile = this.containedPath(`${id}.summary.json`);
1839
+ const summary = fs4.existsSync(summaryFile) ? parseJson(fs4.readFileSync(summaryFile, "utf8")) : this.summarizeTranscript(id);
1840
+ if (!summary || summary.id !== id) throw new Error("summary identity mismatch");
1841
+ const transcript = this.containedPath(`${id}.jsonl`);
1842
+ const stat = fs4.existsSync(transcript) ? fs4.statSync(transcript) : void 0;
1843
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1844
+ this.db.prepare(
1845
+ "INSERT INTO sessions(session_id,transcript_relative_path,summary_relative_path,summary_json,transcript_size,transcript_mtime_ms,summary_revision,indexed_at,damaged) VALUES (?,?,?,?,?,?,?,?,0)"
1846
+ ).run(
1847
+ id,
1848
+ `${id}.jsonl`,
1849
+ `${id}.summary.json`,
1850
+ JSON.stringify(summary),
1851
+ stat?.size ?? 0,
1852
+ stat?.mtimeMs ?? 0,
1853
+ 1,
1854
+ now
1855
+ );
1856
+ indexed++;
1857
+ } catch {
1858
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1859
+ const fallback = {
1860
+ id,
1861
+ title: id,
1862
+ startedAt: now,
1863
+ model: "",
1864
+ provider: "",
1865
+ tokenTotal: 0
1866
+ };
1867
+ this.db.prepare(
1868
+ "INSERT INTO sessions(session_id,transcript_relative_path,summary_relative_path,summary_json,summary_revision,indexed_at,damaged) VALUES (?,?,?,?,1,?,1)"
1869
+ ).run(id, `${id}.jsonl`, `${id}.summary.json`, JSON.stringify(fallback), now);
1870
+ damaged++;
1871
+ }
1872
+ }
1873
+ this.db.prepare(
1874
+ "INSERT INTO catalog_meta(key,value) VALUES ('last_reconciliation',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value"
1875
+ ).run((/* @__PURE__ */ new Date()).toISOString());
1876
+ this.bumpGeneration();
1877
+ });
1878
+ return { indexed, damaged };
1879
+ }
1880
+ walkFiles(root, suffix) {
1881
+ const result = [];
1882
+ const visit = (dir) => {
1883
+ for (const entry of fs4.readdirSync(dir, { withFileTypes: true })) {
1884
+ if (entry.isDirectory()) {
1885
+ if (entry.name !== "_cas" && entry.name !== "_trash") visit(path4.join(dir, entry.name));
1886
+ } else if (entry.isFile() && entry.name.endsWith(suffix))
1887
+ result.push(path4.join(dir, entry.name));
1888
+ }
1889
+ };
1890
+ visit(root);
1891
+ return result;
1892
+ }
1893
+ summarizeTranscript(id) {
1894
+ const file = this.containedPath(`${id}.jsonl`);
1895
+ const lines = fs4.readFileSync(file, "utf8").split(/\r?\n/);
1896
+ let start;
1897
+ let endedAt;
1898
+ let lastActivityAt;
1899
+ let messageCount = 0;
1900
+ let iterationCount = 0;
1901
+ let toolCallCount = 0;
1902
+ let compactionCount = 0;
1903
+ let tokenTotal = 0;
1904
+ for (const line of lines) {
1905
+ if (!line) continue;
1906
+ let event;
1907
+ try {
1908
+ event = parseJson(line);
1909
+ } catch {
1910
+ continue;
1911
+ }
1912
+ lastActivityAt = event.ts;
1913
+ if (event.type === "session_start") start = event;
1914
+ if (event.type === "session_end") endedAt = event.ts;
1915
+ if (event.type === "message_appended" && (event.message.role === "user" || event.message.role === "assistant"))
1916
+ messageCount++;
1917
+ if (event.type === "llm_response") {
1918
+ iterationCount++;
1919
+ tokenTotal += event.usage.input + event.usage.output + (event.usage.cacheRead ?? 0) + (event.usage.cacheWrite ?? 0);
1920
+ }
1921
+ if (event.type === "tool_call_end") toolCallCount++;
1922
+ if (event.type === "compaction") compactionCount++;
1923
+ }
1924
+ if (!start) throw new Error("missing session_start");
1925
+ return {
1926
+ id,
1927
+ title: id,
1928
+ startedAt: start.ts,
1929
+ ...endedAt ? { endedAt } : {},
1930
+ model: start.model,
1931
+ provider: start.provider,
1932
+ tokenTotal,
1933
+ ...lastActivityAt ? { lastActivityAt } : {},
1934
+ messageCount,
1935
+ iterationCount,
1936
+ toolCallCount,
1937
+ compactionCount
1938
+ };
1939
+ }
1940
+ health(base) {
1941
+ this.reapExpired();
1942
+ const count = (table, where = "") => Number(
1943
+ this.db.prepare(`SELECT COUNT(*) AS count FROM ${table} ${where}`).get().count
1944
+ );
1945
+ const reconciliation = this.db.prepare("SELECT value FROM catalog_meta WHERE key='last_reconciliation'").get();
1946
+ return {
1947
+ ...base,
1948
+ catalogRows: count("sessions"),
1949
+ damagedRows: count("sessions", "WHERE damaged<>0"),
1950
+ liveLeases: count("session_leases"),
1951
+ reservations: count("resume_reservations"),
1952
+ maintenanceLeases: count("maintenance_leases"),
1953
+ generation: this.generation(),
1954
+ ...reconciliation ? { lastReconciliation: reconciliation.value } : {}
1955
+ };
1956
+ }
1957
+ };
1958
+ export {
1959
+ ProjectSessionRegistry,
1960
+ SESSION_CATALOG_DEFAULT_LEASE_MS,
1961
+ SESSION_CATALOG_DEFAULT_RESERVATION_MS,
1962
+ SESSION_CATALOG_MAX_AGENTS,
1963
+ SESSION_CATALOG_MAX_FRAME_CHARS,
1964
+ SESSION_CATALOG_METADATA_FILE,
1965
+ SESSION_CATALOG_PROTOCOL_VERSION,
1966
+ SessionCatalogProjectClient,
1967
+ SessionCatalogStore,
1968
+ encodeSessionCatalogMessage,
1969
+ ensureSessionCatalogSocketDirectory,
1970
+ getProjectSessionRegistry,
1971
+ hasProjectSessionRegistry,
1972
+ resolveSessionCatalogDaemonAvailability,
1973
+ resolveSessionCatalogProjectServerUrl,
1974
+ sessionCatalogProjectServerEndpoint,
1975
+ sessionCatalogProjectServerKey,
1976
+ sessionCatalogProjectServerMetadataPath
1977
+ };
1978
+ //# sourceMappingURL=index.js.map