@mago-foundation/mago-ski 0.0.0-stage → 0.2.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 +202 -0
- package/NOTICE +4 -0
- package/README.md +139 -2
- package/action.yml +58 -0
- package/dist/hosts/github/run.d.ts +27 -0
- package/dist/hosts/github/run.js +152 -0
- package/dist/hosts/pi/index.d.ts +13 -0
- package/dist/hosts/pi/index.js +550 -0
- package/dist/hosts/pi/paths.d.ts +9 -0
- package/dist/hosts/pi/paths.js +55 -0
- package/dist/src/admin.d.ts +74 -0
- package/dist/src/admin.js +243 -0
- package/dist/src/canonical-json.d.ts +12 -0
- package/dist/src/canonical-json.js +149 -0
- package/dist/src/certificate.d.ts +34 -0
- package/dist/src/certificate.js +112 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +595 -0
- package/dist/src/diff.d.ts +26 -0
- package/dist/src/diff.js +404 -0
- package/dist/src/dsse.d.ts +25 -0
- package/dist/src/dsse.js +71 -0
- package/dist/src/experimental/sigstore.d.ts +26 -0
- package/dist/src/experimental/sigstore.js +153 -0
- package/dist/src/fs-safe.d.ts +27 -0
- package/dist/src/fs-safe.js +229 -0
- package/dist/src/index.d.ts +14 -0
- package/dist/src/index.js +14 -0
- package/dist/src/keys.d.ts +21 -0
- package/dist/src/keys.js +154 -0
- package/dist/src/main-module.d.ts +5 -0
- package/dist/src/main-module.js +19 -0
- package/dist/src/names.d.ts +7 -0
- package/dist/src/names.js +38 -0
- package/dist/src/policy.d.ts +81 -0
- package/dist/src/policy.js +349 -0
- package/dist/src/revocations.d.ts +28 -0
- package/dist/src/revocations.js +93 -0
- package/dist/src/time.d.ts +25 -0
- package/dist/src/time.js +74 -0
- package/dist/src/tree-digest.d.ts +46 -0
- package/dist/src/tree-digest.js +268 -0
- package/dist/src/trust-root.d.ts +38 -0
- package/dist/src/trust-root.js +136 -0
- package/dist/src/verify.d.ts +96 -0
- package/dist/src/verify.js +380 -0
- package/docs/hosts/adapter-interface.md +33 -0
- package/docs/hosts/github-action.md +45 -0
- package/docs/hosts/pi.md +41 -0
- package/docs/spec/root-recovery-v1.md +430 -0
- package/docs/spec/skill-certificate-v1.md +60 -0
- package/docs/spec/skill-tree-v2.md +59 -0
- package/docs/spec/trust-documents-v1.md +103 -0
- package/docs/spec/verification.md +56 -0
- package/docs/threat-model.md +45 -0
- package/package.json +77 -4
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { lstat, realpath } from 'node:fs/promises';
|
|
3
|
+
import { homedir, hostname } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { isInside, readRegularFile } from "../../src/fs-safe.js";
|
|
6
|
+
import { appendDecision, loadPolicy, loadPolicyTrust, verifyWithPolicy } from "../../src/policy.js";
|
|
7
|
+
import { formatTimestamp } from "../../src/time.js";
|
|
8
|
+
import { CERTIFICATE_FILENAME, hashFile, sha256Hex } from "../../src/tree-digest.js";
|
|
9
|
+
import { validateSkillName } from "../../src/names.js";
|
|
10
|
+
import { unverifiable } from "../../src/verify.js";
|
|
11
|
+
import { piReadTarget, piReadVariants, piResolveToCwd } from "./paths.js";
|
|
12
|
+
const SHELL_TOOLS = new Set(['bash', 'powershell']);
|
|
13
|
+
const FILE_TOOLS = new Set(['read', 'edit', 'write', 'grep', 'find', 'ls']);
|
|
14
|
+
const HOME_POLICY_DIR = '.mago-ski';
|
|
15
|
+
/** Where the policy comes from when nothing is configured. */
|
|
16
|
+
function homePolicyPath() {
|
|
17
|
+
return path.join(homedir(), HOME_POLICY_DIR, 'policy.json');
|
|
18
|
+
}
|
|
19
|
+
/** Resolves symlinks on the longest existing prefix. Throws on errors other than ENOENT. */
|
|
20
|
+
async function canonical(target) {
|
|
21
|
+
let current = path.resolve(target);
|
|
22
|
+
const rest = [];
|
|
23
|
+
while (true) {
|
|
24
|
+
try {
|
|
25
|
+
return path.join(await realpath(current), ...rest.reverse());
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (error?.code !== 'ENOENT')
|
|
29
|
+
throw error;
|
|
30
|
+
const parent = path.dirname(current);
|
|
31
|
+
if (parent === current)
|
|
32
|
+
return path.resolve(target);
|
|
33
|
+
rest.push(path.basename(current));
|
|
34
|
+
current = parent;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function expandHome(value) {
|
|
39
|
+
return value === '~' ? homedir() : value.startsWith('~/') ? path.join(homedir(), value.slice(2)) : value;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Skill paths reach the model in Pi's Skill list and in `/skill:` blocks, but the certificate does
|
|
43
|
+
* not cover the Skill directory, so a contributor can rename it. Beneath a base the user chose (the
|
|
44
|
+
* working directory, the home directory) a path may use only the characters below; the base itself
|
|
45
|
+
* only has to be free of control characters and quoting or markup characters.
|
|
46
|
+
*/
|
|
47
|
+
const PROMPT_PATH_PART = /^[A-Za-z0-9._/~@+-]*$/u;
|
|
48
|
+
const PROMPT_PATH_BASE = /^[^\p{C}\p{Zl}\p{Zp}<>"'`\\]+$/u;
|
|
49
|
+
/** Why a path must not be shown to the model, or null when it may be. `bases` are trusted prefixes. */
|
|
50
|
+
export function promptPathProblem(target, bases = []) {
|
|
51
|
+
if (target.length <= 1024 && PROMPT_PATH_PART.test(target) && target !== '')
|
|
52
|
+
return null;
|
|
53
|
+
for (const base of bases) {
|
|
54
|
+
const prefix = base.endsWith('/') ? base : `${base}/`;
|
|
55
|
+
if (!path.isAbsolute(base) || !PROMPT_PATH_BASE.test(base) || !(target === base || target.startsWith(prefix)))
|
|
56
|
+
continue;
|
|
57
|
+
const rest = target.slice(base.length);
|
|
58
|
+
if (target.length <= 1024 && PROMPT_PATH_PART.test(rest))
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
return 'the Skill directory path has characters outside A-Z a-z 0-9 . _ / ~ @ + - below your working or home directory (or is too long), and the certificate does not cover the path; rename or move the directory';
|
|
62
|
+
}
|
|
63
|
+
/** Same frontmatter handling and block format as Pi's own /skill: expansion. Throws on unsafe metadata. */
|
|
64
|
+
export function skillBlock(name, filePath, baseDir, content, args, trustedBases = []) {
|
|
65
|
+
validateSkillName(name);
|
|
66
|
+
const problem = promptPathProblem(filePath, trustedBases) ?? promptPathProblem(baseDir, trustedBases);
|
|
67
|
+
if (problem)
|
|
68
|
+
throw new Error(problem);
|
|
69
|
+
const body = content.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/u, '').trim();
|
|
70
|
+
const block = `<skill name="${name}" location="${filePath}">\nReferences are relative to ${baseDir}.\n\n${body}\n</skill>`;
|
|
71
|
+
return args ? `${block}\n\n${args}` : block;
|
|
72
|
+
}
|
|
73
|
+
function dirsOf(entry) {
|
|
74
|
+
return entry.lexDir === entry.realDir ? [entry.lexDir] : [entry.lexDir, entry.realDir];
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Excluded paths that a tool could expose. The in-tree certificate is safe only when it is the
|
|
78
|
+
* certificate that verified this Skill; otherwise its bytes are unchecked and may hold anything.
|
|
79
|
+
*/
|
|
80
|
+
function riskyExclusions(entry) {
|
|
81
|
+
const verifiedInTree = entry.result.certificateSource === path.join(entry.realDir, CERTIFICATE_FILENAME);
|
|
82
|
+
return entry.result.excluded.filter((item) => !(item === CERTIFICATE_FILENAME && verifiedInTree));
|
|
83
|
+
}
|
|
84
|
+
export function createMagoSkiExtension(options = {}) {
|
|
85
|
+
return function magoSki(pi) {
|
|
86
|
+
const now = options.now ?? (() => new Date());
|
|
87
|
+
let policy = null;
|
|
88
|
+
/** Set when a policy file exists but cannot be loaded; the extension then fails closed. */
|
|
89
|
+
let policyError = null;
|
|
90
|
+
let loaded = false;
|
|
91
|
+
let entries = [];
|
|
92
|
+
/** Lexical Skill directories from the last run, recorded before any verification can fail. */
|
|
93
|
+
let knownDirs = [];
|
|
94
|
+
/** Enforce-mode latch: verification itself crashed, so every Skill path is treated as unverified. */
|
|
95
|
+
let failedClosed = false;
|
|
96
|
+
const lastLogged = new Map();
|
|
97
|
+
/** Skill directories already reported for an unsafe path, so the notice and log line appear once. */
|
|
98
|
+
const reportedPaths = new Set();
|
|
99
|
+
const mode = () => (policy ? policy.mode : 'enforce');
|
|
100
|
+
const active = () => policy !== null || policyError !== null;
|
|
101
|
+
const enforcing = () => mode() === 'enforce';
|
|
102
|
+
/**
|
|
103
|
+
* The policy decides the mode, so it must come from the host, never from the project. An explicit
|
|
104
|
+
* path (option or $MAGO_SKI_POLICY) has to be absolute and must not resolve into the project,
|
|
105
|
+
* unless it lives under ~/.mago-ski. Returns the reason it is refused, or null.
|
|
106
|
+
*/
|
|
107
|
+
async function policyPathProblem(configured, ctx) {
|
|
108
|
+
if (!path.isAbsolute(configured))
|
|
109
|
+
return 'the policy path must be absolute (or start with "~/"); a relative path would resolve against the project';
|
|
110
|
+
const target = await canonical(configured);
|
|
111
|
+
const hostDir = await canonical(path.join(homedir(), HOME_POLICY_DIR));
|
|
112
|
+
if (isInside(hostDir, target))
|
|
113
|
+
return null;
|
|
114
|
+
const home = await canonical(homedir());
|
|
115
|
+
const roots = new Set();
|
|
116
|
+
for (const start of [ctx.cwd, process.cwd()]) {
|
|
117
|
+
if (typeof start !== 'string' || start === '')
|
|
118
|
+
continue;
|
|
119
|
+
const cwd = await canonical(start);
|
|
120
|
+
roots.add(cwd);
|
|
121
|
+
// A policy anywhere in the same repository counts as the project's, even from a subdirectory.
|
|
122
|
+
// The search stops at the home directory, so a dotfiles repository there does not claim it all.
|
|
123
|
+
for (let dir = cwd; dir !== home; dir = path.dirname(dir)) {
|
|
124
|
+
if (existsSync(path.join(dir, '.git'))) {
|
|
125
|
+
roots.add(dir);
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
if (path.dirname(dir) === dir)
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
for (const root of roots)
|
|
133
|
+
if (isInside(root, target))
|
|
134
|
+
return `the policy file is inside the project (${root}); project files may be controlled by the code under review`;
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
async function ensurePolicy(ctx) {
|
|
138
|
+
if (loaded)
|
|
139
|
+
return;
|
|
140
|
+
loaded = true;
|
|
141
|
+
const explicit = options.policyPath ?? (process.env.MAGO_SKI_POLICY || undefined);
|
|
142
|
+
const policyPath = explicit === undefined ? homePolicyPath() : expandHome(explicit);
|
|
143
|
+
try {
|
|
144
|
+
if (explicit !== undefined) {
|
|
145
|
+
const problem = await policyPathProblem(policyPath, ctx);
|
|
146
|
+
if (problem)
|
|
147
|
+
throw Object.assign(new Error(problem), { code: 'EPOLICYPATH' });
|
|
148
|
+
}
|
|
149
|
+
policy = await loadPolicy(policyPath);
|
|
150
|
+
}
|
|
151
|
+
catch (error) {
|
|
152
|
+
if (error?.code === 'ENOENT') {
|
|
153
|
+
if (ctx.hasUI)
|
|
154
|
+
ctx.ui.notify(`mago-ski: no policy at ${policyPath}; Skills are not being checked`, 'warning');
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
policyError = `cannot load policy ${policyPath}: ${error.message}`;
|
|
158
|
+
if (ctx.hasUI)
|
|
159
|
+
ctx.ui.notify(`mago-ski: ${policyError}. Blocking all Skills until fixed.`, 'error');
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async function log(record, verified) {
|
|
163
|
+
if (!policy?.decisionLogPath)
|
|
164
|
+
return;
|
|
165
|
+
const action = verified ? 'allow' : enforcing() ? 'block' : 'would-block';
|
|
166
|
+
await appendDecision(policy.decisionLogPath, { timestamp: formatTimestamp(now()), host: hostname(), mode: mode(), action, ...record })
|
|
167
|
+
.catch(() => { });
|
|
168
|
+
}
|
|
169
|
+
async function trustContext() {
|
|
170
|
+
if (!policy)
|
|
171
|
+
return { ok: false, verdict: 'UNVERIFIABLE', reason: policyError ?? 'no policy' };
|
|
172
|
+
try {
|
|
173
|
+
return await loadPolicyTrust(policy, now());
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
return { ok: false, verdict: 'UNVERIFIABLE', reason: error.message };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/** Never throws: any failure becomes an UNVERIFIABLE entry for that Skill. */
|
|
180
|
+
async function verifyEntry(skill, context) {
|
|
181
|
+
const lexDir = path.resolve(skill.baseDir);
|
|
182
|
+
const entry = {
|
|
183
|
+
name: skill.name, baseDir: skill.baseDir, lexDir, realDir: lexDir, filePath: skill.filePath,
|
|
184
|
+
result: unverifiable(lexDir, skill.name, 'verification did not complete', now()),
|
|
185
|
+
};
|
|
186
|
+
try {
|
|
187
|
+
entry.realDir = await canonical(lexDir);
|
|
188
|
+
if (path.basename(skill.filePath) !== 'SKILL.md') {
|
|
189
|
+
entry.result = unverifiable(entry.realDir, skill.name, 'standalone Markdown Skills cannot be certified; use a directory with SKILL.md', now());
|
|
190
|
+
}
|
|
191
|
+
else if (!context.ok) {
|
|
192
|
+
entry.result = unverifiable(entry.realDir, skill.name, context.reason, now(), context.verdict);
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
entry.result = await verifyWithPolicy(policy, entry.realDir, { now: now(), skillName: skill.name, context: context.context });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
entry.result = unverifiable(entry.realDir, skill.name, `verification failed: ${error.message}`, now());
|
|
200
|
+
}
|
|
201
|
+
return entry;
|
|
202
|
+
}
|
|
203
|
+
function recordFor(entry, event, verdict = entry.result.verdict, reason = entry.result.reason) {
|
|
204
|
+
return {
|
|
205
|
+
event, skill: entry.name, skill_dir: entry.realDir, digest: entry.result.digest,
|
|
206
|
+
certificate_id: entry.result.certificateId, verdict, reason,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
async function refresh(skills, ctx) {
|
|
210
|
+
const context = await trustContext();
|
|
211
|
+
const fresh = [];
|
|
212
|
+
for (const skill of skills)
|
|
213
|
+
fresh.push(await verifyEntry(skill, context));
|
|
214
|
+
entries = fresh;
|
|
215
|
+
for (const entry of fresh) {
|
|
216
|
+
if (lastLogged.get(entry.lexDir) === entry.result.verdict)
|
|
217
|
+
continue;
|
|
218
|
+
lastLogged.set(entry.lexDir, entry.result.verdict);
|
|
219
|
+
await log(recordFor(entry, 'advertise'), entry.result.verdict === 'VERIFIED');
|
|
220
|
+
if (entry.result.verdict !== 'VERIFIED' && ctx.hasUI) {
|
|
221
|
+
const verb = enforcing() ? 'blocked' : 'would block (shadow)';
|
|
222
|
+
ctx.ui.notify(`mago-ski ${verb} Skill "${entry.name}": ${entry.result.verdict} - ${entry.result.reason}`, enforcing() ? 'error' : 'warning');
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (ctx.hasUI) {
|
|
226
|
+
const ok = fresh.filter((entry) => entry.result.verdict === 'VERIFIED').length;
|
|
227
|
+
ctx.ui.setStatus('mago-ski', `mago-ski ${mode()}: ${ok}/${fresh.length} Skills verified`);
|
|
228
|
+
}
|
|
229
|
+
return fresh;
|
|
230
|
+
}
|
|
231
|
+
async function reverify(entry) {
|
|
232
|
+
const updated = await verifyEntry({ name: entry.name, baseDir: entry.baseDir, filePath: entry.filePath }, await trustContext());
|
|
233
|
+
entries = entries.map((item) => (item === entry ? updated : item));
|
|
234
|
+
return updated;
|
|
235
|
+
}
|
|
236
|
+
function byName(name) {
|
|
237
|
+
return entries.find((entry) => entry.name === name);
|
|
238
|
+
}
|
|
239
|
+
/** Skills a path is inside, matching the lexical and the canonical path against both Skill forms. */
|
|
240
|
+
function containing(paths) {
|
|
241
|
+
return entries.filter((entry) => dirsOf(entry).some((dir) => paths.some((target) => isInside(dir, target))));
|
|
242
|
+
}
|
|
243
|
+
/** Skills inside a directory a tool would search. */
|
|
244
|
+
function contained(paths) {
|
|
245
|
+
return entries.filter((entry) => dirsOf(entry).some((dir) => paths.some((target) => target !== dir && isInside(target, dir))));
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Rewrites the text of a `find` or `ls` result that listed an unverified Skill. Both tools print one
|
|
249
|
+
* path (relative to `root`) per line plus an optional trailing notice. Names may contain newlines, so
|
|
250
|
+
* a line is kept only if it names something that exists under `root` and is not in an unverified
|
|
251
|
+
* Skill. Returns null when nothing had to be removed.
|
|
252
|
+
*/
|
|
253
|
+
async function filterListing(text, root, unverified) {
|
|
254
|
+
const notice = /\n\n(\[(?:\d+ (?:results|entries) limit reached(?:\. Use limit=\d+ for more(?:, or refine pattern)?)?|[\d.]+KB limit reached)(?:\. [\d.]+KB limit reached)?\])$/u.exec(text);
|
|
255
|
+
const body = notice ? text.slice(0, notice.index) : text;
|
|
256
|
+
if (body === '(empty directory)' || body === 'No files found matching pattern')
|
|
257
|
+
return null;
|
|
258
|
+
const kept = [];
|
|
259
|
+
let removed = 0;
|
|
260
|
+
for (const line of body.split('\n')) {
|
|
261
|
+
const abs = path.join(root, line);
|
|
262
|
+
let inSkill = false;
|
|
263
|
+
if (line !== '') {
|
|
264
|
+
try {
|
|
265
|
+
await lstat(abs);
|
|
266
|
+
const real = await canonical(abs);
|
|
267
|
+
inSkill = unverified.some((entry) => dirsOf(entry).some((dir) => isInside(dir, abs) || isInside(dir, real)));
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
inSkill = true; // not a real path (part of a name with a newline) or unreadable: do not pass it on
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
if (inSkill)
|
|
274
|
+
removed++;
|
|
275
|
+
else
|
|
276
|
+
kept.push(line);
|
|
277
|
+
}
|
|
278
|
+
if (removed === 0)
|
|
279
|
+
return null;
|
|
280
|
+
const hidden = `[mago-ski: ${removed} entr${removed === 1 ? 'y' : 'ies'} hidden because they belong to a Skill that is not verified]`;
|
|
281
|
+
const list = kept.join('\n');
|
|
282
|
+
return { text: [list, notice?.[1], hidden].filter((part) => part).join('\n\n'), list, removed };
|
|
283
|
+
}
|
|
284
|
+
/** Logs the decision; returns a block in enforce mode, undefined in shadow mode. */
|
|
285
|
+
async function judge(entry, event, verdict, reason) {
|
|
286
|
+
await log(recordFor(entry, event, verdict, reason), false);
|
|
287
|
+
return enforcing() ? { block: true, reason: `mago-ski: Skill "${entry.name}" ${verdict}: ${reason}` } : undefined;
|
|
288
|
+
}
|
|
289
|
+
async function checkShell(toolName, command) {
|
|
290
|
+
// Best-effort: shell commands can reach files in ways a string match cannot see.
|
|
291
|
+
for (const entry of [...entries]) {
|
|
292
|
+
const forms = new Set([...dirsOf(entry), entry.baseDir]);
|
|
293
|
+
for (const dir of [...forms])
|
|
294
|
+
if (dir.startsWith(homedir()))
|
|
295
|
+
forms.add(`~${dir.slice(homedir().length)}`);
|
|
296
|
+
if (![...forms].some((form) => command.includes(form)))
|
|
297
|
+
continue;
|
|
298
|
+
const current = entry.result.verdict === 'VERIFIED' ? await reverify(entry) : entry;
|
|
299
|
+
if (current.result.verdict !== 'VERIFIED') {
|
|
300
|
+
const blocked = await judge(current, `tool:${toolName}`, current.result.verdict, current.result.reason);
|
|
301
|
+
if (blocked)
|
|
302
|
+
return blocked;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
return undefined;
|
|
306
|
+
}
|
|
307
|
+
async function checkGrep(affected) {
|
|
308
|
+
for (const entry of affected) {
|
|
309
|
+
if (entry.result.verdict !== 'VERIFIED') {
|
|
310
|
+
const blocked = await judge(entry, 'tool:grep', entry.result.verdict, entry.result.reason);
|
|
311
|
+
if (blocked)
|
|
312
|
+
return blocked;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
const risky = riskyExclusions(entry);
|
|
316
|
+
if (risky.length > 0) {
|
|
317
|
+
const blocked = await judge(entry, 'tool:grep', 'UNAPPROVED_CHANGE', `the Skill has files excluded from its certificate (${risky.slice(0, 3).join(', ')}); grep could return them. Use read on specific files`);
|
|
318
|
+
if (blocked)
|
|
319
|
+
return blocked;
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
const current = await reverify(entry);
|
|
323
|
+
if (current.result.verdict !== 'VERIFIED') {
|
|
324
|
+
const blocked = await judge(current, 'tool:grep', current.result.verdict, current.result.reason);
|
|
325
|
+
if (blocked)
|
|
326
|
+
return blocked;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
// Files can appear in excluded locations after the run started; check the fresh result too.
|
|
330
|
+
const late = riskyExclusions(current);
|
|
331
|
+
if (late.length > 0) {
|
|
332
|
+
const blocked = await judge(current, 'tool:grep', 'UNAPPROVED_CHANGE', `the Skill has files excluded from its certificate (${late.slice(0, 3).join(', ')}); grep could return them. Use read on specific files`);
|
|
333
|
+
if (blocked)
|
|
334
|
+
return blocked;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return undefined;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Every path a file tool call could touch: Pi's own resolution of the argument (and, for read,
|
|
341
|
+
* the filename variants Pi tries), a plain resolution as a fallback, and each one's canonical form.
|
|
342
|
+
*/
|
|
343
|
+
async function toolTargets(toolName, rawPath, cwd) {
|
|
344
|
+
const piPath = piResolveToCwd(rawPath, cwd);
|
|
345
|
+
const lexicals = new Set([...(toolName === 'read' ? piReadVariants(piPath) : [piPath]), path.resolve(cwd, expandHome(rawPath))]);
|
|
346
|
+
const targets = new Set();
|
|
347
|
+
for (const lexical of lexicals) {
|
|
348
|
+
targets.add(lexical);
|
|
349
|
+
// An unresolvable path (for example, permission denied) is still matched lexically.
|
|
350
|
+
targets.add(await canonical(lexical).catch(() => lexical));
|
|
351
|
+
}
|
|
352
|
+
return { targets: [...targets], piPath };
|
|
353
|
+
}
|
|
354
|
+
async function checkFileTool(toolName, rawPath, cwd) {
|
|
355
|
+
const { targets, piPath } = await toolTargets(toolName, rawPath, cwd);
|
|
356
|
+
const inside = containing(targets);
|
|
357
|
+
if (toolName === 'grep')
|
|
358
|
+
return await checkGrep([...inside, ...contained(targets).filter((entry) => !inside.includes(entry))]);
|
|
359
|
+
const unverified = inside.find((entry) => entry.result.verdict !== 'VERIFIED');
|
|
360
|
+
if (unverified)
|
|
361
|
+
return await judge(unverified, `tool:${toolName}`, unverified.result.verdict, unverified.result.reason);
|
|
362
|
+
const entry = inside[0];
|
|
363
|
+
if (!entry)
|
|
364
|
+
return undefined;
|
|
365
|
+
if (toolName === 'edit' || toolName === 'write') {
|
|
366
|
+
return await judge(entry, `tool:${toolName}`, 'UNAPPROVED_CHANGE', 'changing an approved Skill would invalidate its certificate');
|
|
367
|
+
}
|
|
368
|
+
if (toolName !== 'read')
|
|
369
|
+
return undefined; // find and ls show names, not contents
|
|
370
|
+
const opened = piReadTarget(piPath);
|
|
371
|
+
const resolved = await canonical(opened).catch(() => opened);
|
|
372
|
+
if (!isInside(entry.realDir, resolved)) {
|
|
373
|
+
return await judge(entry, 'tool:read', 'UNAPPROVED_CHANGE', `${rawPath} leaves the Skill directory through a link`);
|
|
374
|
+
}
|
|
375
|
+
const relative = path.relative(entry.realDir, resolved).split(path.sep).join('/');
|
|
376
|
+
const approved = entry.result.files?.find((file) => file.path === relative);
|
|
377
|
+
if (!approved)
|
|
378
|
+
return await judge(entry, 'tool:read', 'UNAPPROVED_CHANGE', `${relative} is not covered by the Skill's certificate`);
|
|
379
|
+
try {
|
|
380
|
+
const actual = await hashFile(resolved, relative);
|
|
381
|
+
if (actual.sha256 !== approved.sha256 || actual.exec !== approved.exec)
|
|
382
|
+
throw new Error(`${relative} changed after verification`);
|
|
383
|
+
}
|
|
384
|
+
catch (error) {
|
|
385
|
+
entry.result = { ...entry.result, verdict: 'UNAPPROVED_CHANGE', reason: error.message, files: null };
|
|
386
|
+
return await judge(entry, 'tool:read', 'UNAPPROVED_CHANGE', error.message);
|
|
387
|
+
}
|
|
388
|
+
return undefined;
|
|
389
|
+
}
|
|
390
|
+
/** Used only after verification itself crashed in enforce mode. Matches Skill dirs in every known form. */
|
|
391
|
+
async function latchBlock(toolName, input, cwd) {
|
|
392
|
+
const reason = 'mago-ski: Skill verification failed earlier in this run; Skill files are blocked until it succeeds';
|
|
393
|
+
if (SHELL_TOOLS.has(toolName)) {
|
|
394
|
+
const command = String(input.command ?? '');
|
|
395
|
+
const forms = new Set(knownDirs);
|
|
396
|
+
for (const dir of knownDirs)
|
|
397
|
+
if (dir.startsWith(homedir()))
|
|
398
|
+
forms.add(`~${dir.slice(homedir().length)}`);
|
|
399
|
+
return [...forms].some((form) => command.includes(form)) ? { block: true, reason } : undefined;
|
|
400
|
+
}
|
|
401
|
+
const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
|
|
402
|
+
const { targets } = await toolTargets(toolName, rawPath, cwd);
|
|
403
|
+
const touches = knownDirs.some((dir) => targets.some((target) => isInside(dir, target) || isInside(target, dir)));
|
|
404
|
+
return touches ? { block: true, reason } : undefined;
|
|
405
|
+
}
|
|
406
|
+
pi.on('session_start', async (_event, ctx) => {
|
|
407
|
+
if (process.platform === 'win32' && ctx.hasUI) {
|
|
408
|
+
ctx.ui.notify('mago-ski: Windows is not supported yet. Executable bits are not covered, so Skills approved on Linux or macOS may not verify.', 'warning');
|
|
409
|
+
}
|
|
410
|
+
await ensurePolicy(ctx);
|
|
411
|
+
});
|
|
412
|
+
pi.on('before_agent_start', async (event, ctx) => {
|
|
413
|
+
await ensurePolicy(ctx);
|
|
414
|
+
if (!active())
|
|
415
|
+
return;
|
|
416
|
+
knownDirs = event.systemPromptOptions.skills.map((skill) => path.resolve(skill.baseDir));
|
|
417
|
+
try {
|
|
418
|
+
for (const dir of [...knownDirs]) {
|
|
419
|
+
const real = await canonical(dir).catch(() => dir);
|
|
420
|
+
if (!knownDirs.includes(real))
|
|
421
|
+
knownDirs.push(real);
|
|
422
|
+
}
|
|
423
|
+
const checked = await refresh(event.systemPromptOptions.skills, ctx);
|
|
424
|
+
failedClosed = false;
|
|
425
|
+
// Pi lists each Skill's path to the model; a verified Skill whose path is not plainly spelled stays out of the list.
|
|
426
|
+
const unsafe = new Set();
|
|
427
|
+
for (const entry of checked) {
|
|
428
|
+
const problem = promptPathProblem(entry.filePath, [ctx.cwd, homedir()]);
|
|
429
|
+
if (!problem || entry.result.verdict !== 'VERIFIED')
|
|
430
|
+
continue;
|
|
431
|
+
unsafe.add(entry.lexDir);
|
|
432
|
+
if (!reportedPaths.has(entry.lexDir)) {
|
|
433
|
+
reportedPaths.add(entry.lexDir);
|
|
434
|
+
await judge(entry, 'advertise', 'UNAPPROVED_CHANGE', problem);
|
|
435
|
+
if (ctx.hasUI)
|
|
436
|
+
ctx.ui.notify(`mago-ski ${enforcing() ? 'did not advertise' : 'would not advertise (shadow)'} Skill "${entry.name}": ${problem}`, enforcing() ? 'error' : 'warning');
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (enforcing()) {
|
|
440
|
+
const allowed = new Set(checked.filter((entry) => entry.result.verdict === 'VERIFIED' && !unsafe.has(entry.lexDir)).map((entry) => entry.lexDir));
|
|
441
|
+
event.systemPromptOptions.skills = event.systemPromptOptions.skills.filter((skill) => allowed.has(path.resolve(skill.baseDir)));
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
catch (error) {
|
|
445
|
+
// Fail closed: an unexpected error must not leave unchecked Skills advertised or readable.
|
|
446
|
+
if (enforcing()) {
|
|
447
|
+
failedClosed = true;
|
|
448
|
+
event.systemPromptOptions.skills = [];
|
|
449
|
+
}
|
|
450
|
+
if (ctx.hasUI)
|
|
451
|
+
ctx.ui.notify(`mago-ski: verification failed (${error.message}); no Skills advertised`, 'error');
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
pi.on('input', async (event, ctx) => {
|
|
455
|
+
await ensurePolicy(ctx);
|
|
456
|
+
if (!active() || !event.text.startsWith('/skill:'))
|
|
457
|
+
return { action: 'continue' };
|
|
458
|
+
const space = event.text.indexOf(' ');
|
|
459
|
+
const name = space === -1 ? event.text.slice(7) : event.text.slice(7, space);
|
|
460
|
+
const args = space === -1 ? '' : event.text.slice(space + 1).trim();
|
|
461
|
+
const known = byName(name);
|
|
462
|
+
if (!known) {
|
|
463
|
+
// Not seen yet (first prompt of a session). Never let Pi expand it unchecked: turn it into a
|
|
464
|
+
// plain request; the model can only use the Skill if it is advertised, and reads are checked.
|
|
465
|
+
if (!enforcing())
|
|
466
|
+
return { action: 'continue' };
|
|
467
|
+
return { action: 'transform', text: `Use the "${name}" skill.${args ? ` ${args}` : ''}` };
|
|
468
|
+
}
|
|
469
|
+
const entry = await reverify(known);
|
|
470
|
+
if (entry.result.verdict === 'VERIFIED') {
|
|
471
|
+
try {
|
|
472
|
+
const bytes = await readRegularFile(entry.filePath, 'SKILL.md', 8 * 1024 * 1024);
|
|
473
|
+
const approved = entry.result.files?.find((file) => file.path === 'SKILL.md');
|
|
474
|
+
if (!approved || approved.sha256 !== sha256Hex(bytes))
|
|
475
|
+
throw new Error('SKILL.md changed after verification');
|
|
476
|
+
return { action: 'transform', text: skillBlock(entry.name, entry.filePath, entry.baseDir, bytes.toString('utf8'), args, [ctx.cwd, homedir()]) };
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
const blocked = await judge(entry, 'skill-command', 'UNAPPROVED_CHANGE', error.message);
|
|
480
|
+
if (!blocked)
|
|
481
|
+
return { action: 'continue' };
|
|
482
|
+
if (ctx.hasUI)
|
|
483
|
+
ctx.ui.notify(blocked.reason, 'error');
|
|
484
|
+
return { action: 'handled' };
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const blocked = await judge(entry, 'skill-command', entry.result.verdict, entry.result.reason);
|
|
488
|
+
if (!blocked)
|
|
489
|
+
return { action: 'continue' };
|
|
490
|
+
if (ctx.hasUI)
|
|
491
|
+
ctx.ui.notify(blocked.reason, 'error');
|
|
492
|
+
return { action: 'handled' };
|
|
493
|
+
});
|
|
494
|
+
// find and ls print names, so names inside an unverified Skill are removed from what the model sees.
|
|
495
|
+
pi.on('tool_result', async (event, ctx) => {
|
|
496
|
+
if (!active() || event.isError || entries.length === 0)
|
|
497
|
+
return undefined;
|
|
498
|
+
if (event.toolName !== 'find' && event.toolName !== 'ls')
|
|
499
|
+
return undefined;
|
|
500
|
+
const input = event.input;
|
|
501
|
+
const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
|
|
502
|
+
const { targets, piPath } = await toolTargets(event.toolName, rawPath, ctx.cwd);
|
|
503
|
+
const unverified = contained(targets).filter((entry) => entry.result.verdict !== 'VERIFIED');
|
|
504
|
+
if (unverified.length === 0)
|
|
505
|
+
return undefined;
|
|
506
|
+
const content = [...event.content];
|
|
507
|
+
let list;
|
|
508
|
+
let removed = 0;
|
|
509
|
+
for (const [index, item] of content.entries()) {
|
|
510
|
+
if (item.type !== 'text')
|
|
511
|
+
continue;
|
|
512
|
+
const filtered = await filterListing(item.text, piPath, unverified);
|
|
513
|
+
if (!filtered)
|
|
514
|
+
continue;
|
|
515
|
+
content[index] = { ...item, text: filtered.text };
|
|
516
|
+
list = filtered.list;
|
|
517
|
+
removed += filtered.removed;
|
|
518
|
+
}
|
|
519
|
+
if (removed === 0)
|
|
520
|
+
return undefined;
|
|
521
|
+
for (const entry of unverified)
|
|
522
|
+
await judge(entry, `tool:${event.toolName}`, entry.result.verdict, entry.result.reason);
|
|
523
|
+
if (!enforcing())
|
|
524
|
+
return undefined;
|
|
525
|
+
// The truncation record in `details` carries the unfiltered text too.
|
|
526
|
+
const details = event.details;
|
|
527
|
+
return {
|
|
528
|
+
content,
|
|
529
|
+
...(details?.truncation ? { details: { ...details, truncation: { ...details.truncation, content: list ?? '' } } } : {}),
|
|
530
|
+
};
|
|
531
|
+
});
|
|
532
|
+
pi.on('tool_call', async (event, ctx) => {
|
|
533
|
+
if (!active())
|
|
534
|
+
return undefined;
|
|
535
|
+
const input = event.input;
|
|
536
|
+
const toolName = event.toolName;
|
|
537
|
+
if (!SHELL_TOOLS.has(toolName) && !FILE_TOOLS.has(toolName))
|
|
538
|
+
return undefined;
|
|
539
|
+
if (failedClosed && enforcing())
|
|
540
|
+
return await latchBlock(toolName, input, ctx.cwd);
|
|
541
|
+
if (entries.length === 0)
|
|
542
|
+
return undefined;
|
|
543
|
+
if (SHELL_TOOLS.has(toolName))
|
|
544
|
+
return await checkShell(toolName, typeof input.command === 'string' ? input.command : '');
|
|
545
|
+
const rawPath = typeof input.path === 'string' && input.path !== '' ? input.path : '.';
|
|
546
|
+
return await checkFileTool(toolName, rawPath, ctx.cwd);
|
|
547
|
+
});
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
export default createMagoSkiExtension();
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Pi's resolveToCwd: Unicode spaces, leading "@", Windows shell paths, "~", file:// URLs, then resolve. */
|
|
2
|
+
export declare function piResolveToCwd(input: string, cwd: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Pi's `read` tool tries these spellings in order when the resolved path does not exist
|
|
5
|
+
* (macOS screenshot names, NFD, curly quotes) and opens the first that exists.
|
|
6
|
+
*/
|
|
7
|
+
export declare function piReadVariants(resolved: string): string[];
|
|
8
|
+
/** The path Pi's `read` will open: the first existing variant, or the resolved path. */
|
|
9
|
+
export declare function piReadTarget(resolved: string): string;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Mirrors how Pi 1.1's built-in tools turn a tool `path` argument into a file system path
|
|
2
|
+
// (dist/utils/paths.js normalizePath/resolvePath and dist/core/tools/path-utils.js), so the
|
|
3
|
+
// extension authorizes the same file Pi will actually open. Keep in sync when Pi changes.
|
|
4
|
+
import { existsSync } from 'node:fs';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
const UNICODE_SPACES = /[ - ]/gu;
|
|
9
|
+
/** Git Bash, MSYS, Cygwin and WSL drive paths, as Pi converts them on native Windows. */
|
|
10
|
+
function normalizeWindowsShellPath(filePath) {
|
|
11
|
+
if (!filePath.startsWith('/') || filePath.startsWith('//') || filePath.includes('\\'))
|
|
12
|
+
return filePath;
|
|
13
|
+
const match = /^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/iu.exec(filePath);
|
|
14
|
+
if (!match)
|
|
15
|
+
return filePath;
|
|
16
|
+
return `${match[1].toUpperCase()}:\\${match[2]?.replaceAll('/', '\\') ?? ''}`;
|
|
17
|
+
}
|
|
18
|
+
/** Pi's resolveToCwd: Unicode spaces, leading "@", Windows shell paths, "~", file:// URLs, then resolve. */
|
|
19
|
+
export function piResolveToCwd(input, cwd) {
|
|
20
|
+
let normalized = input.replace(UNICODE_SPACES, ' ');
|
|
21
|
+
if (normalized.startsWith('@'))
|
|
22
|
+
normalized = normalized.slice(1);
|
|
23
|
+
if (process.platform === 'win32')
|
|
24
|
+
normalized = normalizeWindowsShellPath(normalized);
|
|
25
|
+
if (normalized === '~') {
|
|
26
|
+
normalized = homedir();
|
|
27
|
+
}
|
|
28
|
+
else if (normalized.startsWith('~/') || (process.platform === 'win32' && normalized.startsWith('~\\'))) {
|
|
29
|
+
normalized = path.join(homedir(), normalized.slice(2));
|
|
30
|
+
}
|
|
31
|
+
else if (/^file:\/\//u.test(normalized)) {
|
|
32
|
+
try {
|
|
33
|
+
normalized = fileURLToPath(normalized);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
// Pi would throw too; leave the text so it is still matched lexically.
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return path.isAbsolute(normalized) ? path.resolve(normalized) : path.resolve(cwd, normalized);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Pi's `read` tool tries these spellings in order when the resolved path does not exist
|
|
43
|
+
* (macOS screenshot names, NFD, curly quotes) and opens the first that exists.
|
|
44
|
+
*/
|
|
45
|
+
export function piReadVariants(resolved) {
|
|
46
|
+
const amPm = resolved.replace(/ (AM|PM)\./giu, ' $1.');
|
|
47
|
+
const nfd = resolved.normalize('NFD');
|
|
48
|
+
const curly = resolved.replace(/'/gu, '’');
|
|
49
|
+
const nfdCurly = nfd.replace(/'/gu, '’');
|
|
50
|
+
return [...new Set([resolved, amPm, nfd, curly, nfdCurly])];
|
|
51
|
+
}
|
|
52
|
+
/** The path Pi's `read` will open: the first existing variant, or the resolved path. */
|
|
53
|
+
export function piReadTarget(resolved) {
|
|
54
|
+
return piReadVariants(resolved).find((candidate) => existsSync(candidate)) ?? resolved;
|
|
55
|
+
}
|