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.
Files changed (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +232 -2
  3. package/dist/acp/agent.js +719 -0
  4. package/dist/acp/agents/connection.js +298 -0
  5. package/dist/acp/agents/manager.js +363 -0
  6. package/dist/acp/agents/registry.js +201 -0
  7. package/dist/acp/agents/relay-session.js +371 -0
  8. package/dist/acp/agents/session-index.js +102 -0
  9. package/dist/acp/backend.js +2 -0
  10. package/dist/acp/config-options.js +26 -0
  11. package/dist/acp/mock-backend.js +277 -0
  12. package/dist/acp/sdk-backend.js +495 -0
  13. package/dist/browser/mcp-acp-client.js +81 -0
  14. package/dist/browser/provider.js +1049 -0
  15. package/dist/browser/schemas.js +221 -0
  16. package/dist/capability-registry.js +92 -0
  17. package/dist/client-heartbeat.js +118 -0
  18. package/dist/compose/schemas.js +90 -0
  19. package/dist/contacts/schemas.js +26 -0
  20. package/dist/installer/cli.js +70 -0
  21. package/dist/installer/common.js +93 -0
  22. package/dist/installer/index.js +366 -0
  23. package/dist/installer/mcp-clients.js +555 -0
  24. package/dist/installer/mcp.js +166 -0
  25. package/dist/installer/platforms.js +277 -0
  26. package/dist/logger.js +54 -0
  27. package/dist/mail/schemas.js +98 -0
  28. package/dist/mutation/schemas.js +31 -0
  29. package/dist/native-host/broker-ipc.js +344 -0
  30. package/dist/native-host/framing.js +76 -0
  31. package/dist/native-host/main.js +545 -0
  32. package/dist/native-host/mcp-server.js +333 -0
  33. package/dist/native-host/mcp-stdio-bridge.js +184 -0
  34. package/dist/native-host/mcp-stdio-main.js +13 -0
  35. package/dist/native-host/relay.js +84 -0
  36. package/dist/native-host/skills-startup.js +167 -0
  37. package/dist/native-host/transport.js +248 -0
  38. package/dist/permission-store.js +207 -0
  39. package/dist/repl/fs-sandbox.js +187 -0
  40. package/dist/repl/provider.js +252 -0
  41. package/dist/repl/runtime.js +436 -0
  42. package/dist/repl/types.js +10 -0
  43. package/dist/repl/worker.js +731 -0
  44. package/dist/skills/extension.js +99 -0
  45. package/dist/skills/grants-file.js +145 -0
  46. package/dist/skills/isolated-runner.js +259 -0
  47. package/dist/skills/mock-session-factory.js +49 -0
  48. package/dist/skills/package-roots.js +25 -0
  49. package/dist/skills/pi-bridge.js +8 -0
  50. package/dist/skills/pi-integration.js +110 -0
  51. package/dist/skills/planner.js +128 -0
  52. package/dist/skills/registry.js +104 -0
  53. package/dist/skills/skills-protocol.js +253 -0
  54. package/dist/skills/skills-service.js +195 -0
  55. package/dist/tool-bridge.js +8 -0
  56. package/dist/workspace.js +70 -0
  57. package/extensions/pi-browser-tools.ts +65 -0
  58. package/extensions/pi-browser.ts +60 -0
  59. package/extensions/pi-skills.ts +14 -0
  60. package/native/pi-agent-host +2 -0
  61. package/native/pi-browser-host +5 -0
  62. package/native/pi-browser-host.cmd +3 -0
  63. package/node_modules/@pi-browser/protocol/.bundled-by-trusted-user-agent +0 -0
  64. package/node_modules/@pi-browser/protocol/dist/acp.d.ts +10 -0
  65. package/node_modules/@pi-browser/protocol/dist/acp.js +9 -0
  66. package/node_modules/@pi-browser/protocol/dist/agents.d.ts +51 -0
  67. package/node_modules/@pi-browser/protocol/dist/agents.js +44 -0
  68. package/node_modules/@pi-browser/protocol/dist/browser-tools.d.ts +33 -0
  69. package/node_modules/@pi-browser/protocol/dist/browser-tools.js +478 -0
  70. package/node_modules/@pi-browser/protocol/dist/callers.d.ts +123 -0
  71. package/node_modules/@pi-browser/protocol/dist/callers.js +58 -0
  72. package/node_modules/@pi-browser/protocol/dist/compose-tools.d.ts +30 -0
  73. package/node_modules/@pi-browser/protocol/dist/compose-tools.js +175 -0
  74. package/node_modules/@pi-browser/protocol/dist/contacts-tools.d.ts +23 -0
  75. package/node_modules/@pi-browser/protocol/dist/contacts-tools.js +63 -0
  76. package/node_modules/@pi-browser/protocol/dist/control-tools.d.ts +32 -0
  77. package/node_modules/@pi-browser/protocol/dist/control-tools.js +201 -0
  78. package/node_modules/@pi-browser/protocol/dist/errors.d.ts +63 -0
  79. package/node_modules/@pi-browser/protocol/dist/errors.js +109 -0
  80. package/node_modules/@pi-browser/protocol/dist/index.d.ts +17 -0
  81. package/node_modules/@pi-browser/protocol/dist/index.js +17 -0
  82. package/node_modules/@pi-browser/protocol/dist/integration.d.ts +414 -0
  83. package/node_modules/@pi-browser/protocol/dist/integration.js +270 -0
  84. package/node_modules/@pi-browser/protocol/dist/jsonrpc.d.ts +33 -0
  85. package/node_modules/@pi-browser/protocol/dist/jsonrpc.js +31 -0
  86. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.d.ts +27 -0
  87. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.js +88 -0
  88. package/node_modules/@pi-browser/protocol/dist/mail-tools.d.ts +133 -0
  89. package/node_modules/@pi-browser/protocol/dist/mail-tools.js +245 -0
  90. package/node_modules/@pi-browser/protocol/dist/permission.d.ts +113 -0
  91. package/node_modules/@pi-browser/protocol/dist/permission.js +257 -0
  92. package/node_modules/@pi-browser/protocol/dist/skills.d.ts +304 -0
  93. package/node_modules/@pi-browser/protocol/dist/skills.js +473 -0
  94. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.d.ts +18 -0
  95. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.js +52 -0
  96. package/node_modules/@pi-browser/protocol/dist/transport.d.ts +17 -0
  97. package/node_modules/@pi-browser/protocol/dist/transport.js +17 -0
  98. package/node_modules/@pi-browser/protocol/package.json +14 -0
  99. package/package.json +69 -4
  100. package/skills/browser-walk/SKILL.md +98 -0
@@ -0,0 +1,495 @@
1
+ /**
2
+ * Production Pi backend: Pi SDK agent sessions in-process
3
+ * (PRODUCT.md §6 "Preferred long-term implementation").
4
+ *
5
+ * Each ACP session maps to one independent Pi `AgentSession` with its own
6
+ * SessionManager (persistence, cwd, model state). The ACP boundary never
7
+ * exposes the SDK directly.
8
+ *
9
+ * Sessions are created through the SDK's *services* layer
10
+ * (`createAgentSessionServices` + `createAgentSessionFromServices`) so that
11
+ * the resource loader runs exactly as it does in the pi CLI: built-in
12
+ * extensions (the llama.cpp provider) and user-installed packages from
13
+ * settings are loaded, and provider credentials resolve. A raw
14
+ * `createAgentSession()` skips that layer and leaves providers unregistered.
15
+ */
16
+ import path from "node:path";
17
+ import { fileURLToPath, pathToFileURL } from "node:url";
18
+ import { createAgentSessionFromServices, createAgentSessionServices, defineTool, ModelRuntime, SessionManager, } from "@earendil-works/pi-coding-agent";
19
+ /**
20
+ * Load the pi package's built-in extension factories (e.g. the llama.cpp
21
+ * provider). The package's exports map only exposes the root entry, so the
22
+ * dist/extensions module is imported by resolved file path.
23
+ */
24
+ async function loadBuiltinExtensionFactories(log) {
25
+ try {
26
+ const mainUrl = import.meta.resolve("@earendil-works/pi-coding-agent");
27
+ const distDir = path.dirname(fileURLToPath(mainUrl));
28
+ // A file:// URL, not a bare path: on Windows `import("C:\...")` is rejected
29
+ // ("Received protocol 'c:'"), which silently dropped every built-in provider.
30
+ const mod = (await import(pathToFileURL(path.join(distDir, "extensions", "index.js")).href));
31
+ return mod.builtInExtensions ?? [];
32
+ }
33
+ catch (err) {
34
+ log.warn("failed to load built-in pi extensions (providers may be unavailable)", err);
35
+ return [];
36
+ }
37
+ }
38
+ import { PI_BROWSER_ERROR, PiBrowserProtocolError } from "@pi-browser/protocol";
39
+ import { createSkillsExtensionFactory } from "../skills/extension.js";
40
+ export class PiSdkBackend {
41
+ opts;
42
+ modelRuntime;
43
+ runtimePromise;
44
+ /** One coherent services bundle per effective session cwd (cached). */
45
+ servicesByCwd = new Map();
46
+ /** Serializes resource reloads per services bundle (concurrent spawns, same cwd). */
47
+ reloadChains = new Map();
48
+ /**
49
+ * Bundles whose resources were loaded by servicesFor() and not yet used by
50
+ * a session. The first spawn skips the pre-spawn resource refresh: the
51
+ * resources are as fresh as a refresh would make them, and a refresh is a
52
+ * second full load (~8 s with a real package set, all of it blocking the
53
+ * event loop).
54
+ */
55
+ unusedBundles = new WeakSet();
56
+ /** Pre-built fresh workspace (prewarmWorkspace), ready to be claimed. */
57
+ prewarmed;
58
+ prewarmStarted = false;
59
+ builtinFactories;
60
+ builtinFactoriesPromise;
61
+ sessions = new Set();
62
+ thinkingLevels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
63
+ constructor(opts) {
64
+ this.opts = opts;
65
+ this.runtimePromise = this.initRuntime().catch((err) => {
66
+ opts.log.error("failed to initialize model runtime", err);
67
+ throw err;
68
+ });
69
+ }
70
+ get ready() {
71
+ return this.runtimePromise;
72
+ }
73
+ /** The shared model runtime, once initialized. Other in-process consumers
74
+ * (the skills host) reuse it so provider credentials resolve identically. */
75
+ async sharedModelRuntime() {
76
+ await this.ready;
77
+ return this.modelRuntime;
78
+ }
79
+ async initRuntime() {
80
+ if (this.modelRuntime)
81
+ return;
82
+ this.modelRuntime = await ModelRuntime.create({
83
+ ...(this.opts.authPath ? { authPath: this.opts.authPath } : {}),
84
+ ...(this.opts.modelsPath ? { modelsPath: this.opts.modelsPath } : {}),
85
+ });
86
+ this.opts.log.info("model runtime ready");
87
+ }
88
+ async runtime() {
89
+ await this.initRuntime();
90
+ return this.modelRuntime;
91
+ }
92
+ builtinFactoriesOnce() {
93
+ this.builtinFactoriesPromise ??= loadBuiltinExtensionFactories(this.opts.log).then((f) => {
94
+ this.builtinFactories = f;
95
+ return f;
96
+ });
97
+ return this.builtinFactoriesPromise;
98
+ }
99
+ /**
100
+ * Get (creating on first use) the cwd-bound services for a session cwd.
101
+ * The shared ModelRuntime lets extension-registered providers (llama.cpp
102
+ * etc.) become visible to every session without re-loading the catalog.
103
+ */
104
+ async servicesFor(cwd) {
105
+ const modelRuntime = await this.runtime();
106
+ const existing = this.servicesByCwd.get(cwd);
107
+ if (existing)
108
+ return existing;
109
+ // The shared skills integration extension is installed once in the
110
+ // host's controlled runtime configuration (skills-runtime-design.md §3):
111
+ // every host-spawned session loads it; isolated skill-job sessions never
112
+ // do (noExtensions in the job's resource loader). In a session without a
113
+ // skills host installed the extension registers nothing.
114
+ const t0 = Date.now();
115
+ const extensionFactories = [
116
+ ...(await this.builtinFactoriesOnce()),
117
+ { name: "pi-browser-skills", factory: createSkillsExtensionFactory() },
118
+ ];
119
+ const services = await createAgentSessionServices({
120
+ cwd,
121
+ modelRuntime,
122
+ ...(this.opts.agentDir ? { agentDir: this.opts.agentDir } : {}),
123
+ resourceLoaderOptions: { extensionFactories: extensionFactories },
124
+ });
125
+ // Extension providers (e.g. llama.cpp) are registered during services
126
+ // creation, but their model lists populate via an async refresh phase.
127
+ // Settle the runtime before any session is spawned against it, so model
128
+ // resolution (default model, session restore) sees the full catalog.
129
+ const t1 = Date.now();
130
+ try {
131
+ await Promise.race([
132
+ modelRuntime.getAvailable(),
133
+ new Promise((resolve) => setTimeout(resolve, 15_000).unref?.()),
134
+ ]);
135
+ }
136
+ catch (err) {
137
+ this.opts.log.warn("model availability refresh failed", err);
138
+ }
139
+ this.servicesByCwd.set(cwd, services);
140
+ this.unusedBundles.add(services);
141
+ this.opts.log.info(`session services ready for cwd=${cwd} in ${Date.now() - t0}ms (resources ${t1 - t0}ms, model refresh ${Date.now() - t1}ms)`);
142
+ return services;
143
+ }
144
+ /**
145
+ * Build one fresh workspace's services in the background so the next
146
+ * "new workspace" session starts without the resource load. Runs once per
147
+ * host. NOTE: the load blocks the event loop for its whole duration (pi
148
+ * transpiles extensions synchronously), so this must run when nothing is
149
+ * waiting on the host — the caller schedules it right after the first
150
+ * client has initialized. Disable with PI_BROWSER_PREWARM=0.
151
+ */
152
+ prewarmWorkspace(createDir) {
153
+ if (this.prewarmStarted || process.env.PI_BROWSER_PREWARM === "0")
154
+ return;
155
+ this.prewarmStarted = true;
156
+ void (async () => {
157
+ try {
158
+ const cwd = await createDir();
159
+ this.prewarmed = { cwd, ready: false };
160
+ const t0 = Date.now();
161
+ await this.servicesFor(cwd);
162
+ if (this.prewarmed?.cwd === cwd)
163
+ this.prewarmed.ready = true;
164
+ this.opts.log.info(`prewarmed workspace ${cwd} in ${Date.now() - t0}ms`);
165
+ }
166
+ catch (err) {
167
+ this.prewarmed = undefined;
168
+ this.opts.log.warn("workspace prewarm failed (sessions start normally)", err);
169
+ }
170
+ })();
171
+ }
172
+ /** Claim the prewarmed workspace if its services are ready. */
173
+ takePrewarmedWorkspace() {
174
+ if (!this.prewarmed?.ready)
175
+ return undefined;
176
+ const { cwd } = this.prewarmed;
177
+ this.prewarmed = undefined;
178
+ return cwd;
179
+ }
180
+ async createSession(opts) {
181
+ const sessionManager = SessionManager.create(opts.cwd);
182
+ const session = await this.spawnSession({
183
+ cwd: opts.cwd,
184
+ sessionManager,
185
+ customTools: opts.customTools,
186
+ modelValueId: opts.modelValueId,
187
+ thinkingLevel: opts.thinkingLevel,
188
+ // Fresh session: a full resource re-scan is safe (nothing to inherit),
189
+ // so a SKILL.md added since this cwd's services bundle was cached is
190
+ // picked up without a host restart.
191
+ refresh: true,
192
+ });
193
+ this.opts.log.info(`created session ${session.sessionId} cwd=${opts.cwd}`);
194
+ return session;
195
+ }
196
+ async openSession(opts) {
197
+ const info = (await SessionManager.listAll()).find((s) => s.id === opts.sessionId);
198
+ if (!info) {
199
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.SESSION_NOT_FOUND, `Pi session not found: ${opts.sessionId}`);
200
+ }
201
+ const sessionManager = SessionManager.open(info.path);
202
+ const session = await this.spawnSession({
203
+ cwd: info.cwd || process.cwd(),
204
+ sessionManager,
205
+ customTools: opts.customTools,
206
+ modelValueId: undefined, // restored from the session file
207
+ thinkingLevel: undefined,
208
+ });
209
+ this.opts.log.info(`opened session ${session.sessionId} from ${info.path}`);
210
+ return session;
211
+ }
212
+ async spawnSession(args) {
213
+ const { cwd, sessionManager, customTools, modelValueId, thinkingLevel, refresh } = args;
214
+ const tStart = Date.now();
215
+ const services = await this.servicesFor(cwd);
216
+ const tServices = Date.now();
217
+ // Just-loaded bundle (fresh build or prewarm): already current — skip the
218
+ // refresh, which would load every extension a second time.
219
+ const unused = this.unusedBundles.delete(services);
220
+ if (refresh && !unused)
221
+ await this.refreshResources(services);
222
+ const tRefresh = Date.now();
223
+ const options = { services, sessionManager };
224
+ if (modelValueId) {
225
+ const model = this.resolveModel(modelValueId);
226
+ if (model)
227
+ options.model = model;
228
+ }
229
+ if (thinkingLevel)
230
+ options.thinkingLevel = thinkingLevel;
231
+ if (customTools && customTools.length > 0) {
232
+ options.customTools = customTools.map((t) => this.toPiTool(t));
233
+ }
234
+ let agentSession;
235
+ try {
236
+ const created = await createAgentSessionFromServices(options);
237
+ agentSession = created.session;
238
+ }
239
+ catch (err) {
240
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.PI_START_FAILED, `failed to start Pi session: ${err instanceof Error ? err.message : String(err)}`);
241
+ }
242
+ const m = agentSession.model;
243
+ if (!m || m.provider === "unknown") {
244
+ this.opts.log.warn(`session ${agentSession.sessionId}: no model resolved ` +
245
+ "(provider not configured?) — prompts will fail until a model is selected");
246
+ }
247
+ this.opts.log.info(`session ${agentSession.sessionId}: model=${m?.provider}/${m?.id} — ready in ${Date.now() - tStart}ms ` +
248
+ `(services ${tServices - tStart}ms, resource refresh ${tRefresh - tServices}ms, session ${Date.now() - tRefresh}ms)`);
249
+ return this.wrapSession(agentSession, cwd);
250
+ }
251
+ /**
252
+ * Re-scan resources (skills, prompt templates, themes, project files) before
253
+ * a NEW session is spawned, so a SKILL.md the user added (or edited) since
254
+ * this cwd's services bundle was cached is visible in the session's system
255
+ * prompt — without restarting the host process. The system prompt reads
256
+ * resourceLoader.getSkills() at session construction, so the reload must
257
+ * happen here, not at servicesFor() time. Only createSession() does this:
258
+ * resumed/loaded sessions keep the resource set they started with, so past
259
+ * turns replay deterministically and resume stays cheap. Best-effort: on
260
+ * failure the loader keeps its previous resource set and the session starts.
261
+ * Reloads are chained per services bundle so concurrent spawns for the same
262
+ * cwd never interleave a reload with another's.
263
+ */
264
+ refreshResources(services) {
265
+ const prev = this.reloadChains.get(services) ?? Promise.resolve();
266
+ const next = prev.then(async () => {
267
+ try {
268
+ const before = services.resourceLoader.getSkills().skills.length;
269
+ await services.resourceLoader.reload();
270
+ const after = services.resourceLoader.getSkills().skills.length;
271
+ if (after !== before) {
272
+ this.opts.log.info(`resources refreshed for cwd=${services.cwd}: skills ${before} -> ${after}`);
273
+ }
274
+ }
275
+ catch (err) {
276
+ this.opts.log.warn(`resource reload failed for cwd=${services.cwd} (keeping previous resource set)`, err);
277
+ }
278
+ });
279
+ this.reloadChains.set(services, next);
280
+ return next;
281
+ }
282
+ resolveModel(valueId) {
283
+ const rt = this.modelRuntime;
284
+ if (!rt)
285
+ return undefined;
286
+ const slash = valueId.indexOf("/");
287
+ if (slash <= 0)
288
+ return undefined;
289
+ const provider = valueId.slice(0, slash);
290
+ const modelId = valueId.slice(slash + 1);
291
+ return rt.getModel(provider, modelId);
292
+ }
293
+ toPiTool(spec) {
294
+ return defineTool({
295
+ name: spec.name,
296
+ label: spec.label ?? spec.name,
297
+ description: spec.description,
298
+ parameters: spec.parameters,
299
+ execute: async (toolCallId, params, signal) => {
300
+ const result = await spec.execute(toolCallId, params, signal);
301
+ return { content: result.content, details: result.details };
302
+ },
303
+ });
304
+ }
305
+ wrapSession(agentSession, cwd) {
306
+ let abortRequested = false;
307
+ const session = {
308
+ get sessionId() {
309
+ return agentSession.sessionId;
310
+ },
311
+ get cwd() {
312
+ return cwd;
313
+ },
314
+ get isStreaming() {
315
+ return agentSession.isStreaming;
316
+ },
317
+ get modelValueId() {
318
+ const m = agentSession.model;
319
+ return m ? `${m.provider}/${m.id}` : undefined;
320
+ },
321
+ get thinkingLevel() {
322
+ return agentSession.thinkingLevel;
323
+ },
324
+ prompt: async (text, images) => {
325
+ abortRequested = false;
326
+ const opts = images && images.length > 0
327
+ ? { images: images.map((i) => ({ type: "image", source: { type: "base64", mediaType: i.mimeType, data: i.data } })) }
328
+ : undefined;
329
+ try {
330
+ await agentSession.prompt(text, opts);
331
+ }
332
+ catch (err) {
333
+ // A prompt that is rejected outright (not an aborted turn) is a
334
+ // protocol-level failure the client should see.
335
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, `prompt failed: ${err instanceof Error ? err.message : String(err)}`);
336
+ }
337
+ return { aborted: abortRequested };
338
+ },
339
+ abort: async () => {
340
+ abortRequested = true;
341
+ try {
342
+ await agentSession.abort();
343
+ }
344
+ catch (err) {
345
+ this.opts.log.warn("abort failed", err);
346
+ }
347
+ },
348
+ setModel: async (valueId) => {
349
+ const model = this.resolveModel(valueId);
350
+ if (!model) {
351
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.ACP_CAPABILITY_UNSUPPORTED, `unknown model: ${valueId}`);
352
+ }
353
+ await agentSession.setModel(model);
354
+ },
355
+ setThinkingLevel: (level) => {
356
+ agentSession.setThinkingLevel(level);
357
+ },
358
+ subscribe: (listener) => {
359
+ return agentSession.subscribe((event) => {
360
+ for (const mapped of mapBackendEvent(event))
361
+ listener(mapped);
362
+ });
363
+ },
364
+ getHistory: async () => {
365
+ const out = [];
366
+ for (const msg of agentSession.messages) {
367
+ const role = msg.role;
368
+ if (role === "user") {
369
+ const content = msg.content;
370
+ const text = typeof content === "string"
371
+ ? content
372
+ : Array.isArray(content)
373
+ ? content
374
+ .filter((c) => c?.type === "text" && typeof c.text === "string")
375
+ .map((c) => c.text)
376
+ .join("")
377
+ : "";
378
+ if (text)
379
+ out.push({ role: "user", text });
380
+ }
381
+ else if (role === "assistant") {
382
+ const content = msg.content;
383
+ const text = Array.isArray(content)
384
+ ? content
385
+ .filter((c) => c?.type === "text" && typeof c.text === "string")
386
+ .map((c) => c.text)
387
+ .join("")
388
+ : "";
389
+ const toolCalls = Array.isArray(content)
390
+ ? content
391
+ .filter((c) => (c?.type === "toolCall" || c?.type === "tool_call") && typeof c.id === "string" && typeof c.name === "string")
392
+ .map((c) => ({ toolCallId: c.id, toolName: c.name, input: c.arguments ?? c.input }))
393
+ : [];
394
+ if (text || toolCalls.length)
395
+ out.push({ role: "assistant", ...(text ? { text } : {}), ...(toolCalls.length ? { toolCalls } : {}) });
396
+ }
397
+ else if (role === "toolResult" || role === "tool") {
398
+ const toolCallId = typeof msg.toolCallId === "string" ? msg.toolCallId : typeof msg.id === "string" ? msg.id : "";
399
+ if (toolCallId)
400
+ out.push({ role: "tool", toolCallId, toolName: typeof msg.toolName === "string" ? msg.toolName : undefined, content: msg.content, isError: msg.isError === true });
401
+ }
402
+ }
403
+ return out;
404
+ },
405
+ dispose: () => {
406
+ this.sessions.delete(session);
407
+ try {
408
+ agentSession.dispose();
409
+ }
410
+ catch (err) {
411
+ this.opts.log.warn("session dispose failed", err);
412
+ }
413
+ },
414
+ };
415
+ this.sessions.add(session);
416
+ return session;
417
+ }
418
+ async listSessions(cwd) {
419
+ await this.initRuntime();
420
+ const all = await SessionManager.listAll();
421
+ const filtered = cwd ? all.filter((s) => s.cwd === cwd) : all;
422
+ return filtered
423
+ .map((s) => ({
424
+ sessionId: s.id,
425
+ cwd: s.cwd,
426
+ updatedAt: s.modified.toISOString(),
427
+ title: s.name || (s.firstMessage ? s.firstMessage.slice(0, 80) : undefined),
428
+ messageCount: s.messageCount,
429
+ }))
430
+ .sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
431
+ }
432
+ async listModels() {
433
+ const rt = await this.runtime();
434
+ const models = await rt.getAvailable();
435
+ return models.map((m) => ({
436
+ valueId: `${m.provider}/${m.id}`,
437
+ name: m.name ?? m.id,
438
+ }));
439
+ }
440
+ dispose() {
441
+ for (const s of [...this.sessions])
442
+ s.dispose();
443
+ this.sessions.clear();
444
+ }
445
+ }
446
+ /**
447
+ * Map Pi `AgentSessionEvent`s to normalized `BackendEvent`s.
448
+ * Returns an empty array for events with no ACP counterpart.
449
+ */
450
+ export function mapBackendEvent(event) {
451
+ const ev = event;
452
+ switch (ev.type) {
453
+ case "message_update": {
454
+ const inner = ev.assistantMessageEvent;
455
+ if (inner?.type === "text_delta" && typeof inner.delta === "string") {
456
+ return [{ type: "text_delta", delta: inner.delta }];
457
+ }
458
+ if (inner?.type === "thinking_delta" && typeof inner.delta === "string") {
459
+ return [{ type: "thinking_delta", delta: inner.delta }];
460
+ }
461
+ return [];
462
+ }
463
+ case "tool_execution_start":
464
+ return [
465
+ {
466
+ type: "tool_start",
467
+ toolCallId: ev.toolCallId ?? "",
468
+ toolName: ev.toolName ?? "tool",
469
+ args: ev.args ?? {},
470
+ },
471
+ ];
472
+ case "tool_execution_update":
473
+ return [
474
+ {
475
+ type: "tool_update",
476
+ toolCallId: ev.toolCallId ?? "",
477
+ toolName: ev.toolName ?? "tool",
478
+ partial: ev.partialResult,
479
+ },
480
+ ];
481
+ case "tool_execution_end":
482
+ return [
483
+ {
484
+ type: "tool_end",
485
+ toolCallId: ev.toolCallId ?? "",
486
+ toolName: ev.toolName ?? "tool",
487
+ result: ev.result,
488
+ isError: ev.isError === true,
489
+ },
490
+ ];
491
+ default:
492
+ return [];
493
+ }
494
+ }
495
+ //# sourceMappingURL=sdk-backend.js.map
@@ -0,0 +1,81 @@
1
+ /**
2
+ * MCP-over-ACP client (PRODUCT.md §27–28).
3
+ *
4
+ * When the client (Firefox) declares an `McpServer` with `type: "acp"` in
5
+ * session/new, the agent connects to it over the existing ACP channel via
6
+ * mcp/connect, mcp/message, and mcp/disconnect, and speaks plain MCP
7
+ * (initialize / tools/list / tools/call) inside mcp/message.
8
+ */
9
+ import { CLIENT_METHODS, MCP_PROTOCOL_VERSION, PI_BROWSER, } from "@pi-browser/protocol";
10
+ export { MCP_PROTOCOL_VERSION };
11
+ export class McpAcpClient {
12
+ opts;
13
+ connectionId;
14
+ connecting;
15
+ disposed = false;
16
+ constructor(opts) {
17
+ this.opts = opts;
18
+ }
19
+ get connected() {
20
+ return this.connectionId !== undefined;
21
+ }
22
+ async connect() {
23
+ const { transport, log, serverId } = this.opts;
24
+ log.info(`mcp/connect serverId=${serverId}`);
25
+ const res = (await transport.request(CLIENT_METHODS.mcp_connect, { serverId }, this.opts.timeoutMs));
26
+ const connectionId = res.connectionId;
27
+ // MCP handshake inside the ACP channel.
28
+ await this.innerRequest(connectionId, "initialize", {
29
+ protocolVersion: MCP_PROTOCOL_VERSION,
30
+ capabilities: {},
31
+ clientInfo: { name: "pi-browser-agent", version: PI_BROWSER.version },
32
+ });
33
+ // MCP "initialized" notification; the ACP mcp/message method is a
34
+ // request, so expect (and ignore) an empty result.
35
+ await this.innerRequest(connectionId, "notifications/initialized", undefined);
36
+ this.connectionId = connectionId;
37
+ log.info(`mcp connected: ${connectionId}`);
38
+ }
39
+ async ensureConnected() {
40
+ if (this.disposed)
41
+ throw new Error("mcp client disposed");
42
+ if (this.connectionId)
43
+ return this.connectionId;
44
+ if (!this.connecting)
45
+ this.connecting = this.connect().catch((err) => {
46
+ this.connecting = undefined;
47
+ throw err;
48
+ });
49
+ await this.connecting;
50
+ return this.connectionId;
51
+ }
52
+ innerRequest(connectionId, method, params) {
53
+ return this.opts.transport.request(CLIENT_METHODS.mcp_message, { connectionId, method, ...(params !== undefined ? { params } : {}) }, this.opts.timeoutMs);
54
+ }
55
+ async listTools() {
56
+ const connectionId = await this.ensureConnected();
57
+ const res = (await this.innerRequest(connectionId, "tools/list"));
58
+ return res.tools ?? [];
59
+ }
60
+ /** Call a tool on the client's MCP server. Returns the MCP tools/call result. */
61
+ async call(tool, args) {
62
+ const connectionId = await this.ensureConnected();
63
+ return await this.innerRequest(connectionId, "tools/call", { name: tool, arguments: args });
64
+ }
65
+ async dispose() {
66
+ if (this.disposed)
67
+ return;
68
+ this.disposed = true;
69
+ const connectionId = this.connectionId;
70
+ this.connectionId = undefined;
71
+ if (connectionId) {
72
+ try {
73
+ await this.opts.transport.request(CLIENT_METHODS.mcp_disconnect, { connectionId }, this.opts.timeoutMs);
74
+ }
75
+ catch {
76
+ // Connection already gone; nothing to clean up.
77
+ }
78
+ }
79
+ }
80
+ }
81
+ //# sourceMappingURL=mcp-acp-client.js.map