@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,331 @@
|
|
|
1
|
+
// ACP `session/update` payload → DriverActivity mapping + stopReason mapping.
|
|
2
|
+
//
|
|
3
|
+
// Pure functions, no I/O: unit-tested against the captured probe transcripts
|
|
4
|
+
// (probe-logs/acp-traffic-run5.jsonl, run6-restart-load-tools.jsonl).
|
|
5
|
+
//
|
|
6
|
+
// Shapes verified against native agy ACP and captured legacy frames:
|
|
7
|
+
// session/update params = { sessionId, update: { sessionUpdate: <discriminator>, ... } }
|
|
8
|
+
// - agent_message_chunk { content: { type: "text", text } } (pure deltas)
|
|
9
|
+
// - agent_thought_chunk { content: { type: "text", text } } (thought TEXT)
|
|
10
|
+
// - user_message_chunk { content: { type: "text", text } } (load replay only)
|
|
11
|
+
// - tool_call { toolCallId, title, kind, status, content?, locations?, rawInput? }
|
|
12
|
+
// - tool_call_update { toolCallId, status: completed|failed, rawOutput? }
|
|
13
|
+
// - plan { entries: [...] }
|
|
14
|
+
// - available_commands_update { availableCommands: [...] }
|
|
15
|
+
// Exact turn usage is read from PromptResponse by the connection.
|
|
16
|
+
|
|
17
|
+
import { StreamSanitizer, sanitizeSystemMessage } from "../stream-sanitizer.js";
|
|
18
|
+
|
|
19
|
+
export { StreamSanitizer, sanitizeSystemMessage };
|
|
20
|
+
|
|
21
|
+
/** Map one `update` object to a driver-level event, or null when the update
|
|
22
|
+
* carries nothing the driver consumes (plan/commands are doctor/phase-2
|
|
23
|
+
* material; user_message_chunk is load replay and must never reach pi as
|
|
24
|
+
* live text). */
|
|
25
|
+
/** Native edit diff carried in tool_call content[] (run 6: edits arrive AS
|
|
26
|
+
* DIFFS: {type:"diff", path, newText, optional oldText}). The provider
|
|
27
|
+
* formats it in memory — no git subprocess needed on the ACP engine. */
|
|
28
|
+
export interface AcpEditDiff {
|
|
29
|
+
path: string;
|
|
30
|
+
oldText?: string;
|
|
31
|
+
newText: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type MappedUpdate =
|
|
35
|
+
| { kind: "text"; delta: string }
|
|
36
|
+
| { kind: "thought"; delta: string }
|
|
37
|
+
| { kind: "usage"; used: number }
|
|
38
|
+
| { kind: "tool_start"; toolCallId: string; name: string; args: Record<string, unknown>; diff?: AcpEditDiff; mcpServer?: string }
|
|
39
|
+
| { kind: "tool_done"; toolCallId: string; output?: string; diff?: AcpEditDiff; mcpServer?: string }
|
|
40
|
+
| { kind: "tool_error"; toolCallId: string; message: string; mcpServer?: string }
|
|
41
|
+
| { kind: "replay_user" }
|
|
42
|
+
| null;
|
|
43
|
+
|
|
44
|
+
export function mapUpdate(update: unknown): MappedUpdate {
|
|
45
|
+
if (typeof update !== "object" || update === null) return null;
|
|
46
|
+
const u = update as Record<string, unknown>;
|
|
47
|
+
const kind = u.sessionUpdate;
|
|
48
|
+
if (typeof kind !== "string") return null;
|
|
49
|
+
switch (kind) {
|
|
50
|
+
case "agent_message_chunk":
|
|
51
|
+
return { kind: "text", delta: chunkText(u.content) };
|
|
52
|
+
case "agent_thought_chunk":
|
|
53
|
+
return { kind: "thought", delta: chunkText(u.content) };
|
|
54
|
+
case "user_message_chunk":
|
|
55
|
+
return { kind: "replay_user" };
|
|
56
|
+
case "usage_update": {
|
|
57
|
+
// Context-window occupancy after one inference. Absent on native agy
|
|
58
|
+
// 1.5.4 (probe 2026-11-10); other ACP runtimes send it per inference.
|
|
59
|
+
const used = u.used;
|
|
60
|
+
return typeof used === "number" && Number.isSafeInteger(used) && used > 0
|
|
61
|
+
? { kind: "usage", used }
|
|
62
|
+
: null;
|
|
63
|
+
}
|
|
64
|
+
case "tool_call": {
|
|
65
|
+
const id = stringField(u.toolCallId);
|
|
66
|
+
if (!id) return null;
|
|
67
|
+
const nativeMcp = nativeMcpTool(u);
|
|
68
|
+
const metaName = metaToolName(u._meta);
|
|
69
|
+
const rawArgs = rawArguments(u.rawInput);
|
|
70
|
+
const resolvedName = metaName ?? nativeMcp?.name ?? stringField(u.name) ?? toolName(u.title, u.kind);
|
|
71
|
+
let name = resolvedName;
|
|
72
|
+
let args = rawArgs;
|
|
73
|
+
let mcpServer = stringField(recordField(recordField(u._meta).mcp).server) ?? nativeMcp?.server;
|
|
74
|
+
// Native agy also invokes MCP tools via the generic `call_mcp_tool`
|
|
75
|
+
// dispatcher ({ ServerName, ToolName, Arguments }). Unwrap only our
|
|
76
|
+
// known pi-bridge / pi-bridge-<pid> server so Pi UI skips duplicate
|
|
77
|
+
// native cards without mislabeling foreign MCP servers or other tools.
|
|
78
|
+
if (!mcpServer && (resolvedName === "call_mcp_tool" || stringField(u.title) === "call_mcp_tool")) {
|
|
79
|
+
const server = stringField(rawArgs.ServerName);
|
|
80
|
+
const tool = stringField(rawArgs.ToolName);
|
|
81
|
+
if (server && /^pi-bridge(?:-\d+)?$/.test(server) && tool) {
|
|
82
|
+
name = tool;
|
|
83
|
+
mcpServer = server;
|
|
84
|
+
args = recordField(rawArgs.Arguments);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
kind: "tool_start",
|
|
89
|
+
toolCallId: id,
|
|
90
|
+
name,
|
|
91
|
+
args,
|
|
92
|
+
mcpServer,
|
|
93
|
+
// Edits carry their native diff HERE, on the pending tool_call
|
|
94
|
+
// frame (run 6:10) — the completed update carries only display
|
|
95
|
+
// text. contentDiff on the update stays as a future-build
|
|
96
|
+
// fallback.
|
|
97
|
+
diff: contentDiff(u.content),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
case "tool_call_update": {
|
|
101
|
+
const id = stringField(u.toolCallId);
|
|
102
|
+
if (!id) return null;
|
|
103
|
+
if (u.status === "failed") {
|
|
104
|
+
// Legacy approved-echo: after an allow, the APPROVED call
|
|
105
|
+
// id reports failed with this sentinel while the real work runs
|
|
106
|
+
// under a different id that reports its own lifecycle. Track
|
|
107
|
+
// effects, not ids: drop the echo instead of rendering a bogus
|
|
108
|
+
// failure next to a successful edit.
|
|
109
|
+
const raw = stringField(u.rawOutput);
|
|
110
|
+
if (raw?.includes("approved but never executed")) return null;
|
|
111
|
+
const mcpServer = stringField(recordField(recordField(u._meta).mcp).server) ?? nativeMcpTool(u)?.server;
|
|
112
|
+
return { kind: "tool_error", toolCallId: id, message: raw ?? "tool failed", ...(mcpServer ? { mcpServer } : {}) };
|
|
113
|
+
}
|
|
114
|
+
if (u.status === "completed") {
|
|
115
|
+
// content[] first (edits carry their diff there); rawOutput alone is
|
|
116
|
+
// often just the server's display title, not the result (probe
|
|
117
|
+
// 2026-09-03: completed MCP call, rawOutput "Call bridge_echo").
|
|
118
|
+
const diff = contentDiff(u.content);
|
|
119
|
+
const mcpServer = stringField(recordField(recordField(u._meta).mcp).server) ?? nativeMcpTool(u)?.server;
|
|
120
|
+
return {
|
|
121
|
+
kind: "tool_done",
|
|
122
|
+
toolCallId: id,
|
|
123
|
+
output: contentText(u.content) ?? stringField(u.rawOutput),
|
|
124
|
+
...(mcpServer ? { mcpServer } : {}),
|
|
125
|
+
...(diff ? { diff } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
return null; // in_progress or unknown status: nothing to render yet
|
|
129
|
+
}
|
|
130
|
+
default:
|
|
131
|
+
// plan / available_commands_update / current_mode_update: consumed by
|
|
132
|
+
// the driver snapshot / future phases, not mapped to activities.
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** MCP tools wrap their args in an `arguments` envelope
|
|
138
|
+
* ({arguments:{...}}); native tools carry them directly (probe 2026-09-03:
|
|
139
|
+
* bridge_echo rawInput {arguments:{text}}, edit_file rawInput {file_path}). */
|
|
140
|
+
function rawArguments(rawInput: unknown): Record<string, unknown> {
|
|
141
|
+
const rec = recordField(rawInput);
|
|
142
|
+
const args = rec.arguments;
|
|
143
|
+
return typeof args === "object" && args !== null && !Array.isArray(args)
|
|
144
|
+
? (args as Record<string, unknown>)
|
|
145
|
+
: rec;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Only our known server prefix is unambiguous without _meta. */
|
|
149
|
+
function nativeMcpTool(update: Record<string, unknown>): { name: string; server: string } | undefined {
|
|
150
|
+
const match = /^mcp_(pi-bridge(?:-\d+)?)_(.+)$/.exec(stringField(update.name) ?? "");
|
|
151
|
+
return match ? { server: match[1]!, name: match[2]! } : undefined;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Clean tool name for MCP tools: the title is "<server>_<tool>" (e.g.
|
|
155
|
+
* "pi-bridge_bridge_echo") and the real name hides in _meta.mcp.tool. */
|
|
156
|
+
function metaToolName(meta: unknown): string | undefined {
|
|
157
|
+
const mcp = recordField(recordField(meta).mcp);
|
|
158
|
+
const tool = mcp.tool;
|
|
159
|
+
return typeof tool === "string" && tool.length > 0 ? tool : undefined;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** First diff entry of a completed tool call: edits carry their native diff
|
|
163
|
+
* in content[] as {type:"diff", path, newText, optional oldText} (run 6). */
|
|
164
|
+
function contentDiff(content: unknown): AcpEditDiff | undefined {
|
|
165
|
+
if (!Array.isArray(content)) return undefined;
|
|
166
|
+
for (const entry of content) {
|
|
167
|
+
const e = recordField(entry);
|
|
168
|
+
if (e.type !== "diff") continue;
|
|
169
|
+
const path = stringField(e.path);
|
|
170
|
+
const newText = stringField(e.newText);
|
|
171
|
+
if (!path || newText === undefined) continue;
|
|
172
|
+
const oldText = stringField(e.oldText);
|
|
173
|
+
return oldText !== undefined ? { path, oldText, newText } : { path, newText };
|
|
174
|
+
}
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Display text of a completed tool call. content[] entries wrap their
|
|
179
|
+
* payload ({type:"content", content:{type:"text", text}}); diff entries
|
|
180
|
+
* carry no text and are skipped. */
|
|
181
|
+
function contentText(content: unknown): string | undefined {
|
|
182
|
+
if (!Array.isArray(content)) return undefined;
|
|
183
|
+
const parts: string[] = [];
|
|
184
|
+
for (const entry of content) {
|
|
185
|
+
const inner = recordField(recordField(entry).content ?? entry);
|
|
186
|
+
if (typeof inner.text === "string" && inner.text.length > 0) parts.push(inner.text);
|
|
187
|
+
}
|
|
188
|
+
return parts.length > 0 ? parts.join("\n") : undefined;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Extract the text of a content block ({type:"text", text}). */
|
|
192
|
+
function chunkText(content: unknown): string {
|
|
193
|
+
if (typeof content === "object" && content !== null) {
|
|
194
|
+
const c = content as Record<string, unknown>;
|
|
195
|
+
if (typeof c.text === "string") return c.text;
|
|
196
|
+
}
|
|
197
|
+
return "";
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function stringField(v: unknown): string | undefined {
|
|
201
|
+
return typeof v === "string" && v.length > 0 ? v : undefined;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function recordField(v: unknown): Record<string, unknown> {
|
|
205
|
+
return typeof v === "object" && v !== null && !Array.isArray(v)
|
|
206
|
+
? (v as Record<string, unknown>)
|
|
207
|
+
: {};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Derive a tool name from the title ("Run create_file?", "Running edit_file")
|
|
211
|
+
* with the kind as fallback. Titles observed live: "Run create_file?",
|
|
212
|
+
* "Running edit_file", "Running view_file". */
|
|
213
|
+
export function toolName(title: unknown, kind: unknown): string {
|
|
214
|
+
if (typeof title === "string") {
|
|
215
|
+
const m = /(?:Run|Running)\s+([A-Za-z_][\w.]*)/i.exec(title);
|
|
216
|
+
if (m) return m[1] as string;
|
|
217
|
+
}
|
|
218
|
+
return typeof kind === "string" && kind.length > 0 ? kind : "tool";
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Map a `session/prompt` result stopReason to a TurnOutcome shape.
|
|
222
|
+
* Verified live: `end_turn`. Schema enumerates cancelled / max_tokens /
|
|
223
|
+
* max_turn_requests / refusal. Native cancellation returns `cancelled`. */
|
|
224
|
+
export function mapStopReason(stopReason: unknown): {
|
|
225
|
+
status: "OK" | "ERROR";
|
|
226
|
+
aborted: boolean;
|
|
227
|
+
error?: string;
|
|
228
|
+
} {
|
|
229
|
+
switch (stopReason) {
|
|
230
|
+
case "end_turn":
|
|
231
|
+
return { status: "OK", aborted: false };
|
|
232
|
+
case "cancelled":
|
|
233
|
+
return { status: "OK", aborted: true };
|
|
234
|
+
case "max_tokens":
|
|
235
|
+
return { status: "OK", aborted: false, error: "ACP: response hit the token cap" };
|
|
236
|
+
case "refusal":
|
|
237
|
+
return { status: "ERROR", aborted: false, error: "ACP: the model refused the request" };
|
|
238
|
+
case "max_turn_requests":
|
|
239
|
+
return { status: "ERROR", aborted: false, error: "ACP: turn exceeded the request limit" };
|
|
240
|
+
default:
|
|
241
|
+
return { status: "OK", aborted: false };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Defensive accumulation with the cumulative-resend port. Native agy streams
|
|
246
|
+
* deltas, so on
|
|
247
|
+
* a compliant server the resend branch stays inert; it exists because the
|
|
248
|
+
* same backend's private protocol exhibited exactly this failure mode.
|
|
249
|
+
*
|
|
250
|
+
* Two guards keep a misflip from corrupting the rest of the turn:
|
|
251
|
+
* - the flip requires the accumulated text to be at least FLIP_MIN_CHARS,
|
|
252
|
+
* because short prefixes ("**", "\n", "#") are trivially extended by
|
|
253
|
+
* ordinary markdown deltas;
|
|
254
|
+
* - in cumulative mode, a frame that no longer extends the accumulator is
|
|
255
|
+
* evidence of a misflip: fall back to append mode instead of slicing. */
|
|
256
|
+
const FLIP_MIN_CHARS = 32;
|
|
257
|
+
|
|
258
|
+
export class TextAccumulator {
|
|
259
|
+
#rawAcc = "";
|
|
260
|
+
#sanitizedAcc = "";
|
|
261
|
+
#cumulative: boolean | undefined;
|
|
262
|
+
#sanitizer = new StreamSanitizer();
|
|
263
|
+
|
|
264
|
+
/** Returns the delta to emit, or null when nothing new should be emitted. */
|
|
265
|
+
append(delta: string): string | null {
|
|
266
|
+
let rawEmit: string | null = null;
|
|
267
|
+
if (this.#cumulative === undefined) this.#cumulative = false;
|
|
268
|
+
else if (
|
|
269
|
+
!this.#cumulative &&
|
|
270
|
+
this.#rawAcc.length >= FLIP_MIN_CHARS &&
|
|
271
|
+
delta.length > this.#rawAcc.length &&
|
|
272
|
+
delta.startsWith(this.#rawAcc)
|
|
273
|
+
) {
|
|
274
|
+
this.#cumulative = true;
|
|
275
|
+
}
|
|
276
|
+
if (this.#cumulative) {
|
|
277
|
+
if (!delta.startsWith(this.#rawAcc)) {
|
|
278
|
+
// Misflip evidence: back to deltas.
|
|
279
|
+
this.#cumulative = false;
|
|
280
|
+
this.#rawAcc += delta;
|
|
281
|
+
rawEmit = delta;
|
|
282
|
+
} else if (delta.length <= this.#rawAcc.length) {
|
|
283
|
+
return null; // duplicate frame
|
|
284
|
+
} else {
|
|
285
|
+
rawEmit = delta.slice(this.#rawAcc.length);
|
|
286
|
+
this.#rawAcc = delta;
|
|
287
|
+
}
|
|
288
|
+
} else {
|
|
289
|
+
this.#rawAcc += delta;
|
|
290
|
+
rawEmit = delta;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (rawEmit === null) return null;
|
|
294
|
+
const sanitized = this.#sanitizer.push(rawEmit);
|
|
295
|
+
if (sanitized.length > 0) {
|
|
296
|
+
this.#sanitizedAcc += sanitized;
|
|
297
|
+
return sanitized;
|
|
298
|
+
}
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
flush(): string | null {
|
|
303
|
+
const flushed = this.#sanitizer.flush();
|
|
304
|
+
if (flushed.length > 0) {
|
|
305
|
+
this.#sanitizedAcc += flushed;
|
|
306
|
+
return flushed;
|
|
307
|
+
}
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
get text(): string {
|
|
312
|
+
return this.#sanitizedAcc;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const USAGE_KEY = /usage|tokens?/i;
|
|
317
|
+
|
|
318
|
+
/** Gate B watch: true when a server payload carries usage/token fields.
|
|
319
|
+
* Key-name based so future shapes (usage blocks, _meta.tokenCount, top-level
|
|
320
|
+
* token totals) all trip it. String values are exempt so auth-style "token"
|
|
321
|
+
* args inside tool-call frames cannot false-positive the latch; depth-capped
|
|
322
|
+
* so the walk stays cheap on every frame until it latches. */
|
|
323
|
+
export function frameCarriesUsage(value: unknown, depth = 0): boolean {
|
|
324
|
+
if (depth > 8 || typeof value !== "object" || value === null) return false;
|
|
325
|
+
if (Array.isArray(value)) return value.some((v) => frameCarriesUsage(v, depth + 1));
|
|
326
|
+
for (const [key, v] of Object.entries(value)) {
|
|
327
|
+
if (USAGE_KEY.test(key) && (typeof v === "number" || typeof v === "object")) return true;
|
|
328
|
+
if (frameCarriesUsage(v, depth + 1)) return true;
|
|
329
|
+
}
|
|
330
|
+
return false;
|
|
331
|
+
}
|
package/src/acp/home.ts
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { isPidAlive } from "../mcp-server.js";
|
|
5
|
+
import { bridgeServerEntry, bridgeServerName, readGlobalMcpConfig } from "../mcp-registration.js";
|
|
6
|
+
import { isValidAgyAgentName } from "../agents.js";
|
|
7
|
+
|
|
8
|
+
function record(value: unknown, label: string): Record<string, unknown> {
|
|
9
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must contain a JSON object`);
|
|
10
|
+
return value as Record<string, unknown>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function linkDirectory(source: string, target: string): void {
|
|
14
|
+
fs.symlinkSync(source, target, "junction");
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function resolveCarrierAgentMd(agent: string, geminiHome: string, explicitRoot?: string): string {
|
|
18
|
+
const candidates = [
|
|
19
|
+
explicitRoot,
|
|
20
|
+
process.env.AGY_AGENTS_ROOT,
|
|
21
|
+
path.join(geminiHome, "config", "agents"),
|
|
22
|
+
path.join(os.homedir(), ".gemini", "config", "agents"),
|
|
23
|
+
];
|
|
24
|
+
for (const root of candidates) {
|
|
25
|
+
if (!root) continue;
|
|
26
|
+
const file = path.join(root, agent, "agent.md");
|
|
27
|
+
try {
|
|
28
|
+
if (fs.statSync(file).isFile()) return file;
|
|
29
|
+
} catch {
|
|
30
|
+
/* try next candidate */
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
throw new Error(`ACP carrier agent "${agent}" not found`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Staging root for isolated agy homes. The directory name predates the
|
|
37
|
+
* stream-json engine adopting homes; renaming it would strand existing
|
|
38
|
+
* installs' unswept dirs, so both engines stage under it. */
|
|
39
|
+
export function agyHomeStagingDir(): string {
|
|
40
|
+
return path.join(os.homedir(), ".pi", "agent", "antigravity-bridge", "acp-homes");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface AgentMcpServerSpec {
|
|
44
|
+
name: string;
|
|
45
|
+
serverUrl: string;
|
|
46
|
+
headers?: Record<string, string>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function formatAgentMcpYaml(servers: readonly AgentMcpServerSpec[]): string {
|
|
50
|
+
const lines: string[] = ["mcpServers:"];
|
|
51
|
+
for (const server of servers) {
|
|
52
|
+
lines.push(` - name: ${JSON.stringify(server.name)}`);
|
|
53
|
+
lines.push(` serverUrl: ${JSON.stringify(server.serverUrl)}`);
|
|
54
|
+
const headers = server.headers ? Object.entries(server.headers) : [];
|
|
55
|
+
if (headers.length > 0) {
|
|
56
|
+
lines.push(" headers:");
|
|
57
|
+
for (const [k, v] of headers) {
|
|
58
|
+
lines.push(` ${JSON.stringify(k)}: ${JSON.stringify(v)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return lines.join("\n");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function injectAgentMcpServers(md: string, servers: readonly AgentMcpServerSpec[]): string {
|
|
66
|
+
if (servers.length === 0) return md;
|
|
67
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---(\r?\n|$)/.exec(md);
|
|
68
|
+
if (!match) throw new Error("ACP carrier agent.md is missing YAML frontmatter");
|
|
69
|
+
const frontmatter = match[1];
|
|
70
|
+
const suffix = match[2];
|
|
71
|
+
const rest = md.slice(match[0].length);
|
|
72
|
+
return `---\n${frontmatter}\n${formatAgentMcpYaml(servers)}\n---${suffix}${rest}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface StageAgyHomeOptions {
|
|
76
|
+
geminiHome?: string;
|
|
77
|
+
parentDir?: string;
|
|
78
|
+
/** Dir-name prefix: "acp-home" (ACP engine, default) or "agy-home"
|
|
79
|
+
* (stream-json). The sweep accepts both. */
|
|
80
|
+
prefix?: string;
|
|
81
|
+
/** This session's bridge entry, written ENABLED straight into the staged
|
|
82
|
+
* config (issue #14). Never ride the suppression marker here: the marker
|
|
83
|
+
* hides bridges from an agy reading the GLOBAL config, and a private-home
|
|
84
|
+
* agy never reads global - a marker-disabled own entry would break G9
|
|
85
|
+
* silently inside our own home. Omit when the bridge is off. */
|
|
86
|
+
ownBridge?: { pid: number; port: number; token: string; tokenHeader: string };
|
|
87
|
+
/** Inherit foreign/global MCP entries from global mcp_config.json (default
|
|
88
|
+
* true for stream-json; ACP sets false because session/new and
|
|
89
|
+
* session/load plus the private agent frontmatter inject pi-bridge). */
|
|
90
|
+
inheritGlobalMcp?: boolean;
|
|
91
|
+
/** Generated carrier agent name for ACP restricted sessions. Copied into
|
|
92
|
+
* <staged>/config/agents/<agent>/agent.md as a real directory (never
|
|
93
|
+
* junctioned to global agents) so AGY_AGENTS_ROOT works and global
|
|
94
|
+
* agents dirs are never mutated. */
|
|
95
|
+
agent?: string;
|
|
96
|
+
/** Explicit agent discovery root for tests; falls back to AGY_AGENTS_ROOT
|
|
97
|
+
* then geminiHome/config/agents. */
|
|
98
|
+
agentsRoot?: string;
|
|
99
|
+
/** Session MCP server specs injected as `mcpServers` list-of-objects into
|
|
100
|
+
* the PRIVATE copied carrier frontmatter so bridge access is part of the
|
|
101
|
+
* custom Agent definition at creation time without writing secrets to the
|
|
102
|
+
* global agent file. */
|
|
103
|
+
agentMcpServers?: AgentMcpServerSpec[];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Isolate a spawned agy from per-pid bridge entries in the global MCP
|
|
107
|
+
* config: the staged home carries the global servers (when inheritGlobalMcp
|
|
108
|
+
* is true) minus every pi-bridge-*, plus (optionally) this session's bridge
|
|
109
|
+
* entry. When an ACP carrier agent is set, stages only that agent into a
|
|
110
|
+
* real config/agents/<agent> directory without junctioning global agents. */
|
|
111
|
+
export function stageAgyHome(opts: StageAgyHomeOptions = {}): string {
|
|
112
|
+
const geminiHome = opts.geminiHome ?? path.join(os.homedir(), ".gemini");
|
|
113
|
+
const globalConfigDir = path.join(geminiHome, "config");
|
|
114
|
+
const globalMcpPath = path.join(globalConfigDir, "mcp_config.json");
|
|
115
|
+
const inheritGlobalMcp = opts.inheritGlobalMcp ?? true;
|
|
116
|
+
let carrierMd: string | undefined;
|
|
117
|
+
if (opts.agent !== undefined) {
|
|
118
|
+
if (!isValidAgyAgentName(opts.agent)) {
|
|
119
|
+
throw new Error(`Invalid ACP agent name: ${opts.agent}`);
|
|
120
|
+
}
|
|
121
|
+
carrierMd = resolveCarrierAgentMd(opts.agent, geminiHome, opts.agentsRoot);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
let config: Record<string, unknown> = { mcpServers: {} };
|
|
125
|
+
let filtered: Record<string, unknown> = {};
|
|
126
|
+
if (inheritGlobalMcp) {
|
|
127
|
+
try {
|
|
128
|
+
// Tolerant of the CLI's 0-byte fresh-install file and a UTF-8 BOM;
|
|
129
|
+
// only a missing file means "no config at all" (issue #11).
|
|
130
|
+
config = record(readGlobalMcpConfig(globalMcpPath), globalMcpPath);
|
|
131
|
+
} catch (err) {
|
|
132
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") {
|
|
133
|
+
throw new Error(`Cannot isolate inherited MCP config ${globalMcpPath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
const servers = record(config.mcpServers ?? {}, `${globalMcpPath} mcpServers`);
|
|
137
|
+
filtered = Object.fromEntries(
|
|
138
|
+
Object.entries(servers).filter(([name]) => !/^pi-bridge(?:-\d+)?$/.test(name)),
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
if (opts.ownBridge) {
|
|
142
|
+
filtered[bridgeServerName(opts.ownBridge.pid)] = bridgeServerEntry({ ...opts.ownBridge, disabled: false });
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const parentDir = opts.parentDir ?? agyHomeStagingDir();
|
|
146
|
+
const prefix = opts.prefix ?? "acp-home";
|
|
147
|
+
fs.mkdirSync(parentDir, { recursive: true, mode: 0o700 });
|
|
148
|
+
const staged = fs.mkdtempSync(path.join(parentDir, `${prefix}-${process.pid}-`));
|
|
149
|
+
try {
|
|
150
|
+
fs.mkdirSync(path.join(staged, "config"), { mode: 0o700 });
|
|
151
|
+
fs.writeFileSync(path.join(staged, "config", "mcp_config.json"), JSON.stringify({ ...config, mcpServers: filtered }), { mode: 0o600 });
|
|
152
|
+
|
|
153
|
+
const appData = path.join(geminiHome, "antigravity-cli");
|
|
154
|
+
if (fs.existsSync(appData)) linkDirectory(appData, path.join(staged, "antigravity-cli"));
|
|
155
|
+
const instructions = path.join(geminiHome, "GEMINI.md");
|
|
156
|
+
if (inheritGlobalMcp && fs.existsSync(instructions)) fs.copyFileSync(instructions, path.join(staged, "GEMINI.md"));
|
|
157
|
+
const skipAgentsJunction = Boolean(opts.agent) || !inheritGlobalMcp;
|
|
158
|
+
if (fs.existsSync(globalConfigDir)) {
|
|
159
|
+
for (const entry of fs.readdirSync(globalConfigDir, { withFileTypes: true })) {
|
|
160
|
+
if (entry.name === "mcp_config.json") continue;
|
|
161
|
+
if (skipAgentsJunction && entry.name === "agents") continue;
|
|
162
|
+
const source = path.join(globalConfigDir, entry.name);
|
|
163
|
+
const target = path.join(staged, "config", entry.name);
|
|
164
|
+
let stat: fs.Stats | fs.Dirent = entry;
|
|
165
|
+
if (entry.isSymbolicLink()) {
|
|
166
|
+
try {
|
|
167
|
+
stat = fs.statSync(source);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
170
|
+
throw err;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (stat.isDirectory()) linkDirectory(source, target);
|
|
174
|
+
else if (stat.isFile()) fs.copyFileSync(source, target);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (opts.agent && carrierMd) {
|
|
178
|
+
const targetDir = path.join(staged, "config", "agents", opts.agent);
|
|
179
|
+
fs.mkdirSync(targetDir, { recursive: true, mode: 0o700 });
|
|
180
|
+
const rawAgentMd = fs.readFileSync(carrierMd, "utf8");
|
|
181
|
+
const privateAgentMd = opts.agentMcpServers?.length
|
|
182
|
+
? injectAgentMcpServers(rawAgentMd, opts.agentMcpServers)
|
|
183
|
+
: rawAgentMd;
|
|
184
|
+
fs.writeFileSync(path.join(targetDir, "agent.md"), privateAgentMd, { mode: 0o600 });
|
|
185
|
+
}
|
|
186
|
+
return staged;
|
|
187
|
+
} catch (err) {
|
|
188
|
+
fs.rmSync(staged, { recursive: true, force: true });
|
|
189
|
+
throw err;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Sweep staged homes whose owning pi process died. Accepts both engine
|
|
194
|
+
* prefixes; a home staged by the CURRENT process is skipped (it may be in
|
|
195
|
+
* use by a live driver - process-exit leftovers are the next start's
|
|
196
|
+
* problem). */
|
|
197
|
+
export function sweepStagedAgyHomes(baseDir: string = agyHomeStagingDir(), alive: (pid: number) => boolean = isPidAlive): void {
|
|
198
|
+
let entries: string[];
|
|
199
|
+
try {
|
|
200
|
+
entries = fs.readdirSync(baseDir);
|
|
201
|
+
} catch {
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
for (const name of entries) {
|
|
205
|
+
const match = /^(?:acp|agy)-home-(\d+)-/.exec(name);
|
|
206
|
+
if (!match) continue;
|
|
207
|
+
const pid = Number(match[1]);
|
|
208
|
+
if (pid === process.pid || alive(pid)) continue;
|
|
209
|
+
removeStagedAgyHome(path.join(baseDir, name));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Add or refresh this session's own bridge entry in an ALREADY-STAGED
|
|
214
|
+
* home (the bridge was enabled after the first spawn staged the home
|
|
215
|
+
* without one). Single-writer file (our pid owns the session), plain
|
|
216
|
+
* write is fine. */
|
|
217
|
+
export function writeOwnBridgeEntry(staged: string, entry: { pid: number; port: number; token: string; tokenHeader: string }): void {
|
|
218
|
+
const cfgPath = path.join(staged, "config", "mcp_config.json");
|
|
219
|
+
const cfg = record(readGlobalMcpConfig(cfgPath), cfgPath);
|
|
220
|
+
const servers = record(cfg.mcpServers ?? {}, `${cfgPath} mcpServers`);
|
|
221
|
+
servers[bridgeServerName(entry.pid)] = bridgeServerEntry({ ...entry, disabled: false });
|
|
222
|
+
// Same-dir tmp + rename: agy watches config dirs, so a truncated
|
|
223
|
+
// mid-write read must be impossible (issue #14 review round 3).
|
|
224
|
+
const tmp = `${cfgPath}.tmp-${process.pid}`;
|
|
225
|
+
fs.writeFileSync(tmp, JSON.stringify({ ...cfg, mcpServers: servers }), { mode: 0o600 });
|
|
226
|
+
fs.renameSync(tmp, cfgPath);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export function removeStagedAgyHome(staged: string): void {
|
|
230
|
+
const base = path.basename(staged);
|
|
231
|
+
if (!base.startsWith("acp-home-") && !base.startsWith("agy-home-")) return;
|
|
232
|
+
try {
|
|
233
|
+
if (!fs.lstatSync(staged).isDirectory()) return;
|
|
234
|
+
fs.rmSync(staged, { recursive: true, force: true });
|
|
235
|
+
} catch {
|
|
236
|
+
// Connection teardown is best-effort; startup sweeps crash leftovers.
|
|
237
|
+
}
|
|
238
|
+
}
|