omp-antigravity-acp-provider 0.2.4 → 0.3.2

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.
@@ -1,11 +1,13 @@
1
- import { AcpFailure } from "../acp-errors.ts";
1
+ import { AcpFailure, classifyAcpFailure, type AcpFailureContext } from "../acp-errors.ts";
2
2
  import { ToolRelay, resolveRelayConfig, relayControlTool, projectedMcpName, TOOL_RELAY_CONTROL_NAME } from "./tools/relay.ts";
3
+ import { RelayDelivery, hasUndeliveredRelay, relayNoticeCallId, type DeliveryBatch, type DeliveryDecision, type DeliveryEntry } from "./tools/delivery.ts";
3
4
  import { claimContinuation } from "../continuation-claim.ts";
4
5
  import { drainCancelledTurn, isSteerAbort, steerMode } from "../turn-cancellation.ts";
5
6
  import { createHistoryFingerprintMemo, createStructuredFingerprintMemo } from "./binding.ts";
6
7
  import { captureImageHistoryCheckpoint, matchesImageHistoryCheckpoint, type ImageHistoryCheckpoint } from "./image-history.ts";
7
8
  import { HistorySeedError, HistorySeedGuard } from "./history-seed.ts";
8
- import { ompToolGuidance, type NativeToolMode, type SessionRoutingKind } from "../tool-routing.ts";
9
+ import { cleanOmpSystemInstructions, ompToolGuidance, type NativeToolMode, type SessionRoutingKind } from "../tool-routing.ts";
10
+ import { cloakText, turnsAway } from "../prompt-cloak.ts";
9
11
  import type {
10
12
  ContentBlock,
11
13
  InitializeResponse,
@@ -136,7 +138,7 @@ export type ShadowCheckpoint =
136
138
  | { kind: "uncertain"; reason: ShadowRebuildReason };
137
139
 
138
140
  interface Binding {
139
- ompFallbackContextTokens?: number; ompInFlight: boolean; ompInvalidated: boolean; ompCompactionInvalidated?: boolean; ompSeeding?: boolean; ompSeedGuard?: HistorySeedGuard; ompImageCheckpoint?: ImageHistoryCheckpoint; ompDropPromise?: Promise<void>; ompExpectedAssistantHasOutput: boolean; ompExpectedAssistantNormalized?: string; ompConversationFingerprint?: string; ompReleaseLease?: (wait?: boolean) => Promise<void>; pendingConversationFingerprint?: string; relay: ToolRelay; relayBridge?: PiMcpBridge; relayFingerprint: string;
141
+ ompFallbackContextTokens?: number; ompInFlight: boolean; ompInvalidated: boolean; ompCompactionInvalidated?: boolean; ompSeeding?: boolean; ompSeedGuard?: HistorySeedGuard; ompImageCheckpoint?: ImageHistoryCheckpoint; ompDropPromise?: Promise<void>; ompExpectedAssistantHasOutput: boolean; ompExpectedAssistantNormalized?: string; ompUnabsorbedToolBoundary?: boolean; ompUnabsorbedToolBoundaryFingerprint?: string; ompUnabsorbedToolBoundaryNormalized?: string; ompConversationFingerprint?: string; ompReleaseLease?: (wait?: boolean) => Promise<void>; pendingConversationFingerprint?: string; relay: ToolRelay; delivery: RelayDelivery; relayBridge?: PiMcpBridge; relayFingerprint: string;
140
142
  ompTerminalStopReason?: PromptResponse["stopReason"];
141
143
  ompCancelledCheckpoint?: boolean;
142
144
  ompCancelledHadOutput?: boolean;
@@ -203,6 +205,16 @@ function ompRoutingChannel(connection: AntigravityAcpConnection): OmpRoutedConne
203
205
  return (connection as AntigravityAcpConnection & OmpRoutedConnection).toolRouting;
204
206
  }
205
207
 
208
+ // The failure classifier only calls a 429 a prompt rejection when the session
209
+ // itself carried a phrase agy refuses. The append channel sends cleaned text
210
+ // and disabled mode cloaks the known phrases away, so the hint must describe
211
+ // what the session received, not the raw OMP instructions.
212
+ function promptFingerprinted(routing: OmpRoutedConnection["toolRouting"], instructions: string): boolean {
213
+ if (routing?.channel !== "system-append") return turnsAway(instructions);
214
+ const cleaned = cleanOmpSystemInstructions(instructions);
215
+ return turnsAway(routing.nativeTools === "disabled" ? cloakText(cleaned).text : cleaned);
216
+ }
217
+
206
218
  export interface PermissionView {
207
219
  id: string;
208
220
  title: string;
@@ -362,6 +374,24 @@ export class AntigravityRuntime {
362
374
  binding.toolFingerprint = nextFp;
363
375
  binding.relayFingerprint = this.ompRelayConfig().fingerprint;
364
376
  }
377
+ private ompDeliveryDecision(binding: Binding, context: Context): DeliveryDecision | undefined {
378
+ if (binding.delivery.open().length === 0) return undefined;
379
+ const absorbed = binding.pendingContextCount;
380
+ const prefixIntact = context.messages.length >= absorbed &&
381
+ this.ompMessagesFingerprint(context.messages.slice(0, absorbed)) === binding.pendingContextFingerprint;
382
+ const arriving = new Set<string>();
383
+ for (const message of context.messages.slice(absorbed)) {
384
+ if (message.role === "toolResult" && typeof message.toolCallId === "string") arriving.add(message.toolCallId);
385
+ }
386
+ return binding.delivery.decide({
387
+ promptLive: binding.turnCompletion !== undefined,
388
+ reusable: !binding.needsReconstruction && !binding.ompCompactionInvalidated && !binding.abortRequested,
389
+ prefixIntact,
390
+ newUserRequest: context.messages.findLastIndex(message => message.role === "user") >= absorbed,
391
+ arriving,
392
+ images: binding.initialize.agentCapabilities?.promptCapabilities?.image === true,
393
+ });
394
+ }
365
395
  private ompNormalizeAssistantForBoundary(message: Context["messages"][number]): Context["messages"][number] {
366
396
  if (message.role !== "assistant") return message;
367
397
  const raw: unknown = Reflect.get(message, "content");
@@ -371,7 +401,7 @@ export class AntigravityRuntime {
371
401
  return {
372
402
  ...message,
373
403
  role: "assistant",
374
- provider: "antigravity-acp",
404
+ provider: "antigravity-acp-provider",
375
405
  model: "",
376
406
  content: filtered.length ? filtered : [{ type: "text", text: "" }],
377
407
  };
@@ -386,7 +416,9 @@ export class AntigravityRuntime {
386
416
  }
387
417
 
388
418
  private readonly bindings = new Map<string, Promise<Binding>>();
419
+ private readonly authReplayedWriters = new WeakSet<PiEventWriter>();
389
420
  private readonly resolvedBindings = new Set<Binding>();
421
+ private readonly retainedDelivery = new Map<string, { entries: readonly DeliveryEntry[]; contextCount: number; contextFingerprint: string }>();
390
422
  private disposed = false;
391
423
  private closePromise: Promise<void> | undefined;
392
424
  private bindingEpoch = 0;
@@ -437,12 +469,22 @@ export class AntigravityRuntime {
437
469
  systemPrompt: getCurrentSystemPrompt(transcript.messages),
438
470
  tools: getCurrentTools(transcript.messages),
439
471
  };
440
- currentSystemInstructions(resolvedContext);
472
+ // The fingerprint hint depends on the routed instruction channel, so
473
+ // each run path sets it once the binding's routing is known.
441
474
  const route = resolveSessionRoute(options.sessionId, options.parentSessionId);
442
475
  const dispatch = route.kind === "shadow"
443
476
  ? this.runShadow(route, model, resolvedContext, options, writer)
444
477
  : this.runQueued(model, resolvedContext, options, writer);
445
478
  void dispatch.catch((error: unknown) => {
479
+ if (error instanceof AcpAuthReplay) {
480
+ const replay = route.kind === "shadow"
481
+ ? this.runShadow(route, model, resolvedContext, options, writer)
482
+ : this.runQueued(model, resolvedContext, options, writer);
483
+ void replay.catch((retryError: unknown) => {
484
+ writer.fail(retryError, options.signal?.aborted === true || isAbort(retryError));
485
+ });
486
+ return;
487
+ }
446
488
  writer.fail(error, options.signal?.aborted === true || isAbort(error));
447
489
  });
448
490
  } catch (error) {
@@ -767,6 +809,7 @@ export class AntigravityRuntime {
767
809
  cancelPiTools(binding, "Provider shut down before Pi returned the tool result");
768
810
  }
769
811
  this.resolvedBindings.clear();
812
+ this.retainedDelivery.clear();
770
813
  // Includes authentication/discovery and sessions still initializing, not just warm bindings.
771
814
  await Promise.allSettled([...this.activeConnections].map((connection) => connection.close()));
772
815
  await Promise.allSettled(
@@ -802,6 +845,11 @@ export class AntigravityRuntime {
802
845
  : (this.findContinuationKey(context) ?? `ephemeral:${crypto.randomUUID()}`);
803
846
  const tools = context.tools ?? [];
804
847
  const instructions = currentSystemInstructions(context);
848
+ const retained = this.retainedDelivery.get(key);
849
+ if (retained && (context.messages.length < retained.contextCount ||
850
+ this.ompMessagesFingerprint(context.messages.slice(0, retained.contextCount)) !== retained.contextFingerprint)) {
851
+ this.retainedDelivery.delete(key);
852
+ }
805
853
  const acpModelId = resolveAcpModelId(model, options.reasoning);
806
854
  let binding = await this.getBinding(key, mainRoute, model, acpModelId, options.apiKey, writer, tools, instructions, options.signal);
807
855
  if (binding.ompCompactionInvalidated) {
@@ -879,6 +927,9 @@ export class AntigravityRuntime {
879
927
  await claimContinuation(binding, async () => {
880
928
  binding.writer = writer;
881
929
  const continuationTurn = binding.turnCompletion; await this.noteContinuationInstructions(binding, context); if (!continuationTurn || binding.turnCompletion !== continuationTurn || binding.abortRequested || options.signal?.aborted || !binding.connection.process.alive) throw abortError();
930
+ binding.ompUnabsorbedToolBoundary = false;
931
+ binding.ompUnabsorbedToolBoundaryFingerprint = undefined;
932
+ binding.ompUnabsorbedToolBoundaryNormalized = undefined;
882
933
  binding.pendingContextCount = context.messages.length;
883
934
  binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
884
935
  binding.pendingConversationFingerprint = this.ompMessagesFingerprint(context.messages.filter(message => message.role !== 'system'));
@@ -916,14 +967,28 @@ export class AntigravityRuntime {
916
967
  binding.pendingTools.clear();
917
968
  binding.needsReconstruction = true;
918
969
  } else {
970
+ const undelivered = hasUndeliveredRelay(binding.delivery, results.map(({ pending }) => pending.invocation.id));
971
+ if (undelivered) {
972
+ binding.ompUnabsorbedToolBoundary = true;
973
+ const boundary = context.messages[binding.pendingContextCount];
974
+ if (boundary?.role === "assistant") {
975
+ binding.ompUnabsorbedToolBoundaryFingerprint = this.ompMessageFingerprint(boundary);
976
+ binding.ompUnabsorbedToolBoundaryNormalized = this.ompMessageFingerprint(this.ompNormalizeAssistantForBoundary(boundary));
977
+ }
978
+ }
919
979
  await claimContinuation(binding, async () => {
920
980
  binding.writer = writer;
921
981
  const continuationTurn = binding.turnCompletion; await this.noteContinuationInstructions(binding, context); if (!continuationTurn || binding.turnCompletion !== continuationTurn || binding.abortRequested || options.signal?.aborted || !binding.connection.process.alive) throw abortError();
922
- binding.pendingContextCount = context.messages.length;
923
- binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
924
- binding.pendingConversationFingerprint = this.ompMessagesFingerprint(context.messages.filter(message => message.role !== 'system'));
925
- binding.ompImageCheckpoint = captureImageHistoryCheckpoint(context.messages, message => this.ompMessageFingerprint(message));
926
- binding.ompFallbackContextTokens = estimateContextTokens(context);
982
+ if (!undelivered) {
983
+ binding.ompUnabsorbedToolBoundary = false;
984
+ binding.ompUnabsorbedToolBoundaryFingerprint = undefined;
985
+ binding.ompUnabsorbedToolBoundaryNormalized = undefined;
986
+ binding.pendingContextCount = context.messages.length;
987
+ binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
988
+ binding.pendingConversationFingerprint = this.ompMessagesFingerprint(context.messages.filter(message => message.role !== 'system'));
989
+ binding.ompImageCheckpoint = captureImageHistoryCheckpoint(context.messages, message => this.ompMessageFingerprint(message));
990
+ binding.ompFallbackContextTokens = estimateContextTokens(context);
991
+ }
927
992
  for (const { pending, message } of results) {
928
993
  binding.pendingTools.delete(pending.invocation.id);
929
994
  pending.resolve(toMcpToolResult(message as ToolResultMessage));
@@ -945,6 +1010,8 @@ export class AntigravityRuntime {
945
1010
  let ompDispatched = false;
946
1011
  let completeTurn: (() => void) | undefined;
947
1012
  let onTurnAbort: (() => void) | undefined;
1013
+ let deliveryBatch: DeliveryBatch | undefined;
1014
+ let deliveryOwner: Binding | undefined;
948
1015
  try {
949
1016
  await this.modeChanges;
950
1017
  this.assertEpoch(epoch);
@@ -983,6 +1050,7 @@ export class AntigravityRuntime {
983
1050
  this.ompMessagesFingerprint(context.messages.slice(0, binding.messageCount)) !==
984
1051
  binding.historyFingerprint
985
1052
  ) {
1053
+ if (context.messages.length < binding.messageCount) this.retainedDelivery.delete(key);
986
1054
  await this.dropBinding(key, binding, true);
987
1055
  binding = await this.getBinding(key, mainRoute, model, acpModelId, options.apiKey, writer, tools, instructions, options.signal);
988
1056
  }
@@ -1013,14 +1081,18 @@ export class AntigravityRuntime {
1013
1081
  // resource even when the agent advertises append support.
1014
1082
  const routing = ompRoutingChannel(binding.connection);
1015
1083
  const sessionAppend = routing?.channel === "system-append";
1084
+ writer.noteFailureContext({ promptFingerprinted: promptFingerprinted(routing, instructions) });
1016
1085
  const bridgeConfigured = binding.initialize.agentCapabilities?.mcpCapabilities?.http === true &&
1017
1086
  binding.bridge !== undefined && !binding.bridge.empty;
1018
1087
  const sessionGuidance = sessionAppend
1019
1088
  ? undefined
1020
1089
  : ompToolGuidance(binding.initialize, routing?.nativeTools ?? "prefer", bridgeConfigured,
1021
1090
  "main", binding.bridge?.projectedToolNames ?? []);
1091
+ const deliveryDecision = this.ompDeliveryDecision(binding, context);
1092
+ deliveryBatch = deliveryDecision?.batch;
1093
+ deliveryOwner = binding;
1022
1094
  const parts = adaptPromptToCapabilities(
1023
- buildPromptParts(context, fresh, unseenStart, { contextWindow: model.contextWindow, maxTokens: model.maxTokens, policy: model.ompContextPolicy, sessionRouting: sessionAppend, sessionGuidance }, ompRetryResend),
1095
+ buildPromptParts(context, fresh, unseenStart, { contextWindow: model.contextWindow, maxTokens: model.maxTokens, policy: model.ompContextPolicy, sessionRouting: sessionAppend, sessionGuidance, deliveryBlocks: deliveryBatch?.blocks }, ompRetryResend),
1024
1096
  binding.initialize,
1025
1097
  );
1026
1098
  await this.modeChanges;
@@ -1037,6 +1109,9 @@ export class AntigravityRuntime {
1037
1109
  binding.instructionsFingerprint = instructionFingerprint(context);
1038
1110
  binding.ompFallbackContextTokens = parts.estimatedContextTokens;
1039
1111
  binding.needsReconstruction = false;
1112
+ binding.ompUnabsorbedToolBoundary = false;
1113
+ binding.ompUnabsorbedToolBoundaryFingerprint = undefined;
1114
+ binding.ompUnabsorbedToolBoundaryNormalized = undefined;
1040
1115
  binding.pendingContextCount = context.messages.length;
1041
1116
  binding.pendingContextFingerprint = this.ompMessagesFingerprint(context.messages);
1042
1117
  binding.pendingConversationFingerprint = this.ompMessagesFingerprint(context.messages.filter(message => message.role !== 'system'));
@@ -1063,6 +1138,7 @@ export class AntigravityRuntime {
1063
1138
  if (binding.ompInvalidated || !binding.connection.process.alive) throw new AntigravityAcpError('protocol', 'ACP session closed before prompt dispatch');
1064
1139
  if (options.signal?.aborted) throw abortError();
1065
1140
  ompDispatched = true;
1141
+
1066
1142
  let ompSeedUsage: PromptUsageResult | undefined;
1067
1143
  if (parts.seedSteps?.length) {
1068
1144
  const savedWriter = binding.writer;
@@ -1083,9 +1159,21 @@ export class AntigravityRuntime {
1083
1159
  if (binding.ompInvalidated) throw new AntigravityAcpError('protocol', 'ACP session ownership was lost');
1084
1160
  if (binding.abortRequested || seedResponse.stopReason === 'cancelled' || options.signal?.aborted) throw abortError();
1085
1161
  // Quota notices keep their existing handling and are checked
1086
- // before the acknowledgement, which they never carry.
1087
- const seedQuota = quotaExhaustion(guard.text);
1162
+ // before the acknowledgement, which they never carry. agy
1163
+ // banners the filter already dropped still count as quota
1164
+ // evidence. A capture that only records a transient
1165
+ // `⚠ API error` retry is not a failure when the step still
1166
+ // acknowledged OK; a terminal banner, a 429 refusal or a
1167
+ // non-OK answer fails with its classified cause.
1168
+ const seedCapture = binding.connection.consumeNoticeCapture?.(binding.session.sessionId);
1169
+ const seedEvidence = seedCapture
1170
+ ? [seedCapture.terminal, seedCapture.apiDetail, seedCapture.refusedDetail].filter(Boolean).join("\n")
1171
+ : "";
1172
+ const seedQuota = quotaExhaustion(seedEvidence ? `${guard.text}\n${seedEvidence}` : guard.text);
1088
1173
  if (seedQuota) await this.ompThrowQuota(binding, seedQuota);
1174
+ if (seedCapture && (seedCapture.terminal !== undefined || seedCapture.refusedDetail !== undefined || guard.text.trim() !== "OK")) {
1175
+ throw captureFailure(seedCapture, writer.failureContext);
1176
+ }
1089
1177
  if (seedResponse.stopReason !== 'end_turn') throw new AntigravityAcpError('protocol', `ACP seed step stopped early with ${seedResponse.stopReason}`);
1090
1178
  guard.assertAcknowledged();
1091
1179
  const seedUsage = usageFromPrompt(seedResponse);
@@ -1119,16 +1207,36 @@ export class AntigravityRuntime {
1119
1207
  if (ompSeedUsage) mergeUsage(usage, ompSeedUsage);
1120
1208
  activeWriter.message.usage = usage;
1121
1209
  this.metrics.record(response, usage);
1122
- const quota = response.stopReason === "cancelled" ? undefined : quotaExhaustion(activeWriter.message.content.map(block => block.type === "text" ? block.text : "").join(""));
1210
+ const noticeCapture = binding.connection.consumeNoticeCapture?.(binding.session.sessionId);
1211
+ const turnText = activeWriter.message.content.map(block => block.type === "text" ? block.text : "").join("");
1212
+ const noticeEvidence = noticeCapture
1213
+ ? [noticeCapture.terminal, noticeCapture.apiDetail, noticeCapture.refusedDetail].filter(Boolean).join("\n")
1214
+ : "";
1215
+ const quota = response.stopReason === "cancelled" ? undefined : quotaExhaustion(noticeEvidence ? `${turnText}\n${noticeEvidence}` : turnText);
1123
1216
  if (quota) await this.ompThrowQuota(binding, quota);
1217
+ // agy reports its own failures as dropped notice lines; an empty turn
1218
+ // with captured failure evidence is a failed turn, not model silence.
1219
+ if (noticeCapture && response.stopReason !== "cancelled" && activeWriter.message.content.length === 0) {
1220
+ throw captureFailure(noticeCapture, activeWriter.failureContext);
1221
+ }
1222
+ // The batch is only delivered once this prompt turn actually consumed
1223
+ // it; a throw, a quota/banner failure or a cancellation leaves the
1224
+ // obligations open for the next turn.
1225
+ if (deliveryBatch && deliveryOwner && response.stopReason !== "cancelled" && response.stopReason !== "refusal") deliveryOwner.delivery.commit(deliveryBatch);
1124
1226
  activeWriter.message.rawStopReason = response.stopReason;
1125
1227
  binding.messageCount = binding.pendingContextCount || parts.messageCount;
1126
1228
  binding.historyFingerprint = binding.pendingContextFingerprint;
1127
1229
  binding.ompConversationFingerprint = binding.pendingConversationFingerprint;
1128
- binding.expectedAssistantFingerprint = this.ompMessageFingerprint(activeWriter.message.content.length
1129
- ? activeWriter.message : { ...activeWriter.message, content: [{ type: 'text', text: '' }] });
1130
- binding.ompExpectedAssistantNormalized = this.ompMessageFingerprint(this.ompNormalizeAssistantForBoundary(activeWriter.message));
1131
- binding.ompExpectedAssistantHasOutput = activeWriter.message.content.some(block => block.type !== 'text' || block.text.length > 0);
1230
+ if (binding.ompUnabsorbedToolBoundary && binding.ompUnabsorbedToolBoundaryFingerprint) {
1231
+ binding.expectedAssistantFingerprint = binding.ompUnabsorbedToolBoundaryFingerprint;
1232
+ binding.ompExpectedAssistantNormalized = binding.ompUnabsorbedToolBoundaryNormalized;
1233
+ binding.ompExpectedAssistantHasOutput = true;
1234
+ } else if (!binding.ompUnabsorbedToolBoundary) {
1235
+ binding.expectedAssistantFingerprint = this.ompMessageFingerprint(activeWriter.message.content.length
1236
+ ? activeWriter.message : { ...activeWriter.message, content: [{ type: 'text', text: '' }] });
1237
+ binding.ompExpectedAssistantNormalized = this.ompMessageFingerprint(this.ompNormalizeAssistantForBoundary(activeWriter.message));
1238
+ binding.ompExpectedAssistantHasOutput = activeWriter.message.content.some(block => block.type !== 'text' || block.text.length > 0);
1239
+ }
1132
1240
  binding.ompInFlight = false;
1133
1241
  if (response.stopReason !== 'cancelled') binding.ompCancelledCheckpoint = false;
1134
1242
  await this.persistBinding(binding);
@@ -1147,7 +1255,11 @@ export class AntigravityRuntime {
1147
1255
  activeWriter.done("stop");
1148
1256
  }
1149
1257
  } catch (error) {
1150
- binding.writer?.fail(error, isAbort(error));
1258
+ const replayWriter = binding.writer ?? writer;
1259
+ const authReplay = ompDispatched && !binding.ompInvalidated && !binding.abortRequested && !isAbort(error) &&
1260
+ replayWriter.message.content.length === 0 && !this.authReplayedWriters.has(writer) &&
1261
+ isAuthExpiryFailure(error);
1262
+ if (!authReplay) binding.writer?.fail(error, isAbort(error));
1151
1263
  if (isAbort(error) || binding.abortRequested) {
1152
1264
  abortTurn(binding);
1153
1265
  if (binding.connection.process.alive && !binding.ompInvalidated && !binding.needsReconstruction && !binding.ompSeeding &&
@@ -1162,20 +1274,31 @@ export class AntigravityRuntime {
1162
1274
  binding.ompCancelledHadOutput = (binding.writer ?? writer).message.content.length > 0;
1163
1275
  binding.ompExpectedAssistantHasOutput = binding.ompCancelledHadOutput;
1164
1276
  binding.ompInFlight = false;
1165
- try { await this.persistBinding(binding); } catch (checkpointError) { await this.invalidateBinding(binding); throw checkpointError; }
1277
+ try { await this.persistBinding(binding); } catch (checkpointError) { this.retainDelivery(binding); await this.invalidateBinding(binding); throw checkpointError; }
1166
1278
  if (ompWasWarm) await binding.connection.confirmReplacement?.(key, binding.session.sessionId);
1167
- } else await this.invalidateBinding(binding);
1279
+ } else { this.retainDelivery(binding); await this.invalidateBinding(binding); }
1280
+ } else if (authReplay) {
1281
+ // Drop the binding (and its saved session) so the retry rebuilds on a
1282
+ // fresh process and reseeds history; the half-persisted ACP turn
1283
+ // must not be resumed. Detach the writer first: late chunks from
1284
+ // the expired attempt must not reach the writer the replay reuses.
1285
+ binding.writer = undefined;
1286
+ this.retainDelivery(binding);
1287
+ await this.invalidateBinding(binding);
1288
+ this.authReplayedWriters.add(writer);
1289
+ throw new AcpAuthReplay();
1168
1290
  } else if (ompDispatched && !binding.ompInvalidated && error instanceof AntigravityAcpError && error.code === "quota") {
1169
1291
  binding.ompInFlight = false;
1170
- try { await this.persistBinding(binding); } catch (checkpointError) { await this.invalidateBinding(binding); throw checkpointError; }
1171
- } else if (ompDispatched && !binding.ompInvalidated) await this.invalidateBinding(binding);
1292
+ try { await this.persistBinding(binding); } catch (checkpointError) { this.retainDelivery(binding); await this.invalidateBinding(binding); throw checkpointError; }
1293
+ } else if (ompDispatched && !binding.ompInvalidated) { this.retainDelivery(binding); await this.invalidateBinding(binding); }
1172
1294
  else binding.ompInFlight = false;
1173
- if (!binding.connection.process.alive) await this.dropBinding(key, binding);
1295
+ if (!binding.connection.process.alive) { this.retainDelivery(binding); await this.dropBinding(key, binding); }
1174
1296
  throw error;
1175
1297
  } finally {
1176
1298
  if (onTurnAbort) options.signal?.removeEventListener("abort", onTurnAbort);
1177
1299
  completeTurn?.();
1178
1300
  binding.relay.endTurn();
1301
+ if (deliveryBatch && deliveryOwner) deliveryOwner.delivery.abandon(deliveryBatch);
1179
1302
  binding.turnCompletion = undefined;
1180
1303
  binding.ompFallbackContextTokens = undefined;
1181
1304
  binding.abortRequested = false;
@@ -1183,7 +1306,7 @@ export class AntigravityRuntime {
1183
1306
  release();
1184
1307
  if (this.queues.get(key) === queue) this.queues.delete(key);
1185
1308
  binding.ompSeeding = false;
1186
- if (!persistent || !binding.connection.process.alive) await this.dropBinding(key, binding);
1309
+ if (!persistent || !binding.connection.process.alive) { if (!binding.connection.process.alive) this.retainDelivery(binding); await this.dropBinding(key, binding); }
1187
1310
  }
1188
1311
  }
1189
1312
 
@@ -1245,12 +1368,13 @@ export class AntigravityRuntime {
1245
1368
  const unseenStart = fresh ? 0 : plan.kind === "delta" ? plan.unseenStart : dispatchContext.messages.length;
1246
1369
  const routing = ompRoutingChannel(binding.connection);
1247
1370
  const sessionAppend = routing?.channel === "system-append";
1371
+ writer.noteFailureContext({ promptFingerprinted: promptFingerprinted(routing, instructions) });
1248
1372
  const bridgeConfigured = binding.initialize.agentCapabilities?.mcpCapabilities?.http === true &&
1249
1373
  binding.bridge !== undefined && !binding.bridge.empty;
1250
1374
  // A side turn never executes tools. Its legacy prompt guidance must say
1251
- // so instead of advertising the main pi_task delegation mapping, and the
1375
+ // so instead of advertising the main omp_task delegation mapping, and the
1252
1376
  // prompt planner must use the ephemeral history/continuation/retry text
1253
- // that prohibits every tool call rather than only the pi_ guidance.
1377
+ // that prohibits every tool call rather than only the omp_ guidance.
1254
1378
  const sessionGuidance = sessionAppend
1255
1379
  ? undefined
1256
1380
  : ompToolGuidance(binding.initialize, routing?.nativeTools ?? "prefer", bridgeConfigured,
@@ -1287,10 +1411,16 @@ export class AntigravityRuntime {
1287
1411
  if (seedUsage) mergeUsage(usage, seedUsage);
1288
1412
  activeWriter.message.usage = usage;
1289
1413
  this.metrics.record(response, usage);
1290
- const quota = response.stopReason === "cancelled"
1291
- ? undefined
1292
- : quotaExhaustion(activeWriter.message.content.map(block => block.type === "text" ? block.text : "").join(""));
1414
+ const shadowNoticeCapture = binding.connection.consumeNoticeCapture?.(binding.session.sessionId);
1415
+ const turnText = activeWriter.message.content.map(block => block.type === "text" ? block.text : "").join("");
1416
+ const shadowEvidence = shadowNoticeCapture
1417
+ ? [shadowNoticeCapture.terminal, shadowNoticeCapture.apiDetail, shadowNoticeCapture.refusedDetail].filter(Boolean).join("\n")
1418
+ : "";
1419
+ const quota = response.stopReason === "cancelled" ? undefined : quotaExhaustion(shadowEvidence ? `${turnText}\n${shadowEvidence}` : turnText);
1293
1420
  if (quota) await this.ompThrowQuota(binding, quota);
1421
+ if (shadowNoticeCapture && response.stopReason !== "cancelled" && activeWriter.message.content.length === 0) {
1422
+ throw captureFailure(shadowNoticeCapture, activeWriter.failureContext);
1423
+ }
1294
1424
  activeWriter.message.rawStopReason = response.stopReason;
1295
1425
  if (response.stopReason === "cancelled") throw abortError();
1296
1426
  // The ACP session now holds exactly this side context; the next turn
@@ -1314,7 +1444,20 @@ export class AntigravityRuntime {
1314
1444
  }
1315
1445
  } catch (error) {
1316
1446
  binding.ompInFlight = false;
1317
- binding.writer?.fail(error, isAbort(error));
1447
+ const replayWriter = binding.writer ?? writer;
1448
+ const authReplay = !binding.ompInvalidated && !binding.abortRequested && !isAbort(error) &&
1449
+ replayWriter.message.content.length === 0 && !this.authReplayedWriters.has(writer) &&
1450
+ isAuthExpiryFailure(error);
1451
+ if (!authReplay) binding.writer?.fail(error, isAbort(error));
1452
+ if (authReplay) {
1453
+ // A side turn has no checkpoint worth keeping: drop the expired
1454
+ // binding and let the replay reseed on a fresh process. Detach the
1455
+ // writer first so late chunks cannot reach the reused writer.
1456
+ binding.writer = undefined;
1457
+ await this.invalidateBinding(binding).catch(() => undefined);
1458
+ this.authReplayedWriters.add(writer);
1459
+ throw new AcpAuthReplay();
1460
+ }
1318
1461
  binding.shadow = {
1319
1462
  kind: "uncertain",
1320
1463
  reason: isAbort(error) || binding.abortRequested ? "cancelled" : "failed",
@@ -1354,8 +1497,15 @@ export class AntigravityRuntime {
1354
1497
  ));
1355
1498
  if (binding.ompInvalidated) throw new AntigravityAcpError("protocol", "ACP session ownership was lost");
1356
1499
  if (binding.abortRequested || response.stopReason === "cancelled" || signal?.aborted) throw abortError();
1357
- const quota = quotaExhaustion(guard.text);
1500
+ const shadowCapture = binding.connection.consumeNoticeCapture?.(binding.session.sessionId);
1501
+ const shadowEvidence = shadowCapture
1502
+ ? [shadowCapture.terminal, shadowCapture.apiDetail, shadowCapture.refusedDetail].filter(Boolean).join("\n")
1503
+ : "";
1504
+ const quota = quotaExhaustion(shadowEvidence ? `${guard.text}\n${shadowEvidence}` : guard.text);
1358
1505
  if (quota) await this.ompThrowQuota(binding, quota);
1506
+ if (shadowCapture && (shadowCapture.terminal !== undefined || shadowCapture.refusedDetail !== undefined || guard.text.trim() !== "OK")) {
1507
+ throw captureFailure(shadowCapture, savedWriter?.failureContext);
1508
+ }
1359
1509
  if (response.stopReason !== "end_turn") throw new AntigravityAcpError("protocol", `ACP seed step stopped early with ${response.stopReason}`);
1360
1510
  guard.assertAcknowledged();
1361
1511
  const stepUsage = usageFromPrompt(response);
@@ -1523,6 +1673,7 @@ export class AntigravityRuntime {
1523
1673
  : tools.filter((tool) => tool.name !== PERMISSION_TOOL_NAME).map((tool) => ({ name: tool.name, reason: "Agent did not advertise MCP over HTTP" }));
1524
1674
  const relayConfig = this.ompRelayConfig();
1525
1675
  const relay = new ToolRelay(relayConfig);
1676
+ const delivery = new RelayDelivery(relay);
1526
1677
  const relayCollision = relayConfig.enabled ? tools.find(tool => projectedMcpName(tool.name) === TOOL_RELAY_CONTROL_NAME) : undefined;
1527
1678
  if (relayCollision) throw new AntigravityAcpError("invalid_input", "Tool " + relayCollision.name + " collides with the relay control tool " + TOOL_RELAY_CONTROL_NAME + "; rename it or disable OMP_ACP_TOOL_RELAY_MS");
1528
1679
  let mcpServer;
@@ -1530,17 +1681,24 @@ export class AntigravityRuntime {
1530
1681
  if (tools.length > 0 && initialize.agentCapabilities?.mcpCapabilities?.http === true) {
1531
1682
  bridge = new PiMcpBridge({
1532
1683
  tools,
1533
- onCall: (invocation) => relay.call(invocation, () => this.requestPiTool(binding, invocation)),
1684
+ onCall: async (invocation) => {
1685
+ const result = await relay.call(invocation, () => this.requestPiTool(binding, invocation));
1686
+ delivery.observe(invocation, relayNoticeCallId(result));
1687
+ return result;
1688
+ },
1534
1689
  });
1535
1690
  mcpServer = await bridge.start();
1536
1691
  if (relayConfig.enabled) {
1537
1692
  relayBridge = new PiMcpBridge({
1538
1693
  tools: [relayControlTool],
1539
- onCall: (invocation) => {
1694
+ onCall: async (invocation) => {
1540
1695
  const callId = invocation.arguments.call_id;
1541
- return typeof callId === "string" && callId
1542
- ? relay.await(callId)
1543
- : Promise.resolve({ content: [{ type: "text", text: "call_id must be a non-empty string" }], isError: true });
1696
+ if (typeof callId !== "string" || !callId) {
1697
+ return { content: [{ type: "text", text: "call_id must be a non-empty string" }], isError: true };
1698
+ }
1699
+ const result = await relay.await(callId);
1700
+ delivery.consume(callId, result);
1701
+ return result;
1544
1702
  },
1545
1703
  });
1546
1704
  relayServer = await relayBridge.start();
@@ -1598,7 +1756,7 @@ export class AntigravityRuntime {
1598
1756
  ompReleaseLease: releaseLease,
1599
1757
  ompExpectedAssistantHasOutput: restored && (saved?.ompExpectedAssistantHasOutput === true ||
1600
1758
  (saved?.ompExpectedAssistantHasOutput === undefined && Boolean(saved?.expectedAssistantFingerprint))),
1601
- relay, relayBridge, relayFingerprint: relayConfig.fingerprint,
1759
+ relay, delivery, relayBridge, relayFingerprint: relayConfig.fingerprint,
1602
1760
  pendingConversationFingerprint: this.ompMessagesFingerprint([]),
1603
1761
  key,
1604
1762
  route,
@@ -1632,11 +1790,14 @@ export class AntigravityRuntime {
1632
1790
  restored,
1633
1791
  };
1634
1792
  binding = createdBinding;
1793
+ const retainedDelivery = this.retainedDelivery.get(key);
1794
+ if (retainedDelivery !== undefined) createdBinding.delivery.adopt(retainedDelivery.entries);
1635
1795
  (binding.connection as AntigravityAcpConnection & OmpRoutedConnection).setOmpContextWindow?.(binding.session.sessionId, model.contextWindow);
1636
1796
  if (leaseLost) throw new AntigravityAcpError('protocol', 'ACP session ownership was lost during initialization');
1637
1797
  await this.persistBinding(createdBinding);
1638
1798
  this.assertEpoch(epoch);
1639
1799
  this.resolvedBindings.add(createdBinding);
1800
+ this.retainedDelivery.delete(key);
1640
1801
  void connection.process.exited.then(() => {
1641
1802
  const completion = createdBinding.turnCompletion;
1642
1803
  const retiring = createdBinding.ompDropPromise;
@@ -1797,6 +1958,15 @@ export class AntigravityRuntime {
1797
1958
  if (typeof this.sessionStore?.removeIfMatches === 'function') await this.sessionStore.removeIfMatches(piSessionId, acpSessionId);
1798
1959
  else await this.sessionStore?.remove(piSessionId);
1799
1960
  }
1961
+ private retainDelivery(binding: Binding): void {
1962
+ const entries = binding.delivery.settledOpen();
1963
+ if (entries.length > 0) this.retainedDelivery.set(binding.key, {
1964
+ entries,
1965
+ contextCount: binding.pendingContextCount,
1966
+ contextFingerprint: binding.pendingContextFingerprint,
1967
+ });
1968
+ }
1969
+
1800
1970
  private async dropBinding(key: string, binding: Binding, removeSaved = false): Promise<void> {
1801
1971
  if (removeSaved) binding.ompInvalidated = true;
1802
1972
  if (binding.ompDropPromise) {
@@ -2204,11 +2374,14 @@ function instructionFingerprint(context: Context): string {
2204
2374
  function abortTurn(binding: Binding): void {
2205
2375
  binding.abortRequested = true;
2206
2376
  cancelPermission(binding);
2207
- cancelPiTools(binding, "Pi turn was aborted before returning the tool result");
2377
+ // Cancellation must not erase a settled result that never reached ACP; the
2378
+ // next turn can still deliver it. Intentional disposal still resets.
2379
+ cancelPiTools(binding, "Pi turn was aborted before returning the tool result", false);
2208
2380
  }
2209
2381
 
2210
- function cancelPiTools(binding: Binding, reason: string): void {
2382
+ function cancelPiTools(binding: Binding, reason: string, resetDelivery = true): void {
2211
2383
  binding.relay.cancelAll(reason);
2384
+ if (resetDelivery) binding.delivery.reset();
2212
2385
  if (binding.toolBatchTimer) clearTimeout(binding.toolBatchTimer);
2213
2386
  binding.toolBatchTimer = undefined;
2214
2387
  for (const pending of binding.pendingTools.values()) {
@@ -2227,6 +2400,38 @@ async function raceAuthentication<T>(
2227
2400
  ]);
2228
2401
  }
2229
2402
 
2403
+ // A live agy process never refreshes its OAuth token; the first model call
2404
+ // after expiry fails auth before anything streams. The stream re-dispatches
2405
+ // once on a fresh process, and the rebuild reseeds history from OMP, so an
2406
+ // idle hour costs one seamless retry instead of a sign-in error.
2407
+ class AcpAuthReplay extends Error {
2408
+ constructor() {
2409
+ super("Antigravity auth expired mid-session; replaying once on a fresh process");
2410
+ }
2411
+ }
2412
+
2413
+ function isAuthExpiryFailure(error: unknown): boolean {
2414
+ const classified = classifyAcpFailure(error);
2415
+ return classified instanceof AcpFailure && classified.code === "auth";
2416
+ }
2417
+
2418
+ // agy banners dropped from the stream still explain the failure: classify the
2419
+ // captured detail so the turn ends with the real cause (auth, quota, server).
2420
+ // The writer's failure context must reach this classification: without it the
2421
+ // quota hint is appended first and the writer's later reclassification can
2422
+ // never surface a prompt rejection.
2423
+ function captureFailure(
2424
+ capture: { terminal?: string; apiDetail?: string; refusedDetail?: string },
2425
+ context?: AcpFailureContext,
2426
+ ): AcpFailure {
2427
+ const detail = capture.refusedDetail ?? capture.apiDetail ?? "";
2428
+ if (detail) {
2429
+ const classified = classifyAcpFailure(new Error(detail), context);
2430
+ if (classified instanceof AcpFailure) return classified;
2431
+ }
2432
+ return new AcpFailure("server", `Antigravity ended the turn with its own error banner (${capture.terminal ?? "error"}) and produced no output`);
2433
+ }
2434
+
2230
2435
  function isAbort(error: unknown): boolean {
2231
2436
  return error instanceof AntigravityAcpError
2232
2437
  ? error.code === "aborted"
@@ -1,4 +1,4 @@
1
- import { classifyAcpFailure } from "../../acp-errors.ts";
1
+ import { classifyAcpFailure, type AcpFailureContext } from "../../acp-errors.ts";
2
2
  import {
3
3
  type Api,
4
4
  type AssistantMessage,
@@ -19,18 +19,26 @@ export class PiEventWriter {
19
19
  private open: { kind: "text" | "thinking"; index: number } | undefined;
20
20
  private started = false;
21
21
  private terminal = false;
22
+ private context: AcpFailureContext;
22
23
 
23
24
  get finished(): boolean {
24
25
  return this.terminal;
25
26
  }
26
27
 
27
- constructor(model: Pick<Model<Api>, "id"> & Partial<Pick<Model<Api>, "api" | "provider">>) {
28
+ // Read-only for the turn runner: a captured banner must be classified with
29
+ // the same hint the writer will use when it reports the failure.
30
+ get failureContext(): AcpFailureContext {
31
+ return this.context;
32
+ }
33
+
34
+ constructor(model: Pick<Model<Api>, "id"> & Partial<Pick<Model<Api>, "api" | "provider">>, failureContext: AcpFailureContext = {}) {
35
+ this.context = failureContext;
28
36
  this.stream = createAssistantMessageEventStream();
29
37
  this.message = {
30
38
  role: "assistant",
31
39
  content: [],
32
- api: model.api ?? "antigravity-acp",
33
- provider: model.provider ?? "antigravity-acp",
40
+ api: model.api ?? "antigravity-acp-provider",
41
+ provider: model.provider ?? "antigravity-acp-provider",
34
42
  model: model.id,
35
43
  usage: emptyUsage(),
36
44
  stopReason: "pending",
@@ -38,6 +46,13 @@ export class PiEventWriter {
38
46
  };
39
47
  }
40
48
 
49
+ // Stream setup resolves the routed instructions after the writer exists;
50
+ // the fingerprint hint must reach the failure classifier before any turn
51
+ // error is written.
52
+ noteFailureContext(context: AcpFailureContext): void {
53
+ this.context = context;
54
+ }
55
+
41
56
  text(delta: string): void {
42
57
  if (!delta || this.terminal) return;
43
58
  const index = this.ensureOpen("text");
@@ -92,7 +107,7 @@ export class PiEventWriter {
92
107
  this.closeOpen();
93
108
  this.terminal = true;
94
109
  this.message.stopReason = aborted ? "aborted" : "error";
95
- this.message.errorMessage = errorMessage(classifyAcpFailure(cause));
110
+ this.message.errorMessage = errorMessage(classifyAcpFailure(cause, this.context));
96
111
  this.stream.push({
97
112
  type: "error",
98
113
  reason: aborted ? "aborted" : "error",