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,201 @@
1
+ /**
2
+ * External ACP agents a sidebar session can run on (openspec
3
+ * sidebar-acp-agents D1).
4
+ *
5
+ * Built in: pi (in-process, not described here), Claude Code and Codex
6
+ * through their ACP adapters. The user adds agents, or overrides a built-in
7
+ * one's command, arguments, environment and idle timeout, in
8
+ * `<data root>/agents.json`:
9
+ *
10
+ * { "agents": { "my-agent": { "name": "My agent", "command": "my-agent", "args": ["--acp"] } } }
11
+ *
12
+ * The file is re-read on every lookup (it is tiny), so edits apply to the
13
+ * next session without a host restart. Availability means the command
14
+ * resolves on PATH (or exists, for an absolute path); nothing is launched.
15
+ *
16
+ * Adapter facts (checked 2026-11-20, task 1.1):
17
+ * - Claude Code: npm `@agentclientprotocol/claude-agent-acp`, binary
18
+ * `claude-agent-acp` (was `@zed-industries/claude-code-acp`). Supports
19
+ * loadSession, resume, close, list; reports configOptions and modes.
20
+ * - Codex: npm `@agentclientprotocol/codex-acp`, binary `codex-acp` (was
21
+ * `@zed-industries/codex-acp`). Same session methods; reports
22
+ * configOptions, models and modes; advertises authMethods.
23
+ * - Google: Antigravity CLI (`agy`) has no ACP mode, so it isn't built in.
24
+ */
25
+ import { existsSync, readFileSync } from "node:fs";
26
+ import { homedir } from "node:os";
27
+ import path from "node:path";
28
+ import { PI_AGENT_ID } from "@pi-browser/protocol";
29
+ /** Default idle timeout before an agent process is stopped (D2a). */
30
+ export const DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
31
+ export const BUILTIN_AGENTS = [
32
+ {
33
+ id: "claude",
34
+ name: "Claude Code",
35
+ command: "claude-agent-acp",
36
+ args: [],
37
+ env: {},
38
+ idleTimeoutMinutes: DEFAULT_IDLE_TIMEOUT_MINUTES,
39
+ loginHint: "run `claude` in a terminal and log in",
40
+ installHint: "npm install -g @agentclientprotocol/claude-agent-acp",
41
+ },
42
+ {
43
+ id: "codex",
44
+ name: "Codex",
45
+ command: "codex-acp",
46
+ args: [],
47
+ env: {},
48
+ idleTimeoutMinutes: DEFAULT_IDLE_TIMEOUT_MINUTES,
49
+ loginHint: "run `codex login` in a terminal",
50
+ installHint: "npm install -g @agentclientprotocol/codex-acp",
51
+ },
52
+ ];
53
+ const GENERIC_LOGIN_HINT = "log in with the agent's own CLI";
54
+ /** Data root shared with the other host files (PI_BROWSER_DATA_ROOT honored). */
55
+ export function dataRoot(env = process.env) {
56
+ return env.PI_BROWSER_DATA_ROOT?.trim() || path.join(homedir(), ".pi", "browser");
57
+ }
58
+ /** Where agents.json lives (PI_BROWSER_AGENTS_FILE overrides, for tests). */
59
+ export function agentsFilePath(env = process.env) {
60
+ return env.PI_BROWSER_AGENTS_FILE?.trim() || path.join(dataRoot(env), "agents.json");
61
+ }
62
+ function isObject(v) {
63
+ return typeof v === "object" && v !== null && !Array.isArray(v);
64
+ }
65
+ /** Find a command on PATH (Windows: .exe, .cmd, .bat). Absolute paths must exist. */
66
+ export function findCommand(command, env, platform) {
67
+ if (path.isAbsolute(command) || command.includes("/") || (platform === "win32" && command.includes("\\"))) {
68
+ return existsSync(command) ? command : undefined;
69
+ }
70
+ const pathVar = env.PATH ?? env.Path ?? "";
71
+ const sep = platform === "win32" ? ";" : ":";
72
+ const exts = platform === "win32"
73
+ ? (path.extname(command) ? [""] : [".exe", ".cmd", ".bat"])
74
+ : [""];
75
+ for (const dir of pathVar.split(sep)) {
76
+ if (!dir)
77
+ continue;
78
+ for (const ext of exts) {
79
+ const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext);
80
+ if (existsSync(candidate))
81
+ return candidate;
82
+ }
83
+ }
84
+ return undefined;
85
+ }
86
+ export class AgentRegistry {
87
+ env;
88
+ platform;
89
+ file;
90
+ constructor(opts = {}) {
91
+ this.env = opts.env ?? process.env;
92
+ this.platform = opts.platform ?? process.platform;
93
+ this.file = opts.file ?? agentsFilePath(this.env);
94
+ }
95
+ get configFile() {
96
+ return this.file;
97
+ }
98
+ /** Built-in specs merged with agents.json. */
99
+ load() {
100
+ const specs = new Map(BUILTIN_AGENTS.map((s) => [s.id, { ...s, args: [...s.args], env: { ...s.env } }]));
101
+ let error;
102
+ if (existsSync(this.file)) {
103
+ try {
104
+ const text = readFileSync(this.file, "utf8");
105
+ const parsed = text.trim() ? JSON.parse(text) : {};
106
+ if (!isObject(parsed))
107
+ throw new Error("the file must contain a JSON object");
108
+ const agents = parsed.agents ?? {};
109
+ if (!isObject(agents))
110
+ throw new Error('"agents" must be an object keyed by agent id');
111
+ const problems = [];
112
+ for (const [id, raw] of Object.entries(agents)) {
113
+ const problem = this.merge(specs, id, raw);
114
+ if (problem)
115
+ problems.push(problem);
116
+ }
117
+ if (problems.length)
118
+ error = `${this.file}: ${problems.join("; ")}`;
119
+ }
120
+ catch (err) {
121
+ error = `${this.file}: ${err instanceof Error ? err.message : String(err)}`;
122
+ }
123
+ }
124
+ return { specs: [...specs.values()], ...(error ? { error } : {}) };
125
+ }
126
+ merge(specs, id, raw) {
127
+ if (id === PI_AGENT_ID)
128
+ return `"${PI_AGENT_ID}" is the built-in agent and can't be configured here`;
129
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(id))
130
+ return `agent id "${id}" must be letters, digits, ".", "_" or "-"`;
131
+ if (!isObject(raw))
132
+ return `agent "${id}" must be an object`;
133
+ if (raw.disabled === true) {
134
+ specs.delete(id);
135
+ return undefined;
136
+ }
137
+ const base = specs.get(id);
138
+ const command = typeof raw.command === "string" && raw.command.trim() ? raw.command.trim() : base?.command;
139
+ if (!command)
140
+ return `agent "${id}" needs a "command"`;
141
+ if (raw.args !== undefined && (!Array.isArray(raw.args) || raw.args.some((a) => typeof a !== "string"))) {
142
+ return `agent "${id}": "args" must be an array of strings`;
143
+ }
144
+ if (raw.env !== undefined && (!isObject(raw.env) || Object.values(raw.env).some((v) => typeof v !== "string"))) {
145
+ return `agent "${id}": "env" must map names to strings`;
146
+ }
147
+ const idle = raw.idleTimeoutMinutes;
148
+ if (idle !== undefined && (typeof idle !== "number" || !Number.isFinite(idle) || idle < 0)) {
149
+ return `agent "${id}": "idleTimeoutMinutes" must be a number ≥ 0`;
150
+ }
151
+ specs.set(id, {
152
+ id,
153
+ name: typeof raw.name === "string" && raw.name.trim() ? raw.name.trim().slice(0, 64) : (base?.name ?? id),
154
+ command,
155
+ args: raw.args ?? base?.args ?? [],
156
+ env: { ...(base?.env ?? {}), ...(raw.env ?? {}) },
157
+ idleTimeoutMinutes: typeof idle === "number" ? idle : (base?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES),
158
+ loginHint: typeof raw.loginHint === "string" && raw.loginHint.trim() ? raw.loginHint.trim() : (base?.loginHint ?? GENERIC_LOGIN_HINT),
159
+ ...(base?.installHint && command === base.command ? { installHint: base.installHint } : {}),
160
+ });
161
+ return undefined;
162
+ }
163
+ /** The spec and executable for an agent id, or why it can't start. */
164
+ resolve(id) {
165
+ const { specs } = this.load();
166
+ const spec = specs.find((s) => s.id === id);
167
+ if (!spec)
168
+ return { ok: false, reason: `unknown agent "${id}"` };
169
+ const executable = findCommand(spec.command, { ...this.env }, this.platform);
170
+ if (!executable) {
171
+ return {
172
+ ok: false,
173
+ spec,
174
+ reason: `not found (${spec.command})${spec.installHint ? ` — install it with \`${spec.installHint}\`` : ""}, or set its command in ${this.file}`,
175
+ };
176
+ }
177
+ return { ok: true, spec, executable };
178
+ }
179
+ /** Display name of an agent id (the id itself when unknown). */
180
+ nameOf(id) {
181
+ if (id === PI_AGENT_ID)
182
+ return "pi";
183
+ return this.load().specs.find((s) => s.id === id)?.name ?? id;
184
+ }
185
+ /** Answer for x-pi-browser/agents: pi first, then the external agents. */
186
+ list() {
187
+ const { specs, error } = this.load();
188
+ const agents = [{ id: PI_AGENT_ID, name: "pi", available: true }];
189
+ for (const spec of specs) {
190
+ const executable = findCommand(spec.command, this.env, this.platform);
191
+ agents.push({
192
+ id: spec.id,
193
+ name: spec.name,
194
+ available: executable !== undefined,
195
+ ...(executable ? {} : { reason: `not found (${spec.command})` }),
196
+ });
197
+ }
198
+ return { agents, defaultAgent: PI_AGENT_ID, ...(error ? { configError: error } : {}) };
199
+ }
200
+ }
201
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1,371 @@
1
+ /**
2
+ * A sidebar session running on an external ACP agent (openspec
3
+ * sidebar-acp-agents D3, D4, D7).
4
+ *
5
+ * The relay forwards ACP both ways and leaves the content alone:
6
+ * - prompts, cancel and close go to the agent;
7
+ * - the agent's `session/update` notifications go to the client that owns
8
+ * the session, as they are (the session id is the agent's own, D5);
9
+ * - the agent's `session/request_permission` goes to the owner's prompt UI,
10
+ * labelled with the agent, with the add-on's prompt timeout; cancel and
11
+ * disconnect answer it `cancelled`.
12
+ *
13
+ * When the agent process stopped (idle stop, D2a, or a crash, D8) the
14
+ * session is *dormant*: it stays open for the add-on, and the next prompt or
15
+ * setting change starts the agent again and reloads the session with its
16
+ * replay suppressed (the sidebar already shows the history).
17
+ */
18
+ import { CLIENT_METHODS, PERMISSION_WITHDRAWN_METHOD, PI_BROWSER_ERROR, PiBrowserProtocolError, } from "@pi-browser/protocol";
19
+ import { TransportTimeoutError } from "../../native-host/transport.js";
20
+ import { AgentRpcError, AgentStoppedError } from "./connection.js";
21
+ /** Updates kept for re-sending history when the add-on loads an open session. */
22
+ const MAX_TRANSCRIPT = 5_000;
23
+ function isRecord(v) {
24
+ return typeof v === "object" && v !== null && !Array.isArray(v);
25
+ }
26
+ /**
27
+ * Settings the agent reported, as the config options the add-on renders:
28
+ * `configOptions` when present, otherwise its models and modes (D4).
29
+ */
30
+ export function settingsFromSessionResult(result) {
31
+ const r = isRecord(result) ? result : {};
32
+ if (Array.isArray(r.configOptions)) {
33
+ return { configOptions: r.configOptions, native: true };
34
+ }
35
+ const options = [];
36
+ const models = isRecord(r.models) ? r.models : undefined;
37
+ if (models && Array.isArray(models.availableModels) && models.availableModels.length) {
38
+ const opts = [];
39
+ for (const m of models.availableModels) {
40
+ if (isRecord(m) && typeof m.modelId === "string") {
41
+ opts.push({ value: m.modelId, name: typeof m.name === "string" ? m.name : m.modelId });
42
+ }
43
+ }
44
+ options.push({
45
+ id: "model",
46
+ name: "Model",
47
+ category: "model",
48
+ type: "select",
49
+ currentValue: typeof models.currentModelId === "string" ? models.currentModelId : (opts[0]?.value ?? ""),
50
+ options: opts,
51
+ });
52
+ }
53
+ const modes = isRecord(r.modes) ? r.modes : undefined;
54
+ if (modes && Array.isArray(modes.availableModes) && modes.availableModes.length) {
55
+ const opts = [];
56
+ for (const m of modes.availableModes) {
57
+ if (isRecord(m) && typeof m.id === "string") {
58
+ opts.push({ value: m.id, name: typeof m.name === "string" ? m.name : m.id });
59
+ }
60
+ }
61
+ options.push({
62
+ id: "mode",
63
+ name: "Mode",
64
+ category: "mode",
65
+ type: "select",
66
+ currentValue: typeof modes.currentModeId === "string" ? modes.currentModeId : (opts[0]?.value ?? ""),
67
+ options: opts,
68
+ });
69
+ }
70
+ return { configOptions: options, native: false };
71
+ }
72
+ export class AcpRelaySession {
73
+ host;
74
+ id;
75
+ agentId;
76
+ agentName;
77
+ cwd;
78
+ owner;
79
+ configOptions = [];
80
+ /** The agent reports `configOptions` (else models/modes are mapped). */
81
+ nativeConfig = false;
82
+ /** The agent process stopped; the next request restarts and reloads. */
83
+ dormant = false;
84
+ streaming = false;
85
+ /** Token the bridge reports as its parent session (PI_BROWSER_PARENT_SESSION). */
86
+ parentToken;
87
+ suppressReplay = false;
88
+ transcript = [];
89
+ waiting = new Set();
90
+ releaseTurn;
91
+ startSeq = 0;
92
+ closed = false;
93
+ constructor(host, id, agentId, agentName, cwd, owner, parentToken) {
94
+ this.host = host;
95
+ this.id = id;
96
+ this.agentId = agentId;
97
+ this.agentName = agentName;
98
+ this.cwd = cwd;
99
+ this.owner = owner;
100
+ this.parentToken = parentToken;
101
+ }
102
+ /** Apply a session/new|load|resume result (settings). */
103
+ applySessionResult(result) {
104
+ const s = settingsFromSessionResult(result);
105
+ this.configOptions = s.configOptions;
106
+ this.nativeConfig = s.native;
107
+ }
108
+ // ------------------------------------------------------------------
109
+ // Agent → add-on
110
+ // ------------------------------------------------------------------
111
+ handleUpdate(update) {
112
+ if (this.suppressReplay)
113
+ return;
114
+ const u = update;
115
+ // Keep the settings in step with what the agent reports.
116
+ if (u.sessionUpdate === "config_option_update" && Array.isArray(u.configOptions)) {
117
+ this.configOptions = u.configOptions;
118
+ this.nativeConfig = true;
119
+ }
120
+ else if (u.sessionUpdate === "current_mode_update" && typeof u.currentModeId === "string") {
121
+ this.setLocalValue("mode", u.currentModeId);
122
+ }
123
+ else if (u.sessionUpdate === "session_info_update" && typeof u.title === "string" && u.title.trim()) {
124
+ this.host.touchIndex(this, u.title.trim());
125
+ }
126
+ this.record(update);
127
+ this.send(update);
128
+ }
129
+ record(update) {
130
+ const kind = update.sessionUpdate;
131
+ // Only what rebuilds the transcript; settings/usage/commands are live state.
132
+ if (kind === "available_commands_update" || kind === "usage_update" || kind === "session_info_update")
133
+ return;
134
+ this.transcript.push(update);
135
+ if (this.transcript.length > MAX_TRANSCRIPT)
136
+ this.transcript.splice(0, this.transcript.length - MAX_TRANSCRIPT);
137
+ }
138
+ send(update) {
139
+ try {
140
+ this.owner.transport.notify(CLIENT_METHODS.session_update, { sessionId: this.id, update });
141
+ }
142
+ catch (err) {
143
+ this.host.log.debug(`relay ${this.id}: update not delivered: ${err instanceof Error ? err.message : String(err)}`);
144
+ }
145
+ }
146
+ /** Re-send the transcript (the add-on loaded a session that is already open). */
147
+ replayTranscript() {
148
+ for (const update of this.transcript)
149
+ this.send(update);
150
+ }
151
+ /** The agent asks permission: show it in the session's UI, return the choice. */
152
+ async handlePermission(params) {
153
+ const p = isRecord(params) ? params : {};
154
+ const toolCall = isRecord(p.toolCall) ? p.toolCall : {};
155
+ const toolCallId = typeof toolCall.toolCallId === "string" ? toolCall.toolCallId : `agent-perm-${Date.now()}`;
156
+ const meta = isRecord(p._meta) ? p._meta : {};
157
+ const piBrowser = isRecord(meta.piBrowser) ? meta.piBrowser : {};
158
+ const request = {
159
+ ...p,
160
+ sessionId: this.id,
161
+ _meta: { ...meta, piBrowser: { ...piBrowser, agent: { id: this.agentId, name: this.agentName } } },
162
+ };
163
+ const release = this.host.liveConnection(this.agentId)?.hold();
164
+ let settle;
165
+ const local = new Promise((resolve) => {
166
+ settle = resolve;
167
+ });
168
+ const entry = { toolCallId, settle };
169
+ this.waiting.add(entry);
170
+ const timeoutMs = this.host.permissionTimeoutMs();
171
+ this.host.log.info(`relay ${this.id}: ${this.agentName} asks permission (${String(toolCall.title ?? toolCallId)})`);
172
+ const remote = this.owner.transport
173
+ .request(CLIENT_METHODS.session_request_permission, request, timeoutMs)
174
+ .then((res) => res, (err) => {
175
+ if (err instanceof TransportTimeoutError) {
176
+ this.host.log.info(`relay ${this.id}: permission prompt timed out after ${Math.round(timeoutMs / 1000)} s`);
177
+ this.withdraw(toolCallId, "timeout");
178
+ }
179
+ else {
180
+ this.host.log.debug(`relay ${this.id}: permission prompt failed: ${err instanceof Error ? err.message : JSON.stringify(err)}`);
181
+ }
182
+ return { outcome: { outcome: "cancelled" } };
183
+ });
184
+ try {
185
+ return await Promise.race([remote, local]);
186
+ }
187
+ finally {
188
+ this.waiting.delete(entry);
189
+ release?.();
190
+ }
191
+ }
192
+ withdraw(toolCallId, reason) {
193
+ try {
194
+ const params = { sessionId: this.id, toolCallId, reason };
195
+ this.owner.transport.notify(PERMISSION_WITHDRAWN_METHOD, params);
196
+ }
197
+ catch {
198
+ /* owner gone */
199
+ }
200
+ }
201
+ /** Answer every waiting permission request `cancelled` and drop it from the UI. */
202
+ cancelWaiting(reason) {
203
+ for (const w of [...this.waiting]) {
204
+ this.waiting.delete(w);
205
+ this.withdraw(w.toolCallId, reason);
206
+ w.settle({ outcome: { outcome: "cancelled" } });
207
+ }
208
+ }
209
+ // ------------------------------------------------------------------
210
+ // Add-on → agent
211
+ // ------------------------------------------------------------------
212
+ /** The live connection, restarting the agent and reloading the session if it stopped. */
213
+ async live() {
214
+ const existing = this.host.liveConnection(this.agentId);
215
+ if (existing && !this.dormant)
216
+ return existing;
217
+ const cardId = `pi-browser-agent-start-${++this.startSeq}`;
218
+ this.send({ sessionUpdate: "tool_call", toolCallId: cardId, title: `Starting ${this.agentName}…`, kind: "other", status: "in_progress" });
219
+ try {
220
+ const conn = await this.host.connection(this.agentId);
221
+ if (!conn.init?.loadSession) {
222
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.SESSION_NOT_FOUND, `${this.agentName} stopped and can't reopen this session. Start a new session.`);
223
+ }
224
+ this.suppressReplay = true;
225
+ let result;
226
+ try {
227
+ result = await conn.request("session/load", { sessionId: this.id, cwd: this.cwd, mcpServers: this.host.mcpServers(this) });
228
+ }
229
+ finally {
230
+ this.suppressReplay = false;
231
+ }
232
+ // Keep the user's choices if the reload reports none.
233
+ const s = settingsFromSessionResult(result);
234
+ if (s.configOptions.length) {
235
+ this.configOptions = s.configOptions;
236
+ this.nativeConfig = s.native;
237
+ }
238
+ this.dormant = false;
239
+ this.send({ sessionUpdate: "tool_call_update", toolCallId: cardId, status: "completed", title: `Started ${this.agentName}` });
240
+ return conn;
241
+ }
242
+ catch (err) {
243
+ this.send({ sessionUpdate: "tool_call_update", toolCallId: cardId, status: "failed", title: `${this.agentName} did not start` });
244
+ if (err instanceof PiBrowserProtocolError)
245
+ throw err;
246
+ throw this.host.describeError(this.agentId, err, "reopen the session");
247
+ }
248
+ }
249
+ async prompt(prompt) {
250
+ if (this.streaming) {
251
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.SESSION_BUSY, `session ${this.id} is busy`);
252
+ }
253
+ this.streaming = true;
254
+ try {
255
+ const conn = await this.live();
256
+ this.releaseTurn = conn.hold();
257
+ // The sidebar shows the user's own message; keep it for a reload replay.
258
+ for (const block of prompt) {
259
+ if (block.type === "text" && block.text) {
260
+ this.record({ sessionUpdate: "user_message_chunk", content: { type: "text", text: block.text } });
261
+ }
262
+ }
263
+ const firstText = prompt.find((b) => b.type === "text");
264
+ if (firstText?.text)
265
+ this.host.touchIndex(this, undefined, firstText.text);
266
+ const result = await conn.request("session/prompt", { sessionId: this.id, prompt });
267
+ this.host.touchIndex(this);
268
+ return { stopReason: typeof result?.stopReason === "string" ? result.stopReason : "end_turn" };
269
+ }
270
+ catch (err) {
271
+ if (err instanceof PiBrowserProtocolError)
272
+ throw err;
273
+ if (err instanceof AgentStoppedError) {
274
+ this.dormant = true;
275
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.INTERNAL, `${err.message}. Send your message again to restart it.`);
276
+ }
277
+ throw this.host.describeError(this.agentId, err, "answer");
278
+ }
279
+ finally {
280
+ this.streaming = false;
281
+ this.releaseTurn?.();
282
+ this.releaseTurn = undefined;
283
+ }
284
+ }
285
+ cancel() {
286
+ this.cancelWaiting("cancelled");
287
+ const conn = this.host.liveConnection(this.agentId);
288
+ if (conn && !this.dormant)
289
+ conn.notify("session/cancel", { sessionId: this.id });
290
+ }
291
+ async setConfigOption(configId, value) {
292
+ const conn = await this.live();
293
+ const release = conn.hold();
294
+ try {
295
+ if (this.nativeConfig) {
296
+ const res = await conn.request("session/set_config_option", {
297
+ sessionId: this.id,
298
+ configId,
299
+ value,
300
+ });
301
+ if (Array.isArray(res?.configOptions))
302
+ this.configOptions = res.configOptions;
303
+ else
304
+ this.setLocalValue(configId, value);
305
+ }
306
+ else if (configId === "model") {
307
+ await conn.request("session/set_model", { sessionId: this.id, modelId: value });
308
+ this.setLocalValue(configId, value);
309
+ }
310
+ else if (configId === "mode") {
311
+ await conn.request("session/set_mode", { sessionId: this.id, modeId: value });
312
+ this.setLocalValue(configId, value);
313
+ }
314
+ else {
315
+ throw new PiBrowserProtocolError(PI_BROWSER_ERROR.ACP_CAPABILITY_UNSUPPORTED, `unknown config option: ${configId}`);
316
+ }
317
+ return this.configOptions;
318
+ }
319
+ catch (err) {
320
+ if (err instanceof PiBrowserProtocolError)
321
+ throw err;
322
+ throw this.host.describeError(this.agentId, err, "change the setting");
323
+ }
324
+ finally {
325
+ release();
326
+ }
327
+ }
328
+ setLocalValue(configId, value) {
329
+ this.configOptions = this.configOptions.map((o) => o.id === configId ? { ...o, currentValue: value } : o);
330
+ }
331
+ /** The agent process went away: the session stays open, dormant. */
332
+ markStopped(notice) {
333
+ this.dormant = true;
334
+ this.cancelWaiting("session_closed");
335
+ if (notice) {
336
+ this.send({
337
+ sessionUpdate: "tool_call",
338
+ toolCallId: `pi-browser-agent-stopped-${Date.now()}`,
339
+ title: notice,
340
+ kind: "other",
341
+ status: "failed",
342
+ });
343
+ }
344
+ }
345
+ /** Close the session (add-on close, or the owner disconnected). */
346
+ async close() {
347
+ if (this.closed)
348
+ return;
349
+ this.closed = true;
350
+ this.cancelWaiting("session_closed");
351
+ const conn = this.host.liveConnection(this.agentId);
352
+ if (conn && !this.dormant) {
353
+ if (this.streaming)
354
+ conn.notify("session/cancel", { sessionId: this.id });
355
+ if (conn.init?.closeSession) {
356
+ try {
357
+ await conn.request("session/close", { sessionId: this.id }, 10_000);
358
+ }
359
+ catch (err) {
360
+ this.host.log.debug(`relay ${this.id}: session/close failed: ${err instanceof Error ? err.message : String(err)}`);
361
+ }
362
+ }
363
+ }
364
+ this.host.forget(this);
365
+ }
366
+ /** For errors from the agent that the relay passes on as they are. */
367
+ static isAgentError(err) {
368
+ return err instanceof AgentRpcError;
369
+ }
370
+ }
371
+ //# sourceMappingURL=relay-session.js.map
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Index of sidebar sessions that run on external ACP agents (openspec
3
+ * sidebar-acp-agents D5): `<data root>/agent-sessions.json`.
4
+ *
5
+ * The agents' own `session/list` returns every session the user has with
6
+ * that agent (terminal sessions included), so the host keeps its own list of
7
+ * the sessions started from Firefox or Thunderbird. Entries are written on
8
+ * create and after each completed turn; `session/list` merges them with pi's
9
+ * sessions, and load/resume look the id up to pick the agent.
10
+ */
11
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
12
+ import path from "node:path";
13
+ import { dataRoot } from "./registry.js";
14
+ /** Most entries kept (oldest dropped first). */
15
+ const MAX_ENTRIES = 500;
16
+ export function agentSessionsFilePath(env = process.env) {
17
+ return env.PI_BROWSER_AGENT_SESSIONS_FILE?.trim() || path.join(dataRoot(env), "agent-sessions.json");
18
+ }
19
+ export class AgentSessionIndex {
20
+ file;
21
+ entries;
22
+ constructor(file = agentSessionsFilePath()) {
23
+ this.file = file;
24
+ }
25
+ load() {
26
+ if (this.entries)
27
+ return this.entries;
28
+ const map = new Map();
29
+ if (existsSync(this.file)) {
30
+ try {
31
+ const parsed = JSON.parse(readFileSync(this.file, "utf8"));
32
+ for (const e of Array.isArray(parsed.sessions) ? parsed.sessions : []) {
33
+ const r = e;
34
+ if (typeof r.sessionId === "string" && typeof r.agent === "string" && typeof r.cwd === "string") {
35
+ map.set(r.sessionId, {
36
+ sessionId: r.sessionId,
37
+ agent: r.agent,
38
+ cwd: r.cwd,
39
+ updatedAt: typeof r.updatedAt === "string" ? r.updatedAt : new Date(0).toISOString(),
40
+ ...(typeof r.title === "string" && r.title ? { title: r.title } : {}),
41
+ });
42
+ }
43
+ }
44
+ }
45
+ catch {
46
+ // Unreadable: start empty; the next write replaces it.
47
+ }
48
+ }
49
+ this.entries = map;
50
+ return map;
51
+ }
52
+ save() {
53
+ const map = this.load();
54
+ const sessions = [...map.values()].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, MAX_ENTRIES);
55
+ if (sessions.length < map.size) {
56
+ this.entries = new Map(sessions.map((s) => [s.sessionId, s]));
57
+ }
58
+ try {
59
+ mkdirSync(path.dirname(this.file), { recursive: true });
60
+ const tmp = `${this.file}.${process.pid}.tmp`;
61
+ writeFileSync(tmp, `${JSON.stringify({ version: 1, sessions }, null, 2)}\n`, { mode: 0o600 });
62
+ renameSync(tmp, this.file);
63
+ }
64
+ catch {
65
+ // Best effort: the session still works, it just won't be listed later.
66
+ }
67
+ }
68
+ get(sessionId) {
69
+ return this.load().get(sessionId);
70
+ }
71
+ list(cwd) {
72
+ const all = [...this.load().values()];
73
+ return (cwd ? all.filter((e) => e.cwd === cwd) : all).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
74
+ }
75
+ /** Insert or update an entry; fields left undefined keep their value. */
76
+ upsert(entry) {
77
+ const map = this.load();
78
+ const prev = map.get(entry.sessionId);
79
+ const title = entry.title ?? prev?.title;
80
+ map.set(entry.sessionId, {
81
+ sessionId: entry.sessionId,
82
+ agent: entry.agent,
83
+ cwd: entry.cwd,
84
+ updatedAt: entry.updatedAt ?? new Date().toISOString(),
85
+ ...(title ? { title } : {}),
86
+ });
87
+ this.save();
88
+ }
89
+ /** Set the title only when the entry has none yet (first prompt). */
90
+ setTitleIfMissing(sessionId, title) {
91
+ const e = this.load().get(sessionId);
92
+ if (!e || e.title)
93
+ return;
94
+ e.title = title;
95
+ this.save();
96
+ }
97
+ remove(sessionId) {
98
+ if (this.load().delete(sessionId))
99
+ this.save();
100
+ }
101
+ }
102
+ //# sourceMappingURL=session-index.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=backend.js.map