pi-agy-acp 0.1.4 → 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/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.0](https://github.com/fdkevin0/pi-agy-acp/compare/v0.1.4...v0.2.0) (2026-11-17)
4
+
5
+
6
+ ### Features
7
+
8
+ * discover model context windows dynamically from session metadata ([#29](https://github.com/fdkevin0/pi-agy-acp/issues/29)) ([c29277f](https://github.com/fdkevin0/pi-agy-acp/commit/c29277ff3e8c64b9549444b14177bcfd283ef50a))
9
+
3
10
  ## [0.1.4](https://github.com/fdkevin0/pi-agy-acp/compare/v0.1.3...v0.1.4) (2026-11-15)
4
11
 
5
12
 
package/docs/reference.md CHANGED
@@ -145,15 +145,19 @@ The fallback families are:
145
145
  - `claude-sonnet-5-5`
146
146
  - `gpt-oss-120b-medium`
147
147
 
148
- These entries are defaults, not a guarantee of account access. Context declarations
149
- are 256,000 tokens, or 131,072 for GPT-OSS. The history replay budget is 160,000 bytes;
150
- older history can be omitted to fit, and historical images become text placeholders.
148
+ These entries are defaults, not a guarantee of account access. Model context windows
149
+ start at `0` until learned dynamically from the server-issued `max_context_tokens`
150
+ metadata in the session database and cached per model in `catalog.json`. The history
151
+ replay budget is 160,000 bytes; older history can be omitted to fit, and historical
152
+ images become text placeholders.
151
153
 
152
154
  ## Usage and costs
153
155
 
154
156
  Usage comes from the ACP session rather than per-step API headers. Parked `toolUse`
155
157
  steps emit zero usage; statistics arrive on the final step when the full ACP turn
156
- finishes (accumulated across any automatic `max_tokens` continuations).
158
+ finishes (accumulated across any automatic `max_tokens` continuations). `max_context_tokens`
159
+ recorded in the session SQLite metadata supplies the model's context window, while
160
+ `usage_update` supplies live token occupancy.
157
161
 
158
162
  The extension separates cumulative token consumption from final-call context
159
163
  occupancy:
@@ -174,8 +178,9 @@ buckets accurately; tiered `inputTokensAbove` rules evaluate against cumulative
174
178
  turn prompt tokens rather than per-call prompt sizes. These estimates are not
175
179
  an invoice amount or a promise of free access.
176
180
 
177
- The extension does not inspect agy's private databases or invoke or distribute
178
- binary patch scripts.
181
+ The extension reads only session-scoped `max_context_tokens` metadata inside `PI_AGY_HOME`;
182
+ it never inspects your global `agy` databases or invokes or distributes binary patch
183
+ scripts.
179
184
 
180
185
  ## Compatibility limits
181
186
 
package/index.ts CHANGED
@@ -172,6 +172,13 @@ export default function (
172
172
  pi.on('cache_warming_decision', (_event, ctx) =>
173
173
  ctx.model?.provider === config.provider ? { action: 'stop' } : undefined,
174
174
  )
175
+ pi.on('session_before_compact', (event, ctx) =>
176
+ ctx.model?.provider === config.provider &&
177
+ event.reason === 'threshold' &&
178
+ (ctx.model.contextWindow ?? 0) <= 0
179
+ ? { cancel: true }
180
+ : undefined,
181
+ )
175
182
  pi.on('model_select', (event, ctx) => {
176
183
  const retarget =
177
184
  pendingSettle &&
@@ -342,7 +349,13 @@ export default function (
342
349
  }
343
350
  const notice = snapshot
344
351
  ? formatQuota(snapshot, undefined, quotaDisplay)
345
- : formatStatus(runtime.status())
352
+ : formatStatus(
353
+ runtime.status(
354
+ ctx.model?.provider === config.provider
355
+ ? ctx.model.id
356
+ : undefined,
357
+ ),
358
+ )
346
359
  if (epoch === uiEpoch)
347
360
  updateStatus(ctx, snapshot ?? activeRuntime?.quota.peek())
348
361
  ctx.ui.notify(notice.text, notice.level)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-agy-acp",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Google Antigravity ACP provider extension for Pi Coding Agent",
package/src/catalog.ts CHANGED
@@ -64,6 +64,10 @@ export function nearestEffort(
64
64
  return best ?? wanted
65
65
  }
66
66
 
67
+ function isValidContextWindow(value: unknown): value is number {
68
+ return typeof value === 'number' && Number.isInteger(value) && value > 0
69
+ }
70
+
67
71
  /** Observed catalog with a disk cache. */
68
72
  export class ModelCatalog {
69
73
  private models: CatalogModel[]
@@ -71,6 +75,8 @@ export class ModelCatalog {
71
75
  private efforts: Effort[] = [...EFFORTS]
72
76
  /** Efforts per model family; an empty array marks a fixed-effort model. */
73
77
  private byModel = new Map<string, Effort[]>()
78
+ /** Server-reported `max_context_tokens` keyed by model id. */
79
+ private readonly contextWindows = new Map<string, number>()
74
80
  /** Latest `availableModels` snapshot, kept for later option updates. */
75
81
  private available: readonly AvailableModel[] | undefined
76
82
  /** Whether a live ACP session has reported the catalog. */
@@ -83,6 +89,38 @@ export class ModelCatalog {
83
89
  this.models = this.load() ?? [...FALLBACK_MODELS]
84
90
  }
85
91
 
92
+ /**
93
+ * Cached server-issued context window (`max_context_tokens`) for one model.
94
+ * @param modelId - family id.
95
+ * @returns positive token limit, or `undefined` when never observed.
96
+ */
97
+ contextWindowFor(modelId: string): number | undefined {
98
+ return this.contextWindows.get(modelId)
99
+ }
100
+
101
+ /**
102
+ * Persist one observed context window if it is valid and changed.
103
+ * @param modelId - family id.
104
+ * @param contextWindow - observed `max_context_tokens`.
105
+ * @returns whether the stored window changed.
106
+ */
107
+ observeContextWindow(
108
+ modelId: string,
109
+ contextWindow: number | undefined,
110
+ ): boolean {
111
+ if (
112
+ typeof modelId !== 'string' ||
113
+ modelId.length === 0 ||
114
+ !isValidContextWindow(contextWindow)
115
+ ) {
116
+ return false
117
+ }
118
+ if (this.contextWindows.get(modelId) === contextWindow) return false
119
+ this.contextWindows.set(modelId, contextWindow)
120
+ this.save()
121
+ return true
122
+ }
123
+
86
124
  /** Current families. */
87
125
  list(): readonly CatalogModel[] {
88
126
  return this.models
@@ -215,6 +253,7 @@ export class ModelCatalog {
215
253
  models: this.models,
216
254
  efforts: this.efforts,
217
255
  byModel: Object.fromEntries(this.byModel),
256
+ contextWindows: Object.fromEntries(this.contextWindows),
218
257
  tier: this.tierInfo,
219
258
  },
220
259
  null,
@@ -233,8 +272,10 @@ export class ModelCatalog {
233
272
  models?: CatalogModel[]
234
273
  efforts?: string[]
235
274
  byModel?: Record<string, string[]>
275
+ contextWindows?: Record<string, unknown>
236
276
  tier?: AcpTierInfo
237
- }
277
+ } | null
278
+ if (parsed === null || typeof parsed !== 'object') return undefined
238
279
  this.tierInfo = normalizeTier(parsed.tier)
239
280
  if (Array.isArray(parsed.efforts)) {
240
281
  const efforts = parsed.efforts.filter((v): v is Effort =>
@@ -251,6 +292,15 @@ export class ModelCatalog {
251
292
  this.byModel.set(id, efforts)
252
293
  }
253
294
  }
295
+ if (
296
+ parsed.contextWindows !== null &&
297
+ typeof parsed.contextWindows === 'object'
298
+ ) {
299
+ for (const [id, value] of Object.entries(parsed.contextWindows)) {
300
+ if (id.length > 0 && isValidContextWindow(value))
301
+ this.contextWindows.set(id, value)
302
+ }
303
+ }
254
304
  const models = Array.isArray(parsed.models)
255
305
  ? parsed.models.filter(
256
306
  (m) => typeof m?.id === 'string' && typeof m?.name === 'string',
package/src/format.ts CHANGED
@@ -447,7 +447,7 @@ export function formatStatus(status: RuntimeStatus): FormattedNotice {
447
447
  ` Home: ${status.home}`,
448
448
  ...(account ? [` Account: ${account}`] : []),
449
449
  ` Sessions: ${status.liveSessions} live · ${status.activeTurns} active turn(s)`,
450
- ` Context: ${Math.round(status.contextWindow / 1024)}K tokens · default effort: ${status.defaultEffort} (${status.efforts.join(', ')})`,
450
+ ` Context: ${status.contextWindow ? `${Math.round(status.contextWindow / 1024)}K tokens` : 'dynamic (unprobed)'} · default effort: ${status.defaultEffort} (${status.efforts.join(', ')})`,
451
451
  ' Models:',
452
452
  ]
453
453
  if (status.models.length === 0) lines.push(' No models available.')
@@ -458,7 +458,10 @@ export function formatStatus(status: RuntimeStatus): FormattedNotice {
458
458
  : model.fixedEffort
459
459
  ? `[${model.fixedEffort}] (fixed)`
460
460
  : 'no effort selector'
461
- lines.push(` ${model.id} (${model.name}) — ${efforts}`)
461
+ const ctx = model.contextWindow
462
+ ? ` · ${Math.round(model.contextWindow / 1024)}K`
463
+ : ''
464
+ lines.push(` ${model.id} (${model.name}) — ${efforts}${ctx}`)
462
465
  }
463
466
  if (status.lastTurn) {
464
467
  const turn = status.lastTurn
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,
@@ -643,6 +675,7 @@ export class AntigravityRuntime {
643
675
  dirty: false,
644
676
  lastUsed: Date.now(),
645
677
  model: undefined,
678
+ metaFloorIdx: 0,
646
679
  effort: undefined,
647
680
  }
648
681
  this.conversations.set(key, conv)
@@ -803,6 +836,13 @@ export class AntigravityRuntime {
803
836
  if (this.catalog.observe(update.configOptions))
804
837
  this.host.onModelsChanged()
805
838
  }
839
+ if (update.sessionUpdate === 'usage_update') {
840
+ this.observeSessionContextWindow(
841
+ conv.sessionId,
842
+ conv.model,
843
+ conv.metaFloorIdx,
844
+ )
845
+ }
806
846
  if (recordReportedToolCall(conv, update) === 'conflict') {
807
847
  this.host.log.warn(
808
848
  `antigravity-acp: agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
@@ -826,6 +866,7 @@ export class AntigravityRuntime {
826
866
  conv.process = proc
827
867
  conv.configOptions = result.configOptions ?? []
828
868
  conv.model = undefined
869
+ conv.metaFloorIdx = 0
829
870
  conv.effort = undefined
830
871
 
831
872
  conv.dirty = false
@@ -976,6 +1017,12 @@ export class AntigravityRuntime {
976
1017
  'UNKNOWN_MODEL',
977
1018
  )
978
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
+ }
979
1026
  if (conv.model !== model && modelOption?.currentValue !== model) {
980
1027
  await this.applyConfigOption(
981
1028
  conv,
@@ -985,6 +1032,13 @@ export class AntigravityRuntime {
985
1032
  model,
986
1033
  )
987
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
+ }
988
1042
  conv.model = model
989
1043
  const levelOption = conv.configOptions.find(
990
1044
  (o) => o.id === 'thought_level' || o.category === 'thought_level',
@@ -1107,6 +1161,7 @@ export class AntigravityRuntime {
1107
1161
  }
1108
1162
 
1109
1163
  private async resetSession(conv: Conversation): Promise<void> {
1164
+ this.observeSessionContextWindow(conv.sessionId, conv.model, conv.metaFloorIdx)
1110
1165
  let closing: Promise<void> | undefined
1111
1166
  if (conv.sessionId !== undefined && conv.process !== undefined) {
1112
1167
  closing = this.closeAndCleanSession(conv.process, conv.sessionId)
@@ -1123,6 +1178,7 @@ export class AntigravityRuntime {
1123
1178
  conv.tenantKey = undefined
1124
1179
  conv.tenantSecret = undefined
1125
1180
  conv.process = undefined
1181
+ conv.metaFloorIdx = null
1126
1182
  conv.advertisedTools = []
1127
1183
  conv.advertisedToolDigests.clear()
1128
1184
  conv.knownTools.clear()
@@ -1156,6 +1212,7 @@ export class AntigravityRuntime {
1156
1212
  effort: Effort,
1157
1213
  ): AsyncGenerator<StreamChunk> {
1158
1214
  const sessionId = conv.sessionId as string
1215
+ const metaFloorIdx = conv.metaFloorIdx
1159
1216
  let finishKind: string | undefined
1160
1217
  let drained = false
1161
1218
  const cancel = () => {
@@ -1208,18 +1265,23 @@ export class AntigravityRuntime {
1208
1265
  const chunk = turn.guard(emitted, signal) as StreamChunk
1209
1266
  if (chunk.type === 'block-end' && chunk.block.type === 'tool-call')
1210
1267
  conv.issuedIds.add(chunk.block.id)
1211
- 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
+ }
1212
1272
  yield chunk
1213
1273
  if (chunk.type === 'finish' && chunk.reason.kind === 'aborted') break
1214
1274
  }
1215
1275
  const interrupted = turn.guard(undefined, signal)
1216
1276
  if (interrupted !== undefined && finishKind !== 'aborted') {
1217
1277
  finishKind = 'aborted'
1278
+ this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1218
1279
  yield interrupted
1219
1280
  }
1220
1281
  drained = true
1221
1282
  } catch (error) {
1222
1283
  finishKind = 'error'
1284
+ this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1223
1285
  throw mapError(error)
1224
1286
  } finally {
1225
1287
  // Only a fully consumed tool handoff keeps the turn and its cancellation owner.