pi-agy-acp 0.1.4 → 0.2.1

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
@@ -25,7 +25,11 @@ import {
25
25
  type AcpPromptResult,
26
26
  type AcpSpawner,
27
27
  } from './acp-process.ts'
28
- import { ModelCatalog, nearestEffort } from './catalog.ts'
28
+ import {
29
+ flattenConfigOptions,
30
+ ModelCatalog,
31
+ nearestEffort,
32
+ } from './catalog.ts'
29
33
  import { asEffort, defaults, type Config, type Effort } from './config.ts'
30
34
  import {
31
35
  AcpTurn,
@@ -33,8 +37,6 @@ import {
33
37
  AWAIT_TOOL_NAME,
34
38
  CALL_TOOL,
35
39
  pumpStep,
36
- relayNotice,
37
- type ParkedCall,
38
40
  type ReportedToolCall,
39
41
  structuredToolMeta,
40
42
  recordReportedToolCall,
@@ -64,11 +66,13 @@ import {
64
66
  } from './mcp-bridge.ts'
65
67
  import {
66
68
  assertSupportedAgyVersion,
69
+ binaryFingerprint,
67
70
  BRIDGE_AGENT,
71
+ defaultAgyHomes,
68
72
  defaultHome,
69
- GPT_OSS_CONTEXT_WINDOW,
70
- DEFAULT_CONTEXT_WINDOW,
71
73
  prepareHome,
74
+ readSessionContextMetadata,
75
+ readSessionNextMetadataIndex,
72
76
  removeSessionArtifacts,
73
77
  readVersion,
74
78
  resolveAgyBinary,
@@ -108,13 +112,14 @@ export interface RuntimeStatus {
108
112
  version?: string
109
113
  home: string
110
114
  account?: AccountInfo
111
- contextWindow: number
115
+ contextWindow?: number
112
116
  defaultEffort: Effort
113
117
  models: {
114
118
  id: string
115
119
  name: string
116
120
  efforts: readonly Effort[]
117
121
  fixedEffort?: Effort
122
+ contextWindow?: number
118
123
  }[]
119
124
  efforts: string[]
120
125
  liveSessions: number
@@ -154,6 +159,8 @@ interface Conversation {
154
159
  dirty: boolean
155
160
  lastUsed: number
156
161
  model: string | undefined
162
+ /** Lower `gen_metadata.idx` bound for `model`, or `null` when unobservable after a failed cursor read. */
163
+ metaFloorIdx: number | null
157
164
  effort: Effort | undefined
158
165
  }
159
166
 
@@ -170,8 +177,10 @@ export class AntigravityRuntime {
170
177
  readonly quota: QuotaReader
171
178
  private readonly home: string
172
179
  private process: AcpProcess | undefined
180
+ private processFingerprint: string | undefined
173
181
  private starting: Promise<AcpProcess> | undefined
174
182
  private preflight: PreflightResult | undefined
183
+ private preflightFingerprint: string | undefined
175
184
  private preflightPromise: Promise<PreflightResult> | undefined
176
185
  private state: RuntimeStatus['state'] = 'idle'
177
186
  private lastError: string | undefined
@@ -193,7 +202,10 @@ export class AntigravityRuntime {
193
202
  constructor(host: RuntimeHost) {
194
203
  this.host = host
195
204
  this.home = host.config.home.length > 0 ? host.config.home : defaultHome()
196
- this.catalog = new ModelCatalog(join(this.home, 'catalog.json'))
205
+ this.catalog = new ModelCatalog(
206
+ join(this.home, 'catalog.json'),
207
+ this.currentBinaryFingerprint(),
208
+ )
197
209
  this.bridge = new McpBridge(
198
210
  {
199
211
  listTools: (tenantKey) => this.listTools(tenantKey),
@@ -214,9 +226,82 @@ export class AntigravityRuntime {
214
226
  }
215
227
 
216
228
  contextWindowFor(model: string): number {
217
- return model.startsWith('gpt-oss')
218
- ? GPT_OSS_CONTEXT_WINDOW
219
- : DEFAULT_CONTEXT_WINDOW
229
+ return this.catalog.contextWindowFor(model) ?? 0
230
+ }
231
+
232
+ private currentBinaryFingerprint(binary?: string): string | undefined {
233
+ try {
234
+ return binaryFingerprint(
235
+ binary ?? resolveAgyBinary(this.host.config.command),
236
+ )
237
+ } catch {
238
+ return undefined
239
+ }
240
+ }
241
+
242
+ private reconcileBinaryFingerprint(binary?: string): void {
243
+ const fp = this.currentBinaryFingerprint(binary)
244
+ if (fp === undefined) return
245
+ if (
246
+ this.preflight !== undefined &&
247
+ this.preflightFingerprint !== undefined &&
248
+ this.preflightFingerprint !== fp
249
+ ) {
250
+ this.preflight = undefined
251
+ this.preflightFingerprint = undefined
252
+ }
253
+ if (
254
+ this.process?.alive &&
255
+ this.starting === undefined &&
256
+ this.processFingerprint !== undefined &&
257
+ this.processFingerprint !== fp &&
258
+ [...this.conversations.values()].every((c) => this.isIdle(c))
259
+ ) {
260
+ // Restart an idle ACP process after an on-disk `agy` upgrade so discovery probes the new binary.
261
+ const stale = this.process
262
+ this.process = undefined
263
+ this.processFingerprint = undefined
264
+ stale.stop()
265
+ }
266
+ if (this.catalog.syncBinaryFingerprint(fp)) {
267
+ this.host.onModelsChanged()
268
+ }
269
+ }
270
+
271
+ private nextTurnMetadataFloor(
272
+ sessionId: string | undefined,
273
+ modelFloor: number | null,
274
+ ): number | null {
275
+ if (!sessionId || modelFloor === null) return null
276
+ const nextIdx = readSessionNextMetadataIndex(this.home, sessionId)
277
+ return nextIdx === null ? null : Math.max(modelFloor, nextIdx)
278
+ }
279
+
280
+ private observeSessionContextWindow(
281
+ sessionId: string | undefined,
282
+ model: string | undefined,
283
+ minIdx: number | null,
284
+ turn?: AcpTurn,
285
+ ): void {
286
+ if (this.lifecycle !== 'active' || !sessionId) return
287
+ const turnFloor = turn?.metaFloorIdx ?? null
288
+ const turnMeta =
289
+ turn !== undefined && turnFloor !== null
290
+ ? readSessionContextMetadata(this.home, sessionId, turnFloor)
291
+ : undefined
292
+ if (turn !== undefined && turnMeta?.estimatedTokensUsed !== undefined) {
293
+ turn.estimatedContextUsed = turnMeta.estimatedTokensUsed
294
+ }
295
+ if (!model || minIdx === null) return
296
+ const maxContextTokens =
297
+ turnMeta?.maxContextTokens ??
298
+ (turn !== undefined && turnFloor === minIdx
299
+ ? undefined
300
+ : readSessionContextMetadata(this.home, sessionId, minIdx)
301
+ ?.maxContextTokens)
302
+ if (this.catalog.observeContextWindow(model, maxContextTokens)) {
303
+ this.host.onModelsChanged()
304
+ }
220
305
  }
221
306
 
222
307
  /**
@@ -234,9 +319,15 @@ export class AntigravityRuntime {
234
319
 
235
320
  /**
236
321
  * Current status for diagnostics surfaces.
322
+ * @param modelId - optional active provider model id.
237
323
  * @returns the status snapshot.
238
324
  */
239
- status(): RuntimeStatus {
325
+ status(modelId?: string): RuntimeStatus {
326
+ const targetModel = modelId ?? this.lastTurn?.model
327
+ const activeContextWindow =
328
+ targetModel !== undefined
329
+ ? this.catalog.contextWindowFor(targetModel)
330
+ : undefined
240
331
  return {
241
332
  state: this.state,
242
333
  ...(this.lastError !== undefined ? { error: this.lastError } : {}),
@@ -248,13 +339,19 @@ export class AntigravityRuntime {
248
339
  : {}),
249
340
  home: this.home,
250
341
  account: this.accountInfo(),
251
- contextWindow: DEFAULT_CONTEXT_WINDOW,
342
+ ...(activeContextWindow !== undefined
343
+ ? { contextWindow: activeContextWindow }
344
+ : {}),
252
345
  defaultEffort: this.host.config.defaultEffort,
253
- models: this.catalog.list().map((m) => ({
254
- ...m,
255
- efforts: this.catalog.effortsFor(m.id),
256
- fixedEffort: this.catalog.fixedEffort(m.id),
257
- })),
346
+ models: this.catalog.list().map((m) => {
347
+ const contextWindow = this.catalog.contextWindowFor(m.id)
348
+ return {
349
+ ...m,
350
+ efforts: this.catalog.effortsFor(m.id),
351
+ fixedEffort: this.catalog.fixedEffort(m.id),
352
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
353
+ }
354
+ }),
258
355
  efforts: [...this.catalog.effortList()],
259
356
  liveSessions: [...this.conversations.values()].filter(
260
357
  (c) => c.sessionId !== undefined,
@@ -267,11 +364,11 @@ export class AntigravityRuntime {
267
364
  }
268
365
 
269
366
  private accountInfo(): AccountInfo | undefined {
270
- const paths = [join(this.home, 'acp.log')]
367
+ const paths = [join(this.home, 'acp.log'), this.home]
271
368
  if (
272
369
  this.home === join(homedir(), '.pi', 'agent', 'cache', 'antigravity-acp')
273
370
  )
274
- paths.push(join(homedir(), '.gemini', 'antigravity-cli', 'cli.log'))
371
+ paths.push(...defaultAgyHomes())
275
372
  const email = readLoggedEmail(paths)
276
373
  const tier = this.catalog.tier()
277
374
  if (!email && !tier) return undefined
@@ -337,6 +434,7 @@ export class AntigravityRuntime {
337
434
  options.signal?.throwIfAborted()
338
435
  if (this.warmupPromise !== undefined)
339
436
  return abortable(this.warmupPromise, options.signal)
437
+ this.reconcileBinaryFingerprint()
340
438
  if (!options.force && this.catalog.observed) return
341
439
  this.warmupPromise = (async () => {
342
440
  const proc = await this.ensureReady()
@@ -405,6 +503,7 @@ export class AntigravityRuntime {
405
503
  this.tenants.clear()
406
504
  this.process?.stop()
407
505
  this.process = undefined
506
+ this.processFingerprint = undefined
408
507
  this.disposal = (async () => {
409
508
  // Preflight waits are cancellable; binding must finish before closing its listener.
410
509
  await this.starting?.catch(() => undefined)
@@ -464,10 +563,9 @@ export class AntigravityRuntime {
464
563
  const split = splitSystem(options)
465
564
  const tools = toBridgeTools(options.tools)
466
565
  conv.toolNames = new Set(tools.map((t) => t.name))
467
- const effort = this.effectiveEffort(
468
- options.model,
469
- asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort,
470
- )
566
+ const requestedEffort =
567
+ asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort
568
+ let effort = this.effectiveEffort(options.model, requestedEffort)
471
569
 
472
570
  if (options.signal?.aborted) {
473
571
  this.dropTurn(conv, 'The harness cancelled this request.')
@@ -525,6 +623,7 @@ export class AntigravityRuntime {
525
623
  if (conv.sessionId === undefined) {
526
624
  conv.systemHash = digest(split.system)
527
625
  supplementalTools = await this.openSession(conv, tools, proc)
626
+ effort = this.effectiveEffort(options.model, requestedEffort)
528
627
  }
529
628
  this.assertOwner(proc, conv, conv.sessionId)
530
629
  await this.select(conv, proc, options.model, effort)
@@ -643,6 +742,7 @@ export class AntigravityRuntime {
643
742
  dirty: false,
644
743
  lastUsed: Date.now(),
645
744
  model: undefined,
745
+ metaFloorIdx: 0,
646
746
  effort: undefined,
647
747
  }
648
748
  this.conversations.set(key, conv)
@@ -680,16 +780,31 @@ export class AntigravityRuntime {
680
780
  log: (message) => this.host.log.warn(message),
681
781
  })
682
782
  this.process = proc
783
+ this.processFingerprint = binaryFingerprint(preflight.binary)
683
784
  const started = proc
684
785
  proc.onExit((error) => this.onProcessExit(started, error))
685
- await proc.start(120_000)
786
+ const init = await proc.start(120_000)
686
787
  this.assertOwner(proc)
788
+ const agentVersion = init?.agentInfo?.version
789
+ if (typeof agentVersion === 'string' && agentVersion.trim().length > 0) {
790
+ assertSupportedAgyVersion(agentVersion, preflight.binary)
791
+ }
792
+ if (
793
+ this.catalog.observeImageSupport(
794
+ init?.agentCapabilities?.promptCapabilities?.image,
795
+ )
796
+ ) {
797
+ this.host.onModelsChanged()
798
+ }
687
799
  this.state = 'ready'
688
800
  this.lastError = undefined
689
801
  return proc
690
802
  } catch (error) {
691
803
  proc?.stop()
692
- if (this.process === proc) this.process = undefined
804
+ if (this.process === proc) {
805
+ this.process = undefined
806
+ this.processFingerprint = undefined
807
+ }
693
808
  if (this.lifecycle !== 'active') throw this.shutdown.signal.reason
694
809
  await this.bridge.close()
695
810
  this.assertActive()
@@ -702,6 +817,7 @@ export class AntigravityRuntime {
702
817
  }
703
818
 
704
819
  private runPreflight(): Promise<PreflightResult> {
820
+ this.reconcileBinaryFingerprint()
705
821
  if (this.preflight !== undefined) {
706
822
  prepareHome(this.home)
707
823
  return Promise.resolve(this.preflight)
@@ -709,6 +825,7 @@ export class AntigravityRuntime {
709
825
  this.preflightPromise ??= (async () => {
710
826
  const config = this.host.config
711
827
  const binary = resolveAgyBinary(config.command)
828
+ this.reconcileBinaryFingerprint(binary)
712
829
  const version = await readVersion(binary, this.host.runCommand)
713
830
  this.assertActive()
714
831
  assertSupportedAgyVersion(version, binary)
@@ -721,6 +838,7 @@ export class AntigravityRuntime {
721
838
  logFile: join(this.home, 'acp.log'),
722
839
  }
723
840
  this.preflight = result
841
+ this.preflightFingerprint = binaryFingerprint(binary)
724
842
  return result
725
843
  })().finally(() => {
726
844
  this.preflightPromise = undefined
@@ -730,7 +848,10 @@ export class AntigravityRuntime {
730
848
 
731
849
  private onProcessExit(proc: AcpProcess, error: Error): void {
732
850
  const current = this.process === proc
733
- if (current) this.process = undefined
851
+ if (current) {
852
+ this.process = undefined
853
+ this.processFingerprint = undefined
854
+ }
734
855
  if (current && this.lifecycle === 'active') {
735
856
  this.state = 'error'
736
857
  this.lastError = error.message
@@ -803,6 +924,14 @@ export class AntigravityRuntime {
803
924
  if (this.catalog.observe(update.configOptions))
804
925
  this.host.onModelsChanged()
805
926
  }
927
+ if (update.sessionUpdate === 'usage_update') {
928
+ this.observeSessionContextWindow(
929
+ conv.sessionId,
930
+ conv.model,
931
+ conv.metaFloorIdx,
932
+ conv.turn,
933
+ )
934
+ }
806
935
  if (recordReportedToolCall(conv, update) === 'conflict') {
807
936
  this.host.log.warn(
808
937
  `antigravity-acp: agent reported conflicting identity for tool call ${String(update.toolCallId)}`,
@@ -826,6 +955,7 @@ export class AntigravityRuntime {
826
955
  conv.process = proc
827
956
  conv.configOptions = result.configOptions ?? []
828
957
  conv.model = undefined
958
+ conv.metaFloorIdx = 0
829
959
  conv.effort = undefined
830
960
 
831
961
  conv.dirty = false
@@ -967,15 +1097,25 @@ export class AntigravityRuntime {
967
1097
  const modelOption = conv.configOptions.find(
968
1098
  (o) => o.id === 'model' || o.category === 'model',
969
1099
  )
1100
+ const modelValues =
1101
+ modelOption?.options !== undefined
1102
+ ? flattenConfigOptions(modelOption.options)
1103
+ : undefined
970
1104
  if (
971
- modelOption?.options !== undefined &&
972
- !modelOption.options.some((o) => o.value === model)
1105
+ modelValues !== undefined &&
1106
+ !modelValues.some((o) => o.value === model)
973
1107
  ) {
974
1108
  throw new LlmError(
975
- `Antigravity does not offer model "${model}" to this account; available: ${modelOption.options.map((o) => o.value).join(', ')}`,
1109
+ `Antigravity does not offer model "${model}" to this account; available: ${modelValues.map((o) => o.value).join(', ')}`,
976
1110
  'UNKNOWN_MODEL',
977
1111
  )
978
1112
  }
1113
+ const previousModel = conv.model
1114
+ const previousFloor = conv.metaFloorIdx
1115
+ if (previousModel !== undefined && previousModel !== model) {
1116
+ this.observeSessionContextWindow(sessionId, previousModel, previousFloor)
1117
+ conv.metaFloorIdx = null
1118
+ }
979
1119
  if (conv.model !== model && modelOption?.currentValue !== model) {
980
1120
  await this.applyConfigOption(
981
1121
  conv,
@@ -985,15 +1125,21 @@ export class AntigravityRuntime {
985
1125
  model,
986
1126
  )
987
1127
  }
1128
+ if (previousModel !== undefined && previousModel !== model) {
1129
+ const nextIdx = readSessionNextMetadataIndex(this.home, sessionId)
1130
+ conv.metaFloorIdx =
1131
+ previousFloor === null || nextIdx === null
1132
+ ? null
1133
+ : Math.max(previousFloor, nextIdx)
1134
+ }
988
1135
  conv.model = model
989
1136
  const levelOption = conv.configOptions.find(
990
1137
  (o) => o.id === 'thought_level' || o.category === 'thought_level',
991
1138
  )
992
- // Fixed-variant families (GPT-OSS) reject every thought_level change; the
993
- // effort already lives in the model id, so only selectable families write it.
994
- const selectable = this.catalog.effortsFor(model)
1139
+ // Fixed-variant families (GPT-OSS) and single-variant orchestrators reject
1140
+ // thought_level writes, so only selectable families write it.
995
1141
  if (
996
- selectable.length > 0 &&
1142
+ this.catalog.supportsEffortSelection(model) &&
997
1143
  levelOption !== undefined &&
998
1144
  conv.effort !== effort &&
999
1145
  levelOption.currentValue !== effort
@@ -1107,6 +1253,7 @@ export class AntigravityRuntime {
1107
1253
  }
1108
1254
 
1109
1255
  private async resetSession(conv: Conversation): Promise<void> {
1256
+ this.observeSessionContextWindow(conv.sessionId, conv.model, conv.metaFloorIdx)
1110
1257
  let closing: Promise<void> | undefined
1111
1258
  if (conv.sessionId !== undefined && conv.process !== undefined) {
1112
1259
  closing = this.closeAndCleanSession(conv.process, conv.sessionId)
@@ -1123,6 +1270,7 @@ export class AntigravityRuntime {
1123
1270
  conv.tenantKey = undefined
1124
1271
  conv.tenantSecret = undefined
1125
1272
  conv.process = undefined
1273
+ conv.metaFloorIdx = null
1126
1274
  conv.advertisedTools = []
1127
1275
  conv.advertisedToolDigests.clear()
1128
1276
  conv.knownTools.clear()
@@ -1139,10 +1287,15 @@ export class AntigravityRuntime {
1139
1287
  // Queue that failure too, so every allocated turn reaches the pump's cleanup owner.
1140
1288
  try {
1141
1289
  this.assertOwner(proc, conv, conv.sessionId)
1142
- turn.promptSettled = proc.prompt(conv.sessionId as string, blocks).then(
1143
- (result) => turn.events.push({ kind: 'done', result }),
1144
- (error: unknown) => turn.fail(mapError(error)),
1145
- )
1290
+ const sessionId = conv.sessionId as string
1291
+ const model = conv.model
1292
+ const modelFloor = conv.metaFloorIdx
1293
+ turn.metaFloorIdx = this.nextTurnMetadataFloor(sessionId, modelFloor)
1294
+ turn.bindPrompt(proc.prompt(sessionId, blocks), {
1295
+ onSettled: () =>
1296
+ this.observeSessionContextWindow(sessionId, model, modelFloor, turn),
1297
+ mapError,
1298
+ })
1146
1299
  } catch (error) {
1147
1300
  turn.fail(mapError(error))
1148
1301
  }
@@ -1156,6 +1309,7 @@ export class AntigravityRuntime {
1156
1309
  effort: Effort,
1157
1310
  ): AsyncGenerator<StreamChunk> {
1158
1311
  const sessionId = conv.sessionId as string
1312
+ const metaFloorIdx = conv.metaFloorIdx
1159
1313
  let finishKind: string | undefined
1160
1314
  let drained = false
1161
1315
  const cancel = () => {
@@ -1196,8 +1350,33 @@ export class AntigravityRuntime {
1196
1350
  {
1197
1351
  parkSettleMs: this.host.config.parkSettleMs,
1198
1352
  maxContinuations: this.host.config.longDecodeContinuations,
1199
- continuePrompt: () =>
1200
- proc.prompt(sessionId, [{ type: 'text', text: CONTINUE_PROMPT }]),
1353
+ continuePrompt: async () => {
1354
+ turn.metaFloorIdx = this.nextTurnMetadataFloor(
1355
+ sessionId,
1356
+ metaFloorIdx,
1357
+ )
1358
+ turn.estimatedContextUsed = undefined
1359
+ try {
1360
+ const result = await proc.prompt(sessionId, [
1361
+ { type: 'text', text: CONTINUE_PROMPT },
1362
+ ])
1363
+ this.observeSessionContextWindow(
1364
+ sessionId,
1365
+ options.model,
1366
+ metaFloorIdx,
1367
+ turn,
1368
+ )
1369
+ return result
1370
+ } catch (error) {
1371
+ this.observeSessionContextWindow(
1372
+ sessionId,
1373
+ options.model,
1374
+ metaFloorIdx,
1375
+ turn,
1376
+ )
1377
+ throw error
1378
+ }
1379
+ },
1201
1380
  cancel: () => {
1202
1381
  if (conv.turn === turn) proc.cancel(sessionId)
1203
1382
  },
@@ -1208,18 +1387,23 @@ export class AntigravityRuntime {
1208
1387
  const chunk = turn.guard(emitted, signal) as StreamChunk
1209
1388
  if (chunk.type === 'block-end' && chunk.block.type === 'tool-call')
1210
1389
  conv.issuedIds.add(chunk.block.id)
1211
- if (chunk.type === 'finish') finishKind = chunk.reason.kind
1390
+ if (chunk.type === 'finish') {
1391
+ finishKind = chunk.reason.kind
1392
+ this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1393
+ }
1212
1394
  yield chunk
1213
1395
  if (chunk.type === 'finish' && chunk.reason.kind === 'aborted') break
1214
1396
  }
1215
1397
  const interrupted = turn.guard(undefined, signal)
1216
1398
  if (interrupted !== undefined && finishKind !== 'aborted') {
1217
1399
  finishKind = 'aborted'
1400
+ this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1218
1401
  yield interrupted
1219
1402
  }
1220
1403
  drained = true
1221
1404
  } catch (error) {
1222
1405
  finishKind = 'error'
1406
+ this.observeSessionContextWindow(sessionId, options.model, metaFloorIdx)
1223
1407
  throw mapError(error)
1224
1408
  } finally {
1225
1409
  // Only a fully consumed tool handoff keeps the turn and its cancellation owner.
@@ -1280,12 +1464,18 @@ export class AntigravityRuntime {
1280
1464
  const extraText = extras.length > 0 ? renderTranscript(extras) : ''
1281
1465
  const toolDelta = consumeToolDelta(conv, tools)
1282
1466
  const suffix = [toolDelta, extraText].filter(Boolean).join('\n\n')
1283
- const pending = [...turn.pendingCalls.values()]
1284
- turn.pendingCalls.clear()
1285
- if (turn.finished || !this.isTurnLive(turn)) {
1467
+ const bridgeResults = new Map<string, BridgeToolResult>()
1468
+ for (const [id, message] of results) {
1469
+ bridgeResults.set(
1470
+ id,
1471
+ this.toBridgeResult(message.content, message.isError === true),
1472
+ )
1473
+ }
1474
+ const delivery = turn.deliverToolResults(bridgeResults, suffix)
1475
+ if (!delivery.resumed) {
1286
1476
  // The agent ended its turn while the harness ran the tools: hand the results over as new input.
1287
1477
  const transcript = renderTranscript(
1288
- pending.map((call) => results.get(call.id) as RequestMessage),
1478
+ delivery.pending.map((call) => results.get(call.id) as RequestMessage),
1289
1479
  )
1290
1480
  // The old turn is over: its reported identities do not carry into the continuation.
1291
1481
  turn.abandon('The agent ended the tool-waiting prompt.')
@@ -1294,32 +1484,14 @@ export class AntigravityRuntime {
1294
1484
  this.startPrompt(conv, next, proc, [
1295
1485
  {
1296
1486
  type: 'text',
1297
- text: `${transcript}${suffix ? `\n\n${suffix}` : ''}\n\nContinue the task with these tool results.`,
1487
+ text: `${transcript}${delivery.suffix ? `\n\n${delivery.suffix}` : ''}\n\nContinue the task with these tool results.`,
1298
1488
  },
1299
1489
  ])
1300
1490
  return next
1301
1491
  }
1302
- for (const [index, call] of pending.entries()) {
1303
- const message = results.get(call.id) as Extract<
1304
- RequestMessage,
1305
- { role: 'tool' }
1306
- >
1307
- const result = this.toBridgeResult(
1308
- message.content,
1309
- message.isError === true,
1310
- )
1311
- if (index === pending.length - 1 && suffix.length > 0)
1312
- result.content.push({ type: 'text', text: `\n\n${suffix}` })
1313
- call.result.resolve(result)
1314
- }
1315
1492
  return turn
1316
1493
  }
1317
1494
 
1318
- private isTurnLive(turn: AcpTurn): boolean {
1319
- const head = turn.events.peek()
1320
- return head?.kind !== 'done' && head?.kind !== 'error'
1321
- }
1322
-
1323
1495
  private toBridgeResult(
1324
1496
  content: readonly ContentBlock[],
1325
1497
  isError: boolean,
@@ -1411,16 +1583,19 @@ export class AntigravityRuntime {
1411
1583
  const turn = conv.turn
1412
1584
  if (turn === undefined || turn.finished)
1413
1585
  return toolError('No harness turn is waiting for this tool call.')
1586
+ const relayAfterMs =
1587
+ this.host.relayAfterMs ??
1588
+ this.host.config.relayAfterMs ??
1589
+ defaults.relayAfterMs
1414
1590
  if (request.name === AWAIT_TOOL_NAME) {
1415
1591
  const callId =
1416
1592
  typeof request.arguments.call_id === 'string'
1417
1593
  ? request.arguments.call_id
1418
1594
  : ''
1419
- const call = turn.calls.get(callId)
1420
- if (call === undefined)
1421
- return toolError(`Unknown harness call id ${callId}.`)
1422
- turn.resumeRelay(callId)
1423
- return this.awaitCall(turn, call, request.signal)
1595
+ return (
1596
+ turn.awaitRelayedCall(callId, relayAfterMs, request.signal) ??
1597
+ toolError(`Unknown harness call id ${callId}.`)
1598
+ )
1424
1599
  }
1425
1600
  let name = request.name
1426
1601
  let args = request.arguments
@@ -1442,43 +1617,7 @@ export class AntigravityRuntime {
1442
1617
  }
1443
1618
  if (!conv.toolNames.has(name))
1444
1619
  return toolError(`The harness has no tool named ${name}.`)
1445
- return this.awaitCall(turn, turn.park(name, args), request.signal)
1446
- }
1447
-
1448
- private async awaitCall(
1449
- turn: AcpTurn,
1450
- call: ParkedCall,
1451
- signal: AbortSignal,
1452
- ): Promise<BridgeToolResult> {
1453
- let timer: ReturnType<typeof setTimeout> | undefined
1454
- const relayAfterMs =
1455
- this.host.relayAfterMs ??
1456
- this.host.config.relayAfterMs ??
1457
- defaults.relayAfterMs
1458
- const relay = new Promise<'relay'>((resolve) => {
1459
- timer = setTimeout(() => resolve('relay'), relayAfterMs)
1460
- })
1461
- let onAbort: (() => void) | undefined
1462
- const aborted = new Promise<'aborted'>((resolve) => {
1463
- if (signal.aborted) resolve('aborted')
1464
- else {
1465
- onAbort = () => resolve('aborted')
1466
- signal.addEventListener('abort', onAbort, { once: true })
1467
- }
1468
- })
1469
- try {
1470
- const outcome = await Promise.race([call.result.promise, relay, aborted])
1471
- if (outcome === 'relay') {
1472
- turn.markRelayed(call.id)
1473
- return relayNotice(call)
1474
- }
1475
- if (outcome === 'aborted')
1476
- return toolError('The tool call was cancelled.')
1477
- return outcome
1478
- } finally {
1479
- if (timer !== undefined) clearTimeout(timer)
1480
- if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
1481
- }
1620
+ return turn.invokeTool(name, args, relayAfterMs, request.signal)
1482
1621
  }
1483
1622
 
1484
1623
  private sweep(): void {