@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.
- package/CHANGELOG.md +902 -0
- package/LICENSE +21 -0
- package/README.md +235 -3
- package/extensions/index.ts +1993 -0
- package/package.json +71 -6
- package/src/acp/connection.ts +623 -0
- package/src/acp/driver.ts +953 -0
- package/src/acp/events.ts +331 -0
- package/src/acp/home.ts +238 -0
- package/src/acp/jsonrpc.ts +232 -0
- package/src/acp/setup.ts +107 -0
- package/src/acp/usage-estimate.ts +61 -0
- package/src/agents.ts +64 -0
- package/src/agy-install.ts +85 -0
- package/src/agy-paths.ts +30 -0
- package/src/agy-setup.ts +72 -0
- package/src/agy-version.ts +283 -0
- package/src/approval-detect.ts +146 -0
- package/src/approval-gate.ts +208 -0
- package/src/approval-hook.ts +270 -0
- package/src/artifacts-ui.ts +88 -0
- package/src/artifacts.ts +144 -0
- package/src/ask-tool.ts +1222 -0
- package/src/background-watch.ts +225 -0
- package/src/bridge-catalog.ts +27 -0
- package/src/config.ts +485 -0
- package/src/daily-log.ts +196 -0
- package/src/dialog-lock.ts +48 -0
- package/src/diff-render.ts +205 -0
- package/src/driver-types.ts +172 -0
- package/src/driver.ts +907 -0
- package/src/engine-picker.ts +160 -0
- package/src/frame-guard.ts +38 -0
- package/src/mcp-registration.ts +382 -0
- package/src/mcp-server.ts +620 -0
- package/src/models.ts +407 -0
- package/src/native-tools.ts +104 -0
- package/src/parked-turn.ts +125 -0
- package/src/patch-cleanup.ts +519 -0
- package/src/poll-fold.ts +55 -0
- package/src/prompt-images.ts +92 -0
- package/src/provider.ts +2066 -0
- package/src/queued-messages.ts +152 -0
- package/src/redact.ts +27 -0
- package/src/sessions.ts +185 -0
- package/src/skills.ts +192 -0
- package/src/stream-events.ts +122 -0
- package/src/stream-sanitizer.ts +180 -0
- package/src/subagent-roster.ts +245 -0
- package/src/sysprompt-agent.ts +163 -0
- package/src/tasks-ui.ts +90 -0
- package/src/tasks.ts +174 -0
- package/src/usage.ts +174 -0
- package/src/web-tools.ts +320 -0
|
@@ -0,0 +1,270 @@
|
|
|
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
|
+
export const GATED_AGY_TOOLS =
|
|
70
|
+
"create_file|write_to_file|replace_file_content|multi_replace_file_content|edit_file|run_command";
|
|
71
|
+
|
|
72
|
+
/** The same list as a set, for the bridge's POST /approval validation: a
|
|
73
|
+
* payload for anything else is answered with a direct deny (defense in
|
|
74
|
+
* depth - the hooks matcher should never let one through). */
|
|
75
|
+
export const GATED_AGY_TOOL_SET: ReadonlySet<string> = new Set(GATED_AGY_TOOLS.split("|"));
|
|
76
|
+
|
|
77
|
+
export interface StageOptions {
|
|
78
|
+
/** Bridge HTTP port (the approval endpoints live on the bridge server). */
|
|
79
|
+
port: number;
|
|
80
|
+
/** Bridge shared secret (x-bridge-token). */
|
|
81
|
+
token: string;
|
|
82
|
+
/** Path to the bundled poll script (written by the caller). */
|
|
83
|
+
scriptPath: string;
|
|
84
|
+
/** Full park budget in ms; the staged hook timeout exceeds it. */
|
|
85
|
+
parkBudgetMs: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Source of the staged poll script. Written to disk by the caller (data
|
|
89
|
+
* dir), referenced by absolute path from the staged hooks.json. Early-acks
|
|
90
|
+
* via POST /approval, then polls GET /approval/<ticket> until a terminal
|
|
91
|
+
* decision or the deadline. Terminal: prints the JSON decision on stdout.
|
|
92
|
+
* Deadline hit: prints {"decision":"deny", ...} (fail closed) - agy may
|
|
93
|
+
* still soft-pass a timed-out hook, but a printed deny is honored (V2). */
|
|
94
|
+
export function hookScriptSource(opts: { port: number; token: string; deadlineMs: number }): string {
|
|
95
|
+
return `#!/usr/bin/env node
|
|
96
|
+
// Bridge approval hook (generated; do not edit). Polls the pi-antigravity-bridge.
|
|
97
|
+
const PORT = ${opts.port};
|
|
98
|
+
const TOKEN = ${JSON.stringify(opts.token)};
|
|
99
|
+
const DEADLINE = Date.now() + ${opts.deadlineMs};
|
|
100
|
+
// Per-fetch abort: a hung fetch must never outlive the park deadline. A hook
|
|
101
|
+
// killed by agy's staged timeout soft-passes (V3), so the script itself must
|
|
102
|
+
// always reach a printed deny.
|
|
103
|
+
const POST_TIMEOUT_MS = Math.min(10_000, ${opts.deadlineMs});
|
|
104
|
+
let body = "";
|
|
105
|
+
process.stdin.setEncoding("utf8");
|
|
106
|
+
for await (const chunk of process.stdin) body += chunk;
|
|
107
|
+
let ticket = "";
|
|
108
|
+
try {
|
|
109
|
+
const res = await fetch(\`http://127.0.0.1:\${PORT}/approval\`, {
|
|
110
|
+
method: "POST",
|
|
111
|
+
headers: { "content-type": "application/json", "x-bridge-token": TOKEN },
|
|
112
|
+
body,
|
|
113
|
+
signal: AbortSignal.timeout(POST_TIMEOUT_MS),
|
|
114
|
+
});
|
|
115
|
+
const json = await res.json();
|
|
116
|
+
// Ungated payloads get a terminal decision right on the POST (no park).
|
|
117
|
+
if (json && typeof json === "object" && typeof json.decision === "string") {
|
|
118
|
+
console.log(JSON.stringify(json));
|
|
119
|
+
process.exit(0);
|
|
120
|
+
}
|
|
121
|
+
ticket = json?.ticket ?? "";
|
|
122
|
+
} catch {}
|
|
123
|
+
if (!ticket) {
|
|
124
|
+
console.log(JSON.stringify({ decision: "deny", reason: "approval gate unreachable (bridge down?)" }));
|
|
125
|
+
process.exit(0);
|
|
126
|
+
}
|
|
127
|
+
while (Date.now() < DEADLINE) {
|
|
128
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
129
|
+
try {
|
|
130
|
+
const res = await fetch(\`http://127.0.0.1:\${PORT}/approval/\${encodeURIComponent(ticket)}\`, {
|
|
131
|
+
headers: { "x-bridge-token": TOKEN },
|
|
132
|
+
// Bounded by the remaining park budget: an aborted poll falls through
|
|
133
|
+
// to the loop condition and lands on the deadline deny.
|
|
134
|
+
signal: AbortSignal.timeout(Math.max(1, DEADLINE - Date.now())),
|
|
135
|
+
});
|
|
136
|
+
const json = await res.json();
|
|
137
|
+
if (json?.status !== "pending") {
|
|
138
|
+
if (json && typeof json === "object" && typeof json.decision === "string") {
|
|
139
|
+
console.log(JSON.stringify(json));
|
|
140
|
+
} else {
|
|
141
|
+
console.log(JSON.stringify({ decision: "deny", reason: "gate returned no decision" }));
|
|
142
|
+
}
|
|
143
|
+
process.exit(0);
|
|
144
|
+
}
|
|
145
|
+
} catch {}
|
|
146
|
+
}
|
|
147
|
+
console.log(JSON.stringify({ decision: "deny", reason: "approval gate deadline exceeded" }));
|
|
148
|
+
`;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Hook timeout (seconds) staged for a given park budget: the budget plus a
|
|
152
|
+
* 60s margin, minimum 60s. V3: a timed-out hook soft-passes, so this must
|
|
153
|
+
* never be smaller than the human can plausibly need. */
|
|
154
|
+
export function stagedTimeoutSeconds(parkBudgetMs: number): number {
|
|
155
|
+
return Math.max(60, Math.ceil(parkBudgetMs / 1000) + 60);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Build our hooks.json group for private-dir staging. */
|
|
159
|
+
export function buildGateGroup(opts: StageOptions): Record<string, unknown> {
|
|
160
|
+
const command = `node ${JSON.stringify(opts.scriptPath)}`;
|
|
161
|
+
return {
|
|
162
|
+
enabled: true,
|
|
163
|
+
PreToolUse: [
|
|
164
|
+
{
|
|
165
|
+
matcher: GATED_AGY_TOOLS,
|
|
166
|
+
hooks: [
|
|
167
|
+
{
|
|
168
|
+
type: "command",
|
|
169
|
+
command,
|
|
170
|
+
timeout: stagedTimeoutSeconds(opts.parkBudgetMs),
|
|
171
|
+
},
|
|
172
|
+
],
|
|
173
|
+
},
|
|
174
|
+
],
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export interface StageResult {
|
|
179
|
+
wrote: boolean;
|
|
180
|
+
/** Why nothing was written (already current, ...). */
|
|
181
|
+
reason?: string;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The session-private hooks.json for gate staging (beside the bridge's
|
|
185
|
+
* mcp_config.json in the per-pid add-dir). */
|
|
186
|
+
function gateHooksFile(dir: string = bridgeMcpConfigDir()): string {
|
|
187
|
+
return path.join(dir, ".agents", "hooks.json");
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** True if this session's gate hooks are currently staged in the private
|
|
191
|
+
* add-dir. The driver uses this to decide whether to pass the extra
|
|
192
|
+
* --add-dir even when the MCP config is absent. */
|
|
193
|
+
export function gateHooksStaged(dir: string = bridgeMcpConfigDir()): boolean {
|
|
194
|
+
return fs.existsSync(gateHooksFile(dir));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Stage the gate group into the session-private per-pid dir:
|
|
198
|
+
* <bridgeMcpConfigDir()>/.agents/hooks.json. The dir (and everything in
|
|
199
|
+
* it) belongs to this pid alone, so the write is a plain atomic replace -
|
|
200
|
+
* no merge, no foreign-file guards. */
|
|
201
|
+
export function stageGateHooks(dir: string, opts: StageOptions): StageResult {
|
|
202
|
+
const file = gateHooksFile(dir);
|
|
203
|
+
const next = JSON.stringify({ [gateGroupKey()]: buildGateGroup(opts) }, null, 2) + "\n";
|
|
204
|
+
try {
|
|
205
|
+
if (fs.readFileSync(file, "utf8") === next) return { wrote: false, reason: "already staged" };
|
|
206
|
+
} catch {
|
|
207
|
+
/* absent or unreadable: write */
|
|
208
|
+
}
|
|
209
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
210
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
211
|
+
try {
|
|
212
|
+
fs.writeFileSync(tmp, next, { mode: 0o600 });
|
|
213
|
+
fs.renameSync(tmp, file);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
try {
|
|
216
|
+
fs.unlinkSync(tmp);
|
|
217
|
+
} catch {
|
|
218
|
+
/* nothing */
|
|
219
|
+
}
|
|
220
|
+
throw err;
|
|
221
|
+
}
|
|
222
|
+
return { wrote: true };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Remove the private gate hooks file. The rest of the per-pid dir (the MCP
|
|
226
|
+
* config) is managed by the bridge server lifecycle and stays until close. */
|
|
227
|
+
export function removeGateHooks(dir: string = bridgeMcpConfigDir()): StageResult {
|
|
228
|
+
const file = gateHooksFile(dir);
|
|
229
|
+
if (!fs.existsSync(file)) return { wrote: false, reason: "no hooks.json" };
|
|
230
|
+
try {
|
|
231
|
+
fs.rmSync(file, { force: true });
|
|
232
|
+
return { wrote: true };
|
|
233
|
+
} catch {
|
|
234
|
+
return { wrote: false, reason: "remove failed" };
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Legacy cleanup (issue #5): remove gate groups that 1.6.x staged into the
|
|
239
|
+
* SHARED workspace `.agents/hooks.json` when their owning session is dead
|
|
240
|
+
* (its bridge is gone; the hook would fail closed forever). Live sessions'
|
|
241
|
+
* groups and groups we cannot attribute are never touched; foreign groups
|
|
242
|
+
* and foreign files are never touched. Returns the number of swept groups. */
|
|
243
|
+
export function sweepWorkspaceGateGroups(workspaceDir: string): number {
|
|
244
|
+
const file = path.join(workspaceDir, ".agents", "hooks.json");
|
|
245
|
+
let current: Record<string, unknown>;
|
|
246
|
+
try {
|
|
247
|
+
if (fs.lstatSync(file).isSymbolicLink()) return 0;
|
|
248
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
249
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return 0;
|
|
250
|
+
current = parsed as Record<string, unknown>;
|
|
251
|
+
} catch {
|
|
252
|
+
return 0;
|
|
253
|
+
}
|
|
254
|
+
let swept = 0;
|
|
255
|
+
for (const key of Object.keys(current)) {
|
|
256
|
+
const isGateGroup = key === GATE_GROUP_PREFIX || key.startsWith(`${GATE_GROUP_PREFIX}-`);
|
|
257
|
+
if (!isGateGroup) continue;
|
|
258
|
+
const pid = gateGroupPid(current[key]);
|
|
259
|
+
if (pid === null || pidAlive(pid)) continue;
|
|
260
|
+
delete current[key];
|
|
261
|
+
swept += 1;
|
|
262
|
+
}
|
|
263
|
+
if (swept === 0) return 0;
|
|
264
|
+
try {
|
|
265
|
+
fs.writeFileSync(file, JSON.stringify(current, null, 2) + "\n");
|
|
266
|
+
} catch {
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
return swept;
|
|
270
|
+
}
|
|
@@ -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
|
+
}
|
package/src/artifacts.ts
ADDED
|
@@ -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
|
+
}
|