pi-agy-acp 0.2.7 → 0.2.8

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
@@ -33,12 +33,9 @@ import {
33
33
  nearestEffort,
34
34
  offeredEffortsFrom,
35
35
  } from './catalog.ts'
36
- import { asEffort, defaults, type Config, type Effort } from './config.ts'
36
+ import { asEffort, DEFAULT_CONFIG, type Config, type Effort } from './config.ts'
37
37
  import {
38
38
  AcpTurn,
39
- AWAIT_TOOL,
40
- AWAIT_TOOL_NAME,
41
- CALL_TOOL,
42
39
  pumpStep,
43
40
  type ReportedToolCall,
44
41
  structuredToolMeta,
@@ -46,11 +43,8 @@ import {
46
43
  isEmptyInput,
47
44
  } from './conversation.ts'
48
45
  import {
49
- AGENT_TOOL_PREFIX,
50
- CALL_TOOL_NAME,
51
46
  bridgeSystemPrompt,
52
47
  inputPrompt,
53
- MCP_SERVER_NAME,
54
48
  openingPrompts,
55
49
  renderSessionInstructions,
56
50
  renderTranscript,
@@ -59,6 +53,12 @@ import {
59
53
  } from './history.ts'
60
54
  import { JsonRpcClosedError, JsonRpcRemoteError } from './jsonrpc.ts'
61
55
  import {
56
+ AGENT_TOOL_PREFIX,
57
+ AWAIT_TOOL,
58
+ AWAIT_TOOL_NAME,
59
+ CALL_TOOL,
60
+ CALL_TOOL_NAME,
61
+ MCP_SERVER_NAME,
62
62
  McpBridge,
63
63
  compactBridgeTool,
64
64
  consumeToolDelta,
@@ -83,6 +83,8 @@ import {
83
83
  type PreflightResult,
84
84
  } from './preflight.ts'
85
85
  import {
86
+ CONTEXT_WINDOW_RE,
87
+ isExplicitQuotaError,
86
88
  readSessionCursors,
87
89
  readSessionTurnData,
88
90
  removeSessionArtifacts,
@@ -94,7 +96,7 @@ import {
94
96
  type AccountInfo,
95
97
  type QuotaSnapshot,
96
98
  } from './quota.ts'
97
- import { digest, KeyedMutex, abortable } from './util.ts'
99
+ import { abortable, digest, isRecord, KeyedMutex } from './util.ts'
98
100
  import { VERSION } from './version.ts'
99
101
 
100
102
  const CONTINUE_PROMPT =
@@ -150,35 +152,45 @@ export interface RuntimeStatus {
150
152
  }
151
153
  }
152
154
 
153
- interface Conversation {
154
- readonly key: string
155
- tenantKey: string | undefined
155
+ interface LiveSession {
156
+ readonly sessionId: string
157
+ readonly process: AcpProcess
158
+ readonly tenantKey: string
156
159
  /** Per-tenant bearer credential presented by the agent on the MCP bridge. */
157
- tenantSecret: string | undefined
158
- sessionId: string | undefined
159
- process: AcpProcess | undefined
160
+ readonly tenantSecret: string
160
161
  configOptions: AcpConfigOption[]
162
+ readonly advertisedTools: readonly BridgeTool[]
163
+ readonly advertisedToolDigests: ReadonlyMap<string, string>
164
+ readonly knownTools: Map<string, string>
165
+ /** Tool calls the agent reported via `session/update` — the only trusted permission source. */
166
+ readonly reportedToolCalls: Map<string, ReportedToolCall>
167
+ model: string | undefined
168
+ effort: Effort | undefined
169
+ /** Lower `gen_metadata.idx` bound for `model`, or `null` when unobservable after a failed cursor read. */
170
+ metaFloorIdx: number | null
171
+ /** Last observed SQLite file/sidecar stamp used to skip unchanged reads during streaming. */
172
+ lastDbStamp?: string
173
+ }
174
+
175
+ interface TenantBinding {
176
+ readonly conv: Conversation
177
+ readonly secret: string
178
+ readonly advertisedTools: readonly BridgeTool[]
179
+ }
180
+
181
+ interface Conversation {
182
+ readonly key: string
183
+ session: LiveSession | undefined
161
184
  systemHash: string | undefined
162
- advertisedTools: BridgeTool[]
163
- advertisedToolDigests: Map<string, string>
164
- knownTools: Map<string, string>
165
185
  toolNames: Set<string>
166
- /** Tool calls the agent reported via `session/update` — the only trusted permission source. */
167
- reportedToolCalls: Map<string, ReportedToolCall>
168
186
  /** True while this conversation is being acquired or its session is opening; never evicted as idle. */
169
- opening: boolean
187
+ inUse: boolean
170
188
  knownIds: string[] | undefined
171
189
  issuedIds: Set<string>
172
190
  turn: AcpTurn | undefined
173
- dirty: boolean
174
- lastUsed: number
191
+ needsRebuild: boolean
192
+ lastUsedMs: number
175
193
  idleMs: number
176
- model: string | undefined
177
- /** Lower `gen_metadata.idx` bound for `model`, or `null` when unobservable after a failed cursor read. */
178
- metaFloorIdx: number | null
179
- /** Last observed SQLite file/sidecar stamp used to skip unchanged reads during streaming. */
180
- lastDbStamp?: string
181
- effort: Effort | undefined
182
194
  }
183
195
 
184
196
  interface ResumableSession {
@@ -213,7 +225,7 @@ export class AntigravityRuntime {
213
225
  private readonly conversations = new Map<string, Conversation>()
214
226
  /** Dormant idle-swept sessions eligible for `session/resume` on next request. */
215
227
  private readonly resumableSessions = new Map<string, ResumableSession>()
216
- private readonly tenants = new Map<string, Conversation>()
228
+ private readonly tenants = new Map<string, TenantBinding>()
217
229
  private readonly mutex = new KeyedMutex()
218
230
  /** Serializes capacity checks and session creation so concurrent requests cannot overshoot maxLiveSessions. */
219
231
  private readonly capacityMutex = new KeyedMutex()
@@ -307,17 +319,15 @@ export class AntigravityRuntime {
307
319
  // Restart an idle ACP process after an on-disk `agy` upgrade so discovery probes the new binary.
308
320
  const stale = this.process
309
321
  const staleSessions = [...this.conversations.values()]
310
- .filter((conv) => conv.process === stale)
311
- .map((conv) => ({ conv, sessionId: conv.sessionId }))
322
+ .filter((conv) => conv.session?.process === stale)
323
+ .map((conv) => ({ conv, sessionId: conv.session!.sessionId }))
312
324
  this.detachProcess(stale)
313
325
  void this.bridge.close()
314
326
  this.clearResumableSessions()
315
327
  for (const { conv, sessionId } of staleSessions) {
316
- if (sessionId !== undefined) {
317
- removeSessionArtifacts(this.home, sessionId)
318
- }
328
+ removeSessionArtifacts(this.home, sessionId)
319
329
  this.clearSession(conv)
320
- conv.dirty = true
330
+ conv.needsRebuild = true
321
331
  }
322
332
  }
323
333
  if (this.catalog.syncBinaryFingerprint(fp)) {
@@ -346,10 +356,10 @@ export class AntigravityRuntime {
346
356
  ifChangedSince: options.ifChangedSince,
347
357
  })
348
358
  if (data === undefined) return undefined
349
- if (conv.sessionId === sessionId) conv.lastDbStamp = data.stamp
359
+ if (conv.session?.sessionId === sessionId) conv.session.lastDbStamp = data.stamp
350
360
  if (data.unchanged) return undefined
351
361
  if (options.turn !== undefined && data.estimatedTokensUsed !== undefined) {
352
- options.turn.estimatedContextUsed = data.estimatedTokensUsed
362
+ options.turn.estimatedContextTokens = data.estimatedTokensUsed
353
363
  }
354
364
  if (
355
365
  model &&
@@ -375,7 +385,7 @@ export class AntigravityRuntime {
375
385
  ? null
376
386
  : Math.max(modelFloor, cursors.nextMetaIdx)
377
387
  turn.lastStepIdx = cursors === null ? null : cursors.lastStepIdx
378
- turn.estimatedContextUsed = undefined
388
+ turn.estimatedContextTokens = undefined
379
389
  let harvested = false
380
390
  try {
381
391
  const result = await proc.prompt(sessionId, blocks)
@@ -394,7 +404,7 @@ export class AntigravityRuntime {
394
404
  },
395
405
  )
396
406
  if (hiddenError !== undefined) {
397
- if (hiddenError.dirtySession) conv.dirty = true
407
+ if (hiddenError.dirtySession) conv.needsRebuild = true
398
408
  throw new LlmError(hiddenError.message, hiddenError.code)
399
409
  }
400
410
  return result
@@ -404,7 +414,7 @@ export class AntigravityRuntime {
404
414
  error.rpc.code === -32002 &&
405
415
  this.owns(proc, conv, sessionId)
406
416
  ) {
407
- conv.dirty = true
417
+ conv.needsRebuild = true
408
418
  }
409
419
  if (!harvested) {
410
420
  this.harvestSessionTurnData(conv, sessionId, model, modelFloor, {
@@ -466,7 +476,7 @@ export class AntigravityRuntime {
466
476
  }),
467
477
  efforts: [...this.catalog.effortList()],
468
478
  liveSessions: [...this.conversations.values()].filter(
469
- (c) => c.sessionId !== undefined,
479
+ (c) => c.session !== undefined,
470
480
  ).length,
471
481
  activeTurns: [...this.conversations.values()].filter(
472
482
  (c) => c.turn !== undefined && !c.turn.finished,
@@ -501,7 +511,7 @@ export class AntigravityRuntime {
501
511
  async readQuota(force = false): Promise<QuotaSnapshot> {
502
512
  this.assertActive()
503
513
  const quota = this.quota.read(force)
504
- if (!this.catalog.tier() && !this.catalog.observed) {
514
+ if (!this.catalog.tier() && !this.catalog.isObserved()) {
505
515
  this.tierDiscovery ??= (async () => {
506
516
  const state = this.state
507
517
  const error = this.lastError
@@ -678,7 +688,7 @@ export class AntigravityRuntime {
678
688
  return this.lifecycle === 'active' && this.process === proc && proc.alive &&
679
689
  (conv === undefined || (
680
690
  this.conversations.get(conv.key) === conv &&
681
- (sessionId === undefined || (conv.process === proc && conv.sessionId === sessionId))
691
+ (sessionId === undefined || (conv.session?.process === proc && conv.session.sessionId === sessionId))
682
692
  ))
683
693
  }
684
694
 
@@ -716,14 +726,13 @@ export class AntigravityRuntime {
716
726
  this.assertActive()
717
727
  conv = await this.acquireConversation(key)
718
728
  this.assertOwner(proc, conv)
719
- conv.lastUsed = this.monotonicNow()
729
+ conv.lastUsedMs = this.monotonicNow()
720
730
  conv.idleMs = 0
721
731
  const split = splitSystem(options)
722
732
  const tools = toBridgeTools(options.tools)
723
733
  conv.toolNames = new Set(tools.map((t) => t.name))
724
734
  const requestedEffort =
725
735
  asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort
726
- let effort = this.effectiveEffort(options.model, requestedEffort)
727
736
 
728
737
  if (options.signal?.aborted) {
729
738
  this.dropTurn(conv, 'The harness cancelled this request.')
@@ -736,17 +745,22 @@ export class AntigravityRuntime {
736
745
  }
737
746
  return
738
747
  }
739
- if (conv.turn !== undefined && conv.turn.pendingCalls.size > 0) {
748
+ if (conv.turn !== undefined && conv.turn.pendingCallCount > 0) {
740
749
  // Resuming a parked turn is only valid while the request still starts
741
750
  // with the exact history and model/effort selection this ACP session
742
751
  // already owns. A compaction checkpoint, pruned/rewritten prefix, or
743
752
  // model/effort change means the live session is stale, so abandon the
744
753
  // turn and let plan() rebuild from Pi's authoritative history.
745
- const resumedEffort = clampEffortToOptions(conv.configOptions, effort)
754
+ const live = conv.session
755
+ const resumedEffort = clampEffortToOptions(
756
+ live?.configOptions ?? [],
757
+ this.effectiveEffort(options.model, requestedEffort),
758
+ )
746
759
  if (
760
+ live === undefined ||
747
761
  !this.historyPrefixIntact(conv, split.system, split.messages) ||
748
- conv.model !== options.model ||
749
- conv.effort !== resumedEffort
762
+ live.model !== options.model ||
763
+ live.effort !== resumedEffort
750
764
  ) {
751
765
  this.dropTurn(
752
766
  conv,
@@ -778,7 +792,7 @@ export class AntigravityRuntime {
778
792
  let plan = this.plan(conv, split.system, split.messages)
779
793
  let supplementalTools: readonly BridgeTool[] = []
780
794
  let resumed = false
781
- if (conv.sessionId === undefined) {
795
+ if (conv.session === undefined) {
782
796
  const resumable = this.resumableSessions.get(conv.key)
783
797
  if (resumable !== undefined) {
784
798
  this.resumableSessions.delete(conv.key)
@@ -801,7 +815,6 @@ export class AntigravityRuntime {
801
815
  supplementalTools = resumedTools
802
816
  plan = { rebuild: false, history: [], input: resumeInput }
803
817
  resumed = true
804
- effort = this.effectiveEffort(options.model, requestedEffort)
805
818
  }
806
819
  }
807
820
  }
@@ -809,15 +822,22 @@ export class AntigravityRuntime {
809
822
  if (!resumed) {
810
823
  if (plan.rebuild) await this.resetSession(conv)
811
824
  this.assertOwner(proc, conv)
812
- if (conv.sessionId === undefined) {
825
+ if (conv.session === undefined) {
813
826
  conv.systemHash = digest(split.system)
814
827
  supplementalTools = await this.openSession(conv, tools, proc)
815
- effort = this.effectiveEffort(options.model, requestedEffort)
816
828
  }
817
829
  }
818
- this.assertOwner(proc, conv, conv.sessionId)
819
- effort = await this.select(conv, proc, options.model, effort)
820
- this.assertOwner(proc, conv, conv.sessionId)
830
+ const session = conv.session
831
+ if (session === undefined)
832
+ throw new LlmError('Conversation ownership changed', 'TRANSPORT')
833
+ this.assertOwner(proc, conv, session.sessionId)
834
+ const effort = await this.select(
835
+ conv,
836
+ proc,
837
+ options.model,
838
+ this.effectiveEffort(options.model, requestedEffort),
839
+ )
840
+ this.assertOwner(proc, conv, session.sessionId)
821
841
  let blocks: AcpPromptBlock[]
822
842
  let preludes: AcpPromptBlock[][] = []
823
843
  if (plan.rebuild) {
@@ -837,7 +857,7 @@ export class AntigravityRuntime {
837
857
  if (toolInstructions.length > 0)
838
858
  blocks.unshift({ type: 'text', text: toolInstructions })
839
859
  }
840
- const toolDelta = consumeToolDelta(conv, tools)
860
+ const toolDelta = consumeToolDelta(session, tools)
841
861
  if (toolDelta.length > 0)
842
862
  blocks.unshift({ type: 'text', text: `${toolDelta}\n\n` })
843
863
  }
@@ -849,9 +869,9 @@ export class AntigravityRuntime {
849
869
  if (
850
870
  preludes.length > 0 &&
851
871
  options.signal?.aborted &&
852
- this.owns(proc, conv, conv.sessionId)
872
+ this.owns(proc, conv, session.sessionId)
853
873
  )
854
- conv.dirty = true
874
+ conv.needsRebuild = true
855
875
  if (options.signal?.aborted) {
856
876
  this.dropTurn(conv, 'The harness cancelled this request.')
857
877
  yield {
@@ -866,14 +886,14 @@ export class AntigravityRuntime {
866
886
  conv.knownIds = messageIds(split.messages)
867
887
  // A new turn starts with an empty reported-identity space: ids from past
868
888
  // turns must never back a fresh permission request.
869
- conv.reportedToolCalls.clear()
889
+ session.reportedToolCalls.clear()
870
890
  const turn = conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
871
891
  this.startPrompt(conv, turn, proc, blocks)
872
892
  yield* this.pump(conv, turn, proc, options, effort)
873
893
  } finally {
874
894
  try {
875
895
  if (conv !== undefined) {
876
- conv.opening = false
896
+ conv.inUse = false
877
897
  await this.afterStep(conv)
878
898
  }
879
899
  } finally {
@@ -897,8 +917,8 @@ export class AntigravityRuntime {
897
917
  this.assertActive()
898
918
  const existing = this.conversations.get(key)
899
919
  if (existing !== undefined) {
900
- existing.opening = true
901
- existing.lastUsed = this.monotonicNow()
920
+ existing.inUse = true
921
+ existing.lastUsedMs = this.monotonicNow()
902
922
  existing.idleMs = 0
903
923
  return existing
904
924
  }
@@ -910,16 +930,16 @@ export class AntigravityRuntime {
910
930
  this.assertActive()
911
931
  const again = this.conversations.get(key)
912
932
  if (again !== undefined) {
913
- again.opening = true
914
- again.lastUsed = this.monotonicNow()
933
+ again.inUse = true
934
+ again.lastUsedMs = this.monotonicNow()
915
935
  again.idleMs = 0
916
936
  return again
917
937
  }
918
938
  const max = Math.max(1, this.host.config.maxLiveSessions)
919
939
  if (this.conversations.size >= max) {
920
940
  const idle = [...this.conversations.values()]
921
- .filter((c) => c.turn === undefined && !c.opening)
922
- .sort((a, b) => a.lastUsed - b.lastUsed)
941
+ .filter((c) => c.turn === undefined && !c.inUse)
942
+ .sort((a, b) => a.lastUsedMs - b.lastUsedMs)
923
943
  while (this.conversations.size >= max && idle.length > 0) {
924
944
  const victim = idle.shift() as Conversation
925
945
  this.conversations.delete(victim.key)
@@ -934,7 +954,7 @@ export class AntigravityRuntime {
934
954
  )
935
955
  }
936
956
  const conv = this.createConversation(key)
937
- conv.opening = true
957
+ conv.inUse = true
938
958
  return conv
939
959
  } finally {
940
960
  unlock()
@@ -944,27 +964,16 @@ export class AntigravityRuntime {
944
964
  private createConversation(key: string): Conversation {
945
965
  const conv: Conversation = {
946
966
  key,
947
- tenantKey: undefined,
948
- tenantSecret: undefined,
949
- sessionId: undefined,
950
- process: undefined,
951
- configOptions: [],
967
+ session: undefined,
952
968
  systemHash: undefined,
953
- advertisedTools: [],
954
- advertisedToolDigests: new Map(),
955
- knownTools: new Map(),
956
969
  toolNames: new Set(),
957
- reportedToolCalls: new Map(),
958
- opening: false,
970
+ inUse: false,
959
971
  knownIds: undefined,
960
972
  issuedIds: new Set(),
961
973
  turn: undefined,
962
- dirty: false,
963
- lastUsed: this.monotonicNow(),
974
+ needsRebuild: false,
975
+ lastUsedMs: this.monotonicNow(),
964
976
  idleMs: 0,
965
- model: undefined,
966
- metaFloorIdx: 0,
967
- effort: undefined,
968
977
  }
969
978
  this.conversations.set(key, conv)
970
979
  return conv
@@ -1084,17 +1093,17 @@ export class AntigravityRuntime {
1084
1093
  if (current && this.lifecycle === 'active') {
1085
1094
  this.state = 'error'
1086
1095
  this.lastError = error.message
1087
- this.host.log.warn(`antigravity-acp: ${error.message}`)
1096
+ this.host.log.warn(error.message)
1088
1097
  }
1089
1098
  for (const conv of this.conversations.values()) {
1090
- if (conv.process !== proc) continue
1099
+ if (conv.session?.process !== proc) continue
1091
1100
  conv.turn?.fail(new LlmError(
1092
1101
  `Antigravity ACP process exited: ${error.message}`,
1093
1102
  'TRANSPORT',
1094
1103
  ))
1095
1104
  conv.turn = undefined
1096
1105
  this.clearSession(conv)
1097
- conv.dirty = true
1106
+ conv.needsRebuild = true
1098
1107
  }
1099
1108
  }
1100
1109
 
@@ -1117,7 +1126,7 @@ export class AntigravityRuntime {
1117
1126
  } catch (error) {
1118
1127
  if (error instanceof JsonRpcRemoteError && this.owns(proc, conv)) {
1119
1128
  this.host.log.warn(
1120
- `antigravity-acp: session/resume failed for ${resumable.sessionId} (${error.message}); falling back to session/new`,
1129
+ `session/resume failed for ${resumable.sessionId} (${error.message}); falling back to session/new`,
1121
1130
  )
1122
1131
  this.clearSession(conv)
1123
1132
  removeSessionArtifacts(this.home, resumable.sessionId)
@@ -1138,17 +1147,15 @@ export class AntigravityRuntime {
1138
1147
  syncOAuthToken(this.home)
1139
1148
  } catch (error) {
1140
1149
  this.host.log.warn(
1141
- `antigravity-acp: OAuth token sync skipped: ${error instanceof Error ? error.message : String(error)}`,
1150
+ `OAuth token sync skipped: ${error instanceof Error ? error.message : String(error)}`,
1142
1151
  )
1143
1152
  }
1144
- conv.reportedToolCalls.clear()
1153
+ this.clearSession(conv)
1145
1154
  const compacted = tools.map(compactBridgeTool)
1146
1155
  const supplementalTools = tools.filter(
1147
1156
  (raw, index) => compacted[index] !== raw,
1148
1157
  )
1149
- conv.advertisedTools = compacted
1150
- conv.advertisedToolDigests = new Map(tools.map((t) => [t.name, digest(t)]))
1151
- conv.knownTools = new Map(conv.advertisedToolDigests)
1158
+ const advertisedToolDigests = new Map(tools.map((t) => [t.name, digest(t)]))
1152
1159
  const tenantKey = randomBytes(16).toString('hex')
1153
1160
  const tenantSecret = randomBytes(24).toString('hex')
1154
1161
  const mcpServers = [
@@ -1159,9 +1166,11 @@ export class AntigravityRuntime {
1159
1166
  headers: [{ name: 'Authorization', value: `Bearer ${tenantSecret}` }],
1160
1167
  },
1161
1168
  ]
1162
- conv.tenantKey = tenantKey
1163
- conv.tenantSecret = tenantSecret
1164
- this.tenants.set(tenantKey, conv)
1169
+ this.tenants.set(tenantKey, {
1170
+ conv,
1171
+ secret: tenantSecret,
1172
+ advertisedTools: compacted,
1173
+ })
1165
1174
  const params: Record<string, unknown> = {
1166
1175
  ...(resumable !== undefined ? { sessionId: resumable.sessionId } : {}),
1167
1176
  cwd: this.preflight?.workspace ?? this.home,
@@ -1176,25 +1185,31 @@ export class AntigravityRuntime {
1176
1185
  }
1177
1186
  const listener = {
1178
1187
  onUpdate: (update: AcpSessionUpdate) => {
1179
- if (!this.owns(proc, conv) || conv.tenantKey !== tenantKey) return
1188
+ const session = conv.session
1189
+ if (
1190
+ !this.owns(proc, conv) ||
1191
+ session === undefined ||
1192
+ session.tenantKey !== tenantKey
1193
+ )
1194
+ return
1180
1195
  if (
1181
1196
  update.sessionUpdate === 'config_option_update' &&
1182
1197
  Array.isArray(update.configOptions)
1183
1198
  ) {
1184
- conv.configOptions = update.configOptions
1199
+ session.configOptions = update.configOptions
1185
1200
  if (this.catalog.observe(update.configOptions))
1186
1201
  this.host.onModelsChanged()
1187
1202
  }
1188
- if (recordReportedToolCall(conv, update) === 'conflict') {
1203
+ if (recordReportedToolCall(session, update) === 'conflict') {
1189
1204
  this.host.log.warn(
1190
- `antigravity-acp: agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
1205
+ `agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
1191
1206
  )
1192
1207
  }
1193
1208
  conv.turn?.onUpdate(update)
1194
1209
  if (update.sessionUpdate === 'usage_update') {
1195
1210
  const hasCachedContextWindow =
1196
- conv.model !== undefined &&
1197
- this.catalog.contextWindowFor(conv.model) !== undefined
1211
+ session.model !== undefined &&
1212
+ this.catalog.contextWindowFor(session.model) !== undefined
1198
1213
  const hasPositiveUsed =
1199
1214
  typeof update.used === 'number' &&
1200
1215
  Number.isFinite(update.used) &&
@@ -1202,19 +1217,19 @@ export class AntigravityRuntime {
1202
1217
  if (!(hasCachedContextWindow && hasPositiveUsed)) {
1203
1218
  this.harvestSessionTurnData(
1204
1219
  conv,
1205
- conv.sessionId,
1206
- conv.model,
1207
- conv.metaFloorIdx,
1220
+ session.sessionId,
1221
+ session.model,
1222
+ session.metaFloorIdx,
1208
1223
  {
1209
1224
  turn: conv.turn,
1210
- ifChangedSince: conv.lastDbStamp,
1225
+ ifChangedSince: session.lastDbStamp,
1211
1226
  },
1212
1227
  )
1213
1228
  }
1214
1229
  }
1215
1230
  },
1216
1231
  onPermission: (request: AcpPermissionRequest) =>
1217
- this.owns(proc, conv) && conv.tenantKey === tenantKey
1232
+ this.owns(proc, conv) && conv.session?.tenantKey === tenantKey
1218
1233
  ? this.answerPermission(conv, request)
1219
1234
  : ({ outcome: 'cancelled' } as const),
1220
1235
  }
@@ -1225,18 +1240,28 @@ export class AntigravityRuntime {
1225
1240
  : await proc.newSession(params, listener, 120_000)
1226
1241
  // A buffered session reply can resolve after its process has exited.
1227
1242
  if (!this.owns(proc, conv)) {
1243
+ this.tenants.delete(tenantKey)
1244
+ this.bridge.forgetTenant(tenantKey)
1228
1245
  await this.closeAndCleanSession(proc, result.sessionId)
1229
1246
  this.assertActive()
1230
1247
  throw new LlmError('Conversation ownership changed', 'TRANSPORT')
1231
1248
  }
1232
- conv.sessionId = result.sessionId
1233
- conv.process = proc
1234
- conv.configOptions = result.configOptions ?? []
1235
- conv.model = undefined
1236
- conv.metaFloorIdx = 0
1237
- conv.lastDbStamp = undefined
1238
- conv.effort = undefined
1239
- conv.dirty = false
1249
+ conv.session = {
1250
+ sessionId: result.sessionId,
1251
+ process: proc,
1252
+ tenantKey,
1253
+ tenantSecret,
1254
+ configOptions: result.configOptions ?? [],
1255
+ advertisedTools: compacted,
1256
+ advertisedToolDigests,
1257
+ knownTools: new Map(advertisedToolDigests),
1258
+ reportedToolCalls: new Map(),
1259
+ model: undefined,
1260
+ effort: undefined,
1261
+ metaFloorIdx: 0,
1262
+ lastDbStamp: undefined,
1263
+ }
1264
+ conv.needsRebuild = false
1240
1265
  if (resumable !== undefined) {
1241
1266
  conv.systemHash = resumable.systemHash
1242
1267
  conv.knownIds = [...resumable.knownIds]
@@ -1254,6 +1279,8 @@ export class AntigravityRuntime {
1254
1279
  this.host.onModelsChanged()
1255
1280
  return supplementalTools
1256
1281
  } catch (error) {
1282
+ this.tenants.delete(tenantKey)
1283
+ this.bridge.forgetTenant(tenantKey)
1257
1284
  this.clearSession(conv)
1258
1285
  if (resumable !== undefined) throw error
1259
1286
  throw mapError(error)
@@ -1266,7 +1293,7 @@ export class AntigravityRuntime {
1266
1293
  bearerToken: string | undefined,
1267
1294
  ): boolean {
1268
1295
  if (tenantKey === undefined || bearerToken === undefined) return false
1269
- const secret = this.tenants.get(tenantKey)?.tenantSecret
1296
+ const secret = this.tenants.get(tenantKey)?.secret
1270
1297
  if (secret === undefined) return false
1271
1298
  const left = Buffer.from(bearerToken, 'utf8')
1272
1299
  const right = Buffer.from(secret, 'utf8')
@@ -1277,13 +1304,6 @@ export class AntigravityRuntime {
1277
1304
  return timingSafeEqual(left, right)
1278
1305
  }
1279
1306
 
1280
- /** Drop one conversation's tenant registration together with its bridge handshake evidence. */
1281
- private releaseTenant(conv: Conversation): void {
1282
- if (conv.tenantKey === undefined) return
1283
- this.tenants.delete(conv.tenantKey)
1284
- this.bridge.forgetTenant(conv.tenantKey)
1285
- }
1286
-
1287
1307
  /**
1288
1308
  * Decide one `session/request_permission` from structured host-reported
1289
1309
  * metadata only. `title` and `rawInput` are never matched against tool
@@ -1298,8 +1318,7 @@ export class AntigravityRuntime {
1298
1318
  if (!Array.isArray(request.options)) return undefined
1299
1319
  const option = request.options.find(
1300
1320
  (o) =>
1301
- o !== null &&
1302
- typeof o === 'object' &&
1321
+ isRecord(o) &&
1303
1322
  o.kind === kind &&
1304
1323
  typeof o.optionId === 'string',
1305
1324
  )
@@ -1309,20 +1328,19 @@ export class AntigravityRuntime {
1309
1328
  }
1310
1329
  const reject = (reason: string): AcpPermissionOutcome => {
1311
1330
  this.host.log.warn(
1312
- `antigravity-acp: refused permission request (${reason}): ${request.toolCall?.title || request.toolCall?.name || 'unknown'}`,
1331
+ `refused permission request (${reason}): ${request.toolCall?.title || request.toolCall?.name || 'unknown'}`,
1313
1332
  )
1314
1333
  return pick('reject_once') ?? { outcome: 'cancelled' }
1315
1334
  }
1316
- if (conv.sessionId === undefined || request.sessionId !== conv.sessionId)
1335
+ const session = conv.session
1336
+ if (session === undefined || request.sessionId !== session.sessionId)
1317
1337
  return reject('session mismatch')
1318
- if (conv.tenantKey === undefined)
1319
- return reject('no MCP bridge is mounted for this session')
1320
1338
  if (conv.turn === undefined || conv.turn.finished)
1321
1339
  return reject('no live turn')
1322
1340
  const toolCallId = request.toolCall?.toolCallId
1323
1341
  if (typeof toolCallId !== 'string' || toolCallId.length === 0)
1324
1342
  return reject('missing toolCallId')
1325
- const reported = conv.reportedToolCalls.get(toolCallId)
1343
+ const reported = session.reportedToolCalls.get(toolCallId)
1326
1344
  const claimed = structuredToolMeta(request.toolCall)
1327
1345
  if (claimed.conflict === true) {
1328
1346
  return reject('conflicting tool metadata in permission request')
@@ -1341,7 +1359,7 @@ export class AntigravityRuntime {
1341
1359
  request.toolCall?.kind === 'other' &&
1342
1360
  isEmptyInput(request.toolCall.rawInput)
1343
1361
  ) {
1344
- if (!this.bridge.hasHandshake(conv.tenantKey)) {
1362
+ if (!this.bridge.hasHandshake(session.tenantKey)) {
1345
1363
  return reject('identity-less probe without a completed MCP handshake')
1346
1364
  }
1347
1365
  return pick('allow_once') ?? { outcome: 'cancelled' }
@@ -1367,7 +1385,7 @@ export class AntigravityRuntime {
1367
1385
  return reject(`unknown MCP server ${reported.serverName ?? '(none)'}`)
1368
1386
  const isAllowedTool =
1369
1387
  reported.toolName !== undefined &&
1370
- (conv.advertisedToolDigests.has(reported.toolName) ||
1388
+ (session.advertisedToolDigests.has(reported.toolName) ||
1371
1389
  reported.toolName === AWAIT_TOOL_NAME ||
1372
1390
  reported.toolName === CALL_TOOL_NAME)
1373
1391
  if (!isAllowedTool) {
@@ -1384,9 +1402,12 @@ export class AntigravityRuntime {
1384
1402
  model: string,
1385
1403
  effort: Effort,
1386
1404
  ): Promise<Effort> {
1387
- const sessionId = conv.sessionId as string
1405
+ const session = conv.session
1406
+ if (session === undefined)
1407
+ throw new LlmError('Conversation ownership changed', 'TRANSPORT')
1408
+ const { sessionId } = session
1388
1409
  this.assertOwner(proc, conv, sessionId)
1389
- const modelOption = findConfigOption(conv.configOptions, 'model')
1410
+ const modelOption = findConfigOption(session.configOptions, 'model')
1390
1411
  const modelValues =
1391
1412
  modelOption?.options !== undefined
1392
1413
  ? flattenConfigOptions(modelOption.options)
@@ -1400,32 +1421,32 @@ export class AntigravityRuntime {
1400
1421
  'UNKNOWN_MODEL',
1401
1422
  )
1402
1423
  }
1403
- const previousModel = conv.model
1404
- const previousFloor = conv.metaFloorIdx
1424
+ const previousModel = session.model
1425
+ const previousFloor = session.metaFloorIdx
1405
1426
  if (previousModel !== undefined && previousModel !== model) {
1406
1427
  this.harvestSessionTurnData(conv, sessionId, previousModel, previousFloor)
1407
- conv.metaFloorIdx = null
1408
- conv.lastDbStamp = undefined
1428
+ session.metaFloorIdx = null
1429
+ session.lastDbStamp = undefined
1409
1430
  }
1410
- if (conv.model !== model && modelOption?.currentValue !== model) {
1431
+ if (session.model !== model && modelOption?.currentValue !== model) {
1411
1432
  await this.applyConfigOption(
1412
1433
  conv,
1413
1434
  proc,
1414
- sessionId,
1435
+ session,
1415
1436
  modelOption?.id ?? 'model',
1416
1437
  model,
1417
1438
  )
1418
1439
  }
1419
1440
  if (previousModel !== undefined && previousModel !== model) {
1420
1441
  const cursors = readSessionCursors(this.home, sessionId)
1421
- conv.metaFloorIdx =
1442
+ session.metaFloorIdx =
1422
1443
  previousFloor === null || cursors === null
1423
1444
  ? null
1424
1445
  : Math.max(previousFloor, cursors.nextMetaIdx)
1425
- conv.lastDbStamp = undefined
1446
+ session.lastDbStamp = undefined
1426
1447
  }
1427
- conv.model = model
1428
- const levelOption = findConfigOption(conv.configOptions, 'thought_level')
1448
+ session.model = model
1449
+ const levelOption = findConfigOption(session.configOptions, 'thought_level')
1429
1450
  const offeredEfforts = offeredEffortsFrom(levelOption)
1430
1451
  const targetEffort =
1431
1452
  offeredEfforts !== undefined && offeredEfforts.length > 0
@@ -1439,28 +1460,29 @@ export class AntigravityRuntime {
1439
1460
  this.catalog.supportsEffortSelection(model) &&
1440
1461
  levelOption !== undefined &&
1441
1462
  (offeredEfforts === undefined || offeredEfforts.length > 0) &&
1442
- conv.effort !== targetEffort &&
1463
+ session.effort !== targetEffort &&
1443
1464
  levelOption.currentValue !== targetEffort
1444
1465
  ) {
1445
1466
  await this.applyConfigOption(
1446
1467
  conv,
1447
1468
  proc,
1448
- sessionId,
1469
+ session,
1449
1470
  levelOption.id,
1450
1471
  targetEffort,
1451
1472
  )
1452
1473
  }
1453
- conv.effort = targetEffort
1474
+ session.effort = targetEffort
1454
1475
  return targetEffort
1455
1476
  }
1456
1477
 
1457
1478
  private async applyConfigOption(
1458
1479
  conv: Conversation,
1459
1480
  proc: AcpProcess,
1460
- sessionId: string,
1481
+ session: LiveSession,
1461
1482
  optionId: string,
1462
1483
  value: string,
1463
1484
  ): Promise<void> {
1485
+ const { sessionId } = session
1464
1486
  const configOptions = await proc
1465
1487
  .setConfigOption(sessionId, optionId, value)
1466
1488
  .catch((error: unknown) => {
@@ -1469,12 +1491,12 @@ export class AntigravityRuntime {
1469
1491
  error.rpc.code === -32002 &&
1470
1492
  this.owns(proc, conv, sessionId)
1471
1493
  ) {
1472
- conv.dirty = true
1494
+ conv.needsRebuild = true
1473
1495
  }
1474
1496
  throw mapError(error)
1475
1497
  })
1476
1498
  this.assertOwner(proc, conv, sessionId)
1477
- conv.configOptions = configOptions
1499
+ session.configOptions = configOptions
1478
1500
  if (this.catalog.observe(configOptions)) {
1479
1501
  this.host.onModelsChanged()
1480
1502
  }
@@ -1485,7 +1507,7 @@ export class AntigravityRuntime {
1485
1507
  system: string,
1486
1508
  messages: readonly RequestMessage[],
1487
1509
  ): PromptPlan {
1488
- if (conv.sessionId !== undefined && !conv.dirty) {
1510
+ if (conv.session !== undefined && !conv.needsRebuild) {
1489
1511
  const input = this.deltaInput(conv, system, messages)
1490
1512
  if (input !== undefined) {
1491
1513
  return { rebuild: false, history: [], input }
@@ -1616,21 +1638,27 @@ export class AntigravityRuntime {
1616
1638
  }
1617
1639
 
1618
1640
  private async evictIdleSession(conv: Conversation): Promise<void> {
1619
- this.harvestSessionTurnData(conv, conv.sessionId, conv.model, conv.metaFloorIdx, {
1620
- ifChangedSince: conv.lastDbStamp,
1621
- })
1641
+ const session = conv.session
1642
+ if (session !== undefined) {
1643
+ this.harvestSessionTurnData(
1644
+ conv,
1645
+ session.sessionId,
1646
+ session.model,
1647
+ session.metaFloorIdx,
1648
+ { ifChangedSince: session.lastDbStamp },
1649
+ )
1650
+ }
1622
1651
  const canPark =
1623
- conv.sessionId !== undefined &&
1652
+ session !== undefined &&
1624
1653
  conv.systemHash !== undefined &&
1625
- !conv.dirty &&
1654
+ !conv.needsRebuild &&
1626
1655
  conv.knownIds !== undefined &&
1627
1656
  !conv.key.startsWith('anon-')
1628
1657
  if (!canPark) {
1629
1658
  await this.resetSession(conv)
1630
1659
  return
1631
1660
  }
1632
- const sessionId = conv.sessionId as string
1633
- const proc = conv.process
1661
+ const { sessionId, process: proc } = session
1634
1662
  this.parkResumableSession(conv.key, {
1635
1663
  sessionId,
1636
1664
  systemHash: conv.systemHash as string,
@@ -1639,39 +1667,36 @@ export class AntigravityRuntime {
1639
1667
  })
1640
1668
  this.clearSession(conv)
1641
1669
  conv.knownIds = undefined
1642
- conv.dirty = false
1643
- if (proc !== undefined) {
1644
- await proc.closeSession(sessionId)
1645
- }
1670
+ conv.needsRebuild = false
1671
+ await proc.closeSession(sessionId)
1646
1672
  }
1647
1673
 
1648
1674
  private async resetSession(conv: Conversation): Promise<void> {
1649
1675
  this.dropResumableSession(conv.key)
1650
- this.harvestSessionTurnData(conv, conv.sessionId, conv.model, conv.metaFloorIdx, {
1651
- ifChangedSince: conv.lastDbStamp,
1652
- })
1676
+ const session = conv.session
1653
1677
  let closing: Promise<void> | undefined
1654
- if (conv.sessionId !== undefined && conv.process !== undefined) {
1655
- closing = this.closeAndCleanSession(conv.process, conv.sessionId)
1678
+ if (session !== undefined) {
1679
+ this.harvestSessionTurnData(
1680
+ conv,
1681
+ session.sessionId,
1682
+ session.model,
1683
+ session.metaFloorIdx,
1684
+ { ifChangedSince: session.lastDbStamp },
1685
+ )
1686
+ closing = this.closeAndCleanSession(session.process, session.sessionId)
1656
1687
  }
1657
1688
  this.clearSession(conv)
1658
1689
  conv.knownIds = undefined
1659
- conv.dirty = false
1690
+ conv.needsRebuild = false
1660
1691
  await closing
1661
1692
  }
1662
1693
 
1663
1694
  private clearSession(conv: Conversation): void {
1664
- this.releaseTenant(conv)
1665
- conv.sessionId = undefined
1666
- conv.tenantKey = undefined
1667
- conv.tenantSecret = undefined
1668
- conv.process = undefined
1669
- conv.metaFloorIdx = null
1670
- conv.lastDbStamp = undefined
1671
- conv.advertisedTools = []
1672
- conv.advertisedToolDigests.clear()
1673
- conv.knownTools.clear()
1674
- conv.reportedToolCalls.clear()
1695
+ const session = conv.session
1696
+ conv.session = undefined
1697
+ if (session === undefined) return
1698
+ this.tenants.delete(session.tenantKey)
1699
+ this.bridge.forgetTenant(session.tenantKey)
1675
1700
  }
1676
1701
 
1677
1702
  /**
@@ -1685,10 +1710,13 @@ export class AntigravityRuntime {
1685
1710
  blocks: AcpPromptBlock[],
1686
1711
  signal: AbortSignal | undefined,
1687
1712
  ): Promise<void> {
1688
- this.assertOwner(proc, conv, conv.sessionId)
1689
- const sessionId = conv.sessionId as string
1713
+ const session = conv.session
1714
+ if (session === undefined)
1715
+ throw new LlmError('Conversation ownership changed', 'TRANSPORT')
1716
+ const { sessionId } = session
1717
+ this.assertOwner(proc, conv, sessionId)
1690
1718
  if (signal?.aborted) {
1691
- conv.dirty = true
1719
+ conv.needsRebuild = true
1692
1720
  return
1693
1721
  }
1694
1722
  const cancel = () => proc.cancel(sessionId)
@@ -1699,18 +1727,18 @@ export class AntigravityRuntime {
1699
1727
  new AcpTurn(`prelude-${randomBytes(4).toString('hex')}`),
1700
1728
  proc,
1701
1729
  sessionId,
1702
- conv.model,
1703
- conv.metaFloorIdx,
1730
+ session.model,
1731
+ session.metaFloorIdx,
1704
1732
  blocks,
1705
1733
  )
1706
1734
  if (
1707
1735
  (result.stopReason === 'cancelled' || signal?.aborted) &&
1708
1736
  this.owns(proc, conv, sessionId)
1709
1737
  ) {
1710
- conv.dirty = true
1738
+ conv.needsRebuild = true
1711
1739
  }
1712
1740
  } catch (error) {
1713
- if (this.owns(proc, conv, sessionId)) conv.dirty = true
1741
+ if (this.owns(proc, conv, sessionId)) conv.needsRebuild = true
1714
1742
  throw mapError(error)
1715
1743
  } finally {
1716
1744
  signal?.removeEventListener('abort', cancel)
@@ -1727,18 +1755,18 @@ export class AntigravityRuntime {
1727
1755
  // AcpProcess.prompt's link() can throw before returning a promise (buffered reply + exit).
1728
1756
  // Queue that failure too, so every allocated turn reaches the pump's cleanup owner.
1729
1757
  try {
1730
- this.assertOwner(proc, conv, conv.sessionId)
1731
- const sessionId = conv.sessionId as string
1732
- const model = conv.model
1733
- const modelFloor = conv.metaFloorIdx
1758
+ const session = conv.session
1759
+ if (session === undefined)
1760
+ throw new LlmError('Conversation ownership changed', 'TRANSPORT')
1761
+ this.assertOwner(proc, conv, session.sessionId)
1734
1762
  turn.bindPrompt(
1735
1763
  this.runPromptSegment(
1736
1764
  conv,
1737
1765
  turn,
1738
1766
  proc,
1739
- sessionId,
1740
- model,
1741
- modelFloor,
1767
+ session.sessionId,
1768
+ session.model,
1769
+ session.metaFloorIdx,
1742
1770
  blocks,
1743
1771
  ),
1744
1772
  { mapError },
@@ -1755,8 +1783,8 @@ export class AntigravityRuntime {
1755
1783
  options: GenerateOptions,
1756
1784
  effort: Effort,
1757
1785
  ): AsyncGenerator<StreamChunk> {
1758
- const sessionId = conv.sessionId as string
1759
- const metaFloorIdx = conv.metaFloorIdx
1786
+ const sessionId = conv.session?.sessionId
1787
+ const metaFloorIdx = conv.session?.metaFloorIdx ?? null
1760
1788
  let finishKind: string | undefined
1761
1789
  let drained = false
1762
1790
  const cancel = () => {
@@ -1797,8 +1825,12 @@ export class AntigravityRuntime {
1797
1825
  {
1798
1826
  parkSettleMs: this.host.config.parkSettleMs,
1799
1827
  maxContinuations: this.host.config.longDecodeContinuations,
1800
- continuePrompt: () =>
1801
- this.runPromptSegment(
1828
+ continuePrompt: () => {
1829
+ if (sessionId === undefined)
1830
+ return Promise.reject(
1831
+ new LlmError('Conversation ownership changed', 'TRANSPORT'),
1832
+ )
1833
+ return this.runPromptSegment(
1802
1834
  conv,
1803
1835
  turn,
1804
1836
  proc,
@@ -1806,9 +1838,11 @@ export class AntigravityRuntime {
1806
1838
  options.model,
1807
1839
  metaFloorIdx,
1808
1840
  [{ type: 'text', text: CONTINUE_PROMPT }],
1809
- ),
1841
+ )
1842
+ },
1810
1843
  cancel: () => {
1811
- if (conv.turn === turn) proc.cancel(sessionId)
1844
+ if (conv.turn === turn && sessionId !== undefined)
1845
+ proc.cancel(sessionId)
1812
1846
  },
1813
1847
  },
1814
1848
  signal,
@@ -1825,7 +1859,7 @@ export class AntigravityRuntime {
1825
1859
  this.catalog.contextWindowFor(options.model) === undefined)
1826
1860
  ) {
1827
1861
  this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1828
- ifChangedSince: conv.lastDbStamp,
1862
+ ifChangedSince: conv.session?.lastDbStamp,
1829
1863
  })
1830
1864
  }
1831
1865
  }
@@ -1836,7 +1870,7 @@ export class AntigravityRuntime {
1836
1870
  if (interrupted !== undefined && finishKind !== 'aborted') {
1837
1871
  finishKind = 'aborted'
1838
1872
  this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1839
- ifChangedSince: conv.lastDbStamp,
1873
+ ifChangedSince: conv.session?.lastDbStamp,
1840
1874
  })
1841
1875
  yield interrupted
1842
1876
  }
@@ -1844,7 +1878,7 @@ export class AntigravityRuntime {
1844
1878
  } catch (error) {
1845
1879
  finishKind = 'error'
1846
1880
  this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1847
- ifChangedSince: conv.lastDbStamp,
1881
+ ifChangedSince: conv.session?.lastDbStamp,
1848
1882
  })
1849
1883
  throw mapError(error)
1850
1884
  } finally {
@@ -1859,7 +1893,7 @@ export class AntigravityRuntime {
1859
1893
  this.dropTurn(conv, 'The harness ended this request.')
1860
1894
  else {
1861
1895
  turn.abandon('The turn completed.')
1862
- conv.reportedToolCalls.clear()
1896
+ conv.session?.reportedToolCalls.clear()
1863
1897
  conv.turn = undefined
1864
1898
  }
1865
1899
  }
@@ -1886,25 +1920,28 @@ export class AntigravityRuntime {
1886
1920
  proc: AcpProcess,
1887
1921
  tools: readonly BridgeTool[],
1888
1922
  ): AcpTurn | undefined {
1889
- this.assertOwner(proc, conv, conv.sessionId)
1923
+ const session = conv.session
1924
+ if (session === undefined)
1925
+ throw new LlmError('Conversation ownership changed', 'TRANSPORT')
1926
+ this.assertOwner(proc, conv, session.sessionId)
1890
1927
  const turn = conv.turn as AcpTurn
1891
1928
  const results = new Map<string, Extract<RequestMessage, { role: 'tool' }>>()
1892
1929
  let last = -1
1893
1930
  messages.forEach((message, index) => {
1894
1931
  if (
1895
1932
  message.role === 'tool' &&
1896
- turn.pendingCalls.has(message.toolCallId)
1933
+ turn.isPendingCall(message.toolCallId)
1897
1934
  ) {
1898
1935
  results.set(message.toolCallId, message)
1899
1936
  last = Math.max(last, index)
1900
1937
  }
1901
1938
  })
1902
- if (results.size !== turn.pendingCalls.size) return undefined
1939
+ if (results.size !== turn.pendingCallCount) return undefined
1903
1940
  const extras = messages.slice(last + 1)
1904
1941
  if (extras.some((m) => m.role === 'assistant' || m.role === 'tool'))
1905
1942
  return undefined
1906
1943
  const extraText = extras.length > 0 ? renderTranscript(extras) : ''
1907
- const toolDelta = consumeToolDelta(conv, tools)
1944
+ const toolDelta = consumeToolDelta(session, tools)
1908
1945
  const suffix = [toolDelta, extraText].filter(Boolean).join('\n\n')
1909
1946
  const bridgeResults = new Map<string, BridgeToolResult>()
1910
1947
  for (const [id, message] of results) {
@@ -1921,7 +1958,7 @@ export class AntigravityRuntime {
1921
1958
  )
1922
1959
  // The old turn is over: its reported identities do not carry into the continuation.
1923
1960
  turn.abandon('The agent ended the tool-waiting prompt.')
1924
- conv.reportedToolCalls.clear()
1961
+ session.reportedToolCalls.clear()
1925
1962
  const next = conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
1926
1963
  this.startPrompt(conv, next, proc, [
1927
1964
  {
@@ -1955,30 +1992,30 @@ export class AntigravityRuntime {
1955
1992
  return { content: items, ...(isError ? { isError: true } : {}) }
1956
1993
  }
1957
1994
 
1958
- /** Release residual work for the Pi run that owns this session. */
1959
- settleSession(sessionId: string): void {
1960
- const conv = this.conversations.get(sessionId)
1995
+ /** Release residual work for the Pi run that owns this conversation. */
1996
+ settleSession(conversationKey: string): void {
1997
+ const conv = this.conversations.get(conversationKey)
1961
1998
  if (conv !== undefined) this.dropTurn(conv, 'The owning Pi run settled.')
1962
1999
  }
1963
2000
 
1964
2001
  private dropTurn(conv: Conversation, reason: string): void {
1965
2002
  const turn = conv.turn
1966
2003
  if (turn === undefined) return
1967
- if (!turn.finished && conv.sessionId !== undefined)
1968
- conv.process?.cancel(conv.sessionId)
2004
+ if (!turn.finished && conv.session !== undefined)
2005
+ conv.session.process.cancel(conv.session.sessionId)
1969
2006
  conv.turn = undefined
1970
2007
  turn.abandon(reason)
1971
- conv.dirty = true
1972
- conv.reportedToolCalls.clear()
2008
+ conv.needsRebuild = true
2009
+ conv.session?.reportedToolCalls.clear()
1973
2010
  }
1974
2011
 
1975
2012
  /** A conversation is idle only when no turn is running and no session is opening. */
1976
2013
  private isIdle(conv: Conversation): boolean {
1977
- return conv.turn === undefined && !conv.opening
2014
+ return conv.turn === undefined && !conv.inUse
1978
2015
  }
1979
2016
 
1980
2017
  private async afterStep(conv: Conversation): Promise<void> {
1981
- conv.lastUsed = this.monotonicNow()
2018
+ conv.lastUsedMs = this.monotonicNow()
1982
2019
  conv.idleMs = 0
1983
2020
  this.processIdleMs = 0
1984
2021
  const idle = this.isIdle(conv)
@@ -1990,7 +2027,7 @@ export class AntigravityRuntime {
1990
2027
  // A failed opening leaves an unusable empty shell: release its capacity slot.
1991
2028
  if (
1992
2029
  idle &&
1993
- conv.sessionId === undefined &&
2030
+ conv.session === undefined &&
1994
2031
  this.conversations.get(conv.key) === conv
1995
2032
  ) {
1996
2033
  this.conversations.delete(conv.key)
@@ -1998,27 +2035,27 @@ export class AntigravityRuntime {
1998
2035
  }
1999
2036
 
2000
2037
  private listTools(tenantKey: string | undefined): BridgeTool[] {
2001
- const conv =
2038
+ const binding =
2002
2039
  tenantKey === undefined ? undefined : this.tenants.get(tenantKey)
2003
- if (conv === undefined) return []
2004
- return [...conv.advertisedTools, AWAIT_TOOL, CALL_TOOL]
2040
+ if (binding === undefined) return []
2041
+ return [...binding.advertisedTools, AWAIT_TOOL, CALL_TOOL]
2005
2042
  }
2006
2043
 
2007
2044
  private async callTool(
2008
2045
  request: BridgeCallRequest,
2009
2046
  ): Promise<BridgeToolResult> {
2010
2047
  // Only the tenant mounted for this exact conversation may drive its tools;
2011
- // a bare `conversationId` never grants routing on its own.
2048
+ // a bare `acpSessionId` never grants routing on its own.
2012
2049
  const conv =
2013
2050
  request.tenantKey !== undefined
2014
- ? this.tenants.get(request.tenantKey)
2051
+ ? this.tenants.get(request.tenantKey)?.conv
2015
2052
  : undefined
2016
2053
  if (conv === undefined)
2017
2054
  return toolError('No harness turn is waiting for this tool call.')
2055
+ const session = conv.session
2018
2056
  if (
2019
- request.conversationId !== undefined &&
2020
- (conv.sessionId === undefined ||
2021
- request.conversationId !== conv.sessionId)
2057
+ request.acpSessionId !== undefined &&
2058
+ (session === undefined || request.acpSessionId !== session.sessionId)
2022
2059
  )
2023
2060
  return toolError('Tenant session mismatch.')
2024
2061
  const turn = conv.turn
@@ -2027,7 +2064,7 @@ export class AntigravityRuntime {
2027
2064
  const relayAfterMs =
2028
2065
  this.host.relayAfterMs ??
2029
2066
  this.host.config.relayAfterMs ??
2030
- defaults.relayAfterMs
2067
+ DEFAULT_CONFIG.relayAfterMs
2031
2068
  if (request.name === AWAIT_TOOL_NAME) {
2032
2069
  const callId =
2033
2070
  typeof request.arguments.call_id === 'string'
@@ -2053,12 +2090,7 @@ export class AntigravityRuntime {
2053
2090
  ? rawTarget.slice(AGENT_TOOL_PREFIX.length)
2054
2091
  : rawTarget
2055
2092
  const rawArgs = request.arguments.arguments
2056
- args =
2057
- rawArgs !== null &&
2058
- typeof rawArgs === 'object' &&
2059
- !Array.isArray(rawArgs)
2060
- ? (rawArgs as Record<string, unknown>)
2061
- : {}
2093
+ args = isRecord(rawArgs) ? rawArgs : {}
2062
2094
  }
2063
2095
  if (!conv.toolNames.has(name))
2064
2096
  return toolError(`The harness has no tool named ${name}.`)
@@ -2080,7 +2112,7 @@ export class AntigravityRuntime {
2080
2112
 
2081
2113
  private hasLiveConversations(): boolean {
2082
2114
  for (const conv of this.conversations.values()) {
2083
- if (conv.sessionId !== undefined || !this.isIdle(conv)) return true
2115
+ if (conv.session !== undefined || !this.isIdle(conv)) return true
2084
2116
  }
2085
2117
  return false
2086
2118
  }
@@ -2228,20 +2260,16 @@ export function mapError(error: unknown): Error {
2228
2260
  }
2229
2261
  if (/timeout|timed out|deadline/i.test(message))
2230
2262
  return new LlmError(message, 'TIMEOUT', { cause: error })
2231
- if (
2232
- /context.*(length|window|limit|overflow|exceeded)|too long|token limit|maximum.*tokens/i.test(
2233
- message,
2234
- )
2235
- )
2263
+ if (CONTEXT_WINDOW_RE.test(message))
2236
2264
  return new LlmError(message, 'CONTEXT_WINDOW_EXCEEDED', { cause: error })
2237
- if (/rate.?limit|429|too many requests|overloaded|capacity/i.test(message))
2238
- return new LlmError(message, 'RATE_LIMIT', { cause: error })
2265
+ if (isExplicitQuotaError(message))
2266
+ return new LlmError(message, 'QUOTA', { cause: error })
2239
2267
  if (
2240
- /quota|resource.?exhausted|limit reached|exceeded your|prepaid\s+balance|spend\s+cap|insufficient\s+(?:funds|credits?|balance)|billing\s+(?:limit|exhausted|disabled|required)/i.test(
2268
+ /resource.?exhausted|rate.?limit|429|too many requests|overloaded|capacity/i.test(
2241
2269
  message,
2242
2270
  )
2243
2271
  )
2244
- return new LlmError(message, 'QUOTA', { cause: error })
2272
+ return new LlmError(message, 'RATE_LIMIT', { cause: error })
2245
2273
  if (
2246
2274
  /\binvalid_argument\b|unable to process input image|http\s+400|\(code\s+400\)|invalid\s+(?:image|request|argument)/i.test(
2247
2275
  message,