pi-agy-acp 0.2.1 → 0.2.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,670 @@
1
+ /**
2
+ * Read-only SQLite session database access, protobuf context-window decoding,
3
+ * hidden upstream API error classification, and scoped artifact cleanup.
4
+ * @module pi-agy-acp/session-db
5
+ */
6
+
7
+ import {
8
+ lstatSync,
9
+ realpathSync,
10
+ rmSync,
11
+ type BigIntStats,
12
+ type Stats,
13
+ } from 'node:fs'
14
+ import { isAbsolute, join, relative } from 'node:path'
15
+ import { DatabaseSync } from 'node:sqlite'
16
+
17
+ const EMPTY_BYTES = new Uint8Array(0)
18
+ const MAX_VARINT_SHIFT = 63n
19
+ const DEFAULT_MAX_META_ROWS = 64
20
+
21
+ /** Context window telemetry decoded from `gen_metadata.data`. */
22
+ export interface ContextWindowMetadata {
23
+ maxContextTokens?: number
24
+ estimatedTokensUsed?: number
25
+ }
26
+
27
+ /** Result of validating and statting one session's SQLite database and sidecars. */
28
+ export type ResolvedSessionDb =
29
+ | { kind: 'ok'; dbPath: string; stamp: string }
30
+ | { kind: 'missing' }
31
+ | { kind: 'invalid' }
32
+
33
+ /** Per-table high-water marks read before a prompt segment begins. */
34
+ export interface SessionCursors {
35
+ nextMetaIdx: number
36
+ lastStepIdx: number
37
+ }
38
+
39
+ /** Classified failure hidden inside a session's `steps` table after `end_turn` or `refusal`. */
40
+ export type HiddenTurnErrorKind =
41
+ | 'quota'
42
+ | 'invalid_thinking_signature'
43
+ | 'rate_limit'
44
+ | 'transient_not_found'
45
+ | 'model_not_found'
46
+
47
+ export interface HiddenTurnError {
48
+ kind: HiddenTurnErrorKind
49
+ code: 'QUOTA' | 'PROVIDER_ERROR' | 'RATE_LIMIT' | 'SERVER' | 'UNKNOWN_MODEL'
50
+ message: string
51
+ dirtySession?: boolean
52
+ resetTimestamp?: string
53
+ retryAfterSeconds?: number
54
+ }
55
+
56
+ /** Options for one merged `readSessionTurnData` query. */
57
+ export interface ReadSessionTurnDataOptions {
58
+ metaFloorIdx: number | null
59
+ turnMetaFloorIdx?: number | null
60
+ lastStepIdx?: number | null
61
+ checkStepsError?: boolean
62
+ ifChangedSince?: string
63
+ maxMetaRows?: number
64
+ }
65
+
66
+ /** Telemetry and optional hidden API error observed from one session DB read. */
67
+ export interface SessionTurnData {
68
+ unchanged?: boolean
69
+ stamp: string
70
+ maxContextTokens?: number
71
+ estimatedTokensUsed?: number
72
+ hiddenError?: HiddenTurnError
73
+ }
74
+
75
+ function isValidSessionId(sessionId: string): boolean {
76
+ return (
77
+ typeof sessionId === 'string' &&
78
+ sessionId.length > 0 &&
79
+ !/[^A-Za-z0-9._-]/.test(sessionId) &&
80
+ sessionId !== '.' &&
81
+ !sessionId.includes('..')
82
+ )
83
+ }
84
+
85
+ function isRealDirectory(path: string): boolean {
86
+ try {
87
+ return lstatSync(path).isDirectory()
88
+ } catch {
89
+ return false
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Remove named entries inside a non-symlinked directory.
95
+ * Never follows a replaced parent directory into paths outside the isolated home.
96
+ */
97
+ export function removeArtifacts(
98
+ directory: string,
99
+ names: readonly string[],
100
+ ): void {
101
+ if (!isRealDirectory(directory)) return
102
+ for (const name of names) {
103
+ try {
104
+ rmSync(join(directory, name), { recursive: true, force: true })
105
+ } catch {
106
+ // Locked or unreadable leftovers can be retried on the next startup.
107
+ }
108
+ }
109
+ }
110
+
111
+ /** Remove only one closed ACP session's files; session ids come from the agent. */
112
+ export function removeSessionArtifacts(home: string, sessionId: string): void {
113
+ if (!isValidSessionId(sessionId)) return
114
+ const appData = join(home, 'agy')
115
+ if (!isRealDirectory(appData)) return
116
+ removeArtifacts(join(appData, 'conversations'), [
117
+ `${sessionId}.db`,
118
+ `${sessionId}.db-wal`,
119
+ `${sessionId}.db-shm`,
120
+ `${sessionId}.db-journal`,
121
+ ])
122
+ removeArtifacts(join(appData, 'brain'), [sessionId])
123
+ removeArtifacts(join(appData, 'annotations'), [`${sessionId}.pbtxt`])
124
+ }
125
+
126
+ function readVarint(
127
+ buf: Uint8Array,
128
+ start: number,
129
+ ): { value: bigint; next: number } | undefined {
130
+ let value = 0n
131
+ let shift = 0n
132
+ let pos = start
133
+ while (pos < buf.length && shift <= MAX_VARINT_SHIFT) {
134
+ const byte = buf[pos++] as number
135
+ value |= BigInt(byte & 0x7f) << shift
136
+ if ((byte & 0x80) === 0) return { value, next: pos }
137
+ shift += 7n
138
+ }
139
+ return undefined
140
+ }
141
+
142
+ function skipField(
143
+ buf: Uint8Array,
144
+ pos: number,
145
+ wireType: number,
146
+ ): number | undefined {
147
+ if (wireType === 0) return readVarint(buf, pos)?.next
148
+ if (wireType === 1) return pos + 8 <= buf.length ? pos + 8 : undefined
149
+ if (wireType === 2) {
150
+ const len = readVarint(buf, pos)
151
+ if (len === undefined) return undefined
152
+ const byteLen = Number(len.value)
153
+ if (!Number.isSafeInteger(byteLen) || byteLen < 0) return undefined
154
+ const end = len.next + byteLen
155
+ return end <= buf.length ? end : undefined
156
+ }
157
+ if (wireType === 5) return pos + 4 <= buf.length ? pos + 4 : undefined
158
+ return undefined
159
+ }
160
+
161
+ function scanMessage<T>(
162
+ buf: Uint8Array,
163
+ targetField: number,
164
+ expectedWireType: 0 | 2,
165
+ onMatch: (payload: Uint8Array, varint: bigint) => T | undefined,
166
+ ): T | undefined {
167
+ let pos = 0
168
+ let result: T | undefined
169
+ while (pos < buf.length) {
170
+ const tag = readVarint(buf, pos)
171
+ if (tag === undefined) break
172
+ pos = tag.next
173
+ const fieldNumber = Number(tag.value >> 3n)
174
+ const wireType = Number(tag.value & 7n)
175
+ if (fieldNumber <= 0) break
176
+ if (fieldNumber === targetField && wireType === expectedWireType) {
177
+ if (wireType === 0) {
178
+ const val = readVarint(buf, pos)
179
+ if (val === undefined) break
180
+ pos = val.next
181
+ const matched = onMatch(EMPTY_BYTES, val.value)
182
+ if (matched !== undefined) result = matched
183
+ continue
184
+ }
185
+ const len = readVarint(buf, pos)
186
+ if (len === undefined) break
187
+ const byteLen = Number(len.value)
188
+ if (!Number.isSafeInteger(byteLen) || byteLen < 0) break
189
+ const end = len.next + byteLen
190
+ if (end > buf.length) break
191
+ const matched = onMatch(buf.subarray(len.next, end), 0n)
192
+ if (matched !== undefined) result = matched
193
+ pos = end
194
+ continue
195
+ }
196
+ const next = skipField(buf, pos, wireType)
197
+ if (next === undefined) break
198
+ pos = next
199
+ }
200
+ return result
201
+ }
202
+
203
+ function decodeCtxWindow(
204
+ ctxWindow: Uint8Array,
205
+ ): ContextWindowMetadata | undefined {
206
+ let maxContextTokens: number | undefined
207
+ let estimatedTokensUsed: number | undefined
208
+ let pos = 0
209
+ while (pos < ctxWindow.length) {
210
+ const tag = readVarint(ctxWindow, pos)
211
+ if (tag === undefined) break
212
+ pos = tag.next
213
+ const fieldNumber = Number(tag.value >> 3n)
214
+ const wireType = Number(tag.value & 7n)
215
+ if (fieldNumber <= 0) break
216
+ if (wireType === 0 && (fieldNumber === 1 || fieldNumber === 4)) {
217
+ const val = readVarint(ctxWindow, pos)
218
+ if (val === undefined) break
219
+ pos = val.next
220
+ const num = Number(val.value)
221
+ if (val.value > 0n && Number.isSafeInteger(num)) {
222
+ if (fieldNumber === 1) estimatedTokensUsed = num
223
+ else maxContextTokens = num
224
+ }
225
+ continue
226
+ }
227
+ const next = skipField(ctxWindow, pos, wireType)
228
+ if (next === undefined) break
229
+ pos = next
230
+ }
231
+ if (maxContextTokens === undefined && estimatedTokensUsed === undefined)
232
+ return undefined
233
+ return {
234
+ ...(maxContextTokens !== undefined ? { maxContextTokens } : {}),
235
+ ...(estimatedTokensUsed !== undefined ? { estimatedTokensUsed } : {}),
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Decode context window telemetry from `gen_metadata.data` along protobuf wire path
241
+ * `1 (chatModel) -> 9 (chatStart) -> 10 (ctxWindow) -> {1: estimated_tokens_used, 4: max_context_tokens}`.
242
+ * @param blob - raw protobuf bytes from `gen_metadata.data`.
243
+ * @returns positive token counts, or `undefined` when absent or malformed.
244
+ */
245
+ export function extractContextWindowMetadata(
246
+ blob: Uint8Array,
247
+ ): ContextWindowMetadata | undefined {
248
+ if (!(blob instanceof Uint8Array) || blob.length === 0) return undefined
249
+ return scanMessage(blob, 1, 2, (chatModel) =>
250
+ scanMessage(chatModel, 9, 2, (chatStart) =>
251
+ scanMessage(chatStart, 10, 2, (ctxWindow) => decodeCtxWindow(ctxWindow)),
252
+ ),
253
+ )
254
+ }
255
+
256
+ function lstatOrMissing(path: string): Stats | 'missing' | 'invalid' {
257
+ try {
258
+ return lstatSync(path)
259
+ } catch (error) {
260
+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT'
261
+ ? 'missing'
262
+ : 'invalid'
263
+ }
264
+ }
265
+
266
+ function lstatBigIntOrMissing(
267
+ path: string,
268
+ ): BigIntStats | 'missing' | 'invalid' {
269
+ try {
270
+ return lstatSync(path, { bigint: true })
271
+ } catch (error) {
272
+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT'
273
+ ? 'missing'
274
+ : 'invalid'
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Validate a session's SQLite database path and sidecar files (`-wal`, `-shm`, `-journal`),
280
+ * rejecting symlinks, non-regular files, and escapes outside `home`, and returning a
281
+ * lightweight change stamp derived from the already-obtained `lstatSync` metadata.
282
+ */
283
+ export function resolveSessionDbPath(
284
+ home: string,
285
+ sessionId: string,
286
+ ): ResolvedSessionDb {
287
+ if (!isValidSessionId(sessionId)) return { kind: 'invalid' }
288
+ const appData = join(home, 'agy')
289
+ const appStat = lstatOrMissing(appData)
290
+ if (appStat === 'missing') return { kind: 'missing' }
291
+ if (
292
+ appStat === 'invalid' ||
293
+ appStat.isSymbolicLink() ||
294
+ !appStat.isDirectory()
295
+ )
296
+ return { kind: 'invalid' }
297
+
298
+ const convDir = join(appData, 'conversations')
299
+ const convStat = lstatOrMissing(convDir)
300
+ if (convStat === 'missing') return { kind: 'missing' }
301
+ if (
302
+ convStat === 'invalid' ||
303
+ convStat.isSymbolicLink() ||
304
+ !convStat.isDirectory()
305
+ )
306
+ return { kind: 'invalid' }
307
+
308
+ let realHome: string
309
+ let realConvDir: string
310
+ try {
311
+ realHome = realpathSync(home)
312
+ realConvDir = realpathSync(convDir)
313
+ } catch {
314
+ return { kind: 'invalid' }
315
+ }
316
+ const rel = relative(realHome, realConvDir)
317
+ if (rel.startsWith('..') || isAbsolute(rel)) return { kind: 'invalid' }
318
+
319
+ const dbPath = join(convDir, `${sessionId}.db`)
320
+ const dbStat = lstatBigIntOrMissing(dbPath)
321
+ if (dbStat === 'missing') return { kind: 'missing' }
322
+ if (dbStat === 'invalid' || dbStat.isSymbolicLink() || !dbStat.isFile())
323
+ return { kind: 'invalid' }
324
+
325
+ let walStat: BigIntStats | undefined
326
+ let journalStat: BigIntStats | undefined
327
+ // Reject symlinked or non-regular SQLite sidecar files before opening.
328
+ for (const suffix of ['-wal', '-shm', '-journal'] as const) {
329
+ const sidecarStat = lstatBigIntOrMissing(`${dbPath}${suffix}`)
330
+ if (sidecarStat === 'missing') continue
331
+ if (
332
+ sidecarStat === 'invalid' ||
333
+ sidecarStat.isSymbolicLink() ||
334
+ !sidecarStat.isFile()
335
+ ) {
336
+ return { kind: 'invalid' }
337
+ }
338
+ if (suffix === '-wal') walStat = sidecarStat
339
+ else if (suffix === '-journal') journalStat = sidecarStat
340
+ }
341
+
342
+ const stamp = `${dbStat.mtimeNs}:${dbStat.size}|${walStat?.mtimeNs ?? 0n}:${walStat?.size ?? 0n}|${journalStat?.mtimeNs ?? 0n}:${journalStat?.size ?? 0n}`
343
+ return { kind: 'ok', dbPath, stamp }
344
+ }
345
+
346
+ const DURATION_FULL_RE =
347
+ /^(?:(?:\d+(?:\.\d*)?|\.\d+)(?:ns|[\u00b5\u03bc]s|ms|s|m|h))+$/
348
+ const DURATION_PART_RE = /(\d+(?:\.\d*)?|\.\d+)(ns|[\u00b5\u03bc]s|ms|s|m|h)/g
349
+
350
+ const DURATION_UNIT_SECONDS: Record<string, number> = {
351
+ h: 3600,
352
+ m: 60,
353
+ s: 1,
354
+ ms: 1e-3,
355
+ '\u00b5s': 1e-6,
356
+ '\u03bcs': 1e-6,
357
+ ns: 1e-9,
358
+ }
359
+
360
+ /**
361
+ * Parse a Go-style composite duration string (e.g. `32m51.529394773s`, `500ms`,
362
+ * `250µs`, `250μs`, `1000ns`) into seconds, or `undefined` when malformed.
363
+ */
364
+ export function parseDurationSeconds(raw: string): number | undefined {
365
+ if (typeof raw !== 'string') return undefined
366
+ const trimmed = raw.trim()
367
+ if (trimmed.length === 0 || !DURATION_FULL_RE.test(trimmed)) return undefined
368
+ let total = 0
369
+ for (const match of trimmed.matchAll(DURATION_PART_RE)) {
370
+ const amount = Number(match[1])
371
+ const unit = DURATION_UNIT_SECONDS[match[2] as string]
372
+ if (!Number.isFinite(amount) || unit === undefined) return undefined
373
+ total += amount * unit
374
+ }
375
+ return Number.isFinite(total) ? total : undefined
376
+ }
377
+
378
+ function extractPayloadField(
379
+ payload: string,
380
+ field: string,
381
+ ): string | undefined {
382
+ const jsonMatch = new RegExp(`"${field}"\\s*:\\s*"([^"]+)"`).exec(payload)
383
+ if (jsonMatch?.[1] !== undefined) return jsonMatch[1]
384
+ const protoQuoted = new RegExp(`\\b${field}\\s*:\\s*"([^"]+)"`).exec(payload)
385
+ if (protoQuoted?.[1] !== undefined) return protoQuoted[1]
386
+ const protoBare = new RegExp(`\\b${field}\\s*:\\s*([^\\s,}"]+)`).exec(payload)
387
+ if (protoBare?.[1] !== undefined) return protoBare[1]
388
+ return undefined
389
+ }
390
+
391
+ const QUOTA_EXHAUSTED_RE =
392
+ /(?:"reason"\s*:\s*"QUOTA_EXHAUSTED"|\breason:QUOTA_EXHAUSTED\b)/
393
+ const INVALID_THINKING_SIG_RE =
394
+ /\bmessages\.\d+\.content\.\d+(?:\.thinking\.signature: Field required|: Invalid `signature` in `thinking` block)/
395
+ const RATE_LIMIT_RE =
396
+ /(?:HTTP\s+429|\(code\s+429\)|"code"\s*:\s*429|\bRESOURCE_EXHAUSTED\b)/
397
+ const NOT_FOUND_RE =
398
+ /(?:HTTP\s+404|\(code\s+404\)|"code"\s*:\s*404|\bNOT_FOUND\b)/
399
+
400
+ /**
401
+ * Classify a terminal `steps` error payload (`step_type = 17`) into a structured
402
+ * error for the runtime, or `undefined` for unclassified/transient payloads.
403
+ */
404
+ export function classifyStepErrorPayload(
405
+ payload: string,
406
+ reachedModel: boolean,
407
+ ): HiddenTurnError | undefined {
408
+ if (typeof payload !== 'string' || payload.length === 0) return undefined
409
+
410
+ if (QUOTA_EXHAUSTED_RE.test(payload)) {
411
+ const resetTimestamp = extractPayloadField(payload, 'quotaResetTimeStamp')
412
+ const rawDelay =
413
+ extractPayloadField(payload, 'quotaResetDelay') ??
414
+ extractPayloadField(payload, 'retryDelay')
415
+ const parsedDelay =
416
+ rawDelay !== undefined ? parseDurationSeconds(rawDelay) : undefined
417
+ const retryAfterSeconds =
418
+ parsedDelay !== undefined && parsedDelay > 0 ? parsedDelay : undefined
419
+ const details: string[] = []
420
+ if (resetTimestamp !== undefined)
421
+ details.push(`resets at ${resetTimestamp}`)
422
+ if (rawDelay !== undefined && retryAfterSeconds !== undefined)
423
+ details.push(`retry in ${rawDelay}`)
424
+ const suffix = details.length > 0 ? ` (${details.join(', ')})` : ''
425
+ return {
426
+ kind: 'quota',
427
+ code: 'QUOTA',
428
+ message: `Antigravity quota exceeded${suffix}`,
429
+ ...(resetTimestamp !== undefined ? { resetTimestamp } : {}),
430
+ ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
431
+ }
432
+ }
433
+
434
+ if (INVALID_THINKING_SIG_RE.test(payload)) {
435
+ return {
436
+ kind: 'invalid_thinking_signature',
437
+ code: 'PROVIDER_ERROR',
438
+ dirtySession: true,
439
+ message:
440
+ 'Antigravity rejected an invalid thinking signature; rebuilding session on the next turn',
441
+ }
442
+ }
443
+
444
+ if (RATE_LIMIT_RE.test(payload)) {
445
+ const rawDelay = extractPayloadField(payload, 'retryDelay')
446
+ const parsedDelay =
447
+ rawDelay !== undefined ? parseDurationSeconds(rawDelay) : undefined
448
+ const retryAfterSeconds =
449
+ parsedDelay !== undefined && parsedDelay > 0 ? parsedDelay : undefined
450
+ const suffix =
451
+ rawDelay !== undefined && retryAfterSeconds !== undefined
452
+ ? ` (retry in ${rawDelay})`
453
+ : ''
454
+ return {
455
+ kind: 'rate_limit',
456
+ code: 'RATE_LIMIT',
457
+ message: `Antigravity rate limit exceeded (429 RESOURCE_EXHAUSTED)${suffix}`,
458
+ ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
459
+ }
460
+ }
461
+
462
+ if (NOT_FOUND_RE.test(payload)) {
463
+ if (reachedModel) {
464
+ return {
465
+ kind: 'transient_not_found',
466
+ code: 'SERVER',
467
+ message:
468
+ 'Antigravity upstream stream returned 404 after reaching the model',
469
+ }
470
+ }
471
+ return {
472
+ kind: 'model_not_found',
473
+ code: 'UNKNOWN_MODEL',
474
+ message: 'Antigravity model is unavailable (404 NOT_FOUND)',
475
+ }
476
+ }
477
+
478
+ return undefined
479
+ }
480
+
481
+ function presentTables(db: DatabaseSync): Set<string> {
482
+ const rows = db
483
+ .prepare(
484
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('gen_metadata', 'steps')",
485
+ )
486
+ .all() as Array<{ name?: unknown }>
487
+ const tables = new Set<string>()
488
+ for (const row of rows) {
489
+ if (typeof row.name === 'string') tables.add(row.name)
490
+ }
491
+ return tables
492
+ }
493
+
494
+ /**
495
+ * Read both `gen_metadata` (`MAX(idx) + 1`, or `0`) and `steps` (`MAX(idx)`, or `-1`)
496
+ * cursors in a single read-only SQLite open before starting a prompt segment.
497
+ * Returns `null` when the session database path is invalid, symlinked, corrupt, or unreadable.
498
+ */
499
+ export function readSessionCursors(
500
+ home: string,
501
+ sessionId: string,
502
+ ): SessionCursors | null {
503
+ const resolved = resolveSessionDbPath(home, sessionId)
504
+ if (resolved.kind === 'missing') return { nextMetaIdx: 0, lastStepIdx: -1 }
505
+ if (resolved.kind === 'invalid') return null
506
+ let db: DatabaseSync | undefined
507
+ try {
508
+ db = new DatabaseSync(resolved.dbPath, { readOnly: true, timeout: 50 })
509
+ const tables = presentTables(db)
510
+ let nextMetaIdx = 0
511
+ if (tables.has('gen_metadata')) {
512
+ const row = db
513
+ .prepare('SELECT MAX(idx) AS maxIdx FROM gen_metadata')
514
+ .get() as { maxIdx?: unknown } | undefined
515
+ if (row?.maxIdx !== null && row?.maxIdx !== undefined) {
516
+ if (typeof row.maxIdx !== 'number' || !Number.isSafeInteger(row.maxIdx))
517
+ return null
518
+ const next = row.maxIdx + 1
519
+ if (!Number.isSafeInteger(next)) return null
520
+ nextMetaIdx = Math.max(0, next)
521
+ }
522
+ }
523
+ let lastStepIdx = -1
524
+ if (tables.has('steps')) {
525
+ const row = db
526
+ .prepare('SELECT MAX(idx) AS maxIdx FROM steps')
527
+ .get() as { maxIdx?: unknown } | undefined
528
+ if (row?.maxIdx !== null && row?.maxIdx !== undefined) {
529
+ if (typeof row.maxIdx !== 'number' || !Number.isSafeInteger(row.maxIdx))
530
+ return null
531
+ lastStepIdx = row.maxIdx
532
+ }
533
+ }
534
+ return { nextMetaIdx, lastStepIdx }
535
+ } catch {
536
+ return null
537
+ } finally {
538
+ db?.close()
539
+ }
540
+ }
541
+
542
+ function validMetaFloor(value: number | null | undefined): number | null {
543
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
544
+ ? value
545
+ : null
546
+ }
547
+
548
+ /**
549
+ * Read bounded context-window metadata and (optionally) terminal hidden API errors
550
+ * from one session's SQLite database in a single read-only open.
551
+ * Skips opening SQLite completely when `ifChangedSince` matches the current file stamp.
552
+ * Strictly fail-closed: any SQLite error returns `undefined`.
553
+ */
554
+ export function readSessionTurnData(
555
+ home: string,
556
+ sessionId: string,
557
+ options: ReadSessionTurnDataOptions,
558
+ ): SessionTurnData | undefined {
559
+ const resolved = resolveSessionDbPath(home, sessionId)
560
+ if (resolved.kind !== 'ok') return undefined
561
+ if (
562
+ options.ifChangedSince !== undefined &&
563
+ options.ifChangedSince === resolved.stamp
564
+ ) {
565
+ return { unchanged: true, stamp: resolved.stamp }
566
+ }
567
+
568
+ const metaFloor = validMetaFloor(options.metaFloorIdx)
569
+ const turnFloor = validMetaFloor(options.turnMetaFloorIdx)
570
+ const stepCursor =
571
+ typeof options.lastStepIdx === 'number' &&
572
+ Number.isSafeInteger(options.lastStepIdx) &&
573
+ options.lastStepIdx >= -1
574
+ ? options.lastStepIdx
575
+ : null
576
+ const limit =
577
+ options.maxMetaRows === undefined
578
+ ? DEFAULT_MAX_META_ROWS
579
+ : Number.isSafeInteger(options.maxMetaRows) && options.maxMetaRows > 0
580
+ ? options.maxMetaRows
581
+ : 0
582
+
583
+ const needMax = metaFloor !== null && limit > 0
584
+ const needEst = turnFloor !== null && limit > 0
585
+ const needSteps = options.checkStepsError === true && stepCursor !== null
586
+ if (!needMax && !needEst && !needSteps) {
587
+ return { stamp: resolved.stamp }
588
+ }
589
+
590
+ let db: DatabaseSync | undefined
591
+ try {
592
+ db = new DatabaseSync(resolved.dbPath, { readOnly: true, timeout: 50 })
593
+ const tables = presentTables(db)
594
+
595
+ let maxContextTokens: number | undefined
596
+ let estimatedTokensUsed: number | undefined
597
+ if ((needMax || needEst) && tables.has('gen_metadata')) {
598
+ const minFloor =
599
+ needMax && needEst
600
+ ? Math.min(metaFloor, turnFloor)
601
+ : needMax
602
+ ? metaFloor
603
+ : (turnFloor as number)
604
+ const stmt = db.prepare(
605
+ 'SELECT idx, data FROM gen_metadata WHERE idx >= ? ORDER BY idx DESC LIMIT ?',
606
+ )
607
+ for (const row of stmt.iterate(minFloor, limit) as Iterable<{
608
+ idx?: unknown
609
+ data?: unknown
610
+ }>) {
611
+ if (typeof row.idx !== 'number' || !(row.data instanceof Uint8Array))
612
+ continue
613
+ const wantMaxHere =
614
+ needMax && maxContextTokens === undefined && row.idx >= metaFloor
615
+ const wantEstHere =
616
+ needEst &&
617
+ estimatedTokensUsed === undefined &&
618
+ row.idx >= (turnFloor as number)
619
+ if (!wantMaxHere && !wantEstHere) break
620
+ const meta = extractContextWindowMetadata(row.data)
621
+ if (meta === undefined) continue
622
+ if (wantMaxHere && meta.maxContextTokens !== undefined)
623
+ maxContextTokens = meta.maxContextTokens
624
+ if (wantEstHere && meta.estimatedTokensUsed !== undefined)
625
+ estimatedTokensUsed = meta.estimatedTokensUsed
626
+ if (
627
+ (!needMax || maxContextTokens !== undefined) &&
628
+ (!needEst || estimatedTokensUsed !== undefined)
629
+ ) {
630
+ break
631
+ }
632
+ }
633
+ }
634
+
635
+ let hiddenError: HiddenTurnError | undefined
636
+ if (needSteps && tables.has('steps')) {
637
+ const latest = db
638
+ .prepare(
639
+ 'SELECT step_type AS type, substr(step_payload, 1, 16384) AS payload FROM steps WHERE idx > ? ORDER BY idx DESC LIMIT 1',
640
+ )
641
+ .get(stepCursor) as { type?: unknown; payload?: unknown } | undefined
642
+ if (latest?.type === 17) {
643
+ const reachedModel =
644
+ db
645
+ .prepare(
646
+ 'SELECT 1 FROM steps WHERE idx > ? AND step_type = 15 LIMIT 1',
647
+ )
648
+ .get(stepCursor) !== undefined
649
+ const text =
650
+ latest.payload instanceof Uint8Array
651
+ ? Buffer.from(latest.payload).toString('utf8')
652
+ : typeof latest.payload === 'string'
653
+ ? latest.payload
654
+ : ''
655
+ hiddenError = classifyStepErrorPayload(text, reachedModel)
656
+ }
657
+ }
658
+
659
+ return {
660
+ stamp: resolved.stamp,
661
+ ...(maxContextTokens !== undefined ? { maxContextTokens } : {}),
662
+ ...(estimatedTokensUsed !== undefined ? { estimatedTokensUsed } : {}),
663
+ ...(hiddenError !== undefined ? { hiddenError } : {}),
664
+ }
665
+ } catch {
666
+ return undefined
667
+ } finally {
668
+ db?.close()
669
+ }
670
+ }