pi-agy-acp 0.1.2 → 0.1.3

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,11 +520,14 @@ 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)
467
524
  if (conv.sessionId === undefined) {
468
525
  conv.systemHash = digest(split.system)
469
526
  await this.openSession(conv, split.system, tools, proc)
470
527
  }
528
+ this.assertOwner(proc, conv, conv.sessionId)
471
529
  await this.select(conv, proc, options.model, effort)
530
+ this.assertOwner(proc, conv, conv.sessionId)
472
531
  let blocks: AcpPromptBlock[]
473
532
  if (plan.rebuild) {
474
533
  blocks = replayPrompt(plan.history, plan.input)
@@ -478,18 +537,32 @@ export class AntigravityRuntime {
478
537
  if (toolDelta.length > 0)
479
538
  blocks.unshift({ type: 'text', text: `${toolDelta}\n\n` })
480
539
  }
540
+ if (options.signal?.aborted) {
541
+ this.dropTurn(conv, 'The harness cancelled this request.')
542
+ yield {
543
+ type: 'finish',
544
+ reason: {
545
+ kind: 'aborted',
546
+ failure: { message: 'Request aborted', code: 'ABORTED' },
547
+ },
548
+ }
549
+ return
550
+ }
481
551
  conv.knownIds = messageIds(split.messages)
482
552
  // A new turn starts with an empty reported-identity space: ids from past
483
553
  // turns must never back a fresh permission request.
484
554
  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)
555
+ const turn = conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
556
+ this.startPrompt(conv, turn, proc, blocks)
557
+ yield* this.pump(conv, turn, proc, options, effort)
488
558
  } finally {
489
- release()
490
- if (conv !== undefined) {
491
- conv.opening = false
492
- await this.afterStep(conv)
559
+ try {
560
+ if (conv !== undefined) {
561
+ conv.opening = false
562
+ await this.afterStep(conv)
563
+ }
564
+ } finally {
565
+ release()
493
566
  }
494
567
  }
495
568
  }
@@ -502,13 +575,18 @@ export class AntigravityRuntime {
502
575
  * deadlock.
503
576
  */
504
577
  private async acquireConversation(key: string): Promise<Conversation> {
578
+ this.assertActive()
505
579
  const existing = this.conversations.get(key)
506
580
  if (existing !== undefined) {
507
581
  existing.opening = true
508
582
  return existing
509
583
  }
510
- const unlock = await this.capacityMutex.acquire('capacity')
584
+ const unlock = await this.capacityMutex.acquire(
585
+ 'capacity',
586
+ this.shutdown.signal,
587
+ )
511
588
  try {
589
+ this.assertActive()
512
590
  const again = this.conversations.get(key)
513
591
  if (again !== undefined) {
514
592
  again.opening = true
@@ -523,6 +601,7 @@ export class AntigravityRuntime {
523
601
  const victim = idle.shift() as Conversation
524
602
  this.conversations.delete(victim.key)
525
603
  await this.resetSession(victim)
604
+ this.assertActive()
526
605
  }
527
606
  }
528
607
  if (this.conversations.size >= max) {
@@ -549,7 +628,7 @@ export class AntigravityRuntime {
549
628
  configOptions: [],
550
629
  systemHash: undefined,
551
630
  advertisedTools: [],
552
- advertisedToolNames: new Set(),
631
+ advertisedToolDigests: new Map(),
553
632
  knownTools: new Map(),
554
633
  toolNames: new Set(),
555
634
  reportedToolCalls: new Map(),
@@ -570,8 +649,10 @@ export class AntigravityRuntime {
570
649
  this.state = 'starting'
571
650
  let proc: AcpProcess | undefined
572
651
  try {
573
- const preflight = await this.runPreflight()
652
+ const preflight = await abortable(this.runPreflight(), this.shutdown.signal)
653
+ this.assertActive()
574
654
  await this.bridge.start()
655
+ this.assertActive()
575
656
  const argv = [
576
657
  preflight.binary,
577
658
  'acp',
@@ -594,16 +675,20 @@ export class AntigravityRuntime {
594
675
  clientVersion: VERSION,
595
676
  log: (message) => this.host.log.warn(message),
596
677
  })
678
+ this.process = proc
597
679
  const started = proc
598
680
  proc.onExit((error) => this.onProcessExit(started, error))
599
681
  await proc.start(120_000)
600
- this.process = proc
682
+ this.assertOwner(proc)
601
683
  this.state = 'ready'
602
684
  this.lastError = undefined
603
685
  return proc
604
686
  } catch (error) {
605
687
  proc?.stop()
688
+ if (this.process === proc) this.process = undefined
689
+ if (this.lifecycle !== 'active') throw this.shutdown.signal.reason
606
690
  await this.bridge.close()
691
+ this.assertActive()
607
692
  if (this.sweeper !== undefined) clearInterval(this.sweeper)
608
693
  this.sweeper = undefined
609
694
  this.state = 'error'
@@ -621,6 +706,7 @@ export class AntigravityRuntime {
621
706
  const config = this.host.config
622
707
  const binary = resolveAgyBinary(config.command)
623
708
  const version = await readVersion(binary, this.host.runCommand)
709
+ this.assertActive()
624
710
  assertSupportedAgyVersion(version, binary)
625
711
  const workspace = prepareHome(this.home)
626
712
  const result: PreflightResult = {
@@ -639,21 +725,20 @@ export class AntigravityRuntime {
639
725
  }
640
726
 
641
727
  private onProcessExit(proc: AcpProcess, error: Error): void {
642
- if (this.process === proc) this.process = undefined
643
- if (!this.disposed) {
728
+ const current = this.process === proc
729
+ if (current) this.process = undefined
730
+ if (current && this.lifecycle === 'active') {
644
731
  this.state = 'error'
645
732
  this.lastError = error.message
646
733
  this.host.log.warn(`antigravity-acp: ${error.message}`)
647
734
  }
648
735
  for (const conv of this.conversations.values()) {
649
736
  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
- })
737
+ conv.turn?.fail(new LlmError(
738
+ `Antigravity ACP process exited: ${error.message}`,
739
+ 'TRANSPORT',
740
+ ))
741
+ conv.turn = undefined
657
742
  this.clearSession(conv)
658
743
  conv.dirty = true
659
744
  }
@@ -665,11 +750,16 @@ export class AntigravityRuntime {
665
750
  tools: readonly BridgeTool[],
666
751
  proc: AcpProcess,
667
752
  ): Promise<void> {
753
+ this.assertOwner(proc, conv)
668
754
  syncOAuthToken(this.home)
669
755
  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)]))
756
+ const compacted = tools.map(compactBridgeTool)
757
+ const supplementalTools = tools.filter(
758
+ (raw, index) => compacted[index] !== raw,
759
+ )
760
+ conv.advertisedTools = compacted
761
+ conv.advertisedToolDigests = new Map(tools.map((t) => [t.name, digest(t)]))
762
+ conv.knownTools = new Map(conv.advertisedToolDigests)
673
763
  const tenantKey = randomBytes(16).toString('hex')
674
764
  const tenantSecret = randomBytes(24).toString('hex')
675
765
  const mcpServers = [
@@ -690,12 +780,18 @@ export class AntigravityRuntime {
690
780
  mcpServers,
691
781
  _meta: {
692
782
  antigravity: {
693
- systemPrompt: { append: bridgeSystemPrompt(system) },
783
+ systemPrompt: {
784
+ append: bridgeSystemPrompt(system, supplementalTools),
785
+ },
694
786
  },
695
787
  },
696
788
  },
697
789
  {
698
790
  onUpdate: (update) => {
791
+ if (
792
+ !this.owns(proc, conv) ||
793
+ conv.tenantKey !== tenantKey
794
+ ) return
699
795
  if (
700
796
  update.sessionUpdate === 'config_option_update' &&
701
797
  Array.isArray(update.configOptions)
@@ -711,10 +807,18 @@ export class AntigravityRuntime {
711
807
  }
712
808
  conv.turn?.onUpdate(update)
713
809
  },
714
- onPermission: (request) => this.answerPermission(conv, request),
810
+ onPermission: (request) => this.owns(proc, conv) && conv.tenantKey === tenantKey
811
+ ? this.answerPermission(conv, request)
812
+ : { outcome: 'cancelled' },
715
813
  },
716
814
  120_000,
717
815
  )
816
+ // A buffered session/new reply can resolve after its process has exited.
817
+ if (!this.owns(proc, conv)) {
818
+ await this.closeAndCleanSession(proc, result.sessionId)
819
+ this.assertActive()
820
+ throw new LlmError('Conversation ownership changed', 'TRANSPORT')
821
+ }
718
822
  conv.sessionId = result.sessionId
719
823
  conv.process = proc
720
824
  conv.configOptions = result.configOptions ?? []
@@ -832,15 +936,12 @@ export class AntigravityRuntime {
832
936
  return reject('tool name conflict')
833
937
  if (reported.serverName !== MCP_SERVER_NAME)
834
938
  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
- ) {
939
+ const isAllowedTool =
940
+ reported.toolName !== undefined &&
941
+ (conv.advertisedToolDigests.has(reported.toolName) ||
942
+ reported.toolName === AWAIT_TOOL_NAME ||
943
+ reported.toolName === CALL_TOOL_NAME)
944
+ if (!isAllowedTool) {
844
945
  return reject(
845
946
  `tool is not offered to this session: ${reported.toolName ?? '(none)'}`,
846
947
  )
@@ -855,6 +956,7 @@ export class AntigravityRuntime {
855
956
  effort: Effort,
856
957
  ): Promise<void> {
857
958
  const sessionId = conv.sessionId as string
959
+ this.assertOwner(proc, conv, sessionId)
858
960
  const modelOption = conv.configOptions.find(
859
961
  (o) => o.id === 'model' || o.category === 'model',
860
962
  )
@@ -868,11 +970,13 @@ export class AntigravityRuntime {
868
970
  )
869
971
  }
870
972
  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
- })
973
+ await this.applyConfigOption(
974
+ conv,
975
+ proc,
976
+ sessionId,
977
+ modelOption?.id ?? 'model',
978
+ model,
979
+ )
876
980
  }
877
981
  conv.model = model
878
982
  const levelOption = conv.configOptions.find(
@@ -887,15 +991,27 @@ export class AntigravityRuntime {
887
991
  conv.effort !== effort &&
888
992
  levelOption.currentValue !== effort
889
993
  ) {
890
- conv.configOptions = await proc
891
- .setConfigOption(sessionId, levelOption.id, effort)
892
- .catch((error: unknown) => {
893
- throw mapError(error)
894
- })
994
+ await this.applyConfigOption(conv, proc, sessionId, levelOption.id, effort)
895
995
  }
896
996
  conv.effort = effort
897
997
  }
898
998
 
999
+ private async applyConfigOption(
1000
+ conv: Conversation,
1001
+ proc: AcpProcess,
1002
+ sessionId: string,
1003
+ optionId: string,
1004
+ value: string,
1005
+ ): Promise<void> {
1006
+ const configOptions = await proc
1007
+ .setConfigOption(sessionId, optionId, value)
1008
+ .catch((error: unknown) => {
1009
+ throw mapError(error)
1010
+ })
1011
+ this.assertOwner(proc, conv, sessionId)
1012
+ conv.configOptions = configOptions
1013
+ }
1014
+
899
1015
  private plan(
900
1016
  conv: Conversation,
901
1017
  system: string,
@@ -972,13 +1088,21 @@ export class AntigravityRuntime {
972
1088
  return false
973
1089
  }
974
1090
 
1091
+ private async closeAndCleanSession(
1092
+ proc: AcpProcess,
1093
+ sessionId: string,
1094
+ ): Promise<void> {
1095
+ try {
1096
+ await proc.closeSession(sessionId)
1097
+ } finally {
1098
+ removeSessionArtifacts(this.home, sessionId)
1099
+ }
1100
+ }
1101
+
975
1102
  private async resetSession(conv: Conversation): Promise<void> {
976
1103
  let closing: Promise<void> | undefined
977
1104
  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))
1105
+ closing = this.closeAndCleanSession(conv.process, conv.sessionId)
982
1106
  }
983
1107
  this.clearSession(conv)
984
1108
  conv.knownIds = undefined
@@ -993,33 +1117,58 @@ export class AntigravityRuntime {
993
1117
  conv.tenantSecret = undefined
994
1118
  conv.process = undefined
995
1119
  conv.advertisedTools = []
996
- conv.advertisedToolNames.clear()
1120
+ conv.advertisedToolDigests.clear()
997
1121
  conv.knownTools.clear()
998
1122
  conv.reportedToolCalls.clear()
999
1123
  }
1000
1124
 
1001
1125
  private startPrompt(
1002
1126
  conv: Conversation,
1127
+ turn: AcpTurn,
1003
1128
  proc: AcpProcess,
1004
1129
  blocks: AcpPromptBlock[],
1005
1130
  ): 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
- )
1131
+ // AcpProcess.prompt's link() can throw before returning a promise (buffered reply + exit).
1132
+ // Queue that failure too, so every allocated turn reaches the pump's cleanup owner.
1133
+ try {
1134
+ this.assertOwner(proc, conv, conv.sessionId)
1135
+ turn.promptSettled = proc.prompt(conv.sessionId as string, blocks).then(
1136
+ (result) => turn.events.push({ kind: 'done', result }),
1137
+ (error: unknown) => turn.fail(mapError(error)),
1138
+ )
1139
+ } catch (error) {
1140
+ turn.fail(mapError(error))
1141
+ }
1012
1142
  }
1013
1143
 
1014
1144
  private async *pump(
1015
1145
  conv: Conversation,
1146
+ turn: AcpTurn,
1016
1147
  proc: AcpProcess,
1017
1148
  options: GenerateOptions,
1018
1149
  effort: Effort,
1019
1150
  ): AsyncGenerator<StreamChunk> {
1020
- const turn = conv.turn as AcpTurn
1021
1151
  const sessionId = conv.sessionId as string
1022
1152
  let finishKind: string | undefined
1153
+ let drained = false
1154
+ const cancel = () => {
1155
+ if (conv.turn === turn)
1156
+ this.dropTurn(conv, 'The harness cancelled this request.')
1157
+ }
1158
+ // Pi 1.5.2 pi-agent-core/dist/agent-loop.js shares this signal with tool execution.
1159
+ turn.releaseSignal?.()
1160
+ turn.releaseSignal = undefined
1161
+ if (options.signal !== undefined) {
1162
+ const signal = options.signal
1163
+ signal.addEventListener('abort', cancel, { once: true })
1164
+ turn.releaseSignal = () => {
1165
+ signal.removeEventListener('abort', cancel)
1166
+ }
1167
+ if (signal.aborted) cancel()
1168
+ }
1169
+ const signal = options.signal === undefined
1170
+ ? turn.cancellation.signal
1171
+ : AbortSignal.any([options.signal, turn.cancellation.signal])
1023
1172
  const recordTurn = (
1024
1173
  outcome: NonNullable<RuntimeStatus['lastTurn']>['outcome'],
1025
1174
  ) => {
@@ -1035,53 +1184,76 @@ export class AntigravityRuntime {
1035
1184
  }
1036
1185
  }
1037
1186
  try {
1038
- for await (const chunk of pumpStep(
1187
+ for await (const emitted of pumpStep(
1039
1188
  turn,
1040
1189
  {
1041
1190
  parkSettleMs: this.host.config.parkSettleMs,
1042
1191
  maxContinuations: this.host.config.longDecodeContinuations,
1043
1192
  continuePrompt: () =>
1044
1193
  proc.prompt(sessionId, [{ type: 'text', text: CONTINUE_PROMPT }]),
1045
- cancel: () => proc.cancel(sessionId),
1194
+ cancel: () => {
1195
+ if (conv.turn === turn) proc.cancel(sessionId)
1196
+ },
1046
1197
  },
1047
- options.signal,
1198
+ signal,
1048
1199
  )) {
1200
+ // for-await adds a microtask boundary after pumpStep's own emission guard.
1201
+ const chunk = turn.guard(emitted, signal) as StreamChunk
1049
1202
  if (chunk.type === 'block-end' && chunk.block.type === 'tool-call')
1050
1203
  conv.issuedIds.add(chunk.block.id)
1051
1204
  if (chunk.type === 'finish') finishKind = chunk.reason.kind
1052
1205
  yield chunk
1206
+ if (chunk.type === 'finish' && chunk.reason.kind === 'aborted') break
1053
1207
  }
1208
+ const interrupted = turn.guard(undefined, signal)
1209
+ if (interrupted !== undefined && finishKind !== 'aborted') {
1210
+ finishKind = 'aborted'
1211
+ yield interrupted
1212
+ }
1213
+ drained = true
1054
1214
  } catch (error) {
1055
- recordTurn('error')
1056
- conv.reportedToolCalls.clear()
1057
- conv.turn = undefined
1058
- conv.dirty = true
1215
+ finishKind = 'error'
1059
1216
  throw mapError(error)
1217
+ } finally {
1218
+ // Only a fully consumed tool handoff keeps the turn and its cancellation owner.
1219
+ if (!(drained && finishKind === 'tool-calls' && !signal.aborted && conv.turn === turn)) {
1220
+ recordTurn(
1221
+ finishKind === 'error' ? 'error' : signal.aborted ? 'aborted'
1222
+ : !drained ? 'error' : 'completed',
1223
+ )
1224
+ if (conv.turn === turn) {
1225
+ if (!drained || finishKind === 'aborted' || finishKind === 'error')
1226
+ this.dropTurn(conv, 'The harness ended this request.')
1227
+ else {
1228
+ turn.abandon('The turn completed.')
1229
+ conv.reportedToolCalls.clear()
1230
+ conv.turn = undefined
1231
+ }
1232
+ }
1233
+ if (finishKind === 'aborted' || !drained) {
1234
+ let timer: ReturnType<typeof setTimeout> | undefined
1235
+ try {
1236
+ await Promise.race([
1237
+ turn.promptSettled,
1238
+ new Promise<void>((resolve) => {
1239
+ timer = setTimeout(resolve, 5_000)
1240
+ }),
1241
+ ])
1242
+ } finally {
1243
+ clearTimeout(timer)
1244
+ }
1245
+ }
1246
+ }
1060
1247
  }
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
1248
  }
1078
1249
 
1079
- private async deliverResults(
1250
+ private deliverResults(
1080
1251
  conv: Conversation,
1081
1252
  messages: readonly RequestMessage[],
1082
1253
  proc: AcpProcess,
1083
1254
  tools: readonly BridgeTool[],
1084
- ): Promise<boolean> {
1255
+ ): AcpTurn | undefined {
1256
+ this.assertOwner(proc, conv, conv.sessionId)
1085
1257
  const turn = conv.turn as AcpTurn
1086
1258
  const results = new Map<string, Extract<RequestMessage, { role: 'tool' }>>()
1087
1259
  let last = -1
@@ -1094,10 +1266,10 @@ export class AntigravityRuntime {
1094
1266
  last = Math.max(last, index)
1095
1267
  }
1096
1268
  })
1097
- if (results.size !== turn.pendingCalls.size) return false
1269
+ if (results.size !== turn.pendingCalls.size) return undefined
1098
1270
  const extras = messages.slice(last + 1)
1099
1271
  if (extras.some((m) => m.role === 'assistant' || m.role === 'tool'))
1100
- return false
1272
+ return undefined
1101
1273
  const extraText = extras.length > 0 ? renderTranscript(extras) : ''
1102
1274
  const toolDelta = consumeToolDelta(conv, tools)
1103
1275
  const suffix = [toolDelta, extraText].filter(Boolean).join('\n\n')
@@ -1109,15 +1281,16 @@ export class AntigravityRuntime {
1109
1281
  pending.map((call) => results.get(call.id) as RequestMessage),
1110
1282
  )
1111
1283
  // The old turn is over: its reported identities do not carry into the continuation.
1284
+ turn.abandon('The agent ended the tool-waiting prompt.')
1112
1285
  conv.reportedToolCalls.clear()
1113
- conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
1114
- this.startPrompt(conv, proc, [
1286
+ const next = conv.turn = new AcpTurn(randomBytes(6).toString('hex'))
1287
+ this.startPrompt(conv, next, proc, [
1115
1288
  {
1116
1289
  type: 'text',
1117
1290
  text: `${transcript}${suffix ? `\n\n${suffix}` : ''}\n\nContinue the task with these tool results.`,
1118
1291
  },
1119
1292
  ])
1120
- return true
1293
+ return next
1121
1294
  }
1122
1295
  for (const [index, call] of pending.entries()) {
1123
1296
  const message = results.get(call.id) as Extract<
@@ -1132,7 +1305,7 @@ export class AntigravityRuntime {
1132
1305
  result.content.push({ type: 'text', text: `\n\n${suffix}` })
1133
1306
  call.result.resolve(result)
1134
1307
  }
1135
- return true
1308
+ return turn
1136
1309
  }
1137
1310
 
1138
1311
  private isTurnLive(turn: AcpTurn): boolean {
@@ -1164,13 +1337,19 @@ export class AntigravityRuntime {
1164
1337
  return { content: items, ...(isError ? { isError: true } : {}) }
1165
1338
  }
1166
1339
 
1340
+ /** Release residual work for the Pi run that owns this session. */
1341
+ settleSession(sessionId: string): void {
1342
+ const conv = this.conversations.get(sessionId)
1343
+ if (conv !== undefined) this.dropTurn(conv, 'The owning Pi run settled.')
1344
+ }
1345
+
1167
1346
  private dropTurn(conv: Conversation, reason: string): void {
1168
1347
  const turn = conv.turn
1169
1348
  if (turn === undefined) return
1170
1349
  if (!turn.finished && conv.sessionId !== undefined)
1171
1350
  conv.process?.cancel(conv.sessionId)
1172
- turn.abandon(reason)
1173
1351
  conv.turn = undefined
1352
+ turn.abandon(reason)
1174
1353
  conv.dirty = true
1175
1354
  conv.reportedToolCalls.clear()
1176
1355
  }
@@ -1233,7 +1412,7 @@ export class AntigravityRuntime {
1233
1412
  const call = turn.calls.get(callId)
1234
1413
  if (call === undefined)
1235
1414
  return toolError(`Unknown harness call id ${callId}.`)
1236
- turn.relaying = false
1415
+ turn.resumeRelay(callId)
1237
1416
  return this.awaitCall(turn, call, request.signal)
1238
1417
  }
1239
1418
  let name = request.name
@@ -1268,21 +1447,22 @@ export class AntigravityRuntime {
1268
1447
  const relayAfterMs =
1269
1448
  this.host.relayAfterMs ??
1270
1449
  this.host.config.relayAfterMs ??
1271
- DEFAULT_RELAY_AFTER_MS
1450
+ defaults.relayAfterMs
1272
1451
  const relay = new Promise<'relay'>((resolve) => {
1273
1452
  timer = setTimeout(() => resolve('relay'), relayAfterMs)
1274
1453
  })
1454
+ let onAbort: (() => void) | undefined
1275
1455
  const aborted = new Promise<'aborted'>((resolve) => {
1276
1456
  if (signal.aborted) resolve('aborted')
1277
- else
1278
- signal.addEventListener('abort', () => resolve('aborted'), {
1279
- once: true,
1280
- })
1457
+ else {
1458
+ onAbort = () => resolve('aborted')
1459
+ signal.addEventListener('abort', onAbort, { once: true })
1460
+ }
1281
1461
  })
1282
1462
  try {
1283
1463
  const outcome = await Promise.race([call.result.promise, relay, aborted])
1284
1464
  if (outcome === 'relay') {
1285
- turn.relaying = true
1465
+ turn.markRelayed(call.id)
1286
1466
  return relayNotice(call)
1287
1467
  }
1288
1468
  if (outcome === 'aborted')
@@ -1290,6 +1470,7 @@ export class AntigravityRuntime {
1290
1470
  return outcome
1291
1471
  } finally {
1292
1472
  if (timer !== undefined) clearTimeout(timer)
1473
+ if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
1293
1474
  }
1294
1475
  }
1295
1476
 
@@ -1298,7 +1479,11 @@ export class AntigravityRuntime {
1298
1479
  const now = Date.now()
1299
1480
  for (const conv of [...this.conversations.values()]) {
1300
1481
  if (this.isIdle(conv) && now - conv.lastUsed > ttl) {
1301
- void this.resetSession(conv)
1482
+ void this.resetSession(conv).catch((error: unknown) => {
1483
+ this.host.log.warn(
1484
+ `session sweep cleanup failed: ${error instanceof Error ? error.message : String(error)}`,
1485
+ )
1486
+ })
1302
1487
  this.conversations.delete(conv.key)
1303
1488
  }
1304
1489
  }
@@ -1338,10 +1523,6 @@ export function mapError(error: unknown): Error {
1338
1523
  { cause: error },
1339
1524
  )
1340
1525
  }
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
1526
  if (/timeout|timed out|deadline/i.test(message))
1346
1527
  return new LlmError(message, 'TIMEOUT', { cause: error })
1347
1528
  if (
@@ -1350,6 +1531,10 @@ export function mapError(error: unknown): Error {
1350
1531
  )
1351
1532
  )
1352
1533
  return new LlmError(message, 'CONTEXT_WINDOW_EXCEEDED', { cause: error })
1534
+ if (/rate.?limit|429|too many requests|overloaded|capacity/i.test(message))
1535
+ return new LlmError(message, 'RATE_LIMIT', { cause: error })
1536
+ if (/quota|resource.?exhausted|limit reached|exceeded your/i.test(message))
1537
+ return new LlmError(message, 'QUOTA', { cause: error })
1353
1538
  if (error instanceof JsonRpcRemoteError)
1354
1539
  return new LlmError(`Antigravity: ${message}`, 'SERVER', { cause: error })
1355
1540
  return new LlmError(message, 'TRANSPORT', { cause: error })