trusted-user-agent 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +232 -2
- package/dist/acp/agent.js +719 -0
- package/dist/acp/agents/connection.js +298 -0
- package/dist/acp/agents/manager.js +363 -0
- package/dist/acp/agents/registry.js +201 -0
- package/dist/acp/agents/relay-session.js +371 -0
- package/dist/acp/agents/session-index.js +102 -0
- package/dist/acp/backend.js +2 -0
- package/dist/acp/config-options.js +26 -0
- package/dist/acp/mock-backend.js +277 -0
- package/dist/acp/sdk-backend.js +495 -0
- package/dist/browser/mcp-acp-client.js +81 -0
- package/dist/browser/provider.js +1049 -0
- package/dist/browser/schemas.js +221 -0
- package/dist/capability-registry.js +92 -0
- package/dist/client-heartbeat.js +118 -0
- package/dist/compose/schemas.js +90 -0
- package/dist/contacts/schemas.js +26 -0
- package/dist/installer/cli.js +70 -0
- package/dist/installer/common.js +93 -0
- package/dist/installer/index.js +366 -0
- package/dist/installer/mcp-clients.js +555 -0
- package/dist/installer/mcp.js +166 -0
- package/dist/installer/platforms.js +277 -0
- package/dist/logger.js +54 -0
- package/dist/mail/schemas.js +98 -0
- package/dist/mutation/schemas.js +31 -0
- package/dist/native-host/broker-ipc.js +344 -0
- package/dist/native-host/framing.js +76 -0
- package/dist/native-host/main.js +545 -0
- package/dist/native-host/mcp-server.js +333 -0
- package/dist/native-host/mcp-stdio-bridge.js +184 -0
- package/dist/native-host/mcp-stdio-main.js +13 -0
- package/dist/native-host/relay.js +84 -0
- package/dist/native-host/skills-startup.js +167 -0
- package/dist/native-host/transport.js +248 -0
- package/dist/permission-store.js +207 -0
- package/dist/repl/fs-sandbox.js +187 -0
- package/dist/repl/provider.js +252 -0
- package/dist/repl/runtime.js +436 -0
- package/dist/repl/types.js +10 -0
- package/dist/repl/worker.js +731 -0
- package/dist/skills/extension.js +99 -0
- package/dist/skills/grants-file.js +145 -0
- package/dist/skills/isolated-runner.js +259 -0
- package/dist/skills/mock-session-factory.js +49 -0
- package/dist/skills/package-roots.js +25 -0
- package/dist/skills/pi-bridge.js +8 -0
- package/dist/skills/pi-integration.js +110 -0
- package/dist/skills/planner.js +128 -0
- package/dist/skills/registry.js +104 -0
- package/dist/skills/skills-protocol.js +253 -0
- package/dist/skills/skills-service.js +195 -0
- package/dist/tool-bridge.js +8 -0
- package/dist/workspace.js +70 -0
- package/extensions/pi-browser-tools.ts +65 -0
- package/extensions/pi-browser.ts +60 -0
- package/extensions/pi-skills.ts +14 -0
- package/native/pi-agent-host +2 -0
- package/native/pi-browser-host +5 -0
- package/native/pi-browser-host.cmd +3 -0
- package/node_modules/@pi-browser/protocol/.bundled-by-trusted-user-agent +0 -0
- package/node_modules/@pi-browser/protocol/dist/acp.d.ts +10 -0
- package/node_modules/@pi-browser/protocol/dist/acp.js +9 -0
- package/node_modules/@pi-browser/protocol/dist/agents.d.ts +51 -0
- package/node_modules/@pi-browser/protocol/dist/agents.js +44 -0
- package/node_modules/@pi-browser/protocol/dist/browser-tools.d.ts +33 -0
- package/node_modules/@pi-browser/protocol/dist/browser-tools.js +478 -0
- package/node_modules/@pi-browser/protocol/dist/callers.d.ts +123 -0
- package/node_modules/@pi-browser/protocol/dist/callers.js +58 -0
- package/node_modules/@pi-browser/protocol/dist/compose-tools.d.ts +30 -0
- package/node_modules/@pi-browser/protocol/dist/compose-tools.js +175 -0
- package/node_modules/@pi-browser/protocol/dist/contacts-tools.d.ts +23 -0
- package/node_modules/@pi-browser/protocol/dist/contacts-tools.js +63 -0
- package/node_modules/@pi-browser/protocol/dist/control-tools.d.ts +32 -0
- package/node_modules/@pi-browser/protocol/dist/control-tools.js +201 -0
- package/node_modules/@pi-browser/protocol/dist/errors.d.ts +63 -0
- package/node_modules/@pi-browser/protocol/dist/errors.js +109 -0
- package/node_modules/@pi-browser/protocol/dist/index.d.ts +17 -0
- package/node_modules/@pi-browser/protocol/dist/index.js +17 -0
- package/node_modules/@pi-browser/protocol/dist/integration.d.ts +414 -0
- package/node_modules/@pi-browser/protocol/dist/integration.js +270 -0
- package/node_modules/@pi-browser/protocol/dist/jsonrpc.d.ts +33 -0
- package/node_modules/@pi-browser/protocol/dist/jsonrpc.js +31 -0
- package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.d.ts +27 -0
- package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.js +88 -0
- package/node_modules/@pi-browser/protocol/dist/mail-tools.d.ts +133 -0
- package/node_modules/@pi-browser/protocol/dist/mail-tools.js +245 -0
- package/node_modules/@pi-browser/protocol/dist/permission.d.ts +113 -0
- package/node_modules/@pi-browser/protocol/dist/permission.js +257 -0
- package/node_modules/@pi-browser/protocol/dist/skills.d.ts +304 -0
- package/node_modules/@pi-browser/protocol/dist/skills.js +473 -0
- package/node_modules/@pi-browser/protocol/dist/tool-capabilities.d.ts +18 -0
- package/node_modules/@pi-browser/protocol/dist/tool-capabilities.js +52 -0
- package/node_modules/@pi-browser/protocol/dist/transport.d.ts +17 -0
- package/node_modules/@pi-browser/protocol/dist/transport.js +17 -0
- package/node_modules/@pi-browser/protocol/package.json +14 -0
- package/package.json +69 -4
- package/skills/browser-walk/SKILL.md +98 -0
|
@@ -0,0 +1,1049 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BrowserToolTransport interface + implementations (PRODUCT.md §29–30).
|
|
3
|
+
*
|
|
4
|
+
* BrowserToolTransport.call(sessionId, tool, args)
|
|
5
|
+
*
|
|
6
|
+
* - LegacyBrowserCallbackTransport: private x-pi-browser/tool JSON-RPC
|
|
7
|
+
* namespace over the Native Messaging connection (the working MVP
|
|
8
|
+
* transport).
|
|
9
|
+
* - NativeMcpOverAcpTransport: MCP-over-ACP (mcp/connect, mcp/message,
|
|
10
|
+
* mcp/disconnect) when the client declares an ACP-transport MCP server.
|
|
11
|
+
*
|
|
12
|
+
* Tool names, arguments, and results are identical across transports —
|
|
13
|
+
* migrating changes only the transport.
|
|
14
|
+
*/
|
|
15
|
+
import { BROWSER_DOWNLOAD_TIMEOUT_MS, BROWSER_SCREENSHOT_TIMEOUT_MS, BROWSER_TOOL_TIMEOUT_MS, isComposeTool, isContactsTool, isMailTool, isMailMutationTool, isReplTool, COMPOSE_TOOL_TIMEOUT_MS, CONTACTS_TOOL_TIMEOUT_MS, MAIL_ATTACHMENT_TIMEOUT_MS, MAIL_MUTATION_TOOL_TIMEOUT_MS, MAIL_TOOL_TIMEOUT_MS, codeFromErrorObject, isStructuredErrorObject, PI_BROWSER_ERROR, PiBrowserProtocolError, X_PI_BROWSER, buildPermissionRequest, buildCallerApprovalRequest, applicationForTool, applicationShortName, getGatedTool, listGatedTools, permissionAllowed, toolRequiresApproval, CALLER_ALLOW_ALWAYS, CALLER_ALLOW_ONCE, CALLER_DENY, PERMISSION_WITHDRAWN_METHOD, REQUEST_PERMISSION_METHOD, } from "@pi-browser/protocol";
|
|
16
|
+
import { PermissionStore } from "../permission-store.js";
|
|
17
|
+
import { BROWSER_TOOL_SCHEMAS, CONTROL_TOOL_SCHEMAS } from "./schemas.js";
|
|
18
|
+
import { MAIL_TOOL_SCHEMAS } from "../mail/schemas.js";
|
|
19
|
+
import { COMPOSE_TOOL_SCHEMAS } from "../compose/schemas.js";
|
|
20
|
+
import { MAIL_MUTATION_TOOL_SCHEMAS } from "../mutation/schemas.js";
|
|
21
|
+
import { CONTACTS_TOOL_SCHEMAS } from "../contacts/schemas.js";
|
|
22
|
+
import { McpAcpClient } from "./mcp-acp-client.js";
|
|
23
|
+
import { REPL_PREAMBLE, ReplProvider } from "../repl/provider.js";
|
|
24
|
+
export { MCP_PROTOCOL_VERSION } from "@pi-browser/protocol";
|
|
25
|
+
import { TransportClosedError, TransportTimeoutError } from "../native-host/transport.js";
|
|
26
|
+
/** JSON.stringify that never throws (cycles, BigInt, undefined) — tool I/O logging. */
|
|
27
|
+
function safeJson(value) {
|
|
28
|
+
try {
|
|
29
|
+
const out = JSON.stringify(value);
|
|
30
|
+
return out === undefined ? String(value) : out;
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return String(value);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
// Normalization
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
/** Convert an MCP tools/call result (or a raw object) into normalized content. */
|
|
40
|
+
export function normalizeToolResult(raw) {
|
|
41
|
+
if (typeof raw === "object" && raw !== null && Array.isArray(raw.content)) {
|
|
42
|
+
const r = raw;
|
|
43
|
+
const content = [];
|
|
44
|
+
for (const c of r.content) {
|
|
45
|
+
if (c?.type === "text" && typeof c.text === "string")
|
|
46
|
+
content.push({ type: "text", text: c.text });
|
|
47
|
+
else if (c?.type === "image" && typeof c.data === "string" && typeof c.mimeType === "string") {
|
|
48
|
+
content.push({ type: "image", data: c.data, mimeType: c.mimeType });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (content.length === 0)
|
|
52
|
+
content.push({ type: "text", text: "(empty result)" });
|
|
53
|
+
return { content, isError: r.isError === true };
|
|
54
|
+
}
|
|
55
|
+
return { content: [{ type: "text", text: JSON.stringify(raw ?? null) }] };
|
|
56
|
+
}
|
|
57
|
+
function timeoutFor(tool) {
|
|
58
|
+
if (tool === "browser_screenshot")
|
|
59
|
+
return BROWSER_SCREENSHOT_TIMEOUT_MS;
|
|
60
|
+
if (tool === "browser_download")
|
|
61
|
+
return BROWSER_DOWNLOAD_TIMEOUT_MS;
|
|
62
|
+
if (tool === "mail_get_attachment")
|
|
63
|
+
return MAIL_ATTACHMENT_TIMEOUT_MS;
|
|
64
|
+
if (isMailTool(tool))
|
|
65
|
+
return MAIL_TOOL_TIMEOUT_MS;
|
|
66
|
+
if (isComposeTool(tool))
|
|
67
|
+
return COMPOSE_TOOL_TIMEOUT_MS;
|
|
68
|
+
if (isMailMutationTool(tool))
|
|
69
|
+
return MAIL_MUTATION_TOOL_TIMEOUT_MS;
|
|
70
|
+
if (isContactsTool(tool))
|
|
71
|
+
return CONTACTS_TOOL_TIMEOUT_MS;
|
|
72
|
+
return BROWSER_TOOL_TIMEOUT_MS;
|
|
73
|
+
}
|
|
74
|
+
export class LegacyBrowserCallbackTransport {
|
|
75
|
+
transport;
|
|
76
|
+
options;
|
|
77
|
+
kind = "legacy";
|
|
78
|
+
constructor(transport, options = {}) {
|
|
79
|
+
this.transport = transport;
|
|
80
|
+
this.options = options;
|
|
81
|
+
}
|
|
82
|
+
async call(sessionId, tool, args, toolCallId) {
|
|
83
|
+
const timeoutMs = (this.options.timeoutMs ?? timeoutFor)(tool);
|
|
84
|
+
const slackMs = this.options.slackMs ?? 5_000;
|
|
85
|
+
try {
|
|
86
|
+
const raw = await this.transport.request(X_PI_BROWSER.tool, { sessionId, tool, arguments: args, timeoutMs, ...(toolCallId ? { toolCallId } : {}) }, timeoutMs + slackMs);
|
|
87
|
+
return normalizeToolResult(raw);
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
// A timed-out incremental search still has a resumable cursor: surface
|
|
91
|
+
// the partial progress so the model can continue with `cursor`.
|
|
92
|
+
if (err instanceof TransportTimeoutError && toolCallId) {
|
|
93
|
+
const partial = this.options.getPartial?.(toolCallId);
|
|
94
|
+
if (partial && (partial.scanned !== undefined || partial.nextCursor)) {
|
|
95
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_TOOL_TIMEOUT, `browser tool timed out: ${tool}`, {
|
|
96
|
+
tool,
|
|
97
|
+
partial: true,
|
|
98
|
+
...(partial.scanned !== undefined ? { scanned: partial.scanned } : {}),
|
|
99
|
+
...(partial.nextCursor ? { nextCursor: partial.nextCursor } : {}),
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
throw translateTransportError(err, tool);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async dispose() {
|
|
107
|
+
// Stateless; nothing to release.
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
// MCP-over-ACP transport
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
export class NativeMcpOverAcpTransport {
|
|
114
|
+
sessionId;
|
|
115
|
+
kind = "mcp-acp";
|
|
116
|
+
client;
|
|
117
|
+
constructor(transport, serverId, log, sessionId) {
|
|
118
|
+
this.sessionId = sessionId;
|
|
119
|
+
this.client = new McpAcpClient({
|
|
120
|
+
transport,
|
|
121
|
+
serverId,
|
|
122
|
+
log,
|
|
123
|
+
timeoutMs: BROWSER_SCREENSHOT_TIMEOUT_MS + 5_000,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
async call(_sessionId, tool, args, _toolCallId) {
|
|
127
|
+
try {
|
|
128
|
+
const raw = await this.client.call(tool, args);
|
|
129
|
+
return normalizeToolResult(raw);
|
|
130
|
+
}
|
|
131
|
+
catch (err) {
|
|
132
|
+
if (err instanceof PiBrowserProtocolError)
|
|
133
|
+
throw err;
|
|
134
|
+
if (isStructuredErrorObject(err)) {
|
|
135
|
+
// Preserve structured codes the client sent (e.g. MCP_TOOL_NOT_FOUND).
|
|
136
|
+
const code = codeFromErrorObject(err) ?? PI_BROWSER_ERROR.MCP_UNAVAILABLE;
|
|
137
|
+
throw new PiBrowserProtocolError(code, err.message, { tool });
|
|
138
|
+
}
|
|
139
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
140
|
+
if (/timed out|timeout/i.test(message)) {
|
|
141
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_TOOL_TIMEOUT, `mcp tool call timed out: ${tool}`);
|
|
142
|
+
}
|
|
143
|
+
if (/disposed|closed/i.test(message)) {
|
|
144
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.MCP_UNAVAILABLE, `mcp connection unavailable: ${tool}`);
|
|
145
|
+
}
|
|
146
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.MCP_UNAVAILABLE, `mcp tool call failed: ${message}`, { tool });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
async listTools() {
|
|
150
|
+
return this.client.listTools();
|
|
151
|
+
}
|
|
152
|
+
get connected() {
|
|
153
|
+
return this.client.connected;
|
|
154
|
+
}
|
|
155
|
+
async dispose() {
|
|
156
|
+
await this.client.dispose();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
// Shared error translation
|
|
161
|
+
// ---------------------------------------------------------------------------
|
|
162
|
+
export function translateTransportError(err, tool) {
|
|
163
|
+
if (err instanceof PiBrowserProtocolError)
|
|
164
|
+
return err;
|
|
165
|
+
if (err instanceof TransportTimeoutError) {
|
|
166
|
+
return new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_TOOL_TIMEOUT, `browser tool timed out: ${tool}`);
|
|
167
|
+
}
|
|
168
|
+
if (err instanceof TransportClosedError) {
|
|
169
|
+
return new PiBrowserProtocolError(PI_BROWSER_ERROR.MCP_UNAVAILABLE, "browser connection closed", { tool });
|
|
170
|
+
}
|
|
171
|
+
if (isStructuredErrorObject(err)) {
|
|
172
|
+
const code = codeFromErrorObject(err) ?? PI_BROWSER_ERROR.INTERNAL;
|
|
173
|
+
return new PiBrowserProtocolError(code, err.message, { tool });
|
|
174
|
+
}
|
|
175
|
+
return new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, err instanceof Error ? err.message : String(err), { tool });
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Window during which parallel permission requests for the same session are
|
|
179
|
+
* collected into one prompt. Models emit same-turn parallel tool calls within
|
|
180
|
+
* the same tick, so 150 ms comfortably groups them with no perceptible delay.
|
|
181
|
+
*/
|
|
182
|
+
const PERMISSION_COALESCE_WINDOW_MS = 150;
|
|
183
|
+
/** Message for calls refused because external MCP access is off. */
|
|
184
|
+
export const EXTERNAL_ACCESS_OFF_MESSAGE = "External MCP access is disabled in the Pi add-on settings. Ask the user to turn on " +
|
|
185
|
+
"\"Allow other apps (MCP) to use these tools\" in the Pi permissions page.";
|
|
186
|
+
/** The caller attribution sent to the add-on (name + version only). */
|
|
187
|
+
function callerMeta(caller) {
|
|
188
|
+
return { name: caller.name, ...(caller.version ? { version: caller.version } : {}) };
|
|
189
|
+
}
|
|
190
|
+
/** Compact, bounded JSON summary of tool args for permission log lines. */
|
|
191
|
+
function summarizeArgs(args) {
|
|
192
|
+
if (!args)
|
|
193
|
+
return undefined;
|
|
194
|
+
try {
|
|
195
|
+
const s = JSON.stringify(args);
|
|
196
|
+
return s.length > 300 ? `${s.slice(0, 300)}…` : s;
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
return "[unserializable args]";
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const PERMISSION_TIMEOUT_MS = 120_000;
|
|
203
|
+
export class CapabilityToolProvider {
|
|
204
|
+
transport;
|
|
205
|
+
log;
|
|
206
|
+
registry;
|
|
207
|
+
sessions = new Map();
|
|
208
|
+
/**
|
|
209
|
+
* Persistent per-tool states (ask | deny | allow, PRODUCT.md §55). Shared
|
|
210
|
+
* by every connected application (one broker process); survives host
|
|
211
|
+
* restarts and is editable from the add-on's Configuration page.
|
|
212
|
+
*/
|
|
213
|
+
permissions;
|
|
214
|
+
/**
|
|
215
|
+
* Tools the user has approved with "Allow for this session", keyed by ACP
|
|
216
|
+
* session id. Cleared when the session is disposed.
|
|
217
|
+
*/
|
|
218
|
+
sessionAllowed = new Map();
|
|
219
|
+
/**
|
|
220
|
+
* In-flight legacy tool calls: toolCallId → routing/sequence state.
|
|
221
|
+
* Used to validate x-pi-browser/tool_update notifications (session, call
|
|
222
|
+
* identity, client, monotonic sequence) and to recover the last streamed
|
|
223
|
+
* batch when a call times out.
|
|
224
|
+
*/
|
|
225
|
+
activeToolCalls = new Map();
|
|
226
|
+
/**
|
|
227
|
+
* Set by the ACP agent: maps a validated tool update onto an ACP
|
|
228
|
+
* `tool_call_update` session/update notification. Display-only — the
|
|
229
|
+
* update never authorizes anything.
|
|
230
|
+
*/
|
|
231
|
+
onToolUpdate;
|
|
232
|
+
/** The host-side `javascript` REPL (BROWSER-USE-REPL-PLAN.md, option C). */
|
|
233
|
+
repl = new ReplProvider({
|
|
234
|
+
log: (line) => this.log.debug(line),
|
|
235
|
+
// First-call recipe (observe -> act -> verify -> persist, guardrails,
|
|
236
|
+
// ref lifecycle, permission semantics): BROWSER-USE-SUPPORT-PLAN.md WS1/T1.2.
|
|
237
|
+
preamble: REPL_PREAMBLE,
|
|
238
|
+
});
|
|
239
|
+
constructor(
|
|
240
|
+
/**
|
|
241
|
+
* Fallback transport (single-client / legacy mode). In registry (broker)
|
|
242
|
+
* mode this may be undefined: every call is routed through the registry.
|
|
243
|
+
*/
|
|
244
|
+
transport, log, registry = undefined, options = {}) {
|
|
245
|
+
this.transport = transport;
|
|
246
|
+
this.log = log;
|
|
247
|
+
this.registry = registry;
|
|
248
|
+
this.timeoutForTool = options.timeoutMsFor ?? timeoutFor;
|
|
249
|
+
this.permissions = options.permissionStore ?? new PermissionStore();
|
|
250
|
+
this.permissionTimeoutMs = options.permissionTimeoutMs ?? PERMISSION_TIMEOUT_MS;
|
|
251
|
+
}
|
|
252
|
+
permissionTimeoutMs;
|
|
253
|
+
/** How long a permission prompt waits for the user (also used for relayed agent prompts). */
|
|
254
|
+
get promptTimeoutMs() {
|
|
255
|
+
return this.permissionTimeoutMs;
|
|
256
|
+
}
|
|
257
|
+
timeoutForTool;
|
|
258
|
+
/** The ACP transport a tool call / permission prompt goes to (legacy mode). */
|
|
259
|
+
legacyTransport() {
|
|
260
|
+
if (this.transport)
|
|
261
|
+
return this.transport;
|
|
262
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.MCP_UNAVAILABLE, "no connected client for tool call (registry mode requires a connected owner)");
|
|
263
|
+
}
|
|
264
|
+
/** Choose the transport for a session from the MCP servers the client declared. */
|
|
265
|
+
selectMode(mcpServers) {
|
|
266
|
+
return mcpServers?.some((s) => typeof s === "object" && s !== null && s.type === "acp")
|
|
267
|
+
? "mcp-acp"
|
|
268
|
+
: "legacy";
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* Build the Pi custom-tool specs for a session. The session id is bound
|
|
272
|
+
* lazily (idRef) because the backend assigns it at session creation.
|
|
273
|
+
*
|
|
274
|
+
* Control tools (pi_*) are only registered for the MCP-over-ACP mode:
|
|
275
|
+
* they are served by the add-on's MCP server and have no equivalent on
|
|
276
|
+
* the legacy x-pi-browser/tool callback path.
|
|
277
|
+
*
|
|
278
|
+
* `capabilities` selects the tool surface (plan §19): a client that
|
|
279
|
+
* advertises "browser" gets the browser tools, one that advertises
|
|
280
|
+
* "mail"/"attachments" gets the read-only mail tools. The default
|
|
281
|
+
* (["browser"]) preserves the pre-capability behaviour for callers that
|
|
282
|
+
* do not pass the client's declared capabilities.
|
|
283
|
+
*/
|
|
284
|
+
createTools(idRef, mode, mcpServerId, capabilities = ["browser"], ownerClientId, ownerApplication = "firefox") {
|
|
285
|
+
// Broker mode: the session sees every connected provider (plan §29),
|
|
286
|
+
// not only the owner's tools.
|
|
287
|
+
const caps = this.registry && ownerClientId !== undefined
|
|
288
|
+
? this.registry.allCapabilities()
|
|
289
|
+
: (capabilities ?? []);
|
|
290
|
+
const hasBrowser = caps.includes("browser");
|
|
291
|
+
const hasMail = caps.includes("mail") || caps.includes("attachments");
|
|
292
|
+
const hasCompose = caps.includes("compose");
|
|
293
|
+
const hasMailModify = caps.includes("mailModify");
|
|
294
|
+
const hasContacts = caps.includes("contacts");
|
|
295
|
+
const schemas = [];
|
|
296
|
+
if (hasBrowser) {
|
|
297
|
+
schemas.push(...BROWSER_TOOL_SCHEMAS);
|
|
298
|
+
if (mode === "mcp-acp")
|
|
299
|
+
schemas.push(...CONTROL_TOOL_SCHEMAS);
|
|
300
|
+
}
|
|
301
|
+
if (hasMail) {
|
|
302
|
+
schemas.push(...MAIL_TOOL_SCHEMAS);
|
|
303
|
+
}
|
|
304
|
+
if (hasCompose) {
|
|
305
|
+
schemas.push(...COMPOSE_TOOL_SCHEMAS);
|
|
306
|
+
}
|
|
307
|
+
if (hasMailModify) {
|
|
308
|
+
schemas.push(...MAIL_MUTATION_TOOL_SCHEMAS);
|
|
309
|
+
}
|
|
310
|
+
if (hasContacts) {
|
|
311
|
+
schemas.push(...CONTACTS_TOOL_SCHEMAS);
|
|
312
|
+
}
|
|
313
|
+
const specs = schemas.map((entry) => ({
|
|
314
|
+
name: entry.name,
|
|
315
|
+
label: entry.name,
|
|
316
|
+
description: entry.description,
|
|
317
|
+
parameters: entry.parameters,
|
|
318
|
+
execute: async (toolCallId, args, _signal) => {
|
|
319
|
+
const sessionId = idRef.id;
|
|
320
|
+
if (!sessionId) {
|
|
321
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, "browser tool invoked before session id assigned");
|
|
322
|
+
}
|
|
323
|
+
const result = await this.routeTool(sessionId, toolCallId, entry.name, args, mode, mcpServerId, ownerClientId, ownerApplication);
|
|
324
|
+
return { content: result.content, details: { piBrowser: true, tool: entry.name } };
|
|
325
|
+
},
|
|
326
|
+
}));
|
|
327
|
+
// The host-side REPL (BROWSER-USE-REPL-PLAN.md): one `javascript` tool per
|
|
328
|
+
// browser session; its cells' page.*/tabs.* primitives reuse the exact
|
|
329
|
+
// routing (and permission prompts) of the regular browser tools.
|
|
330
|
+
if (hasBrowser) {
|
|
331
|
+
specs.push(this.replToolSpec(idRef, mode, mcpServerId, ownerClientId, ownerApplication));
|
|
332
|
+
}
|
|
333
|
+
return specs;
|
|
334
|
+
}
|
|
335
|
+
/** The session's REPL worker child pid (undefined when not running). */
|
|
336
|
+
childPidFor(sessionId) {
|
|
337
|
+
return this.repl.childPidFor(sessionId);
|
|
338
|
+
}
|
|
339
|
+
/** The `javascript` ToolSpec, with cells' tool calls routed like any other. */
|
|
340
|
+
replToolSpec(idRef, mode, mcpServerId, ownerClientId, ownerApplication) {
|
|
341
|
+
return this.repl.toolSpec(idRef, this.replExecutor(mode, mcpServerId, ownerClientId, ownerApplication));
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* The REPL executor shared by the ACP tool spec and the MCP/bridge path:
|
|
345
|
+
* routes a cell's page.* / tabs.* primitive through the standard routeTool
|
|
346
|
+
* path with the owning session's routing context, so in-cell browser tool
|
|
347
|
+
* calls keep the same transport + permission prompts as direct calls.
|
|
348
|
+
*/
|
|
349
|
+
replExecutor(mode, mcpServerId, ownerClientId, ownerApplication, caller) {
|
|
350
|
+
return (sessionId, tool, args) => this.routeTool(sessionId, `repl:${tool}:${crypto.randomUUID()}`, tool, args, mode, mcpServerId, ownerClientId, ownerApplication, caller);
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Execute one tool call arriving over the in-process tool bridge (a Pi
|
|
354
|
+
* extension registering the browser tools for a session that the broker
|
|
355
|
+
* did not create itself — e.g. a subagent session). Goes through the same
|
|
356
|
+
* routing + approval path as the regular tool specs; sessionId and ctx
|
|
357
|
+
* identify the owning ACP session (the bridge resolves the fallback).
|
|
358
|
+
*/
|
|
359
|
+
async bridgeCall(opts) {
|
|
360
|
+
const caller = opts.ctx?.caller;
|
|
361
|
+
// The `javascript` REPL is host-executed (it owns a V8 worker child +
|
|
362
|
+
// per-session cell state) — it must run in THIS process, not be routed
|
|
363
|
+
// to the connected app like a browser tool. Runs for REPL tools only.
|
|
364
|
+
if (isReplTool(opts.tool)) {
|
|
365
|
+
// The cell itself has no executing app, so no caller approval: its
|
|
366
|
+
// page.*/tabs.* primitives go through routeTool (and the caller gate).
|
|
367
|
+
// The external-access switch still refuses the whole call.
|
|
368
|
+
if (caller && !this.permissions.getExternalAccess()) {
|
|
369
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_PERMISSION_DENIED, EXTERNAL_ACCESS_OFF_MESSAGE, {
|
|
370
|
+
tool: opts.tool,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
const mode = opts.ctx?.mode ?? "legacy";
|
|
374
|
+
const spec = this.repl.toolSpec({ id: opts.sessionId }, this.replExecutor(mode, opts.ctx?.mcpServerId, opts.ctx?.ownerClientId, opts.ctx?.ownerApplication ?? "firefox", caller));
|
|
375
|
+
const res = await spec.execute(opts.toolCallId ?? `bridge:${opts.tool}:${crypto.randomUUID()}`, opts.args, undefined);
|
|
376
|
+
return { content: res.content };
|
|
377
|
+
}
|
|
378
|
+
return this.routeTool(opts.sessionId, opts.toolCallId ?? `bridge:${opts.tool}:${crypto.randomUUID()}`, opts.tool, opts.args, opts.ctx?.mode ?? "legacy", opts.ctx?.mcpServerId, opts.ctx?.ownerClientId, opts.ctx?.ownerApplication ?? "firefox", caller);
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Route one tool call to the connected client that provides it (owner
|
|
382
|
+
* first; cross-app peer otherwise, plan §29) and apply the approval
|
|
383
|
+
* policy. Shared by the regular tool specs and the REPL's cell tool calls.
|
|
384
|
+
*/
|
|
385
|
+
async routeTool(sessionId, toolCallId, toolName, args, mode, mcpServerId, ownerClientId, ownerApplication,
|
|
386
|
+
/** Set for caller sessions (external MCP clients, no owner). */
|
|
387
|
+
caller) {
|
|
388
|
+
// In legacy (no registry) mode there is a single client — always the target.
|
|
389
|
+
const target = this.registry ? this.resolveTargetFor(ownerClientId, toolName, caller) : undefined;
|
|
390
|
+
const targetTransport = target ? target.transport : this.legacyTransport();
|
|
391
|
+
const isOwnerPath = !target || target.clientId === ownerClientId;
|
|
392
|
+
// Tools the policy marks as approval-gated (browser_screenshot on
|
|
393
|
+
// Firefox; every mail-surface tool on Thunderbird) require explicit
|
|
394
|
+
// user approval before they run. The policy is keyed on the application
|
|
395
|
+
// of the client that EXECUTES the tool — the routed target in broker
|
|
396
|
+
// mode, the owner otherwise.
|
|
397
|
+
const executingApp = target ? target.application : ownerApplication;
|
|
398
|
+
// External callers: the external-access switch, then a one-time approval
|
|
399
|
+
// of the caller for the executing app — before the per-tool policy.
|
|
400
|
+
if (caller)
|
|
401
|
+
await this.approveCaller(sessionId, caller, executingApp, targetTransport, toolName);
|
|
402
|
+
if (toolRequiresApproval(executingApp, toolName) && !this.autoApproves(toolName)) {
|
|
403
|
+
// Persistent "Deny" (PRODUCT.md §55): the user configured this tool to
|
|
404
|
+
// be refused WITHOUT asking — no prompt, structured denial.
|
|
405
|
+
if (this.permissions.isDenied(toolName)) {
|
|
406
|
+
this.log.info(`${toolName}: persistently denied by the user — refusing without a prompt`);
|
|
407
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_PERMISSION_DENIED, `${toolName} is denied by the user in the Permission Configuration. Ask them to set it to Ask or Always approve.`, { tool: toolName });
|
|
408
|
+
}
|
|
409
|
+
// Cross-app: the prompt shows in ANOTHER app than the one the user is
|
|
410
|
+
// watching. Tell the session owner so its UI can point the user at the
|
|
411
|
+
// mail/browser client (display-only; the executing client owns the
|
|
412
|
+
// actual session/request_permission round-trip). In broker mode the
|
|
413
|
+
// registry is authoritative for the owner's application (the
|
|
414
|
+
// createTools parameter is only the legacy-mode default).
|
|
415
|
+
if (this.willPrompt(sessionId, toolName)) {
|
|
416
|
+
const ownerApp = this.registry && ownerClientId !== undefined
|
|
417
|
+
? this.registry.get(ownerClientId)?.application ?? ownerApplication
|
|
418
|
+
: ownerApplication;
|
|
419
|
+
this.announceRemotePrompt({
|
|
420
|
+
ownerClientId,
|
|
421
|
+
ownerApplication: ownerApp,
|
|
422
|
+
executingApp,
|
|
423
|
+
sessionId,
|
|
424
|
+
toolCallId,
|
|
425
|
+
toolName,
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
await this.requestPermission(sessionId, toolCallId, toolName, targetTransport, args, caller);
|
|
429
|
+
}
|
|
430
|
+
if (toolRequiresApproval(executingApp, toolName) && this.autoApproves(toolName)) {
|
|
431
|
+
this.log.info(`${toolName}: approval auto-granted via PI_BROWSER_AUTO_APPROVE (test seam)`);
|
|
432
|
+
}
|
|
433
|
+
const state = this.ensureState(sessionId, mode, mcpServerId, isOwnerPath ? targetTransport : undefined);
|
|
434
|
+
// The session's own MCP-over-ACP connection is used only for the owner's
|
|
435
|
+
// own tools; cross-app tools always go over the target client's legacy
|
|
436
|
+
// x-pi-browser/tool callback.
|
|
437
|
+
const useOwnerMcp = isOwnerPath && state.mode === "mcp-acp" && state.mcp !== undefined;
|
|
438
|
+
const transport = useOwnerMcp
|
|
439
|
+
? state.mcp
|
|
440
|
+
: new LegacyBrowserCallbackTransport(targetTransport, {
|
|
441
|
+
timeoutMs: this.timeoutForTool,
|
|
442
|
+
// Last streamed batch for the timed-out call (mail_search).
|
|
443
|
+
getPartial: (id) => this.partialFor(id),
|
|
444
|
+
});
|
|
445
|
+
// Track the call so tool_update notifications can be validated against
|
|
446
|
+
// (and cleaned up after) it.
|
|
447
|
+
this.activeToolCalls.set(toolCallId, {
|
|
448
|
+
sessionId,
|
|
449
|
+
tool: toolName,
|
|
450
|
+
clientId: target?.clientId ?? ownerClientId,
|
|
451
|
+
lastSequence: 0,
|
|
452
|
+
lastBatch: undefined,
|
|
453
|
+
lastScanned: undefined,
|
|
454
|
+
startedAt: Date.now(),
|
|
455
|
+
});
|
|
456
|
+
const t0 = Date.now();
|
|
457
|
+
// The round-trip line logs only duration + isError — with
|
|
458
|
+
// PI_BROWSER_LOG_TOOL_IO the full request args and response are logged too.
|
|
459
|
+
const toolIo = this.logToolIo();
|
|
460
|
+
if (toolIo)
|
|
461
|
+
this.log.info(`${toolName}: REQUEST ${safeJson(args)}`);
|
|
462
|
+
try {
|
|
463
|
+
const result = await this.executeWithTracking(transport, sessionId, toolName, args, toolCallId);
|
|
464
|
+
this.log.info(`${toolName}: tool round-trip ${Date.now() - t0}ms (client=${target?.clientId ?? "legacy"}, transport=${useOwnerMcp ? "mcp-acp" : "callback"}, isError=${result.isError ?? false})`);
|
|
465
|
+
if (toolIo)
|
|
466
|
+
this.log.info(`${toolName}: RESPONSE ${safeJson(result)}`);
|
|
467
|
+
return result;
|
|
468
|
+
}
|
|
469
|
+
catch (err) {
|
|
470
|
+
this.log.info(`${toolName}: tool round-trip FAILED after ${Date.now() - t0}ms: ${String(err)}`);
|
|
471
|
+
throw err;
|
|
472
|
+
}
|
|
473
|
+
finally {
|
|
474
|
+
this.activeToolCalls.delete(toolCallId);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Test-only approval seam: PI_BROWSER_AUTO_APPROVE (comma list of tool
|
|
479
|
+
* names or "*") grants the host-side approval gate WITHOUT prompting a
|
|
480
|
+
* user. Never read in production paths — the launcher must opt in.
|
|
481
|
+
* Used by .probe/live-mail-search.mjs, which has no UI to click.
|
|
482
|
+
*/
|
|
483
|
+
autoApproves(toolName) {
|
|
484
|
+
const raw = process.env.PI_BROWSER_AUTO_APPROVE;
|
|
485
|
+
if (!raw)
|
|
486
|
+
return false;
|
|
487
|
+
const list = raw.split(",").map((s) => s.trim()).filter(Boolean);
|
|
488
|
+
return list.includes("*") || list.includes(toolName);
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Test-only I/O logging seam: PI_BROWSER_LOG_TOOL_IO=1 makes the host log
|
|
492
|
+
* the FULL request args and response of every browser tool call. The skills
|
|
493
|
+
* e2e matrix sets it so each scripted step is reconstructable from
|
|
494
|
+
* host.log; off in production.
|
|
495
|
+
*/
|
|
496
|
+
logToolIo() {
|
|
497
|
+
return process.env.PI_BROWSER_LOG_TOOL_IO === "1";
|
|
498
|
+
}
|
|
499
|
+
// ------------------------------------------------------------------
|
|
500
|
+
// Permission configuration (x-pi-browser/permissions|set|clear, §55)
|
|
501
|
+
// ------------------------------------------------------------------
|
|
502
|
+
/**
|
|
503
|
+
* The full gated-tool inventory with each tool's persistent state
|
|
504
|
+
* (ask | deny | allow) — the data the add-on's Configuration page
|
|
505
|
+
* renders.
|
|
506
|
+
*/
|
|
507
|
+
permissionConfig() {
|
|
508
|
+
return {
|
|
509
|
+
tools: listGatedTools().map((t) => ({
|
|
510
|
+
name: t.name,
|
|
511
|
+
description: t.description,
|
|
512
|
+
group: t.group,
|
|
513
|
+
state: this.permissions.getState(t.name),
|
|
514
|
+
...(t.managedBy ? { managedBy: t.managedBy } : {}),
|
|
515
|
+
...(t.note ? { note: t.note } : {}),
|
|
516
|
+
})),
|
|
517
|
+
externalAccess: this.permissions.getExternalAccess(),
|
|
518
|
+
callers: this.permissions.listCallers(),
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
/** Turn external MCP access on or off (Configuration page). */
|
|
522
|
+
setExternalAccess(on) {
|
|
523
|
+
this.permissions.setExternalAccess(on);
|
|
524
|
+
this.log.info(`external MCP access turned ${on ? "on" : "off"} from Configuration page`);
|
|
525
|
+
return { externalAccess: on };
|
|
526
|
+
}
|
|
527
|
+
/** Remember or forget ("ask") a caller's decision for one app. */
|
|
528
|
+
setCallerPermission(caller, state) {
|
|
529
|
+
if (caller.application !== "firefox" && caller.application !== "thunderbird") {
|
|
530
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, `unknown application: ${String(caller.application)}`);
|
|
531
|
+
}
|
|
532
|
+
if (typeof caller.name !== "string" || caller.name === "") {
|
|
533
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, "caller name required");
|
|
534
|
+
}
|
|
535
|
+
this.permissions.setCallerState(caller.application, caller.name, state);
|
|
536
|
+
// Running caller sessions re-check the store on their next call.
|
|
537
|
+
for (const entry of this.callerApprovals.values()) {
|
|
538
|
+
if (entry.name === caller.name)
|
|
539
|
+
entry.apps.delete(caller.application);
|
|
540
|
+
}
|
|
541
|
+
this.log.info(`caller ${caller.name}: ${caller.application} decision set to "${state}" from Configuration page`);
|
|
542
|
+
return { caller: { application: caller.application, name: caller.name }, state };
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Set one tool's persistent state (ask | deny | allow) from the
|
|
546
|
+
* Configuration page. Unknown tools and app-managed grants
|
|
547
|
+
* (browser_evaluate — Firefox owns its userScripts permission) are
|
|
548
|
+
* rejected.
|
|
549
|
+
*/
|
|
550
|
+
setToolPermission(tool, state) {
|
|
551
|
+
const entry = getGatedTool(tool);
|
|
552
|
+
if (!entry) {
|
|
553
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.MCP_TOOL_NOT_FOUND, `unknown tool: ${tool}`);
|
|
554
|
+
}
|
|
555
|
+
if (entry.managedBy) {
|
|
556
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, `${tool} is managed by ${entry.managedBy} — its grant cannot be changed here`);
|
|
557
|
+
}
|
|
558
|
+
if (entry.note) {
|
|
559
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, `${tool} has no toggleable state: ${entry.note}`);
|
|
560
|
+
}
|
|
561
|
+
this.permissions.setState(tool, state);
|
|
562
|
+
this.log.info(`${tool}: persistent state set to "${state}" from Configuration page`);
|
|
563
|
+
return { tool, state };
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Clear one tool's persistent grant, or every grant when `tool` is
|
|
567
|
+
* omitted. Returns the names that were cleared ("clear all" feedback).
|
|
568
|
+
*/
|
|
569
|
+
clearToolPermissions(tool) {
|
|
570
|
+
if (tool !== undefined) {
|
|
571
|
+
const entry = getGatedTool(tool);
|
|
572
|
+
if (!entry) {
|
|
573
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.MCP_TOOL_NOT_FOUND, `unknown tool: ${tool}`);
|
|
574
|
+
}
|
|
575
|
+
this.permissions.clear(tool);
|
|
576
|
+
this.log.info(`${tool}: persistent allow cleared from Configuration page`);
|
|
577
|
+
return { cleared: [tool] };
|
|
578
|
+
}
|
|
579
|
+
const cleared = this.permissions.clearAll();
|
|
580
|
+
this.log.info(`permissions: cleared ALL persistent allows (${cleared.length} tool(s))`);
|
|
581
|
+
return { cleared };
|
|
582
|
+
}
|
|
583
|
+
/** The last streamed progress for an in-flight call (timeout recovery). */
|
|
584
|
+
partialFor(toolCallId) {
|
|
585
|
+
const call = this.activeToolCalls.get(toolCallId);
|
|
586
|
+
if (!call)
|
|
587
|
+
return undefined;
|
|
588
|
+
const scanned = call.lastBatch?.scanned ?? call.lastScanned;
|
|
589
|
+
const nextCursor = call.lastBatch?.nextCursor ?? undefined;
|
|
590
|
+
if (scanned === undefined && !nextCursor)
|
|
591
|
+
return undefined;
|
|
592
|
+
return { ...(scanned !== undefined ? { scanned } : {}), ...(nextCursor ? { nextCursor } : {}) };
|
|
593
|
+
}
|
|
594
|
+
async executeWithTracking(transport, sessionId, toolName, args, toolCallId) {
|
|
595
|
+
const result = await transport.call(sessionId, toolName, args, toolCallId);
|
|
596
|
+
if (result.isError) {
|
|
597
|
+
const text = result.content
|
|
598
|
+
.filter((c) => c.type === "text")
|
|
599
|
+
.map((c) => c.text)
|
|
600
|
+
.join("\n");
|
|
601
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, text || "browser tool failed", {
|
|
602
|
+
tool: toolName,
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
return result;
|
|
606
|
+
}
|
|
607
|
+
/**
|
|
608
|
+
* Validate one x-pi-browser/tool_update notification (client → host) and
|
|
609
|
+
* forward it to the ACP mapping hook. Drops (never throws) when any check
|
|
610
|
+
* fails:
|
|
611
|
+
* - the toolCallId is not an in-flight call;
|
|
612
|
+
* - the sessionId does not match the pending call;
|
|
613
|
+
* - the tool is not mail_search (the only streaming tool today);
|
|
614
|
+
* - the source client is not the client executing the call;
|
|
615
|
+
* - the sequence is not strictly greater than the last accepted one.
|
|
616
|
+
* The update never authorizes anything — it only reports results of the
|
|
617
|
+
* already-approved call.
|
|
618
|
+
*/
|
|
619
|
+
handleToolUpdate(params, sourceClientId) {
|
|
620
|
+
const call = this.activeToolCalls.get(params.toolCallId);
|
|
621
|
+
if (!call) {
|
|
622
|
+
this.log.debug(`tool_update dropped: unknown toolCall ${params.toolCallId}`);
|
|
623
|
+
return;
|
|
624
|
+
}
|
|
625
|
+
if (params.sessionId !== call.sessionId) {
|
|
626
|
+
this.log.debug(`tool_update dropped: session mismatch for ${params.toolCallId}`);
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
if (params.tool !== "mail_search" || call.tool !== "mail_search") {
|
|
630
|
+
this.log.debug(`tool_update dropped: tool ${params.tool} does not stream`);
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
if (call.clientId !== undefined && sourceClientId !== undefined && call.clientId !== sourceClientId) {
|
|
634
|
+
this.log.debug(`tool_update dropped: client ${sourceClientId} is not executing ${params.toolCallId}`);
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
if (params.sequence !== undefined) {
|
|
638
|
+
if (params.sequence <= call.lastSequence) {
|
|
639
|
+
this.log.debug(`tool_update dropped: non-monotonic sequence ${params.sequence} for ${params.toolCallId}`);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
call.lastSequence = params.sequence;
|
|
643
|
+
}
|
|
644
|
+
if (params.update.kind === "batch")
|
|
645
|
+
call.lastBatch = params.update.result;
|
|
646
|
+
else if (params.update.kind === "progress")
|
|
647
|
+
call.lastScanned = params.update.scanned;
|
|
648
|
+
const extra = params.update.kind === "progress"
|
|
649
|
+
? ` scanned=${params.update.scanned} elapsedMs=${params.update.elapsedMs ?? "?"} pageMs=${params.update.pageMs ?? "?"}`
|
|
650
|
+
: params.update.kind === "batch"
|
|
651
|
+
? ` messages=${params.update.result.messages.length} scanned=${params.update.result.scanned ?? "?"} complete=${params.update.result.complete ?? "?"}`
|
|
652
|
+
: "";
|
|
653
|
+
this.log.info(`mail_search tool_update kind=${params.update.kind} seq=${params.sequence ?? "-"}${extra} at ${Date.now() - call.startedAt}ms`);
|
|
654
|
+
this.onToolUpdate?.(call.sessionId, params.toolCallId, params.update);
|
|
655
|
+
}
|
|
656
|
+
/**
|
|
657
|
+
* Coalesced permission groups: parallel tool calls that arrive while a
|
|
658
|
+
* session's approval prompt is being assembled share ONE prompt card.
|
|
659
|
+
* Models routinely emit several tool calls in the same turn (e.g. two
|
|
660
|
+
* mail_get_message_body calls for two messages); without coalescing the
|
|
661
|
+
* client UI shows only the last card and the other request times out.
|
|
662
|
+
*/
|
|
663
|
+
permissionGroups = new Map();
|
|
664
|
+
/**
|
|
665
|
+
* Ask the client for permission to run a sensitive tool. Blocks until the
|
|
666
|
+
* user responds (or the prompt times out). "Always allow" is remembered for
|
|
667
|
+
* the rest of the host lifetime. A denial/timeout surfaces a structured
|
|
668
|
+
* BROWSER_PERMISSION_DENIED error so the agent can react.
|
|
669
|
+
*
|
|
670
|
+
* Concurrent requests for the same session are coalesced: a short window
|
|
671
|
+
* collects parallel calls, then ONE request_permission is sent whose card
|
|
672
|
+
* names every coalesced call; the single answer applies to all of them.
|
|
673
|
+
*/
|
|
674
|
+
/** True when a permission prompt WILL be sent for this tool call. */
|
|
675
|
+
willPrompt(sessionId, toolName) {
|
|
676
|
+
if (toolName === "browser_evaluate")
|
|
677
|
+
return true; // Firefox checks the current browser grant.
|
|
678
|
+
return (!this.autoApproves(toolName) &&
|
|
679
|
+
!this.permissions.isAllowed(toolName) &&
|
|
680
|
+
!this.sessionAllowed.get(sessionId)?.has(toolName));
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Tell the session-owner client that the approval prompt is being shown in
|
|
684
|
+
* a different app (cross-app routing, plan §29). Fire-and-forget: if the
|
|
685
|
+
* owner's UI is closed or the app is a version without the banner, the
|
|
686
|
+
* prompt still works — the executing client's modal is authoritative.
|
|
687
|
+
*/
|
|
688
|
+
announceRemotePrompt(ctx) {
|
|
689
|
+
if (!this.registry ||
|
|
690
|
+
ctx.ownerClientId === undefined ||
|
|
691
|
+
ctx.ownerApplication === ctx.executingApp)
|
|
692
|
+
return;
|
|
693
|
+
const owner = this.registry.get(ctx.ownerClientId);
|
|
694
|
+
if (!owner)
|
|
695
|
+
return;
|
|
696
|
+
const params = {
|
|
697
|
+
sessionId: ctx.sessionId,
|
|
698
|
+
toolCallId: ctx.toolCallId,
|
|
699
|
+
tool: ctx.toolName,
|
|
700
|
+
application: ctx.executingApp,
|
|
701
|
+
};
|
|
702
|
+
this.log.info(`${ctx.toolName}: approval prompt shows in ${ctx.executingApp}; notifying session owner ${owner.clientId} (${owner.application})`);
|
|
703
|
+
owner.transport
|
|
704
|
+
.request(X_PI_BROWSER.permission_prompted, params, 5_000)
|
|
705
|
+
.catch((err) => {
|
|
706
|
+
this.log.debug(`permission_prompted → owner ${owner.clientId} failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
707
|
+
});
|
|
708
|
+
}
|
|
709
|
+
async requestPermission(sessionId, toolCallId, toolName, target, args, caller) {
|
|
710
|
+
if (!this.willPrompt(sessionId, toolName)) {
|
|
711
|
+
this.log.debug(`${toolName}: already allowed (session or host scope); skipping permission prompt`);
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
const argsSummary = summarizeArgs(args);
|
|
715
|
+
this.log.info(`${toolName}: requesting user permission (toolCall=${toolCallId}${argsSummary ? ` args=${argsSummary}` : ""})`);
|
|
716
|
+
return new Promise((resolve, reject) => {
|
|
717
|
+
const isEvaluate = toolName === "browser_evaluate";
|
|
718
|
+
let group = this.permissionGroups.get(sessionId);
|
|
719
|
+
// browser_evaluate has a different option set (Firefox owns the grant);
|
|
720
|
+
// it never joins a group of regular tools, and vice versa.
|
|
721
|
+
if (group && group.hasEvaluate !== isEvaluate)
|
|
722
|
+
group = undefined;
|
|
723
|
+
if (!group) {
|
|
724
|
+
group = { members: [], hasEvaluate: isEvaluate, target, settled: false, ...(caller ? { caller } : {}) };
|
|
725
|
+
this.permissionGroups.set(sessionId, group);
|
|
726
|
+
const captured = group;
|
|
727
|
+
group.flushTimer = setTimeout(() => { void this.sendPermissionRequest(sessionId, captured); }, PERMISSION_COALESCE_WINDOW_MS);
|
|
728
|
+
}
|
|
729
|
+
group.members.push({ toolCallId, toolName, resolve, reject });
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Send the single coalesced permission prompt for a group's members and
|
|
734
|
+
* settle every member with the user's one decision.
|
|
735
|
+
*/
|
|
736
|
+
async sendPermissionRequest(sessionId, group) {
|
|
737
|
+
if (group.settled)
|
|
738
|
+
return;
|
|
739
|
+
group.settled = true;
|
|
740
|
+
if (group.flushTimer)
|
|
741
|
+
clearTimeout(group.flushTimer);
|
|
742
|
+
this.permissionGroups.delete(sessionId);
|
|
743
|
+
const { members } = group;
|
|
744
|
+
const first = members[0];
|
|
745
|
+
const title = members.length === 1
|
|
746
|
+
? first.toolName
|
|
747
|
+
: `${members.length} parallel calls: ` +
|
|
748
|
+
[...new Set(members.map((m) => m.toolName))].map((n) => {
|
|
749
|
+
const c = members.filter((m) => m.toolName === n).length;
|
|
750
|
+
return c > 1 ? `${n} ×${c}` : n;
|
|
751
|
+
}).join(", ");
|
|
752
|
+
this.log.info(`permission: prompting for ${members.length} call(s) [${title}] (session=${sessionId})`);
|
|
753
|
+
const request = buildPermissionRequest({
|
|
754
|
+
sessionId,
|
|
755
|
+
toolCallId: first.toolCallId,
|
|
756
|
+
title,
|
|
757
|
+
toolName: first.toolName,
|
|
758
|
+
...(group.caller ? { caller: callerMeta(group.caller) } : {}),
|
|
759
|
+
});
|
|
760
|
+
let response;
|
|
761
|
+
let failure;
|
|
762
|
+
try {
|
|
763
|
+
response = await this.sendTrackedPrompt(sessionId, group.target, request);
|
|
764
|
+
}
|
|
765
|
+
catch (err) {
|
|
766
|
+
failure = err instanceof TransportTimeoutError
|
|
767
|
+
? `the user did not respond to the permission prompt for ${first.toolName} within ${Math.round(this.permissionTimeoutMs / 1000)} s`
|
|
768
|
+
: `permission request for ${first.toolName} failed or timed out: ${err instanceof Error ? err.message : String(err)}`;
|
|
769
|
+
}
|
|
770
|
+
const allowed = failure === undefined && permissionAllowed(response);
|
|
771
|
+
if (allowed && response) {
|
|
772
|
+
const optionId = response.outcome.outcome === "selected" ? response.outcome.optionId : "";
|
|
773
|
+
// The card named every coalesced tool — the answer applies to all of
|
|
774
|
+
// them, including the remembered scopes.
|
|
775
|
+
for (const toolName of new Set(members.map((m) => m.toolName))) {
|
|
776
|
+
if (toolName === "browser_evaluate")
|
|
777
|
+
continue; // Never cache Firefox's revocable userScripts grant.
|
|
778
|
+
if (optionId === "allow_always") {
|
|
779
|
+
// Persistent: remembered across host restarts and toggleable from
|
|
780
|
+
// the add-on's Configuration page.
|
|
781
|
+
this.permissions.setAllowed(toolName, true);
|
|
782
|
+
this.log.info(`${toolName}: user chose Always allow (persisted)`);
|
|
783
|
+
}
|
|
784
|
+
else if (optionId === "allow_session") {
|
|
785
|
+
let set = this.sessionAllowed.get(sessionId);
|
|
786
|
+
if (!set) {
|
|
787
|
+
set = new Set();
|
|
788
|
+
this.sessionAllowed.set(sessionId, set);
|
|
789
|
+
}
|
|
790
|
+
set.add(toolName);
|
|
791
|
+
this.log.info(`${toolName}: user chose Allow for this session (${sessionId})`);
|
|
792
|
+
}
|
|
793
|
+
else {
|
|
794
|
+
this.log.info(`${toolName}: user chose Allow once`);
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
else if (!allowed) {
|
|
799
|
+
this.log.warn(`permission: user denied (or prompt failed) for [${title}]`);
|
|
800
|
+
}
|
|
801
|
+
for (const m of members) {
|
|
802
|
+
if (allowed) {
|
|
803
|
+
m.resolve();
|
|
804
|
+
}
|
|
805
|
+
else {
|
|
806
|
+
m.reject(new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_PERMISSION_DENIED, failure ?? `user denied permission to run ${m.toolName}`, { tool: m.toolName }));
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
// ------------------------------------------------------------------
|
|
811
|
+
// External MCP callers (openspec external-mcp-callers, D4–D6)
|
|
812
|
+
// ------------------------------------------------------------------
|
|
813
|
+
/** Caller-session approvals per executing app, cached for the session. */
|
|
814
|
+
callerApprovals = new Map();
|
|
815
|
+
/** In-flight caller-approval prompts ("<session>|<app>"): concurrent calls share one. */
|
|
816
|
+
callerPrompts = new Map();
|
|
817
|
+
/** Permission requests still waiting for an answer, per session (for withdrawal). */
|
|
818
|
+
openPrompts = new Map();
|
|
819
|
+
/**
|
|
820
|
+
* resolveTarget, with a caller-friendly error when no connected app
|
|
821
|
+
* serves the tool ("browser_get_page needs Firefox with the Pi add-on
|
|
822
|
+
* running").
|
|
823
|
+
*/
|
|
824
|
+
resolveTargetFor(ownerClientId, toolName, caller) {
|
|
825
|
+
const registry = this.registry;
|
|
826
|
+
try {
|
|
827
|
+
return registry.resolveTarget(ownerClientId, toolName);
|
|
828
|
+
}
|
|
829
|
+
catch (err) {
|
|
830
|
+
const app = applicationForTool(toolName);
|
|
831
|
+
if (!caller || !app || !(err instanceof PiBrowserProtocolError) || err.code !== PI_BROWSER_ERROR.MCP_UNAVAILABLE) {
|
|
832
|
+
throw err;
|
|
833
|
+
}
|
|
834
|
+
const name = applicationShortName(app);
|
|
835
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.MCP_UNAVAILABLE, `${toolName} needs ${name} with the Pi add-on running. Ask the user to open ${name}, then retry.`, { tool: toolName });
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* The caller gate: refuse when external access is off; otherwise make sure
|
|
840
|
+
* the caller is approved for the executing app (session cache → stored
|
|
841
|
+
* decision → one prompt in that app).
|
|
842
|
+
*/
|
|
843
|
+
async approveCaller(sessionId, caller, app, target, toolName) {
|
|
844
|
+
if (!this.permissions.getExternalAccess()) {
|
|
845
|
+
this.log.info(`${toolName}: external MCP access is off — refusing ${caller.name} without a prompt`);
|
|
846
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_PERMISSION_DENIED, EXTERNAL_ACCESS_OFF_MESSAGE, {
|
|
847
|
+
tool: toolName,
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
const appName = applicationShortName(app);
|
|
851
|
+
const deniedError = () => new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_PERMISSION_DENIED, `the user denied ${caller.name} access to the ${appName} tools. Ask them to allow it in the Pi permissions page.`, { tool: toolName });
|
|
852
|
+
const cached = this.callerApprovals.get(sessionId)?.apps.get(app);
|
|
853
|
+
if (cached === "allow")
|
|
854
|
+
return;
|
|
855
|
+
if (cached === "deny")
|
|
856
|
+
throw deniedError();
|
|
857
|
+
const stored = this.permissions.getCallerState(app, caller.name);
|
|
858
|
+
if (stored) {
|
|
859
|
+
this.cacheCallerDecision(sessionId, caller, app, stored);
|
|
860
|
+
if (stored === "allow")
|
|
861
|
+
return;
|
|
862
|
+
this.log.info(`${toolName}: caller ${caller.name} is denied for ${app} — refusing without a prompt`);
|
|
863
|
+
throw deniedError();
|
|
864
|
+
}
|
|
865
|
+
if (this.autoApproves("*")) {
|
|
866
|
+
this.log.info(`caller ${caller.name}: approval auto-granted for ${app} via PI_BROWSER_AUTO_APPROVE (test seam)`);
|
|
867
|
+
this.cacheCallerDecision(sessionId, caller, app, "allow");
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
const key = `${sessionId}|${app}`;
|
|
871
|
+
let pending = this.callerPrompts.get(key);
|
|
872
|
+
if (!pending) {
|
|
873
|
+
pending = this.promptCaller(sessionId, caller, app, target, toolName).finally(() => {
|
|
874
|
+
this.callerPrompts.delete(key);
|
|
875
|
+
});
|
|
876
|
+
this.callerPrompts.set(key, pending);
|
|
877
|
+
}
|
|
878
|
+
await pending;
|
|
879
|
+
}
|
|
880
|
+
cacheCallerDecision(sessionId, caller, app, state) {
|
|
881
|
+
let entry = this.callerApprovals.get(sessionId);
|
|
882
|
+
if (!entry) {
|
|
883
|
+
entry = { name: caller.name, apps: new Map() };
|
|
884
|
+
this.callerApprovals.set(sessionId, entry);
|
|
885
|
+
}
|
|
886
|
+
entry.apps.set(app, state);
|
|
887
|
+
}
|
|
888
|
+
/** Ask the executing app whether the caller may use its tools. */
|
|
889
|
+
async promptCaller(sessionId, caller, app, target, toolName) {
|
|
890
|
+
const appName = applicationShortName(app);
|
|
891
|
+
const request = buildCallerApprovalRequest({
|
|
892
|
+
sessionId,
|
|
893
|
+
toolCallId: `caller:${crypto.randomUUID()}`,
|
|
894
|
+
caller: callerMeta(caller),
|
|
895
|
+
application: app,
|
|
896
|
+
toolName,
|
|
897
|
+
});
|
|
898
|
+
this.log.info(`caller ${caller.name}: asking ${app} to approve it (first call: ${toolName}, session=${sessionId})`);
|
|
899
|
+
let response;
|
|
900
|
+
try {
|
|
901
|
+
response = await this.sendTrackedPrompt(sessionId, target, request);
|
|
902
|
+
}
|
|
903
|
+
catch (err) {
|
|
904
|
+
const text = err instanceof TransportTimeoutError
|
|
905
|
+
? `the user did not respond within ${Math.round(this.permissionTimeoutMs / 1000)} s to the prompt allowing ${caller.name} to use the ${appName} tools`
|
|
906
|
+
: `the prompt allowing ${caller.name} to use the ${appName} tools failed: ${err instanceof Error ? err.message : String(err)}`;
|
|
907
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_PERMISSION_DENIED, text, { tool: toolName });
|
|
908
|
+
}
|
|
909
|
+
const outcome = response?.outcome;
|
|
910
|
+
const optionId = outcome?.outcome === "selected" ? outcome.optionId : undefined;
|
|
911
|
+
if (optionId === CALLER_ALLOW_ALWAYS) {
|
|
912
|
+
this.permissions.setCallerState(app, caller.name, "allow");
|
|
913
|
+
this.cacheCallerDecision(sessionId, caller, app, "allow");
|
|
914
|
+
this.log.info(`caller ${caller.name}: always allowed for ${app} (persisted)`);
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
if (optionId === CALLER_ALLOW_ONCE) {
|
|
918
|
+
this.cacheCallerDecision(sessionId, caller, app, "allow");
|
|
919
|
+
this.log.info(`caller ${caller.name}: allowed for ${app} for this connection`);
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
if (optionId === CALLER_DENY) {
|
|
923
|
+
this.permissions.setCallerState(app, caller.name, "deny");
|
|
924
|
+
this.cacheCallerDecision(sessionId, caller, app, "deny");
|
|
925
|
+
this.log.info(`caller ${caller.name}: denied for ${app} (persisted)`);
|
|
926
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_PERMISSION_DENIED, `the user denied ${caller.name} access to the ${appName} tools. Ask them to allow it in the Pi permissions page.`, { tool: toolName });
|
|
927
|
+
}
|
|
928
|
+
// Cancelled (approval window closed, add-on-side timeout) or unknown:
|
|
929
|
+
// deny this call only — nothing is remembered, the next call asks again.
|
|
930
|
+
this.log.info(`caller ${caller.name}: approval for ${app} cancelled (not remembered)`);
|
|
931
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.BROWSER_PERMISSION_DENIED, `the user denied the request (the approval prompt for ${caller.name} was closed without an answer)`, { tool: toolName });
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Send a session/request_permission and remember it until it settles, so
|
|
935
|
+
* a timeout or a closed caller session can withdraw it from the add-on UI
|
|
936
|
+
* (x-pi-browser/permission_withdrawn).
|
|
937
|
+
*/
|
|
938
|
+
async sendTrackedPrompt(sessionId, target, request) {
|
|
939
|
+
const entry = { toolCallId: request.toolCall.toolCallId, target };
|
|
940
|
+
let set = this.openPrompts.get(sessionId);
|
|
941
|
+
if (!set) {
|
|
942
|
+
set = new Set();
|
|
943
|
+
this.openPrompts.set(sessionId, set);
|
|
944
|
+
}
|
|
945
|
+
set.add(entry);
|
|
946
|
+
try {
|
|
947
|
+
return await target.request(REQUEST_PERMISSION_METHOD, request, this.permissionTimeoutMs);
|
|
948
|
+
}
|
|
949
|
+
catch (err) {
|
|
950
|
+
if (err instanceof TransportTimeoutError)
|
|
951
|
+
this.withdrawPrompt(sessionId, entry, "timeout");
|
|
952
|
+
throw err;
|
|
953
|
+
}
|
|
954
|
+
finally {
|
|
955
|
+
const s = this.openPrompts.get(sessionId);
|
|
956
|
+
s?.delete(entry);
|
|
957
|
+
if (s && s.size === 0)
|
|
958
|
+
this.openPrompts.delete(sessionId);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
withdrawPrompt(sessionId, prompt, reason) {
|
|
962
|
+
const params = { sessionId, toolCallId: prompt.toolCallId, reason };
|
|
963
|
+
try {
|
|
964
|
+
prompt.target.notify(PERMISSION_WITHDRAWN_METHOD, params);
|
|
965
|
+
}
|
|
966
|
+
catch (err) {
|
|
967
|
+
this.log.debug(`permission_withdrawn failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
/** Ensure per-session transport state exists (called at tool execution). */
|
|
971
|
+
ensureState(sessionId, mode, mcpServerId, ownerTransport) {
|
|
972
|
+
let state = this.sessions.get(sessionId);
|
|
973
|
+
if (!state) {
|
|
974
|
+
if (mode === "mcp-acp" && mcpServerId && ownerTransport) {
|
|
975
|
+
// Only the session owner's MCP-over-ACP connection is created (the
|
|
976
|
+
// owner passes its transport); peer (cross-app) calls use legacy.
|
|
977
|
+
state = {
|
|
978
|
+
mode,
|
|
979
|
+
mcp: new NativeMcpOverAcpTransport(ownerTransport, mcpServerId, this.log, sessionId),
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
else {
|
|
983
|
+
state = { mode };
|
|
984
|
+
}
|
|
985
|
+
this.sessions.set(sessionId, state);
|
|
986
|
+
this.log.info(`browser state for session ${sessionId}: mode=${state.mode}`);
|
|
987
|
+
}
|
|
988
|
+
return state;
|
|
989
|
+
}
|
|
990
|
+
/** Handle x-pi-browser/notify (tab closed/navigated, binding changes). */
|
|
991
|
+
handleNotify(params) {
|
|
992
|
+
this.log.debug(`x-pi-browser/notify ${params.event} session=${params.sessionId}`);
|
|
993
|
+
// Element references are owned by the content script and validated at
|
|
994
|
+
// use time (isConnected). No host-side ref state to invalidate today; the
|
|
995
|
+
// hook exists so future transports can react (e.g. drop MCP connections
|
|
996
|
+
// when the bound tab closes).
|
|
997
|
+
if (params.event === "tab_closed") {
|
|
998
|
+
const state = this.sessions.get(params.sessionId);
|
|
999
|
+
if (state?.mcp) {
|
|
1000
|
+
// Keep the MCP connection: the provider tab may have other tabs
|
|
1001
|
+
// bound later, and reconnecting is cheap. Log only.
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
// The REPL's page handle (active tab) and element refs are stale after
|
|
1005
|
+
// any of these events; the next cell starts with a warning note.
|
|
1006
|
+
const replNotes = {
|
|
1007
|
+
binding_changed: "The session's tab binding changed — inspect the page (snapshot) before acting.",
|
|
1008
|
+
binding_removed: "The session's tab binding was removed — page.* calls will fail with BROWSER_NOT_BOUND until re-bound.",
|
|
1009
|
+
tab_closed: "The bound tab was closed — page.* calls will fail with BROWSER_TAB_CLOSED until re-bound.",
|
|
1010
|
+
tab_navigated: "The bound tab navigated — element refs are stale; snapshot again before acting.",
|
|
1011
|
+
};
|
|
1012
|
+
this.repl.invalidate(params.sessionId, replNotes[params.event]);
|
|
1013
|
+
}
|
|
1014
|
+
/**
|
|
1015
|
+
* Bind a session's `javascript` REPL workspace to the task's scratch dir
|
|
1016
|
+
* (the session cwd). Delegates to the REPL provider; takes effect from the
|
|
1017
|
+
* session's next cell.
|
|
1018
|
+
*/
|
|
1019
|
+
bindWorkspace(sessionId, workspace) {
|
|
1020
|
+
this.repl.bindWorkspace(sessionId, workspace);
|
|
1021
|
+
}
|
|
1022
|
+
/** Release per-session state (session/close or host shutdown). */
|
|
1023
|
+
async disposeSession(sessionId) {
|
|
1024
|
+
this.sessionAllowed.delete(sessionId);
|
|
1025
|
+
this.callerApprovals.delete(sessionId);
|
|
1026
|
+
// A prompt still showing for a session that ended (an MCP caller
|
|
1027
|
+
// disconnected) can never be answered usefully: withdraw it.
|
|
1028
|
+
for (const prompt of this.openPrompts.get(sessionId) ?? [])
|
|
1029
|
+
this.withdrawPrompt(sessionId, prompt, "session_closed");
|
|
1030
|
+
this.openPrompts.delete(sessionId);
|
|
1031
|
+
const state = this.sessions.get(sessionId);
|
|
1032
|
+
if (state) {
|
|
1033
|
+
this.sessions.delete(sessionId);
|
|
1034
|
+
if (state.mcp)
|
|
1035
|
+
await state.mcp.dispose();
|
|
1036
|
+
}
|
|
1037
|
+
// Reap the session's REPL worker child (no orphan processes). A session
|
|
1038
|
+
// may have a runtime without browser state (cells that never touched a
|
|
1039
|
+
// browser tool), so this runs unconditionally and is idempotent.
|
|
1040
|
+
await this.repl.disposeSession(sessionId);
|
|
1041
|
+
}
|
|
1042
|
+
async shutdown() {
|
|
1043
|
+
for (const id of [...this.sessions.keys()])
|
|
1044
|
+
await this.disposeSession(id);
|
|
1045
|
+
// Runtimes of sessions with no browser state are reaped here.
|
|
1046
|
+
await this.repl.shutdown();
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
//# sourceMappingURL=provider.js.map
|