pi-agy-acp 0.1.3 → 0.2.0

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/src/preflight.ts CHANGED
@@ -15,23 +15,22 @@ import {
15
15
  mkdirSync,
16
16
  writeFileSync,
17
17
  readFileSync,
18
+ realpathSync,
18
19
  statSync,
19
20
  lstatSync,
20
21
  readdirSync,
21
22
  rmSync,
23
+ type Stats,
22
24
  } from 'node:fs'
23
25
  import { homedir } from 'node:os'
24
- import { delimiter, isAbsolute, join } from 'node:path'
26
+ import { delimiter, isAbsolute, join, relative } from 'node:path'
27
+ import { DatabaseSync } from 'node:sqlite'
25
28
  import { readJson } from './config.ts'
26
29
 
27
30
  /** Agent id installed in the isolated home. */
28
31
  export const BRIDGE_AGENT = 'pi-bridge'
29
32
  /** Minimum official CLI version supporting `agy acp --process-per-session`. */
30
33
  export const MIN_AGY_VERSION: readonly [number, number, number] = [1, 4, 12]
31
- /** Default context window for the official CLI. */
32
- export const DEFAULT_CONTEXT_WINDOW = 256_000
33
- /** GPT-OSS 120B has its own 128K-class window. */
34
- export const GPT_OSS_CONTEXT_WINDOW = 131_072
35
34
 
36
35
  /** Output of one finished helper command. */
37
36
  export interface CommandOutput {
@@ -212,16 +211,246 @@ export function syncOAuthToken(
212
211
  }
213
212
  }
214
213
 
215
- /** Remove only one closed ACP session's files; session ids come from the agent. */
216
- export function removeSessionArtifacts(home: string, sessionId: string): void {
214
+ const EMPTY_BYTES = new Uint8Array(0)
215
+ const MAX_VARINT_SHIFT = 63n
216
+
217
+ function isValidSessionId(sessionId: string): boolean {
218
+ return (
219
+ typeof sessionId === 'string' &&
220
+ sessionId.length > 0 &&
221
+ !/[^A-Za-z0-9._-]/.test(sessionId) &&
222
+ sessionId !== '.' &&
223
+ !sessionId.includes('..')
224
+ )
225
+ }
226
+
227
+ function readVarint(
228
+ buf: Uint8Array,
229
+ start: number,
230
+ ): { value: bigint; next: number } | undefined {
231
+ let value = 0n
232
+ let shift = 0n
233
+ let pos = start
234
+ while (pos < buf.length && shift <= MAX_VARINT_SHIFT) {
235
+ const byte = buf[pos++] as number
236
+ value |= BigInt(byte & 0x7f) << shift
237
+ if ((byte & 0x80) === 0) return { value, next: pos }
238
+ shift += 7n
239
+ }
240
+ return undefined
241
+ }
242
+
243
+ function skipField(
244
+ buf: Uint8Array,
245
+ pos: number,
246
+ wireType: number,
247
+ ): number | undefined {
248
+ if (wireType === 0) return readVarint(buf, pos)?.next
249
+ if (wireType === 1) return pos + 8 <= buf.length ? pos + 8 : undefined
250
+ if (wireType === 2) {
251
+ const len = readVarint(buf, pos)
252
+ if (len === undefined) return undefined
253
+ const byteLen = Number(len.value)
254
+ if (!Number.isSafeInteger(byteLen) || byteLen < 0) return undefined
255
+ const end = len.next + byteLen
256
+ return end <= buf.length ? end : undefined
257
+ }
258
+ if (wireType === 5) return pos + 4 <= buf.length ? pos + 4 : undefined
259
+ return undefined
260
+ }
261
+
262
+ function scanMessage<T>(
263
+ buf: Uint8Array,
264
+ targetField: number,
265
+ expectedWireType: 0 | 2,
266
+ onMatch: (payload: Uint8Array, varint: bigint) => T | undefined,
267
+ ): T | undefined {
268
+ let pos = 0
269
+ let result: T | undefined
270
+ while (pos < buf.length) {
271
+ const tag = readVarint(buf, pos)
272
+ if (tag === undefined) break
273
+ pos = tag.next
274
+ const fieldNumber = Number(tag.value >> 3n)
275
+ const wireType = Number(tag.value & 7n)
276
+ if (fieldNumber <= 0) break
277
+ if (fieldNumber === targetField && wireType === expectedWireType) {
278
+ if (wireType === 0) {
279
+ const val = readVarint(buf, pos)
280
+ if (val === undefined) break
281
+ pos = val.next
282
+ const matched = onMatch(EMPTY_BYTES, val.value)
283
+ if (matched !== undefined) result = matched
284
+ continue
285
+ }
286
+ const len = readVarint(buf, pos)
287
+ if (len === undefined) break
288
+ const byteLen = Number(len.value)
289
+ if (!Number.isSafeInteger(byteLen) || byteLen < 0) break
290
+ const end = len.next + byteLen
291
+ if (end > buf.length) break
292
+ const matched = onMatch(buf.subarray(len.next, end), 0n)
293
+ if (matched !== undefined) result = matched
294
+ pos = end
295
+ continue
296
+ }
297
+ const next = skipField(buf, pos, wireType)
298
+ if (next === undefined) break
299
+ pos = next
300
+ }
301
+ return result
302
+ }
303
+
304
+ /**
305
+ * Decode `max_context_tokens` from `gen_metadata.data` along protobuf wire path
306
+ * `1 (bytes) -> 9 (bytes) -> 10 (bytes) -> 4 (varint)`.
307
+ * @param blob - raw protobuf bytes from `gen_metadata.data`.
308
+ * @returns positive token count, or `undefined` when absent or malformed.
309
+ */
310
+ export function extractMaxContextTokens(blob: Uint8Array): number | undefined {
311
+ if (!(blob instanceof Uint8Array) || blob.length === 0) return undefined
312
+ return scanMessage(blob, 1, 2, (chatModel) =>
313
+ scanMessage(chatModel, 9, 2, (chatStart) =>
314
+ scanMessage(chatStart, 10, 2, (ctxWindow) =>
315
+ scanMessage(ctxWindow, 4, 0, (_empty, value) => {
316
+ const num = Number(value)
317
+ return value > 0n && Number.isSafeInteger(num) ? num : undefined
318
+ }),
319
+ ),
320
+ ),
321
+ )
322
+ }
323
+
324
+ function lstatOrMissing(path: string): Stats | 'missing' | 'invalid' {
325
+ try {
326
+ return lstatSync(path)
327
+ } catch (error) {
328
+ return (error as NodeJS.ErrnoException)?.code === 'ENOENT'
329
+ ? 'missing'
330
+ : 'invalid'
331
+ }
332
+ }
333
+
334
+ function resolveSessionDbPath(
335
+ home: string,
336
+ sessionId: string,
337
+ ): { kind: 'ok'; dbPath: string } | { kind: 'missing' } | { kind: 'invalid' } {
338
+ if (!isValidSessionId(sessionId)) return { kind: 'invalid' }
339
+ const appData = join(home, 'agy')
340
+ const appStat = lstatOrMissing(appData)
341
+ if (appStat === 'missing') return { kind: 'missing' }
342
+ if (
343
+ appStat === 'invalid' ||
344
+ appStat.isSymbolicLink() ||
345
+ !appStat.isDirectory()
346
+ )
347
+ return { kind: 'invalid' }
348
+
349
+ const convDir = join(appData, 'conversations')
350
+ const convStat = lstatOrMissing(convDir)
351
+ if (convStat === 'missing') return { kind: 'missing' }
217
352
  if (
218
- typeof sessionId !== 'string' ||
219
- sessionId.length === 0 ||
220
- /[^A-Za-z0-9._-]/.test(sessionId) ||
221
- sessionId === '.' ||
222
- sessionId.includes('..')
353
+ convStat === 'invalid' ||
354
+ convStat.isSymbolicLink() ||
355
+ !convStat.isDirectory()
223
356
  )
224
- return
357
+ return { kind: 'invalid' }
358
+
359
+ let realHome: string
360
+ let realConvDir: string
361
+ try {
362
+ realHome = realpathSync(home)
363
+ realConvDir = realpathSync(convDir)
364
+ } catch {
365
+ return { kind: 'invalid' }
366
+ }
367
+ const rel = relative(realHome, realConvDir)
368
+ if (rel.startsWith('..') || isAbsolute(rel)) return { kind: 'invalid' }
369
+
370
+ const dbPath = join(convDir, `${sessionId}.db`)
371
+ const dbStat = lstatOrMissing(dbPath)
372
+ if (dbStat === 'missing') return { kind: 'missing' }
373
+ if (dbStat === 'invalid' || dbStat.isSymbolicLink() || !dbStat.isFile())
374
+ return { kind: 'invalid' }
375
+
376
+ return { kind: 'ok', dbPath }
377
+ }
378
+
379
+ /**
380
+ * Read server-issued `max_context_tokens` from one ACP session's SQLite database.
381
+ * @param home - isolated `--gemini-dir` root.
382
+ * @param sessionId - ACP session id.
383
+ * @param minIdx - lowest `gen_metadata.idx` owned by the current model.
384
+ * @returns positive `max_context_tokens`, or `undefined` when unavailable.
385
+ */
386
+ export function readSessionMaxContextTokens(
387
+ home: string,
388
+ sessionId: string,
389
+ minIdx = 0,
390
+ ): number | undefined {
391
+ if (typeof minIdx !== 'number' || !Number.isSafeInteger(minIdx) || minIdx < 0)
392
+ return undefined
393
+ const resolved = resolveSessionDbPath(home, sessionId)
394
+ if (resolved.kind !== 'ok') return undefined
395
+ let db: DatabaseSync | undefined
396
+ try {
397
+ db = new DatabaseSync(resolved.dbPath, { readOnly: true, timeout: 50 })
398
+ const stmt = db.prepare(
399
+ 'SELECT data FROM gen_metadata WHERE idx >= ? ORDER BY idx DESC',
400
+ )
401
+ for (const row of stmt.iterate(minIdx) as Iterable<{ data?: unknown }>) {
402
+ if (!(row.data instanceof Uint8Array)) continue
403
+ const tokens = extractMaxContextTokens(row.data)
404
+ if (tokens !== undefined) return tokens
405
+ }
406
+ return undefined
407
+ } catch {
408
+ return undefined
409
+ } finally {
410
+ db?.close()
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Compute the next `gen_metadata.idx` floor (`MAX(idx) + 1`, or `0` when no rows exist)
416
+ * before switching models inside a reused ACP session. Returns `null` when the
417
+ * session database path is invalid, symlinked, corrupt, or unreadable (fail-closed).
418
+ */
419
+ export function readSessionNextMetadataIndex(
420
+ home: string,
421
+ sessionId: string,
422
+ ): number | null {
423
+ const resolved = resolveSessionDbPath(home, sessionId)
424
+ if (resolved.kind === 'missing') return 0
425
+ if (resolved.kind === 'invalid') return null
426
+ let db: DatabaseSync | undefined
427
+ try {
428
+ db = new DatabaseSync(resolved.dbPath, { readOnly: true, timeout: 50 })
429
+ const hasTable = db
430
+ .prepare(
431
+ "SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'gen_metadata'",
432
+ )
433
+ .get()
434
+ if (hasTable === undefined) return 0
435
+ const row = db
436
+ .prepare('SELECT MAX(idx) AS maxIdx FROM gen_metadata')
437
+ .get() as { maxIdx?: unknown } | undefined
438
+ if (row?.maxIdx === null || row?.maxIdx === undefined) return 0
439
+ if (typeof row.maxIdx === 'number' && Number.isSafeInteger(row.maxIdx)) {
440
+ const next = row.maxIdx + 1
441
+ return Number.isSafeInteger(next) ? Math.max(0, next) : null
442
+ }
443
+ return null
444
+ } catch {
445
+ return null
446
+ } finally {
447
+ db?.close()
448
+ }
449
+ }
450
+
451
+ /** Remove only one closed ACP session's files; session ids come from the agent. */
452
+ export function removeSessionArtifacts(home: string, sessionId: string): void {
453
+ if (!isValidSessionId(sessionId)) return
225
454
  const appData = join(home, 'agy')
226
455
  if (!isRealDirectory(appData)) return
227
456
  removeArtifacts(join(appData, 'conversations'), [
package/src/runtime.ts CHANGED
@@ -66,9 +66,9 @@ import {
66
66
  assertSupportedAgyVersion,
67
67
  BRIDGE_AGENT,
68
68
  defaultHome,
69
- GPT_OSS_CONTEXT_WINDOW,
70
- DEFAULT_CONTEXT_WINDOW,
71
69
  prepareHome,
70
+ readSessionMaxContextTokens,
71
+ readSessionNextMetadataIndex,
72
72
  removeSessionArtifacts,
73
73
  readVersion,
74
74
  resolveAgyBinary,
@@ -108,13 +108,14 @@ export interface RuntimeStatus {
108
108
  version?: string
109
109
  home: string
110
110
  account?: AccountInfo
111
- contextWindow: number
111
+ contextWindow?: number
112
112
  defaultEffort: Effort
113
113
  models: {
114
114
  id: string
115
115
  name: string
116
116
  efforts: readonly Effort[]
117
117
  fixedEffort?: Effort
118
+ contextWindow?: number
118
119
  }[]
119
120
  efforts: string[]
120
121
  liveSessions: number
@@ -154,6 +155,8 @@ interface Conversation {
154
155
  dirty: boolean
155
156
  lastUsed: number
156
157
  model: string | undefined
158
+ /** Lower `gen_metadata.idx` bound for `model`, or `null` when unobservable after a failed cursor read. */
159
+ metaFloorIdx: number | null
157
160
  effort: Effort | undefined
158
161
  }
159
162
 
@@ -214,9 +217,26 @@ export class AntigravityRuntime {
214
217
  }
215
218
 
216
219
  contextWindowFor(model: string): number {
217
- return model.startsWith('gpt-oss')
218
- ? GPT_OSS_CONTEXT_WINDOW
219
- : DEFAULT_CONTEXT_WINDOW
220
+ return this.catalog.contextWindowFor(model) ?? 0
221
+ }
222
+
223
+ private observeSessionContextWindow(
224
+ sessionId: string | undefined,
225
+ model: string | undefined,
226
+ minIdx: number | null,
227
+ ): void {
228
+ if (
229
+ this.lifecycle !== 'active' ||
230
+ !sessionId ||
231
+ !model ||
232
+ minIdx === null
233
+ ) {
234
+ return
235
+ }
236
+ const tokens = readSessionMaxContextTokens(this.home, sessionId, minIdx)
237
+ if (this.catalog.observeContextWindow(model, tokens)) {
238
+ this.host.onModelsChanged()
239
+ }
220
240
  }
221
241
 
222
242
  /**
@@ -234,9 +254,15 @@ export class AntigravityRuntime {
234
254
 
235
255
  /**
236
256
  * Current status for diagnostics surfaces.
257
+ * @param modelId - optional active provider model id.
237
258
  * @returns the status snapshot.
238
259
  */
239
- status(): RuntimeStatus {
260
+ status(modelId?: string): RuntimeStatus {
261
+ const targetModel = modelId ?? this.lastTurn?.model
262
+ const activeContextWindow =
263
+ targetModel !== undefined
264
+ ? this.catalog.contextWindowFor(targetModel)
265
+ : undefined
240
266
  return {
241
267
  state: this.state,
242
268
  ...(this.lastError !== undefined ? { error: this.lastError } : {}),
@@ -248,13 +274,19 @@ export class AntigravityRuntime {
248
274
  : {}),
249
275
  home: this.home,
250
276
  account: this.accountInfo(),
251
- contextWindow: DEFAULT_CONTEXT_WINDOW,
277
+ ...(activeContextWindow !== undefined
278
+ ? { contextWindow: activeContextWindow }
279
+ : {}),
252
280
  defaultEffort: this.host.config.defaultEffort,
253
- models: this.catalog.list().map((m) => ({
254
- ...m,
255
- efforts: this.catalog.effortsFor(m.id),
256
- fixedEffort: this.catalog.fixedEffort(m.id),
257
- })),
281
+ models: this.catalog.list().map((m) => {
282
+ const contextWindow = this.catalog.contextWindowFor(m.id)
283
+ return {
284
+ ...m,
285
+ efforts: this.catalog.effortsFor(m.id),
286
+ fixedEffort: this.catalog.fixedEffort(m.id),
287
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
288
+ }
289
+ }),
258
290
  efforts: [...this.catalog.effortList()],
259
291
  liveSessions: [...this.conversations.values()].filter(
260
292
  (c) => c.sessionId !== undefined,
@@ -521,16 +553,20 @@ export class AntigravityRuntime {
521
553
  const plan = this.plan(conv, split.system, split.messages)
522
554
  if (plan.rebuild) await this.resetSession(conv)
523
555
  this.assertOwner(proc, conv)
556
+ let supplementalTools: readonly BridgeTool[] = []
524
557
  if (conv.sessionId === undefined) {
525
558
  conv.systemHash = digest(split.system)
526
- await this.openSession(conv, split.system, tools, proc)
559
+ supplementalTools = await this.openSession(conv, tools, proc)
527
560
  }
528
561
  this.assertOwner(proc, conv, conv.sessionId)
529
562
  await this.select(conv, proc, options.model, effort)
530
563
  this.assertOwner(proc, conv, conv.sessionId)
531
564
  let blocks: AcpPromptBlock[]
532
565
  if (plan.rebuild) {
533
- blocks = replayPrompt(plan.history, plan.input)
566
+ blocks = replayPrompt(plan.history, plan.input, {
567
+ system: split.system,
568
+ supplementalTools,
569
+ })
534
570
  } else {
535
571
  blocks = inputPrompt(plan.input)
536
572
  const toolDelta = consumeToolDelta(conv, tools)
@@ -639,6 +675,7 @@ export class AntigravityRuntime {
639
675
  dirty: false,
640
676
  lastUsed: Date.now(),
641
677
  model: undefined,
678
+ metaFloorIdx: 0,
642
679
  effort: undefined,
643
680
  }
644
681
  this.conversations.set(key, conv)
@@ -746,10 +783,9 @@ export class AntigravityRuntime {
746
783
 
747
784
  private async openSession(
748
785
  conv: Conversation,
749
- system: string,
750
786
  tools: readonly BridgeTool[],
751
787
  proc: AcpProcess,
752
- ): Promise<void> {
788
+ ): Promise<readonly BridgeTool[]> {
753
789
  this.assertOwner(proc, conv)
754
790
  syncOAuthToken(this.home)
755
791
  conv.reportedToolCalls.clear()
@@ -781,7 +817,7 @@ export class AntigravityRuntime {
781
817
  _meta: {
782
818
  antigravity: {
783
819
  systemPrompt: {
784
- append: bridgeSystemPrompt(system, supplementalTools),
820
+ append: bridgeSystemPrompt(),
785
821
  },
786
822
  },
787
823
  },
@@ -800,6 +836,13 @@ export class AntigravityRuntime {
800
836
  if (this.catalog.observe(update.configOptions))
801
837
  this.host.onModelsChanged()
802
838
  }
839
+ if (update.sessionUpdate === 'usage_update') {
840
+ this.observeSessionContextWindow(
841
+ conv.sessionId,
842
+ conv.model,
843
+ conv.metaFloorIdx,
844
+ )
845
+ }
803
846
  if (recordReportedToolCall(conv, update) === 'conflict') {
804
847
  this.host.log.warn(
805
848
  `antigravity-acp: agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
@@ -823,6 +866,7 @@ export class AntigravityRuntime {
823
866
  conv.process = proc
824
867
  conv.configOptions = result.configOptions ?? []
825
868
  conv.model = undefined
869
+ conv.metaFloorIdx = 0
826
870
  conv.effort = undefined
827
871
 
828
872
  conv.dirty = false
@@ -835,6 +879,7 @@ export class AntigravityRuntime {
835
879
  )
836
880
  )
837
881
  this.host.onModelsChanged()
882
+ return supplementalTools
838
883
  } catch (error) {
839
884
  this.clearSession(conv)
840
885
  throw mapError(error)
@@ -883,7 +928,7 @@ export class AntigravityRuntime {
883
928
  }
884
929
  const reject = (reason: string): AcpPermissionOutcome => {
885
930
  this.host.log.warn(
886
- `antigravity-acp: refused permission request (${reason}): ${request.toolCall?.title ?? 'unknown'}`,
931
+ `antigravity-acp: refused permission request (${reason}): ${request.toolCall?.title || request.toolCall?.name || 'unknown'}`,
887
932
  )
888
933
  return pick('reject_once') ?? { outcome: 'cancelled' }
889
934
  }
@@ -898,6 +943,9 @@ export class AntigravityRuntime {
898
943
  return reject('missing toolCallId')
899
944
  const reported = conv.reportedToolCalls.get(toolCallId)
900
945
  const claimed = structuredToolMeta(request.toolCall)
946
+ if (claimed.conflict === true) {
947
+ return reject('conflicting tool metadata in permission request')
948
+ }
901
949
  if (reported === undefined) {
902
950
  // Nothing the agent reported in `session/update` backs this call: its own
903
951
  // in-request metadata is untrusted (stale or cross-session toolCallId).
@@ -969,6 +1017,12 @@ export class AntigravityRuntime {
969
1017
  'UNKNOWN_MODEL',
970
1018
  )
971
1019
  }
1020
+ const previousModel = conv.model
1021
+ const previousFloor = conv.metaFloorIdx
1022
+ if (previousModel !== undefined && previousModel !== model) {
1023
+ this.observeSessionContextWindow(sessionId, previousModel, previousFloor)
1024
+ conv.metaFloorIdx = null
1025
+ }
972
1026
  if (conv.model !== model && modelOption?.currentValue !== model) {
973
1027
  await this.applyConfigOption(
974
1028
  conv,
@@ -978,6 +1032,13 @@ export class AntigravityRuntime {
978
1032
  model,
979
1033
  )
980
1034
  }
1035
+ if (previousModel !== undefined && previousModel !== model) {
1036
+ const nextIdx = readSessionNextMetadataIndex(this.home, sessionId)
1037
+ conv.metaFloorIdx =
1038
+ previousFloor === null || nextIdx === null
1039
+ ? null
1040
+ : Math.max(previousFloor, nextIdx)
1041
+ }
981
1042
  conv.model = model
982
1043
  const levelOption = conv.configOptions.find(
983
1044
  (o) => o.id === 'thought_level' || o.category === 'thought_level',
@@ -1100,6 +1161,7 @@ export class AntigravityRuntime {
1100
1161
  }
1101
1162
 
1102
1163
  private async resetSession(conv: Conversation): Promise<void> {
1164
+ this.observeSessionContextWindow(conv.sessionId, conv.model, conv.metaFloorIdx)
1103
1165
  let closing: Promise<void> | undefined
1104
1166
  if (conv.sessionId !== undefined && conv.process !== undefined) {
1105
1167
  closing = this.closeAndCleanSession(conv.process, conv.sessionId)
@@ -1116,6 +1178,7 @@ export class AntigravityRuntime {
1116
1178
  conv.tenantKey = undefined
1117
1179
  conv.tenantSecret = undefined
1118
1180
  conv.process = undefined
1181
+ conv.metaFloorIdx = null
1119
1182
  conv.advertisedTools = []
1120
1183
  conv.advertisedToolDigests.clear()
1121
1184
  conv.knownTools.clear()
@@ -1149,6 +1212,7 @@ export class AntigravityRuntime {
1149
1212
  effort: Effort,
1150
1213
  ): AsyncGenerator<StreamChunk> {
1151
1214
  const sessionId = conv.sessionId as string
1215
+ const metaFloorIdx = conv.metaFloorIdx
1152
1216
  let finishKind: string | undefined
1153
1217
  let drained = false
1154
1218
  const cancel = () => {
@@ -1201,18 +1265,23 @@ export class AntigravityRuntime {
1201
1265
  const chunk = turn.guard(emitted, signal) as StreamChunk
1202
1266
  if (chunk.type === 'block-end' && chunk.block.type === 'tool-call')
1203
1267
  conv.issuedIds.add(chunk.block.id)
1204
- if (chunk.type === 'finish') finishKind = chunk.reason.kind
1268
+ if (chunk.type === 'finish') {
1269
+ finishKind = chunk.reason.kind
1270
+ this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1271
+ }
1205
1272
  yield chunk
1206
1273
  if (chunk.type === 'finish' && chunk.reason.kind === 'aborted') break
1207
1274
  }
1208
1275
  const interrupted = turn.guard(undefined, signal)
1209
1276
  if (interrupted !== undefined && finishKind !== 'aborted') {
1210
1277
  finishKind = 'aborted'
1278
+ this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1211
1279
  yield interrupted
1212
1280
  }
1213
1281
  drained = true
1214
1282
  } catch (error) {
1215
1283
  finishKind = 'error'
1284
+ this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1216
1285
  throw mapError(error)
1217
1286
  } finally {
1218
1287
  // Only a fully consumed tool handoff keeps the turn and its cancellation owner.