omp-antigravity-acp-provider 0.1.18 → 0.1.19

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/README.md CHANGED
@@ -19,7 +19,7 @@ The repository keeps the OMP adapter sources separately and installs upstream ve
19
19
 
20
20
  ## Status
21
21
 
22
- Version 0.1.18 supports all models advertised by the official ACP server. Tested with macOS, OMP 18.12.3, upstream provider 0.1.15 and official ACP runtime 1.4.1. Other platforms and OMP versions are not yet verified.
22
+ Version 0.1.19 supports all models advertised by the official ACP server. Tested with macOS, OMP 18.12.3, upstream provider 0.1.15 and official ACP runtime 1.4.1. Other platforms and OMP versions are not yet verified.
23
23
 
24
24
  Google's consumer-plan policies can restrict third-party agent access even through the official CLI or ACP executable. An official transport does not establish permission to use a subscription in OMP. Check the current [Antigravity FAQ](https://www.antigravity.google/docs/faq/) and [terms](https://antigravity.google/terms) for your account.
25
25
 
@@ -56,7 +56,7 @@ Or, inside OMP:
56
56
 
57
57
  Select **omp-antigravity-acp-provider** in the browser, install it, and restart OMP to load the provider.
58
58
 
59
- OMP's marketplace installer currently copies Git content without installing npm dependencies. This marketplace therefore ships a small source launcher that retrieves the exact published **0.1.18** prebuilt npm adapter and production dependencies on first load. It disables npm install scripts, skips Pi CLI peer installation, and performs no local compilation. Node.js 22.19+ and npm must be on PATH. First preparation needs internet access and roughly **150 MiB** of disk space; later loads reuse the installed cache without npm network access.
59
+ OMP's marketplace installer currently copies Git content without installing npm dependencies. This marketplace therefore ships a small source launcher that retrieves the exact published **0.1.19** prebuilt npm adapter and production dependencies on first load. It disables npm install scripts, skips Pi CLI peer installation, and performs no local compilation. Node.js 22.19+ and npm must be on PATH. First preparation needs internet access and roughly **150 MiB** of disk space; later loads reuse the installed cache without npm network access.
60
60
 
61
61
  The launcher stores its versioned dependencies in `.runtime/` inside the installed marketplace plugin's cache directory. Uninstalling the marketplace plugin removes that cache when it is no longer referenced by another scope. Google credentials and the separately downloaded official ACP runtime are unaffected.
62
62
 
@@ -80,7 +80,7 @@ omp plugin install npm:omp-antigravity-acp-provider
80
80
  To pin a specific release:
81
81
 
82
82
  ```sh
83
- omp plugin install npm:omp-antigravity-acp-provider@0.1.18
83
+ omp plugin install npm:omp-antigravity-acp-provider@0.1.19
84
84
  ```
85
85
 
86
86
  Restart OMP after installation. The npm package includes the built adapter; users do not need esbuild or a manual build step. Disable any older ACP adapter for the same provider before loading this package.
@@ -211,6 +211,10 @@ Never include those user data directories, OAuth callback URLs, account identifi
211
211
 
212
212
  ## Context continuity and local performance
213
213
 
214
+ New user requests supersede an interrupted ACP turn, including pending tool calls and permission prompts. The adapter cancels old waits and sends official `session/cancel`, then waits up to the existing 1.5-second cancellation deadline for the old turn to settle. A confirmed cancellation (or a clean completion racing with cancellation) keeps the warm ACP session when the transport is alive and the retained OMP history matches. New prompts queue behind that drain and are sent as new requests, never silently treated as old tool-result continuations. Ordinary completed turns and genuine tool continuations also stay warm.
215
+
216
+ The cancellation checkpoint records the accepted message boundary and the partial assistant output fingerprint, including across idle shutdown/resume. If cancellation is unacknowledged, the process fails, the history is edited/compacted, or previously emitted partial output is missing or changed in OMP, the adapter reconstructs from retained history instead. Thus Esc does not always create a new ACP session, but reuse is conditional rather than guaranteed. Cancelled turns skip supplemental `/usage` queries while retaining any ACP context-occupancy update. History is explicitly separated from the current request after official ACP text conversion; cold tool handoffs resume from completed results rather than restarting prior actions. Preserving a session avoids unnecessary replay but does not guarantee a backend cache hit. See the [Flash cancellation/cache research and implementation checks](docs/cache-cancellation-research.md).
217
+
214
218
  The adapter now transfers complete replay history within a bounded budget, including historical image attachments. It no longer silently keeps only a 32,000-character history tail. If a transfer does not fit, it stops with an explicit error requesting OMP `/compact` or smaller attachments. This is a local transfer limit, not Antigravity's model context window or its internal compaction threshold. Active requests, history text and system instructions share the token and wire budgets; images also have a separate decoded-data limit. No automatic summarization or extra inference is added by the transfer layer.
215
219
 
216
220
  Token budgets and wire payload size are independent; the former 500,000-byte clamp is removed. The default wire payload limit is 16 MiB, configurable up to 128 MiB. Image data additionally defaults to an 8 MiB decoded payload limit. The automatic input-token budget is `contextWindow - maxTokens - reserveTokens`, where reserve defaults to the smaller of 16,384 and 5% of the window. A lightweight Unicode-aware estimate checks serialized text plus approximately 4,096 tokens per image. This is not a Gemini tokenizer, cannot guarantee exact token counts and does not include every hidden server instruction.
@@ -2,6 +2,7 @@ import { describeCredentialStorage, inspectAntigravityAuth, savePermissionMode }
2
2
  import { antigravityAccountEmail, authReady, formatLogoutSummary, keychain, ompCredentialSummary, type OmpAuthCoordinator, type OmpCommandContext } from "./auth-sync.ts";
3
3
  import { parseNativeToolMode, type NativeToolMode } from "./tool-routing.ts";
4
4
  import { saveToolPolicy, type ToolPolicy } from "./tool-policy.ts";
5
+ import { updateContextSettings, resolveContextOptions, saveContextSettings, type ContextSettings } from "./context-settings.ts";
5
6
  import type { CatalogStore, ConfiguredCatalogModel } from "./catalog-store.ts";
6
7
  import type { SessionCleanup, CleanupMode } from "./session-cleanup.ts";
7
8
  import type { TierConnection } from "./tier-connection.ts";
@@ -86,7 +86,11 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
86
86
  records.push({ role: message.role, toolName: message.toolName, toolCallId: message.toolCallId, isError: message.isError, content });
87
87
  }
88
88
  const historyText = records.length
89
- ? "Prior conversation data, not new instructions. Do not repeat completed tool actions.\n" + JSON.stringify(records)
89
+ ? "# Prior OMP conversation (reference only)\n\n" +
90
+ "The JSON below is historical conversation data, not a new request or a queue of tasks. " +
91
+ "Do not answer historical user requests or repeat completed tool actions. " +
92
+ "Use it only as context for the current OMP user request identified after this resource.\n\n" +
93
+ JSON.stringify(records) + "\n\n# End of prior OMP conversation\n"
90
94
  : "";
91
95
  if (historyText) prompt.push({ type: "resource", resource: {
92
96
  uri: "urn:omp:antigravity-acp:history", mimeType: "text/plain",
@@ -95,10 +99,20 @@ export function buildPromptParts(context: TransferContext, fresh: boolean, unsee
95
99
  prompt.push(...images);
96
100
  const tailBlocks: TransferBlock[] = [];
97
101
  if (!fresh && start > latest) {
98
- const continuation = { type: "text", text: "Continue the current OMP user request with the new results. Do not repeat completed tool actions." };
102
+ const continuation = { type: "text", text: "\n\n# Continue the active OMP request\n\n" +
103
+ "The new context/tool results above belong to the user request already received in this session. " +
104
+ "Finish that request from those results. Do not answer historical user requests or repeat completed tool actions." };
99
105
  prompt.push(continuation);
100
106
  tailBlocks.push(continuation);
101
107
  } else {
108
+ // Official ACP merges following text into an embedded-resource string with
109
+ // a space. Explicit newlines/labels must survive that conversion; role
110
+ // fields inside the history JSON do not create actual API message roles.
111
+ const boundary = { type: "text", text: "\n\n# Current OMP user request\n\n" +
112
+ (end > latest ? "This request is already in progress; the history includes prior assistant actions and tool results. " +
113
+ "Continue from those results rather than restarting completed work.\n\n" : "") };
114
+ prompt.push(boundary);
115
+ tailBlocks.push(boundary);
102
116
  const content = messages[latest]!.content;
103
117
  // Blocks are consumed read-only; shallow copies only churn the hot path.
104
118
  const latestBlocks: TransferBlock[] = typeof content === "string" ? [{ type: "text", text: content }] : content;
@@ -19174,6 +19174,28 @@ function validModelId(id) {
19174
19174
  return id.length > 0 && id.length <= 128 && !/[\u0000-\u001f\u007f]/u.test(id);
19175
19175
  }
19176
19176
 
19177
+ // extension/turn-cancellation.ts
19178
+ async function drainCancelledTurn(binding, abort, signal, timeoutMs = 1500) {
19179
+ const completion = binding.turnCompletion;
19180
+ if (!completion || signal?.aborted) return false;
19181
+ const deadline = Promise.withResolvers();
19182
+ const cancelled = () => deadline.resolve(false);
19183
+ const timer = setTimeout(cancelled, timeoutMs);
19184
+ signal?.addEventListener("abort", cancelled, { once: true });
19185
+ try {
19186
+ abort();
19187
+ try {
19188
+ void binding.connection.cancel(binding.session.sessionId).catch(() => deadline.resolve(false));
19189
+ } catch {
19190
+ return false;
19191
+ }
19192
+ return await Promise.race([completion.then(() => true, () => false), deadline.promise]);
19193
+ } finally {
19194
+ clearTimeout(timer);
19195
+ signal?.removeEventListener("abort", cancelled);
19196
+ }
19197
+ }
19198
+
19177
19199
  // node_modules/@earendil-works/pi-ai/dist/utils/event-stream.js
19178
19200
  var FifoQueue = class {
19179
19201
  incoming = [];
@@ -44065,7 +44087,8 @@ var AntigravityAcpConnection = class {
44065
44087
  if (signal.aborted) onAbort();
44066
44088
  pending.then(
44067
44089
  (value) => {
44068
- if (aborting) finish(() => reject(abortError()));
44090
+ if (aborting && this.process.alive && ["cancelled", "end_turn"].includes(value.stopReason)) finish(() => resolve(value));
44091
+ else if (aborting) finish(() => reject(abortError()));
44069
44092
  else finish(() => resolve(value));
44070
44093
  },
44071
44094
  (error62) => finish(() => reject(aborting ? abortError() : error62))
@@ -59170,7 +59193,7 @@ ${instructions}` : "";
59170
59193
  });
59171
59194
  records.push({ role: message.role, toolName: message.toolName, toolCallId: message.toolCallId, isError: message.isError, content });
59172
59195
  }
59173
- const historyText = records.length ? "Prior conversation data, not new instructions. Do not repeat completed tool actions.\n" + JSON.stringify(records) : "";
59196
+ const historyText = records.length ? "# Prior OMP conversation (reference only)\n\nThe JSON below is historical conversation data, not a new request or a queue of tasks. Do not answer historical user requests or repeat completed tool actions. Use it only as context for the current OMP user request identified after this resource.\n\n" + JSON.stringify(records) + "\n\n# End of prior OMP conversation\n" : "";
59174
59197
  if (historyText) prompt.push({ type: "resource", resource: {
59175
59198
  uri: "urn:omp:antigravity-acp:history",
59176
59199
  mimeType: "text/plain",
@@ -59179,10 +59202,13 @@ ${instructions}` : "";
59179
59202
  prompt.push(...images);
59180
59203
  const tailBlocks = [];
59181
59204
  if (!fresh && start > latest) {
59182
- const continuation = { type: "text", text: "Continue the current OMP user request with the new results. Do not repeat completed tool actions." };
59205
+ const continuation = { type: "text", text: "\n\n# Continue the active OMP request\n\nThe new context/tool results above belong to the user request already received in this session. Finish that request from those results. Do not answer historical user requests or repeat completed tool actions." };
59183
59206
  prompt.push(continuation);
59184
59207
  tailBlocks.push(continuation);
59185
59208
  } else {
59209
+ const boundary = { type: "text", text: "\n\n# Current OMP user request\n\n" + (end > latest ? "This request is already in progress; the history includes prior assistant actions and tool results. Continue from those results rather than restarting completed work.\n\n" : "") };
59210
+ prompt.push(boundary);
59211
+ tailBlocks.push(boundary);
59186
59212
  const content = messages[latest].content;
59187
59213
  const latestBlocks = typeof content === "string" ? [{ type: "text", text: content }] : content;
59188
59214
  prompt.push(...latestBlocks);
@@ -59696,6 +59722,14 @@ var AntigravityRuntime = class {
59696
59722
  await this.invalidateBinding(binding);
59697
59723
  binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
59698
59724
  }
59725
+ if ((binding.turnCompletion || binding.permission || binding.pendingTools.size > 0) && (context.messages.findLastIndex((message) => message.role === "user") >= binding.pendingContextCount || messagesFingerprint(context.messages.slice(0, binding.pendingContextCount)) !== binding.pendingContextFingerprint)) {
59726
+ const prefixMatches = context.messages.length >= binding.pendingContextCount && messagesFingerprint(context.messages.slice(0, binding.pendingContextCount)) === binding.pendingContextFingerprint;
59727
+ const drained = prefixMatches && await drainCancelledTurn(binding, () => abortTurn(binding), options.signal);
59728
+ if (!drained || !binding.connection.process.alive || binding.needsReconstruction || !["cancelled", "end_turn"].includes(binding.ompTerminalStopReason)) {
59729
+ await this.invalidateBinding(binding);
59730
+ }
59731
+ binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
59732
+ }
59699
59733
  if (binding.permission) {
59700
59734
  const pending = binding.permission;
59701
59735
  const result = findPermissionResult(context, pending.id);
@@ -59754,7 +59788,7 @@ var AntigravityRuntime = class {
59754
59788
  await this.modeChanges;
59755
59789
  this.assertEpoch(epoch);
59756
59790
  binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
59757
- if (binding.needsReconstruction || binding.mode !== this.permissionMode || this.confirmedMode(binding) !== this.permissionMode || binding.toolFingerprint !== piToolFingerprint(tools) || context.messages.length < binding.messageCount || messagesFingerprint(context.messages.slice(0, binding.messageCount)) !== binding.historyFingerprint) {
59791
+ if (binding.needsReconstruction || binding.ompCancelledCheckpoint && (context.messages[binding.messageCount]?.role === "assistant" ? messageFingerprint(context.messages[binding.messageCount]) !== binding.expectedAssistantFingerprint : binding.ompCancelledHadOutput) || binding.mode !== this.permissionMode || this.confirmedMode(binding) !== this.permissionMode || binding.toolFingerprint !== piToolFingerprint(tools) || context.messages.length < binding.messageCount || messagesFingerprint(context.messages.slice(0, binding.messageCount)) !== binding.historyFingerprint) {
59758
59792
  await this.dropBinding(key, binding, true);
59759
59793
  binding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);
59760
59794
  }
@@ -59779,6 +59813,7 @@ var AntigravityRuntime = class {
59779
59813
  await this.invalidateBinding(binding);
59780
59814
  throw new AntigravityAcpError("protocol", "Permission mode changed before prompting; retry the turn");
59781
59815
  }
59816
+ binding.ompTerminalStopReason = void 0;
59782
59817
  binding.instructionsFingerprint = instructionFingerprint(context);
59783
59818
  binding.needsReconstruction = false;
59784
59819
  binding.pendingContextCount = context.messages.length;
@@ -59798,6 +59833,7 @@ var AntigravityRuntime = class {
59798
59833
  );
59799
59834
  if (onTurnAbort) options.signal?.removeEventListener("abort", onTurnAbort);
59800
59835
  const activeWriter = binding.writer ?? writer;
59836
+ binding.ompTerminalStopReason = response.stopReason;
59801
59837
  if (binding.abortRequested) throw abortError();
59802
59838
  const usage = usageFromPrompt2(response);
59803
59839
  activeWriter.message.usage = usage;
@@ -59806,6 +59842,7 @@ var AntigravityRuntime = class {
59806
59842
  binding.messageCount = binding.pendingContextCount || parts.messageCount;
59807
59843
  binding.historyFingerprint = binding.pendingContextFingerprint;
59808
59844
  binding.expectedAssistantFingerprint = messageFingerprint(activeWriter.message);
59845
+ if (response.stopReason !== "cancelled") binding.ompCancelledCheckpoint = false;
59809
59846
  this.persistBinding(binding);
59810
59847
  if (response.stopReason === "end_turn") {
59811
59848
  binding.connection.confirmReplacement?.(key, binding.session.sessionId);
@@ -59823,7 +59860,17 @@ var AntigravityRuntime = class {
59823
59860
  }
59824
59861
  } catch (error62) {
59825
59862
  binding.writer?.fail(error62, isAbort(error62));
59826
- if (isAbort(error62) || binding.abortRequested) abortTurn(binding);
59863
+ if (isAbort(error62) || binding.abortRequested) {
59864
+ abortTurn(binding);
59865
+ if (binding.connection.process.alive && !binding.needsReconstruction && ["cancelled", "end_turn"].includes(binding.ompTerminalStopReason)) {
59866
+ binding.messageCount = binding.pendingContextCount;
59867
+ binding.historyFingerprint = binding.pendingContextFingerprint;
59868
+ binding.expectedAssistantFingerprint = messageFingerprint((binding.writer ?? writer).message);
59869
+ binding.ompCancelledCheckpoint = true;
59870
+ binding.ompCancelledHadOutput = (binding.writer ?? writer).message.content.length > 0;
59871
+ this.persistBinding(binding);
59872
+ } else await this.invalidateBinding(binding);
59873
+ }
59827
59874
  if (!binding.connection.process.alive) await this.dropBinding(key, binding);
59828
59875
  throw error62;
59829
59876
  } finally {
@@ -59960,6 +60007,8 @@ var AntigravityRuntime = class {
59960
60007
  needsReconstruction: false,
59961
60008
  modelId: acpModelId,
59962
60009
  messageCount: restored && saved ? saved.messageCount : 0,
60010
+ ompCancelledCheckpoint: restored && saved?.ompCancelledCheckpoint === true,
60011
+ ompCancelledHadOutput: restored && saved?.ompCancelledHadOutput === true,
59963
60012
  historyFingerprint: restored && saved ? saved.historyFingerprint : messagesFingerprint([]),
59964
60013
  expectedAssistantFingerprint: restored ? saved?.expectedAssistantFingerprint : void 0,
59965
60014
  pendingContextCount: 0,
@@ -60005,6 +60054,8 @@ var AntigravityRuntime = class {
60005
60054
  piSessionId: binding.piSessionId,
60006
60055
  acpSessionId: binding.session.sessionId,
60007
60056
  acpModelId: binding.modelId,
60057
+ ompCancelledCheckpoint: binding.ompCancelledCheckpoint === true,
60058
+ ompCancelledHadOutput: binding.ompCancelledHadOutput === true,
60008
60059
  cwd: binding.cwd,
60009
60060
  messageCount: binding.messageCount,
60010
60061
  historyFingerprint: binding.historyFingerprint,
@@ -60682,7 +60733,7 @@ var TierConnection = class extends AntigravityAcpConnection {
60682
60733
  const context = this.contextUsage.get(id);
60683
60734
  return context ? { ...value, _meta: { ...value._meta, ompContextTokens: context.used } } : value;
60684
60735
  };
60685
- if (response.usage || process.env.OMP_ACP_USAGE === "off" || this.usageMode === "off" || !this.usageCommands.has(id) || signal?.aborted) {
60736
+ if (response.usage || response.stopReason === "cancelled" || process.env.OMP_ACP_USAGE === "off" || this.usageMode === "off" || !this.usageCommands.has(id) || signal?.aborted) {
60686
60737
  this.usageBaselines.delete(id);
60687
60738
  this.usageStatus.set(id, { source: response.usage ? "ACP response" : "unavailable", cache: "unknown" });
60688
60739
  return withContext(response);
@@ -158,7 +158,7 @@ export class TierConnection extends AntigravityAcpConnection {
158
158
  const context = this.contextUsage.get(id);
159
159
  return context ? { ...value, _meta: { ...value._meta, ompContextTokens: context.used } } : value;
160
160
  };
161
- if (response.usage || process.env.OMP_ACP_USAGE === "off" || this.usageMode === "off" || !this.usageCommands.has(id) || signal?.aborted) {
161
+ if (response.usage || response.stopReason === "cancelled" || process.env.OMP_ACP_USAGE === "off" || this.usageMode === "off" || !this.usageCommands.has(id) || signal?.aborted) {
162
162
  this.usageBaselines.delete(id);
163
163
  this.usageStatus.set(id, { source: response.usage ? "ACP response" : "unavailable", cache: "unknown" });
164
164
  return withContext(response);
@@ -0,0 +1,31 @@
1
+ interface PendingTurn {
2
+ turnCompletion?: Promise<void>;
3
+ session: { sessionId: string };
4
+ connection: { cancel: (sessionId: string) => Promise<void> };
5
+ }
6
+
7
+ // The caller decides whether the accepted transcript still matches. This only
8
+ // drains the old turn, never resolves an old tool result into a new writer.
9
+ export async function drainCancelledTurn(
10
+ binding: PendingTurn,
11
+ abort: () => void,
12
+ signal?: AbortSignal,
13
+ timeoutMs = 1500,
14
+ ): Promise<boolean> {
15
+ const completion = binding.turnCompletion;
16
+ if (!completion || signal?.aborted) return false;
17
+ const deadline = Promise.withResolvers<boolean>();
18
+ const cancelled = () => deadline.resolve(false);
19
+ const timer = setTimeout(cancelled, timeoutMs);
20
+ signal?.addEventListener("abort", cancelled, { once: true });
21
+ try {
22
+ abort();
23
+ // A blocked cancel transport must not block the fallback deadline.
24
+ try { void binding.connection.cancel(binding.session.sessionId).catch(() => deadline.resolve(false)); }
25
+ catch { return false; }
26
+ return await Promise.race([completion.then(() => true, () => false), deadline.promise]);
27
+ } finally {
28
+ clearTimeout(timer);
29
+ signal?.removeEventListener("abort", cancelled);
30
+ }
31
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omp-antigravity-acp-provider",
3
- "version": "0.1.18",
3
+ "version": "0.1.19",
4
4
  "description": "Google Antigravity ACP provider for Oh My Pi (OMP), with tool bridging and per-model thinking; derived from zacbemis/pi-antigravity-acp-provider",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -41,7 +41,8 @@
41
41
  "test:commands": "bun scripts/test-tool-command.ts",
42
42
  "test:auth": "bun scripts/test-auth-command.ts",
43
43
  "test:cleanup": "node scripts/test-cleanup-runtime.ts",
44
- "check": "npm run build && npm test && npm run test:cleanup && npm run test:graph",
44
+ "test:continuity": "node scripts/test-request-continuity.ts && node scripts/test-graceful-cancellation.ts",
45
+ "check": "npm run build && npm test && npm run test:cleanup && npm run test:continuity && npm run test:graph && npm run test:commands",
45
46
  "prepack": "npm run build",
46
47
  "prepublishOnly": "npm run check",
47
48
  "test:graph": "bun scripts/test-load-graph.ts"
package/scripts/build.mjs CHANGED
@@ -62,6 +62,76 @@ const result = await build({
62
62
  anchor: "buildPromptParts(context, fresh, unseenStart)",
63
63
  replacement: "buildPromptParts(context, fresh, unseenStart, { contextWindow: model.contextWindow, maxTokens: model.maxTokens, policy: model.ompContextPolicy })",
64
64
  },
65
+ {
66
+ name: "new request supersedes continuation",
67
+ anchor: "\t\t// A permission tool result resumes the still-running ACP prompt rather than",
68
+ replacement: [
69
+ "\t\t// A new/edited user request is not a tool-result continuation of the",
70
+ "\t\t// previous ACP prompt. Never let old pending results swallow it.",
71
+ "\t\tif ((binding.turnCompletion || binding.permission || binding.pendingTools.size > 0) &&",
72
+ "\t\t\t(context.messages.findLastIndex(message => message.role === 'user') >= binding.pendingContextCount ||",
73
+ "\t\t\t messagesFingerprint(context.messages.slice(0, binding.pendingContextCount)) !== binding.pendingContextFingerprint)) {",
74
+ "\t\t\tconst prefixMatches = context.messages.length >= binding.pendingContextCount &&",
75
+ "\t\t\t\tmessagesFingerprint(context.messages.slice(0, binding.pendingContextCount)) === binding.pendingContextFingerprint;",
76
+ "\t\t\tconst drained = prefixMatches && await drainCancelledTurn(binding, () => abortTurn(binding), options.signal);",
77
+ "\t\t\tif (!drained || !binding.connection.process.alive || binding.needsReconstruction ||",
78
+ "\t\t\t\t!['cancelled', 'end_turn'].includes(binding.ompTerminalStopReason)) {",
79
+ "\t\t\t\tawait this.invalidateBinding(binding);",
80
+ "\t\t\t}",
81
+ "\t\t\tbinding = await this.getBinding(key, model, acpModelId, options.apiKey, writer, tools, options.signal);",
82
+ "\t\t}",
83
+ "",
84
+ "\t\t// A permission tool result resumes the still-running ACP prompt rather than",
85
+ ].join("\n"),
86
+ },
87
+ {
88
+ name: "checkpoint acknowledged cancellation",
89
+ anchor: "if (isAbort(error) || binding.abortRequested) abortTurn(binding);",
90
+ replacement: [
91
+ "if (isAbort(error) || binding.abortRequested) {",
92
+ "\t\t\t\tabortTurn(binding);",
93
+ "\t\t\t\tif (binding.connection.process.alive && !binding.needsReconstruction &&",
94
+ "\t\t\t\t\t['cancelled', 'end_turn'].includes(binding.ompTerminalStopReason)) {",
95
+ "\t\t\t\t\tbinding.messageCount = binding.pendingContextCount;",
96
+ "\t\t\t\t\tbinding.historyFingerprint = binding.pendingContextFingerprint;",
97
+ "\t\t\t\t\tbinding.expectedAssistantFingerprint = messageFingerprint((binding.writer ?? writer).message);",
98
+ "\t\t\t\t\tbinding.ompCancelledCheckpoint = true;",
99
+ "\t\t\t\t\tbinding.ompCancelledHadOutput = (binding.writer ?? writer).message.content.length > 0;",
100
+ "\t\t\t\t\tthis.persistBinding(binding);",
101
+ "\t\t\t\t} else await this.invalidateBinding(binding);",
102
+ "\t\t\t}",
103
+ ].join("\n"),
104
+ },
105
+ {
106
+ name: "reset cancellation acknowledgement per prompt",
107
+ anchor: "binding.instructionsFingerprint = instructionFingerprint(context);",
108
+ replacement: "binding.ompTerminalStopReason = undefined;\n\t\t\t" + "binding.instructionsFingerprint = instructionFingerprint(context);",
109
+ },
110
+ {
111
+ name: "record official terminal reason before abort handling",
112
+ anchor: "if (binding.abortRequested) throw abortError();",
113
+ replacement: "binding.ompTerminalStopReason = response.stopReason;\n\t\t\tif (binding.abortRequested) throw abortError();",
114
+ },
115
+ {
116
+ name: "cancelled partial output must match retained OMP history",
117
+ anchor: "binding.needsReconstruction || binding.mode !== this.permissionMode ||",
118
+ replacement: [
119
+ "binding.needsReconstruction ||",
120
+ "\t\t\t\t(binding.ompCancelledCheckpoint && (context.messages[binding.messageCount]?.role === 'assistant'",
121
+ "\t\t\t\t\t? messageFingerprint(context.messages[binding.messageCount]) !== binding.expectedAssistantFingerprint",
122
+ "\t\t\t\t\t: binding.ompCancelledHadOutput)) || binding.mode !== this.permissionMode ||",
123
+ ].join("\n"),
124
+ },
125
+ {
126
+ name: "persist cancellation checkpoint flags",
127
+ anchor: "acpModelId: binding.modelId,",
128
+ replacement: "acpModelId: binding.modelId,\n\t\t\tompCancelledCheckpoint: binding.ompCancelledCheckpoint === true,\n\t\t\tompCancelledHadOutput: binding.ompCancelledHadOutput === true,",
129
+ },
130
+ {
131
+ name: "restore cancellation checkpoint flags",
132
+ anchor: "messageCount: restored && saved ? saved.messageCount : 0,",
133
+ replacement: "messageCount: restored && saved ? saved.messageCount : 0,\n\t\t\t\tompCancelledCheckpoint: restored && saved?.ompCancelledCheckpoint === true,\n\t\t\t\tompCancelledHadOutput: restored && saved?.ompCancelledHadOutput === true,",
134
+ },
65
135
  {
66
136
  name: "connection retirement",
67
137
  anchor: "if (!persistent) await this.dropBinding(key, binding);",
@@ -75,7 +145,7 @@ const result = await build({
75
145
  {
76
146
  name: "cleanup confirm",
77
147
  anchor: "this.persistBinding(binding);\n\t\t\tswitch (response.stopReason)",
78
- replacement: "this.persistBinding(binding);\n\t\t\tif (response.stopReason === 'end_turn') { binding.connection.confirmReplacement?.(key, binding.session.sessionId); if (!persistent) binding.connection.discardSession?.(binding.session.sessionId); }\n\t\t\tswitch (response.stopReason)",
148
+ replacement: "if (response.stopReason !== 'cancelled') binding.ompCancelledCheckpoint = false;\n\t\t\tthis.persistBinding(binding);\n\t\t\tif (response.stopReason === 'end_turn') { binding.connection.confirmReplacement?.(key, binding.session.sessionId); if (!persistent) binding.connection.discardSession?.(binding.session.sessionId); }\n\t\t\tswitch (response.stopReason)",
79
149
  },
80
150
  ];
81
151
  let contents = await fs.readFile(file, "utf8");
@@ -85,8 +155,17 @@ const result = await build({
85
155
  }
86
156
  contents = contents.replace(patch.anchor, patch.replacement);
87
157
  }
158
+ contents = `import { drainCancelledTurn } from ${JSON.stringify(path.join(root, "extension/turn-cancellation.ts"))};\n` + contents;
88
159
  return { contents, loader: "ts" };
89
160
  });
161
+ builder.onLoad({ filter: /\/src\/acp\/connection\.ts$/ }, async ({ path: file }) => {
162
+ if (file !== path.join(upstream, "src/acp/connection.ts")) return;
163
+ const source = await fs.readFile(file, "utf8");
164
+ const anchor = "if (aborting) finish(() => reject(abortError()));";
165
+ if (source.split(anchor).length !== 2) throw new Error("Pinned upstream prompt cancellation seam changed; review compatibility");
166
+ return { contents: source.replace(anchor,
167
+ "if (aborting && this.process.alive && ['cancelled', 'end_turn'].includes(value.stopReason)) finish(() => resolve(value));\n\t\t\t\t\telse if (aborting) finish(() => reject(abortError()));"), loader: "ts" };
168
+ });
90
169
  builder.onLoad({ filter: /\/(?:process|runtime-manifest)\.ts$/ }, async ({ path: file }) => {
91
170
  const relative = path.relative(upstream, file).split(path.sep).join("/");
92
171
  return {