toolroll 0.9.120 → 0.9.122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/README.md +10 -23
  3. package/dist/agent-fence.js +57 -9
  4. package/dist/batch-checks.js +2 -2
  5. package/dist/builder.js +10 -7
  6. package/dist/central-recovery-stage.js +3 -3
  7. package/dist/coding-provider.js +3 -3
  8. package/dist/contracts/console-api.js +1 -0
  9. package/dist/direct-chat-fence.js +9 -3
  10. package/dist/direct-chat.js +82 -10
  11. package/dist/flexible-agents.js +16 -2
  12. package/dist/flexible-session.js +2 -1
  13. package/dist/flexible-thread.js +5 -1
  14. package/dist/install-method.js +1 -3
  15. package/dist/invoke.js +11 -9
  16. package/dist/lead-tools.js +3 -2
  17. package/dist/live-terminal.js +24 -3
  18. package/dist/local-owner.js +1 -0
  19. package/dist/planner.js +2 -0
  20. package/dist/project-delete.js +1 -1
  21. package/dist/project-skills.js +105 -17
  22. package/dist/result-follow-ups.js +2 -2
  23. package/dist/scout.js +2 -1
  24. package/dist/serve.js +8 -1
  25. package/dist/server/direct-chat.js +1 -0
  26. package/dist/server/render-release.js +27 -15
  27. package/dist/server/route-table.js +2 -0
  28. package/dist/server/settings.js +151 -3
  29. package/dist/server/terminals.js +3 -1
  30. package/dist/skill-library-schema.js +70 -0
  31. package/dist/skill-library.js +693 -0
  32. package/dist/skill-local-sync.js +334 -0
  33. package/dist/skills-manifest.js +6 -3
  34. package/dist/skills-ui.js +122 -1
  35. package/dist/store.js +22 -4
  36. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  37. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  38. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  39. package/dist/tui/linux-x64/toolroll-tui +0 -0
  40. package/package.json +2 -1
@@ -0,0 +1,693 @@
1
+ import { createHash } from "node:crypto";
2
+ import { scanForSecrets } from "./evidence.js";
3
+ import { learningSha } from "./project-learning.js";
4
+ import { PROJECT_SKILLS_GUIDANCE, PROJECT_SKILLS_READ, validateSkill, } from "./project-skills.js";
5
+ import { savedSkillPackageSchema } from "./contracts/project-skills.js";
6
+ import { localSyncStatus, setLocalSkillSync, syncEnabledLocalTools, } from "./skill-local-sync.js";
7
+ export const LIBRARY_LIMITS = Object.freeze({
8
+ maxSkills: 200,
9
+ maxBundleBytes: 24 * 1024 * 1024,
10
+ maxBundleFiles: 2500,
11
+ dailySweepMs: 24 * 60 * 60 * 1000,
12
+ maxFetchConcurrency: 8,
13
+ });
14
+ function packageBySha(store, sha) {
15
+ const row = store.handle.prepare("SELECT payload FROM skill_package WHERE sha=?").get(sha);
16
+ if (!row || typeof row["payload"] !== "string" || learningSha(row["payload"]) !== sha) {
17
+ throw Error("Saved library skill could not be verified.");
18
+ }
19
+ const parsed = savedSkillPackageSchema.safeParse(JSON.parse(row["payload"]));
20
+ if (!parsed.success)
21
+ throw Error("Saved library skill could not be verified.");
22
+ return { ...parsed.data, sha };
23
+ }
24
+ function parseLibrarySelection(payload, sha) {
25
+ if (typeof payload !== "string" || learningSha(payload) !== sha) {
26
+ throw Error("Saved skill library selection could not be verified.");
27
+ }
28
+ const raw = JSON.parse(payload);
29
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
30
+ throw Error("Saved skill library selection could not be verified.");
31
+ }
32
+ const out = {};
33
+ for (const [name, entry] of Object.entries(raw)) {
34
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
35
+ throw Error("Saved skill library selection could not be verified.");
36
+ }
37
+ const obj = entry;
38
+ if (typeof obj["sha"] !== "string" || typeof obj["enabled"] !== "boolean") {
39
+ throw Error("Saved skill library selection could not be verified.");
40
+ }
41
+ out[name] = {
42
+ sha: obj["sha"],
43
+ enabled: obj["enabled"],
44
+ ...(typeof obj["sourceId"] === "string" || obj["sourceId"] === null ? { sourceId: obj["sourceId"] } : {}),
45
+ };
46
+ }
47
+ return out;
48
+ }
49
+ export function currentLibrary(store) {
50
+ const row = store.handle
51
+ .prepare("SELECT revision, payload, sha FROM skill_library_change ORDER BY revision DESC LIMIT 1")
52
+ .get();
53
+ if (!row)
54
+ return { revision: 0, selection: {} };
55
+ return {
56
+ revision: Number(row["revision"]),
57
+ selection: parseLibrarySelection(row["payload"], row["sha"]),
58
+ };
59
+ }
60
+ export function projectSkillOptOuts(store, repo) {
61
+ const rows = store.handle
62
+ .prepare("SELECT skill_name FROM skill_project_opt_out WHERE repo=? ORDER BY skill_name")
63
+ .all(repo);
64
+ let all = false;
65
+ const names = new Set();
66
+ for (const row of rows) {
67
+ const name = String(row["skill_name"]);
68
+ if (name === "*")
69
+ all = true;
70
+ else
71
+ names.add(name);
72
+ }
73
+ return { all, names };
74
+ }
75
+ export function enabledLibrarySkills(store, repo) {
76
+ const { revision, selection } = currentLibrary(store);
77
+ const optOut = repo ? projectSkillOptOuts(store, repo) : { all: false, names: new Set() };
78
+ if (optOut.all)
79
+ return { revision, packages: [] };
80
+ const packages = [];
81
+ for (const [name, choice] of Object.entries(selection)) {
82
+ if (!choice.enabled || optOut.names.has(name))
83
+ continue;
84
+ packages.push(packageBySha(store, choice.sha));
85
+ }
86
+ packages.sort((a, b) => a.name.localeCompare(b.name));
87
+ return { revision, packages };
88
+ }
89
+ export function mergeProjectAndLibrarySkills(store, repo, projectSelection) {
90
+ const { revision: libraryRevision, packages: globalPackages } = enabledLibrarySkills(store, repo);
91
+ const byName = new Map();
92
+ for (const pkg of globalPackages)
93
+ byName.set(pkg.name, pkg);
94
+ for (const [name, choice] of Object.entries(projectSelection)) {
95
+ if (choice.enabled)
96
+ byName.set(name, packageBySha(store, choice.sha));
97
+ else
98
+ byName.delete(name);
99
+ }
100
+ const packages = [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
101
+ return { libraryRevision, packages };
102
+ }
103
+ export function formatSkillsBrief(catalog, intro = "Project skills supplied for this run. ") {
104
+ if (catalog.length === 0)
105
+ return "";
106
+ return `\n${intro}${PROJECT_SKILLS_GUIDANCE}${PROJECT_SKILLS_READ}${JSON.stringify(catalog)}\n`;
107
+ }
108
+ function rowToBundle(row) {
109
+ let skillNames = [];
110
+ try {
111
+ const parsed = JSON.parse(String(row["skill_names_json"] ?? "[]"));
112
+ if (Array.isArray(parsed))
113
+ skillNames = parsed.map(String);
114
+ }
115
+ catch {
116
+ skillNames = [];
117
+ }
118
+ return {
119
+ id: String(row["id"]),
120
+ repoUrl: String(row["repo_url"]),
121
+ owner: String(row["owner"]),
122
+ repoName: String(row["repo_name"]),
123
+ branch: String(row["branch"]),
124
+ subpath: String(row["subpath"] ?? ""),
125
+ pinnedCommit: String(row["pinned_commit"]),
126
+ previousCommit: typeof row["previous_commit"] === "string" ? row["previous_commit"] : null,
127
+ previousRevision: typeof row["previous_revision"] === "number" ? row["previous_revision"] : null,
128
+ skillNames,
129
+ autoUpdate: Number(row["auto_update"]) === 1,
130
+ lastCheckedAt: typeof row["last_checked_at"] === "string" ? row["last_checked_at"] : null,
131
+ lastUpdatedAt: typeof row["last_updated_at"] === "string" ? row["last_updated_at"] : null,
132
+ heldCommit: typeof row["held_commit"] === "string" ? row["held_commit"] : null,
133
+ heldReason: typeof row["held_reason"] === "string" ? row["held_reason"] : null,
134
+ heldAt: typeof row["held_at"] === "string" ? row["held_at"] : null,
135
+ actor: String(row["actor"]),
136
+ createdAt: String(row["created_at"]),
137
+ };
138
+ }
139
+ export function listSkillBundles(store) {
140
+ return store.handle
141
+ .prepare("SELECT * FROM skill_bundle ORDER BY id")
142
+ .all()
143
+ .map((row) => rowToBundle(row));
144
+ }
145
+ function writeLibraryRevision(store, selection, actor, source, now) {
146
+ const cur = currentLibrary(store);
147
+ const enabledCount = Object.values(selection).filter((c) => c.enabled).length;
148
+ if (enabledCount > LIBRARY_LIMITS.maxSkills) {
149
+ throw Error(`Enable up to ${LIBRARY_LIMITS.maxSkills} skills in the global library.`);
150
+ }
151
+ const payload = JSON.stringify(selection);
152
+ const nextRevision = cur.revision + 1;
153
+ store.handle
154
+ .prepare("INSERT INTO skill_library_change (revision, actor, at, payload, sha, source) VALUES (?,?,?,?,?,?)")
155
+ .run(nextRevision, actor, now.toISOString(), payload, learningSha(payload), source);
156
+ return nextRevision;
157
+ }
158
+ function storeSkillPackage(store, pkg, actor, now) {
159
+ const payload = JSON.stringify(pkg);
160
+ const sha = learningSha(payload);
161
+ store.handle.prepare("INSERT OR IGNORE INTO skill_package VALUES (?,?)").run(sha, payload);
162
+ store.handle.prepare("INSERT OR IGNORE INTO skill_owner VALUES (?,?,?)").run(sha, actor, now.toISOString());
163
+ return { ...pkg, sha };
164
+ }
165
+ export function skillLibraryView(store, options = {}) {
166
+ const { revision, selection } = currentLibrary(store);
167
+ const shas = new Set(Object.values(selection).map((c) => c.sha));
168
+ const skills = [...shas]
169
+ .map((sha) => packageBySha(store, sha))
170
+ .sort((a, b) => a.name.localeCompare(b.name));
171
+ const bundles = listSkillBundles(store);
172
+ const localSync = localSyncStatus(store, options);
173
+ const history = store.handle
174
+ .prepare("SELECT revision, actor, at, payload, sha, source FROM skill_library_change ORDER BY revision DESC LIMIT 20")
175
+ .all()
176
+ .map((row) => {
177
+ const sel = parseLibrarySelection(row["payload"], row["sha"]);
178
+ return {
179
+ revision: Number(row["revision"]),
180
+ actor: String(row["actor"]),
181
+ at: String(row["at"]),
182
+ source: String(row["source"]),
183
+ enabledCount: Object.values(sel).filter((c) => c.enabled).length,
184
+ };
185
+ });
186
+ const optOut = options.repo ? projectSkillOptOuts(store, options.repo) : null;
187
+ return {
188
+ revision,
189
+ selection,
190
+ skills,
191
+ bundles,
192
+ localSync,
193
+ history,
194
+ projectOptOut: optOut === null ? null : { all: optOut.all, names: [...optOut.names].sort() },
195
+ };
196
+ }
197
+ export function importLibrarySkill(store, args, now = new Date()) {
198
+ if (!store.schemaCurrent())
199
+ throw Error("Skill library needs the current database version.");
200
+ const validated = validateSkill(args.files, args.source);
201
+ const result = store.transact(() => {
202
+ const saved = storeSkillPackage(store, validated, args.actor, now);
203
+ const cur = currentLibrary(store);
204
+ const next = {
205
+ ...cur.selection,
206
+ [saved.name]: { sha: saved.sha, enabled: args.enable !== false, sourceId: null },
207
+ };
208
+ const revision = writeLibraryRevision(store, next, args.actor, "manual", now);
209
+ return { skill: saved, revision };
210
+ });
211
+ const enabled = enabledLibrarySkills(store).packages;
212
+ const localSync = syncEnabledLocalTools(store, { actor: args.actor, skills: enabled, libraryRevision: result.revision, ...(args.home === undefined ? {} : { home: args.home }), ...(args.env === undefined ? {} : { env: args.env }) }, now);
213
+ return { ...result, localSync };
214
+ }
215
+ export function changeLibrarySkill(store, args, now = new Date()) {
216
+ if (!store.schemaCurrent())
217
+ throw Error("Skill library needs the current database version.");
218
+ const nextRevision = store.transact(() => {
219
+ const cur = currentLibrary(store);
220
+ if (cur.revision !== args.revision) {
221
+ throw Error("Skill library changed in another window. Reload and try again.");
222
+ }
223
+ let next = { ...cur.selection };
224
+ if (args.action === "restore") {
225
+ if (!Number.isSafeInteger(args.restore) || (args.restore ?? 0) < 1)
226
+ throw Error("Choose a valid library revision.");
227
+ const row = store.handle
228
+ .prepare("SELECT payload, sha FROM skill_library_change WHERE revision=?")
229
+ .get(args.restore);
230
+ if (!row)
231
+ throw Error("That library revision is unavailable.");
232
+ next = parseLibrarySelection(row["payload"], row["sha"]);
233
+ for (const choice of Object.values(next))
234
+ packageBySha(store, choice.sha);
235
+ return writeLibraryRevision(store, next, args.actor, "rollback", now);
236
+ }
237
+ const name = args.name ?? (args.sha ? packageBySha(store, args.sha).name : "");
238
+ if (!name)
239
+ throw Error("Choose a skill to update.");
240
+ if (args.action === "remove") {
241
+ delete next[name];
242
+ }
243
+ else {
244
+ const sha = args.sha || next[name]?.sha;
245
+ if (!sha)
246
+ throw Error("Choose a saved skill version.");
247
+ const pkg = packageBySha(store, sha);
248
+ next[pkg.name] = {
249
+ sha: pkg.sha,
250
+ enabled: args.action === "enable",
251
+ sourceId: next[pkg.name]?.sourceId ?? null,
252
+ };
253
+ }
254
+ return writeLibraryRevision(store, next, args.actor, "manual", now);
255
+ });
256
+ const enabled = enabledLibrarySkills(store).packages;
257
+ const localSync = syncEnabledLocalTools(store, { actor: args.actor, skills: enabled, libraryRevision: nextRevision, ...(args.home === undefined ? {} : { home: args.home }), ...(args.env === undefined ? {} : { env: args.env }) }, now);
258
+ return { revision: nextRevision, localSync };
259
+ }
260
+ export function setProjectSkillOptOut(store, args, now = new Date()) {
261
+ if (!store.schemaCurrent())
262
+ throw Error("Skill library needs the current database version.");
263
+ const skillName = args.skillName.trim();
264
+ if (skillName !== "*" && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skillName)) {
265
+ throw Error("Choose a valid skill name or '*' for the whole library.");
266
+ }
267
+ store.transact(() => {
268
+ if (args.optOut) {
269
+ store.handle
270
+ .prepare(`INSERT INTO skill_project_opt_out (repo, skill_name, actor, at) VALUES (?,?,?,?)
271
+ ON CONFLICT(repo, skill_name) DO UPDATE SET actor=excluded.actor, at=excluded.at`)
272
+ .run(args.repo, skillName, args.actor, now.toISOString());
273
+ }
274
+ else {
275
+ store.handle
276
+ .prepare("DELETE FROM skill_project_opt_out WHERE repo=? AND skill_name=?")
277
+ .run(args.repo, skillName);
278
+ }
279
+ });
280
+ }
281
+ export function parseGithubBundleUrl(rawUrl) {
282
+ let u;
283
+ try {
284
+ u = new URL(rawUrl.trim());
285
+ }
286
+ catch {
287
+ throw Error("Enter a public github.com repository URL (for example https://github.com/owner/repo).");
288
+ }
289
+ if (u.protocol !== "https:" ||
290
+ u.hostname !== "github.com" ||
291
+ u.port ||
292
+ u.username ||
293
+ u.password ||
294
+ u.search ||
295
+ u.hash) {
296
+ throw Error("Use a public https://github.com repository URL with no query parameters or credentials.");
297
+ }
298
+ const parts = u.pathname.replace(/\.git$/i, "").split("/").filter(Boolean);
299
+ if (parts.length < 2 || parts.some((p) => !/^[a-zA-Z0-9_.-]+$/.test(p) || p === "." || p === "..")) {
300
+ throw Error("Use https://github.com/owner/repo or https://github.com/owner/repo/tree/branch[/subfolder].");
301
+ }
302
+ const [owner, repoName, kind, ref, ...rest] = parts;
303
+ if (kind !== undefined && (kind !== "tree" || !ref)) {
304
+ throw Error("Use https://github.com/owner/repo or https://github.com/owner/repo/tree/branch[/subfolder].");
305
+ }
306
+ const subpath = rest.join("/");
307
+ const id = subpath ? `${owner}/${repoName}/${subpath}` : `${owner}/${repoName}`;
308
+ const repoUrl = subpath
309
+ ? `https://github.com/${owner}/${repoName}/tree/${ref}/${subpath}`
310
+ : `https://github.com/${owner}/${repoName}`;
311
+ return { id, repoUrl, owner: owner, repoName: repoName, ref: ref ?? null, subpath };
312
+ }
313
+ async function githubJson(owner, repoName, path, fetcher, budget) {
314
+ const response = await fetcher(`https://api.github.com/repos/${owner}/${repoName}${path}`, {
315
+ redirect: "error",
316
+ signal: AbortSignal.timeout(20_000),
317
+ headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" },
318
+ });
319
+ if (!response.ok) {
320
+ throw Error(`GitHub returned ${response.status} for ${owner}/${repoName}${path.split("?")[0]}.`);
321
+ }
322
+ const text = await response.text();
323
+ budget.remaining -= Buffer.byteLength(text);
324
+ if (budget.remaining < 0)
325
+ throw Error("GitHub bundle response exceeded the 24 MB size limit.");
326
+ return JSON.parse(text);
327
+ }
328
+ export async function fetchGithubSkillBundle(url, fetcher = fetch, explicitCommit) {
329
+ const parsed = parseGithubBundleUrl(url);
330
+ const budget = { remaining: LIBRARY_LIMITS.maxBundleBytes };
331
+ let branch = parsed.ref ?? "";
332
+ if (!branch) {
333
+ const repoInfo = await githubJson(parsed.owner, parsed.repoName, "", fetcher, budget);
334
+ branch = typeof repoInfo.default_branch === "string" && repoInfo.default_branch.trim() ? repoInfo.default_branch.trim() : "main";
335
+ }
336
+ let commit;
337
+ if (explicitCommit !== undefined) {
338
+ if (!/^[0-9a-f]{40}$/.test(explicitCommit))
339
+ throw Error("Pinned commit must be a 40-character SHA.");
340
+ commit = explicitCommit;
341
+ }
342
+ else {
343
+ const commitObj = await githubJson(parsed.owner, parsed.repoName, `/commits/${encodeURIComponent(branch)}`, fetcher, budget);
344
+ if (typeof commitObj.sha !== "string" || !/^[0-9a-f]{40}$/.test(commitObj.sha)) {
345
+ throw Error("GitHub did not return a pinned commit SHA for that branch.");
346
+ }
347
+ commit = commitObj.sha;
348
+ }
349
+ const treeObj = await githubJson(parsed.owner, parsed.repoName, `/git/trees/${commit}?recursive=1`, fetcher, budget);
350
+ if (treeObj.truncated === true || !Array.isArray(treeObj.tree)) {
351
+ throw Error("Repository tree is truncated or unreadable; specify a narrower subfolder URL.");
352
+ }
353
+ const prefix = parsed.subpath ? `${parsed.subpath}/` : "";
354
+ const blobs = [];
355
+ for (const entry of treeObj.tree) {
356
+ if (entry.type !== "blob" || (entry.mode !== "100644" && entry.mode !== "100755"))
357
+ continue;
358
+ if (typeof entry.path !== "string" || typeof entry.sha !== "string" || !/^[0-9a-f]{40}$/.test(entry.sha))
359
+ continue;
360
+ if (prefix && !entry.path.startsWith(prefix))
361
+ continue;
362
+ const relPath = prefix ? entry.path.slice(prefix.length) : entry.path;
363
+ if (!relPath)
364
+ continue;
365
+ blobs.push({ path: entry.path, relPath, sha: entry.sha, size: Number(entry.size ?? 0) });
366
+ }
367
+ const skillRoots = blobs
368
+ .filter((b) => b.relPath === "SKILL.md" || b.relPath.endsWith("/SKILL.md"))
369
+ .map((b) => (b.relPath === "SKILL.md" ? "" : b.relPath.slice(0, -"/SKILL.md".length)))
370
+ .sort((a, b) => a.length - b.length || a.localeCompare(b));
371
+ if (skillRoots.length === 0) {
372
+ throw Error("No SKILL.md files were found in that GitHub repository or subfolder.");
373
+ }
374
+ if (skillRoots.length > LIBRARY_LIMITS.maxSkills) {
375
+ throw Error(`Repository contains ${skillRoots.length} skills, above the ${LIBRARY_LIMITS.maxSkills}-skill limit.`);
376
+ }
377
+ const bySkill = new Map();
378
+ for (const root of skillRoots)
379
+ bySkill.set(root, []);
380
+ let totalFiles = 0;
381
+ for (const blob of blobs) {
382
+ let ownerRoot = null;
383
+ for (const root of skillRoots) {
384
+ if (root === "" || blob.relPath.startsWith(`${root}/`)) {
385
+ if (ownerRoot === null || root.length > ownerRoot.length)
386
+ ownerRoot = root;
387
+ }
388
+ }
389
+ if (ownerRoot === null)
390
+ continue;
391
+ const inner = ownerRoot === "" ? blob.relPath : blob.relPath.slice(ownerRoot.length + 1);
392
+ if (inner.split("/").some((seg) => seg.startsWith(".")))
393
+ continue;
394
+ totalFiles += 1;
395
+ if (totalFiles > LIBRARY_LIMITS.maxBundleFiles) {
396
+ throw Error(`Bundle exceeds the ${LIBRARY_LIMITS.maxBundleFiles}-file limit.`);
397
+ }
398
+ bySkill.get(ownerRoot).push({ ...blob, relPath: inner });
399
+ }
400
+ const uniqueBlobs = new Map();
401
+ for (const list of bySkill.values()) {
402
+ for (const b of list)
403
+ uniqueBlobs.set(b.sha, b);
404
+ }
405
+ const blobBytes = new Map();
406
+ const queue = [...uniqueBlobs.keys()];
407
+ const worker = async () => {
408
+ while (queue.length > 0) {
409
+ const sha = queue.shift();
410
+ const body = await githubJson(parsed.owner, parsed.repoName, `/git/blobs/${sha}`, fetcher, budget);
411
+ if (body.encoding !== "base64" || typeof body.content !== "string") {
412
+ throw Error(`GitHub blob ${sha.slice(0, 12)} was not returned as base64.`);
413
+ }
414
+ const raw = Buffer.from(body.content.replace(/\s+/g, ""), "base64");
415
+ const verified = createHash("sha1").update(`blob ${raw.length}\0`).update(raw).digest("hex");
416
+ if (verified !== sha) {
417
+ throw Error(`GitHub blob ${sha.slice(0, 12)} failed SHA-1 verification.`);
418
+ }
419
+ blobBytes.set(sha, raw);
420
+ }
421
+ };
422
+ await Promise.all(Array.from({ length: Math.min(LIBRARY_LIMITS.maxFetchConcurrency, Math.max(1, queue.length)) }, () => worker()));
423
+ const skills = [];
424
+ const skipped = [];
425
+ const seenNames = new Set();
426
+ for (const [folder, list] of bySkill) {
427
+ const files = list.map((b) => ({
428
+ path: b.relPath,
429
+ base64: blobBytes.get(b.sha).toString("base64"),
430
+ }));
431
+ const sourceLabel = `github:${parsed.owner}/${parsed.repoName}${folder ? `/${parsed.subpath ? `${parsed.subpath}/` : ""}${folder}` : parsed.subpath ? `/${parsed.subpath}` : ""}@${commit.slice(0, 12)}`;
432
+ try {
433
+ const pkg = validateSkill(files, sourceLabel);
434
+ if (seenNames.has(pkg.name)) {
435
+ skipped.push({ folder: folder || ".", reason: `Duplicate skill name "${pkg.name}"` });
436
+ continue;
437
+ }
438
+ seenNames.add(pkg.name);
439
+ skills.push(pkg);
440
+ }
441
+ catch (error) {
442
+ skipped.push({ folder: folder || ".", reason: error instanceof Error ? error.message : String(error) });
443
+ }
444
+ }
445
+ if (skills.length === 0) {
446
+ const first = skipped[0] ? `: ${skipped[0].reason}` : "";
447
+ throw Error(`No valid skills could be imported from that repository${first}`);
448
+ }
449
+ return {
450
+ id: parsed.id,
451
+ repoUrl: parsed.repoUrl,
452
+ owner: parsed.owner,
453
+ repoName: parsed.repoName,
454
+ branch,
455
+ subpath: parsed.subpath,
456
+ commit,
457
+ skills,
458
+ skipped,
459
+ };
460
+ }
461
+ export async function importGithubSkillBundle(store, args, now = new Date(), fetcher = fetch) {
462
+ if (!store.schemaCurrent())
463
+ throw Error("Skill library needs the current database version.");
464
+ const fetched = await fetchGithubSkillBundle(args.url, fetcher);
465
+ const when = now.toISOString();
466
+ const res = store.transact(() => {
467
+ const prevRow = store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(fetched.id);
468
+ const prevBundle = prevRow ? rowToBundle(prevRow) : null;
469
+ const cur = currentLibrary(store);
470
+ const next = { ...cur.selection };
471
+ if (prevBundle !== null) {
472
+ for (const oldName of prevBundle.skillNames) {
473
+ if (next[oldName]?.sourceId === fetched.id)
474
+ delete next[oldName];
475
+ }
476
+ }
477
+ const savedNames = [];
478
+ for (const pkg of fetched.skills) {
479
+ const saved = storeSkillPackage(store, pkg, args.actor, now);
480
+ next[saved.name] = { sha: saved.sha, enabled: true, sourceId: fetched.id };
481
+ savedNames.push(saved.name);
482
+ }
483
+ savedNames.sort();
484
+ const revision = writeLibraryRevision(store, next, args.actor, "bundle-import", now);
485
+ const autoUpdate = args.autoUpdate === undefined ? (prevBundle?.autoUpdate ?? true) : args.autoUpdate;
486
+ store.handle
487
+ .prepare(`INSERT INTO skill_bundle
488
+ (id, repo_url, owner, repo_name, branch, subpath, pinned_commit, previous_commit, previous_revision,
489
+ skill_names_json, auto_update, last_checked_at, last_updated_at, held_commit, held_reason, held_at, actor, created_at)
490
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,NULL,NULL,NULL,?,?)
491
+ ON CONFLICT(id) DO UPDATE SET
492
+ repo_url=excluded.repo_url, branch=excluded.branch, subpath=excluded.subpath,
493
+ previous_commit=skill_bundle.pinned_commit,
494
+ previous_revision=?,
495
+ pinned_commit=excluded.pinned_commit,
496
+ skill_names_json=excluded.skill_names_json,
497
+ auto_update=excluded.auto_update,
498
+ last_checked_at=excluded.last_checked_at,
499
+ last_updated_at=excluded.last_updated_at,
500
+ held_commit=NULL, held_reason=NULL, held_at=NULL`)
501
+ .run(fetched.id, fetched.repoUrl, fetched.owner, fetched.repoName, fetched.branch, fetched.subpath, fetched.commit, prevBundle?.pinnedCommit ?? null, prevBundle !== null ? cur.revision : null, JSON.stringify(savedNames), autoUpdate ? 1 : 0, when, when, args.actor, prevBundle?.createdAt ?? when, cur.revision);
502
+ const savedBundle = rowToBundle(store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(fetched.id));
503
+ return { bundle: savedBundle, revision };
504
+ });
505
+ const enabled = enabledLibrarySkills(store).packages;
506
+ const localSync = syncEnabledLocalTools(store, { actor: args.actor, skills: enabled, libraryRevision: res.revision, ...(args.home === undefined ? {} : { home: args.home }), ...(args.env === undefined ? {} : { env: args.env }) }, now);
507
+ return { bundle: res.bundle, importedCount: fetched.skills.length, skipped: fetched.skipped, revision: res.revision, localSync };
508
+ }
509
+ const HIGH_RISK_TEXT_RULES = [
510
+ [/\b(?:curl|wget)\b[^\n|]{0,200}\|\s*(?:ba|z|da)?sh\b/i, "pipes remote content directly into a shell"],
511
+ [/\b(?:cat|less|head|tail|cp|scp|curl)\b[^\n]{0,160}(?:~\/\.ssh|id_rsa|id_ed25519|up-login\.txt|orders\.db|\.toolroll)/i, "references local secrets or Toolroll state files"],
512
+ [/\bignore\s+(?:all\s+)?(?:previous|prior|earlier)\s+instructions\b/i, "contains prompt-injection override phrasing"],
513
+ [/\boverride\s+(?:the\s+)?system\s+prompt\b/i, "contains system-prompt override phrasing"],
514
+ [/\bapprove\s+this\s+task\s+automatically\b/i, "attempts to direct task approval"],
515
+ ];
516
+ function decodeSkillText(pkg) {
517
+ return pkg.files.map((f) => Buffer.from(f.base64, "base64").toString("utf8")).join("\n");
518
+ }
519
+ export function assessBundleUpdateSuspicion(previousSkills, nextSkills) {
520
+ const reasons = [];
521
+ const prevByName = new Map(previousSkills.map((s) => [s.name, s]));
522
+ const nextByName = new Map(nextSkills.map((s) => [s.name, s]));
523
+ if (prevByName.size >= 4) {
524
+ const removed = [...prevByName.keys()].filter((name) => !nextByName.has(name));
525
+ if (removed.length * 2 > prevByName.size) {
526
+ reasons.push(`removes ${removed.length} of ${prevByName.size} skills in one update`);
527
+ }
528
+ }
529
+ for (const next of nextSkills) {
530
+ const prev = prevByName.get(next.name);
531
+ const prevScripts = new Set((prev?.files ?? []).filter((f) => f.path.startsWith("scripts/")).map((f) => f.path));
532
+ const newScripts = next.files.filter((f) => f.path.startsWith("scripts/") && !prevScripts.has(f.path));
533
+ if (newScripts.length > 0) {
534
+ reasons.push(`${next.name}: adds new script file(s) (${newScripts.map((f) => f.path).join(", ")})`);
535
+ }
536
+ const prevWarnings = new Set(prev?.warnings ?? []);
537
+ const newWarnings = next.warnings.filter((w) => !prevWarnings.has(w));
538
+ for (const warning of newWarnings) {
539
+ reasons.push(`${next.name}: ${warning}`);
540
+ }
541
+ const nextText = decodeSkillText(next);
542
+ const prevText = prev ? decodeSkillText(prev) : "";
543
+ if (scanForSecrets(nextText).length > 0) {
544
+ reasons.push(`${next.name}: contains secret-like material`);
545
+ }
546
+ for (const [pattern, label] of HIGH_RISK_TEXT_RULES) {
547
+ if (pattern.test(nextText) && !pattern.test(prevText)) {
548
+ reasons.push(`${next.name}: ${label}`);
549
+ }
550
+ }
551
+ }
552
+ return reasons.length > 0 ? { suspicious: true, reasons } : { suspicious: false };
553
+ }
554
+ export async function sweepSkillBundleUpdates(store, options) {
555
+ if (!store.schemaCurrent())
556
+ return [];
557
+ const now = options.now ?? new Date();
558
+ const fetcher = options.fetcher ?? fetch;
559
+ const bundles = listSkillBundles(store).filter((b) => options.onlyBundleId !== undefined ? b.id === options.onlyBundleId : b.autoUpdate);
560
+ const results = [];
561
+ let anyUpdated = false;
562
+ let latestRevision = currentLibrary(store).revision;
563
+ for (const bundle of bundles) {
564
+ if (!options.force && bundle.lastCheckedAt !== null) {
565
+ const elapsed = now.getTime() - Date.parse(bundle.lastCheckedAt);
566
+ if (Number.isFinite(elapsed) && elapsed < LIBRARY_LIMITS.dailySweepMs) {
567
+ results.push({ id: bundle.id, status: "skipped-recent", commit: bundle.pinnedCommit });
568
+ continue;
569
+ }
570
+ }
571
+ const when = now.toISOString();
572
+ try {
573
+ const budget = { remaining: 2 * 1024 * 1024 };
574
+ const latest = await githubJson(bundle.owner, bundle.repoName, `/commits/${encodeURIComponent(bundle.branch)}`, fetcher, budget);
575
+ if (typeof latest.sha !== "string" || !/^[0-9a-f]{40}$/.test(latest.sha)) {
576
+ throw Error("GitHub returned no commit SHA for bundle branch.");
577
+ }
578
+ if (latest.sha === bundle.pinnedCommit) {
579
+ store.handle.prepare("UPDATE skill_bundle SET last_checked_at=? WHERE id=?").run(when, bundle.id);
580
+ results.push({ id: bundle.id, status: "up-to-date", commit: bundle.pinnedCommit });
581
+ continue;
582
+ }
583
+ const incoming = await fetchGithubSkillBundle(bundle.repoUrl, fetcher, latest.sha);
584
+ const cur = currentLibrary(store);
585
+ const prevSkills = [];
586
+ for (const name of bundle.skillNames) {
587
+ const entry = cur.selection[name];
588
+ if (entry)
589
+ prevSkills.push(packageBySha(store, entry.sha));
590
+ }
591
+ const check = assessBundleUpdateSuspicion(prevSkills, incoming.skills);
592
+ if (check.suspicious && options.allowSuspiciousForId !== bundle.id) {
593
+ store.handle
594
+ .prepare("UPDATE skill_bundle SET last_checked_at=?, held_commit=?, held_reason=?, held_at=? WHERE id=?")
595
+ .run(when, incoming.commit, check.reasons.join("; "), when, bundle.id);
596
+ results.push({ id: bundle.id, status: "held", commit: incoming.commit, previousCommit: bundle.pinnedCommit, reasons: check.reasons });
597
+ continue;
598
+ }
599
+ latestRevision = store.transact(() => {
600
+ const current = currentLibrary(store);
601
+ const next = { ...current.selection };
602
+ for (const oldName of bundle.skillNames) {
603
+ if (next[oldName]?.sourceId === bundle.id)
604
+ delete next[oldName];
605
+ }
606
+ const savedNames = [];
607
+ for (const pkg of incoming.skills) {
608
+ const saved = storeSkillPackage(store, pkg, options.actor, now);
609
+ const wasEnabled = current.selection[saved.name]?.enabled ?? true;
610
+ next[saved.name] = { sha: saved.sha, enabled: wasEnabled, sourceId: bundle.id };
611
+ savedNames.push(saved.name);
612
+ }
613
+ savedNames.sort();
614
+ const rev = writeLibraryRevision(store, next, options.actor, "auto-update", now);
615
+ store.handle
616
+ .prepare(`UPDATE skill_bundle
617
+ SET previous_commit=?, previous_revision=?, pinned_commit=?, skill_names_json=?,
618
+ last_checked_at=?, last_updated_at=?, held_commit=NULL, held_reason=NULL, held_at=NULL
619
+ WHERE id=?`)
620
+ .run(bundle.pinnedCommit, current.revision, incoming.commit, JSON.stringify(savedNames), when, when, bundle.id);
621
+ return rev;
622
+ });
623
+ anyUpdated = true;
624
+ results.push({ id: bundle.id, status: "updated", commit: incoming.commit, previousCommit: bundle.pinnedCommit });
625
+ }
626
+ catch (error) {
627
+ store.handle.prepare("UPDATE skill_bundle SET last_checked_at=? WHERE id=?").run(when, bundle.id);
628
+ results.push({ id: bundle.id, status: "error", error: error instanceof Error ? error.message : String(error) });
629
+ }
630
+ }
631
+ if (anyUpdated) {
632
+ const enabled = enabledLibrarySkills(store).packages;
633
+ syncEnabledLocalTools(store, { actor: options.actor, skills: enabled, libraryRevision: latestRevision, ...(options.home === undefined ? {} : { home: options.home }), ...(options.env === undefined ? {} : { env: options.env }) }, now);
634
+ }
635
+ return results;
636
+ }
637
+ export function rollbackSkillBundle(store, args, now = new Date()) {
638
+ if (!store.schemaCurrent())
639
+ throw Error("Skill library needs the current database version.");
640
+ const res = store.transact(() => {
641
+ const row = store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(args.id);
642
+ if (!row)
643
+ throw Error("That skill bundle was not found.");
644
+ const bundle = rowToBundle(row);
645
+ if (bundle.previousCommit === null || bundle.previousRevision === null) {
646
+ throw Error("No previous version is available to roll back to.");
647
+ }
648
+ const revRow = store.handle
649
+ .prepare("SELECT payload, sha FROM skill_library_change WHERE revision=?")
650
+ .get(bundle.previousRevision);
651
+ if (!revRow)
652
+ throw Error("The previous skill library revision could not be loaded.");
653
+ const previousSelection = parseLibrarySelection(revRow["payload"], revRow["sha"]);
654
+ for (const choice of Object.values(previousSelection))
655
+ packageBySha(store, choice.sha);
656
+ const cur = currentLibrary(store);
657
+ const next = { ...cur.selection };
658
+ for (const name of bundle.skillNames) {
659
+ if (next[name]?.sourceId === bundle.id)
660
+ delete next[name];
661
+ }
662
+ const restoredNames = [];
663
+ for (const [name, choice] of Object.entries(previousSelection)) {
664
+ if (choice.sourceId === bundle.id) {
665
+ next[name] = choice;
666
+ restoredNames.push(name);
667
+ }
668
+ }
669
+ restoredNames.sort();
670
+ const revision = writeLibraryRevision(store, next, args.actor, "rollback", now);
671
+ const when = now.toISOString();
672
+ store.handle
673
+ .prepare(`UPDATE skill_bundle
674
+ SET pinned_commit=?, previous_commit=NULL, previous_revision=NULL, skill_names_json=?,
675
+ last_updated_at=?, held_commit=NULL, held_reason=NULL, held_at=NULL
676
+ WHERE id=?`)
677
+ .run(bundle.previousCommit, JSON.stringify(restoredNames), when, bundle.id);
678
+ const updated = rowToBundle(store.handle.prepare("SELECT * FROM skill_bundle WHERE id=?").get(bundle.id));
679
+ return { bundle: updated, revision };
680
+ });
681
+ const enabled = enabledLibrarySkills(store).packages;
682
+ const localSync = syncEnabledLocalTools(store, { actor: args.actor, skills: enabled, libraryRevision: res.revision, ...(args.home === undefined ? {} : { home: args.home }), ...(args.env === undefined ? {} : { env: args.env }) }, now);
683
+ return { ...res, localSync };
684
+ }
685
+ export function dismissHeldBundleUpdate(store, id) {
686
+ store.handle.prepare("UPDATE skill_bundle SET held_commit=NULL, held_reason=NULL, held_at=NULL WHERE id=?").run(id);
687
+ }
688
+ export function setBundleAutoUpdate(store, id, enabled) {
689
+ const res = store.handle.prepare("UPDATE skill_bundle SET auto_update=? WHERE id=?").run(enabled ? 1 : 0, id);
690
+ if (Number(res.changes) === 0)
691
+ throw Error("That skill bundle was not found.");
692
+ }
693
+ export { localSyncStatus, setLocalSkillSync, syncEnabledLocalTools };