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,298 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One external ACP agent process and the host's ACP *client* connection to
|
|
3
|
+
* it (openspec sidebar-acp-agents D2).
|
|
4
|
+
*
|
|
5
|
+
* The host speaks newline-delimited JSON-RPC 2.0 over the agent's stdio, the
|
|
6
|
+
* ACP stdio transport. It does not go through the SDK's typed client: the
|
|
7
|
+
* relay forwards the agent's `session/update` notifications to the add-on
|
|
8
|
+
* as they are, and a schema-validating client would drop fields it doesn't
|
|
9
|
+
* know (newer update kinds, `_meta`).
|
|
10
|
+
*
|
|
11
|
+
* - initialize once per start, with no client file system or terminal;
|
|
12
|
+
* - every message in either direction counts as activity (idle stop, D2a);
|
|
13
|
+
* - the agent's stderr goes to the host log, prefixed with its id;
|
|
14
|
+
* - when the process exits, every pending request rejects with
|
|
15
|
+
* "<Agent> stopped (exit code N)" and `onExit` fires.
|
|
16
|
+
*/
|
|
17
|
+
import { spawn } from "node:child_process";
|
|
18
|
+
import { createInterface } from "node:readline";
|
|
19
|
+
import { PROTOCOL_VERSION, PI_BROWSER_META } from "@pi-browser/protocol";
|
|
20
|
+
/** A JSON-RPC error the agent returned. */
|
|
21
|
+
export class AgentRpcError extends Error {
|
|
22
|
+
code;
|
|
23
|
+
data;
|
|
24
|
+
constructor(code, message, data) {
|
|
25
|
+
super(message);
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.data = data;
|
|
28
|
+
this.name = "AgentRpcError";
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** The agent process ended while a request was waiting. */
|
|
32
|
+
export class AgentStoppedError extends Error {
|
|
33
|
+
constructor(message) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = "AgentStoppedError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Quote one argument for cmd.exe /s /c "<line>". */
|
|
39
|
+
function quoteForCmd(arg) {
|
|
40
|
+
if (arg !== "" && !/[\s"&|<>^%()!,;=]/.test(arg))
|
|
41
|
+
return arg;
|
|
42
|
+
return `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"`;
|
|
43
|
+
}
|
|
44
|
+
export class AgentConnection {
|
|
45
|
+
spec;
|
|
46
|
+
log;
|
|
47
|
+
handlers;
|
|
48
|
+
now;
|
|
49
|
+
stopGraceMs;
|
|
50
|
+
initializeTimeoutMs;
|
|
51
|
+
executable;
|
|
52
|
+
child;
|
|
53
|
+
nextId = 1;
|
|
54
|
+
pending = new Map();
|
|
55
|
+
stopping = false;
|
|
56
|
+
exited = false;
|
|
57
|
+
/** Last message in either direction (ms). */
|
|
58
|
+
lastActivity;
|
|
59
|
+
/** Turns running + permission requests waiting (D2a: not idle while > 0). */
|
|
60
|
+
holds = 0;
|
|
61
|
+
init;
|
|
62
|
+
constructor(opts) {
|
|
63
|
+
this.spec = opts.spec;
|
|
64
|
+
this.executable = opts.executable;
|
|
65
|
+
this.log = opts.log;
|
|
66
|
+
this.handlers = opts.handlers;
|
|
67
|
+
this.now = opts.now ?? Date.now;
|
|
68
|
+
this.stopGraceMs = opts.stopGraceMs ?? 3_000;
|
|
69
|
+
this.initializeTimeoutMs = opts.initializeTimeoutMs ?? 60_000;
|
|
70
|
+
this.lastActivity = this.now();
|
|
71
|
+
}
|
|
72
|
+
get alive() {
|
|
73
|
+
return this.child !== undefined && !this.exited;
|
|
74
|
+
}
|
|
75
|
+
get pid() {
|
|
76
|
+
return this.child?.pid;
|
|
77
|
+
}
|
|
78
|
+
/** Busy (a turn or a permission request): never idle-stopped. */
|
|
79
|
+
get busy() {
|
|
80
|
+
return this.holds > 0;
|
|
81
|
+
}
|
|
82
|
+
/** Mark a turn or a waiting permission request; call the returned function when it ends. */
|
|
83
|
+
hold() {
|
|
84
|
+
this.holds++;
|
|
85
|
+
this.touch();
|
|
86
|
+
let released = false;
|
|
87
|
+
return () => {
|
|
88
|
+
if (released)
|
|
89
|
+
return;
|
|
90
|
+
released = true;
|
|
91
|
+
this.holds = Math.max(0, this.holds - 1);
|
|
92
|
+
this.touch();
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
touch() {
|
|
96
|
+
this.lastActivity = this.now();
|
|
97
|
+
}
|
|
98
|
+
/** Spawn the process and initialize it. Rejects with a readable error. */
|
|
99
|
+
async start() {
|
|
100
|
+
const { spec } = this;
|
|
101
|
+
const env = { ...process.env, ...spec.env };
|
|
102
|
+
const isCmd = process.platform === "win32" && /\.(cmd|bat)$/i.test(this.executable);
|
|
103
|
+
// Node refuses to spawn .cmd/.bat directly; go through cmd.exe with a
|
|
104
|
+
// fully quoted line. windowsHide: never flash a console window.
|
|
105
|
+
const child = isCmd
|
|
106
|
+
? spawn(env.ComSpec ?? "cmd.exe", ["/d", "/s", "/c", `"${[this.executable, ...spec.args].map(quoteForCmd).join(" ")}"`], {
|
|
107
|
+
env,
|
|
108
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
109
|
+
windowsHide: true,
|
|
110
|
+
windowsVerbatimArguments: true,
|
|
111
|
+
})
|
|
112
|
+
: spawn(this.executable, spec.args, { env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
|
|
113
|
+
this.child = child;
|
|
114
|
+
this.log.info(`agent ${spec.id}: started ${this.executable}${spec.args.length ? ` ${spec.args.join(" ")}` : ""} (pid ${child.pid ?? "?"})`);
|
|
115
|
+
const spawnError = new Promise((_, reject) => {
|
|
116
|
+
child.once("error", (err) => {
|
|
117
|
+
this.exited = true;
|
|
118
|
+
reject(new AgentStoppedError(`${spec.name} could not start: ${err.message}`));
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
spawnError.catch(() => undefined);
|
|
122
|
+
createInterface({ input: child.stdout, crlfDelay: Infinity }).on("line", (line) => this.onLine(line));
|
|
123
|
+
createInterface({ input: child.stderr, crlfDelay: Infinity }).on("line", (line) => {
|
|
124
|
+
if (line.trim())
|
|
125
|
+
this.log.debug(`[agent ${spec.id}] ${line.slice(0, 2000)}`);
|
|
126
|
+
});
|
|
127
|
+
child.stdin.on("error", (err) => this.log.debug(`agent ${spec.id}: stdin error: ${err.message}`));
|
|
128
|
+
child.once("exit", (code, signal) => {
|
|
129
|
+
this.exited = true;
|
|
130
|
+
const expected = this.stopping;
|
|
131
|
+
const what = code !== null ? `exit code ${code}` : `signal ${signal ?? "?"}`;
|
|
132
|
+
this.log[expected ? "info" : "warn"](`agent ${spec.id}: process ${child.pid ?? "?"} exited (${what})${expected ? "" : " unexpectedly"}`);
|
|
133
|
+
const err = new AgentStoppedError(`${spec.name} stopped (${what})`);
|
|
134
|
+
for (const p of this.pending.values()) {
|
|
135
|
+
if (p.timer)
|
|
136
|
+
clearTimeout(p.timer);
|
|
137
|
+
p.reject(err);
|
|
138
|
+
}
|
|
139
|
+
this.pending.clear();
|
|
140
|
+
this.handlers.onExit({ code, signal, expected });
|
|
141
|
+
});
|
|
142
|
+
const result = (await Promise.race([
|
|
143
|
+
this.request("initialize", {
|
|
144
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
145
|
+
clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
|
|
146
|
+
clientInfo: { name: "pi-browser", title: "Pi Browser", version: PI_BROWSER_META.version },
|
|
147
|
+
}, this.initializeTimeoutMs),
|
|
148
|
+
spawnError,
|
|
149
|
+
]));
|
|
150
|
+
const caps = result?.agentCapabilities ?? {};
|
|
151
|
+
this.init = {
|
|
152
|
+
loadSession: caps.loadSession === true,
|
|
153
|
+
closeSession: !!caps.sessionCapabilities?.close,
|
|
154
|
+
resumeSession: !!caps.sessionCapabilities?.resume,
|
|
155
|
+
authMethods: Array.isArray(result?.authMethods) ? result.authMethods : [],
|
|
156
|
+
...(result?.agentInfo ? { agentInfo: result.agentInfo } : {}),
|
|
157
|
+
};
|
|
158
|
+
this.log.info(`agent ${spec.id}: initialized ${result?.agentInfo?.name ?? "?"} ${result?.agentInfo?.version ?? ""} ` +
|
|
159
|
+
`(loadSession=${this.init.loadSession} close=${this.init.closeSession})`);
|
|
160
|
+
return this.init;
|
|
161
|
+
}
|
|
162
|
+
write(msg) {
|
|
163
|
+
if (!this.child || this.exited)
|
|
164
|
+
throw new AgentStoppedError(`${this.spec.name} is not running`);
|
|
165
|
+
this.touch();
|
|
166
|
+
this.child.stdin.write(`${JSON.stringify(msg)}\n`);
|
|
167
|
+
}
|
|
168
|
+
request(method, params, timeoutMs = 0) {
|
|
169
|
+
return new Promise((resolve, reject) => {
|
|
170
|
+
const id = this.nextId++;
|
|
171
|
+
const entry = { method, resolve: resolve, reject };
|
|
172
|
+
if (timeoutMs > 0) {
|
|
173
|
+
entry.timer = setTimeout(() => {
|
|
174
|
+
this.pending.delete(id);
|
|
175
|
+
reject(new AgentRpcError(-32603, `${this.spec.name} did not answer ${method} within ${Math.round(timeoutMs / 1000)} s`));
|
|
176
|
+
}, timeoutMs);
|
|
177
|
+
entry.timer.unref?.();
|
|
178
|
+
}
|
|
179
|
+
this.pending.set(id, entry);
|
|
180
|
+
try {
|
|
181
|
+
this.write({ jsonrpc: "2.0", id, method, params });
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
this.pending.delete(id);
|
|
185
|
+
if (entry.timer)
|
|
186
|
+
clearTimeout(entry.timer);
|
|
187
|
+
reject(err);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
notify(method, params) {
|
|
192
|
+
try {
|
|
193
|
+
this.write({ jsonrpc: "2.0", method, params });
|
|
194
|
+
}
|
|
195
|
+
catch (err) {
|
|
196
|
+
this.log.debug(`agent ${this.spec.id}: ${method} not sent: ${err instanceof Error ? err.message : String(err)}`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
onLine(line) {
|
|
200
|
+
if (!line.trim())
|
|
201
|
+
return;
|
|
202
|
+
this.touch();
|
|
203
|
+
let msg;
|
|
204
|
+
try {
|
|
205
|
+
msg = JSON.parse(line);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
this.log.debug(`[agent ${this.spec.id}] non-JSON stdout: ${line.slice(0, 300)}`);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
if (typeof msg.method === "string") {
|
|
212
|
+
if (msg.id !== undefined && msg.id !== null) {
|
|
213
|
+
const id = msg.id;
|
|
214
|
+
void Promise.resolve()
|
|
215
|
+
.then(() => this.handlers.onRequest(msg.method, msg.params))
|
|
216
|
+
.then((result) => this.safeWrite({ jsonrpc: "2.0", id, result: result ?? null }), (err) => {
|
|
217
|
+
const e = err;
|
|
218
|
+
this.safeWrite({
|
|
219
|
+
jsonrpc: "2.0",
|
|
220
|
+
id,
|
|
221
|
+
error: { code: typeof e?.code === "number" ? e.code : -32603, message: typeof e?.message === "string" ? e.message : String(err) },
|
|
222
|
+
});
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
try {
|
|
227
|
+
this.handlers.onNotification(msg.method, msg.params);
|
|
228
|
+
}
|
|
229
|
+
catch (err) {
|
|
230
|
+
this.log.warn(`agent ${this.spec.id}: ${msg.method} handler failed`, err);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
if (typeof msg.id === "number") {
|
|
236
|
+
const p = this.pending.get(msg.id);
|
|
237
|
+
if (!p)
|
|
238
|
+
return;
|
|
239
|
+
this.pending.delete(msg.id);
|
|
240
|
+
if (p.timer)
|
|
241
|
+
clearTimeout(p.timer);
|
|
242
|
+
if (msg.error) {
|
|
243
|
+
p.reject(new AgentRpcError(typeof msg.error.code === "number" ? msg.error.code : -32603, typeof msg.error.message === "string" ? msg.error.message : `${p.method} failed`, msg.error.data));
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
p.resolve(msg.result);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
safeWrite(msg) {
|
|
251
|
+
try {
|
|
252
|
+
this.write(msg);
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
/* agent gone */
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** Stop the process: close stdin, then kill after the grace period. Resolves when it exited. */
|
|
259
|
+
stop() {
|
|
260
|
+
const child = this.child;
|
|
261
|
+
if (!child || this.exited)
|
|
262
|
+
return Promise.resolve();
|
|
263
|
+
this.stopping = true;
|
|
264
|
+
return new Promise((resolve) => {
|
|
265
|
+
const killTimer = setTimeout(() => {
|
|
266
|
+
if (!this.exited) {
|
|
267
|
+
this.log.info(`agent ${this.spec.id}: killing process ${child.pid ?? "?"} after the grace period`);
|
|
268
|
+
killTree(child);
|
|
269
|
+
}
|
|
270
|
+
}, this.stopGraceMs);
|
|
271
|
+
killTimer.unref?.();
|
|
272
|
+
child.once("exit", () => {
|
|
273
|
+
clearTimeout(killTimer);
|
|
274
|
+
resolve();
|
|
275
|
+
});
|
|
276
|
+
try {
|
|
277
|
+
child.stdin.end();
|
|
278
|
+
}
|
|
279
|
+
catch {
|
|
280
|
+
/* already closed */
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/** Kill a process and, on Windows, its children (cmd.exe shims). */
|
|
286
|
+
function killTree(child) {
|
|
287
|
+
if (process.platform === "win32" && child.pid !== undefined) {
|
|
288
|
+
try {
|
|
289
|
+
spawn("taskkill", ["/pid", String(child.pid), "/t", "/f"], { windowsHide: true, stdio: "ignore" }).on("error", () => child.kill());
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
/* fall through */
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
child.kill("SIGKILL");
|
|
297
|
+
}
|
|
298
|
+
//# sourceMappingURL=connection.js.map
|
|
@@ -0,0 +1,363 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* External ACP agents for sidebar sessions (openspec sidebar-acp-agents).
|
|
3
|
+
*
|
|
4
|
+
* Broker-wide: one agent process per agent id, shared by every session on
|
|
5
|
+
* that agent, whichever app (Firefox, Thunderbird) owns the session (D2).
|
|
6
|
+
* The manager:
|
|
7
|
+
* - starts an agent on its first session and initializes it once;
|
|
8
|
+
* - routes the agent's updates and permission requests to the session's
|
|
9
|
+
* relay (and so to the client that owns it);
|
|
10
|
+
* - keeps the session index for `session/list` and reopening (D5);
|
|
11
|
+
* - gives each session the pi-browser stdio bridge, tied to it by a token
|
|
12
|
+
* in PI_BROWSER_PARENT_SESSION (D6);
|
|
13
|
+
* - stops idle agents and restarts them on demand (D2a);
|
|
14
|
+
* - turns missing commands, logins and crashes into readable errors (D8).
|
|
15
|
+
*/
|
|
16
|
+
import { randomUUID } from "node:crypto";
|
|
17
|
+
import { homedir } from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { fileURLToPath } from "node:url";
|
|
20
|
+
import { HOST_CHILD_ENV, PARENT_SESSION_ENV, PI_BROKER, PI_BROWSER_ERROR, PiBrowserProtocolError, } from "@pi-browser/protocol";
|
|
21
|
+
import { AgentConnection, AgentRpcError, AgentStoppedError } from "./connection.js";
|
|
22
|
+
import { AgentRegistry } from "./registry.js";
|
|
23
|
+
import { AcpRelaySession } from "./relay-session.js";
|
|
24
|
+
import { AgentSessionIndex } from "./session-index.js";
|
|
25
|
+
/** ACP's "authentication required" error code. */
|
|
26
|
+
const AUTH_REQUIRED_CODE = -32000;
|
|
27
|
+
/** Updates kept for a session the agent reports before its id is registered. */
|
|
28
|
+
const MAX_EARLY_UPDATES = 200;
|
|
29
|
+
/** Default bridge launch: `node <pkg>/dist/native-host/mcp-stdio-main.js` (same as the installers). */
|
|
30
|
+
export function defaultBridgeLaunch() {
|
|
31
|
+
return {
|
|
32
|
+
command: process.execPath,
|
|
33
|
+
args: [fileURLToPath(new URL("../../native-host/mcp-stdio-main.js", import.meta.url))],
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export class ExternalAgents {
|
|
37
|
+
log;
|
|
38
|
+
registry;
|
|
39
|
+
index;
|
|
40
|
+
conns = new Map();
|
|
41
|
+
starting = new Map();
|
|
42
|
+
sessions = new Map();
|
|
43
|
+
tokens = new Map();
|
|
44
|
+
early = new Map();
|
|
45
|
+
instanceId;
|
|
46
|
+
bridge;
|
|
47
|
+
promptTimeout;
|
|
48
|
+
now;
|
|
49
|
+
stopGraceMs;
|
|
50
|
+
idleTimer;
|
|
51
|
+
constructor(opts) {
|
|
52
|
+
this.log = opts.log;
|
|
53
|
+
this.registry = opts.registry ?? new AgentRegistry();
|
|
54
|
+
this.index = opts.index ?? new AgentSessionIndex();
|
|
55
|
+
this.instanceId = opts.instanceId;
|
|
56
|
+
this.bridge = opts.bridgeLaunch ?? defaultBridgeLaunch();
|
|
57
|
+
this.promptTimeout = opts.permissionTimeoutMs ?? (() => 120_000);
|
|
58
|
+
this.now = opts.now ?? Date.now;
|
|
59
|
+
this.stopGraceMs = opts.stopGraceMs;
|
|
60
|
+
const every = opts.idleCheckMs ?? 60_000;
|
|
61
|
+
if (every > 0) {
|
|
62
|
+
this.idleTimer = setInterval(() => this.checkIdle(), every);
|
|
63
|
+
this.idleTimer.unref?.();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// ------------------------------------------------------------------
|
|
67
|
+
// Listing
|
|
68
|
+
// ------------------------------------------------------------------
|
|
69
|
+
list() {
|
|
70
|
+
return this.registry.list();
|
|
71
|
+
}
|
|
72
|
+
/** The indexed entry of an external-agent session (load/resume, list). */
|
|
73
|
+
entry(sessionId) {
|
|
74
|
+
return this.index.get(sessionId);
|
|
75
|
+
}
|
|
76
|
+
isAgentSession(sessionId) {
|
|
77
|
+
return this.sessions.has(sessionId) || this.index.get(sessionId) !== undefined;
|
|
78
|
+
}
|
|
79
|
+
/** Open relay for a session id, if any. */
|
|
80
|
+
session(sessionId) {
|
|
81
|
+
return this.sessions.get(sessionId);
|
|
82
|
+
}
|
|
83
|
+
/** Sidebar session a bridge's PI_BROWSER_PARENT_SESSION token names. */
|
|
84
|
+
resolveParentToken(token) {
|
|
85
|
+
return this.tokens.get(token);
|
|
86
|
+
}
|
|
87
|
+
/** Whether an agent's process is running (status, tests). */
|
|
88
|
+
isRunning(agentId) {
|
|
89
|
+
return this.conns.get(agentId)?.alive === true;
|
|
90
|
+
}
|
|
91
|
+
runningPid(agentId) {
|
|
92
|
+
const c = this.conns.get(agentId);
|
|
93
|
+
return c?.alive ? c.pid : undefined;
|
|
94
|
+
}
|
|
95
|
+
// ------------------------------------------------------------------
|
|
96
|
+
// RelayHost
|
|
97
|
+
// ------------------------------------------------------------------
|
|
98
|
+
liveConnection(agentId) {
|
|
99
|
+
const c = this.conns.get(agentId);
|
|
100
|
+
return c?.alive ? c : undefined;
|
|
101
|
+
}
|
|
102
|
+
connection(agentId) {
|
|
103
|
+
const live = this.liveConnection(agentId);
|
|
104
|
+
if (live)
|
|
105
|
+
return Promise.resolve(live);
|
|
106
|
+
const pending = this.starting.get(agentId);
|
|
107
|
+
if (pending)
|
|
108
|
+
return pending;
|
|
109
|
+
const start = this.startAgent(agentId).finally(() => this.starting.delete(agentId));
|
|
110
|
+
this.starting.set(agentId, start);
|
|
111
|
+
return start;
|
|
112
|
+
}
|
|
113
|
+
async startAgent(agentId) {
|
|
114
|
+
const resolved = this.registry.resolve(agentId);
|
|
115
|
+
if (!resolved.ok) {
|
|
116
|
+
const name = resolved.spec?.name ?? agentId;
|
|
117
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.ACP_INITIALIZATION_FAILED, `${name} is not available: ${resolved.reason}`);
|
|
118
|
+
}
|
|
119
|
+
const spec = resolved.spec;
|
|
120
|
+
const conn = new AgentConnection({
|
|
121
|
+
spec,
|
|
122
|
+
executable: resolved.executable,
|
|
123
|
+
log: this.log,
|
|
124
|
+
now: this.now,
|
|
125
|
+
...(this.stopGraceMs !== undefined ? { stopGraceMs: this.stopGraceMs } : {}),
|
|
126
|
+
handlers: {
|
|
127
|
+
onNotification: (method, params) => this.onAgentNotification(spec, method, params),
|
|
128
|
+
onRequest: (method, params) => this.onAgentRequest(spec, method, params),
|
|
129
|
+
onExit: ({ code, signal, expected }) => {
|
|
130
|
+
if (this.conns.get(agentId) === conn)
|
|
131
|
+
this.conns.delete(agentId);
|
|
132
|
+
const what = code !== null ? `exit code ${code}` : `signal ${signal ?? "?"}`;
|
|
133
|
+
for (const s of this.sessions.values()) {
|
|
134
|
+
if (s.agentId !== agentId || s.dormant)
|
|
135
|
+
continue;
|
|
136
|
+
s.markStopped(expected ? undefined : `${spec.name} stopped (${what}). Your next message restarts it.`);
|
|
137
|
+
}
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
});
|
|
141
|
+
this.conns.set(agentId, conn);
|
|
142
|
+
try {
|
|
143
|
+
await conn.start();
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
if (this.conns.get(agentId) === conn)
|
|
147
|
+
this.conns.delete(agentId);
|
|
148
|
+
void conn.stop();
|
|
149
|
+
throw this.describeError(agentId, err, "start");
|
|
150
|
+
}
|
|
151
|
+
return conn;
|
|
152
|
+
}
|
|
153
|
+
mcpServers(session) {
|
|
154
|
+
const env = [{ name: PARENT_SESSION_ENV, value: session.parentToken }];
|
|
155
|
+
if (this.instanceId)
|
|
156
|
+
env.unshift({ name: HOST_CHILD_ENV, value: this.instanceId });
|
|
157
|
+
// Some agents start MCP servers with a trimmed environment (Codex keeps
|
|
158
|
+
// only a few inherited variables), so name the broker's run dir here
|
|
159
|
+
// instead of relying on inheritance.
|
|
160
|
+
env.push({
|
|
161
|
+
name: "PI_BROWSER_BROKER_DIR",
|
|
162
|
+
value: process.env.PI_BROWSER_BROKER_DIR || path.join(homedir(), ".pi", PI_BROKER.runDir),
|
|
163
|
+
});
|
|
164
|
+
return [{ name: "pi-browser", command: this.bridge.command, args: [...this.bridge.args], env }];
|
|
165
|
+
}
|
|
166
|
+
permissionTimeoutMs() {
|
|
167
|
+
return this.promptTimeout();
|
|
168
|
+
}
|
|
169
|
+
touchIndex(session, title, firstPrompt) {
|
|
170
|
+
if (firstPrompt !== undefined) {
|
|
171
|
+
const t = firstPrompt.replace(/\s+/g, " ").trim().slice(0, 80);
|
|
172
|
+
if (t)
|
|
173
|
+
this.index.setTitleIfMissing(session.id, t);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
this.index.upsert({ sessionId: session.id, agent: session.agentId, cwd: session.cwd, ...(title ? { title } : {}) });
|
|
177
|
+
}
|
|
178
|
+
describeError(agentId, err, action) {
|
|
179
|
+
if (err instanceof PiBrowserProtocolError)
|
|
180
|
+
return err;
|
|
181
|
+
const spec = this.registry.load().specs.find((s) => s.id === agentId);
|
|
182
|
+
const name = spec?.name ?? agentId;
|
|
183
|
+
if (err instanceof AgentRpcError && isAuthError(err)) {
|
|
184
|
+
return new PiBrowserProtocolError(PI_BROWSER_ERROR.ACP_INITIALIZATION_FAILED, `${name} needs you to log in: ${spec?.loginHint ?? "log in with the agent's own CLI"}, then try again`);
|
|
185
|
+
}
|
|
186
|
+
if (err instanceof AgentStoppedError)
|
|
187
|
+
return new PiBrowserProtocolError(PI_BROWSER_ERROR.ACP_INITIALIZATION_FAILED, err.message);
|
|
188
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
189
|
+
return new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, `${name} could not ${action}: ${message}`);
|
|
190
|
+
}
|
|
191
|
+
forget(session) {
|
|
192
|
+
if (this.sessions.get(session.id) === session)
|
|
193
|
+
this.sessions.delete(session.id);
|
|
194
|
+
this.tokens.delete(session.parentToken);
|
|
195
|
+
}
|
|
196
|
+
// ------------------------------------------------------------------
|
|
197
|
+
// Agent → relay routing
|
|
198
|
+
// ------------------------------------------------------------------
|
|
199
|
+
onAgentNotification(spec, method, params) {
|
|
200
|
+
if (method !== "session/update") {
|
|
201
|
+
this.log.debug(`agent ${spec.id}: ignoring ${method}`);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const p = params;
|
|
205
|
+
if (typeof p?.sessionId !== "string" || typeof p.update !== "object" || p.update === null)
|
|
206
|
+
return;
|
|
207
|
+
const relay = this.sessions.get(p.sessionId);
|
|
208
|
+
if (relay && relay.agentId === spec.id) {
|
|
209
|
+
relay.handleUpdate(p.update);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
// Updates for a session whose session/new hasn't answered yet.
|
|
213
|
+
const list = this.early.get(p.sessionId) ?? [];
|
|
214
|
+
if (list.length < MAX_EARLY_UPDATES)
|
|
215
|
+
list.push(p.update);
|
|
216
|
+
this.early.set(p.sessionId, list);
|
|
217
|
+
}
|
|
218
|
+
async onAgentRequest(spec, method, params) {
|
|
219
|
+
if (method === "session/request_permission") {
|
|
220
|
+
const sessionId = params?.sessionId;
|
|
221
|
+
const relay = typeof sessionId === "string" ? this.sessions.get(sessionId) : undefined;
|
|
222
|
+
if (!relay || relay.agentId !== spec.id)
|
|
223
|
+
return { outcome: { outcome: "cancelled" } };
|
|
224
|
+
return relay.handlePermission(params);
|
|
225
|
+
}
|
|
226
|
+
// No client file system or terminals (not advertised in initialize).
|
|
227
|
+
throw new AgentRpcError(-32601, `method not supported by this client: ${method}`);
|
|
228
|
+
}
|
|
229
|
+
// ------------------------------------------------------------------
|
|
230
|
+
// Sessions
|
|
231
|
+
// ------------------------------------------------------------------
|
|
232
|
+
register(relay) {
|
|
233
|
+
this.sessions.set(relay.id, relay);
|
|
234
|
+
this.tokens.set(relay.parentToken, relay.id);
|
|
235
|
+
const early = this.early.get(relay.id);
|
|
236
|
+
this.early.delete(relay.id);
|
|
237
|
+
for (const u of early ?? [])
|
|
238
|
+
relay.handleUpdate(u);
|
|
239
|
+
}
|
|
240
|
+
nameOf(agentId) {
|
|
241
|
+
return this.registry.nameOf(agentId);
|
|
242
|
+
}
|
|
243
|
+
/** Create a session on an agent. */
|
|
244
|
+
async createSession(agentId, cwd, owner) {
|
|
245
|
+
const conn = await this.connection(agentId);
|
|
246
|
+
const release = conn.hold();
|
|
247
|
+
try {
|
|
248
|
+
const token = randomUUID();
|
|
249
|
+
// The bridge env needs the token before the agent assigns the id: a
|
|
250
|
+
// placeholder relay supplies it, and the real one is registered below.
|
|
251
|
+
const placeholder = new AcpRelaySession(this, "", agentId, this.nameOf(agentId), cwd, owner, token);
|
|
252
|
+
let result;
|
|
253
|
+
try {
|
|
254
|
+
result = await conn.request("session/new", { cwd, mcpServers: this.mcpServers(placeholder) });
|
|
255
|
+
}
|
|
256
|
+
catch (err) {
|
|
257
|
+
throw this.describeError(agentId, err, "start a session");
|
|
258
|
+
}
|
|
259
|
+
if (typeof result?.sessionId !== "string" || !result.sessionId) {
|
|
260
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, `${this.nameOf(agentId)} returned no session id`);
|
|
261
|
+
}
|
|
262
|
+
if (this.sessions.has(result.sessionId)) {
|
|
263
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.SESSION_BUSY, `session ${result.sessionId} is already open`);
|
|
264
|
+
}
|
|
265
|
+
const relay = new AcpRelaySession(this, result.sessionId, agentId, this.nameOf(agentId), cwd, owner, token);
|
|
266
|
+
relay.applySessionResult(result);
|
|
267
|
+
this.index.upsert({ sessionId: relay.id, agent: agentId, cwd });
|
|
268
|
+
this.register(relay);
|
|
269
|
+
this.log.info(`agent ${agentId}: session/new -> ${relay.id} cwd=${cwd}`);
|
|
270
|
+
return relay;
|
|
271
|
+
}
|
|
272
|
+
finally {
|
|
273
|
+
release();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Reopen an indexed session (session/load or session/resume from the
|
|
278
|
+
* add-on). A session already open for the same client is handed back with
|
|
279
|
+
* its transcript re-sent; one open in another app is refused.
|
|
280
|
+
*/
|
|
281
|
+
async openSession(sessionId, owner, how, cwdHint) {
|
|
282
|
+
const open = this.sessions.get(sessionId);
|
|
283
|
+
if (open) {
|
|
284
|
+
if (open.owner.transport !== owner.transport) {
|
|
285
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.SESSION_BUSY, `session ${sessionId} is open in another app`);
|
|
286
|
+
}
|
|
287
|
+
if (how === "load")
|
|
288
|
+
open.replayTranscript();
|
|
289
|
+
return open;
|
|
290
|
+
}
|
|
291
|
+
const entry = this.index.get(sessionId);
|
|
292
|
+
if (!entry)
|
|
293
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.SESSION_NOT_FOUND, `unknown session: ${sessionId}`);
|
|
294
|
+
const name = this.nameOf(entry.agent);
|
|
295
|
+
const conn = await this.connection(entry.agent);
|
|
296
|
+
if (!conn.init?.loadSession) {
|
|
297
|
+
throw new PiBrowserProtocolError(PI_BROWSER_ERROR.SESSION_NOT_FOUND, `This session can't be reopened with ${name}: it doesn't support loading sessions. Start a new session.`);
|
|
298
|
+
}
|
|
299
|
+
const release = conn.hold();
|
|
300
|
+
try {
|
|
301
|
+
const relay = new AcpRelaySession(this, sessionId, entry.agent, name, cwdHint || entry.cwd, owner, randomUUID());
|
|
302
|
+
// Register first: session/load replays the history as updates.
|
|
303
|
+
this.register(relay);
|
|
304
|
+
try {
|
|
305
|
+
const result = await conn.request("session/load", { sessionId, cwd: relay.cwd, mcpServers: this.mcpServers(relay) });
|
|
306
|
+
relay.applySessionResult(result);
|
|
307
|
+
}
|
|
308
|
+
catch (err) {
|
|
309
|
+
this.forget(relay);
|
|
310
|
+
throw this.describeError(entry.agent, err, "reopen the session");
|
|
311
|
+
}
|
|
312
|
+
this.log.info(`agent ${entry.agent}: session/${how} -> ${sessionId}`);
|
|
313
|
+
return relay;
|
|
314
|
+
}
|
|
315
|
+
finally {
|
|
316
|
+
release();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
// ------------------------------------------------------------------
|
|
320
|
+
// Idle stop (D2a)
|
|
321
|
+
// ------------------------------------------------------------------
|
|
322
|
+
/** Stop agents idle past their timeout whose open sessions can all be reloaded. */
|
|
323
|
+
checkIdle() {
|
|
324
|
+
const stopped = [];
|
|
325
|
+
for (const [agentId, conn] of this.conns) {
|
|
326
|
+
if (!conn.alive)
|
|
327
|
+
continue;
|
|
328
|
+
const minutes = conn.spec.idleTimeoutMinutes;
|
|
329
|
+
if (!(minutes > 0))
|
|
330
|
+
continue;
|
|
331
|
+
if (conn.busy)
|
|
332
|
+
continue;
|
|
333
|
+
if (this.now() - conn.lastActivity < minutes * 60_000)
|
|
334
|
+
continue;
|
|
335
|
+
const open = [...this.sessions.values()].filter((s) => s.agentId === agentId && !s.dormant);
|
|
336
|
+
const reloadable = open.every((s) => conn.init?.loadSession === true && this.index.get(s.id) !== undefined);
|
|
337
|
+
if (!reloadable)
|
|
338
|
+
continue;
|
|
339
|
+
this.log.info(`agent ${agentId}: idle for ${minutes} min; stopping (${open.length} session(s) kept, reloaded on the next request)`);
|
|
340
|
+
for (const s of open)
|
|
341
|
+
s.markStopped();
|
|
342
|
+
this.conns.delete(agentId);
|
|
343
|
+
void conn.stop();
|
|
344
|
+
stopped.push(agentId);
|
|
345
|
+
}
|
|
346
|
+
return stopped;
|
|
347
|
+
}
|
|
348
|
+
/** Stop every agent (host shutdown). */
|
|
349
|
+
async shutdown() {
|
|
350
|
+
if (this.idleTimer)
|
|
351
|
+
clearInterval(this.idleTimer);
|
|
352
|
+
this.idleTimer = undefined;
|
|
353
|
+
const conns = [...this.conns.values()];
|
|
354
|
+
this.conns.clear();
|
|
355
|
+
await Promise.all(conns.map((c) => c.stop().catch(() => undefined)));
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
function isAuthError(err) {
|
|
359
|
+
if (err.code === AUTH_REQUIRED_CODE && /auth|log ?in|sign ?in|credential|api key/i.test(err.message))
|
|
360
|
+
return true;
|
|
361
|
+
return /authenticat(ion|e) required|not (logged|signed) in|please (log|sign) in|unauthori[sz]ed/i.test(err.message);
|
|
362
|
+
}
|
|
363
|
+
//# sourceMappingURL=manager.js.map
|