@firespoon/pi-antigravity-bridge 0.0.0-stage → 1.10.7

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.
Files changed (54) hide show
  1. package/CHANGELOG.md +902 -0
  2. package/LICENSE +21 -0
  3. package/README.md +235 -3
  4. package/extensions/index.ts +1993 -0
  5. package/package.json +71 -6
  6. package/src/acp/connection.ts +623 -0
  7. package/src/acp/driver.ts +953 -0
  8. package/src/acp/events.ts +331 -0
  9. package/src/acp/home.ts +238 -0
  10. package/src/acp/jsonrpc.ts +232 -0
  11. package/src/acp/setup.ts +107 -0
  12. package/src/acp/usage-estimate.ts +61 -0
  13. package/src/agents.ts +64 -0
  14. package/src/agy-install.ts +85 -0
  15. package/src/agy-paths.ts +30 -0
  16. package/src/agy-setup.ts +72 -0
  17. package/src/agy-version.ts +283 -0
  18. package/src/approval-detect.ts +146 -0
  19. package/src/approval-gate.ts +208 -0
  20. package/src/approval-hook.ts +270 -0
  21. package/src/artifacts-ui.ts +88 -0
  22. package/src/artifacts.ts +144 -0
  23. package/src/ask-tool.ts +1222 -0
  24. package/src/background-watch.ts +225 -0
  25. package/src/bridge-catalog.ts +27 -0
  26. package/src/config.ts +485 -0
  27. package/src/daily-log.ts +196 -0
  28. package/src/dialog-lock.ts +48 -0
  29. package/src/diff-render.ts +205 -0
  30. package/src/driver-types.ts +172 -0
  31. package/src/driver.ts +907 -0
  32. package/src/engine-picker.ts +160 -0
  33. package/src/frame-guard.ts +38 -0
  34. package/src/mcp-registration.ts +382 -0
  35. package/src/mcp-server.ts +620 -0
  36. package/src/models.ts +407 -0
  37. package/src/native-tools.ts +104 -0
  38. package/src/parked-turn.ts +125 -0
  39. package/src/patch-cleanup.ts +519 -0
  40. package/src/poll-fold.ts +55 -0
  41. package/src/prompt-images.ts +92 -0
  42. package/src/provider.ts +2066 -0
  43. package/src/queued-messages.ts +152 -0
  44. package/src/redact.ts +27 -0
  45. package/src/sessions.ts +185 -0
  46. package/src/skills.ts +192 -0
  47. package/src/stream-events.ts +122 -0
  48. package/src/stream-sanitizer.ts +180 -0
  49. package/src/subagent-roster.ts +245 -0
  50. package/src/sysprompt-agent.ts +163 -0
  51. package/src/tasks-ui.ts +90 -0
  52. package/src/tasks.ts +174 -0
  53. package/src/usage.ts +174 -0
  54. package/src/web-tools.ts +320 -0
@@ -0,0 +1,283 @@
1
+ // agy CLI version gate.
2
+ //
3
+ // An agy older than MIN_AGY_VERSION fails stream-json turns with raw stream
4
+ // errors that look like bridge bugs, so we detect it once per process and
5
+ // say so plainly (session-start warning + /agy doctor) instead of letting
6
+ // users debug parse noise. Pure functions here; the only subprocess is
7
+ // `agy --version`, memoized per binary because discovery already spawns agy
8
+ // once per load and the version will not change mid-process.
9
+ //
10
+ // The ACP server reports the CLI version at initialize. agy acp has its own
11
+ // floor because older CLI releases do not ship the subcommand.
12
+
13
+ import { spawn } from "node:child_process";
14
+ import fs from "node:fs";
15
+ import os from "node:os";
16
+ import path from "node:path";
17
+
18
+ /** Floor for the stream-json CLI. Matches the protocol grammar our driver
19
+ * and the event mapping rely on; older agy predates verified fields. */
20
+ export const MIN_AGY_VERSION = "1.1.22";
21
+ export const MIN_AGY_ACP_VERSION = "1.5.3";
22
+ /** Highest agy release where the top-level --gemini_dir flag was
23
+ * live-verified to isolate MCP discovery (issue #14 work, 2026-11-13).
24
+ * The flag is undocumented upstream and may change shape in future
25
+ * releases; the parse probe catches removal, but a flag that parses yet is
26
+ * IGNORED cannot be probed without quota - versions above this floor warn
27
+ * so a silent G9 tool drop gets noticed. */
28
+ export const MIN_GEMINI_DIR_VERSION = "1.5.8";
29
+
30
+ const VERSION_TIMEOUT_MS = 5_000;
31
+
32
+ export type AgyVersionStatus =
33
+ | "ok"
34
+ | "unsupported"
35
+ | "development"
36
+ | "invalid"
37
+ | "unavailable";
38
+
39
+ export interface AgyVersionCheck {
40
+ status: AgyVersionStatus;
41
+ /** Extracted triple when status is ok/unsupported; raw dev token for development. */
42
+ version?: string;
43
+ /** Full --version output, for doctor detail. */
44
+ raw: string;
45
+ }
46
+
47
+ /** Pull the first strict triple (`1.2.10`) out of arbitrary version output.
48
+ * Prefixed forms like "agy_acp_server_1.1.1" and banner text both match;
49
+ * anything without a triple is not a version we can gate on. */
50
+ export function parseAgyVersionTriple(text: string): string | undefined {
51
+ return /\d+\.\d+\.\d+/.exec(text)?.[0];
52
+ }
53
+
54
+ /** Numeric triple compare; 1.10.0 > 1.9.9, unlike string compare. */
55
+ export function compareVersionTuples(a: string, b: string): number {
56
+ const pa = a.split(".").map(Number);
57
+ const pb = b.split(".").map(Number);
58
+ for (let i = 0; i < 3; i++) {
59
+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);
60
+ if (d !== 0) return d;
61
+ }
62
+ return 0;
63
+ }
64
+
65
+ /** Classify raw `--version` output against a floor. Pure: unit-tested for
66
+ * every status; checkAgyCliVersion wraps this with the subprocess. */
67
+ export function agyVersionVerdict(
68
+ raw: string,
69
+ floor: string = MIN_AGY_VERSION,
70
+ ): AgyVersionCheck {
71
+ // Development builds (agy from source) self-identify as dev, HEAD, or the
72
+ // spelled-out word; never gate any of them.
73
+ if (/\b(dev|head|development)\b/i.test(raw))
74
+ return { status: "development", version: "dev", raw };
75
+ const triple = parseAgyVersionTriple(raw);
76
+ if (!triple) return { status: "invalid", raw };
77
+ if (compareVersionTuples(triple, floor) < 0) return { status: "unsupported", version: triple, raw };
78
+ return { status: "ok", version: triple, raw };
79
+ }
80
+
81
+ const checkCache = new Map<string, Promise<AgyVersionCheck>>();
82
+
83
+ /** Run `binary --version` and classify the result. Memoized per binary for
84
+ * the process lifetime (resetAgyVersionCache clears it for tests). Fail
85
+ * paths: spawn error (ENOENT etc.) and watchdog timeout are "unavailable",
86
+ * a distinct status so doctor can say "could not run" instead of blaming
87
+ * the version string. */
88
+ export function checkAgyCliVersion(binary: string = "agy"): Promise<AgyVersionCheck> {
89
+ const cached = checkCache.get(binary);
90
+ if (cached) return cached;
91
+ const run = new Promise<AgyVersionCheck>((resolve) => {
92
+ let out = "";
93
+ let done = false;
94
+ const finish = (check: AgyVersionCheck) => {
95
+ if (done) return;
96
+ done = true;
97
+ clearTimeout(watchdog);
98
+ resolve(check);
99
+ };
100
+ let proc: ReturnType<typeof spawn>;
101
+ try {
102
+ proc = spawn(binary, ["--version"], { stdio: ["ignore", "pipe", "ignore"], shell: false });
103
+ } catch {
104
+ finish({ status: "unavailable", raw: "" });
105
+ return;
106
+ }
107
+ proc.stdout?.setEncoding("utf8");
108
+ proc.stdout?.on("data", (d: string) => (out = (out + d).slice(0, 4096)));
109
+ proc.on("error", () => finish({ status: "unavailable", raw: "" }));
110
+ // Exit code is ignored on purpose: `agy --version` failures print to
111
+ // stderr (ignored) and leave junk or empty stdout, which classifies as
112
+ // invalid — close enough in effect to unavailable for a warn-only gate.
113
+ proc.on("close", () => finish(agyVersionVerdict(out)));
114
+ const watchdog = setTimeout(() => {
115
+ try {
116
+ proc.kill("SIGKILL");
117
+ } catch {
118
+ /* already gone */
119
+ }
120
+ finish({ status: "unavailable", raw: out });
121
+ }, VERSION_TIMEOUT_MS);
122
+ });
123
+ checkCache.set(binary, run);
124
+ return run;
125
+ }
126
+
127
+ /** Test seam: drop all memoized checks. */
128
+ export function resetAgyVersionCache(): void {
129
+ checkCache.clear();
130
+ }
131
+
132
+ // --- --gemini_dir capability probe (issue #14) -------------------------------
133
+
134
+ export interface GeminiDirProbe {
135
+ /** True when the running agy parses --gemini_dir on the default run path
136
+ * (the stream-json spawn shape). Refusal means fall back to global MCP
137
+ * registration plus the suppression machinery. */
138
+ supported: boolean;
139
+ version?: string;
140
+ /** Supported but the version is above MIN_GEMINI_DIR_VERSION (or
141
+ * unreadable): the parse probe cannot detect a flag that is accepted but
142
+ * ignored, so the caller should warn once. */
143
+ unverifiedVersion: boolean;
144
+ /** Why the probe said no (absent when supported). Distinguishes an agy
145
+ * that refuses the flag from one the probe could not run at all. */
146
+ detail?: "refused" | "timeout" | "spawn-failure";
147
+ }
148
+
149
+ /** How the stream-json engine should deliver MCP (issue #14). */
150
+ export type StreamHomeMode = "isolated" | "override-skip" | "legacy";
151
+
152
+ /** Decide the stream-json MCP-home mode BEFORE any probe spawn. The
153
+ * AGY_AGENTS_ROOT sandbox override wins over everything: carriers stage
154
+ * outside the staged home's live agents view, so isolation would silently
155
+ * drop the system-prompt carrier regardless of what the probe says. */
156
+ export function resolveStreamHomeMode(input: {
157
+ engine: string;
158
+ agentsRootOverride: boolean;
159
+ probe: GeminiDirProbe | undefined;
160
+ }): StreamHomeMode {
161
+ if (input.engine !== "stream-json") return "legacy";
162
+ if (input.agentsRootOverride) return "override-skip";
163
+ return input.probe?.supported ? "isolated" : "legacy";
164
+ }
165
+
166
+ export interface ProbeGeminiDirOptions {
167
+ /** Parent dir for the probe home (tests inject an unwritable root). */
168
+ tmpRoot?: string;
169
+ /** Probe watchdog budget (tests shrink the 5s default). */
170
+ watchdogMs?: number;
171
+ /** Extra env for the spawned probe (tests select fixture behaviors). */
172
+ env?: Record<string, string>;
173
+ }
174
+
175
+ const probeCache = new Map<string, Promise<GeminiDirProbe>>();
176
+
177
+ /** One spawn answers BOTH questions: `agy --gemini_dir <tmp> --version`
178
+ * prints the version when the flag parses, and a Go flag-package refusal
179
+ * ("flag provided but not defined", nonzero exit, empty stdout) when it
180
+ * does not. The default run path parses the underscore form; the acp
181
+ * subcommand takes the hyphen form (both live-verified 2026-11-13 on agy
182
+ * 1.5.8). Memoized per binary until resetGeminiDirProbeCache. */
183
+ export function probeGeminiDirFlag(binary: string = "agy", opts: ProbeGeminiDirOptions = {}): Promise<GeminiDirProbe> {
184
+ const cached = probeCache.get(binary);
185
+ if (cached) return cached;
186
+ const run = new Promise<GeminiDirProbe>((resolve) => {
187
+ let tmp: string;
188
+ try {
189
+ tmp = fs.mkdtempSync(path.join(opts.tmpRoot ?? os.tmpdir(), "agy-geminidir-probe-"));
190
+ } catch {
191
+ // Cannot even stage the probe home: the flag is unproven, fall back.
192
+ resolve({ supported: false, unverifiedVersion: false, detail: "spawn-failure" });
193
+ return;
194
+ }
195
+ let out = "";
196
+ let err = "";
197
+ let code: number | null = null;
198
+ let done = false;
199
+ const finish = () => {
200
+ if (done) return;
201
+ done = true;
202
+ clearTimeout(watchdog);
203
+ fs.rmSync(tmp, { recursive: true, force: true });
204
+ // Exit 0 wins: a CLI can print arbitrary warnings (including text
205
+ // that happens to contain "not defined") on a successful probe.
206
+ if (code === 0) {
207
+ const verdict = agyVersionVerdict(out);
208
+ if (verdict.status === "development") {
209
+ resolve({ supported: true, version: "dev", unverifiedVersion: true });
210
+ return;
211
+ }
212
+ const version = verdict.version;
213
+ resolve({
214
+ supported: true,
215
+ version,
216
+ unverifiedVersion:
217
+ !version || compareVersionTuples(version, MIN_GEMINI_DIR_VERSION) > 0,
218
+ });
219
+ return;
220
+ }
221
+ const detail: NonNullable<GeminiDirProbe["detail"]> = /not defined/.test(err)
222
+ ? "refused"
223
+ : code === null
224
+ ? "timeout"
225
+ : "spawn-failure";
226
+ resolve({ supported: false, unverifiedVersion: false, detail });
227
+ };
228
+ let proc: ReturnType<typeof spawn>;
229
+ try {
230
+ proc = spawn(binary, ["--gemini_dir", tmp, "--version"], {
231
+ stdio: ["ignore", "pipe", "pipe"],
232
+ shell: false,
233
+ env: opts.env ? { ...process.env, ...opts.env } : process.env,
234
+ });
235
+ } catch {
236
+ fs.rmSync(tmp, { recursive: true, force: true });
237
+ resolve({ supported: false, unverifiedVersion: false, detail: "spawn-failure" });
238
+ return;
239
+ }
240
+ proc.stdout?.setEncoding("utf8");
241
+ proc.stderr?.setEncoding("utf8");
242
+ proc.stdout?.on("data", (d: string) => (out = (out + d).slice(0, 4096)));
243
+ proc.stderr?.on("data", (d: string) => (err = (err + d).slice(0, 4096)));
244
+ proc.on("error", () => {
245
+ code = code ?? -1;
246
+ finish();
247
+ });
248
+ proc.on("close", (c) => {
249
+ code = c;
250
+ finish();
251
+ });
252
+ const watchdog = setTimeout(() => {
253
+ try {
254
+ proc.kill("SIGKILL");
255
+ } catch {
256
+ /* already gone */
257
+ }
258
+ }, opts.watchdogMs ?? 5_000);
259
+ });
260
+ probeCache.set(binary, run);
261
+ return run;
262
+ }
263
+
264
+ /** Test seam: drop the memoized gemini_dir probes. */
265
+ export function resetGeminiDirProbeCache(): void {
266
+ probeCache.clear();
267
+ }
268
+
269
+ /** One-line doctor rendering. */
270
+ export function describeAgyVersionCheck(check: AgyVersionCheck): string {
271
+ switch (check.status) {
272
+ case "ok":
273
+ return check.version ?? "ok";
274
+ case "unsupported":
275
+ return `${check.version} TOO OLD`;
276
+ case "development":
277
+ return "development build";
278
+ case "invalid":
279
+ return "unreadable version output";
280
+ case "unavailable":
281
+ return "could not run --version";
282
+ }
283
+ }
@@ -0,0 +1,146 @@
1
+ // Third-party pi permission-extension detection for the approval gate
2
+ // (docs/TODO.md 2.5). The gate defaults to "auto": OFF until one of these
3
+ // extensions is present. Detection reads pi's settings (the packages array
4
+ // is the primary, name-exact signal) plus known on-disk config markers for
5
+ // the audited permission packages (sources: ~/tmp/pi-perm-research/, audit
6
+ // 2026-09-07). Best effort by design: a miss only means the user enables
7
+ // the gate manually; a false positive stages hooks.json, which is inert
8
+ // unless the ACP/CLI server loads it, and observation-only hooks are safe.
9
+ //
10
+ // Run: npm test
11
+
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+
16
+ /** npm names of the audited pi permission packages (docs/TODO.md 2.4). */
17
+ export const KNOWN_GATE_PACKAGES = [
18
+ "@gotgenes/pi-permission-system",
19
+ "@zhushanwen/pi-permission",
20
+ "pi-permission-system",
21
+ "@xzzpig/pi-permission-system",
22
+ "@diegopetrucci/pi-permission-gate",
23
+ "pi-permission-modes",
24
+ "@inobit/pi-permission",
25
+ "@thurstonsand/pi-permissions",
26
+ "@monroewilliams/pi-permission-system",
27
+ "@rhedbull/pi-permissions",
28
+ ] as const;
29
+
30
+ export interface GateExtensionHit {
31
+ /** The known package name matched. */
32
+ name: string;
33
+ /** How it was detected: "settings:<path>" or "config:<path>". */
34
+ evidence: string;
35
+ }
36
+
37
+ function readJsonIfPresent(file: string): { packages?: unknown } | undefined {
38
+ try {
39
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
40
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : undefined;
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }
45
+
46
+ function packagesFrom(settingsFile: string): string[] {
47
+ const parsed = readJsonIfPresent(settingsFile);
48
+ const raw = parsed?.packages;
49
+ if (!Array.isArray(raw)) return [];
50
+ return raw.filter((entry): entry is string => typeof entry === "string");
51
+ }
52
+
53
+ function nameMatchesPackage(entry: string): string | undefined {
54
+ // entries look like "npm:@scope/name@1.2.3", "git:...", or a bare path.
55
+ // Boundary-aware match: the known name must start after :/@ (or the
56
+ // string start) and must not be a prefix of a longer package name
57
+ // ("pi-permission-system-clone" must NOT match). Version suffix @x.y is
58
+ // fine. Peer review 2026-09-07 finding 4.
59
+ const lower = entry.toLowerCase();
60
+ let best: string | undefined;
61
+ for (const name of KNOWN_GATE_PACKAGES) {
62
+ if (containsName(lower, name) && (best === undefined || name.length > best.length)) best = name;
63
+ }
64
+ // Longest match wins: "@xzzpig/pi-permission-system" must resolve to the
65
+ // scoped name, not to the shorter unscoped fork "pi-permission-system".
66
+ return best;
67
+ }
68
+
69
+ function containsName(lower: string, name: string): boolean {
70
+ let idx = lower.indexOf(name);
71
+ while (idx >= 0) {
72
+ const before = idx === 0 ? "" : lower[idx - 1];
73
+ const after = lower[idx + name.length] ?? "";
74
+ const okBefore = before === "" || ":/@".includes(before);
75
+ const okAfter = after === "" || after === "@" || !/[a-z0-9_-]/.test(after);
76
+ if (okBefore && okAfter) return true;
77
+ idx = lower.indexOf(name, idx + 1);
78
+ }
79
+ return false;
80
+ }
81
+
82
+ /**
83
+ * Detect installed third-party permission extensions.
84
+ *
85
+ * @param opts.home HOME override for tests.
86
+ * @param opts.cwd project dir override for tests (project settings).
87
+ * @param opts.settingsFiles extra settings files to scan (tests).
88
+ */
89
+ export function detectPermissionGateExtensions(
90
+ opts: { home?: string; cwd?: string; settingsFiles?: string[] } = {},
91
+ ): GateExtensionHit[] {
92
+ const home = opts.home ?? os.homedir();
93
+ const cwd = opts.cwd ?? process.cwd();
94
+ const hits: GateExtensionHit[] = [];
95
+ const seen = new Set<string>();
96
+
97
+ const settingsCandidates = [
98
+ ...(opts.settingsFiles ?? []),
99
+ path.join(home, ".pi", "agent", "settings.json"),
100
+ path.join(cwd, ".pi", "settings.json"),
101
+ ];
102
+ for (const file of settingsCandidates) {
103
+ for (const entry of packagesFrom(file)) {
104
+ const name = nameMatchesPackage(entry);
105
+ if (name && !seen.has(name)) {
106
+ seen.add(name);
107
+ hits.push({ name, evidence: `settings:${file}` });
108
+ }
109
+ }
110
+ }
111
+
112
+ // Known config-file markers from the audit. Presence of the config does
113
+ // not prove the extension is installed, but every audited package writes
114
+ // its config only after install + first run, which is evidence enough for
115
+ // an opt-in default.
116
+ const markers: Array<{ file: string; name: string }> = [
117
+ { file: path.join(home, ".pi", "agent", "extensions", "pi-permission-system"), name: "@gotgenes/pi-permission-system" },
118
+ { file: path.join(home, ".agent", "pi-permissions.jsonc"), name: "@monroewilliams/pi-permission-system" },
119
+ { file: path.join(home, ".pi", "agent", "extensions", "permissions.json"), name: "@rhedbull/pi-permissions" },
120
+ { file: path.join(cwd, ".pi", "agent", "pi-permissions.jsonc"), name: "@gotgenes/pi-permission-system" },
121
+ ];
122
+ for (const marker of markers) {
123
+ if (!seen.has(marker.name)) {
124
+ try {
125
+ fs.statSync(marker.file);
126
+ seen.add(marker.name);
127
+ hits.push({ name: marker.name, evidence: `config:${marker.file}` });
128
+ } catch {
129
+ /* absent - fine */
130
+ }
131
+ }
132
+ }
133
+
134
+ return hits;
135
+ }
136
+
137
+ /** Resolve the effective gate shape from config + detection. "auto" defers
138
+ * to detection (shadow when any gate extension is present, else off). */
139
+ export function resolveGateMode(
140
+ gateMode: "auto" | "shadow" | "dedicated" | "off",
141
+ hits: GateExtensionHit[],
142
+ ): "shadow" | "dedicated" | "off" {
143
+ if (gateMode === "off") return "off";
144
+ if (gateMode === "shadow" || gateMode === "dedicated") return gateMode;
145
+ return hits.length > 0 ? "shadow" : "off";
146
+ }
@@ -0,0 +1,208 @@
1
+ // Approval-gate shadow tools (docs/TODO.md section 2.5, design v2).
2
+ //
3
+ // When the approval gate is active, the bridge re-registers pi's mutating
4
+ // builtins (bash, write, edit) as SHADOW tools: same name, same schema plus
5
+ // internal __agy* marker fields. Two behaviors, keyed on the marker:
6
+ //
7
+ // - marker absent: delegate to the captured real builtin. Normal pi
8
+ // behavior (including the G9 path, where pi tools execute for real) is
9
+ // untouched.
10
+ // - marker present: the call is an approval round-trip for an agy NATIVE
11
+ // tool. NEVER execute locally. Ask the policy for a decision; agy runs
12
+ // the tool in its own loop either way.
13
+ //
14
+ // Decision mapping (consumed by the provider's /approval park):
15
+ // resolve (success result) -> {"decision":"allow"}
16
+ // throw -> {"decision":"deny","reason": message}
17
+ // pi's tool executor converts thrown errors into error tool results with
18
+ // the message as text, matching how builtins report failures (write.js,
19
+ // edit-diff.js). A tool_call handler that blocks the shadow call upstream
20
+ // (any third-party permission extension) produces the same error result
21
+ // without execute() running, so both paths land on the same deny mapping.
22
+ //
23
+ // Run: npm test
24
+
25
+ import type {
26
+ AgentToolResult,
27
+ AgentToolUpdateCallback,
28
+ ExtensionToolContext,
29
+ ToolDefinition,
30
+ } from "@earendil-works/pi-coding-agent";
31
+
32
+ /** Marker flag: this shadow-tool call is an approval round-trip, not a real
33
+ * invocation. The bridge's provider sets it when composing the toolUse. */
34
+ export const GATE_MARKER = "__agyGate";
35
+
36
+ /** Internal context fields the provider may attach next to the marker.
37
+ * Stripped before delegating to the real builtin. */
38
+ export const MARKER_FIELDS = [GATE_MARKER, "__agyTicket", "__agyTool"] as const;
39
+
40
+ export type AnyToolDefinition = ToolDefinition<any, any, any>;
41
+
42
+ export interface GateDecision {
43
+ allow: boolean;
44
+ reason?: string;
45
+ }
46
+
47
+ /** Fallback policy: consulted only when NO extension blocked the shadow
48
+ * tool_call. Implementations map approvals.mode: ask -> ctx.ui.confirm
49
+ * (guarded by ctx.hasUI), allow -> {allow:true}, deny -> {allow:false}. */
50
+ export type GatePolicy = (call: {
51
+ tool: string;
52
+ params: Record<string, unknown>;
53
+ ctx: unknown;
54
+ }) => Promise<GateDecision> | GateDecision;
55
+
56
+ /** Marker schemas injected into the shadow parameters. Optional, so the
57
+ * model's own calls stay valid; audited permission extensions match only
58
+ * their known fields (command/path) and ignore these. */
59
+ const MARKER_SCHEMAS: Record<string, unknown> = {
60
+ [GATE_MARKER]: {
61
+ type: "boolean",
62
+ description:
63
+ "Internal bridge approval marker. Never set this yourself; calls without local execution intent must not set it.",
64
+ },
65
+ __agyTicket: { type: "string" },
66
+ __agyTool: { type: "string", description: "Native agy tool this approval round-trip is for." },
67
+ };
68
+
69
+ /** Clone a tool's parameter schema with the marker fields added as optional
70
+ * properties. Field-exact for everything the permission extensions match on
71
+ * (command, path, edits, ...). Does not mutate the base schema. */
72
+ export function withGateMarkerSchema(base: AnyToolDefinition["parameters"]): AnyToolDefinition["parameters"] {
73
+ const src = base as { properties?: Record<string, unknown> };
74
+ return { ...base, properties: { ...src.properties, ...MARKER_SCHEMAS } } as AnyToolDefinition["parameters"];
75
+ }
76
+
77
+ /** Copy of params without the internal marker fields, for delegation. */
78
+ export function stripMarkerFields(params: Record<string, unknown>): Record<string, unknown> {
79
+ const out = { ...params };
80
+ for (const field of MARKER_FIELDS) delete out[field];
81
+ return out;
82
+ }
83
+
84
+ export interface ShadowMapping {
85
+ shadow: "bash" | "write" | "edit";
86
+ input: Record<string, unknown>;
87
+ }
88
+
89
+ /** Map an agy native tool call (hook stdin payload) onto the shadow surface.
90
+ * Field names follow the TODO 2.5 table: create_file is live-captured (F1);
91
+ * the edit-class arg names are docs-attested and degrade gracefully - a
92
+ * wrong guess only weakens the confirm-dialog text, never the decision
93
+ * (the tool runs in agy's loop either way). Unknown names return null:
94
+ * read-only tools are not gated. */
95
+ export function mapNativeToShadow(name: string, args: Record<string, unknown>): ShadowMapping | null {
96
+ const a = args ?? {};
97
+ const str = (v: unknown): string => (typeof v === "string" ? v : v === undefined || v === null ? "" : String(v));
98
+ switch (name) {
99
+ case "run_command": {
100
+ const input: Record<string, unknown> = { command: str(a.CommandLine) };
101
+ if (a.Cwd !== undefined && a.Cwd !== null && a.Cwd !== "") input.cwd = str(a.Cwd);
102
+ return { shadow: "bash", input };
103
+ }
104
+ case "write_to_file":
105
+ case "create_file":
106
+ return { shadow: "write", input: { path: str(a.TargetFile), content: str(a.CodeContent) } };
107
+ case "replace_file_content":
108
+ case "edit_file":
109
+ return {
110
+ shadow: "edit",
111
+ input: {
112
+ path: str(a.TargetFile),
113
+ edits: [{ oldText: str(a.SearchText), newText: str(a.ReplacementContent) }],
114
+ },
115
+ };
116
+ case "multi_replace_file_content": {
117
+ const chunks = Array.isArray(a.ReplacementChunks) ? a.ReplacementChunks : [];
118
+ return {
119
+ shadow: "edit",
120
+ input: {
121
+ path: str(a.TargetFile),
122
+ edits: chunks.map((c) => {
123
+ const chunk = (c ?? {}) as Record<string, unknown>;
124
+ return { oldText: str(chunk.SearchText), newText: str(chunk.ReplacementContent) };
125
+ }),
126
+ },
127
+ };
128
+ }
129
+ default:
130
+ return null;
131
+ }
132
+ }
133
+
134
+ /** Options for the shadow factory. */
135
+ export interface ShadowOptions {
136
+ /** Registry lookup for the park's ticket. When set, a marker call whose
137
+ * __agyTicket is missing or unrecognized throws (deny) BEFORE the policy
138
+ * runs: a model that sets __agyGate:true itself can then never produce a
139
+ * fake-approved result, even under approvals.mode "allow". */
140
+ verifyTicket?: (ticket: string) => boolean;
141
+ }
142
+
143
+ /** Build the shadow definition for one builtin. `base` MUST be a definition
144
+ * of the real builtin - the extension passes factory twins created with
145
+ * pi's public createBashToolDefinition/createWriteToolDefinition/
146
+ * createEditToolDefinition (pi.getAllTools() returns ToolInfo, which strips
147
+ * execute, so the live definition cannot be captured). */
148
+ export function createShadowTool(base: AnyToolDefinition, policy: GatePolicy, opts: ShadowOptions = {}): AnyToolDefinition {
149
+ const execute = async (
150
+ toolCallId: string,
151
+ params: any,
152
+ signal: AbortSignal | undefined,
153
+ onUpdate: AgentToolUpdateCallback<any> | undefined,
154
+ ctx: ExtensionToolContext,
155
+ ): Promise<AgentToolResult<unknown>> => {
156
+ const p = (params ?? {}) as Record<string, unknown>;
157
+ if (p[GATE_MARKER] !== true) {
158
+ return base.execute(toolCallId, stripMarkerFields(p), signal, onUpdate, ctx);
159
+ }
160
+ const native = typeof p.__agyTool === "string" && p.__agyTool.length > 0 ? p.__agyTool : base.name;
161
+ // Ticket binding (peer review 2026-09-07): only calls the provider parked
162
+ // carry a live ticket. Anything else with the marker set was forged by
163
+ // the model (or the park is gone); fail closed without consulting the
164
+ // policy, so approvals.mode "allow" can never bless it either.
165
+ const ticket = typeof p.__agyTicket === "string" ? p.__agyTicket : "";
166
+ if (!ticket || !opts.verifyTicket?.(ticket)) {
167
+ throw new Error(
168
+ `approval gate: unrecognized or stale approval ticket; refusing to decide (${native}).`,
169
+ );
170
+ }
171
+ if (signal?.aborted) {
172
+ throw new Error(`approval gate aborted before a decision was reached (${native}).`);
173
+ }
174
+ let decision: GateDecision;
175
+ // Race the policy against the abort signal: a cancelled turn must
176
+ // unblock execute() instead of hanging on a human decision.
177
+ const aborted = new Error(`approval gate aborted before a decision was reached (${native}).`);
178
+ const abortp = new Promise<never>((_, reject) => {
179
+ signal?.addEventListener("abort", () => reject(aborted), { once: true });
180
+ });
181
+ abortp.catch(() => {}); // late rejection must not become unhandled
182
+ try {
183
+ decision = await Promise.race([Promise.resolve(policy({ tool: native, params: p, ctx })), abortp]);
184
+ } catch (err) {
185
+ if (signal?.aborted) throw aborted;
186
+ // Fail closed: a broken policy must never look like an approval.
187
+ throw new Error(`approval gate policy failed: ${err instanceof Error ? err.message : String(err)}`);
188
+ }
189
+ if (signal?.aborted) {
190
+ // Sync-abort inside the policy settles the policy promise BEFORE the
191
+ // race starts, so the rejection loses the ordering tie. Re-check.
192
+ throw aborted;
193
+ }
194
+ if (!decision.allow) {
195
+ throw new Error(decision.reason || `blocked by approval gate (${native}).`);
196
+ }
197
+ return {
198
+ content: [
199
+ {
200
+ type: "text",
201
+ text: `Approved by approval gate: ${native}. No local execution happened; the tool runs in the Antigravity agent loop.`,
202
+ },
203
+ ],
204
+ details: { gate: "allow", native },
205
+ };
206
+ };
207
+ return { ...base, parameters: withGateMarkerSchema(base.parameters), execute } as AnyToolDefinition;
208
+ }