pi-agy-acp 0.1.2 → 0.1.4

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
@@ -26,7 +26,7 @@ import {
26
26
  type AcpSpawner,
27
27
  } from './acp-process.ts'
28
28
  import { ModelCatalog, nearestEffort } from './catalog.ts'
29
- import { asEffort, type Config, type Effort } from './config.ts'
29
+ import { asEffort, defaults, type Config, type Effort } from './config.ts'
30
30
  import {
31
31
  AcpTurn,
32
32
  AWAIT_TOOL,
@@ -54,6 +54,7 @@ import {
54
54
  import { JsonRpcClosedError, JsonRpcRemoteError } from './jsonrpc.ts'
55
55
  import {
56
56
  McpBridge,
57
+ compactBridgeTool,
57
58
  consumeToolDelta,
58
59
  toBridgeTools,
59
60
  type BridgeCallRequest,
@@ -81,11 +82,9 @@ import {
81
82
  type AccountInfo,
82
83
  type QuotaSnapshot,
83
84
  } from './quota.ts'
84
- import { delay, digest, KeyedMutex, abortable } from './util.ts'
85
+ import { digest, KeyedMutex, abortable } from './util.ts'
85
86
  import { VERSION } from './version.ts'
86
87
 
87
- /** Parked calls answer with a still-running notice before Gemini cache TTL expiry and agy's 180-second MCP deadline. */
88
- export const DEFAULT_RELAY_AFTER_MS = 85_000
89
88
  const CONTINUE_PROMPT =
90
89
  'Continue exactly where your previous output stopped. Do not repeat any earlier text.'
91
90
 
@@ -142,7 +141,7 @@ interface Conversation {
142
141
  configOptions: AcpConfigOption[]
143
142
  systemHash: string | undefined
144
143
  advertisedTools: BridgeTool[]
145
- advertisedToolNames: Set<string>
144
+ advertisedToolDigests: Map<string, string>
146
145
  knownTools: Map<string, string>
147
146
  toolNames: Set<string>
148
147
  /** Tool calls the agent reported via `session/update` — the only trusted permission source. */
@@ -185,7 +184,9 @@ export class AntigravityRuntime {
185
184
  private readonly capacityMutex = new KeyedMutex()
186
185
  private sweeper: ReturnType<typeof setInterval> | undefined
187
186
  private lastTurn: RuntimeStatus['lastTurn']
188
- private disposed = false
187
+ private lifecycle: 'active' | 'disposing' | 'disposed' = 'active'
188
+ private readonly shutdown = new AbortController()
189
+ private disposal: Promise<void> | undefined
189
190
  private readonly host: RuntimeHost
190
191
 
191
192
  /** @param host - host services. */
@@ -279,6 +280,7 @@ export class AntigravityRuntime {
279
280
 
280
281
  /** Fetch quota and try once per runtime to discover an uncached plan. */
281
282
  async readQuota(force = false): Promise<QuotaSnapshot> {
283
+ this.assertActive()
282
284
  const quota = this.quota.read(force)
283
285
  if (!this.catalog.tier()) {
284
286
  this.tierDiscovery ??= (async () => {
@@ -309,17 +311,19 @@ export class AntigravityRuntime {
309
311
  * @returns the running process.
310
312
  */
311
313
  async ensureReady(): Promise<AcpProcess> {
312
- if (this.disposed)
313
- throw new LlmError('Antigravity provider was disposed', 'TRANSPORT')
314
+ this.assertActive()
314
315
  if (this.sweeper === undefined) {
315
316
  this.sweeper = setInterval(() => this.sweep(), 60_000)
316
317
  this.sweeper.unref?.()
317
318
  }
318
- if (this.process?.alive === true) return this.process
319
+ if (this.starting === undefined && this.process?.alive === true)
320
+ return this.process
319
321
  this.starting ??= this.start().finally(() => {
320
322
  this.starting = undefined
321
323
  })
322
- return this.starting
324
+ const proc = await this.starting
325
+ this.assertOwner(proc)
326
+ return proc
323
327
  }
324
328
 
325
329
  /**
@@ -329,12 +333,14 @@ export class AntigravityRuntime {
329
333
  async warmup(
330
334
  options: { force?: boolean; signal?: AbortSignal } = {},
331
335
  ): Promise<void> {
336
+ this.assertActive()
332
337
  options.signal?.throwIfAborted()
333
338
  if (this.warmupPromise !== undefined)
334
339
  return abortable(this.warmupPromise, options.signal)
335
340
  if (!options.force && this.catalog.observed) return
336
341
  this.warmupPromise = (async () => {
337
342
  const proc = await this.ensureReady()
343
+ this.assertOwner(proc)
338
344
  const result = await proc.newSession(
339
345
  {
340
346
  cwd: this.preflight?.workspace ?? this.home,
@@ -344,6 +350,7 @@ export class AntigravityRuntime {
344
350
  120_000,
345
351
  )
346
352
  try {
353
+ this.assertOwner(proc)
347
354
  if (
348
355
  this.catalog.observe(
349
356
  result.configOptions,
@@ -353,11 +360,7 @@ export class AntigravityRuntime {
353
360
  )
354
361
  this.host.onModelsChanged()
355
362
  } finally {
356
- try {
357
- await proc.closeSession(result.sessionId)
358
- } finally {
359
- removeSessionArtifacts(this.home, result.sessionId)
360
- }
363
+ await this.closeAndCleanSession(proc, result.sessionId)
361
364
  }
362
365
  })().finally(() => {
363
366
  this.warmupPromise = undefined
@@ -367,12 +370,13 @@ export class AntigravityRuntime {
367
370
 
368
371
  /** Close conversation sessions while retaining the process and discovery/quota caches. */
369
372
  async resetConversations(): Promise<void> {
373
+ this.assertActive()
370
374
  const conversations = [...this.conversations.values()]
371
375
  for (const conv of conversations)
372
376
  this.dropTurn(conv, 'The Pi session changed.')
373
377
  await Promise.all(
374
378
  conversations.map(async (conv) => {
375
- const release = await this.mutex.acquire(conv.key)
379
+ const release = await this.mutex.acquire(conv.key, this.shutdown.signal)
376
380
  try {
377
381
  if (this.conversations.get(conv.key) !== conv) return
378
382
  await this.resetSession(conv)
@@ -385,16 +389,50 @@ export class AntigravityRuntime {
385
389
  }
386
390
 
387
391
  /** Stop every session, the process, and the bridge. */
388
- async dispose(): Promise<void> {
389
- this.disposed = true
392
+ dispose(): Promise<void> {
393
+ if (this.disposal !== undefined) return this.disposal
394
+ this.lifecycle = 'disposing'
395
+ this.shutdown.abort(
396
+ new LlmError('Antigravity provider was disposed', 'TRANSPORT'),
397
+ )
390
398
  if (this.sweeper !== undefined) clearInterval(this.sweeper)
391
- for (const conv of this.conversations.values())
399
+ this.sweeper = undefined
400
+ for (const conv of this.conversations.values()) {
392
401
  conv.turn?.abandon('The harness provider was unloaded.')
402
+ this.clearSession(conv)
403
+ }
393
404
  this.conversations.clear()
394
405
  this.tenants.clear()
395
406
  this.process?.stop()
396
407
  this.process = undefined
397
- await this.bridge.close()
408
+ this.disposal = (async () => {
409
+ // Preflight waits are cancellable; binding must finish before closing its listener.
410
+ await this.starting?.catch(() => undefined)
411
+ await this.warmupPromise?.catch(() => undefined)
412
+ await this.bridge.close()
413
+ this.state = 'idle'
414
+ this.lifecycle = 'disposed'
415
+ })()
416
+ return this.disposal
417
+ }
418
+
419
+ private assertActive(): void {
420
+ if (this.lifecycle !== 'active') throw this.shutdown.signal.reason
421
+ }
422
+
423
+ /** A captured owner remains usable only while every enclosing owner is current. */
424
+ private owns(proc: AcpProcess, conv?: Conversation, sessionId?: string): boolean {
425
+ return this.lifecycle === 'active' && this.process === proc && proc.alive &&
426
+ (conv === undefined || (
427
+ this.conversations.get(conv.key) === conv &&
428
+ (sessionId === undefined || (conv.process === proc && conv.sessionId === sessionId))
429
+ ))
430
+ }
431
+
432
+ private assertOwner(proc: AcpProcess, conv?: Conversation, sessionId?: string): void {
433
+ this.assertActive()
434
+ if (!this.owns(proc, conv, sessionId))
435
+ throw new LlmError('Conversation ownership changed', 'TRANSPORT')
398
436
  }
399
437
 
400
438
  /**
@@ -404,6 +442,7 @@ export class AntigravityRuntime {
404
442
  */
405
443
  async *stream(options: GenerateOptions): AsyncGenerator<StreamChunk> {
406
444
  if (options.signal?.aborted === true) {
445
+ if (options.sessionId !== undefined) this.settleSession(options.sessionId)
407
446
  yield {
408
447
  type: 'finish',
409
448
  reason: {
@@ -414,12 +453,13 @@ export class AntigravityRuntime {
414
453
  return
415
454
  }
416
455
  const proc = await this.ensureReady()
417
- const scope = options.sessionId ?? `anon-${randomBytes(6).toString('hex')}`
418
- const key = scope
419
- const release = await this.mutex.acquire(key)
456
+ const key = options.sessionId ?? `anon-${randomBytes(6).toString('hex')}`
457
+ const release = await this.mutex.acquire(key, this.shutdown.signal)
420
458
  let conv: Conversation | undefined
421
459
  try {
460
+ this.assertActive()
422
461
  conv = await this.acquireConversation(key)
462
+ this.assertOwner(proc, conv)
423
463
  conv.lastUsed = Date.now()
424
464
  const split = splitSystem(options)
425
465
  const tools = toBridgeTools(options.tools)
@@ -429,28 +469,44 @@ export class AntigravityRuntime {
429
469
  asEffort(options.reasoningEffort) ?? this.host.config.defaultEffort,
430
470
  )
431
471
 
472
+ if (options.signal?.aborted) {
473
+ this.dropTurn(conv, 'The harness cancelled this request.')
474
+ yield {
475
+ type: 'finish',
476
+ reason: {
477
+ kind: 'aborted',
478
+ failure: { message: 'Request aborted', code: 'ABORTED' },
479
+ },
480
+ }
481
+ return
482
+ }
432
483
  if (conv.turn !== undefined && conv.turn.pendingCalls.size > 0) {
433
484
  // Resuming a parked turn is only valid while the request still starts
434
- // with the exact history this ACP session already owns. A compaction
435
- // checkpoint or a pruned/rewritten prefix means the live server-side
436
- // context is stale: resolving the parked calls would grow it further
437
- // instead of adopting the compacted history, so abandon the turn and
438
- // let plan() rebuild the session from Pi's authoritative messages.
439
- if (!this.historyPrefixIntact(conv, split.system, split.messages)) {
485
+ // with the exact history and model/effort selection this ACP session
486
+ // already owns. A compaction checkpoint, pruned/rewritten prefix, or
487
+ // model/effort change means the live session is stale, so abandon the
488
+ // turn and let plan() rebuild from Pi's authoritative history.
489
+ if (
490
+ !this.historyPrefixIntact(conv, split.system, split.messages) ||
491
+ conv.model !== options.model ||
492
+ conv.effort !== effort
493
+ ) {
440
494
  this.dropTurn(
441
495
  conv,
442
- 'The conversation history was compacted or rewritten; rebuilding the session from the harness history.',
496
+ 'The conversation history or model selection changed; rebuilding the session from the harness history.',
443
497
  )
444
498
  } else {
445
- const resumed = await this.deliverResults(
499
+ // Tool waiters can abort in their result microtask; hand off the exact turn synchronously.
500
+ const resumed = this.deliverResults(
446
501
  conv,
447
502
  split.messages,
448
503
  proc,
449
504
  tools,
450
505
  )
451
- if (resumed) {
506
+ this.assertActive()
507
+ if (resumed !== undefined) {
452
508
  conv.knownIds = messageIds(split.messages)
453
- yield* this.pump(conv, proc, options, effort)
509
+ yield* this.pump(conv, resumed, proc, options, effort)
454
510
  return
455
511
  }
456
512
  this.dropTurn(
@@ -464,32 +520,53 @@ export class AntigravityRuntime {
464
520
 
465
521
  const plan = this.plan(conv, split.system, split.messages)
466
522
  if (plan.rebuild) await this.resetSession(conv)
523
+ this.assertOwner(proc, conv)
524
+ let supplementalTools: readonly BridgeTool[] = []
467
525
  if (conv.sessionId === undefined) {
468
526
  conv.systemHash = digest(split.system)
469
- await this.openSession(conv, split.system, tools, proc)
527
+ supplementalTools = await this.openSession(conv, tools, proc)
470
528
  }
529
+ this.assertOwner(proc, conv, conv.sessionId)
471
530
  await this.select(conv, proc, options.model, effort)
531
+ this.assertOwner(proc, conv, conv.sessionId)
472
532
  let blocks: AcpPromptBlock[]
473
533
  if (plan.rebuild) {
474
- blocks = replayPrompt(plan.history, plan.input)
534
+ blocks = replayPrompt(plan.history, plan.input, {
535
+ system: split.system,
536
+ supplementalTools,
537
+ })
475
538
  } else {
476
539
  blocks = inputPrompt(plan.input)
477
540
  const toolDelta = consumeToolDelta(conv, tools)
478
541
  if (toolDelta.length > 0)
479
542
  blocks.unshift({ type: 'text', text: `${toolDelta}\n\n` })
480
543
  }
544
+ if (options.signal?.aborted) {
545
+ this.dropTurn(conv, 'The harness cancelled this request.')
546
+ yield {
547
+ type: 'finish',
548
+ reason: {
549
+ kind: 'aborted',
550
+ failure: { message: 'Request aborted', code: 'ABORTED' },
551
+ },
552
+ }
553
+ return
554
+ }
481
555
  conv.knownIds = messageIds(split.messages)
482
556
  // A new turn starts with an empty reported-identity space: ids from past
483
557
  // turns must never back a fresh permission request.
484
558
  conv.reportedToolCalls.clear()
485
- conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
486
- this.startPrompt(conv, proc, blocks)
487
- yield* this.pump(conv, proc, options, effort)
559
+ const turn = conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
560
+ this.startPrompt(conv, turn, proc, blocks)
561
+ yield* this.pump(conv, turn, proc, options, effort)
488
562
  } finally {
489
- release()
490
- if (conv !== undefined) {
491
- conv.opening = false
492
- await this.afterStep(conv)
563
+ try {
564
+ if (conv !== undefined) {
565
+ conv.opening = false
566
+ await this.afterStep(conv)
567
+ }
568
+ } finally {
569
+ release()
493
570
  }
494
571
  }
495
572
  }
@@ -502,13 +579,18 @@ export class AntigravityRuntime {
502
579
  * deadlock.
503
580
  */
504
581
  private async acquireConversation(key: string): Promise<Conversation> {
582
+ this.assertActive()
505
583
  const existing = this.conversations.get(key)
506
584
  if (existing !== undefined) {
507
585
  existing.opening = true
508
586
  return existing
509
587
  }
510
- const unlock = await this.capacityMutex.acquire('capacity')
588
+ const unlock = await this.capacityMutex.acquire(
589
+ 'capacity',
590
+ this.shutdown.signal,
591
+ )
511
592
  try {
593
+ this.assertActive()
512
594
  const again = this.conversations.get(key)
513
595
  if (again !== undefined) {
514
596
  again.opening = true
@@ -523,6 +605,7 @@ export class AntigravityRuntime {
523
605
  const victim = idle.shift() as Conversation
524
606
  this.conversations.delete(victim.key)
525
607
  await this.resetSession(victim)
608
+ this.assertActive()
526
609
  }
527
610
  }
528
611
  if (this.conversations.size >= max) {
@@ -549,7 +632,7 @@ export class AntigravityRuntime {
549
632
  configOptions: [],
550
633
  systemHash: undefined,
551
634
  advertisedTools: [],
552
- advertisedToolNames: new Set(),
635
+ advertisedToolDigests: new Map(),
553
636
  knownTools: new Map(),
554
637
  toolNames: new Set(),
555
638
  reportedToolCalls: new Map(),
@@ -570,8 +653,10 @@ export class AntigravityRuntime {
570
653
  this.state = 'starting'
571
654
  let proc: AcpProcess | undefined
572
655
  try {
573
- const preflight = await this.runPreflight()
656
+ const preflight = await abortable(this.runPreflight(), this.shutdown.signal)
657
+ this.assertActive()
574
658
  await this.bridge.start()
659
+ this.assertActive()
575
660
  const argv = [
576
661
  preflight.binary,
577
662
  'acp',
@@ -594,16 +679,20 @@ export class AntigravityRuntime {
594
679
  clientVersion: VERSION,
595
680
  log: (message) => this.host.log.warn(message),
596
681
  })
682
+ this.process = proc
597
683
  const started = proc
598
684
  proc.onExit((error) => this.onProcessExit(started, error))
599
685
  await proc.start(120_000)
600
- this.process = proc
686
+ this.assertOwner(proc)
601
687
  this.state = 'ready'
602
688
  this.lastError = undefined
603
689
  return proc
604
690
  } catch (error) {
605
691
  proc?.stop()
692
+ if (this.process === proc) this.process = undefined
693
+ if (this.lifecycle !== 'active') throw this.shutdown.signal.reason
606
694
  await this.bridge.close()
695
+ this.assertActive()
607
696
  if (this.sweeper !== undefined) clearInterval(this.sweeper)
608
697
  this.sweeper = undefined
609
698
  this.state = 'error'
@@ -621,6 +710,7 @@ export class AntigravityRuntime {
621
710
  const config = this.host.config
622
711
  const binary = resolveAgyBinary(config.command)
623
712
  const version = await readVersion(binary, this.host.runCommand)
713
+ this.assertActive()
624
714
  assertSupportedAgyVersion(version, binary)
625
715
  const workspace = prepareHome(this.home)
626
716
  const result: PreflightResult = {
@@ -639,21 +729,20 @@ export class AntigravityRuntime {
639
729
  }
640
730
 
641
731
  private onProcessExit(proc: AcpProcess, error: Error): void {
642
- if (this.process === proc) this.process = undefined
643
- if (!this.disposed) {
732
+ const current = this.process === proc
733
+ if (current) this.process = undefined
734
+ if (current && this.lifecycle === 'active') {
644
735
  this.state = 'error'
645
736
  this.lastError = error.message
646
737
  this.host.log.warn(`antigravity-acp: ${error.message}`)
647
738
  }
648
739
  for (const conv of this.conversations.values()) {
649
740
  if (conv.process !== proc) continue
650
- conv.turn?.events.push({
651
- kind: 'error',
652
- error: new LlmError(
653
- `Antigravity ACP process exited: ${error.message}`,
654
- 'TRANSPORT',
655
- ),
656
- })
741
+ conv.turn?.fail(new LlmError(
742
+ `Antigravity ACP process exited: ${error.message}`,
743
+ 'TRANSPORT',
744
+ ))
745
+ conv.turn = undefined
657
746
  this.clearSession(conv)
658
747
  conv.dirty = true
659
748
  }
@@ -661,15 +750,19 @@ export class AntigravityRuntime {
661
750
 
662
751
  private async openSession(
663
752
  conv: Conversation,
664
- system: string,
665
753
  tools: readonly BridgeTool[],
666
754
  proc: AcpProcess,
667
- ): Promise<void> {
755
+ ): Promise<readonly BridgeTool[]> {
756
+ this.assertOwner(proc, conv)
668
757
  syncOAuthToken(this.home)
669
758
  conv.reportedToolCalls.clear()
670
- conv.advertisedTools = [...tools]
671
- conv.advertisedToolNames = new Set(tools.map((t) => t.name))
672
- conv.knownTools = new Map(tools.map((t) => [t.name, digest(t)]))
759
+ const compacted = tools.map(compactBridgeTool)
760
+ const supplementalTools = tools.filter(
761
+ (raw, index) => compacted[index] !== raw,
762
+ )
763
+ conv.advertisedTools = compacted
764
+ conv.advertisedToolDigests = new Map(tools.map((t) => [t.name, digest(t)]))
765
+ conv.knownTools = new Map(conv.advertisedToolDigests)
673
766
  const tenantKey = randomBytes(16).toString('hex')
674
767
  const tenantSecret = randomBytes(24).toString('hex')
675
768
  const mcpServers = [
@@ -690,12 +783,18 @@ export class AntigravityRuntime {
690
783
  mcpServers,
691
784
  _meta: {
692
785
  antigravity: {
693
- systemPrompt: { append: bridgeSystemPrompt(system) },
786
+ systemPrompt: {
787
+ append: bridgeSystemPrompt(),
788
+ },
694
789
  },
695
790
  },
696
791
  },
697
792
  {
698
793
  onUpdate: (update) => {
794
+ if (
795
+ !this.owns(proc, conv) ||
796
+ conv.tenantKey !== tenantKey
797
+ ) return
699
798
  if (
700
799
  update.sessionUpdate === 'config_option_update' &&
701
800
  Array.isArray(update.configOptions)
@@ -711,10 +810,18 @@ export class AntigravityRuntime {
711
810
  }
712
811
  conv.turn?.onUpdate(update)
713
812
  },
714
- onPermission: (request) => this.answerPermission(conv, request),
813
+ onPermission: (request) => this.owns(proc, conv) && conv.tenantKey === tenantKey
814
+ ? this.answerPermission(conv, request)
815
+ : { outcome: 'cancelled' },
715
816
  },
716
817
  120_000,
717
818
  )
819
+ // A buffered session/new reply can resolve after its process has exited.
820
+ if (!this.owns(proc, conv)) {
821
+ await this.closeAndCleanSession(proc, result.sessionId)
822
+ this.assertActive()
823
+ throw new LlmError('Conversation ownership changed', 'TRANSPORT')
824
+ }
718
825
  conv.sessionId = result.sessionId
719
826
  conv.process = proc
720
827
  conv.configOptions = result.configOptions ?? []
@@ -731,6 +838,7 @@ export class AntigravityRuntime {
731
838
  )
732
839
  )
733
840
  this.host.onModelsChanged()
841
+ return supplementalTools
734
842
  } catch (error) {
735
843
  this.clearSession(conv)
736
844
  throw mapError(error)
@@ -779,7 +887,7 @@ export class AntigravityRuntime {
779
887
  }
780
888
  const reject = (reason: string): AcpPermissionOutcome => {
781
889
  this.host.log.warn(
782
- `antigravity-acp: refused permission request (${reason}): ${request.toolCall?.title ?? 'unknown'}`,
890
+ `antigravity-acp: refused permission request (${reason}): ${request.toolCall?.title || request.toolCall?.name || 'unknown'}`,
783
891
  )
784
892
  return pick('reject_once') ?? { outcome: 'cancelled' }
785
893
  }
@@ -794,6 +902,9 @@ export class AntigravityRuntime {
794
902
  return reject('missing toolCallId')
795
903
  const reported = conv.reportedToolCalls.get(toolCallId)
796
904
  const claimed = structuredToolMeta(request.toolCall)
905
+ if (claimed.conflict === true) {
906
+ return reject('conflicting tool metadata in permission request')
907
+ }
797
908
  if (reported === undefined) {
798
909
  // Nothing the agent reported in `session/update` backs this call: its own
799
910
  // in-request metadata is untrusted (stale or cross-session toolCallId).
@@ -832,15 +943,12 @@ export class AntigravityRuntime {
832
943
  return reject('tool name conflict')
833
944
  if (reported.serverName !== MCP_SERVER_NAME)
834
945
  return reject(`unknown MCP server ${reported.serverName ?? '(none)'}`)
835
- const allowedTools = new Set([
836
- ...conv.advertisedToolNames,
837
- AWAIT_TOOL_NAME,
838
- CALL_TOOL_NAME,
839
- ])
840
- if (
841
- reported.toolName === undefined ||
842
- !allowedTools.has(reported.toolName)
843
- ) {
946
+ const isAllowedTool =
947
+ reported.toolName !== undefined &&
948
+ (conv.advertisedToolDigests.has(reported.toolName) ||
949
+ reported.toolName === AWAIT_TOOL_NAME ||
950
+ reported.toolName === CALL_TOOL_NAME)
951
+ if (!isAllowedTool) {
844
952
  return reject(
845
953
  `tool is not offered to this session: ${reported.toolName ?? '(none)'}`,
846
954
  )
@@ -855,6 +963,7 @@ export class AntigravityRuntime {
855
963
  effort: Effort,
856
964
  ): Promise<void> {
857
965
  const sessionId = conv.sessionId as string
966
+ this.assertOwner(proc, conv, sessionId)
858
967
  const modelOption = conv.configOptions.find(
859
968
  (o) => o.id === 'model' || o.category === 'model',
860
969
  )
@@ -868,11 +977,13 @@ export class AntigravityRuntime {
868
977
  )
869
978
  }
870
979
  if (conv.model !== model && modelOption?.currentValue !== model) {
871
- conv.configOptions = await proc
872
- .setConfigOption(sessionId, modelOption?.id ?? 'model', model)
873
- .catch((error: unknown) => {
874
- throw mapError(error)
875
- })
980
+ await this.applyConfigOption(
981
+ conv,
982
+ proc,
983
+ sessionId,
984
+ modelOption?.id ?? 'model',
985
+ model,
986
+ )
876
987
  }
877
988
  conv.model = model
878
989
  const levelOption = conv.configOptions.find(
@@ -887,15 +998,27 @@ export class AntigravityRuntime {
887
998
  conv.effort !== effort &&
888
999
  levelOption.currentValue !== effort
889
1000
  ) {
890
- conv.configOptions = await proc
891
- .setConfigOption(sessionId, levelOption.id, effort)
892
- .catch((error: unknown) => {
893
- throw mapError(error)
894
- })
1001
+ await this.applyConfigOption(conv, proc, sessionId, levelOption.id, effort)
895
1002
  }
896
1003
  conv.effort = effort
897
1004
  }
898
1005
 
1006
+ private async applyConfigOption(
1007
+ conv: Conversation,
1008
+ proc: AcpProcess,
1009
+ sessionId: string,
1010
+ optionId: string,
1011
+ value: string,
1012
+ ): Promise<void> {
1013
+ const configOptions = await proc
1014
+ .setConfigOption(sessionId, optionId, value)
1015
+ .catch((error: unknown) => {
1016
+ throw mapError(error)
1017
+ })
1018
+ this.assertOwner(proc, conv, sessionId)
1019
+ conv.configOptions = configOptions
1020
+ }
1021
+
899
1022
  private plan(
900
1023
  conv: Conversation,
901
1024
  system: string,
@@ -972,13 +1095,21 @@ export class AntigravityRuntime {
972
1095
  return false
973
1096
  }
974
1097
 
1098
+ private async closeAndCleanSession(
1099
+ proc: AcpProcess,
1100
+ sessionId: string,
1101
+ ): Promise<void> {
1102
+ try {
1103
+ await proc.closeSession(sessionId)
1104
+ } finally {
1105
+ removeSessionArtifacts(this.home, sessionId)
1106
+ }
1107
+ }
1108
+
975
1109
  private async resetSession(conv: Conversation): Promise<void> {
976
1110
  let closing: Promise<void> | undefined
977
1111
  if (conv.sessionId !== undefined && conv.process !== undefined) {
978
- const sessionId = conv.sessionId
979
- closing = conv.process
980
- .closeSession(sessionId)
981
- .finally(() => removeSessionArtifacts(this.home, sessionId))
1112
+ closing = this.closeAndCleanSession(conv.process, conv.sessionId)
982
1113
  }
983
1114
  this.clearSession(conv)
984
1115
  conv.knownIds = undefined
@@ -993,33 +1124,58 @@ export class AntigravityRuntime {
993
1124
  conv.tenantSecret = undefined
994
1125
  conv.process = undefined
995
1126
  conv.advertisedTools = []
996
- conv.advertisedToolNames.clear()
1127
+ conv.advertisedToolDigests.clear()
997
1128
  conv.knownTools.clear()
998
1129
  conv.reportedToolCalls.clear()
999
1130
  }
1000
1131
 
1001
1132
  private startPrompt(
1002
1133
  conv: Conversation,
1134
+ turn: AcpTurn,
1003
1135
  proc: AcpProcess,
1004
1136
  blocks: AcpPromptBlock[],
1005
1137
  ): void {
1006
- const turn = conv.turn as AcpTurn
1007
- turn.promptSettled = proc.prompt(conv.sessionId as string, blocks).then(
1008
- (result) => turn.events.push({ kind: 'done', result }),
1009
- (error: unknown) =>
1010
- turn.events.push({ kind: 'error', error: mapError(error) }),
1011
- )
1138
+ // AcpProcess.prompt's link() can throw before returning a promise (buffered reply + exit).
1139
+ // Queue that failure too, so every allocated turn reaches the pump's cleanup owner.
1140
+ try {
1141
+ 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
+ )
1146
+ } catch (error) {
1147
+ turn.fail(mapError(error))
1148
+ }
1012
1149
  }
1013
1150
 
1014
1151
  private async *pump(
1015
1152
  conv: Conversation,
1153
+ turn: AcpTurn,
1016
1154
  proc: AcpProcess,
1017
1155
  options: GenerateOptions,
1018
1156
  effort: Effort,
1019
1157
  ): AsyncGenerator<StreamChunk> {
1020
- const turn = conv.turn as AcpTurn
1021
1158
  const sessionId = conv.sessionId as string
1022
1159
  let finishKind: string | undefined
1160
+ let drained = false
1161
+ const cancel = () => {
1162
+ if (conv.turn === turn)
1163
+ this.dropTurn(conv, 'The harness cancelled this request.')
1164
+ }
1165
+ // Pi 1.5.2 pi-agent-core/dist/agent-loop.js shares this signal with tool execution.
1166
+ turn.releaseSignal?.()
1167
+ turn.releaseSignal = undefined
1168
+ if (options.signal !== undefined) {
1169
+ const signal = options.signal
1170
+ signal.addEventListener('abort', cancel, { once: true })
1171
+ turn.releaseSignal = () => {
1172
+ signal.removeEventListener('abort', cancel)
1173
+ }
1174
+ if (signal.aborted) cancel()
1175
+ }
1176
+ const signal = options.signal === undefined
1177
+ ? turn.cancellation.signal
1178
+ : AbortSignal.any([options.signal, turn.cancellation.signal])
1023
1179
  const recordTurn = (
1024
1180
  outcome: NonNullable<RuntimeStatus['lastTurn']>['outcome'],
1025
1181
  ) => {
@@ -1035,53 +1191,76 @@ export class AntigravityRuntime {
1035
1191
  }
1036
1192
  }
1037
1193
  try {
1038
- for await (const chunk of pumpStep(
1194
+ for await (const emitted of pumpStep(
1039
1195
  turn,
1040
1196
  {
1041
1197
  parkSettleMs: this.host.config.parkSettleMs,
1042
1198
  maxContinuations: this.host.config.longDecodeContinuations,
1043
1199
  continuePrompt: () =>
1044
1200
  proc.prompt(sessionId, [{ type: 'text', text: CONTINUE_PROMPT }]),
1045
- cancel: () => proc.cancel(sessionId),
1201
+ cancel: () => {
1202
+ if (conv.turn === turn) proc.cancel(sessionId)
1203
+ },
1046
1204
  },
1047
- options.signal,
1205
+ signal,
1048
1206
  )) {
1207
+ // for-await adds a microtask boundary after pumpStep's own emission guard.
1208
+ const chunk = turn.guard(emitted, signal) as StreamChunk
1049
1209
  if (chunk.type === 'block-end' && chunk.block.type === 'tool-call')
1050
1210
  conv.issuedIds.add(chunk.block.id)
1051
1211
  if (chunk.type === 'finish') finishKind = chunk.reason.kind
1052
1212
  yield chunk
1213
+ if (chunk.type === 'finish' && chunk.reason.kind === 'aborted') break
1214
+ }
1215
+ const interrupted = turn.guard(undefined, signal)
1216
+ if (interrupted !== undefined && finishKind !== 'aborted') {
1217
+ finishKind = 'aborted'
1218
+ yield interrupted
1053
1219
  }
1220
+ drained = true
1054
1221
  } catch (error) {
1055
- recordTurn('error')
1056
- conv.reportedToolCalls.clear()
1057
- conv.turn = undefined
1058
- conv.dirty = true
1222
+ finishKind = 'error'
1059
1223
  throw mapError(error)
1224
+ } finally {
1225
+ // Only a fully consumed tool handoff keeps the turn and its cancellation owner.
1226
+ if (!(drained && finishKind === 'tool-calls' && !signal.aborted && conv.turn === turn)) {
1227
+ recordTurn(
1228
+ finishKind === 'error' ? 'error' : signal.aborted ? 'aborted'
1229
+ : !drained ? 'error' : 'completed',
1230
+ )
1231
+ if (conv.turn === turn) {
1232
+ if (!drained || finishKind === 'aborted' || finishKind === 'error')
1233
+ this.dropTurn(conv, 'The harness ended this request.')
1234
+ else {
1235
+ turn.abandon('The turn completed.')
1236
+ conv.reportedToolCalls.clear()
1237
+ conv.turn = undefined
1238
+ }
1239
+ }
1240
+ if (finishKind === 'aborted' || !drained) {
1241
+ let timer: ReturnType<typeof setTimeout> | undefined
1242
+ try {
1243
+ await Promise.race([
1244
+ turn.promptSettled,
1245
+ new Promise<void>((resolve) => {
1246
+ timer = setTimeout(resolve, 5_000)
1247
+ }),
1248
+ ])
1249
+ } finally {
1250
+ clearTimeout(timer)
1251
+ }
1252
+ }
1253
+ }
1060
1254
  }
1061
- if (finishKind === 'tool-calls') return
1062
- recordTurn(
1063
- finishKind === 'aborted'
1064
- ? 'aborted'
1065
- : finishKind === 'error'
1066
- ? 'error'
1067
- : 'completed',
1068
- )
1069
- if (finishKind === 'aborted') {
1070
- // A cancelled turn leaves partial agent-side history; rebuild from Pi history next time.
1071
- await Promise.race([turn.promptSettled, delay(5_000)])
1072
- conv.dirty = true
1073
- }
1074
- // The turn is over: clear the identities it established with it.
1075
- conv.reportedToolCalls.clear()
1076
- conv.turn = undefined
1077
1255
  }
1078
1256
 
1079
- private async deliverResults(
1257
+ private deliverResults(
1080
1258
  conv: Conversation,
1081
1259
  messages: readonly RequestMessage[],
1082
1260
  proc: AcpProcess,
1083
1261
  tools: readonly BridgeTool[],
1084
- ): Promise<boolean> {
1262
+ ): AcpTurn | undefined {
1263
+ this.assertOwner(proc, conv, conv.sessionId)
1085
1264
  const turn = conv.turn as AcpTurn
1086
1265
  const results = new Map<string, Extract<RequestMessage, { role: 'tool' }>>()
1087
1266
  let last = -1
@@ -1094,10 +1273,10 @@ export class AntigravityRuntime {
1094
1273
  last = Math.max(last, index)
1095
1274
  }
1096
1275
  })
1097
- if (results.size !== turn.pendingCalls.size) return false
1276
+ if (results.size !== turn.pendingCalls.size) return undefined
1098
1277
  const extras = messages.slice(last + 1)
1099
1278
  if (extras.some((m) => m.role === 'assistant' || m.role === 'tool'))
1100
- return false
1279
+ return undefined
1101
1280
  const extraText = extras.length > 0 ? renderTranscript(extras) : ''
1102
1281
  const toolDelta = consumeToolDelta(conv, tools)
1103
1282
  const suffix = [toolDelta, extraText].filter(Boolean).join('\n\n')
@@ -1109,15 +1288,16 @@ export class AntigravityRuntime {
1109
1288
  pending.map((call) => results.get(call.id) as RequestMessage),
1110
1289
  )
1111
1290
  // The old turn is over: its reported identities do not carry into the continuation.
1291
+ turn.abandon('The agent ended the tool-waiting prompt.')
1112
1292
  conv.reportedToolCalls.clear()
1113
- conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
1114
- this.startPrompt(conv, proc, [
1293
+ const next = conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
1294
+ this.startPrompt(conv, next, proc, [
1115
1295
  {
1116
1296
  type: 'text',
1117
1297
  text: `${transcript}${suffix ? `\n\n${suffix}` : ''}\n\nContinue the task with these tool results.`,
1118
1298
  },
1119
1299
  ])
1120
- return true
1300
+ return next
1121
1301
  }
1122
1302
  for (const [index, call] of pending.entries()) {
1123
1303
  const message = results.get(call.id) as Extract<
@@ -1132,7 +1312,7 @@ export class AntigravityRuntime {
1132
1312
  result.content.push({ type: 'text', text: `\n\n${suffix}` })
1133
1313
  call.result.resolve(result)
1134
1314
  }
1135
- return true
1315
+ return turn
1136
1316
  }
1137
1317
 
1138
1318
  private isTurnLive(turn: AcpTurn): boolean {
@@ -1164,13 +1344,19 @@ export class AntigravityRuntime {
1164
1344
  return { content: items, ...(isError ? { isError: true } : {}) }
1165
1345
  }
1166
1346
 
1347
+ /** Release residual work for the Pi run that owns this session. */
1348
+ settleSession(sessionId: string): void {
1349
+ const conv = this.conversations.get(sessionId)
1350
+ if (conv !== undefined) this.dropTurn(conv, 'The owning Pi run settled.')
1351
+ }
1352
+
1167
1353
  private dropTurn(conv: Conversation, reason: string): void {
1168
1354
  const turn = conv.turn
1169
1355
  if (turn === undefined) return
1170
1356
  if (!turn.finished && conv.sessionId !== undefined)
1171
1357
  conv.process?.cancel(conv.sessionId)
1172
- turn.abandon(reason)
1173
1358
  conv.turn = undefined
1359
+ turn.abandon(reason)
1174
1360
  conv.dirty = true
1175
1361
  conv.reportedToolCalls.clear()
1176
1362
  }
@@ -1233,7 +1419,7 @@ export class AntigravityRuntime {
1233
1419
  const call = turn.calls.get(callId)
1234
1420
  if (call === undefined)
1235
1421
  return toolError(`Unknown harness call id ${callId}.`)
1236
- turn.relaying = false
1422
+ turn.resumeRelay(callId)
1237
1423
  return this.awaitCall(turn, call, request.signal)
1238
1424
  }
1239
1425
  let name = request.name
@@ -1268,21 +1454,22 @@ export class AntigravityRuntime {
1268
1454
  const relayAfterMs =
1269
1455
  this.host.relayAfterMs ??
1270
1456
  this.host.config.relayAfterMs ??
1271
- DEFAULT_RELAY_AFTER_MS
1457
+ defaults.relayAfterMs
1272
1458
  const relay = new Promise<'relay'>((resolve) => {
1273
1459
  timer = setTimeout(() => resolve('relay'), relayAfterMs)
1274
1460
  })
1461
+ let onAbort: (() => void) | undefined
1275
1462
  const aborted = new Promise<'aborted'>((resolve) => {
1276
1463
  if (signal.aborted) resolve('aborted')
1277
- else
1278
- signal.addEventListener('abort', () => resolve('aborted'), {
1279
- once: true,
1280
- })
1464
+ else {
1465
+ onAbort = () => resolve('aborted')
1466
+ signal.addEventListener('abort', onAbort, { once: true })
1467
+ }
1281
1468
  })
1282
1469
  try {
1283
1470
  const outcome = await Promise.race([call.result.promise, relay, aborted])
1284
1471
  if (outcome === 'relay') {
1285
- turn.relaying = true
1472
+ turn.markRelayed(call.id)
1286
1473
  return relayNotice(call)
1287
1474
  }
1288
1475
  if (outcome === 'aborted')
@@ -1290,6 +1477,7 @@ export class AntigravityRuntime {
1290
1477
  return outcome
1291
1478
  } finally {
1292
1479
  if (timer !== undefined) clearTimeout(timer)
1480
+ if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
1293
1481
  }
1294
1482
  }
1295
1483
 
@@ -1298,7 +1486,11 @@ export class AntigravityRuntime {
1298
1486
  const now = Date.now()
1299
1487
  for (const conv of [...this.conversations.values()]) {
1300
1488
  if (this.isIdle(conv) && now - conv.lastUsed > ttl) {
1301
- void this.resetSession(conv)
1489
+ void this.resetSession(conv).catch((error: unknown) => {
1490
+ this.host.log.warn(
1491
+ `session sweep cleanup failed: ${error instanceof Error ? error.message : String(error)}`,
1492
+ )
1493
+ })
1302
1494
  this.conversations.delete(conv.key)
1303
1495
  }
1304
1496
  }
@@ -1338,10 +1530,6 @@ export function mapError(error: unknown): Error {
1338
1530
  { cause: error },
1339
1531
  )
1340
1532
  }
1341
- if (/quota|resource.?exhausted|limit reached|exceeded your/i.test(message))
1342
- return new LlmError(message, 'QUOTA', { cause: error })
1343
- if (/rate.?limit|429|too many requests|overloaded|capacity/i.test(message))
1344
- return new LlmError(message, 'RATE_LIMIT', { cause: error })
1345
1533
  if (/timeout|timed out|deadline/i.test(message))
1346
1534
  return new LlmError(message, 'TIMEOUT', { cause: error })
1347
1535
  if (
@@ -1350,6 +1538,10 @@ export function mapError(error: unknown): Error {
1350
1538
  )
1351
1539
  )
1352
1540
  return new LlmError(message, 'CONTEXT_WINDOW_EXCEEDED', { cause: error })
1541
+ if (/rate.?limit|429|too many requests|overloaded|capacity/i.test(message))
1542
+ return new LlmError(message, 'RATE_LIMIT', { cause: error })
1543
+ if (/quota|resource.?exhausted|limit reached|exceeded your/i.test(message))
1544
+ return new LlmError(message, 'QUOTA', { cause: error })
1353
1545
  if (error instanceof JsonRpcRemoteError)
1354
1546
  return new LlmError(`Antigravity: ${message}`, 'SERVER', { cause: error })
1355
1547
  return new LlmError(message, 'TRANSPORT', { cause: error })