@juanbenjumea/pi-agy 0.6.11 → 0.7.0
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 +9 -0
- package/README.md +57 -1
- package/extensions/commands.ts +13 -105
- package/extensions/index.ts +164 -47
- package/extensions/lib/args.ts +125 -0
- package/extensions/lib/cli.ts +31 -1223
- package/extensions/lib/command-args.ts +101 -0
- package/extensions/lib/config.ts +12 -0
- package/extensions/lib/confirm.ts +43 -0
- package/extensions/lib/doctor.ts +37 -1
- package/extensions/lib/inspect.ts +254 -0
- package/extensions/lib/lock.ts +1 -1
- package/extensions/lib/model-sort.ts +46 -0
- package/extensions/lib/provider-driver.ts +728 -0
- package/extensions/lib/provider-mcp.ts +580 -0
- package/extensions/lib/provider-models.ts +251 -0
- package/extensions/lib/provider.ts +1124 -0
- package/extensions/lib/retry.ts +34 -0
- package/extensions/lib/spawn.ts +411 -0
- package/extensions/lib/usage.ts +398 -0
- package/extensions/lib/verify.ts +11 -0
- package/package.json +6 -1
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Localhost MCP bridge: exposes Pi-side read-only context to agy turns.
|
|
3
|
+
*
|
|
4
|
+
* agy reads `.agents/mcp_config.json` from its `--add-dir` directories, so
|
|
5
|
+
* the provider passes a bridge-controlled dir as an extra `--add-dir` — the
|
|
6
|
+
* user's global agy config is never touched. Each Pi process owns one
|
|
7
|
+
* config dir (`pi-agy-bridge-<pid>`); stale dirs from crashed sessions are
|
|
8
|
+
* swept on start.
|
|
9
|
+
*
|
|
10
|
+
* Phase 1 tools are all read-only and served synchronously (no Pi-turn
|
|
11
|
+
* round-trip needed): recorded sessions, quota report, model catalog. They
|
|
12
|
+
* let an agy agent inspect Pi-side state itself instead of guessing.
|
|
13
|
+
* Mutating Pi-tool bridging (park + shadow toolUse + approval gates) builds
|
|
14
|
+
* on this transport later.
|
|
15
|
+
*
|
|
16
|
+
* Hardening: 127.0.0.1 only, per-process shared-secret header (blocks
|
|
17
|
+
* browser CSRF — a simple cross-origin POST cannot set a custom header),
|
|
18
|
+
* 1 MiB body cap, atomic config writes with restrictive modes, and a
|
|
19
|
+
* request handler that degrades to error results instead of ever crashing
|
|
20
|
+
* Pi. Startup never throws: failure returns `undefined` and turns proceed
|
|
21
|
+
* without `--add-dir`.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
25
|
+
import { chmod, mkdir, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
26
|
+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
|
27
|
+
import * as os from "node:os";
|
|
28
|
+
import * as path from "node:path";
|
|
29
|
+
import { Server as McpServer } from "@modelcontextprotocol/sdk/server/index.js";
|
|
30
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
31
|
+
import {
|
|
32
|
+
CallToolRequestSchema,
|
|
33
|
+
ListToolsRequestSchema,
|
|
34
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
35
|
+
|
|
36
|
+
import { getDefaultConfigPath } from "./config.js";
|
|
37
|
+
import { checkAgyUsage, formatAgyUsage } from "./cli.js";
|
|
38
|
+
import {
|
|
39
|
+
FALLBACK_PROVIDER_MODELS,
|
|
40
|
+
parseProviderCatalog,
|
|
41
|
+
type AgyProviderModelEntry,
|
|
42
|
+
} from "./provider-models.js";
|
|
43
|
+
import { getHistory } from "./sessions.js";
|
|
44
|
+
import { runPreflightCommand } from "./spawn.js";
|
|
45
|
+
|
|
46
|
+
export const BRIDGE_MCP_KEY = "pi-agy-tools";
|
|
47
|
+
/** Built-in read-only tools (sessions, quota, catalog), plus dynamic bridged Pi tools. */
|
|
48
|
+
const BUILTIN_TOOL_COUNT = 3;
|
|
49
|
+
export const BRIDGE_TOKEN_HEADER = "x-pi-agy-token";
|
|
50
|
+
const BRIDGE_MCP_PATH = "/mcp";
|
|
51
|
+
const MAX_BODY_BYTES = 1024 * 1024;
|
|
52
|
+
const CATALOG_TTL_MS = 5 * 60_000;
|
|
53
|
+
const HISTORY_LIMIT = 10;
|
|
54
|
+
|
|
55
|
+
function agentDir(): string {
|
|
56
|
+
// Mirror getDefaultConfigPath(): $PI_CODING_AGENT_DIR/agy-config.json.
|
|
57
|
+
return path.dirname(getDefaultConfigPath());
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function bridgeBaseDir(): string {
|
|
61
|
+
return path.join(agentDir(), "pi-agy-bridge");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
let bridgeSequence = 0;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Unique config dir per bridge instance. Per-pid alone collides: one Pi
|
|
68
|
+
* process serves many workspace dirs, and the second bridge would overwrite
|
|
69
|
+
* the first bridge's port/token (and stop() would delete both).
|
|
70
|
+
*/
|
|
71
|
+
function allocateBridgeConfigDir(): string {
|
|
72
|
+
bridgeSequence += 1;
|
|
73
|
+
return path.join(bridgeBaseDir(), `bridge-${process.pid}-${bridgeSequence}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function bridgeConfigPath(configDir: string): string {
|
|
77
|
+
return path.join(configDir, ".agents", "mcp_config.json");
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isPidAlive(pid: number): boolean {
|
|
81
|
+
try {
|
|
82
|
+
process.kill(pid, 0);
|
|
83
|
+
return true;
|
|
84
|
+
} catch (error) {
|
|
85
|
+
// EPERM: alive but not ours to signal. ESRCH: no such process.
|
|
86
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Best-effort sweep of config dirs left by crashed sessions. */
|
|
91
|
+
async function sweepStaleBridgeDirs(): Promise<void> {
|
|
92
|
+
let entries: string[];
|
|
93
|
+
try {
|
|
94
|
+
entries = await readdir(bridgeBaseDir());
|
|
95
|
+
} catch {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
for (const name of entries) {
|
|
99
|
+
if (!name.startsWith("bridge-")) continue;
|
|
100
|
+
// bridge-<pid>[-<seq>]: only the leading segment is the owner pid.
|
|
101
|
+
// pid 0 is never a real owner (kill(0) tests the process group).
|
|
102
|
+
const pid = Number(name.slice("bridge-".length).split("-", 1)[0]);
|
|
103
|
+
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) continue;
|
|
104
|
+
if (isPidAlive(pid)) continue;
|
|
105
|
+
try {
|
|
106
|
+
await rm(path.join(bridgeBaseDir(), name), { recursive: true, force: true });
|
|
107
|
+
} catch {
|
|
108
|
+
// Best effort.
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function writeBridgeConfig(configDir: string, port: number, token: string): Promise<void> {
|
|
114
|
+
const configPath = bridgeConfigPath(configDir);
|
|
115
|
+
await mkdir(path.dirname(configPath), { recursive: true, mode: 0o700 });
|
|
116
|
+
const config = {
|
|
117
|
+
mcpServers: {
|
|
118
|
+
[BRIDGE_MCP_KEY]: {
|
|
119
|
+
serverUrl: `http://127.0.0.1:${port}${BRIDGE_MCP_PATH}`,
|
|
120
|
+
headers: { [BRIDGE_TOKEN_HEADER]: token },
|
|
121
|
+
},
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
// Unique dir per bridge instance: no tmp-name contention, and `wx` fails
|
|
125
|
+
// closed instead of following a planted symlink.
|
|
126
|
+
const tmp = `${configPath}.${process.pid}.tmp`;
|
|
127
|
+
try {
|
|
128
|
+
await writeFile(tmp, JSON.stringify(config, null, 2) + "\n", { mode: 0o600, flag: "wx" });
|
|
129
|
+
await chmod(tmp, 0o600);
|
|
130
|
+
await rename(tmp, configPath);
|
|
131
|
+
} catch (error) {
|
|
132
|
+
try {
|
|
133
|
+
await rm(tmp, { force: true });
|
|
134
|
+
} catch {
|
|
135
|
+
// Best effort.
|
|
136
|
+
}
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function toolText(text: string, isError = false): {
|
|
142
|
+
content: Array<{ type: "text"; text: string }>;
|
|
143
|
+
isError?: boolean;
|
|
144
|
+
} {
|
|
145
|
+
return isError ? { content: [{ type: "text", text }], isError } : { content: [{ type: "text", text }] };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function stringArg(value: unknown): string | undefined {
|
|
149
|
+
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export interface McpBridgeHandle {
|
|
153
|
+
/** Directory to pass as extra agy `--add-dir`. */
|
|
154
|
+
configDir: string;
|
|
155
|
+
/** Local server URL (debugging only; agy reads it from the config file). */
|
|
156
|
+
url: string;
|
|
157
|
+
stop: () => Promise<void>;
|
|
158
|
+
/** Replace the bridged Pi-tool catalog (refreshed per turn). */
|
|
159
|
+
setTools: (tools: BridgeToolDef[]) => void;
|
|
160
|
+
/** Parked-call handler: return true to hold the MCP response open. */
|
|
161
|
+
setParkHandler: (handler: BridgeParkHandler | undefined) => void;
|
|
162
|
+
/** Deliver a Pi tool result to a parked call. False when unknown. */
|
|
163
|
+
completePark: (callId: string, result: BridgeToolResult) => boolean;
|
|
164
|
+
/** Fail every parked call (teardown, cancelled turns). */
|
|
165
|
+
failAllParks: (message: string) => void;
|
|
166
|
+
/** Point-in-time description for status surfaces. */
|
|
167
|
+
describe: () => { configDir: string; url: string; toolCount: number };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A Pi tool projected for agy: MCP-safe advertised name, real Pi identity. */
|
|
171
|
+
export interface BridgeToolDef {
|
|
172
|
+
/** MCP-safe name as advertised to agy. */
|
|
173
|
+
name: string;
|
|
174
|
+
/** Real Pi tool name (invoked via shadow toolUse). */
|
|
175
|
+
piName: string;
|
|
176
|
+
description: string;
|
|
177
|
+
inputSchema: Record<string, unknown>;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export interface BridgePark {
|
|
181
|
+
callId: string;
|
|
182
|
+
/** Real Pi tool name. */
|
|
183
|
+
toolName: string;
|
|
184
|
+
args: Record<string, unknown>;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export interface BridgeToolResult {
|
|
188
|
+
text: string;
|
|
189
|
+
isError: boolean;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export type BridgeParkHandler = (park: BridgePark) => boolean;
|
|
193
|
+
|
|
194
|
+
/** MCP tool names: [a-zA-Z0-9_-]{1,64}. Pi names are sanitized into that. */
|
|
195
|
+
export function toSafeBridgeName(name: string): string {
|
|
196
|
+
const safe = name
|
|
197
|
+
.replace(/[^a-zA-Z0-9_-]+/g, "_")
|
|
198
|
+
.replace(/^_+|_+$/g, "")
|
|
199
|
+
.slice(0, 64);
|
|
200
|
+
return safe || "tool";
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
interface CatalogCache {
|
|
204
|
+
raw: string;
|
|
205
|
+
at: number;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Start the bridge for a workspace directory. Never throws: any failure
|
|
210
|
+
* cleans up and resolves `undefined` so provider turns proceed plain.
|
|
211
|
+
*/
|
|
212
|
+
export async function startMcpBridge(dir: string): Promise<McpBridgeHandle | undefined> {
|
|
213
|
+
const token = randomBytes(32).toString("hex");
|
|
214
|
+
let catalogCache: CatalogCache | undefined;
|
|
215
|
+
|
|
216
|
+
const mcp = new McpServer(
|
|
217
|
+
{ name: "pi-agy-bridge", version: "1" },
|
|
218
|
+
{ capabilities: { tools: {} } },
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
let bridgedTools: BridgeToolDef[] = [];
|
|
222
|
+
let parkHandler: BridgeParkHandler | undefined;
|
|
223
|
+
const parks = new Map<string, (result: BridgeToolResult) => void>();
|
|
224
|
+
|
|
225
|
+
mcp.setRequestHandler(ListToolsRequestSchema, () => ({
|
|
226
|
+
tools: [
|
|
227
|
+
...bridgedTools.map((tool) => ({
|
|
228
|
+
name: tool.name,
|
|
229
|
+
description: `${tool.description} (Pi tool: runs with Pi permissions and review.)`,
|
|
230
|
+
inputSchema: tool.inputSchema,
|
|
231
|
+
})),
|
|
232
|
+
{
|
|
233
|
+
name: "agy_sessions_list",
|
|
234
|
+
description:
|
|
235
|
+
"List recorded agy conversations for a directory (ids, models, ages, summaries) to find a conversation to resume. Read-only.",
|
|
236
|
+
inputSchema: {
|
|
237
|
+
type: "object",
|
|
238
|
+
properties: {
|
|
239
|
+
dir: { type: "string", description: "Directory to list. Defaults to the current workspace." },
|
|
240
|
+
limit: { type: "number", description: "Maximum entries (default 10, max 10)." },
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
name: "agy_quota_report",
|
|
246
|
+
description:
|
|
247
|
+
"Read current Antigravity model quotas and reset times without spending a model turn. Read-only.",
|
|
248
|
+
inputSchema: {
|
|
249
|
+
type: "object",
|
|
250
|
+
properties: {
|
|
251
|
+
model: { type: "string", description: "Optional agy model slug to focus the report." },
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
},
|
|
255
|
+
{
|
|
256
|
+
name: "agy_model_catalog",
|
|
257
|
+
description:
|
|
258
|
+
"List agy models available to this workspace as Pi picker entries (id, agy --model value, effort tiers). Read-only.",
|
|
259
|
+
inputSchema: { type: "object", properties: {} },
|
|
260
|
+
},
|
|
261
|
+
],
|
|
262
|
+
}));
|
|
263
|
+
|
|
264
|
+
mcp.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
265
|
+
try {
|
|
266
|
+
const name = request.params.name;
|
|
267
|
+
const args = (request.params.arguments ?? {}) as Record<string, unknown>;
|
|
268
|
+
if (name === "agy_sessions_list") {
|
|
269
|
+
// Constrain overrides to the bound workspace: session summaries
|
|
270
|
+
// must not wander across directories on an agent's say-so.
|
|
271
|
+
const requested = path.resolve(stringArg(args.dir) ?? dir);
|
|
272
|
+
const root = path.resolve(dir);
|
|
273
|
+
if (requested !== root && !requested.startsWith(root + path.sep)) {
|
|
274
|
+
return toolText(`Access denied: sessions outside the workspace (${dir}) are not visible.`, true);
|
|
275
|
+
}
|
|
276
|
+
const target = requested;
|
|
277
|
+
const limit = Math.min(Math.max(Math.floor(Number(args.limit) || HISTORY_LIMIT), 1), HISTORY_LIMIT);
|
|
278
|
+
const history = (await getHistory(target)).slice(0, limit);
|
|
279
|
+
if (history.length === 0) return toolText(`No agy conversations recorded for ${target} yet.`);
|
|
280
|
+
const lines = history.map(
|
|
281
|
+
(entry) =>
|
|
282
|
+
`- ${entry.conversation_id} · ${entry.model ?? "unknown model"}${entry.agent ? ` · agent ${entry.agent}` : ""} · ${entry.updated_at}${entry.summary ? ` · ${entry.summary}` : ""}`,
|
|
283
|
+
);
|
|
284
|
+
return toolText(`agy conversations for ${target} (most recent first):\n${lines.join("\n")}`);
|
|
285
|
+
}
|
|
286
|
+
if (name === "agy_quota_report") {
|
|
287
|
+
const model = stringArg(args.model);
|
|
288
|
+
const quota = await checkAgyUsage(dir, undefined);
|
|
289
|
+
const report = formatAgyUsage(quota, model) ?? "agy quota information is unavailable";
|
|
290
|
+
return toolText(report);
|
|
291
|
+
}
|
|
292
|
+
if (name === "agy_model_catalog") {
|
|
293
|
+
const entries = await readCatalog(dir, catalogCache);
|
|
294
|
+
catalogCache = entries.cache;
|
|
295
|
+
const lines = entries.models.map(
|
|
296
|
+
(entry) =>
|
|
297
|
+
`- ${entry.id} (--model ${entry.full}${entry.efforts ? `; effort: ${entry.efforts.join("/")}` : "; fixed thinking"})`,
|
|
298
|
+
);
|
|
299
|
+
return toolText(
|
|
300
|
+
`agy models${entries.fallback ? " (fallback catalog — live discovery unavailable)" : ""}:\n${lines.join("\n")}`,
|
|
301
|
+
);
|
|
302
|
+
}
|
|
303
|
+
const bridged = bridgedTools.find((tool) => tool.name === name);
|
|
304
|
+
if (bridged) {
|
|
305
|
+
const callArgs =
|
|
306
|
+
args && typeof args === "object" && !Array.isArray(args)
|
|
307
|
+
? (args as Record<string, unknown>)
|
|
308
|
+
: {};
|
|
309
|
+
const callId = randomUUID();
|
|
310
|
+
const handler = parkHandler;
|
|
311
|
+
if (!handler) {
|
|
312
|
+
return toolText("Pi tool bridge is not awaiting calls right now; retry shortly.", true);
|
|
313
|
+
}
|
|
314
|
+
const parked = await new Promise<BridgeToolResult | undefined>((resolve) => {
|
|
315
|
+
parks.set(callId, resolve);
|
|
316
|
+
let accepted = false;
|
|
317
|
+
try {
|
|
318
|
+
accepted = handler({ callId, toolName: bridged.piName, args: callArgs });
|
|
319
|
+
} catch {
|
|
320
|
+
accepted = false;
|
|
321
|
+
}
|
|
322
|
+
if (!accepted) {
|
|
323
|
+
parks.delete(callId);
|
|
324
|
+
resolve(undefined);
|
|
325
|
+
}
|
|
326
|
+
});
|
|
327
|
+
if (!parked) {
|
|
328
|
+
return toolText("Pi turn is not awaiting tool calls; the call was not executed.", true);
|
|
329
|
+
}
|
|
330
|
+
return {
|
|
331
|
+
content: [{ type: "text" as const, text: parked.text }],
|
|
332
|
+
...(parked.isError ? { isError: true as const } : {}),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
return toolText(`Unknown tool: ${name}`, true);
|
|
336
|
+
} catch (error) {
|
|
337
|
+
// Tool failures degrade to error results; the transport stays up.
|
|
338
|
+
return toolText(
|
|
339
|
+
`Bridge tool failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
340
|
+
true,
|
|
341
|
+
);
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
|
|
345
|
+
// Stateful: one transport serves many agy sessions, routed by the
|
|
346
|
+
// session id header. The default (no generator) is stateless and rejects
|
|
347
|
+
// any second request on the same transport.
|
|
348
|
+
const transport = new StreamableHTTPServerTransport({
|
|
349
|
+
sessionIdGenerator: () => randomUUID(),
|
|
350
|
+
});
|
|
351
|
+
const configDir = allocateBridgeConfigDir();
|
|
352
|
+
// Filled after bind; the request handler validates Host against it
|
|
353
|
+
// (defense-in-depth against DNS rebinding past the loopback bind).
|
|
354
|
+
const bound = { port: 0 };
|
|
355
|
+
const http = createServer((req, res) => {
|
|
356
|
+
void handleBridgeRequest(req, res, transport, token, bound.port).catch(() => {
|
|
357
|
+
// handleBridgeRequest guards every response path; this is unreachable
|
|
358
|
+
// belt-and-braces so a client error can never crash Pi.
|
|
359
|
+
if (!res.headersSent) {
|
|
360
|
+
try {
|
|
361
|
+
res.writeHead(500).end();
|
|
362
|
+
} catch {
|
|
363
|
+
// Ignore.
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
// A server with zero error listeners throws uncaught on socket-level
|
|
370
|
+
// failures and kills Pi; per-request paths already settle themselves.
|
|
371
|
+
http.on("error", () => {
|
|
372
|
+
// Never crash the host on loopback transport noise.
|
|
373
|
+
});
|
|
374
|
+
http.on("clientError", (_error, socket) => {
|
|
375
|
+
try {
|
|
376
|
+
socket.destroy();
|
|
377
|
+
} catch {
|
|
378
|
+
// Ignore.
|
|
379
|
+
}
|
|
380
|
+
});
|
|
381
|
+
|
|
382
|
+
const failAllParks = (message: string): void => {
|
|
383
|
+
if (parks.size === 0) return;
|
|
384
|
+
const pending = [...parks.values()];
|
|
385
|
+
parks.clear();
|
|
386
|
+
for (const resolve of pending) {
|
|
387
|
+
try {
|
|
388
|
+
resolve({ text: message, isError: true });
|
|
389
|
+
} catch {
|
|
390
|
+
// Ignore settle races.
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
|
|
395
|
+
const completePark = (callId: string, result: BridgeToolResult): boolean => {
|
|
396
|
+
const resolve = parks.get(callId);
|
|
397
|
+
if (!resolve) return false;
|
|
398
|
+
parks.delete(callId);
|
|
399
|
+
try {
|
|
400
|
+
resolve(result);
|
|
401
|
+
} catch {
|
|
402
|
+
// Ignore settle races.
|
|
403
|
+
}
|
|
404
|
+
return true;
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
const stop = async (): Promise<void> => {
|
|
408
|
+
failAllParks("Pi tool bridge stopped.");
|
|
409
|
+
try {
|
|
410
|
+
await transport.close();
|
|
411
|
+
} catch {
|
|
412
|
+
// Best effort.
|
|
413
|
+
}
|
|
414
|
+
try {
|
|
415
|
+
await mcp.close();
|
|
416
|
+
} catch {
|
|
417
|
+
// Best effort.
|
|
418
|
+
}
|
|
419
|
+
// close() alone waits out keep-alive/SSE sockets; destroy them and
|
|
420
|
+
// bound the wait so session shutdown can never hang on a lingerer.
|
|
421
|
+
try {
|
|
422
|
+
http.closeAllConnections?.();
|
|
423
|
+
} catch {
|
|
424
|
+
// Best effort (older Node typings).
|
|
425
|
+
}
|
|
426
|
+
await Promise.race([
|
|
427
|
+
new Promise<void>((resolve) => http.close(() => resolve())),
|
|
428
|
+
new Promise<void>((resolve) => setTimeout(resolve, 2000)),
|
|
429
|
+
]);
|
|
430
|
+
try {
|
|
431
|
+
await rm(configDir, { recursive: true, force: true });
|
|
432
|
+
} catch {
|
|
433
|
+
// Best effort.
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
|
|
437
|
+
try {
|
|
438
|
+
await sweepStaleBridgeDirs();
|
|
439
|
+
await new Promise<void>((resolve, reject) => {
|
|
440
|
+
http.once("error", reject);
|
|
441
|
+
http.listen(0, "127.0.0.1", () => {
|
|
442
|
+
http.off("error", reject);
|
|
443
|
+
resolve();
|
|
444
|
+
});
|
|
445
|
+
});
|
|
446
|
+
const address = http.address();
|
|
447
|
+
const port = typeof address === "object" && address ? address.port : 0;
|
|
448
|
+
if (!port) throw new Error("bridge bound no port");
|
|
449
|
+
await mcp.connect(transport);
|
|
450
|
+
await writeBridgeConfig(configDir, port, token);
|
|
451
|
+
bound.port = port;
|
|
452
|
+
return {
|
|
453
|
+
configDir,
|
|
454
|
+
url: `http://127.0.0.1:${port}${BRIDGE_MCP_PATH}`,
|
|
455
|
+
stop,
|
|
456
|
+
describe: () => ({
|
|
457
|
+
configDir,
|
|
458
|
+
url: `http://127.0.0.1:${port}${BRIDGE_MCP_PATH}`,
|
|
459
|
+
toolCount: bridgedTools.length + BUILTIN_TOOL_COUNT,
|
|
460
|
+
}),
|
|
461
|
+
setTools: (tools: BridgeToolDef[]) => {
|
|
462
|
+
bridgedTools = tools;
|
|
463
|
+
},
|
|
464
|
+
setParkHandler: (handler: BridgeParkHandler | undefined) => {
|
|
465
|
+
parkHandler = handler;
|
|
466
|
+
},
|
|
467
|
+
completePark,
|
|
468
|
+
failAllParks,
|
|
469
|
+
};
|
|
470
|
+
} catch {
|
|
471
|
+
try {
|
|
472
|
+
await stop();
|
|
473
|
+
} catch {
|
|
474
|
+
// Best effort.
|
|
475
|
+
}
|
|
476
|
+
return undefined;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
async function readCatalog(
|
|
481
|
+
dir: string,
|
|
482
|
+
cache: CatalogCache | undefined,
|
|
483
|
+
): Promise<{ models: AgyProviderModelEntry[]; fallback: boolean; cache: CatalogCache | undefined }> {
|
|
484
|
+
if (cache && Date.now() - cache.at < CATALOG_TTL_MS) {
|
|
485
|
+
const models = parseProviderCatalog(cache.raw);
|
|
486
|
+
if (models.length > 0) return { models, fallback: false, cache };
|
|
487
|
+
}
|
|
488
|
+
try {
|
|
489
|
+
const raw = await runPreflightCommand(["models"], dir, undefined, "agy bridge model catalog", true);
|
|
490
|
+
const models = parseProviderCatalog(raw);
|
|
491
|
+
if (models.length > 0) return { models, fallback: false, cache: { raw, at: Date.now() } };
|
|
492
|
+
} catch {
|
|
493
|
+
// Fall through to the fallback catalog.
|
|
494
|
+
}
|
|
495
|
+
return { models: [...FALLBACK_PROVIDER_MODELS], fallback: true, cache };
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
async function readBody(req: IncomingMessage): Promise<{ body?: unknown; tooLarge: boolean }> {
|
|
499
|
+
const chunks: Buffer[] = [];
|
|
500
|
+
let size = 0;
|
|
501
|
+
for await (const chunk of req) {
|
|
502
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
|
|
503
|
+
size += buffer.length;
|
|
504
|
+
if (size > MAX_BODY_BYTES) return { body: undefined, tooLarge: true };
|
|
505
|
+
chunks.push(buffer);
|
|
506
|
+
}
|
|
507
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
508
|
+
if (!text.trim()) return { body: undefined, tooLarge: false };
|
|
509
|
+
try {
|
|
510
|
+
return { body: JSON.parse(text), tooLarge: false };
|
|
511
|
+
} catch {
|
|
512
|
+
return { body: undefined, tooLarge: false };
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async function handleBridgeRequest(
|
|
517
|
+
req: IncomingMessage,
|
|
518
|
+
res: ServerResponse,
|
|
519
|
+
transport: StreamableHTTPServerTransport,
|
|
520
|
+
token: string,
|
|
521
|
+
port: number,
|
|
522
|
+
): Promise<void> {
|
|
523
|
+
try {
|
|
524
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
525
|
+
if (url.pathname !== BRIDGE_MCP_PATH) {
|
|
526
|
+
res.writeHead(404).end();
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if (req.method !== "POST" && req.method !== "GET" && req.method !== "DELETE") {
|
|
530
|
+
res.writeHead(405).end();
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
// Shared secret: exact match only (duplicated headers parse as arrays
|
|
534
|
+
// and never equal the token). Compared in constant time.
|
|
535
|
+
const presented = req.headers[BRIDGE_TOKEN_HEADER];
|
|
536
|
+
const expected = Buffer.from(token);
|
|
537
|
+
const actual = typeof presented === "string" ? Buffer.from(presented) : undefined;
|
|
538
|
+
if (!actual || actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
|
|
539
|
+
res.writeHead(403).end();
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
// Defense-in-depth against DNS rebinding past the loopback bind.
|
|
543
|
+
const host = req.headers.host ?? "";
|
|
544
|
+
if (port > 0 && host !== `127.0.0.1:${port}` && host !== `localhost:${port}`) {
|
|
545
|
+
res.writeHead(403).end();
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (req.method === "POST") {
|
|
549
|
+
const { body, tooLarge } = await readBody(req);
|
|
550
|
+
if (tooLarge) {
|
|
551
|
+
try {
|
|
552
|
+
req.destroy();
|
|
553
|
+
} catch {
|
|
554
|
+
// Ignore.
|
|
555
|
+
}
|
|
556
|
+
try {
|
|
557
|
+
res.writeHead(413, { Connection: "close" }).end();
|
|
558
|
+
} catch {
|
|
559
|
+
// Socket already gone.
|
|
560
|
+
}
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
if (body === undefined) {
|
|
564
|
+
res.writeHead(400).end();
|
|
565
|
+
return;
|
|
566
|
+
}
|
|
567
|
+
await transport.handleRequest(req, res, body);
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
await transport.handleRequest(req, res);
|
|
571
|
+
} catch {
|
|
572
|
+
if (!res.headersSent) {
|
|
573
|
+
try {
|
|
574
|
+
res.writeHead(500).end();
|
|
575
|
+
} catch {
|
|
576
|
+
// Ignore.
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
}
|