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,166 @@
1
+ /**
2
+ * `/pi-browser mcp` — register the pi-browser MCP server in Pi's global
3
+ * MCP config (`~/.pi/agent/mcp.json`).
4
+ *
5
+ * The broker process (native-host/main.js) exposes the add-on tools as an
6
+ * MCP server on a private unix socket / Windows named pipe
7
+ * (PI_BROKER.mcpSocketFile). The config entry launches the stdio bridge
8
+ * (native-host/mcp-stdio-main.js), which every MCP client can run: pi's
9
+ * built-in client (pi >= 1.5) only speaks stdio and HTTP. The entry is
10
+ * { command: <node>, args: [<bridge>], directTools: true, exposure: "deferred" }
11
+ * — `directTools` for pi-mcp-adapter, `exposure` for pi's built-in client
12
+ * (each ignores the other's key). mcp.json is global, so the built-in client
13
+ * would put all ~50 tools into EVERY pi session's prompt with "direct";
14
+ * "deferred" keeps them out until the model loads them via tool_search.
15
+ * The user can change exposure in pi's /mcp manager: install keeps the
16
+ * user-owned keys (exposure, toolExposure, enabled, directTools) of an
17
+ * existing entry, and status checks only command + args.
18
+ *
19
+ * Sub-commands (mirroring the host commands):
20
+ * mcp [install] write/update the pi-browser entry (idempotent)
21
+ * mcp status report the configured entry vs. the expected one
22
+ * mcp uninstall remove the pi-browser entry
23
+ */
24
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
25
+ import path from "node:path";
26
+ import { PI_BROKER } from "@pi-browser/protocol";
27
+ import { ipcEndpoint } from "../native-host/broker-ipc.js";
28
+ export const MCP_SERVER_NAME = "pi-browser";
29
+ /** Broker MCP socket path for this home dir (matches mcp-server.ts default). */
30
+ export function mcpSocketPath(homeDir, platform = process.platform) {
31
+ // Windows: a named pipe (pi-mcp-adapter's socket transport accepts it).
32
+ return ipcEndpoint(path.join(homeDir, ".pi", PI_BROKER.runDir), PI_BROKER.mcpSocketFile, platform);
33
+ }
34
+ /** Pi's global MCP config (pi-mcp-adapter's getAgentPath("mcp.json")). */
35
+ export function mcpConfigPath(homeDir) {
36
+ return path.join(homeDir, ".pi", "agent", "mcp.json");
37
+ }
38
+ /** The stdio bridge entry point inside the package. */
39
+ export function mcpBridgePath(pkgRoot) {
40
+ return path.join(pkgRoot, "dist", "native-host", "mcp-stdio-main.js");
41
+ }
42
+ export function mcpServerEntry(opts) {
43
+ return {
44
+ command: opts.nodePath ?? process.execPath,
45
+ args: [mcpBridgePath(opts.pkgRoot)],
46
+ directTools: true,
47
+ exposure: "deferred",
48
+ };
49
+ }
50
+ /** Keys of an existing entry the user may have tuned; install keeps them. */
51
+ const USER_OWNED_KEYS = ["exposure", "toolExposure", "enabled", "directTools"];
52
+ /** Same bridge launch (command + args) — the parts this installer owns. */
53
+ function sameLaunch(a, b) {
54
+ return a.command === b.command && JSON.stringify(a.args) === JSON.stringify(b.args) && a.socket === b.socket;
55
+ }
56
+ function readConfig(file) {
57
+ if (!existsSync(file))
58
+ return null;
59
+ try {
60
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
61
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
62
+ return parsed;
63
+ }
64
+ catch {
65
+ // corrupt file: reported, never rewritten (install refuses; status reports it)
66
+ }
67
+ return null;
68
+ }
69
+ function writeConfig(file, config) {
70
+ mkdirSync(path.dirname(file), { recursive: true });
71
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
72
+ }
73
+ export function runMcpCommand(sub, homeDir, entryOpts) {
74
+ const file = mcpConfigPath(homeDir);
75
+ const entry = mcpServerEntry(entryOpts);
76
+ const describe = (e) => typeof e.socket === "string" ? `socket ${e.socket}` : `${String(e.command)} ${e.args?.join(" ") ?? ""}`.trim();
77
+ switch (sub) {
78
+ case "install": {
79
+ if (existsSync(file) && !readConfig(file)) {
80
+ // Never overwrite a file we can't parse: the user's other servers live there.
81
+ return { ok: false, lines: [`mcp: ${file} is not valid JSON — fix or remove it, then run /pi-browser mcp again (left unchanged)`] };
82
+ }
83
+ const config = readConfig(file) ?? {};
84
+ const servers = config.mcpServers && typeof config.mcpServers === "object" && !Array.isArray(config.mcpServers)
85
+ ? config.mcpServers
86
+ : {};
87
+ const existing = servers[MCP_SERVER_NAME];
88
+ const already = !!existing && sameLaunch(existing, entry);
89
+ const merged = { ...entry };
90
+ if (existing && already) {
91
+ for (const key of USER_OWNED_KEYS)
92
+ if (key in existing)
93
+ merged[key] = existing[key];
94
+ }
95
+ servers[MCP_SERVER_NAME] = merged;
96
+ config.mcpServers = servers;
97
+ writeConfig(file, config);
98
+ const lines = [
99
+ `mcp: ${already ? "already configured" : "configured"} in ${file}`,
100
+ ` server: ${MCP_SERVER_NAME} → stdio bridge: ${describe(entry)}`,
101
+ ];
102
+ if (!already) {
103
+ lines.push(" new Pi sessions pick the config up at startup");
104
+ lines.push(" tool names: mcp__pi-browser__<tool> (pi built-in MCP; exposure \"deferred\" — the model loads them via tool_search) or mcp:pi-browser/<tool> (pi-mcp-adapter)");
105
+ lines.push(" works before Firefox/Thunderbird start; calls succeed once an app with the Pi add-on is running");
106
+ }
107
+ return { ok: true, lines };
108
+ }
109
+ case "status": {
110
+ if (!existsSync(file)) {
111
+ return {
112
+ ok: false,
113
+ lines: [
114
+ `mcp: not configured (${file} missing)`,
115
+ ` run /pi-browser mcp to register the ${MCP_SERVER_NAME} server`,
116
+ ],
117
+ };
118
+ }
119
+ const config = readConfig(file);
120
+ if (!config) {
121
+ return { ok: false, lines: [`mcp: ${file} exists but is not valid JSON — fix or remove it, then run /pi-browser mcp`] };
122
+ }
123
+ const existing = config.mcpServers?.[MCP_SERVER_NAME];
124
+ if (!existing) {
125
+ return {
126
+ ok: false,
127
+ lines: [
128
+ `mcp: ${file} has no ${MCP_SERVER_NAME} entry`,
129
+ ` run /pi-browser mcp to add it`,
130
+ ],
131
+ };
132
+ }
133
+ if (!sameLaunch(existing, entry)) {
134
+ return {
135
+ ok: false,
136
+ lines: [
137
+ `mcp: STALE entry in ${file} — run /pi-browser mcp to update`,
138
+ ` current: ${JSON.stringify(existing)}`,
139
+ ` expected: ${JSON.stringify(entry)}`,
140
+ ],
141
+ };
142
+ }
143
+ return { ok: true, lines: [`mcp: OK — ${MCP_SERVER_NAME} → stdio bridge (${describe(existing)}) in ${file}`] };
144
+ }
145
+ case "uninstall": {
146
+ const config = readConfig(file);
147
+ if (!config || !config.mcpServers?.[MCP_SERVER_NAME]) {
148
+ return { ok: true, lines: [`mcp: nothing to remove (${MCP_SERVER_NAME} not configured)`] };
149
+ }
150
+ delete config.mcpServers[MCP_SERVER_NAME];
151
+ if (Object.keys(config.mcpServers).length === 0) {
152
+ delete config.mcpServers;
153
+ if (Object.keys(config).length === 0) {
154
+ rmSync(file, { force: true });
155
+ return { ok: true, lines: [`mcp: removed ${MCP_SERVER_NAME} entry and empty config ${file}`] };
156
+ }
157
+ }
158
+ writeConfig(file, config);
159
+ return { ok: true, lines: [`mcp: removed ${MCP_SERVER_NAME} entry from ${file}`] };
160
+ }
161
+ default: {
162
+ throw new Error(`unknown mcp subcommand: ${sub}`);
163
+ }
164
+ }
165
+ }
166
+ //# sourceMappingURL=mcp.js.map
@@ -0,0 +1,277 @@
1
+ /**
2
+ * Per-platform install targets. Each implements the same operations over
3
+ * an injected environment so every platform is unit-testable.
4
+ *
5
+ * The host is application-neutral (com.matbee.agent). Manifest locations are
6
+ * per-app (plan §23); on Linux/Windows both apps share one location.
7
+ */
8
+ import { execFile } from "node:child_process";
9
+ import { mkdir, readFile, writeFile, rm, chmod, stat, cp } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { buildManifest, cmdLauncherContent, distinctManifestLocations, legacyManifestPath, NATIVE_HOST_NAME, shLauncherContent, WINDOWS_LEGACY_REGISTRY_KEY, WINDOWS_REGISTRY_KEY, } from "./common.js";
12
+ const NATIVE_HOST_FILE = NATIVE_HOST_NAME.replace(/\./g, "_");
13
+ /**
14
+ * Skill shipped with the package (WS1/T1.3 of BROWSER-USE-SUPPORT-PLAN.md).
15
+ * Source lives in the package: skills/browser-walk/SKILL.md.
16
+ */
17
+ export const SKILL_DIRNAME = "browser-walk";
18
+ export const SKILL_SOURCE_PATH = (pkgRoot) => path.join(pkgRoot, "skills", SKILL_DIRNAME, "SKILL.md");
19
+ /**
20
+ * Where the skill is installed for the agent: the harness-neutral global
21
+ * skills dir (~/.agents/skills) — used by this machine and shared by other
22
+ * harnesses (Agent Skills standard).
23
+ */
24
+ export const SKILL_INSTALL_PATH = (homeDir) => path.join(homeDir, ".agents", "skills", SKILL_DIRNAME, "SKILL.md");
25
+ const BASE = {
26
+ launcherPath: (pkgRoot) => path.join(pkgRoot, "native", "pi-agent-host"),
27
+ windowsManifestPath: (pkgRoot) => path.join(pkgRoot, "native", `${NATIVE_HOST_FILE}.json`),
28
+ };
29
+ export const LINUX = {
30
+ id: "linux",
31
+ ...BASE,
32
+ launcherContent: shLauncherContent,
33
+ needsChmod: true,
34
+ };
35
+ export const MACOS = {
36
+ id: "macos",
37
+ ...BASE,
38
+ launcherContent: shLauncherContent,
39
+ needsChmod: true,
40
+ };
41
+ export const WINDOWS = {
42
+ id: "windows",
43
+ ...BASE,
44
+ launcherPath: (pkgRoot) => path.join(pkgRoot, "native", "pi-agent-host.cmd"),
45
+ launcherContent: cmdLauncherContent,
46
+ needsChmod: false,
47
+ };
48
+ /** Resolve where each requested app's manifest lives on this platform. */
49
+ function appManifestPaths(targets, env, pkgRoot, apps) {
50
+ if (targets.id === "windows") {
51
+ const file = targets.windowsManifestPath(pkgRoot);
52
+ const out = {};
53
+ for (const app of apps)
54
+ out[app] = file;
55
+ return out;
56
+ }
57
+ const perApp = {};
58
+ for (const loc of distinctManifestLocations(apps, env.homeDir, env.platform)) {
59
+ for (const app of loc.apps)
60
+ perApp[app] = loc.path;
61
+ }
62
+ return perApp;
63
+ }
64
+ export async function installHost(opts, targets) {
65
+ const { env, pkgRoot } = opts;
66
+ const nodePath = opts.nodePath ?? process.execPath;
67
+ const mainJs = opts.mainJs;
68
+ const launcherPath = targets.launcherPath(pkgRoot);
69
+ const lines = [];
70
+ // Launcher (shared by all apps — one host implementation).
71
+ await mkdir(path.dirname(launcherPath), { recursive: true });
72
+ await writeFile(launcherPath, targets.launcherContent(nodePath, mainJs), "utf8");
73
+ if (targets.needsChmod)
74
+ await chmod(launcherPath, 0o755);
75
+ lines.push(`launcher: ${launcherPath}`);
76
+ // Skill (steering layer: the model reads it when a tab-walk task comes up).
77
+ const skillSource = SKILL_SOURCE_PATH(pkgRoot);
78
+ const skillTarget = SKILL_INSTALL_PATH(env.homeDir);
79
+ await mkdir(path.dirname(skillTarget), { recursive: true });
80
+ await cp(skillSource, skillTarget, { force: true });
81
+ lines.push(`skill: ${skillTarget}`);
82
+ // Manifest(s)
83
+ const manifest = buildManifest(launcherPath);
84
+ const manifestPaths = appManifestPaths(targets, env, pkgRoot, opts.apps);
85
+ if (targets.id === "windows") {
86
+ const winManifestFile = targets.windowsManifestPath(pkgRoot);
87
+ await mkdir(path.dirname(winManifestFile), { recursive: true });
88
+ await writeFile(winManifestFile, JSON.stringify(manifest, null, 2), "utf8");
89
+ lines.push(`manifest: ${winManifestFile}`);
90
+ const add = await env.exec("reg", [
91
+ "add",
92
+ `HKCU\\${WINDOWS_REGISTRY_KEY}`,
93
+ "/ve",
94
+ "/d",
95
+ winManifestFile,
96
+ "/f",
97
+ ]);
98
+ if (add.code !== 0)
99
+ throw new Error(`registry update failed: ${add.stderr || add.stdout}`);
100
+ lines.push(`registry: HKCU\\${WINDOWS_REGISTRY_KEY} -> ${winManifestFile} (apps: ${opts.apps.join(", ")})`);
101
+ }
102
+ else {
103
+ for (const loc of distinctManifestLocations(opts.apps, env.homeDir, env.platform)) {
104
+ await mkdir(path.dirname(loc.path), { recursive: true });
105
+ await writeFile(loc.path, JSON.stringify(manifest, null, 2), "utf8");
106
+ lines.push(`manifest: ${loc.path} (apps: ${loc.apps.join(", ")})`);
107
+ }
108
+ }
109
+ return { ok: true, lines, manifestPaths, launcherPath };
110
+ }
111
+ async function checkManifest(manifest, launcherPath, lines, issues) {
112
+ lines.push(`host name: ${manifest.name}`);
113
+ lines.push(`allowed_extensions: ${manifest.allowed_extensions.join(", ")}`);
114
+ if (manifest.name !== NATIVE_HOST_NAME)
115
+ issues.push(`unexpected host name: ${manifest.name}`);
116
+ if (!manifest.allowed_extensions.includes("pi-agent-firefox@matbee.com")) {
117
+ issues.push("allowed_extensions does not include pi-agent-firefox@matbee.com (Firefox)");
118
+ }
119
+ if (!manifest.allowed_extensions.includes("pi-agent-thunderbird@matbee.com")) {
120
+ issues.push("allowed_extensions does not include pi-agent-thunderbird@matbee.com (Thunderbird)");
121
+ }
122
+ if (manifest.type !== "stdio")
123
+ issues.push(`unexpected manifest type: ${manifest.type}`);
124
+ const targetLauncher = manifest.path;
125
+ const launcherExists = await fileExists(targetLauncher);
126
+ lines.push(`launcher: ${targetLauncher} (${launcherExists ? "ok" : "MISSING"})`);
127
+ if (!launcherExists)
128
+ issues.push(`launcher missing: ${targetLauncher}`);
129
+ if (launcherPath && manifest.path !== launcherPath) {
130
+ lines.push(`note: launcher differs from current package location (${launcherPath}); run install to repair`);
131
+ issues.push("stale launcher path (package moved?)");
132
+ }
133
+ return issues.length === 0;
134
+ }
135
+ async function readManifestFile(file) {
136
+ const manifest = await readJsonFile(file);
137
+ return manifest;
138
+ }
139
+ export async function statusHost(env, pkgRoot, targets, apps) {
140
+ const launcherPath = targets.launcherPath(pkgRoot);
141
+ const lines = [];
142
+ const issues = [];
143
+ const perApp = {};
144
+ const isWin = targets.id === "windows";
145
+ let registryValue;
146
+ if (isWin) {
147
+ const q = await env.exec("reg", ["query", `HKCU\\${WINDOWS_REGISTRY_KEY}`]);
148
+ if (q.code === 0) {
149
+ const match = q.stdout.split(/\r?\n/).find((l) => /REG_SZ/i.test(l));
150
+ registryValue = match?.split(/\s{2,}/).pop() ?? "";
151
+ }
152
+ }
153
+ for (const app of apps) {
154
+ const appLines = [];
155
+ const appIssues = [];
156
+ let manifest;
157
+ if (isWin) {
158
+ const manifestPath = targets.windowsManifestPath(pkgRoot);
159
+ if (!registryValue) {
160
+ appIssues.push("registry key missing");
161
+ }
162
+ else {
163
+ appLines.push(`registry: HKCU\\${WINDOWS_REGISTRY_KEY} -> ${registryValue}`);
164
+ manifest = await readJsonFile(registryValue);
165
+ if (!manifest)
166
+ appIssues.push(`manifest not found at registry path: ${registryValue}`);
167
+ }
168
+ perApp[app] = { installed: false, manifestPath: registryValue ?? manifestPath, issues: appIssues };
169
+ }
170
+ else {
171
+ const manifestPath = distinctManifestLocations([app], env.homeDir, env.platform)[0].path;
172
+ manifest = await readManifestFile(manifestPath);
173
+ if (!manifest) {
174
+ appIssues.push("manifest missing");
175
+ }
176
+ else {
177
+ appLines.push(`manifest: ${manifestPath}`);
178
+ }
179
+ perApp[app] = { installed: false, manifestPath, issues: appIssues };
180
+ }
181
+ if (manifest) {
182
+ // Check shared fields once per distinct file; per-app lines are short.
183
+ await checkManifest(manifest, isWin ? "" : launcherPath, appLines, appIssues);
184
+ perApp[app].installed = appIssues.length === 0;
185
+ perApp[app].issues = appIssues;
186
+ }
187
+ lines.push(`[${app}] ${perApp[app].installed ? "installed" : "NOT installed"}`);
188
+ for (const l of appLines)
189
+ lines.push(` ${l}`);
190
+ for (const i of appIssues) {
191
+ lines.push(` issue: ${i}`);
192
+ issues.push(`${app}: ${i}`);
193
+ }
194
+ }
195
+ return {
196
+ installed: apps.every((a) => perApp[a].installed),
197
+ lines,
198
+ perApp,
199
+ manifestPath: perApp[apps[0]]?.manifestPath,
200
+ launcherPath,
201
+ issues,
202
+ };
203
+ }
204
+ export async function uninstallHost(env, pkgRoot, targets, apps) {
205
+ const lines = [];
206
+ if (targets.id === "windows") {
207
+ const del = await env.exec("reg", ["delete", `HKCU\\${WINDOWS_REGISTRY_KEY}`, "/f"]);
208
+ if (del.code === 0)
209
+ lines.push("removed registry key");
210
+ else
211
+ lines.push(`registry delete reported: ${del.stderr || del.stdout || "already absent"}`);
212
+ const legacyDel = await env.exec("reg", ["delete", `HKCU\\${WINDOWS_LEGACY_REGISTRY_KEY}`, "/f"]);
213
+ if (legacyDel.code === 0)
214
+ lines.push("removed legacy registry key (dev.pi.browser)");
215
+ const manifestFile = targets.windowsManifestPath(pkgRoot);
216
+ await rm(manifestFile, { force: true });
217
+ lines.push(`removed manifest: ${manifestFile}`);
218
+ }
219
+ else {
220
+ const allApps = ["firefox", "thunderbird"];
221
+ for (const loc of distinctManifestLocations(allApps, env.homeDir, env.platform)) {
222
+ await rm(loc.path, { force: true });
223
+ lines.push(`removed manifest: ${loc.path}`);
224
+ }
225
+ for (const app of allApps) {
226
+ const legacy = legacyManifestPath(app, env.homeDir, env.platform);
227
+ if (legacy) {
228
+ await rm(legacy, { force: true });
229
+ lines.push(`removed legacy manifest: ${legacy}`);
230
+ }
231
+ }
232
+ }
233
+ // Skill removal applies to ALL platforms: install copies it unconditionally.
234
+ await rm(SKILL_INSTALL_PATH(env.homeDir), { force: true });
235
+ lines.push(`removed skill: ${SKILL_INSTALL_PATH(env.homeDir)}`);
236
+ return lines;
237
+ }
238
+ export function defaultExec() {
239
+ return (cmd, args) => new Promise((resolve) => {
240
+ execFile(cmd, args, { timeout: 30_000 }, (error, stdout, stderr) => {
241
+ let code = 0;
242
+ if (error) {
243
+ code = typeof error.code === "number" ? error.code : 1;
244
+ }
245
+ resolve({ code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
246
+ });
247
+ });
248
+ }
249
+ export function detectTargets(platform) {
250
+ if (platform === "darwin")
251
+ return MACOS;
252
+ if (platform === "win32")
253
+ return WINDOWS;
254
+ return LINUX;
255
+ }
256
+ async function readJsonFile(file) {
257
+ try {
258
+ const raw = await readFile(file, "utf8");
259
+ const parsed = JSON.parse(raw);
260
+ if (typeof parsed?.path !== "string" || typeof parsed?.name !== "string")
261
+ return undefined;
262
+ return parsed;
263
+ }
264
+ catch {
265
+ return undefined;
266
+ }
267
+ }
268
+ async function fileExists(file) {
269
+ try {
270
+ const s = await stat(file);
271
+ return s.isFile();
272
+ }
273
+ catch {
274
+ return false;
275
+ }
276
+ }
277
+ //# sourceMappingURL=platforms.js.map
package/dist/logger.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * stderr-only diagnostics logger (PRODUCT.md §43).
3
+ *
4
+ * `stdout` belongs exclusively to the Firefox Native Messaging protocol.
5
+ * Everything the host wants to log goes to stderr (which Firefox forwards
6
+ * to browser debugging output). Optionally mirrors to a log file.
7
+ */
8
+ import { createWriteStream, mkdirSync } from "node:fs";
9
+ import { dirname } from "node:path";
10
+ const LEVEL_RANK = { debug: 10, info: 20, warn: 30, error: 40 };
11
+ export function createLogger(options = {}) {
12
+ const level = options.level ?? (envLevel() ?? "info");
13
+ const stderr = options.stderr ?? process.stderr;
14
+ let logFile;
15
+ if (options.filePath) {
16
+ try {
17
+ mkdirSync(dirname(options.filePath), { recursive: true });
18
+ logFile = createWriteStream(options.filePath, { flags: "a" });
19
+ }
20
+ catch {
21
+ // Logging file is best-effort; never break the host over it.
22
+ logFile = undefined;
23
+ }
24
+ }
25
+ function emit(lvl, msg, data) {
26
+ if (LEVEL_RANK[lvl] < LEVEL_RANK[level])
27
+ return;
28
+ const line = `[${new Date().toISOString()}] [${lvl}] [pi-browser-host] ${msg}` +
29
+ (data !== undefined ? ` ${safeStringify(data)}` : "");
30
+ stderr.write(line + "\n");
31
+ logFile?.write(line + "\n");
32
+ }
33
+ return {
34
+ debug: (m, d) => emit("debug", m, d),
35
+ info: (m, d) => emit("info", m, d),
36
+ warn: (m, d) => emit("warn", m, d),
37
+ error: (m, d) => emit("error", m, d),
38
+ };
39
+ }
40
+ function envLevel() {
41
+ const v = (process.env.PI_BROWSER_LOG_LEVEL ?? "").toLowerCase();
42
+ return v === "debug" || v === "info" || v === "warn" || v === "error" ? v : undefined;
43
+ }
44
+ function safeStringify(data) {
45
+ try {
46
+ if (data instanceof Error)
47
+ return `${data.name}: ${data.message}`;
48
+ return JSON.stringify(data);
49
+ }
50
+ catch {
51
+ return String(data);
52
+ }
53
+ }
54
+ //# sourceMappingURL=logger.js.map
@@ -0,0 +1,98 @@
1
+ /**
2
+ * TypeBox parameter schemas for the read-only Thunderbird mail tools.
3
+ *
4
+ * These MUST stay in sync with the JSON Schemas in
5
+ * @pi-browser/protocol (mail-tools.ts) — the JSON is the transport-neutral
6
+ * contract, the TypeBox schemas are what Pi validates against and hands to
7
+ * the model. test/tool-schemas.test.ts enforces the sync.
8
+ */
9
+ import { Type } from "typebox";
10
+ import { MAIL_TOOLS } from "@pi-browser/protocol";
11
+ const empty = () => Type.Object({}, { additionalProperties: false });
12
+ const messageId = Type.Number({
13
+ description: "Thunderbird numeric message id. Transient: valid only within the current session; take it from the current context or a list/search result.",
14
+ });
15
+ const isoDate = (what) => Type.String({
16
+ description: `ISO 8601 date/time. Only messages ${what} this instant are returned.`,
17
+ });
18
+ const SCHEMAS = {
19
+ mail_get_context: empty(),
20
+ mail_get_selected_messages: Type.Object({
21
+ tabId: Type.Optional(Type.Number({ description: "Mail tab id (default: the current mail tab)." })),
22
+ limit: Type.Optional(Type.Number({ description: "Maximum number of messages to return (default 50, hard cap 200)." })),
23
+ }, { additionalProperties: false }),
24
+ mail_get_displayed_messages: Type.Object({
25
+ tabId: Type.Optional(Type.Number({ description: "Mail tab id (default: the current mail tab)." })),
26
+ limit: Type.Optional(Type.Number({ description: "Maximum number of messages to return (default 50, hard cap 200)." })),
27
+ }, { additionalProperties: false }),
28
+ mail_get_message: Type.Object({ messageId }, { additionalProperties: false, required: ["messageId"] }),
29
+ mail_get_message_body: Type.Object({
30
+ messageId,
31
+ prefer: Type.Optional(Type.Union([Type.Literal("text"), Type.Literal("html"), Type.Literal("auto")], {
32
+ description: "Which MIME part to prefer (default auto: text if present, else html).",
33
+ })),
34
+ maxChars: Type.Optional(Type.Number({ description: "Truncate the body to this many characters (default 50000)." })),
35
+ }, { additionalProperties: false, required: ["messageId"] }),
36
+ mail_search: Type.Object({
37
+ text: Type.Optional(Type.String({ description: "Case-insensitive text search in subject, body, sender, and recipient addresses (To/Cc/Bcc). Runs on the Gloda full-text index (the search bar's engine): words are AND-combined and quoted spans match as phrases, so word forms matter — 'addon' does not match 'Add-ons'." })),
38
+ from: Type.Optional(Type.String({ description: "Match the author/sender." })),
39
+ to: Type.Optional(Type.String({ description: "Match the recipients." })),
40
+ subject: Type.Optional(Type.String({ description: "Match the subject line." })),
41
+ accountId: Type.Optional(Type.String({ description: "Limit the search to one account." })),
42
+ folderId: Type.Optional(Type.String({ description: "Limit the search to one folder. Overrides scope." })),
43
+ scope: Type.Optional(Type.Union([Type.Literal("inbox"), Type.Literal("all")], {
44
+ description: "Search scope when no folderId is given: 'inbox' or 'all'. Defaults to all folders for filtered searches, Inbox(es) for bare listings.",
45
+ })),
46
+ after: Type.Optional(isoDate("sent after")),
47
+ before: Type.Optional(isoDate("sent before")),
48
+ hasAttachments: Type.Optional(Type.Boolean({ description: "Only messages with (true) or without (false) attachments." })),
49
+ unread: Type.Optional(Type.Boolean({ description: "Only unread (true) or read (false) messages." })),
50
+ tags: Type.Optional(Type.Array(Type.String(), {
51
+ description: "Only messages carrying the given tag(s) (tag names or keys). Combined per tagMode.",
52
+ })),
53
+ tagMode: Type.Optional(Type.Union([Type.Literal("all"), Type.Literal("any")], {
54
+ description: "How to combine multiple tags (default any: match at least one).",
55
+ })),
56
+ sort: Type.Optional(Type.Union([Type.Literal("date"), Type.Literal("subject"), Type.Literal("from")], {
57
+ description: "Sort key for the results (default date). 'from' sorts by author.",
58
+ })),
59
+ order: Type.Optional(Type.Union([Type.Literal("desc"), Type.Literal("asc")], {
60
+ description: "Sort direction (default desc: newest / last letter first).",
61
+ })),
62
+ limit: Type.Optional(Type.Number({ description: "Maximum number of results per page (default 25, max 100)." })),
63
+ cursor: Type.Optional(Type.String({
64
+ description: "Short opaque pagination token from a previous search result's nextCursor; pass it back unchanged to continue the same search — including an unfinished one, where it resumes the in-flight scan. It expires after a while of disuse, if the mailbox changes, or if the extension is reloaded — re-run mail_search for a fresh first page.",
65
+ })),
66
+ }, { additionalProperties: false }),
67
+ mail_debug_query: Type.Object({
68
+ query: Type.Object({}, {
69
+ description: "Raw WDAPI messages.query() parameters: fullText, body, subject, author, recipients, folderId, accountId, fromDate, toDate, flagged, read, new, junk, attachment, size, tags, messagesPerPage, autoPaginationTimeout, returnMessageListId, includeSubFolders.",
70
+ }),
71
+ poll: Type.Optional(Type.Object({
72
+ intervalMs: Type.Optional(Type.Number({ description: "Poll interval in ms (default 2000, max 10000)." })),
73
+ maxMs: Type.Optional(Type.Number({ description: "Stop polling after this many ms (default 60000, hard cap 110000)." })),
74
+ }, {
75
+ additionalProperties: false,
76
+ description: "When the query returns a messageListId (returnMessageListId: true), poll continueList on an interval. { intervalMs (default 2000, max 10000), maxMs (default 60000, hard cap 110000) }.",
77
+ })),
78
+ }, { additionalProperties: false, required: ["query"] }),
79
+ mail_list_attachments: Type.Object({ messageId }, { additionalProperties: false, required: ["messageId"] }),
80
+ mail_get_attachment: Type.Object({
81
+ messageId,
82
+ partName: Type.String({ description: "Attachment part name (from mail_list_attachments)." }),
83
+ maxBytes: Type.Optional(Type.Number({ description: "Maximum bytes to return (default 1048576, max 5242880)." })),
84
+ }, { additionalProperties: false, required: ["messageId", "partName"] }),
85
+ mail_list_accounts: empty(),
86
+ mail_list_tags: empty(),
87
+ mail_list_folders: Type.Object({
88
+ accountId: Type.Optional(Type.String({ description: "Limit to one account (default: all accounts)." })),
89
+ }, { additionalProperties: false }),
90
+ };
91
+ /** One entry per protocol mail tool, with its TypeBox parameter schema. */
92
+ export const MAIL_TOOL_SCHEMAS = MAIL_TOOLS.map((def) => {
93
+ const parameters = SCHEMAS[def.name];
94
+ if (!parameters)
95
+ throw new Error(`missing TypeBox schema for tool ${def.name}`);
96
+ return { name: def.name, description: def.description, parameters, readOnly: def.readOnly };
97
+ });
98
+ //# sourceMappingURL=schemas.js.map
@@ -0,0 +1,31 @@
1
+ /**
2
+ * TypeBox parameter schemas for the Thunderbird mail-organization (T4) tools.
3
+ * MUST stay in sync with the JSON Schemas in @pi-browser/protocol
4
+ * (mail-mutation-tools.ts) — enforced by test/tool-schemas.test.ts.
5
+ */
6
+ import { Type } from "typebox";
7
+ import { MAIL_MUTATION_TOOLS } from "@pi-browser/protocol";
8
+ const messageIds = Type.Array(Type.Number(), {
9
+ description: "The Thunderbird numeric message ids to act on (from the current context or selection). Transient: valid only within the current session.",
10
+ });
11
+ const read = Type.Boolean({ description: "Set read (true, default) or unread (false)." });
12
+ const tags = Type.Array(Type.String(), {
13
+ description: 'Tag names to apply, e.g. ["Finance"].',
14
+ });
15
+ const additive = Type.Boolean({
16
+ description: "Add to existing tags (true, default) or replace them (false).",
17
+ });
18
+ const folderId = Type.String({ description: "Destination folder id (from mail_list_folders)." });
19
+ const SCHEMAS = {
20
+ mail_mark_read: Type.Object({ messageIds, read: Type.Optional(read) }, { additionalProperties: false, required: ["messageIds"] }),
21
+ mail_set_tags: Type.Object({ messageIds, tags, additive: Type.Optional(additive) }, { additionalProperties: false, required: ["messageIds", "tags"] }),
22
+ mail_archive: Type.Object({ messageIds }, { additionalProperties: false, required: ["messageIds"] }),
23
+ mail_move: Type.Object({ messageIds, folderId }, { additionalProperties: false, required: ["messageIds", "folderId"] }),
24
+ };
25
+ export const MAIL_MUTATION_TOOL_SCHEMAS = MAIL_MUTATION_TOOLS.map((def) => {
26
+ const parameters = SCHEMAS[def.name];
27
+ if (!parameters)
28
+ throw new Error(`missing TypeBox schema for tool ${def.name}`);
29
+ return { name: def.name, description: def.description, parameters, readOnly: def.readOnly };
30
+ });
31
+ //# sourceMappingURL=schemas.js.map