omp-antigravity-acp-provider 0.1.42 → 0.1.44

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/AGENT_INSTALL.md CHANGED
@@ -19,7 +19,8 @@ Steps:
19
19
  6. Tell the user to restart OMP, then run `/login` → "Google Antigravity (ACP)" and `/antigravity-acp refresh` inside OMP. Do not perform these steps yourself.
20
20
 
21
21
  Notes:
22
- - The adapter auto-selects the newer of the `agy` CLI's bundled server and its managed registry runtime; no channel configuration is required. An explicit `AGY_ACP_BIN` environment variable overrides the choice — do not set it unless the user asks.
22
+ - The adapter prefers a usable `agy` CLI and falls back to the managed registry runtime. It never installs the CLI. An explicit `AGY_ACP_BIN` environment variable overrides the choice. Do not set it unless the user asks.
23
+ - To pin a channel, set `runtimeSource` in `~/.omp/agent/antigravity-acp-provider/config.json` to `auto`, `cli`, or `managed`. A pinned source fails instead of downloading the other channel.
23
24
  - ACP sessions are stored under `~/.gemini/antigravity-acp/`. The user's personal `agy` CLI chats under `~/.gemini/antigravity-cli/` are never read or deleted by the adapter.
24
25
 
25
26
  Acceptance: one adapter installed, `omp models antigravity-acp --json` returns valid JSON, and no credential material appears in any output. Report the commands run, the adapter version, any model IDs and the first step that failed.
package/README.md CHANGED
@@ -17,27 +17,30 @@ This is an independent adaptation, **NOT** an official Google or OMP integration
17
17
  ## Features
18
18
 
19
19
  - All server-advertised models, including Claude, GPT-OSS and future IDs when the ACP endpoint advertises them.
20
- - Newest-server auto-selection. When the `agy` CLI on PATH bundles a newer ACP server than the registry-installed runtime, the adapter launches it through a generated `AGY_ACP_BIN` wrapper, so CLI-first models appear without manual setup. An explicit `AGY_ACP_BIN` always wins.
20
+ - CLI-first selection. When a usable `agy` CLI is on `PATH`, the adapter launches it through a generated `AGY_ACP_BIN` wrapper. The managed runtime is the fallback. An explicit `AGY_ACP_BIN` always wins.
21
21
  - Per-model thinking levels, exposed only when the server confirms them.
22
22
  - OMP tools through an authenticated loopback MCP bridge.
23
23
  - Optional `disabled` native-tool mode for strict OMP-only sessions.
24
24
  - Lazy ACP startup and warm session reuse.
25
25
  - `/login` plus `/antigravity-acp` account, usage and cleanup commands.
26
- - API-equivalent cost estimates, not subscription billing.
26
+ - API-equivalent cost estimates from a model-ID rate table, not subscription billing. ACP model records do not include price fields.
27
27
  - Long-running OMP tools survive the MCP request window through a relay. The model resumes the same result with `pi_omp_await_result`; the control tool is a separate MCP server and never appears in OMP's tool list.
28
28
  - Permission requests are tied to the originating session, turn and tool call. Forged, conflicting or previous-turn identities fail closed, while normal requests still use OMP's human review.
29
29
  - The MCP `tools/list` reflects the current OMP tool set. The offline wire test covers add, remove and restore on one warm ACP session.
30
+ - Tool-argument hardening on the MCP bridge. Habitual alias mistakes such as `path` for `file_path` are corrected only when the tool schema makes the mapping unambiguous, and rejected calls return the missing required keys plus the tool's expected signature instead of a bare schema failure.
31
+ - Loopback traffic always bypasses proxied environments. When `HTTP(S)_PROXY` or `ALL_PROXY` is set for the ACP child process, the adapter appends `localhost`, `127.0.0.1` and `::1` to `NO_PROXY`/`no_proxy` so the loopback MCP bridge is never routed through an external proxy.
32
+ - OAuth material is redacted from failure text. Authorization URLs, sensitive query values, `Bearer` tokens and OAuth pairs such as `code_challenge` or `access_token` are masked before messages reach OMP, while ordinary diagnostics like `exit code=1` stay intact.
30
33
 
31
34
  ## Install: for human
32
35
 
33
- Follow these steps in order. The whole flow takes a few minutes, plus Google's sign-in and the first runtime download.
36
+ Follow these steps in order. The whole flow takes a few minutes, plus Google's sign-in. A runtime download is only needed when no usable `agy` CLI is installed.
34
37
 
35
38
  ### 1. Check prerequisites
36
39
 
37
40
  - OMP is installed and `omp --version` works.
38
41
  - Node.js 22.19 or newer (`node --version`) and npm are on `PATH`; the marketplace launcher uses them on first load.
39
42
  - A supported platform: macOS, Linux or Windows. Live testing has been on macOS.
40
- - Internet access for the first run. The official Antigravity runtime downloads separately (about 383 MiB on macOS) into `~/.local/opt/agy-acp/`.
43
+ - Internet access when no usable `agy` CLI is installed. The managed fallback downloads separately (about 383 MiB on macOS) into `~/.local/opt/agy-acp/`.
41
44
 
42
45
  ### 2. Install exactly one adapter
43
46
 
@@ -99,16 +102,43 @@ The installation runbook is in [AGENT_INSTALL.md](AGENT_INSTALL.md). Hand that f
99
102
 
100
103
  ## ACP server channels and selection
101
104
 
102
- Google ships the same ACP server through two channels; the adapter picks between them automatically at every OMP startup.
105
+ Google ships the same ACP server through two channels. The adapter chooses one at every OMP startup.
103
106
 
104
- - **`agy` CLI** — the self-updating command-line product. When its bundled server is newer than the registry runtime, the adapter launches it through a generated `AGY_ACP_BIN` wrapper, so CLI-first models (for example Claude and GPT-OSS) appear without manual setup.
105
- - **Managed runtime** — the registry-signed release downloaded and verified into `~/.local/opt/agy-acp/`. Used when the CLI is missing or not newer, and installed automatically when neither channel exists.
107
+ - **`agy` CLI.** Preferred whenever `agy` or `agy.exe` is on `PATH` and `agy acp --version` returns a semantic version. The adapter writes `agy-acp-cli.sh` or `agy-acp-cli.cmd` and points `AGY_ACP_BIN` at that wrapper.
108
+ - **Managed runtime.** The registry-signed release in `~/.local/opt/agy-acp/`. It is the fallback when the CLI is missing or unusable.
106
109
 
107
110
  Selection order:
108
111
 
109
- 1. An explicit `AGY_ACP_BIN` always wins. Point it at an `agy acp`-capable executable or wrapper to force a channel.
110
- 2. Otherwise the newer server version wins; ties go to the managed runtime.
111
- 3. With neither present, the managed runtime is downloaded from Google's registry on next use.
112
+ 1. An explicit non-wrapper `AGY_ACP_BIN` wins. The adapter's generated wrapper is not a user override.
113
+ 2. If `runtimeSource` is `cli` or `managed`, the adapter uses that source exclusively. A missing pinned source fails the first ACP use and is not downloaded.
114
+ 3. If `runtimeSource` is `auto`, a usable CLI wins, even when its version is older than the managed runtime.
115
+ 4. In `auto`, if the CLI is missing or unusable, the adapter uses the managed runtime. If the managed runtime is missing, it downloads it from Google's registry.
116
+ 5. In `auto`, if writing the CLI wrapper or runtime record fails, the adapter falls back to the managed runtime.
117
+
118
+ The adapter never installs the `agy` CLI. It downloads the managed runtime only in `auto` when no usable CLI is selected. Inference and quota use the same selection.
119
+
120
+ On the first session start after OMP launches, the adapter attempts one background model refresh. A successful refresh re-registers the provider so newly advertised models and their API-equivalent rates become available. If login or ACP startup fails, the cached catalog remains usable and `/antigravity-acp refresh` still forces a refresh.
121
+
122
+ Create or edit `~/.omp/agent/antigravity-acp-provider/config.json`:
123
+
124
+ ```json
125
+ {
126
+ "permissions": "yolo",
127
+ "runtimeSource": "auto",
128
+ "nativeTools": "prefer",
129
+ "debugToolUpdates": false,
130
+ "usageMode": "off",
131
+ "diagnostics": false
132
+ }
133
+ ```
134
+
135
+ `permissions` accepts `default`, `auto_edit`, or `yolo`. `runtimeSource` accepts `auto`, `cli`, or `managed`. `nativeTools` accepts `prefer` or `disabled`. `usageMode` accepts `auto` or `off`. `debugToolUpdates` and `diagnostics` are booleans. Missing fields use these defaults: `permissions: "yolo"`, `runtimeSource: "auto"`, `nativeTools: "prefer"`, `debugToolUpdates: false`, `usageMode: "off"`, and `diagnostics: false`. Slash commands write the command-backed fields and keep the legacy setting files in sync. Context budgets remain in `context.json`; cleanup policy remains in `cleanup.json`.
136
+
137
+ - `auto` uses the CLI first and falls back to the managed runtime. If no usable CLI exists, it downloads the managed runtime.
138
+ - `cli` requires a usable `agy` CLI. If the CLI is missing or unusable, the first ACP use fails and nothing is downloaded.
139
+ - `managed` requires the managed runtime. If it is missing, the first ACP use fails and nothing is downloaded.
140
+
141
+ A pinned source never falls back to the other channel and never downloads it. An explicit non-wrapper `AGY_ACP_BIN` still wins over this setting. If `PI_CODING_AGENT_DIR` is set, use its actual path for `config.json`. Other `runtimeSource` values fail provider startup.
112
142
 
113
143
  Session storage follows the server's own `--app_data_dir`. The generated wrapper pins `antigravity-acp` — the managed runtime's own default — so CLI-launched ACP sessions land in `~/.gemini/antigravity-acp/`, where `/antigravity-acp cleanup` and session ownership tracking operate. Personal `agy` CLI chats stay in `~/.gemini/antigravity-cli/` and are never read or deleted by the adapter. `GEMINI_HOME` relocates the managed runtime's tree (upstream behavior); the `agy` CLI stores under `~/.gemini` regardless.
114
144
 
@@ -118,29 +148,68 @@ Permission IDs differ between the channels. Managed ACP 1.4.5 supports `default`
118
148
 
119
149
  CLI ACP 1.5.3 omits `mcpCapabilities` from its initialization response, but it still discovers HTTP MCP servers and calls `tools/list`. The adapter normalizes this capability for that server identity so OMP tools remain available. CLI 1.5.3 reports no audio input, while the adapter's model catalog already limits input to text and images.
120
150
 
151
+ ### Context occupancy and compaction
152
+
153
+ ACP may report live occupancy with `usage_update`. When it does, the adapter forwards that server value. When a runtime (for example CLI ACP 1.5.4) reports only cumulative billable usage, the adapter estimates the full OMP context from the system prompt, retained messages and tool schemas with `estimateTransferTokens`, then sets `usage.contextTokens` and marks `contextTokensSource: "estimate"`. The billable `input`, `cacheRead` and `output` counters are left untouched.
154
+
155
+ The estimate is a heuristic, not a server measurement. To use managed ACP when exact occupancy matters, set `AGY_ACP_BIN` to the managed binary. CLI-first selection does not switch automatically. In this source checkout, `scripts/with-managed-context.sh` starts OMP with the installed managed binary while preserving an explicit `AGY_ACP_BIN`. Run `/antigravity-acp refresh` afterward to inspect the models that runtime actually advertises.
156
+
157
+ Keep `compaction.autoContinue` enabled for normal long-running work. The false context rollover was fixed at the occupancy signal, not by disabling automatic continuation.
158
+
121
159
  ## Commands
122
160
 
123
- | Command | Purpose |
161
+ Use the `/antigravity-acp ` prefix once, followed by a row below. For example, `status` means `/antigravity-acp status`.
162
+
163
+ ### Common operations
164
+
165
+ | Subcommand | Purpose |
166
+ | --- | --- |
167
+ | *(none)* or `status` | Show login readiness, negotiated runtime/native channel when available, permission policy, native tools, non-empty usage records and active sessions. Requested and wire permissions share one row when they differ. Empty process details are omitted; runtime/API warnings remain visible. |
168
+ | `account` | Show the signed-in account, ACP authentication and non-secret OMP marker. Token ownership, logout behavior and account/store inconsistencies are not hidden. |
169
+ | `login` | Start a fresh Google authorization. |
170
+ | `logout` | Clear Antigravity credentials, saved sessions and the OMP marker. |
171
+ | `quota` | Query live quota and print one model heading with one remaining/reset row per quota window. Query failures are reported explicitly. |
172
+ | `refresh` | Discover and cache advertised models, then list the refreshed IDs. |
173
+ | `usage` | Show configured → effective supplemental-query mode (`OMP_ACP_USAGE=off` forces `off`) and only populated per-connection context, compaction and accounting details. |
174
+ | `usage auto` | Query supplemental usage after each reply. Context occupancy updates remain enabled. |
175
+ | `usage off` | Skip supplemental queries without disabling context occupancy updates. |
176
+
177
+ Quota results use a 60-second cache. When the adapter selects the CLI, the quota command runs the CLI's print-mode `/usage` command with the same `--app_data_dir` as the CLI ACP wrapper. When it selects managed ACP, the quota command uses a short-lived ACP session. An explicit `AGY_ACP_BIN` remains authoritative. If an ACP runtime does not advertise `usage`, the adapter reports the limitation without sending a model prompt. The quota display excludes usage counters for temporary ACP sessions.
178
+
179
+ OMP's built-in `omp usage`, interactive `/usage`, and the statusline `usage` segment read the same quota through the provider's registered usage source. The adapter uses the CLI `/usage` command first and queries an installed managed runtime only when the user is signed in. A usage probe never downloads a runtime. Statusline selects the active model's limit group when that group maps to one model. Multi-model groups remain visible in `/usage`. The custom `/antigravity-acp quota` command remains the detailed text view.
180
+
181
+ ### Advanced maintenance
182
+
183
+ | Subcommand and options | Purpose |
124
184
  | --- | --- |
125
- | `/antigravity-acp status` | Runtime, thinking and usage information |
126
- | `/antigravity-acp account` | Signed-in account and authentication state |
127
- | `/antigravity-acp login` | Re-run the Google authorization |
128
- | `/antigravity-acp logout` | Clear Antigravity credentials and saved sessions |
129
- | `/antigravity-acp refresh` | Discover and cache advertised models |
130
- | `/antigravity-acp usage [auto\|off]` | Context occupancy and supplemental usage queries |
131
- | `/antigravity-acp context` | Per-model context budgets |
132
- | `/antigravity-acp cleanup [mode]` | Session-file cleanup policy |
133
- | `/antigravity-acp diagnostics [on\|off\|reset]` | Adapter stage timing samples |
134
- | `/antigravity-acp native-tools prefer\|disabled` | Native built-in tool policy |
135
- | `/antigravity-acp tools` | Available and omitted OMP tool schemas |
136
- | `/antigravity-acp debug on\|off` | ACP tool-status lines |
137
- | `/antigravity-acp permissions default\|auto-edit\|yolo` | Permission mode |
185
+ | `tools` | Inspect offered/available OMP tools, every omission reason and live MCP capability checks. |
186
+ | `context` | Show saved shared defaults separately from each cached model's effective limits and model-only overrides. Effective values include the input, output, reserve, transfer and image budgets used by runtime compatibility checks. |
187
+ | `context set default KEY NUMBER` | Change a shared numeric context setting. |
188
+ | `context set MODEL KEY NUMBER` | Change one model override. Reselect the model or restart OMP to refresh its displayed limits. |
189
+ | `context set default usageMode auto\|off` | Equivalent to `usage auto\|off`. |
190
+ | `cleanup` | Collect using the saved policy and show its mode, retention, non-empty session counts, actual removals, warnings and state-loss risk. |
191
+ | `cleanup off` | Keep every saved session. |
192
+ | `cleanup conservative` | Remove only eligible idle, unmapped sessions while preserving mapped history and live leases. |
193
+ | `cleanup timeout [DAYS]` | Apply timeout collection, optionally with a custom idle retention in days. |
194
+ | `cleanup balanced [DAYS]` | Apply timeout and soft-budget cleanup with recovery protection, optionally with custom idle days. |
195
+ | `cleanup budget MAX_SESSIONS MAX_MIB` | Set soft session/byte limits; `0` disables either limit. Active and recently used sessions can remain above a soft budget. Timeout deletion loses ACP-only state but retains OMP history. |
196
+ | `diagnostics` | Show collection state and non-empty samples as count/median/max per stage. |
197
+ | `diagnostics on\|off` | Enable or disable bounded local timing collection. |
198
+ | `diagnostics reset` | Clear collected samples without changing the enabled state. |
199
+ | `debug on\|off` | Toggle raw ACP tool-status lines; normal tool results and thought summaries are preserved. |
200
+ | `native-tools prefer` | Let OMP tools shadow matching ACP-native tools. |
201
+ | `native-tools disabled` | Disable ACP-native built-ins for strict OMP-tool sessions while retaining MCP configuration; connections are recreated on the next request. |
202
+ | `permissions default` | Confirm edits and commands. |
203
+ | `permissions auto-edit` | Auto-accept edits. |
204
+ | `permissions yolo` | Auto-accept everything; changing modes recreates runtimes to avoid reusing an unsafe process. |
205
+
206
+ Context `KEY` is one of `contextWindow`, `maxTokens`, `inputTokenBudget`, `reserveTokens`, `maxTransferBytes` or `maxImageBytes`.
138
207
 
139
208
  The OMP input autocompletes this command. Type `/antigravity-acp ` to list the subcommands, and keep typing to filter them. Fixed values such as `permissions` modes and `context set` targets (default plus the cached model IDs) complete the same way.
140
209
 
141
210
  ## Steering and queued messages
142
211
 
143
- By default a new user message waits for the active ACP turn to finish (`OMP_ACP_STEER_MODE=queue`) and then continues on the warm session, avoiding a full replay and OMP auto-compaction. Set `OMP_ACP_STEER_MODE=steer` to restore immediate interruption. At tool/permission boundaries the adapter falls back to steer and waits for the ACP terminal response; `OMP_ACP_STEER_GRACE_MS` (default 60000) and `OMP_ACP_STEER_GRACE_MAX_MS` (default 300000) bound that wait.
212
+ By default a new user message waits for the active ACP turn to finish (`OMP_ACP_STEER_MODE=queue`) and then continues on the warm session, avoiding a full replay and OMP auto-compaction. Set `OMP_ACP_STEER_MODE=steer` to restore immediate interruption. At tool/permission boundaries the adapter falls back to steer and waits for the ACP terminal response; `OMP_ACP_STEER_GRACE_MS` (default 60000) and `OMP_ACP_STEER_GRACE_MAX_MS` (default 300000) bound that wait. Explicit user cancellation is never held: the adapter aborts the upstream prompt immediately, so the ACP server receives `session/cancel` at once. Queue steering still holds the active turn, and the graceful drain and checkpoint reuse semantics are unchanged.
144
213
 
145
214
  ACP runtimes stay warm for 15 minutes by default. Set `OMP_ACP_IDLE_TIMEOUT_MS=0` to keep them until OMP exits, or lower the value to reclaim memory sooner.
146
215
 
@@ -170,7 +239,7 @@ A `refusal` stop reason is reported as an explicit provider refusal. An empty `e
170
239
  - No guaranteed prompt-cache hits, cache discounts, or identical tokenization.
171
240
  - No full native history or hidden reasoning across a cold rebuild; server-side compaction is outside adapter control.
172
241
  - No per-tool native allowlist; `native-tools` supports only `prefer` and `disabled`, and global MCP servers remain.
173
- - No standalone client; the official ACP runtime is required.
242
+ - No standalone client; a usable ACP server, either the `agy` CLI or the managed runtime, is required.
174
243
 
175
244
  Detailed behavior, advanced settings and limitations: [docs/](docs/) and [CHANGELOG.md](CHANGELOG.md).
176
245
 
@@ -1,6 +1,8 @@
1
1
  // OMP decides whether to retry from the assistant error text. Keep the
2
2
  // transport's distinction between account exhaustion and a transient throttle
3
3
  // visible instead of collapsing both into "protocol".
4
+ import { redactSensitiveText } from "./redact.ts";
5
+
4
6
  export type AcpFailureCode =
5
7
  | "auth"
6
8
  | "quota"
@@ -103,16 +105,19 @@ function isAntigravityAcpError(error: unknown): error is AntigravityAcpErrorLike
103
105
  export function classifyAcpFailure(error: unknown): Error {
104
106
  if (isAntigravityAcpError(error)) {
105
107
  if (error.code === "aborted") return error;
106
- if (error.code === "auth") return new AcpFailure("auth", appendHint(error.message, AUTH_RULE), { cause: error });
107
- if (error.code === "timeout") return new AcpFailure("timeout", appendHint(error.message, TIMEOUT_RULE), { cause: error });
108
- if (error.code === "spawn" || error.code === "process_exit") return new AcpFailure("transport", appendHint(error.message, TRANSPORT_RULE), { cause: error });
109
- if (error.code === "invalid_input") return new AcpFailure("protocol", appendHint(error.message, PROTOCOL_RULE), { cause: error });
110
- if (error.code === "model") return new AcpFailure("model", error.message, { cause: error });
108
+ if (error.code === "auth") return new AcpFailure("auth", redactSensitiveText(appendHint(error.message, AUTH_RULE)), { cause: error });
109
+ if (error.code === "quota") return new AcpFailure("quota", redactSensitiveText(appendHint(error.message, QUOTA_RULE)), { cause: error });
110
+ if (error.code === "timeout") return new AcpFailure("timeout", redactSensitiveText(appendHint(error.message, TIMEOUT_RULE)), { cause: error });
111
+ if (error.code === "spawn" || error.code === "process_exit") return new AcpFailure("transport", redactSensitiveText(appendHint(error.message, TRANSPORT_RULE)), { cause: error });
112
+ if (error.code === "invalid_input") return new AcpFailure("protocol", redactSensitiveText(appendHint(error.message, PROTOCOL_RULE)), { cause: error });
113
+ if (error.code === "model") return new AcpFailure("model", redactSensitiveText(error.message), { cause: error });
111
114
  }
112
115
  const message = error instanceof Error ? error.message : String(error);
113
116
  if (!message.trim()) return error instanceof Error ? error : new Error(message);
114
117
  for (const rule of RULES) {
115
- if (rule.match.test(message)) return new AcpFailure(rule.code, appendHint(message, rule), { cause: error });
118
+ if (rule.match.test(message)) return new AcpFailure(rule.code, redactSensitiveText(appendHint(message, rule)), { cause: error });
116
119
  }
117
- return error instanceof Error ? error : new Error(message);
120
+ const redacted = redactSensitiveText(message);
121
+ if (redacted === message) return error instanceof Error ? error : new Error(message);
122
+ return new Error(redacted);
118
123
  }
@@ -1,11 +1,5 @@
1
1
  // Google ships the same ACP server through two channels: the registry-signed
2
2
  // runtime installed under ~/.local/opt/agy-acp, and the agy CLI, which bundles
3
- // the server and self-updates on its own. The registry has lagged the CLI
4
- // (Claude and GPT-OSS models arrived in the CLI's server first), so when the
5
- // CLI on PATH is newer the adapter routes the launch through upstream's
6
- // AGY_ACP_BIN override instead of modifying vendored code. An explicit
7
- // AGY_ACP_BIN always wins, and every OMP process re-evaluates the choice so a
8
- // registry release that moves back ahead reclaims the launch.
9
3
 
10
4
  import { execFile } from "node:child_process";
11
5
  import fs from "node:fs";
@@ -13,6 +7,7 @@ import os from "node:os";
13
7
  import path from "node:path";
14
8
  import { promisify } from "node:util";
15
9
 
10
+ import { loadRuntimeSourcePreference } from "./adapter-config.ts";
16
11
  import { writeJsonAtomic } from "./fs-atomic.ts";
17
12
 
18
13
  const execFileAsync = promisify(execFile);
@@ -34,6 +29,43 @@ export interface AcpPermissionProfile {
34
29
  autoApproveProcess: boolean;
35
30
  }
36
31
 
32
+ export type AcpQuotaSource =
33
+ | { kind: "cli"; cliPath: string }
34
+ | { kind: "acp"; command: string; args: string[] };
35
+
36
+ export async function resolveAcpQuotaSource(
37
+ stateDir: string,
38
+ env: NodeJS.ProcessEnv = process.env,
39
+ home = os.homedir(),
40
+ platform: NodeJS.Platform = process.platform,
41
+ signal?: AbortSignal,
42
+ preference?: AcpRuntimePreference,
43
+ ): Promise<AcpQuotaSource | undefined> {
44
+ const wrapper = cliWrapperPath(stateDir, platform);
45
+ const configured = env.AGY_ACP_BIN?.trim();
46
+ const configuredIsWrapper = configured !== undefined && path.resolve(configured) === path.resolve(wrapper);
47
+ if (configured && !configuredIsWrapper) return { kind: "acp", ...resolveExplicitAcpCommand(configured, home, platform) };
48
+ if (preference?.source === "env") return configured ? { kind: "acp", ...resolveExplicitAcpCommand(configured, home, platform) } : undefined;
49
+ if (preference?.source === "cli") return preference.cliPath ? { kind: "cli", cliPath: preference.cliPath } : undefined;
50
+ if (preference?.source === "managed") {
51
+ const managed = resolveManagedAcpCommand(home, platform);
52
+ return managed ? { kind: "acp", ...managed } : undefined;
53
+ }
54
+ const runtimeSource = loadRuntimeSourcePreference(stateDir);
55
+ if (runtimeSource === "managed") {
56
+ const managed = resolveManagedAcpCommand(home, platform);
57
+ return managed ? { kind: "acp", ...managed } : undefined;
58
+ }
59
+ const recorded = configuredIsWrapper ? readRuntimeSourceRecord(stateDir) : undefined;
60
+ const recordedCli = recorded?.cliPath !== undefined && isExecutableFile(recorded.cliPath)
61
+ ? recorded.cliPath : undefined;
62
+ const cli = recordedCli ?? (await findAgyCli(env, signal))?.path;
63
+ if (cli) return { kind: "cli", cliPath: cli };
64
+ if (runtimeSource === "cli") return undefined;
65
+ const managed = resolveManagedAcpCommand(home, platform);
66
+ return managed ? { kind: "acp", ...managed } : undefined;
67
+ }
68
+
37
69
  export function resolveAcpPermissionProfile(
38
70
  preference: AcpRuntimePreference | undefined,
39
71
  requestedMode: AcpRequestedPermissionMode,
@@ -48,59 +80,117 @@ export function resolveAcpPermissionProfile(
48
80
  };
49
81
  }
50
82
 
83
+ function resolveExplicitAcpCommand(
84
+ configured: string,
85
+ home: string,
86
+ platform: NodeJS.Platform,
87
+ ): { command: string; args: string[] } {
88
+ const command = configured === "~" ? home
89
+ : configured.startsWith("~/") ? path.join(home, configured.slice(2)) : configured;
90
+ if (platform !== "linux") return { command, args: [] };
91
+ try {
92
+ const fd = fs.openSync(command, "r");
93
+ try {
94
+ const prefix = Buffer.alloc(2);
95
+ const count = fs.readSync(fd, prefix, 0, prefix.length, 0);
96
+ return { command, args: prefix.subarray(0, count).toString("utf8") === "#!" ? [] : ["--uid="] };
97
+ } finally {
98
+ fs.closeSync(fd);
99
+ }
100
+ } catch {
101
+ return { command, args: [] };
102
+ }
103
+ }
104
+
105
+ export function resolveManagedAcpCommand(
106
+ home = os.homedir(), platform: NodeJS.Platform = process.platform,
107
+ ): { command: string; args: string[] } | undefined {
108
+ const root = path.join(home, ".local", "opt", "agy-acp", "current");
109
+ for (const name of ["agy_acp_server.par", "agy_acp_server.exe"]) {
110
+ const command = path.join(root, name);
111
+ if (isExecutableFile(command)) return { command, args: platform === "linux" ? ["--uid="] : [] };
112
+ }
113
+ return undefined;
114
+ }
115
+
51
116
  export function assertSelectedAcpCliLaunch(
52
117
  stateDir: string,
53
118
  preference: AcpRuntimePreference | undefined,
54
119
  env: NodeJS.ProcessEnv = process.env,
55
- ): void {
120
+ platform: NodeJS.Platform = process.platform,
121
+ ): { command: string; args: string[] } | undefined {
56
122
  if (preference?.source !== "cli") return;
57
- const wrapper = path.join(stateDir, "agy-acp-cli.sh");
123
+ const wrapper = cliWrapperPath(stateDir, platform);
124
+ const configured = env.AGY_ACP_BIN?.trim();
58
125
  let intact = false;
59
126
  try {
60
- intact = preference.cliPath !== undefined && fs.readFileSync(wrapper, "utf8") === cliWrapperScript(preference.cliPath);
127
+ intact = preference.cliPath !== undefined && fs.readFileSync(wrapper, "utf8") === cliWrapperScript(preference.cliPath, platform);
61
128
  } catch {
62
129
  // Missing and unreadable wrappers fail the same launch check.
63
130
  }
64
- if (env.AGY_ACP_BIN !== wrapper || !isExecutableFile(wrapper) || !intact) {
131
+ if (!configured || path.resolve(configured) !== path.resolve(wrapper) || !isExecutableFile(wrapper) || !intact) {
65
132
  throw new Error(`Selected ACP CLI wrapper is missing, changed, not executable, or not selected by AGY_ACP_BIN: ${wrapper}`);
66
133
  }
67
134
  }
68
135
 
69
- export async function preferNewestAcpRuntime(
136
+ export async function selectAcpRuntime(
70
137
  stateDir: string,
71
138
  env: NodeJS.ProcessEnv = process.env,
72
139
  home = os.homedir(),
140
+ platform: NodeJS.Platform = process.platform,
73
141
  ): Promise<AcpRuntimePreference> {
74
- const wrapper = path.join(stateDir, "agy-acp-cli.sh");
142
+ const wrapper = cliWrapperPath(stateDir, platform);
75
143
  const configured = env.AGY_ACP_BIN?.trim();
76
- // A wrapper written by this adapter is not a user override. A second
77
- // extension instance can see the first instance's AGY_ACP_BIN and must
78
- // recover the CLI profile instead of treating it as an explicit env runtime.
79
- if (configured && path.resolve(configured) === path.resolve(wrapper)) {
144
+ const configuredIsWrapper = configured !== undefined && path.resolve(configured) === path.resolve(wrapper);
145
+ if (configured && !configuredIsWrapper) return { source: "env" };
146
+ const runtimeSource = loadRuntimeSourcePreference(stateDir);
147
+ const managedVersion = readManagedVersion(home);
148
+ if (runtimeSource === "cli") {
149
+ if (configuredIsWrapper) delete env.AGY_ACP_BIN;
80
150
  const cli = await findAgyCli(env);
81
- if (cli) {
82
- const preference = { source: "cli", cliPath: cli.path, cliVersion: cli.version, managedVersion: readManagedVersion(home) } as const;
83
- writeCliWrapper(wrapper, cli.path);
84
- writeRuntimeSourceRecord(stateDir, preference);
85
- env.AGY_ACP_BIN = wrapper;
86
- return preference;
151
+ if (!cli) throw new Error('runtimeSource is "cli" in config.json, but no usable agy CLI was found. Install the CLI or set runtimeSource to "auto".');
152
+ return selectCli(stateDir, wrapper, env, platform, cli, managedVersion);
153
+ }
154
+ if (runtimeSource === "managed") {
155
+ if (configuredIsWrapper) delete env.AGY_ACP_BIN;
156
+ if (!resolveManagedAcpCommand(home, platform)) {
157
+ throw new Error('runtimeSource is "managed" in config.json, but the managed ACP runtime is missing. Install it or set runtimeSource to "auto".');
87
158
  }
88
- const recorded = readRuntimeSourceRecord(stateDir);
89
- if (recorded) return recorded;
90
- } else if (configured) {
91
- return { source: "env" };
159
+ return { source: "managed", managedVersion };
92
160
  }
93
- // The generated wrapper is a POSIX shell script that upstream launches
94
- // directly; Windows cannot execute it, so it stays managed-only there.
95
- if (process.platform === "win32") return { source: "managed" };
96
161
  const cli = await findAgyCli(env);
97
- const managedVersion = readManagedVersion(home);
98
- if (!cli || (managedVersion && compareVersions(cli.version, managedVersion) <= 0)) {
99
- if (configured) delete env.AGY_ACP_BIN;
100
- return { source: "managed", cliPath: cli?.path, cliVersion: cli?.version, managedVersion };
162
+ if (cli) {
163
+ try {
164
+ return selectCli(stateDir, wrapper, env, platform, cli, managedVersion);
165
+ } catch {
166
+ // Fall through to recorded CLI or managed runtime when wrapper persistence fails.
167
+ }
101
168
  }
169
+ if (configuredIsWrapper) {
170
+ const recorded = readRuntimeSourceRecord(stateDir);
171
+ if (recorded && isExecutableFile(recorded.cliPath)) {
172
+ try {
173
+ writeCliWrapper(wrapper, recorded.cliPath, platform);
174
+ return recorded;
175
+ } catch {
176
+ // Fall through to managed runtime when wrapper persistence fails.
177
+ }
178
+ }
179
+ }
180
+ if (configured) delete env.AGY_ACP_BIN;
181
+ return { source: "managed", cliPath: cli?.path, cliVersion: cli?.version, managedVersion };
182
+ }
183
+
184
+ function selectCli(
185
+ stateDir: string,
186
+ wrapper: string,
187
+ env: NodeJS.ProcessEnv,
188
+ platform: NodeJS.Platform,
189
+ cli: { path: string; version: string },
190
+ managedVersion: string | undefined,
191
+ ): AcpRuntimePreference {
102
192
  const preference = { source: "cli", cliPath: cli.path, cliVersion: cli.version, managedVersion } as const;
103
- writeCliWrapper(wrapper, cli.path);
193
+ writeCliWrapper(wrapper, cli.path, platform);
104
194
  writeRuntimeSourceRecord(stateDir, preference);
105
195
  env.AGY_ACP_BIN = wrapper;
106
196
  return preference;
@@ -126,13 +216,16 @@ function readRuntimeSourceRecord(stateDir: string): AcpRuntimePreference | undef
126
216
  }
127
217
  }
128
218
 
129
- async function findAgyCli(env: NodeJS.ProcessEnv): Promise<{ path: string; version: string } | undefined> {
219
+ async function findAgyCli(env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<{ path: string; version: string } | undefined> {
130
220
  const agy = findExecutableOnPath("agy", env) ?? findExecutableOnPath("agy.exe", env);
131
221
  if (!agy) return undefined;
132
222
  try {
133
223
  // `acp --version` both proves the subcommand exists and reports the
134
224
  // bundled server version; a CLI without it must not be selected.
135
- const { stdout } = await execFileAsync(agy, ["acp", "--version"], { timeout: CLI_VERSION_TIMEOUT_MS });
225
+ const { stdout } = await execFileAsync(agy, ["acp", "--version"], {
226
+ timeout: CLI_VERSION_TIMEOUT_MS,
227
+ ...(signal ? { signal } : {}),
228
+ });
136
229
  const version = /\d+\.\d+\.\d+/.exec(stdout)?.[0];
137
230
  return version ? { path: agy, version } : undefined;
138
231
  } catch {
@@ -180,15 +273,23 @@ function compareVersions(left: string, right: string): number {
180
273
  return 0;
181
274
  }
182
275
 
183
- function cliWrapperScript(agyPath: string): string {
276
+ function cliWrapperPath(stateDir: string, platform: NodeJS.Platform): string {
277
+ return path.join(stateDir, platform === "win32" ? "agy-acp-cli.cmd" : "agy-acp-cli.sh");
278
+ }
279
+
280
+ function cliWrapperScript(agyPath: string, platform: NodeJS.Platform = process.platform): string {
281
+ if (platform === "win32") {
282
+ const escaped = agyPath.replace(/%/g, "%%");
283
+ return `@echo off\r\nsetlocal\r\nset "OMP_ACP_EXTRA="\r\nif "%OMP_ACP_DANGEROUSLY_SKIP_PERMISSIONS%"=="1" set "OMP_ACP_EXTRA=--dangerously-skip-permissions"\r\n"${escaped}" acp --app_data_dir=antigravity-acp %OMP_ACP_EXTRA% %*\r\nexit /b %ERRORLEVEL%\r\n`;
284
+ }
184
285
  // --app_data_dir=antigravity-acp is the managed .par's own default: the CLI
185
286
  // binary would otherwise default to antigravity-cli, mixing ACP sessions
186
287
  // with personal CLI chats outside session cleanup's tracked tree.
187
- return `#!/bin/sh\nif [ -n "\${OMP_ACP_DANGEROUSLY_SKIP_PERMISSIONS:-}" ]; then\n set -- --dangerously-skip-permissions "$@"\nfi\nexec '${agyPath.replace(/'/g, "'\\''")}' acp --app_data_dir=antigravity-acp "$@"\n`;
288
+ return `#!/bin/sh\nif [ "\${OMP_ACP_DANGEROUSLY_SKIP_PERMISSIONS:-}" = "1" ]; then\n set -- --dangerously-skip-permissions "$@"\nfi\nexec '${agyPath.replace(/'/g, "'\\''")}' acp --app_data_dir=antigravity-acp "$@"\n`;
188
289
  }
189
290
 
190
- function writeCliWrapper(file: string, agyPath: string): void {
191
- const script = cliWrapperScript(agyPath);
291
+ function writeCliWrapper(file: string, agyPath: string, platform: NodeJS.Platform = process.platform): void {
292
+ const script = cliWrapperScript(agyPath, platform);
192
293
  try {
193
294
  if (fs.readFileSync(file, "utf8") === script) return;
194
295
  } catch {
@@ -0,0 +1,104 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { writeJsonAtomic } from "./fs-atomic.ts";
4
+
5
+ export type AdapterPermissionMode = "default" | "auto_edit" | "yolo";
6
+ export type AdapterRuntimeUpdateMode = "automatic" | "notify" | "manual";
7
+ export type RuntimeSourcePreference = "auto" | "cli" | "managed";
8
+ export type AdapterUsageMode = "auto" | "off";
9
+ export type AdapterNativeToolMode = "prefer" | "disabled";
10
+
11
+ export interface AdapterConfig {
12
+ permissions: AdapterPermissionMode;
13
+ runtimeUpdates: AdapterRuntimeUpdateMode;
14
+ runtimeSource: RuntimeSourcePreference;
15
+ nativeTools: AdapterNativeToolMode;
16
+ debugToolUpdates: boolean;
17
+ usageMode: AdapterUsageMode;
18
+ diagnostics: boolean;
19
+ }
20
+
21
+ export interface AdapterConfigSeed {
22
+ nativeTools?: AdapterNativeToolMode;
23
+ debugToolUpdates?: boolean;
24
+ usageMode?: AdapterUsageMode;
25
+ diagnostics?: boolean;
26
+ }
27
+
28
+ const DEFAULTS: AdapterConfig = {
29
+ permissions: "yolo",
30
+ runtimeUpdates: "automatic",
31
+ runtimeSource: "auto",
32
+ nativeTools: "prefer",
33
+ debugToolUpdates: false,
34
+ usageMode: "off",
35
+ diagnostics: false,
36
+ };
37
+
38
+ function seeded(seed: AdapterConfigSeed): AdapterConfig {
39
+ return {
40
+ ...DEFAULTS,
41
+ nativeTools: seed.nativeTools ?? DEFAULTS.nativeTools,
42
+ debugToolUpdates: seed.debugToolUpdates ?? DEFAULTS.debugToolUpdates,
43
+ usageMode: seed.usageMode ?? DEFAULTS.usageMode,
44
+ diagnostics: seed.diagnostics ?? DEFAULTS.diagnostics,
45
+ };
46
+ }
47
+
48
+ export function loadAdapterConfig(file: string, seed: AdapterConfigSeed = {}): AdapterConfig {
49
+ let parsed: unknown;
50
+ try {
51
+ parsed = JSON.parse(fs.readFileSync(file, "utf8"));
52
+ } catch {
53
+ return seeded(seed);
54
+ }
55
+ if (!parsed || typeof parsed !== "object") return seeded(seed);
56
+ const record = parsed as Record<string, unknown>;
57
+ const runtimeSource = record.runtimeSource;
58
+ if (runtimeSource !== undefined && runtimeSource !== "auto" && runtimeSource !== "cli" && runtimeSource !== "managed") {
59
+ throw new Error('runtimeSource must be "auto", "cli", or "managed"');
60
+ }
61
+ if (record.nativeTools !== undefined && record.nativeTools !== "prefer" && record.nativeTools !== "disabled") {
62
+ throw new Error("nativeTools must be prefer or disabled");
63
+ }
64
+ if (record.debugToolUpdates !== undefined && typeof record.debugToolUpdates !== "boolean") {
65
+ throw new Error("debugToolUpdates must be boolean");
66
+ }
67
+ if (record.usageMode !== undefined && record.usageMode !== "auto" && record.usageMode !== "off") {
68
+ throw new Error("usageMode must be auto or off");
69
+ }
70
+ if (record.diagnostics !== undefined && typeof record.diagnostics !== "boolean") {
71
+ throw new Error("diagnostics must be boolean");
72
+ }
73
+ return {
74
+ permissions: record.permissions === "default" || record.permissions === "auto_edit" || record.permissions === "yolo"
75
+ ? record.permissions : DEFAULTS.permissions,
76
+ runtimeUpdates: record.runtimeUpdates === "automatic" || record.runtimeUpdates === "notify" || record.runtimeUpdates === "manual"
77
+ ? record.runtimeUpdates : DEFAULTS.runtimeUpdates,
78
+ runtimeSource: runtimeSource ?? DEFAULTS.runtimeSource,
79
+ nativeTools: record.nativeTools ?? seed.nativeTools ?? DEFAULTS.nativeTools,
80
+ debugToolUpdates: record.debugToolUpdates ?? seed.debugToolUpdates ?? DEFAULTS.debugToolUpdates,
81
+ usageMode: record.usageMode ?? seed.usageMode ?? DEFAULTS.usageMode,
82
+ diagnostics: record.diagnostics ?? seed.diagnostics ?? DEFAULTS.diagnostics,
83
+ };
84
+ }
85
+
86
+ export function updateAdapterConfig(file: string, patch: Partial<AdapterConfig>): AdapterConfig {
87
+ let raw: Record<string, unknown> = {};
88
+ try {
89
+ const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
90
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) raw = parsed as Record<string, unknown>;
91
+ } catch {
92
+ // A missing or malformed file starts from an empty object.
93
+ }
94
+ writeJsonAtomic(file, { ...raw, ...patch });
95
+ return loadAdapterConfig(file);
96
+ }
97
+
98
+ export function saveAdapterPermissionMode(mode: AdapterPermissionMode, file: string): void {
99
+ updateAdapterConfig(file, { permissions: mode });
100
+ }
101
+
102
+ export function loadRuntimeSourcePreference(stateDir: string): RuntimeSourcePreference {
103
+ return loadAdapterConfig(path.join(stateDir, "config.json")).runtimeSource;
104
+ }
@@ -18,14 +18,23 @@ const agentCommand = genericCommand ? entryOrCommand : process.execPath;
18
18
  const agentArgs = genericCommand ? forwardedArgs : [entryOrCommand, ...forwardedArgs];
19
19
 
20
20
  const parentPid = process.ppid;
21
- const agent = spawn(agentCommand, agentArgs, {
22
- stdio: ["pipe", "pipe", "pipe"],
23
- shell: false,
24
- windowsHide: true,
25
- // Give Antigravity and every tool it starts a group separate from the watchdog.
26
- detached: process.platform !== "win32",
27
- env: process.env,
28
- });
21
+ const windowsBatch = process.platform === "win32" && /\.(?:cmd|bat)$/iu.test(agentCommand);
22
+ const agent = windowsBatch
23
+ ? spawn(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", `call "${agentCommand}"`, ...agentArgs], {
24
+ stdio: ["pipe", "pipe", "pipe"],
25
+ windowsHide: true,
26
+ windowsVerbatimArguments: true,
27
+ detached: false,
28
+ env: process.env,
29
+ })
30
+ : spawn(agentCommand, agentArgs, {
31
+ stdio: ["pipe", "pipe", "pipe"],
32
+ shell: false,
33
+ windowsHide: true,
34
+ // Give Antigravity and every tool it starts a group separate from the watchdog.
35
+ detached: process.platform !== "win32",
36
+ env: process.env,
37
+ });
29
38
 
30
39
  let shuttingDown = false;
31
40
  let hardKillTimer;