@wrongstack/core 0.313.0 → 0.313.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chronicle/index.js +84 -6391
- package/dist/chronicle/project-server.js +84 -4868
- package/dist/chunk-2BUUIMQB.js +225 -0
- package/dist/chunk-2FK4WTFF.js +207 -0
- package/dist/chunk-2FQL4PDC.js +292 -0
- package/dist/chunk-2KKODIQU.js +2256 -0
- package/dist/chunk-2YU4WVBW.js +134 -0
- package/dist/chunk-3E244UDA.js +356 -0
- package/dist/chunk-3XPVB7BA.js +135 -0
- package/dist/chunk-4LJJYBAU.js +388 -0
- package/dist/chunk-4VWO3ZXL.js +342 -0
- package/dist/chunk-4XV6IR37.js +187 -0
- package/dist/chunk-4ZHTKJHM.js +183 -0
- package/dist/chunk-52RTVH4M.js +361 -0
- package/dist/chunk-57GEWK5X.js +26 -0
- package/dist/chunk-5DSMEVA4.js +931 -0
- package/dist/chunk-5RP3QTRL.js +1223 -0
- package/dist/chunk-5S437PRC.js +50 -0
- package/dist/chunk-5XDUGTKN.js +511 -0
- package/dist/chunk-62V2AFVG.js +422 -0
- package/dist/chunk-65RDIOR2.js +2470 -0
- package/dist/chunk-6AKOTGLM.js +597 -0
- package/dist/chunk-7ZHZE5EO.js +28 -0
- package/dist/chunk-A455ATZB.js +140 -0
- package/dist/chunk-AD7ZFZCS.js +46 -0
- package/dist/chunk-AI4LLQ2U.js +856 -0
- package/dist/chunk-ASX6AW36.js +789 -0
- package/dist/chunk-AT4V4XGI.js +3522 -0
- package/dist/chunk-AWNQ6ED6.js +311 -0
- package/dist/chunk-B4AMLZPB.js +9 -0
- package/dist/chunk-BAKVJLEV.js +417 -0
- package/dist/chunk-BJHVULHO.js +55 -0
- package/dist/chunk-CB2HFKTP.js +9 -0
- package/dist/chunk-CE4ZOCOI.js +1640 -0
- package/dist/chunk-CQQL4ZOQ.js +151 -0
- package/dist/chunk-DEIQMBD2.js +65 -0
- package/dist/chunk-E6I5RXVK.js +58 -0
- package/dist/chunk-EFEHDQGY.js +1589 -0
- package/dist/chunk-EODDVJBM.js +82 -0
- package/dist/chunk-EPC3GZD4.js +308 -0
- package/dist/chunk-FAYRX2AD.js +13 -0
- package/dist/chunk-FFSX2QDQ.js +362 -0
- package/dist/chunk-FHAMQS7Q.js +5856 -0
- package/dist/chunk-FIV4IJL7.js +2263 -0
- package/dist/chunk-FNXVT7HF.js +52 -0
- package/dist/chunk-FSWCWSTS.js +395 -0
- package/dist/chunk-FW5LDDMJ.js +16464 -0
- package/dist/chunk-FXQLIX3K.js +211 -0
- package/dist/chunk-G5AAKEEZ.js +228 -0
- package/dist/chunk-G5S3S5ZN.js +38 -0
- package/dist/chunk-GAZEWQEZ.js +231 -0
- package/dist/chunk-GFJOMSHG.js +125 -0
- package/dist/chunk-GFXZTHNI.js +158 -0
- package/dist/chunk-GM54GJBU.js +960 -0
- package/dist/chunk-GPQ3NJPR.js +900 -0
- package/dist/chunk-GTCU6DZ3.js +1 -0
- package/dist/chunk-H5E77KUJ.js +15 -0
- package/dist/chunk-H72H4XDU.js +1023 -0
- package/dist/chunk-HA4ZYA6T.js +178 -0
- package/dist/chunk-I45KAW2N.js +5020 -0
- package/dist/chunk-IQ35HMQL.js +1396 -0
- package/dist/chunk-IYFBFX34.js +86 -0
- package/dist/chunk-JJPMWPB6.js +109 -0
- package/dist/chunk-JTHKOYWU.js +663 -0
- package/dist/chunk-JVGPR3TS.js +365 -0
- package/dist/chunk-JVKB2TBL.js +48 -0
- package/dist/chunk-JX7VBZDK.js +31 -0
- package/dist/chunk-K3G6JBUC.js +5232 -0
- package/dist/chunk-K4YUNKU7.js +589 -0
- package/dist/chunk-KBZGE6LN.js +710 -0
- package/dist/chunk-KDQJCT2J.js +45 -0
- package/dist/chunk-KI4L2DUL.js +560 -0
- package/dist/chunk-KJ2ZTQSL.js +47 -0
- package/dist/chunk-KSJ5UTP7.js +154 -0
- package/dist/chunk-LHOA5DWA.js +28 -0
- package/dist/chunk-LX5QWLBL.js +27 -0
- package/dist/chunk-LZDDLNCZ.js +279 -0
- package/dist/chunk-M2WF6AXG.js +115 -0
- package/dist/chunk-M7BS2K6U.js +1 -0
- package/dist/chunk-NDBIPFNY.js +102 -0
- package/dist/chunk-NEMIWEXC.js +1199 -0
- package/dist/chunk-NFAYHPRH.js +323 -0
- package/dist/chunk-O37BQ65S.js +21 -0
- package/dist/chunk-O74MJHXU.js +187 -0
- package/dist/chunk-OJZEX73F.js +112 -0
- package/dist/chunk-PAAWLLZX.js +74 -0
- package/dist/chunk-PFXFQQRT.js +339 -0
- package/dist/chunk-PFZO3C6H.js +14 -0
- package/dist/chunk-PHH7LD45.js +113 -0
- package/dist/chunk-QRTG4XTI.js +188 -0
- package/dist/chunk-QVOVMXJR.js +1351 -0
- package/dist/chunk-RCQYT2I4.js +757 -0
- package/dist/chunk-RD6DEE36.js +1178 -0
- package/dist/chunk-RJIZEJ42.js +30 -0
- package/dist/chunk-RPOA7IAE.js +150 -0
- package/dist/chunk-SN2DQRL6.js +1172 -0
- package/dist/chunk-SQJVFEBV.js +41 -0
- package/dist/chunk-SQP64RCS.js +5391 -0
- package/dist/chunk-SVT4RNTR.js +49 -0
- package/dist/chunk-SWUFN7XM.js +43 -0
- package/dist/chunk-SXMVYC5H.js +174 -0
- package/dist/chunk-SZ6AYUIZ.js +23 -0
- package/dist/chunk-T3KGZBU5.js +3171 -0
- package/dist/chunk-TBRL2RCC.js +9 -0
- package/dist/chunk-TRT2HRWZ.js +18 -0
- package/dist/chunk-TYW2GI5I.js +1077 -0
- package/dist/chunk-UIWONWVG.js +4959 -0
- package/dist/chunk-VB3H5WWB.js +151 -0
- package/dist/chunk-W4A6QA3D.js +258 -0
- package/dist/chunk-WBPVKEEE.js +227 -0
- package/dist/chunk-WEBMSQP2.js +123 -0
- package/dist/chunk-WOEZV3Q4.js +333 -0
- package/dist/chunk-WQQON3SV.js +473 -0
- package/dist/chunk-WQTOVMGV.js +119 -0
- package/dist/chunk-WZO23AWO.js +2779 -0
- package/dist/chunk-XBDP4QPW.js +7 -0
- package/dist/chunk-XEBHSJLT.js +103 -0
- package/dist/chunk-XQ2ECNK3.js +1 -0
- package/dist/chunk-XQ2XGIBF.js +2086 -0
- package/dist/chunk-Y2GE5TSI.js +355 -0
- package/dist/chunk-YBUJCZ57.js +351 -0
- package/dist/chunk-YNCVSFGF.js +149 -0
- package/dist/chunk-YUPMXOGP.js +282 -0
- package/dist/chunk-YY6APYUM.js +49 -0
- package/dist/chunk-Z2IJUO45.js +691 -0
- package/dist/chunk-ZEHUCJHY.js +129 -0
- package/dist/chunk-ZYU2YOJ6.js +1496 -0
- package/dist/chunk-ZZ4V3WIZ.js +163 -0
- package/dist/coordination/agents/index.js +145 -6260
- package/dist/coordination/index.js +365 -34324
- package/dist/coordination/mailbox-project-server.js +48 -3276
- package/dist/coordination/provider-status-tracker.d.ts +4 -0
- package/dist/core/agent.d.ts +14 -1
- package/dist/core/index.js +267 -12480
- package/dist/core/model-ref.js +5 -23
- package/dist/core/provider-runner.d.ts +36 -1
- package/dist/design/index.js +50 -1087
- package/dist/execution/index.d.ts +1 -1
- package/dist/execution/index.js +1599 -21888
- package/dist/execution/prompt-enhancer.js +16 -535
- package/dist/execution/retry-policy.d.ts +31 -1
- package/dist/extension/index.js +7 -311
- package/dist/goal/index.js +33 -3435
- package/dist/hooks/index.js +14 -1138
- package/dist/hq/index.js +112 -5139
- package/dist/hq/protocol.js +21 -668
- package/dist/index.js +1410 -92656
- package/dist/infrastructure/index.js +64 -4811
- package/dist/kernel/events/provider-events.d.ts +15 -0
- package/dist/kernel/index.js +14 -992
- package/dist/models/index.js +40 -1117
- package/dist/notifications/index.js +3 -108
- package/dist/observability/index.js +17 -279
- package/dist/plugin/index.js +584 -14835
- package/dist/prompts/index.js +14 -948
- package/dist/registry/index.js +9 -822
- package/dist/registry-R23UBE7H.js +14 -0
- package/dist/replay/index.js +6 -84
- package/dist/review-finding-store-DKAV3AS6.js +21 -0
- package/dist/review-report-store-OWY3EC3N.js +19 -0
- package/dist/security/index.js +114 -2202
- package/dist/session-catalog/index.js +36 -2103
- package/dist/session-catalog/project-server.js +42 -1435
- package/dist/skills/index.js +35 -1578
- package/dist/storage/index.js +182 -15600
- package/dist/tasking/index.js +10 -676
- package/dist/tools/index.js +52 -9590
- package/dist/types/config/autonomy.d.ts +5 -0
- package/dist/types/config/ui.d.ts +1 -1
- package/dist/types/errors.d.ts +18 -0
- package/dist/types/index.js +121 -1342
- package/dist/types/provider-runner.d.ts +8 -0
- package/dist/types/session-markers.js +8 -144
- package/dist/utils/error.js +3 -4
- package/dist/utils/expect-defined.js +3 -9
- package/dist/utils/heap-watchdog.js +6 -706
- package/dist/utils/index.js +269 -5685
- package/dist/utils/sage-output-block.js +5 -42
- package/dist/wiring/proxy-rewrite.d.ts +18 -0
- package/dist/wiring/proxy-rewrite.js +18 -121
- package/dist/worktree/index.js +6 -887
- package/package.json +4 -4
|
@@ -1,1433 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
SessionCatalogStore
|
|
4
|
+
} from "../chunk-AI4LLQ2U.js";
|
|
5
|
+
import {
|
|
6
|
+
SESSION_CATALOG_MAX_FRAME_CHARS,
|
|
7
|
+
SESSION_CATALOG_PROTOCOL_VERSION,
|
|
8
|
+
encodeSessionCatalogMessage,
|
|
9
|
+
sessionCatalogProjectServerEndpoint,
|
|
10
|
+
sessionCatalogProjectServerMetadataPath
|
|
11
|
+
} from "../chunk-E6I5RXVK.js";
|
|
12
|
+
import "../chunk-GM54GJBU.js";
|
|
13
|
+
import "../chunk-W4A6QA3D.js";
|
|
14
|
+
import {
|
|
15
|
+
restrictFilePermissions
|
|
16
|
+
} from "../chunk-H5E77KUJ.js";
|
|
17
|
+
import "../chunk-3E244UDA.js";
|
|
18
|
+
import {
|
|
19
|
+
useDaemonPerfDefaults
|
|
20
|
+
} from "../chunk-FNXVT7HF.js";
|
|
21
|
+
import "../chunk-AD7ZFZCS.js";
|
|
22
|
+
import "../chunk-TRT2HRWZ.js";
|
|
23
|
+
import "../chunk-LX5QWLBL.js";
|
|
24
|
+
import "../chunk-FAYRX2AD.js";
|
|
25
|
+
import {
|
|
26
|
+
atomicWrite
|
|
27
|
+
} from "../chunk-7ZHZE5EO.js";
|
|
28
|
+
import "../chunk-YNCVSFGF.js";
|
|
29
|
+
import "../chunk-WOEZV3Q4.js";
|
|
30
|
+
import "../chunk-TBRL2RCC.js";
|
|
2
31
|
|
|
3
32
|
// src/session-catalog/project-server.ts
|
|
4
|
-
import { randomBytes
|
|
33
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
5
34
|
import * as fsp from "node:fs/promises";
|
|
6
35
|
import * as net from "node:net";
|
|
7
|
-
import * as path4 from "node:path";
|
|
8
|
-
import { bindProjectEndpoint } from "@wrongstack/persistence";
|
|
9
|
-
|
|
10
|
-
// src/security/file-permissions.ts
|
|
11
|
-
import {
|
|
12
|
-
restrictDirPermissions,
|
|
13
|
-
restrictFilePermissions,
|
|
14
|
-
SECRET_DIR_MODE,
|
|
15
|
-
SECRET_FILE_MODE
|
|
16
|
-
} from "@wrongstack/persistence";
|
|
17
|
-
|
|
18
|
-
// src/utils/atomic-write.ts
|
|
19
|
-
import {
|
|
20
|
-
createPersistencePrimitives
|
|
21
|
-
} from "@wrongstack/persistence";
|
|
22
|
-
|
|
23
|
-
// src/types/errors.ts
|
|
24
|
-
var ERROR_CODES = {
|
|
25
|
-
// Provider
|
|
26
|
-
PROVIDER_RATE_LIMITED: "PROVIDER_RATE_LIMITED",
|
|
27
|
-
PROVIDER_AUTH_FAILED: "PROVIDER_AUTH_FAILED",
|
|
28
|
-
PROVIDER_OVERLOADED: "PROVIDER_OVERLOADED",
|
|
29
|
-
PROVIDER_INVALID_REQUEST: "PROVIDER_INVALID_REQUEST",
|
|
30
|
-
PROVIDER_SERVER_ERROR: "PROVIDER_SERVER_ERROR",
|
|
31
|
-
PROVIDER_NETWORK_ERROR: "PROVIDER_NETWORK_ERROR",
|
|
32
|
-
PROVIDER_CONTEXT_OVERFLOW: "PROVIDER_CONTEXT_OVERFLOW",
|
|
33
|
-
// Tool
|
|
34
|
-
TOOL_NOT_FOUND: "TOOL_NOT_FOUND",
|
|
35
|
-
TOOL_PERMISSION_DENIED: "TOOL_PERMISSION_DENIED",
|
|
36
|
-
TOOL_EXECUTION_FAILED: "TOOL_EXECUTION_FAILED",
|
|
37
|
-
TOOL_TIMEOUT: "TOOL_TIMEOUT",
|
|
38
|
-
TOOL_INPUT_INVALID: "TOOL_INPUT_INVALID",
|
|
39
|
-
// Config
|
|
40
|
-
CONFIG_INVALID: "CONFIG_INVALID",
|
|
41
|
-
CONFIG_NOT_FOUND: "CONFIG_NOT_FOUND",
|
|
42
|
-
CONFIG_PARSE_FAILED: "CONFIG_PARSE_FAILED",
|
|
43
|
-
CONFIG_MIGRATION_NEEDED: "CONFIG_MIGRATION_NEEDED",
|
|
44
|
-
// Plugin
|
|
45
|
-
PLUGIN_LOAD_FAILED: "PLUGIN_LOAD_FAILED",
|
|
46
|
-
PLUGIN_API_MISMATCH: "PLUGIN_API_MISMATCH",
|
|
47
|
-
PLUGIN_MISSING_DEPENDENCY: "PLUGIN_MISSING_DEPENDENCY",
|
|
48
|
-
// Agent
|
|
49
|
-
AGENT_ITERATION_LIMIT: "AGENT_ITERATION_LIMIT",
|
|
50
|
-
AGENT_CONTEXT_OVERFLOW: "AGENT_CONTEXT_OVERFLOW",
|
|
51
|
-
AGENT_ABORTED: "AGENT_ABORTED",
|
|
52
|
-
AGENT_RUN_FAILED: "AGENT_RUN_FAILED",
|
|
53
|
-
// Session
|
|
54
|
-
SESSION_NOT_FOUND: "SESSION_NOT_FOUND",
|
|
55
|
-
SESSION_CORRUPTED: "SESSION_CORRUPTED",
|
|
56
|
-
SESSION_WRITE_FAILED: "SESSION_WRITE_FAILED",
|
|
57
|
-
// Container / Registry
|
|
58
|
-
CONTAINER_TOKEN_ALREADY_BOUND: "CONTAINER_TOKEN_ALREADY_BOUND",
|
|
59
|
-
CONTAINER_TOKEN_NOT_BOUND: "CONTAINER_TOKEN_NOT_BOUND",
|
|
60
|
-
CONTAINER_CIRCULAR_DEPENDENCY: "CONTAINER_CIRCULAR_DEPENDENCY",
|
|
61
|
-
REGISTRY_DUPLICATE: "REGISTRY_DUPLICATE",
|
|
62
|
-
REGISTRY_NOT_FOUND: "REGISTRY_NOT_FOUND",
|
|
63
|
-
REGISTRY_INVALID: "REGISTRY_INVALID",
|
|
64
|
-
// File system
|
|
65
|
-
FS_READ_FAILED: "FS_READ_FAILED",
|
|
66
|
-
FS_WRITE_FAILED: "FS_WRITE_FAILED",
|
|
67
|
-
FS_MKDIR_FAILED: "FS_MKDIR_FAILED",
|
|
68
|
-
FS_DELETE_FAILED: "FS_DELETE_FAILED",
|
|
69
|
-
FS_ATOMIC_WRITE_FAILED: "FS_ATOMIC_WRITE_FAILED",
|
|
70
|
-
// SDD (Spec-Driven Development)
|
|
71
|
-
SDD_VALIDATION_FAILED: "SDD_VALIDATION_FAILED",
|
|
72
|
-
SDD_PARSE_FAILED: "SDD_PARSE_FAILED",
|
|
73
|
-
SDD_INVALID_STATE: "SDD_INVALID_STATE",
|
|
74
|
-
SDD_NOT_READY: "SDD_NOT_READY",
|
|
75
|
-
// General
|
|
76
|
-
VALIDATION_ERROR: "VALIDATION_ERROR",
|
|
77
|
-
PARSE_FAILED: "PARSE_FAILED",
|
|
78
|
-
UNKNOWN: "UNKNOWN"
|
|
79
|
-
};
|
|
80
|
-
var WrongStackError = class extends Error {
|
|
81
|
-
code;
|
|
82
|
-
subsystem;
|
|
83
|
-
severity;
|
|
84
|
-
recoverable;
|
|
85
|
-
context;
|
|
86
|
-
constructor(opts) {
|
|
87
|
-
super(opts.message, { cause: opts.cause });
|
|
88
|
-
this.name = "WrongStackError";
|
|
89
|
-
this.code = opts.code;
|
|
90
|
-
this.subsystem = opts.subsystem;
|
|
91
|
-
this.severity = opts.severity ?? "error";
|
|
92
|
-
this.recoverable = opts.recoverable ?? false;
|
|
93
|
-
this.context = opts.context;
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Render a one-line user-facing description.
|
|
97
|
-
* Subclasses should override for domain-specific formatting.
|
|
98
|
-
*/
|
|
99
|
-
describe() {
|
|
100
|
-
const ctx = this.context ? ` ${formatContext(this.context)}` : "";
|
|
101
|
-
return `${this.code}: ${this.message}${ctx}`;
|
|
102
|
-
}
|
|
103
|
-
};
|
|
104
|
-
function formatContext(ctx) {
|
|
105
|
-
const parts = Object.entries(ctx).filter(([, v]) => v !== void 0).slice(0, 3).map(([k, v]) => `${k}=${String(v)}`);
|
|
106
|
-
return parts.length > 0 ? `[${parts.join(" ")}]` : "";
|
|
107
|
-
}
|
|
108
|
-
var FsError = class extends WrongStackError {
|
|
109
|
-
path;
|
|
110
|
-
constructor(opts) {
|
|
111
|
-
super({
|
|
112
|
-
message: opts.message,
|
|
113
|
-
code: opts.code,
|
|
114
|
-
subsystem: "fs",
|
|
115
|
-
severity: "error",
|
|
116
|
-
recoverable: opts.code !== ERROR_CODES.FS_READ_FAILED,
|
|
117
|
-
context: { path: opts.path, ...opts.context },
|
|
118
|
-
cause: opts.cause
|
|
119
|
-
});
|
|
120
|
-
this.name = "FsError";
|
|
121
|
-
this.path = opts.path;
|
|
122
|
-
}
|
|
123
|
-
};
|
|
124
|
-
|
|
125
|
-
// src/utils/atomic-write.ts
|
|
126
|
-
var primitives = createPersistencePrimitives({
|
|
127
|
-
createLockTimeoutError: ({ targetPath, timeoutMs }) => new FsError({
|
|
128
|
-
message: `Timed out waiting for file lock: ${targetPath}`,
|
|
129
|
-
code: "FS_ATOMIC_WRITE_FAILED",
|
|
130
|
-
path: targetPath,
|
|
131
|
-
context: { timeoutMs }
|
|
132
|
-
})
|
|
133
|
-
});
|
|
134
|
-
var atomicWrite = primitives.atomicWrite;
|
|
135
|
-
var atomicReplaceWithWriter = primitives.atomicReplaceWithWriter;
|
|
136
|
-
var ensureDir = primitives.ensureDir;
|
|
137
|
-
var withFileLock = primitives.withFileLock;
|
|
138
|
-
|
|
139
|
-
// src/utils/perf-profile.ts
|
|
140
|
-
var daemonDefaults = false;
|
|
141
|
-
function useDaemonPerfDefaults() {
|
|
142
|
-
daemonDefaults = true;
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// src/session-catalog/endpoint.ts
|
|
146
|
-
import { createHash } from "node:crypto";
|
|
147
|
-
import * as os from "node:os";
|
|
148
36
|
import * as path from "node:path";
|
|
149
|
-
|
|
150
|
-
// src/session-catalog/protocol.ts
|
|
151
|
-
var SESSION_CATALOG_PROTOCOL_VERSION = 1;
|
|
152
|
-
var SESSION_CATALOG_MAX_FRAME_CHARS = 4 * 1024 * 1024;
|
|
153
|
-
var SESSION_CATALOG_DEFAULT_LEASE_MS = 3e4;
|
|
154
|
-
var SESSION_CATALOG_DEFAULT_RESERVATION_MS = 15e3;
|
|
155
|
-
var SESSION_CATALOG_MAX_AGENTS = 128;
|
|
156
|
-
function encodeSessionCatalogMessage(message) {
|
|
157
|
-
return `${JSON.stringify(message)}
|
|
158
|
-
`;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
// src/session-catalog/endpoint.ts
|
|
162
|
-
var SESSION_CATALOG_METADATA_FILE = ".session-catalog-server.json";
|
|
163
|
-
function normalizedPath(value) {
|
|
164
|
-
const resolved = path.resolve(value);
|
|
165
|
-
return process.platform === "win32" ? resolved.toLowerCase() : resolved;
|
|
166
|
-
}
|
|
167
|
-
function sessionCatalogProjectServerKey(projectDir) {
|
|
168
|
-
return createHash("sha256").update(normalizedPath(projectDir)).digest("hex").slice(0, 24);
|
|
169
|
-
}
|
|
170
|
-
function sessionCatalogProjectServerEndpoint(projectDir) {
|
|
171
|
-
const key = sessionCatalogProjectServerKey(projectDir);
|
|
172
|
-
if (process.platform === "win32") {
|
|
173
|
-
return `\\\\.\\pipe\\wrongstack-session-catalog-v${SESSION_CATALOG_PROTOCOL_VERSION}-${key}`;
|
|
174
|
-
}
|
|
175
|
-
return path.join(os.tmpdir(), `wssc-v${SESSION_CATALOG_PROTOCOL_VERSION}`, `${key}.sock`);
|
|
176
|
-
}
|
|
177
|
-
function sessionCatalogProjectServerMetadataPath(projectDir) {
|
|
178
|
-
return path.join(projectDir, SESSION_CATALOG_METADATA_FILE);
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
// src/session-catalog/store.ts
|
|
182
|
-
import { randomBytes, randomUUID } from "node:crypto";
|
|
183
|
-
import * as fs2 from "node:fs";
|
|
184
|
-
import * as path3 from "node:path";
|
|
185
|
-
|
|
186
|
-
// src/coordination/sqlite-mailbox-schema.ts
|
|
187
|
-
import { loadRuntimeDatabaseSync } from "@wrongstack/persistence";
|
|
188
|
-
|
|
189
|
-
// src/utils/sqlite-warning.ts
|
|
190
|
-
var SQLITE_EXPERIMENTAL_WARNING_RE = /sqlite is an experimental feature/i;
|
|
191
|
-
function isSqliteExperimentalWarning(warning, rest) {
|
|
192
|
-
const message = typeof warning === "string" ? warning : warning instanceof Error ? warning.message : "";
|
|
193
|
-
const typeOrOptions = rest[0];
|
|
194
|
-
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 : "";
|
|
195
|
-
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 : "";
|
|
196
|
-
return SQLITE_EXPERIMENTAL_WARNING_RE.test(message) && (warningType === "ExperimentalWarning" || warningCode === "ExperimentalWarning");
|
|
197
|
-
}
|
|
198
|
-
function withSqliteExperimentalWarningSuppressed(run) {
|
|
199
|
-
const originalEmitWarning = process.emitWarning;
|
|
200
|
-
const forwardWarning = originalEmitWarning.bind(process);
|
|
201
|
-
process.emitWarning = ((warning, ...rest) => {
|
|
202
|
-
if (isSqliteExperimentalWarning(warning, rest)) return;
|
|
203
|
-
forwardWarning(warning, ...rest);
|
|
204
|
-
});
|
|
205
|
-
try {
|
|
206
|
-
return run();
|
|
207
|
-
} finally {
|
|
208
|
-
process.emitWarning = originalEmitWarning;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
// src/coordination/sqlite-mailbox-schema.ts
|
|
213
|
-
var DatabaseSyncCtor;
|
|
214
|
-
function loadDatabaseSync() {
|
|
215
|
-
if (DatabaseSyncCtor) return DatabaseSyncCtor;
|
|
216
|
-
return withSqliteExperimentalWarningSuppressed(() => {
|
|
217
|
-
DatabaseSyncCtor = loadRuntimeDatabaseSync();
|
|
218
|
-
return DatabaseSyncCtor;
|
|
219
|
-
});
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
// src/security/secret-scrubber.ts
|
|
223
|
-
var JSON_CREDENTIAL_KEY_ANCHORS = [
|
|
224
|
-
'Key"',
|
|
225
|
-
'key"',
|
|
226
|
-
'KEY"',
|
|
227
|
-
'token"',
|
|
228
|
-
'Token"',
|
|
229
|
-
'TOKEN"',
|
|
230
|
-
'secret"',
|
|
231
|
-
'Secret"',
|
|
232
|
-
'SECRET"',
|
|
233
|
-
'password"',
|
|
234
|
-
'Password"',
|
|
235
|
-
'PASSWORD"',
|
|
236
|
-
'authorization"',
|
|
237
|
-
'Authorization"',
|
|
238
|
-
'bearer"',
|
|
239
|
-
'Bearer"'
|
|
240
|
-
];
|
|
241
|
-
var PATTERNS = [
|
|
242
|
-
// Anchored at the start where possible so partial matches inside larger
|
|
243
|
-
// strings don't trigger false positives.
|
|
244
|
-
{
|
|
245
|
-
type: "anthropic_key",
|
|
246
|
-
regex: /(?<![A-Za-z0-9])sk-ant-api\d+-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9])/g,
|
|
247
|
-
anchor: "sk-ant-"
|
|
248
|
-
},
|
|
249
|
-
{ type: "openai_key", regex: /(?<![A-Za-z0-9])sk-(?:proj-)?[A-Za-z0-9_-]{20,}(?![A-Za-z0-9])/g, anchor: "sk-" },
|
|
250
|
-
{
|
|
251
|
-
// `xai` is a first-class provider in this codebase, but its key shape was
|
|
252
|
-
// absent here — so the one credential format WrongStack itself hands users
|
|
253
|
-
// was the one the scrubber could not recognize (audit 2026-08-20).
|
|
254
|
-
type: "xai_key",
|
|
255
|
-
regex: /(?<![A-Za-z0-9])xai-[A-Za-z0-9]{20,}(?![A-Za-z0-9])/g,
|
|
256
|
-
anchor: "xai-"
|
|
257
|
-
},
|
|
258
|
-
{ type: "github_pat", regex: /(?<![A-Za-z0-9])ghp_[A-Za-z0-9]{36,}(?![A-Za-z0-9])/g, anchor: "ghp_" },
|
|
259
|
-
{ type: "github_pat_v2", regex: /(?<![A-Za-z0-9])github_pat_[A-Za-z0-9_]{50,}(?![A-Za-z0-9])/g, anchor: "github_pat_" },
|
|
260
|
-
{ type: "aws_access_key", regex: /(?<![A-Za-z0-9])AKIA[0-9A-Z]{16}(?![A-Za-z0-9])/g, anchor: "AKIA" },
|
|
261
|
-
{ type: "gcp_key", regex: /(?<![A-Za-z0-9])AIza[0-9A-Za-z_-]{35}(?![A-Za-z0-9])/g, anchor: "AIza" },
|
|
262
|
-
{ type: "slack_token", regex: /(?<![A-Za-z0-9-])xox[abpos]-[A-Za-z0-9-]{10,}(?![A-Za-z0-9-])/g, anchor: "xox" },
|
|
263
|
-
{
|
|
264
|
-
type: "stripe_key",
|
|
265
|
-
regex: /(?<![A-Za-z0-9])sk_(?:live|test)_[A-Za-z0-9]{24,}(?![A-Za-z0-9])/g,
|
|
266
|
-
anchor: "sk_"
|
|
267
|
-
},
|
|
268
|
-
{
|
|
269
|
-
type: "twilio_sid",
|
|
270
|
-
regex: /(?<![A-Za-z0-9])AC[a-f0-9]{32}(?![A-Za-z0-9])/g,
|
|
271
|
-
anchor: "AC"
|
|
272
|
-
},
|
|
273
|
-
{
|
|
274
|
-
type: "telegram_bot_token",
|
|
275
|
-
// Telegram tokens are of the form bot<digits>:<alphanum> in URL paths
|
|
276
|
-
regex: /\/bot\d+:[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
|
|
277
|
-
anchor: "/bot"
|
|
278
|
-
},
|
|
279
|
-
{
|
|
280
|
-
type: "jwt",
|
|
281
|
-
// Anchored: look for literal "eyJ" which is unambiguous for JWT header
|
|
282
|
-
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,
|
|
283
|
-
anchor: "eyJ"
|
|
284
|
-
},
|
|
285
|
-
{
|
|
286
|
-
type: "private_key",
|
|
287
|
-
// Anchored: start must be BEGIN, end must be END with no extra dashes after END
|
|
288
|
-
regex: /(?:^|\n)-----BEGIN (?:RSA|EC|OPENSSH|DSA|PGP)? ?PRIVATE KEY-----[\s\S]*?-----END[^-]*-----(?:\n|$)/g,
|
|
289
|
-
anchor: "-----BEGIN"
|
|
290
|
-
},
|
|
291
|
-
{ type: "mongodb_uri", regex: /mongodb(?:\+srv)?:\/\/[^\s"'`]+/g, anchor: "mongodb" },
|
|
292
|
-
{ type: "postgres_uri", regex: /postgres(?:ql)?:\/\/[^\s"'`]+/g, anchor: "postgres" },
|
|
293
|
-
{ type: "mysql_uri", regex: /mysql:\/\/[^\s"'`]+/g, anchor: "mysql://" },
|
|
294
|
-
{ type: "redis_uri", regex: /redis:\/\/[^\s"'`]+/g, anchor: "redis://" },
|
|
295
|
-
// AI/ML provider keys — modern LLM services with well-known prefixes
|
|
296
|
-
{
|
|
297
|
-
type: "huggingface_token",
|
|
298
|
-
// HuggingFace tokens: hf_ followed by 34 alphanumeric chars
|
|
299
|
-
regex: /(?<![A-Za-z0-9])hf_[A-Za-z0-9]{34}(?![A-Za-z0-9])/g,
|
|
300
|
-
anchor: "hf_"
|
|
301
|
-
},
|
|
302
|
-
{
|
|
303
|
-
type: "replicate_token",
|
|
304
|
-
// Replicate tokens: r8_ followed by 40+ alphanumeric chars
|
|
305
|
-
regex: /(?<![A-Za-z0-9])r8_[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
|
|
306
|
-
anchor: "r8_"
|
|
307
|
-
},
|
|
308
|
-
{
|
|
309
|
-
type: "perplexity_key",
|
|
310
|
-
// Perplexity API keys: pplx- followed by 40+ alphanumeric chars
|
|
311
|
-
regex: /(?<![A-Za-z0-9])pplx-[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
|
|
312
|
-
anchor: "pplx-"
|
|
313
|
-
},
|
|
314
|
-
{
|
|
315
|
-
type: "groq_key",
|
|
316
|
-
// Groq API keys: gsk_ followed by 40+ alphanumeric chars
|
|
317
|
-
regex: /(?<![A-Za-z0-9])gsk_[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
|
|
318
|
-
anchor: "gsk_"
|
|
319
|
-
},
|
|
320
|
-
{
|
|
321
|
-
type: "bearer_token",
|
|
322
|
-
// Anchored with alternation instead of negative lookahead — avoids V8
|
|
323
|
-
// backtracking risk on adversarial input. Bounded at 512 chars.
|
|
324
|
-
// Min 12 chars: some OAuth providers issue shorter-lived tokens (< 20
|
|
325
|
-
// chars). A 12-char base64 string has ~71 bits of entropy — above the
|
|
326
|
-
// threshold where random strings are unlikely to produce false matches.
|
|
327
|
-
// The trailing boundary is a NON-consuming lookahead: two adjacent bearer
|
|
328
|
-
// tokens sharing a single delimiter (`Bearer a… Bearer b…`) must both be
|
|
329
|
-
// redacted. A consuming trailing delimiter would eat the separator the
|
|
330
|
-
// next match needs for its leading anchor, leaking the second token.
|
|
331
|
-
regex: /(?:^|[^A-Za-z0-9_.~+/-])Bearer\s+[A-Za-z0-9._~+/-]{12,512}=*(?=$|[^A-Za-z0-9_.~+/-])/g,
|
|
332
|
-
anchor: "Bearer"
|
|
333
|
-
},
|
|
334
|
-
{
|
|
335
|
-
type: "high_entropy_env",
|
|
336
|
-
// Anchored with alternation instead of lookbehind to avoid backtracking.
|
|
337
|
-
// Value bounded at 512 chars.
|
|
338
|
-
// The trailing boundary is a NON-consuming lookahead so two secrets
|
|
339
|
-
// separated by a single delimiter (one space OR one newline, e.g.
|
|
340
|
-
// `printenv` / `.env` dumps: `API_KEY=… \n SESSION_TOKEN=…`) are BOTH
|
|
341
|
-
// redacted. A consuming trailing `\s` would swallow the separator the
|
|
342
|
-
// next match needs for its leading anchor, so every other secret would
|
|
343
|
-
// leak in plaintext.
|
|
344
|
-
// The leading delimiter is CAPTURED (group 1) and re-emitted by the
|
|
345
|
-
// replacement so the separator between adjacent secrets is preserved
|
|
346
|
-
// rather than collapsed. Capture groups are therefore: 1=leading
|
|
347
|
-
// delimiter, 2=key name, 3=value.
|
|
348
|
-
regex: /(^|\s)([A-Z_]{4,}(?:KEY|TOKEN|SECRET|PASSWORD|PWD|PASSPHRASE))\s*[:=]\s*['"]?([A-Za-z0-9_/+=-]{20,512})['"]?(?=\s|$)/g,
|
|
349
|
-
anchor: ["KEY", "TOKEN", "SECRET", "PASSWORD", "PWD", "PASSPHRASE"]
|
|
350
|
-
},
|
|
351
|
-
{
|
|
352
|
-
type: "json_credential_key",
|
|
353
|
-
// The JSON counterpart to `high_entropy_env`, and the pattern that the
|
|
354
|
-
// now-deleted `JSON_KEY_ANCHORS` list was written for. Without it those
|
|
355
|
-
// anchors only widened the cheap pre-scan — `hasCredentialAnchors` said
|
|
356
|
-
// "this text may hold a secret", every pattern then declined to match, and
|
|
357
|
-
// the value went out verbatim. `high_entropy_env` cannot cover these: it
|
|
358
|
-
// requires an UPPERCASE unquoted key (`API_KEY=…`), so `{"apiKey":"…"}`
|
|
359
|
-
// never matched.
|
|
360
|
-
//
|
|
361
|
-
// Tool results are routinely serialised as JSON, and a credential with no
|
|
362
|
-
// recognisable prefix (Azure, self-hosted gateways, Anthropic/Codex OAuth)
|
|
363
|
-
// has no other pattern that can catch it — this is the only thing standing
|
|
364
|
-
// between such a value and the session JSONL, chronicle, HQ broadcast and
|
|
365
|
-
// the model's own context.
|
|
366
|
-
//
|
|
367
|
-
// The key may carry a prefix (`"anthropicApiKey"`), but the credential word
|
|
368
|
-
// must END the key: `"tokenCount"` and `"maxTokens"` do not match, because
|
|
369
|
-
// the closing quote has to follow the word immediately.
|
|
370
|
-
// Value floor of 8 chars keeps enum-ish values (`"authorization":"none"`)
|
|
371
|
-
// out. Capture groups: 1=key + punctuation, 2=value, 3=closing quote.
|
|
372
|
-
regex: /("[A-Za-z0-9_]*(?:apiKey|api_key|token|secret|password|authorization|bearer|private_key|access_token|refresh_token|client_secret)"\s*:\s*")([^"\\]{8,512})(")/gi,
|
|
373
|
-
anchor: JSON_CREDENTIAL_KEY_ANCHORS
|
|
374
|
-
},
|
|
375
|
-
// ── Ported from packages/plugins credential-patterns.ts (WS-034) ─────────
|
|
376
|
-
// The plugin runtime carried 37 patterns while this scrubber — the one that
|
|
377
|
-
// guards session JSONL, chronicle, HQ broadcast, WebUI events and the auth
|
|
378
|
-
// audit — carried 22. The plugin side already had a parity test; it just did
|
|
379
|
-
// not cover core. Most consequential: WrongStack mints `gho_` tokens itself
|
|
380
|
-
// in the Copilot OAuth flow, and `gh[ousr]_` was absent here.
|
|
381
|
-
{
|
|
382
|
-
type: "github_oauth_token",
|
|
383
|
-
regex: /(?<![A-Za-z0-9])gh[ousr]_[A-Za-z0-9]{36,}(?![A-Za-z0-9])/g,
|
|
384
|
-
anchor: ["gho_", "ghu_", "ghs_", "ghr_"]
|
|
385
|
-
},
|
|
386
|
-
{
|
|
387
|
-
type: "gitlab_pat",
|
|
388
|
-
regex: /(?<![A-Za-z0-9])glpat-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
|
|
389
|
-
anchor: "glpat-"
|
|
390
|
-
},
|
|
391
|
-
{
|
|
392
|
-
type: "gitlab_runner_token",
|
|
393
|
-
regex: /(?<![A-Za-z0-9])glrt-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
|
|
394
|
-
anchor: "glrt-"
|
|
395
|
-
},
|
|
396
|
-
{
|
|
397
|
-
type: "npm_token",
|
|
398
|
-
regex: /(?<![A-Za-z0-9])npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])/g,
|
|
399
|
-
anchor: "npm_"
|
|
400
|
-
},
|
|
401
|
-
{
|
|
402
|
-
type: "slack_app_token",
|
|
403
|
-
regex: /(?<![A-Za-z0-9-])xapp-\d-[A-Za-z0-9-]{10,}(?![A-Za-z0-9-])/g,
|
|
404
|
-
anchor: "xapp-"
|
|
405
|
-
},
|
|
406
|
-
{
|
|
407
|
-
type: "slack_webhook",
|
|
408
|
-
regex: /https:\/\/hooks\.slack\.com\/services\/T[A-Za-z0-9_-]+\/B[A-Za-z0-9_-]+\/[A-Za-z0-9]{16,}/g,
|
|
409
|
-
anchor: "hooks.slack.com"
|
|
410
|
-
},
|
|
411
|
-
{
|
|
412
|
-
type: "sendgrid_key",
|
|
413
|
-
regex: /(?<![A-Za-z0-9])SG\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
|
|
414
|
-
anchor: "SG."
|
|
415
|
-
},
|
|
416
|
-
{
|
|
417
|
-
type: "digitalocean_token",
|
|
418
|
-
regex: /(?<![A-Za-z0-9])dop_v1_[a-f0-9]{64}(?![A-Za-z0-9])/g,
|
|
419
|
-
anchor: "dop_v1_"
|
|
420
|
-
},
|
|
421
|
-
{
|
|
422
|
-
type: "doppler_token",
|
|
423
|
-
regex: /(?<![A-Za-z0-9])dp\.(?:pt|st|sa|scim|audit)\.[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
|
|
424
|
-
anchor: "dp."
|
|
425
|
-
},
|
|
426
|
-
{
|
|
427
|
-
type: "shopify_token",
|
|
428
|
-
regex: /(?<![A-Za-z0-9])shp(?:at|ca|pa|ss)_[a-fA-F0-9]{32}(?![A-Za-z0-9])/g,
|
|
429
|
-
anchor: "shp"
|
|
430
|
-
},
|
|
431
|
-
{
|
|
432
|
-
type: "docker_pat",
|
|
433
|
-
regex: /(?<![A-Za-z0-9])dckr_pat_[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
|
|
434
|
-
anchor: "dckr_pat_"
|
|
435
|
-
},
|
|
436
|
-
{
|
|
437
|
-
type: "linear_key",
|
|
438
|
-
regex: /(?<![A-Za-z0-9])lin_api_[A-Za-z0-9]{40,}(?![A-Za-z0-9])/g,
|
|
439
|
-
anchor: "lin_api_"
|
|
440
|
-
},
|
|
441
|
-
{
|
|
442
|
-
type: "atlassian_token",
|
|
443
|
-
regex: /(?<![A-Za-z0-9])ATATT3[A-Za-z0-9_\-=]{40,}(?![A-Za-z0-9_\-=])/g,
|
|
444
|
-
anchor: "ATATT3"
|
|
445
|
-
},
|
|
446
|
-
{
|
|
447
|
-
type: "square_token",
|
|
448
|
-
regex: /(?<![A-Za-z0-9])(?:sq0(?:atp|csp)-|EAAA)[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
|
|
449
|
-
anchor: ["sq0atp-", "sq0csp-", "EAAA"]
|
|
450
|
-
},
|
|
451
|
-
{
|
|
452
|
-
type: "google_oauth_client_secret",
|
|
453
|
-
regex: /(?<![A-Za-z0-9_-])GOCSPX-[A-Za-z0-9_-]{20,}(?![A-Za-z0-9_-])/g,
|
|
454
|
-
anchor: "GOCSPX-"
|
|
455
|
-
}
|
|
456
|
-
];
|
|
457
|
-
var SIMPLE_PATTERNS = PATTERNS.filter(
|
|
458
|
-
(p) => p.type !== "high_entropy_env" && p.type !== "json_credential_key"
|
|
459
|
-
);
|
|
460
|
-
var COMBINED_REGEX = new RegExp(SIMPLE_PATTERNS.map((p) => `(${p.regex.source})`).join("|"), "g");
|
|
461
|
-
var HIGH_ENTROPY_REGEX = PATTERNS.find((p) => p.type === "high_entropy_env").regex;
|
|
462
|
-
var JSON_CREDENTIAL_REGEX = PATTERNS.find((p) => p.type === "json_credential_key").regex;
|
|
463
|
-
var COMBINED_REPLACEMENTS = SIMPLE_PATTERNS.map((p) => `[REDACTED:${p.type}]`);
|
|
464
|
-
var SCRUB_CHUNK_BYTES = 64 * 1024;
|
|
465
|
-
var SCRUB_OVERLAP_BYTES = 1024;
|
|
466
|
-
var PEM_PRIVATE_KEY_BEGIN_RE = /-----BEGIN (?:RSA|EC|OPENSSH|DSA|PGP)? ?PRIVATE KEY-----/;
|
|
467
|
-
var PEM_END_MARKER = "-----END";
|
|
468
|
-
var MAX_PEM_BLOCK_BYTES = 64 * 1024;
|
|
469
|
-
var PEM_END_LINE_TOLERANCE = 64;
|
|
470
|
-
function extendChunkBoundaryPastPem(text, chunkStart, proposedEnd) {
|
|
471
|
-
const head = text.slice(chunkStart, proposedEnd);
|
|
472
|
-
const lastBegin = head.lastIndexOf("-----BEGIN ");
|
|
473
|
-
if (lastBegin === -1) return proposedEnd;
|
|
474
|
-
const fromBegin = text.slice(chunkStart + lastBegin);
|
|
475
|
-
const marker = PEM_PRIVATE_KEY_BEGIN_RE.exec(fromBegin);
|
|
476
|
-
if (!marker || marker.index !== 0) return proposedEnd;
|
|
477
|
-
const bodyStart = marker[0].length;
|
|
478
|
-
const cap = Math.min(text.length, chunkStart + lastBegin + MAX_PEM_BLOCK_BYTES);
|
|
479
|
-
const closeIdx = fromBegin.indexOf(PEM_END_MARKER, bodyStart);
|
|
480
|
-
if (closeIdx === -1 || chunkStart + lastBegin + closeIdx >= cap + PEM_END_LINE_TOLERANCE) {
|
|
481
|
-
return proposedEnd;
|
|
482
|
-
}
|
|
483
|
-
const lineEnd = fromBegin.indexOf("\n", closeIdx);
|
|
484
|
-
const end = lineEnd === -1 ? text.length : chunkStart + lastBegin + lineEnd + 1;
|
|
485
|
-
return Math.max(proposedEnd, end);
|
|
486
|
-
}
|
|
487
|
-
var PATTERN_ANCHORS = [
|
|
488
|
-
...new Set(
|
|
489
|
-
PATTERNS.flatMap(
|
|
490
|
-
(pattern) => typeof pattern.anchor === "string" ? [pattern.anchor] : [...pattern.anchor]
|
|
491
|
-
)
|
|
492
|
-
)
|
|
493
|
-
];
|
|
494
|
-
var ALL_ANCHORS = PATTERN_ANCHORS;
|
|
495
|
-
function hasCredentialAnchors(text) {
|
|
496
|
-
for (const anchor of ALL_ANCHORS) {
|
|
497
|
-
if (text.includes(anchor)) return true;
|
|
498
|
-
}
|
|
499
|
-
return false;
|
|
500
|
-
}
|
|
501
|
-
var DefaultSecretScrubber = class {
|
|
502
|
-
scrub(text) {
|
|
503
|
-
if (!text) return text;
|
|
504
|
-
if (!hasCredentialAnchors(text)) return text;
|
|
505
|
-
if (text.length <= SCRUB_CHUNK_BYTES) {
|
|
506
|
-
return this.scrubOne(text);
|
|
507
|
-
}
|
|
508
|
-
const out = [];
|
|
509
|
-
let i = 0;
|
|
510
|
-
while (i < text.length) {
|
|
511
|
-
let end = Math.min(i + SCRUB_CHUNK_BYTES, text.length);
|
|
512
|
-
if (end < text.length) {
|
|
513
|
-
const limit = Math.min(end + SCRUB_OVERLAP_BYTES, text.length);
|
|
514
|
-
let safe = -1;
|
|
515
|
-
for (let j = end; j < limit; j++) {
|
|
516
|
-
const ch = text.charCodeAt(j);
|
|
517
|
-
if (ch === 32 || ch === 9 || ch === 10 || ch === 13) {
|
|
518
|
-
safe = j;
|
|
519
|
-
break;
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
end = safe === -1 ? end : safe + 1;
|
|
523
|
-
end = extendChunkBoundaryPastPem(text, i, end);
|
|
524
|
-
}
|
|
525
|
-
out.push(this.scrubOne(text.slice(i, end)));
|
|
526
|
-
i = end;
|
|
527
|
-
}
|
|
528
|
-
return out.join("");
|
|
529
|
-
}
|
|
530
|
-
scrubOne(text) {
|
|
531
|
-
if (!hasCredentialAnchors(text)) return text;
|
|
532
|
-
let out = text.replace(
|
|
533
|
-
COMBINED_REGEX,
|
|
534
|
-
(match, ...groups) => {
|
|
535
|
-
const idx = groups.findIndex((g) => g !== void 0);
|
|
536
|
-
if (idx < 0) return match;
|
|
537
|
-
const replacement = COMBINED_REPLACEMENTS[idx];
|
|
538
|
-
return replacement !== void 0 ? replacement : match;
|
|
539
|
-
}
|
|
540
|
-
);
|
|
541
|
-
out = out.replace(HIGH_ENTROPY_REGEX, (_match, lead, key, _value) => {
|
|
542
|
-
return `${lead}${key}=[REDACTED:high_entropy_env]`;
|
|
543
|
-
});
|
|
544
|
-
out = out.replace(JSON_CREDENTIAL_REGEX, (_match, keyPrefix, _value, closingQuote) => {
|
|
545
|
-
return `${keyPrefix}[REDACTED:json_credential_key]${closingQuote}`;
|
|
546
|
-
});
|
|
547
|
-
return out;
|
|
548
|
-
}
|
|
549
|
-
/**
|
|
550
|
-
* Recursively scrub every string value in an object/array graph. Secrets can
|
|
551
|
-
* appear under any key — a URL query param, an `authorization` header, an
|
|
552
|
-
* arbitrarily-named nested field — so we don't gate recursion on key names.
|
|
553
|
-
* The per-string `scrub()` fast-path (anchor pre-scan) keeps this cheap: any
|
|
554
|
-
* value without a credential anchor returns immediately without regex work.
|
|
555
|
-
*/
|
|
556
|
-
scrubObject(obj) {
|
|
557
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
558
|
-
const visit = (v) => {
|
|
559
|
-
if (typeof v === "string") return this.scrub(v);
|
|
560
|
-
if (v === null || typeof v !== "object") return v;
|
|
561
|
-
if (seen.has(v)) return v;
|
|
562
|
-
seen.add(v);
|
|
563
|
-
if (Array.isArray(v)) return v.map(visit);
|
|
564
|
-
const out = {};
|
|
565
|
-
for (const [k, val] of Object.entries(v)) {
|
|
566
|
-
out[k] = visit(val);
|
|
567
|
-
}
|
|
568
|
-
return out;
|
|
569
|
-
};
|
|
570
|
-
return visit(obj);
|
|
571
|
-
}
|
|
572
|
-
};
|
|
573
|
-
|
|
574
|
-
// src/utils/pid.ts
|
|
575
|
-
function isPidAlive(pid) {
|
|
576
|
-
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
577
|
-
if (pid === process.pid) return true;
|
|
578
|
-
try {
|
|
579
|
-
process.kill(pid, 0);
|
|
580
|
-
return true;
|
|
581
|
-
} catch (err) {
|
|
582
|
-
const code = err.code;
|
|
583
|
-
if (code === "EPERM") return true;
|
|
584
|
-
return false;
|
|
585
|
-
}
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
// src/session-catalog/store-rebuild.ts
|
|
589
|
-
import * as fs from "node:fs";
|
|
590
|
-
import * as path2 from "node:path";
|
|
591
|
-
|
|
592
|
-
// src/utils/session-scoped-path.ts
|
|
593
|
-
var SESSION_SIDECAR_JSONL_SUFFIXES = [
|
|
594
|
-
".replay.jsonl",
|
|
595
|
-
".audit.jsonl",
|
|
596
|
-
".annotations.jsonl"
|
|
597
|
-
];
|
|
598
|
-
var RESERVED_SESSION_JSONL_NAMES = /* @__PURE__ */ new Set([
|
|
599
|
-
"_index.jsonl",
|
|
600
|
-
"_mailbox.jsonl"
|
|
601
|
-
]);
|
|
602
|
-
function isSessionTranscriptFileName(name) {
|
|
603
|
-
if (!name.endsWith(".jsonl")) return false;
|
|
604
|
-
if (RESERVED_SESSION_JSONL_NAMES.has(name)) return false;
|
|
605
|
-
return !SESSION_SIDECAR_JSONL_SUFFIXES.some((suffix) => name.endsWith(suffix));
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
// src/session-catalog/store-schema.ts
|
|
609
|
-
import { createHash as createHash2, timingSafeEqual } from "node:crypto";
|
|
610
|
-
var SCHEMA_VERSION = 1;
|
|
611
|
-
var MAX_LEASE_MS = 12e4;
|
|
612
|
-
var MAX_RESERVATION_MS = 6e4;
|
|
613
|
-
var MAX_MAINTENANCE_MS = 5 * 6e4;
|
|
614
|
-
var MAX_PAGE = 1e3;
|
|
615
|
-
function hashSecret(secret) {
|
|
616
|
-
return createHash2("sha256").update(secret).digest("hex");
|
|
617
|
-
}
|
|
618
|
-
function secretMatches(secret, expectedHex) {
|
|
619
|
-
const actual = Buffer.from(hashSecret(secret), "hex");
|
|
620
|
-
const expected = Buffer.from(expectedHex, "hex");
|
|
621
|
-
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
622
|
-
}
|
|
623
|
-
function boundedMs(value, fallback, max) {
|
|
624
|
-
return Math.min(max, Math.max(1e3, Number.isFinite(value) ? Math.floor(value) : fallback));
|
|
625
|
-
}
|
|
626
|
-
function parseJson(value) {
|
|
627
|
-
return JSON.parse(value);
|
|
628
|
-
}
|
|
629
|
-
function conflict(message) {
|
|
630
|
-
const error = new Error(message);
|
|
631
|
-
error.name = "SessionOwnershipConflictError";
|
|
632
|
-
return error;
|
|
633
|
-
}
|
|
634
|
-
function assertId(value, label = "session id") {
|
|
635
|
-
if (!value || value.length > 256 || value.includes("\\") || value.startsWith("/") || value.includes("..")) {
|
|
636
|
-
throw new TypeError(`Invalid ${label}`);
|
|
637
|
-
}
|
|
638
|
-
}
|
|
639
|
-
function boundPresenceValue(value, depth) {
|
|
640
|
-
if (typeof value === "string") {
|
|
641
|
-
return value.length <= 6e3 ? value : `${value.slice(0, 5988)}\u2026[truncated]`;
|
|
642
|
-
}
|
|
643
|
-
if (value === null || typeof value !== "object") return value;
|
|
644
|
-
if (depth >= 8) return "[truncated depth]";
|
|
645
|
-
if (Array.isArray(value)) {
|
|
646
|
-
return value.slice(0, 64).map((item) => boundPresenceValue(item, depth + 1));
|
|
647
|
-
}
|
|
648
|
-
const result = {};
|
|
649
|
-
for (const [key, item] of Object.entries(value).slice(0, 64)) {
|
|
650
|
-
result[key] = boundPresenceValue(item, depth + 1);
|
|
651
|
-
}
|
|
652
|
-
return result;
|
|
653
|
-
}
|
|
654
|
-
function configureCatalogDatabase(db) {
|
|
655
|
-
db.exec(
|
|
656
|
-
"PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000; PRAGMA synchronous=NORMAL;"
|
|
657
|
-
);
|
|
658
|
-
}
|
|
659
|
-
function initializeCatalogSchema(db) {
|
|
660
|
-
db.exec(`
|
|
661
|
-
CREATE TABLE IF NOT EXISTS catalog_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
|
662
|
-
CREATE TABLE IF NOT EXISTS sessions (
|
|
663
|
-
session_id TEXT PRIMARY KEY,
|
|
664
|
-
transcript_relative_path TEXT NOT NULL,
|
|
665
|
-
summary_relative_path TEXT NOT NULL,
|
|
666
|
-
summary_json TEXT NOT NULL,
|
|
667
|
-
transcript_size INTEGER NOT NULL DEFAULT 0,
|
|
668
|
-
transcript_mtime_ms REAL NOT NULL DEFAULT 0,
|
|
669
|
-
summary_revision INTEGER NOT NULL DEFAULT 1,
|
|
670
|
-
indexed_at TEXT NOT NULL,
|
|
671
|
-
damaged INTEGER NOT NULL DEFAULT 0
|
|
672
|
-
);
|
|
673
|
-
CREATE TABLE IF NOT EXISTS session_leases (
|
|
674
|
-
session_id TEXT PRIMARY KEY,
|
|
675
|
-
lease_id TEXT NOT NULL UNIQUE,
|
|
676
|
-
lease_secret_hash TEXT NOT NULL,
|
|
677
|
-
owner_instance_id TEXT NOT NULL,
|
|
678
|
-
owner_pid INTEGER NOT NULL,
|
|
679
|
-
owner_started_at TEXT NOT NULL,
|
|
680
|
-
entry_json TEXT NOT NULL,
|
|
681
|
-
agent_revision INTEGER NOT NULL DEFAULT 0,
|
|
682
|
-
status TEXT NOT NULL,
|
|
683
|
-
last_heartbeat_at INTEGER NOT NULL,
|
|
684
|
-
lease_expires_at INTEGER NOT NULL
|
|
685
|
-
);
|
|
686
|
-
CREATE TABLE IF NOT EXISTS resume_reservations (
|
|
687
|
-
reservation_id TEXT PRIMARY KEY,
|
|
688
|
-
target_session_id TEXT NOT NULL UNIQUE,
|
|
689
|
-
requester_instance_id TEXT NOT NULL,
|
|
690
|
-
current_session_id TEXT,
|
|
691
|
-
created_at INTEGER NOT NULL,
|
|
692
|
-
expires_at INTEGER NOT NULL
|
|
693
|
-
);
|
|
694
|
-
CREATE TABLE IF NOT EXISTS maintenance_leases (
|
|
695
|
-
session_id TEXT PRIMARY KEY,
|
|
696
|
-
operation TEXT NOT NULL,
|
|
697
|
-
holder_id TEXT NOT NULL,
|
|
698
|
-
lease_id TEXT NOT NULL UNIQUE,
|
|
699
|
-
acquired_at INTEGER NOT NULL,
|
|
700
|
-
expires_at INTEGER NOT NULL
|
|
701
|
-
);
|
|
702
|
-
CREATE INDEX IF NOT EXISTS idx_sessions_activity ON sessions(indexed_at DESC);
|
|
703
|
-
CREATE INDEX IF NOT EXISTS idx_leases_expiry ON session_leases(lease_expires_at);
|
|
704
|
-
CREATE INDEX IF NOT EXISTS idx_reservations_expiry ON resume_reservations(expires_at);
|
|
705
|
-
CREATE INDEX IF NOT EXISTS idx_maintenance_expiry ON maintenance_leases(expires_at);
|
|
706
|
-
`);
|
|
707
|
-
db.prepare("INSERT INTO catalog_meta(key,value) VALUES (?,?) ON CONFLICT(key) DO NOTHING").run("schema_version", String(SCHEMA_VERSION));
|
|
708
|
-
db.prepare("INSERT INTO catalog_meta(key,value) VALUES (?,?) ON CONFLICT(key) DO NOTHING").run("generation", "0");
|
|
709
|
-
const row = db.prepare("SELECT value FROM catalog_meta WHERE key=?").get("schema_version");
|
|
710
|
-
if (Number(row.value) !== SCHEMA_VERSION)
|
|
711
|
-
throw new Error(`Unsupported session catalog schema ${row.value}`);
|
|
712
|
-
}
|
|
713
|
-
|
|
714
|
-
// src/session-catalog/store-rebuild.ts
|
|
715
|
-
function walkSessionFiles(root, suffix) {
|
|
716
|
-
const result = [];
|
|
717
|
-
const visit = (dir) => {
|
|
718
|
-
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
719
|
-
if (entry.isDirectory()) {
|
|
720
|
-
if (entry.name !== "_cas" && entry.name !== "_trash") visit(path2.join(dir, entry.name));
|
|
721
|
-
} else if (entry.isFile() && entry.name.endsWith(suffix))
|
|
722
|
-
result.push(path2.join(dir, entry.name));
|
|
723
|
-
}
|
|
724
|
-
};
|
|
725
|
-
visit(root);
|
|
726
|
-
return result;
|
|
727
|
-
}
|
|
728
|
-
function summarizeTranscriptFile(transcriptFilePath, id) {
|
|
729
|
-
const lines = fs.readFileSync(transcriptFilePath, "utf8").split(/\r?\n/);
|
|
730
|
-
let start;
|
|
731
|
-
let endedAt;
|
|
732
|
-
let lastActivityAt;
|
|
733
|
-
let messageCount = 0;
|
|
734
|
-
let iterationCount = 0;
|
|
735
|
-
let toolCallCount = 0;
|
|
736
|
-
let compactionCount = 0;
|
|
737
|
-
let tokenTotal = 0;
|
|
738
|
-
for (const line of lines) {
|
|
739
|
-
if (!line) continue;
|
|
740
|
-
let event;
|
|
741
|
-
try {
|
|
742
|
-
event = parseJson(line);
|
|
743
|
-
} catch {
|
|
744
|
-
continue;
|
|
745
|
-
}
|
|
746
|
-
lastActivityAt = event.ts;
|
|
747
|
-
if (event.type === "session_start") start = event;
|
|
748
|
-
if (event.type === "session_end") endedAt = event.ts;
|
|
749
|
-
if (event.type === "message_appended" && (event.message.role === "user" || event.message.role === "assistant"))
|
|
750
|
-
messageCount++;
|
|
751
|
-
if (event.type === "llm_response") {
|
|
752
|
-
iterationCount++;
|
|
753
|
-
tokenTotal += event.usage.input + event.usage.output + (event.usage.cacheRead ?? 0) + (event.usage.cacheWrite ?? 0);
|
|
754
|
-
}
|
|
755
|
-
if (event.type === "tool_call_end") toolCallCount++;
|
|
756
|
-
if (event.type === "compaction") compactionCount++;
|
|
757
|
-
}
|
|
758
|
-
if (!start) throw new Error("missing session_start");
|
|
759
|
-
return {
|
|
760
|
-
id,
|
|
761
|
-
title: id,
|
|
762
|
-
startedAt: start.ts,
|
|
763
|
-
...endedAt ? { endedAt } : {},
|
|
764
|
-
model: start.model,
|
|
765
|
-
provider: start.provider,
|
|
766
|
-
tokenTotal,
|
|
767
|
-
...lastActivityAt ? { lastActivityAt } : {},
|
|
768
|
-
messageCount,
|
|
769
|
-
iterationCount,
|
|
770
|
-
toolCallCount,
|
|
771
|
-
compactionCount
|
|
772
|
-
};
|
|
773
|
-
}
|
|
774
|
-
function rebuildCatalogIndex(db, sessionsDir, containedPathFn, transactionFn, bumpGenerationFn) {
|
|
775
|
-
const summaries = walkSessionFiles(sessionsDir, ".summary.json");
|
|
776
|
-
const transcripts = walkSessionFiles(sessionsDir, ".jsonl").filter(
|
|
777
|
-
(file) => isSessionTranscriptFileName(path2.basename(file))
|
|
778
|
-
);
|
|
779
|
-
const ids = /* @__PURE__ */ new Set();
|
|
780
|
-
for (const file of [...summaries, ...transcripts]) {
|
|
781
|
-
const relative3 = path2.relative(sessionsDir, file).replaceAll("\\", "/");
|
|
782
|
-
ids.add(relative3.replace(/\.summary\.json$|\.jsonl$/, ""));
|
|
783
|
-
}
|
|
784
|
-
let indexed = 0;
|
|
785
|
-
let damaged = 0;
|
|
786
|
-
transactionFn(() => {
|
|
787
|
-
db.prepare("DELETE FROM sessions").run();
|
|
788
|
-
for (const id of ids) {
|
|
789
|
-
try {
|
|
790
|
-
const summaryFile = containedPathFn(`${id}.summary.json`);
|
|
791
|
-
const summary = fs.existsSync(summaryFile) ? parseJson(fs.readFileSync(summaryFile, "utf8")) : summarizeTranscriptFile(containedPathFn(`${id}.jsonl`), id);
|
|
792
|
-
if (!summary || summary.id !== id) throw new Error("summary identity mismatch");
|
|
793
|
-
const transcript = containedPathFn(`${id}.jsonl`);
|
|
794
|
-
const stat = fs.existsSync(transcript) ? fs.statSync(transcript) : void 0;
|
|
795
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
796
|
-
db.prepare(
|
|
797
|
-
"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)"
|
|
798
|
-
).run(
|
|
799
|
-
id,
|
|
800
|
-
`${id}.jsonl`,
|
|
801
|
-
`${id}.summary.json`,
|
|
802
|
-
JSON.stringify(summary),
|
|
803
|
-
stat?.size ?? 0,
|
|
804
|
-
stat?.mtimeMs ?? 0,
|
|
805
|
-
1,
|
|
806
|
-
now
|
|
807
|
-
);
|
|
808
|
-
indexed++;
|
|
809
|
-
} catch {
|
|
810
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
811
|
-
const fallback = {
|
|
812
|
-
id,
|
|
813
|
-
title: id,
|
|
814
|
-
startedAt: now,
|
|
815
|
-
model: "",
|
|
816
|
-
provider: "",
|
|
817
|
-
tokenTotal: 0
|
|
818
|
-
};
|
|
819
|
-
db.prepare(
|
|
820
|
-
"INSERT INTO sessions(session_id,transcript_relative_path,summary_relative_path,summary_json,summary_revision,indexed_at,damaged) VALUES (?,?,?,?,1,?,1)"
|
|
821
|
-
).run(id, `${id}.jsonl`, `${id}.summary.json`, JSON.stringify(fallback), now);
|
|
822
|
-
damaged++;
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
db.prepare(
|
|
826
|
-
"INSERT INTO catalog_meta(key,value) VALUES ('last_reconciliation',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value"
|
|
827
|
-
).run((/* @__PURE__ */ new Date()).toISOString());
|
|
828
|
-
bumpGenerationFn();
|
|
829
|
-
});
|
|
830
|
-
return { indexed, damaged };
|
|
831
|
-
}
|
|
832
|
-
|
|
833
|
-
// src/session-catalog/store.ts
|
|
834
|
-
var SessionCatalogStore = class {
|
|
835
|
-
constructor(projectDir) {
|
|
836
|
-
this.projectDir = projectDir;
|
|
837
|
-
this.sessionsDir = path3.join(projectDir, "sessions");
|
|
838
|
-
fs2.mkdirSync(this.sessionsDir, { recursive: true, mode: 448 });
|
|
839
|
-
this.databasePath = path3.join(this.sessionsDir, "catalog.sqlite");
|
|
840
|
-
const Database = loadDatabaseSync();
|
|
841
|
-
this.db = new Database(this.databasePath);
|
|
842
|
-
try {
|
|
843
|
-
this.configureDatabase();
|
|
844
|
-
this.initialize();
|
|
845
|
-
} catch (error) {
|
|
846
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
847
|
-
if (!/SQLITE_CORRUPT|SQLITE_NOTADB|database disk image is malformed|file is not a database/i.test(
|
|
848
|
-
message
|
|
849
|
-
)) {
|
|
850
|
-
this.db.close();
|
|
851
|
-
throw error;
|
|
852
|
-
}
|
|
853
|
-
this.db.close();
|
|
854
|
-
const quarantine = `${this.databasePath}.corrupt-${Date.now()}`;
|
|
855
|
-
try {
|
|
856
|
-
fs2.renameSync(this.databasePath, quarantine);
|
|
857
|
-
} catch {
|
|
858
|
-
}
|
|
859
|
-
for (const suffix of ["-wal", "-shm"]) {
|
|
860
|
-
try {
|
|
861
|
-
fs2.renameSync(`${this.databasePath}${suffix}`, `${quarantine}${suffix}`);
|
|
862
|
-
} catch {
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
this.db = new Database(this.databasePath);
|
|
866
|
-
this.configureDatabase();
|
|
867
|
-
this.initialize();
|
|
868
|
-
}
|
|
869
|
-
this.reapExpired();
|
|
870
|
-
const rowCount = Number(
|
|
871
|
-
this.db.prepare("SELECT COUNT(*) AS count FROM sessions").get().count
|
|
872
|
-
);
|
|
873
|
-
if (rowCount === 0 && walkSessionFiles(this.sessionsDir, ".jsonl").some((file) => !file.endsWith("_index.jsonl"))) {
|
|
874
|
-
this.rebuildCatalog();
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
projectDir;
|
|
878
|
-
databasePath;
|
|
879
|
-
sessionsDir;
|
|
880
|
-
db;
|
|
881
|
-
scrubber = new DefaultSecretScrubber();
|
|
882
|
-
configureDatabase() {
|
|
883
|
-
configureCatalogDatabase(this.db);
|
|
884
|
-
}
|
|
885
|
-
close() {
|
|
886
|
-
this.db.close();
|
|
887
|
-
}
|
|
888
|
-
initialize() {
|
|
889
|
-
initializeCatalogSchema(this.db);
|
|
890
|
-
}
|
|
891
|
-
transaction(run) {
|
|
892
|
-
this.db.exec("BEGIN IMMEDIATE");
|
|
893
|
-
try {
|
|
894
|
-
const result = run();
|
|
895
|
-
this.db.exec("COMMIT");
|
|
896
|
-
return result;
|
|
897
|
-
} catch (error) {
|
|
898
|
-
this.db.exec("ROLLBACK");
|
|
899
|
-
throw error;
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
bumpGeneration() {
|
|
903
|
-
this.db.prepare("UPDATE catalog_meta SET value=CAST(value AS INTEGER)+1 WHERE key='generation'").run();
|
|
904
|
-
return this.generation();
|
|
905
|
-
}
|
|
906
|
-
generation() {
|
|
907
|
-
const row = this.db.prepare("SELECT value FROM catalog_meta WHERE key='generation'").get();
|
|
908
|
-
return Number(row.value) || 0;
|
|
909
|
-
}
|
|
910
|
-
reapExpired(now = Date.now()) {
|
|
911
|
-
this.db.prepare("DELETE FROM resume_reservations WHERE expires_at<=?").run(now);
|
|
912
|
-
this.db.prepare("DELETE FROM maintenance_leases WHERE expires_at<=?").run(now);
|
|
913
|
-
const rows = this.db.prepare("SELECT * FROM session_leases WHERE lease_expires_at<=?").all(now);
|
|
914
|
-
for (const row of rows) {
|
|
915
|
-
if (!isPidAlive(row.owner_pid)) {
|
|
916
|
-
this.db.prepare("DELETE FROM session_leases WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
|
|
917
|
-
} else if (row.status !== "lost") {
|
|
918
|
-
this.db.prepare("UPDATE session_leases SET status='lost' WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
|
|
919
|
-
}
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
maintenanceExists(sessionId) {
|
|
923
|
-
return Boolean(
|
|
924
|
-
this.db.prepare("SELECT 1 AS yes FROM maintenance_leases WHERE session_id=? AND expires_at>?").get(sessionId, Date.now())
|
|
925
|
-
);
|
|
926
|
-
}
|
|
927
|
-
leaseRow(sessionId) {
|
|
928
|
-
return this.db.prepare("SELECT * FROM session_leases WHERE session_id=?").get(sessionId);
|
|
929
|
-
}
|
|
930
|
-
foreignLiveLease(sessionId, callerPid = process.pid) {
|
|
931
|
-
const live = this.leaseRow(sessionId);
|
|
932
|
-
return Boolean(live) && live.owner_pid !== callerPid;
|
|
933
|
-
}
|
|
934
|
-
verifyCredential(credential) {
|
|
935
|
-
assertId(credential.sessionId);
|
|
936
|
-
const row = this.leaseRow(credential.sessionId);
|
|
937
|
-
if (!row || row.lease_id !== credential.leaseId || row.owner_instance_id !== credential.ownerInstanceId || !secretMatches(credential.leaseSecret, row.lease_secret_hash)) {
|
|
938
|
-
throw conflict(`Session ${credential.sessionId} lease proof is invalid or no longer owned`);
|
|
939
|
-
}
|
|
940
|
-
return row;
|
|
941
|
-
}
|
|
942
|
-
createLease(entry, ownerInstanceId, leaseMs) {
|
|
943
|
-
assertId(entry.sessionId);
|
|
944
|
-
if (!ownerInstanceId || ownerInstanceId.length > 256)
|
|
945
|
-
throw new TypeError("Invalid owner instance id");
|
|
946
|
-
if (!Number.isSafeInteger(entry.pid) || entry.pid <= 0)
|
|
947
|
-
throw new TypeError("Invalid owner pid");
|
|
948
|
-
const now = Date.now();
|
|
949
|
-
const leaseId = randomUUID();
|
|
950
|
-
const leaseSecret = randomBytes(32).toString("hex");
|
|
951
|
-
const expiresAt = now + boundedMs(leaseMs, SESSION_CATALOG_DEFAULT_LEASE_MS, MAX_LEASE_MS);
|
|
952
|
-
this.db.prepare(`INSERT INTO session_leases(
|
|
953
|
-
session_id,lease_id,lease_secret_hash,owner_instance_id,owner_pid,owner_started_at,
|
|
954
|
-
entry_json,agent_revision,status,last_heartbeat_at,lease_expires_at
|
|
955
|
-
) VALUES (?,?,?,?,?,?,?,?,?,?,?)`).run(
|
|
956
|
-
entry.sessionId,
|
|
957
|
-
leaseId,
|
|
958
|
-
hashSecret(leaseSecret),
|
|
959
|
-
ownerInstanceId,
|
|
960
|
-
entry.pid,
|
|
961
|
-
entry.startedAt,
|
|
962
|
-
JSON.stringify(entry),
|
|
963
|
-
0,
|
|
964
|
-
entry.status,
|
|
965
|
-
now,
|
|
966
|
-
expiresAt
|
|
967
|
-
);
|
|
968
|
-
return { sessionId: entry.sessionId, leaseId, leaseSecret, ownerInstanceId, expiresAt };
|
|
969
|
-
}
|
|
970
|
-
claimNew(entry, ownerInstanceId, leaseMs) {
|
|
971
|
-
return this.transaction(() => {
|
|
972
|
-
this.reapExpired();
|
|
973
|
-
const existing = this.leaseRow(entry.sessionId);
|
|
974
|
-
if (existing)
|
|
975
|
-
throw conflict(
|
|
976
|
-
`Session ${entry.sessionId} is already open in another running wstack (pid ${existing.owner_pid}).`
|
|
977
|
-
);
|
|
978
|
-
if (this.maintenanceExists(entry.sessionId))
|
|
979
|
-
throw conflict(`Session ${entry.sessionId} is under maintenance`);
|
|
980
|
-
const reserved = this.db.prepare(
|
|
981
|
-
"SELECT 1 AS yes FROM resume_reservations WHERE target_session_id=? AND expires_at>?"
|
|
982
|
-
).get(entry.sessionId, Date.now());
|
|
983
|
-
if (reserved) throw conflict(`Session ${entry.sessionId} is reserved for resume`);
|
|
984
|
-
const credential = this.createLease(entry, ownerInstanceId, leaseMs);
|
|
985
|
-
this.bumpGeneration();
|
|
986
|
-
return credential;
|
|
987
|
-
});
|
|
988
|
-
}
|
|
989
|
-
reconnectLease(credential) {
|
|
990
|
-
return this.transaction(() => {
|
|
991
|
-
const row = this.verifyCredential(credential);
|
|
992
|
-
if (row.owner_pid !== process.pid && !isPidAlive(row.owner_pid))
|
|
993
|
-
throw conflict(`Session ${credential.sessionId} owner process is no longer alive`);
|
|
994
|
-
const expiresAt = Date.now() + SESSION_CATALOG_DEFAULT_LEASE_MS;
|
|
995
|
-
this.db.prepare(
|
|
996
|
-
"UPDATE session_leases SET lease_expires_at=?,last_heartbeat_at=?,status=? WHERE session_id=? AND lease_id=?"
|
|
997
|
-
).run(
|
|
998
|
-
expiresAt,
|
|
999
|
-
Date.now(),
|
|
1000
|
-
row.status === "lost" ? "idle" : row.status,
|
|
1001
|
-
row.session_id,
|
|
1002
|
-
row.lease_id
|
|
1003
|
-
);
|
|
1004
|
-
return { ...credential, expiresAt };
|
|
1005
|
-
});
|
|
1006
|
-
}
|
|
1007
|
-
reserveResume(targetSessionId, requesterInstanceId, currentSessionId, reservationMs) {
|
|
1008
|
-
assertId(targetSessionId);
|
|
1009
|
-
return this.transaction(() => {
|
|
1010
|
-
this.reapExpired();
|
|
1011
|
-
const live = this.leaseRow(targetSessionId);
|
|
1012
|
-
if (live)
|
|
1013
|
-
throw conflict(
|
|
1014
|
-
`Session ${targetSessionId} is already open in another running wstack (pid ${live.owner_pid}).`
|
|
1015
|
-
);
|
|
1016
|
-
if (this.maintenanceExists(targetSessionId))
|
|
1017
|
-
throw conflict(`Session ${targetSessionId} is under maintenance`);
|
|
1018
|
-
const catalog = this.db.prepare("SELECT 1 AS yes FROM sessions WHERE session_id=?").get(targetSessionId);
|
|
1019
|
-
if (!catalog && !fs2.existsSync(this.containedPath(`${targetSessionId}.jsonl`)))
|
|
1020
|
-
throw new Error(`Session not found: ${targetSessionId}`);
|
|
1021
|
-
const reservationId = randomUUID();
|
|
1022
|
-
const now = Date.now();
|
|
1023
|
-
const expiresAt = now + boundedMs(reservationMs, SESSION_CATALOG_DEFAULT_RESERVATION_MS, MAX_RESERVATION_MS);
|
|
1024
|
-
try {
|
|
1025
|
-
this.db.prepare(
|
|
1026
|
-
"INSERT INTO resume_reservations(reservation_id,target_session_id,requester_instance_id,current_session_id,created_at,expires_at) VALUES (?,?,?,?,?,?)"
|
|
1027
|
-
).run(
|
|
1028
|
-
reservationId,
|
|
1029
|
-
targetSessionId,
|
|
1030
|
-
requesterInstanceId,
|
|
1031
|
-
currentSessionId ?? null,
|
|
1032
|
-
now,
|
|
1033
|
-
expiresAt
|
|
1034
|
-
);
|
|
1035
|
-
} catch {
|
|
1036
|
-
throw conflict(`Session ${targetSessionId} is already reserved for resume`);
|
|
1037
|
-
}
|
|
1038
|
-
this.bumpGeneration();
|
|
1039
|
-
return { reservationId, targetSessionId, requesterInstanceId, expiresAt };
|
|
1040
|
-
});
|
|
1041
|
-
}
|
|
1042
|
-
activateReservation(reservation, entry, leaseMs) {
|
|
1043
|
-
return this.transaction(() => {
|
|
1044
|
-
this.reapExpired();
|
|
1045
|
-
const row = this.db.prepare("SELECT * FROM resume_reservations WHERE reservation_id=?").get(reservation.reservationId);
|
|
1046
|
-
if (!row || row.target_session_id !== reservation.targetSessionId || row.requester_instance_id !== reservation.requesterInstanceId || row.expires_at <= Date.now())
|
|
1047
|
-
throw conflict("Resume reservation expired or is not owned by this requester");
|
|
1048
|
-
if (entry.sessionId !== row.target_session_id)
|
|
1049
|
-
throw new TypeError("Reservation target and session entry differ");
|
|
1050
|
-
if (this.leaseRow(entry.sessionId) || this.maintenanceExists(entry.sessionId))
|
|
1051
|
-
throw conflict(`Session ${entry.sessionId} can no longer be activated`);
|
|
1052
|
-
const credential = this.createLease(entry, reservation.requesterInstanceId, leaseMs);
|
|
1053
|
-
this.db.prepare("DELETE FROM resume_reservations WHERE reservation_id=?").run(row.reservation_id);
|
|
1054
|
-
this.bumpGeneration();
|
|
1055
|
-
return credential;
|
|
1056
|
-
});
|
|
1057
|
-
}
|
|
1058
|
-
cancelReservation(reservationId, requesterInstanceId) {
|
|
1059
|
-
this.db.prepare("DELETE FROM resume_reservations WHERE reservation_id=? AND requester_instance_id=?").run(reservationId, requesterInstanceId);
|
|
1060
|
-
}
|
|
1061
|
-
heartbeat(credential, status) {
|
|
1062
|
-
return this.transaction(() => {
|
|
1063
|
-
const row = this.verifyCredential(credential);
|
|
1064
|
-
const expiresAt = Date.now() + SESSION_CATALOG_DEFAULT_LEASE_MS;
|
|
1065
|
-
const nextStatus = status ?? (row.status === "closing" ? "closing" : row.status === "lost" ? "idle" : row.status);
|
|
1066
|
-
const entry = parseJson(row.entry_json);
|
|
1067
|
-
entry.status = nextStatus;
|
|
1068
|
-
entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1069
|
-
this.db.prepare(
|
|
1070
|
-
"UPDATE session_leases SET status=?,entry_json=?,last_heartbeat_at=?,lease_expires_at=? WHERE session_id=? AND lease_id=?"
|
|
1071
|
-
).run(
|
|
1072
|
-
nextStatus,
|
|
1073
|
-
JSON.stringify(entry),
|
|
1074
|
-
Date.now(),
|
|
1075
|
-
expiresAt,
|
|
1076
|
-
row.session_id,
|
|
1077
|
-
row.lease_id
|
|
1078
|
-
);
|
|
1079
|
-
return { ...credential, expiresAt };
|
|
1080
|
-
});
|
|
1081
|
-
}
|
|
1082
|
-
publishAgents(credential, revision, agents) {
|
|
1083
|
-
if (!Number.isSafeInteger(revision) || revision < 0)
|
|
1084
|
-
throw new TypeError("Invalid presence revision");
|
|
1085
|
-
if (!Array.isArray(agents) || agents.length > SESSION_CATALOG_MAX_AGENTS)
|
|
1086
|
-
throw new TypeError(`Agent snapshot exceeds ${SESSION_CATALOG_MAX_AGENTS} agents`);
|
|
1087
|
-
const boundedAgents = boundPresenceValue(
|
|
1088
|
-
this.scrubber.scrubObject(agents),
|
|
1089
|
-
0
|
|
1090
|
-
);
|
|
1091
|
-
const encoded = JSON.stringify(boundedAgents);
|
|
1092
|
-
if (encoded.length > 1024 * 1024) throw new TypeError("Agent snapshot exceeds 1 MiB");
|
|
1093
|
-
return this.transaction(() => {
|
|
1094
|
-
const row = this.verifyCredential(credential);
|
|
1095
|
-
if (revision <= row.agent_revision) return { accepted: false, revision: row.agent_revision };
|
|
1096
|
-
const entry = parseJson(row.entry_json);
|
|
1097
|
-
entry.agents = boundedAgents;
|
|
1098
|
-
entry.agentCount = boundedAgents.length;
|
|
1099
|
-
entry.status = boundedAgents.some((agent) => agent.status !== "idle") ? "active" : "idle";
|
|
1100
|
-
entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1101
|
-
this.db.prepare(
|
|
1102
|
-
"UPDATE session_leases SET entry_json=?,agent_revision=?,status=?,last_heartbeat_at=? WHERE session_id=? AND lease_id=?"
|
|
1103
|
-
).run(
|
|
1104
|
-
JSON.stringify(entry),
|
|
1105
|
-
revision,
|
|
1106
|
-
entry.status,
|
|
1107
|
-
Date.now(),
|
|
1108
|
-
row.session_id,
|
|
1109
|
-
row.lease_id
|
|
1110
|
-
);
|
|
1111
|
-
this.bumpGeneration();
|
|
1112
|
-
return { accepted: true, revision };
|
|
1113
|
-
});
|
|
1114
|
-
}
|
|
1115
|
-
markClosing(credential) {
|
|
1116
|
-
const row = this.verifyCredential(credential);
|
|
1117
|
-
const entry = parseJson(row.entry_json);
|
|
1118
|
-
entry.status = "closing";
|
|
1119
|
-
entry.lastHeartbeatAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1120
|
-
this.db.prepare(
|
|
1121
|
-
"UPDATE session_leases SET status='closing',entry_json=?,last_heartbeat_at=? WHERE session_id=? AND lease_id=?"
|
|
1122
|
-
).run(JSON.stringify(entry), Date.now(), row.session_id, row.lease_id);
|
|
1123
|
-
this.bumpGeneration();
|
|
1124
|
-
}
|
|
1125
|
-
release(credential) {
|
|
1126
|
-
this.transaction(() => {
|
|
1127
|
-
const row = this.verifyCredential(credential);
|
|
1128
|
-
this.db.prepare("DELETE FROM session_leases WHERE session_id=? AND lease_id=?").run(row.session_id, row.lease_id);
|
|
1129
|
-
this.bumpGeneration();
|
|
1130
|
-
});
|
|
1131
|
-
}
|
|
1132
|
-
listLive() {
|
|
1133
|
-
this.reapExpired();
|
|
1134
|
-
return this.db.prepare(
|
|
1135
|
-
"SELECT entry_json,status,last_heartbeat_at FROM session_leases ORDER BY last_heartbeat_at DESC"
|
|
1136
|
-
).all().map((row) => ({
|
|
1137
|
-
...parseJson(row.entry_json),
|
|
1138
|
-
status: row.status,
|
|
1139
|
-
lastHeartbeatAt: new Date(row.last_heartbeat_at).toISOString()
|
|
1140
|
-
}));
|
|
1141
|
-
}
|
|
1142
|
-
getLive(sessionId) {
|
|
1143
|
-
return this.listLive().find((entry) => entry.sessionId === sessionId) ?? null;
|
|
1144
|
-
}
|
|
1145
|
-
containedPath(relative3) {
|
|
1146
|
-
assertId(relative3.replace(/\.(jsonl|summary\.json)$/, ""), "session path");
|
|
1147
|
-
const root = path3.resolve(this.sessionsDir);
|
|
1148
|
-
const candidate = path3.resolve(root, relative3);
|
|
1149
|
-
const prefix = `${root}${path3.sep}`;
|
|
1150
|
-
if (candidate !== root && !(process.platform === "win32" ? candidate.toLowerCase().startsWith(prefix.toLowerCase()) : candidate.startsWith(prefix)))
|
|
1151
|
-
throw new TypeError("Session path escapes sessions directory");
|
|
1152
|
-
return candidate;
|
|
1153
|
-
}
|
|
1154
|
-
upsertSummary(summary, transcriptRelativePath = `${summary.id}.jsonl`, summaryRelativePath = `${summary.id}.summary.json`) {
|
|
1155
|
-
assertId(summary.id);
|
|
1156
|
-
summary = this.scrubber.scrubObject(summary);
|
|
1157
|
-
const normalizedTranscript = transcriptRelativePath.replaceAll("\\", "/");
|
|
1158
|
-
const normalizedSummary = summaryRelativePath.replaceAll("\\", "/");
|
|
1159
|
-
if (normalizedTranscript !== `${summary.id}.jsonl` || normalizedSummary !== `${summary.id}.summary.json`) {
|
|
1160
|
-
throw new TypeError("Session catalog paths must match the canonical session identity");
|
|
1161
|
-
}
|
|
1162
|
-
transcriptRelativePath = normalizedTranscript;
|
|
1163
|
-
summaryRelativePath = normalizedSummary;
|
|
1164
|
-
const transcript = this.containedPath(transcriptRelativePath);
|
|
1165
|
-
const stat = fs2.existsSync(transcript) ? fs2.statSync(transcript) : void 0;
|
|
1166
|
-
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
1167
|
-
return this.transaction(() => {
|
|
1168
|
-
const prior = this.db.prepare("SELECT summary_revision FROM sessions WHERE session_id=?").get(summary.id);
|
|
1169
|
-
const revision = (prior?.summary_revision ?? 0) + 1;
|
|
1170
|
-
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)
|
|
1171
|
-
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(
|
|
1172
|
-
summary.id,
|
|
1173
|
-
transcriptRelativePath,
|
|
1174
|
-
summaryRelativePath,
|
|
1175
|
-
JSON.stringify(summary),
|
|
1176
|
-
stat?.size ?? 0,
|
|
1177
|
-
stat?.mtimeMs ?? 0,
|
|
1178
|
-
revision,
|
|
1179
|
-
now
|
|
1180
|
-
);
|
|
1181
|
-
this.bumpGeneration();
|
|
1182
|
-
return {
|
|
1183
|
-
...summary,
|
|
1184
|
-
transcriptRelativePath,
|
|
1185
|
-
summaryRelativePath,
|
|
1186
|
-
transcriptSize: stat?.size ?? 0,
|
|
1187
|
-
transcriptMtimeMs: stat?.mtimeMs ?? 0,
|
|
1188
|
-
summaryRevision: revision,
|
|
1189
|
-
indexedAt: now,
|
|
1190
|
-
damaged: false
|
|
1191
|
-
};
|
|
1192
|
-
});
|
|
1193
|
-
}
|
|
1194
|
-
catalogRecord(row) {
|
|
1195
|
-
return {
|
|
1196
|
-
...parseJson(row.summary_json),
|
|
1197
|
-
transcriptRelativePath: row.transcript_relative_path,
|
|
1198
|
-
summaryRelativePath: row.summary_relative_path,
|
|
1199
|
-
transcriptSize: row.transcript_size,
|
|
1200
|
-
transcriptMtimeMs: row.transcript_mtime_ms,
|
|
1201
|
-
summaryRevision: row.summary_revision,
|
|
1202
|
-
indexedAt: row.indexed_at,
|
|
1203
|
-
damaged: row.damaged !== 0
|
|
1204
|
-
};
|
|
1205
|
-
}
|
|
1206
|
-
listCatalog(criteria = {}) {
|
|
1207
|
-
const requestedLimit = criteria.limit ?? 100;
|
|
1208
|
-
if (!Number.isFinite(requestedLimit)) throw new TypeError("Invalid session catalog limit");
|
|
1209
|
-
const bounded = Math.min(MAX_PAGE, Math.max(1, Math.floor(requestedLimit)));
|
|
1210
|
-
const clauses = [];
|
|
1211
|
-
const values = [];
|
|
1212
|
-
const jsonText = (field) => `CASE WHEN json_valid(summary_json) THEN json_extract(summary_json,'$.${field}') END`;
|
|
1213
|
-
const literalLike = (value) => `%${value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_")}%`;
|
|
1214
|
-
const search = criteria.search?.trim();
|
|
1215
|
-
if (search) {
|
|
1216
|
-
const pattern = literalLike(search);
|
|
1217
|
-
clauses.push(
|
|
1218
|
-
`(session_id LIKE ? ESCAPE '\\' OR ${jsonText("title")} LIKE ? ESCAPE '\\' OR ${jsonText("name")} LIKE ? ESCAPE '\\')`
|
|
1219
|
-
);
|
|
1220
|
-
values.push(pattern, pattern, pattern);
|
|
1221
|
-
}
|
|
1222
|
-
if (criteria.since) {
|
|
1223
|
-
clauses.push(`${jsonText("startedAt")}>=?`);
|
|
1224
|
-
values.push(criteria.since);
|
|
1225
|
-
}
|
|
1226
|
-
if (criteria.until) {
|
|
1227
|
-
clauses.push(`${jsonText("startedAt")}<=?`);
|
|
1228
|
-
values.push(criteria.until);
|
|
1229
|
-
}
|
|
1230
|
-
if (criteria.provider) {
|
|
1231
|
-
clauses.push(`${jsonText("provider")}=?`);
|
|
1232
|
-
values.push(criteria.provider);
|
|
1233
|
-
}
|
|
1234
|
-
if (criteria.model) {
|
|
1235
|
-
clauses.push(`${jsonText("model")}=?`);
|
|
1236
|
-
values.push(criteria.model);
|
|
1237
|
-
}
|
|
1238
|
-
if (criteria.minTokens !== void 0) {
|
|
1239
|
-
if (!Number.isFinite(criteria.minTokens)) throw new TypeError("Invalid minimum token count");
|
|
1240
|
-
clauses.push(`CAST(COALESCE(${jsonText("tokenTotal")},0) AS REAL)>=?`);
|
|
1241
|
-
values.push(criteria.minTokens);
|
|
1242
|
-
}
|
|
1243
|
-
if (criteria.titleContains) {
|
|
1244
|
-
clauses.push(`${jsonText("title")} LIKE ? ESCAPE '\\'`);
|
|
1245
|
-
values.push(literalLike(criteria.titleContains.toLocaleLowerCase()));
|
|
1246
|
-
}
|
|
1247
|
-
const where = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : "";
|
|
1248
|
-
const rows = this.db.prepare(
|
|
1249
|
-
`SELECT * FROM sessions${where} ORDER BY COALESCE(${jsonText("lastActivityAt")},${jsonText("endedAt")},${jsonText("startedAt")}) DESC,${jsonText("startedAt")} DESC,session_id ASC LIMIT ?`
|
|
1250
|
-
).all(...values, bounded);
|
|
1251
|
-
return rows.map((row) => this.catalogRecord(row));
|
|
1252
|
-
}
|
|
1253
|
-
getSummary(sessionId) {
|
|
1254
|
-
const row = this.db.prepare("SELECT * FROM sessions WHERE session_id=?").get(sessionId);
|
|
1255
|
-
return row ? this.catalogRecord(row) : null;
|
|
1256
|
-
}
|
|
1257
|
-
resolveId(query) {
|
|
1258
|
-
const normalized = query.trim();
|
|
1259
|
-
if (!normalized) throw new Error("Session not found: (empty query)");
|
|
1260
|
-
if (this.getSummary(normalized)) return normalized;
|
|
1261
|
-
const rows = this.db.prepare(
|
|
1262
|
-
"SELECT session_id FROM sessions WHERE session_id LIKE ? OR session_id LIKE ? LIMIT 3"
|
|
1263
|
-
).all(`%/${normalized}`, `${normalized}%`);
|
|
1264
|
-
const ids = [...new Set(rows.map((row) => row.session_id))];
|
|
1265
|
-
if (ids.length === 1) return ids[0];
|
|
1266
|
-
if (ids.length === 0) throw new Error(`Session not found: ${query}`);
|
|
1267
|
-
throw new Error(`Ambiguous session id "${query}": ${ids.join(", ")}`);
|
|
1268
|
-
}
|
|
1269
|
-
async rename(sessionId, name) {
|
|
1270
|
-
const current = this.getSummary(this.resolveId(sessionId));
|
|
1271
|
-
if (!current) throw new Error(`Session not found: ${sessionId}`);
|
|
1272
|
-
const trimmed = name.trim();
|
|
1273
|
-
const summary = { ...current };
|
|
1274
|
-
for (const key of [
|
|
1275
|
-
"transcriptRelativePath",
|
|
1276
|
-
"summaryRelativePath",
|
|
1277
|
-
"transcriptSize",
|
|
1278
|
-
"transcriptMtimeMs",
|
|
1279
|
-
"summaryRevision",
|
|
1280
|
-
"indexedAt",
|
|
1281
|
-
"damaged"
|
|
1282
|
-
])
|
|
1283
|
-
delete summary[key];
|
|
1284
|
-
const previous = { ...summary };
|
|
1285
|
-
if (trimmed) summary.name = this.scrubber.scrub(trimmed).slice(0, 500);
|
|
1286
|
-
else delete summary.name;
|
|
1287
|
-
const summaryPath = this.containedPath(current.summaryRelativePath);
|
|
1288
|
-
fs2.mkdirSync(path3.dirname(summaryPath), { recursive: true, mode: 448 });
|
|
1289
|
-
await atomicWrite(summaryPath, `${JSON.stringify(summary)}
|
|
1290
|
-
`, { mode: 384 });
|
|
1291
|
-
try {
|
|
1292
|
-
return this.upsertSummary(
|
|
1293
|
-
summary,
|
|
1294
|
-
current.transcriptRelativePath,
|
|
1295
|
-
current.summaryRelativePath
|
|
1296
|
-
);
|
|
1297
|
-
} catch (error) {
|
|
1298
|
-
await atomicWrite(summaryPath, `${JSON.stringify(previous)}
|
|
1299
|
-
`, { mode: 384 }).catch(
|
|
1300
|
-
() => void 0
|
|
1301
|
-
);
|
|
1302
|
-
throw error;
|
|
1303
|
-
}
|
|
1304
|
-
}
|
|
1305
|
-
acquireMaintenance(sessionId, operation, holderId, leaseMs, holderPid) {
|
|
1306
|
-
assertId(sessionId);
|
|
1307
|
-
return this.transaction(() => {
|
|
1308
|
-
this.reapExpired();
|
|
1309
|
-
const live = this.leaseRow(sessionId);
|
|
1310
|
-
if (live && (operation === "delete" || this.foreignLiveLease(sessionId, holderPid))) {
|
|
1311
|
-
throw conflict(`Session ${sessionId} is live`);
|
|
1312
|
-
}
|
|
1313
|
-
const reservation = this.db.prepare(
|
|
1314
|
-
"SELECT 1 AS yes FROM resume_reservations WHERE target_session_id=? AND expires_at>?"
|
|
1315
|
-
).get(sessionId, Date.now());
|
|
1316
|
-
if (reservation) throw conflict(`Session ${sessionId} is reserved for resume`);
|
|
1317
|
-
const leaseId = randomUUID();
|
|
1318
|
-
const now = Date.now();
|
|
1319
|
-
const expiresAt = now + boundedMs(leaseMs, 6e4, MAX_MAINTENANCE_MS);
|
|
1320
|
-
try {
|
|
1321
|
-
this.db.prepare(
|
|
1322
|
-
"INSERT INTO maintenance_leases(session_id,operation,holder_id,lease_id,acquired_at,expires_at) VALUES (?,?,?,?,?,?)"
|
|
1323
|
-
).run(sessionId, operation, holderId, leaseId, now, expiresAt);
|
|
1324
|
-
} catch {
|
|
1325
|
-
throw conflict(`Session ${sessionId} already has maintenance in progress`);
|
|
1326
|
-
}
|
|
1327
|
-
return { sessionId, operation, holderId, leaseId, expiresAt };
|
|
1328
|
-
});
|
|
1329
|
-
}
|
|
1330
|
-
releaseMaintenance(lease) {
|
|
1331
|
-
this.db.prepare("DELETE FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=?").run(lease.sessionId, lease.leaseId, lease.holderId);
|
|
1332
|
-
}
|
|
1333
|
-
delete(sessionId, lease) {
|
|
1334
|
-
const row = this.db.prepare(
|
|
1335
|
-
"SELECT * FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=? AND operation=? AND expires_at>?"
|
|
1336
|
-
).get(sessionId, lease.leaseId, lease.holderId, lease.operation, Date.now());
|
|
1337
|
-
if (!row || lease.operation !== "delete")
|
|
1338
|
-
throw conflict("A valid delete maintenance lease is required");
|
|
1339
|
-
const record = this.getSummary(sessionId);
|
|
1340
|
-
if (!record) throw new Error(`Session not found: ${sessionId}`);
|
|
1341
|
-
const transcript = this.containedPath(record.transcriptRelativePath);
|
|
1342
|
-
const artifacts = [
|
|
1343
|
-
transcript,
|
|
1344
|
-
this.containedPath(record.summaryRelativePath),
|
|
1345
|
-
this.containedPath(`${sessionId}.plan.json`),
|
|
1346
|
-
this.containedPath(`${sessionId}.tasks.json`),
|
|
1347
|
-
this.containedPath(`${sessionId}.todos.json`),
|
|
1348
|
-
path3.join(path3.dirname(transcript), path3.basename(sessionId))
|
|
1349
|
-
];
|
|
1350
|
-
const trashRoot = path3.join(this.sessionsDir, "_trash", lease.leaseId);
|
|
1351
|
-
fs2.mkdirSync(trashRoot, { recursive: true, mode: 448 });
|
|
1352
|
-
const moved = [];
|
|
1353
|
-
try {
|
|
1354
|
-
artifacts.forEach((artifact, index) => {
|
|
1355
|
-
if (!fs2.existsSync(artifact)) return;
|
|
1356
|
-
const target = path3.join(trashRoot, `${index}-${path3.basename(artifact)}`);
|
|
1357
|
-
fs2.renameSync(artifact, target);
|
|
1358
|
-
moved.push({ from: artifact, to: target });
|
|
1359
|
-
});
|
|
1360
|
-
this.transaction(() => {
|
|
1361
|
-
const current = this.db.prepare(
|
|
1362
|
-
"SELECT 1 AS yes FROM maintenance_leases WHERE session_id=? AND lease_id=? AND holder_id=? AND operation=? AND expires_at>?"
|
|
1363
|
-
).get(sessionId, lease.leaseId, lease.holderId, "delete", Date.now());
|
|
1364
|
-
if (!current) throw conflict("Delete maintenance lease expired while staging artifacts");
|
|
1365
|
-
this.db.prepare("DELETE FROM sessions WHERE session_id=?").run(sessionId);
|
|
1366
|
-
this.db.prepare("DELETE FROM maintenance_leases WHERE session_id=?").run(sessionId);
|
|
1367
|
-
this.bumpGeneration();
|
|
1368
|
-
});
|
|
1369
|
-
} catch (error) {
|
|
1370
|
-
for (const item of moved.reverse()) {
|
|
1371
|
-
try {
|
|
1372
|
-
fs2.mkdirSync(path3.dirname(item.from), { recursive: true, mode: 448 });
|
|
1373
|
-
fs2.renameSync(item.to, item.from);
|
|
1374
|
-
} catch {
|
|
1375
|
-
}
|
|
1376
|
-
}
|
|
1377
|
-
throw error;
|
|
1378
|
-
}
|
|
1379
|
-
try {
|
|
1380
|
-
fs2.rmSync(trashRoot, { recursive: true, force: true });
|
|
1381
|
-
const trashParent = path3.dirname(trashRoot);
|
|
1382
|
-
if (fs2.readdirSync(trashParent).length === 0) fs2.rmdirSync(trashParent);
|
|
1383
|
-
} catch {
|
|
1384
|
-
}
|
|
1385
|
-
}
|
|
1386
|
-
prune(maxAgeDays, holderId) {
|
|
1387
|
-
if (!Number.isFinite(maxAgeDays) || maxAgeDays < 0) throw new TypeError("Invalid prune age");
|
|
1388
|
-
const cutoff = Date.now() - maxAgeDays * 864e5;
|
|
1389
|
-
const candidates = this.db.prepare("SELECT session_id FROM sessions WHERE transcript_mtime_ms<?").all(cutoff);
|
|
1390
|
-
let deleted = 0;
|
|
1391
|
-
for (const { session_id: id } of candidates) {
|
|
1392
|
-
try {
|
|
1393
|
-
const lease = this.acquireMaintenance(id, "delete", holderId);
|
|
1394
|
-
this.delete(id, lease);
|
|
1395
|
-
deleted++;
|
|
1396
|
-
} catch (error) {
|
|
1397
|
-
if (error.name !== "SessionOwnershipConflictError") throw error;
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
|
-
return deleted;
|
|
1401
|
-
}
|
|
1402
|
-
rebuildCatalog() {
|
|
1403
|
-
return rebuildCatalogIndex(
|
|
1404
|
-
this.db,
|
|
1405
|
-
this.sessionsDir,
|
|
1406
|
-
(rel) => this.containedPath(rel),
|
|
1407
|
-
(run) => this.transaction(run),
|
|
1408
|
-
() => this.bumpGeneration()
|
|
1409
|
-
);
|
|
1410
|
-
}
|
|
1411
|
-
health(base) {
|
|
1412
|
-
this.reapExpired();
|
|
1413
|
-
const count = (table, where = "") => Number(
|
|
1414
|
-
this.db.prepare(`SELECT COUNT(*) AS count FROM ${table} ${where}`).get().count
|
|
1415
|
-
);
|
|
1416
|
-
const reconciliation = this.db.prepare("SELECT value FROM catalog_meta WHERE key='last_reconciliation'").get();
|
|
1417
|
-
return {
|
|
1418
|
-
...base,
|
|
1419
|
-
catalogRows: count("sessions"),
|
|
1420
|
-
damagedRows: count("sessions", "WHERE damaged<>0"),
|
|
1421
|
-
liveLeases: count("session_leases"),
|
|
1422
|
-
reservations: count("resume_reservations"),
|
|
1423
|
-
maintenanceLeases: count("maintenance_leases"),
|
|
1424
|
-
generation: this.generation(),
|
|
1425
|
-
...reconciliation ? { lastReconciliation: reconciliation.value } : {}
|
|
1426
|
-
};
|
|
1427
|
-
}
|
|
1428
|
-
};
|
|
1429
|
-
|
|
1430
|
-
// src/session-catalog/project-server.ts
|
|
37
|
+
import { bindProjectEndpoint } from "@wrongstack/persistence";
|
|
1431
38
|
function parseArgs(argv) {
|
|
1432
39
|
const values = /* @__PURE__ */ new Map();
|
|
1433
40
|
for (let index = 0; index < argv.length; index++) {
|
|
@@ -1438,16 +45,16 @@ function parseArgs(argv) {
|
|
|
1438
45
|
const projectRoot = values.get("--project-root");
|
|
1439
46
|
if (!projectDir) throw new Error("Session Catalog project server requires --project-dir");
|
|
1440
47
|
if (!projectRoot) throw new Error("Session Catalog project server requires --project-root");
|
|
1441
|
-
return { projectDir:
|
|
48
|
+
return { projectDir: path.resolve(projectDir), projectRoot: path.resolve(projectRoot) };
|
|
1442
49
|
}
|
|
1443
50
|
useDaemonPerfDefaults();
|
|
1444
51
|
var parsed = parseArgs(process.argv.slice(2));
|
|
1445
52
|
var endpoint = sessionCatalogProjectServerEndpoint(parsed.projectDir);
|
|
1446
53
|
var metadataPath = sessionCatalogProjectServerMetadataPath(parsed.projectDir);
|
|
1447
|
-
var databasePath =
|
|
54
|
+
var databasePath = path.join(parsed.projectDir, "sessions", "catalog.sqlite");
|
|
1448
55
|
var startedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1449
|
-
var instanceId =
|
|
1450
|
-
var authToken =
|
|
56
|
+
var instanceId = randomUUID();
|
|
57
|
+
var authToken = randomBytes(32).toString("hex");
|
|
1451
58
|
var idleInput = Number(process.env["WRONGSTACK_SESSION_CATALOG_IDLE_MS"]);
|
|
1452
59
|
var idleMs = Number.isFinite(idleInput) && idleInput >= 100 ? idleInput : 5 * 6e4;
|
|
1453
60
|
var disconnectedIdleMs = Math.min(idleMs, 250);
|
|
@@ -1461,7 +68,7 @@ var serverInfo = {
|
|
|
1461
68
|
instanceId,
|
|
1462
69
|
startedAt
|
|
1463
70
|
};
|
|
1464
|
-
process.title = `wrongstack-session-catalog:${
|
|
71
|
+
process.title = `wrongstack-session-catalog:${path.basename(parsed.projectRoot)}`;
|
|
1465
72
|
var store;
|
|
1466
73
|
var activeRequests = 0;
|
|
1467
74
|
var stopping = false;
|
|
@@ -1470,8 +77,8 @@ var clients = /* @__PURE__ */ new Set();
|
|
|
1470
77
|
var MAX_CLIENTS = 256;
|
|
1471
78
|
var eventSequence = 0;
|
|
1472
79
|
var metadataReadyResolve;
|
|
1473
|
-
var metadataReady = new Promise((
|
|
1474
|
-
metadataReadyResolve =
|
|
80
|
+
var metadataReady = new Promise((resolve2) => {
|
|
81
|
+
metadataReadyResolve = resolve2;
|
|
1475
82
|
});
|
|
1476
83
|
function send(state, message) {
|
|
1477
84
|
if (state.socket.destroyed) return;
|
|
@@ -1565,13 +172,13 @@ function validateOperationArgs(op, args) {
|
|
|
1565
172
|
if (record["entry"] !== void 0) exact(record["entry"], `${op}.entry`, entryKeys);
|
|
1566
173
|
if (record["entry"] && typeof record["entry"] === "object") {
|
|
1567
174
|
const entry = record["entry"];
|
|
1568
|
-
if (typeof entry["projectRoot"] !== "string" || (process.platform === "win32" ?
|
|
175
|
+
if (typeof entry["projectRoot"] !== "string" || (process.platform === "win32" ? path.resolve(entry["projectRoot"]).toLowerCase() !== parsed.projectRoot.toLowerCase() : path.resolve(entry["projectRoot"]) !== parsed.projectRoot)) {
|
|
1569
176
|
throw new TypeError(`${op}.entry project identity does not match this daemon`);
|
|
1570
177
|
}
|
|
1571
178
|
if (typeof entry["workingDir"] !== "string")
|
|
1572
179
|
throw new TypeError(`${op}.entry workingDir is required`);
|
|
1573
|
-
const
|
|
1574
|
-
if (
|
|
180
|
+
const relative2 = path.relative(parsed.projectRoot, path.resolve(entry["workingDir"]));
|
|
181
|
+
if (relative2 === ".." || relative2.startsWith(`..${path.sep}`) || path.isAbsolute(relative2)) {
|
|
1575
182
|
throw new TypeError(`${op}.entry workingDir is outside the project root`);
|
|
1576
183
|
}
|
|
1577
184
|
}
|
|
@@ -1866,7 +473,7 @@ async function stop(_reason) {
|
|
|
1866
473
|
if (idleTimer) clearTimeout(idleTimer);
|
|
1867
474
|
for (const state of clients) state.socket.destroy();
|
|
1868
475
|
clients.clear();
|
|
1869
|
-
await new Promise((
|
|
476
|
+
await new Promise((resolve2) => server.close(() => resolve2()));
|
|
1870
477
|
store?.close();
|
|
1871
478
|
store = void 0;
|
|
1872
479
|
if (process.platform !== "win32") await fsp.rm(endpoint, { force: true }).catch(() => void 0);
|