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.
- package/LICENSE +21 -0
- package/README.md +232 -2
- package/dist/acp/agent.js +719 -0
- package/dist/acp/agents/connection.js +298 -0
- package/dist/acp/agents/manager.js +363 -0
- package/dist/acp/agents/registry.js +201 -0
- package/dist/acp/agents/relay-session.js +371 -0
- package/dist/acp/agents/session-index.js +102 -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 +1049 -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 +366 -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 +545 -0
- package/dist/native-host/mcp-server.js +333 -0
- package/dist/native-host/mcp-stdio-bridge.js +184 -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/agents.d.ts +51 -0
- package/node_modules/@pi-browser/protocol/dist/agents.js +44 -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 +123 -0
- package/node_modules/@pi-browser/protocol/dist/callers.js +58 -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 +17 -0
- package/node_modules/@pi-browser/protocol/dist/index.js +17 -0
- package/node_modules/@pi-browser/protocol/dist/integration.d.ts +414 -0
- package/node_modules/@pi-browser/protocol/dist/integration.js +270 -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 +69 -4
- package/skills/browser-walk/SKILL.md +98 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skills host wiring (skills-runtime-design.md §10, §13 "pi-integration").
|
|
3
|
+
*
|
|
4
|
+
* createSkillsHost() assembles the host-owned pieces:
|
|
5
|
+
* - the bounded SkillsService (scheduling, deadlines, deduplication, admission)
|
|
6
|
+
* - the IsolatedSkillRunner (isolated job execution)
|
|
7
|
+
* - the extension-facing SkillsBridge (installed process-wide for extensions)
|
|
8
|
+
*
|
|
9
|
+
* The factory registers capabilities; it starts no global watchers or
|
|
10
|
+
* background loops. SkillsService is owned by the embedding native host:
|
|
11
|
+
* the host calls close() on shutdown, which drains every job and clears the
|
|
12
|
+
* bridge.
|
|
13
|
+
*/
|
|
14
|
+
import { EventEmitter } from "node:events";
|
|
15
|
+
import { SkillsService } from "./skills-service.js";
|
|
16
|
+
import { IsolatedSkillRunner } from "./isolated-runner.js";
|
|
17
|
+
import { setSkillsBridge } from "./pi-bridge.js";
|
|
18
|
+
function kindFor(type) {
|
|
19
|
+
return type === "triggered" ? "gate" : type === "active" ? "active" : "passive";
|
|
20
|
+
}
|
|
21
|
+
export function createSkillsHost(deps) {
|
|
22
|
+
const runner = new IsolatedSkillRunner({
|
|
23
|
+
log: deps.log,
|
|
24
|
+
...(deps.modelRuntime ? { modelRuntime: deps.modelRuntime } : {}),
|
|
25
|
+
...(deps.model !== undefined ? { model: deps.model } : {}),
|
|
26
|
+
...(deps.cwd ? { cwd: deps.cwd } : {}),
|
|
27
|
+
...(deps.agentDir ? { agentDir: deps.agentDir } : {}),
|
|
28
|
+
...(deps.browserBridge ? { browserBridge: deps.browserBridge } : {}),
|
|
29
|
+
...(deps.sessionFactory ? { sessionFactory: deps.sessionFactory } : {}),
|
|
30
|
+
});
|
|
31
|
+
const service = new SkillsService(deps.limits);
|
|
32
|
+
const events = new EventEmitter();
|
|
33
|
+
let sessionBinding;
|
|
34
|
+
let attached = 0;
|
|
35
|
+
const submit = (spec) => {
|
|
36
|
+
const key = spec.key ?? `${spec.skill.key}:${spec.eventId}`;
|
|
37
|
+
const kind = spec.kind ?? kindFor(spec.skill.definition.type);
|
|
38
|
+
const promise = service.submit({
|
|
39
|
+
key,
|
|
40
|
+
kind,
|
|
41
|
+
timeoutMs: spec.timeoutMs ?? spec.skill.definition.execution.timeoutMs,
|
|
42
|
+
// The service settles "done" with the run body's return value, so
|
|
43
|
+
// return the raw report — never a pre-shaped outcome (double wrapping).
|
|
44
|
+
run: (signal) => runner.run(spec, signal).then((result) => {
|
|
45
|
+
if (!result.ok || !result.report)
|
|
46
|
+
throw new Error(result.error ?? "skill job failed");
|
|
47
|
+
return result.report;
|
|
48
|
+
}),
|
|
49
|
+
});
|
|
50
|
+
void promise.then((outcome) => events.emit("job-result", { key, outcome }));
|
|
51
|
+
return promise;
|
|
52
|
+
};
|
|
53
|
+
const bridge = {
|
|
54
|
+
runActive: (skillKey, instructions) => {
|
|
55
|
+
const skill = deps.registry?.get(skillKey);
|
|
56
|
+
if (!skill) {
|
|
57
|
+
return Promise.resolve({ status: "unavailable", reason: `unknown skill: ${skillKey}` });
|
|
58
|
+
}
|
|
59
|
+
const spec = {
|
|
60
|
+
skill,
|
|
61
|
+
context: JSON.stringify({ invocation: "active", instructions: instructions ?? "" }),
|
|
62
|
+
eventId: "active",
|
|
63
|
+
jobId: `active:${skillKey}`,
|
|
64
|
+
kind: "active",
|
|
65
|
+
grantedTools: [],
|
|
66
|
+
key: `${skillKey}:active`,
|
|
67
|
+
};
|
|
68
|
+
return submit(spec);
|
|
69
|
+
},
|
|
70
|
+
cancel: (key) => service.cancel(key),
|
|
71
|
+
get stats() {
|
|
72
|
+
return service.stats;
|
|
73
|
+
},
|
|
74
|
+
bindSession: (binding) => {
|
|
75
|
+
sessionBinding = binding;
|
|
76
|
+
},
|
|
77
|
+
unbindSession: () => {
|
|
78
|
+
sessionBinding = undefined;
|
|
79
|
+
},
|
|
80
|
+
currentBinding: () => sessionBinding,
|
|
81
|
+
sessionAttached: () => {
|
|
82
|
+
attached += 1;
|
|
83
|
+
},
|
|
84
|
+
sessionDetached: () => {
|
|
85
|
+
attached = Math.max(0, attached - 1);
|
|
86
|
+
},
|
|
87
|
+
onJobResult: (cb) => {
|
|
88
|
+
const handler = (data) => cb(data);
|
|
89
|
+
events.on("job-result", handler);
|
|
90
|
+
return () => events.off("job-result", handler);
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
const host = {
|
|
94
|
+
service,
|
|
95
|
+
runner,
|
|
96
|
+
bridge,
|
|
97
|
+
submit,
|
|
98
|
+
cancel: (key) => service.cancel(key),
|
|
99
|
+
close: async () => {
|
|
100
|
+
// Clear the bridge first so no new extension-side work can arrive
|
|
101
|
+
// while the service drains.
|
|
102
|
+
setSkillsBridge(undefined);
|
|
103
|
+
await service.close();
|
|
104
|
+
events.removeAllListeners();
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
setSkillsBridge(bridge);
|
|
108
|
+
return host;
|
|
109
|
+
}
|
|
110
|
+
//# sourceMappingURL=pi-integration.js.map
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { normalizeSkillHost, } from "@pi-browser/protocol";
|
|
3
|
+
/** Package-level scope match: the manifest owns hosts, the URL is the truth. */
|
|
4
|
+
function matchesPackage(manifest, context, url) {
|
|
5
|
+
if (manifest.application !== context.application)
|
|
6
|
+
return false;
|
|
7
|
+
const host = url.hostname.toLowerCase().replace(/\.$/, "");
|
|
8
|
+
const exact = manifest.hosts.includes(host);
|
|
9
|
+
const subdomain = manifest.subdomainHosts?.some((base) => host === base || host.endsWith(`.${base}`)) ?? false;
|
|
10
|
+
if (!exact && !subdomain)
|
|
11
|
+
return false;
|
|
12
|
+
return manifest.pathPrefixes === undefined || manifest.pathPrefixes.some((prefix) => url.pathname.startsWith(prefix));
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Compact app/host index over package manifests. The package IS its adapter:
|
|
16
|
+
* coverage of a subscription is derived from the manifest's own event
|
|
17
|
+
* definitions (validated at load), so a host-matched package's subscriptions
|
|
18
|
+
* are always covered — the only failure modes are revision and mode.
|
|
19
|
+
*/
|
|
20
|
+
function indexInto(buckets, skill) {
|
|
21
|
+
const manifest = skill.manifest;
|
|
22
|
+
for (const host of new Set([...manifest.hosts, ...(manifest.subdomainHosts ?? [])])) {
|
|
23
|
+
const key = `${manifest.application}:${normalizeSkillHost(host)}`;
|
|
24
|
+
const entries = buckets.get(key) ?? [];
|
|
25
|
+
if (entries.length >= 4096)
|
|
26
|
+
throw new Error("Host skill rule bucket exceeds limit");
|
|
27
|
+
entries.push(skill);
|
|
28
|
+
buckets.set(key, entries);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
export class SkillsPlanner {
|
|
32
|
+
buckets;
|
|
33
|
+
constructor(skills) {
|
|
34
|
+
const buckets = new Map();
|
|
35
|
+
for (const skill of structuredClone(skills))
|
|
36
|
+
indexInto(buckets, skill);
|
|
37
|
+
this.buckets = buckets;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Replace the index atomically from a fresh registry snapshot (catalog
|
|
41
|
+
* reload). The instance stays the same object, so per-client protocol
|
|
42
|
+
* surfaces keep compiling against the new index; already-compiled plans
|
|
43
|
+
* keep their stored rules until re-planned.
|
|
44
|
+
*/
|
|
45
|
+
reload(skills) {
|
|
46
|
+
const buckets = new Map();
|
|
47
|
+
for (const skill of structuredClone(skills))
|
|
48
|
+
indexInto(buckets, skill);
|
|
49
|
+
this.buckets = buckets;
|
|
50
|
+
}
|
|
51
|
+
candidates(context, url) {
|
|
52
|
+
const found = new Map();
|
|
53
|
+
const labels = url.hostname.toLowerCase().replace(/\.$/, "").split(".");
|
|
54
|
+
for (let i = 0; i < labels.length; i++) {
|
|
55
|
+
for (const skill of this.buckets.get(`${context.application}:${labels.slice(i).join(".")}`) ?? [])
|
|
56
|
+
found.set(skill.key, skill);
|
|
57
|
+
}
|
|
58
|
+
return [...found.values()].filter((skill) => matchesPackage(skill.manifest, context, url));
|
|
59
|
+
}
|
|
60
|
+
compile(context, grants, version, now = Date.now()) {
|
|
61
|
+
const url = new URL(context.url);
|
|
62
|
+
if (!["http:", "https:"].includes(url.protocol))
|
|
63
|
+
throw new Error("Unsupported document URL");
|
|
64
|
+
const rules = [];
|
|
65
|
+
const unavailable = [];
|
|
66
|
+
for (const skill of this.candidates(context, url)) {
|
|
67
|
+
const grant = grants.get(skill.key);
|
|
68
|
+
if (!grant || !eligibleGrant(skill, grant, context))
|
|
69
|
+
continue;
|
|
70
|
+
const result = compileRule(skill, grant);
|
|
71
|
+
if (typeof result === "string")
|
|
72
|
+
unavailable.push({ skillKey: skill.key, reason: result });
|
|
73
|
+
else
|
|
74
|
+
rules.push(result);
|
|
75
|
+
}
|
|
76
|
+
if (rules.length > 64 || rules.reduce((count, rule) => count + rule.subscriptions.length, 0) > 64) {
|
|
77
|
+
throw new Error("Document rule limit exceeded; no plan armed");
|
|
78
|
+
}
|
|
79
|
+
if (unavailable.length > 64)
|
|
80
|
+
throw new Error("Too many unavailable rules; no plan armed");
|
|
81
|
+
const identity = JSON.stringify({ context, version, rules, unavailable });
|
|
82
|
+
return { planId: createHash("sha256").update(identity).digest("hex"), planVersion: version,
|
|
83
|
+
documentGeneration: context.documentGeneration, expiresAt: now + 60_000, rules, unavailable };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function eligibleGrant(skill, grant, context) {
|
|
87
|
+
if (!grant.enabled || skill.definition.type === "active")
|
|
88
|
+
return false;
|
|
89
|
+
if (grant.accounts && (!context.accountId || !grant.accounts.includes(context.accountId)))
|
|
90
|
+
return false;
|
|
91
|
+
return skill.definition.type !== "passive" || grant.learningEnabled === true;
|
|
92
|
+
}
|
|
93
|
+
function compileRule(skill, grant) {
|
|
94
|
+
if (grant.revision !== skill.revision)
|
|
95
|
+
return "Package changed; review permissions";
|
|
96
|
+
const definition = skill.definition;
|
|
97
|
+
const capabilities = definition.capabilities.filter((capability) => grant.capabilities.includes(capability));
|
|
98
|
+
if (!capabilities.includes("context.read"))
|
|
99
|
+
return "Context access is not granted";
|
|
100
|
+
const subscriptions = definition.subscriptions ?? definition.observations ?? [];
|
|
101
|
+
const mode = grant.mode ?? "advisory";
|
|
102
|
+
if (mode === "review-before-submit" && !subscriptions.some((sub) => skill.manifest.events[sub.event]?.kind === "gate")) {
|
|
103
|
+
return "Review before submit requires a gate event subscription";
|
|
104
|
+
}
|
|
105
|
+
const events = {};
|
|
106
|
+
for (const sub of subscriptions) {
|
|
107
|
+
const event = skill.manifest.events[sub.event];
|
|
108
|
+
if (!event)
|
|
109
|
+
return `Package event is missing: ${sub.event}`;
|
|
110
|
+
events[sub.event] = structuredClone(event);
|
|
111
|
+
}
|
|
112
|
+
// Runtime placement: JS-dialect targets must execute where string codegen
|
|
113
|
+
// is legal, and the gate consult is synchronous — so ANY js target in the
|
|
114
|
+
// rule's events moves the WHOLE rule to the main world. Manifest-derived,
|
|
115
|
+
// static, auditable.
|
|
116
|
+
const usedTargets = new Set();
|
|
117
|
+
for (const event of Object.values(events)) {
|
|
118
|
+
for (const matcher of [...(event.sequence ?? []), ...(event.alternatives ?? []).flat()])
|
|
119
|
+
usedTargets.add(matcher.target);
|
|
120
|
+
for (const field of Object.values(event.payload ?? {}))
|
|
121
|
+
usedTargets.add(field.from);
|
|
122
|
+
}
|
|
123
|
+
const world = [...usedTargets].some((name) => skill.manifest.targets[name]?.kind === "js") ? "main" : "isolated";
|
|
124
|
+
return { skillKey: skill.key, skillRevision: skill.revision, packageId: skill.packageId, world,
|
|
125
|
+
targets: structuredClone(skill.manifest.targets), events,
|
|
126
|
+
subscriptions: structuredClone(subscriptions), mode, capabilities };
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=planner.js.map
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { open, realpath, readdir } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { parseSkillPackage } from "@pi-browser/protocol";
|
|
5
|
+
const MAX_MANIFEST_BYTES = 256 * 1024;
|
|
6
|
+
const MAX_INSTRUCTION_BYTES = 32 * 1024;
|
|
7
|
+
const MAX_REGISTRY_BYTES = 32 * 1024 * 1024;
|
|
8
|
+
const MAX_PACKAGES = 4096;
|
|
9
|
+
/** Resolve real paths before reading, including symlinks in intermediate directories. */
|
|
10
|
+
async function packageFile(root, relative, maxBytes) {
|
|
11
|
+
const file = await realpath(path.resolve(root, relative));
|
|
12
|
+
const within = path.relative(root, file);
|
|
13
|
+
if (within.startsWith(`..${path.sep}`) || within === ".." || path.isAbsolute(within))
|
|
14
|
+
throw new Error("Package path escapes root");
|
|
15
|
+
const handle = await open(file, "r");
|
|
16
|
+
try {
|
|
17
|
+
const stat = await handle.stat();
|
|
18
|
+
if (!stat.isFile() || stat.size > maxBytes)
|
|
19
|
+
throw new Error("Package file exceeds limit or is not a file");
|
|
20
|
+
// Read a bounded buffer even if the file grows after stat.
|
|
21
|
+
const bytes = Buffer.alloc(maxBytes + 1);
|
|
22
|
+
let offset = 0;
|
|
23
|
+
while (offset < bytes.length) {
|
|
24
|
+
const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, null);
|
|
25
|
+
if (!bytesRead)
|
|
26
|
+
break;
|
|
27
|
+
offset += bytesRead;
|
|
28
|
+
}
|
|
29
|
+
if (offset > maxBytes)
|
|
30
|
+
throw new Error("Package file exceeds limit");
|
|
31
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, offset));
|
|
32
|
+
}
|
|
33
|
+
finally {
|
|
34
|
+
await handle.close();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Host-owned registry. Reload publishes all definitions together or preserves
|
|
39
|
+
* the old snapshot. A skill's revision covers its whole package manifest
|
|
40
|
+
* (shared targets/events) plus its own instructions — any site-definition
|
|
41
|
+
* change re-revisions every skill in the package.
|
|
42
|
+
*/
|
|
43
|
+
export class SkillsRegistry {
|
|
44
|
+
entries = new Map();
|
|
45
|
+
generation = 0;
|
|
46
|
+
reloadTail = Promise.resolve();
|
|
47
|
+
get version() { return this.generation; }
|
|
48
|
+
get size() { return this.entries.size; }
|
|
49
|
+
snapshot() { return structuredClone([...this.entries.values()]); }
|
|
50
|
+
get(key) {
|
|
51
|
+
const skill = this.entries.get(key);
|
|
52
|
+
return skill && structuredClone(skill);
|
|
53
|
+
}
|
|
54
|
+
/** Current revision for a key without cloning the definition (grant rebinding). */
|
|
55
|
+
revisionOf(key) { return this.entries.get(key)?.revision ?? ""; }
|
|
56
|
+
/** Explicit external paths are allowed; nested instruction paths remain confined to each root. */
|
|
57
|
+
reload(packageRoots) {
|
|
58
|
+
const roots = [...packageRoots];
|
|
59
|
+
const next = this.reloadTail.then(() => this.load(roots));
|
|
60
|
+
// Only the internal queue recovers; the returned promise still rejects for the caller.
|
|
61
|
+
this.reloadTail = next.catch(() => { });
|
|
62
|
+
return next;
|
|
63
|
+
}
|
|
64
|
+
async load(packageRoots) {
|
|
65
|
+
if (packageRoots.length > MAX_PACKAGES)
|
|
66
|
+
throw new Error("Too many skill packages");
|
|
67
|
+
const next = new Map();
|
|
68
|
+
const packageIds = new Set();
|
|
69
|
+
let totalBytes = 0;
|
|
70
|
+
for (const packageRoot of packageRoots) {
|
|
71
|
+
const root = await realpath(packageRoot);
|
|
72
|
+
const raw = await packageFile(root, "activation.json", MAX_MANIFEST_BYTES);
|
|
73
|
+
const manifest = parseSkillPackage(JSON.parse(raw));
|
|
74
|
+
if (packageIds.has(manifest.packageId))
|
|
75
|
+
throw new Error(`Duplicate package ID: ${manifest.packageId}`);
|
|
76
|
+
packageIds.add(manifest.packageId);
|
|
77
|
+
totalBytes += Buffer.byteLength(raw);
|
|
78
|
+
const manifestJson = JSON.stringify(manifest);
|
|
79
|
+
for (const definition of manifest.skills) {
|
|
80
|
+
const instructions = await packageFile(root, definition.instructions, MAX_INSTRUCTION_BYTES);
|
|
81
|
+
if (!instructions.trim())
|
|
82
|
+
throw new Error("Skill instructions are empty");
|
|
83
|
+
totalBytes += Buffer.byteLength(instructions);
|
|
84
|
+
if (totalBytes > MAX_REGISTRY_BYTES || next.size >= 16_384)
|
|
85
|
+
throw new Error("Skill registry exceeds limit");
|
|
86
|
+
const key = `${manifest.packageId}/${definition.id}`;
|
|
87
|
+
const revision = createHash("sha256").update(manifestJson).update("\0").update(instructions).digest("hex");
|
|
88
|
+
next.set(key, { key, revision, packageId: manifest.packageId, definition, instructions, manifest });
|
|
89
|
+
}
|
|
90
|
+
if (totalBytes > MAX_REGISTRY_BYTES)
|
|
91
|
+
throw new Error("Skill registry exceeds limit");
|
|
92
|
+
}
|
|
93
|
+
this.entries = next;
|
|
94
|
+
this.generation += 1;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/** Discover direct package directories without loading package.json or executing entry points. */
|
|
98
|
+
export async function discoverSkillPackages(packagesRoot) {
|
|
99
|
+
const entries = await readdir(packagesRoot, { withFileTypes: true });
|
|
100
|
+
if (entries.length > MAX_PACKAGES)
|
|
101
|
+
throw new Error("Too many package directory entries");
|
|
102
|
+
return entries.filter((entry) => entry.isDirectory()).map((entry) => path.join(packagesRoot, entry.name)).sort();
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=registry.js.map
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skills protocol surface for the native host (skills-runtime-design.md
|
|
3
|
+
* §2, §7, §13 "addon-coordinator" host half).
|
|
4
|
+
*
|
|
5
|
+
* Application messages ride the existing ACP transport under the negotiated
|
|
6
|
+
* x-pi-browser/skills_* namespace; standard prompt traffic stays separate.
|
|
7
|
+
* One SkillsProtocol instance wraps ONE client connection (one addon
|
|
8
|
+
* connection = one source of verified identity) and shares the broker's
|
|
9
|
+
* single SkillsHost across all clients.
|
|
10
|
+
*
|
|
11
|
+
* Flow (all messages carry explicit request IDs):
|
|
12
|
+
* client → host skills_plan compile a page plan for a verified source
|
|
13
|
+
* client → host skills_event submit a verified event (ack: accepted/…)
|
|
14
|
+
* host → client skills_context resolve contextRef (bounded snapshot)
|
|
15
|
+
* host → client skills_result deliver a job outcome (acked)
|
|
16
|
+
* client → host skills_cancel / skills_status
|
|
17
|
+
*
|
|
18
|
+
* Identity rules (design §7): the coordinator's source identity is
|
|
19
|
+
* authoritative — a page payload cannot claim another tab, frame, document
|
|
20
|
+
* generation, epoch, account, or plan. Events naming an unknown or stale
|
|
21
|
+
* plan are rejected, never guessed. Runtime failures are separate from
|
|
22
|
+
* semantic results: an unavailable outcome never clears a required review.
|
|
23
|
+
*/
|
|
24
|
+
import { X_PI_BROWSER, parseSkillsCancelParams, parseSkillsContextResult, parseSkillsEventParams, parseSkillsPlanParams, PI_BROWSER_ERROR, } from "@pi-browser/protocol";
|
|
25
|
+
import { skillEventName } from "@pi-browser/protocol";
|
|
26
|
+
const MAX_PLANS_PER_CLIENT = 64;
|
|
27
|
+
const MAX_JOBS_PER_CLIENT = 256;
|
|
28
|
+
function planKey(source) {
|
|
29
|
+
return source.tabId !== undefined && source.frameId !== undefined
|
|
30
|
+
? `doc:${source.tabId}:${source.frameId}:${source.documentGeneration ?? ""}`
|
|
31
|
+
: `mail:${source.accountId ?? "default"}`;
|
|
32
|
+
}
|
|
33
|
+
function handlePlan(ctx, raw) {
|
|
34
|
+
const { deps, state } = ctx;
|
|
35
|
+
const params = parseSkillsPlanParams(raw);
|
|
36
|
+
const key = planKey(params.source);
|
|
37
|
+
const version = (state.planVersions.get(key) ?? 0) + 1;
|
|
38
|
+
state.planVersions.set(key, version);
|
|
39
|
+
let compiled;
|
|
40
|
+
try {
|
|
41
|
+
compiled = deps.planner.compile({
|
|
42
|
+
application: params.source.application,
|
|
43
|
+
url: params.url,
|
|
44
|
+
documentGeneration: params.source.documentGeneration ?? "mail",
|
|
45
|
+
...(params.source.accountId ? { accountId: params.source.accountId } : {}),
|
|
46
|
+
}, deps.grants(), version);
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
deps.log.warn(`skills plan failed for ${key}: ${err instanceof Error ? err.message : String(err)}`);
|
|
50
|
+
deps.onLifecycle?.({ type: "plan", doc: key, status: "unavailable", rules: 0, unavailable: [] });
|
|
51
|
+
return { status: "unavailable", reason: err instanceof Error ? err.message : String(err) };
|
|
52
|
+
}
|
|
53
|
+
if (state.plans.size >= MAX_PLANS_PER_CLIENT && !state.plans.has(key))
|
|
54
|
+
state.plans.delete(state.plans.keys().next().value);
|
|
55
|
+
state.plans.set(key, { planId: compiled.planId, planVersion: compiled.planVersion, expiresAt: compiled.expiresAt, rules: compiled.rules });
|
|
56
|
+
deps.onLifecycle?.({
|
|
57
|
+
type: "plan", doc: key, status: "ok",
|
|
58
|
+
rules: compiled.rules.length, unavailable: compiled.unavailable,
|
|
59
|
+
planVersion: compiled.planVersion, planId: compiled.planId,
|
|
60
|
+
});
|
|
61
|
+
return { status: "ok", plan: compiled };
|
|
62
|
+
}
|
|
63
|
+
async function handleEvent(ctx, raw) {
|
|
64
|
+
const { deps, state } = ctx;
|
|
65
|
+
const params = parseSkillsEventParams(raw);
|
|
66
|
+
const evt = params.event;
|
|
67
|
+
const key = planKey(evt.source);
|
|
68
|
+
const stored = state.plans.get(key);
|
|
69
|
+
if (!stored || stored.planVersion !== evt.planVersion) {
|
|
70
|
+
return { status: "stale-plan", reason: "no plan for this document generation or version mismatch; re-plan" };
|
|
71
|
+
}
|
|
72
|
+
if (Date.now() > stored.expiresAt) {
|
|
73
|
+
return { status: "stale-plan", reason: "plan expired; re-plan" };
|
|
74
|
+
}
|
|
75
|
+
// Events are package-scoped: `packageId:local`. A rule matches when the
|
|
76
|
+
// event's package is the rule's package and a subscription names it.
|
|
77
|
+
const rules = stored.rules.filter((rule) => rule.subscriptions.some((sub) => evt.event === skillEventName(rule.packageId, sub.event)));
|
|
78
|
+
if (rules.length === 0) {
|
|
79
|
+
deps.onLifecycle?.({ type: "event", eventId: evt.eventId, event: evt.event, status: "no-match" });
|
|
80
|
+
return { status: "no-match" };
|
|
81
|
+
}
|
|
82
|
+
// Resolve the context snapshot through the coordinator's capability
|
|
83
|
+
// (design §7: contextRef resolves ONLY here, privacy by request).
|
|
84
|
+
// Field names are package-defined payload fields; the snapshot store
|
|
85
|
+
// answers only the fields the matching rules requested.
|
|
86
|
+
const resolved = await resolveEventContext(ctx, rules, evt);
|
|
87
|
+
if (resolved.payload === undefined)
|
|
88
|
+
return { status: "unavailable", reason: resolved.reason ?? "context unavailable" };
|
|
89
|
+
const jobs = submitRuleJobs(ctx, evt, rules, resolved.payload);
|
|
90
|
+
const result = jobs.length ? { status: "accepted", jobs } : { status: "unavailable", reason: "no usable rules" };
|
|
91
|
+
deps.onLifecycle?.({
|
|
92
|
+
type: "event", eventId: evt.eventId, event: evt.event, status: result.status,
|
|
93
|
+
...(result.status === "accepted" ? { jobs: result.jobs.length } : { reason: result.reason }),
|
|
94
|
+
});
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
async function resolveEventContext(ctx, rules, evt) {
|
|
98
|
+
const { deps } = ctx;
|
|
99
|
+
const fields = [...new Set(rules.flatMap((rule) => {
|
|
100
|
+
const skill = deps.registry.get(rule.skillKey);
|
|
101
|
+
return skill ? [...skill.definition.context.required, ...skill.definition.context.optional] : [];
|
|
102
|
+
}))];
|
|
103
|
+
try {
|
|
104
|
+
const request = {
|
|
105
|
+
contextRef: evt.contextRef, interactionId: evt.interactionId,
|
|
106
|
+
planVersion: evt.planVersion, fields, maxBytes: ctx.maxContextBytes,
|
|
107
|
+
};
|
|
108
|
+
const response = await deps.endpoint.request(X_PI_BROWSER.skills_context, request, ctx.contextTimeoutMs);
|
|
109
|
+
const parsed = parseSkillsContextResult(response, ctx.maxContextBytes);
|
|
110
|
+
return { payload: JSON.stringify(parsed.context) };
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
114
|
+
deps.log.warn(`skills context unavailable for ${evt.eventId}: ${reason}`);
|
|
115
|
+
return { reason: `context unavailable: ${reason}` };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function submitRuleJobs(ctx, evt, rules, contextPayload) {
|
|
119
|
+
const { deps, state } = ctx;
|
|
120
|
+
const jobs = [];
|
|
121
|
+
for (const rule of rules) {
|
|
122
|
+
const skill = deps.registry.get(rule.skillKey);
|
|
123
|
+
if (!skill) {
|
|
124
|
+
deps.log.warn(`skills rule names unknown skill ${rule.skillKey}; skipped`);
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
const jobId = `job:${evt.eventId}:${rule.skillKey}`;
|
|
128
|
+
const dedupeKey = `${rule.skillKey}:${evt.interactionId}:${evt.draftRevision ?? 0}`;
|
|
129
|
+
const local = evt.event.slice(rule.packageId.length + 1);
|
|
130
|
+
const kind = rule.events[local]?.kind === "gate" ? "gate" : "speculative";
|
|
131
|
+
void deps.host
|
|
132
|
+
.submit({
|
|
133
|
+
skill,
|
|
134
|
+
context: contextPayload,
|
|
135
|
+
eventId: evt.eventId,
|
|
136
|
+
jobId,
|
|
137
|
+
key: dedupeKey,
|
|
138
|
+
kind,
|
|
139
|
+
grantedTools: [],
|
|
140
|
+
})
|
|
141
|
+
.then((outcome) => ctx.deliverResult(outcome, rule, jobId, evt.eventId));
|
|
142
|
+
if (state.jobKeys.size >= MAX_JOBS_PER_CLIENT)
|
|
143
|
+
state.jobKeys.delete(state.jobKeys.values().next().value);
|
|
144
|
+
state.jobKeys.add(dedupeKey);
|
|
145
|
+
jobs.push({ jobId, skillKey: rule.skillKey, key: dedupeKey });
|
|
146
|
+
}
|
|
147
|
+
return jobs;
|
|
148
|
+
}
|
|
149
|
+
function handleCancel(ctx, raw) {
|
|
150
|
+
const { deps, state } = ctx;
|
|
151
|
+
const params = parseSkillsCancelParams(raw);
|
|
152
|
+
let cancelled = 0;
|
|
153
|
+
for (const key of [...state.jobKeys]) {
|
|
154
|
+
if (key.includes(`:${params.interactionId}:`)) {
|
|
155
|
+
cancelled += deps.host.cancel(key);
|
|
156
|
+
state.jobKeys.delete(key);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return { cancelled };
|
|
160
|
+
}
|
|
161
|
+
function handleStatus(ctx) {
|
|
162
|
+
const { deps, state } = ctx;
|
|
163
|
+
const stats = deps.host.service.stats;
|
|
164
|
+
return {
|
|
165
|
+
available: !stats.closed,
|
|
166
|
+
stats: {
|
|
167
|
+
running: stats.running,
|
|
168
|
+
queued: stats.queued,
|
|
169
|
+
replacements: stats.replacements,
|
|
170
|
+
closed: stats.closed,
|
|
171
|
+
outcomes: { ...stats.outcomes },
|
|
172
|
+
},
|
|
173
|
+
plans: state.plans.size,
|
|
174
|
+
armedRules: [...state.plans.values()].reduce((sum, p) => sum + p.rules.length, 0),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function deliverResult(ctx, outcome, rule, jobId, eventId) {
|
|
178
|
+
const params = outcome.status === "done" && outcome.value
|
|
179
|
+
? (() => {
|
|
180
|
+
const report = outcome.value;
|
|
181
|
+
return {
|
|
182
|
+
jobId, eventId, skillKey: rule.skillKey, skillRevision: rule.skillRevision, status: "done",
|
|
183
|
+
decision: report.decision,
|
|
184
|
+
...(report.explanation !== undefined ? { explanation: report.explanation } : {}),
|
|
185
|
+
...(report.replacementText !== undefined ? { replacementText: report.replacementText } : {}),
|
|
186
|
+
};
|
|
187
|
+
})()
|
|
188
|
+
: {
|
|
189
|
+
jobId, eventId, skillKey: rule.skillKey, skillRevision: rule.skillRevision, status: "unavailable",
|
|
190
|
+
reason: outcome.reason ?? outcome.error?.message ?? outcome.status,
|
|
191
|
+
};
|
|
192
|
+
ctx.deps.onLifecycle?.({
|
|
193
|
+
type: "result", jobId, skillKey: rule.skillKey, status: params.status,
|
|
194
|
+
...(params.status === "done" ? { decision: params.decision } : { reason: params.reason }),
|
|
195
|
+
});
|
|
196
|
+
// Delivery is best-effort and acked: a client that is gone (disconnect,
|
|
197
|
+
// navigation) must not wedge the already-settled job.
|
|
198
|
+
ctx.deps.endpoint
|
|
199
|
+
.request(X_PI_BROWSER.skills_result, params, ctx.contextTimeoutMs)
|
|
200
|
+
.catch((err) => ctx.deps.log.warn(`skills result delivery failed for ${jobId}: ${err instanceof Error ? err.message : String(err)}`));
|
|
201
|
+
}
|
|
202
|
+
export function createSkillsProtocol(deps) {
|
|
203
|
+
const state = { plans: new Map(), planVersions: new Map(), jobKeys: new Set() };
|
|
204
|
+
const ctx = {
|
|
205
|
+
deps,
|
|
206
|
+
state,
|
|
207
|
+
maxContextBytes: deps.maxContextBytes ?? 32_768,
|
|
208
|
+
contextTimeoutMs: deps.contextTimeoutMs ?? 5_000,
|
|
209
|
+
deliverResult: (outcome, rule, jobId, eventId) => deliverResult(ctx, outcome, rule, jobId, eventId),
|
|
210
|
+
};
|
|
211
|
+
return {
|
|
212
|
+
handle(method, params, respond, respondError) {
|
|
213
|
+
const fail = (err) => {
|
|
214
|
+
const message = `skills: ${err instanceof Error ? err.message : JSON.stringify(err)}`;
|
|
215
|
+
deps.log.warn(`skills protocol error (${method}): ${message}`);
|
|
216
|
+
respondError(PI_BROWSER_ERROR.INTERNAL, message);
|
|
217
|
+
};
|
|
218
|
+
try {
|
|
219
|
+
switch (method) {
|
|
220
|
+
case X_PI_BROWSER.skills_plan:
|
|
221
|
+
respond(handlePlan(ctx, params));
|
|
222
|
+
return true;
|
|
223
|
+
case X_PI_BROWSER.skills_event:
|
|
224
|
+
void handleEvent(ctx, params).then(respond, fail);
|
|
225
|
+
return true;
|
|
226
|
+
case X_PI_BROWSER.skills_cancel:
|
|
227
|
+
respond(handleCancel(ctx, params));
|
|
228
|
+
return true;
|
|
229
|
+
case X_PI_BROWSER.skills_status:
|
|
230
|
+
respond(handleStatus(ctx));
|
|
231
|
+
return true;
|
|
232
|
+
default:
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
fail(err);
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
dispose() {
|
|
242
|
+
for (const key of state.jobKeys)
|
|
243
|
+
deps.host.cancel(key);
|
|
244
|
+
state.jobKeys.clear();
|
|
245
|
+
state.plans.clear();
|
|
246
|
+
state.planVersions.clear();
|
|
247
|
+
},
|
|
248
|
+
plans() {
|
|
249
|
+
return { count: state.plans.size, armedRules: [...state.plans.values()].reduce((sum, p) => sum + p.rules.length, 0) };
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
//# sourceMappingURL=skills-protocol.js.map
|