trusted-user-agent 0.0.0-stage → 0.3.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.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/dist/acp/agent.js +601 -0
  3. package/dist/acp/backend.js +2 -0
  4. package/dist/acp/config-options.js +26 -0
  5. package/dist/acp/mock-backend.js +277 -0
  6. package/dist/acp/sdk-backend.js +495 -0
  7. package/dist/browser/mcp-acp-client.js +81 -0
  8. package/dist/browser/provider.js +1045 -0
  9. package/dist/browser/schemas.js +221 -0
  10. package/dist/capability-registry.js +92 -0
  11. package/dist/client-heartbeat.js +118 -0
  12. package/dist/compose/schemas.js +90 -0
  13. package/dist/contacts/schemas.js +26 -0
  14. package/dist/installer/cli.js +70 -0
  15. package/dist/installer/common.js +93 -0
  16. package/dist/installer/index.js +341 -0
  17. package/dist/installer/mcp-clients.js +555 -0
  18. package/dist/installer/mcp.js +166 -0
  19. package/dist/installer/platforms.js +277 -0
  20. package/dist/logger.js +54 -0
  21. package/dist/mail/schemas.js +98 -0
  22. package/dist/mutation/schemas.js +31 -0
  23. package/dist/native-host/broker-ipc.js +344 -0
  24. package/dist/native-host/framing.js +76 -0
  25. package/dist/native-host/main.js +520 -0
  26. package/dist/native-host/mcp-server.js +322 -0
  27. package/dist/native-host/mcp-stdio-bridge.js +179 -0
  28. package/dist/native-host/mcp-stdio-main.js +13 -0
  29. package/dist/native-host/relay.js +84 -0
  30. package/dist/native-host/skills-startup.js +167 -0
  31. package/dist/native-host/transport.js +248 -0
  32. package/dist/permission-store.js +207 -0
  33. package/dist/repl/fs-sandbox.js +187 -0
  34. package/dist/repl/provider.js +252 -0
  35. package/dist/repl/runtime.js +436 -0
  36. package/dist/repl/types.js +10 -0
  37. package/dist/repl/worker.js +731 -0
  38. package/dist/skills/extension.js +99 -0
  39. package/dist/skills/grants-file.js +145 -0
  40. package/dist/skills/isolated-runner.js +259 -0
  41. package/dist/skills/mock-session-factory.js +49 -0
  42. package/dist/skills/package-roots.js +25 -0
  43. package/dist/skills/pi-bridge.js +8 -0
  44. package/dist/skills/pi-integration.js +110 -0
  45. package/dist/skills/planner.js +128 -0
  46. package/dist/skills/registry.js +104 -0
  47. package/dist/skills/skills-protocol.js +253 -0
  48. package/dist/skills/skills-service.js +195 -0
  49. package/dist/tool-bridge.js +8 -0
  50. package/dist/workspace.js +70 -0
  51. package/extensions/pi-browser-tools.ts +65 -0
  52. package/extensions/pi-browser.ts +60 -0
  53. package/extensions/pi-skills.ts +14 -0
  54. package/native/pi-agent-host +2 -0
  55. package/native/pi-browser-host +5 -0
  56. package/native/pi-browser-host.cmd +3 -0
  57. package/node_modules/@pi-browser/protocol/.bundled-by-trusted-user-agent +0 -0
  58. package/node_modules/@pi-browser/protocol/dist/acp.d.ts +10 -0
  59. package/node_modules/@pi-browser/protocol/dist/acp.js +9 -0
  60. package/node_modules/@pi-browser/protocol/dist/browser-tools.d.ts +33 -0
  61. package/node_modules/@pi-browser/protocol/dist/browser-tools.js +478 -0
  62. package/node_modules/@pi-browser/protocol/dist/callers.d.ts +108 -0
  63. package/node_modules/@pi-browser/protocol/dist/callers.js +56 -0
  64. package/node_modules/@pi-browser/protocol/dist/compose-tools.d.ts +30 -0
  65. package/node_modules/@pi-browser/protocol/dist/compose-tools.js +175 -0
  66. package/node_modules/@pi-browser/protocol/dist/contacts-tools.d.ts +23 -0
  67. package/node_modules/@pi-browser/protocol/dist/contacts-tools.js +63 -0
  68. package/node_modules/@pi-browser/protocol/dist/control-tools.d.ts +32 -0
  69. package/node_modules/@pi-browser/protocol/dist/control-tools.js +201 -0
  70. package/node_modules/@pi-browser/protocol/dist/errors.d.ts +63 -0
  71. package/node_modules/@pi-browser/protocol/dist/errors.js +109 -0
  72. package/node_modules/@pi-browser/protocol/dist/index.d.ts +16 -0
  73. package/node_modules/@pi-browser/protocol/dist/index.js +16 -0
  74. package/node_modules/@pi-browser/protocol/dist/integration.d.ts +409 -0
  75. package/node_modules/@pi-browser/protocol/dist/integration.js +260 -0
  76. package/node_modules/@pi-browser/protocol/dist/jsonrpc.d.ts +33 -0
  77. package/node_modules/@pi-browser/protocol/dist/jsonrpc.js +31 -0
  78. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.d.ts +27 -0
  79. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.js +88 -0
  80. package/node_modules/@pi-browser/protocol/dist/mail-tools.d.ts +133 -0
  81. package/node_modules/@pi-browser/protocol/dist/mail-tools.js +245 -0
  82. package/node_modules/@pi-browser/protocol/dist/permission.d.ts +113 -0
  83. package/node_modules/@pi-browser/protocol/dist/permission.js +257 -0
  84. package/node_modules/@pi-browser/protocol/dist/skills.d.ts +304 -0
  85. package/node_modules/@pi-browser/protocol/dist/skills.js +473 -0
  86. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.d.ts +18 -0
  87. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.js +52 -0
  88. package/node_modules/@pi-browser/protocol/dist/transport.d.ts +17 -0
  89. package/node_modules/@pi-browser/protocol/dist/transport.js +17 -0
  90. package/node_modules/@pi-browser/protocol/package.json +14 -0
  91. package/package.json +71 -6
  92. package/skills/browser-walk/SKILL.md +98 -0
  93. package/README.md +0 -3
@@ -0,0 +1,520 @@
1
+ /**
2
+ * Pi Agent native host entry point (PRODUCT.md §7, §42, §43;
3
+ * THUNDERBIRD-PLAN.md §2–31 — application-neutral `com.matbee.agent`).
4
+ *
5
+ * Launched by Firefox or Thunderbird via connectNative("com.matbee.agent")
6
+ * (legacy Firefox registrations still use "dev.pi.browser").
7
+ *
8
+ * Topology (plan §26–27): the FIRST process to start becomes the broker —
9
+ * it owns the ACP agent, Pi sessions, and the capability provider registry,
10
+ * and listens on private OS IPC (~/.pi/run/agent-broker.sock) for peers.
11
+ * Later processes attach to it as relays (byte passthrough over the same
12
+ * framing). Native Messaging remains the only externally visible Mozilla
13
+ * boundary; no localhost TCP. Windows: the same broker/relay protocol over
14
+ * per-user named pipes (broker-ipc.ts ipcEndpoint).
15
+ *
16
+ * Which provider capabilities (browser / mail / ...) a tool call is routed
17
+ * to is negotiated by each client's pi.agent.hello handshake and resolved
18
+ * per tool (plan §29) — one session can use both apps' tools.
19
+ *
20
+ * stdout invariant: only the host/relay transport writes to stdout;
21
+ * everything else logs to stderr.
22
+ */
23
+ import { lstatSync, readFileSync, readdirSync, statSync, symlinkSync, unlinkSync } from "node:fs";
24
+ import { createRequire } from "node:module";
25
+ import { homedir } from "node:os";
26
+ import { basename, dirname, join } from "node:path";
27
+ import { randomUUID } from "node:crypto";
28
+ import { HOST_CHILD_ENV, PI_BROWSER_ERROR, PI_BROWSER_META, PiBrowserProtocolError, SESSION_ENDED_METHOD, isCallerSessionId, } from "@pi-browser/protocol";
29
+ import { createLogger } from "../logger.js";
30
+ import { setBrowserToolBridge, } from "../tool-bridge.js";
31
+ import { createStdioTransport } from "./transport.js";
32
+ import { createClientSkillsProtocol, createSkillsEventLog, startSkillsCatalogReloader, startSkillsRuntime, } from "./skills-startup.js";
33
+ import { loadSkillsGrantFile } from "../skills/grants-file.js";
34
+ import { createScriptedSessionFactory } from "../skills/mock-session-factory.js";
35
+ import { AcpAgent } from "../acp/agent.js";
36
+ import { MockBackend } from "../acp/mock-backend.js";
37
+ import { PiSdkBackend } from "../acp/sdk-backend.js";
38
+ import { CapabilityToolProvider } from "../browser/provider.js";
39
+ import { CapabilityRegistry } from "../capability-registry.js";
40
+ import { startBrokerServer, tryRelayAttach, waitForRelayAttach, } from "./broker-ipc.js";
41
+ import { startMcpBrowserServer } from "./mcp-server.js";
42
+ import { runRelay } from "./relay.js";
43
+ const require = createRequire(import.meta.url);
44
+ /**
45
+ * Mock-mode skills config (test seam; PI_BROWSER_BACKEND=mock only).
46
+ *
47
+ * PI_BROWSER_SKILLS_CONFIG is a JSON file path (or inline JSON):
48
+ * {
49
+ * "grants": [{ "skillKey": "pkg/skill", "revision": "*", "capabilities": ["context.read"],
50
+ * "mode": "review-before-submit" }], // optional; defaults to advisory
51
+ * "job": { "report": { "decision": "suggest", "explanation": "...", "replacementText": "..." } }
52
+ * }
53
+ * Grants arm the plan compiler (packages are their own adapters — coverage
54
+ * derives from each package manifest); the scripted job factory makes
55
+ * isolated job runs deterministic. The production (Pi SDK) host never reads
56
+ * this variable.
57
+ */
58
+ function loadMockSkillsConfig(log) {
59
+ const raw = process.env.PI_BROWSER_SKILLS_CONFIG?.trim();
60
+ if (!raw)
61
+ return undefined;
62
+ let parsed;
63
+ try {
64
+ parsed = JSON.parse(raw.startsWith("{") ? raw : readFileSync(raw, "utf8"));
65
+ }
66
+ catch (err) {
67
+ log.warn(`PI_BROWSER_SKILLS_CONFIG unreadable; continuing without mock skills config: ${err instanceof Error ? err.message : String(err)}`);
68
+ return undefined;
69
+ }
70
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
71
+ log.warn("PI_BROWSER_SKILLS_CONFIG must be a JSON object; ignoring");
72
+ return undefined;
73
+ }
74
+ const entry = parsed;
75
+ if (!Array.isArray(entry.grants) || (entry.job !== undefined && (typeof entry.job !== "object" || entry.job === null))) {
76
+ log.warn("PI_BROWSER_SKILLS_CONFIG shape invalid (needs grants[], optional job{}); ignoring");
77
+ return undefined;
78
+ }
79
+ // Mock grants are explicit test-arm declarations: they are enabled by
80
+ // construction (SkillGrant.enabled is required and the config has no
81
+ // per-grant enable field).
82
+ const grants = entry.grants.map((g) => ({ enabled: true, ...g }));
83
+ return { grants, job: entry.job ?? {} };
84
+ }
85
+ /**
86
+ * Persistent host log (PRODUCT.md §43): defaults to
87
+ * ~/.pi/browser/logs/host-<pid>.log. Native-host stderr only survives in the
88
+ * about:debugging runtime log, so a file is what makes mid-session drops
89
+ * (e.g. a tool call stuck at in_progress) diagnosable after the fact.
90
+ * PI_BROWSER_LOG_FILE overrides the path; "off" (or empty) disables logging
91
+ * to file (stderr stays on).
92
+ */
93
+ function resolveLogPath() {
94
+ const env = process.env.PI_BROWSER_LOG_FILE;
95
+ if (env === "off" || env === "none")
96
+ return undefined;
97
+ if (env === undefined || env === "") {
98
+ return join(homedir(), ".pi", "browser", "logs", `host-${process.pid}.log`);
99
+ }
100
+ return env;
101
+ }
102
+ /**
103
+ * Best-effort stable log handle: host-current.log -> host-<pid>.log, so the
104
+ * agent (and humans) can tail the current host without resolving the pid.
105
+ */
106
+ function linkCurrentHostLog(logPath) {
107
+ try {
108
+ const link = join(dirname(logPath), "host-current.log");
109
+ try {
110
+ if (lstatSync(link).isSymbolicLink())
111
+ unlinkSync(link);
112
+ }
113
+ catch {
114
+ /* no link yet */
115
+ }
116
+ symlinkSync(basename(logPath), link);
117
+ }
118
+ catch {
119
+ /* best-effort */
120
+ }
121
+ }
122
+ /** Best-effort cleanup of old per-pid host logs (broker startup only). */
123
+ function pruneOldLogs(dir) {
124
+ const cutoff = Date.now() - 7 * 24 * 60 * 60 * 1000;
125
+ let names;
126
+ try {
127
+ names = readdirSync(dir);
128
+ }
129
+ catch {
130
+ return; // dir may not exist yet — createLogger mkdirs it on first write
131
+ }
132
+ for (const name of names) {
133
+ if (!name.startsWith("host-") || !name.endsWith(".log"))
134
+ continue;
135
+ try {
136
+ if (statSync(join(dir, name)).mtimeMs < cutoff)
137
+ unlinkSync(join(dir, name));
138
+ }
139
+ catch {
140
+ // concurrent removal — ignore
141
+ }
142
+ }
143
+ }
144
+ /**
145
+ * The host's graceful shutdown sequence.
146
+ *
147
+ * Hard-exit backstop: a half-open socket must never keep the host alive
148
+ * (e.g. a relay that was SIGKILLed instead of closing its pipe).
149
+ */
150
+ function createShutdownSequence(deps) {
151
+ let shuttingDown = false;
152
+ return async (reason) => {
153
+ if (shuttingDown)
154
+ return;
155
+ shuttingDown = true;
156
+ deps.log.info(`shutting down: ${reason}`);
157
+ const backstop = setTimeout(() => {
158
+ deps.log.warn("shutdown timed out; forcing exit");
159
+ process.exit(0);
160
+ }, 5_000);
161
+ backstop.unref?.();
162
+ try {
163
+ for (const agent of deps.agents.values())
164
+ agent.shutdown();
165
+ deps.agents.clear();
166
+ // Drain/abort skill jobs before the provider goes down — a running job
167
+ // may still be routing browser tool calls through it.
168
+ if (deps.skillsHost) {
169
+ try {
170
+ await deps.skillsHost.close();
171
+ }
172
+ catch (err) {
173
+ deps.log.warn("skills host close error", err);
174
+ }
175
+ }
176
+ try {
177
+ await deps.provider.shutdown();
178
+ }
179
+ catch (err) {
180
+ deps.log.warn("provider shutdown error", err);
181
+ }
182
+ const broker = deps.brokerServer();
183
+ if (broker) {
184
+ try {
185
+ await broker.close();
186
+ }
187
+ catch (err) {
188
+ deps.log.warn("broker close error", err);
189
+ }
190
+ }
191
+ const mcp = deps.mcpServer();
192
+ if (mcp) {
193
+ try {
194
+ await mcp.close();
195
+ }
196
+ catch (err) {
197
+ deps.log.warn("mcp server close error", err);
198
+ }
199
+ }
200
+ const reloader = deps.catalogReloader();
201
+ if (reloader) {
202
+ try {
203
+ await reloader.close();
204
+ }
205
+ catch (err) {
206
+ deps.log.warn("catalog reloader close error", err);
207
+ }
208
+ }
209
+ const eventLog = deps.skillsEventLog();
210
+ if (eventLog) {
211
+ try {
212
+ await eventLog.close();
213
+ }
214
+ catch (err) {
215
+ deps.log.warn("skills event log close error", err);
216
+ }
217
+ }
218
+ deps.backend.dispose();
219
+ }
220
+ finally {
221
+ clearTimeout(backstop);
222
+ process.exit(0);
223
+ }
224
+ };
225
+ }
226
+ function piVersion() {
227
+ try {
228
+ const pkgPath = require.resolve("@earendil-works/pi-coding-agent/package.json");
229
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
230
+ return pkg.version ?? "unknown";
231
+ }
232
+ catch {
233
+ return "unknown";
234
+ }
235
+ }
236
+ /** How long a broker-race loser keeps retrying the relay attach. */
237
+ const RELAY_ATTACH_RETRY_MS = 3_000;
238
+ async function main() {
239
+ const logPath = resolveLogPath();
240
+ const log = createLogger(logPath ? { filePath: logPath } : {});
241
+ if (logPath)
242
+ linkCurrentHostLog(logPath);
243
+ log.info(`host starting pid=${process.pid} node=${process.version}${logPath ? ` log=${logPath}` : " log=off"}`);
244
+ // --- Relay mode: a broker is already running (plan §26) ----------------
245
+ const attachment = await tryRelayAttach(log);
246
+ if (attachment) {
247
+ log.info("attaching to running broker as relay");
248
+ await runRelay(attachment.channel, attachment.initial, process.stdin, process.stdout, log);
249
+ log.info("relay finished; exiting");
250
+ process.exit(0);
251
+ }
252
+ // --- Broker mode: own the ACP agent, sessions, and provider registry ---
253
+ // Every process this broker spawns (pi subagents, the MCP servers their
254
+ // clients start) inherits this marker; the MCP server compares it with the
255
+ // value the stdio bridge reports to tell host children from external
256
+ // callers (openspec external-mcp-callers D3). A stale id never matches.
257
+ const instanceId = randomUUID();
258
+ process.env[HOST_CHILD_ENV] = instanceId;
259
+ const backendKind = process.env.PI_BROWSER_BACKEND ?? "pi";
260
+ const backend = backendKind === "mock" ? new MockBackend(process.env.PI_BROWSER_MOCK_SCRIPT) : new PiSdkBackend({
261
+ log,
262
+ ...(process.env.PI_BROWSER_AGENT_DIR ? { agentDir: process.env.PI_BROWSER_AGENT_DIR } : {}),
263
+ });
264
+ log.info(`backend: ${backendKind}`);
265
+ // Only the broker prunes: relays exit within milliseconds of startup.
266
+ if (logPath)
267
+ pruneOldLogs(dirname(logPath));
268
+ const registry = new CapabilityRegistry(log);
269
+ const provider = new CapabilityToolProvider(undefined, log, registry);
270
+ // In-process tool bridge: Pi sessions created by other code in this
271
+ // process (e.g. pi-subagents children of a sidebar session) can register
272
+ // the browser tools via a Pi extension and route calls back through the
273
+ // provider with the owning ACP session's routing context. Calls without
274
+ // an explicit session id fall back to the most recently prompted one —
275
+ // the session the user is driving in the add-on UI.
276
+ const bridgeSessions = new Map();
277
+ let lastActiveBridgeSession;
278
+ // Caller sessions (external MCP clients, one per MCP connection): no ACP
279
+ // session, no owner app; routed through the registry and the caller gate.
280
+ const callerSessions = new Set();
281
+ const toolBridge = {
282
+ registerSession: (id, ctx) => {
283
+ bridgeSessions.set(id, ctx);
284
+ },
285
+ touchSession: (id) => {
286
+ lastActiveBridgeSession = id;
287
+ },
288
+ closeSession: (id) => {
289
+ if (callerSessions.delete(id)) {
290
+ // Grants, pending prompts and the REPL worker go with the session;
291
+ // the apps drop its tab binding and REPL tabs.
292
+ void provider.disposeSession(id).catch((err) => log.warn(`dispose caller session ${id} failed`, err));
293
+ const params = { sessionId: id };
294
+ for (const client of registry.list()) {
295
+ try {
296
+ client.transport.notify(SESSION_ENDED_METHOD, params);
297
+ }
298
+ catch {
299
+ /* client going away */
300
+ }
301
+ }
302
+ log.info(`caller session ${id} ended`);
303
+ return;
304
+ }
305
+ bridgeSessions.delete(id);
306
+ if (lastActiveBridgeSession === id) {
307
+ lastActiveBridgeSession = [...bridgeSessions.keys()].pop();
308
+ }
309
+ },
310
+ call: (o) => {
311
+ if (o.caller) {
312
+ if (!o.sessionId || !isCallerSessionId(o.sessionId)) {
313
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, "caller calls need a caller session id (mcp:<uuid>)");
314
+ }
315
+ if (!callerSessions.has(o.sessionId)) {
316
+ callerSessions.add(o.sessionId);
317
+ log.info(`caller session ${o.sessionId} started for "${o.caller.name}"`);
318
+ }
319
+ return provider.bridgeCall({
320
+ tool: o.tool,
321
+ args: o.args,
322
+ sessionId: o.sessionId,
323
+ ...(o.toolCallId ? { toolCallId: o.toolCallId } : {}),
324
+ ctx: { ownerApplication: "firefox", mode: "legacy", caller: o.caller },
325
+ });
326
+ }
327
+ const sid = o.sessionId ?? lastActiveBridgeSession;
328
+ const ctx = sid ? bridgeSessions.get(sid) : undefined;
329
+ if (!sid || !ctx) {
330
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.SESSION_NOT_FOUND, "no active ACP session to route the bridge tool call to");
331
+ }
332
+ return provider.bridgeCall({
333
+ tool: o.tool,
334
+ args: o.args,
335
+ sessionId: sid,
336
+ ...(o.toolCallId ? { toolCallId: o.toolCallId } : {}),
337
+ ctx,
338
+ });
339
+ },
340
+ };
341
+ setBrowserToolBridge(toolBridge);
342
+ // Skills runtime (skills-runtime-design.md §10, §13): the broker owns the
343
+ // registry, the bounded SkillsService, and the isolated job runner.
344
+ // Best-effort: degrades to "no skills" without blocking startup.
345
+ const mockSkills = backend instanceof MockBackend ? loadMockSkillsConfig(log) : undefined;
346
+ const skillsRuntime = await startSkillsRuntime({
347
+ log, backend, toolBridge,
348
+ ...(mockSkills ? { sessionFactory: createScriptedSessionFactory(mockSkills.job) } : {}),
349
+ });
350
+ // Grants are read at plan time; "*" rebinds against the LIVE registry
351
+ // snapshot, so a catalog reload picks up the new package revision
352
+ // without a host restart (mock/dev grants only — real user grants stay
353
+ // revision-bound and report "Package changed" until re-granted).
354
+ let mockGrants;
355
+ if (mockSkills && skillsRuntime) {
356
+ mockGrants = () => new Map(mockSkills.grants.map((g) => [
357
+ g.skillKey,
358
+ {
359
+ enabled: true,
360
+ revision: g.revision === "*" ? skillsRuntime.registry.revisionOf(g.skillKey) : g.revision,
361
+ capabilities: g.capabilities,
362
+ ...(g.mode ? { mode: g.mode } : {}),
363
+ },
364
+ ]));
365
+ }
366
+ // Real-user grants (design §12 seam): <data root>/skills-grants.json,
367
+ // re-read at every plan compile (no host restart to grant), revision-bound.
368
+ const fileGrants = loadSkillsGrantFile(log);
369
+ // Browser-tools MCP server: lets pi-subagent children (separate node
370
+ // processes with no ACP channel) reach the browser tools over MCP on a
371
+ // private IPC endpoint (unix socket; named pipe on Windows).
372
+ let mcpServer;
373
+ // Dev-loop catalog reloader: the agent touches the trigger file in the
374
+ // broker run dir to re-read skill packages without a host restart.
375
+ let catalogReloader;
376
+ // JSONL skills lifecycle log (agent observation channel): one line per
377
+ // plan/event/result/reload in the broker run dir.
378
+ let skillsEventLog;
379
+ const agents = new Map();
380
+ // A peer app connected/disconnected: tell every client so its UI can
381
+ // update the "capabilities:" line (display-only, plan §29).
382
+ registry.onChange = (caps) => {
383
+ for (const agent of agents.values())
384
+ agent.notifyCapabilitiesChanged(caps);
385
+ };
386
+ const clients = new Set();
387
+ let relaySeq = 0;
388
+ // Getters defer to the brokerServer/mcpServer bindings, which initialize
389
+ // later in startup; shutdown only ever runs after they have.
390
+ const shutdown = createShutdownSequence({
391
+ log,
392
+ agents,
393
+ provider,
394
+ backend,
395
+ skillsHost: skillsRuntime?.host,
396
+ brokerServer: () => brokerServer,
397
+ mcpServer: () => mcpServer,
398
+ catalogReloader: () => catalogReloader,
399
+ skillsEventLog: () => skillsEventLog,
400
+ });
401
+ const wireClient = (clientId, dispatcher) => {
402
+ clients.add(clientId);
403
+ // One skills protocol surface per client connection (design §7):
404
+ // verified source identity is per-connection, results route back on
405
+ // the same transport.
406
+ const clientSkills = skillsRuntime
407
+ ? createClientSkillsProtocol({
408
+ log, runtime: skillsRuntime, transport: dispatcher.transport,
409
+ ...(mockGrants ? { grants: mockGrants } : { grants: fileGrants }),
410
+ ...(skillsEventLog ? { record: skillsEventLog.record } : {}),
411
+ })
412
+ : undefined;
413
+ const agent = new AcpAgent({
414
+ backend,
415
+ provider,
416
+ transport: dispatcher.transport,
417
+ log,
418
+ agentInfo: { name: "pi-coding-agent", version: piVersion() },
419
+ clientId,
420
+ registry,
421
+ bridge: toolBridge,
422
+ extendedRequest: clientSkills?.extendedRequest,
423
+ });
424
+ agents.set(clientId, agent);
425
+ dispatcher.transport.onEof = () => {
426
+ clients.delete(clientId);
427
+ agents.delete(clientId);
428
+ registry.remove(clientId);
429
+ clientSkills?.dispose();
430
+ agent.shutdown();
431
+ log.info(`client ${clientId} disconnected (${clients.size} connected)`);
432
+ if (clients.size === 0)
433
+ void shutdown("last client disconnected");
434
+ };
435
+ };
436
+ let brokerServer;
437
+ try {
438
+ brokerServer = await startBrokerServer({
439
+ log,
440
+ onClient: (channel) => {
441
+ const id = `relay-${++relaySeq}`;
442
+ log.info(`broker: client ${id} connected`);
443
+ wireClient(id, createStdioTransport(channel, channel, log));
444
+ },
445
+ });
446
+ log.info(`broker: listening on ${brokerServer.socketPath}`);
447
+ }
448
+ catch (err) {
449
+ // Lost the race: another process became broker between our probe and
450
+ // listen. Attach as a relay instead.
451
+ log.warn("could not start broker; retrying relay attach", err);
452
+ // The winner publishes its state file (pid + token) just AFTER listen
453
+ // succeeds, so a simultaneous loser can land in that window: poll
454
+ // briefly instead of failing the election outright.
455
+ const attachment = await waitForRelayAttach(log, RELAY_ATTACH_RETRY_MS);
456
+ if (attachment) {
457
+ log.info("attaching to running broker as relay (race fallback)");
458
+ await runRelay(attachment.channel, attachment.initial, process.stdin, process.stdout, log);
459
+ process.exit(0);
460
+ }
461
+ // Let the add-on reconnect after an election failure instead of keeping
462
+ // an isolated host alive with cross-app routing permanently disabled.
463
+ throw new Error("broker election failed; reconnect to retry", { cause: err });
464
+ }
465
+ // Browser-tools MCP server: broker-only, started AFTER winning the
466
+ // election — a race loser that grabbed the endpoint first would serve MCP
467
+ // from a relay process whose tool bridge has no clients.
468
+ try {
469
+ mcpServer = await startMcpBrowserServer({ log, bridge: toolBridge, instanceId });
470
+ }
471
+ catch (err) {
472
+ // Non-fatal: the in-process bridge (extensions/pi-browser-tools.ts)
473
+ // keeps working for foreground children; only subagent MCP access is
474
+ // unavailable until the socket is free again.
475
+ log.warn("could not start mcp browser server", err);
476
+ }
477
+ // Skills dev-loop observation (skills-events.jsonl) + catalog reloader:
478
+ // broker-only (a relay never reaches this point), one writer per run dir.
479
+ if (skillsRuntime && brokerServer) {
480
+ try {
481
+ const runDir = process.env.PI_BROWSER_BROKER_DIR?.trim() || join(homedir(), ".pi", "run");
482
+ skillsEventLog = createSkillsEventLog(log, join(runDir, "skills-events.jsonl"));
483
+ }
484
+ catch (err) {
485
+ // Non-fatal: live runs stay observable through the host log only.
486
+ log.warn("skills event log unavailable", err);
487
+ }
488
+ try {
489
+ catalogReloader = startSkillsCatalogReloader({
490
+ log, runtime: skillsRuntime,
491
+ ...(skillsEventLog ? { record: skillsEventLog.record } : {}),
492
+ });
493
+ }
494
+ catch (err) {
495
+ // Non-fatal: the catalog stays at its startup snapshot; the
496
+ // dev loop falls back to a host restart.
497
+ log.warn("skills catalog reloader unavailable; catalog fixed for this host run", err);
498
+ }
499
+ }
500
+ // Elect the broker before consuming stdin: a race loser must relay the
501
+ // original initialize request, with no competing dispatcher on its pipes.
502
+ const stdioDispatcher = createStdioTransport(process.stdin, process.stdout, log);
503
+ wireClient("stdio", stdioDispatcher);
504
+ process.on("SIGINT", () => void shutdown("SIGINT"));
505
+ process.on("SIGTERM", () => void shutdown("SIGTERM"));
506
+ process.on("uncaughtException", (err) => {
507
+ log.error("uncaught exception", err);
508
+ void shutdown("uncaught exception");
509
+ });
510
+ process.on("unhandledRejection", (err) => {
511
+ log.error("unhandled rejection", err);
512
+ });
513
+ log.info(`host ready (pi ${piVersion()}, integration v${PI_BROWSER_META.version} proto=${PI_BROWSER_META.protocolVersion}, mode=broker)`);
514
+ }
515
+ main().catch((err) => {
516
+ // stderr only — stdout is protocol data.
517
+ process.stderr.write(`[pi-browser-host] fatal: ${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);
518
+ process.exit(1);
519
+ });
520
+ //# sourceMappingURL=main.js.map