omp-antigravity-acp-provider 0.1.35 → 0.1.37

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
@@ -17,12 +17,16 @@ 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
21
  - Per-model thinking levels, exposed only when the server confirms them.
21
22
  - OMP tools through an authenticated loopback MCP bridge.
22
23
  - Optional `disabled` native-tool mode for strict OMP-only sessions.
23
24
  - Lazy ACP startup and warm session reuse.
24
25
  - `/login` plus `/antigravity-acp` account, usage and cleanup commands.
25
26
  - API-equivalent cost estimates, not subscription billing.
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
+ - 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
+ - The MCP `tools/list` reflects the current OMP tool set. The offline wire test covers add, remove and restore on one warm ACP session.
26
30
 
27
31
  ## Install: for human
28
32
 
@@ -87,6 +91,7 @@ This shows the runtime, native-tool mode and usage state. Send a short prompt to
87
91
  | Login opens the wrong Google account | Both login paths always start a fresh sign-in. Choose the intended account (or "Use another account") on Google's consent screen. |
88
92
  | `disabled` native-tool mode rejects the session | The official runtime must advertise system-append support (1.4.1+). Upgrade the runtime or run `/antigravity-acp native-tools prefer`. |
89
93
  | The first request is slow | Runtime download and cold ACP start happen once; later turns reuse the warm session. |
94
+ | A tool call returns a relay notice | The model should call `pi_omp_await_result` with the notice's `call_id`. Lower `OMP_ACP_TOOL_RELAY_MS` or set it to `0` to disable relay. |
90
95
 
91
96
  ## Install: for agents
92
97
 
@@ -104,12 +109,13 @@ The installation runbook is in [AGENT_INSTALL.md](AGENT_INSTALL.md). Hand that f
104
109
  | `/antigravity-acp usage [auto\|off]` | Context occupancy and supplemental usage queries |
105
110
  | `/antigravity-acp context` | Per-model context budgets |
106
111
  | `/antigravity-acp cleanup [mode]` | Session-file cleanup policy |
112
+ | `/antigravity-acp diagnostics [on\|off\|reset]` | Adapter stage timing samples |
107
113
  | `/antigravity-acp native-tools prefer\|disabled` | Native built-in tool policy |
108
114
  | `/antigravity-acp tools` | Available and omitted OMP tool schemas |
109
115
  | `/antigravity-acp debug on\|off` | ACP tool-status lines |
110
116
  | `/antigravity-acp permissions default\|auto-edit\|yolo` | Permission mode |
111
117
 
112
- Supplemental `/usage` queries are off by default. Context occupancy still comes from ACP `usage_update`. Run `/antigravity-acp usage auto` to opt into the extra query.
118
+ 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.
113
119
 
114
120
  ## Steering and queued messages
115
121
 
@@ -117,8 +123,21 @@ By default a new user message waits for the active ACP turn to finish (`OMP_ACP_
117
123
 
118
124
  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.
119
125
 
126
+ An ACP turn that ends at the model's output limit is continued on the same session up to three times. `OMP_ACP_MAX_CONTINUATIONS=0` disables the loop; if agy already reported its own output-cap continuation, the adapter does not add another.
127
+
120
128
  Inference and `/antigravity-acp refresh` refuse to start ACP when no local Google login is available; run `/login` (or `/antigravity-acp login`) first instead of waiting for an interactive consent flow inside `session/new`.
121
129
 
130
+ ## Long tools and relay
131
+
132
+ A tool call that outlives `OMP_ACP_TOOL_RELAY_MS` (default 85000, `0` disables, otherwise 5000 through 165000) returns a relay notice instead of holding the MCP request open. The model calls `pi_omp_await_result` with the notice's `call_id`; the adapter returns the same original result, not a second execution. The control tool is a separate MCP server and is not added to OMP's tool list. If the ACP turn ends before the result arrives, the adapter retries the same result in a fresh ACP turn; it never delivers a stale result to a new writer.
133
+
134
+ Permission requests are correlated by session, turn and `toolCallId` with structured `mcpServerName`/`mcpToolName` metadata. A conflicting update, a previous-turn id, or a permission-before-update that claims MCP identity is rejected with `reject_once` when available, otherwise `cancelled`. Normal requests still go through OMP's human review.
135
+
136
+ The bridge's MCP `tools/list` always reflects the current OMP tool set. The offline wire test covers add, remove and restore on one warm ACP session. A live agent re-list has not been verified against the official agy runtime, so the adapter does not claim that the agent will always see a changed list.
137
+
138
+ A `refusal` stop reason is reported as an explicit provider refusal. An empty `end_turn` remains tolerated to preserve OMP's warm `/retry` path.
139
+
140
+
122
141
  ## Limitations vs direct OAuth
123
142
 
124
143
  - No direct model API endpoint or reverse-proxy mode.
@@ -1046,7 +1046,7 @@ IN THE SOFTWARE.
1046
1046
 
1047
1047
  ============================================================
1048
1048
 
1049
- typebox@1.3.27
1049
+ typebox@1.3.36
1050
1050
  License: MIT
1051
1051
 
1052
1052
  license
@@ -1076,7 +1076,7 @@ THE SOFTWARE.
1076
1076
 
1077
1077
  ============================================================
1078
1078
 
1079
- typebox@1.3.36
1079
+ typebox@1.3.27
1080
1080
  License: MIT
1081
1081
 
1082
1082
  license
@@ -0,0 +1,118 @@
1
+ // OMP decides whether to retry from the assistant error text. Keep the
2
+ // transport's distinction between account exhaustion and a transient throttle
3
+ // visible instead of collapsing both into "protocol".
4
+ export type AcpFailureCode =
5
+ | "auth"
6
+ | "quota"
7
+ | "rate_limit"
8
+ | "context"
9
+ | "timeout"
10
+ | "server"
11
+ | "transport"
12
+ | "protocol"
13
+ | "model"
14
+ | "refusal"
15
+ | "aborted";
16
+
17
+ export class AcpFailure extends Error {
18
+ constructor(readonly code: AcpFailureCode, message: string, options?: ErrorOptions) {
19
+ super(message, options);
20
+ this.name = "AcpFailure";
21
+ }
22
+ }
23
+
24
+ interface FailureRule {
25
+ code: Exclude<AcpFailureCode, "aborted">;
26
+ match: RegExp;
27
+ ensure: RegExp;
28
+ append: string;
29
+ }
30
+
31
+ const AUTH_RULE: FailureRule = {
32
+ code: "auth",
33
+ match: /authentication required|not logged in|not signed in|unauthenticated|sign in|invalid_grant|401 unauthorized/i,
34
+ ensure: /run `agy`|terminal/i,
35
+ append: "run `agy` once in a terminal to sign in",
36
+ };
37
+ const QUOTA_RULE: FailureRule = {
38
+ code: "quota",
39
+ match: /quota|resource.?exhausted|limit reached|exceeded your|insufficient_quota|out of budget|billing/i,
40
+ ensure: /quota exceeded|insufficient_quota|billing/i,
41
+ append: "quota exceeded",
42
+ };
43
+ const RATE_LIMIT_RULE: FailureRule = {
44
+ code: "rate_limit",
45
+ match: /rate.?limit|429|too many requests|overloaded|capacity|server_busy|high demand/i,
46
+ ensure: /rate.?limit|429|too many requests/i,
47
+ append: "rate limit",
48
+ };
49
+ const CONTEXT_RULE: FailureRule = {
50
+ code: "context",
51
+ match: /context (?:window|length|limit)|context_length_exceeded|too long|token limit|maximum.*tokens|prompt is too long/i,
52
+ ensure: /context|token limit|too long/i,
53
+ append: "context window exceeded",
54
+ };
55
+ const TIMEOUT_RULE: FailureRule = {
56
+ code: "timeout",
57
+ match: /timeout|timed out|deadline/i,
58
+ ensure: /timeout|timed out/i,
59
+ append: "timeout",
60
+ };
61
+ const PROTOCOL_RULE: FailureRule = {
62
+ code: "protocol",
63
+ match: /ownership was lost|unexpected permission mode|already running|already in progress|protocol/i,
64
+ ensure: /protocol|ownership|permission mode|already/i,
65
+ append: "protocol error",
66
+ };
67
+ const SERVER_RULE: FailureRule = {
68
+ code: "server",
69
+ match: /internal.?error|server.?error|5\d\d|service.?(?:is.?)?(?:temporarily.?)?unavailable/i,
70
+ ensure: /server|5\d\d|unavailable/i,
71
+ append: "server error",
72
+ };
73
+ const TRANSPORT_RULE: FailureRule = {
74
+ code: "transport",
75
+ match: /network|connection|fetch failed|socket|stream ended|closed|ENOTFOUND|EAI_AGAIN|broken pipe|EPIPE|failed to bind|process exited/i,
76
+ ensure: /connection|network|socket|stream|bind|process/i,
77
+ append: "connection error",
78
+ };
79
+ const RULES: FailureRule[] = [
80
+ AUTH_RULE,
81
+ QUOTA_RULE,
82
+ RATE_LIMIT_RULE,
83
+ CONTEXT_RULE,
84
+ TIMEOUT_RULE,
85
+ PROTOCOL_RULE,
86
+ SERVER_RULE,
87
+ TRANSPORT_RULE,
88
+ ];
89
+
90
+ function appendHint(message: string, rule: FailureRule): string {
91
+ return rule.ensure.test(message) ? message : `${message} (${rule.append})`;
92
+ }
93
+ interface AntigravityAcpErrorLike extends Error {
94
+ name: "AntigravityAcpError";
95
+ code: string;
96
+ }
97
+
98
+ function isAntigravityAcpError(error: unknown): error is AntigravityAcpErrorLike {
99
+ return error instanceof Error && error.name === "AntigravityAcpError"
100
+ && typeof (error as { code?: unknown }).code === "string";
101
+ }
102
+
103
+ export function classifyAcpFailure(error: unknown): Error {
104
+ if (isAntigravityAcpError(error)) {
105
+ 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 });
111
+ }
112
+ const message = error instanceof Error ? error.message : String(error);
113
+ if (!message.trim()) return error instanceof Error ? error : new Error(message);
114
+ for (const rule of RULES) {
115
+ if (rule.match.test(message)) return new AcpFailure(rule.code, appendHint(message, rule), { cause: error });
116
+ }
117
+ return error instanceof Error ? error : new Error(message);
118
+ }
@@ -0,0 +1,123 @@
1
+ // Google ships the same ACP server through two channels: the registry-signed
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
+
10
+ import { execFile } from "node:child_process";
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { promisify } from "node:util";
15
+
16
+ import { writeJsonAtomic } from "./fs-atomic.ts";
17
+
18
+ const execFileAsync = promisify(execFile);
19
+
20
+ const CLI_VERSION_TIMEOUT_MS = 5000;
21
+
22
+ export interface AcpRuntimePreference {
23
+ source: "env" | "cli" | "managed";
24
+ cliPath?: string;
25
+ cliVersion?: string;
26
+ managedVersion?: string;
27
+ }
28
+
29
+ export async function preferNewestAcpRuntime(
30
+ stateDir: string,
31
+ env: NodeJS.ProcessEnv = process.env,
32
+ home = os.homedir(),
33
+ ): Promise<AcpRuntimePreference> {
34
+ if (env.AGY_ACP_BIN?.trim()) return { source: "env" };
35
+ // The generated wrapper is a POSIX shell script that upstream launches
36
+ // directly; Windows cannot execute it, so it stays managed-only there.
37
+ if (process.platform === "win32") return { source: "managed" };
38
+ const cli = await findAgyCli(env);
39
+ const managedVersion = readManagedVersion(home);
40
+ if (!cli || (managedVersion && compareVersions(cli.version, managedVersion) <= 0)) {
41
+ return { source: "managed", cliPath: cli?.path, cliVersion: cli?.version, managedVersion };
42
+ }
43
+ const wrapper = path.join(stateDir, "agy-acp-cli.sh");
44
+ writeCliWrapper(wrapper, cli.path);
45
+ env.AGY_ACP_BIN = wrapper;
46
+ writeRuntimeSourceRecord(stateDir, { source: "cli", cliPath: cli.path, cliVersion: cli.version, managedVersion });
47
+ return { source: "cli", cliPath: cli.path, cliVersion: cli.version, managedVersion };
48
+ }
49
+
50
+ async function findAgyCli(env: NodeJS.ProcessEnv): Promise<{ path: string; version: string } | undefined> {
51
+ const agy = findExecutableOnPath("agy", env) ?? findExecutableOnPath("agy.exe", env);
52
+ if (!agy) return undefined;
53
+ try {
54
+ // `acp --version` both proves the subcommand exists and reports the
55
+ // bundled server version; a CLI without it must not be selected.
56
+ const { stdout } = await execFileAsync(agy, ["acp", "--version"], { timeout: CLI_VERSION_TIMEOUT_MS });
57
+ const version = /\d+\.\d+\.\d+/.exec(stdout)?.[0];
58
+ return version ? { path: agy, version } : undefined;
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ }
63
+
64
+ function findExecutableOnPath(name: string, env: NodeJS.ProcessEnv): string | undefined {
65
+ for (const directory of (env.PATH ?? "").split(path.delimiter)) {
66
+ if (!directory) continue;
67
+ const candidate = path.join(directory, name);
68
+ if (isExecutableFile(candidate)) return candidate;
69
+ }
70
+ return undefined;
71
+ }
72
+
73
+ function isExecutableFile(file: string): boolean {
74
+ try {
75
+ fs.accessSync(file, fs.constants.X_OK);
76
+ return fs.statSync(file).isFile();
77
+ } catch {
78
+ return false;
79
+ }
80
+ }
81
+
82
+ function readManagedVersion(home: string): string | undefined {
83
+ try {
84
+ const record = JSON.parse(
85
+ fs.readFileSync(path.join(home, ".local", "opt", "agy-acp", "current", "install-integrity.json"), "utf8"),
86
+ ) as { version?: unknown };
87
+ return typeof record.version === "string" ? record.version : undefined;
88
+ } catch {
89
+ return undefined;
90
+ }
91
+ }
92
+
93
+ function compareVersions(left: string, right: string): number {
94
+ const parse = (value: string) => value.split(".").map(part => Number.parseInt(part, 10) || 0);
95
+ const a = parse(left);
96
+ const b = parse(right);
97
+ for (let index = 0; index < Math.max(a.length, b.length); index += 1) {
98
+ const difference = (a[index] ?? 0) - (b[index] ?? 0);
99
+ if (difference) return Math.sign(difference);
100
+ }
101
+ return 0;
102
+ }
103
+
104
+ function writeCliWrapper(file: string, agyPath: string): void {
105
+ const script = `#!/bin/sh\nexec '${agyPath.replace(/'/g, "'\\''")}' acp "$@"\n`;
106
+ try {
107
+ if (fs.readFileSync(file, "utf8") === script) return;
108
+ } catch {
109
+ // Absent or unreadable; write a fresh copy below.
110
+ }
111
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
112
+ const temporary = `${file}.${process.pid}.tmp`;
113
+ try {
114
+ fs.writeFileSync(temporary, script, { mode: 0o755 });
115
+ fs.renameSync(temporary, file);
116
+ } finally {
117
+ fs.rmSync(temporary, { force: true });
118
+ }
119
+ }
120
+
121
+ function writeRuntimeSourceRecord(stateDir: string, record: AcpRuntimePreference): void {
122
+ writeJsonAtomic(path.join(stateDir, "acp-runtime-source.json"), { ...record, decidedAt: new Date().toISOString() });
123
+ }
@@ -0,0 +1,83 @@
1
+ // agy streams transport retries and its own output-cap continuation notice as
2
+ // assistant text. They are diagnostics, not model output, so keep them out of
3
+ // OMP's transcript without dropping a chunk that only looks like a prefix.
4
+ const AGENT_RETRY_NOTICE = /^\s*⚠\s*API error \(attempt \d+\)/i;
5
+ const OUTPUT_LIMIT_HEAD = "your previous response was cut off because it exceeded the output token limit";
6
+ const OUTPUT_LIMIT_TAIL = "please continue from where you left off, keeping your response shorter";
7
+
8
+ export type NoticeVerdict = "drop" | "hold" | "emit";
9
+
10
+ function noticeText(raw: string): string {
11
+ return raw.replace(/⚠/g, " ").replace(/\bError:/gi, " ").replace(/\s+/g, " ").trim().toLowerCase();
12
+ }
13
+
14
+ export function classifyOutputLimitNotice(raw: string): NoticeVerdict {
15
+ const text = noticeText(raw);
16
+ if (text.length === 0) return "emit";
17
+ const stripped = text.replace(/\s*retries remaining:\s*\d*\s*$/i, "").trim();
18
+ const retry = text.slice(stripped.length).trim();
19
+ if (retry.length > 0 && !/^retries remaining:\s*\d*$/i.test(retry)) return "emit";
20
+ if (stripped.length === 0) return /^retries remaining:\s*\d+$/i.test(text) ? "drop" : "emit";
21
+ const full = `${OUTPUT_LIMIT_HEAD} ${OUTPUT_LIMIT_TAIL}`;
22
+ if (stripped === full || stripped === OUTPUT_LIMIT_HEAD || stripped === OUTPUT_LIMIT_TAIL) return "drop";
23
+ if (full.startsWith(stripped) && stripped.startsWith("your previous")) return "hold";
24
+ if (OUTPUT_LIMIT_TAIL.startsWith(stripped) && stripped.startsWith("please continue from where you left off")) return "hold";
25
+ if ("retries remaining:".startsWith(text) && text.startsWith("retries")) return "hold";
26
+ return "emit";
27
+ }
28
+
29
+ // ACP notifications from several sessions share one connection callback, so
30
+ // the hold state is keyed by session and never leaks across streams.
31
+ export class AgentNoticeFilter {
32
+ private readonly holds = new Map<string, string>();
33
+ private readonly limitNotices = new Set<string>();
34
+ dropped = 0;
35
+
36
+ accept(sessionId: string, text: string): string | undefined {
37
+ const combined = (this.holds.get(sessionId) ?? "") + text;
38
+ const verdict = classifyOutputLimitNotice(combined);
39
+ if (verdict === "hold") {
40
+ this.holds.set(sessionId, combined);
41
+ return undefined;
42
+ }
43
+ this.holds.delete(sessionId);
44
+ if (verdict === "drop") {
45
+ this.dropped++;
46
+ this.limitNotices.add(sessionId);
47
+ return undefined;
48
+ }
49
+ if (AGENT_RETRY_NOTICE.test(combined)) {
50
+ this.dropped++;
51
+ return undefined;
52
+ }
53
+ return combined;
54
+ }
55
+
56
+ // A thought chunk proves the held text was model output rather than the
57
+ // start of agy's notice. A finished notice is counted and discarded.
58
+ flush(sessionId: string): string | undefined {
59
+ const held = this.holds.get(sessionId);
60
+ if (held === undefined) return undefined;
61
+ this.holds.delete(sessionId);
62
+ if (classifyOutputLimitNotice(held) === "drop") {
63
+ this.dropped++;
64
+ this.limitNotices.add(sessionId);
65
+ return undefined;
66
+ }
67
+ return held;
68
+ }
69
+
70
+ consumeOutputLimitNotice(sessionId: string): boolean {
71
+ return this.limitNotices.delete(sessionId);
72
+ }
73
+
74
+ forget(sessionId: string): void {
75
+ this.holds.delete(sessionId);
76
+ this.limitNotices.delete(sessionId);
77
+ }
78
+
79
+ clear(): void {
80
+ this.holds.clear();
81
+ this.limitNotices.clear();
82
+ }
83
+ }
@@ -84,6 +84,150 @@ export interface CommandControllerDeps {
84
84
  onModelsUpdated: (models: ConfiguredCatalogModel[]) => void;
85
85
  }
86
86
 
87
+ // OMP's TUI forwards an extension command's getArgumentCompletions into its
88
+ // slash-command autocomplete (same wiring the built-in autoresearch command
89
+ // uses). Items replace the argument text after "/antigravity-acp ", so values
90
+ // carry a trailing space to keep chained completion flowing.
91
+ export interface AntigravityCompletionItem {
92
+ value: string;
93
+ label: string;
94
+ description: string;
95
+ hint?: string;
96
+ }
97
+
98
+ export interface AntigravityCompletionDeps {
99
+ catalog: { currentModels: ReadonlyArray<{ id: string }> };
100
+ }
101
+
102
+ interface SubcommandSpec {
103
+ name: string;
104
+ description: string;
105
+ usage?: string;
106
+ values?: Array<[label: string, description: string]>;
107
+ }
108
+
109
+ const CONTEXT_SETTING_KEYS: Array<[label: string, description: string]> = [
110
+ ["contextWindow", "Total context window in tokens"],
111
+ ["maxTokens", "Maximum output tokens"],
112
+ ["inputTokenBudget", "Maximum input tokens per request"],
113
+ ["reserveTokens", "Tokens reserved for replies"],
114
+ ["maxTransferBytes", "Context transfer byte budget"],
115
+ ["maxImageBytes", "Per-image byte budget"],
116
+ ];
117
+
118
+ const SUBCOMMANDS: SubcommandSpec[] = [
119
+ { name: "status", description: "Runtime, permissions and usage report (default)" },
120
+ { name: "account", description: "Signed-in Google account and credential state" },
121
+ { name: "login", description: "Start a fresh Antigravity Google authorization" },
122
+ { name: "logout", description: "Clear Antigravity credentials, saved sessions and the OMP marker" },
123
+ { name: "tools", description: "Inspect the OMP↔ACP tool bridge" },
124
+ {
125
+ name: "usage",
126
+ description: "Usage accounting and connection state",
127
+ usage: "[auto|off]",
128
+ values: [["auto", "Query usage after each reply"], ["off", "Skip supplemental usage queries"]],
129
+ },
130
+ {
131
+ name: "context",
132
+ description: "Context window and transfer settings",
133
+ usage: "[set default|MODEL KEY NUMBER]",
134
+ values: [["set", "Override one setting for default or a model"]],
135
+ },
136
+ {
137
+ name: "cleanup",
138
+ description: "Collect saved ACP sessions now",
139
+ usage: "[off|conservative|timeout|balanced [DAYS]] | budget MAX_SESSIONS MAX_MIB",
140
+ values: [
141
+ ["off", "Keep every saved session"],
142
+ ["conservative", "Remove idle sessions (default)"],
143
+ ["timeout", "Remove sessions idle for DAYS"],
144
+ ["balanced", "Timeout cleanup plus budget enforcement"],
145
+ ["budget", "Cap MAX_SESSIONS and MAX_MIB"],
146
+ ],
147
+ },
148
+ {
149
+ name: "diagnostics",
150
+ description: "Diagnostics collection status",
151
+ usage: "[on|off|reset]",
152
+ values: [
153
+ ["on", "Enable diagnostics collection"],
154
+ ["off", "Disable diagnostics collection"],
155
+ ["reset", "Clear collected diagnostics"],
156
+ ],
157
+ },
158
+ {
159
+ name: "debug",
160
+ description: "Raw ACP tool-status display",
161
+ usage: "on|off",
162
+ values: [["on", "Show raw tool-status updates"], ["off", "Hide raw tool-status updates"]],
163
+ },
164
+ {
165
+ name: "native-tools",
166
+ description: "Native ACP tool exposure",
167
+ usage: "prefer|disabled",
168
+ values: [["prefer", "Let OMP tools shadow ACP natives (default)"], ["disabled", "Expose ACP-native tools only"]],
169
+ },
170
+ {
171
+ name: "permissions",
172
+ description: "Requested ACP permission mode",
173
+ usage: "default|auto-edit|yolo",
174
+ values: [
175
+ ["default", "Confirm edits and commands"],
176
+ ["auto-edit", "Auto-accept edits"],
177
+ ["yolo", "Auto-accept everything"],
178
+ ],
179
+ },
180
+ { name: "refresh", description: "Discover and cache advertised models" },
181
+ ];
182
+
183
+ function completeValues(typed: string, values: Array<[label: string, description: string]>,
184
+ valueOf: (label: string) => string): AntigravityCompletionItem[] | null {
185
+ const prefix = typed.toLowerCase();
186
+ const matched = values.filter(([label]) => label.toLowerCase().startsWith(prefix));
187
+ return matched.length ? matched.map(([label, description]) => ({ value: valueOf(label), label, description })) : null;
188
+ }
189
+
190
+ export function createAntigravityArgumentCompletions(deps: AntigravityCompletionDeps) {
191
+ return function getArgumentCompletions(args: string): AntigravityCompletionItem[] | null {
192
+ const firstSpace = args.indexOf(" ");
193
+ if (firstSpace === -1) {
194
+ const typed = args.toLowerCase();
195
+ const matched = SUBCOMMANDS.filter(spec => spec.name.startsWith(typed));
196
+ return matched.length ? matched.map(spec => ({
197
+ value: `${spec.name} `,
198
+ label: spec.name,
199
+ description: spec.description,
200
+ hint: spec.usage ? `${spec.name.slice(typed.length)} ${spec.usage}` : undefined,
201
+ })) : null;
202
+ }
203
+ const name = args.slice(0, firstSpace).toLowerCase();
204
+ const spec = SUBCOMMANDS.find(entry => entry.name === name);
205
+ const rest = args.slice(firstSpace + 1);
206
+ if (!spec?.values) return null;
207
+ if (spec.name === "context") {
208
+ const restSpace = rest.indexOf(" ");
209
+ if (restSpace === -1) return completeValues(rest, spec.values, label => `context ${label} `);
210
+ if (rest.slice(0, restSpace).toLowerCase() !== "set") return null;
211
+ const target = rest.slice(restSpace + 1);
212
+ const targetSpace = target.indexOf(" ");
213
+ if (targetSpace === -1) {
214
+ const targets: Array<[label: string, description: string]> = [
215
+ ["default", "Applied to every model"],
216
+ ...deps.catalog.currentModels.map(model => [model.id, "Per-model override"] as [string, string]),
217
+ ];
218
+ return completeValues(target, targets, label => `context set ${label} `);
219
+ }
220
+ const targetName = target.slice(0, targetSpace);
221
+ const settingKey = target.slice(targetSpace + 1);
222
+ if (settingKey.includes(" ")) return null;
223
+ const keys = [...CONTEXT_SETTING_KEYS];
224
+ if (targetName === "default") keys.push(["usageMode", "auto or off"]);
225
+ return completeValues(settingKey, keys, label => `context set ${targetName} ${label} `);
226
+ }
227
+ return completeValues(rest, spec.values, label => `${spec.name} ${label} `);
228
+ };
229
+ }
230
+
87
231
  export function createAntigravityCommandHandler(deps: CommandControllerDeps) {
88
232
  const sessionIdOf = (ctx: OmpCommandContext | undefined): string | undefined => ctx?.sessionManager?.getSessionId?.();
89
233
 
@@ -4,6 +4,7 @@ import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { applyApiCostEstimate } from "./pricing.ts";
7
+ import { preferNewestAcpRuntime } from "./acp-runtime-source.ts";
7
8
  import { SessionRuntimePool } from "./runtime-pool.ts";
8
9
  import { createStructuredFingerprintMemo } from "./structured-fingerprint.ts";
9
10
  import { Diagnostics, instrumentRuntime } from "./diagnostics.ts";
@@ -25,8 +26,9 @@ import {
25
26
  type OmpCommandContext,
26
27
  } from "./auth-sync.ts";
27
28
  import { CatalogStore } from "./catalog-store.ts";
28
- import { createAntigravityCommandHandler, type RuntimeBundleView, type ToolAuditSummary } from "./commands.ts";
29
+ import { createAntigravityArgumentCompletions, createAntigravityCommandHandler, type AntigravityCompletionItem, type RuntimeBundleView, type ToolAuditSummary } from "./commands.ts";
29
30
  import { formatCompactionNotice } from "./acp-compaction.ts";
31
+ import { classifyAcpFailure } from "./acp-errors.ts";
30
32
  import {
31
33
  AcpSessionStore,
32
34
  AntigravityRuntime,
@@ -51,7 +53,13 @@ interface OmpHostApi {
51
53
  registerProvider: (name: string, config: unknown) => void;
52
54
  unregisterProvider?: (name: string) => void;
53
55
  registerTool: (tool: unknown) => void;
54
- registerCommand: (name: string, command: { description: string; handler: (args: string, ctx: OmpCommandContext) => Promise<void> }) => void;
56
+ registerCommand: (name: string, command: {
57
+ description: string;
58
+ handler: (args: string, ctx: OmpCommandContext) => Promise<void>;
59
+ // OMP's autocomplete calls this with the text after "/<name> " and renders
60
+ // the returned items; optional so older hosts simply skip completion.
61
+ getArgumentCompletions?: (args: string) => AntigravityCompletionItem[] | null | Promise<AntigravityCompletionItem[] | null>;
62
+ }) => void;
55
63
  }
56
64
 
57
65
  export function resolveAdapterStateDir(env: NodeJS.ProcessEnv = process.env, home = os.homedir()): string {
@@ -94,8 +102,10 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
94
102
 
95
103
  // Loading this global extension must not start ACP or query Google.
96
104
  let readiness: Promise<void> | undefined;
105
+ let runtimePreference: Promise<void> | undefined;
97
106
  function prepareRuntime() {
98
- readiness ??= ensureAntigravityAcpReady().catch((error: unknown) => {
107
+ runtimePreference ??= preferNewestAcpRuntime(stateDir).catch(() => undefined);
108
+ readiness ??= runtimePreference.then(() => ensureAntigravityAcpReady()).catch((error: unknown) => {
99
109
  readiness = undefined;
100
110
  throw error;
101
111
  });
@@ -286,6 +296,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
286
296
  adapted.registerProvider();
287
297
  },
288
298
  }),
299
+ getArgumentCompletions: createAntigravityArgumentCompletions({ catalog: catalogStore }),
289
300
  });
290
301
 
291
302
  const adapted = new Proxy(pi, {
@@ -384,7 +395,7 @@ export async function registerOmpAdapter(pi: OmpHostApi, stateDir: string,
384
395
  } finally { lease.release(); }
385
396
  } catch (error) {
386
397
  routingFailed = true;
387
- deferred.fail(error, options?.signal?.aborted === true);
398
+ deferred.fail(classifyAcpFailure(error), options?.signal?.aborted === true);
388
399
  } finally {
389
400
  if (routingFailed) routing.noteFailure(routingId);
390
401
  lifecycle.finish(ticket);