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