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,99 @@
|
|
|
1
|
+
import { getSkillsBridge } from "./pi-bridge.js";
|
|
2
|
+
export const SKILL_AUDIT_TYPE = "pi-browser:skill";
|
|
3
|
+
export const SKILL_INSTRUCTIONS_TYPE = "pi-browser:skill-instructions";
|
|
4
|
+
export const SKILL_JOB_RESULT_CHANNEL = "pi-browser:skill-job-result";
|
|
5
|
+
async function handleSkillsCommand(bridge, args, ctx) {
|
|
6
|
+
const [command = "status", ...rest] = (args ?? "").trim().split(/\s+/).filter(Boolean);
|
|
7
|
+
if (command === "status") {
|
|
8
|
+
const s = bridge.stats;
|
|
9
|
+
ctx.ui.notify(`skills: running=${s.running} queued=${s.queued} closed=${s.closed} outcomes=${JSON.stringify(s.outcomes)}`, "info");
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
if (command === "run") {
|
|
13
|
+
const skillKey = rest[0];
|
|
14
|
+
if (!skillKey) {
|
|
15
|
+
ctx.ui.notify("usage: /pi-skills run <skillKey> [instructions]", "warning");
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
const instructions = rest.slice(1).join(" ") || undefined;
|
|
19
|
+
ctx.ui.notify(`starting skill job: ${skillKey}`, "info");
|
|
20
|
+
const outcome = await bridge.runActive(skillKey, instructions);
|
|
21
|
+
if (outcome.status === "done" && outcome.value) {
|
|
22
|
+
const report = outcome.value;
|
|
23
|
+
ctx.ui.notify(`skill ${skillKey}: ${report.decision}${report.explanation ? ` — ${report.explanation}` : ""}`, "info");
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
ctx.ui.notify(`skill job ${skillKey}: ${outcome.status}${outcome.reason ? ` (${outcome.reason})` : ""}${outcome.error ? ` (${outcome.error.message})` : ""}`, outcome.status === "failed" ? "error" : "warning");
|
|
27
|
+
}
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (command === "cancel") {
|
|
31
|
+
const key = rest[0];
|
|
32
|
+
if (!key) {
|
|
33
|
+
ctx.ui.notify("usage: /pi-skills cancel <key>", "warning");
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const cancelled = bridge.cancel(key);
|
|
37
|
+
ctx.ui.notify(cancelled > 0 ? `cancelled ${cancelled} job(s) for ${key}` : `no pending job for ${key}`, "info");
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
ctx.ui.notify("usage: /pi-skills [run <skillKey> [instructions] | status | cancel <key>]", "warning");
|
|
41
|
+
}
|
|
42
|
+
export function createSkillsExtensionFactory() {
|
|
43
|
+
return function piSkillsExtension(pi) {
|
|
44
|
+
// The host installs the bridge once per process, before any session
|
|
45
|
+
// spawns, so capturing it at load time is stable for the session's life.
|
|
46
|
+
const bridge = getSkillsBridge();
|
|
47
|
+
if (!bridge)
|
|
48
|
+
return; // plain pi session — no host, nothing to register
|
|
49
|
+
// Idempotent attach/detach: a session change or reload detaches only its
|
|
50
|
+
// binding; host shutdown clears everything via close().
|
|
51
|
+
pi.on("session_start", () => {
|
|
52
|
+
bridge.sessionAttached();
|
|
53
|
+
});
|
|
54
|
+
pi.on("session_shutdown", () => {
|
|
55
|
+
bridge.sessionDetached();
|
|
56
|
+
});
|
|
57
|
+
// Only explicitly selected skill paths — never ambient discovery output.
|
|
58
|
+
pi.on("resources_discover", () => {
|
|
59
|
+
const skillPaths = bridge.currentBinding()?.skillPaths ?? [];
|
|
60
|
+
return skillPaths.length > 0 ? { skillPaths } : {};
|
|
61
|
+
});
|
|
62
|
+
// Inject selected task instructions as a custom message into the turn.
|
|
63
|
+
pi.on("before_agent_start", () => {
|
|
64
|
+
const instructions = bridge.currentBinding()?.instructions;
|
|
65
|
+
if (!instructions)
|
|
66
|
+
return;
|
|
67
|
+
return {
|
|
68
|
+
message: {
|
|
69
|
+
customType: SKILL_INSTRUCTIONS_TYPE,
|
|
70
|
+
content: instructions.instructions,
|
|
71
|
+
display: true,
|
|
72
|
+
details: { skillKey: instructions.skillKey },
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
});
|
|
76
|
+
// Gate agent tool calls when the host scoped this session's tools.
|
|
77
|
+
pi.on("tool_call", (event) => {
|
|
78
|
+
const allowed = bridge.currentBinding()?.allowedTools;
|
|
79
|
+
if (!allowed)
|
|
80
|
+
return;
|
|
81
|
+
if (allowed.includes(event.toolName))
|
|
82
|
+
return;
|
|
83
|
+
return { block: true, reason: `tool "${event.toolName}" is not permitted in the current skill session` };
|
|
84
|
+
});
|
|
85
|
+
// Session-local audit entries (outside model context) + local events.
|
|
86
|
+
const audit = (data) => {
|
|
87
|
+
pi.appendEntry(SKILL_AUDIT_TYPE, data);
|
|
88
|
+
};
|
|
89
|
+
bridge.onJobResult(({ key, outcome }) => {
|
|
90
|
+
audit({ key, status: outcome.status, ...(outcome.reason ? { reason: outcome.reason } : {}) });
|
|
91
|
+
pi.events.emit(SKILL_JOB_RESULT_CHANNEL, { key, outcome });
|
|
92
|
+
});
|
|
93
|
+
pi.registerCommand("pi-skills", {
|
|
94
|
+
description: "Run an Active skill job: /pi-skills run <skillKey> [instructions] | status | cancel <key>",
|
|
95
|
+
handler: (args, ctx) => handleSkillsCommand(bridge, args, ctx),
|
|
96
|
+
});
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=extension.js.map
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Real-user skill grants (skills-runtime-design.md §12 seam).
|
|
3
|
+
*
|
|
4
|
+
* The mock backend gets grants from PI_BROWSER_SKILLS_CONFIG (test seam,
|
|
5
|
+
* main.ts). Real users get grants from ONE file in the data root:
|
|
6
|
+
*
|
|
7
|
+
* <PI_BROWSER_DATA_ROOT || ~/.pi/browser>/skills-grants.json
|
|
8
|
+
*
|
|
9
|
+
* {
|
|
10
|
+
* "grants": [{
|
|
11
|
+
* "skillKey": "tone-rewrite/tone",
|
|
12
|
+
* "revision": "<registry sha256>",
|
|
13
|
+
* "capabilities": ["context.read", "suggestion.present", "draft.replace-on-accept"],
|
|
14
|
+
* "mode": "advisory" // optional: advisory | review-before-submit
|
|
15
|
+
* }]
|
|
16
|
+
* }
|
|
17
|
+
*
|
|
18
|
+
* Real grants are revision-bound BY DESIGN (no "*" rebinding, unlike the
|
|
19
|
+
* mock seam): a package change re-revisions its skills and the grant stops
|
|
20
|
+
* matching until the file is updated.
|
|
21
|
+
*
|
|
22
|
+
* The loader is a plan-time GETTER (the createClientSkillsProtocol seam):
|
|
23
|
+
* the file is re-read on every plan compile, so granting or re-granting a
|
|
24
|
+
* skill needs no host restart — the next navigation re-plans from the
|
|
25
|
+
* fresh file. Fail-closed: a missing file means "nothing granted"; an
|
|
26
|
+
* invalid file is warned once and treated as empty. A grant file can never
|
|
27
|
+
* take down plan compilation.
|
|
28
|
+
*/
|
|
29
|
+
import { readFileSync, statSync } from "node:fs";
|
|
30
|
+
import { homedir } from "node:os";
|
|
31
|
+
import path from "node:path";
|
|
32
|
+
import { SKILL_CAPABILITIES } from "@pi-browser/protocol";
|
|
33
|
+
const MAX_GRANTS_FILE_BYTES = 64 * 1024;
|
|
34
|
+
const MAX_GRANTS = 256;
|
|
35
|
+
export function skillsGrantsPath() {
|
|
36
|
+
const dataRoot = process.env.PI_BROWSER_DATA_ROOT?.trim() || path.join(homedir(), ".pi", "browser");
|
|
37
|
+
return path.join(dataRoot, "skills-grants.json");
|
|
38
|
+
}
|
|
39
|
+
function parseCapabilities(value) {
|
|
40
|
+
if (!Array.isArray(value) || value.length > SKILL_CAPABILITIES.length)
|
|
41
|
+
throw new Error("Invalid capabilities");
|
|
42
|
+
const result = [];
|
|
43
|
+
for (const item of value) {
|
|
44
|
+
if (typeof item !== "string" || !SKILL_CAPABILITIES.includes(item))
|
|
45
|
+
throw new Error("Unknown capability");
|
|
46
|
+
if (!result.includes(item))
|
|
47
|
+
result.push(item);
|
|
48
|
+
}
|
|
49
|
+
if (!result.length)
|
|
50
|
+
throw new Error("Grant has no capabilities");
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
function parseGrant(value) {
|
|
54
|
+
const entry = value;
|
|
55
|
+
for (const key of Object.keys(entry)) {
|
|
56
|
+
if (!["skillKey", "revision", "capabilities", "mode", "accounts", "learningEnabled"].includes(key))
|
|
57
|
+
throw new Error(`Unknown grant field: ${key}`);
|
|
58
|
+
}
|
|
59
|
+
const revision = entry.revision;
|
|
60
|
+
if (typeof revision !== "string" || !/^[a-f0-9]{64}$/.test(revision))
|
|
61
|
+
throw new Error("Grant revision must be a 64-char sha256 (real grants are revision-bound)");
|
|
62
|
+
const grant = { enabled: true, revision, capabilities: parseCapabilities(entry.capabilities) };
|
|
63
|
+
if (entry.mode !== undefined) {
|
|
64
|
+
if (entry.mode !== "advisory" && entry.mode !== "review-before-submit")
|
|
65
|
+
throw new Error("Invalid mode");
|
|
66
|
+
grant.mode = entry.mode;
|
|
67
|
+
}
|
|
68
|
+
if (entry.accounts !== undefined) {
|
|
69
|
+
if (!Array.isArray(entry.accounts) || entry.accounts.length > 64 || !entry.accounts.every((a) => typeof a === "string"))
|
|
70
|
+
throw new Error("Invalid accounts");
|
|
71
|
+
grant.accounts = entry.accounts;
|
|
72
|
+
}
|
|
73
|
+
if (entry.learningEnabled !== undefined) {
|
|
74
|
+
if (typeof entry.learningEnabled !== "boolean")
|
|
75
|
+
throw new Error("Invalid learningEnabled");
|
|
76
|
+
grant.learningEnabled = entry.learningEnabled;
|
|
77
|
+
}
|
|
78
|
+
return grant;
|
|
79
|
+
}
|
|
80
|
+
function parseFile(raw) {
|
|
81
|
+
let value;
|
|
82
|
+
try {
|
|
83
|
+
value = JSON.parse(raw);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
throw new Error("Not valid JSON");
|
|
87
|
+
}
|
|
88
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
89
|
+
throw new Error("Root must be an object");
|
|
90
|
+
const entry = value;
|
|
91
|
+
for (const key of Object.keys(entry)) {
|
|
92
|
+
if (key !== "grants")
|
|
93
|
+
throw new Error(`Unknown field: ${key}`);
|
|
94
|
+
}
|
|
95
|
+
if (!Array.isArray(entry.grants) || entry.grants.length > MAX_GRANTS)
|
|
96
|
+
throw new Error("Invalid grants array");
|
|
97
|
+
const map = new Map();
|
|
98
|
+
for (const value of entry.grants) {
|
|
99
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
100
|
+
throw new Error("Grant must be an object");
|
|
101
|
+
const skillKey = value.skillKey;
|
|
102
|
+
if (typeof skillKey !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skillKey))
|
|
103
|
+
throw new Error("Invalid skillKey");
|
|
104
|
+
map.set(skillKey, parseGrant(value));
|
|
105
|
+
}
|
|
106
|
+
return map;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Plan-time grant source: re-reads the grants file on every call. Synchronous
|
|
110
|
+
* and bounded (≤ 64 KiB) — plan compiles are rare (navigation / 60 s plan
|
|
111
|
+
* expiry), so the read is negligible; invalid state degrades to "nothing
|
|
112
|
+
* granted" and never throws out of the getter.
|
|
113
|
+
*/
|
|
114
|
+
export function loadSkillsGrantFile(log) {
|
|
115
|
+
let lastSignature = "";
|
|
116
|
+
let lastMap = new Map();
|
|
117
|
+
let lastWarning = "";
|
|
118
|
+
return () => {
|
|
119
|
+
try {
|
|
120
|
+
const file = skillsGrantsPath();
|
|
121
|
+
const stat = statSync(file);
|
|
122
|
+
const signature = `${stat.size}:${stat.mtimeMs}`;
|
|
123
|
+
if (signature === lastSignature)
|
|
124
|
+
return lastMap;
|
|
125
|
+
const raw = readFileSync(file, "utf8");
|
|
126
|
+
if (Buffer.byteLength(raw) > MAX_GRANTS_FILE_BYTES)
|
|
127
|
+
throw new Error("Grants file exceeds limit");
|
|
128
|
+
lastMap = parseFile(raw);
|
|
129
|
+
lastSignature = signature;
|
|
130
|
+
lastWarning = "";
|
|
131
|
+
return lastMap;
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
135
|
+
if (message !== lastWarning) {
|
|
136
|
+
lastWarning = message;
|
|
137
|
+
log.warn(`skills grants file unavailable (${skillsGrantsPath()}); nothing granted: ${message}`);
|
|
138
|
+
}
|
|
139
|
+
lastMap = new Map();
|
|
140
|
+
lastSignature = "";
|
|
141
|
+
return lastMap;
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
//# sourceMappingURL=grants-file.js.map
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Isolated skill job runner (skills-runtime-design.md §10).
|
|
3
|
+
*
|
|
4
|
+
* Triggered and Passive evaluations run in an ISOLATED Pi execution context:
|
|
5
|
+
* - explicit resource loading only: the resource loader disables ambient
|
|
6
|
+
* extension and skill discovery (`noExtensions`/`noSkills`) and injects
|
|
7
|
+
* the single selected skill via `skillsOverride`. This prevents the
|
|
8
|
+
* manager's own extension from being recursively loaded into workers.
|
|
9
|
+
* - minimal toolset: an explicit `tools` allowlist — never the default
|
|
10
|
+
* read/bash/edit/write set. A simple comment review gets ONLY skill_report.
|
|
11
|
+
* - in-memory session: job traffic never lands in a persisted session file.
|
|
12
|
+
* - verified reporting: the job resolves "ok" only when the model calls
|
|
13
|
+
* skill_report with a payload that parses against the protocol
|
|
14
|
+
* ReviewResult AND matches the immutable job identity (jobId/eventId/
|
|
15
|
+
* skillKey/skillRevision) — the model cannot report for another job.
|
|
16
|
+
*
|
|
17
|
+
* The runner never talks to the user's chat session: no sendUserMessage,
|
|
18
|
+
* no sendMessage. Results are returned to the caller (SkillsService) and
|
|
19
|
+
* surfaced deliberately.
|
|
20
|
+
*/
|
|
21
|
+
import path from "node:path";
|
|
22
|
+
import Type from "typebox";
|
|
23
|
+
import { createAgentSession, createSyntheticSourceInfo, defineTool, DefaultResourceLoader, SessionManager, } from "@earendil-works/pi-coding-agent";
|
|
24
|
+
import { parseReviewResult } from "@pi-browser/protocol";
|
|
25
|
+
import { BROWSER_TOOL_SCHEMAS } from "../browser/schemas.js";
|
|
26
|
+
function skillBlock(spec) {
|
|
27
|
+
return [
|
|
28
|
+
`# Skill: ${spec.skill.key} (revision ${spec.skill.revision})`,
|
|
29
|
+
"",
|
|
30
|
+
spec.skill.instructions,
|
|
31
|
+
].join("\n");
|
|
32
|
+
}
|
|
33
|
+
function contractBlock(spec) {
|
|
34
|
+
return [
|
|
35
|
+
"## Job contract",
|
|
36
|
+
`jobId: ${spec.jobId}`,
|
|
37
|
+
`eventId: ${spec.eventId}`,
|
|
38
|
+
`skillKey: ${spec.skill.key}`,
|
|
39
|
+
`skillRevision: ${spec.skill.revision}`,
|
|
40
|
+
'When done, call skill_report EXACTLY ONCE with a decision ("clear" | "suggest" | "abstain"), a one-sentence explanation, and replacementText only when decision is "suggest". Do NOT provide jobId/eventId/skillKey/skillRevision: the runtime binds the job identity for you. Then stop. You have no access to the user\'s chat session.',
|
|
41
|
+
].join("\n");
|
|
42
|
+
}
|
|
43
|
+
function taskPrompt(spec) {
|
|
44
|
+
return [
|
|
45
|
+
`## Context (event ${spec.eventId})`,
|
|
46
|
+
spec.context,
|
|
47
|
+
"",
|
|
48
|
+
"Perform the skill's task now using this context.",
|
|
49
|
+
].join("\n");
|
|
50
|
+
}
|
|
51
|
+
/** Synthetic loader entry so the selected skill is explicitly loaded. Its
|
|
52
|
+
* instructions are injected via the system prompt; the file does not exist,
|
|
53
|
+
* so model-invocation (file re-reads) is disabled. */
|
|
54
|
+
function syntheticSkill(skill) {
|
|
55
|
+
const baseDir = path.join(".pi", "browser-skills", ...skill.key.split("/"));
|
|
56
|
+
const filePath = path.join(baseDir, "SKILL.md");
|
|
57
|
+
return {
|
|
58
|
+
name: skill.key,
|
|
59
|
+
description: `Skill job ${skill.key}`,
|
|
60
|
+
filePath,
|
|
61
|
+
baseDir,
|
|
62
|
+
sourceInfo: createSyntheticSourceInfo(filePath, { source: "sdk" }),
|
|
63
|
+
disableModelInvocation: true,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function reportTool(spec, onReport) {
|
|
67
|
+
return defineTool({
|
|
68
|
+
name: "skill_report",
|
|
69
|
+
label: "Skill Report",
|
|
70
|
+
description: "Report the verified result of this skill job. Call exactly once with a decision, then stop. The job identity (jobId/eventId/skillKey/skillRevision) is bound by the runtime; you do not need to provide it.",
|
|
71
|
+
parameters: Type.Object({
|
|
72
|
+
decision: Type.Union([Type.Literal("clear"), Type.Literal("suggest"), Type.Literal("abstain")]),
|
|
73
|
+
explanation: Type.Optional(Type.String()),
|
|
74
|
+
replacementText: Type.Optional(Type.String()),
|
|
75
|
+
}),
|
|
76
|
+
execute: async (toolCallId, params) => {
|
|
77
|
+
const raw = { ...params };
|
|
78
|
+
// The job identity is immutable and known to the runner: ALWAYS bind it
|
|
79
|
+
// from the spec, ignoring whatever the model echoes. Small local models
|
|
80
|
+
// hallucinate opaque identity strings (jobId/revision) reliably enough
|
|
81
|
+
// to make echo-verification a dead end; the security property (a report
|
|
82
|
+
// can never name a foreign job) is preserved because the identity is the
|
|
83
|
+
// spec's, never the model's. The model supplies only decision,
|
|
84
|
+
// explanation, and replacementText.
|
|
85
|
+
raw.jobId = spec.jobId;
|
|
86
|
+
raw.eventId = spec.eventId;
|
|
87
|
+
raw.skillKey = spec.skill.key;
|
|
88
|
+
raw.skillRevision = spec.skill.revision;
|
|
89
|
+
onReport(raw);
|
|
90
|
+
return { content: [{ type: "text", text: "Report recorded. Stop now." }], details: { recorded: true } };
|
|
91
|
+
},
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
/** Verify shape via the protocol parser, then bind to the immutable job identity. */
|
|
95
|
+
export function verifyReport(raw, spec) {
|
|
96
|
+
const report = parseReviewResult(raw);
|
|
97
|
+
if (report.jobId !== spec.jobId)
|
|
98
|
+
throw new Error("report jobId does not match the job");
|
|
99
|
+
if (report.eventId !== spec.eventId)
|
|
100
|
+
throw new Error("report eventId does not match the job");
|
|
101
|
+
if (report.skillKey !== spec.skill.key)
|
|
102
|
+
throw new Error("report skillKey does not match the job");
|
|
103
|
+
if (report.skillRevision !== spec.skill.revision)
|
|
104
|
+
throw new Error("report skillRevision does not match the job");
|
|
105
|
+
return report;
|
|
106
|
+
}
|
|
107
|
+
function extractTranscript(messages) {
|
|
108
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
109
|
+
const msg = messages[i];
|
|
110
|
+
if (!msg || msg.role !== "assistant")
|
|
111
|
+
continue;
|
|
112
|
+
const text = Array.isArray(msg.content)
|
|
113
|
+
? msg.content
|
|
114
|
+
.filter((c) => c?.type === "text" && typeof c.text === "string")
|
|
115
|
+
.map((c) => c.text)
|
|
116
|
+
.join("")
|
|
117
|
+
: "";
|
|
118
|
+
if (text)
|
|
119
|
+
return text;
|
|
120
|
+
}
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
function message(err) {
|
|
124
|
+
return err instanceof Error ? err.message : String(err);
|
|
125
|
+
}
|
|
126
|
+
export class IsolatedSkillRunner {
|
|
127
|
+
opts;
|
|
128
|
+
factory;
|
|
129
|
+
constructor(opts) {
|
|
130
|
+
this.opts = opts;
|
|
131
|
+
this.factory = opts.sessionFactory ?? defaultSessionFactory;
|
|
132
|
+
}
|
|
133
|
+
async run(spec, signal) {
|
|
134
|
+
if (signal.aborted)
|
|
135
|
+
return { ok: false, error: "aborted" };
|
|
136
|
+
let rawReport;
|
|
137
|
+
const granted = this.grantBrowserTools(spec);
|
|
138
|
+
const options = {
|
|
139
|
+
cwd: this.opts.cwd ?? process.cwd(),
|
|
140
|
+
agentDir: this.opts.agentDir ?? path.join(process.env.HOME ?? "/tmp", ".pi", "agent"),
|
|
141
|
+
...(this.opts.modelRuntime ? { modelRuntime: this.opts.modelRuntime } : {}),
|
|
142
|
+
...(this.opts.model !== undefined ? { model: this.opts.model } : {}),
|
|
143
|
+
skill: spec.skill,
|
|
144
|
+
noExtensions: true,
|
|
145
|
+
noSkills: true,
|
|
146
|
+
inMemorySession: true,
|
|
147
|
+
systemPromptAppend: [skillBlock(spec), contractBlock(spec)],
|
|
148
|
+
taskPrompt: taskPrompt(spec),
|
|
149
|
+
tools: ["skill_report", ...granted.map((t) => t.name)],
|
|
150
|
+
customTools: [reportTool(spec, (raw) => { rawReport = raw; }), ...granted],
|
|
151
|
+
};
|
|
152
|
+
let session;
|
|
153
|
+
try {
|
|
154
|
+
session = await this.factory(options);
|
|
155
|
+
}
|
|
156
|
+
catch (err) {
|
|
157
|
+
this.opts.log.warn(`skill job ${spec.jobId}: failed to start isolated session: ${message(err)}`);
|
|
158
|
+
return { ok: false, error: `failed to start isolated session: ${message(err)}` };
|
|
159
|
+
}
|
|
160
|
+
this.opts.log.info(`skill job ${spec.jobId}: isolated session running (tools=${options.tools.join(",")})`);
|
|
161
|
+
const onAbort = () => { void session.abort().catch(() => { }); };
|
|
162
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
163
|
+
try {
|
|
164
|
+
await session.prompt(options.taskPrompt);
|
|
165
|
+
}
|
|
166
|
+
catch (err) {
|
|
167
|
+
if (signal.aborted)
|
|
168
|
+
return { ok: false, error: "aborted" };
|
|
169
|
+
this.opts.log.warn(`skill job ${spec.jobId}: session failed: ${message(err)}`);
|
|
170
|
+
return { ok: false, error: `job session failed: ${message(err)}` };
|
|
171
|
+
}
|
|
172
|
+
finally {
|
|
173
|
+
signal.removeEventListener("abort", onAbort);
|
|
174
|
+
try {
|
|
175
|
+
session.dispose();
|
|
176
|
+
}
|
|
177
|
+
catch { /* best-effort teardown */ }
|
|
178
|
+
}
|
|
179
|
+
return this.settle(rawReport, session.messages, spec);
|
|
180
|
+
}
|
|
181
|
+
/** Bind the recorded report to the job identity; absence is a failure. */
|
|
182
|
+
settle(rawReport, messages, spec) {
|
|
183
|
+
const transcript = extractTranscript(messages);
|
|
184
|
+
if (!rawReport) {
|
|
185
|
+
this.opts.log.warn(`skill job ${spec.jobId}: finished without a verified report`);
|
|
186
|
+
return { ok: false, transcript, error: "job finished without a verified report" };
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
const report = verifyReport(rawReport, spec);
|
|
190
|
+
this.opts.log.info(`skill job ${spec.jobId}: report accepted (decision=${report.decision})`);
|
|
191
|
+
return { ok: true, report, transcript };
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
this.opts.log.warn(`skill job ${spec.jobId}: invalid report: ${message(err)} raw=${JSON.stringify(rawReport)}`);
|
|
195
|
+
return { ok: false, transcript, error: `invalid report: ${message(err)}` };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Map granted browser tool names onto bridge-routed custom tools. Unknown
|
|
199
|
+
* names are skipped (the allowlist can never grant tools the host lacks). */
|
|
200
|
+
grantBrowserTools(spec) {
|
|
201
|
+
const bridge = this.opts.browserBridge;
|
|
202
|
+
if (!bridge || spec.grantedTools.length === 0)
|
|
203
|
+
return [];
|
|
204
|
+
return spec.grantedTools.flatMap((name) => {
|
|
205
|
+
const schema = BROWSER_TOOL_SCHEMAS.find((t) => t.name === name);
|
|
206
|
+
if (!schema) {
|
|
207
|
+
this.opts.log.warn(`skill job ${spec.jobId}: skipping unknown granted tool ${name}`);
|
|
208
|
+
return [];
|
|
209
|
+
}
|
|
210
|
+
const definition = schema;
|
|
211
|
+
return [
|
|
212
|
+
defineTool({
|
|
213
|
+
name: definition.name,
|
|
214
|
+
label: definition.name,
|
|
215
|
+
description: definition.description,
|
|
216
|
+
parameters: definition.parameters,
|
|
217
|
+
execute: async (toolCallId, params) => {
|
|
218
|
+
const result = await bridge.call({ tool: definition.name, args: params, toolCallId });
|
|
219
|
+
return {
|
|
220
|
+
content: result.content,
|
|
221
|
+
details: { piBrowser: true, tool: definition.name },
|
|
222
|
+
...(result.isError ? { isError: true } : {}),
|
|
223
|
+
};
|
|
224
|
+
},
|
|
225
|
+
}),
|
|
226
|
+
];
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/** SDK default: explicit resource loading, in-memory session, minimal tools. */
|
|
231
|
+
async function defaultSessionFactory(opts) {
|
|
232
|
+
const loader = new DefaultResourceLoader({
|
|
233
|
+
cwd: opts.cwd,
|
|
234
|
+
agentDir: opts.agentDir,
|
|
235
|
+
noExtensions: true,
|
|
236
|
+
noSkills: true,
|
|
237
|
+
noPromptTemplates: true,
|
|
238
|
+
noThemes: true,
|
|
239
|
+
noContextFiles: true,
|
|
240
|
+
appendSystemPrompt: opts.systemPromptAppend,
|
|
241
|
+
skillsOverride: (base) => ({ skills: [syntheticSkill(opts.skill)], diagnostics: base.diagnostics }),
|
|
242
|
+
});
|
|
243
|
+
const created = await createAgentSession({
|
|
244
|
+
cwd: opts.cwd,
|
|
245
|
+
agentDir: opts.agentDir,
|
|
246
|
+
...(opts.modelRuntime ? { modelRuntime: opts.modelRuntime } : {}),
|
|
247
|
+
...(opts.model !== undefined ? { model: opts.model } : {}),
|
|
248
|
+
// Skill jobs run under a hard execution deadline (protocol cap 10 s):
|
|
249
|
+
// reasoning burns most of that budget before the first token, so the
|
|
250
|
+
// isolated job session always runs with reasoning off.
|
|
251
|
+
thinkingLevel: "off",
|
|
252
|
+
tools: opts.tools,
|
|
253
|
+
customTools: opts.customTools,
|
|
254
|
+
resourceLoader: loader,
|
|
255
|
+
sessionManager: SessionManager.inMemory(),
|
|
256
|
+
});
|
|
257
|
+
return created.session;
|
|
258
|
+
}
|
|
259
|
+
//# sourceMappingURL=isolated-runner.js.map
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
function field(block, name) {
|
|
2
|
+
const line = block.split("\n").find((l) => l.startsWith(`${name}: `));
|
|
3
|
+
return line ? line.slice(name.length + 2) : "";
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Build a factory whose sessions play the scripted model. Job identity is
|
|
7
|
+
* parsed from the runner's own contract block, so a scripted report can
|
|
8
|
+
* never drift from the identity the runner verified.
|
|
9
|
+
*/
|
|
10
|
+
export function createScriptedSessionFactory(job) {
|
|
11
|
+
return async (opts) => {
|
|
12
|
+
const contract = opts.systemPromptAppend.find((b) => b.includes("## Job contract")) ?? "";
|
|
13
|
+
const identity = {
|
|
14
|
+
jobId: field(contract, "jobId"),
|
|
15
|
+
eventId: field(contract, "eventId"),
|
|
16
|
+
skillKey: field(contract, "skillKey"),
|
|
17
|
+
skillRevision: field(contract, "skillRevision"),
|
|
18
|
+
};
|
|
19
|
+
const reportTool = opts.customTools.find((t) => t.name === "skill_report");
|
|
20
|
+
const messages = [
|
|
21
|
+
{ role: "assistant", content: [{ type: "text", text: `scripted job finished (${identity.jobId})` }] },
|
|
22
|
+
];
|
|
23
|
+
return {
|
|
24
|
+
messages,
|
|
25
|
+
async prompt() {
|
|
26
|
+
if (job.fail)
|
|
27
|
+
throw new Error(job.fail);
|
|
28
|
+
if (job.delayMs)
|
|
29
|
+
await new Promise((r) => setTimeout(r, job.delayMs));
|
|
30
|
+
if (!job.report)
|
|
31
|
+
return; // no report -> unavailable outcome
|
|
32
|
+
if (!reportTool)
|
|
33
|
+
throw new Error("scripted job: skill_report tool missing from job options");
|
|
34
|
+
// defineTool is an identity wrapper: the job's skill_report execute
|
|
35
|
+
// is the runner's two-argument closure (toolCallId, params).
|
|
36
|
+
const run = reportTool.execute;
|
|
37
|
+
await run("scripted-report", {
|
|
38
|
+
...identity,
|
|
39
|
+
decision: job.report.decision,
|
|
40
|
+
...(job.report.explanation !== undefined ? { explanation: job.report.explanation } : {}),
|
|
41
|
+
...(job.report.replacementText !== undefined ? { replacementText: job.report.replacementText } : {}),
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
async abort() { },
|
|
45
|
+
dispose() { },
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=mock-session-factory.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill package root resolution (skills-runtime-design.md §3).
|
|
3
|
+
*
|
|
4
|
+
* Application data lives under a configurable native-host data root
|
|
5
|
+
* (default ~/.pi/browser): `packages/` holds skill source packages.
|
|
6
|
+
* PI_BROWSER_SKILL_ROOTS adds registered external package roots
|
|
7
|
+
* (path.delimiter separated).
|
|
8
|
+
*/
|
|
9
|
+
import path from "node:path";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
export const DEFAULT_DATA_ROOT = path.join(homedir(), ".pi", "browser");
|
|
12
|
+
export function resolveSkillPackageRoots(env = process.env) {
|
|
13
|
+
const dataRoot = env.PI_BROWSER_DATA_ROOT?.trim() || DEFAULT_DATA_ROOT;
|
|
14
|
+
const roots = [path.join(dataRoot, "packages")];
|
|
15
|
+
const extra = env.PI_BROWSER_SKILL_ROOTS?.trim();
|
|
16
|
+
if (extra) {
|
|
17
|
+
for (const entry of extra.split(path.delimiter)) {
|
|
18
|
+
const root = entry.trim();
|
|
19
|
+
if (root)
|
|
20
|
+
roots.push(path.resolve(root));
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return [...new Set(roots)];
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=package-roots.js.map
|