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.
- package/LICENSE +21 -0
- package/dist/acp/agent.js +601 -0
- package/dist/acp/backend.js +2 -0
- package/dist/acp/config-options.js +26 -0
- package/dist/acp/mock-backend.js +277 -0
- package/dist/acp/sdk-backend.js +495 -0
- package/dist/browser/mcp-acp-client.js +81 -0
- package/dist/browser/provider.js +1045 -0
- package/dist/browser/schemas.js +221 -0
- package/dist/capability-registry.js +92 -0
- package/dist/client-heartbeat.js +118 -0
- package/dist/compose/schemas.js +90 -0
- package/dist/contacts/schemas.js +26 -0
- package/dist/installer/cli.js +70 -0
- package/dist/installer/common.js +93 -0
- package/dist/installer/index.js +341 -0
- package/dist/installer/mcp-clients.js +555 -0
- package/dist/installer/mcp.js +166 -0
- package/dist/installer/platforms.js +277 -0
- package/dist/logger.js +54 -0
- package/dist/mail/schemas.js +98 -0
- package/dist/mutation/schemas.js +31 -0
- package/dist/native-host/broker-ipc.js +344 -0
- package/dist/native-host/framing.js +76 -0
- package/dist/native-host/main.js +520 -0
- package/dist/native-host/mcp-server.js +322 -0
- package/dist/native-host/mcp-stdio-bridge.js +179 -0
- package/dist/native-host/mcp-stdio-main.js +13 -0
- package/dist/native-host/relay.js +84 -0
- package/dist/native-host/skills-startup.js +167 -0
- package/dist/native-host/transport.js +248 -0
- package/dist/permission-store.js +207 -0
- package/dist/repl/fs-sandbox.js +187 -0
- package/dist/repl/provider.js +252 -0
- package/dist/repl/runtime.js +436 -0
- package/dist/repl/types.js +10 -0
- package/dist/repl/worker.js +731 -0
- package/dist/skills/extension.js +99 -0
- package/dist/skills/grants-file.js +145 -0
- package/dist/skills/isolated-runner.js +259 -0
- package/dist/skills/mock-session-factory.js +49 -0
- package/dist/skills/package-roots.js +25 -0
- package/dist/skills/pi-bridge.js +8 -0
- package/dist/skills/pi-integration.js +110 -0
- package/dist/skills/planner.js +128 -0
- package/dist/skills/registry.js +104 -0
- package/dist/skills/skills-protocol.js +253 -0
- package/dist/skills/skills-service.js +195 -0
- package/dist/tool-bridge.js +8 -0
- package/dist/workspace.js +70 -0
- package/extensions/pi-browser-tools.ts +65 -0
- package/extensions/pi-browser.ts +60 -0
- package/extensions/pi-skills.ts +14 -0
- package/native/pi-agent-host +2 -0
- package/native/pi-browser-host +5 -0
- package/native/pi-browser-host.cmd +3 -0
- package/node_modules/@pi-browser/protocol/.bundled-by-trusted-user-agent +0 -0
- package/node_modules/@pi-browser/protocol/dist/acp.d.ts +10 -0
- package/node_modules/@pi-browser/protocol/dist/acp.js +9 -0
- package/node_modules/@pi-browser/protocol/dist/browser-tools.d.ts +33 -0
- package/node_modules/@pi-browser/protocol/dist/browser-tools.js +478 -0
- package/node_modules/@pi-browser/protocol/dist/callers.d.ts +108 -0
- package/node_modules/@pi-browser/protocol/dist/callers.js +56 -0
- package/node_modules/@pi-browser/protocol/dist/compose-tools.d.ts +30 -0
- package/node_modules/@pi-browser/protocol/dist/compose-tools.js +175 -0
- package/node_modules/@pi-browser/protocol/dist/contacts-tools.d.ts +23 -0
- package/node_modules/@pi-browser/protocol/dist/contacts-tools.js +63 -0
- package/node_modules/@pi-browser/protocol/dist/control-tools.d.ts +32 -0
- package/node_modules/@pi-browser/protocol/dist/control-tools.js +201 -0
- package/node_modules/@pi-browser/protocol/dist/errors.d.ts +63 -0
- package/node_modules/@pi-browser/protocol/dist/errors.js +109 -0
- package/node_modules/@pi-browser/protocol/dist/index.d.ts +16 -0
- package/node_modules/@pi-browser/protocol/dist/index.js +16 -0
- package/node_modules/@pi-browser/protocol/dist/integration.d.ts +409 -0
- package/node_modules/@pi-browser/protocol/dist/integration.js +260 -0
- package/node_modules/@pi-browser/protocol/dist/jsonrpc.d.ts +33 -0
- package/node_modules/@pi-browser/protocol/dist/jsonrpc.js +31 -0
- package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.d.ts +27 -0
- package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.js +88 -0
- package/node_modules/@pi-browser/protocol/dist/mail-tools.d.ts +133 -0
- package/node_modules/@pi-browser/protocol/dist/mail-tools.js +245 -0
- package/node_modules/@pi-browser/protocol/dist/permission.d.ts +113 -0
- package/node_modules/@pi-browser/protocol/dist/permission.js +257 -0
- package/node_modules/@pi-browser/protocol/dist/skills.d.ts +304 -0
- package/node_modules/@pi-browser/protocol/dist/skills.js +473 -0
- package/node_modules/@pi-browser/protocol/dist/tool-capabilities.d.ts +18 -0
- package/node_modules/@pi-browser/protocol/dist/tool-capabilities.js +52 -0
- package/node_modules/@pi-browser/protocol/dist/transport.d.ts +17 -0
- package/node_modules/@pi-browser/protocol/dist/transport.js +17 -0
- package/node_modules/@pi-browser/protocol/package.json +14 -0
- package/package.json +71 -6
- package/skills/browser-walk/SKILL.md +98 -0
- package/README.md +0 -3
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skills runtime startup for the native host (skills-runtime-design.md §3, §13).
|
|
3
|
+
*
|
|
4
|
+
* The broker owns the registry and the SkillsService. The registry is
|
|
5
|
+
* best-effort: a missing or invalid packages root degrades to "no skills"
|
|
6
|
+
* and never blocks browser integration startup.
|
|
7
|
+
*/
|
|
8
|
+
import { mkdirSync, statSync, watch } from "node:fs";
|
|
9
|
+
import { appendFile, rename, unlink } from "node:fs/promises";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import { discoverSkillPackages, SkillsRegistry } from "../skills/registry.js";
|
|
13
|
+
import { createSkillsHost } from "../skills/pi-integration.js";
|
|
14
|
+
import { SkillsPlanner } from "../skills/planner.js";
|
|
15
|
+
import { resolveSkillPackageRoots } from "../skills/package-roots.js";
|
|
16
|
+
import { PiSdkBackend } from "../acp/sdk-backend.js";
|
|
17
|
+
import { toErrorObject } from "@pi-browser/protocol";
|
|
18
|
+
import { createSkillsProtocol } from "../skills/skills-protocol.js";
|
|
19
|
+
/** Discover the skill packages under every configured root (best-effort). */
|
|
20
|
+
async function loadSkillPackages() {
|
|
21
|
+
const packageRoots = resolveSkillPackageRoots();
|
|
22
|
+
const packages = (await Promise.all(packageRoots.map(async (root) => {
|
|
23
|
+
try {
|
|
24
|
+
return await discoverSkillPackages(root);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return []; // root absent (first run) — nothing to load from it
|
|
28
|
+
}
|
|
29
|
+
}))).flat();
|
|
30
|
+
return packages;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* One catalog reload: re-discover the packages, atomically swap the
|
|
34
|
+
* registry snapshot, and rebuild the planner index from it. A failed
|
|
35
|
+
* reload preserves the previous snapshot (registry.reload contract), so a
|
|
36
|
+
* half-written package can never take down the running catalog.
|
|
37
|
+
*/
|
|
38
|
+
export async function reloadSkillCatalog(log, runtime) {
|
|
39
|
+
const packages = await loadSkillPackages();
|
|
40
|
+
await runtime.registry.reload(packages);
|
|
41
|
+
runtime.planner.reload(runtime.registry.snapshot());
|
|
42
|
+
const result = { packages: packages.length, skills: runtime.registry.size, generation: runtime.registry.version };
|
|
43
|
+
log.info(`skills catalog reloaded (packages=${result.packages}, skills=${result.skills}, generation=${result.generation})`);
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
const SKILLS_EVENT_LOG_MAX_BYTES = 1024 * 1024;
|
|
47
|
+
export function createSkillsEventLog(log, filePath) {
|
|
48
|
+
let tail = Promise.resolve();
|
|
49
|
+
return {
|
|
50
|
+
record(event) {
|
|
51
|
+
const line = `${JSON.stringify({ t: Date.now(), ...event })}\n`;
|
|
52
|
+
tail = tail.then(async () => {
|
|
53
|
+
try {
|
|
54
|
+
// The first write creates the file; statSync is for rotation only.
|
|
55
|
+
try {
|
|
56
|
+
if (statSync(filePath).size > SKILLS_EVENT_LOG_MAX_BYTES) {
|
|
57
|
+
await rename(filePath, `${filePath}.1`).catch(() => { });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
catch { /* no file yet */ }
|
|
61
|
+
await appendFile(filePath, line, "utf8");
|
|
62
|
+
}
|
|
63
|
+
catch (err) {
|
|
64
|
+
log.warn(`skills event log write failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
65
|
+
}
|
|
66
|
+
}).catch(() => { });
|
|
67
|
+
},
|
|
68
|
+
close: async () => { await tail.catch(() => { }); },
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export function startSkillsCatalogReloader(deps) {
|
|
72
|
+
const runDir = process.env.PI_BROWSER_BROKER_DIR?.trim() || path.join(homedir(), ".pi", "run");
|
|
73
|
+
const triggerPath = path.join(runDir, SKILLS_CATALOG_RELOAD_FILE);
|
|
74
|
+
// Normally the broker created it already; don't depend on that ordering.
|
|
75
|
+
mkdirSync(runDir, { recursive: true, mode: 0o700 });
|
|
76
|
+
let timer;
|
|
77
|
+
let tail = Promise.resolve();
|
|
78
|
+
let closed = false;
|
|
79
|
+
const watcher = watch(runDir, (eventType, filename) => {
|
|
80
|
+
if (closed || filename !== SKILLS_CATALOG_RELOAD_FILE)
|
|
81
|
+
return;
|
|
82
|
+
// Consume the request IMMEDIATELY: the unlink itself fires a watch
|
|
83
|
+
// event, and consuming at execution time would re-arm a second reload.
|
|
84
|
+
void unlink(triggerPath).catch(() => { });
|
|
85
|
+
// Debounce: touch + the consuming unlink arrive as separate events;
|
|
86
|
+
// the latter only re-arms the timer (the file is already gone).
|
|
87
|
+
if (timer)
|
|
88
|
+
clearTimeout(timer);
|
|
89
|
+
timer = setTimeout(() => {
|
|
90
|
+
timer = undefined;
|
|
91
|
+
tail = tail.then(async () => {
|
|
92
|
+
try {
|
|
93
|
+
const result = await reloadSkillCatalog(deps.log, deps.runtime);
|
|
94
|
+
deps.record?.({ type: "reload", ...result, ok: true });
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
deps.log.warn(`skills catalog reload failed; keeping previous snapshot: ${err instanceof Error ? err.message : String(err)}`);
|
|
98
|
+
deps.record?.({ type: "reload", packages: deps.runtime.registry.size, skills: deps.runtime.registry.size, generation: deps.runtime.registry.version, ok: false });
|
|
99
|
+
}
|
|
100
|
+
}).catch(() => { });
|
|
101
|
+
}, 250);
|
|
102
|
+
});
|
|
103
|
+
watcher.on("error", (err) => deps.log.warn(`skills catalog reload watcher error: ${err.message}`));
|
|
104
|
+
deps.log.info(`skills catalog reload armed: touch ${triggerPath}`);
|
|
105
|
+
return {
|
|
106
|
+
path: triggerPath,
|
|
107
|
+
close: async () => {
|
|
108
|
+
closed = true;
|
|
109
|
+
if (timer)
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
watcher.close();
|
|
112
|
+
await tail.catch(() => { });
|
|
113
|
+
},
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** Trigger file name inside the broker run dir (host-side dev seam only). */
|
|
117
|
+
export const SKILLS_CATALOG_RELOAD_FILE = "skills-catalog-reload";
|
|
118
|
+
export async function startSkillsRuntime(deps) {
|
|
119
|
+
const registry = new SkillsRegistry();
|
|
120
|
+
try {
|
|
121
|
+
const packageRoots = resolveSkillPackageRoots();
|
|
122
|
+
const packages = await loadSkillPackages();
|
|
123
|
+
if (packages.length > 0)
|
|
124
|
+
await registry.reload(packages);
|
|
125
|
+
const host = createSkillsHost({
|
|
126
|
+
log: deps.log,
|
|
127
|
+
registry,
|
|
128
|
+
browserBridge: deps.toolBridge,
|
|
129
|
+
// Reuse the backend's model runtime so provider credentials resolve
|
|
130
|
+
// identically for job sessions and chat sessions.
|
|
131
|
+
...(deps.backend instanceof PiSdkBackend ? { modelRuntime: await deps.backend.sharedModelRuntime() } : {}),
|
|
132
|
+
...(process.env.PI_BROWSER_AGENT_DIR ? { agentDir: process.env.PI_BROWSER_AGENT_DIR } : {}),
|
|
133
|
+
...(deps.sessionFactory ? { sessionFactory: deps.sessionFactory } : {}),
|
|
134
|
+
});
|
|
135
|
+
deps.log.info(`skills host ready (package roots=${packageRoots.length}, packages=${packages.length}, skills=${registry.snapshot().length})`);
|
|
136
|
+
return { host, registry, planner: new SkillsPlanner(registry.snapshot()) };
|
|
137
|
+
}
|
|
138
|
+
catch (err) {
|
|
139
|
+
deps.log.warn("skills runtime unavailable; continuing without skills", err);
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* One skills protocol surface per client connection (design §7): verified
|
|
145
|
+
* source identity is per-connection, results route back on the same
|
|
146
|
+
* transport. v1 ships no settings store and no site adapters, so nothing is
|
|
147
|
+
* granted and no plan arms a rule: the surface is fully wired but inert by
|
|
148
|
+
* design (design §12: installed ≠ enabled ≠ armed). The getters are injected
|
|
149
|
+
* so a later settings/adapter module swaps in real values without touching
|
|
150
|
+
* the host wiring.
|
|
151
|
+
*/
|
|
152
|
+
export function createClientSkillsProtocol(deps) {
|
|
153
|
+
const protocol = createSkillsProtocol({
|
|
154
|
+
log: deps.log,
|
|
155
|
+
host: deps.runtime.host,
|
|
156
|
+
registry: deps.runtime.registry,
|
|
157
|
+
planner: deps.runtime.planner,
|
|
158
|
+
grants: deps.grants ?? (() => new Map()),
|
|
159
|
+
endpoint: deps.transport,
|
|
160
|
+
...(deps.record ? { onLifecycle: deps.record } : {}),
|
|
161
|
+
});
|
|
162
|
+
return {
|
|
163
|
+
extendedRequest: (method, params, id) => protocol.handle(method, params, (result) => deps.transport.respond(id, result), (code, message) => deps.transport.respondError(id, toErrorObject(code, message))),
|
|
164
|
+
dispose: () => protocol.dispose(),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
//# sourceMappingURL=skills-startup.js.map
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { encodeFrame, FrameDecoder, FramingError } from "./framing.js";
|
|
2
|
+
import { isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, JSONRPC_ERROR, } from "@pi-browser/protocol";
|
|
3
|
+
export class TransportTimeoutError extends Error {
|
|
4
|
+
method;
|
|
5
|
+
timeoutMs;
|
|
6
|
+
constructor(method, timeoutMs) {
|
|
7
|
+
super(`request timed out after ${timeoutMs}ms: ${method}`);
|
|
8
|
+
this.method = method;
|
|
9
|
+
this.timeoutMs = timeoutMs;
|
|
10
|
+
this.name = "TransportTimeoutError";
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export class TransportClosedError extends Error {
|
|
14
|
+
constructor() {
|
|
15
|
+
super("transport closed");
|
|
16
|
+
this.name = "TransportClosedError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
|
|
20
|
+
/**
|
|
21
|
+
* Core JSON-RPC dispatcher shared by the stdio and in-memory transports.
|
|
22
|
+
* `write` is invoked with parsed JSON-RPC messages (the stdio adapter
|
|
23
|
+
* wraps them into Firefox frames).
|
|
24
|
+
*/
|
|
25
|
+
export function createJsonRpcDispatcher(write, opts) {
|
|
26
|
+
const { log } = opts;
|
|
27
|
+
const pending = new Map();
|
|
28
|
+
let nextId = 1;
|
|
29
|
+
let closed = false;
|
|
30
|
+
let eofEmitted = false;
|
|
31
|
+
const transport = {
|
|
32
|
+
get closed() {
|
|
33
|
+
return closed;
|
|
34
|
+
},
|
|
35
|
+
onRequest: undefined,
|
|
36
|
+
onNotification: undefined,
|
|
37
|
+
onEof: undefined,
|
|
38
|
+
request(method, params, timeoutMs = DEFAULT_REQUEST_TIMEOUT_MS) {
|
|
39
|
+
if (closed)
|
|
40
|
+
return Promise.reject(new TransportClosedError());
|
|
41
|
+
const id = nextId++;
|
|
42
|
+
const msg = { jsonrpc: "2.0", id, method, ...(params !== undefined ? { params } : {}) };
|
|
43
|
+
const promise = new Promise((resolve, reject) => {
|
|
44
|
+
const timer = setTimeout(() => {
|
|
45
|
+
pending.delete(id);
|
|
46
|
+
reject(new TransportTimeoutError(method, timeoutMs));
|
|
47
|
+
}, timeoutMs);
|
|
48
|
+
pending.set(id, { resolve, reject, timer, method });
|
|
49
|
+
});
|
|
50
|
+
try {
|
|
51
|
+
write(msg);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
const p = pending.get(id);
|
|
55
|
+
if (p) {
|
|
56
|
+
clearTimeout(p.timer);
|
|
57
|
+
pending.delete(id);
|
|
58
|
+
}
|
|
59
|
+
log.error(`failed to send request ${method}`, err);
|
|
60
|
+
return Promise.reject(err);
|
|
61
|
+
}
|
|
62
|
+
return promise;
|
|
63
|
+
},
|
|
64
|
+
notify(method, params) {
|
|
65
|
+
if (closed)
|
|
66
|
+
return;
|
|
67
|
+
try {
|
|
68
|
+
write({ jsonrpc: "2.0", method, ...(params !== undefined ? { params } : {}) });
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
log.error(`failed to send notification ${method}`, err);
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
respond(id, result) {
|
|
75
|
+
if (closed)
|
|
76
|
+
return;
|
|
77
|
+
try {
|
|
78
|
+
write({ jsonrpc: "2.0", id, result: result === undefined ? null : result });
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
log.error("failed to send response", err);
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
respondError(id, error) {
|
|
85
|
+
if (closed)
|
|
86
|
+
return;
|
|
87
|
+
try {
|
|
88
|
+
write({ jsonrpc: "2.0", id, error });
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
log.error("failed to send error response", err);
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
close() {
|
|
95
|
+
if (closed)
|
|
96
|
+
return;
|
|
97
|
+
closed = true;
|
|
98
|
+
for (const p of pending.values()) {
|
|
99
|
+
clearTimeout(p.timer);
|
|
100
|
+
p.reject(new TransportClosedError());
|
|
101
|
+
}
|
|
102
|
+
pending.clear();
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
function deliverMessage(msg) {
|
|
106
|
+
if (closed)
|
|
107
|
+
return;
|
|
108
|
+
if (isJsonRpcResponse(msg)) {
|
|
109
|
+
const p = pending.get(msg.id);
|
|
110
|
+
if (!p) {
|
|
111
|
+
log.debug(`response for unknown id ${msg.id}`);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
clearTimeout(p.timer);
|
|
115
|
+
pending.delete(msg.id);
|
|
116
|
+
if (msg.error)
|
|
117
|
+
p.reject({ jsonrpc: "2.0", ...msg.error });
|
|
118
|
+
else
|
|
119
|
+
p.resolve(msg.result);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (isJsonRpcRequest(msg)) {
|
|
123
|
+
const handler = transport.onRequest;
|
|
124
|
+
if (!handler) {
|
|
125
|
+
transport.respondError(msg.id, {
|
|
126
|
+
code: JSONRPC_ERROR.METHOD_NOT_FOUND,
|
|
127
|
+
message: `no request handler for ${msg.method}`,
|
|
128
|
+
});
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
handler(msg.method, msg.params, msg.id);
|
|
133
|
+
}
|
|
134
|
+
catch (err) {
|
|
135
|
+
log.error(`request handler threw: ${msg.method}`, err);
|
|
136
|
+
transport.respondError(msg.id, {
|
|
137
|
+
code: JSONRPC_ERROR.INTERNAL,
|
|
138
|
+
message: err instanceof Error ? err.message : String(err),
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (isJsonRpcNotification(msg)) {
|
|
144
|
+
try {
|
|
145
|
+
transport.onNotification?.(msg.method, msg.params);
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
log.error(`notification handler threw: ${msg.method}`, err);
|
|
149
|
+
}
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
log.warn(`dropping malformed message: ${String(msg).slice(0, 200)}`);
|
|
153
|
+
}
|
|
154
|
+
function emitEof() {
|
|
155
|
+
if (eofEmitted)
|
|
156
|
+
return;
|
|
157
|
+
eofEmitted = true;
|
|
158
|
+
try {
|
|
159
|
+
transport.onEof?.();
|
|
160
|
+
}
|
|
161
|
+
catch (err) {
|
|
162
|
+
log.error("onEof handler threw", err);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
transport,
|
|
167
|
+
deliverMessage,
|
|
168
|
+
dispose() {
|
|
169
|
+
// First dispose signals the peer went away (input EOF/error) — emit
|
|
170
|
+
// onEof exactly once, then. A later local close() (shutdown) must not
|
|
171
|
+
// emit a second EOF.
|
|
172
|
+
const firstDispose = !closed;
|
|
173
|
+
closed = true;
|
|
174
|
+
for (const p of pending.values()) {
|
|
175
|
+
clearTimeout(p.timer);
|
|
176
|
+
p.reject(new TransportClosedError());
|
|
177
|
+
}
|
|
178
|
+
pending.clear();
|
|
179
|
+
if (firstDispose)
|
|
180
|
+
emitEof();
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Host-side transport: Firefox framing on stdin/stdout.
|
|
186
|
+
*/
|
|
187
|
+
export function createStdioTransport(input, output, log) {
|
|
188
|
+
const decoder = new FrameDecoder();
|
|
189
|
+
const dispatcher = createJsonRpcDispatcher((msg) => {
|
|
190
|
+
const frame = encodeFrame(msg);
|
|
191
|
+
if (!output.write(frame)) {
|
|
192
|
+
// Backpressure: drain before the next write is safe. Native Messaging
|
|
193
|
+
// messages are small except screenshots; buffer briefly.
|
|
194
|
+
log.debug("stdout backpressure; waiting for drain");
|
|
195
|
+
}
|
|
196
|
+
}, { log });
|
|
197
|
+
input.on("data", (chunk) => {
|
|
198
|
+
try {
|
|
199
|
+
decoder.push(chunk);
|
|
200
|
+
for (const frame of decoder.readAll()) {
|
|
201
|
+
let msg;
|
|
202
|
+
try {
|
|
203
|
+
msg = JSON.parse(frame.toString("utf8"));
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
log.warn("malformed JSON frame dropped");
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
dispatcher.deliverMessage(msg);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
catch (err) {
|
|
213
|
+
if (err instanceof FramingError) {
|
|
214
|
+
log.error(`framing violation (${err.reason}); terminating connection`, err);
|
|
215
|
+
dispatcher.dispose();
|
|
216
|
+
output.end();
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
log.error("framing error", err);
|
|
220
|
+
dispatcher.dispose();
|
|
221
|
+
output.end();
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
input.on("end", () => dispatcher.dispose());
|
|
226
|
+
input.on("close", () => dispatcher.dispose());
|
|
227
|
+
input.on("error", (err) => {
|
|
228
|
+
log.error("stdin error", err);
|
|
229
|
+
dispatcher.dispose();
|
|
230
|
+
});
|
|
231
|
+
output.on("error", (err) => {
|
|
232
|
+
log.error("stdout error", err);
|
|
233
|
+
dispatcher.dispose();
|
|
234
|
+
});
|
|
235
|
+
return dispatcher;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* In-memory transport pair for tests and for wiring two in-process
|
|
239
|
+
* dispatchers (e.g. a fake Firefox driving the real host transport code).
|
|
240
|
+
*/
|
|
241
|
+
export function createMemoryTransportPair(aLog, bLog) {
|
|
242
|
+
let a;
|
|
243
|
+
let b;
|
|
244
|
+
a = createJsonRpcDispatcher((msg) => b.deliverMessage(msg), { log: aLog });
|
|
245
|
+
b = createJsonRpcDispatcher((msg) => a.deliverMessage(msg), { log: bLog });
|
|
246
|
+
return { a, b };
|
|
247
|
+
}
|
|
248
|
+
//# sourceMappingURL=transport.js.map
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Persistent per-tool permission store (PRODUCT.md §55, 2026-09-15).
|
|
3
|
+
*
|
|
4
|
+
* Every add-on tool is approval-gated; the user's persistent decision for
|
|
5
|
+
* each tool — "ask" (default), "deny", or "allow" — is remembered HERE, in a
|
|
6
|
+
* small JSON file under ~/.pi/browser, so it survives host restarts and is
|
|
7
|
+
* shared by every connected application (the broker process is the single
|
|
8
|
+
* owner of this state). The add-on's Configuration page renders and edits
|
|
9
|
+
* exactly this state.
|
|
10
|
+
*
|
|
11
|
+
* File format (v2):
|
|
12
|
+
* { "version": 2, "tools": { "mail_search": "allow", "mail_move": "deny" } }
|
|
13
|
+
*
|
|
14
|
+
* External MCP callers (v0.3.0) add two optional keys to the same v2 file:
|
|
15
|
+
* "callers": { "firefox": { "codex": "allow" }, "thunderbird": { "x": "deny" } }
|
|
16
|
+
* "externalAccess": false (stored only when turned off; default on)
|
|
17
|
+
* Older hosts ignore both keys.
|
|
18
|
+
*
|
|
19
|
+
* Only tools with a non-default decision are stored; absence means "ask".
|
|
20
|
+
* v1 files ({"tools": {"name": true}}) are migrated on load (true → allow).
|
|
21
|
+
* The file is small (one key per tool), so synchronous fs calls are fine;
|
|
22
|
+
* writes are atomic (tmp + rename) so a crash never leaves a truncated file.
|
|
23
|
+
*/
|
|
24
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { homedir } from "node:os";
|
|
26
|
+
import { dirname, join } from "node:path";
|
|
27
|
+
const CALLER_APPS = ["firefox", "thunderbird"];
|
|
28
|
+
export function defaultPermissionFilePath() {
|
|
29
|
+
return process.env.PI_BROWSER_PERMISSIONS_FILE
|
|
30
|
+
? process.env.PI_BROWSER_PERMISSIONS_FILE
|
|
31
|
+
: join(homedir(), ".pi", "browser", "permissions.json");
|
|
32
|
+
}
|
|
33
|
+
export class PermissionStore {
|
|
34
|
+
filePath;
|
|
35
|
+
/** Only non-default decisions are kept; absence = "ask". */
|
|
36
|
+
tools = new Map();
|
|
37
|
+
/** Remembered caller decisions: "<app>\u0000<name>" → allow | deny. */
|
|
38
|
+
callers = new Map();
|
|
39
|
+
externalAccess = true;
|
|
40
|
+
loaded = false;
|
|
41
|
+
constructor(options = {}) {
|
|
42
|
+
this.filePath = options.filePath ?? defaultPermissionFilePath();
|
|
43
|
+
}
|
|
44
|
+
/** The backing file (tests, diagnostics). */
|
|
45
|
+
get file() {
|
|
46
|
+
return this.filePath;
|
|
47
|
+
}
|
|
48
|
+
ensureLoaded() {
|
|
49
|
+
if (this.loaded)
|
|
50
|
+
return;
|
|
51
|
+
this.loaded = true;
|
|
52
|
+
try {
|
|
53
|
+
if (!existsSync(this.filePath))
|
|
54
|
+
return;
|
|
55
|
+
const raw = JSON.parse(readFileSync(this.filePath, "utf8"));
|
|
56
|
+
if (typeof raw.tools !== "object" || raw.tools === null)
|
|
57
|
+
return;
|
|
58
|
+
if (raw.version === 2) {
|
|
59
|
+
for (const [name, state] of Object.entries(raw.tools)) {
|
|
60
|
+
if (state === "allow" || state === "deny")
|
|
61
|
+
this.tools.set(name, state);
|
|
62
|
+
}
|
|
63
|
+
const v2 = raw;
|
|
64
|
+
if (v2.externalAccess === false)
|
|
65
|
+
this.externalAccess = false;
|
|
66
|
+
if (typeof v2.callers === "object" && v2.callers !== null) {
|
|
67
|
+
for (const app of CALLER_APPS) {
|
|
68
|
+
const byName = v2.callers[app];
|
|
69
|
+
if (typeof byName !== "object" || byName === null)
|
|
70
|
+
continue;
|
|
71
|
+
for (const [name, state] of Object.entries(byName)) {
|
|
72
|
+
if (state === "allow" || state === "deny")
|
|
73
|
+
this.callers.set(callerKey(app, name), state);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
else if (raw.version === 1) {
|
|
79
|
+
// v1 stored only allows (true); migrate to the tri-state file.
|
|
80
|
+
for (const [name, allowed] of Object.entries(raw.tools)) {
|
|
81
|
+
if (allowed === true)
|
|
82
|
+
this.tools.set(name, "allow");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
// Corrupt/unreadable file: start clean rather than crashing the host.
|
|
88
|
+
// The user's decisions are lost, which is safe (worst case: prompts).
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** The tool's persistent state ("ask" when no decision was stored). */
|
|
92
|
+
getState(tool) {
|
|
93
|
+
this.ensureLoaded();
|
|
94
|
+
return this.tools.get(tool) ?? "ask";
|
|
95
|
+
}
|
|
96
|
+
/** True when the tool is persistently allowed ("Always approve"). */
|
|
97
|
+
isAllowed(tool) {
|
|
98
|
+
return this.getState(tool) === "allow";
|
|
99
|
+
}
|
|
100
|
+
/** True when the tool is persistently denied (refuse without asking). */
|
|
101
|
+
isDenied(tool) {
|
|
102
|
+
return this.getState(tool) === "deny";
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Set the tool's persistent state. "ask" removes any stored decision.
|
|
106
|
+
*/
|
|
107
|
+
setState(tool, state) {
|
|
108
|
+
this.ensureLoaded();
|
|
109
|
+
if (state === "ask")
|
|
110
|
+
this.tools.delete(tool);
|
|
111
|
+
else
|
|
112
|
+
this.tools.set(tool, state);
|
|
113
|
+
this.persist();
|
|
114
|
+
}
|
|
115
|
+
/** Grant (state="allow") or revoke (state="ask") a tool's persistent allow. */
|
|
116
|
+
setAllowed(tool, allowed) {
|
|
117
|
+
this.setState(tool, allowed ? "allow" : "ask");
|
|
118
|
+
}
|
|
119
|
+
/** Clear one tool's persistent decision (no-op when it was "ask"). */
|
|
120
|
+
clear(tool) {
|
|
121
|
+
this.ensureLoaded();
|
|
122
|
+
if (this.tools.delete(tool))
|
|
123
|
+
this.persist();
|
|
124
|
+
}
|
|
125
|
+
/** Clear every persistent decision. Returns the names that were cleared. */
|
|
126
|
+
clearAll() {
|
|
127
|
+
this.ensureLoaded();
|
|
128
|
+
const cleared = [...this.tools.keys()].sort();
|
|
129
|
+
this.tools.clear();
|
|
130
|
+
if (cleared.length > 0)
|
|
131
|
+
this.persist();
|
|
132
|
+
return cleared;
|
|
133
|
+
}
|
|
134
|
+
/** Sorted list of currently-allowed tool names. */
|
|
135
|
+
allowedTools() {
|
|
136
|
+
this.ensureLoaded();
|
|
137
|
+
return [...this.tools.entries()]
|
|
138
|
+
.filter(([, s]) => s === "allow")
|
|
139
|
+
.map(([t]) => t)
|
|
140
|
+
.sort();
|
|
141
|
+
}
|
|
142
|
+
// ------------------------------------------------------------------
|
|
143
|
+
// External MCP callers
|
|
144
|
+
// ------------------------------------------------------------------
|
|
145
|
+
/** Whether external MCP callers may use the tools at all (default true). */
|
|
146
|
+
getExternalAccess() {
|
|
147
|
+
this.ensureLoaded();
|
|
148
|
+
return this.externalAccess;
|
|
149
|
+
}
|
|
150
|
+
setExternalAccess(on) {
|
|
151
|
+
this.ensureLoaded();
|
|
152
|
+
this.externalAccess = on;
|
|
153
|
+
this.persist();
|
|
154
|
+
}
|
|
155
|
+
/** A caller's remembered decision for one app (undefined = ask). */
|
|
156
|
+
getCallerState(app, name) {
|
|
157
|
+
this.ensureLoaded();
|
|
158
|
+
return this.callers.get(callerKey(app, name));
|
|
159
|
+
}
|
|
160
|
+
/** Remember (allow | deny) or forget ("ask") a caller's decision for one app. */
|
|
161
|
+
setCallerState(app, name, state) {
|
|
162
|
+
this.ensureLoaded();
|
|
163
|
+
if (state === "ask") {
|
|
164
|
+
if (!this.callers.delete(callerKey(app, name)))
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
this.callers.set(callerKey(app, name), state);
|
|
169
|
+
}
|
|
170
|
+
this.persist();
|
|
171
|
+
}
|
|
172
|
+
/** Every remembered caller decision, sorted by app then name. */
|
|
173
|
+
listCallers() {
|
|
174
|
+
this.ensureLoaded();
|
|
175
|
+
return [...this.callers.entries()]
|
|
176
|
+
.map(([key, state]) => {
|
|
177
|
+
const [application, name] = splitCallerKey(key);
|
|
178
|
+
return { application, name, state };
|
|
179
|
+
})
|
|
180
|
+
.sort((a, b) => a.application.localeCompare(b.application) || a.name.localeCompare(b.name));
|
|
181
|
+
}
|
|
182
|
+
persist() {
|
|
183
|
+
const callers = {};
|
|
184
|
+
for (const { application, name, state } of this.listCallers()) {
|
|
185
|
+
(callers[application] ??= {})[name] = state;
|
|
186
|
+
}
|
|
187
|
+
const file = {
|
|
188
|
+
version: 2,
|
|
189
|
+
tools: Object.fromEntries([...this.tools.entries()].sort(([a], [b]) => a.localeCompare(b))),
|
|
190
|
+
...(Object.keys(callers).length > 0 ? { callers } : {}),
|
|
191
|
+
...(this.externalAccess ? {} : { externalAccess: false }),
|
|
192
|
+
};
|
|
193
|
+
const dir = dirname(this.filePath);
|
|
194
|
+
mkdirSync(dir, { recursive: true });
|
|
195
|
+
const tmp = `${this.filePath}.tmp`;
|
|
196
|
+
writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", "utf8");
|
|
197
|
+
renameSync(tmp, this.filePath);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function callerKey(app, name) {
|
|
201
|
+
return `${app}\u0000${name}`;
|
|
202
|
+
}
|
|
203
|
+
function splitCallerKey(key) {
|
|
204
|
+
const i = key.indexOf("\u0000");
|
|
205
|
+
return [key.slice(0, i), key.slice(i + 1)];
|
|
206
|
+
}
|
|
207
|
+
//# sourceMappingURL=permission-store.js.map
|