@atlaswork/atlascode 0.0.0-stage → 0.1.125
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/README.md +124 -2
- package/dist/cli.js +506227 -0
- package/dist/web-contract/index.d.ts +727 -0
- package/dist/web-contract/index.js +260 -0
- package/dist/web-session-runtime/atlascode/web/contract.d.ts +10 -0
- package/dist/web-session-runtime/atlascode/web/cursorLedger.d.ts +63 -0
- package/dist/web-session-runtime/atlascode/web/entry.d.ts +19 -0
- package/dist/web-session-runtime/atlascode/web/errors.d.ts +16 -0
- package/dist/web-session-runtime/atlascode/web/follow.d.ts +82 -0
- package/dist/web-session-runtime/atlascode/web/limits.d.ts +63 -0
- package/dist/web-session-runtime/atlascode/web/projection.d.ts +69 -0
- package/dist/web-session-runtime/atlascode/web/readonlyRuntime.d.ts +156 -0
- package/dist/web-session-runtime/atlascode/web/runtimeDefault.d.ts +26 -0
- package/dist/web-session-runtime/atlascode/web/sessionStoreAdapter.d.ts +70 -0
- package/dist/web-session-runtime/engine/session/env.d.ts +32 -0
- package/dist/web-session-runtime/engine/session/firstPrompt.d.ts +21 -0
- package/dist/web-session-runtime/engine/session/json.d.ts +27 -0
- package/dist/web-session-runtime/engine/session/load.d.ts +88 -0
- package/dist/web-session-runtime/engine/session/paths.d.ts +25 -0
- package/dist/web-session-runtime/engine/session/predicates.d.ts +55 -0
- package/dist/web-session-runtime/engine/session/readonly.d.ts +29 -0
- package/dist/web-session-runtime/engine/session/scanner.d.ts +26 -0
- package/dist/web-session-runtime/engine/session/search.d.ts +44 -0
- package/dist/web-session-runtime/engine/session/types.d.ts +379 -0
- package/dist/web-session-runtime/index.d.ts +1 -0
- package/dist/web-session-runtime/index.js +2635 -0
- package/dist/web-session-runtime/kernel/protocol/webSessionV0.d.ts +727 -0
- package/dist/web-session-runtime/shared/ProductDefinition.d.ts +47 -0
- package/dist/web-session-runtime/shared/agentRoleTemplates.d.ts +44 -0
- package/dist/web-session-runtime/shared/agentSwarmsEnabled.d.ts +5 -0
- package/dist/web-session-runtime/shared/boundedImageRead.d.ts +31 -0
- package/dist/web-session-runtime/shared/circular-buffer.d.ts +42 -0
- package/dist/web-session-runtime/shared/configDir.d.ts +57 -0
- package/dist/web-session-runtime/shared/constants.d.ts +19 -0
- package/dist/web-session-runtime/shared/debug.d.ts +32 -0
- package/dist/web-session-runtime/shared/env.d.ts +38 -0
- package/dist/web-session-runtime/shared/errors.d.ts +56 -0
- package/dist/web-session-runtime/shared/feature.d.ts +25 -0
- package/dist/web-session-runtime/shared/format.d.ts +11 -0
- package/dist/web-session-runtime/shared/fs-operations.d.ts +116 -0
- package/dist/web-session-runtime/shared/hash.d.ts +13 -0
- package/dist/web-session-runtime/shared/identity.d.ts +23 -0
- package/dist/web-session-runtime/shared/index.d.ts +46 -0
- package/dist/web-session-runtime/shared/lazySchema.d.ts +12 -0
- package/dist/web-session-runtime/shared/log.d.ts +1 -0
- package/dist/web-session-runtime/shared/path.d.ts +22 -0
- package/dist/web-session-runtime/shared/pdfPageImages.d.ts +19 -0
- package/dist/web-session-runtime/shared/pdfReference.d.ts +70 -0
- package/dist/web-session-runtime/shared/permissionDeadline.d.ts +24 -0
- package/dist/web-session-runtime/shared/platform.d.ts +8 -0
- package/dist/web-session-runtime/shared/stringUtils.d.ts +110 -0
- package/dist/web-session-runtime/shared/swarmSchemaFilter.d.ts +23 -0
- package/dist/web-session-runtime/shared/teamFileSchema.d.ts +151 -0
- package/dist/web-session-runtime/shared/teamInboxSchema.d.ts +112 -0
- package/dist/web-session-runtime/shared/teammateContext.d.ts +89 -0
- package/dist/web-session-runtime/shared/tempDir.d.ts +1 -0
- package/dist/web-session-runtime/shared/textEncoding.d.ts +41 -0
- package/dist/web-session-runtime/shared/tokenEstimation.d.ts +36 -0
- package/dist/web-session-runtime/shared/types-session.d.ts +266 -0
- package/dist/web-session-runtime/shared/types.d.ts +190 -0
- package/dist/web-session-runtime/shared/unc.d.ts +5 -0
- package/dist/web-session-runtime/shared/windowsPaths.d.ts +24 -0
- package/package.json +116 -4
|
@@ -0,0 +1,2635 @@
|
|
|
1
|
+
// src/atlascode/web/readonlyRuntime.ts
|
|
2
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
3
|
+
|
|
4
|
+
// src/engine/session/load.ts
|
|
5
|
+
import { open, readFile, stat } from "fs/promises";
|
|
6
|
+
import { constants as fsConstants } from "node:fs";
|
|
7
|
+
|
|
8
|
+
// src/shared/env.ts
|
|
9
|
+
function isEnvTruthy(envVar) {
|
|
10
|
+
if (!envVar)
|
|
11
|
+
return false;
|
|
12
|
+
if (typeof envVar === "boolean")
|
|
13
|
+
return envVar;
|
|
14
|
+
const normalizedValue = envVar.toLowerCase().trim();
|
|
15
|
+
return ["1", "true", "yes", "on"].includes(normalizedValue);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/shared/debug.ts
|
|
19
|
+
var _sink = null;
|
|
20
|
+
function logForDebugging(message, options) {
|
|
21
|
+
if (_sink !== null) {
|
|
22
|
+
_sink(message, options);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// src/engine/session/json.ts
|
|
27
|
+
var bunJSONLParse = (() => {
|
|
28
|
+
if (typeof Bun === "undefined")
|
|
29
|
+
return false;
|
|
30
|
+
const b = Bun;
|
|
31
|
+
const jsonl = b.JSONL;
|
|
32
|
+
if (!jsonl?.parseChunk)
|
|
33
|
+
return false;
|
|
34
|
+
return jsonl.parseChunk;
|
|
35
|
+
})();
|
|
36
|
+
function parseJSONLBun(data) {
|
|
37
|
+
const parse = bunJSONLParse;
|
|
38
|
+
const len = data.length;
|
|
39
|
+
const result = parse(data);
|
|
40
|
+
if (!result.error || result.done || result.read >= len) {
|
|
41
|
+
return result.values;
|
|
42
|
+
}
|
|
43
|
+
let values = result.values;
|
|
44
|
+
let offset = result.read;
|
|
45
|
+
while (offset < len) {
|
|
46
|
+
const newlineIndex = typeof data === "string" ? data.indexOf(`
|
|
47
|
+
`, offset) : data.indexOf(10, offset);
|
|
48
|
+
if (newlineIndex === -1)
|
|
49
|
+
break;
|
|
50
|
+
offset = newlineIndex + 1;
|
|
51
|
+
const next = parse(data, offset);
|
|
52
|
+
if (next.values.length > 0) {
|
|
53
|
+
values = values.concat(next.values);
|
|
54
|
+
}
|
|
55
|
+
if (!next.error || next.done || next.read >= len)
|
|
56
|
+
break;
|
|
57
|
+
offset = next.read;
|
|
58
|
+
}
|
|
59
|
+
return values;
|
|
60
|
+
}
|
|
61
|
+
function parseJSONLBuffer(buf) {
|
|
62
|
+
const bufLen = buf.length;
|
|
63
|
+
let start = 0;
|
|
64
|
+
if (buf[0] === 239 && buf[1] === 187 && buf[2] === 191) {
|
|
65
|
+
start = 3;
|
|
66
|
+
}
|
|
67
|
+
const results = [];
|
|
68
|
+
while (start < bufLen) {
|
|
69
|
+
let end = buf.indexOf(10, start);
|
|
70
|
+
if (end === -1)
|
|
71
|
+
end = bufLen;
|
|
72
|
+
const line = buf.toString("utf8", start, end).trim();
|
|
73
|
+
start = end + 1;
|
|
74
|
+
if (!line)
|
|
75
|
+
continue;
|
|
76
|
+
try {
|
|
77
|
+
results.push(JSON.parse(line));
|
|
78
|
+
} catch {}
|
|
79
|
+
}
|
|
80
|
+
return results;
|
|
81
|
+
}
|
|
82
|
+
function parseJSONLString(data) {
|
|
83
|
+
const stripped = data.startsWith("\uFEFF") ? data.slice(1) : data;
|
|
84
|
+
const len = stripped.length;
|
|
85
|
+
let start = 0;
|
|
86
|
+
const results = [];
|
|
87
|
+
while (start < len) {
|
|
88
|
+
let end = stripped.indexOf(`
|
|
89
|
+
`, start);
|
|
90
|
+
if (end === -1)
|
|
91
|
+
end = len;
|
|
92
|
+
const line = stripped.substring(start, end).trim();
|
|
93
|
+
start = end + 1;
|
|
94
|
+
if (!line)
|
|
95
|
+
continue;
|
|
96
|
+
try {
|
|
97
|
+
results.push(JSON.parse(line));
|
|
98
|
+
} catch {}
|
|
99
|
+
}
|
|
100
|
+
return results;
|
|
101
|
+
}
|
|
102
|
+
function parseJSONL(data) {
|
|
103
|
+
if (bunJSONLParse) {
|
|
104
|
+
return parseJSONLBun(data);
|
|
105
|
+
}
|
|
106
|
+
if (typeof data === "string") {
|
|
107
|
+
return parseJSONLString(data);
|
|
108
|
+
}
|
|
109
|
+
return parseJSONLBuffer(data);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/engine/session/predicates.ts
|
|
113
|
+
function isTranscriptMessage(entry) {
|
|
114
|
+
return entry.type === "user" || entry.type === "assistant" || entry.type === "attachment" || entry.type === "system";
|
|
115
|
+
}
|
|
116
|
+
function isLegacyProgressEntry(entry) {
|
|
117
|
+
return typeof entry === "object" && entry !== null && "type" in entry && entry.type === "progress" && "uuid" in entry && typeof entry.uuid === "string";
|
|
118
|
+
}
|
|
119
|
+
var EPHEMERAL_PROGRESS_TYPES = new Set([
|
|
120
|
+
"bash_progress",
|
|
121
|
+
"powershell_progress",
|
|
122
|
+
"mcp_progress"
|
|
123
|
+
]);
|
|
124
|
+
function isCompactBoundaryMessage(message) {
|
|
125
|
+
return message?.type === "system" && message.subtype === "compact_boundary";
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// src/engine/session/paths.ts
|
|
129
|
+
var _projectDirCache = new Map;
|
|
130
|
+
var MAX_TRANSCRIPT_READ_BYTES = 50 * 1024 * 1024;
|
|
131
|
+
var agentTranscriptSubdirs = new Map;
|
|
132
|
+
|
|
133
|
+
// src/engine/session/scanner.ts
|
|
134
|
+
import { open as fsOpen } from "fs/promises";
|
|
135
|
+
var TRANSCRIPT_READ_CHUNK_SIZE = 1024 * 1024;
|
|
136
|
+
var SKIP_PRECOMPACT_THRESHOLD = 5 * 1024 * 1024;
|
|
137
|
+
var _compactBoundaryMarker;
|
|
138
|
+
function compactBoundaryMarker() {
|
|
139
|
+
return _compactBoundaryMarker ??= Buffer.from('"compact_boundary"');
|
|
140
|
+
}
|
|
141
|
+
function parseBoundaryLine(line) {
|
|
142
|
+
try {
|
|
143
|
+
const parsed = JSON.parse(line);
|
|
144
|
+
if (parsed.type !== "system" || parsed.subtype !== "compact_boundary") {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
hasPreservedSegment: Boolean(parsed.compactMetadata?.preservedSegment)
|
|
149
|
+
};
|
|
150
|
+
} catch {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function sinkWrite(s, src, start, end) {
|
|
155
|
+
const n = end - start;
|
|
156
|
+
if (n <= 0)
|
|
157
|
+
return;
|
|
158
|
+
if (s.len + n > s.buf.length) {
|
|
159
|
+
const grown = Buffer.allocUnsafe(Math.min(Math.max(s.buf.length * 2, s.len + n), s.cap));
|
|
160
|
+
s.buf.copy(grown, 0, 0, s.len);
|
|
161
|
+
s.buf = grown;
|
|
162
|
+
}
|
|
163
|
+
src.copy(s.buf, s.len, start, end);
|
|
164
|
+
s.len += n;
|
|
165
|
+
}
|
|
166
|
+
function hasPrefix(src, prefix, at, end) {
|
|
167
|
+
return end - at >= prefix.length && src.compare(prefix, 0, prefix.length, at, at + prefix.length) === 0;
|
|
168
|
+
}
|
|
169
|
+
var ATTR_SNAP_PREFIX = Buffer.from('{"type":"attribution-snapshot"');
|
|
170
|
+
var SYSTEM_PREFIX = Buffer.from('{"type":"system"');
|
|
171
|
+
var LF = 10;
|
|
172
|
+
var LF_BYTE = Buffer.from([LF]);
|
|
173
|
+
var BOUNDARY_SEARCH_BOUND = 256;
|
|
174
|
+
function processStraddle(s, chunk, bytesRead) {
|
|
175
|
+
s.straddleSnapCarryLen = 0;
|
|
176
|
+
s.straddleSnapTailEnd = 0;
|
|
177
|
+
if (s.carryLen === 0)
|
|
178
|
+
return 0;
|
|
179
|
+
const cb = s.carryBuf;
|
|
180
|
+
const firstNl = chunk.indexOf(LF);
|
|
181
|
+
if (firstNl === -1 || firstNl >= bytesRead)
|
|
182
|
+
return 0;
|
|
183
|
+
const tailEnd = firstNl + 1;
|
|
184
|
+
if (hasPrefix(cb, ATTR_SNAP_PREFIX, 0, s.carryLen)) {
|
|
185
|
+
s.straddleSnapCarryLen = s.carryLen;
|
|
186
|
+
s.straddleSnapTailEnd = tailEnd;
|
|
187
|
+
s.lastSnapSrc = null;
|
|
188
|
+
} else if (s.carryLen < ATTR_SNAP_PREFIX.length) {
|
|
189
|
+
return 0;
|
|
190
|
+
} else {
|
|
191
|
+
if (hasPrefix(cb, SYSTEM_PREFIX, 0, s.carryLen)) {
|
|
192
|
+
const hit = parseBoundaryLine(cb.toString("utf-8", 0, s.carryLen) + chunk.toString("utf-8", 0, firstNl));
|
|
193
|
+
if (hit?.hasPreservedSegment) {
|
|
194
|
+
s.hasPreservedSegment = true;
|
|
195
|
+
} else if (hit) {
|
|
196
|
+
s.out.len = 0;
|
|
197
|
+
s.boundaryStartOffset = s.bufFileOff;
|
|
198
|
+
s.hasPreservedSegment = false;
|
|
199
|
+
s.lastSnapSrc = null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
sinkWrite(s.out, cb, 0, s.carryLen);
|
|
203
|
+
sinkWrite(s.out, chunk, 0, tailEnd);
|
|
204
|
+
}
|
|
205
|
+
s.bufFileOff += s.carryLen + tailEnd;
|
|
206
|
+
s.carryLen = 0;
|
|
207
|
+
return tailEnd;
|
|
208
|
+
}
|
|
209
|
+
function scanChunkLines(s, buf, boundaryMarker) {
|
|
210
|
+
let boundaryAt = buf.indexOf(boundaryMarker);
|
|
211
|
+
let runStart = 0;
|
|
212
|
+
let lineStart = 0;
|
|
213
|
+
let lastSnapStart = -1;
|
|
214
|
+
let lastSnapEnd = -1;
|
|
215
|
+
let nl = buf.indexOf(LF);
|
|
216
|
+
while (nl !== -1) {
|
|
217
|
+
const lineEnd = nl + 1;
|
|
218
|
+
if (boundaryAt !== -1 && boundaryAt < lineStart) {
|
|
219
|
+
boundaryAt = buf.indexOf(boundaryMarker, lineStart);
|
|
220
|
+
}
|
|
221
|
+
if (hasPrefix(buf, ATTR_SNAP_PREFIX, lineStart, lineEnd)) {
|
|
222
|
+
sinkWrite(s.out, buf, runStart, lineStart);
|
|
223
|
+
lastSnapStart = lineStart;
|
|
224
|
+
lastSnapEnd = lineEnd;
|
|
225
|
+
runStart = lineEnd;
|
|
226
|
+
} else if (boundaryAt >= lineStart && boundaryAt < Math.min(lineStart + BOUNDARY_SEARCH_BOUND, lineEnd)) {
|
|
227
|
+
const hit = parseBoundaryLine(buf.toString("utf-8", lineStart, nl));
|
|
228
|
+
if (hit?.hasPreservedSegment) {
|
|
229
|
+
s.hasPreservedSegment = true;
|
|
230
|
+
} else if (hit) {
|
|
231
|
+
s.out.len = 0;
|
|
232
|
+
s.boundaryStartOffset = s.bufFileOff + lineStart;
|
|
233
|
+
s.hasPreservedSegment = false;
|
|
234
|
+
s.lastSnapSrc = null;
|
|
235
|
+
lastSnapStart = -1;
|
|
236
|
+
s.straddleSnapCarryLen = 0;
|
|
237
|
+
runStart = lineStart;
|
|
238
|
+
}
|
|
239
|
+
boundaryAt = buf.indexOf(boundaryMarker, boundaryAt + boundaryMarker.length);
|
|
240
|
+
}
|
|
241
|
+
lineStart = lineEnd;
|
|
242
|
+
nl = buf.indexOf(LF, lineStart);
|
|
243
|
+
}
|
|
244
|
+
sinkWrite(s.out, buf, runStart, lineStart);
|
|
245
|
+
return { lastSnapStart, lastSnapEnd, trailStart: lineStart };
|
|
246
|
+
}
|
|
247
|
+
function captureSnap(s, buf, chunk, lastSnapStart, lastSnapEnd) {
|
|
248
|
+
if (lastSnapStart !== -1) {
|
|
249
|
+
s.lastSnapLen = lastSnapEnd - lastSnapStart;
|
|
250
|
+
if (s.lastSnapBuf === undefined || s.lastSnapLen > s.lastSnapBuf.length) {
|
|
251
|
+
s.lastSnapBuf = Buffer.allocUnsafe(s.lastSnapLen);
|
|
252
|
+
}
|
|
253
|
+
buf.copy(s.lastSnapBuf, 0, lastSnapStart, lastSnapEnd);
|
|
254
|
+
s.lastSnapSrc = s.lastSnapBuf;
|
|
255
|
+
} else if (s.straddleSnapCarryLen > 0) {
|
|
256
|
+
s.lastSnapLen = s.straddleSnapCarryLen + s.straddleSnapTailEnd;
|
|
257
|
+
if (s.lastSnapBuf === undefined || s.lastSnapLen > s.lastSnapBuf.length) {
|
|
258
|
+
s.lastSnapBuf = Buffer.allocUnsafe(s.lastSnapLen);
|
|
259
|
+
}
|
|
260
|
+
s.carryBuf.copy(s.lastSnapBuf, 0, 0, s.straddleSnapCarryLen);
|
|
261
|
+
chunk.copy(s.lastSnapBuf, s.straddleSnapCarryLen, 0, s.straddleSnapTailEnd);
|
|
262
|
+
s.lastSnapSrc = s.lastSnapBuf;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
function captureCarry(s, buf, trailStart) {
|
|
266
|
+
s.carryLen = buf.length - trailStart;
|
|
267
|
+
if (s.carryLen > 0) {
|
|
268
|
+
if (s.carryBuf === undefined || s.carryLen > s.carryBuf.length) {
|
|
269
|
+
s.carryBuf = Buffer.allocUnsafe(s.carryLen);
|
|
270
|
+
}
|
|
271
|
+
buf.copy(s.carryBuf, 0, trailStart, buf.length);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
function finalizeOutput(s) {
|
|
275
|
+
if (s.carryLen > 0) {
|
|
276
|
+
const cb = s.carryBuf;
|
|
277
|
+
if (hasPrefix(cb, ATTR_SNAP_PREFIX, 0, s.carryLen)) {
|
|
278
|
+
s.lastSnapSrc = cb;
|
|
279
|
+
s.lastSnapLen = s.carryLen;
|
|
280
|
+
} else {
|
|
281
|
+
sinkWrite(s.out, cb, 0, s.carryLen);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
if (s.lastSnapSrc) {
|
|
285
|
+
if (s.out.len > 0 && s.out.buf[s.out.len - 1] !== LF) {
|
|
286
|
+
sinkWrite(s.out, LF_BYTE, 0, 1);
|
|
287
|
+
}
|
|
288
|
+
sinkWrite(s.out, s.lastSnapSrc, 0, s.lastSnapLen);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
async function readTranscriptForLoad(filePath, fileSize, opts) {
|
|
292
|
+
const boundaryMarker = compactBoundaryMarker();
|
|
293
|
+
const CHUNK_SIZE = TRANSCRIPT_READ_CHUNK_SIZE;
|
|
294
|
+
const s = {
|
|
295
|
+
out: {
|
|
296
|
+
buf: Buffer.allocUnsafe(Math.min(fileSize, 8 * 1024 * 1024)),
|
|
297
|
+
len: 0,
|
|
298
|
+
cap: fileSize + 1
|
|
299
|
+
},
|
|
300
|
+
boundaryStartOffset: 0,
|
|
301
|
+
hasPreservedSegment: false,
|
|
302
|
+
lastSnapSrc: null,
|
|
303
|
+
lastSnapLen: 0,
|
|
304
|
+
lastSnapBuf: undefined,
|
|
305
|
+
bufFileOff: 0,
|
|
306
|
+
carryLen: 0,
|
|
307
|
+
carryBuf: undefined,
|
|
308
|
+
straddleSnapCarryLen: 0,
|
|
309
|
+
straddleSnapTailEnd: 0
|
|
310
|
+
};
|
|
311
|
+
const chunk = Buffer.allocUnsafe(CHUNK_SIZE);
|
|
312
|
+
const fd = opts?.fd ?? await fsOpen(filePath, "r");
|
|
313
|
+
try {
|
|
314
|
+
let filePos = 0;
|
|
315
|
+
while (filePos < fileSize) {
|
|
316
|
+
const { bytesRead } = await fd.read(chunk, 0, Math.min(CHUNK_SIZE, fileSize - filePos), filePos);
|
|
317
|
+
if (bytesRead === 0)
|
|
318
|
+
break;
|
|
319
|
+
filePos += bytesRead;
|
|
320
|
+
const chunkOff = processStraddle(s, chunk, bytesRead);
|
|
321
|
+
let buf;
|
|
322
|
+
if (s.carryLen > 0) {
|
|
323
|
+
const bufLen = s.carryLen + (bytesRead - chunkOff);
|
|
324
|
+
buf = Buffer.allocUnsafe(bufLen);
|
|
325
|
+
s.carryBuf.copy(buf, 0, 0, s.carryLen);
|
|
326
|
+
chunk.copy(buf, s.carryLen, chunkOff, bytesRead);
|
|
327
|
+
} else {
|
|
328
|
+
buf = chunk.subarray(chunkOff, bytesRead);
|
|
329
|
+
}
|
|
330
|
+
const r = scanChunkLines(s, buf, boundaryMarker);
|
|
331
|
+
captureSnap(s, buf, chunk, r.lastSnapStart, r.lastSnapEnd);
|
|
332
|
+
captureCarry(s, buf, r.trailStart);
|
|
333
|
+
s.bufFileOff += r.trailStart;
|
|
334
|
+
}
|
|
335
|
+
finalizeOutput(s);
|
|
336
|
+
} finally {
|
|
337
|
+
if (!opts?.fd)
|
|
338
|
+
await fd.close();
|
|
339
|
+
}
|
|
340
|
+
return {
|
|
341
|
+
boundaryStartOffset: s.boundaryStartOffset,
|
|
342
|
+
postBoundaryBuf: s.out.buf.subarray(0, s.out.len),
|
|
343
|
+
hasPreservedSegment: s.hasPreservedSegment
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// src/engine/session/load.ts
|
|
348
|
+
function applyPreservedSegmentRelinks(messages) {
|
|
349
|
+
let lastSeg;
|
|
350
|
+
let lastSegBoundaryIdx = -1;
|
|
351
|
+
let absoluteLastBoundaryIdx = -1;
|
|
352
|
+
const entryIndex = new Map;
|
|
353
|
+
let i = 0;
|
|
354
|
+
for (const entry of messages.values()) {
|
|
355
|
+
entryIndex.set(entry.uuid, i);
|
|
356
|
+
if (isCompactBoundaryMessage(entry)) {
|
|
357
|
+
absoluteLastBoundaryIdx = i;
|
|
358
|
+
const seg = entry.compactMetadata?.preservedSegment;
|
|
359
|
+
if (seg) {
|
|
360
|
+
lastSeg = seg;
|
|
361
|
+
lastSegBoundaryIdx = i;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
i++;
|
|
365
|
+
}
|
|
366
|
+
if (!lastSeg)
|
|
367
|
+
return;
|
|
368
|
+
const segIsLive = lastSegBoundaryIdx === absoluteLastBoundaryIdx;
|
|
369
|
+
const preservedUuids = new Set;
|
|
370
|
+
if (segIsLive) {
|
|
371
|
+
const walkSeen = new Set;
|
|
372
|
+
let cur = messages.get(lastSeg.tailUuid);
|
|
373
|
+
let reachedHead = false;
|
|
374
|
+
while (cur && !walkSeen.has(cur.uuid)) {
|
|
375
|
+
walkSeen.add(cur.uuid);
|
|
376
|
+
preservedUuids.add(cur.uuid);
|
|
377
|
+
if (cur.uuid === lastSeg.headUuid) {
|
|
378
|
+
reachedHead = true;
|
|
379
|
+
break;
|
|
380
|
+
}
|
|
381
|
+
cur = cur.parentUuid ? messages.get(cur.parentUuid) : undefined;
|
|
382
|
+
}
|
|
383
|
+
if (!reachedHead) {
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
if (segIsLive) {
|
|
388
|
+
const head = messages.get(lastSeg.headUuid);
|
|
389
|
+
if (head) {
|
|
390
|
+
messages.set(lastSeg.headUuid, {
|
|
391
|
+
...head,
|
|
392
|
+
parentUuid: lastSeg.anchorUuid
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
for (const [uuid, msg] of messages) {
|
|
396
|
+
if (msg.parentUuid === lastSeg.anchorUuid && uuid !== lastSeg.headUuid) {
|
|
397
|
+
messages.set(uuid, { ...msg, parentUuid: lastSeg.tailUuid });
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
for (const uuid of preservedUuids) {
|
|
401
|
+
const msg = messages.get(uuid);
|
|
402
|
+
if (msg?.type !== "assistant")
|
|
403
|
+
continue;
|
|
404
|
+
messages.set(uuid, {
|
|
405
|
+
...msg,
|
|
406
|
+
message: {
|
|
407
|
+
...msg.message,
|
|
408
|
+
usage: {
|
|
409
|
+
...msg.message?.usage,
|
|
410
|
+
input_tokens: 0,
|
|
411
|
+
output_tokens: 0,
|
|
412
|
+
cache_creation_input_tokens: 0,
|
|
413
|
+
cache_read_input_tokens: 0
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
const toDelete = [];
|
|
420
|
+
for (const [uuid] of messages) {
|
|
421
|
+
const idx = entryIndex.get(uuid);
|
|
422
|
+
if (idx !== undefined && idx < absoluteLastBoundaryIdx && !preservedUuids.has(uuid)) {
|
|
423
|
+
toDelete.push(uuid);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
for (const uuid of toDelete)
|
|
427
|
+
messages.delete(uuid);
|
|
428
|
+
}
|
|
429
|
+
function applySnipRemovals(messages) {
|
|
430
|
+
const toDelete = new Set;
|
|
431
|
+
for (const entry of messages.values()) {
|
|
432
|
+
const removedUuids = entry.snipMetadata?.removedUuids;
|
|
433
|
+
if (!removedUuids)
|
|
434
|
+
continue;
|
|
435
|
+
for (const uuid of removedUuids)
|
|
436
|
+
toDelete.add(uuid);
|
|
437
|
+
}
|
|
438
|
+
if (toDelete.size === 0)
|
|
439
|
+
return;
|
|
440
|
+
const deletedParent = new Map;
|
|
441
|
+
let removedCount = 0;
|
|
442
|
+
for (const uuid of toDelete) {
|
|
443
|
+
const entry = messages.get(uuid);
|
|
444
|
+
if (!entry)
|
|
445
|
+
continue;
|
|
446
|
+
deletedParent.set(uuid, entry.parentUuid);
|
|
447
|
+
messages.delete(uuid);
|
|
448
|
+
removedCount++;
|
|
449
|
+
}
|
|
450
|
+
const resolve = (start) => {
|
|
451
|
+
const path = [];
|
|
452
|
+
const visited = new Set;
|
|
453
|
+
let cur = start;
|
|
454
|
+
while (cur && toDelete.has(cur)) {
|
|
455
|
+
if (visited.has(cur)) {
|
|
456
|
+
cur = null;
|
|
457
|
+
break;
|
|
458
|
+
}
|
|
459
|
+
visited.add(cur);
|
|
460
|
+
path.push(cur);
|
|
461
|
+
cur = deletedParent.get(cur);
|
|
462
|
+
if (cur === undefined) {
|
|
463
|
+
cur = null;
|
|
464
|
+
break;
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
for (const p of path)
|
|
468
|
+
deletedParent.set(p, cur);
|
|
469
|
+
return cur;
|
|
470
|
+
};
|
|
471
|
+
let relinkedCount = 0;
|
|
472
|
+
for (const [uuid, msg] of messages) {
|
|
473
|
+
if (!msg.parentUuid || !toDelete.has(msg.parentUuid))
|
|
474
|
+
continue;
|
|
475
|
+
messages.set(uuid, { ...msg, parentUuid: resolve(msg.parentUuid) });
|
|
476
|
+
relinkedCount++;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
function buildConversationChain(messages, leafMessage) {
|
|
480
|
+
const transcript = [];
|
|
481
|
+
const seen = new Set;
|
|
482
|
+
let currentMsg = leafMessage;
|
|
483
|
+
while (currentMsg) {
|
|
484
|
+
if (seen.has(currentMsg.uuid)) {
|
|
485
|
+
logForDebugging(`Cycle detected in parentUuid chain at message ${currentMsg.uuid}. Returning partial transcript.`, { level: "error" });
|
|
486
|
+
break;
|
|
487
|
+
}
|
|
488
|
+
seen.add(currentMsg.uuid);
|
|
489
|
+
transcript.push(currentMsg);
|
|
490
|
+
currentMsg = currentMsg.parentUuid ? messages.get(currentMsg.parentUuid) : undefined;
|
|
491
|
+
}
|
|
492
|
+
transcript.reverse();
|
|
493
|
+
return recoverOrphanedParallelToolResults(messages, transcript, seen);
|
|
494
|
+
}
|
|
495
|
+
function recoverOrphanedParallelToolResults(messages, chain, seen) {
|
|
496
|
+
const chainAssistants = chain.filter((m) => m.type === "assistant");
|
|
497
|
+
if (chainAssistants.length === 0)
|
|
498
|
+
return chain;
|
|
499
|
+
const anchorByMsgId = new Map;
|
|
500
|
+
for (const a of chainAssistants) {
|
|
501
|
+
const id = a.message?.id;
|
|
502
|
+
if (id)
|
|
503
|
+
anchorByMsgId.set(id, a);
|
|
504
|
+
}
|
|
505
|
+
const siblingsByMsgId = new Map;
|
|
506
|
+
const toolResultsByAsst = new Map;
|
|
507
|
+
for (const m of messages.values()) {
|
|
508
|
+
if (m.type === "assistant" && m.message?.id) {
|
|
509
|
+
const group = siblingsByMsgId.get(m.message.id);
|
|
510
|
+
if (group)
|
|
511
|
+
group.push(m);
|
|
512
|
+
else
|
|
513
|
+
siblingsByMsgId.set(m.message.id, [m]);
|
|
514
|
+
} else if (m.type === "user" && m.parentUuid && Array.isArray(m.message?.content) && m.message.content.some((b) => b.type === "tool_result")) {
|
|
515
|
+
const group = toolResultsByAsst.get(m.parentUuid);
|
|
516
|
+
if (group)
|
|
517
|
+
group.push(m);
|
|
518
|
+
else
|
|
519
|
+
toolResultsByAsst.set(m.parentUuid, [m]);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
const processedGroups = new Set;
|
|
523
|
+
const inserts = new Map;
|
|
524
|
+
let recoveredCount = 0;
|
|
525
|
+
for (const asst of chainAssistants) {
|
|
526
|
+
const msgId = asst.message?.id;
|
|
527
|
+
if (!msgId || processedGroups.has(msgId))
|
|
528
|
+
continue;
|
|
529
|
+
processedGroups.add(msgId);
|
|
530
|
+
const group = siblingsByMsgId.get(msgId) ?? [asst];
|
|
531
|
+
const orphanedSiblings = group.filter((s) => !seen.has(s.uuid));
|
|
532
|
+
const orphanedTRs = [];
|
|
533
|
+
for (const member of group) {
|
|
534
|
+
const trs = toolResultsByAsst.get(member.uuid);
|
|
535
|
+
if (!trs)
|
|
536
|
+
continue;
|
|
537
|
+
for (const tr of trs) {
|
|
538
|
+
if (!seen.has(tr.uuid))
|
|
539
|
+
orphanedTRs.push(tr);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
if (orphanedSiblings.length === 0 && orphanedTRs.length === 0)
|
|
543
|
+
continue;
|
|
544
|
+
orphanedSiblings.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
545
|
+
orphanedTRs.sort((a, b) => a.timestamp.localeCompare(b.timestamp));
|
|
546
|
+
const anchor = anchorByMsgId.get(msgId);
|
|
547
|
+
const recovered = [...orphanedSiblings, ...orphanedTRs];
|
|
548
|
+
for (const r of recovered)
|
|
549
|
+
seen.add(r.uuid);
|
|
550
|
+
recoveredCount += recovered.length;
|
|
551
|
+
inserts.set(anchor.uuid, recovered);
|
|
552
|
+
}
|
|
553
|
+
if (recoveredCount === 0)
|
|
554
|
+
return chain;
|
|
555
|
+
const result = [];
|
|
556
|
+
for (const m of chain) {
|
|
557
|
+
result.push(m);
|
|
558
|
+
const toInsert = inserts.get(m.uuid);
|
|
559
|
+
if (toInsert)
|
|
560
|
+
result.push(...toInsert);
|
|
561
|
+
}
|
|
562
|
+
return result;
|
|
563
|
+
}
|
|
564
|
+
var METADATA_TYPE_MARKERS = [
|
|
565
|
+
'"type":"summary"',
|
|
566
|
+
'"type":"custom-title"',
|
|
567
|
+
'"type":"tag"',
|
|
568
|
+
'"type":"agent-name"',
|
|
569
|
+
'"type":"agent-color"',
|
|
570
|
+
'"type":"agent-setting"',
|
|
571
|
+
'"type":"mode"',
|
|
572
|
+
'"type":"worktree-state"',
|
|
573
|
+
'"type":"goal-state"',
|
|
574
|
+
'"type":"pr-link"'
|
|
575
|
+
];
|
|
576
|
+
var METADATA_MARKER_BUFS = METADATA_TYPE_MARKERS.map((m) => Buffer.from(m));
|
|
577
|
+
var METADATA_PREFIX_BOUND = 25;
|
|
578
|
+
function resolveMetadataBuf(carry, chunkBuf) {
|
|
579
|
+
if (carry === null || carry.length === 0)
|
|
580
|
+
return chunkBuf;
|
|
581
|
+
if (carry.length < METADATA_PREFIX_BOUND) {
|
|
582
|
+
return Buffer.concat([carry, chunkBuf]);
|
|
583
|
+
}
|
|
584
|
+
if (carry[0] === 123) {
|
|
585
|
+
for (const m of METADATA_MARKER_BUFS) {
|
|
586
|
+
if (carry.compare(m, 0, m.length, 1, 1 + m.length) === 0) {
|
|
587
|
+
return Buffer.concat([carry, chunkBuf]);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
const firstNl = chunkBuf.indexOf(10);
|
|
592
|
+
return firstNl === -1 ? null : chunkBuf.subarray(firstNl + 1);
|
|
593
|
+
}
|
|
594
|
+
async function scanPreBoundaryMetadata(filePath, endOffset, opts) {
|
|
595
|
+
const { createReadStream } = await import("fs");
|
|
596
|
+
const NEWLINE = 10;
|
|
597
|
+
const stream = opts?.fd ? opts.fd.createReadStream({ end: endOffset - 1, autoClose: false }) : createReadStream(filePath, { end: endOffset - 1 });
|
|
598
|
+
const metadataLines = [];
|
|
599
|
+
let carry = null;
|
|
600
|
+
for await (const chunk of stream) {
|
|
601
|
+
const chunkBuf = chunk;
|
|
602
|
+
const buf = resolveMetadataBuf(carry, chunkBuf);
|
|
603
|
+
if (buf === null) {
|
|
604
|
+
carry = null;
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
let hasAnyMarker = false;
|
|
608
|
+
for (const m of METADATA_MARKER_BUFS) {
|
|
609
|
+
if (buf.includes(m)) {
|
|
610
|
+
hasAnyMarker = true;
|
|
611
|
+
break;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
if (hasAnyMarker) {
|
|
615
|
+
let lineStart = 0;
|
|
616
|
+
let nl = buf.indexOf(NEWLINE);
|
|
617
|
+
while (nl !== -1) {
|
|
618
|
+
for (const m of METADATA_MARKER_BUFS) {
|
|
619
|
+
const mIdx = buf.indexOf(m, lineStart);
|
|
620
|
+
if (mIdx !== -1 && mIdx < nl) {
|
|
621
|
+
metadataLines.push(buf.toString("utf-8", lineStart, nl));
|
|
622
|
+
break;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
lineStart = nl + 1;
|
|
626
|
+
nl = buf.indexOf(NEWLINE, lineStart);
|
|
627
|
+
}
|
|
628
|
+
carry = buf.subarray(lineStart);
|
|
629
|
+
} else {
|
|
630
|
+
const lastNl = buf.lastIndexOf(NEWLINE);
|
|
631
|
+
carry = lastNl >= 0 ? buf.subarray(lastNl + 1) : buf;
|
|
632
|
+
}
|
|
633
|
+
if (carry.length > 65536)
|
|
634
|
+
carry = null;
|
|
635
|
+
}
|
|
636
|
+
if (carry !== null && carry.length > 0) {
|
|
637
|
+
for (const m of METADATA_MARKER_BUFS) {
|
|
638
|
+
if (carry.includes(m)) {
|
|
639
|
+
metadataLines.push(carry.toString("utf-8"));
|
|
640
|
+
break;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
return metadataLines;
|
|
645
|
+
}
|
|
646
|
+
function pickDepthOneUuidCandidate(buf, lineStart, candidates) {
|
|
647
|
+
const QUOTE = 34;
|
|
648
|
+
const BACKSLASH = 92;
|
|
649
|
+
const OPEN_BRACE = 123;
|
|
650
|
+
const CLOSE_BRACE = 125;
|
|
651
|
+
let depth = 0;
|
|
652
|
+
let inString = false;
|
|
653
|
+
let escapeNext = false;
|
|
654
|
+
let ci = 0;
|
|
655
|
+
for (let i = lineStart;ci < candidates.length; i++) {
|
|
656
|
+
if (i === candidates[ci]) {
|
|
657
|
+
if (depth === 1 && !inString)
|
|
658
|
+
return candidates[ci];
|
|
659
|
+
ci++;
|
|
660
|
+
}
|
|
661
|
+
const b = buf[i];
|
|
662
|
+
if (escapeNext) {
|
|
663
|
+
escapeNext = false;
|
|
664
|
+
} else if (inString) {
|
|
665
|
+
if (b === BACKSLASH)
|
|
666
|
+
escapeNext = true;
|
|
667
|
+
else if (b === QUOTE)
|
|
668
|
+
inString = false;
|
|
669
|
+
} else if (b === QUOTE)
|
|
670
|
+
inString = true;
|
|
671
|
+
else if (b === OPEN_BRACE)
|
|
672
|
+
depth++;
|
|
673
|
+
else if (b === CLOSE_BRACE)
|
|
674
|
+
depth--;
|
|
675
|
+
}
|
|
676
|
+
return candidates.at(-1);
|
|
677
|
+
}
|
|
678
|
+
function walkChainBeforeParse(buf) {
|
|
679
|
+
const NEWLINE = 10;
|
|
680
|
+
const OPEN_BRACE = 123;
|
|
681
|
+
const QUOTE = 34;
|
|
682
|
+
const PARENT_PREFIX = Buffer.from('{"parentUuid":');
|
|
683
|
+
const UUID_KEY = Buffer.from('"uuid":"');
|
|
684
|
+
const SIDECHAIN_TRUE = Buffer.from('"isSidechain":true');
|
|
685
|
+
const UUID_LEN = 36;
|
|
686
|
+
const TS_SUFFIX = Buffer.from('","timestamp":"');
|
|
687
|
+
const TS_SUFFIX_LEN = TS_SUFFIX.length;
|
|
688
|
+
const PREFIX_LEN = PARENT_PREFIX.length;
|
|
689
|
+
const KEY_LEN = UUID_KEY.length;
|
|
690
|
+
const msgIdx = [];
|
|
691
|
+
const metaRanges = [];
|
|
692
|
+
const uuidToSlot = new Map;
|
|
693
|
+
let pos = 0;
|
|
694
|
+
const len = buf.length;
|
|
695
|
+
while (pos < len) {
|
|
696
|
+
const nl = buf.indexOf(NEWLINE, pos);
|
|
697
|
+
const lineEnd = nl === -1 ? len : nl + 1;
|
|
698
|
+
if (lineEnd - pos > PREFIX_LEN && buf[pos] === OPEN_BRACE && buf.compare(PARENT_PREFIX, 0, PREFIX_LEN, pos, pos + PREFIX_LEN) === 0) {
|
|
699
|
+
const parentStart = buf[pos + PREFIX_LEN] === QUOTE ? pos + PREFIX_LEN + 1 : -1;
|
|
700
|
+
let firstAny = -1;
|
|
701
|
+
let suffix0 = -1;
|
|
702
|
+
let suffixN;
|
|
703
|
+
let from = pos;
|
|
704
|
+
for (;; ) {
|
|
705
|
+
const next = buf.indexOf(UUID_KEY, from);
|
|
706
|
+
if (next < 0 || next >= lineEnd)
|
|
707
|
+
break;
|
|
708
|
+
if (firstAny < 0)
|
|
709
|
+
firstAny = next;
|
|
710
|
+
const after = next + KEY_LEN + UUID_LEN;
|
|
711
|
+
if (after + TS_SUFFIX_LEN <= lineEnd && buf.compare(TS_SUFFIX, 0, TS_SUFFIX_LEN, after, after + TS_SUFFIX_LEN) === 0) {
|
|
712
|
+
if (suffix0 < 0)
|
|
713
|
+
suffix0 = next;
|
|
714
|
+
else
|
|
715
|
+
(suffixN ??= [suffix0]).push(next);
|
|
716
|
+
}
|
|
717
|
+
from = next + KEY_LEN;
|
|
718
|
+
}
|
|
719
|
+
const uk = suffixN ? pickDepthOneUuidCandidate(buf, pos, suffixN) : suffix0 >= 0 ? suffix0 : firstAny;
|
|
720
|
+
if (uk >= 0) {
|
|
721
|
+
const uuidStart = uk + KEY_LEN;
|
|
722
|
+
const uuid = buf.toString("latin1", uuidStart, uuidStart + UUID_LEN);
|
|
723
|
+
uuidToSlot.set(uuid, msgIdx.length);
|
|
724
|
+
msgIdx.push(pos, lineEnd, parentStart);
|
|
725
|
+
} else {
|
|
726
|
+
metaRanges.push(pos, lineEnd);
|
|
727
|
+
}
|
|
728
|
+
} else {
|
|
729
|
+
metaRanges.push(pos, lineEnd);
|
|
730
|
+
}
|
|
731
|
+
pos = lineEnd;
|
|
732
|
+
}
|
|
733
|
+
let leafSlot = -1;
|
|
734
|
+
for (let i = msgIdx.length - 3;i >= 0; i -= 3) {
|
|
735
|
+
const sc = buf.indexOf(SIDECHAIN_TRUE, msgIdx[i]);
|
|
736
|
+
if (sc === -1 || sc >= msgIdx[i + 1]) {
|
|
737
|
+
leafSlot = i;
|
|
738
|
+
break;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
if (leafSlot < 0)
|
|
742
|
+
return buf;
|
|
743
|
+
const seen = new Set;
|
|
744
|
+
const chain = new Set;
|
|
745
|
+
let chainBytes = 0;
|
|
746
|
+
let slot = leafSlot;
|
|
747
|
+
while (slot !== undefined) {
|
|
748
|
+
if (seen.has(slot))
|
|
749
|
+
break;
|
|
750
|
+
seen.add(slot);
|
|
751
|
+
chain.add(msgIdx[slot]);
|
|
752
|
+
chainBytes += msgIdx[slot + 1] - msgIdx[slot];
|
|
753
|
+
const parentStart = msgIdx[slot + 2];
|
|
754
|
+
if (parentStart < 0)
|
|
755
|
+
break;
|
|
756
|
+
const parent = buf.toString("latin1", parentStart, parentStart + UUID_LEN);
|
|
757
|
+
slot = uuidToSlot.get(parent);
|
|
758
|
+
}
|
|
759
|
+
if (len - chainBytes < len >> 1)
|
|
760
|
+
return buf;
|
|
761
|
+
const parts = [];
|
|
762
|
+
let m = 0;
|
|
763
|
+
for (let i = 0;i < msgIdx.length; i += 3) {
|
|
764
|
+
const start = msgIdx[i];
|
|
765
|
+
while (m < metaRanges.length && metaRanges[m] < start) {
|
|
766
|
+
parts.push(buf.subarray(metaRanges[m], metaRanges[m + 1]));
|
|
767
|
+
m += 2;
|
|
768
|
+
}
|
|
769
|
+
if (chain.has(start)) {
|
|
770
|
+
parts.push(buf.subarray(start, msgIdx[i + 1]));
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
while (m < metaRanges.length) {
|
|
774
|
+
parts.push(buf.subarray(metaRanges[m], metaRanges[m + 1]));
|
|
775
|
+
m += 2;
|
|
776
|
+
}
|
|
777
|
+
return Buffer.concat(parts);
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
class TranscriptTooLargeError extends Error {
|
|
781
|
+
name = "TranscriptTooLargeError";
|
|
782
|
+
size;
|
|
783
|
+
maxBytes;
|
|
784
|
+
constructor(size, maxBytes) {
|
|
785
|
+
super(`transcript exceeds maxBytes (${size} > ${maxBytes} bytes)`);
|
|
786
|
+
this.size = size;
|
|
787
|
+
this.maxBytes = maxBytes;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
class TranscriptChangedDuringReadError extends Error {
|
|
792
|
+
name = "TranscriptChangedDuringReadError";
|
|
793
|
+
constructor() {
|
|
794
|
+
super("file changed during transcript read (not a stable snapshot)");
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
async function loadTranscriptFile(filePath, opts) {
|
|
798
|
+
const messages = new Map;
|
|
799
|
+
const summaries = new Map;
|
|
800
|
+
const customTitles = new Map;
|
|
801
|
+
const tags = new Map;
|
|
802
|
+
const worktreeStates = new Map;
|
|
803
|
+
const contentReplacements = new Map;
|
|
804
|
+
const goalStates = new Map;
|
|
805
|
+
try {
|
|
806
|
+
let buf = null;
|
|
807
|
+
let metadataLines = null;
|
|
808
|
+
let hasPreservedSegment = false;
|
|
809
|
+
const forceFull = opts?.precompactSkip === "force-full";
|
|
810
|
+
const useFdChain = opts !== undefined && (opts.precompactSkip !== undefined || opts.maxBytes !== undefined);
|
|
811
|
+
if (useFdChain) {
|
|
812
|
+
const noFollow = fsConstants.O_NOFOLLOW ?? 0;
|
|
813
|
+
const fd = await open(filePath, fsConstants.O_RDONLY | noFollow);
|
|
814
|
+
try {
|
|
815
|
+
const fst = await fd.stat();
|
|
816
|
+
if (opts?.expectIno !== undefined && fst.ino !== opts.expectIno) {
|
|
817
|
+
throw new TranscriptChangedDuringReadError;
|
|
818
|
+
}
|
|
819
|
+
if (opts?.maxBytes !== undefined && fst.size > opts.maxBytes) {
|
|
820
|
+
throw new TranscriptTooLargeError(fst.size, opts.maxBytes);
|
|
821
|
+
}
|
|
822
|
+
const skipEnabled = !forceFull && !isEnvTruthy(process.env.ATLAS_DISABLE_PRECOMPACT_SKIP);
|
|
823
|
+
if (skipEnabled && fst.size > SKIP_PRECOMPACT_THRESHOLD) {
|
|
824
|
+
const scan = await readTranscriptForLoad(filePath, fst.size, { fd });
|
|
825
|
+
buf = scan.postBoundaryBuf;
|
|
826
|
+
hasPreservedSegment = scan.hasPreservedSegment;
|
|
827
|
+
if (scan.boundaryStartOffset > 0) {
|
|
828
|
+
metadataLines = await scanPreBoundaryMetadata(filePath, scan.boundaryStartOffset, { fd });
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
if (buf === null) {
|
|
832
|
+
buf = Buffer.allocUnsafe(fst.size);
|
|
833
|
+
let filled = 0;
|
|
834
|
+
while (filled < fst.size) {
|
|
835
|
+
const len = Math.min(TRANSCRIPT_READ_CHUNK_SIZE, fst.size - filled);
|
|
836
|
+
const { bytesRead } = await fd.read(buf, filled, len, filled);
|
|
837
|
+
if (bytesRead <= 0) {
|
|
838
|
+
throw new TranscriptChangedDuringReadError;
|
|
839
|
+
}
|
|
840
|
+
filled += bytesRead;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
const fst2 = await fd.stat();
|
|
844
|
+
if (fst2.ino !== fst.ino || fst2.size !== fst.size) {
|
|
845
|
+
throw new TranscriptChangedDuringReadError;
|
|
846
|
+
}
|
|
847
|
+
} finally {
|
|
848
|
+
await fd.close();
|
|
849
|
+
}
|
|
850
|
+
} else if (!forceFull && !isEnvTruthy(process.env.ATLAS_DISABLE_PRECOMPACT_SKIP)) {
|
|
851
|
+
const { size } = await stat(filePath);
|
|
852
|
+
if (size > SKIP_PRECOMPACT_THRESHOLD) {
|
|
853
|
+
const scan = await readTranscriptForLoad(filePath, size);
|
|
854
|
+
buf = scan.postBoundaryBuf;
|
|
855
|
+
hasPreservedSegment = scan.hasPreservedSegment;
|
|
856
|
+
if (scan.boundaryStartOffset > 0) {
|
|
857
|
+
metadataLines = await scanPreBoundaryMetadata(filePath, scan.boundaryStartOffset);
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
buf ??= await readFile(filePath);
|
|
861
|
+
} else {
|
|
862
|
+
buf = await readFile(filePath);
|
|
863
|
+
}
|
|
864
|
+
if (!opts?.keepAllLeaves && !forceFull && !hasPreservedSegment && !isEnvTruthy(process.env.ATLAS_DISABLE_PRECOMPACT_SKIP) && buf.length > SKIP_PRECOMPACT_THRESHOLD) {
|
|
865
|
+
buf = walkChainBeforeParse(buf);
|
|
866
|
+
}
|
|
867
|
+
if (metadataLines && metadataLines.length > 0) {
|
|
868
|
+
const metaEntries = parseJSONL(Buffer.from(metadataLines.join(`
|
|
869
|
+
`)));
|
|
870
|
+
for (const entry of metaEntries) {
|
|
871
|
+
if (entry.type === "summary" && entry.leafUuid) {
|
|
872
|
+
summaries.set(entry.leafUuid, entry.summary);
|
|
873
|
+
} else if (entry.type === "custom-title" && entry.sessionId) {
|
|
874
|
+
customTitles.set(entry.sessionId, entry.customTitle);
|
|
875
|
+
} else if (entry.type === "tag" && entry.sessionId) {
|
|
876
|
+
tags.set(entry.sessionId, entry.tag);
|
|
877
|
+
} else if (entry.type === "worktree-state" && entry.sessionId) {
|
|
878
|
+
worktreeStates.set(entry.sessionId, entry.worktreeSession);
|
|
879
|
+
} else if (entry.type === "goal-state" && entry.sessionId) {
|
|
880
|
+
goalStates.set(entry.sessionId, entry.goal);
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
const entries = parseJSONL(buf);
|
|
885
|
+
const progressBridge = new Map;
|
|
886
|
+
for (const entry of entries) {
|
|
887
|
+
if (isLegacyProgressEntry(entry)) {
|
|
888
|
+
const progressEntry = entry;
|
|
889
|
+
const parent = progressEntry.parentUuid;
|
|
890
|
+
progressBridge.set(progressEntry.uuid, parent && progressBridge.has(parent) ? progressBridge.get(parent) ?? null : parent);
|
|
891
|
+
continue;
|
|
892
|
+
}
|
|
893
|
+
if (isTranscriptMessage(entry)) {
|
|
894
|
+
if (entry.parentUuid && progressBridge.has(entry.parentUuid)) {
|
|
895
|
+
entry.parentUuid = progressBridge.get(entry.parentUuid) ?? null;
|
|
896
|
+
}
|
|
897
|
+
messages.set(entry.uuid, entry);
|
|
898
|
+
} else if (entry.type === "summary" && entry.leafUuid) {
|
|
899
|
+
summaries.set(entry.leafUuid, entry.summary);
|
|
900
|
+
} else if (entry.type === "custom-title" && entry.sessionId) {
|
|
901
|
+
customTitles.set(entry.sessionId, entry.customTitle);
|
|
902
|
+
} else if (entry.type === "tag" && entry.sessionId) {
|
|
903
|
+
tags.set(entry.sessionId, entry.tag);
|
|
904
|
+
} else if (entry.type === "worktree-state" && entry.sessionId) {
|
|
905
|
+
worktreeStates.set(entry.sessionId, entry.worktreeSession);
|
|
906
|
+
} else if (entry.type === "goal-state" && entry.sessionId) {
|
|
907
|
+
goalStates.set(entry.sessionId, entry.goal);
|
|
908
|
+
} else if (entry.type === "content-replacement" && !entry.agentId) {
|
|
909
|
+
const existing = contentReplacements.get(entry.sessionId) ?? [];
|
|
910
|
+
contentReplacements.set(entry.sessionId, existing);
|
|
911
|
+
existing.push(...entry.replacements);
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
} catch (e) {
|
|
915
|
+
if (e instanceof TranscriptTooLargeError || e instanceof TranscriptChangedDuringReadError) {
|
|
916
|
+
throw e;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
applyPreservedSegmentRelinks(messages);
|
|
920
|
+
applySnipRemovals(messages);
|
|
921
|
+
const allMessages = [...messages.values()];
|
|
922
|
+
const parentUuids = new Set(allMessages.map((msg) => msg.parentUuid).filter((uuid) => uuid !== null));
|
|
923
|
+
const terminalMessages = allMessages.filter((msg) => !parentUuids.has(msg.uuid));
|
|
924
|
+
const leafUuids = new Set;
|
|
925
|
+
let hasCycle = false;
|
|
926
|
+
for (const terminal of terminalMessages) {
|
|
927
|
+
const seen = new Set;
|
|
928
|
+
let current = terminal;
|
|
929
|
+
while (current) {
|
|
930
|
+
if (seen.has(current.uuid)) {
|
|
931
|
+
hasCycle = true;
|
|
932
|
+
break;
|
|
933
|
+
}
|
|
934
|
+
seen.add(current.uuid);
|
|
935
|
+
if (current.type === "user" || current.type === "assistant") {
|
|
936
|
+
leafUuids.add(current.uuid);
|
|
937
|
+
break;
|
|
938
|
+
}
|
|
939
|
+
current = current.parentUuid ? messages.get(current.parentUuid) : undefined;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
return {
|
|
943
|
+
messages,
|
|
944
|
+
summaries,
|
|
945
|
+
customTitles,
|
|
946
|
+
tags,
|
|
947
|
+
worktreeStates,
|
|
948
|
+
contentReplacements,
|
|
949
|
+
goalStates,
|
|
950
|
+
leafUuids
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
// src/engine/session/readonly.ts
|
|
955
|
+
async function loadTranscriptFull(filePath, opts) {
|
|
956
|
+
return loadTranscriptFile(filePath, {
|
|
957
|
+
precompactSkip: "force-full",
|
|
958
|
+
maxBytes: opts?.maxBytes,
|
|
959
|
+
expectIno: opts?.expectIno
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// src/atlascode/web/cursorLedger.ts
|
|
964
|
+
import { randomUUID } from "node:crypto";
|
|
965
|
+
|
|
966
|
+
// src/atlascode/web/errors.ts
|
|
967
|
+
class WebSessionError extends Error {
|
|
968
|
+
code;
|
|
969
|
+
retryable;
|
|
970
|
+
constructor(code, message, retryable) {
|
|
971
|
+
super(message);
|
|
972
|
+
this.name = "WebSessionError";
|
|
973
|
+
this.code = code;
|
|
974
|
+
if (retryable !== undefined)
|
|
975
|
+
this.retryable = retryable;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
// src/atlascode/web/cursorLedger.ts
|
|
980
|
+
class CursorLedger {
|
|
981
|
+
capacity;
|
|
982
|
+
ttlMs;
|
|
983
|
+
maxPayloadBytes;
|
|
984
|
+
onActiveEvict;
|
|
985
|
+
entries = new Map;
|
|
986
|
+
payloadBytes = new Map;
|
|
987
|
+
constructor(capacity, ttlMs, maxPayloadBytes, onActiveEvict) {
|
|
988
|
+
this.capacity = capacity;
|
|
989
|
+
this.ttlMs = ttlMs;
|
|
990
|
+
this.maxPayloadBytes = maxPayloadBytes;
|
|
991
|
+
this.onActiveEvict = onActiveEvict;
|
|
992
|
+
}
|
|
993
|
+
issue(binding, payloadBytes = 0) {
|
|
994
|
+
this.evictForInsert(payloadBytes);
|
|
995
|
+
const token = randomUUID();
|
|
996
|
+
this.entries.set(token, {
|
|
997
|
+
token,
|
|
998
|
+
binding,
|
|
999
|
+
expiresAt: Date.now() + this.ttlMs,
|
|
1000
|
+
pinned: false
|
|
1001
|
+
});
|
|
1002
|
+
this.payloadBytes.set(token, payloadBytes);
|
|
1003
|
+
return token;
|
|
1004
|
+
}
|
|
1005
|
+
pin(token) {
|
|
1006
|
+
const e = this.entries.get(token);
|
|
1007
|
+
if (e)
|
|
1008
|
+
e.pinned = true;
|
|
1009
|
+
}
|
|
1010
|
+
unpin(token) {
|
|
1011
|
+
const e = this.entries.get(token);
|
|
1012
|
+
if (e)
|
|
1013
|
+
e.pinned = false;
|
|
1014
|
+
}
|
|
1015
|
+
refreshExpiry(token) {
|
|
1016
|
+
const e = this.entries.get(token);
|
|
1017
|
+
if (e)
|
|
1018
|
+
e.expiresAt = Date.now() + this.ttlMs;
|
|
1019
|
+
}
|
|
1020
|
+
verify(token, who) {
|
|
1021
|
+
const e = this.entries.get(token);
|
|
1022
|
+
if (!e) {
|
|
1023
|
+
return { ok: false, why: "unknown", message: "cursor unknown (restart or forged)" };
|
|
1024
|
+
}
|
|
1025
|
+
const b = e.binding;
|
|
1026
|
+
if (b.productId !== who.productId || b.scopeId !== who.scopeId || b.sessionId !== who.sessionId) {
|
|
1027
|
+
return { ok: false, why: "mismatch", message: "cursor bound to a different domain" };
|
|
1028
|
+
}
|
|
1029
|
+
if (Date.now() > e.expiresAt) {
|
|
1030
|
+
this.entries.delete(token);
|
|
1031
|
+
this.payloadBytes.delete(token);
|
|
1032
|
+
return { ok: false, why: "expired", message: "cursor expired" };
|
|
1033
|
+
}
|
|
1034
|
+
this.entries.delete(token);
|
|
1035
|
+
this.entries.set(token, e);
|
|
1036
|
+
return { ok: true, binding: b };
|
|
1037
|
+
}
|
|
1038
|
+
totalPayloadBytes() {
|
|
1039
|
+
let n = 0;
|
|
1040
|
+
for (const v of this.payloadBytes.values())
|
|
1041
|
+
n += v;
|
|
1042
|
+
return n;
|
|
1043
|
+
}
|
|
1044
|
+
size() {
|
|
1045
|
+
return this.entries.size;
|
|
1046
|
+
}
|
|
1047
|
+
evictForInsert(incomingBytes) {
|
|
1048
|
+
const now = Date.now();
|
|
1049
|
+
for (const [t, e] of this.entries) {
|
|
1050
|
+
if (now > e.expiresAt) {
|
|
1051
|
+
this.entries.delete(t);
|
|
1052
|
+
this.payloadBytes.delete(t);
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
while (this.entries.size >= this.capacity || this.totalPayloadBytes() + incomingBytes > this.maxPayloadBytes) {
|
|
1056
|
+
const unpinned = [...this.entries.values()].filter((e) => !e.pinned);
|
|
1057
|
+
const victim = unpinned[0] ?? this.entries.values().next().value;
|
|
1058
|
+
if (!victim)
|
|
1059
|
+
break;
|
|
1060
|
+
this.entries.delete(victim.token);
|
|
1061
|
+
this.payloadBytes.delete(victim.token);
|
|
1062
|
+
if (victim.pinned) {
|
|
1063
|
+
this.onActiveEvict?.(victim.token, victim.binding);
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
// src/atlascode/web/limits.ts
|
|
1070
|
+
var MIB = 1024 * 1024;
|
|
1071
|
+
var DEFAULT_MAX_TRANSCRIPT_BYTES = 64 * MIB;
|
|
1072
|
+
var HARD_MAX_TRANSCRIPT_BYTES = 256 * MIB;
|
|
1073
|
+
var DEFAULT_MAX_SCAN_SESSIONS = 4096;
|
|
1074
|
+
var HARD_MAX_SCAN_SESSIONS = 16384;
|
|
1075
|
+
var HARD_MAX_SCOPES_PER_RUNTIME = 128;
|
|
1076
|
+
var DEFAULT_PAGE_SIZE = 50;
|
|
1077
|
+
var HARD_MAX_PAGE_SIZE = 200;
|
|
1078
|
+
var DEFAULT_MAX_RECORD_BYTES = MIB;
|
|
1079
|
+
var HARD_MAX_RECORD_BYTES = 8 * MIB;
|
|
1080
|
+
var DEFAULT_MAX_PARSE_RECORDS = 1e5;
|
|
1081
|
+
var HARD_MAX_PARSE_RECORDS = 500000;
|
|
1082
|
+
var DEFAULT_MAX_PROJECTION_BYTES = 4 * MIB;
|
|
1083
|
+
var HARD_MAX_PROJECTION_BYTES = 16 * MIB;
|
|
1084
|
+
var TITLE_HEAD_BYTES = 64 * 1024;
|
|
1085
|
+
var TITLE_MAX_CODE_POINTS = 512;
|
|
1086
|
+
var TITLE_USER_MESSAGE_CODE_POINTS = 120;
|
|
1087
|
+
var DEFAULT_MAX_SUBSCRIPTIONS = 16;
|
|
1088
|
+
var HARD_MAX_SUBSCRIPTIONS = 64;
|
|
1089
|
+
var DEFAULT_MAX_CONCURRENT_READS = 4;
|
|
1090
|
+
var HARD_MAX_CONCURRENT_READS = 16;
|
|
1091
|
+
var DEFAULT_MAX_PENDING_EVENTS = 8;
|
|
1092
|
+
var HARD_MAX_PENDING_EVENTS = 32;
|
|
1093
|
+
var DEFAULT_MAX_PENDING_BYTES = 8 * MIB;
|
|
1094
|
+
var HARD_MAX_PENDING_BYTES = 32 * MIB;
|
|
1095
|
+
var DEFAULT_POLLING_INTERVAL_MS = 1000;
|
|
1096
|
+
var HARD_MIN_POLLING_INTERVAL_MS = 100;
|
|
1097
|
+
var HARD_MAX_POLLING_INTERVAL_MS = 60000;
|
|
1098
|
+
var DEFAULT_REQUEST_DEADLINE_MS = 1e4;
|
|
1099
|
+
var HARD_MIN_REQUEST_DEADLINE_MS = 1;
|
|
1100
|
+
var HARD_MAX_REQUEST_DEADLINE_MS = 60000;
|
|
1101
|
+
var DEFAULT_IDLE_LEASE_MS = 120000;
|
|
1102
|
+
var HARD_MIN_IDLE_LEASE_MS = 1000;
|
|
1103
|
+
var HARD_MAX_IDLE_LEASE_MS = 600000;
|
|
1104
|
+
var DEFAULT_CURSOR_TTL_MS = 600000;
|
|
1105
|
+
var HARD_MIN_CURSOR_TTL_MS = 1000;
|
|
1106
|
+
var HARD_MAX_CURSOR_TTL_MS = 3600000;
|
|
1107
|
+
var DEFAULT_CLOSE_DEADLINE_MS = 2000;
|
|
1108
|
+
var HARD_MIN_CLOSE_DEADLINE_MS = 1;
|
|
1109
|
+
var HARD_MAX_CLOSE_DEADLINE_MS = 1e4;
|
|
1110
|
+
var DEFAULT_LEDGER_CAPACITY = 128;
|
|
1111
|
+
var HARD_MAX_LEDGER_CAPACITY = 1024;
|
|
1112
|
+
var DEFAULT_LEDGER_PAYLOAD_BYTES = 16 * MIB;
|
|
1113
|
+
var HARD_MAX_LEDGER_PAYLOAD_BYTES = 64 * MIB;
|
|
1114
|
+
var READ_CHUNK_SIZE = 64 * 1024;
|
|
1115
|
+
var PARSE_BATCH_SIZE = 256;
|
|
1116
|
+
function validateBoundedInt(name, value, defaultValue, hardMax, hardMin = 1) {
|
|
1117
|
+
if (value === undefined)
|
|
1118
|
+
return defaultValue;
|
|
1119
|
+
if (typeof value !== "number" || Number.isNaN(value) || !Number.isFinite(value) || !Number.isInteger(value) || value < hardMin || value > hardMax) {
|
|
1120
|
+
throw new WebSessionError("invalidRequest", `limit ${name} must be an integer in [${hardMin}, ${hardMax}]`);
|
|
1121
|
+
}
|
|
1122
|
+
return value;
|
|
1123
|
+
}
|
|
1124
|
+
|
|
1125
|
+
// src/atlascode/web/projection.ts
|
|
1126
|
+
var ACTIVITY_LABEL_MAX = 256;
|
|
1127
|
+
function serializedProjectionBytes(p) {
|
|
1128
|
+
return Buffer.byteLength(JSON.stringify(p));
|
|
1129
|
+
}
|
|
1130
|
+
function projectBlocks(msg) {
|
|
1131
|
+
const blocks = [];
|
|
1132
|
+
const content = msg.message?.content;
|
|
1133
|
+
const pushText = (text) => {
|
|
1134
|
+
if (typeof text === "string" && text.length > 0) {
|
|
1135
|
+
blocks.push({ kind: "text", text });
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1138
|
+
if (typeof content === "string") {
|
|
1139
|
+
pushText(content);
|
|
1140
|
+
} else if (Array.isArray(content)) {
|
|
1141
|
+
for (const item of content) {
|
|
1142
|
+
if (!item || typeof item !== "object")
|
|
1143
|
+
continue;
|
|
1144
|
+
const rec = item;
|
|
1145
|
+
if (rec.type === "text") {
|
|
1146
|
+
pushText(rec.text);
|
|
1147
|
+
} else if (rec.type === "tool_use") {
|
|
1148
|
+
const name = typeof rec.name === "string" ? rec.name : "activity";
|
|
1149
|
+
const label = name.length > ACTIVITY_LABEL_MAX ? name.slice(0, ACTIVITY_LABEL_MAX) : name;
|
|
1150
|
+
blocks.push({ kind: "activity", label });
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
return blocks;
|
|
1155
|
+
}
|
|
1156
|
+
function computeLeafUuids(messages) {
|
|
1157
|
+
const all = [...messages.values()];
|
|
1158
|
+
const parentUuids = new Set(all.map((m) => m.parentUuid).filter((u) => u !== null));
|
|
1159
|
+
const terminals = all.filter((m) => !parentUuids.has(m.uuid));
|
|
1160
|
+
const leafUuids = new Set;
|
|
1161
|
+
for (const terminal of terminals) {
|
|
1162
|
+
const seen = new Set;
|
|
1163
|
+
let current = terminal;
|
|
1164
|
+
while (current) {
|
|
1165
|
+
if (seen.has(current.uuid))
|
|
1166
|
+
break;
|
|
1167
|
+
seen.add(current.uuid);
|
|
1168
|
+
if (current.type === "user" || current.type === "assistant") {
|
|
1169
|
+
leafUuids.add(current.uuid);
|
|
1170
|
+
break;
|
|
1171
|
+
}
|
|
1172
|
+
current = current.parentUuid ? messages.get(current.parentUuid) : undefined;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
return leafUuids;
|
|
1176
|
+
}
|
|
1177
|
+
function projectConversation(load, meta, engine) {
|
|
1178
|
+
const { messages, leafUuids } = load;
|
|
1179
|
+
let leaf;
|
|
1180
|
+
for (const uuid of leafUuids) {
|
|
1181
|
+
const m = messages.get(uuid);
|
|
1182
|
+
if (!m)
|
|
1183
|
+
continue;
|
|
1184
|
+
if (!leaf || (m.timestamp ?? "") >= (leaf.timestamp ?? "")) {
|
|
1185
|
+
leaf = m;
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
const chain = leaf ? engine.buildConversationChain(messages, leaf) : [];
|
|
1189
|
+
const out = [];
|
|
1190
|
+
for (const m of chain) {
|
|
1191
|
+
if (m.type !== "user" && m.type !== "assistant")
|
|
1192
|
+
continue;
|
|
1193
|
+
const blocks = projectBlocks(m);
|
|
1194
|
+
if (blocks.length === 0)
|
|
1195
|
+
continue;
|
|
1196
|
+
out.push({
|
|
1197
|
+
id: m.uuid,
|
|
1198
|
+
role: m.type,
|
|
1199
|
+
createdAt: m.timestamp ?? null,
|
|
1200
|
+
blocks
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
return {
|
|
1204
|
+
sessionId: meta.sessionId,
|
|
1205
|
+
productId: meta.productId,
|
|
1206
|
+
scopeId: meta.scopeId,
|
|
1207
|
+
semantics: "persisted-effective-conversation",
|
|
1208
|
+
messages: out,
|
|
1209
|
+
truncated: false
|
|
1210
|
+
};
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
// src/atlascode/web/follow.ts
|
|
1214
|
+
function rankOf(ev) {
|
|
1215
|
+
if (ev.kind === "closed")
|
|
1216
|
+
return 4;
|
|
1217
|
+
if (ev.kind === "error") {
|
|
1218
|
+
return ev.error.code === "cancelled" ? 3 : 2;
|
|
1219
|
+
}
|
|
1220
|
+
return 0;
|
|
1221
|
+
}
|
|
1222
|
+
var isDataEvent = (ev) => ev.kind === "baseline" || ev.kind === "replacement";
|
|
1223
|
+
function envelope(deps) {
|
|
1224
|
+
return {
|
|
1225
|
+
schemaVersion: 0,
|
|
1226
|
+
productId: deps.productId,
|
|
1227
|
+
scopeId: deps.scopeId,
|
|
1228
|
+
subscriptionId: deps.subscriptionId,
|
|
1229
|
+
...deps.requestId ? { requestId: deps.requestId } : {}
|
|
1230
|
+
};
|
|
1231
|
+
}
|
|
1232
|
+
function buildProjection(state, deps) {
|
|
1233
|
+
return projectConversation(state, {
|
|
1234
|
+
sessionId: deps.sessionId,
|
|
1235
|
+
productId: deps.productId,
|
|
1236
|
+
scopeId: deps.scopeId
|
|
1237
|
+
}, { buildConversationChain: deps.buildConversationChain });
|
|
1238
|
+
}
|
|
1239
|
+
var CLOSE_JOIN_TIMEOUT_MS = 2000;
|
|
1240
|
+
var BASELINE_SAMPLE_ATTEMPTS = 3;
|
|
1241
|
+
function createFollowSubscription(deps) {
|
|
1242
|
+
const { adapter, limits, ledger } = deps;
|
|
1243
|
+
let running = false;
|
|
1244
|
+
let finished = false;
|
|
1245
|
+
let terminalEvent = null;
|
|
1246
|
+
let terminalRank = -1;
|
|
1247
|
+
let terminalDelivered = false;
|
|
1248
|
+
const queue = [];
|
|
1249
|
+
let queuedBytes = 0;
|
|
1250
|
+
const waiters = [];
|
|
1251
|
+
let generation = crypto.randomUUID();
|
|
1252
|
+
let baselineId = crypto.randomUUID();
|
|
1253
|
+
let revision = 0;
|
|
1254
|
+
let state = null;
|
|
1255
|
+
let offset = 0;
|
|
1256
|
+
let anchorIno = -1;
|
|
1257
|
+
let lastMtimeMs = -1;
|
|
1258
|
+
let pendingPartial = Buffer.alloc(0);
|
|
1259
|
+
const issuedTokens = [];
|
|
1260
|
+
let leaseTimer = null;
|
|
1261
|
+
let wakeSleep = null;
|
|
1262
|
+
let closeRequested = false;
|
|
1263
|
+
let released = false;
|
|
1264
|
+
let workerDoneResolve = null;
|
|
1265
|
+
const workerDone = new Promise((resolve) => {
|
|
1266
|
+
workerDoneResolve = resolve;
|
|
1267
|
+
});
|
|
1268
|
+
function notify() {
|
|
1269
|
+
while (waiters.length > 0) {
|
|
1270
|
+
waiters.shift()();
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
function releaseOnce() {
|
|
1274
|
+
if (!released) {
|
|
1275
|
+
released = true;
|
|
1276
|
+
deps.onRelease();
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
function disarmLease() {
|
|
1280
|
+
if (leaseTimer) {
|
|
1281
|
+
clearTimeout(leaseTimer);
|
|
1282
|
+
leaseTimer = null;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
function armLease() {
|
|
1286
|
+
disarmLease();
|
|
1287
|
+
leaseTimer = setTimeout(() => {
|
|
1288
|
+
setTerminal(closedEvent("lease expired (idle)"));
|
|
1289
|
+
}, limits.idleLeaseMs);
|
|
1290
|
+
}
|
|
1291
|
+
function closedEvent(reason) {
|
|
1292
|
+
return { ...envelope(deps), kind: "closed", reason };
|
|
1293
|
+
}
|
|
1294
|
+
function errorEvent(code, message, retryable) {
|
|
1295
|
+
const err = { code, message };
|
|
1296
|
+
if (retryable !== undefined)
|
|
1297
|
+
err.retryable = retryable;
|
|
1298
|
+
return { ...envelope(deps), kind: "error", error: err };
|
|
1299
|
+
}
|
|
1300
|
+
function stripTerminalFromQueue() {
|
|
1301
|
+
for (let i = queue.length - 1;i >= 0; i--) {
|
|
1302
|
+
const k = queue[i].kind;
|
|
1303
|
+
if (k === "error" || k === "closed")
|
|
1304
|
+
queue.splice(i, 1);
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
function setTerminal(ev) {
|
|
1308
|
+
if (finished)
|
|
1309
|
+
return;
|
|
1310
|
+
if (ev.kind !== "closed" && ev.kind !== "error")
|
|
1311
|
+
return;
|
|
1312
|
+
const rank = ev.kind === "closed" ? 4 : rankOf(ev);
|
|
1313
|
+
if (terminalEvent && rank <= terminalRank)
|
|
1314
|
+
return;
|
|
1315
|
+
stripTerminalFromQueue();
|
|
1316
|
+
if (ev.kind === "error") {
|
|
1317
|
+
queue.push(ev);
|
|
1318
|
+
queue.push(closedEvent("terminal error"));
|
|
1319
|
+
} else {
|
|
1320
|
+
queue.push(ev);
|
|
1321
|
+
}
|
|
1322
|
+
terminalEvent = closedEvent("terminal");
|
|
1323
|
+
terminalRank = rank;
|
|
1324
|
+
running = false;
|
|
1325
|
+
disarmLease();
|
|
1326
|
+
for (const t of issuedTokens)
|
|
1327
|
+
ledger.unpin(t);
|
|
1328
|
+
notify();
|
|
1329
|
+
}
|
|
1330
|
+
function queueData(ev) {
|
|
1331
|
+
if (terminalEvent || finished)
|
|
1332
|
+
return;
|
|
1333
|
+
const bytes = serializedProjectionBytes(ev);
|
|
1334
|
+
if (bytes > limits.pendingBytes || bytes > limits.maxProjectionBytes) {
|
|
1335
|
+
setTerminal(errorEvent("resourceLimit", `event exceeds serialization limit (${bytes} bytes)`));
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
const dataCount = queue.filter(isDataEvent).length;
|
|
1339
|
+
if (dataCount >= limits.pendingEvents || queuedBytes + bytes > limits.pendingBytes) {
|
|
1340
|
+
for (let i = queue.length - 1;i >= 0; i--) {
|
|
1341
|
+
if (isDataEvent(queue[i])) {
|
|
1342
|
+
const dropped = queue.splice(i, 1)[0];
|
|
1343
|
+
queuedBytes -= serializedProjectionBytes(dropped);
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
}
|
|
1347
|
+
queue.push(ev);
|
|
1348
|
+
queuedBytes += bytes;
|
|
1349
|
+
notify();
|
|
1350
|
+
}
|
|
1351
|
+
function interrupted() {
|
|
1352
|
+
return terminalEvent !== null || finished || closeRequested;
|
|
1353
|
+
}
|
|
1354
|
+
async function issueBaseline(reason) {
|
|
1355
|
+
if (interrupted())
|
|
1356
|
+
return false;
|
|
1357
|
+
if (deps.signal?.aborted) {
|
|
1358
|
+
setTerminal(errorEvent("cancelled", "follow aborted"));
|
|
1359
|
+
return false;
|
|
1360
|
+
}
|
|
1361
|
+
if (reason) {
|
|
1362
|
+
queueData({
|
|
1363
|
+
...envelope(deps),
|
|
1364
|
+
kind: "resetRequired",
|
|
1365
|
+
generation,
|
|
1366
|
+
reason
|
|
1367
|
+
});
|
|
1368
|
+
if (terminalEvent)
|
|
1369
|
+
return false;
|
|
1370
|
+
}
|
|
1371
|
+
let loaded = null;
|
|
1372
|
+
let stPost = null;
|
|
1373
|
+
for (let attempt = 0;attempt < BASELINE_SAMPLE_ATTEMPTS; attempt++) {
|
|
1374
|
+
const stPre = await adapter.statTranscript(deps.scopeId, deps.sessionId);
|
|
1375
|
+
if (!stPre) {
|
|
1376
|
+
setTerminal(errorEvent("notFound", "session file missing before baseline"));
|
|
1377
|
+
return false;
|
|
1378
|
+
}
|
|
1379
|
+
if (interrupted())
|
|
1380
|
+
return false;
|
|
1381
|
+
try {
|
|
1382
|
+
const filePath = await deps.resolvePath(deps.scopeId, deps.sessionId);
|
|
1383
|
+
if (interrupted())
|
|
1384
|
+
return false;
|
|
1385
|
+
loaded = await deps.loadFull(filePath);
|
|
1386
|
+
} catch (e) {
|
|
1387
|
+
if (e instanceof TranscriptTooLargeError) {
|
|
1388
|
+
setTerminal(errorEvent("resourceLimit", `transcript exceeds limit (${e.size} > ${e.maxBytes} bytes)`, false));
|
|
1389
|
+
return false;
|
|
1390
|
+
}
|
|
1391
|
+
if (e instanceof WebSessionError) {
|
|
1392
|
+
setTerminal(errorEvent(e.code, e.message, e.retryable));
|
|
1393
|
+
} else {
|
|
1394
|
+
setTerminal(errorEvent("ioUnavailable", `baseline load failed: ${String(e)}`, true));
|
|
1395
|
+
}
|
|
1396
|
+
return false;
|
|
1397
|
+
}
|
|
1398
|
+
if (interrupted())
|
|
1399
|
+
return false;
|
|
1400
|
+
stPost = await adapter.statTranscript(deps.scopeId, deps.sessionId);
|
|
1401
|
+
if (!stPost) {
|
|
1402
|
+
setTerminal(errorEvent("notFound", "session file disappeared during baseline"));
|
|
1403
|
+
return false;
|
|
1404
|
+
}
|
|
1405
|
+
if (stPost.ino === stPre.ino && stPost.sizeBytes === stPre.sizeBytes && stPost.mtimeMs === stPre.mtimeMs) {
|
|
1406
|
+
break;
|
|
1407
|
+
}
|
|
1408
|
+
loaded = null;
|
|
1409
|
+
stPost = null;
|
|
1410
|
+
if (interrupted())
|
|
1411
|
+
return false;
|
|
1412
|
+
}
|
|
1413
|
+
if (!loaded || !stPost) {
|
|
1414
|
+
setTerminal(errorEvent("ioUnavailable", "baseline snapshot never stabilized under concurrent writes", true));
|
|
1415
|
+
return false;
|
|
1416
|
+
}
|
|
1417
|
+
state = { messages: loaded.messages, leafUuids: loaded.leafUuids };
|
|
1418
|
+
generation = crypto.randomUUID();
|
|
1419
|
+
baselineId = crypto.randomUUID();
|
|
1420
|
+
revision = 0;
|
|
1421
|
+
offset = stPost.sizeBytes;
|
|
1422
|
+
anchorIno = stPost.ino;
|
|
1423
|
+
lastMtimeMs = stPost.mtimeMs;
|
|
1424
|
+
pendingPartial = Buffer.alloc(0);
|
|
1425
|
+
const projection = buildProjection(state, deps);
|
|
1426
|
+
const bytes = serializedProjectionBytes(projection);
|
|
1427
|
+
if (bytes > limits.maxProjectionBytes) {
|
|
1428
|
+
setTerminal(errorEvent("resourceLimit", `projection exceeds limit (${bytes} bytes)`));
|
|
1429
|
+
return false;
|
|
1430
|
+
}
|
|
1431
|
+
const cursor = ledger.issue({
|
|
1432
|
+
v: 1,
|
|
1433
|
+
productId: deps.productId,
|
|
1434
|
+
scopeId: deps.scopeId,
|
|
1435
|
+
sessionId: deps.sessionId,
|
|
1436
|
+
baselineId,
|
|
1437
|
+
generation,
|
|
1438
|
+
revision,
|
|
1439
|
+
byteOffset: offset,
|
|
1440
|
+
ino: anchorIno
|
|
1441
|
+
}, bytes);
|
|
1442
|
+
ledger.pin(cursor);
|
|
1443
|
+
issuedTokens.push(cursor);
|
|
1444
|
+
queueData({
|
|
1445
|
+
...envelope(deps),
|
|
1446
|
+
kind: "baseline",
|
|
1447
|
+
generation,
|
|
1448
|
+
baselineId,
|
|
1449
|
+
revision,
|
|
1450
|
+
cursor,
|
|
1451
|
+
projection
|
|
1452
|
+
});
|
|
1453
|
+
return true;
|
|
1454
|
+
}
|
|
1455
|
+
function ingestLines(lines) {
|
|
1456
|
+
if (!state)
|
|
1457
|
+
return { changed: false, corrupt: null, oversize: false };
|
|
1458
|
+
const parsed = [];
|
|
1459
|
+
for (const line of lines) {
|
|
1460
|
+
if (line.length > limits.maxRecordBytes) {
|
|
1461
|
+
return { changed: false, corrupt: null, oversize: true };
|
|
1462
|
+
}
|
|
1463
|
+
let entry;
|
|
1464
|
+
try {
|
|
1465
|
+
entry = JSON.parse(line.toString("utf8"));
|
|
1466
|
+
} catch {
|
|
1467
|
+
return { changed: false, corrupt: "unparseable complete record", oversize: false };
|
|
1468
|
+
}
|
|
1469
|
+
parsed.push(entry);
|
|
1470
|
+
}
|
|
1471
|
+
let changed = false;
|
|
1472
|
+
for (const rec of parsed) {
|
|
1473
|
+
if (rec && typeof rec.uuid === "string" && (rec.type === "user" || rec.type === "assistant" || rec.type === "system" || rec.type === "attachment")) {
|
|
1474
|
+
state.messages.set(rec.uuid, rec);
|
|
1475
|
+
changed = true;
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
if (changed)
|
|
1479
|
+
state.leafUuids = computeLeafUuids(state.messages);
|
|
1480
|
+
return { changed, corrupt: null, oversize: false };
|
|
1481
|
+
}
|
|
1482
|
+
async function pollOnce() {
|
|
1483
|
+
const st = await adapter.statTranscript(deps.scopeId, deps.sessionId);
|
|
1484
|
+
if (!st) {
|
|
1485
|
+
setTerminal(errorEvent("notFound", "session file removed"));
|
|
1486
|
+
return;
|
|
1487
|
+
}
|
|
1488
|
+
if (st.ino === anchorIno && st.sizeBytes === offset && st.mtimeMs === lastMtimeMs) {
|
|
1489
|
+
return;
|
|
1490
|
+
}
|
|
1491
|
+
if (st.ino !== anchorIno || st.sizeBytes < offset) {
|
|
1492
|
+
await issueBaseline("file replaced or truncated (identity discontinuity)");
|
|
1493
|
+
return;
|
|
1494
|
+
}
|
|
1495
|
+
const tail = await adapter.readTranscriptTail(deps.scopeId, deps.sessionId, offset, deps.signal);
|
|
1496
|
+
const buf = pendingPartial.length > 0 ? Buffer.concat([pendingPartial, Buffer.from(tail.bytes)]) : Buffer.from(tail.bytes);
|
|
1497
|
+
const lastNewline = buf.lastIndexOf(10);
|
|
1498
|
+
if (lastNewline === -1) {
|
|
1499
|
+
if (buf.length > limits.maxRecordBytes) {
|
|
1500
|
+
setTerminal(errorEvent("resourceLimit", `pending record exceeds limit (${buf.length} bytes)`));
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
pendingPartial = buf;
|
|
1504
|
+
offset = tail.sizeBytes;
|
|
1505
|
+
anchorIno = tail.ino;
|
|
1506
|
+
lastMtimeMs = st.mtimeMs;
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
const complete = buf.subarray(0, lastNewline + 1);
|
|
1510
|
+
pendingPartial = buf.subarray(lastNewline + 1);
|
|
1511
|
+
offset = tail.sizeBytes;
|
|
1512
|
+
anchorIno = tail.ino;
|
|
1513
|
+
lastMtimeMs = st.mtimeMs;
|
|
1514
|
+
const lines = complete.toString("utf8").split(`
|
|
1515
|
+
`).filter((l) => l.length > 0);
|
|
1516
|
+
for (let i = 0;i < lines.length; i += PARSE_BATCH_SIZE) {
|
|
1517
|
+
if (deps.signal?.aborted || interrupted()) {
|
|
1518
|
+
if (deps.signal?.aborted && !interrupted()) {
|
|
1519
|
+
setTerminal(errorEvent("cancelled", "follow aborted"));
|
|
1520
|
+
}
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
const batch = lines.slice(i, i + PARSE_BATCH_SIZE).map((l) => Buffer.from(l, "utf8"));
|
|
1524
|
+
const r = ingestLines(batch);
|
|
1525
|
+
if (r.oversize) {
|
|
1526
|
+
setTerminal(errorEvent("resourceLimit", "record exceeds max record bytes"));
|
|
1527
|
+
return;
|
|
1528
|
+
}
|
|
1529
|
+
if (r.corrupt) {
|
|
1530
|
+
await resampleAfterCorrupt();
|
|
1531
|
+
return;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
await emitReplacement();
|
|
1535
|
+
}
|
|
1536
|
+
async function emitReplacement() {
|
|
1537
|
+
if (!state || interrupted())
|
|
1538
|
+
return;
|
|
1539
|
+
const projection = buildProjection(state, deps);
|
|
1540
|
+
const bytes = serializedProjectionBytes(projection);
|
|
1541
|
+
if (bytes > limits.maxProjectionBytes) {
|
|
1542
|
+
setTerminal(errorEvent("resourceLimit", `projection exceeds limit (${bytes} bytes)`));
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
revision++;
|
|
1546
|
+
const cursor = ledger.issue({
|
|
1547
|
+
v: 1,
|
|
1548
|
+
productId: deps.productId,
|
|
1549
|
+
scopeId: deps.scopeId,
|
|
1550
|
+
sessionId: deps.sessionId,
|
|
1551
|
+
baselineId,
|
|
1552
|
+
generation,
|
|
1553
|
+
revision,
|
|
1554
|
+
byteOffset: offset,
|
|
1555
|
+
ino: anchorIno
|
|
1556
|
+
}, bytes);
|
|
1557
|
+
ledger.pin(cursor);
|
|
1558
|
+
issuedTokens.push(cursor);
|
|
1559
|
+
queueData({
|
|
1560
|
+
...envelope(deps),
|
|
1561
|
+
kind: "replacement",
|
|
1562
|
+
generation,
|
|
1563
|
+
baselineId,
|
|
1564
|
+
revision,
|
|
1565
|
+
cursor,
|
|
1566
|
+
projection
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
async function resampleAfterCorrupt() {
|
|
1570
|
+
if (interrupted() || deps.signal?.aborted)
|
|
1571
|
+
return;
|
|
1572
|
+
const st = await adapter.statTranscript(deps.scopeId, deps.sessionId);
|
|
1573
|
+
if (!st) {
|
|
1574
|
+
setTerminal(errorEvent("notFound", "session file removed during resample"));
|
|
1575
|
+
return;
|
|
1576
|
+
}
|
|
1577
|
+
if (interrupted())
|
|
1578
|
+
return;
|
|
1579
|
+
if (st.sizeBytes > limits.maxTranscriptBytes) {
|
|
1580
|
+
setTerminal(errorEvent("resourceLimit", `resample transcript exceeds limit (${st.sizeBytes} > ${limits.maxTranscriptBytes} bytes)`));
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
let raw;
|
|
1584
|
+
try {
|
|
1585
|
+
raw = await adapter.readTranscript(deps.scopeId, deps.sessionId, deps.signal);
|
|
1586
|
+
} catch (e) {
|
|
1587
|
+
if (e instanceof WebSessionError) {
|
|
1588
|
+
setTerminal(errorEvent(e.code, e.message, e.retryable));
|
|
1589
|
+
} else {
|
|
1590
|
+
setTerminal(errorEvent("ioUnavailable", `resample read failed: ${String(e)}`, true));
|
|
1591
|
+
}
|
|
1592
|
+
return;
|
|
1593
|
+
}
|
|
1594
|
+
if (interrupted())
|
|
1595
|
+
return;
|
|
1596
|
+
const stPost = await adapter.statTranscript(deps.scopeId, deps.sessionId);
|
|
1597
|
+
if (!stPost) {
|
|
1598
|
+
setTerminal(errorEvent("notFound", "session file removed during resample"));
|
|
1599
|
+
return;
|
|
1600
|
+
}
|
|
1601
|
+
if (stPost.ino !== st.ino || stPost.sizeBytes !== st.sizeBytes || stPost.mtimeMs !== st.mtimeMs) {
|
|
1602
|
+
return;
|
|
1603
|
+
}
|
|
1604
|
+
const text = Buffer.from(raw).toString("utf8");
|
|
1605
|
+
const endsWithNewline = text.endsWith(`
|
|
1606
|
+
`);
|
|
1607
|
+
const allLines = text.split(`
|
|
1608
|
+
`).filter((l) => l.length > 0);
|
|
1609
|
+
const completeLines = endsWithNewline ? allLines : allLines.slice(0, -1);
|
|
1610
|
+
for (const line of completeLines) {
|
|
1611
|
+
if (Buffer.byteLength(line, "utf8") > limits.maxRecordBytes) {
|
|
1612
|
+
setTerminal(errorEvent("resourceLimit", "record exceeds max record bytes"));
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
try {
|
|
1616
|
+
JSON.parse(line);
|
|
1617
|
+
} catch {
|
|
1618
|
+
setTerminal(errorEvent("corruptData", "unparseable complete record (resample confirmed)"));
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
let filePath;
|
|
1623
|
+
try {
|
|
1624
|
+
filePath = await deps.resolvePath(deps.scopeId, deps.sessionId);
|
|
1625
|
+
} catch (e) {
|
|
1626
|
+
setTerminal(errorEvent("ioUnavailable", `resample resolve failed: ${String(e)}`, true));
|
|
1627
|
+
return;
|
|
1628
|
+
}
|
|
1629
|
+
if (interrupted())
|
|
1630
|
+
return;
|
|
1631
|
+
let loaded;
|
|
1632
|
+
try {
|
|
1633
|
+
loaded = await deps.loadFull(filePath);
|
|
1634
|
+
} catch (e) {
|
|
1635
|
+
if (e instanceof TranscriptTooLargeError) {
|
|
1636
|
+
setTerminal(errorEvent("resourceLimit", `transcript exceeds limit (${e.size} > ${e.maxBytes} bytes)`, false));
|
|
1637
|
+
return;
|
|
1638
|
+
}
|
|
1639
|
+
if (e instanceof WebSessionError) {
|
|
1640
|
+
setTerminal(errorEvent(e.code, e.message, e.retryable));
|
|
1641
|
+
} else {
|
|
1642
|
+
setTerminal(errorEvent("ioUnavailable", `resample load failed: ${String(e)}`, true));
|
|
1643
|
+
}
|
|
1644
|
+
return;
|
|
1645
|
+
}
|
|
1646
|
+
if (interrupted() || !state)
|
|
1647
|
+
return;
|
|
1648
|
+
let prefixSame = true;
|
|
1649
|
+
for (const [uuid, msg] of state.messages) {
|
|
1650
|
+
const again = loaded.messages.get(uuid);
|
|
1651
|
+
if (!again || JSON.stringify(again) !== JSON.stringify(msg)) {
|
|
1652
|
+
prefixSame = false;
|
|
1653
|
+
break;
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
if (!prefixSame) {
|
|
1657
|
+
await issueBaseline("transcript rewritten (resample prefix mismatch)");
|
|
1658
|
+
return;
|
|
1659
|
+
}
|
|
1660
|
+
const grew = loaded.messages.size > state.messages.size;
|
|
1661
|
+
state = { messages: loaded.messages, leafUuids: loaded.leafUuids };
|
|
1662
|
+
offset = stPost.sizeBytes;
|
|
1663
|
+
anchorIno = stPost.ino;
|
|
1664
|
+
lastMtimeMs = stPost.mtimeMs;
|
|
1665
|
+
pendingPartial = Buffer.alloc(0);
|
|
1666
|
+
if (grew)
|
|
1667
|
+
await emitReplacement();
|
|
1668
|
+
}
|
|
1669
|
+
async function resumeFromCursor(token) {
|
|
1670
|
+
const verdict = ledger.verify(token, {
|
|
1671
|
+
productId: deps.productId,
|
|
1672
|
+
scopeId: deps.scopeId,
|
|
1673
|
+
sessionId: deps.sessionId
|
|
1674
|
+
});
|
|
1675
|
+
if (verdict.ok === false) {
|
|
1676
|
+
return issueBaseline(`resume cursor rejected (${verdict.why}): ${verdict.message}`);
|
|
1677
|
+
}
|
|
1678
|
+
const binding = verdict.binding;
|
|
1679
|
+
if (binding.v !== 1 || typeof binding.byteOffset !== "number" || typeof binding.ino !== "number") {
|
|
1680
|
+
return issueBaseline("resume cursor lacks byte anchor (unsupported payload version)");
|
|
1681
|
+
}
|
|
1682
|
+
if (interrupted())
|
|
1683
|
+
return false;
|
|
1684
|
+
if (deps.signal?.aborted) {
|
|
1685
|
+
setTerminal(errorEvent("cancelled", "follow aborted"));
|
|
1686
|
+
return false;
|
|
1687
|
+
}
|
|
1688
|
+
try {
|
|
1689
|
+
const st = await adapter.statTranscript(deps.scopeId, deps.sessionId);
|
|
1690
|
+
if (!st) {
|
|
1691
|
+
setTerminal(errorEvent("notFound", "session file missing before resume"));
|
|
1692
|
+
return false;
|
|
1693
|
+
}
|
|
1694
|
+
if (interrupted())
|
|
1695
|
+
return false;
|
|
1696
|
+
if (st.ino !== binding.ino || st.sizeBytes < binding.byteOffset) {
|
|
1697
|
+
return issueBaseline("resumed cursor identity mismatch (file replaced or truncated)");
|
|
1698
|
+
}
|
|
1699
|
+
const raw = await adapter.readTranscript(deps.scopeId, deps.sessionId, deps.signal);
|
|
1700
|
+
if (interrupted())
|
|
1701
|
+
return false;
|
|
1702
|
+
const stPost = await adapter.statTranscript(deps.scopeId, deps.sessionId);
|
|
1703
|
+
if (!stPost) {
|
|
1704
|
+
setTerminal(errorEvent("notFound", "session file disappeared during resume"));
|
|
1705
|
+
return false;
|
|
1706
|
+
}
|
|
1707
|
+
if (stPost.ino !== st.ino || stPost.sizeBytes < binding.byteOffset) {
|
|
1708
|
+
return issueBaseline("resumed cursor identity mismatch (file replaced or truncated)");
|
|
1709
|
+
}
|
|
1710
|
+
const prefixText = Buffer.from(raw.subarray(0, binding.byteOffset)).toString("utf8");
|
|
1711
|
+
const lastNewline = prefixText.lastIndexOf(`
|
|
1712
|
+
`);
|
|
1713
|
+
const completePart = lastNewline >= 0 ? prefixText.slice(0, lastNewline + 1) : "";
|
|
1714
|
+
const partialPart = lastNewline >= 0 ? prefixText.slice(lastNewline + 1) : prefixText;
|
|
1715
|
+
state = { messages: new Map, leafUuids: new Set };
|
|
1716
|
+
const lines = completePart.split(`
|
|
1717
|
+
`).filter((l) => l.length > 0);
|
|
1718
|
+
for (let i = 0;i < lines.length; i += PARSE_BATCH_SIZE) {
|
|
1719
|
+
if (interrupted())
|
|
1720
|
+
return false;
|
|
1721
|
+
const batch = lines.slice(i, i + PARSE_BATCH_SIZE).map((l) => Buffer.from(l, "utf8"));
|
|
1722
|
+
const r = ingestLines(batch);
|
|
1723
|
+
if (r.oversize) {
|
|
1724
|
+
setTerminal(errorEvent("resourceLimit", "record exceeds max record bytes"));
|
|
1725
|
+
return false;
|
|
1726
|
+
}
|
|
1727
|
+
if (r.corrupt) {
|
|
1728
|
+
return issueBaseline("resumed prefix contains unparseable record (identity mismatch)");
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
if (!state || interrupted())
|
|
1732
|
+
return false;
|
|
1733
|
+
generation = binding.generation;
|
|
1734
|
+
baselineId = binding.baselineId;
|
|
1735
|
+
revision = binding.revision;
|
|
1736
|
+
offset = binding.byteOffset;
|
|
1737
|
+
anchorIno = stPost.ino;
|
|
1738
|
+
lastMtimeMs = stPost.mtimeMs;
|
|
1739
|
+
pendingPartial = Buffer.from(partialPart, "utf8");
|
|
1740
|
+
return true;
|
|
1741
|
+
} catch (e) {
|
|
1742
|
+
if (e instanceof WebSessionError) {
|
|
1743
|
+
setTerminal(errorEvent(e.code, e.message, e.retryable));
|
|
1744
|
+
} else {
|
|
1745
|
+
setTerminal(errorEvent("ioUnavailable", `resume failed: ${String(e)}`, true));
|
|
1746
|
+
}
|
|
1747
|
+
return false;
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
async function run() {
|
|
1751
|
+
try {
|
|
1752
|
+
armLease();
|
|
1753
|
+
const ok = deps.resumeCursor ? await resumeFromCursor(deps.resumeCursor) : await issueBaseline();
|
|
1754
|
+
if (!ok || interrupted())
|
|
1755
|
+
return;
|
|
1756
|
+
running = true;
|
|
1757
|
+
while (running && !finished && !terminalEvent && !closeRequested) {
|
|
1758
|
+
await new Promise((resolve) => {
|
|
1759
|
+
const timer = setTimeout(() => {
|
|
1760
|
+
wakeSleep = null;
|
|
1761
|
+
resolve();
|
|
1762
|
+
}, limits.pollingIntervalMs);
|
|
1763
|
+
wakeSleep = () => {
|
|
1764
|
+
clearTimeout(timer);
|
|
1765
|
+
wakeSleep = null;
|
|
1766
|
+
resolve();
|
|
1767
|
+
};
|
|
1768
|
+
if (closeRequested)
|
|
1769
|
+
wakeSleep();
|
|
1770
|
+
});
|
|
1771
|
+
if (interrupted() || finished)
|
|
1772
|
+
break;
|
|
1773
|
+
if (deps.signal?.aborted) {
|
|
1774
|
+
setTerminal(errorEvent("cancelled", "follow aborted"));
|
|
1775
|
+
break;
|
|
1776
|
+
}
|
|
1777
|
+
try {
|
|
1778
|
+
await pollOnce();
|
|
1779
|
+
} catch (e) {
|
|
1780
|
+
if (e instanceof WebSessionError) {
|
|
1781
|
+
setTerminal(errorEvent(e.code, e.message, e.retryable));
|
|
1782
|
+
} else {
|
|
1783
|
+
setTerminal(errorEvent("ioUnavailable", `poll failed: ${String(e)}`, true));
|
|
1784
|
+
}
|
|
1785
|
+
break;
|
|
1786
|
+
}
|
|
1787
|
+
}
|
|
1788
|
+
} catch (e) {
|
|
1789
|
+
if (e instanceof WebSessionError) {
|
|
1790
|
+
setTerminal(errorEvent(e.code, e.message, e.retryable));
|
|
1791
|
+
} else {
|
|
1792
|
+
setTerminal(errorEvent("ioUnavailable", `follow worker failed: ${String(e)}`, true));
|
|
1793
|
+
}
|
|
1794
|
+
} finally {
|
|
1795
|
+
disarmLease();
|
|
1796
|
+
releaseOnce();
|
|
1797
|
+
workerDoneResolve?.();
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
run();
|
|
1801
|
+
return {
|
|
1802
|
+
[Symbol.asyncIterator]() {
|
|
1803
|
+
return {
|
|
1804
|
+
async next() {
|
|
1805
|
+
if (queue.length > 0) {
|
|
1806
|
+
const ev = queue.shift();
|
|
1807
|
+
if (isDataEvent(ev))
|
|
1808
|
+
queuedBytes -= serializedProjectionBytes(ev);
|
|
1809
|
+
if (ev.kind === "closed") {
|
|
1810
|
+
terminalDelivered = true;
|
|
1811
|
+
finished = true;
|
|
1812
|
+
disarmLease();
|
|
1813
|
+
}
|
|
1814
|
+
return { value: ev, done: false };
|
|
1815
|
+
}
|
|
1816
|
+
if (terminalDelivered || finished) {
|
|
1817
|
+
return { value: undefined, done: true };
|
|
1818
|
+
}
|
|
1819
|
+
armLease();
|
|
1820
|
+
await new Promise((resolve) => waiters.push(resolve));
|
|
1821
|
+
return this.next();
|
|
1822
|
+
},
|
|
1823
|
+
async return() {
|
|
1824
|
+
setTerminal(closedEvent("consumer stopped iteration"));
|
|
1825
|
+
return { value: undefined, done: true };
|
|
1826
|
+
}
|
|
1827
|
+
};
|
|
1828
|
+
},
|
|
1829
|
+
async renewLease() {
|
|
1830
|
+
if (finished || terminalEvent)
|
|
1831
|
+
return false;
|
|
1832
|
+
armLease();
|
|
1833
|
+
return true;
|
|
1834
|
+
},
|
|
1835
|
+
async close() {
|
|
1836
|
+
closeRequested = true;
|
|
1837
|
+
setTerminal(closedEvent("closed by caller"));
|
|
1838
|
+
wakeSleep?.();
|
|
1839
|
+
await Promise.race([
|
|
1840
|
+
workerDone,
|
|
1841
|
+
new Promise((resolve) => setTimeout(resolve, CLOSE_JOIN_TIMEOUT_MS))
|
|
1842
|
+
]);
|
|
1843
|
+
}
|
|
1844
|
+
};
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
// src/atlascode/web/sessionStoreAdapter.ts
|
|
1848
|
+
import { constants as fsConstants2 } from "node:fs";
|
|
1849
|
+
import { lstat, open as open2, readdir, realpath, stat as stat2 } from "node:fs/promises";
|
|
1850
|
+
import { isAbsolute, join, resolve, sep } from "node:path";
|
|
1851
|
+
var SESSION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
1852
|
+
function assertSessionIdShape(sessionId) {
|
|
1853
|
+
if (!SESSION_ID_RE.test(sessionId)) {
|
|
1854
|
+
throw new WebSessionError("invalidRequest", "sessionId must be a plain identifier (no path segments)");
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
function mapFsError(e, what) {
|
|
1858
|
+
const code = e?.code;
|
|
1859
|
+
if (code === "ENOENT") {
|
|
1860
|
+
throw new WebSessionError("notFound", `${what} not found`);
|
|
1861
|
+
}
|
|
1862
|
+
if (code === "EACCES" || code === "EPERM") {
|
|
1863
|
+
throw new WebSessionError("ioUnavailable", `${what} not readable (permission)`, false);
|
|
1864
|
+
}
|
|
1865
|
+
throw new WebSessionError("ioUnavailable", `${what} read failed: ${code ?? "unknown"}`, true);
|
|
1866
|
+
}
|
|
1867
|
+
function createNodeFsSessionStoreAdapter(options) {
|
|
1868
|
+
const maxTranscriptBytes = validateBoundedInt("maxTranscriptBytes", options.limits?.maxTranscriptBytes, DEFAULT_MAX_TRANSCRIPT_BYTES, HARD_MAX_TRANSCRIPT_BYTES);
|
|
1869
|
+
const roots = new Map;
|
|
1870
|
+
let started = false;
|
|
1871
|
+
function assertStarted() {
|
|
1872
|
+
if (!started) {
|
|
1873
|
+
throw new WebSessionError("closed", "adapter not started");
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
function assertScope(scopeId) {
|
|
1877
|
+
const root = roots.get(scopeId);
|
|
1878
|
+
if (!root) {
|
|
1879
|
+
throw new WebSessionError("scopeDenied", `scope not authorized: ${scopeId}`);
|
|
1880
|
+
}
|
|
1881
|
+
return root;
|
|
1882
|
+
}
|
|
1883
|
+
async function openValidated(scopeId, sessionId) {
|
|
1884
|
+
assertStarted();
|
|
1885
|
+
const root = assertScope(scopeId);
|
|
1886
|
+
assertSessionIdShape(sessionId);
|
|
1887
|
+
const filePath = join(root.dir, `${sessionId}.jsonl`);
|
|
1888
|
+
const resolved = resolve(filePath);
|
|
1889
|
+
if (!resolved.startsWith(root.canonical + sep)) {
|
|
1890
|
+
throw new WebSessionError("scopeDenied", "path escapes authorized root");
|
|
1891
|
+
}
|
|
1892
|
+
let pre;
|
|
1893
|
+
try {
|
|
1894
|
+
pre = await lstat(filePath);
|
|
1895
|
+
} catch (e) {
|
|
1896
|
+
mapFsError(e, "transcript");
|
|
1897
|
+
}
|
|
1898
|
+
if (pre.isSymbolicLink() || !pre.isFile()) {
|
|
1899
|
+
throw new WebSessionError("ioUnavailable", "transcript is not a regular file (symlink/device/fifo rejected)", false);
|
|
1900
|
+
}
|
|
1901
|
+
let fh;
|
|
1902
|
+
try {
|
|
1903
|
+
fh = await open2(filePath, fsConstants2.O_RDONLY | fsConstants2.O_NOFOLLOW);
|
|
1904
|
+
} catch (e) {
|
|
1905
|
+
mapFsError(e, "transcript open");
|
|
1906
|
+
}
|
|
1907
|
+
const st = await fh.stat();
|
|
1908
|
+
if (!st.isFile()) {
|
|
1909
|
+
await fh.close();
|
|
1910
|
+
throw new WebSessionError("ioUnavailable", "opened fd is not a regular file", false);
|
|
1911
|
+
}
|
|
1912
|
+
if (st.ino !== pre.ino) {
|
|
1913
|
+
await fh.close();
|
|
1914
|
+
throw new WebSessionError("ioUnavailable", "file identity changed between lstat and open", true);
|
|
1915
|
+
}
|
|
1916
|
+
if (st.size > maxTranscriptBytes) {
|
|
1917
|
+
await fh.close();
|
|
1918
|
+
throw new WebSessionError("resourceLimit", `transcript exceeds limit (${st.size} > ${maxTranscriptBytes} bytes)`);
|
|
1919
|
+
}
|
|
1920
|
+
return { fh, st };
|
|
1921
|
+
}
|
|
1922
|
+
async function readFromFd(fh, size, from, signal) {
|
|
1923
|
+
const chunks = [];
|
|
1924
|
+
let read = from;
|
|
1925
|
+
while (read < size) {
|
|
1926
|
+
if (signal?.aborted) {
|
|
1927
|
+
throw new WebSessionError("cancelled", "read aborted");
|
|
1928
|
+
}
|
|
1929
|
+
const want = Math.min(READ_CHUNK_SIZE, size - read);
|
|
1930
|
+
const buf = Buffer.alloc(want);
|
|
1931
|
+
const { bytesRead } = await fh.read(buf, 0, want, read);
|
|
1932
|
+
if (bytesRead <= 0)
|
|
1933
|
+
break;
|
|
1934
|
+
chunks.push(buf.subarray(0, bytesRead));
|
|
1935
|
+
read += bytesRead;
|
|
1936
|
+
}
|
|
1937
|
+
return chunks;
|
|
1938
|
+
}
|
|
1939
|
+
async function readTranscript(scopeId, sessionId, signal) {
|
|
1940
|
+
const { fh, st } = await openValidated(scopeId, sessionId);
|
|
1941
|
+
try {
|
|
1942
|
+
if (st.size > maxTranscriptBytes) {
|
|
1943
|
+
throw new WebSessionError("resourceLimit", `transcript exceeds limit (${st.size} > ${maxTranscriptBytes} bytes)`);
|
|
1944
|
+
}
|
|
1945
|
+
const chunks = await readFromFd(fh, st.size, 0, signal);
|
|
1946
|
+
const st2 = await fh.stat();
|
|
1947
|
+
if (st2.ino !== st.ino || st2.size !== st.size) {
|
|
1948
|
+
throw new WebSessionError("ioUnavailable", "file changed during read (not a stable snapshot)", true);
|
|
1949
|
+
}
|
|
1950
|
+
return new Uint8Array(Buffer.concat(chunks));
|
|
1951
|
+
} finally {
|
|
1952
|
+
await fh.close();
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
async function statTranscript(scopeId, sessionId) {
|
|
1956
|
+
assertStarted();
|
|
1957
|
+
const root = assertScope(scopeId);
|
|
1958
|
+
assertSessionIdShape(sessionId);
|
|
1959
|
+
try {
|
|
1960
|
+
const st = await lstat(join(root.dir, `${sessionId}.jsonl`));
|
|
1961
|
+
if (st.isSymbolicLink() || !st.isFile())
|
|
1962
|
+
return null;
|
|
1963
|
+
return { sizeBytes: st.size, mtimeMs: st.mtimeMs, ino: st.ino };
|
|
1964
|
+
} catch (e) {
|
|
1965
|
+
const code = e?.code;
|
|
1966
|
+
if (code === "ENOENT")
|
|
1967
|
+
return null;
|
|
1968
|
+
mapFsError(e, "transcript stat");
|
|
1969
|
+
}
|
|
1970
|
+
}
|
|
1971
|
+
async function readTranscriptTail(scopeId, sessionId, offset, signal) {
|
|
1972
|
+
if (!Number.isInteger(offset) || offset < 0) {
|
|
1973
|
+
throw new WebSessionError("invalidRequest", "offset must be a non-negative integer");
|
|
1974
|
+
}
|
|
1975
|
+
const { fh, st } = await openValidated(scopeId, sessionId);
|
|
1976
|
+
try {
|
|
1977
|
+
if (st.size > maxTranscriptBytes) {
|
|
1978
|
+
throw new WebSessionError("resourceLimit", `transcript exceeds limit (${st.size} > ${maxTranscriptBytes} bytes)`);
|
|
1979
|
+
}
|
|
1980
|
+
if (offset > st.size) {
|
|
1981
|
+
throw new WebSessionError("ioUnavailable", `file shrank below offset (${offset} > ${st.size})`, true);
|
|
1982
|
+
}
|
|
1983
|
+
const chunks = await readFromFd(fh, st.size, offset, signal);
|
|
1984
|
+
const st2 = await fh.stat();
|
|
1985
|
+
if (st2.ino !== st.ino || st2.size !== st.size) {
|
|
1986
|
+
throw new WebSessionError("ioUnavailable", "file changed during tail read (not a stable snapshot)", true);
|
|
1987
|
+
}
|
|
1988
|
+
return {
|
|
1989
|
+
bytes: new Uint8Array(Buffer.concat(chunks)),
|
|
1990
|
+
sizeBytes: st.size,
|
|
1991
|
+
ino: st.ino
|
|
1992
|
+
};
|
|
1993
|
+
} finally {
|
|
1994
|
+
await fh.close();
|
|
1995
|
+
}
|
|
1996
|
+
}
|
|
1997
|
+
async function readTranscriptHead(scopeId, sessionId, maxBytes, signal) {
|
|
1998
|
+
if (!Number.isInteger(maxBytes) || maxBytes <= 0) {
|
|
1999
|
+
throw new WebSessionError("invalidRequest", "maxBytes must be a positive integer");
|
|
2000
|
+
}
|
|
2001
|
+
const { fh, st } = await openValidated(scopeId, sessionId);
|
|
2002
|
+
try {
|
|
2003
|
+
const want = Math.min(st.size, maxBytes);
|
|
2004
|
+
const chunks = await readFromFd(fh, want, 0, signal);
|
|
2005
|
+
const st2 = await fh.stat();
|
|
2006
|
+
if (st2.ino !== st.ino || st2.size !== st.size) {
|
|
2007
|
+
throw new WebSessionError("ioUnavailable", "file changed during head read (not a stable snapshot)", true);
|
|
2008
|
+
}
|
|
2009
|
+
return {
|
|
2010
|
+
bytes: new Uint8Array(Buffer.concat(chunks)),
|
|
2011
|
+
sizeBytes: st.size,
|
|
2012
|
+
ino: st.ino
|
|
2013
|
+
};
|
|
2014
|
+
} finally {
|
|
2015
|
+
await fh.close();
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
return {
|
|
2019
|
+
async start() {
|
|
2020
|
+
if (options.productId !== "atlascode") {
|
|
2021
|
+
throw new WebSessionError("invalidRequest", `productId must be 'atlascode' (static ProductDefinition), got '${options.productId}'`);
|
|
2022
|
+
}
|
|
2023
|
+
roots.clear();
|
|
2024
|
+
for (const { scopeId, storageDir } of options.scopes) {
|
|
2025
|
+
if (roots.has(scopeId)) {
|
|
2026
|
+
throw new WebSessionError("invalidRequest", `duplicate scopeId: ${scopeId}`);
|
|
2027
|
+
}
|
|
2028
|
+
if (!isAbsolute(storageDir)) {
|
|
2029
|
+
throw new WebSessionError("invalidRequest", `storageDir must be absolute for scope ${scopeId}`);
|
|
2030
|
+
}
|
|
2031
|
+
let canonical;
|
|
2032
|
+
try {
|
|
2033
|
+
canonical = await realpath(storageDir);
|
|
2034
|
+
} catch (e) {
|
|
2035
|
+
mapFsError(e, `storage root for scope ${scopeId}`);
|
|
2036
|
+
}
|
|
2037
|
+
const st = await stat2(canonical).catch((e) => {
|
|
2038
|
+
mapFsError(e, `storage root for scope ${scopeId}`);
|
|
2039
|
+
});
|
|
2040
|
+
if (!st.isDirectory()) {
|
|
2041
|
+
throw new WebSessionError("invalidRequest", `storage root for scope ${scopeId} is not a directory`);
|
|
2042
|
+
}
|
|
2043
|
+
roots.set(scopeId, { scopeId, canonical, dir: storageDir });
|
|
2044
|
+
}
|
|
2045
|
+
started = true;
|
|
2046
|
+
},
|
|
2047
|
+
async listSessionFiles(scopeId) {
|
|
2048
|
+
assertStarted();
|
|
2049
|
+
const root = assertScope(scopeId);
|
|
2050
|
+
let dirents;
|
|
2051
|
+
try {
|
|
2052
|
+
dirents = await readdir(root.dir, { withFileTypes: true });
|
|
2053
|
+
} catch (e) {
|
|
2054
|
+
mapFsError(e, `scope ${scopeId} directory`);
|
|
2055
|
+
}
|
|
2056
|
+
const entries = [];
|
|
2057
|
+
for (const d of dirents) {
|
|
2058
|
+
if (!d.name.endsWith(".jsonl"))
|
|
2059
|
+
continue;
|
|
2060
|
+
if (d.isSymbolicLink() || !d.isFile())
|
|
2061
|
+
continue;
|
|
2062
|
+
const sessionId = d.name.slice(0, -".jsonl".length);
|
|
2063
|
+
if (!SESSION_ID_RE.test(sessionId))
|
|
2064
|
+
continue;
|
|
2065
|
+
try {
|
|
2066
|
+
const st = await stat2(join(root.dir, d.name));
|
|
2067
|
+
entries.push({
|
|
2068
|
+
sessionId,
|
|
2069
|
+
filePath: join(root.dir, d.name),
|
|
2070
|
+
sizeBytes: st.size,
|
|
2071
|
+
updatedAt: st.mtime.toISOString(),
|
|
2072
|
+
createdAt: st.birthtimeMs > 0 ? st.birthtime.toISOString() : null,
|
|
2073
|
+
mtimeMs: st.mtimeMs
|
|
2074
|
+
});
|
|
2075
|
+
} catch {}
|
|
2076
|
+
}
|
|
2077
|
+
entries.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
2078
|
+
return entries.map(({ mtimeMs: _mtimeMs, ...rest }) => rest);
|
|
2079
|
+
},
|
|
2080
|
+
readTranscript,
|
|
2081
|
+
statTranscript,
|
|
2082
|
+
readTranscriptTail,
|
|
2083
|
+
readTranscriptHead,
|
|
2084
|
+
async resolveTranscriptPath(scopeId, sessionId) {
|
|
2085
|
+
const { fh } = await openValidated(scopeId, sessionId);
|
|
2086
|
+
await fh.close();
|
|
2087
|
+
const root = roots.get(scopeId);
|
|
2088
|
+
return join(root.dir, `${sessionId}.jsonl`);
|
|
2089
|
+
},
|
|
2090
|
+
async close() {
|
|
2091
|
+
started = false;
|
|
2092
|
+
roots.clear();
|
|
2093
|
+
}
|
|
2094
|
+
};
|
|
2095
|
+
}
|
|
2096
|
+
|
|
2097
|
+
// src/engine/session/search.ts
|
|
2098
|
+
var INTERRUPT_MESSAGE = "[Request interrupted by user]";
|
|
2099
|
+
var INTERRUPT_MESSAGE_FOR_TOOL_USE = "[Request interrupted by user for tool use]";
|
|
2100
|
+
var SYSTEM_REMINDER_CLOSE = "</system-reminder>";
|
|
2101
|
+
var RENDERED_AS_SENTINEL = new Set([
|
|
2102
|
+
INTERRUPT_MESSAGE,
|
|
2103
|
+
INTERRUPT_MESSAGE_FOR_TOOL_USE
|
|
2104
|
+
]);
|
|
2105
|
+
var searchTextCache = new WeakMap;
|
|
2106
|
+
function renderableSearchText(msg) {
|
|
2107
|
+
const cached = searchTextCache.get(msg);
|
|
2108
|
+
if (cached !== undefined)
|
|
2109
|
+
return cached;
|
|
2110
|
+
const result = computeSearchText(msg).toLowerCase();
|
|
2111
|
+
searchTextCache.set(msg, result);
|
|
2112
|
+
return result;
|
|
2113
|
+
}
|
|
2114
|
+
function computeSearchText(msg) {
|
|
2115
|
+
let raw = "";
|
|
2116
|
+
switch (msg.type) {
|
|
2117
|
+
case "user": {
|
|
2118
|
+
const c = msg.message.content;
|
|
2119
|
+
if (typeof c === "string") {
|
|
2120
|
+
raw = RENDERED_AS_SENTINEL.has(c) ? "" : c;
|
|
2121
|
+
} else {
|
|
2122
|
+
const parts = [];
|
|
2123
|
+
for (const b of c) {
|
|
2124
|
+
if (b.type === "text") {
|
|
2125
|
+
const text = b.text;
|
|
2126
|
+
if (!RENDERED_AS_SENTINEL.has(text))
|
|
2127
|
+
parts.push(text);
|
|
2128
|
+
} else if (b.type === "tool_result") {
|
|
2129
|
+
parts.push(toolResultSearchText(msg.toolUseResult));
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
raw = parts.join(`
|
|
2133
|
+
`);
|
|
2134
|
+
}
|
|
2135
|
+
break;
|
|
2136
|
+
}
|
|
2137
|
+
case "assistant": {
|
|
2138
|
+
const c = msg.message.content;
|
|
2139
|
+
if (Array.isArray(c)) {
|
|
2140
|
+
raw = c.flatMap((b) => {
|
|
2141
|
+
if (b.type === "text")
|
|
2142
|
+
return [b.text];
|
|
2143
|
+
if (b.type === "tool_use")
|
|
2144
|
+
return [toolUseSearchText(b.input)];
|
|
2145
|
+
return [];
|
|
2146
|
+
}).join(`
|
|
2147
|
+
`);
|
|
2148
|
+
}
|
|
2149
|
+
break;
|
|
2150
|
+
}
|
|
2151
|
+
case "attachment": {
|
|
2152
|
+
if (msg.attachment.type === "relevant_memories") {
|
|
2153
|
+
raw = (msg.attachment.memories ?? []).map((m) => m.content).join(`
|
|
2154
|
+
`);
|
|
2155
|
+
} else if (msg.attachment.type === "queued_command" && msg.attachment.commandMode !== "task-notification" && !msg.attachment.isMeta) {
|
|
2156
|
+
const p = msg.attachment.prompt;
|
|
2157
|
+
raw = typeof p === "string" ? p : (p ?? []).flatMap((b) => b.type === "text" ? [b.text] : []).join(`
|
|
2158
|
+
`);
|
|
2159
|
+
}
|
|
2160
|
+
break;
|
|
2161
|
+
}
|
|
2162
|
+
case "collapsed_read_search": {
|
|
2163
|
+
if (msg.relevantMemories) {
|
|
2164
|
+
raw = msg.relevantMemories.map((m) => m.content).join(`
|
|
2165
|
+
`);
|
|
2166
|
+
}
|
|
2167
|
+
break;
|
|
2168
|
+
}
|
|
2169
|
+
default:
|
|
2170
|
+
break;
|
|
2171
|
+
}
|
|
2172
|
+
let t = raw;
|
|
2173
|
+
let open = t.indexOf("<system-reminder>");
|
|
2174
|
+
while (open >= 0) {
|
|
2175
|
+
const close = t.indexOf(SYSTEM_REMINDER_CLOSE, open);
|
|
2176
|
+
if (close < 0)
|
|
2177
|
+
break;
|
|
2178
|
+
t = t.slice(0, open) + t.slice(close + SYSTEM_REMINDER_CLOSE.length);
|
|
2179
|
+
open = t.indexOf("<system-reminder>");
|
|
2180
|
+
}
|
|
2181
|
+
return t;
|
|
2182
|
+
}
|
|
2183
|
+
function toolUseSearchText(input) {
|
|
2184
|
+
if (!input || typeof input !== "object")
|
|
2185
|
+
return "";
|
|
2186
|
+
const o = input;
|
|
2187
|
+
const parts = [];
|
|
2188
|
+
for (const k of [
|
|
2189
|
+
"command",
|
|
2190
|
+
"pattern",
|
|
2191
|
+
"file_path",
|
|
2192
|
+
"path",
|
|
2193
|
+
"prompt",
|
|
2194
|
+
"description",
|
|
2195
|
+
"query",
|
|
2196
|
+
"url",
|
|
2197
|
+
"skill"
|
|
2198
|
+
]) {
|
|
2199
|
+
const v = o[k];
|
|
2200
|
+
if (typeof v === "string")
|
|
2201
|
+
parts.push(v);
|
|
2202
|
+
}
|
|
2203
|
+
for (const k of ["args", "files"]) {
|
|
2204
|
+
const v = o[k];
|
|
2205
|
+
if (Array.isArray(v) && v.every((x) => typeof x === "string")) {
|
|
2206
|
+
parts.push(v.join(" "));
|
|
2207
|
+
}
|
|
2208
|
+
}
|
|
2209
|
+
return parts.join(`
|
|
2210
|
+
`);
|
|
2211
|
+
}
|
|
2212
|
+
function toolResultSearchText(r) {
|
|
2213
|
+
if (!r || typeof r !== "object")
|
|
2214
|
+
return typeof r === "string" ? r : "";
|
|
2215
|
+
const o = r;
|
|
2216
|
+
if (typeof o.stdout === "string") {
|
|
2217
|
+
const err = typeof o.stderr === "string" ? o.stderr : "";
|
|
2218
|
+
return o.stdout + (err ? `
|
|
2219
|
+
` + err : "");
|
|
2220
|
+
}
|
|
2221
|
+
if (o.file && typeof o.file === "object" && typeof o.file.content === "string") {
|
|
2222
|
+
return o.file.content;
|
|
2223
|
+
}
|
|
2224
|
+
const parts = [];
|
|
2225
|
+
for (const k of ["content", "output", "result", "text", "message"]) {
|
|
2226
|
+
const v = o[k];
|
|
2227
|
+
if (typeof v === "string")
|
|
2228
|
+
parts.push(v);
|
|
2229
|
+
}
|
|
2230
|
+
for (const k of ["filenames", "lines", "results"]) {
|
|
2231
|
+
const v = o[k];
|
|
2232
|
+
if (Array.isArray(v) && v.every((x) => typeof x === "string")) {
|
|
2233
|
+
parts.push(v.join(`
|
|
2234
|
+
`));
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
return parts.join(`
|
|
2238
|
+
`);
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
// src/atlascode/web/readonlyRuntime.ts
|
|
2242
|
+
function toSummary(entry, productId, scopeId) {
|
|
2243
|
+
return {
|
|
2244
|
+
sessionId: entry.sessionId,
|
|
2245
|
+
title: null,
|
|
2246
|
+
createdAt: entry.createdAt,
|
|
2247
|
+
updatedAt: entry.updatedAt,
|
|
2248
|
+
messageCount: null,
|
|
2249
|
+
productId,
|
|
2250
|
+
scopeId
|
|
2251
|
+
};
|
|
2252
|
+
}
|
|
2253
|
+
function userMessageText(message) {
|
|
2254
|
+
if (typeof message !== "object" || message === null)
|
|
2255
|
+
return null;
|
|
2256
|
+
const content = message.content;
|
|
2257
|
+
if (typeof content === "string")
|
|
2258
|
+
return content;
|
|
2259
|
+
if (!Array.isArray(content))
|
|
2260
|
+
return null;
|
|
2261
|
+
const parts = [];
|
|
2262
|
+
for (const block of content) {
|
|
2263
|
+
if (typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string") {
|
|
2264
|
+
parts.push(block.text);
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
return parts.length > 0 ? parts.join(" ") : null;
|
|
2268
|
+
}
|
|
2269
|
+
function clampCodePoints(text, max, ellipsis = false) {
|
|
2270
|
+
const points = Array.from(text);
|
|
2271
|
+
if (points.length <= max)
|
|
2272
|
+
return text;
|
|
2273
|
+
const keep = ellipsis ? max - 1 : max;
|
|
2274
|
+
return `${points.slice(0, keep).join("")}…`;
|
|
2275
|
+
}
|
|
2276
|
+
function extractListFace(bytes, fullRead) {
|
|
2277
|
+
const text = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
|
|
2278
|
+
const lines = text.split(`
|
|
2279
|
+
`);
|
|
2280
|
+
lines.pop();
|
|
2281
|
+
let customTitle = null;
|
|
2282
|
+
let summaryText = null;
|
|
2283
|
+
let firstUserText = null;
|
|
2284
|
+
let messageCount = fullRead ? 0 : null;
|
|
2285
|
+
for (const line of lines) {
|
|
2286
|
+
if (line.length === 0)
|
|
2287
|
+
continue;
|
|
2288
|
+
let entry;
|
|
2289
|
+
try {
|
|
2290
|
+
entry = JSON.parse(line);
|
|
2291
|
+
} catch {
|
|
2292
|
+
continue;
|
|
2293
|
+
}
|
|
2294
|
+
const type = entry.type;
|
|
2295
|
+
if (type === "custom-title" && typeof entry.customTitle === "string" && customTitle === null) {
|
|
2296
|
+
customTitle = entry.customTitle;
|
|
2297
|
+
} else if (type === "summary" && typeof entry.summary === "string" && summaryText === null) {
|
|
2298
|
+
summaryText = entry.summary;
|
|
2299
|
+
} else if (type === "user" || type === "assistant") {
|
|
2300
|
+
if (messageCount !== null)
|
|
2301
|
+
messageCount++;
|
|
2302
|
+
if (type === "user" && firstUserText === null) {
|
|
2303
|
+
const text2 = userMessageText(entry.message);
|
|
2304
|
+
if (text2 !== null && text2.trim().length > 0)
|
|
2305
|
+
firstUserText = text2;
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
2308
|
+
}
|
|
2309
|
+
const raw = customTitle ?? summaryText ?? firstUserText;
|
|
2310
|
+
let title = null;
|
|
2311
|
+
if (raw !== null) {
|
|
2312
|
+
const collapsed = raw.replace(/\s+/gu, " ").trim();
|
|
2313
|
+
if (collapsed.length > 0) {
|
|
2314
|
+
title = clampCodePoints(collapsed, raw === firstUserText && customTitle === null && summaryText === null ? TITLE_USER_MESSAGE_CODE_POINTS : TITLE_MAX_CODE_POINTS, true);
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
return { title, messageCount };
|
|
2318
|
+
}
|
|
2319
|
+
function createReadonlySessionRuntime(options) {
|
|
2320
|
+
const epoch = randomUUID2();
|
|
2321
|
+
const adapter = options.adapter ?? createNodeFsSessionStoreAdapter({
|
|
2322
|
+
productId: options.productId,
|
|
2323
|
+
scopes: options.scopes,
|
|
2324
|
+
limits: { maxTranscriptBytes: options.limits?.maxTranscriptBytes }
|
|
2325
|
+
});
|
|
2326
|
+
const L = {
|
|
2327
|
+
maxTranscriptBytes: validateBoundedInt("maxTranscriptBytes", options.limits?.maxTranscriptBytes, DEFAULT_MAX_TRANSCRIPT_BYTES, HARD_MAX_TRANSCRIPT_BYTES),
|
|
2328
|
+
maxScanSessions: validateBoundedInt("maxScanSessions", options.limits?.maxScanSessions, DEFAULT_MAX_SCAN_SESSIONS, HARD_MAX_SCAN_SESSIONS),
|
|
2329
|
+
pageSize: validateBoundedInt("pageSize", options.limits?.pageSize, DEFAULT_PAGE_SIZE, HARD_MAX_PAGE_SIZE),
|
|
2330
|
+
maxRecordBytes: validateBoundedInt("maxRecordBytes", options.limits?.maxRecordBytes, DEFAULT_MAX_RECORD_BYTES, HARD_MAX_RECORD_BYTES),
|
|
2331
|
+
maxParseRecords: validateBoundedInt("maxParseRecords", options.limits?.maxParseRecords, DEFAULT_MAX_PARSE_RECORDS, HARD_MAX_PARSE_RECORDS),
|
|
2332
|
+
maxProjectionBytes: validateBoundedInt("maxProjectionBytes", options.limits?.maxProjectionBytes, DEFAULT_MAX_PROJECTION_BYTES, HARD_MAX_PROJECTION_BYTES),
|
|
2333
|
+
maxSubscriptions: validateBoundedInt("maxSubscriptions", options.limits?.maxSubscriptions, DEFAULT_MAX_SUBSCRIPTIONS, HARD_MAX_SUBSCRIPTIONS),
|
|
2334
|
+
maxConcurrentReads: validateBoundedInt("maxConcurrentReads", options.limits?.maxConcurrentReads, DEFAULT_MAX_CONCURRENT_READS, HARD_MAX_CONCURRENT_READS),
|
|
2335
|
+
maxPendingEvents: validateBoundedInt("maxPendingEvents", options.limits?.maxPendingEvents, DEFAULT_MAX_PENDING_EVENTS, HARD_MAX_PENDING_EVENTS),
|
|
2336
|
+
maxPendingBytes: validateBoundedInt("maxPendingBytes", options.limits?.maxPendingBytes, DEFAULT_MAX_PENDING_BYTES, HARD_MAX_PENDING_BYTES),
|
|
2337
|
+
pollingIntervalMs: validateBoundedInt("pollingIntervalMs", options.limits?.pollingIntervalMs, DEFAULT_POLLING_INTERVAL_MS, HARD_MAX_POLLING_INTERVAL_MS, HARD_MIN_POLLING_INTERVAL_MS),
|
|
2338
|
+
requestDeadlineMs: validateBoundedInt("requestDeadlineMs", options.limits?.requestDeadlineMs, DEFAULT_REQUEST_DEADLINE_MS, HARD_MAX_REQUEST_DEADLINE_MS, HARD_MIN_REQUEST_DEADLINE_MS),
|
|
2339
|
+
idleLeaseMs: validateBoundedInt("idleLeaseMs", options.limits?.idleLeaseMs, DEFAULT_IDLE_LEASE_MS, HARD_MAX_IDLE_LEASE_MS, HARD_MIN_IDLE_LEASE_MS),
|
|
2340
|
+
cursorTtlMs: validateBoundedInt("cursorTtlMs", options.limits?.cursorTtlMs, DEFAULT_CURSOR_TTL_MS, HARD_MAX_CURSOR_TTL_MS, HARD_MIN_CURSOR_TTL_MS),
|
|
2341
|
+
closeDeadlineMs: validateBoundedInt("closeDeadlineMs", options.limits?.closeDeadlineMs, DEFAULT_CLOSE_DEADLINE_MS, HARD_MAX_CLOSE_DEADLINE_MS, HARD_MIN_CLOSE_DEADLINE_MS),
|
|
2342
|
+
ledgerCapacity: validateBoundedInt("ledgerCapacity", options.limits?.ledgerCapacity, DEFAULT_LEDGER_CAPACITY, HARD_MAX_LEDGER_CAPACITY),
|
|
2343
|
+
ledgerPayloadBytes: validateBoundedInt("ledgerPayloadBytes", options.limits?.ledgerPayloadBytes, DEFAULT_LEDGER_PAYLOAD_BYTES, HARD_MAX_LEDGER_PAYLOAD_BYTES)
|
|
2344
|
+
};
|
|
2345
|
+
const authorizedScopes = new Set(options.scopes.map((s) => s.scopeId));
|
|
2346
|
+
let state = "idle";
|
|
2347
|
+
const subscriptions = new Set;
|
|
2348
|
+
let activeReads = 0;
|
|
2349
|
+
const cursorLedger = new CursorLedger(L.ledgerCapacity, L.cursorTtlMs, L.ledgerPayloadBytes);
|
|
2350
|
+
function assertStarted(operation) {
|
|
2351
|
+
if (state === "idle") {
|
|
2352
|
+
throw new WebSessionError("closed", "not started");
|
|
2353
|
+
}
|
|
2354
|
+
if (state === "closed") {
|
|
2355
|
+
throw new WebSessionError("closed", `runtime closed: cannot ${operation}`);
|
|
2356
|
+
}
|
|
2357
|
+
}
|
|
2358
|
+
function assertScope(scopeId) {
|
|
2359
|
+
if (!authorizedScopes.has(scopeId)) {
|
|
2360
|
+
throw new WebSessionError("scopeDenied", `scope not authorized: ${scopeId}`);
|
|
2361
|
+
}
|
|
2362
|
+
}
|
|
2363
|
+
function acquireRead() {
|
|
2364
|
+
if (activeReads >= L.maxConcurrentReads) {
|
|
2365
|
+
throw new WebSessionError("resourceLimit", `concurrent read limit exceeded (${activeReads} >= ${L.maxConcurrentReads})`);
|
|
2366
|
+
}
|
|
2367
|
+
activeReads++;
|
|
2368
|
+
}
|
|
2369
|
+
function releaseRead() {
|
|
2370
|
+
activeReads--;
|
|
2371
|
+
}
|
|
2372
|
+
async function resolvePath(scopeId, sessionId) {
|
|
2373
|
+
assertScope(scopeId);
|
|
2374
|
+
return adapter.resolveTranscriptPath(scopeId, sessionId);
|
|
2375
|
+
}
|
|
2376
|
+
async function loadProjection(scopeId, sessionId, signal) {
|
|
2377
|
+
acquireRead();
|
|
2378
|
+
try {
|
|
2379
|
+
if (signal?.aborted) {
|
|
2380
|
+
throw new WebSessionError("cancelled", "operation aborted");
|
|
2381
|
+
}
|
|
2382
|
+
const stPre = await adapter.statTranscript(scopeId, sessionId);
|
|
2383
|
+
if (!stPre) {
|
|
2384
|
+
throw new WebSessionError("notFound", `session not found: ${sessionId}`);
|
|
2385
|
+
}
|
|
2386
|
+
if (stPre.sizeBytes > L.maxTranscriptBytes) {
|
|
2387
|
+
throw new WebSessionError("resourceLimit", `transcript exceeds limit (${stPre.sizeBytes} > ${L.maxTranscriptBytes} bytes)`);
|
|
2388
|
+
}
|
|
2389
|
+
const filePath = await resolvePath(scopeId, sessionId);
|
|
2390
|
+
let loaded;
|
|
2391
|
+
try {
|
|
2392
|
+
loaded = await options.engine.loadTranscriptFull(filePath, {
|
|
2393
|
+
maxBytes: L.maxTranscriptBytes,
|
|
2394
|
+
expectIno: stPre.ino
|
|
2395
|
+
});
|
|
2396
|
+
} catch (e) {
|
|
2397
|
+
if (e instanceof TranscriptTooLargeError) {
|
|
2398
|
+
throw new WebSessionError("resourceLimit", `transcript exceeds limit (${e.size} > ${e.maxBytes} bytes)`);
|
|
2399
|
+
}
|
|
2400
|
+
if (e instanceof TranscriptChangedDuringReadError) {
|
|
2401
|
+
throw new WebSessionError("ioUnavailable", e.message, true);
|
|
2402
|
+
}
|
|
2403
|
+
throw e;
|
|
2404
|
+
}
|
|
2405
|
+
if (signal?.aborted) {
|
|
2406
|
+
throw new WebSessionError("cancelled", "operation aborted");
|
|
2407
|
+
}
|
|
2408
|
+
const stPost = await adapter.statTranscript(scopeId, sessionId);
|
|
2409
|
+
if (!stPost || stPost.ino !== stPre.ino || stPost.sizeBytes !== stPre.sizeBytes || stPost.mtimeMs !== stPre.mtimeMs) {
|
|
2410
|
+
throw new WebSessionError("ioUnavailable", "transcript changed during replay load (snapshot inconsistency)", true);
|
|
2411
|
+
}
|
|
2412
|
+
const projection = projectConversation(loaded, { sessionId, productId: options.productId, scopeId }, { buildConversationChain: options.engine.buildConversationChain });
|
|
2413
|
+
const bytes = serializedProjectionBytes(projection);
|
|
2414
|
+
if (bytes > L.maxProjectionBytes) {
|
|
2415
|
+
throw new WebSessionError("resourceLimit", `projection exceeds limit (${bytes} > ${L.maxProjectionBytes} bytes)`);
|
|
2416
|
+
}
|
|
2417
|
+
return projection;
|
|
2418
|
+
} finally {
|
|
2419
|
+
releaseRead();
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
return {
|
|
2423
|
+
epoch,
|
|
2424
|
+
limits: L,
|
|
2425
|
+
async start() {
|
|
2426
|
+
if (state === "closed") {
|
|
2427
|
+
throw new WebSessionError("closed", "runtime closed: start cannot restart; create a new runtime (new epoch)");
|
|
2428
|
+
}
|
|
2429
|
+
if (state === "started")
|
|
2430
|
+
return;
|
|
2431
|
+
if (options.productId !== "atlascode") {
|
|
2432
|
+
throw new WebSessionError("invalidRequest", `productId must be 'atlascode' (static ProductDefinition), got '${options.productId}'`);
|
|
2433
|
+
}
|
|
2434
|
+
if (options.scopes.length === 0) {
|
|
2435
|
+
throw new WebSessionError("invalidRequest", "at least one scope required");
|
|
2436
|
+
}
|
|
2437
|
+
if (options.scopes.length > HARD_MAX_SCOPES_PER_RUNTIME) {
|
|
2438
|
+
throw new WebSessionError("invalidRequest", `too many scopes (${options.scopes.length} > ${HARD_MAX_SCOPES_PER_RUNTIME})`);
|
|
2439
|
+
}
|
|
2440
|
+
const seen = new Set;
|
|
2441
|
+
for (const s of options.scopes) {
|
|
2442
|
+
if (seen.has(s.scopeId)) {
|
|
2443
|
+
throw new WebSessionError("invalidRequest", `duplicate scopeId: ${s.scopeId}`);
|
|
2444
|
+
}
|
|
2445
|
+
seen.add(s.scopeId);
|
|
2446
|
+
}
|
|
2447
|
+
await adapter.start();
|
|
2448
|
+
state = "started";
|
|
2449
|
+
},
|
|
2450
|
+
async listSessions(req, signal) {
|
|
2451
|
+
assertStarted("list sessions");
|
|
2452
|
+
assertScope(req.scopeId);
|
|
2453
|
+
const entries = await adapter.listSessionFiles(req.scopeId);
|
|
2454
|
+
if (entries.length > L.maxScanSessions) {
|
|
2455
|
+
throw new WebSessionError("resourceLimit", `scope ${req.scopeId} exceeds scan limit (${entries.length} > ${L.maxScanSessions})`);
|
|
2456
|
+
}
|
|
2457
|
+
const sessions = await Promise.all(entries.map(async (e) => {
|
|
2458
|
+
const summary = toSummary(e, options.productId, req.scopeId);
|
|
2459
|
+
try {
|
|
2460
|
+
const head = await adapter.readTranscriptHead?.(req.scopeId, e.sessionId, TITLE_HEAD_BYTES, signal);
|
|
2461
|
+
if (head !== undefined) {
|
|
2462
|
+
const face = extractListFace(head.bytes, head.sizeBytes <= TITLE_HEAD_BYTES);
|
|
2463
|
+
summary.title = face.title;
|
|
2464
|
+
summary.messageCount = face.messageCount;
|
|
2465
|
+
}
|
|
2466
|
+
} catch {}
|
|
2467
|
+
return summary;
|
|
2468
|
+
}));
|
|
2469
|
+
return { sessions };
|
|
2470
|
+
},
|
|
2471
|
+
async searchSessions(req, signal) {
|
|
2472
|
+
assertStarted("search sessions");
|
|
2473
|
+
assertScope(req.scopeId);
|
|
2474
|
+
const needle = req.query.toLowerCase();
|
|
2475
|
+
const pageSize = Math.max(1, Math.min(req.pageSize ?? L.pageSize, L.pageSize));
|
|
2476
|
+
let offset = 0;
|
|
2477
|
+
if (req.pageToken !== undefined) {
|
|
2478
|
+
if (!/^\d+$/.test(req.pageToken)) {
|
|
2479
|
+
throw new WebSessionError("invalidRequest", "malformed pageToken");
|
|
2480
|
+
}
|
|
2481
|
+
offset = Number.parseInt(req.pageToken, 10);
|
|
2482
|
+
}
|
|
2483
|
+
acquireRead();
|
|
2484
|
+
try {
|
|
2485
|
+
if (signal?.aborted) {
|
|
2486
|
+
throw new WebSessionError("cancelled", "operation aborted");
|
|
2487
|
+
}
|
|
2488
|
+
const entries = await adapter.listSessionFiles(req.scopeId);
|
|
2489
|
+
if (entries.length > L.maxScanSessions) {
|
|
2490
|
+
throw new WebSessionError("resourceLimit", `scope ${req.scopeId} exceeds scan limit (${entries.length} > ${L.maxScanSessions})`);
|
|
2491
|
+
}
|
|
2492
|
+
const results = [];
|
|
2493
|
+
for (let i = offset;i < entries.length; i++) {
|
|
2494
|
+
const entry = entries[i];
|
|
2495
|
+
if (signal?.aborted) {
|
|
2496
|
+
throw new WebSessionError("cancelled", "operation aborted");
|
|
2497
|
+
}
|
|
2498
|
+
const st = await adapter.statTranscript(req.scopeId, entry.sessionId);
|
|
2499
|
+
if (!st)
|
|
2500
|
+
continue;
|
|
2501
|
+
if (st.sizeBytes > L.maxTranscriptBytes) {
|
|
2502
|
+
throw new WebSessionError("resourceLimit", `transcript exceeds limit (${st.sizeBytes} > ${L.maxTranscriptBytes} bytes)`);
|
|
2503
|
+
}
|
|
2504
|
+
let loaded;
|
|
2505
|
+
try {
|
|
2506
|
+
loaded = await options.engine.loadTranscriptFull(entry.filePath, {
|
|
2507
|
+
maxBytes: L.maxTranscriptBytes,
|
|
2508
|
+
expectIno: st.ino
|
|
2509
|
+
});
|
|
2510
|
+
} catch (e) {
|
|
2511
|
+
if (e instanceof TranscriptTooLargeError) {
|
|
2512
|
+
throw new WebSessionError("resourceLimit", `transcript exceeds limit (${e.size} > ${e.maxBytes} bytes)`);
|
|
2513
|
+
}
|
|
2514
|
+
if (e instanceof TranscriptChangedDuringReadError) {
|
|
2515
|
+
throw new WebSessionError("ioUnavailable", e.message, true);
|
|
2516
|
+
}
|
|
2517
|
+
throw e;
|
|
2518
|
+
}
|
|
2519
|
+
if (loaded.messages.size > L.maxParseRecords) {
|
|
2520
|
+
throw new WebSessionError("resourceLimit", `transcript exceeds parse record limit (${loaded.messages.size} > ${L.maxParseRecords})`);
|
|
2521
|
+
}
|
|
2522
|
+
let leaf;
|
|
2523
|
+
for (const uuid of loaded.leafUuids) {
|
|
2524
|
+
const m = loaded.messages.get(uuid);
|
|
2525
|
+
if (!m)
|
|
2526
|
+
continue;
|
|
2527
|
+
if (!leaf || (m.timestamp ?? "") >= (leaf.timestamp ?? "")) {
|
|
2528
|
+
leaf = m;
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2531
|
+
const chain = leaf ? options.engine.buildConversationChain(loaded.messages, leaf) : [];
|
|
2532
|
+
for (const m of chain) {
|
|
2533
|
+
if (signal?.aborted) {
|
|
2534
|
+
throw new WebSessionError("cancelled", "operation aborted");
|
|
2535
|
+
}
|
|
2536
|
+
if (m.type !== "user" && m.type !== "assistant")
|
|
2537
|
+
continue;
|
|
2538
|
+
const text = renderableSearchText(m);
|
|
2539
|
+
const idx = text.indexOf(needle);
|
|
2540
|
+
if (idx === -1)
|
|
2541
|
+
continue;
|
|
2542
|
+
const snippet = Array.from(text.slice(idx, idx + 1024)).slice(0, 512).join("");
|
|
2543
|
+
results.push({
|
|
2544
|
+
sessionId: entry.sessionId,
|
|
2545
|
+
messageId: m.uuid,
|
|
2546
|
+
snippet
|
|
2547
|
+
});
|
|
2548
|
+
}
|
|
2549
|
+
if (results.length >= pageSize) {
|
|
2550
|
+
return { results, nextPageToken: String(i + 1) };
|
|
2551
|
+
}
|
|
2552
|
+
}
|
|
2553
|
+
return { results };
|
|
2554
|
+
} finally {
|
|
2555
|
+
releaseRead();
|
|
2556
|
+
}
|
|
2557
|
+
},
|
|
2558
|
+
async replaySession(req, signal) {
|
|
2559
|
+
assertStarted("replay session");
|
|
2560
|
+
assertScope(req.scopeId);
|
|
2561
|
+
const projection = await loadProjection(req.scopeId, req.sessionId, signal);
|
|
2562
|
+
return { of: "replaySession", projection };
|
|
2563
|
+
},
|
|
2564
|
+
async followSession(req, signal) {
|
|
2565
|
+
assertStarted("follow session");
|
|
2566
|
+
assertScope(req.scopeId);
|
|
2567
|
+
if (subscriptions.size >= L.maxSubscriptions) {
|
|
2568
|
+
throw new WebSessionError("resourceLimit", `subscription limit exceeded (${subscriptions.size} >= ${L.maxSubscriptions})`);
|
|
2569
|
+
}
|
|
2570
|
+
const handle = createFollowSubscription({
|
|
2571
|
+
adapter,
|
|
2572
|
+
productId: options.productId,
|
|
2573
|
+
scopeId: req.scopeId,
|
|
2574
|
+
sessionId: req.sessionId,
|
|
2575
|
+
subscriptionId: randomUUID2(),
|
|
2576
|
+
...req.requestId ? { requestId: req.requestId } : {},
|
|
2577
|
+
...req.resumeCursor ? { resumeCursor: req.resumeCursor } : {},
|
|
2578
|
+
limits: {
|
|
2579
|
+
pollingIntervalMs: L.pollingIntervalMs,
|
|
2580
|
+
idleLeaseMs: L.idleLeaseMs,
|
|
2581
|
+
pendingEvents: L.maxPendingEvents,
|
|
2582
|
+
pendingBytes: L.maxPendingBytes,
|
|
2583
|
+
maxProjectionBytes: L.maxProjectionBytes,
|
|
2584
|
+
maxRecordBytes: L.maxRecordBytes,
|
|
2585
|
+
maxTranscriptBytes: L.maxTranscriptBytes
|
|
2586
|
+
},
|
|
2587
|
+
signal,
|
|
2588
|
+
ledger: cursorLedger,
|
|
2589
|
+
loadFull: options.engine.loadTranscriptFull,
|
|
2590
|
+
buildConversationChain: options.engine.buildConversationChain,
|
|
2591
|
+
resolvePath,
|
|
2592
|
+
onRelease: () => subscriptions.delete(handle)
|
|
2593
|
+
});
|
|
2594
|
+
subscriptions.add(handle);
|
|
2595
|
+
return handle;
|
|
2596
|
+
},
|
|
2597
|
+
async close() {
|
|
2598
|
+
if (state === "closed")
|
|
2599
|
+
return;
|
|
2600
|
+
state = "closed";
|
|
2601
|
+
const deadline = new Promise((resolve) => setTimeout(resolve, L.closeDeadlineMs));
|
|
2602
|
+
await Promise.race([
|
|
2603
|
+
Promise.all([...subscriptions].map(async (sub) => {
|
|
2604
|
+
try {
|
|
2605
|
+
await sub.close();
|
|
2606
|
+
} catch {}
|
|
2607
|
+
})),
|
|
2608
|
+
deadline
|
|
2609
|
+
]);
|
|
2610
|
+
subscriptions.clear();
|
|
2611
|
+
await adapter.close();
|
|
2612
|
+
}
|
|
2613
|
+
};
|
|
2614
|
+
}
|
|
2615
|
+
// src/atlascode/web/runtimeDefault.ts
|
|
2616
|
+
function atlasWebSessionEngine() {
|
|
2617
|
+
return {
|
|
2618
|
+
loadTranscriptFull: async (filePath, opts) => {
|
|
2619
|
+
const loaded = await loadTranscriptFull(filePath, opts);
|
|
2620
|
+
return {
|
|
2621
|
+
messages: loaded.messages,
|
|
2622
|
+
leafUuids: loaded.leafUuids
|
|
2623
|
+
};
|
|
2624
|
+
},
|
|
2625
|
+
buildConversationChain: (messages, leaf) => buildConversationChain(messages, leaf)
|
|
2626
|
+
};
|
|
2627
|
+
}
|
|
2628
|
+
function createDefaultReadonlySessionRuntime(options) {
|
|
2629
|
+
return createReadonlySessionRuntime({ ...options, engine: atlasWebSessionEngine() });
|
|
2630
|
+
}
|
|
2631
|
+
export {
|
|
2632
|
+
WebSessionError,
|
|
2633
|
+
createDefaultReadonlySessionRuntime,
|
|
2634
|
+
createReadonlySessionRuntime
|
|
2635
|
+
};
|