@estebanforge/pi-antigravity-bridge 1.13.1 → 1.13.3
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 +23 -0
- package/README.md +9 -5
- package/extensions/index.ts +113 -68
- package/package.json +1 -1
- package/src/acp/connection.ts +16 -4
- package/src/acp/driver.ts +11 -6
- package/src/atomic-write.ts +41 -0
- package/src/config.ts +95 -39
- package/src/mcp-registration.ts +3 -8
- package/src/mcp-server.ts +54 -23
- package/src/native-tools.ts +2 -0
- package/src/provider.ts +148 -47
- package/src/runtime.ts +310 -0
- package/src/sessions.ts +11 -0
package/src/config.ts
CHANGED
|
@@ -14,6 +14,7 @@ import fs from "node:fs";
|
|
|
14
14
|
import path from "node:path";
|
|
15
15
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
16
16
|
import { normalizeAgyAgentName } from "./agents.js";
|
|
17
|
+
import { writeJsonAtomic } from "./atomic-write.js";
|
|
17
18
|
|
|
18
19
|
/** pi's agent dir (env override PI_CODING_AGENT_DIR, else ~/.pi/agent); every
|
|
19
20
|
* bridge-owned path derives from it so isolated or rebranded pi homes keep
|
|
@@ -140,6 +141,10 @@ export interface AgyConfig {
|
|
|
140
141
|
* on the installed pi. The notice never repeats; /agy patch-cleanup is
|
|
141
142
|
* always available. */
|
|
142
143
|
patchCleanupNotified?: boolean;
|
|
144
|
+
/** config.json values that were present but unparseable and fell back or
|
|
145
|
+
* failed closed (issue #23). Surfaced by /agy doctor; undefined when
|
|
146
|
+
* every value parsed. Computed per load, never persisted by saveConfig. */
|
|
147
|
+
parseWarnings?: string[];
|
|
143
148
|
/** Custom agy agent for stream-json turns (`--agent`, /agy agent).
|
|
144
149
|
* Absent = agy's default agent. ACP turns ignore it (no protocol slot). */
|
|
145
150
|
agent?: string;
|
|
@@ -261,6 +266,60 @@ export function parseCapMinutes(raw: string | number | undefined, fallback: numb
|
|
|
261
266
|
return n >= 1 && n <= MAX_TURN_CAP_MIN ? n : fallback;
|
|
262
267
|
}
|
|
263
268
|
|
|
269
|
+
/** Boolean spellings shared by the AGY_* env grammar and config.json (issue
|
|
270
|
+
* #23): the /agy UI's on/off vocabulary plus the JSON literals and digits. */
|
|
271
|
+
const BOOLISH_TRUE = new Set(["1", "true", "on"]);
|
|
272
|
+
const BOOLISH_FALSE = new Set(["0", "false", "off"]);
|
|
273
|
+
|
|
274
|
+
/** The literal boolean grammar shared by parseBoolish, parseReadOnlyValue,
|
|
275
|
+
* and saveConfig's pass-through: JSON booleans, the /agy vocabulary as
|
|
276
|
+
* strings (case/whitespace tolerated), and the JSON numbers 0/1. Returns
|
|
277
|
+
* undefined for anything outside the grammar. */
|
|
278
|
+
function parseBoolishLiteral(raw: unknown): boolean | undefined {
|
|
279
|
+
if (typeof raw === "boolean") return raw;
|
|
280
|
+
if (raw === 0 || raw === 1) return raw === 1;
|
|
281
|
+
if (typeof raw === "string") {
|
|
282
|
+
const v = raw.trim().toLowerCase();
|
|
283
|
+
if (BOOLISH_TRUE.has(v)) return true;
|
|
284
|
+
if (BOOLISH_FALSE.has(v)) return false;
|
|
285
|
+
}
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** Parse a config.json boolean that a hand editor may have written as a
|
|
290
|
+
* string ("off", "false", "0" - the README and /agy vocabulary) or as the
|
|
291
|
+
* JSON numbers 0/1. Present but unparseable values fall back to the given
|
|
292
|
+
* default and warn; the silence is what made issue #23 invisible. */
|
|
293
|
+
function parseBoolish(raw: unknown, label: string, fallback: boolean, warnings: string[]): boolean {
|
|
294
|
+
const v = parseBoolishLiteral(raw);
|
|
295
|
+
if (v !== undefined) return v;
|
|
296
|
+
if (raw === undefined || raw === null) return fallback;
|
|
297
|
+
warnings.push(`${label}: ${JSON.stringify(raw)} is not a recognized boolean (true/false, on/off, 1/0); using default ${fallback}`);
|
|
298
|
+
return fallback;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** File-path readOnly parse: the AGY_READONLY env grammar mirrored (issue
|
|
302
|
+
* #23). Explicit blanks and spelled-out falsities are OFF, every other
|
|
303
|
+
* present value counts as ON so a typo can never disable the safety knob. */
|
|
304
|
+
function parseReadOnlyValue(raw: unknown, warnings: string[]): boolean {
|
|
305
|
+
const failClosed = (rawValue: unknown): boolean => {
|
|
306
|
+
warnings.push(`readOnly: ${JSON.stringify(rawValue)} is not a recognized boolean (true/false, on/off, 1/0); failing closed to true`);
|
|
307
|
+
return true;
|
|
308
|
+
};
|
|
309
|
+
const v = parseBoolishLiteral(raw);
|
|
310
|
+
if (v !== undefined) return v;
|
|
311
|
+
if (typeof raw === "string" && raw === "") return false;
|
|
312
|
+
if (raw === undefined || raw === null) return DEFAULTS.readOnly;
|
|
313
|
+
return failClosed(raw);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** One-line startup/doctor summary for unparseable config values (issue
|
|
317
|
+
* #23). The toast points at /agy doctor because the per-value detail
|
|
318
|
+
* (label, raw value, fallback) lives in the parseWarnings row list. */
|
|
319
|
+
export function configWarningsMessage(warnings: string[]): string {
|
|
320
|
+
return `config.json: ${warnings.length} unparseable value${warnings.length === 1 ? "" : "s"} fell back to defaults (readOnly fails closed); run /agy doctor for details.`;
|
|
321
|
+
}
|
|
322
|
+
|
|
264
323
|
/** Read the raw config file (no defaults, no env). Shared by loadConfig and
|
|
265
324
|
* saveConfig so persisted writes can never bake env overrides into the file. */
|
|
266
325
|
function readConfigFile(configPath: string): Partial<AgyConfig> {
|
|
@@ -285,15 +344,14 @@ export function removeLegacyAcpBin(configFile: string = configPath()): boolean {
|
|
|
285
344
|
const acp = file.acp as Record<string, unknown>;
|
|
286
345
|
if (!("bin" in acp)) return false;
|
|
287
346
|
delete acp.bin;
|
|
288
|
-
|
|
289
|
-
// write through the resolved target so the link survives.
|
|
290
|
-
writeConfigJson(fs.realpathSync(configFile), file);
|
|
347
|
+
writeJsonAtomic(configFile, file);
|
|
291
348
|
return true;
|
|
292
349
|
}
|
|
293
350
|
|
|
294
351
|
/** Load config merged over defaults. Env vars override the file when set. */
|
|
295
352
|
export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
296
353
|
let file: Partial<AgyConfig> = readConfigFile(configFile);
|
|
354
|
+
const parseWarnings: string[] = [];
|
|
297
355
|
|
|
298
356
|
// Env overrides file (matches the skipPermissions pattern).
|
|
299
357
|
// The naive OR `env === "plan" || file.mode === "plan"` would ignore an
|
|
@@ -323,7 +381,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
323
381
|
const skipPermissions =
|
|
324
382
|
envPerm !== undefined
|
|
325
383
|
? envPerm === "1" || envPerm.toLowerCase() === "true"
|
|
326
|
-
: file.skipPermissions
|
|
384
|
+
: parseBoolish(file.skipPermissions, "skipPermissions", DEFAULTS.skipPermissions, parseWarnings);
|
|
327
385
|
|
|
328
386
|
const envReadOnly = process.env.AGY_READONLY;
|
|
329
387
|
// Fail-closed parse for a safety knob: empty string means the user
|
|
@@ -334,7 +392,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
334
392
|
? envReadOnly === ""
|
|
335
393
|
? false
|
|
336
394
|
: !["0", "false", "off"].includes(envReadOnly.trim().toLowerCase())
|
|
337
|
-
: file.readOnly
|
|
395
|
+
: parseReadOnlyValue(file.readOnly, parseWarnings);
|
|
338
396
|
|
|
339
397
|
const defaultModelRaw =
|
|
340
398
|
process.env.AGY_DEFAULT_MODEL ?? file.defaultModel ?? DEFAULTS.defaultModel;
|
|
@@ -342,19 +400,19 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
342
400
|
typeof defaultModelRaw === "string" ? defaultModelRaw.trim() || DEFAULTS.defaultModel : DEFAULTS.defaultModel;
|
|
343
401
|
|
|
344
402
|
const envThink = process.env.AGY_DEFAULT_THINKING;
|
|
345
|
-
const thinkRaw = (envThink ?? file.defaultThinking ?? DEFAULTS.defaultThinking).toLowerCase();
|
|
403
|
+
const thinkRaw = String(envThink ?? file.defaultThinking ?? DEFAULTS.defaultThinking).toLowerCase();
|
|
346
404
|
const defaultThinking: ThinkingTier =
|
|
347
405
|
thinkRaw === "low" || thinkRaw === "high" ? thinkRaw : "medium";
|
|
348
406
|
|
|
349
407
|
const askTool = process.env.AGY_ASK_TOOL !== undefined
|
|
350
408
|
? ["1", "true", "on"].includes(process.env.AGY_ASK_TOOL.toLowerCase())
|
|
351
|
-
: file.askTool
|
|
409
|
+
: parseBoolish(file.askTool, "askTool", DEFAULTS.askTool, parseWarnings);
|
|
352
410
|
|
|
353
411
|
const webTools = process.env.AGY_WEB_TOOLS !== undefined
|
|
354
412
|
? ["1", "true", "on"].includes(process.env.AGY_WEB_TOOLS.toLowerCase())
|
|
355
|
-
: file.webTools
|
|
413
|
+
: parseBoolish(file.webTools, "webTools", DEFAULTS.webTools, parseWarnings);
|
|
356
414
|
|
|
357
|
-
const bridgeRaw = (process.env.AGY_BRIDGE_TOOLS ?? file.bridgeTools ?? DEFAULTS.bridgeTools).toLowerCase();
|
|
415
|
+
const bridgeRaw = String(process.env.AGY_BRIDGE_TOOLS ?? file.bridgeTools ?? DEFAULTS.bridgeTools).toLowerCase();
|
|
358
416
|
const bridgeTools: BridgeTools =
|
|
359
417
|
bridgeRaw === "none" || bridgeRaw === "all" || bridgeRaw === "mcp"
|
|
360
418
|
? bridgeRaw
|
|
@@ -376,12 +434,12 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
376
434
|
|
|
377
435
|
const digest = process.env.AGY_DIGEST !== undefined
|
|
378
436
|
? ["1", "true", "on"].includes(process.env.AGY_DIGEST.toLowerCase())
|
|
379
|
-
: file.digest
|
|
437
|
+
: parseBoolish(file.digest, "digest", DEFAULTS.digest, parseWarnings);
|
|
380
438
|
|
|
381
439
|
const envSys = process.env.AGY_SYSTEM_PROMPT;
|
|
382
440
|
const systemPrompt = envSys !== undefined
|
|
383
441
|
? ["1", "true", "on"].includes(envSys.toLowerCase())
|
|
384
|
-
: file.systemPrompt
|
|
442
|
+
: parseBoolish(file.systemPrompt, "systemPrompt", DEFAULTS.systemPrompt, parseWarnings);
|
|
385
443
|
|
|
386
444
|
// Turn caps, minutes. Env wins over the file (same pattern as mode).
|
|
387
445
|
const turnTimeoutMin = parseCapMinutes(
|
|
@@ -395,12 +453,12 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
395
453
|
|
|
396
454
|
// Approval gate (docs/TODO.md 2.5). Unknown values fall back to "auto"
|
|
397
455
|
// so a typo can never silently force the gate on.
|
|
398
|
-
const gateRaw = (process.env.AGY_APPROVALS ?? file.approvals?.gateMode ?? DEFAULTS.approvals.gateMode).toLowerCase();
|
|
456
|
+
const gateRaw = String(process.env.AGY_APPROVALS ?? file.approvals?.gateMode ?? DEFAULTS.approvals.gateMode).toLowerCase();
|
|
399
457
|
const gateMode: GateMode =
|
|
400
458
|
gateRaw === "shadow" || gateRaw === "dedicated" || gateRaw === "off"
|
|
401
459
|
? gateRaw
|
|
402
460
|
: "auto";
|
|
403
|
-
const askRaw = (process.env.AGY_APPROVALS_MODE ?? file.approvals?.mode ?? DEFAULTS.approvals.mode).toLowerCase();
|
|
461
|
+
const askRaw = String(process.env.AGY_APPROVALS_MODE ?? file.approvals?.mode ?? DEFAULTS.approvals.mode).toLowerCase();
|
|
404
462
|
const gateAskMode: GateAskMode =
|
|
405
463
|
askRaw === "allow" || askRaw === "deny"
|
|
406
464
|
? askRaw
|
|
@@ -421,13 +479,14 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
421
479
|
const envSessionRetry = process.env.AGY_ACP_SESSION_RETRY;
|
|
422
480
|
const sessionRetryOnTimeout = envSessionRetry !== undefined
|
|
423
481
|
? ["1", "true", "on"].includes(envSessionRetry.toLowerCase())
|
|
424
|
-
: fileAcp.sessionRetryOnTimeout
|
|
482
|
+
: parseBoolish(fileAcp.sessionRetryOnTimeout, "acp.sessionRetryOnTimeout", DEFAULTS.acp.sessionRetryOnTimeout, parseWarnings);
|
|
425
483
|
const acp: AcpConfig = { usageEstimate, sessionTimeoutMs, sessionRetryOnTimeout };
|
|
426
484
|
|
|
427
485
|
// Custom agent for stream-json turns (--agent). Env wins over the file
|
|
428
486
|
// (same pattern as mode). Normalized (trim/cap/control-strip); an empty
|
|
429
487
|
// result means agy's default agent.
|
|
430
|
-
const
|
|
488
|
+
const agentRaw: unknown = process.env.AGY_AGENT ?? file.agent;
|
|
489
|
+
const agent = normalizeAgyAgentName(typeof agentRaw === "string" ? agentRaw : undefined);
|
|
431
490
|
|
|
432
491
|
return {
|
|
433
492
|
engine,
|
|
@@ -448,6 +507,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
448
507
|
agent,
|
|
449
508
|
approvals: { gateMode, mode: gateAskMode },
|
|
450
509
|
patchCleanupNotified: file.patchCleanupNotified === true,
|
|
510
|
+
parseWarnings: parseWarnings.length > 0 ? parseWarnings : undefined,
|
|
451
511
|
};
|
|
452
512
|
}
|
|
453
513
|
|
|
@@ -459,31 +519,13 @@ function narrowEngine(raw: string): Engine {
|
|
|
459
519
|
return raw === "acp" || raw === "stream-json" ? raw : DEFAULT_ENGINE;
|
|
460
520
|
}
|
|
461
521
|
|
|
462
|
-
/** Atomic JSON write (temp + rename, 0600) shared by every config writer. */
|
|
463
|
-
function writeConfigJson(configPath: string, value: unknown): void {
|
|
464
|
-
const dir = path.dirname(configPath);
|
|
465
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
466
|
-
const tmp = `${configPath}.${process.pid}.tmp`;
|
|
467
|
-
try {
|
|
468
|
-
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + "\n", { mode: 0o600 });
|
|
469
|
-
fs.renameSync(tmp, configPath);
|
|
470
|
-
} catch (err) {
|
|
471
|
-
try {
|
|
472
|
-
fs.unlinkSync(tmp);
|
|
473
|
-
} catch {
|
|
474
|
-
/* nothing to clean */
|
|
475
|
-
}
|
|
476
|
-
throw err;
|
|
477
|
-
}
|
|
478
|
-
}
|
|
479
|
-
|
|
480
522
|
/** Atomically persist a config patch (temp + rename). Merges onto the RAW
|
|
481
523
|
* FILE values, never loadConfig(): env overrides must not be baked into the
|
|
482
524
|
* file (AGY_READONLY=1 in the env would otherwise persist readOnly: true to
|
|
483
525
|
* disk on any unrelated save, outliving the env var). Nested objects are
|
|
484
526
|
* re-normalized to their known keys: a raw passthrough would resurrect
|
|
485
527
|
* legacy keys (acp.permissions) that loadConfig normalization drops. */
|
|
486
|
-
export type ConfigPatch = Partial<Omit<AgyConfig, "acp">> & { acp?: Partial<AcpConfig> };
|
|
528
|
+
export type ConfigPatch = Partial<Omit<AgyConfig, "acp" | "parseWarnings">> & { acp?: Partial<AcpConfig> };
|
|
487
529
|
|
|
488
530
|
export function saveConfig(patch: ConfigPatch, configFile: string = configPath()): AgyConfig {
|
|
489
531
|
const file = readConfigFile(configFile);
|
|
@@ -506,10 +548,22 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
|
|
|
506
548
|
patchAcp?.sessionTimeoutMs ?? fileAcp.sessionTimeoutMs,
|
|
507
549
|
DEFAULTS.acp.sessionTimeoutMs,
|
|
508
550
|
),
|
|
509
|
-
|
|
551
|
+
// Silent literal-grammar pass-through (saveConfig has no warning
|
|
552
|
+
// channel; loadConfig already reports junk at startup / /agy doctor).
|
|
553
|
+
sessionRetryOnTimeout:
|
|
554
|
+
patchAcp?.sessionRetryOnTimeout
|
|
555
|
+
?? parseBoolishLiteral(fileAcp.sessionRetryOnTimeout)
|
|
556
|
+
?? DEFAULTS.acp.sessionRetryOnTimeout,
|
|
510
557
|
};
|
|
511
|
-
|
|
512
|
-
|
|
558
|
+
// The DEFAULTS 0 is a load-time placeholder (defaultTurnTimeoutMin resolves
|
|
559
|
+
// per TTY state); persisting it would flip absence into "cap disabled"
|
|
560
|
+
// (parseCapMinutes reads 0 as off) on the next load.
|
|
561
|
+
const { turnTimeoutMin: _placeholder, ...defaultsOnDisk } = DEFAULTS;
|
|
562
|
+
// On-disk shape, not AgyConfig: turnTimeoutMin is written only when the
|
|
563
|
+
// file or the patch carries it, and a blanket cast would drop checking
|
|
564
|
+
// for every other key in the literal.
|
|
565
|
+
const next: Omit<AgyConfig, "turnTimeoutMin"> & Partial<Pick<AgyConfig, "turnTimeoutMin">> = {
|
|
566
|
+
...defaultsOnDisk,
|
|
513
567
|
...file,
|
|
514
568
|
...(file.approvals !== undefined
|
|
515
569
|
? { approvals: { gateMode: fileApprovals.gateMode ?? DEFAULTS.approvals.gateMode, mode: fileApprovals.mode ?? DEFAULTS.approvals.mode } }
|
|
@@ -517,7 +571,9 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
|
|
|
517
571
|
...restPatch,
|
|
518
572
|
acp: mergedAcp,
|
|
519
573
|
engine: narrowEngine(String(persistedEngine).toLowerCase()),
|
|
574
|
+
// Computed per load; a raw file spread must never persist it.
|
|
575
|
+
parseWarnings: undefined,
|
|
520
576
|
};
|
|
521
|
-
|
|
522
|
-
return next;
|
|
577
|
+
writeJsonAtomic(configFile, next);
|
|
578
|
+
return next as AgyConfig;
|
|
523
579
|
}
|
package/src/mcp-registration.ts
CHANGED
|
@@ -19,6 +19,7 @@ import fs from "node:fs";
|
|
|
19
19
|
import os from "node:os";
|
|
20
20
|
import path from "node:path";
|
|
21
21
|
import { extensionsDataDir } from "./config.js";
|
|
22
|
+
import { writeJsonAtomic } from "./atomic-write.js";
|
|
22
23
|
|
|
23
24
|
/** Name convention for the bridge's per-pid server entries. */
|
|
24
25
|
export function bridgeServerName(pid: number): string {
|
|
@@ -70,10 +71,7 @@ function writeConfig(file: string, config: McpConfig): void {
|
|
|
70
71
|
// 0700/0600: the file carries the bridge's shared-secret token in its
|
|
71
72
|
// headers, and it lives in the USER'S global agy config (audit 2026-09-07:
|
|
72
73
|
// it previously landed at the umask default, typically world-readable).
|
|
73
|
-
|
|
74
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
75
|
-
fs.writeFileSync(tmp, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 });
|
|
76
|
-
fs.renameSync(tmp, file);
|
|
74
|
+
writeJsonAtomic(file, config, { dirMode: 0o700 });
|
|
77
75
|
}
|
|
78
76
|
|
|
79
77
|
/** The canonical mcp_config.json entry shape for a bridge server. Single
|
|
@@ -205,10 +203,7 @@ function readSuppressionMarker(file: string): SuppressionMarker {
|
|
|
205
203
|
}
|
|
206
204
|
|
|
207
205
|
function writeSuppressionMarker(file: string, marker: SuppressionMarker): void {
|
|
208
|
-
|
|
209
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
210
|
-
fs.writeFileSync(tmp, JSON.stringify(marker, null, 2) + "\n", { mode: 0o600 });
|
|
211
|
-
fs.renameSync(tmp, file);
|
|
206
|
+
writeJsonAtomic(file, marker, { dirMode: 0o700 });
|
|
212
207
|
}
|
|
213
208
|
|
|
214
209
|
function delegatorLive(pid: string, entry: { since?: number } | undefined, isAlive: (pid: number) => boolean, now: number): boolean {
|
package/src/mcp-server.ts
CHANGED
|
@@ -8,8 +8,8 @@
|
|
|
8
8
|
// Hardening:
|
|
9
9
|
// - The whole request handler is wrapped so a client error (ECONNRESET on a
|
|
10
10
|
// killed-mid-call agy) can never crash the pi process.
|
|
11
|
-
// - Per-process config dir (agy-mcp-<pid>)
|
|
12
|
-
//
|
|
11
|
+
// - Per-process config dir (agy-mcp-<pid>) and one realm-shared HTTP listener
|
|
12
|
+
// with per-session route tokens: concurrent sessions stay isolated.
|
|
13
13
|
// - Shared-secret header: agy sends it from the config; a browser cannot set a
|
|
14
14
|
// custom header on a simple cross-origin POST, so this blocks CSRF against
|
|
15
15
|
// the loopback server. Combined with 127.0.0.1 binding.
|
|
@@ -82,6 +82,10 @@ export interface McpServerHandle {
|
|
|
82
82
|
token: string;
|
|
83
83
|
/** Approval-gate park controls (docs/TODO.md 2.5). */
|
|
84
84
|
approvals: ApprovalParkApi;
|
|
85
|
+
/** Serve another bridge surface on this listener behind its own token.
|
|
86
|
+
* Requests carrying that token reach `deps`; requests carrying `token`
|
|
87
|
+
* keep reaching the deps passed to startMcpServer. remove() revokes it. */
|
|
88
|
+
addRoute: (deps: McpBridgeDeps) => { token: string; remove: () => void };
|
|
85
89
|
close: () => Promise<void>;
|
|
86
90
|
}
|
|
87
91
|
|
|
@@ -286,18 +290,26 @@ export async function startMcpServer(
|
|
|
286
290
|
log?: (s: string, d?: unknown) => void;
|
|
287
291
|
/** Test override for the per-park timeout (deny, fail closed). */
|
|
288
292
|
approvalTimeoutMs?: number;
|
|
293
|
+
/** Write the add-dir `.agents/mcp_config.json` carrying `token` (default
|
|
294
|
+
* true). The shared realm listener sets this false so each session
|
|
295
|
+
* reaches it on its own route token. */
|
|
296
|
+
addDirConfig?: boolean;
|
|
289
297
|
} = {},
|
|
290
298
|
): Promise<McpStartResult> {
|
|
291
299
|
const log = opts.log ?? (() => {});
|
|
292
300
|
const approvalTimeoutMs = opts.approvalTimeoutMs ?? APPROVAL_PARK_TIMEOUT_MS;
|
|
293
301
|
|
|
294
|
-
const listHandler = async () => {
|
|
295
|
-
const tools =
|
|
302
|
+
const listHandler = async (surface: McpBridgeDeps) => {
|
|
303
|
+
const tools = surface.listTools();
|
|
296
304
|
log("list-tools", { count: tools.length });
|
|
297
305
|
return { tools };
|
|
298
306
|
};
|
|
299
307
|
|
|
300
|
-
const callHandler = async (
|
|
308
|
+
const callHandler = async (
|
|
309
|
+
surface: McpBridgeDeps,
|
|
310
|
+
request: { params: { name: string; arguments?: unknown } },
|
|
311
|
+
signal?: AbortSignal,
|
|
312
|
+
) => {
|
|
301
313
|
const { name, arguments: args } = request.params;
|
|
302
314
|
// Progress probe: agy's MCP client killed long bridge calls at exactly
|
|
303
315
|
// ~180s (see ACP-PROTOCOL-REFERENCE). If its requests ever carry a
|
|
@@ -310,7 +322,7 @@ export async function startMcpServer(
|
|
|
310
322
|
const callId = crypto.randomUUID();
|
|
311
323
|
log("call-tool", { name, callId });
|
|
312
324
|
try {
|
|
313
|
-
const r = await
|
|
325
|
+
const r = await surface.onToolCall(
|
|
314
326
|
callId,
|
|
315
327
|
name,
|
|
316
328
|
(args && typeof args === "object" ? args : {}) as Record<string, unknown>,
|
|
@@ -327,13 +339,13 @@ export async function startMcpServer(
|
|
|
327
339
|
}
|
|
328
340
|
};
|
|
329
341
|
|
|
330
|
-
const makeServer = (signal: AbortSignal) => {
|
|
342
|
+
const makeServer = (surface: McpBridgeDeps, signal: AbortSignal) => {
|
|
331
343
|
const s = new Server(
|
|
332
344
|
{ name: "pi-antigravity-bridge", version: "1.1.0" },
|
|
333
345
|
{ capabilities: { tools: {} } },
|
|
334
346
|
);
|
|
335
|
-
s.setRequestHandler(ListToolsRequestSchema, listHandler);
|
|
336
|
-
s.setRequestHandler(CallToolRequestSchema, (request) => callHandler(request, signal));
|
|
347
|
+
s.setRequestHandler(ListToolsRequestSchema, () => listHandler(surface));
|
|
348
|
+
s.setRequestHandler(CallToolRequestSchema, (request) => callHandler(surface, request, signal));
|
|
337
349
|
return s;
|
|
338
350
|
};
|
|
339
351
|
|
|
@@ -371,13 +383,19 @@ export async function startMcpServer(
|
|
|
371
383
|
res.writeHead(200, { "content-type": "application/json" });
|
|
372
384
|
res.end(decisionBody({ allow: false, reason }));
|
|
373
385
|
};
|
|
374
|
-
|
|
386
|
+
// Extra surfaces (addRoute): token -> deps. The handle token keeps serving
|
|
387
|
+
// the deps passed in, so a single-surface caller sees no change.
|
|
388
|
+
const routes = new Map<string, McpBridgeDeps>();
|
|
389
|
+
const sameToken = (received: string, expected: string): boolean =>
|
|
390
|
+
received.length === expected.length && crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected));
|
|
391
|
+
const surfaceFor = (req: http.IncomingMessage): McpBridgeDeps | null => {
|
|
375
392
|
const received = req.headers[TOKEN_HEADER];
|
|
376
|
-
return
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
393
|
+
if (typeof received !== "string") return null;
|
|
394
|
+
if (sameToken(received, token)) return deps;
|
|
395
|
+
for (const [routeToken, routeDeps] of routes) {
|
|
396
|
+
if (sameToken(received, routeToken)) return routeDeps;
|
|
397
|
+
}
|
|
398
|
+
return null;
|
|
381
399
|
};
|
|
382
400
|
const readBody = async (req: http.IncomingMessage): Promise<string | null> => {
|
|
383
401
|
let body = "";
|
|
@@ -394,7 +412,8 @@ export async function startMcpServer(
|
|
|
394
412
|
res: http.ServerResponse,
|
|
395
413
|
route: string,
|
|
396
414
|
): Promise<void> => {
|
|
397
|
-
|
|
415
|
+
const surface = surfaceFor(req);
|
|
416
|
+
if (!surface) {
|
|
398
417
|
log("unauthorized", { url: req.url });
|
|
399
418
|
res.writeHead(403, { "content-type": "application/json" }).end('{"error":"forbidden"}');
|
|
400
419
|
return;
|
|
@@ -425,7 +444,7 @@ export async function startMcpServer(
|
|
|
425
444
|
denyDirect(res, `tool ${payload.toolCall.name} is not in the approval matcher set`);
|
|
426
445
|
return;
|
|
427
446
|
}
|
|
428
|
-
if (typeof
|
|
447
|
+
if (typeof surface.onApproval !== "function") {
|
|
429
448
|
log("approval-unwired", { name: payload.toolCall.name });
|
|
430
449
|
denyDirect(res, "approval gate is not wired; denying");
|
|
431
450
|
return;
|
|
@@ -438,10 +457,11 @@ export async function startMcpServer(
|
|
|
438
457
|
settlePark(ticket, { allow: false, reason: `approval gate timed out after ${Math.round(approvalTimeoutMs / 1000)}s` });
|
|
439
458
|
log("approval-timeout", { ticket, name: payload.toolCall.name });
|
|
440
459
|
}, approvalTimeoutMs);
|
|
460
|
+
timer.unref();
|
|
441
461
|
parks.set(ticket, { name: payload.toolCall.name, since: Date.now(), timer });
|
|
442
462
|
log("approval-parked", { ticket, name: payload.toolCall.name });
|
|
443
463
|
try {
|
|
444
|
-
|
|
464
|
+
surface.onApproval(ticket, payload);
|
|
445
465
|
} catch (e) {
|
|
446
466
|
// A throwing provider must never hang the hook: settle deny now.
|
|
447
467
|
log("approval-onapproval-fail", { ticket, msg: e instanceof Error ? e.message : String(e) });
|
|
@@ -501,7 +521,8 @@ export async function startMcpServer(
|
|
|
501
521
|
}
|
|
502
522
|
// #3: require the shared-secret header. Constant-time compare so a
|
|
503
523
|
// timing oracle can't recover the token byte-by-byte.
|
|
504
|
-
|
|
524
|
+
const surface = surfaceFor(req);
|
|
525
|
+
if (!surface) {
|
|
505
526
|
log("unauthorized", { url: req.url });
|
|
506
527
|
res.writeHead(403, { "content-type": "application/json" }).end('{"error":"forbidden"}');
|
|
507
528
|
return;
|
|
@@ -551,7 +572,7 @@ export async function startMcpServer(
|
|
|
551
572
|
// Stateless: a fresh transport+server per request.
|
|
552
573
|
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
553
574
|
transport.onerror = (e: Error) => log("transport-error", e.message);
|
|
554
|
-
const server = makeServer(ac.signal);
|
|
575
|
+
const server = makeServer(surface, ac.signal);
|
|
555
576
|
await server.connect(transport);
|
|
556
577
|
await transport.handleRequest(req, res, parsed as object);
|
|
557
578
|
} catch (e) {
|
|
@@ -582,8 +603,10 @@ export async function startMcpServer(
|
|
|
582
603
|
return;
|
|
583
604
|
}
|
|
584
605
|
try {
|
|
585
|
-
|
|
586
|
-
|
|
606
|
+
if (opts.addDirConfig !== false) {
|
|
607
|
+
writeBridgeMcpConfig(port, token);
|
|
608
|
+
log("bridge-config-written", { port, path: bridgeMcpConfigPath() });
|
|
609
|
+
}
|
|
587
610
|
} catch (e) {
|
|
588
611
|
log("bridge-config-write-failed", e instanceof Error ? e.message : String(e));
|
|
589
612
|
}
|
|
@@ -598,6 +621,11 @@ export async function startMcpServer(
|
|
|
598
621
|
port,
|
|
599
622
|
token,
|
|
600
623
|
approvals: approvalsApi,
|
|
624
|
+
addRoute: (routeDeps) => {
|
|
625
|
+
const routeToken = crypto.randomBytes(24).toString("hex");
|
|
626
|
+
routes.set(routeToken, routeDeps);
|
|
627
|
+
return { token: routeToken, remove: () => void routes.delete(routeToken) };
|
|
628
|
+
},
|
|
601
629
|
close: async () => {
|
|
602
630
|
// Pending approvals fail closed on shutdown: the hook gets a
|
|
603
631
|
// terminal deny instead of a 404 on its next poll.
|
|
@@ -605,7 +633,10 @@ export async function startMcpServer(
|
|
|
605
633
|
if (p.terminal) continue;
|
|
606
634
|
settlePark(ticket, { allow: false, reason: "approval gate bridge shut down" });
|
|
607
635
|
}
|
|
608
|
-
|
|
636
|
+
routes.clear();
|
|
637
|
+
const closed = new Promise<void>((r) => httpServer.close(() => r()));
|
|
638
|
+
httpServer.closeAllConnections?.();
|
|
639
|
+
await closed;
|
|
609
640
|
removeBridgeMcpConfig();
|
|
610
641
|
disposeExitCleanup();
|
|
611
642
|
log("bridge-config-removed", { port });
|
package/src/native-tools.ts
CHANGED
|
@@ -57,6 +57,8 @@ export function mapAgyToolToNative(
|
|
|
57
57
|
args: Record<string, unknown>,
|
|
58
58
|
): NativeToolCall | undefined {
|
|
59
59
|
switch (tool) {
|
|
60
|
+
// agy 1.5.14 renamed view_file to read_file (same Path/StartLine/EndLine args).
|
|
61
|
+
case "read_file":
|
|
60
62
|
case "view_file": {
|
|
61
63
|
if (!onlyKeys(args, [...VIEW_PATH_KEYS, ...START_LINE_KEYS, ...END_LINE_KEYS])) {
|
|
62
64
|
return undefined;
|