pi-agy-acp 0.2.6 → 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,19 +43,22 @@ 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,
48
+ openingPrompts,
54
49
  renderSessionInstructions,
55
50
  renderTranscript,
56
- replayPrompt,
57
51
  splitSystem,
58
52
  type AcpPromptBlock,
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,21 +822,31 @@ 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[]
842
+ let preludes: AcpPromptBlock[][] = []
822
843
  if (plan.rebuild) {
823
- blocks = replayPrompt(plan.history, plan.input, {
844
+ const prompts = openingPrompts(plan.history, plan.input, {
824
845
  system: split.system,
825
846
  supplementalTools,
826
847
  })
848
+ blocks = prompts[prompts.length - 1] as AcpPromptBlock[]
849
+ preludes = prompts.slice(0, -1)
827
850
  } else {
828
851
  blocks = inputPrompt(plan.input)
829
852
  if (supplementalTools.length > 0) {
@@ -834,10 +857,21 @@ export class AntigravityRuntime {
834
857
  if (toolInstructions.length > 0)
835
858
  blocks.unshift({ type: 'text', text: toolInstructions })
836
859
  }
837
- const toolDelta = consumeToolDelta(conv, tools)
860
+ const toolDelta = consumeToolDelta(session, tools)
838
861
  if (toolDelta.length > 0)
839
862
  blocks.unshift({ type: 'text', text: `${toolDelta}\n\n` })
840
863
  }
864
+ for (const prelude of preludes) {
865
+ if (options.signal?.aborted) break
866
+ await this.runPrelude(conv, proc, prelude, options.signal)
867
+ }
868
+ // A session holding instructions without its history/input must be rebuilt.
869
+ if (
870
+ preludes.length > 0 &&
871
+ options.signal?.aborted &&
872
+ this.owns(proc, conv, session.sessionId)
873
+ )
874
+ conv.needsRebuild = true
841
875
  if (options.signal?.aborted) {
842
876
  this.dropTurn(conv, 'The harness cancelled this request.')
843
877
  yield {
@@ -852,14 +886,14 @@ export class AntigravityRuntime {
852
886
  conv.knownIds = messageIds(split.messages)
853
887
  // A new turn starts with an empty reported-identity space: ids from past
854
888
  // turns must never back a fresh permission request.
855
- conv.reportedToolCalls.clear()
889
+ session.reportedToolCalls.clear()
856
890
  const turn = conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
857
891
  this.startPrompt(conv, turn, proc, blocks)
858
892
  yield* this.pump(conv, turn, proc, options, effort)
859
893
  } finally {
860
894
  try {
861
895
  if (conv !== undefined) {
862
- conv.opening = false
896
+ conv.inUse = false
863
897
  await this.afterStep(conv)
864
898
  }
865
899
  } finally {
@@ -883,8 +917,8 @@ export class AntigravityRuntime {
883
917
  this.assertActive()
884
918
  const existing = this.conversations.get(key)
885
919
  if (existing !== undefined) {
886
- existing.opening = true
887
- existing.lastUsed = this.monotonicNow()
920
+ existing.inUse = true
921
+ existing.lastUsedMs = this.monotonicNow()
888
922
  existing.idleMs = 0
889
923
  return existing
890
924
  }
@@ -896,16 +930,16 @@ export class AntigravityRuntime {
896
930
  this.assertActive()
897
931
  const again = this.conversations.get(key)
898
932
  if (again !== undefined) {
899
- again.opening = true
900
- again.lastUsed = this.monotonicNow()
933
+ again.inUse = true
934
+ again.lastUsedMs = this.monotonicNow()
901
935
  again.idleMs = 0
902
936
  return again
903
937
  }
904
938
  const max = Math.max(1, this.host.config.maxLiveSessions)
905
939
  if (this.conversations.size >= max) {
906
940
  const idle = [...this.conversations.values()]
907
- .filter((c) => c.turn === undefined && !c.opening)
908
- .sort((a, b) => a.lastUsed - b.lastUsed)
941
+ .filter((c) => c.turn === undefined && !c.inUse)
942
+ .sort((a, b) => a.lastUsedMs - b.lastUsedMs)
909
943
  while (this.conversations.size >= max && idle.length > 0) {
910
944
  const victim = idle.shift() as Conversation
911
945
  this.conversations.delete(victim.key)
@@ -920,7 +954,7 @@ export class AntigravityRuntime {
920
954
  )
921
955
  }
922
956
  const conv = this.createConversation(key)
923
- conv.opening = true
957
+ conv.inUse = true
924
958
  return conv
925
959
  } finally {
926
960
  unlock()
@@ -930,27 +964,16 @@ export class AntigravityRuntime {
930
964
  private createConversation(key: string): Conversation {
931
965
  const conv: Conversation = {
932
966
  key,
933
- tenantKey: undefined,
934
- tenantSecret: undefined,
935
- sessionId: undefined,
936
- process: undefined,
937
- configOptions: [],
967
+ session: undefined,
938
968
  systemHash: undefined,
939
- advertisedTools: [],
940
- advertisedToolDigests: new Map(),
941
- knownTools: new Map(),
942
969
  toolNames: new Set(),
943
- reportedToolCalls: new Map(),
944
- opening: false,
970
+ inUse: false,
945
971
  knownIds: undefined,
946
972
  issuedIds: new Set(),
947
973
  turn: undefined,
948
- dirty: false,
949
- lastUsed: this.monotonicNow(),
974
+ needsRebuild: false,
975
+ lastUsedMs: this.monotonicNow(),
950
976
  idleMs: 0,
951
- model: undefined,
952
- metaFloorIdx: 0,
953
- effort: undefined,
954
977
  }
955
978
  this.conversations.set(key, conv)
956
979
  return conv
@@ -1070,17 +1093,17 @@ export class AntigravityRuntime {
1070
1093
  if (current && this.lifecycle === 'active') {
1071
1094
  this.state = 'error'
1072
1095
  this.lastError = error.message
1073
- this.host.log.warn(`antigravity-acp: ${error.message}`)
1096
+ this.host.log.warn(error.message)
1074
1097
  }
1075
1098
  for (const conv of this.conversations.values()) {
1076
- if (conv.process !== proc) continue
1099
+ if (conv.session?.process !== proc) continue
1077
1100
  conv.turn?.fail(new LlmError(
1078
1101
  `Antigravity ACP process exited: ${error.message}`,
1079
1102
  'TRANSPORT',
1080
1103
  ))
1081
1104
  conv.turn = undefined
1082
1105
  this.clearSession(conv)
1083
- conv.dirty = true
1106
+ conv.needsRebuild = true
1084
1107
  }
1085
1108
  }
1086
1109
 
@@ -1103,7 +1126,7 @@ export class AntigravityRuntime {
1103
1126
  } catch (error) {
1104
1127
  if (error instanceof JsonRpcRemoteError && this.owns(proc, conv)) {
1105
1128
  this.host.log.warn(
1106
- `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`,
1107
1130
  )
1108
1131
  this.clearSession(conv)
1109
1132
  removeSessionArtifacts(this.home, resumable.sessionId)
@@ -1124,17 +1147,15 @@ export class AntigravityRuntime {
1124
1147
  syncOAuthToken(this.home)
1125
1148
  } catch (error) {
1126
1149
  this.host.log.warn(
1127
- `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)}`,
1128
1151
  )
1129
1152
  }
1130
- conv.reportedToolCalls.clear()
1153
+ this.clearSession(conv)
1131
1154
  const compacted = tools.map(compactBridgeTool)
1132
1155
  const supplementalTools = tools.filter(
1133
1156
  (raw, index) => compacted[index] !== raw,
1134
1157
  )
1135
- conv.advertisedTools = compacted
1136
- conv.advertisedToolDigests = new Map(tools.map((t) => [t.name, digest(t)]))
1137
- conv.knownTools = new Map(conv.advertisedToolDigests)
1158
+ const advertisedToolDigests = new Map(tools.map((t) => [t.name, digest(t)]))
1138
1159
  const tenantKey = randomBytes(16).toString('hex')
1139
1160
  const tenantSecret = randomBytes(24).toString('hex')
1140
1161
  const mcpServers = [
@@ -1145,9 +1166,11 @@ export class AntigravityRuntime {
1145
1166
  headers: [{ name: 'Authorization', value: `Bearer ${tenantSecret}` }],
1146
1167
  },
1147
1168
  ]
1148
- conv.tenantKey = tenantKey
1149
- conv.tenantSecret = tenantSecret
1150
- this.tenants.set(tenantKey, conv)
1169
+ this.tenants.set(tenantKey, {
1170
+ conv,
1171
+ secret: tenantSecret,
1172
+ advertisedTools: compacted,
1173
+ })
1151
1174
  const params: Record<string, unknown> = {
1152
1175
  ...(resumable !== undefined ? { sessionId: resumable.sessionId } : {}),
1153
1176
  cwd: this.preflight?.workspace ?? this.home,
@@ -1162,25 +1185,31 @@ export class AntigravityRuntime {
1162
1185
  }
1163
1186
  const listener = {
1164
1187
  onUpdate: (update: AcpSessionUpdate) => {
1165
- 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
1166
1195
  if (
1167
1196
  update.sessionUpdate === 'config_option_update' &&
1168
1197
  Array.isArray(update.configOptions)
1169
1198
  ) {
1170
- conv.configOptions = update.configOptions
1199
+ session.configOptions = update.configOptions
1171
1200
  if (this.catalog.observe(update.configOptions))
1172
1201
  this.host.onModelsChanged()
1173
1202
  }
1174
- if (recordReportedToolCall(conv, update) === 'conflict') {
1203
+ if (recordReportedToolCall(session, update) === 'conflict') {
1175
1204
  this.host.log.warn(
1176
- `antigravity-acp: agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
1205
+ `agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
1177
1206
  )
1178
1207
  }
1179
1208
  conv.turn?.onUpdate(update)
1180
1209
  if (update.sessionUpdate === 'usage_update') {
1181
1210
  const hasCachedContextWindow =
1182
- conv.model !== undefined &&
1183
- this.catalog.contextWindowFor(conv.model) !== undefined
1211
+ session.model !== undefined &&
1212
+ this.catalog.contextWindowFor(session.model) !== undefined
1184
1213
  const hasPositiveUsed =
1185
1214
  typeof update.used === 'number' &&
1186
1215
  Number.isFinite(update.used) &&
@@ -1188,19 +1217,19 @@ export class AntigravityRuntime {
1188
1217
  if (!(hasCachedContextWindow && hasPositiveUsed)) {
1189
1218
  this.harvestSessionTurnData(
1190
1219
  conv,
1191
- conv.sessionId,
1192
- conv.model,
1193
- conv.metaFloorIdx,
1220
+ session.sessionId,
1221
+ session.model,
1222
+ session.metaFloorIdx,
1194
1223
  {
1195
1224
  turn: conv.turn,
1196
- ifChangedSince: conv.lastDbStamp,
1225
+ ifChangedSince: session.lastDbStamp,
1197
1226
  },
1198
1227
  )
1199
1228
  }
1200
1229
  }
1201
1230
  },
1202
1231
  onPermission: (request: AcpPermissionRequest) =>
1203
- this.owns(proc, conv) && conv.tenantKey === tenantKey
1232
+ this.owns(proc, conv) && conv.session?.tenantKey === tenantKey
1204
1233
  ? this.answerPermission(conv, request)
1205
1234
  : ({ outcome: 'cancelled' } as const),
1206
1235
  }
@@ -1211,18 +1240,28 @@ export class AntigravityRuntime {
1211
1240
  : await proc.newSession(params, listener, 120_000)
1212
1241
  // A buffered session reply can resolve after its process has exited.
1213
1242
  if (!this.owns(proc, conv)) {
1243
+ this.tenants.delete(tenantKey)
1244
+ this.bridge.forgetTenant(tenantKey)
1214
1245
  await this.closeAndCleanSession(proc, result.sessionId)
1215
1246
  this.assertActive()
1216
1247
  throw new LlmError('Conversation ownership changed', 'TRANSPORT')
1217
1248
  }
1218
- conv.sessionId = result.sessionId
1219
- conv.process = proc
1220
- conv.configOptions = result.configOptions ?? []
1221
- conv.model = undefined
1222
- conv.metaFloorIdx = 0
1223
- conv.lastDbStamp = undefined
1224
- conv.effort = undefined
1225
- 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
1226
1265
  if (resumable !== undefined) {
1227
1266
  conv.systemHash = resumable.systemHash
1228
1267
  conv.knownIds = [...resumable.knownIds]
@@ -1240,6 +1279,8 @@ export class AntigravityRuntime {
1240
1279
  this.host.onModelsChanged()
1241
1280
  return supplementalTools
1242
1281
  } catch (error) {
1282
+ this.tenants.delete(tenantKey)
1283
+ this.bridge.forgetTenant(tenantKey)
1243
1284
  this.clearSession(conv)
1244
1285
  if (resumable !== undefined) throw error
1245
1286
  throw mapError(error)
@@ -1252,7 +1293,7 @@ export class AntigravityRuntime {
1252
1293
  bearerToken: string | undefined,
1253
1294
  ): boolean {
1254
1295
  if (tenantKey === undefined || bearerToken === undefined) return false
1255
- const secret = this.tenants.get(tenantKey)?.tenantSecret
1296
+ const secret = this.tenants.get(tenantKey)?.secret
1256
1297
  if (secret === undefined) return false
1257
1298
  const left = Buffer.from(bearerToken, 'utf8')
1258
1299
  const right = Buffer.from(secret, 'utf8')
@@ -1263,13 +1304,6 @@ export class AntigravityRuntime {
1263
1304
  return timingSafeEqual(left, right)
1264
1305
  }
1265
1306
 
1266
- /** Drop one conversation's tenant registration together with its bridge handshake evidence. */
1267
- private releaseTenant(conv: Conversation): void {
1268
- if (conv.tenantKey === undefined) return
1269
- this.tenants.delete(conv.tenantKey)
1270
- this.bridge.forgetTenant(conv.tenantKey)
1271
- }
1272
-
1273
1307
  /**
1274
1308
  * Decide one `session/request_permission` from structured host-reported
1275
1309
  * metadata only. `title` and `rawInput` are never matched against tool
@@ -1284,8 +1318,7 @@ export class AntigravityRuntime {
1284
1318
  if (!Array.isArray(request.options)) return undefined
1285
1319
  const option = request.options.find(
1286
1320
  (o) =>
1287
- o !== null &&
1288
- typeof o === 'object' &&
1321
+ isRecord(o) &&
1289
1322
  o.kind === kind &&
1290
1323
  typeof o.optionId === 'string',
1291
1324
  )
@@ -1295,20 +1328,19 @@ export class AntigravityRuntime {
1295
1328
  }
1296
1329
  const reject = (reason: string): AcpPermissionOutcome => {
1297
1330
  this.host.log.warn(
1298
- `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'}`,
1299
1332
  )
1300
1333
  return pick('reject_once') ?? { outcome: 'cancelled' }
1301
1334
  }
1302
- if (conv.sessionId === undefined || request.sessionId !== conv.sessionId)
1335
+ const session = conv.session
1336
+ if (session === undefined || request.sessionId !== session.sessionId)
1303
1337
  return reject('session mismatch')
1304
- if (conv.tenantKey === undefined)
1305
- return reject('no MCP bridge is mounted for this session')
1306
1338
  if (conv.turn === undefined || conv.turn.finished)
1307
1339
  return reject('no live turn')
1308
1340
  const toolCallId = request.toolCall?.toolCallId
1309
1341
  if (typeof toolCallId !== 'string' || toolCallId.length === 0)
1310
1342
  return reject('missing toolCallId')
1311
- const reported = conv.reportedToolCalls.get(toolCallId)
1343
+ const reported = session.reportedToolCalls.get(toolCallId)
1312
1344
  const claimed = structuredToolMeta(request.toolCall)
1313
1345
  if (claimed.conflict === true) {
1314
1346
  return reject('conflicting tool metadata in permission request')
@@ -1327,7 +1359,7 @@ export class AntigravityRuntime {
1327
1359
  request.toolCall?.kind === 'other' &&
1328
1360
  isEmptyInput(request.toolCall.rawInput)
1329
1361
  ) {
1330
- if (!this.bridge.hasHandshake(conv.tenantKey)) {
1362
+ if (!this.bridge.hasHandshake(session.tenantKey)) {
1331
1363
  return reject('identity-less probe without a completed MCP handshake')
1332
1364
  }
1333
1365
  return pick('allow_once') ?? { outcome: 'cancelled' }
@@ -1353,7 +1385,7 @@ export class AntigravityRuntime {
1353
1385
  return reject(`unknown MCP server ${reported.serverName ?? '(none)'}`)
1354
1386
  const isAllowedTool =
1355
1387
  reported.toolName !== undefined &&
1356
- (conv.advertisedToolDigests.has(reported.toolName) ||
1388
+ (session.advertisedToolDigests.has(reported.toolName) ||
1357
1389
  reported.toolName === AWAIT_TOOL_NAME ||
1358
1390
  reported.toolName === CALL_TOOL_NAME)
1359
1391
  if (!isAllowedTool) {
@@ -1370,9 +1402,12 @@ export class AntigravityRuntime {
1370
1402
  model: string,
1371
1403
  effort: Effort,
1372
1404
  ): Promise<Effort> {
1373
- 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
1374
1409
  this.assertOwner(proc, conv, sessionId)
1375
- const modelOption = findConfigOption(conv.configOptions, 'model')
1410
+ const modelOption = findConfigOption(session.configOptions, 'model')
1376
1411
  const modelValues =
1377
1412
  modelOption?.options !== undefined
1378
1413
  ? flattenConfigOptions(modelOption.options)
@@ -1386,32 +1421,32 @@ export class AntigravityRuntime {
1386
1421
  'UNKNOWN_MODEL',
1387
1422
  )
1388
1423
  }
1389
- const previousModel = conv.model
1390
- const previousFloor = conv.metaFloorIdx
1424
+ const previousModel = session.model
1425
+ const previousFloor = session.metaFloorIdx
1391
1426
  if (previousModel !== undefined && previousModel !== model) {
1392
1427
  this.harvestSessionTurnData(conv, sessionId, previousModel, previousFloor)
1393
- conv.metaFloorIdx = null
1394
- conv.lastDbStamp = undefined
1428
+ session.metaFloorIdx = null
1429
+ session.lastDbStamp = undefined
1395
1430
  }
1396
- if (conv.model !== model && modelOption?.currentValue !== model) {
1431
+ if (session.model !== model && modelOption?.currentValue !== model) {
1397
1432
  await this.applyConfigOption(
1398
1433
  conv,
1399
1434
  proc,
1400
- sessionId,
1435
+ session,
1401
1436
  modelOption?.id ?? 'model',
1402
1437
  model,
1403
1438
  )
1404
1439
  }
1405
1440
  if (previousModel !== undefined && previousModel !== model) {
1406
1441
  const cursors = readSessionCursors(this.home, sessionId)
1407
- conv.metaFloorIdx =
1442
+ session.metaFloorIdx =
1408
1443
  previousFloor === null || cursors === null
1409
1444
  ? null
1410
1445
  : Math.max(previousFloor, cursors.nextMetaIdx)
1411
- conv.lastDbStamp = undefined
1446
+ session.lastDbStamp = undefined
1412
1447
  }
1413
- conv.model = model
1414
- const levelOption = findConfigOption(conv.configOptions, 'thought_level')
1448
+ session.model = model
1449
+ const levelOption = findConfigOption(session.configOptions, 'thought_level')
1415
1450
  const offeredEfforts = offeredEffortsFrom(levelOption)
1416
1451
  const targetEffort =
1417
1452
  offeredEfforts !== undefined && offeredEfforts.length > 0
@@ -1425,28 +1460,29 @@ export class AntigravityRuntime {
1425
1460
  this.catalog.supportsEffortSelection(model) &&
1426
1461
  levelOption !== undefined &&
1427
1462
  (offeredEfforts === undefined || offeredEfforts.length > 0) &&
1428
- conv.effort !== targetEffort &&
1463
+ session.effort !== targetEffort &&
1429
1464
  levelOption.currentValue !== targetEffort
1430
1465
  ) {
1431
1466
  await this.applyConfigOption(
1432
1467
  conv,
1433
1468
  proc,
1434
- sessionId,
1469
+ session,
1435
1470
  levelOption.id,
1436
1471
  targetEffort,
1437
1472
  )
1438
1473
  }
1439
- conv.effort = targetEffort
1474
+ session.effort = targetEffort
1440
1475
  return targetEffort
1441
1476
  }
1442
1477
 
1443
1478
  private async applyConfigOption(
1444
1479
  conv: Conversation,
1445
1480
  proc: AcpProcess,
1446
- sessionId: string,
1481
+ session: LiveSession,
1447
1482
  optionId: string,
1448
1483
  value: string,
1449
1484
  ): Promise<void> {
1485
+ const { sessionId } = session
1450
1486
  const configOptions = await proc
1451
1487
  .setConfigOption(sessionId, optionId, value)
1452
1488
  .catch((error: unknown) => {
@@ -1455,12 +1491,12 @@ export class AntigravityRuntime {
1455
1491
  error.rpc.code === -32002 &&
1456
1492
  this.owns(proc, conv, sessionId)
1457
1493
  ) {
1458
- conv.dirty = true
1494
+ conv.needsRebuild = true
1459
1495
  }
1460
1496
  throw mapError(error)
1461
1497
  })
1462
1498
  this.assertOwner(proc, conv, sessionId)
1463
- conv.configOptions = configOptions
1499
+ session.configOptions = configOptions
1464
1500
  if (this.catalog.observe(configOptions)) {
1465
1501
  this.host.onModelsChanged()
1466
1502
  }
@@ -1471,7 +1507,7 @@ export class AntigravityRuntime {
1471
1507
  system: string,
1472
1508
  messages: readonly RequestMessage[],
1473
1509
  ): PromptPlan {
1474
- if (conv.sessionId !== undefined && !conv.dirty) {
1510
+ if (conv.session !== undefined && !conv.needsRebuild) {
1475
1511
  const input = this.deltaInput(conv, system, messages)
1476
1512
  if (input !== undefined) {
1477
1513
  return { rebuild: false, history: [], input }
@@ -1602,21 +1638,27 @@ export class AntigravityRuntime {
1602
1638
  }
1603
1639
 
1604
1640
  private async evictIdleSession(conv: Conversation): Promise<void> {
1605
- this.harvestSessionTurnData(conv, conv.sessionId, conv.model, conv.metaFloorIdx, {
1606
- ifChangedSince: conv.lastDbStamp,
1607
- })
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
+ }
1608
1651
  const canPark =
1609
- conv.sessionId !== undefined &&
1652
+ session !== undefined &&
1610
1653
  conv.systemHash !== undefined &&
1611
- !conv.dirty &&
1654
+ !conv.needsRebuild &&
1612
1655
  conv.knownIds !== undefined &&
1613
1656
  !conv.key.startsWith('anon-')
1614
1657
  if (!canPark) {
1615
1658
  await this.resetSession(conv)
1616
1659
  return
1617
1660
  }
1618
- const sessionId = conv.sessionId as string
1619
- const proc = conv.process
1661
+ const { sessionId, process: proc } = session
1620
1662
  this.parkResumableSession(conv.key, {
1621
1663
  sessionId,
1622
1664
  systemHash: conv.systemHash as string,
@@ -1625,39 +1667,83 @@ export class AntigravityRuntime {
1625
1667
  })
1626
1668
  this.clearSession(conv)
1627
1669
  conv.knownIds = undefined
1628
- conv.dirty = false
1629
- if (proc !== undefined) {
1630
- await proc.closeSession(sessionId)
1631
- }
1670
+ conv.needsRebuild = false
1671
+ await proc.closeSession(sessionId)
1632
1672
  }
1633
1673
 
1634
1674
  private async resetSession(conv: Conversation): Promise<void> {
1635
1675
  this.dropResumableSession(conv.key)
1636
- this.harvestSessionTurnData(conv, conv.sessionId, conv.model, conv.metaFloorIdx, {
1637
- ifChangedSince: conv.lastDbStamp,
1638
- })
1676
+ const session = conv.session
1639
1677
  let closing: Promise<void> | undefined
1640
- if (conv.sessionId !== undefined && conv.process !== undefined) {
1641
- 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)
1642
1687
  }
1643
1688
  this.clearSession(conv)
1644
1689
  conv.knownIds = undefined
1645
- conv.dirty = false
1690
+ conv.needsRebuild = false
1646
1691
  await closing
1647
1692
  }
1648
1693
 
1649
1694
  private clearSession(conv: Conversation): void {
1650
- this.releaseTenant(conv)
1651
- conv.sessionId = undefined
1652
- conv.tenantKey = undefined
1653
- conv.tenantSecret = undefined
1654
- conv.process = undefined
1655
- conv.metaFloorIdx = null
1656
- conv.lastDbStamp = undefined
1657
- conv.advertisedTools = []
1658
- conv.advertisedToolDigests.clear()
1659
- conv.knownTools.clear()
1660
- 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)
1700
+ }
1701
+
1702
+ /**
1703
+ * Deliver one prelude of session instructions before the live turn. No turn
1704
+ * is bound on `conv` while it runs, so streamed chunks are dropped and tool
1705
+ * calls/permissions are refused, while hidden SQLite API errors still surface.
1706
+ */
1707
+ private async runPrelude(
1708
+ conv: Conversation,
1709
+ proc: AcpProcess,
1710
+ blocks: AcpPromptBlock[],
1711
+ signal: AbortSignal | undefined,
1712
+ ): Promise<void> {
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)
1718
+ if (signal?.aborted) {
1719
+ conv.needsRebuild = true
1720
+ return
1721
+ }
1722
+ const cancel = () => proc.cancel(sessionId)
1723
+ signal?.addEventListener('abort', cancel, { once: true })
1724
+ try {
1725
+ const result = await this.runPromptSegment(
1726
+ conv,
1727
+ new AcpTurn(`prelude-${randomBytes(4).toString('hex')}`),
1728
+ proc,
1729
+ sessionId,
1730
+ session.model,
1731
+ session.metaFloorIdx,
1732
+ blocks,
1733
+ )
1734
+ if (
1735
+ (result.stopReason === 'cancelled' || signal?.aborted) &&
1736
+ this.owns(proc, conv, sessionId)
1737
+ ) {
1738
+ conv.needsRebuild = true
1739
+ }
1740
+ } catch (error) {
1741
+ if (this.owns(proc, conv, sessionId)) conv.needsRebuild = true
1742
+ throw mapError(error)
1743
+ } finally {
1744
+ signal?.removeEventListener('abort', cancel)
1745
+ }
1746
+ this.assertOwner(proc, conv, sessionId)
1661
1747
  }
1662
1748
 
1663
1749
  private startPrompt(
@@ -1669,18 +1755,18 @@ export class AntigravityRuntime {
1669
1755
  // AcpProcess.prompt's link() can throw before returning a promise (buffered reply + exit).
1670
1756
  // Queue that failure too, so every allocated turn reaches the pump's cleanup owner.
1671
1757
  try {
1672
- this.assertOwner(proc, conv, conv.sessionId)
1673
- const sessionId = conv.sessionId as string
1674
- const model = conv.model
1675
- 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)
1676
1762
  turn.bindPrompt(
1677
1763
  this.runPromptSegment(
1678
1764
  conv,
1679
1765
  turn,
1680
1766
  proc,
1681
- sessionId,
1682
- model,
1683
- modelFloor,
1767
+ session.sessionId,
1768
+ session.model,
1769
+ session.metaFloorIdx,
1684
1770
  blocks,
1685
1771
  ),
1686
1772
  { mapError },
@@ -1697,8 +1783,8 @@ export class AntigravityRuntime {
1697
1783
  options: GenerateOptions,
1698
1784
  effort: Effort,
1699
1785
  ): AsyncGenerator<StreamChunk> {
1700
- const sessionId = conv.sessionId as string
1701
- const metaFloorIdx = conv.metaFloorIdx
1786
+ const sessionId = conv.session?.sessionId
1787
+ const metaFloorIdx = conv.session?.metaFloorIdx ?? null
1702
1788
  let finishKind: string | undefined
1703
1789
  let drained = false
1704
1790
  const cancel = () => {
@@ -1739,8 +1825,12 @@ export class AntigravityRuntime {
1739
1825
  {
1740
1826
  parkSettleMs: this.host.config.parkSettleMs,
1741
1827
  maxContinuations: this.host.config.longDecodeContinuations,
1742
- continuePrompt: () =>
1743
- this.runPromptSegment(
1828
+ continuePrompt: () => {
1829
+ if (sessionId === undefined)
1830
+ return Promise.reject(
1831
+ new LlmError('Conversation ownership changed', 'TRANSPORT'),
1832
+ )
1833
+ return this.runPromptSegment(
1744
1834
  conv,
1745
1835
  turn,
1746
1836
  proc,
@@ -1748,9 +1838,11 @@ export class AntigravityRuntime {
1748
1838
  options.model,
1749
1839
  metaFloorIdx,
1750
1840
  [{ type: 'text', text: CONTINUE_PROMPT }],
1751
- ),
1841
+ )
1842
+ },
1752
1843
  cancel: () => {
1753
- if (conv.turn === turn) proc.cancel(sessionId)
1844
+ if (conv.turn === turn && sessionId !== undefined)
1845
+ proc.cancel(sessionId)
1754
1846
  },
1755
1847
  },
1756
1848
  signal,
@@ -1767,7 +1859,7 @@ export class AntigravityRuntime {
1767
1859
  this.catalog.contextWindowFor(options.model) === undefined)
1768
1860
  ) {
1769
1861
  this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1770
- ifChangedSince: conv.lastDbStamp,
1862
+ ifChangedSince: conv.session?.lastDbStamp,
1771
1863
  })
1772
1864
  }
1773
1865
  }
@@ -1778,7 +1870,7 @@ export class AntigravityRuntime {
1778
1870
  if (interrupted !== undefined && finishKind !== 'aborted') {
1779
1871
  finishKind = 'aborted'
1780
1872
  this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1781
- ifChangedSince: conv.lastDbStamp,
1873
+ ifChangedSince: conv.session?.lastDbStamp,
1782
1874
  })
1783
1875
  yield interrupted
1784
1876
  }
@@ -1786,7 +1878,7 @@ export class AntigravityRuntime {
1786
1878
  } catch (error) {
1787
1879
  finishKind = 'error'
1788
1880
  this.harvestSessionTurnData(conv, sessionId, options.model, metaFloorIdx, {
1789
- ifChangedSince: conv.lastDbStamp,
1881
+ ifChangedSince: conv.session?.lastDbStamp,
1790
1882
  })
1791
1883
  throw mapError(error)
1792
1884
  } finally {
@@ -1801,7 +1893,7 @@ export class AntigravityRuntime {
1801
1893
  this.dropTurn(conv, 'The harness ended this request.')
1802
1894
  else {
1803
1895
  turn.abandon('The turn completed.')
1804
- conv.reportedToolCalls.clear()
1896
+ conv.session?.reportedToolCalls.clear()
1805
1897
  conv.turn = undefined
1806
1898
  }
1807
1899
  }
@@ -1828,25 +1920,28 @@ export class AntigravityRuntime {
1828
1920
  proc: AcpProcess,
1829
1921
  tools: readonly BridgeTool[],
1830
1922
  ): AcpTurn | undefined {
1831
- 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)
1832
1927
  const turn = conv.turn as AcpTurn
1833
1928
  const results = new Map<string, Extract<RequestMessage, { role: 'tool' }>>()
1834
1929
  let last = -1
1835
1930
  messages.forEach((message, index) => {
1836
1931
  if (
1837
1932
  message.role === 'tool' &&
1838
- turn.pendingCalls.has(message.toolCallId)
1933
+ turn.isPendingCall(message.toolCallId)
1839
1934
  ) {
1840
1935
  results.set(message.toolCallId, message)
1841
1936
  last = Math.max(last, index)
1842
1937
  }
1843
1938
  })
1844
- if (results.size !== turn.pendingCalls.size) return undefined
1939
+ if (results.size !== turn.pendingCallCount) return undefined
1845
1940
  const extras = messages.slice(last + 1)
1846
1941
  if (extras.some((m) => m.role === 'assistant' || m.role === 'tool'))
1847
1942
  return undefined
1848
1943
  const extraText = extras.length > 0 ? renderTranscript(extras) : ''
1849
- const toolDelta = consumeToolDelta(conv, tools)
1944
+ const toolDelta = consumeToolDelta(session, tools)
1850
1945
  const suffix = [toolDelta, extraText].filter(Boolean).join('\n\n')
1851
1946
  const bridgeResults = new Map<string, BridgeToolResult>()
1852
1947
  for (const [id, message] of results) {
@@ -1863,7 +1958,7 @@ export class AntigravityRuntime {
1863
1958
  )
1864
1959
  // The old turn is over: its reported identities do not carry into the continuation.
1865
1960
  turn.abandon('The agent ended the tool-waiting prompt.')
1866
- conv.reportedToolCalls.clear()
1961
+ session.reportedToolCalls.clear()
1867
1962
  const next = conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
1868
1963
  this.startPrompt(conv, next, proc, [
1869
1964
  {
@@ -1897,30 +1992,30 @@ export class AntigravityRuntime {
1897
1992
  return { content: items, ...(isError ? { isError: true } : {}) }
1898
1993
  }
1899
1994
 
1900
- /** Release residual work for the Pi run that owns this session. */
1901
- settleSession(sessionId: string): void {
1902
- 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)
1903
1998
  if (conv !== undefined) this.dropTurn(conv, 'The owning Pi run settled.')
1904
1999
  }
1905
2000
 
1906
2001
  private dropTurn(conv: Conversation, reason: string): void {
1907
2002
  const turn = conv.turn
1908
2003
  if (turn === undefined) return
1909
- if (!turn.finished && conv.sessionId !== undefined)
1910
- conv.process?.cancel(conv.sessionId)
2004
+ if (!turn.finished && conv.session !== undefined)
2005
+ conv.session.process.cancel(conv.session.sessionId)
1911
2006
  conv.turn = undefined
1912
2007
  turn.abandon(reason)
1913
- conv.dirty = true
1914
- conv.reportedToolCalls.clear()
2008
+ conv.needsRebuild = true
2009
+ conv.session?.reportedToolCalls.clear()
1915
2010
  }
1916
2011
 
1917
2012
  /** A conversation is idle only when no turn is running and no session is opening. */
1918
2013
  private isIdle(conv: Conversation): boolean {
1919
- return conv.turn === undefined && !conv.opening
2014
+ return conv.turn === undefined && !conv.inUse
1920
2015
  }
1921
2016
 
1922
2017
  private async afterStep(conv: Conversation): Promise<void> {
1923
- conv.lastUsed = this.monotonicNow()
2018
+ conv.lastUsedMs = this.monotonicNow()
1924
2019
  conv.idleMs = 0
1925
2020
  this.processIdleMs = 0
1926
2021
  const idle = this.isIdle(conv)
@@ -1932,7 +2027,7 @@ export class AntigravityRuntime {
1932
2027
  // A failed opening leaves an unusable empty shell: release its capacity slot.
1933
2028
  if (
1934
2029
  idle &&
1935
- conv.sessionId === undefined &&
2030
+ conv.session === undefined &&
1936
2031
  this.conversations.get(conv.key) === conv
1937
2032
  ) {
1938
2033
  this.conversations.delete(conv.key)
@@ -1940,27 +2035,27 @@ export class AntigravityRuntime {
1940
2035
  }
1941
2036
 
1942
2037
  private listTools(tenantKey: string | undefined): BridgeTool[] {
1943
- const conv =
2038
+ const binding =
1944
2039
  tenantKey === undefined ? undefined : this.tenants.get(tenantKey)
1945
- if (conv === undefined) return []
1946
- return [...conv.advertisedTools, AWAIT_TOOL, CALL_TOOL]
2040
+ if (binding === undefined) return []
2041
+ return [...binding.advertisedTools, AWAIT_TOOL, CALL_TOOL]
1947
2042
  }
1948
2043
 
1949
2044
  private async callTool(
1950
2045
  request: BridgeCallRequest,
1951
2046
  ): Promise<BridgeToolResult> {
1952
2047
  // Only the tenant mounted for this exact conversation may drive its tools;
1953
- // a bare `conversationId` never grants routing on its own.
2048
+ // a bare `acpSessionId` never grants routing on its own.
1954
2049
  const conv =
1955
2050
  request.tenantKey !== undefined
1956
- ? this.tenants.get(request.tenantKey)
2051
+ ? this.tenants.get(request.tenantKey)?.conv
1957
2052
  : undefined
1958
2053
  if (conv === undefined)
1959
2054
  return toolError('No harness turn is waiting for this tool call.')
2055
+ const session = conv.session
1960
2056
  if (
1961
- request.conversationId !== undefined &&
1962
- (conv.sessionId === undefined ||
1963
- request.conversationId !== conv.sessionId)
2057
+ request.acpSessionId !== undefined &&
2058
+ (session === undefined || request.acpSessionId !== session.sessionId)
1964
2059
  )
1965
2060
  return toolError('Tenant session mismatch.')
1966
2061
  const turn = conv.turn
@@ -1969,7 +2064,7 @@ export class AntigravityRuntime {
1969
2064
  const relayAfterMs =
1970
2065
  this.host.relayAfterMs ??
1971
2066
  this.host.config.relayAfterMs ??
1972
- defaults.relayAfterMs
2067
+ DEFAULT_CONFIG.relayAfterMs
1973
2068
  if (request.name === AWAIT_TOOL_NAME) {
1974
2069
  const callId =
1975
2070
  typeof request.arguments.call_id === 'string'
@@ -1995,12 +2090,7 @@ export class AntigravityRuntime {
1995
2090
  ? rawTarget.slice(AGENT_TOOL_PREFIX.length)
1996
2091
  : rawTarget
1997
2092
  const rawArgs = request.arguments.arguments
1998
- args =
1999
- rawArgs !== null &&
2000
- typeof rawArgs === 'object' &&
2001
- !Array.isArray(rawArgs)
2002
- ? (rawArgs as Record<string, unknown>)
2003
- : {}
2093
+ args = isRecord(rawArgs) ? rawArgs : {}
2004
2094
  }
2005
2095
  if (!conv.toolNames.has(name))
2006
2096
  return toolError(`The harness has no tool named ${name}.`)
@@ -2022,7 +2112,7 @@ export class AntigravityRuntime {
2022
2112
 
2023
2113
  private hasLiveConversations(): boolean {
2024
2114
  for (const conv of this.conversations.values()) {
2025
- if (conv.sessionId !== undefined || !this.isIdle(conv)) return true
2115
+ if (conv.session !== undefined || !this.isIdle(conv)) return true
2026
2116
  }
2027
2117
  return false
2028
2118
  }
@@ -2170,20 +2260,16 @@ export function mapError(error: unknown): Error {
2170
2260
  }
2171
2261
  if (/timeout|timed out|deadline/i.test(message))
2172
2262
  return new LlmError(message, 'TIMEOUT', { cause: error })
2173
- if (
2174
- /context.*(length|window|limit|overflow|exceeded)|too long|token limit|maximum.*tokens/i.test(
2175
- message,
2176
- )
2177
- )
2263
+ if (CONTEXT_WINDOW_RE.test(message))
2178
2264
  return new LlmError(message, 'CONTEXT_WINDOW_EXCEEDED', { cause: error })
2179
- if (/rate.?limit|429|too many requests|overloaded|capacity/i.test(message))
2180
- return new LlmError(message, 'RATE_LIMIT', { cause: error })
2265
+ if (isExplicitQuotaError(message))
2266
+ return new LlmError(message, 'QUOTA', { cause: error })
2181
2267
  if (
2182
- /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(
2183
2269
  message,
2184
2270
  )
2185
2271
  )
2186
- return new LlmError(message, 'QUOTA', { cause: error })
2272
+ return new LlmError(message, 'RATE_LIMIT', { cause: error })
2187
2273
  if (
2188
2274
  /\binvalid_argument\b|unable to process input image|http\s+400|\(code\s+400\)|invalid\s+(?:image|request|argument)/i.test(
2189
2275
  message,