pi-agy-acp 0.2.0 → 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.
package/src/runtime.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import { randomBytes, timingSafeEqual } from 'node:crypto'
11
- import { homedir } from 'node:os'
11
+ import { statSync } from 'node:fs'
12
12
  import { join } from 'node:path'
13
13
  import { LlmError } from './protocol.ts'
14
14
  import type {
@@ -25,7 +25,11 @@ import {
25
25
  type AcpPromptResult,
26
26
  type AcpSpawner,
27
27
  } from './acp-process.ts'
28
- import { ModelCatalog, nearestEffort } from './catalog.ts'
28
+ import {
29
+ flattenConfigOptions,
30
+ ModelCatalog,
31
+ nearestEffort,
32
+ } from './catalog.ts'
29
33
  import { asEffort, defaults, type Config, type Effort } from './config.ts'
30
34
  import {
31
35
  AcpTurn,
@@ -33,8 +37,6 @@ import {
33
37
  AWAIT_TOOL_NAME,
34
38
  CALL_TOOL,
35
39
  pumpStep,
36
- relayNotice,
37
- type ParkedCall,
38
40
  type ReportedToolCall,
39
41
  structuredToolMeta,
40
42
  recordReportedToolCall,
@@ -64,18 +66,24 @@ import {
64
66
  } from './mcp-bridge.ts'
65
67
  import {
66
68
  assertSupportedAgyVersion,
69
+ binaryFingerprint,
67
70
  BRIDGE_AGENT,
71
+ defaultAgyHomes,
68
72
  defaultHome,
73
+ isDefaultPiAgyHome,
69
74
  prepareHome,
70
- readSessionMaxContextTokens,
71
- readSessionNextMetadataIndex,
72
- removeSessionArtifacts,
73
75
  readVersion,
74
76
  resolveAgyBinary,
75
77
  syncOAuthToken,
76
78
  type CommandRunner,
77
79
  type PreflightResult,
78
80
  } from './preflight.ts'
81
+ import {
82
+ readSessionCursors,
83
+ readSessionTurnData,
84
+ removeSessionArtifacts,
85
+ type HiddenTurnError,
86
+ } from './session-db.ts'
79
87
  import {
80
88
  QuotaReader,
81
89
  readLoggedEmail,
@@ -87,6 +95,8 @@ import { VERSION } from './version.ts'
87
95
 
88
96
  const CONTINUE_PROMPT =
89
97
  'Continue exactly where your previous output stopped. Do not repeat any earlier text.'
98
+ const SWEEP_INTERVAL_MS = 60_000
99
+ const EMAIL_CACHE_TTL_MS = 10_000
90
100
 
91
101
  /** Host services the runtime uses. */
92
102
  export interface RuntimeHost {
@@ -98,6 +108,10 @@ export interface RuntimeHost {
98
108
  onModelsChanged(): void
99
109
  /** Delay before a parked call answers with a still-running notice; overrides config.relayAfterMs (85 seconds). */
100
110
  relayAfterMs?: number
111
+ /** Monotonic clock in milliseconds for quota TTL checks; defaults to `performance.now()`. */
112
+ quotaNow?: () => number
113
+ /** Monotonic clock in milliseconds for idle-session sweeping, LRU ordering, and log-email cache TTL; defaults to `performance.now()`. */
114
+ monotonicNow?: () => number
101
115
  }
102
116
 
103
117
  /** Snapshot reported to the settings page and quota pill. */
@@ -154,9 +168,12 @@ interface Conversation {
154
168
  turn: AcpTurn | undefined
155
169
  dirty: boolean
156
170
  lastUsed: number
171
+ idleMs: number
157
172
  model: string | undefined
158
173
  /** Lower `gen_metadata.idx` bound for `model`, or `null` when unobservable after a failed cursor read. */
159
174
  metaFloorIdx: number | null
175
+ /** Last observed SQLite file/sidecar stamp used to skip unchanged reads during streaming. */
176
+ lastDbStamp?: string
160
177
  effort: Effort | undefined
161
178
  }
162
179
 
@@ -173,8 +190,10 @@ export class AntigravityRuntime {
173
190
  readonly quota: QuotaReader
174
191
  private readonly home: string
175
192
  private process: AcpProcess | undefined
193
+ private processFingerprint: string | undefined
176
194
  private starting: Promise<AcpProcess> | undefined
177
195
  private preflight: PreflightResult | undefined
196
+ private preflightFingerprint: string | undefined
178
197
  private preflightPromise: Promise<PreflightResult> | undefined
179
198
  private state: RuntimeStatus['state'] = 'idle'
180
199
  private lastError: string | undefined
@@ -186,6 +205,11 @@ export class AntigravityRuntime {
186
205
  /** Serializes capacity checks and session creation so concurrent requests cannot overshoot maxLiveSessions. */
187
206
  private readonly capacityMutex = new KeyedMutex()
188
207
  private sweeper: ReturnType<typeof setInterval> | undefined
208
+ private readonly monotonicNow: () => number
209
+ private lastSweepAt: number
210
+ private emailCache:
211
+ | { fingerprint: string; email: string | undefined; at: number }
212
+ | undefined
189
213
  private lastTurn: RuntimeStatus['lastTurn']
190
214
  private lifecycle: 'active' | 'disposing' | 'disposed' = 'active'
191
215
  private readonly shutdown = new AbortController()
@@ -195,8 +219,13 @@ export class AntigravityRuntime {
195
219
  /** @param host - host services. */
196
220
  constructor(host: RuntimeHost) {
197
221
  this.host = host
222
+ this.monotonicNow = host.monotonicNow ?? (() => performance.now())
223
+ this.lastSweepAt = this.monotonicNow()
198
224
  this.home = host.config.home.length > 0 ? host.config.home : defaultHome()
199
- this.catalog = new ModelCatalog(join(this.home, 'catalog.json'))
225
+ this.catalog = new ModelCatalog(
226
+ join(this.home, 'catalog.json'),
227
+ this.currentBinaryFingerprint(),
228
+ )
200
229
  this.bridge = new McpBridge(
201
230
  {
202
231
  listTools: (tenantKey) => this.listTools(tenantKey),
@@ -213,6 +242,7 @@ export class AntigravityRuntime {
213
242
  () => resolveAgyBinary(host.config.command),
214
243
  host.runCommand,
215
244
  host.config.quotaTtlMs,
245
+ host.quotaNow,
216
246
  )
217
247
  }
218
248
 
@@ -220,23 +250,138 @@ export class AntigravityRuntime {
220
250
  return this.catalog.contextWindowFor(model) ?? 0
221
251
  }
222
252
 
223
- private observeSessionContextWindow(
253
+ private currentBinaryFingerprint(binary?: string): string | undefined {
254
+ try {
255
+ return binaryFingerprint(
256
+ binary ?? resolveAgyBinary(this.host.config.command),
257
+ )
258
+ } catch {
259
+ return undefined
260
+ }
261
+ }
262
+
263
+ private reconcileBinaryFingerprint(binary?: string): void {
264
+ const fp = this.currentBinaryFingerprint(binary)
265
+ if (fp === undefined) return
266
+ if (
267
+ this.preflight !== undefined &&
268
+ this.preflightFingerprint !== undefined &&
269
+ this.preflightFingerprint !== fp
270
+ ) {
271
+ this.preflight = undefined
272
+ this.preflightFingerprint = undefined
273
+ }
274
+ if (
275
+ this.process?.alive &&
276
+ this.starting === undefined &&
277
+ this.processFingerprint !== undefined &&
278
+ this.processFingerprint !== fp &&
279
+ [...this.conversations.values()].every((c) => this.isIdle(c))
280
+ ) {
281
+ // Restart an idle ACP process after an on-disk `agy` upgrade so discovery probes the new binary.
282
+ const stale = this.process
283
+ const staleSessions = [...this.conversations.values()]
284
+ .filter((conv) => conv.process === stale)
285
+ .map((conv) => ({ conv, sessionId: conv.sessionId }))
286
+ this.process = undefined
287
+ this.processFingerprint = undefined
288
+ this.state = 'idle'
289
+ stale.stop()
290
+ for (const { conv, sessionId } of staleSessions) {
291
+ if (sessionId !== undefined) {
292
+ removeSessionArtifacts(this.home, sessionId)
293
+ }
294
+ this.clearSession(conv)
295
+ conv.dirty = true
296
+ }
297
+ }
298
+ if (this.catalog.syncBinaryFingerprint(fp)) {
299
+ this.host.onModelsChanged()
300
+ }
301
+ }
302
+
303
+ private harvestSessionTurnData(
304
+ conv: Conversation,
224
305
  sessionId: string | undefined,
225
306
  model: string | undefined,
226
- minIdx: number | null,
227
- ): void {
307
+ modelFloor: number | null,
308
+ options: {
309
+ turn?: AcpTurn
310
+ lastStepIdx?: number | null
311
+ checkStepsError?: boolean
312
+ ifChangedSince?: string
313
+ } = {},
314
+ ): HiddenTurnError | undefined {
315
+ if (this.lifecycle !== 'active' || !sessionId) return undefined
316
+ const data = readSessionTurnData(this.home, sessionId, {
317
+ metaFloorIdx: model ? modelFloor : null,
318
+ turnMetaFloorIdx: options.turn?.metaFloorIdx ?? null,
319
+ lastStepIdx: options.lastStepIdx,
320
+ checkStepsError: options.checkStepsError,
321
+ ifChangedSince: options.ifChangedSince,
322
+ })
323
+ if (data === undefined) return undefined
324
+ if (conv.sessionId === sessionId) conv.lastDbStamp = data.stamp
325
+ if (data.unchanged) return undefined
326
+ if (options.turn !== undefined && data.estimatedTokensUsed !== undefined) {
327
+ options.turn.estimatedContextUsed = data.estimatedTokensUsed
328
+ }
228
329
  if (
229
- this.lifecycle !== 'active' ||
230
- !sessionId ||
231
- !model ||
232
- minIdx === null
330
+ model &&
331
+ this.catalog.observeContextWindow(model, data.maxContextTokens)
233
332
  ) {
234
- return
235
- }
236
- const tokens = readSessionMaxContextTokens(this.home, sessionId, minIdx)
237
- if (this.catalog.observeContextWindow(model, tokens)) {
238
333
  this.host.onModelsChanged()
239
334
  }
335
+ return data.hiddenError
336
+ }
337
+
338
+ private async runPromptSegment(
339
+ conv: Conversation,
340
+ turn: AcpTurn,
341
+ proc: AcpProcess,
342
+ sessionId: string,
343
+ model: string | undefined,
344
+ modelFloor: number | null,
345
+ blocks: AcpPromptBlock[],
346
+ ): Promise<AcpPromptResult> {
347
+ const cursors = readSessionCursors(this.home, sessionId)
348
+ turn.metaFloorIdx =
349
+ modelFloor === null || cursors === null
350
+ ? null
351
+ : Math.max(modelFloor, cursors.nextMetaIdx)
352
+ turn.lastStepIdx = cursors === null ? null : cursors.lastStepIdx
353
+ turn.estimatedContextUsed = undefined
354
+ let harvested = false
355
+ try {
356
+ const result = await proc.prompt(sessionId, blocks)
357
+ harvested = true
358
+ const checkStepsError =
359
+ result.stopReason === 'end_turn' || result.stopReason === 'refusal'
360
+ const hiddenError = this.harvestSessionTurnData(
361
+ conv,
362
+ sessionId,
363
+ model,
364
+ modelFloor,
365
+ {
366
+ turn,
367
+ lastStepIdx: turn.lastStepIdx,
368
+ checkStepsError,
369
+ },
370
+ )
371
+ if (hiddenError !== undefined) {
372
+ if (hiddenError.dirtySession) conv.dirty = true
373
+ throw new LlmError(hiddenError.message, hiddenError.code)
374
+ }
375
+ return result
376
+ } catch (error) {
377
+ if (!harvested) {
378
+ this.harvestSessionTurnData(conv, sessionId, model, modelFloor, {
379
+ turn,
380
+ checkStepsError: false,
381
+ })
382
+ }
383
+ throw error
384
+ }
240
385
  }
241
386
 
242
387
  /**
@@ -299,12 +444,22 @@ export class AntigravityRuntime {
299
444
  }
300
445
 
301
446
  private accountInfo(): AccountInfo | undefined {
302
- const paths = [join(this.home, 'acp.log')]
447
+ const paths = [join(this.home, 'acp.log'), this.home]
448
+ if (isDefaultPiAgyHome(this.home))
449
+ paths.push(...defaultAgyHomes())
450
+ const now = this.monotonicNow()
451
+ const fingerprint = logPathsFingerprint(paths)
452
+ let email: string | undefined
303
453
  if (
304
- this.home === join(homedir(), '.pi', 'agent', 'cache', 'antigravity-acp')
305
- )
306
- paths.push(join(homedir(), '.gemini', 'antigravity-cli', 'cli.log'))
307
- const email = readLoggedEmail(paths)
454
+ this.emailCache !== undefined &&
455
+ this.emailCache.fingerprint === fingerprint &&
456
+ now - this.emailCache.at < EMAIL_CACHE_TTL_MS
457
+ ) {
458
+ email = this.emailCache.email
459
+ } else {
460
+ email = readLoggedEmail(paths)
461
+ this.emailCache = { fingerprint, email, at: now }
462
+ }
308
463
  const tier = this.catalog.tier()
309
464
  if (!email && !tier) return undefined
310
465
  return { email, plan: tier?.name, tierId: tier?.id }
@@ -345,7 +500,8 @@ export class AntigravityRuntime {
345
500
  async ensureReady(): Promise<AcpProcess> {
346
501
  this.assertActive()
347
502
  if (this.sweeper === undefined) {
348
- this.sweeper = setInterval(() => this.sweep(), 60_000)
503
+ this.lastSweepAt = this.monotonicNow()
504
+ this.sweeper = setInterval(() => this.sweep(), SWEEP_INTERVAL_MS)
349
505
  this.sweeper.unref?.()
350
506
  }
351
507
  if (this.starting === undefined && this.process?.alive === true)
@@ -369,6 +525,7 @@ export class AntigravityRuntime {
369
525
  options.signal?.throwIfAborted()
370
526
  if (this.warmupPromise !== undefined)
371
527
  return abortable(this.warmupPromise, options.signal)
528
+ this.reconcileBinaryFingerprint()
372
529
  if (!options.force && this.catalog.observed) return
373
530
  this.warmupPromise = (async () => {
374
531
  const proc = await this.ensureReady()
@@ -437,6 +594,7 @@ export class AntigravityRuntime {
437
594
  this.tenants.clear()
438
595
  this.process?.stop()
439
596
  this.process = undefined
597
+ this.processFingerprint = undefined
440
598
  this.disposal = (async () => {
441
599
  // Preflight waits are cancellable; binding must finish before closing its listener.
442
600
  await this.starting?.catch(() => undefined)
@@ -492,14 +650,14 @@ export class AntigravityRuntime {
492
650
  this.assertActive()
493
651
  conv = await this.acquireConversation(key)
494
652
  this.assertOwner(proc, conv)
495
- conv.lastUsed = Date.now()
653
+ conv.lastUsed = this.monotonicNow()
654
+ conv.idleMs = 0
496
655
  const split = splitSystem(options)
497
656
  const tools = toBridgeTools(options.tools)
498
657
  conv.toolNames = new Set(tools.map((t) => t.name))
499
- const effort = this.effectiveEffort(
500
- options.model,
501
- asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort,
502
- )
658
+ const requestedEffort =
659
+ asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort
660
+ let effort = this.effectiveEffort(options.model, requestedEffort)
503
661
 
504
662
  if (options.signal?.aborted) {
505
663
  this.dropTurn(conv, 'The harness cancelled this request.')
@@ -518,10 +676,11 @@ export class AntigravityRuntime {
518
676
  // already owns. A compaction checkpoint, pruned/rewritten prefix, or
519
677
  // model/effort change means the live session is stale, so abandon the
520
678
  // turn and let plan() rebuild from Pi's authoritative history.
679
+ const resumedEffort = clampEffortToOptions(conv.configOptions, effort)
521
680
  if (
522
681
  !this.historyPrefixIntact(conv, split.system, split.messages) ||
523
682
  conv.model !== options.model ||
524
- conv.effort !== effort
683
+ conv.effort !== resumedEffort
525
684
  ) {
526
685
  this.dropTurn(
527
686
  conv,
@@ -538,7 +697,7 @@ export class AntigravityRuntime {
538
697
  this.assertActive()
539
698
  if (resumed !== undefined) {
540
699
  conv.knownIds = messageIds(split.messages)
541
- yield* this.pump(conv, resumed, proc, options, effort)
700
+ yield* this.pump(conv, resumed, proc, options, resumedEffort)
542
701
  return
543
702
  }
544
703
  this.dropTurn(
@@ -557,9 +716,10 @@ export class AntigravityRuntime {
557
716
  if (conv.sessionId === undefined) {
558
717
  conv.systemHash = digest(split.system)
559
718
  supplementalTools = await this.openSession(conv, tools, proc)
719
+ effort = this.effectiveEffort(options.model, requestedEffort)
560
720
  }
561
721
  this.assertOwner(proc, conv, conv.sessionId)
562
- await this.select(conv, proc, options.model, effort)
722
+ effort = await this.select(conv, proc, options.model, effort)
563
723
  this.assertOwner(proc, conv, conv.sessionId)
564
724
  let blocks: AcpPromptBlock[]
565
725
  if (plan.rebuild) {
@@ -615,6 +775,8 @@ export class AntigravityRuntime {
615
775
  const existing = this.conversations.get(key)
616
776
  if (existing !== undefined) {
617
777
  existing.opening = true
778
+ existing.lastUsed = this.monotonicNow()
779
+ existing.idleMs = 0
618
780
  return existing
619
781
  }
620
782
  const unlock = await this.capacityMutex.acquire(
@@ -626,6 +788,8 @@ export class AntigravityRuntime {
626
788
  const again = this.conversations.get(key)
627
789
  if (again !== undefined) {
628
790
  again.opening = true
791
+ again.lastUsed = this.monotonicNow()
792
+ again.idleMs = 0
629
793
  return again
630
794
  }
631
795
  const max = Math.max(1, this.host.config.maxLiveSessions)
@@ -673,7 +837,8 @@ export class AntigravityRuntime {
673
837
  issuedIds: new Set(),
674
838
  turn: undefined,
675
839
  dirty: false,
676
- lastUsed: Date.now(),
840
+ lastUsed: this.monotonicNow(),
841
+ idleMs: 0,
677
842
  model: undefined,
678
843
  metaFloorIdx: 0,
679
844
  effort: undefined,
@@ -713,16 +878,31 @@ export class AntigravityRuntime {
713
878
  log: (message) => this.host.log.warn(message),
714
879
  })
715
880
  this.process = proc
881
+ this.processFingerprint = binaryFingerprint(preflight.binary)
716
882
  const started = proc
717
883
  proc.onExit((error) => this.onProcessExit(started, error))
718
- await proc.start(120_000)
884
+ const init = await proc.start(120_000)
719
885
  this.assertOwner(proc)
886
+ const agentVersion = init?.agentInfo?.version
887
+ if (typeof agentVersion === 'string' && agentVersion.trim().length > 0) {
888
+ assertSupportedAgyVersion(agentVersion, preflight.binary)
889
+ }
890
+ if (
891
+ this.catalog.observeImageSupport(
892
+ init?.agentCapabilities?.promptCapabilities?.image,
893
+ )
894
+ ) {
895
+ this.host.onModelsChanged()
896
+ }
720
897
  this.state = 'ready'
721
898
  this.lastError = undefined
722
899
  return proc
723
900
  } catch (error) {
724
901
  proc?.stop()
725
- if (this.process === proc) this.process = undefined
902
+ if (this.process === proc) {
903
+ this.process = undefined
904
+ this.processFingerprint = undefined
905
+ }
726
906
  if (this.lifecycle !== 'active') throw this.shutdown.signal.reason
727
907
  await this.bridge.close()
728
908
  this.assertActive()
@@ -735,17 +915,20 @@ export class AntigravityRuntime {
735
915
  }
736
916
 
737
917
  private runPreflight(): Promise<PreflightResult> {
918
+ this.reconcileBinaryFingerprint()
919
+ const warn = (message: string) => this.host.log.warn(message)
738
920
  if (this.preflight !== undefined) {
739
- prepareHome(this.home)
921
+ prepareHome(this.home, undefined, undefined, warn)
740
922
  return Promise.resolve(this.preflight)
741
923
  }
742
924
  this.preflightPromise ??= (async () => {
743
925
  const config = this.host.config
744
926
  const binary = resolveAgyBinary(config.command)
927
+ this.reconcileBinaryFingerprint(binary)
745
928
  const version = await readVersion(binary, this.host.runCommand)
746
929
  this.assertActive()
747
930
  assertSupportedAgyVersion(version, binary)
748
- const workspace = prepareHome(this.home)
931
+ const workspace = prepareHome(this.home, undefined, undefined, warn)
749
932
  const result: PreflightResult = {
750
933
  binary,
751
934
  version,
@@ -754,6 +937,7 @@ export class AntigravityRuntime {
754
937
  logFile: join(this.home, 'acp.log'),
755
938
  }
756
939
  this.preflight = result
940
+ this.preflightFingerprint = binaryFingerprint(binary)
757
941
  return result
758
942
  })().finally(() => {
759
943
  this.preflightPromise = undefined
@@ -763,7 +947,10 @@ export class AntigravityRuntime {
763
947
 
764
948
  private onProcessExit(proc: AcpProcess, error: Error): void {
765
949
  const current = this.process === proc
766
- if (current) this.process = undefined
950
+ if (current) {
951
+ this.process = undefined
952
+ this.processFingerprint = undefined
953
+ }
767
954
  if (current && this.lifecycle === 'active') {
768
955
  this.state = 'error'
769
956
  this.lastError = error.message
@@ -787,7 +974,13 @@ export class AntigravityRuntime {
787
974
  proc: AcpProcess,
788
975
  ): Promise<readonly BridgeTool[]> {
789
976
  this.assertOwner(proc, conv)
790
- syncOAuthToken(this.home)
977
+ try {
978
+ syncOAuthToken(this.home)
979
+ } catch (error) {
980
+ this.host.log.warn(
981
+ `antigravity-acp: OAuth token sync skipped: ${error instanceof Error ? error.message : String(error)}`,
982
+ )
983
+ }
791
984
  conv.reportedToolCalls.clear()
792
985
  const compacted = tools.map(compactBridgeTool)
793
986
  const supplementalTools = tools.filter(
@@ -836,19 +1029,33 @@ export class AntigravityRuntime {
836
1029
  if (this.catalog.observe(update.configOptions))
837
1030
  this.host.onModelsChanged()
838
1031
  }
839
- if (update.sessionUpdate === 'usage_update') {
840
- this.observeSessionContextWindow(
841
- conv.sessionId,
842
- conv.model,
843
- conv.metaFloorIdx,
844
- )
845
- }
846
1032
  if (recordReportedToolCall(conv, update) === 'conflict') {
847
1033
  this.host.log.warn(
848
1034
  `antigravity-acp: agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
849
1035
  )
850
1036
  }
851
1037
  conv.turn?.onUpdate(update)
1038
+ if (update.sessionUpdate === 'usage_update') {
1039
+ const hasCachedContextWindow =
1040
+ conv.model !== undefined &&
1041
+ this.catalog.contextWindowFor(conv.model) !== undefined
1042
+ const hasPositiveUsed =
1043
+ typeof update.used === 'number' &&
1044
+ Number.isFinite(update.used) &&
1045
+ update.used > 0
1046
+ if (!(hasCachedContextWindow && hasPositiveUsed)) {
1047
+ this.harvestSessionTurnData(
1048
+ conv,
1049
+ conv.sessionId,
1050
+ conv.model,
1051
+ conv.metaFloorIdx,
1052
+ {
1053
+ turn: conv.turn,
1054
+ ifChangedSince: conv.lastDbStamp,
1055
+ },
1056
+ )
1057
+ }
1058
+ }
852
1059
  },
853
1060
  onPermission: (request) => this.owns(proc, conv) && conv.tenantKey === tenantKey
854
1061
  ? this.answerPermission(conv, request)
@@ -867,6 +1074,7 @@ export class AntigravityRuntime {
867
1074
  conv.configOptions = result.configOptions ?? []
868
1075
  conv.model = undefined
869
1076
  conv.metaFloorIdx = 0
1077
+ conv.lastDbStamp = undefined
870
1078
  conv.effort = undefined
871
1079
 
872
1080
  conv.dirty = false
@@ -1002,26 +1210,31 @@ export class AntigravityRuntime {
1002
1210
  proc: AcpProcess,
1003
1211
  model: string,
1004
1212
  effort: Effort,
1005
- ): Promise<void> {
1213
+ ): Promise<Effort> {
1006
1214
  const sessionId = conv.sessionId as string
1007
1215
  this.assertOwner(proc, conv, sessionId)
1008
1216
  const modelOption = conv.configOptions.find(
1009
1217
  (o) => o.id === 'model' || o.category === 'model',
1010
1218
  )
1219
+ const modelValues =
1220
+ modelOption?.options !== undefined
1221
+ ? flattenConfigOptions(modelOption.options)
1222
+ : undefined
1011
1223
  if (
1012
- modelOption?.options !== undefined &&
1013
- !modelOption.options.some((o) => o.value === model)
1224
+ modelValues !== undefined &&
1225
+ !modelValues.some((o) => o.value === model)
1014
1226
  ) {
1015
1227
  throw new LlmError(
1016
- `Antigravity does not offer model "${model}" to this account; available: ${modelOption.options.map((o) => o.value).join(', ')}`,
1228
+ `Antigravity does not offer model "${model}" to this account; available: ${modelValues.map((o) => o.value).join(', ')}`,
1017
1229
  'UNKNOWN_MODEL',
1018
1230
  )
1019
1231
  }
1020
1232
  const previousModel = conv.model
1021
1233
  const previousFloor = conv.metaFloorIdx
1022
1234
  if (previousModel !== undefined && previousModel !== model) {
1023
- this.observeSessionContextWindow(sessionId, previousModel, previousFloor)
1235
+ this.harvestSessionTurnData(conv, sessionId, previousModel, previousFloor)
1024
1236
  conv.metaFloorIdx = null
1237
+ conv.lastDbStamp = undefined
1025
1238
  }
1026
1239
  if (conv.model !== model && modelOption?.currentValue !== model) {
1027
1240
  await this.applyConfigOption(
@@ -1033,28 +1246,48 @@ export class AntigravityRuntime {
1033
1246
  )
1034
1247
  }
1035
1248
  if (previousModel !== undefined && previousModel !== model) {
1036
- const nextIdx = readSessionNextMetadataIndex(this.home, sessionId)
1249
+ const cursors = readSessionCursors(this.home, sessionId)
1037
1250
  conv.metaFloorIdx =
1038
- previousFloor === null || nextIdx === null
1251
+ previousFloor === null || cursors === null
1039
1252
  ? null
1040
- : Math.max(previousFloor, nextIdx)
1253
+ : Math.max(previousFloor, cursors.nextMetaIdx)
1254
+ conv.lastDbStamp = undefined
1041
1255
  }
1042
1256
  conv.model = model
1043
1257
  const levelOption = conv.configOptions.find(
1044
1258
  (o) => o.id === 'thought_level' || o.category === 'thought_level',
1045
1259
  )
1046
- // Fixed-variant families (GPT-OSS) reject every thought_level change; the
1047
- // effort already lives in the model id, so only selectable families write it.
1048
- const selectable = this.catalog.effortsFor(model)
1260
+ const offeredEfforts =
1261
+ levelOption?.options !== undefined
1262
+ ? flattenConfigOptions(levelOption.options)
1263
+ .map((o) => asEffort(o.value))
1264
+ .filter((v): v is Effort => v !== undefined)
1265
+ : undefined
1266
+ const targetEffort =
1267
+ offeredEfforts !== undefined && offeredEfforts.length > 0
1268
+ ? offeredEfforts.includes(effort)
1269
+ ? effort
1270
+ : nearestEffort(effort, offeredEfforts)
1271
+ : effort
1272
+ // Fixed-variant families (GPT-OSS) and single-variant orchestrators reject
1273
+ // thought_level writes, so only selectable families with offered levels write it.
1049
1274
  if (
1050
- selectable.length > 0 &&
1275
+ this.catalog.supportsEffortSelection(model) &&
1051
1276
  levelOption !== undefined &&
1052
- conv.effort !== effort &&
1053
- levelOption.currentValue !== effort
1277
+ (offeredEfforts === undefined || offeredEfforts.length > 0) &&
1278
+ conv.effort !== targetEffort &&
1279
+ levelOption.currentValue !== targetEffort
1054
1280
  ) {
1055
- await this.applyConfigOption(conv, proc, sessionId, levelOption.id, effort)
1281
+ await this.applyConfigOption(
1282
+ conv,
1283
+ proc,
1284
+ sessionId,
1285
+ levelOption.id,
1286
+ targetEffort,
1287
+ )
1056
1288
  }
1057
- conv.effort = effort
1289
+ conv.effort = targetEffort
1290
+ return targetEffort
1058
1291
  }
1059
1292
 
1060
1293
  private async applyConfigOption(
@@ -1071,6 +1304,9 @@ export class AntigravityRuntime {
1071
1304
  })
1072
1305
  this.assertOwner(proc, conv, sessionId)
1073
1306
  conv.configOptions = configOptions
1307
+ if (this.catalog.observe(configOptions)) {
1308
+ this.host.onModelsChanged()
1309
+ }
1074
1310
  }
1075
1311
 
1076
1312
  private plan(
@@ -1161,7 +1397,9 @@ export class AntigravityRuntime {
1161
1397
  }
1162
1398
 
1163
1399
  private async resetSession(conv: Conversation): Promise<void> {
1164
- this.observeSessionContextWindow(conv.sessionId, conv.model, conv.metaFloorIdx)
1400
+ this.harvestSessionTurnData(conv, conv.sessionId, conv.model, conv.metaFloorIdx, {
1401
+ ifChangedSince: conv.lastDbStamp,
1402
+ })
1165
1403
  let closing: Promise<void> | undefined
1166
1404
  if (conv.sessionId !== undefined && conv.process !== undefined) {
1167
1405
  closing = this.closeAndCleanSession(conv.process, conv.sessionId)
@@ -1179,6 +1417,7 @@ export class AntigravityRuntime {
1179
1417
  conv.tenantSecret = undefined
1180
1418
  conv.process = undefined
1181
1419
  conv.metaFloorIdx = null
1420
+ conv.lastDbStamp = undefined
1182
1421
  conv.advertisedTools = []
1183
1422
  conv.advertisedToolDigests.clear()
1184
1423
  conv.knownTools.clear()
@@ -1195,9 +1434,20 @@ export class AntigravityRuntime {
1195
1434
  // Queue that failure too, so every allocated turn reaches the pump's cleanup owner.
1196
1435
  try {
1197
1436
  this.assertOwner(proc, conv, conv.sessionId)
1198
- turn.promptSettled = proc.prompt(conv.sessionId as string, blocks).then(
1199
- (result) => turn.events.push({ kind: 'done', result }),
1200
- (error: unknown) => turn.fail(mapError(error)),
1437
+ const sessionId = conv.sessionId as string
1438
+ const model = conv.model
1439
+ const modelFloor = conv.metaFloorIdx
1440
+ turn.bindPrompt(
1441
+ this.runPromptSegment(
1442
+ conv,
1443
+ turn,
1444
+ proc,
1445
+ sessionId,
1446
+ model,
1447
+ modelFloor,
1448
+ blocks,
1449
+ ),
1450
+ { mapError },
1201
1451
  )
1202
1452
  } catch (error) {
1203
1453
  turn.fail(mapError(error))
@@ -1254,7 +1504,15 @@ export class AntigravityRuntime {
1254
1504
  parkSettleMs: this.host.config.parkSettleMs,
1255
1505
  maxContinuations: this.host.config.longDecodeContinuations,
1256
1506
  continuePrompt: () =>
1257
- proc.prompt(sessionId, [{ type: 'text', text: CONTINUE_PROMPT }]),
1507
+ this.runPromptSegment(
1508
+ conv,
1509
+ turn,
1510
+ proc,
1511
+ sessionId,
1512
+ options.model,
1513
+ metaFloorIdx,
1514
+ [{ type: 'text', text: CONTINUE_PROMPT }],
1515
+ ),
1258
1516
  cancel: () => {
1259
1517
  if (conv.turn === turn) proc.cancel(sessionId)
1260
1518
  },
@@ -1267,7 +1525,15 @@ export class AntigravityRuntime {
1267
1525
  conv.issuedIds.add(chunk.block.id)
1268
1526
  if (chunk.type === 'finish') {
1269
1527
  finishKind = chunk.reason.kind
1270
- this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1528
+ if (
1529
+ finishKind === 'aborted' ||
1530
+ (finishKind === 'tool-calls' &&
1531
+ this.catalog.contextWindowFor(options.model) === undefined)
1532
+ ) {
1533
+ this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1534
+ ifChangedSince: conv.lastDbStamp,
1535
+ })
1536
+ }
1271
1537
  }
1272
1538
  yield chunk
1273
1539
  if (chunk.type === 'finish' && chunk.reason.kind === 'aborted') break
@@ -1275,13 +1541,17 @@ export class AntigravityRuntime {
1275
1541
  const interrupted = turn.guard(undefined, signal)
1276
1542
  if (interrupted !== undefined && finishKind !== 'aborted') {
1277
1543
  finishKind = 'aborted'
1278
- this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1544
+ this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1545
+ ifChangedSince: conv.lastDbStamp,
1546
+ })
1279
1547
  yield interrupted
1280
1548
  }
1281
1549
  drained = true
1282
1550
  } catch (error) {
1283
1551
  finishKind = 'error'
1284
- this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1552
+ this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1553
+ ifChangedSince: conv.lastDbStamp,
1554
+ })
1285
1555
  throw mapError(error)
1286
1556
  } finally {
1287
1557
  // Only a fully consumed tool handoff keeps the turn and its cancellation owner.
@@ -1342,12 +1612,18 @@ export class AntigravityRuntime {
1342
1612
  const extraText = extras.length > 0 ? renderTranscript(extras) : ''
1343
1613
  const toolDelta = consumeToolDelta(conv, tools)
1344
1614
  const suffix = [toolDelta, extraText].filter(Boolean).join('\n\n')
1345
- const pending = [...turn.pendingCalls.values()]
1346
- turn.pendingCalls.clear()
1347
- if (turn.finished || !this.isTurnLive(turn)) {
1615
+ const bridgeResults = new Map<string, BridgeToolResult>()
1616
+ for (const [id, message] of results) {
1617
+ bridgeResults.set(
1618
+ id,
1619
+ this.toBridgeResult(message.content, message.isError === true),
1620
+ )
1621
+ }
1622
+ const delivery = turn.deliverToolResults(bridgeResults, suffix)
1623
+ if (!delivery.resumed) {
1348
1624
  // The agent ended its turn while the harness ran the tools: hand the results over as new input.
1349
1625
  const transcript = renderTranscript(
1350
- pending.map((call) => results.get(call.id) as RequestMessage),
1626
+ delivery.pending.map((call) => results.get(call.id) as RequestMessage),
1351
1627
  )
1352
1628
  // The old turn is over: its reported identities do not carry into the continuation.
1353
1629
  turn.abandon('The agent ended the tool-waiting prompt.')
@@ -1356,32 +1632,14 @@ export class AntigravityRuntime {
1356
1632
  this.startPrompt(conv, next, proc, [
1357
1633
  {
1358
1634
  type: 'text',
1359
- text: `${transcript}${suffix ? `\n\n${suffix}` : ''}\n\nContinue the task with these tool results.`,
1635
+ text: `${transcript}${delivery.suffix ? `\n\n${delivery.suffix}` : ''}\n\nContinue the task with these tool results.`,
1360
1636
  },
1361
1637
  ])
1362
1638
  return next
1363
1639
  }
1364
- for (const [index, call] of pending.entries()) {
1365
- const message = results.get(call.id) as Extract<
1366
- RequestMessage,
1367
- { role: 'tool' }
1368
- >
1369
- const result = this.toBridgeResult(
1370
- message.content,
1371
- message.isError === true,
1372
- )
1373
- if (index === pending.length - 1 && suffix.length > 0)
1374
- result.content.push({ type: 'text', text: `\n\n${suffix}` })
1375
- call.result.resolve(result)
1376
- }
1377
1640
  return turn
1378
1641
  }
1379
1642
 
1380
- private isTurnLive(turn: AcpTurn): boolean {
1381
- const head = turn.events.peek()
1382
- return head?.kind !== 'done' && head?.kind !== 'error'
1383
- }
1384
-
1385
1643
  private toBridgeResult(
1386
1644
  content: readonly ContentBlock[],
1387
1645
  isError: boolean,
@@ -1429,7 +1687,8 @@ export class AntigravityRuntime {
1429
1687
  }
1430
1688
 
1431
1689
  private async afterStep(conv: Conversation): Promise<void> {
1432
- conv.lastUsed = Date.now()
1690
+ conv.lastUsed = this.monotonicNow()
1691
+ conv.idleMs = 0
1433
1692
  const idle = this.isIdle(conv)
1434
1693
  if (idle && conv.key.startsWith('anon-')) {
1435
1694
  await this.resetSession(conv)
@@ -1473,16 +1732,23 @@ export class AntigravityRuntime {
1473
1732
  const turn = conv.turn
1474
1733
  if (turn === undefined || turn.finished)
1475
1734
  return toolError('No harness turn is waiting for this tool call.')
1735
+ const relayAfterMs =
1736
+ this.host.relayAfterMs ??
1737
+ this.host.config.relayAfterMs ??
1738
+ defaults.relayAfterMs
1476
1739
  if (request.name === AWAIT_TOOL_NAME) {
1477
1740
  const callId =
1478
1741
  typeof request.arguments.call_id === 'string'
1479
1742
  ? request.arguments.call_id
1480
1743
  : ''
1481
- const call = turn.calls.get(callId)
1482
- if (call === undefined)
1483
- return toolError(`Unknown harness call id ${callId}.`)
1484
- turn.resumeRelay(callId)
1485
- return this.awaitCall(turn, call, request.signal)
1744
+ return (
1745
+ turn.awaitRelayedCall(
1746
+ callId,
1747
+ relayAfterMs,
1748
+ request.signal,
1749
+ request.commit,
1750
+ ) ?? toolError(`Unknown harness call id ${callId}.`)
1751
+ )
1486
1752
  }
1487
1753
  let name = request.name
1488
1754
  let args = request.arguments
@@ -1504,50 +1770,25 @@ export class AntigravityRuntime {
1504
1770
  }
1505
1771
  if (!conv.toolNames.has(name))
1506
1772
  return toolError(`The harness has no tool named ${name}.`)
1507
- return this.awaitCall(turn, turn.park(name, args), request.signal)
1508
- }
1509
-
1510
- private async awaitCall(
1511
- turn: AcpTurn,
1512
- call: ParkedCall,
1513
- signal: AbortSignal,
1514
- ): Promise<BridgeToolResult> {
1515
- let timer: ReturnType<typeof setTimeout> | undefined
1516
- const relayAfterMs =
1517
- this.host.relayAfterMs ??
1518
- this.host.config.relayAfterMs ??
1519
- defaults.relayAfterMs
1520
- const relay = new Promise<'relay'>((resolve) => {
1521
- timer = setTimeout(() => resolve('relay'), relayAfterMs)
1522
- })
1523
- let onAbort: (() => void) | undefined
1524
- const aborted = new Promise<'aborted'>((resolve) => {
1525
- if (signal.aborted) resolve('aborted')
1526
- else {
1527
- onAbort = () => resolve('aborted')
1528
- signal.addEventListener('abort', onAbort, { once: true })
1529
- }
1530
- })
1531
- try {
1532
- const outcome = await Promise.race([call.result.promise, relay, aborted])
1533
- if (outcome === 'relay') {
1534
- turn.markRelayed(call.id)
1535
- return relayNotice(call)
1536
- }
1537
- if (outcome === 'aborted')
1538
- return toolError('The tool call was cancelled.')
1539
- return outcome
1540
- } finally {
1541
- if (timer !== undefined) clearTimeout(timer)
1542
- if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
1543
- }
1773
+ return turn.invokeTool(
1774
+ name,
1775
+ args,
1776
+ relayAfterMs,
1777
+ request.signal,
1778
+ request.commit,
1779
+ )
1544
1780
  }
1545
1781
 
1546
1782
  private sweep(): void {
1547
1783
  const ttl = this.host.config.idleSessionTtlMs
1548
- const now = Date.now()
1784
+ const now = this.monotonicNow()
1785
+ const delta = Math.max(0, now - this.lastSweepAt)
1786
+ this.lastSweepAt = now
1787
+ const slice = Math.min(delta, SWEEP_INTERVAL_MS * 2)
1549
1788
  for (const conv of [...this.conversations.values()]) {
1550
- if (this.isIdle(conv) && now - conv.lastUsed > ttl) {
1789
+ if (!this.isIdle(conv)) continue
1790
+ conv.idleMs += slice
1791
+ if (conv.idleMs > ttl) {
1551
1792
  void this.resetSession(conv).catch((error: unknown) => {
1552
1793
  this.host.log.warn(
1553
1794
  `session sweep cleanup failed: ${error instanceof Error ? error.message : String(error)}`,
@@ -1559,6 +1800,43 @@ export class AntigravityRuntime {
1559
1800
  }
1560
1801
  }
1561
1802
 
1803
+ function clampEffortToOptions(
1804
+ configOptions: readonly AcpConfigOption[],
1805
+ effort: Effort,
1806
+ ): Effort {
1807
+ const levelOption = configOptions.find(
1808
+ (o) => o.id === 'thought_level' || o.category === 'thought_level',
1809
+ )
1810
+ if (levelOption?.options === undefined) return effort
1811
+ const offered = flattenConfigOptions(levelOption.options)
1812
+ .map((o) => asEffort(o.value))
1813
+ .filter((v): v is Effort => v !== undefined)
1814
+ if (offered.length === 0 || offered.includes(effort)) return effort
1815
+ return nearestEffort(effort, offered)
1816
+ }
1817
+
1818
+ function statSignature(path: string): string {
1819
+ try {
1820
+ const st = statSync(path, { bigint: true })
1821
+ return `${st.isDirectory() ? 'd' : 'f'}:${st.ino}:${st.mtimeNs}:${st.ctimeNs}:${st.size}`
1822
+ } catch {
1823
+ return 'missing'
1824
+ }
1825
+ }
1826
+
1827
+ function logPathsFingerprint(paths: readonly string[]): string {
1828
+ const parts: string[] = []
1829
+ for (const p of paths) {
1830
+ const sig = statSignature(p)
1831
+ parts.push(`${p}=${sig}`)
1832
+ if (sig.startsWith('d:')) {
1833
+ parts.push(`${p}/cli.log=${statSignature(join(p, 'cli.log'))}`)
1834
+ parts.push(`${p}/log=${statSignature(join(p, 'log'))}`)
1835
+ }
1836
+ }
1837
+ return parts.join('|')
1838
+ }
1839
+
1562
1840
  function messageIds(messages: readonly RequestMessage[]): string[] {
1563
1841
  return messages.map((m) => m.id ?? '')
1564
1842
  }