@herbertgao/pi-extensions 2026.11.18 → 2026.11.20
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 +18 -0
- package/README.md +5 -5
- package/THIRD_PARTY_NOTICES.md +3 -24
- package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
- package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
- package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
- package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
- package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
- package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
- package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
- package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
- package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
- package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
- package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
- package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
- package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
- package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
- package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
- package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
- package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
- package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
- package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
- package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
- package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
- package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
- package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
- package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
- package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
- package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
- package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
- package/node_modules/pi-commandcode-provider/README.md +3 -2
- package/node_modules/pi-commandcode-provider/index.ts +120 -13
- package/node_modules/pi-commandcode-provider/package.json +4 -3
- package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
- package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
- package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
- package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
- package/node_modules/pi-typesafe/README.md +1 -1
- package/node_modules/pi-typesafe/dist/ask.js +6 -3
- package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
- package/node_modules/pi-typesafe/dist/auth.js +159 -55
- package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
- package/node_modules/pi-typesafe/dist/batch.js +62 -22
- package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
- package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
- package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
- package/node_modules/pi-typesafe/dist/client.js +67 -27
- package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
- package/node_modules/pi-typesafe/dist/errors.js +105 -2
- package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
- package/node_modules/pi-typesafe/dist/extension.js +206 -106
- package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
- package/node_modules/pi-typesafe/dist/index.js +3 -3
- package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
- package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
- package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
- package/node_modules/pi-typesafe/dist/login.js +167 -13
- package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
- package/node_modules/pi-typesafe/dist/schema.js +47 -13
- package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
- package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
- package/node_modules/pi-typesafe/dist/usage.js +79 -40
- package/node_modules/pi-typesafe/package.json +3 -3
- package/package.json +12 -15
- package/node_modules/pi-antigravity/README.md +0 -298
- package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
- package/node_modules/pi-antigravity/package.json +0 -87
- package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
- package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
- package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
- package/node_modules/pi-antigravity/src/client/client.ts +0 -602
- package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
- package/node_modules/pi-antigravity/src/client/index.ts +0 -2
- package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
- package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
- package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
- package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
- package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
- package/node_modules/pi-antigravity/src/image/image.ts +0 -427
- package/node_modules/pi-antigravity/src/image/index.ts +0 -1
- package/node_modules/pi-antigravity/src/image/native.ts +0 -69
- package/node_modules/pi-antigravity/src/index.ts +0 -547
- package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
- package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
- package/node_modules/pi-antigravity/src/models/index.ts +0 -3
- package/node_modules/pi-antigravity/src/models/models.ts +0 -647
- package/node_modules/pi-antigravity/src/search/index.ts +0 -1
- package/node_modules/pi-antigravity/src/search/search.ts +0 -967
- package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
- package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
- package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
- package/node_modules/pi-antigravity/src/types/index.ts +0 -2
- package/node_modules/pi-antigravity/src/types/types.ts +0 -329
- package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
- package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
- package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
- package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
- package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
- package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
- package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
- package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
- package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
- package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
- package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
- package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
- package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
- package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
- package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
- package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
- package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
- package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
- package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
- package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
- package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
- package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
- package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
- package/node_modules/pi-antigravity/tsconfig.json +0 -21
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
// Capability-gated MCP server: exposes pi's tools to agy over Streamable HTTP.
|
|
2
|
+
//
|
|
3
|
+
// agy reads .agents/mcp_config.json from its --add-dir directories (verified),
|
|
4
|
+
// NOT from cwd. So we write our config into a bridge-controlled dir and the
|
|
5
|
+
// provider passes that dir as an EXTRA --add-dir. AskAntigravity omits it, so
|
|
6
|
+
// its agy starts plain. The user's global agy config is never touched.
|
|
7
|
+
//
|
|
8
|
+
// Hardening:
|
|
9
|
+
// - The whole request handler is wrapped so a client error (ECONNRESET on a
|
|
10
|
+
// killed-mid-call agy) can never crash the pi process.
|
|
11
|
+
// - Per-process config dir (agy-mcp-<pid>): concurrent pi sessions each own
|
|
12
|
+
// their file; no shared-file race, no cross-session routing.
|
|
13
|
+
// - Shared-secret header: agy sends it from the config; a browser cannot set a
|
|
14
|
+
// custom header on a simple cross-origin POST, so this blocks CSRF against
|
|
15
|
+
// the loopback server. Combined with 127.0.0.1 binding.
|
|
16
|
+
// - Request body size cap.
|
|
17
|
+
//
|
|
18
|
+
// The bridge routes calls through the provider's toolUse round-trip; it
|
|
19
|
+
// needs no privileged pi API.
|
|
20
|
+
|
|
21
|
+
import http from "node:http";
|
|
22
|
+
import fs from "node:fs";
|
|
23
|
+
import path from "node:path";
|
|
24
|
+
import crypto from "node:crypto";
|
|
25
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
26
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
27
|
+
import {
|
|
28
|
+
CallToolRequestSchema,
|
|
29
|
+
ListToolsRequestSchema,
|
|
30
|
+
LATEST_PROTOCOL_VERSION,
|
|
31
|
+
SUPPORTED_PROTOCOL_VERSIONS,
|
|
32
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
33
|
+
import { GATED_AGY_TOOL_SET } from "./approval-hook.js";
|
|
34
|
+
import { bridgeDir } from "./config.js";
|
|
35
|
+
|
|
36
|
+
/** Tools we do NOT expose to agy: it would just error (the provider is already
|
|
37
|
+
* antigravity, so the tool's own guard refuses; advertising it is noise). */
|
|
38
|
+
const SKIP_CIRCULAR = new Set(["AskAntigravity"]);
|
|
39
|
+
|
|
40
|
+
const BRIDGE_MCP_KEY = "pi-antigravity-bridge";
|
|
41
|
+
/** Shared-secret header every bridge request must carry. Exported: the ACP
|
|
42
|
+
* engine's mcpServers registration needs the same header name (the stream
|
|
43
|
+
* engine gets it via .agents/mcp_config.json; ACP gets it via headers[]). */
|
|
44
|
+
export const TOKEN_HEADER = "x-bridge-token";
|
|
45
|
+
const MAX_BODY_BYTES = 1_000_000;
|
|
46
|
+
|
|
47
|
+
// --- approval gate (docs/TODO.md 2.5) ---------------------------------------
|
|
48
|
+
|
|
49
|
+
/** stdin JSON of a PreToolUse hook, forwarded verbatim by the bundled poll
|
|
50
|
+
* script. Only toolCall is load-bearing here. */
|
|
51
|
+
export interface ApprovalPayload {
|
|
52
|
+
toolCall: { name: string; args: Record<string, unknown> };
|
|
53
|
+
stepIdx?: number;
|
|
54
|
+
conversationId?: string;
|
|
55
|
+
[key: string]: unknown;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Terminal decision for a parked approval (mirrors GateDecision from
|
|
59
|
+
* approval-gate.ts; deny MUST carry a reason - it is the only feedback
|
|
60
|
+
* agy's model gets, see V2). */
|
|
61
|
+
export type ApprovalDecision = { allow: true } | { allow: false; reason: string };
|
|
62
|
+
|
|
63
|
+
/** Provider-facing park controls: ticket verification for the shadow tools'
|
|
64
|
+
* marker calls, and completion when pi's tool result maps to a decision. */
|
|
65
|
+
export interface ApprovalParkApi {
|
|
66
|
+
/** True while the ticket is still parked (unanswered, unexpired). */
|
|
67
|
+
has(ticket: string): boolean;
|
|
68
|
+
/** Settle a ticket. False when the id is unknown or already terminal. */
|
|
69
|
+
resolve(ticket: string, decision: ApprovalDecision): boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Human-decision latency budget for one parked approval. The staged hook
|
|
73
|
+
* timeout (approval-hook.stagedTimeoutSeconds) exceeds this with margin:
|
|
74
|
+
* a timed-out hook soft-passes (V3), so the park must time out FIRST and
|
|
75
|
+
* print a deny. Mirrors the G9 park budget. */
|
|
76
|
+
export const APPROVAL_PARK_TIMEOUT_MS = 480_000;
|
|
77
|
+
|
|
78
|
+
export interface McpServerHandle {
|
|
79
|
+
port: number;
|
|
80
|
+
/** Shared secret for TOKEN_HEADER. Callers that register the bridge with
|
|
81
|
+
* an engine other than the stream-json discovery file need it. */
|
|
82
|
+
token: string;
|
|
83
|
+
/** Approval-gate park controls (docs/TODO.md 2.5). */
|
|
84
|
+
approvals: ApprovalParkApi;
|
|
85
|
+
close: () => Promise<void>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface McpStartResult {
|
|
89
|
+
ok: boolean;
|
|
90
|
+
port?: number;
|
|
91
|
+
handle?: McpServerHandle;
|
|
92
|
+
reason?: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Provider-owned bridge surface. The provider builds the tool catalog
|
|
96
|
+
* (config-filtered: none|mcp|all + skills) and owns the toolUse round-trip:
|
|
97
|
+
* onToolCall parks the call, ends the pi assistant message with stopReason
|
|
98
|
+
* "toolUse" for the REAL pi tool, and resolves when pi hands back the
|
|
99
|
+
* toolResult on the next stream call. Fail-closed: the provider enforces a
|
|
100
|
+
* 480s timeout and rejects when no agy turn is active. */
|
|
101
|
+
export interface McpBridgeDeps {
|
|
102
|
+
listTools(): Array<{ name: string; description: string; inputSchema: object }>;
|
|
103
|
+
onToolCall(
|
|
104
|
+
callId: string,
|
|
105
|
+
name: string,
|
|
106
|
+
args: Record<string, unknown>,
|
|
107
|
+
signal: AbortSignal,
|
|
108
|
+
): Promise<import("./provider.js").BridgeCallResultShape>;
|
|
109
|
+
/** Approval gate: called once per parked POST /approval, right after the
|
|
110
|
+
* early-ack. The provider interrupts the pi-side view of the agy turn and
|
|
111
|
+
* emits the shadow toolUse; the decision returns via approvals.resolve.
|
|
112
|
+
* Optional: absent = every approval POST is denied directly (fail closed). */
|
|
113
|
+
onApproval?(ticket: string, payload: ApprovalPayload): void;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Clamp an unsupported MCP-Protocol-Version header down to the SDK's LATEST.
|
|
117
|
+
*
|
|
118
|
+
* agy negotiates a protocol version newer than this SDK ships (e.g. 2026-07-28
|
|
119
|
+
* vs LATEST 2025-11-25). initialize is exempt from the transport's header
|
|
120
|
+
* check, and the SDK's initialize handler already downgrades the body version
|
|
121
|
+
* itself, but EVERY follow-up (tools/list, tools/call,
|
|
122
|
+
* notifications/initialized) is validated against the header -> 400 +
|
|
123
|
+
* transport-error. This server is stateless (a fresh transport per request),
|
|
124
|
+
* so it cannot track the negotiated version across requests; rewriting any
|
|
125
|
+
* unsupported value to LATEST is the correct, spec-friendly downgrade. The
|
|
126
|
+
* Node->Web conversion (Hono getRequestListener) builds the Web Request from
|
|
127
|
+
* req.rawHeaders, NOT the parsed req.headers object, so the value must be
|
|
128
|
+
* rewritten in the raw array (kept in sync with req.headers for any other
|
|
129
|
+
* reader). */
|
|
130
|
+
function clampProtocolVersionHeader(req: http.IncomingMessage): void {
|
|
131
|
+
const sent = req.headers["mcp-protocol-version"];
|
|
132
|
+
if (typeof sent !== "string" || SUPPORTED_PROTOCOL_VERSIONS.includes(sent)) return;
|
|
133
|
+
req.headers["mcp-protocol-version"] = LATEST_PROTOCOL_VERSION;
|
|
134
|
+
const raw = req.rawHeaders;
|
|
135
|
+
for (let i = 0; i < raw.length - 1; i += 2) {
|
|
136
|
+
if (raw[i].toLowerCase() === "mcp-protocol-version") raw[i + 1] = LATEST_PROTOCOL_VERSION;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Per-process config dir. Each pi session owns its own file, so concurrent
|
|
141
|
+
* sessions never race on or cross-route through one shared config. */
|
|
142
|
+
export function bridgeMcpConfigDir(): string {
|
|
143
|
+
return path.join(bridgeDir(), `agy-mcp-${process.pid}`);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function bridgeMcpConfigPath(): string {
|
|
147
|
+
return path.join(bridgeMcpConfigDir(), ".agents", "mcp_config.json");
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** True if this process's bridge config exists (server is running). The
|
|
151
|
+
* provider uses this to decide whether to add the extra --add-dir. */
|
|
152
|
+
export function bridgeMcpConfigExists(): boolean {
|
|
153
|
+
return fs.existsSync(bridgeMcpConfigPath());
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function isPidAlive(pid: number): boolean {
|
|
157
|
+
try {
|
|
158
|
+
process.kill(pid, 0);
|
|
159
|
+
return true;
|
|
160
|
+
} catch (e) {
|
|
161
|
+
// EPERM: alive but not ours to signal. ESRCH: no such process.
|
|
162
|
+
return (e as NodeJS.ErrnoException).code === "EPERM";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Best-effort cleanup of stale per-pid dirs left by crashed sessions. */
|
|
167
|
+
export function sweepStaleBridgeDirs(baseDir: string = bridgeDir(), alive: (pid: number) => boolean = isPidAlive): void {
|
|
168
|
+
let entries: string[];
|
|
169
|
+
try {
|
|
170
|
+
entries = fs.readdirSync(baseDir);
|
|
171
|
+
} catch {
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
for (const name of entries) {
|
|
175
|
+
if (!name.startsWith("agy-mcp-")) continue;
|
|
176
|
+
const pid = Number(name.slice("agy-mcp-".length));
|
|
177
|
+
if (!Number.isInteger(pid) || pid === process.pid) continue;
|
|
178
|
+
if (alive(pid)) continue;
|
|
179
|
+
try {
|
|
180
|
+
fs.rmSync(path.join(baseDir, name), { recursive: true, force: true });
|
|
181
|
+
} catch {
|
|
182
|
+
/* best effort */
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Write our .agents/mcp_config.json (serverUrl + shared-secret header) so a
|
|
188
|
+
* provider agy that adds this dir via --add-dir discovers us. Atomic write. */
|
|
189
|
+
function writeBridgeMcpConfig(port: number, token: string): void {
|
|
190
|
+
const cfgPath = bridgeMcpConfigPath();
|
|
191
|
+
fs.mkdirSync(path.dirname(cfgPath), { recursive: true, mode: 0o700 });
|
|
192
|
+
const cfg = {
|
|
193
|
+
mcpServers: {
|
|
194
|
+
[BRIDGE_MCP_KEY]: {
|
|
195
|
+
serverUrl: `http://127.0.0.1:${port}/mcp`,
|
|
196
|
+
headers: { [TOKEN_HEADER]: token },
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
const tmp = `${cfgPath}.${process.pid}.tmp`;
|
|
201
|
+
try {
|
|
202
|
+
fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
|
|
203
|
+
fs.renameSync(tmp, cfgPath);
|
|
204
|
+
} catch (err) {
|
|
205
|
+
try {
|
|
206
|
+
fs.unlinkSync(tmp);
|
|
207
|
+
} catch {
|
|
208
|
+
/* nothing */
|
|
209
|
+
}
|
|
210
|
+
throw err;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Remove this process's config dir. Safe to delete unconditionally: only this
|
|
215
|
+
* pid owns it. */
|
|
216
|
+
function removeBridgeMcpConfig(): void {
|
|
217
|
+
try {
|
|
218
|
+
fs.rmSync(bridgeMcpConfigDir(), { recursive: true, force: true });
|
|
219
|
+
} catch {
|
|
220
|
+
/* best effort */
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Options for {@link registerExitCleanup}. */
|
|
225
|
+
export interface ExitCleanupOptions {
|
|
226
|
+
/** Signals to catch for abrupt-termination cleanup. Default SIGINT/SIGTERM. */
|
|
227
|
+
signals?: NodeJS.Signals[];
|
|
228
|
+
/** Override the host-ownership check (tests). Default: process.listenerCount(sig) > 0. */
|
|
229
|
+
hasHostListener?: (sig: NodeJS.Signals) => boolean;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** Register best-effort cleanup of this process's bridge config dir on process
|
|
233
|
+
* exit, returning a disposer that removes the handlers (call from close()).
|
|
234
|
+
*
|
|
235
|
+
* - 'exit' is always registered: synchronous, safe, catches process.exit() and
|
|
236
|
+
* event-loop drain. It does NOT fire on signal death.
|
|
237
|
+
* - For each signal in `signals` (default SIGINT/SIGTERM) we install a handler
|
|
238
|
+
* ONLY when the host process has no existing listener for it, so this
|
|
239
|
+
* extension never interferes with the host's own signal handling (e.g. a TUI
|
|
240
|
+
* cancel/quit flow). When we do install, we run cleanup then re-raise the
|
|
241
|
+
* signal so Node's default termination and exit code are preserved. Any
|
|
242
|
+
* abrupt termination that still bypasses these is swept on the next launch
|
|
243
|
+
* (sweepStaleBridgeDirs).
|
|
244
|
+
*
|
|
245
|
+
* `hasHostListener` is injectable so tests can exercise both branches without
|
|
246
|
+
* depending on which signals the test runtime happens to listen on. */
|
|
247
|
+
export function registerExitCleanup(
|
|
248
|
+
cleanup: () => void,
|
|
249
|
+
opts: ExitCleanupOptions = {},
|
|
250
|
+
): () => void {
|
|
251
|
+
const signals = opts.signals ?? ["SIGINT", "SIGTERM"];
|
|
252
|
+
const hasHostListener = opts.hasHostListener ?? ((sig) => process.listenerCount(sig) > 0);
|
|
253
|
+
const onExit = (): void => cleanup();
|
|
254
|
+
process.once("exit", onExit);
|
|
255
|
+
|
|
256
|
+
const installed: Array<{ sig: NodeJS.Signals; handler: () => void }> = [];
|
|
257
|
+
for (const sig of signals) {
|
|
258
|
+
// Host owns this signal: defer. The exit handler plus next-launch sweep
|
|
259
|
+
// cover the abrupt-death gap without racing the host's handler.
|
|
260
|
+
if (hasHostListener(sig)) continue;
|
|
261
|
+
const handler = (): void => {
|
|
262
|
+
cleanup();
|
|
263
|
+
process.removeListener(sig, handler);
|
|
264
|
+
// Re-raise so default termination runs with the right exit code, BUT
|
|
265
|
+
// only if no host listener has appeared since install (ours is removed
|
|
266
|
+
// now, so listenerCount reflects the host). If the host registered
|
|
267
|
+
// later it already received this delivery alongside us; re-raising
|
|
268
|
+
// would double-deliver (e.g. triggering a "Ctrl-C twice to quit" path
|
|
269
|
+
// on the first keypress). When nobody owns it, re-raise safely.
|
|
270
|
+
if (process.listenerCount(sig) === 0) process.kill(process.pid, sig);
|
|
271
|
+
};
|
|
272
|
+
process.once(sig, handler);
|
|
273
|
+
installed.push({ sig, handler });
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return (): void => {
|
|
277
|
+
process.removeListener("exit", onExit);
|
|
278
|
+
for (const { sig, handler } of installed) process.removeListener(sig, handler);
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export async function startMcpServer(
|
|
283
|
+
deps: McpBridgeDeps,
|
|
284
|
+
opts: {
|
|
285
|
+
preferredPort?: number;
|
|
286
|
+
log?: (s: string, d?: unknown) => void;
|
|
287
|
+
/** Test override for the per-park timeout (deny, fail closed). */
|
|
288
|
+
approvalTimeoutMs?: number;
|
|
289
|
+
} = {},
|
|
290
|
+
): Promise<McpStartResult> {
|
|
291
|
+
const log = opts.log ?? (() => {});
|
|
292
|
+
const approvalTimeoutMs = opts.approvalTimeoutMs ?? APPROVAL_PARK_TIMEOUT_MS;
|
|
293
|
+
|
|
294
|
+
const listHandler = async () => {
|
|
295
|
+
const tools = deps.listTools();
|
|
296
|
+
log("list-tools", { count: tools.length });
|
|
297
|
+
return { tools };
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
const callHandler = async (request: { params: { name: string; arguments?: unknown } }, signal?: AbortSignal) => {
|
|
301
|
+
const { name, arguments: args } = request.params;
|
|
302
|
+
// Progress probe: agy's MCP client killed long bridge calls at exactly
|
|
303
|
+
// ~180s (see ACP-PROTOCOL-REFERENCE). If its requests ever carry a
|
|
304
|
+
// progressToken, MCP progress notifications become a testable zero-UX
|
|
305
|
+
// fix for that deadline; log presence to find out.
|
|
306
|
+
const meta = (request.params as { _meta?: { progressToken?: unknown } })._meta;
|
|
307
|
+
if (meta && meta.progressToken !== undefined) {
|
|
308
|
+
log("progress-token", { name, token: String(meta.progressToken) });
|
|
309
|
+
}
|
|
310
|
+
const callId = crypto.randomUUID();
|
|
311
|
+
log("call-tool", { name, callId });
|
|
312
|
+
try {
|
|
313
|
+
const r = await deps.onToolCall(
|
|
314
|
+
callId,
|
|
315
|
+
name,
|
|
316
|
+
(args && typeof args === "object" ? args : {}) as Record<string, unknown>,
|
|
317
|
+
signal ?? new AbortController().signal,
|
|
318
|
+
);
|
|
319
|
+
const content =
|
|
320
|
+
r.content && r.content.length > 0 ? r.content : [{ type: "text", text: JSON.stringify(r) }];
|
|
321
|
+
log("call-tool-ok", { name, callId });
|
|
322
|
+
return { content, isError: r.isError ?? false };
|
|
323
|
+
} catch (e) {
|
|
324
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
325
|
+
log("call-tool-fail", { name, callId, msg });
|
|
326
|
+
return { content: [{ type: "text", text: `Error: ${msg}` }], isError: true };
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
const makeServer = (signal: AbortSignal) => {
|
|
331
|
+
const s = new Server(
|
|
332
|
+
{ name: "pi-antigravity-bridge", version: "1.1.0" },
|
|
333
|
+
{ capabilities: { tools: {} } },
|
|
334
|
+
);
|
|
335
|
+
s.setRequestHandler(ListToolsRequestSchema, listHandler);
|
|
336
|
+
s.setRequestHandler(CallToolRequestSchema, (request) => callHandler(request, signal));
|
|
337
|
+
return s;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
// Shared secret: agy sends it from the config headers. Browsers cannot set
|
|
341
|
+
// custom headers on a simple cross-origin POST, so this blocks web CSRF
|
|
342
|
+
// against the loopback server; local clients need the token too.
|
|
343
|
+
const token = crypto.randomUUID();
|
|
344
|
+
sweepStaleBridgeDirs();
|
|
345
|
+
|
|
346
|
+
// --- approval park (docs/TODO.md 2.5) ------------------------------------
|
|
347
|
+
// Ticket -> parked approval. A settled ticket STAYS in the map until its
|
|
348
|
+
// terminal decision is delivered to a poll, so the hook never 404s on the
|
|
349
|
+
// answer; an unknown/expired ticket 404s and the hook fails closed.
|
|
350
|
+
const parks = new Map<
|
|
351
|
+
string,
|
|
352
|
+
{ name: string; since: number; timer: NodeJS.Timeout; terminal?: ApprovalDecision }
|
|
353
|
+
>();
|
|
354
|
+
const settlePark = (ticket: string, decision: ApprovalDecision): boolean => {
|
|
355
|
+
const p = parks.get(ticket);
|
|
356
|
+
if (!p || p.terminal) return false;
|
|
357
|
+
p.terminal = decision;
|
|
358
|
+
clearTimeout(p.timer);
|
|
359
|
+
return true;
|
|
360
|
+
};
|
|
361
|
+
const approvalsApi: ApprovalParkApi = {
|
|
362
|
+
has: (ticket) => {
|
|
363
|
+
const p = parks.get(ticket);
|
|
364
|
+
return p !== undefined && p.terminal === undefined;
|
|
365
|
+
},
|
|
366
|
+
resolve: (ticket, decision) => settlePark(ticket, decision),
|
|
367
|
+
};
|
|
368
|
+
const decisionBody = (d: ApprovalDecision): string =>
|
|
369
|
+
d.allow ? JSON.stringify({ decision: "allow" }) : JSON.stringify({ decision: "deny", reason: d.reason });
|
|
370
|
+
const denyDirect = (res: http.ServerResponse, reason: string): void => {
|
|
371
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
372
|
+
res.end(decisionBody({ allow: false, reason }));
|
|
373
|
+
};
|
|
374
|
+
const tokenOk = (req: http.IncomingMessage): boolean => {
|
|
375
|
+
const received = req.headers[TOKEN_HEADER];
|
|
376
|
+
return (
|
|
377
|
+
typeof received === "string" &&
|
|
378
|
+
received.length === token.length &&
|
|
379
|
+
crypto.timingSafeEqual(Buffer.from(received), Buffer.from(token))
|
|
380
|
+
);
|
|
381
|
+
};
|
|
382
|
+
const readBody = async (req: http.IncomingMessage): Promise<string | null> => {
|
|
383
|
+
let body = "";
|
|
384
|
+
let bytes = 0;
|
|
385
|
+
for await (const chunk of req) {
|
|
386
|
+
body += chunk;
|
|
387
|
+
bytes += chunk.length;
|
|
388
|
+
if (bytes > MAX_BODY_BYTES) return null;
|
|
389
|
+
}
|
|
390
|
+
return body;
|
|
391
|
+
};
|
|
392
|
+
const approvalRoute = async (
|
|
393
|
+
req: http.IncomingMessage,
|
|
394
|
+
res: http.ServerResponse,
|
|
395
|
+
route: string,
|
|
396
|
+
): Promise<void> => {
|
|
397
|
+
if (!tokenOk(req)) {
|
|
398
|
+
log("unauthorized", { url: req.url });
|
|
399
|
+
res.writeHead(403, { "content-type": "application/json" }).end('{"error":"forbidden"}');
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
if (req.method === "POST" && route === "/approval") {
|
|
403
|
+
const body = await readBody(req);
|
|
404
|
+
if (body === null) {
|
|
405
|
+
res.writeHead(413, { "content-type": "application/json", connection: "close" }).end('{"error":"payload too large"}');
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
let payload: ApprovalPayload;
|
|
409
|
+
try {
|
|
410
|
+
const parsed = JSON.parse(body) as ApprovalPayload;
|
|
411
|
+
const name = parsed?.toolCall?.name;
|
|
412
|
+
if (typeof name !== "string" || name.length === 0) throw new Error("no toolCall.name");
|
|
413
|
+
if (!parsed.toolCall.args || typeof parsed.toolCall.args !== "object") {
|
|
414
|
+
parsed.toolCall.args = {};
|
|
415
|
+
}
|
|
416
|
+
payload = parsed;
|
|
417
|
+
} catch {
|
|
418
|
+
res.writeHead(400, { "content-type": "application/json" }).end('{"error":"invalid payload"}');
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
// Defense in depth: the hooks matcher should never let an ungated
|
|
422
|
+
// tool through; deny directly instead of parking.
|
|
423
|
+
if (!GATED_AGY_TOOL_SET.has(payload.toolCall.name)) {
|
|
424
|
+
log("approval-ungated", { name: payload.toolCall.name });
|
|
425
|
+
denyDirect(res, `tool ${payload.toolCall.name} is not in the approval matcher set`);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
if (typeof deps.onApproval !== "function") {
|
|
429
|
+
log("approval-unwired", { name: payload.toolCall.name });
|
|
430
|
+
denyDirect(res, "approval gate is not wired; denying");
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
const ticket = crypto.randomUUID();
|
|
434
|
+
const timer = setTimeout(() => {
|
|
435
|
+
// Fail closed FIRST: the staged hook timeout is longer than this
|
|
436
|
+
// park budget (V3: a hook outliving its timeout soft-passes, so the
|
|
437
|
+
// park must answer the deny before the hook is killed).
|
|
438
|
+
settlePark(ticket, { allow: false, reason: `approval gate timed out after ${Math.round(approvalTimeoutMs / 1000)}s` });
|
|
439
|
+
log("approval-timeout", { ticket, name: payload.toolCall.name });
|
|
440
|
+
}, approvalTimeoutMs);
|
|
441
|
+
parks.set(ticket, { name: payload.toolCall.name, since: Date.now(), timer });
|
|
442
|
+
log("approval-parked", { ticket, name: payload.toolCall.name });
|
|
443
|
+
try {
|
|
444
|
+
deps.onApproval(ticket, payload);
|
|
445
|
+
} catch (e) {
|
|
446
|
+
// A throwing provider must never hang the hook: settle deny now.
|
|
447
|
+
log("approval-onapproval-fail", { ticket, msg: e instanceof Error ? e.message : String(e) });
|
|
448
|
+
settlePark(ticket, { allow: false, reason: "approval gate internal error" });
|
|
449
|
+
}
|
|
450
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
451
|
+
res.end(JSON.stringify({ ticket }));
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
if (req.method === "GET" && route.startsWith("/approval/")) {
|
|
455
|
+
const ticket = decodeURIComponent(route.slice("/approval/".length));
|
|
456
|
+
const p = parks.get(ticket);
|
|
457
|
+
if (!p) {
|
|
458
|
+
// Unknown or already delivered: the hook fails closed on a 404.
|
|
459
|
+
res.writeHead(404, { "content-type": "application/json" }).end('{"error":"unknown ticket"}');
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
if (p.terminal) {
|
|
463
|
+
parks.delete(ticket); // delivered; a repeat poll 404s (fail closed)
|
|
464
|
+
log("approval-delivered", { ticket, name: p.name });
|
|
465
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
466
|
+
res.end(decisionBody(p.terminal));
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
470
|
+
res.end(JSON.stringify({ status: "pending" }));
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
res.writeHead(405).end();
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
return new Promise<McpStartResult>((resolve) => {
|
|
477
|
+
const httpServer = http.createServer(async (req, res) => {
|
|
478
|
+
// #1: a client-side stream error must never crash pi.
|
|
479
|
+
req.on("error", (e) => {
|
|
480
|
+
log("request-error", e instanceof Error ? e.message : String(e));
|
|
481
|
+
try {
|
|
482
|
+
if (!res.headersSent) res.writeHead(400).end();
|
|
483
|
+
else res.end();
|
|
484
|
+
} catch {
|
|
485
|
+
/* socket already gone */
|
|
486
|
+
}
|
|
487
|
+
});
|
|
488
|
+
try {
|
|
489
|
+
if (req.url?.includes("/.well-known/")) {
|
|
490
|
+
res.writeHead(404, { "content-type": "application/json" }).end('{"error":"not found"}');
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
const route = (req.url ?? "").split("?")[0];
|
|
494
|
+
if (route === "/approval" || route.startsWith("/approval/")) {
|
|
495
|
+
await approvalRoute(req, res, route);
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
if (req.method !== "POST") {
|
|
499
|
+
res.writeHead(405).end();
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
// #3: require the shared-secret header. Constant-time compare so a
|
|
503
|
+
// timing oracle can't recover the token byte-by-byte.
|
|
504
|
+
if (!tokenOk(req)) {
|
|
505
|
+
log("unauthorized", { url: req.url });
|
|
506
|
+
res.writeHead(403, { "content-type": "application/json" }).end('{"error":"forbidden"}');
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
// #4: cap request body size.
|
|
510
|
+
let body = "";
|
|
511
|
+
let bytes = 0;
|
|
512
|
+
let tooLarge = false;
|
|
513
|
+
for await (const chunk of req) {
|
|
514
|
+
body += chunk;
|
|
515
|
+
bytes += chunk.length;
|
|
516
|
+
if (bytes > MAX_BODY_BYTES) {
|
|
517
|
+
tooLarge = true;
|
|
518
|
+
break;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (tooLarge) {
|
|
522
|
+
// We bailed before draining the oversize body; close the connection
|
|
523
|
+
// so the unread bytes can't desync the next request on this socket.
|
|
524
|
+
res.writeHead(413, { "content-type": "application/json", connection: "close" }).end('{"error":"payload too large"}');
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
let parsed: { method?: string; params?: { protocolVersion?: string } };
|
|
528
|
+
try {
|
|
529
|
+
parsed = JSON.parse(body);
|
|
530
|
+
} catch {
|
|
531
|
+
res.writeHead(400).end("invalid json");
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
// Protocol version: agy negotiates a version newer than this SDK ships
|
|
535
|
+
// (e.g. 2026-07-28 vs LATEST 2025-11-25). initialize is exempt from the
|
|
536
|
+
// transport's header check and the SDK downgrades its body version
|
|
537
|
+
// itself, but every follow-up (tools/list, tools/call,
|
|
538
|
+
// notifications/initialized) is header-checked -> 400 + transport-error.
|
|
539
|
+
// Clamp unsupported headers to LATEST. Stateless server (fresh transport
|
|
540
|
+
// per request) can't track the negotiated version across requests.
|
|
541
|
+
clampProtocolVersionHeader(req);
|
|
542
|
+
// #6: cancel the invoked tool if agy disconnects mid-call (e.g. killed
|
|
543
|
+
// by the runner timeout). req 'close' would fire on normal completion,
|
|
544
|
+
// so we only abort on client abort / response-closed-before-finished.
|
|
545
|
+
const ac = new AbortController();
|
|
546
|
+
req.on("aborted", () => ac.abort());
|
|
547
|
+
res.on("close", () => {
|
|
548
|
+
if (!res.writableEnded) ac.abort();
|
|
549
|
+
});
|
|
550
|
+
try {
|
|
551
|
+
// Stateless: a fresh transport+server per request.
|
|
552
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
553
|
+
transport.onerror = (e: Error) => log("transport-error", e.message);
|
|
554
|
+
const server = makeServer(ac.signal);
|
|
555
|
+
await server.connect(transport);
|
|
556
|
+
await transport.handleRequest(req, res, parsed as object);
|
|
557
|
+
} catch (e) {
|
|
558
|
+
log("handleRequest-error", e instanceof Error ? e.message : String(e));
|
|
559
|
+
if (!res.headersSent) res.writeHead(500).end();
|
|
560
|
+
}
|
|
561
|
+
} catch (e) {
|
|
562
|
+
// Catch-all (e.g. errors during body read/clamp) so pi never crashes.
|
|
563
|
+
log("request-handler-error", e instanceof Error ? e.message : String(e));
|
|
564
|
+
try {
|
|
565
|
+
if (!res.headersSent) res.writeHead(500).end();
|
|
566
|
+
} catch {
|
|
567
|
+
/* socket gone */
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
|
|
572
|
+
httpServer.on("error", (e) => {
|
|
573
|
+
log("http-error", e instanceof Error ? e.message : String(e));
|
|
574
|
+
resolve({ ok: false, reason: `http server error: ${e instanceof Error ? e.message : String(e)}` });
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
httpServer.listen(opts.preferredPort ?? 0, "127.0.0.1", () => {
|
|
578
|
+
const addr = httpServer.address();
|
|
579
|
+
const port = typeof addr === "object" && addr ? addr.port : 0;
|
|
580
|
+
if (!port) {
|
|
581
|
+
resolve({ ok: false, reason: "failed to bind" });
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
try {
|
|
585
|
+
writeBridgeMcpConfig(port, token);
|
|
586
|
+
log("bridge-config-written", { port, path: bridgeMcpConfigPath() });
|
|
587
|
+
} catch (e) {
|
|
588
|
+
log("bridge-config-write-failed", e instanceof Error ? e.message : String(e));
|
|
589
|
+
}
|
|
590
|
+
// Clean up the config dir on abrupt termination (SIGINT/SIGTERM/crash)
|
|
591
|
+
// where session_shutdown -> close() does not run. Disposed in close().
|
|
592
|
+
const disposeExitCleanup = registerExitCleanup(removeBridgeMcpConfig);
|
|
593
|
+
log("listening", { port });
|
|
594
|
+
resolve({
|
|
595
|
+
ok: true,
|
|
596
|
+
port,
|
|
597
|
+
handle: {
|
|
598
|
+
port,
|
|
599
|
+
token,
|
|
600
|
+
approvals: approvalsApi,
|
|
601
|
+
close: async () => {
|
|
602
|
+
// Pending approvals fail closed on shutdown: the hook gets a
|
|
603
|
+
// terminal deny instead of a 404 on its next poll.
|
|
604
|
+
for (const [ticket, p] of [...parks]) {
|
|
605
|
+
if (p.terminal) continue;
|
|
606
|
+
settlePark(ticket, { allow: false, reason: "approval gate bridge shut down" });
|
|
607
|
+
}
|
|
608
|
+
await new Promise<void>((r) => httpServer.close(() => r()));
|
|
609
|
+
removeBridgeMcpConfig();
|
|
610
|
+
disposeExitCleanup();
|
|
611
|
+
log("bridge-config-removed", { port });
|
|
612
|
+
log("closed", { port });
|
|
613
|
+
},
|
|
614
|
+
},
|
|
615
|
+
});
|
|
616
|
+
});
|
|
617
|
+
});
|
|
618
|
+
}
|