@herbertgao/pi-extensions 2026.11.18 → 2026.11.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -3
  3. package/THIRD_PARTY_NOTICES.md +2 -23
  4. package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
  5. package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
  6. package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
  7. package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
  8. package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
  9. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
  10. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
  11. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
  12. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
  13. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
  14. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
  15. package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
  16. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
  17. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
  18. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
  19. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
  20. package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
  21. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
  22. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
  23. package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
  24. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
  25. package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
  26. package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
  27. package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
  28. package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
  29. package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
  30. package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
  31. package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
  32. package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
  33. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
  34. package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
  35. package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
  36. package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
  37. package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
  38. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
  39. package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
  40. package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
  41. package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
  42. package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
  43. package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
  44. package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
  45. package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
  46. package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
  47. package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
  48. package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
  49. package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
  50. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
  51. package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
  52. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
  53. package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
  54. package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
  55. package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
  56. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
  57. package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
  58. package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
  59. package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
  60. package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
  61. package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
  62. package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
  63. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  64. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
  65. package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
  66. package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
  67. package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
  68. package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
  69. package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
  70. package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
  71. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
  72. package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
  73. package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
  74. package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
  75. package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
  76. package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
  77. package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
  78. package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
  79. package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
  80. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
  81. package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
  82. package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
  83. package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
  84. package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
  85. package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
  86. package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
  87. package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
  88. package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
  89. package/node_modules/pi-commandcode-provider/README.md +3 -2
  90. package/node_modules/pi-commandcode-provider/index.ts +120 -13
  91. package/node_modules/pi-commandcode-provider/package.json +4 -3
  92. package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
  93. package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
  94. package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
  95. package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
  96. package/package.json +11 -14
  97. package/node_modules/pi-antigravity/README.md +0 -298
  98. package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
  99. package/node_modules/pi-antigravity/package.json +0 -87
  100. package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
  101. package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
  102. package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
  103. package/node_modules/pi-antigravity/src/client/client.ts +0 -602
  104. package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
  105. package/node_modules/pi-antigravity/src/client/index.ts +0 -2
  106. package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
  107. package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
  108. package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
  109. package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
  110. package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
  111. package/node_modules/pi-antigravity/src/image/image.ts +0 -427
  112. package/node_modules/pi-antigravity/src/image/index.ts +0 -1
  113. package/node_modules/pi-antigravity/src/image/native.ts +0 -69
  114. package/node_modules/pi-antigravity/src/index.ts +0 -547
  115. package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
  116. package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
  117. package/node_modules/pi-antigravity/src/models/index.ts +0 -3
  118. package/node_modules/pi-antigravity/src/models/models.ts +0 -647
  119. package/node_modules/pi-antigravity/src/search/index.ts +0 -1
  120. package/node_modules/pi-antigravity/src/search/search.ts +0 -967
  121. package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
  122. package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
  123. package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
  124. package/node_modules/pi-antigravity/src/types/index.ts +0 -2
  125. package/node_modules/pi-antigravity/src/types/types.ts +0 -329
  126. package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
  127. package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
  128. package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
  129. package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
  130. package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
  131. package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
  132. package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
  133. package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
  134. package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
  135. package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
  136. package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
  137. package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
  138. package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
  139. package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
  140. package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
  141. package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
  142. package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
  143. package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
  144. package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
  145. package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
  146. package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
  147. package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
  148. package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
  149. package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
  150. package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
  151. package/node_modules/pi-antigravity/tsconfig.json +0 -21
@@ -0,0 +1,325 @@
1
+ // Staging for the approval-gate hooks.json (docs/TODO.md 2.5).
2
+ //
3
+ // The agy CLI discovers `.agents/hooks.json` in its --add-dir directories
4
+ // (live-probed 2026-09-22: stream-json and interactive sessions load and
5
+ // execute PreToolUse hooks from any add-dir; print mode reads only the
6
+ // global config) and fires them before a gated tool runs (V2: deny
7
+ // honored, reason reaches the model; V3: hook TIMEOUT = soft-pass, agy
8
+ // proceeds ungated). Therefore:
9
+ // - the staged handler timeout must exceed the whole park budget with
10
+ // margin (never rely on timeout as a deny), and
11
+ // - the staged command delegates to the bundled poll script, which
12
+ // early-acks and polls the bridge for the terminal decision.
13
+ //
14
+ // ISOLATION (issue #5): the gate group is staged into the session-private
15
+ // per-pid bridge dir (bridgeMcpConfigDir()), NOT the shared workspace. Only
16
+ // this session's agy gets that dir as an extra --add-dir (driver.ts), so
17
+ // standalone IDE/CLI sessions in the workspace can never load the gate -
18
+ // neither denying their tools while pi is idle nor parking their calls
19
+ // into a live pi turn. The private file is ours alone: no merge, no
20
+ // foreign-file backup dance.
21
+ //
22
+ // Legacy: 1.6.x staged into the shared workspace `.agents/hooks.json`.
23
+ // sweepWorkspaceGateGroups() removes gate groups left there by sessions
24
+ // whose pid is dead; groups of live sessions and foreign groups are never
25
+ // touched.
26
+ //
27
+ // Run: npm test
28
+
29
+ import fs from "node:fs";
30
+ import path from "node:path";
31
+ import { bridgeMcpConfigDir } from "./mcp-server.js";
32
+
33
+ export const HOOK_GROUP = "pi-bridge-gate";
34
+
35
+ /** Group-key namespace. Each session's group is keyed per-pid
36
+ * (`pi-bridge-gate-<pid>`): the key doubles as the ownership proof for the
37
+ * legacy workspace sweep, which may only remove groups whose owning
38
+ * session is dead (a stale shared key must never strip a live session's
39
+ * gate - audit 2026-09-07). */
40
+ export const GATE_GROUP_PREFIX = "pi-bridge-gate";
41
+
42
+ /** This session's group key. */
43
+ export function gateGroupKey(pid: number = process.pid): string {
44
+ return `${GATE_GROUP_PREFIX}-${pid}`;
45
+ }
46
+
47
+ /** True if the process is running (EPERM counts: alive but not ours). */
48
+ function pidAlive(pid: number): boolean {
49
+ if (!Number.isInteger(pid) || pid <= 0) return false;
50
+ try {
51
+ process.kill(pid, 0);
52
+ return true;
53
+ } catch (e) {
54
+ return (e as NodeJS.ErrnoException).code === "EPERM";
55
+ }
56
+ }
57
+
58
+ /** Which session a gate group belongs to, parsed from the script path its
59
+ * command embeds (`.../approval-hook-<pid>.js`). The pid is the ownership
60
+ * proof: the script is per-pid (0600, written by that session). Returns
61
+ * null for groups we cannot attribute (foreign/future formats - never
62
+ * touched). */
63
+ function gateGroupPid(group: unknown): number | null {
64
+ const m = /approval-hook-(\d+)\.js/.exec(JSON.stringify(group));
65
+ return m ? Number(m[1]) : null;
66
+ }
67
+
68
+ /** agy native tools worth gating: everything that mutates the machine.
69
+ * Includes both the legacy and the agy 1.5.11+ tool families (issue #18). */
70
+ export const GATED_AGY_TOOLS =
71
+ "create_file|write_to_file|write_file|replace_file_content|multi_replace_file_content|edit_file|run_command";
72
+
73
+ /** The same list as a set, for the bridge's POST /approval validation: a
74
+ * payload for anything else is answered with a direct deny (defense in
75
+ * depth - the hooks matcher should never let one through). */
76
+ export const GATED_AGY_TOOL_SET: ReadonlySet<string> = new Set(GATED_AGY_TOOLS.split("|"));
77
+
78
+ export interface StageOptions {
79
+ /** Bridge HTTP port (the approval endpoints live on the bridge server). */
80
+ port: number;
81
+ /** Bridge shared secret (x-bridge-token). */
82
+ token: string;
83
+ /** Path to the bundled poll script (written by the caller). */
84
+ scriptPath: string;
85
+ /** Full park budget in ms; the staged hook timeout exceeds it. */
86
+ parkBudgetMs: number;
87
+ }
88
+
89
+ /** Source of the staged poll script. Written to disk by the caller (data
90
+ * dir), referenced by absolute path from the staged hooks.json. Early-acks
91
+ * via POST /approval, then polls GET /approval/<ticket> until a terminal
92
+ * decision or the deadline. Terminal: prints the JSON decision on stdout.
93
+ * Deadline hit: prints {"decision":"deny", ...} (fail closed) - agy may
94
+ * still soft-pass a timed-out hook, but a printed deny is honored (V2). */
95
+ export function hookScriptSource(opts: { port: number; token: string; deadlineMs: number }): string {
96
+ return `#!/usr/bin/env node
97
+ // Bridge approval hook (generated; do not edit). Polls the pi-antigravity-bridge.
98
+ const PORT = ${opts.port};
99
+ const TOKEN = ${JSON.stringify(opts.token)};
100
+ const DEADLINE = Date.now() + ${opts.deadlineMs};
101
+ // Per-fetch abort: a hung fetch must never outlive the park deadline. A hook
102
+ // killed by agy's staged timeout soft-passes (V3), so the script itself must
103
+ // always reach a printed deny.
104
+ const POST_TIMEOUT_MS = Math.min(10_000, ${opts.deadlineMs});
105
+ let body = "";
106
+ process.stdin.setEncoding("utf8");
107
+ for await (const chunk of process.stdin) body += chunk;
108
+ let ticket = "";
109
+ try {
110
+ const res = await fetch(\`http://127.0.0.1:\${PORT}/approval\`, {
111
+ method: "POST",
112
+ headers: { "content-type": "application/json", "x-bridge-token": TOKEN },
113
+ body,
114
+ signal: AbortSignal.timeout(POST_TIMEOUT_MS),
115
+ });
116
+ const json = await res.json();
117
+ // Ungated payloads get a terminal decision right on the POST (no park).
118
+ if (json && typeof json === "object" && typeof json.decision === "string") {
119
+ console.log(JSON.stringify(json));
120
+ process.exit(0);
121
+ }
122
+ ticket = json?.ticket ?? "";
123
+ } catch {}
124
+ if (!ticket) {
125
+ console.log(JSON.stringify({ decision: "deny", reason: "approval gate unreachable (bridge down?)" }));
126
+ process.exit(0);
127
+ }
128
+ while (Date.now() < DEADLINE) {
129
+ await new Promise((r) => setTimeout(r, 500));
130
+ try {
131
+ const res = await fetch(\`http://127.0.0.1:\${PORT}/approval/\${encodeURIComponent(ticket)}\`, {
132
+ headers: { "x-bridge-token": TOKEN },
133
+ // Bounded by the remaining park budget: an aborted poll falls through
134
+ // to the loop condition and lands on the deadline deny.
135
+ signal: AbortSignal.timeout(Math.max(1, DEADLINE - Date.now())),
136
+ });
137
+ const json = await res.json();
138
+ if (json?.status !== "pending") {
139
+ if (json && typeof json === "object" && typeof json.decision === "string") {
140
+ console.log(JSON.stringify(json));
141
+ } else {
142
+ console.log(JSON.stringify({ decision: "deny", reason: "gate returned no decision" }));
143
+ }
144
+ process.exit(0);
145
+ }
146
+ } catch {}
147
+ }
148
+ console.log(JSON.stringify({ decision: "deny", reason: "approval gate deadline exceeded" }));
149
+ `;
150
+ }
151
+
152
+ /** Hook timeout (seconds) staged for a given park budget: the budget plus a
153
+ * 60s margin, minimum 60s. V3: a timed-out hook soft-passes, so this must
154
+ * never be smaller than the human can plausibly need. */
155
+ export function stagedTimeoutSeconds(parkBudgetMs: number): number {
156
+ return Math.max(60, Math.ceil(parkBudgetMs / 1000) + 60);
157
+ }
158
+
159
+ /** Build our hooks.json group for private-dir staging. */
160
+ export function buildGateGroup(opts: StageOptions): Record<string, unknown> {
161
+ const command = `node ${JSON.stringify(opts.scriptPath)}`;
162
+ return {
163
+ enabled: true,
164
+ PreToolUse: [
165
+ {
166
+ matcher: GATED_AGY_TOOLS,
167
+ hooks: [
168
+ {
169
+ type: "command",
170
+ command,
171
+ timeout: stagedTimeoutSeconds(opts.parkBudgetMs),
172
+ },
173
+ ],
174
+ },
175
+ ],
176
+ };
177
+ }
178
+
179
+ export interface StageResult {
180
+ wrote: boolean;
181
+ /** Why nothing was written (already current, ...). */
182
+ reason?: string;
183
+ }
184
+
185
+ /** The session-private hooks.json for gate staging (beside the bridge's
186
+ * mcp_config.json in the per-pid add-dir). */
187
+ function gateHooksFile(dir: string = bridgeMcpConfigDir()): string {
188
+ return path.join(dir, ".agents", "hooks.json");
189
+ }
190
+
191
+ /** True if this session's gate hooks are currently staged in the private
192
+ * add-dir. The driver uses this to decide whether to pass the extra
193
+ * --add-dir even when the MCP config is absent. */
194
+ export function gateHooksStaged(dir: string = bridgeMcpConfigDir()): boolean {
195
+ return fs.existsSync(gateHooksFile(dir));
196
+ }
197
+
198
+ /** Stage the gate group into the session-private per-pid dir:
199
+ * <bridgeMcpConfigDir()>/.agents/hooks.json. The dir (and everything in
200
+ * it) belongs to this pid alone, so the write is a plain atomic replace -
201
+ * no merge, no foreign-file guards. */
202
+ export function stageGateHooks(dir: string, opts: StageOptions): StageResult {
203
+ const file = gateHooksFile(dir);
204
+ const next = JSON.stringify({ [gateGroupKey()]: buildGateGroup(opts) }, null, 2) + "\n";
205
+ try {
206
+ if (fs.readFileSync(file, "utf8") === next) return { wrote: false, reason: "already staged" };
207
+ } catch {
208
+ /* absent or unreadable: write */
209
+ }
210
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
211
+ const tmp = `${file}.${process.pid}.tmp`;
212
+ try {
213
+ fs.writeFileSync(tmp, next, { mode: 0o600 });
214
+ fs.renameSync(tmp, file);
215
+ } catch (err) {
216
+ try {
217
+ fs.unlinkSync(tmp);
218
+ } catch {
219
+ /* nothing */
220
+ }
221
+ throw err;
222
+ }
223
+ return { wrote: true };
224
+ }
225
+
226
+ /** Deliver this session's gate group into a staged ACP home's
227
+ * config/hooks.json. The staged home is private per connection (stageAgyHome),
228
+ * so foreign groups - the user's global hooks, copied in by stageAgyHome -
229
+ * are preserved and only this pid's group is added. An unparsable existing
230
+ * file is gate-only overwritten: agy could not have read it either. No-op
231
+ * only when the per-pid gate file is ABSENT (gate off at load); a staged
232
+ * file that exists but cannot be read, parsed, or does not carry this
233
+ * session's usable group throws, because running the spawn ungated while
234
+ * the gate is on would fail open (issue #18).
235
+ * mergeGateGroupIntoAcpHome's delivery is probed live on agy 1.5.12
236
+ * (scripts/probe-acp-hooks.mjs). */
237
+ export function mergeGateGroupIntoAcpHome(stagedHome: string, sourceDir: string = bridgeMcpConfigDir()): StageResult {
238
+ let staged: Record<string, unknown>;
239
+ try {
240
+ staged = JSON.parse(fs.readFileSync(gateHooksFile(sourceDir), "utf8")) as Record<string, unknown>;
241
+ } catch (err) {
242
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return { wrote: false, reason: "no staged gate" };
243
+ throw err;
244
+ }
245
+ // The source file is session-private (per-pid dir), so a parsable file
246
+ // without this session's usable group means something rewrote it between
247
+ // staging and merge - spawning ungated then would fail open.
248
+ const group: unknown = staged[gateGroupKey()];
249
+ if (!group || typeof group !== "object") {
250
+ throw new Error(`staged approval-gate file has no usable group for this session (${gateGroupKey()}); failing closed`);
251
+ }
252
+ const target = path.join(stagedHome, "config", "hooks.json");
253
+ let merged: Record<string, unknown> = {};
254
+ try {
255
+ const existing = JSON.parse(fs.readFileSync(target, "utf8")) as unknown;
256
+ if (existing && typeof existing === "object" && !Array.isArray(existing)) {
257
+ merged = existing as Record<string, unknown>;
258
+ }
259
+ } catch {
260
+ /* absent or unparsable: the merge result is gate-only */
261
+ }
262
+ merged[gateGroupKey()] = group;
263
+ const next = JSON.stringify(merged, null, 2) + "\n";
264
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
265
+ const tmp = `${target}.${process.pid}.tmp`;
266
+ try {
267
+ fs.writeFileSync(tmp, next, { mode: 0o600 });
268
+ fs.renameSync(tmp, target);
269
+ } catch (err) {
270
+ try {
271
+ fs.unlinkSync(tmp);
272
+ } catch {
273
+ /* nothing */
274
+ }
275
+ throw err;
276
+ }
277
+ return { wrote: true };
278
+ }
279
+
280
+ /** Remove the private gate hooks file. The rest of the per-pid dir (the MCP
281
+ * config) is managed by the bridge server lifecycle and stays until close. */
282
+ export function removeGateHooks(dir: string = bridgeMcpConfigDir()): StageResult {
283
+ const file = gateHooksFile(dir);
284
+ if (!fs.existsSync(file)) return { wrote: false, reason: "no hooks.json" };
285
+ try {
286
+ fs.rmSync(file, { force: true });
287
+ return { wrote: true };
288
+ } catch {
289
+ return { wrote: false, reason: "remove failed" };
290
+ }
291
+ }
292
+
293
+ /** Legacy cleanup (issue #5): remove gate groups that 1.6.x staged into the
294
+ * SHARED workspace `.agents/hooks.json` when their owning session is dead
295
+ * (its bridge is gone; the hook would fail closed forever). Live sessions'
296
+ * groups and groups we cannot attribute are never touched; foreign groups
297
+ * and foreign files are never touched. Returns the number of swept groups. */
298
+ export function sweepWorkspaceGateGroups(workspaceDir: string): number {
299
+ const file = path.join(workspaceDir, ".agents", "hooks.json");
300
+ let current: Record<string, unknown>;
301
+ try {
302
+ if (fs.lstatSync(file).isSymbolicLink()) return 0;
303
+ const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
304
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return 0;
305
+ current = parsed as Record<string, unknown>;
306
+ } catch {
307
+ return 0;
308
+ }
309
+ let swept = 0;
310
+ for (const key of Object.keys(current)) {
311
+ const isGateGroup = key === GATE_GROUP_PREFIX || key.startsWith(`${GATE_GROUP_PREFIX}-`);
312
+ if (!isGateGroup) continue;
313
+ const pid = gateGroupPid(current[key]);
314
+ if (pid === null || pidAlive(pid)) continue;
315
+ delete current[key];
316
+ swept += 1;
317
+ }
318
+ if (swept === 0) return 0;
319
+ try {
320
+ fs.writeFileSync(file, JSON.stringify(current, null, 2) + "\n");
321
+ } catch {
322
+ return 0;
323
+ }
324
+ return swept;
325
+ }
@@ -0,0 +1,88 @@
1
+ // /agy artifacts overlay: SelectList over one conversation's artifacts.
2
+ //
3
+ // UI mirrors the engine picker (tui.md "Pattern 1"): SelectList framed by
4
+ // DynamicBorder inside pi's native overlay. Read-only on purpose: enter
5
+ // opens the selected file with the OS default handler, r rescans (the list
6
+ // is always a fresh scan), esc closes. No delete keys — agy's files are
7
+ // agy's to manage.
8
+
9
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
10
+ import { DynamicBorder } from "@earendil-works/pi-coding-agent";
11
+ import { Container, type SelectItem, SelectList, Spacer, Text } from "@earendil-works/pi-tui";
12
+ import { dialogBlocked } from "@estebanforge/pi-tui-dialogs";
13
+ import type { AgyArtifact } from "./artifacts.js";
14
+
15
+ export type ArtifactsBrowserAction =
16
+ | { type: "open"; artifact: AgyArtifact }
17
+ | { type: "rescan" }
18
+ | { type: "close" };
19
+
20
+ function humanBytes(n: number): string {
21
+ if (n < 1024) return `${n}B`;
22
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;
23
+ return `${(n / (1024 * 1024)).toFixed(1)}MB`;
24
+ }
25
+
26
+ export function artifactItems(artifacts: AgyArtifact[]): SelectItem[] {
27
+ return artifacts.map((a, i) => {
28
+ const when = new Date(a.modifiedMs);
29
+ const stamp = `${when.getFullYear()}-${String(when.getMonth() + 1).padStart(2, "0")}-${String(when.getDate()).padStart(2, "0")} ${String(when.getHours()).padStart(2, "0")}:${String(when.getMinutes()).padStart(2, "0")}`;
30
+ return {
31
+ value: String(i),
32
+ label: a.name,
33
+ description: `${a.kind} · ${a.mediaType} · ${humanBytes(a.bytes)} · ${stamp}`,
34
+ };
35
+ });
36
+ }
37
+
38
+ /** Render the overlay. Resolves with what the user asked for: open (with the
39
+ * selected artifact), rescan, or close. */
40
+ export async function showArtifactsBrowser(
41
+ ctx: ExtensionUIContext,
42
+ artifacts: AgyArtifact[],
43
+ ): Promise<ArtifactsBrowserAction> {
44
+ const items = artifactItems(artifacts);
45
+ return ctx.custom<ArtifactsBrowserAction>((tui, theme, _keybindings, done) => {
46
+ const container = new Container();
47
+ container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
48
+ container.addChild(
49
+ new Text(theme.fg("accent", theme.bold(`Antigravity artifacts (${artifacts.length})`)), 1, 0),
50
+ );
51
+ container.addChild(new Spacer(1));
52
+
53
+ const list = new SelectList(items, Math.min(items.length, 12), {
54
+ selectedPrefix: (t: string) => theme.fg("accent", t),
55
+ selectedText: (t: string) => theme.fg("accent", t),
56
+ description: (t: string) => theme.fg("muted", t),
57
+ scrollInfo: (t: string) => theme.fg("dim", t),
58
+ noMatch: (t: string) => theme.fg("warning", t),
59
+ });
60
+ list.onSelect = (item) => done({ type: "open", artifact: artifacts[Number(item.value)] });
61
+ list.onCancel = () => done({ type: "close" });
62
+ container.addChild(list);
63
+
64
+ container.addChild(new Spacer(1));
65
+ container.addChild(
66
+ new Text(theme.fg("dim", "↑↓ navigate · enter open · r rescan · esc close"), 1, 0),
67
+ );
68
+ container.addChild(new DynamicBorder((s: string) => theme.fg("accent", s)));
69
+
70
+ return {
71
+ render: (width: number) => container.render(width),
72
+ invalidate: () => container.invalidate(),
73
+ handleInput: (data: string) => {
74
+ // r rescan; enter opens (via onSelect), esc cancels (via onCancel).
75
+ if (data.trim().toLowerCase() === "r") {
76
+ done({ type: "rescan" });
77
+ return;
78
+ }
79
+ list.handleInput(data);
80
+ tui.requestRender();
81
+ },
82
+ };
83
+ }, {
84
+ overlay: true,
85
+ overlayOptions: { anchor: "center" as const, width: 84, maxHeight: "85%" as const, margin: 1 },
86
+ blocked: dialogBlocked(`Antigravity artifacts (${artifacts.length})`),
87
+ });
88
+ }
@@ -0,0 +1,144 @@
1
+ // Read-only artifact scan over one agy conversation's brain dir.
2
+ //
3
+ // agy drops files in three places under brain/<conversationId>/: the
4
+ // conversation root itself, .tempmediaStorage/ (media agy generated), and
5
+ // .user_uploaded/ (files the user handed it). Nothing else surfaces them,
6
+ // so this module lists them for pi (live-probed 2026-09-24: both trees
7
+ // exist per engine; media dirs are created on demand and may be absent).
8
+ //
9
+ // Read-only by design: list and open, never delete. Each entry is
10
+ // realpath'd and containment-checked canonical-to-canonical, which defeats
11
+ // symlinks pointing outside the conversation root and stays correct when
12
+ // the conversation dir itself is reached through a symlinked ancestor
13
+ // (macOS /var -> /private/var, symlinked homes). A file could still be
14
+ // swapped for a symlink between listing and a later `open` — the OS opener
15
+ // would follow it; that is outside this module's guarantee and acceptable
16
+ // for a single-user, own-home tool.
17
+
18
+ import { readdir, realpath, stat } from "node:fs/promises";
19
+ import path from "node:path";
20
+
21
+ export type AgyArtifactKind = "conversation" | "generated" | "uploaded";
22
+ export type AgyArtifactMediaType =
23
+ | "image"
24
+ | "audio"
25
+ | "video"
26
+ | "pdf"
27
+ | "markdown"
28
+ | "text"
29
+ | "other";
30
+
31
+ export interface AgyArtifact {
32
+ name: string;
33
+ absolutePath: string;
34
+ kind: AgyArtifactKind;
35
+ mediaType: AgyArtifactMediaType;
36
+ bytes: number;
37
+ modifiedMs: number;
38
+ }
39
+
40
+ const EXT_TO_MEDIA: Record<string, AgyArtifactMediaType> = {
41
+ png: "image",
42
+ jpg: "image",
43
+ jpeg: "image",
44
+ gif: "image",
45
+ webp: "image",
46
+ svg: "image",
47
+ bmp: "image",
48
+ mp3: "audio",
49
+ wav: "audio",
50
+ ogg: "audio",
51
+ m4a: "audio",
52
+ flac: "audio",
53
+ mp4: "video",
54
+ mov: "video",
55
+ webm: "video",
56
+ mkv: "video",
57
+ pdf: "pdf",
58
+ md: "markdown",
59
+ markdown: "markdown",
60
+ txt: "text",
61
+ csv: "text",
62
+ json: "text",
63
+ };
64
+
65
+ function mediaTypeFor(name: string): AgyArtifactMediaType {
66
+ return EXT_TO_MEDIA[path.extname(name).slice(1).toLowerCase()] ?? "other";
67
+ }
68
+
69
+ /** Files that are agy bookkeeping, not user-facing artifacts. */
70
+ function isSkippedName(name: string): boolean {
71
+ return name.startsWith(".") || name.endsWith(".metadata.json");
72
+ }
73
+
74
+ const SCAN_ROOTS: Array<{ sub: string | null; kind: AgyArtifactKind }> = [
75
+ { sub: null, kind: "conversation" },
76
+ { sub: ".tempmediaStorage", kind: "generated" },
77
+ { sub: ".user_uploaded", kind: "uploaded" },
78
+ ];
79
+
80
+ /** List artifacts under one conversation dir. Missing subdirs are normal
81
+ * (created on demand) and skip silently; a missing conversation dir
82
+ * returns []. Newest first. */
83
+ export async function listAgyArtifacts(conversationDir: string): Promise<AgyArtifact[]> {
84
+ // Canonicalize ONCE and derive everything from the canonical root: a
85
+ // raw-vs-canonical containment check silently rejects every entry when
86
+ // any ancestor is a symlink (the relative prefix comparison crosses
87
+ // resolved/unresolved segments and yields a bogus "..").
88
+ let root: string;
89
+ try {
90
+ root = await realpath(conversationDir);
91
+ } catch {
92
+ return [];
93
+ }
94
+ const byPath = new Map<string, AgyArtifact>();
95
+ for (const { sub, kind } of SCAN_ROOTS) {
96
+ const dir = sub === null ? root : path.join(root, sub);
97
+ let entries;
98
+ try {
99
+ entries = await readdir(dir, { withFileTypes: true });
100
+ } catch {
101
+ continue;
102
+ }
103
+ for (const entry of entries) {
104
+ if (!entry.isFile()) continue; // Dirent type: symlinks excluded here
105
+ if (isSkippedName(entry.name)) continue;
106
+ // Re-resolve per entry and re-check containment on the canonical
107
+ // path: catches anything swapped in between readdir and use.
108
+ let canonical: string;
109
+ let stats;
110
+ try {
111
+ canonical = await realpath(path.join(dir, entry.name));
112
+ if (!containedIn(root, canonical)) continue;
113
+ stats = await stat(canonical);
114
+ } catch {
115
+ continue;
116
+ }
117
+ if (!stats.isFile()) continue;
118
+ const key = canonical;
119
+ if (byPath.has(key)) continue;
120
+ byPath.set(key, {
121
+ name: entry.name,
122
+ absolutePath: canonical,
123
+ kind,
124
+ mediaType: mediaTypeFor(entry.name),
125
+ bytes: stats.size,
126
+ modifiedMs: stats.mtimeMs,
127
+ });
128
+ }
129
+ }
130
+ return [...byPath.values()].sort((a, b) => b.modifiedMs - a.modifiedMs);
131
+ }
132
+
133
+ function containedIn(root: string, candidate: string): boolean {
134
+ const rel = path.relative(root, candidate);
135
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
136
+ }
137
+
138
+ /** OS open command for the user's default handler. Undefined on unknown
139
+ * platforms (caller renders a message instead of spawning blind). */
140
+ export function artifactOpenCommand(): { cmd: string } | undefined {
141
+ if (process.platform === "darwin") return { cmd: "open" };
142
+ if (process.platform === "linux") return { cmd: "xdg-open" };
143
+ return undefined;
144
+ }