pi-agy-acp 0.2.0 → 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,10 +66,12 @@ 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
73
  prepareHome,
70
- readSessionMaxContextTokens,
74
+ readSessionContextMetadata,
71
75
  readSessionNextMetadataIndex,
72
76
  removeSessionArtifacts,
73
77
  readVersion,
@@ -173,8 +177,10 @@ export class AntigravityRuntime {
173
177
  readonly quota: QuotaReader
174
178
  private readonly home: string
175
179
  private process: AcpProcess | undefined
180
+ private processFingerprint: string | undefined
176
181
  private starting: Promise<AcpProcess> | undefined
177
182
  private preflight: PreflightResult | undefined
183
+ private preflightFingerprint: string | undefined
178
184
  private preflightPromise: Promise<PreflightResult> | undefined
179
185
  private state: RuntimeStatus['state'] = 'idle'
180
186
  private lastError: string | undefined
@@ -196,7 +202,10 @@ export class AntigravityRuntime {
196
202
  constructor(host: RuntimeHost) {
197
203
  this.host = host
198
204
  this.home = host.config.home.length > 0 ? host.config.home : defaultHome()
199
- this.catalog = new ModelCatalog(join(this.home, 'catalog.json'))
205
+ this.catalog = new ModelCatalog(
206
+ join(this.home, 'catalog.json'),
207
+ this.currentBinaryFingerprint(),
208
+ )
200
209
  this.bridge = new McpBridge(
201
210
  {
202
211
  listTools: (tenantKey) => this.listTools(tenantKey),
@@ -220,21 +229,77 @@ export class AntigravityRuntime {
220
229
  return this.catalog.contextWindowFor(model) ?? 0
221
230
  }
222
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
+
223
280
  private observeSessionContextWindow(
224
281
  sessionId: string | undefined,
225
282
  model: string | undefined,
226
283
  minIdx: number | null,
284
+ turn?: AcpTurn,
227
285
  ): void {
228
- if (
229
- this.lifecycle !== 'active' ||
230
- !sessionId ||
231
- !model ||
232
- minIdx === null
233
- ) {
234
- return
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
235
294
  }
236
- const tokens = readSessionMaxContextTokens(this.home, sessionId, minIdx)
237
- if (this.catalog.observeContextWindow(model, tokens)) {
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)) {
238
303
  this.host.onModelsChanged()
239
304
  }
240
305
  }
@@ -299,11 +364,11 @@ export class AntigravityRuntime {
299
364
  }
300
365
 
301
366
  private accountInfo(): AccountInfo | undefined {
302
- const paths = [join(this.home, 'acp.log')]
367
+ const paths = [join(this.home, 'acp.log'), this.home]
303
368
  if (
304
369
  this.home === join(homedir(), '.pi', 'agent', 'cache', 'antigravity-acp')
305
370
  )
306
- paths.push(join(homedir(), '.gemini', 'antigravity-cli', 'cli.log'))
371
+ paths.push(...defaultAgyHomes())
307
372
  const email = readLoggedEmail(paths)
308
373
  const tier = this.catalog.tier()
309
374
  if (!email && !tier) return undefined
@@ -369,6 +434,7 @@ export class AntigravityRuntime {
369
434
  options.signal?.throwIfAborted()
370
435
  if (this.warmupPromise !== undefined)
371
436
  return abortable(this.warmupPromise, options.signal)
437
+ this.reconcileBinaryFingerprint()
372
438
  if (!options.force && this.catalog.observed) return
373
439
  this.warmupPromise = (async () => {
374
440
  const proc = await this.ensureReady()
@@ -437,6 +503,7 @@ export class AntigravityRuntime {
437
503
  this.tenants.clear()
438
504
  this.process?.stop()
439
505
  this.process = undefined
506
+ this.processFingerprint = undefined
440
507
  this.disposal = (async () => {
441
508
  // Preflight waits are cancellable; binding must finish before closing its listener.
442
509
  await this.starting?.catch(() => undefined)
@@ -496,10 +563,9 @@ export class AntigravityRuntime {
496
563
  const split = splitSystem(options)
497
564
  const tools = toBridgeTools(options.tools)
498
565
  conv.toolNames = new Set(tools.map((t) => t.name))
499
- const effort = this.effectiveEffort(
500
- options.model,
501
- asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort,
502
- )
566
+ const requestedEffort =
567
+ asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort
568
+ let effort = this.effectiveEffort(options.model, requestedEffort)
503
569
 
504
570
  if (options.signal?.aborted) {
505
571
  this.dropTurn(conv, 'The harness cancelled this request.')
@@ -557,6 +623,7 @@ export class AntigravityRuntime {
557
623
  if (conv.sessionId === undefined) {
558
624
  conv.systemHash = digest(split.system)
559
625
  supplementalTools = await this.openSession(conv, tools, proc)
626
+ effort = this.effectiveEffort(options.model, requestedEffort)
560
627
  }
561
628
  this.assertOwner(proc, conv, conv.sessionId)
562
629
  await this.select(conv, proc, options.model, effort)
@@ -713,16 +780,31 @@ export class AntigravityRuntime {
713
780
  log: (message) => this.host.log.warn(message),
714
781
  })
715
782
  this.process = proc
783
+ this.processFingerprint = binaryFingerprint(preflight.binary)
716
784
  const started = proc
717
785
  proc.onExit((error) => this.onProcessExit(started, error))
718
- await proc.start(120_000)
786
+ const init = await proc.start(120_000)
719
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
+ }
720
799
  this.state = 'ready'
721
800
  this.lastError = undefined
722
801
  return proc
723
802
  } catch (error) {
724
803
  proc?.stop()
725
- if (this.process === proc) this.process = undefined
804
+ if (this.process === proc) {
805
+ this.process = undefined
806
+ this.processFingerprint = undefined
807
+ }
726
808
  if (this.lifecycle !== 'active') throw this.shutdown.signal.reason
727
809
  await this.bridge.close()
728
810
  this.assertActive()
@@ -735,6 +817,7 @@ export class AntigravityRuntime {
735
817
  }
736
818
 
737
819
  private runPreflight(): Promise<PreflightResult> {
820
+ this.reconcileBinaryFingerprint()
738
821
  if (this.preflight !== undefined) {
739
822
  prepareHome(this.home)
740
823
  return Promise.resolve(this.preflight)
@@ -742,6 +825,7 @@ export class AntigravityRuntime {
742
825
  this.preflightPromise ??= (async () => {
743
826
  const config = this.host.config
744
827
  const binary = resolveAgyBinary(config.command)
828
+ this.reconcileBinaryFingerprint(binary)
745
829
  const version = await readVersion(binary, this.host.runCommand)
746
830
  this.assertActive()
747
831
  assertSupportedAgyVersion(version, binary)
@@ -754,6 +838,7 @@ export class AntigravityRuntime {
754
838
  logFile: join(this.home, 'acp.log'),
755
839
  }
756
840
  this.preflight = result
841
+ this.preflightFingerprint = binaryFingerprint(binary)
757
842
  return result
758
843
  })().finally(() => {
759
844
  this.preflightPromise = undefined
@@ -763,7 +848,10 @@ export class AntigravityRuntime {
763
848
 
764
849
  private onProcessExit(proc: AcpProcess, error: Error): void {
765
850
  const current = this.process === proc
766
- if (current) this.process = undefined
851
+ if (current) {
852
+ this.process = undefined
853
+ this.processFingerprint = undefined
854
+ }
767
855
  if (current && this.lifecycle === 'active') {
768
856
  this.state = 'error'
769
857
  this.lastError = error.message
@@ -841,6 +929,7 @@ export class AntigravityRuntime {
841
929
  conv.sessionId,
842
930
  conv.model,
843
931
  conv.metaFloorIdx,
932
+ conv.turn,
844
933
  )
845
934
  }
846
935
  if (recordReportedToolCall(conv, update) === 'conflict') {
@@ -1008,12 +1097,16 @@ export class AntigravityRuntime {
1008
1097
  const modelOption = conv.configOptions.find(
1009
1098
  (o) => o.id === 'model' || o.category === 'model',
1010
1099
  )
1100
+ const modelValues =
1101
+ modelOption?.options !== undefined
1102
+ ? flattenConfigOptions(modelOption.options)
1103
+ : undefined
1011
1104
  if (
1012
- modelOption?.options !== undefined &&
1013
- !modelOption.options.some((o) => o.value === model)
1105
+ modelValues !== undefined &&
1106
+ !modelValues.some((o) => o.value === model)
1014
1107
  ) {
1015
1108
  throw new LlmError(
1016
- `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(', ')}`,
1017
1110
  'UNKNOWN_MODEL',
1018
1111
  )
1019
1112
  }
@@ -1043,11 +1136,10 @@ export class AntigravityRuntime {
1043
1136
  const levelOption = conv.configOptions.find(
1044
1137
  (o) => o.id === 'thought_level' || o.category === 'thought_level',
1045
1138
  )
1046
- // Fixed-variant families (GPT-OSS) reject every thought_level change; the
1047
- // effort already lives in the model id, so only selectable families write it.
1048
- const selectable = this.catalog.effortsFor(model)
1139
+ // Fixed-variant families (GPT-OSS) and single-variant orchestrators reject
1140
+ // thought_level writes, so only selectable families write it.
1049
1141
  if (
1050
- selectable.length > 0 &&
1142
+ this.catalog.supportsEffortSelection(model) &&
1051
1143
  levelOption !== undefined &&
1052
1144
  conv.effort !== effort &&
1053
1145
  levelOption.currentValue !== effort
@@ -1195,10 +1287,15 @@ export class AntigravityRuntime {
1195
1287
  // Queue that failure too, so every allocated turn reaches the pump's cleanup owner.
1196
1288
  try {
1197
1289
  this.assertOwner(proc, conv, conv.sessionId)
1198
- turn.promptSettled = proc.prompt(conv.sessionId as string, blocks).then(
1199
- (result) => turn.events.push({ kind: 'done', result }),
1200
- (error: unknown) => turn.fail(mapError(error)),
1201
- )
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
+ })
1202
1299
  } catch (error) {
1203
1300
  turn.fail(mapError(error))
1204
1301
  }
@@ -1253,8 +1350,33 @@ export class AntigravityRuntime {
1253
1350
  {
1254
1351
  parkSettleMs: this.host.config.parkSettleMs,
1255
1352
  maxContinuations: this.host.config.longDecodeContinuations,
1256
- continuePrompt: () =>
1257
- 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
+ },
1258
1380
  cancel: () => {
1259
1381
  if (conv.turn === turn) proc.cancel(sessionId)
1260
1382
  },
@@ -1342,12 +1464,18 @@ export class AntigravityRuntime {
1342
1464
  const extraText = extras.length > 0 ? renderTranscript(extras) : ''
1343
1465
  const toolDelta = consumeToolDelta(conv, tools)
1344
1466
  const suffix = [toolDelta, extraText].filter(Boolean).join('\n\n')
1345
- const pending = [...turn.pendingCalls.values()]
1346
- turn.pendingCalls.clear()
1347
- if (turn.finished || !this.isTurnLive(turn)) {
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) {
1348
1476
  // The agent ended its turn while the harness ran the tools: hand the results over as new input.
1349
1477
  const transcript = renderTranscript(
1350
- pending.map((call) => results.get(call.id) as RequestMessage),
1478
+ delivery.pending.map((call) => results.get(call.id) as RequestMessage),
1351
1479
  )
1352
1480
  // The old turn is over: its reported identities do not carry into the continuation.
1353
1481
  turn.abandon('The agent ended the tool-waiting prompt.')
@@ -1356,32 +1484,14 @@ export class AntigravityRuntime {
1356
1484
  this.startPrompt(conv, next, proc, [
1357
1485
  {
1358
1486
  type: 'text',
1359
- 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.`,
1360
1488
  },
1361
1489
  ])
1362
1490
  return next
1363
1491
  }
1364
- for (const [index, call] of pending.entries()) {
1365
- const message = results.get(call.id) as Extract<
1366
- RequestMessage,
1367
- { role: 'tool' }
1368
- >
1369
- const result = this.toBridgeResult(
1370
- message.content,
1371
- message.isError === true,
1372
- )
1373
- if (index === pending.length - 1 && suffix.length > 0)
1374
- result.content.push({ type: 'text', text: `\n\n${suffix}` })
1375
- call.result.resolve(result)
1376
- }
1377
1492
  return turn
1378
1493
  }
1379
1494
 
1380
- private isTurnLive(turn: AcpTurn): boolean {
1381
- const head = turn.events.peek()
1382
- return head?.kind !== 'done' && head?.kind !== 'error'
1383
- }
1384
-
1385
1495
  private toBridgeResult(
1386
1496
  content: readonly ContentBlock[],
1387
1497
  isError: boolean,
@@ -1473,16 +1583,19 @@ export class AntigravityRuntime {
1473
1583
  const turn = conv.turn
1474
1584
  if (turn === undefined || turn.finished)
1475
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
1476
1590
  if (request.name === AWAIT_TOOL_NAME) {
1477
1591
  const callId =
1478
1592
  typeof request.arguments.call_id === 'string'
1479
1593
  ? request.arguments.call_id
1480
1594
  : ''
1481
- const call = turn.calls.get(callId)
1482
- if (call === undefined)
1483
- return toolError(`Unknown harness call id ${callId}.`)
1484
- turn.resumeRelay(callId)
1485
- return this.awaitCall(turn, call, request.signal)
1595
+ return (
1596
+ turn.awaitRelayedCall(callId, relayAfterMs, request.signal) ??
1597
+ toolError(`Unknown harness call id ${callId}.`)
1598
+ )
1486
1599
  }
1487
1600
  let name = request.name
1488
1601
  let args = request.arguments
@@ -1504,43 +1617,7 @@ export class AntigravityRuntime {
1504
1617
  }
1505
1618
  if (!conv.toolNames.has(name))
1506
1619
  return toolError(`The harness has no tool named ${name}.`)
1507
- return this.awaitCall(turn, turn.park(name, args), request.signal)
1508
- }
1509
-
1510
- private async awaitCall(
1511
- turn: AcpTurn,
1512
- call: ParkedCall,
1513
- signal: AbortSignal,
1514
- ): Promise<BridgeToolResult> {
1515
- let timer: ReturnType<typeof setTimeout> | undefined
1516
- const relayAfterMs =
1517
- this.host.relayAfterMs ??
1518
- this.host.config.relayAfterMs ??
1519
- defaults.relayAfterMs
1520
- const relay = new Promise<'relay'>((resolve) => {
1521
- timer = setTimeout(() => resolve('relay'), relayAfterMs)
1522
- })
1523
- let onAbort: (() => void) | undefined
1524
- const aborted = new Promise<'aborted'>((resolve) => {
1525
- if (signal.aborted) resolve('aborted')
1526
- else {
1527
- onAbort = () => resolve('aborted')
1528
- signal.addEventListener('abort', onAbort, { once: true })
1529
- }
1530
- })
1531
- try {
1532
- const outcome = await Promise.race([call.result.promise, relay, aborted])
1533
- if (outcome === 'relay') {
1534
- turn.markRelayed(call.id)
1535
- return relayNotice(call)
1536
- }
1537
- if (outcome === 'aborted')
1538
- return toolError('The tool call was cancelled.')
1539
- return outcome
1540
- } finally {
1541
- if (timer !== undefined) clearTimeout(timer)
1542
- if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
1543
- }
1620
+ return turn.invokeTool(name, args, relayAfterMs, request.signal)
1544
1621
  }
1545
1622
 
1546
1623
  private sweep(): void {