@kabxx/dsh-session-move 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,190 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { readFile } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { performance } from 'node:perf_hooks'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ export const historyMessageBytes = 8 * 1024 * 1024
9
+ export const historyTimeoutMs = 180_000
10
+ export const historyWorkerArg = 'dsh-session-move-history-worker'
11
+ export const historyReady = 'H1\n'
12
+
13
+ const entry = fileURLToPath(new URL('./history-worker.js', import.meta.url))
14
+ const workerKey = Symbol.for('dsh-session-move.history-process')
15
+ const readyPrefix = Buffer.from(historyReady)
16
+ const v8Only = process.platform === 'win32' || process.platform === 'darwin'
17
+ const oldSpaceMiB = 128
18
+ const memoryMiB = 256
19
+ const virtualBytes = 1024 ** 3
20
+ const unitPrefix = 'dsh-session-move-history-'
21
+ const unitPattern = /\/dsh-session-move-history-[a-f0-9-]+\.scope$/u
22
+
23
+ function failure(code, message, cause) {
24
+ return Object.assign(new Error(message, { cause }), { code })
25
+ }
26
+
27
+ /** Called by the child before it tells the Host that it can accept input. */
28
+ export async function verifyHistoryIsolation(mode) {
29
+ const heapBounded = process.execArgv.includes(`--max-old-space-size=${oldSpaceMiB}`)
30
+ if (heapBounded && mode === 'v8' && v8Only) return
31
+ if (heapBounded && process.platform === 'linux') {
32
+ if (mode === 'cgroup') {
33
+ const groups = await readFile('/proc/self/cgroup', 'utf8')
34
+ const group = groups.split('\n').find(line => line.startsWith('0::'))?.slice(3)
35
+ if (group?.startsWith('/') && unitPattern.test(group)) {
36
+ const directory = join('/sys/fs/cgroup', group)
37
+ const memory = Number((await readFile(join(directory, 'memory.max'), 'utf8')).trim())
38
+ const swap = (await readFile(join(directory, 'memory.swap.max'), 'utf8')).trim()
39
+ if (Number.isSafeInteger(memory) && memory > 0 && memory <= memoryMiB * 1024 ** 2 && swap === '0') return
40
+ }
41
+ } else if (mode === 'rlimit') {
42
+ const limits = await readFile('/proc/self/limits', 'utf8')
43
+ const addresses = /^Max address space\s+(\d+)\s+(\d+)\s+bytes/mu.exec(limits)
44
+ if (addresses && Number(addresses[1]) <= virtualBytes && Number(addresses[2]) <= virtualBytes) return
45
+ }
46
+ }
47
+ throw failure('history-isolation-unavailable', 'Session history worker could not verify its memory limits')
48
+ }
49
+
50
+ function killWorker(child) {
51
+ if (child.pid && process.platform === 'linux') {
52
+ try { process.kill(-child.pid, 'SIGKILL'); return } catch { /* The wrapper may already have exited. */ }
53
+ }
54
+ child.kill('SIGKILL')
55
+ }
56
+
57
+ function readResult(buffer) {
58
+ let result
59
+ try { result = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(buffer)) } catch (cause) {
60
+ return { error: failure('history-protocol', 'Invalid session history response', cause) }
61
+ }
62
+ if (result?.ok === true && Object.hasOwn(result, 'value')) return { value: result.value }
63
+ if (result?.ok === false && typeof result.code === 'string' && /^[a-z][a-z0-9-]{0,63}$/u.test(result.code)) {
64
+ const message = typeof result.message === 'string' ? result.message.slice(0, 512) : 'Session history operation failed'
65
+ return { error: failure(result.code, message) }
66
+ }
67
+ return { error: failure('history-protocol', 'Incomplete session history response') }
68
+ }
69
+
70
+ function runProcess(command, args, request, { signal, remaining, installDirectory }) {
71
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => key.toUpperCase() !== 'NODE_OPTIONS'))
72
+ if (installDirectory) env.DSH_INSTALL_DIR = installDirectory
73
+ if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = '1'
74
+ return new Promise(resolve => {
75
+ const child = spawn(command, args, {
76
+ stdio: ['pipe', 'pipe', 'ignore'], detached: process.platform === 'linux', windowsHide: true, env,
77
+ })
78
+ const output = []
79
+ const prefix = Buffer.alloc(readyPrefix.length)
80
+ let bytes = 0
81
+ let ready = false
82
+ let failureCause
83
+ let stopped
84
+ const terminate = error => {
85
+ if (stopped) return
86
+ stopped = error
87
+ killWorker(child)
88
+ }
89
+ const cancel = () => terminate(failure('history-cancelled', 'Session history preparation was cancelled'))
90
+ const deadline = setTimeout(() => {
91
+ terminate(failure('history-timeout', 'Session history preparation timed out'))
92
+ }, Math.max(1, remaining))
93
+
94
+ child.once('error', error => { failureCause ??= error })
95
+ child.stdout.on('error', error => { failureCause ??= error })
96
+ child.stdout.on('data', chunk => {
97
+ if (stopped) return
98
+ if (bytes + chunk.length > historyMessageBytes) {
99
+ terminate(failure('history-ipc-limit', 'Session history response exceeds the IPC size limit'))
100
+ return
101
+ }
102
+ if (!ready) {
103
+ chunk.copy(prefix, bytes, 0, Math.min(chunk.length, readyPrefix.length - bytes))
104
+ if (bytes + chunk.length >= readyPrefix.length) {
105
+ ready = prefix.equals(readyPrefix)
106
+ if (!ready) {
107
+ terminate(failure('history-protocol', 'Invalid session history ready marker'))
108
+ return
109
+ }
110
+ // Deliver filesystem paths only after the worker proves its limits.
111
+ child.stdin.end(request)
112
+ }
113
+ }
114
+ bytes += chunk.length
115
+ output.push(chunk)
116
+ })
117
+ child.stdin.on('error', error => { failureCause ??= error })
118
+ child.once('close', (code, exitSignal) => {
119
+ clearTimeout(deadline)
120
+ signal?.removeEventListener('abort', cancel)
121
+ if (stopped) {
122
+ resolve({ error: stopped })
123
+ } else if (!ready) {
124
+ resolve({ unavailable: true, error: failure('history-isolation-unavailable', 'Unable to start a memory-limited session history worker', failureCause) })
125
+ } else if (failureCause || code !== 0) {
126
+ const detail = exitSignal ? `signal ${exitSignal}` : `exit code ${code}`
127
+ resolve({ error: failure('history-resource', `Session history worker exited with ${detail}`, failureCause) })
128
+ } else {
129
+ resolve(readResult(Buffer.concat(output, bytes).subarray(readyPrefix.length)))
130
+ }
131
+ })
132
+ signal?.addEventListener('abort', cancel, { once: true })
133
+ if (signal?.aborted) cancel()
134
+ })
135
+ }
136
+
137
+ /** Launch one worker at a time and enforce a single deadline across launcher fallbacks. */
138
+ export async function runHistory(request, { signal, timeoutMs = historyTimeoutMs, installDirectory } = {}) {
139
+ if (signal?.aborted) throw failure('history-cancelled', 'Session history preparation was cancelled')
140
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > historyTimeoutMs) {
141
+ throw failure('history-timeout', 'Invalid session history preparation deadline')
142
+ }
143
+ if (globalThis[workerKey]) throw failure('history-busy', 'A session history worker is already running')
144
+ if (process.platform !== 'linux' && !v8Only) {
145
+ throw failure('history-isolation-unavailable', 'Session history isolation is unavailable on this platform')
146
+ }
147
+
148
+ const start = performance.now()
149
+ let encoded
150
+ try { encoded = JSON.stringify(request) } catch (cause) {
151
+ throw failure('history-protocol', 'Invalid session history request', cause)
152
+ }
153
+ if (encoded === undefined) throw failure('history-protocol', 'Missing session history request')
154
+ if (Buffer.byteLength(encoded) > historyMessageBytes) {
155
+ throw failure('history-ipc-limit', 'Session history request exceeds the IPC size limit')
156
+ }
157
+
158
+ const remaining = () => timeoutMs - (performance.now() - start)
159
+ const launch = (command, args) => {
160
+ if (signal?.aborted) throw failure('history-cancelled', 'Session history preparation was cancelled')
161
+ const timeLeft = remaining()
162
+ if (timeLeft <= 0) throw failure('history-timeout', 'Session history preparation timed out')
163
+ return runProcess(command, args, encoded, { signal, remaining: timeLeft, installDirectory })
164
+ }
165
+ const node = [process.execPath, `--max-old-space-size=${oldSpaceMiB}`]
166
+ globalThis[workerKey] = true
167
+ try {
168
+ let result
169
+ if (process.platform === 'linux') {
170
+ result = await launch('systemd-run', [
171
+ '--user', '--scope', '--quiet', '--collect', `--unit=${unitPrefix}${randomUUID()}`,
172
+ '-p', `MemoryMax=${memoryMiB}M`, '-p', 'MemorySwapMax=0', '--',
173
+ 'prlimit', '--core=0', '--', ...node, entry, historyWorkerArg, 'cgroup',
174
+ ])
175
+ if (result.unavailable) {
176
+ // V8 reserves code address space independently of its old-generation heap.
177
+ result = await launch('prlimit', [
178
+ `--as=${virtualBytes}`, '--core=0', '--', ...node, '--jitless', entry, historyWorkerArg, 'rlimit',
179
+ ])
180
+ }
181
+ } else {
182
+ // Native Windows and macOS still get a separate Node process and heap cap.
183
+ result = await launch(process.execPath, [node[1], entry, historyWorkerArg, 'v8'])
184
+ }
185
+ if (result.error) throw result.error
186
+ return result.value
187
+ } finally {
188
+ delete globalThis[workerKey]
189
+ }
190
+ }
@@ -0,0 +1,483 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { constants as fileFlags } from 'node:fs'
3
+ import { lstat, open, realpath } from 'node:fs/promises'
4
+ import { basename, isAbsolute, resolve } from 'node:path'
5
+ import { Readable } from 'node:stream'
6
+ import { pipeline } from 'node:stream/promises'
7
+ import { pathToFileURL } from 'node:url'
8
+ import { deserialize, serialize } from 'node:v8'
9
+ import { constants, createZstdDecompress } from 'node:zlib'
10
+ import { sessionRequire } from './platform-fs.js'
11
+ import { createFrameScanner } from './zstd-frame.js'
12
+
13
+ export const HISTORY_CHUNK_BYTES = 128 * 1024
14
+ export const MAX_HISTORY_RECORD_BYTES = 16 * 1024 * 1024
15
+ export const MAX_SUMMARY_STRING_BYTES = 1024 * 1024
16
+ const windows = process.platform === 'win32'
17
+ const maxReferencesPerRecord = 256 * 1024
18
+ const maxRelationshipStateBytes = 48 * 1024 * 1024
19
+ const knownRelationshipTypes = new Set([
20
+ 'system/message', 'user/message', 'developer/message', 'assistant/message', 'tool/result', 'assistant/attempt',
21
+ 'turn/start', 'turn/end', 'step/start', 'step/end', 'tool/call', 'request/header', 'request/context',
22
+ 'tool/ptc-dispatch-start', 'tool/ptc-dispatch', 'llm/retry', 'llm/retry-started', 'session/title',
23
+ 'session/title-llm-request', 'command/run', 'command/done', 'compaction/start', 'compaction/summary',
24
+ 'compaction/end', 'compaction/prune', 'session/end-seed', 'subagent/catalog', 'session-log-deepseek/delivery-accepted',
25
+ ])
26
+ let modules
27
+
28
+ function sessionFormat() {
29
+ return modules ??= (async () => {
30
+ const require = sessionRequire()
31
+ const load = (name) => import(pathToFileURL(require.resolve(`@deepseek-ai/${name}`)).href)
32
+ const [format, session] = await Promise.all([load('dsh-session-format-v3-to-v4'), load('dsh-session')])
33
+ return { ...format, ...session }
34
+ })()
35
+ }
36
+
37
+ function requireHistory(condition, message, code = 'unsupported') {
38
+ if (!condition) throw Object.assign(new Error(message), { code })
39
+ }
40
+
41
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value)
42
+ const fields = (value, keys) => isRecord(value)
43
+ ? Object.fromEntries(keys.filter((key) => Object.hasOwn(value, key)).map((key) => [key, value[key]]))
44
+ : value
45
+
46
+ function checkMessageSources({ type, data }) {
47
+ if (!isRecord(data)) return
48
+ let messages
49
+ switch (type) {
50
+ case 'user/message': messages = [data]; break
51
+ case 'system/message': case 'developer/message': case 'assistant/message': case 'tool/result': messages = [data.message]; break
52
+ case 'agent/inbox/spliced': messages = data.inserted; break
53
+ case 'session/title-llm-request': messages = data.messages; break
54
+ default: return
55
+ }
56
+ requireHistory(Array.isArray(messages), `${type} requires a message array`)
57
+ for (const item of messages) {
58
+ requireHistory(isRecord(item) && isRecord(item.source) && typeof item.source.kind === 'string'
59
+ && item.source.kind.length > 0 && item.source.kind !== 'plugin', 'Invalid durable message source')
60
+ }
61
+ }
62
+
63
+ // V4 encodes ranges in a single short row. Bound expansion before asking the
64
+ // native codec to allocate the expanded array and its uniqueness set.
65
+ function checkReferenceSize({ sourceEventSeqs }) {
66
+ if (!Array.isArray(sourceEventSeqs)) return
67
+ let count = 0
68
+ for (const source of sourceEventSeqs) {
69
+ count += Array.isArray(source) && Number.isSafeInteger(source[0]) && Number.isSafeInteger(source[1])
70
+ ? Math.max(1, source[1] - source[0] + 1) : 1
71
+ requireHistory(count <= maxReferencesPerRecord, 'History record exceeds the source reference budget', 'history-resource')
72
+ }
73
+ }
74
+
75
+ function toolResultShape(data) {
76
+ const { turn, step, message, error } = data
77
+ const shape = fields(message, ['toolCallId', 'id', 'isError'])
78
+ if (isRecord(shape)) shape.source = fields(message.source, ['kind'])
79
+ // The native validator only inspects tool result content for its special
80
+ // interrupted-before-start repair. Carry that witness without retaining tool output.
81
+ const correction = 'The tool call was interrupted before the Harness recorded it as started. Retry it if it is still needed.'
82
+ if (Array.isArray(message?.content) && message.content.length === 1 && message.content[0]?.type === 'text'
83
+ && message.content[0]?.text === correction) shape.content = [{ type: 'text', text: correction }]
84
+ else if (Array.isArray(message?.content)) shape.content = []
85
+ return { turn, step, message: shape, error: fields(error, ['name', 'code']) }
86
+ }
87
+
88
+ // Values used only in tool-lifecycle equality checks can be represented by
89
+ // collision-resistant hashes. The two domains stay separate: ordinary tool
90
+ // calls compare strings by value, while PTC uses deep, order-independent JSON.
91
+ function toolArgument(value) {
92
+ return typeof value === 'string'
93
+ ? createHash('sha256').update(value, 'utf16le').digest('hex') : value
94
+ }
95
+
96
+ function dispatchArgument(value) {
97
+ if (value === undefined) return undefined
98
+ const hash = createHash('sha256')
99
+ function visit(item) {
100
+ if (Array.isArray(item)) {
101
+ hash.update('[')
102
+ for (const child of item) visit(child)
103
+ hash.update(']')
104
+ } else if (isRecord(item)) {
105
+ hash.update('{')
106
+ for (const key of Object.keys(item).sort()) {
107
+ hash.update(JSON.stringify(key)).update(':')
108
+ visit(item[key])
109
+ }
110
+ hash.update('}')
111
+ } else {
112
+ // Distinguish the JSON numeric forms that isDeepStrictEqual treats as distinct.
113
+ const token = typeof item === 'number' && !Number.isFinite(item) ? `number:${item}`
114
+ : Object.is(item, -0) ? '-0' : JSON.stringify(item)
115
+ hash.update(token).update(',')
116
+ }
117
+ }
118
+ visit(value)
119
+ return hash.digest('hex')
120
+ }
121
+
122
+ /** Capture exactly the earlier facts used by the pinned V4 relationship pass. */
123
+ function relationshipFact(event) {
124
+ const { type, seq, data, surfaceOp, sourceEventSeqs } = event
125
+ let evidence = data
126
+ if (isRecord(data)) {
127
+ switch (type) {
128
+ case 'user/message':
129
+ evidence = { source: fields(data.source, ['kind', 'compactionId', 'sourceCommandId']) }
130
+ break
131
+ case 'system/message':
132
+ evidence = { turn: data.turn, step: data.step, message: { source: fields(data.message?.source, ['kind']) } }
133
+ break
134
+ case 'assistant/message': case 'developer/message': {
135
+ const message = fields(data.message, ['id', 'role'])
136
+ // Assistant source.replayState may carry a large model replay payload.
137
+ // The native relationship pass needs only the producer kind.
138
+ if (isRecord(message)) message.source = fields(data.message.source, ['kind'])
139
+ const content = data.message?.content
140
+ if (isRecord(message)) message.content = Array.isArray(content)
141
+ ? content.filter((block) => !isRecord(block) || (type === 'assistant/message'
142
+ ? block.type === 'tool-call' : block.type === 'tool-addition'))
143
+ .map((block) => {
144
+ const selected = fields(block, ['type', 'id', 'name', 'arguments', 'toolName'])
145
+ if (isRecord(selected) && Object.hasOwn(selected, 'arguments')) selected.arguments = toolArgument(selected.arguments)
146
+ return selected
147
+ }) : content
148
+ evidence = { ...fields(data, ['turn', 'step', 'headerSeq']), message }
149
+ break
150
+ }
151
+ case 'tool/result': evidence = toolResultShape(data); break
152
+ case 'request/header': {
153
+ const { config, tools } = data.header
154
+ evidence = { header: { config: fields(config, ['provider']), tools: Array.isArray(tools)
155
+ ? tools.map((tool) => isRecord(tool) ? { ...fields(tool, ['name', 'description']),
156
+ description: typeof tool.description === 'string' ? '' : tool.description,
157
+ parameters: isRecord(tool.parameters) ? {} : null } : null) : tools } }
158
+ break
159
+ }
160
+ case 'session/title-llm-request':
161
+ evidence = { messageSeqs: data.messageSeqs, messages: Array.isArray(data.messages)
162
+ ? data.messages.map((message) => {
163
+ const selected = fields(message, ['role'])
164
+ if (isRecord(selected)) {
165
+ selected.source = fields(message.source, ['kind'])
166
+ selected.content = Array.isArray(message.content)
167
+ ? message.content.map((part) => fields(part, ['type'])) : message.content
168
+ }
169
+ return selected
170
+ }) : data.messages }
171
+ break
172
+ case 'session/title': evidence = fields(data, ['source', 'messageSeqs']); break
173
+ case 'tool/ptc-dispatch': case 'tool/ptc-dispatch-start':
174
+ evidence = fields(data, ['subCallId', 'rootCallId', 'parentCallId', 'name'])
175
+ evidence.arguments = dispatchArgument(data.arguments)
176
+ break
177
+ case 'tool/call':
178
+ evidence = fields(data, ['turn', 'step', 'callId', 'name'])
179
+ evidence.arguments = toolArgument(data.arguments)
180
+ break
181
+ case 'compaction/start': case 'compaction/summary': case 'compaction/end': case 'compaction/prune':
182
+ evidence = fields(data, ['turn', 'compactionId', 'sourceCommandId', 'shadowedRange', 'shadowedSeqs', 'error']); break
183
+ case 'llm/retry': case 'llm/retry-started': evidence = fields(data, ['turn', 'step', 'provider', 'retryId', 'retry', 'policyKey']); break
184
+ case 'command/run': case 'command/done': evidence = fields(data, ['commandId', 'sourceEventSeq', 'kind']); break
185
+ case 'turn/start': case 'turn/end': case 'step/start': case 'step/end': case 'assistant/attempt':
186
+ evidence = fields(data, ['turn', 'step']); break
187
+ case 'request/context': case 'session/end-seed': evidence = {}; break
188
+ // Keep the catalog and delivery objects for native ownership checks.
189
+ }
190
+ }
191
+ return { type, seq, data: evidence, surfaceOp, sourceEventSeqs }
192
+ }
193
+
194
+ class RelationshipState {
195
+ #bytes = 0
196
+ #facts = new Map()
197
+ #headers = new Map()
198
+
199
+ append(event) {
200
+ if (!knownRelationshipTypes.has(event.type)) return
201
+ const { seq, ...evidence } = relationshipFact(event)
202
+ let fact = serialize(evidence)
203
+ let newFactBytes = fact.byteLength
204
+ if (event.type === 'request/header') {
205
+ // Native writes commonly repeat one tool schema across many requests.
206
+ const fingerprint = createHash('sha256').update(fact).digest('hex')
207
+ const existing = this.#headers.get(fingerprint)
208
+ if (existing) {
209
+ requireHistory(existing.equals(fact), 'Conflicting native request header evidence')
210
+ fact = existing
211
+ newFactBytes = 0
212
+ } else this.#headers.set(fingerprint, fact)
213
+ }
214
+ // Budget backing storage plus room for the index and the native validator's
215
+ // surface, command, retry, and dispatch indices. No transcript text is stored.
216
+ this.#bytes += newFactBytes * 2 + 96
217
+ requireHistory(this.#bytes <= maxRelationshipStateBytes,
218
+ `History exceeds the relationship validation budget at seq ${seq}`, 'history-resource')
219
+ this.#facts.set(seq, fact)
220
+ }
221
+
222
+ events() {
223
+ const facts = this.#facts
224
+ return new Proxy({
225
+ *[Symbol.iterator]() {
226
+ for (const [seq, value] of facts) yield { ...deserialize(value), seq }
227
+ },
228
+ }, {
229
+ get(target, key) {
230
+ if (typeof key !== 'string' || !/^(0|[1-9]\d*)$/u.test(key)) return Reflect.get(target, key)
231
+ const seq = Number(key)
232
+ const fact = facts.get(seq)
233
+ return fact === undefined ? undefined : { ...deserialize(fact), seq }
234
+ },
235
+ })
236
+ }
237
+ }
238
+
239
+ async function scanBoundaries(file, size) {
240
+ const buffer = Buffer.allocUnsafe(Math.min(HISTORY_CHUNK_BYTES, size))
241
+ const scanner = createFrameScanner()
242
+ let headerEnd
243
+ let offset = 0
244
+ while (offset < size) {
245
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, size - offset), offset)
246
+ requireHistory(bytesRead > 0, 'Session log changed while scanning', 'changed')
247
+ try {
248
+ scanner.write(buffer.subarray(0, bytesRead), (frame) => { headerEnd ??= frame.end })
249
+ } catch (error) {
250
+ throw Object.assign(error, { code: 'unsupported' })
251
+ }
252
+ offset += bytesRead
253
+ if (headerEnd === undefined) {
254
+ requireHistory(offset <= MAX_HISTORY_RECORD_BYTES, 'Compressed Zstandard header exceeds the record limit', 'history-resource')
255
+ }
256
+ }
257
+ requireHistory(headerEnd !== undefined, 'Missing complete Zstandard header frame')
258
+ requireHistory(headerEnd <= MAX_HISTORY_RECORD_BYTES, 'Compressed Zstandard header exceeds the record limit', 'history-resource')
259
+ return { headerEnd, tornTruncateTo: scanner.finish() }
260
+ }
261
+
262
+ // Some Node releases silently discard a later frame when its bytes arrive in
263
+ // the same input chunk as an earlier one. Isolate each frame while keeping both
264
+ // the compressed input and decompressed output streaming.
265
+ async function* frameParts(input) {
266
+ const scanner = createFrameScanner()
267
+ let offset = 0
268
+ for await (const chunk of input) {
269
+ const ends = []
270
+ scanner.write(chunk, ({ end }) => ends.push(end - offset))
271
+ let cursor = 0
272
+ for (const end of ends) {
273
+ yield { bytes: chunk.subarray(cursor, end), last: true }
274
+ cursor = end
275
+ }
276
+ if (cursor < chunk.length) yield { bytes: chunk.subarray(cursor), last: false }
277
+ offset += chunk.length
278
+ }
279
+ requireHistory(scanner.finish() === undefined, 'Incomplete Zstandard frame')
280
+ }
281
+
282
+ async function* readFrame(parts, part) {
283
+ for (;;) {
284
+ yield part.bytes
285
+ if (part.last) return
286
+ const next = await parts.next()
287
+ requireHistory(!next.done, 'Incomplete Zstandard frame')
288
+ part = next.value
289
+ }
290
+ }
291
+
292
+ async function* decodeFrames(input) {
293
+ const parts = frameParts(input)
294
+ try {
295
+ for await (const first of parts) {
296
+ const frame = Readable.from(readFrame(parts, first), { objectMode: false, highWaterMark: HISTORY_CHUNK_BYTES })
297
+ const decoder = createZstdDecompress({ chunkSize: HISTORY_CHUNK_BYTES,
298
+ params: { [constants.ZSTD_d_windowLogMax]: 27 } })
299
+ const transport = pipeline(frame, decoder).then(() => undefined, (error) => error)
300
+ try {
301
+ yield* decoder
302
+ const error = await transport
303
+ if (error) throw error
304
+ } finally {
305
+ decoder.destroy()
306
+ await transport
307
+ }
308
+ }
309
+ } finally {
310
+ await parts.return()
311
+ }
312
+ }
313
+
314
+ async function* readRecords(file, { compressed, start, end }) {
315
+ const input = file.createReadStream({ start, end, autoClose: false, highWaterMark: HISTORY_CHUNK_BYTES })
316
+ const decoded = compressed ? decodeFrames(input) : input
317
+ // Match the native scanner's UTF-8 replacement behavior. Keep the line cap
318
+ // on raw bytes while collecting only an incomplete record between chunks.
319
+ let fragments = []
320
+ let bytes = 0
321
+ for await (const chunk of decoded) {
322
+ let cursor = 0
323
+ while (cursor < chunk.length) {
324
+ const newline = chunk.indexOf(0x0a, cursor)
325
+ const part = chunk.subarray(cursor, newline < 0 ? chunk.length : newline + 1)
326
+ bytes += part.length
327
+ requireHistory(bytes <= MAX_HISTORY_RECORD_BYTES, 'History contains a record larger than 16 MiB', 'history-resource')
328
+ if (newline < 0) fragments.push(part)
329
+ else {
330
+ const line = fragments.length ? Buffer.concat([...fragments, part], bytes) : part
331
+ fragments = []
332
+ bytes = 0
333
+ yield JSON.parse(line.toString('utf8'))
334
+ }
335
+ cursor += part.length
336
+ }
337
+ }
338
+ requireHistory(bytes === 0, 'History contains an incomplete final record')
339
+ }
340
+
341
+ // Mirror DSH's `readZstdPrefix` torn-tail recovery: flush available plaintext
342
+ // from a structurally incomplete final frame, keep complete newline-terminated
343
+ // records, and drop an incomplete final line.
344
+ async function* readTornRecords(file, { start, end }) {
345
+ const input = file.createReadStream({ start, end, autoClose: false, highWaterMark: HISTORY_CHUNK_BYTES })
346
+ const decoder = createZstdDecompress({
347
+ chunkSize: HISTORY_CHUNK_BYTES,
348
+ finishFlush: constants.ZSTD_e_flush,
349
+ params: { [constants.ZSTD_d_windowLogMax]: 27 },
350
+ })
351
+ const transport = pipeline(input, decoder).then(() => undefined, (error) => error)
352
+ const iterator = decoder[Symbol.asyncIterator]()
353
+ let fragments = []
354
+ let bytes = 0
355
+ let emitted = 0
356
+ try {
357
+ for (;;) {
358
+ let step
359
+ try {
360
+ step = await iterator.next()
361
+ } catch (error) {
362
+ if (emitted === 0) return
363
+ throw Object.assign(new Error('Corrupt trailing Zstandard frame', { cause: error }), { code: 'unsupported' })
364
+ }
365
+ if (step.done) break
366
+ const chunk = step.value
367
+ let cursor = 0
368
+ while (cursor < chunk.length) {
369
+ const newline = chunk.indexOf(0x0a, cursor)
370
+ const part = chunk.subarray(cursor, newline < 0 ? chunk.length : newline + 1)
371
+ bytes += part.length
372
+ requireHistory(bytes <= MAX_HISTORY_RECORD_BYTES, 'History contains a record larger than 16 MiB', 'history-resource')
373
+ if (newline < 0) fragments.push(part)
374
+ else {
375
+ const line = fragments.length ? Buffer.concat([...fragments, part], bytes) : part
376
+ fragments = []
377
+ bytes = 0
378
+ const record = JSON.parse(line.toString('utf8'))
379
+ emitted++
380
+ yield record
381
+ }
382
+ cursor += part.length
383
+ }
384
+ }
385
+ const error = await transport
386
+ if (error && emitted > 0) {
387
+ throw Object.assign(new Error('Corrupt trailing Zstandard frame', { cause: error }), { code: 'unsupported' })
388
+ }
389
+ } finally {
390
+ decoder.destroy()
391
+ await transport
392
+ }
393
+ }
394
+
395
+ function sameFile(first, next) {
396
+ return next.isFile() && ['dev', 'ino', 'size', 'mtimeNs', 'ctimeNs'].every((key) => first[key] === next[key])
397
+ }
398
+
399
+ function sameCanonicalPath(actual, expected) {
400
+ if (resolve(expected) !== expected) return false
401
+ const normalize = (value) => windows ? value.toLowerCase() : value
402
+ return normalize(actual) === normalize(expected)
403
+ }
404
+
405
+ /** Read an unchanged v4 artifact, awaiting each callback before advancing. */
406
+ export async function scanHistory(path, { onHeader, onEvent } = {}) {
407
+ requireHistory(typeof path === 'string' && isAbsolute(path) && /^session\.v4\.jsonl(?:\.zstd)?$/u.test(basename(path)),
408
+ 'Invalid current session log path')
409
+ requireHistory(sameCanonicalPath(await realpath(path), path), 'Noncanonical session log path', 'changed')
410
+ const file = await open(path, fileFlags.O_RDONLY | (fileFlags.O_NONBLOCK ?? 0) | (fileFlags.O_NOFOLLOW ?? 0))
411
+ try {
412
+ const initial = await file.stat({ bigint: true })
413
+ requireHistory(initial.isFile() && initial.size > 0n && initial.size <= BigInt(Number.MAX_SAFE_INTEGER), 'Invalid session log size')
414
+ requireHistory(sameFile(initial, await lstat(path, { bigint: true })), 'Session log identity changed', 'changed')
415
+ const size = Number(initial.size)
416
+ const end = size - 1
417
+ const compressed = path.endsWith('.zstd')
418
+ const boundaries = compressed ? await scanBoundaries(file, size) : undefined
419
+ const headerEnd = boundaries?.headerEnd
420
+ const tornTruncateTo = boundaries?.tornTruncateTo
421
+ const { adoptSessionEvent, KNOWN_SESSION_EVENT_TYPES, releasedV4SessionFormatCodec, assertReleasedV4Header,
422
+ assertV4RowAdmission, assertReleasedV4Relationships } = await sessionFormat()
423
+ const relationships = new RelationshipState()
424
+ let decoder
425
+ let eventCount = 0
426
+ let tornRecoveredCount = 0
427
+ const decodeHeader = async (record) => {
428
+ requireHistory(decoder === undefined, 'The first Zstandard frame must contain exactly one header record')
429
+ decoder = releasedV4SessionFormatCodec.createDecoder(record, 'strict')
430
+ assertReleasedV4Header(decoder.header)
431
+ await onHeader?.(Object.freeze(decoder.header))
432
+ }
433
+ let event
434
+ const context = {
435
+ emitEvent(value) { event = adoptSessionEvent(value) },
436
+ emitRun() { throw new Error('Unexpected compressed event run in v4 log') },
437
+ }
438
+ const decodeEvent = async (record) => {
439
+ const known = KNOWN_SESSION_EVENT_TYPES.has(record?.type)
440
+ requireHistory(known || record?.ignorable === true, 'History contains an unknown required event')
441
+ requireHistory(record?.type !== 'request/header' || record.data?.reason !== 'fallback', 'History contains a retired request header')
442
+ checkReferenceSize(record)
443
+ assertV4RowAdmission(record, KNOWN_SESSION_EVENT_TYPES)
444
+ decoder.decodeRow(record, context)
445
+ if (known) {
446
+ checkMessageSources(event)
447
+ relationships.append(event)
448
+ }
449
+ eventCount++
450
+ await onEvent?.(event)
451
+ event = undefined
452
+ }
453
+ if (compressed) {
454
+ for await (const record of readRecords(file, { compressed, start: 0, end: headerEnd - 1 })) await decodeHeader(record)
455
+ requireHistory(decoder !== undefined, 'Missing session header')
456
+ const completeEnd = (tornTruncateTo ?? size) - 1
457
+ if (headerEnd <= completeEnd) {
458
+ for await (const record of readRecords(file, { compressed, start: headerEnd, end: completeEnd })) await decodeEvent(record)
459
+ }
460
+ if (tornTruncateTo !== undefined) {
461
+ for await (const record of readTornRecords(file, { start: tornTruncateTo, end })) {
462
+ await decodeEvent(record)
463
+ tornRecoveredCount++
464
+ }
465
+ }
466
+ } else {
467
+ for await (const record of readRecords(file, { compressed, start: 0, end })) {
468
+ if (decoder === undefined) await decodeHeader(record)
469
+ else await decodeEvent(record)
470
+ }
471
+ requireHistory(decoder !== undefined, 'Missing session header')
472
+ }
473
+ const header = decoder.header
474
+ const inheritedEventCount = decoder.finish(context)
475
+ assertReleasedV4Relationships({ header, inheritedEventCount, events: relationships.events() }, KNOWN_SESSION_EVENT_TYPES)
476
+ requireHistory(sameFile(initial, await file.stat({ bigint: true })) && sameFile(initial, await lstat(path, { bigint: true }))
477
+ && sameCanonicalPath(await realpath(path), path), 'Session log changed while scanning', 'changed')
478
+ return {
479
+ header, inheritedEventCount, eventCount, lastSeq: eventCount - 1,
480
+ ...(tornTruncateTo === undefined ? {} : { tornTruncateTo, tornRecoveredCount }),
481
+ }
482
+ } finally { await file.close() }
483
+ }