Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(skill,mcp): scan and batch-import from other agent tools
PI-Desktop5348c21befd7
diff --git a/apps/desktop/electron/main/importers/agent-mcp-scan.ts b/apps/desktop/electron/main/importers/agent-mcp-scan.tsnew file mode 100644index 000000000..f79dd2afa--- /dev/null+++ b/apps/desktop/electron/main/importers/agent-mcp-scan.ts@@ -0,0 +1,570 @@+/**+ * Scan third-party AI-tool config files for MCP server definitions.+ *+ * Every source produces `McpCandidate` records; ids and shapes are normalized+ * enough for the UI to display them, but the actual host-core admission gates+ * still run at upsert time. Failures during read/parse become `sources[].error`+ * so the UI can show one row per source instead of dropping the entry.+ */+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { mcpImportId } from "@pi-desktop/shared";++export type McpSourceKind =+ | "claude-desktop"+ | "claude-code"+ | "cursor-global"+ | "cursor-project"+ | "codex"+ | "opencode"+ | "chatgpt-desktop";++export interface McpCandidate {+ source: McpSourceKind;+ sourcePath: string;+ id: string;+ rawKey: string;+ label?: string;+ description?: string;+ transport: "stdio" | "http";+ command?: string;+ args?: string[];+ env?: Record<string, string>;+ url?: string;+ headers?: Record<string, string>;+ disabled?: boolean;+ warnings: string[];+}++export interface McpSourceReport {+ kind: McpSourceKind;+ path: string;+ exists: boolean;+ error?: string;+ count: number;+}++export interface McpScanResult {+ candidates: McpCandidate[];+ sources: McpSourceReport[];+}++export interface McpScanOptions {+ projectPath?: string;+ homeDir?: string;+ platform?: NodeJS.Platform;+ env?: NodeJS.ProcessEnv;+}++async function readText(filePath: string): Promise<{ text: string | null; error?: string }> {+ try {+ const text = await fs.readFile(filePath, "utf8");+ return { text };+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === "ENOENT") return { text: null };+ return { text: null, error: `${code ?? "ERR"}: ${(err as Error).message}` };+ }+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return !!value && typeof value === "object" && !Array.isArray(value);+}++function stringMap(value: unknown): Record<string, string> | undefined {+ if (!isRecord(value)) return undefined;+ const out: Record<string, string> = {};+ for (const [k, v] of Object.entries(value)) {+ if (typeof v === "string") out[k] = v;+ else if (typeof v === "number" || typeof v === "boolean") out[k] = String(v);+ }+ return out;+}++function stringList(value: unknown): string[] | undefined {+ if (!Array.isArray(value)) return undefined;+ return value.filter((entry): entry is string => typeof entry === "string");+}++/**+ * Turn one config entry into a candidate. The rules mirror `parseMcpImport` in+ * `@pi-desktop/shared` but produce the richer scan shape and never throw.+ */+function toCandidate(+ source: McpSourceKind,+ sourcePath: string,+ rawKey: string,+ index: number,+ raw: Record<string, unknown>,+): McpCandidate {+ const warnings: string[] = [];+ const id = mcpImportId(rawKey, index);+ const label =+ typeof raw.label === "string" && raw.label.trim()+ ? raw.label.trim()+ : typeof raw.name === "string" && raw.name.trim()+ ? raw.name.trim()+ : id;+ const description =+ typeof raw.description === "string" && raw.description.trim()+ ? raw.description.trim()+ : undefined;++ const url = typeof raw.url === "string" ? raw.url.trim() : "";+ const command = typeof raw.command === "string" ? raw.command.trim() : "";+ const declared =+ typeof raw.type === "string"+ ? raw.type.toLowerCase()+ : typeof raw.transport === "string"+ ? raw.transport.toLowerCase()+ : "";+ const declaredSse = declared.includes("sse");+ if (declaredSse) warnings.push("declared sse mapped to http");+ const wantsHttp = url ? true : declared.includes("http") || declaredSse;+ const disabled = raw.disabled === true || raw.enabled === false ? true : undefined;++ if (wantsHttp) {+ if (!url) warnings.push("http server missing url");+ else if (!/^https?:\/\//i.test(url)) warnings.push("url is not http(s)");+ return {+ source,+ sourcePath,+ id,+ rawKey,+ label,+ description,+ transport: "http",+ url: url || undefined,+ headers: stringMap(raw.headers),+ disabled,+ warnings,+ };+ }++ if (!command) warnings.push("stdio server missing command");+ return {+ source,+ sourcePath,+ id,+ rawKey,+ label,+ description,+ transport: "stdio",+ command: command || undefined,+ args: stringList(raw.args) ?? [],+ env: stringMap(raw.env) ?? {},+ disabled,+ warnings,+ };+}++function dedupeById(candidates: McpCandidate[]): McpCandidate[] {+ const seen = new Set<string>();+ const out: McpCandidate[] = [];+ for (const cand of candidates) {+ if (seen.has(cand.id)) continue;+ seen.add(cand.id);+ out.push(cand);+ }+ return out;+}++interface MapScan {+ candidates: McpCandidate[];+ count: number;+}++function scanServerMap(+ source: McpSourceKind,+ sourcePath: string,+ map: Record<string, unknown>,+): MapScan {+ const collected: McpCandidate[] = [];+ let index = 0;+ for (const [key, value] of Object.entries(map)) {+ if (!isRecord(value)) continue;+ collected.push(toCandidate(source, sourcePath, key, index, value));+ index += 1;+ }+ const deduped = dedupeById(collected);+ return { candidates: deduped, count: deduped.length };+}++function parseJson(text: string): { value: unknown | null; error?: string } {+ try {+ return { value: JSON.parse(text) as unknown };+ } catch (err) {+ return { value: null, error: `invalid json: ${(err as Error).message}` };+ }+}++async function scanJsonMcpServers(+ source: McpSourceKind,+ filePath: string,+ container: (root: Record<string, unknown>) => Record<string, unknown> | null,+): Promise<{ report: McpSourceReport; candidates: McpCandidate[] }> {+ const report: McpSourceReport = { kind: source, path: filePath, exists: false, count: 0 };+ const { text, error } = await readText(filePath);+ if (error) {+ report.error = error;+ return { report, candidates: [] };+ }+ if (text == null) return { report, candidates: [] };+ report.exists = true;+ const { value, error: parseErr } = parseJson(text);+ if (parseErr) {+ report.error = parseErr;+ return { report, candidates: [] };+ }+ if (!isRecord(value)) {+ report.error = "root is not an object";+ return { report, candidates: [] };+ }+ const map = container(value);+ if (!map) return { report, candidates: [] };+ const { candidates, count } = scanServerMap(source, filePath, map);+ report.count = count;+ return { report, candidates };+}++async function scanClaudeDesktop(+ home: string,+ platform: NodeJS.Platform,+ env: NodeJS.ProcessEnv,+): Promise<{ report: McpSourceReport; candidates: McpCandidate[] }> {+ const filePath = claudeDesktopConfigPath(home, platform, env);+ return scanJsonMcpServers("claude-desktop", filePath, (root) =>+ isRecord(root.mcpServers) ? root.mcpServers : null,+ );+}++function claudeDesktopConfigPath(+ home: string,+ platform: NodeJS.Platform,+ env: NodeJS.ProcessEnv,+): string {+ if (platform === "darwin") {+ return path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");+ }+ if (platform === "win32") {+ const appdata = env.APPDATA && env.APPDATA.trim() ? env.APPDATA : path.join(home, "AppData", "Roaming");+ return path.join(appdata, "Claude", "claude_desktop_config.json");+ }+ const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.trim() ? env.XDG_CONFIG_HOME : path.join(home, ".config");+ return path.join(xdg, "Claude", "claude_desktop_config.json");+}++/**+ * Claude Code writes MCP servers to either `~/.claude.json` (the older layout)+ * or `~/.claude/settings.json`. When both exist, the settings file wins for+ * shared keys — it is the one the CLI writes today.+ */+async function scanClaudeCode(+ home: string,+): Promise<{ reports: McpSourceReport[]; candidates: McpCandidate[] }> {+ const legacyPath = path.join(home, ".claude.json");+ const settingsPath = path.join(home, ".claude", "settings.json");+ const [legacy, settings] = await Promise.all([+ scanJsonMcpServers("claude-code", legacyPath, (root) =>+ isRecord(root.mcpServers) ? root.mcpServers : null,+ ),+ scanJsonMcpServers("claude-code", settingsPath, (root) =>+ isRecord(root.mcpServers) ? root.mcpServers : null,+ ),+ ]);+ const merged = new Map<string, McpCandidate>();+ for (const cand of legacy.candidates) merged.set(cand.id, cand);+ for (const cand of settings.candidates) merged.set(cand.id, cand);+ return {+ reports: [legacy.report, settings.report],+ candidates: [...merged.values()],+ };+}++async function scanCursorGlobal(home: string) {+ const filePath = path.join(home, ".cursor", "mcp.json");+ return scanJsonMcpServers("cursor-global", filePath, (root) =>+ isRecord(root.mcpServers) ? root.mcpServers : null,+ );+}++async function scanCursorProject(projectPath: string) {+ const filePath = path.join(projectPath, ".cursor", "mcp.json");+ return scanJsonMcpServers("cursor-project", filePath, (root) =>+ isRecord(root.mcpServers) ? root.mcpServers : null,+ );+}++async function scanOpencode(+ home: string,+ env: NodeJS.ProcessEnv,+): Promise<{ report: McpSourceReport; candidates: McpCandidate[] }> {+ const xdg = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.trim() ? env.XDG_CONFIG_HOME : path.join(home, ".config");+ const primary = path.join(xdg, "opencode", "opencode.json");+ const fallback = path.join(home, ".opencode.json");+ const { text: primaryText, error: primaryErr } = await readText(primary);+ const chosenPath = primaryText != null || primaryErr ? primary : fallback;+ const report: McpSourceReport = { kind: "opencode", path: chosenPath, exists: false, count: 0 };+ let text: string | null;+ let err: string | undefined;+ if (primaryText != null || primaryErr) {+ text = primaryText;+ err = primaryErr;+ } else {+ const second = await readText(fallback);+ text = second.text;+ err = second.error;+ }+ if (err) {+ report.error = err;+ return { report, candidates: [] };+ }+ if (text == null) return { report, candidates: [] };+ report.exists = true;+ const { value, error: parseErr } = parseJson(text);+ if (parseErr) {+ report.error = parseErr;+ return { report, candidates: [] };+ }+ if (!isRecord(value)) {+ report.error = "root is not an object";+ return { report, candidates: [] };+ }+ const container = isRecord(value.mcp) ? value.mcp : null;+ if (!container) return { report, candidates: [] };+ const collected: McpCandidate[] = [];+ let index = 0;+ for (const [key, raw] of Object.entries(container)) {+ if (!isRecord(raw)) continue;+ const mapped = opencodeToCandidate("opencode", chosenPath, key, index, raw);+ collected.push(mapped);+ index += 1;+ }+ const deduped = dedupeById(collected);+ report.count = deduped.length;+ return { report, candidates: deduped };+}++/**+ * opencode uses `type: "local" | "remote"` and packs argv into a single+ * `command: [cmd, ...args]` array. Map it to the common candidate shape.+ */+function opencodeToCandidate(+ source: McpSourceKind,+ sourcePath: string,+ rawKey: string,+ index: number,+ raw: Record<string, unknown>,+): McpCandidate {+ const typeStr = typeof raw.type === "string" ? raw.type.toLowerCase() : "";+ const remote = typeStr === "remote" || typeof raw.url === "string";+ if (remote) {+ return toCandidate(source, sourcePath, rawKey, index, {+ ...raw,+ type: "http",+ url: typeof raw.url === "string" ? raw.url : "",+ headers: raw.headers,+ });+ }+ let command = "";+ let args: string[] = [];+ const cmdField = raw.command;+ if (Array.isArray(cmdField)) {+ const parts = cmdField.filter((v): v is string => typeof v === "string");+ command = parts[0] ?? "";+ args = parts.slice(1);+ } else if (typeof cmdField === "string") {+ command = cmdField;+ args = stringList(raw.args) ?? [];+ }+ return toCandidate(source, sourcePath, rawKey, index, {+ ...raw,+ type: "stdio",+ command,+ args,+ });+}++/**+ * Minimal TOML parser for codex `[mcp_servers.<id>]` sections. Handles the+ * subset actually used: string, bool, int, string array, inline env table.+ * Anything unrecognized is skipped rather than erroring — a real TOML crate+ * would just be extra risk here.+ */+export function parseCodexMcpToml(text: string): Record<string, Record<string, unknown>> {+ const result: Record<string, Record<string, unknown>> = {};+ const lines = text.split(/\r?\n/);+ let current: Record<string, unknown> | null = null;+ for (let raw of lines) {+ const line = raw.replace(/^\uFEFF/, "").trim();+ if (!line || line.startsWith("#")) continue;+ const section = /^\[([^\]]+)\]$/.exec(line);+ if (section) {+ const name = section[1].trim();+ const match = /^mcp_servers\.(.+)$/.exec(name);+ if (match) {+ const id = match[1].replace(/^["']|["']$/g, "").trim();+ current = {};+ result[id] = current;+ } else {+ current = null;+ }+ continue;+ }+ if (!current) continue;+ const eq = line.indexOf("=");+ if (eq === -1) continue;+ const key = line.slice(0, eq).trim();+ const value = stripInlineComment(line.slice(eq + 1).trim());+ current[key] = parseTomlValue(value);+ }+ return result;+}++function stripInlineComment(value: string): string {+ // Don't strip `#` that lives inside a string; simple state machine is enough.+ let inSingle = false;+ let inDouble = false;+ for (let i = 0; i < value.length; i += 1) {+ const ch = value[i];+ if (ch === "'" && !inDouble) inSingle = !inSingle;+ else if (ch === '"' && !inSingle) inDouble = !inDouble;+ else if (ch === "#" && !inSingle && !inDouble) return value.slice(0, i).trim();+ }+ return value.trim();+}++function parseTomlValue(text: string): unknown {+ if (!text.length) return "";+ const first = text[0];+ if (first === '"' || first === "'") {+ const end = text.lastIndexOf(first);+ if (end > 0) return text.slice(1, end);+ return text.slice(1);+ }+ if (first === "[") {+ const end = text.lastIndexOf("]");+ const inner = end > 0 ? text.slice(1, end) : text.slice(1);+ return splitTopLevel(inner).map((chunk) => parseTomlValue(chunk.trim()));+ }+ if (first === "{") {+ const end = text.lastIndexOf("}");+ const inner = end > 0 ? text.slice(1, end) : text.slice(1);+ const obj: Record<string, unknown> = {};+ for (const part of splitTopLevel(inner)) {+ const trimmed = part.trim();+ if (!trimmed) continue;+ const eq = trimmed.indexOf("=");+ if (eq === -1) continue;+ const k = trimmed.slice(0, eq).trim().replace(/^["']|["']$/g, "");+ obj[k] = parseTomlValue(trimmed.slice(eq + 1).trim());+ }+ return obj;+ }+ if (text === "true") return true;+ if (text === "false") return false;+ if (/^-?\d+$/.test(text)) return Number(text);+ return text;+}++function splitTopLevel(text: string): string[] {+ const out: string[] = [];+ let depth = 0;+ let inSingle = false;+ let inDouble = false;+ let start = 0;+ for (let i = 0; i < text.length; i += 1) {+ const ch = text[i];+ if (ch === "'" && !inDouble) inSingle = !inSingle;+ else if (ch === '"' && !inSingle) inDouble = !inDouble;+ else if (!inSingle && !inDouble) {+ if (ch === "[" || ch === "{") depth += 1;+ else if (ch === "]" || ch === "}") depth -= 1;+ else if (ch === "," && depth === 0) {+ out.push(text.slice(start, i));+ start = i + 1;+ }+ }+ }+ const tail = text.slice(start);+ if (tail.trim() || out.length) out.push(tail);+ return out;+}++async function scanCodex(+ home: string,+): Promise<{ report: McpSourceReport; candidates: McpCandidate[] }> {+ const filePath = path.join(home, ".codex", "config.toml");+ const report: McpSourceReport = { kind: "codex", path: filePath, exists: false, count: 0 };+ const { text, error } = await readText(filePath);+ if (error) {+ report.error = error;+ return { report, candidates: [] };+ }+ if (text == null) return { report, candidates: [] };+ report.exists = true;+ let parsed: Record<string, Record<string, unknown>>;+ try {+ parsed = parseCodexMcpToml(text);+ } catch (err) {+ report.error = `toml parse failed: ${(err as Error).message}`;+ return { report, candidates: [] };+ }+ const collected: McpCandidate[] = [];+ let index = 0;+ for (const [key, raw] of Object.entries(parsed)) {+ collected.push(toCandidate("codex", filePath, key, index, raw));+ index += 1;+ }+ const deduped = dedupeById(collected);+ report.count = deduped.length;+ return { report, candidates: deduped };+}++async function scanChatgptDesktop(): Promise<{+ report: McpSourceReport;+ candidates: McpCandidate[];+}> {+ // ChatGPT Desktop stores MCP config in a proprietary, undocumented location+ // (varies by channel and platform). Ship the source row so the UI can render+ // "not detected" without silently omitting it, and revisit when the layout+ // stabilizes.+ return {+ report: { kind: "chatgpt-desktop", path: "", exists: false, count: 0 },+ candidates: [],+ };+}++export async function scanExternalMcp(opts: McpScanOptions = {}): Promise<McpScanResult> {+ const home = opts.homeDir ?? os.homedir();+ const platform = opts.platform ?? process.platform;+ const env = opts.env ?? process.env;++ const [claudeDesktop, claudeCode, cursorGlobal, opencode, codex, chatgpt] = await Promise.all([+ scanClaudeDesktop(home, platform, env),+ scanClaudeCode(home),+ scanCursorGlobal(home),+ scanOpencode(home, env),+ scanCodex(home),+ scanChatgptDesktop(),+ ]);++ const parts: Array<{ reports: McpSourceReport[]; candidates: McpCandidate[] }> = [+ { reports: [claudeDesktop.report], candidates: claudeDesktop.candidates },+ { reports: claudeCode.reports, candidates: claudeCode.candidates },+ { reports: [cursorGlobal.report], candidates: cursorGlobal.candidates },+ { reports: [opencode.report], candidates: opencode.candidates },+ { reports: [codex.report], candidates: codex.candidates },+ { reports: [chatgpt.report], candidates: chatgpt.candidates },+ ];++ if (opts.projectPath) {+ const cursorProject = await scanCursorProject(opts.projectPath);+ parts.push({ reports: [cursorProject.report], candidates: cursorProject.candidates });+ }++ const candidates = parts.flatMap((p) => p.candidates);+ const sources = parts.flatMap((p) => p.reports);+ return { candidates, sources };+}diff --git a/apps/desktop/electron/main/importers/agent-skill-scan.ts b/apps/desktop/electron/main/importers/agent-skill-scan.tsnew file mode 100644index 000000000..a7ca071d0--- /dev/null+++ b/apps/desktop/electron/main/importers/agent-skill-scan.ts@@ -0,0 +1,257 @@+/**+ * Scan third-party AI-tool skill directories for Skill definitions.+ *+ * Two on-disk shapes are recognized: a bare `<id>.md` file, and the+ * Claude-style `<name>/SKILL.md` directory. Both carry a YAML frontmatter+ * block with at least `name` and `description`. Anything unreadable or empty+ * is dropped, but the source row still reports it via `count` and `error`.+ */+import { promises as fs, type Stats } from "node:fs";+import os from "node:os";+import path from "node:path";++export type SkillSourceKind = "claude-user" | "claude-project" | "pi-user" | "pi-project";++export interface SkillCandidate {+ source: SkillSourceKind;+ sourcePath: string;+ rootDir?: string;+ shape: "file" | "dir";+ id: string;+ name: string;+ description: string;+ bytes: number;+ warnings: string[];+}++export interface SkillSourceReport {+ kind: SkillSourceKind;+ path: string;+ exists: boolean;+ error?: string;+ count: number;+}++export interface SkillScanResult {+ candidates: SkillCandidate[];+ sources: SkillSourceReport[];+}++export interface SkillScanOptions {+ projectPath?: string;+ homeDir?: string;+ env?: NodeJS.ProcessEnv;+}++const MAX_SKILL_BYTES = 128 * 1024;+const MAX_CANDIDATES_PER_SOURCE = 128;++function slugify(input: string): string {+ const cleaned = input+ .normalize("NFKD")+ .replace(/[^a-zA-Z0-9_-]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .toLowerCase();+ return cleaned.slice(0, 64) || "skill";+}++/**+ * Minimal frontmatter reader — enough for the `--- key: value ---` blocks+ * Claude and PI both emit. A real YAML parser would be strictly bigger risk+ * for the two fields we actually read.+ */+export function readFrontmatter(text: string): {+ data: Record<string, string>;+ body: string;+ ok: boolean;+} {+ const stripped = text.replace(/^\uFEFF/, "");+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(stripped);+ if (!match) return { data: {}, body: stripped, ok: false };+ const data: Record<string, string> = {};+ for (const rawLine of match[1].split(/\r?\n/)) {+ const line = rawLine.replace(/^\s*#.*$/, "").trim();+ if (!line) continue;+ const idx = line.indexOf(":");+ if (idx === -1) continue;+ const key = line.slice(0, idx).trim();+ let value = line.slice(idx + 1).trim();+ const hash = findUnquotedHash(value);+ if (hash !== -1) value = value.slice(0, hash).trim();+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {+ value = value.slice(1, -1);+ }+ if (key) data[key] = value;+ }+ return { data, body: match[2] ?? "", ok: true };+}++function findUnquotedHash(value: string): number {+ let inSingle = false;+ let inDouble = false;+ for (let i = 0; i < value.length; i += 1) {+ const ch = value[i];+ if (ch === "'" && !inDouble) inSingle = !inSingle;+ else if (ch === '"' && !inSingle) inDouble = !inDouble;+ else if (ch === "#" && !inSingle && !inDouble) return i;+ }+ return -1;+}++async function statSafe(target: string): Promise<Stats | null> {+ try {+ return await fs.stat(target);+ } catch {+ return null;+ }+}++async function listDir(dir: string): Promise<{ entries: string[]; error?: string; exists: boolean }> {+ try {+ const entries = await fs.readdir(dir);+ return { entries, exists: true };+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === "ENOENT") return { entries: [], exists: false };+ return { entries: [], exists: false, error: `${code ?? "ERR"}: ${(err as Error).message}` };+ }+}++async function readSkillFile(+ filePath: string,+): Promise<{ text: string | null; bytes: number; error?: string }> {+ try {+ const stat = await fs.stat(filePath);+ if (!stat.isFile()) return { text: null, bytes: 0 };+ if (stat.size > MAX_SKILL_BYTES) {+ return { text: null, bytes: stat.size, error: `skill exceeds ${MAX_SKILL_BYTES}B limit` };+ }+ const text = await fs.readFile(filePath, "utf8");+ return { text, bytes: stat.size };+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === "ENOENT") return { text: null, bytes: 0 };+ return { text: null, bytes: 0, error: `${code ?? "ERR"}: ${(err as Error).message}` };+ }+}++function extractCandidate(+ source: SkillSourceKind,+ sourcePath: string,+ rootDir: string | undefined,+ shape: "file" | "dir",+ fallbackId: string,+ text: string,+ bytes: number,+): SkillCandidate | null {+ const warnings: string[] = [];+ const parsed = readFrontmatter(text);+ if (!parsed.ok) warnings.push("missing frontmatter");+ if (!parsed.body.trim()) return null;+ const nameRaw = parsed.data.name?.trim() ?? "";+ const description = parsed.data.description?.trim() ?? "";+ if (!nameRaw) warnings.push("frontmatter missing name");+ if (!description) warnings.push("frontmatter missing description");+ const name = nameRaw || fallbackId;+ if (source === "pi-user" || source === "pi-project") {+ warnings.push("already in current registry");+ }+ return {+ source,+ sourcePath,+ rootDir,+ shape,+ id: slugify(nameRaw || fallbackId),+ name,+ description,+ bytes,+ warnings,+ };+}++async function scanDirectory(+ source: SkillSourceKind,+ dir: string,+): Promise<{ report: SkillSourceReport; candidates: SkillCandidate[] }> {+ const report: SkillSourceReport = { kind: source, path: dir, exists: false, count: 0 };+ const listing = await listDir(dir);+ if (listing.error) {+ report.error = listing.error;+ return { report, candidates: [] };+ }+ if (!listing.exists) return { report, candidates: [] };+ report.exists = true;++ const candidates: SkillCandidate[] = [];+ const errors: string[] = [];+ for (const entry of listing.entries.sort()) {+ if (candidates.length >= MAX_CANDIDATES_PER_SOURCE) break;+ const abs = path.join(dir, entry);+ const stat = await statSafe(abs);+ if (!stat) continue;+ if (stat.isFile() && entry.toLowerCase().endsWith(".md")) {+ const fallbackId = entry.replace(/\.md$/i, "");+ const { text, bytes, error } = await readSkillFile(abs);+ if (error) {+ errors.push(`${entry}: ${error}`);+ continue;+ }+ if (text == null) continue;+ const cand = extractCandidate(source, abs, undefined, "file", fallbackId, text, bytes);+ if (cand) candidates.push(cand);+ continue;+ }+ if (stat.isDirectory()) {+ const skillPath = path.join(abs, "SKILL.md");+ const { text, bytes, error } = await readSkillFile(skillPath);+ if (error) {+ errors.push(`${entry}: ${error}`);+ continue;+ }+ if (text == null) continue;+ const cand = extractCandidate(source, skillPath, abs, "dir", entry, text, bytes);+ if (cand) candidates.push(cand);+ }+ }++ const deduped: SkillCandidate[] = [];+ const seen = new Set<string>();+ for (const cand of candidates) {+ if (seen.has(cand.id)) continue;+ seen.add(cand.id);+ deduped.push(cand);+ }+ report.count = deduped.length;+ if (errors.length) report.error = errors.join("; ");+ return { report, candidates: deduped };+}++function claudeUserDir(home: string): string {+ return path.join(home, ".claude", "skills");+}++function piUserDir(home: string, env: NodeJS.ProcessEnv): string {+ const override = env.PI_DESKTOP_AGENTS_DIR;+ if (override && override.trim()) return path.join(override, "skills");+ return path.join(home, ".agents", "skills");+}++export async function scanExternalSkills(opts: SkillScanOptions = {}): Promise<SkillScanResult> {+ const home = opts.homeDir ?? os.homedir();+ const env = opts.env ?? process.env;+ const parts: Array<{ report: SkillSourceReport; candidates: SkillCandidate[] }> = [];++ parts.push(await scanDirectory("claude-user", claudeUserDir(home)));+ if (opts.projectPath) {+ parts.push(await scanDirectory("claude-project", path.join(opts.projectPath, ".claude", "skills")));+ }+ parts.push(await scanDirectory("pi-user", piUserDir(home, env)));+ if (opts.projectPath) {+ parts.push(await scanDirectory("pi-project", path.join(opts.projectPath, ".agents", "skills")));+ }++ return {+ candidates: parts.flatMap((p) => p.candidates),+ sources: parts.map((p) => p.report),+ };+}diff --git a/apps/desktop/electron/main/ipc/agent-import-ipc.ts b/apps/desktop/electron/main/ipc/agent-import-ipc.tsnew file mode 100644index 000000000..c531c6d81--- /dev/null+++ b/apps/desktop/electron/main/ipc/agent-import-ipc.ts@@ -0,0 +1,287 @@+/**+ * Batch import handlers for third-party AI-tool skills and MCP servers.+ *+ * `*Scan` handlers wrap the on-disk scanners in the `importers/` directory and+ * translate their failures into a `sources[]` row so the panel never receives a+ * rejected promise. `*Run` handlers replay each candidate through the host RPC+ * one at a time and bucket the results into `imported / skipped / failed`, so a+ * single bad entry does not abort the batch.+ *+ * `runSkillImport` and `runMcpImport` are exported so the unit test can drive+ * them against a stub host without booting a real sidecar.+ */+import { IPC } from "@pi-desktop/shared";+import type { HostProcess } from "../host-process";+import {+ scanExternalMcp,+ type McpCandidate,+ type McpScanResult,+ type McpSourceKind,+} from "../importers/agent-mcp-scan";+import {+ scanExternalSkills,+ type SkillCandidate,+ type SkillScanResult,+ type SkillSourceKind,+} from "../importers/agent-skill-scan";+import type { IpcRegistrar } from "./types";++export type HostCall = <T = unknown>(method: string, params?: unknown) => Promise<T>;++export type AgentImportIpcDependencies = {+ registrar: IpcRegistrar;+ getHost: () => HostProcess | null;+ sendToRenderer: (channel: string, payload?: unknown) => void;+ refreshUserMcp?: (projectPath?: string | null) => Promise<unknown>;+ currentWorkspacePath?: () => string | null;+};++export interface SkillImportRunItem {+ source: SkillSourceKind;+ sourcePath: string;+ shape: "file" | "dir";+ rootDir?: string;+ id: string;+ name: string;+ description?: string;+}++export interface SkillImportRunPayload {+ level: "global" | "project";+ projectPath?: string;+ mode?: "copy" | "link";+ items: SkillImportRunItem[];+}++export interface SkillImportRunResult {+ imported: Array<{ item: SkillImportRunItem; skill: unknown }>;+ skipped: Array<{ item: SkillImportRunItem; reason: string }>;+ failed: Array<{ item: SkillImportRunItem; error: string }>;+}++export interface McpImportRunItem {+ source: McpSourceKind;+ sourcePath: string;+ id: string;+ rawKey: string;+ label?: string;+ description?: string;+ transport: "stdio" | "http";+ command?: string;+ args?: string[];+ env?: Record<string, string>;+ url?: string;+ headers?: Record<string, string>;+ disabled?: boolean;+}++export interface McpImportRunPayload {+ items: McpImportRunItem[];+}++export interface McpImportRunResult {+ imported: Array<{ item: McpImportRunItem; server: unknown }>;+ skipped: Array<{ item: McpImportRunItem; reason: string }>;+ failed: Array<{ item: McpImportRunItem; error: string }>;+}++/** True when a host error message is the "same name/id already imported" case. */+function isExistsError(message: string): boolean {+ return /already exists/i.test(message);+}++function describeError(error: unknown): string {+ if (error instanceof Error) return error.message;+ try {+ return String(error);+ } catch {+ return "unknown error";+ }+}++/**+ * Replay each skill candidate through `skills.import`. One failure never stops+ * the batch; anything that reads like "already at this level" is skipped, and+ * every other RPC error is captured with its message.+ */+export async function runSkillImport(+ hostCall: HostCall,+ payload: SkillImportRunPayload,+): Promise<SkillImportRunResult> {+ const mode = payload.mode ?? "copy";+ const level = payload.level;+ const projectPath = payload.projectPath;+ const result: SkillImportRunResult = {+ imported: [],+ skipped: [],+ failed: [],+ };+ for (const item of payload.items) {+ // Directory shape: `rootDir` is the folder that contains SKILL.md, and the+ // scanner leaves it filled. Fall back to the source path only when it is+ // missing so a partly-formed candidate still reports through the failed+ // bucket rather than silently pointing at the SKILL.md file itself.+ const path = item.shape === "dir" ? item.rootDir ?? item.sourcePath : item.sourcePath;+ const params: Record<string, unknown> = {+ path,+ id: item.id,+ name: item.name,+ level,+ mode,+ shape: item.shape,+ ...(item.description !== undefined ? { description: item.description } : {}),+ ...(projectPath !== undefined ? { projectPath } : {}),+ };+ try {+ const res = await hostCall<{ skill: unknown }>("skills.import", params);+ result.imported.push({ item, skill: res?.skill });+ } catch (error) {+ const message = describeError(error);+ if (isExistsError(message)) {+ result.skipped.push({ item, reason: "exists" });+ } else {+ result.failed.push({ item, error: message });+ }+ }+ }+ return result;+}++/**+ * Assemble each MCP candidate into an `mcp.upsert` server payload. `disabled`+ * is stripped from the payload — host-core's `McpConfig` does not accept it —+ * and applied separately through `mcp.setEnabled` after a successful import so+ * the runtime never briefly starts a server the user asked to keep off.+ */+export async function runMcpImport(+ hostCall: HostCall,+ payload: McpImportRunPayload,+): Promise<McpImportRunResult> {+ const result: McpImportRunResult = {+ imported: [],+ skipped: [],+ failed: [],+ };+ for (const item of payload.items) {+ const server: Record<string, unknown> = {+ id: item.id,+ transport: item.transport,+ ...(item.label !== undefined ? { label: item.label } : {}),+ ...(item.description !== undefined ? { description: item.description } : {}),+ ...(item.command !== undefined ? { command: item.command } : {}),+ ...(item.args !== undefined ? { args: item.args } : {}),+ ...(item.env !== undefined ? { env: item.env } : {}),+ ...(item.url !== undefined ? { url: item.url } : {}),+ ...(item.headers !== undefined ? { headers: item.headers } : {}),+ };+ try {+ const res = await hostCall<{ server: unknown }>("mcp.upsert", { server });+ if (item.disabled === true) {+ try {+ await hostCall("mcp.setEnabled", { id: item.id, enabled: false });+ } catch (error) {+ // Turning off failed after the server was written; report it as a+ // failure so the user is not left with an enabled server they did+ // not want, even though the write itself succeeded.+ result.failed.push({ item, error: describeError(error) });+ continue;+ }+ }+ result.imported.push({ item, server: res?.server });+ } catch (error) {+ const message = describeError(error);+ if (isExistsError(message)) {+ result.skipped.push({ item, reason: "exists" });+ } else {+ result.failed.push({ item, error: message });+ }+ }+ }+ return result;+}++/**+ * A synthetic `sources[]` row for a scan whose top-level call threw. The panel+ * knows how to render one; a rejected IPC promise it has nowhere to display.+ *+ * `kind: "error"` sits outside the scanners' own unions on purpose — no real+ * source ever emits it — so the row is distinguishable from a normal source+ * that happened to be missing on disk.+ */+type ScanErrorReport = {+ candidates: [];+ sources: [{ kind: "error"; path: string; exists: false; error: string; count: 0 }];+};++function scanErrorReport(error: unknown): ScanErrorReport {+ return {+ candidates: [],+ sources: [+ {+ kind: "error",+ path: "",+ exists: false,+ error: describeError(error),+ count: 0,+ },+ ],+ };+}++/** Register the four `*importScan` / `*importRun` handlers. */+export function registerAgentImportIpc({+ registrar,+ getHost,+ sendToRenderer,+ refreshUserMcp,+ currentWorkspacePath,+}: AgentImportIpcDependencies): void {+ registrar.handle(+ IPC.invoke.skillImportScan,+ async ({ projectPath }: { projectPath?: string } = {}) => {+ try {+ return await scanExternalSkills({ projectPath });+ } catch (error) {+ return scanErrorReport(error);+ }+ },+ );++ registrar.handle(IPC.invoke.skillImportRun, async (payload: SkillImportRunPayload) => {+ const host = getHost();+ if (!host) throw new Error("host unavailable");+ const hostCall: HostCall = (method, params) => host.call(method, params);+ const result = await runSkillImport(hostCall, payload);+ if (result.imported.length) {+ sendToRenderer(IPC.event.pluginChanged, { reason: "skill" });+ }+ return result;+ });++ registrar.handle(+ IPC.invoke.mcpImportScan,+ async ({ projectPath }: { projectPath?: string } = {}) => {+ try {+ return await scanExternalMcp({ projectPath });+ } catch (error) {+ return scanErrorReport(error);+ }+ },+ );++ registrar.handle(IPC.invoke.mcpImportRun, async (payload: McpImportRunPayload) => {+ const host = getHost();+ if (!host) throw new Error("host unavailable");+ const hostCall: HostCall = (method, params) => host.call(method, params);+ const result = await runMcpImport(hostCall, payload);+ if (result.imported.length) {+ if (refreshUserMcp && currentWorkspacePath) {+ await refreshUserMcp(currentWorkspacePath()).catch(() => undefined);+ }+ sendToRenderer(IPC.event.pluginChanged, { reason: "mcp" });+ }+ return result;+ });+}++export type { McpCandidate, McpScanResult, SkillCandidate, SkillScanResult };diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex 99fd44992..2d4347fe5 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -20,6 +20,7 @@ import { registerScheduledIpc } from "./scheduled-ipc";import { registerSessionIpc } from "./session-ipc";import { registerSettingsIpc } from "./settings-ipc";import { registerSkillsIpc } from "./skills-ipc";+import { registerAgentImportIpc } from "./agent-import-ipc";import { fetchSkillMarketDocument, searchSkillMarket } from "../skill-market-catalog";import { registerWindowIpc } from "./window-ipc";import { createComposerTemplateLoader, registerWorkspaceIpc } from "./workspace-ipc";@@ -370,6 +371,15 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {});+ registerAgentImportIpc({+ registrar,+ getHost,+ sendToRenderer,+ refreshUserMcp,+ currentWorkspacePath,+ });++registerPluginUiIpc({registrar,plugins,diff --git a/apps/desktop/electron/main/ipc/skills-ipc.ts b/apps/desktop/electron/main/ipc/skills-ipc.tsindex 1a19102e3..9184b93ed 100644--- a/apps/desktop/electron/main/ipc/skills-ipc.ts+++ b/apps/desktop/electron/main/ipc/skills-ipc.ts@@ -158,22 +158,45 @@ export function registerSkillsIpc({return res;});- /** Import exactly one markdown file into the selected capability directory. */- handle(IPC.invoke.skillImport, async (query: Partial<AgentCapabilityQuery> = {}) => {- if (!host) throw new Error("host unavailable");- const picked = await dialog.showOpenDialog({- title: "Import skill",- properties: ["openFile"],- filters: [{ name: "Markdown", extensions: ["md", "markdown"] }],- });- if (picked.canceled || !picked.filePaths[0]) return { canceled: true };- const res = await host.call("skills.import", {- path: picked.filePaths[0],- ...query,- });- sendToRenderer(IPC.event.pluginChanged,{ reason: "skill" });- return res;- });+ /**+ * Import exactly one Skill from a native picker. The default single-file+ * picker is kept so existing callers keep working; a caller may also ask for+ * a directory picker (Claude-style `<name>/SKILL.md` skills) or pass+ * `mode: "link"` for a symlink import instead of a copy. The value is+ * forwarded to `skills.import` intact so host-core still owns the policy.+ */+ handle(+ IPC.invoke.skillImport,+ async (+ query: Partial<AgentCapabilityQuery> & {+ sourceKind?: "file" | "dir";+ mode?: "copy" | "link";+ } = {},+ ) => {+ if (!host) throw new Error("host unavailable");+ const { sourceKind, mode, ...rest } = query;+ const picked =+ sourceKind === "dir"+ ? await dialog.showOpenDialog({+ title: "Import skill",+ properties: ["openDirectory"],+ })+ : await dialog.showOpenDialog({+ title: "Import skill",+ properties: ["openFile"],+ filters: [{ name: "Markdown", extensions: ["md", "markdown"] }],+ });+ if (picked.canceled || !picked.filePaths[0]) return { canceled: true };+ const res = await host.call("skills.import", {+ path: picked.filePaths[0],+ ...(sourceKind === "dir" ? { shape: "dir" } : {}),+ ...(mode ? { mode } : {}),+ ...rest,+ });+ sendToRenderer(IPC.event.pluginChanged, { reason: "skill" });+ return res;+ },+ );handle(IPC.invoke.skillUpdate,diff --git a/apps/desktop/electron/test/agent-import-ipc.test.mjs b/apps/desktop/electron/test/agent-import-ipc.test.mjsnew file mode 100644index 000000000..31951ddea--- /dev/null+++ b/apps/desktop/electron/test/agent-import-ipc.test.mjs@@ -0,0 +1,172 @@+/**+ * Unit tests for the batch skill / MCP importers.+ *+ * The IPC handlers themselves are thin wrappers around `runSkillImport` and+ * `runMcpImport`; the pure functions carry the bucketing logic, so the test+ * drives them with a stub host-call and checks the three-way partition. A+ * real sidecar never boots — no filesystem, no RPC transport, no host.+ */+import assert from "node:assert/strict";+import { dirname, join } from "node:path";+import { register } from "node:module";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "..", "..", "test", "helpers", "ts-import-hooks.mjs")));+const { runSkillImport, runMcpImport } = await import(+ "../main/ipc/agent-import-ipc.ts"+);++/** Build a host-call stub whose responses are queued per method. */+function stubHost(responsesByMethod) {+ const calls = [];+ const queues = new Map();+ for (const [method, list] of Object.entries(responsesByMethod)) {+ queues.set(method, Array.isArray(list) ? [...list] : [list]);+ }+ const call = async (method, params) => {+ calls.push({ method, params });+ const q = queues.get(method);+ if (!q || q.length === 0) {+ throw new Error(`no stubbed response for ${method}`);+ }+ const next = q.shift();+ if (typeof next === "function") return next(params);+ if (next && next.throw) throw next.throw;+ return next;+ };+ return { call, calls };+}++test("runSkillImport partitions success / exists / other-error into three buckets", async () => {+ const host = stubHost({+ "skills.import": [+ { skill: { id: "ok", name: "OK" } },+ { throw: new Error("SKILL_INVALID: a skill with this name already exists at this level") },+ { throw: new Error("SKILL_INVALID: document is empty") },+ ],+ });+ const items = [+ { source: "pi-user", sourcePath: "/a.md", shape: "file", id: "ok", name: "OK" },+ { source: "pi-user", sourcePath: "/b.md", shape: "file", id: "dup", name: "Dup" },+ { source: "pi-user", sourcePath: "/c.md", shape: "file", id: "bad", name: "Bad" },+ ];+ const result = await runSkillImport(host.call, { level: "global", items });+ assert.equal(result.imported.length, 1, "imported has one entry");+ assert.equal(result.imported[0].item.id, "ok");+ assert.deepEqual(result.imported[0].skill, { id: "ok", name: "OK" });+ assert.equal(result.skipped.length, 1, "skipped has the exists entry");+ assert.equal(result.skipped[0].reason, "exists");+ assert.equal(result.skipped[0].item.id, "dup");+ assert.equal(result.failed.length, 1, "failed has the other-error entry");+ assert.match(result.failed[0].error, /document is empty/);+ assert.equal(host.calls.length, 3, "one host call per item");+});++test("runSkillImport keeps going after a failure so later items still land", async () => {+ const host = stubHost({+ "skills.import": [+ { throw: new Error("boom") },+ { skill: { id: "after" } },+ ],+ });+ const items = [+ { source: "pi-user", sourcePath: "/one.md", shape: "file", id: "one", name: "One" },+ { source: "pi-user", sourcePath: "/two.md", shape: "file", id: "after", name: "After" },+ ];+ const result = await runSkillImport(host.call, { level: "global", items });+ assert.equal(result.failed.length, 1);+ assert.equal(result.imported.length, 1);+ assert.equal(result.imported[0].item.id, "after");+});++test("runSkillImport for a dir shape sends rootDir as `path`, not sourcePath", async () => {+ const host = stubHost({+ "skills.import": [{ skill: { id: "d" } }],+ });+ const items = [+ {+ source: "claude-user",+ sourcePath: "/root/SKILL.md",+ rootDir: "/root",+ shape: "dir",+ id: "d",+ name: "Dir",+ },+ ];+ await runSkillImport(host.call, {+ level: "project",+ projectPath: "/proj",+ mode: "link",+ items,+ });+ assert.equal(host.calls.length, 1);+ const [{ method, params }] = host.calls;+ assert.equal(method, "skills.import");+ assert.equal(params.path, "/root", "dir shape forwards rootDir as path");+ assert.equal(params.shape, "dir");+ assert.equal(params.mode, "link");+ assert.equal(params.level, "project");+ assert.equal(params.projectPath, "/proj");+});++test("runMcpImport disables a server after upsert when the item asks for it", async () => {+ const host = stubHost({+ "mcp.upsert": [{ server: { id: "off" } }],+ "mcp.setEnabled": [{ ok: true }],+ });+ const items = [+ {+ source: "claude-desktop",+ sourcePath: "/cfg.json",+ id: "off",+ rawKey: "off",+ transport: "stdio",+ command: "npx",+ disabled: true,+ },+ ];+ const result = await runMcpImport(host.call, { items });+ assert.equal(result.imported.length, 1);+ assert.equal(host.calls.length, 2, "one upsert plus one setEnabled");+ assert.equal(host.calls[0].method, "mcp.upsert");+ const server = host.calls[0].params.server;+ assert.equal(server.id, "off");+ assert.equal(server.command, "npx");+ assert.equal(server.disabled, undefined, "disabled is stripped from the payload");+ assert.equal(host.calls[1].method, "mcp.setEnabled");+ assert.deepEqual(host.calls[1].params, { id: "off", enabled: false });+});++test("runMcpImport reports an `already exists` upsert as skipped, not failed", async () => {+ const host = stubHost({+ "mcp.upsert": [+ { throw: new Error("MCP_INVALID: a server with this name already exists at this level") },+ { server: { id: "fresh" } },+ ],+ });+ const items = [+ {+ source: "cursor-global",+ sourcePath: "/a.json",+ id: "dup",+ rawKey: "dup",+ transport: "http",+ url: "https://example.test",+ },+ {+ source: "cursor-global",+ sourcePath: "/b.json",+ id: "fresh",+ rawKey: "fresh",+ transport: "http",+ url: "https://ok.test",+ },+ ];+ const result = await runMcpImport(host.call, { items });+ assert.equal(result.skipped.length, 1);+ assert.equal(result.skipped[0].reason, "exists");+ assert.equal(result.imported.length, 1);+ assert.equal(result.failed.length, 0);+});diff --git a/apps/desktop/electron/test/agent-mcp-scan.test.mjs b/apps/desktop/electron/test/agent-mcp-scan.test.mjsnew file mode 100644index 000000000..3c142463e--- /dev/null+++ b/apps/desktop/electron/test/agent-mcp-scan.test.mjs@@ -0,0 +1,231 @@+import assert from "node:assert/strict";+import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, dirname } from "node:path";+import { register } from "node:module";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "..", "..", "test", "helpers", "ts-import-hooks.mjs")));+const { scanExternalMcp, parseCodexMcpToml } = await import(+ "../main/importers/agent-mcp-scan.ts"+);++async function makeHome() {+ const root = await mkdtemp(join(tmpdir(), "pi-mcp-scan-"));+ const home = join(root, "home");+ await mkdir(home, { recursive: true });+ return { root, home };+}++test("claude-desktop config on darwin is read and mapped to a candidate", async () => {+ const { root, home } = await makeHome();+ try {+ const cfg = join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json");+ await mkdir(dirname(cfg), { recursive: true });+ await writeFile(+ cfg,+ JSON.stringify({+ mcpServers: {+ "context 7": { command: "npx", args: ["-y", "@upstash/context7-mcp"], env: { A: "1" } },+ },+ }),+ );+ const result = await scanExternalMcp({ homeDir: home, platform: "darwin", env: {} });+ const found = result.candidates.find((c) => c.source === "claude-desktop");+ assert.ok(found, "candidate missing");+ assert.equal(found.transport, "stdio");+ assert.equal(found.command, "npx");+ assert.deepEqual(found.args, ["-y", "@upstash/context7-mcp"]);+ assert.deepEqual(found.env, { A: "1" });+ assert.equal(found.rawKey, "context 7");+ assert.equal(found.id, "context-7");+ const src = result.sources.find((s) => s.kind === "claude-desktop");+ assert.equal(src.exists, true);+ assert.equal(src.count, 1);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("claude-desktop config on win32 honours APPDATA and falls back to HOME", async () => {+ const { root, home } = await makeHome();+ try {+ const cfg = join(home, "AppData", "Roaming", "Claude", "claude_desktop_config.json");+ await mkdir(dirname(cfg), { recursive: true });+ await writeFile(cfg, JSON.stringify({ mcpServers: { s: { command: "c" } } }));+ const result = await scanExternalMcp({ homeDir: home, platform: "win32", env: {} });+ const src = result.sources.find((s) => s.kind === "claude-desktop");+ assert.equal(src.exists, true);+ assert.equal(src.path.endsWith("Roaming/Claude/claude_desktop_config.json") ||+ src.path.endsWith("Roaming\\Claude\\claude_desktop_config.json"), true);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("claude-code merges .claude.json legacy with settings.json overrides", async () => {+ const { root, home } = await makeHome();+ try {+ await writeFile(+ join(home, ".claude.json"),+ JSON.stringify({ mcpServers: { alpha: { command: "old" }, beta: { command: "b" } } }),+ );+ await mkdir(join(home, ".claude"), { recursive: true });+ await writeFile(+ join(home, ".claude", "settings.json"),+ JSON.stringify({ mcpServers: { alpha: { command: "new" }, gamma: { command: "g" } } }),+ );+ const result = await scanExternalMcp({ homeDir: home, platform: "linux", env: {} });+ const found = result.candidates.filter((c) => c.source === "claude-code");+ const ids = found.map((c) => c.id).sort();+ assert.deepEqual(ids, ["alpha", "beta", "gamma"]);+ const alpha = found.find((c) => c.id === "alpha");+ assert.equal(alpha.command, "new");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("cursor global and project trees each report their own candidates", async () => {+ const { root, home } = await makeHome();+ const project = join(root, "project");+ try {+ await mkdir(join(home, ".cursor"), { recursive: true });+ await writeFile(+ join(home, ".cursor", "mcp.json"),+ JSON.stringify({+ mcpServers: {+ remote: { url: "https://mcp.example.com/sse", headers: { Authorization: "Bearer x" }, type: "sse" },+ },+ }),+ );+ await mkdir(join(project, ".cursor"), { recursive: true });+ await writeFile(+ join(project, ".cursor", "mcp.json"),+ JSON.stringify({ mcpServers: { local: { command: "./bin/mcp" } } }),+ );+ const result = await scanExternalMcp({+ homeDir: home,+ projectPath: project,+ platform: "linux",+ env: {},+ });+ const global = result.candidates.find((c) => c.source === "cursor-global");+ assert.equal(global.transport, "http");+ assert.equal(global.url, "https://mcp.example.com/sse");+ assert.deepEqual(global.headers, { Authorization: "Bearer x" });+ assert.ok(global.warnings.includes("declared sse mapped to http"));+ const proj = result.candidates.find((c) => c.source === "cursor-project");+ assert.equal(proj.transport, "stdio");+ assert.equal(proj.command, "./bin/mcp");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("codex config.toml is parsed with the mini TOML reader", async () => {+ const { root, home } = await makeHome();+ try {+ await mkdir(join(home, ".codex"), { recursive: true });+ await writeFile(+ join(home, ".codex", "config.toml"),+ [+ "# top comment",+ "[mcp_servers.playwright]",+ 'command = "npx"',+ 'args = ["-y", "@playwright/mcp"]',+ 'env = { HEADLESS = "1" }',+ "",+ "[mcp_servers.remote]",+ 'url = "https://mcp.example.com/rpc"',+ 'transport = "http"',+ ].join("\n"),+ );+ const result = await scanExternalMcp({ homeDir: home, platform: "linux", env: {} });+ const cands = result.candidates.filter((c) => c.source === "codex");+ assert.equal(cands.length, 2);+ const pw = cands.find((c) => c.id === "playwright");+ assert.equal(pw.transport, "stdio");+ assert.equal(pw.command, "npx");+ assert.deepEqual(pw.args, ["-y", "@playwright/mcp"]);+ assert.deepEqual(pw.env, { HEADLESS: "1" });+ const remote = cands.find((c) => c.id === "remote");+ assert.equal(remote.transport, "http");+ assert.equal(remote.url, "https://mcp.example.com/rpc");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("opencode maps command-array and remote-url shapes", async () => {+ const { root, home } = await makeHome();+ try {+ const xdg = join(home, ".config", "opencode");+ await mkdir(xdg, { recursive: true });+ await writeFile(+ join(xdg, "opencode.json"),+ JSON.stringify({+ mcp: {+ local: { type: "local", command: ["node", "server.js", "--port", "8080"] },+ net: { type: "remote", url: "http://192.168.1.5:9000/mcp" },+ },+ }),+ );+ const result = await scanExternalMcp({ homeDir: home, platform: "linux", env: {} });+ const cands = result.candidates.filter((c) => c.source === "opencode");+ const local = cands.find((c) => c.id === "local");+ assert.equal(local.transport, "stdio");+ assert.equal(local.command, "node");+ assert.deepEqual(local.args, ["server.js", "--port", "8080"]);+ const net = cands.find((c) => c.id === "net");+ assert.equal(net.transport, "http");+ assert.equal(net.url, "http://192.168.1.5:9000/mcp");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("invalid json is reported through sources[].error, never as a candidate", async () => {+ const { root, home } = await makeHome();+ try {+ await mkdir(join(home, ".cursor"), { recursive: true });+ await writeFile(join(home, ".cursor", "mcp.json"), "{ not json");+ const result = await scanExternalMcp({ homeDir: home, platform: "linux", env: {} });+ const src = result.sources.find((s) => s.kind === "cursor-global");+ assert.equal(src.exists, true);+ assert.match(src.error, /invalid json/);+ assert.equal(result.candidates.filter((c) => c.source === "cursor-global").length, 0);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("chatgpt-desktop always reports as not detected until a stable path exists", async () => {+ const { root, home } = await makeHome();+ try {+ const result = await scanExternalMcp({ homeDir: home, platform: "darwin", env: {} });+ const src = result.sources.find((s) => s.kind === "chatgpt-desktop");+ assert.ok(src);+ assert.equal(src.exists, false);+ assert.equal(src.count, 0);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("parseCodexMcpToml ignores unrelated sections and comments", () => {+ const parsed = parseCodexMcpToml(+ [+ "[other]",+ 'x = "1"',+ "[mcp_servers.only]",+ 'command = "run" # inline comment',+ "disabled = true",+ ].join("\n"),+ );+ assert.deepEqual(Object.keys(parsed), ["only"]);+ assert.equal(parsed.only.command, "run");+ assert.equal(parsed.only.disabled, true);+});diff --git a/apps/desktop/electron/test/agent-skill-scan.test.mjs b/apps/desktop/electron/test/agent-skill-scan.test.mjsnew file mode 100644index 000000000..3117f31f6--- /dev/null+++ b/apps/desktop/electron/test/agent-skill-scan.test.mjs@@ -0,0 +1,160 @@+import assert from "node:assert/strict";+import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, dirname } from "node:path";+import { register } from "node:module";+import test from "node:test";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "..", "..", "test", "helpers", "ts-import-hooks.mjs")));+const { scanExternalSkills, readFrontmatter } = await import(+ "../main/importers/agent-skill-scan.ts"+);++async function makeHome() {+ const root = await mkdtemp(join(tmpdir(), "pi-skill-scan-"));+ const home = join(root, "home");+ await mkdir(home, { recursive: true });+ return { root, home };+}++const skillFile = (name, description, body = "instructions go here") =>+ ["---", `name: ${name}`, `description: ${description}`, "---", "", body, ""].join("\n");++test("file-shaped skills under ~/.claude/skills produce candidates", async () => {+ const { root, home } = await makeHome();+ try {+ const dir = join(home, ".claude", "skills");+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, "review.md"), skillFile("Review", "Reviews changes"));+ const result = await scanExternalSkills({ homeDir: home, env: {} });+ const cands = result.candidates.filter((c) => c.source === "claude-user");+ assert.equal(cands.length, 1);+ assert.equal(cands[0].shape, "file");+ assert.equal(cands[0].id, "review");+ assert.equal(cands[0].name, "Review");+ assert.equal(cands[0].description, "Reviews changes");+ assert.ok(cands[0].bytes > 0);+ const src = result.sources.find((s) => s.kind === "claude-user");+ assert.equal(src.exists, true);+ assert.equal(src.count, 1);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("directory-shaped skills read SKILL.md and record rootDir", async () => {+ const { root, home } = await makeHome();+ try {+ const dir = join(home, ".claude", "skills", "code-review");+ await mkdir(dir, { recursive: true });+ await writeFile(+ join(dir, "SKILL.md"),+ skillFile("Code Review", "Deep review of a diff", "walk the diff hunks"),+ );+ const result = await scanExternalSkills({ homeDir: home, env: {} });+ const cand = result.candidates.find((c) => c.source === "claude-user");+ assert.equal(cand.shape, "dir");+ assert.equal(cand.rootDir, dir);+ assert.equal(cand.sourcePath, join(dir, "SKILL.md"));+ assert.equal(cand.name, "Code Review");+ assert.equal(cand.id, "code-review");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("missing frontmatter still produces a candidate with warnings", async () => {+ const { root, home } = await makeHome();+ try {+ const dir = join(home, ".claude", "skills");+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, "loose.md"), "just body text, no frontmatter\n");+ const result = await scanExternalSkills({ homeDir: home, env: {} });+ const cand = result.candidates.find((c) => c.source === "claude-user");+ assert.ok(cand);+ assert.equal(cand.id, "loose");+ assert.equal(cand.name, "loose");+ assert.equal(cand.description, "");+ assert.ok(cand.warnings.includes("missing frontmatter"));+ assert.ok(cand.warnings.includes("frontmatter missing name"));+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("skills with an empty body are skipped entirely", async () => {+ const { root, home } = await makeHome();+ try {+ const dir = join(home, ".claude", "skills");+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, "empty.md"), ["---", "name: Empty", "description: nothing", "---", ""].join("\n"));+ await writeFile(join(dir, "good.md"), skillFile("Good", "has body"));+ const result = await scanExternalSkills({ homeDir: home, env: {} });+ const ids = result.candidates.filter((c) => c.source === "claude-user").map((c) => c.id);+ assert.deepEqual(ids, ["good"]);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("project-level scanning picks up .claude/skills and .agents/skills", async () => {+ const { root, home } = await makeHome();+ const project = join(root, "project");+ try {+ await mkdir(join(project, ".claude", "skills"), { recursive: true });+ await writeFile(+ join(project, ".claude", "skills", "spec.md"),+ skillFile("Spec Writer", "Writes specs"),+ );+ await mkdir(join(project, ".agents", "skills"), { recursive: true });+ await writeFile(+ join(project, ".agents", "skills", "helper.md"),+ skillFile("Helper", "helps out"),+ );+ const result = await scanExternalSkills({ homeDir: home, projectPath: project, env: {} });+ const claudeProj = result.candidates.find((c) => c.source === "claude-project");+ const piProj = result.candidates.find((c) => c.source === "pi-project");+ assert.ok(claudeProj);+ assert.equal(claudeProj.id, "spec-writer");+ assert.ok(piProj);+ assert.equal(piProj.id, "helper");+ assert.ok(piProj.warnings.includes("already in current registry"));+ const kinds = result.sources.map((s) => s.kind);+ assert.ok(kinds.includes("claude-user"));+ assert.ok(kinds.includes("claude-project"));+ assert.ok(kinds.includes("pi-user"));+ assert.ok(kinds.includes("pi-project"));+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("PI_DESKTOP_AGENTS_DIR overrides the default pi-user skills root", async () => {+ const { root, home } = await makeHome();+ const override = join(root, "custom");+ try {+ await mkdir(join(override, "skills"), { recursive: true });+ await writeFile(+ join(override, "skills", "boot.md"),+ skillFile("Boot", "bootstrap thing"),+ );+ const result = await scanExternalSkills({+ homeDir: home,+ env: { PI_DESKTOP_AGENTS_DIR: override },+ });+ const src = result.sources.find((s) => s.kind === "pi-user");+ assert.equal(src.path, join(override, "skills"));+ assert.equal(src.count, 1);+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("readFrontmatter strips quotes and inline comments", () => {+ const { data, ok } = readFrontmatter("---\nname: 'Boxed'\ndescription: \"line\" # trailing\n---\nbody\n");+ assert.equal(ok, true);+ assert.equal(data.name, "Boxed");+ assert.equal(data.description, "line");+});diff --git a/apps/desktop/src/components/settings/AgentSkillsPage.tsx b/apps/desktop/src/components/settings/AgentSkillsPage.tsxindex b2d302846..98747d880 100644--- a/apps/desktop/src/components/settings/AgentSkillsPage.tsx+++ b/apps/desktop/src/components/settings/AgentSkillsPage.tsx@@ -235,15 +235,19 @@ export function AgentSkillsPage() {}};- const importSkill = async (level: AgentCapabilityLevel = targetLevel) => {+ const importSkill = async (+ level: AgentCapabilityLevel = targetLevel,+ sourceKind: "file" | "dir" = "file",+ ) => {if (level === "project" && !selectedProjectPath) {showToast(t("settings.selectProjectFirst"), { variant: "error" });return;}- setBusyId("import");+ setBusyId(sourceKind === "dir" ? "import-dir" : "import");try {const result = await api.importUserSkill({level,+ sourceKind,...(level === "project" && selectedProjectPath? { projectPath: selectedProjectPath }: {}),@@ -451,18 +455,32 @@ export function AgentSkillsPage() {? t("settings.capabilityCreateInProject"): t("settings.capabilityCreateInGlobal");const importButton = (level: AgentCapabilityLevel) => (- <CapabilityButton- busy={busyId === "import"}- title={- level === "project"- ? t("settings.capabilityImportToProject")- : t("settings.capabilityImportToGlobal")- }- onClick={() => void importSkill(level)}- >- <IconDownload size={14} />- {t("settings.importSkill")}- </CapabilityButton>+ <>+ <CapabilityButton+ busy={busyId === "import"}+ title={+ level === "project"+ ? t("settings.capabilityImportToProject")+ : t("settings.capabilityImportToGlobal")+ }+ onClick={() => void importSkill(level, "file")}+ >+ <IconDownload size={14} />+ {t("settings.importSkillFile")}+ </CapabilityButton>+ <CapabilityButton+ busy={busyId === "import-dir"}+ title={+ level === "project"+ ? t("settings.capabilityImportToProject")+ : t("settings.capabilityImportToGlobal")+ }+ onClick={() => void importSkill(level, "dir")}+ >+ <IconDownload size={14} />+ {t("settings.importSkillDir")}+ </CapabilityButton>+ </>);const marketButton = (diff --git a/apps/desktop/src/features/settings/agent-sections.tsx b/apps/desktop/src/features/settings/agent-sections.tsxindex 1950ecf86..175901992 100644--- a/apps/desktop/src/features/settings/agent-sections.tsx+++ b/apps/desktop/src/features/settings/agent-sections.tsx@@ -3,7 +3,18 @@ import { useTranslation } from "react-i18next";import type { AgentInstructionFile } from "@pi-desktop/shared";import { useAppStore } from "../../stores/app-store";import { api } from "../../lib/api";-import type { ImportCandidate, ModelConfigImportCandidate } from "../../lib/api";+import type {+ ImportCandidate,+ ModelConfigImportCandidate,+ ExternalSkillCandidate,+ ExternalSkillImportItem,+ ExternalSkillScanResult,+ ExternalSkillSourceKind,+ ExternalMcpCandidate,+ ExternalMcpImportItem,+ ExternalMcpScanResult,+ ExternalMcpSourceKind,+} from "../../lib/api";import { useUpdateState } from "../../hooks/use-update-state";import {DEFAULT_IMPORT_GROUP_BY,@@ -197,6 +208,8 @@ export function ImportSection() {<div className="settings-stack"><SessionImportPanel /><ModelConfigImportPanel />+ <SkillsScanImportPanel />+ <McpScanImportPanel /></div>);}@@ -673,3 +686,407 @@ export function ModelConfigImportPanel() {* which is also what unlocks F12 and the macOS View ▸ developer tools item* (enforced in the main process, not here).*/++// ---------------------------------------------------------------------------+// Scan skills / MCP servers from other agent tools on this machine.+// ---------------------------------------------------------------------------++const SKILL_SOURCE_KEY: Record<ExternalSkillSourceKind, string> = {+ "claude-user": "settings.importAgentScanSourceClaudeUser",+ "claude-project": "settings.importAgentScanSourceClaudeProject",+ "pi-user": "settings.importAgentScanSourcePiUser",+ "pi-project": "settings.importAgentScanSourcePiProject",+};++const MCP_SOURCE_KEY: Record<ExternalMcpSourceKind, string> = {+ "claude-desktop": "settings.importAgentScanSourceClaudeDesktop",+ "claude-code": "settings.importAgentScanSourceClaudeCode",+ "cursor-global": "settings.importAgentScanSourceCursorGlobal",+ "cursor-project": "settings.importAgentScanSourceCursorProject",+ codex: "settings.importAgentScanSourceCodex",+ opencode: "settings.importAgentScanSourceOpenCode",+ "chatgpt-desktop": "settings.importAgentScanSourceChatgpt",+};++function groupBySource<C extends { source: string }>(+ candidates: C[],+): Array<{ id: string; items: C[] }> {+ const map = new Map<string, C[]>();+ for (const c of candidates) {+ const bucket = map.get(c.source);+ if (bucket) bucket.push(c);+ else map.set(c.source, [c]);+ }+ return Array.from(map.entries()).map(([id, items]) => ({ id, items }));+}++export function SkillsScanImportPanel() {+ const { t } = useTranslation();+ const showToast = useAppStore((s) => s.showToast);+ const [result, setResult] = useState<ExternalSkillScanResult | null>(null);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [mode, setMode] = useState<"copy" | "link">("copy");+ const [scanning, setScanning] = useState(false);+ const [importing, setImporting] = useState(false);++ const keyOf = (c: ExternalSkillCandidate) => `${c.source}:${c.sourcePath}`;++ const scan = async () => {+ setScanning(true);+ try {+ const res = await api.scanExternalSkills();+ setResult(res);+ setSelected(new Set());+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setScanning(false);+ }+ };++ const runImport = async () => {+ if (!result) return;+ const items: ExternalSkillImportItem[] = result.candidates+ .filter((c) => selected.has(keyOf(c)))+ .map((c) => ({+ source: c.source,+ sourcePath: c.sourcePath,+ shape: c.shape,+ rootDir: c.rootDir,+ id: c.id,+ name: c.name,+ description: c.description,+ }));+ if (items.length === 0) return;+ setImporting(true);+ try {+ const res = await api.runExternalSkillsImport({+ level: "global",+ mode,+ items,+ });+ showToast(+ t("settings.importAgentScanResult", {+ imported: res.imported.length,+ skipped: res.skipped.length,+ failed: res.failed.length,+ }),+ { variant: res.failed.length > 0 ? "error" : "success" },+ );+ // Refresh scan so already-imported rows disappear next round.+ await scan();+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setImporting(false);+ }+ };++ const toggle = (k: string, on: boolean) =>+ setSelected((prev) => {+ const next = new Set(prev);+ if (on) next.add(k);+ else next.delete(k);+ return next;+ });++ const groups = useMemo(() => groupBySource(result?.candidates ?? []), [result]);+ const allKeys = useMemo(+ () => (result?.candidates ?? []).map(keyOf),+ [result],+ );+ const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));++ return (+ <>+ <SettingsCard title={t("settings.importAgentSkillsTitle")}>+ <div className="settings-description">+ {t("settings.importAgentSkillsDesc")}+ </div>+ <SettingsRow title={t("settings.importScan")}>+ <Button variant="secondary" disabled={scanning} onClick={() => void scan()}>+ {scanning ? t("settings.importScanning") : t("settings.importScan")}+ </Button>+ </SettingsRow>+ <SettingsRow title={t("settings.importAgentScanMode")}>+ <SettingsMenuSelect+ label={t("settings.importAgentScanMode")}+ value={mode}+ onChange={(id) => setMode(id as "copy" | "link")}+ options={[+ { id: "copy", label: t("settings.importAgentScanModeCopy") },+ { id: "link", label: t("settings.importAgentScanModeLink") },+ ]}+ />+ <div className="settings-hint">+ {t("settings.importAgentScanModeHint")}+ </div>+ </SettingsRow>+ </SettingsCard>++ {result !== null && (+ <SettingsCard>+ {result.candidates.length === 0 ? (+ <div className="settings-empty">{t("settings.importAgentScanNone")}</div>+ ) : (+ <>+ <div className="import-toolbar">+ <label className="import-select-all">+ <input+ type="checkbox"+ checked={allSelected}+ aria-label={t("settings.importSelectAll")}+ onChange={(e) => {+ const on = e.target.checked;+ setSelected(on ? new Set(allKeys) : new Set());+ }}+ />+ <span>+ {t("settings.importAgentScanFoundSkills", {+ count: result.candidates.length,+ })}+ {selected.size > 0+ ? ` · ${t("settings.importSelectedCount", { count: selected.size })}`+ : ""}+ </span>+ </label>+ <Button+ variant="primary"+ disabled={importing || selected.size === 0}+ onClick={() => void runImport()}+ >+ {importing+ ? t("settings.importing")+ : t("settings.importSelected", { count: selected.size })}+ </Button>+ </div>+ <div className="import-groups">+ {groups.map((g) => (+ <div key={g.id} className="import-group">+ <div className="import-group-header">+ <span className="import-group-title">+ {t(+ SKILL_SOURCE_KEY[g.id as ExternalSkillSourceKind] ??+ "settings.importSourcePi",+ )}+ </span>+ <Badge tone="neutral">{g.items.length}</Badge>+ </div>+ <div className="import-group-body">+ {g.items.map((c) => {+ const k = keyOf(c);+ return (+ <label key={k} className="import-row">+ <input+ type="checkbox"+ checked={selected.has(k)}+ onChange={(e) => toggle(k, e.target.checked)}+ />+ <span className="import-row-main">+ <span className="import-row-title">{c.name || c.id}</span>+ <span className="import-row-meta">+ {c.description || c.sourcePath}+ </span>+ </span>+ <Badge+ tone={c.shape === "dir" ? "success" : "neutral"}+ >+ {c.shape === "dir"+ ? t("settings.importAgentScanShapeDir")+ : t("settings.importAgentScanShapeFile")}+ </Badge>+ </label>+ );+ })}+ </div>+ </div>+ ))}+ </div>+ </>+ )}+ </SettingsCard>+ )}+ </>+ );+}++export function McpScanImportPanel() {+ const { t } = useTranslation();+ const showToast = useAppStore((s) => s.showToast);+ const [result, setResult] = useState<ExternalMcpScanResult | null>(null);+ const [selected, setSelected] = useState<Set<string>>(new Set());+ const [scanning, setScanning] = useState(false);+ const [importing, setImporting] = useState(false);++ const keyOf = (c: ExternalMcpCandidate) => `${c.source}:${c.id}`;++ const scan = async () => {+ setScanning(true);+ try {+ const res = await api.scanExternalMcp();+ setResult(res);+ setSelected(new Set());+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setScanning(false);+ }+ };++ const runImport = async () => {+ if (!result) return;+ const items: ExternalMcpImportItem[] = result.candidates+ .filter((c) => selected.has(keyOf(c)))+ .map((c) => ({+ source: c.source,+ sourcePath: c.sourcePath,+ id: c.id,+ rawKey: c.rawKey,+ label: c.label,+ description: c.description,+ transport: c.transport,+ command: c.command,+ args: c.args,+ env: c.env,+ url: c.url,+ headers: c.headers,+ disabled: c.disabled,+ }));+ if (items.length === 0) return;+ setImporting(true);+ try {+ const res = await api.runExternalMcpImport({ items });+ showToast(+ t("settings.importAgentScanResult", {+ imported: res.imported.length,+ skipped: res.skipped.length,+ failed: res.failed.length,+ }),+ { variant: res.failed.length > 0 ? "error" : "success" },+ );+ await scan();+ } catch (e) {+ showToast(e instanceof Error ? e.message : String(e), { variant: "error" });+ } finally {+ setImporting(false);+ }+ };++ const toggle = (k: string, on: boolean) =>+ setSelected((prev) => {+ const next = new Set(prev);+ if (on) next.add(k);+ else next.delete(k);+ return next;+ });++ const groups = useMemo(() => groupBySource(result?.candidates ?? []), [result]);+ const allKeys = useMemo(+ () => (result?.candidates ?? []).map(keyOf),+ [result],+ );+ const allSelected = allKeys.length > 0 && allKeys.every((k) => selected.has(k));++ return (+ <>+ <SettingsCard title={t("settings.importAgentMcpTitle")}>+ <div className="settings-description">+ {t("settings.importAgentMcpDesc")}+ </div>+ <SettingsRow title={t("settings.importScan")}>+ <Button variant="secondary" disabled={scanning} onClick={() => void scan()}>+ {scanning ? t("settings.importScanning") : t("settings.importScan")}+ </Button>+ </SettingsRow>+ </SettingsCard>++ {result !== null && (+ <SettingsCard>+ {result.candidates.length === 0 ? (+ <div className="settings-empty">{t("settings.importAgentScanNone")}</div>+ ) : (+ <>+ <div className="import-toolbar">+ <label className="import-select-all">+ <input+ type="checkbox"+ checked={allSelected}+ aria-label={t("settings.importSelectAll")}+ onChange={(e) => {+ const on = e.target.checked;+ setSelected(on ? new Set(allKeys) : new Set());+ }}+ />+ <span>+ {t("settings.importAgentScanFoundMcp", {+ count: result.candidates.length,+ })}+ {selected.size > 0+ ? ` · ${t("settings.importSelectedCount", { count: selected.size })}`+ : ""}+ </span>+ </label>+ <Button+ variant="primary"+ disabled={importing || selected.size === 0}+ onClick={() => void runImport()}+ >+ {importing+ ? t("settings.importing")+ : t("settings.importSelected", { count: selected.size })}+ </Button>+ </div>+ <div className="import-groups">+ {groups.map((g) => (+ <div key={g.id} className="import-group">+ <div className="import-group-header">+ <span className="import-group-title">+ {t(+ MCP_SOURCE_KEY[g.id as ExternalMcpSourceKind] ??+ "settings.importSourcePi",+ )}+ </span>+ <Badge tone="neutral">{g.items.length}</Badge>+ </div>+ <div className="import-group-body">+ {g.items.map((c) => {+ const k = keyOf(c);+ return (+ <label key={k} className="import-row">+ <input+ type="checkbox"+ checked={selected.has(k)}+ onChange={(e) => toggle(k, e.target.checked)}+ />+ <span className="import-row-main">+ <span className="import-row-title">+ {c.label || c.id}+ </span>+ <span className="import-row-meta">+ {c.description ||+ c.command ||+ c.url ||+ c.sourcePath}+ </span>+ </span>+ <Badge+ tone={c.transport === "http" ? "warning" : "neutral"}+ >+ {c.transport === "http"+ ? t("settings.importAgentScanTransportHttp")+ : t("settings.importAgentScanTransportStdio")}+ </Badge>+ </label>+ );+ })}+ </div>+ </div>+ ))}+ </div>+ </>+ )}+ </SettingsCard>+ )}+ </>+ );+}diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 5372e3c85..67ad3157a 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -146,6 +146,130 @@ export interface ImportRunResult {failed: number;}+// --- External skill / MCP scan-and-import ---------------------------------+// Renderer-side mirrors of the electron-main scanner output so the panel does+// not have to import from `electron/`. Keep the field names in sync with+// `apps/desktop/electron/main/importers/agent-*-scan.ts`.++export type ExternalSkillSourceKind =+ | "claude-user"+ | "claude-project"+ | "pi-user"+ | "pi-project";++export interface ExternalSkillCandidate {+ source: ExternalSkillSourceKind;+ sourcePath: string;+ rootDir?: string;+ shape: "file" | "dir";+ id: string;+ name: string;+ description: string;+ bytes: number;+ warnings: string[];+}++export interface ExternalSkillSourceReport {+ kind: ExternalSkillSourceKind | "error";+ path: string;+ exists: boolean;+ error?: string;+ count: number;+}++export interface ExternalSkillScanResult {+ candidates: ExternalSkillCandidate[];+ sources: ExternalSkillSourceReport[];+}++export interface ExternalSkillImportItem {+ source: ExternalSkillSourceKind;+ sourcePath: string;+ shape: "file" | "dir";+ rootDir?: string;+ id: string;+ name: string;+ description?: string;+}++export interface ExternalSkillImportPayload {+ level: "global" | "project";+ projectPath?: string;+ mode?: "copy" | "link";+ items: ExternalSkillImportItem[];+}++export interface ExternalSkillImportRunResult {+ imported: Array<{ item: ExternalSkillImportItem; skill: UserSkillRecord }>;+ skipped: Array<{ item: ExternalSkillImportItem; reason: string }>;+ failed: Array<{ item: ExternalSkillImportItem; error: string }>;+}++export type ExternalMcpSourceKind =+ | "claude-desktop"+ | "claude-code"+ | "cursor-global"+ | "cursor-project"+ | "codex"+ | "opencode"+ | "chatgpt-desktop";++export interface ExternalMcpCandidate {+ source: ExternalMcpSourceKind;+ sourcePath: string;+ id: string;+ rawKey: string;+ label?: string;+ description?: string;+ transport: "stdio" | "http";+ command?: string;+ args?: string[];+ env?: Record<string, string>;+ url?: string;+ headers?: Record<string, string>;+ disabled?: boolean;+ warnings: string[];+}++export interface ExternalMcpSourceReport {+ kind: ExternalMcpSourceKind | "error";+ path: string;+ exists: boolean;+ error?: string;+ count: number;+}++export interface ExternalMcpScanResult {+ candidates: ExternalMcpCandidate[];+ sources: ExternalMcpSourceReport[];+}++export interface ExternalMcpImportItem {+ source: ExternalMcpSourceKind;+ sourcePath: string;+ id: string;+ rawKey: string;+ label?: string;+ description?: string;+ transport: "stdio" | "http";+ command?: string;+ args?: string[];+ env?: Record<string, string>;+ url?: string;+ headers?: Record<string, string>;+ disabled?: boolean;+}++export interface ExternalMcpImportPayload {+ items: ExternalMcpImportItem[];+}++export interface ExternalMcpImportRunResult {+ imported: Array<{ item: ExternalMcpImportItem; server: McpServerRecord }>;+ skipped: Array<{ item: ExternalMcpImportItem; reason: string }>;+ failed: Array<{ item: ExternalMcpImportItem; error: string }>;+}+declare global {interface Window {piDesktop?: {@@ -777,6 +901,20 @@ export const api = {imported: McpServerRecord[];failed: Array<{ id: string; reason: string }>;}>(IPC.invoke.mcpImport, { text }),+ /**+ * Scan third-party AI-tool config files for MCP server definitions. The+ * scanner never throws; a source that failed to read is reported with an+ * `error` on its row and a zero count.+ */+ scanExternalMcp: (query?: { projectPath?: string }) =>+ invoke<ExternalMcpScanResult>(IPC.invoke.mcpImportScan, query ?? {}),+ /**+ * Import each candidate through `mcp.upsert` one at a time; a `disabled`+ * item is turned off with `mcp.setEnabled` after it is written. One failure+ * never aborts the batch.+ */+ runExternalMcpImport: (payload: ExternalMcpImportPayload) =>+ invoke<ExternalMcpImportRunResult>(IPC.invoke.mcpImportRun, payload),/** Query the configured market sources; `failedSources` names dead ones. */searchMcpMarketRegistry: (query: string, sources: MarketSource[], options?: { more?: boolean }) =>invoke<{ entries: McpCatalogEntry[]; failedSources?: string[]; exhausted?: boolean }>(@@ -819,9 +957,30 @@ export const api = {invoke<{ skills: UserSkillRecord[] }>(IPC.invoke.skillList, query),createUserSkill: (skill: UserSkillInput) =>invoke<{ skill: UserSkillRecord }>(IPC.invoke.skillCreate, skill),- /** Opens a native picker for one file; `canceled` when the user backed out. */- importUserSkill: (query?: AgentCapabilityQuery) =>- invoke<{ canceled?: boolean; skill?: UserSkillRecord }>(IPC.invoke.skillImport, query),+ /**+ * Opens a native picker for one file or (when `sourceKind === "dir"`) a+ * folder; `canceled` when the user backed out. `mode: "link"` swaps copy+ * for a symlink import.+ */+ importUserSkill: (+ query?: AgentCapabilityQuery & {+ sourceKind?: "file" | "dir";+ mode?: "copy" | "link";+ },+ ) => invoke<{ canceled?: boolean; skill?: UserSkillRecord }>(IPC.invoke.skillImport, query),+ /**+ * Scan third-party AI-tool skill directories. The scanner never throws;+ * a source that failed to read is reported with an `error` on its row.+ */+ scanExternalSkills: (query?: { projectPath?: string }) =>+ invoke<ExternalSkillScanResult>(IPC.invoke.skillImportScan, query ?? {}),+ /**+ * Import each candidate through `skills.import` one at a time. `mode`+ * defaults to `"copy"`; a `dir` shape sends its `rootDir` as the source+ * path so host-core knows it is a `<name>/SKILL.md` skill.+ */+ runExternalSkillsImport: (payload: ExternalSkillImportPayload) =>+ invoke<ExternalSkillImportRunResult>(IPC.invoke.skillImportRun, payload),updateUserSkill: (id: string, skill: Omit<UserSkillInput, "id">) =>invoke<{ skill: UserSkillRecord }>(IPC.invoke.skillUpdate, { id, ...skill }),/** The record plus the document body, for the editor. */diff --git a/crates/host-core/src/user_skills.rs b/crates/host-core/src/user_skills.rsindex 6aa8500a9..0528c4c9a 100644--- a/crates/host-core/src/user_skills.rs+++ b/crates/host-core/src/user_skills.rs@@ -53,12 +53,131 @@ pub struct UserSkillInput {/// instead of writing activation scope into a skill document.#[allow(dead_code)]pub scope: Option<ActivationScope>,+ /// Import mode: `"copy"` (default) keeps a private byte-for-byte replica so+ /// deleting or moving the source does not break the skill; `"link"` places+ /// a symlink so an external editor's updates are picked up on the next+ /// scan. Ignored by `create` and `update`.+ pub mode: Option<String>,+ /// Optional shape hint for `import`. When absent, a directory source is+ /// treated as the `<name>/SKILL.md` convention and a regular file is+ /// treated as `<id>.md`. A caller that pre-scanned the candidate can pass+ /// `"dir"` to require the SKILL.md convention.+ pub shape: Option<String>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ImportMode {+ Copy,+ Link,+}++impl ImportMode {+ fn parse(value: Option<&str>) -> Result<Self> {+ match value.map(str::trim).unwrap_or("copy") {+ "" | "copy" => Ok(Self::Copy),+ "link" | "symlink" => Ok(Self::Link),+ other => bail!("SKILL_INVALID: unknown import mode `{other}`"),+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ImportShape {+ File,+ Dir,+}++impl ImportShape {+ fn parse(value: &str) -> Result<Self> {+ match value.trim() {+ "file" => Ok(Self::File),+ "dir" | "directory" => Ok(Self::Dir),+ other => bail!("SKILL_INVALID: unknown import shape `{other}`"),+ }+ }}pub struct UserSkillRegistry {state: CapabilityState,}+/// Place a single skill file at `target`, either as a copy or a symlink.+///+/// Copy: `fs::copy` — a private byte replica so a moved or deleted source does+/// not break the skill.+/// Link: `symlink` (unix) / `symlink_file` (windows). On platforms or file+/// systems that reject symlinks the caller receives the OS error and must+/// decide whether to retry with `"copy"`.+fn place_file(source: &Path, target: &Path, mode: ImportMode) -> Result<()> {+ if target.exists() {+ bail!(+ "SKILL_INVALID: destination already exists: {}",+ target.display()+ );+ }+ match mode {+ ImportMode::Copy => {+ fs::copy(source, target).with_context(|| {+ format!("copy {} to {}", source.display(), target.display())+ })?;+ }+ ImportMode::Link => symlink_path(source, target)?,+ }+ Ok(())+}++/// Place a skill directory (Anthropic `<name>/SKILL.md` shape) at `target_dir`.+///+/// Copy: recursive copy so the destination owns every byte, including resources+/// beside `SKILL.md`.+/// Link: one symlink at the root pointing at the source directory. External+/// edits are picked up on the next scan; the caller is responsible for warning+/// the user that a source rename or deletion silently invalidates the skill.+fn place_dir(source_dir: &Path, target_dir: &Path, mode: ImportMode) -> Result<()> {+ if target_dir.exists() {+ bail!(+ "SKILL_INVALID: destination already exists: {}",+ target_dir.display()+ );+ }+ match mode {+ ImportMode::Copy => copy_directory_tree(source_dir, target_dir, false)?,+ ImportMode::Link => symlink_path(source_dir, target_dir)?,+ }+ Ok(())+}++#[cfg(unix)]+fn symlink_path(source: &Path, target: &Path) -> Result<()> {+ std::os::unix::fs::symlink(source, target).with_context(|| {+ format!("symlink {} -> {}", target.display(), source.display())+ })+}++#[cfg(windows)]+fn symlink_path(source: &Path, target: &Path) -> Result<()> {+ // Directory vs file must be picked at link time on Windows; falling back to+ // `symlink_file` for a directory would produce a link that resolves to a+ // regular file entry.+ let result = if source.is_dir() {+ std::os::windows::fs::symlink_dir(source, target)+ } else {+ std::os::windows::fs::symlink_file(source, target)+ };+ result.with_context(|| {+ format!(+ "symlink {} -> {} (Windows may require Developer Mode or elevation)",+ target.display(),+ source.display()+ )+ })+}++#[cfg(not(any(unix, windows)))]+fn symlink_path(_source: &Path, _target: &Path) -> Result<()> {+ bail!("SKILL_INVALID: symlink import is not supported on this platform")+}+fn clip(value: &str, max_chars: usize) -> String {let trimmed = value.trim();if trimmed.chars().count() <= max_chars {@@ -650,15 +769,74 @@ impl UserSkillRegistry {.ok_or_else(|| anyhow::anyhow!("SKILL_INVALID: created skill was not found"))}- /// Import exactly one file and preserve its bytes. The native dialog is also- /// single-file; this guard prevents a caller from turning import into a- /// directory copy.+ /// Import a Markdown skill from an external location. `input.shape` picks+ /// between the single-file (`<id>.md`) form and the Anthropic-style+ /// directory form (`<name>/SKILL.md` plus resources); when absent, a+ /// directory source is treated as `"dir"` and a regular file as `"file"`.+ /// `input.mode` chooses between `"copy"` (default, byte-for-byte replica)+ /// and `"link"` (symlink so external edits are picked up on next scan).+ /// The catalog cap and the per-document byte cap are enforced up front so a+ /// batch import never leaves partial state.pub fn import(&mut self, source: &str, input: UserSkillInput) -> Result<UserSkillRecord> {let source_path = PathBuf::from(source);+ let mode = ImportMode::parse(input.mode.as_deref())?;+ let shape = match input.shape.as_deref() {+ Some(value) => ImportShape::parse(value)?,+ None => {+ if source_path.is_dir() {+ ImportShape::Dir+ } else if source_path.is_file() {+ ImportShape::File+ } else {+ bail!("SKILL_INVALID: import source does not exist");+ }+ }+ };+ let (level, project_path) = level_and_project(&input)?;+ let existing = self.list(level, project_path.as_deref())?;+ if existing.len() >= MAX_SKILLS {+ bail!("SKILL_INVALID: at most {MAX_SKILLS} skills");+ }+ let directory = capability_dir(level, project_path.as_deref(), "skills")?;+ fs::create_dir_all(&directory)?;++ match shape {+ ImportShape::File => self.import_file(+ &source_path,+ &input,+ level,+ project_path.as_deref(),+ mode,+ &directory,+ &existing,+ ),+ ImportShape::Dir => self.import_dir(+ &source_path,+ &input,+ level,+ project_path.as_deref(),+ mode,+ &directory,+ &existing,+ ),+ }+ }++ #[allow(clippy::too_many_arguments)]+ fn import_file(+ &mut self,+ source_path: &Path,+ input: &UserSkillInput,+ level: CapabilityLevel,+ project_path: Option<&str>,+ mode: ImportMode,+ directory: &Path,+ existing: &[UserSkillRecord],+ ) -> Result<UserSkillRecord> {if !source_path.is_file() {- bail!("SKILL_INVALID: import requires one file");+ bail!("SKILL_INVALID: import file source does not exist");}- let raw = fs::read_to_string(&source_path)+ let raw = fs::read_to_string(source_path).with_context(|| format!("read {}", source_path.display()))?;if raw.len() > MAX_SKILL_BYTES {bail!("SKILL_INVALID: document exceeds {MAX_SKILL_BYTES} bytes");@@ -667,38 +845,116 @@ impl UserSkillRegistry {if body.trim().is_empty() {bail!("SKILL_INVALID: document is empty");}- let fallback = path_stem_for_id(&source_path);+ let fallback = path_stem_for_id(source_path);let name = clip(front.get("name").map(String::as_str).unwrap_or(&fallback),MAX_NAME_CHARS,);+ if name.is_empty() {+ bail!("SKILL_INVALID: the file needs a name");+ }let id = input.id.as_deref().filter(|value| valid_id(value)).map(str::to_string)- .unwrap_or_else(|| capability_id(&name, &source_path, 64));+ .unwrap_or_else(|| capability_id(&name, source_path, 64));if !valid_id(&id) {bail!("SKILL_INVALID: the file needs a name or a valid id");}- let (level, project_path) = level_and_project(&input)?;- if self- .list(level, project_path.as_deref())?+ if existing.iter().any(|record| record.id == id || record.name.eq_ignore_ascii_case(&name)){bail!("SKILL_INVALID: a skill with this name already exists at this level");}- let directory = capability_dir(level, project_path.as_deref(), "skills")?;- fs::create_dir_all(&directory)?;let target = directory.join(format!("{id}.md"));- fs::copy(&source_path, &target)- .with_context(|| format!("copy {} to {}", source_path.display(), target.display()))?;- if input.enabled == Some(false) {+ place_file(source_path, &target, mode)?;+ self.finish_import(&id, level, project_path, input.enabled)+ }++ #[allow(clippy::too_many_arguments)]+ fn import_dir(+ &mut self,+ source_dir: &Path,+ input: &UserSkillInput,+ level: CapabilityLevel,+ project_path: Option<&str>,+ mode: ImportMode,+ directory: &Path,+ existing: &[UserSkillRecord],+ ) -> Result<UserSkillRecord> {+ if !source_dir.is_dir() {+ bail!("SKILL_INVALID: import directory source does not exist");+ }+ let skill_file = source_dir.join("SKILL.md");+ if !skill_file.is_file() {+ bail!("SKILL_INVALID: directory import needs a SKILL.md at the root");+ }+ let raw = fs::read_to_string(&skill_file)+ .with_context(|| format!("read {}", skill_file.display()))?;+ if raw.len() > MAX_SKILL_BYTES {+ bail!("SKILL_INVALID: SKILL.md exceeds {MAX_SKILL_BYTES} bytes");+ }+ let (front, body) = parse_front_matter(&raw);+ if body.trim().is_empty() {+ bail!("SKILL_INVALID: SKILL.md is empty");+ }+ // Directory name is the natural fallback id; file stem "SKILL" is not.+ let dir_name = source_dir+ .file_name()+ .and_then(|value| value.to_str())+ .unwrap_or_default();+ let name = clip(+ front.get("name").map(String::as_str).unwrap_or(dir_name),+ MAX_NAME_CHARS,+ );+ if name.is_empty() {+ bail!("SKILL_INVALID: SKILL.md needs a name");+ }+ let id = input+ .id+ .as_deref()+ .filter(|value| valid_id(value))+ .map(str::to_string)+ .unwrap_or_else(|| {+ // Prefer the directory basename so nested resources keep their+ // relative paths intact under `<capability_dir>/skills/<id>/`.+ let fallback_path = source_dir.join(format!("{name}"));+ capability_id(&name, &fallback_path, 64)+ });+ if !valid_id(&id) {+ bail!("SKILL_INVALID: the directory needs a name or a valid id");+ }+ if existing+ .iter()+ .any(|record| record.id == id || record.name.eq_ignore_ascii_case(&name))+ {+ bail!("SKILL_INVALID: a skill with this name already exists at this level");+ }+ let target_dir = directory.join(&id);+ if target_dir.exists() {+ bail!(+ "SKILL_INVALID: destination already exists: {}",+ target_dir.display()+ );+ }+ place_dir(source_dir, &target_dir, mode)?;+ self.finish_import(&id, level, project_path, input.enabled)+ }++ fn finish_import(+ &mut self,+ id: &str,+ level: CapabilityLevel,+ project_path: Option<&str>,+ enabled: Option<bool>,+ ) -> Result<UserSkillRecord> {+ if enabled == Some(false) {self.state- .set_enabled(SKILL_KIND, level, &id, project_path.as_deref(), false)?;+ .set_enabled(SKILL_KIND, level, id, project_path, false)?;}- self.find(&id, Some(level), project_path.as_deref())?+ self.find(id, Some(level), project_path)?.ok_or_else(|| anyhow::anyhow!("SKILL_INVALID: imported skill was not found"))}diff --git a/crates/host-core/src/user_skills/tests.rs b/crates/host-core/src/user_skills/tests.rsindex 74879b352..6380c0e68 100644--- a/crates/host-core/src/user_skills/tests.rs+++ b/crates/host-core/src/user_skills/tests.rs@@ -668,3 +668,166 @@ fn rewriting_a_name_keeps_the_frontmatter_shaped_document_intact() {"---\nmeta:\n name: A\nname: C\n---\n\nBody\n");}++#[test]+fn imports_a_directory_with_skill_md_in_copy_mode() {+ let app = tempdir().unwrap();+ let source_dir = app.path().join("incoming/example-skill");+ fs::create_dir_all(&source_dir).unwrap();+ fs::write(+ source_dir.join("SKILL.md"),+ "---\nname: Example\ndescription: Anthropic-style skill\n---\n\nBody.\n",+ )+ .unwrap();+ fs::write(source_dir.join("resource.txt"), "extra\n").unwrap();++ let mut registry = UserSkillRegistry::new(app.path());+ let record = registry+ .import(+ source_dir.to_str().unwrap(),+ input(+ "Ignored",+ "project",+ Some(app.path().to_str().unwrap()),+ ),+ )+ .unwrap();+ let normalized_project =+ crate::agent_capabilities::normalize_project_path(app.path().to_str().unwrap());+ let expected_root = crate::agent_capabilities::capability_dir(+ CapabilityLevel::Project,+ Some(&normalized_project),+ "skills",+ )+ .unwrap()+ .join("example");+ assert!(expected_root.is_dir(), "target dir exists");+ assert!(expected_root.join("SKILL.md").is_file(), "SKILL.md placed");+ assert!(expected_root.join("resource.txt").is_file(), "resources copied");+ assert_eq!(record.name, "Example");+ // The record path points at the SKILL.md the scanner selects.+ assert_eq!(record.path, expected_root.join("SKILL.md").to_string_lossy());+ // Source is untouched under copy mode.+ assert!(source_dir.join("SKILL.md").is_file());+}++#[test]+fn imports_a_directory_with_skill_md_in_link_mode() {+ let app = tempdir().unwrap();+ let source_dir = app.path().join("incoming/linked-skill");+ fs::create_dir_all(&source_dir).unwrap();+ fs::write(+ source_dir.join("SKILL.md"),+ "---\nname: Linked\n---\n\nBody.\n",+ )+ .unwrap();++ let mut registry = UserSkillRegistry::new(app.path());+ let mut payload = input("Ignored", "project", Some(app.path().to_str().unwrap()));+ payload.mode = Some("link".into());+ let record = registry+ .import(source_dir.to_str().unwrap(), payload)+ .unwrap();+ let normalized_project =+ crate::agent_capabilities::normalize_project_path(app.path().to_str().unwrap());+ let expected_root = crate::agent_capabilities::capability_dir(+ CapabilityLevel::Project,+ Some(&normalized_project),+ "skills",+ )+ .unwrap()+ .join("linked");+ let metadata = fs::symlink_metadata(&expected_root).unwrap();+ assert!(+ metadata.file_type().is_symlink(),+ "link mode leaves a symlink at the destination"+ );+ // The symlink resolves and the scanned SKILL.md path reads back through it.+ assert!(expected_root.join("SKILL.md").is_file());+ assert_eq!(record.name, "Linked");+}++#[test]+fn imports_a_file_in_link_mode() {+ let app = tempdir().unwrap();+ let source = app.path().join("incoming/notes.md");+ fs::create_dir_all(source.parent().unwrap()).unwrap();+ fs::write(+ &source,+ "---\nname: Notes\ndescription: linked file\n---\n\nBody.\n",+ )+ .unwrap();++ let mut registry = UserSkillRegistry::new(app.path());+ let mut payload = input("Ignored", "project", Some(app.path().to_str().unwrap()));+ payload.mode = Some("link".into());+ let record = registry.import(source.to_str().unwrap(), payload).unwrap();+ let normalized_project =+ crate::agent_capabilities::normalize_project_path(app.path().to_str().unwrap());+ let expected = crate::agent_capabilities::capability_dir(+ CapabilityLevel::Project,+ Some(&normalized_project),+ "skills",+ )+ .unwrap()+ .join("notes.md");+ let metadata = fs::symlink_metadata(&expected).unwrap();+ assert!(metadata.file_type().is_symlink());+ assert_eq!(record.name, "Notes");+}++#[test]+fn directory_import_without_skill_md_is_rejected() {+ let app = tempdir().unwrap();+ let source_dir = app.path().join("incoming/no-skill");+ fs::create_dir_all(&source_dir).unwrap();+ fs::write(source_dir.join("readme.md"), "just docs\n").unwrap();++ let mut registry = UserSkillRegistry::new(app.path());+ let err = registry+ .import(+ source_dir.to_str().unwrap(),+ input("Ignored", "project", Some(app.path().to_str().unwrap())),+ )+ .unwrap_err()+ .to_string();+ assert!(err.contains("SKILL_INVALID"), "err = {err}");+ assert!(err.contains("SKILL.md"), "err = {err}");+}++#[test]+fn unknown_import_mode_is_rejected() {+ let app = tempdir().unwrap();+ let source = app.path().join("incoming.md");+ fs::write(+ &source,+ "---\nname: Any\n---\n\nBody.\n",+ )+ .unwrap();+ let mut registry = UserSkillRegistry::new(app.path());+ let mut payload = input("Ignored", "project", Some(app.path().to_str().unwrap()));+ payload.mode = Some("teleport".into());+ let err = registry+ .import(source.to_str().unwrap(), payload)+ .unwrap_err()+ .to_string();+ assert!(err.contains("unknown import mode"), "err = {err}");+}++#[test]+fn shape_dir_requires_a_directory_source() {+ let app = tempdir().unwrap();+ let source = app.path().join("incoming.md");+ fs::write(&source, "---\nname: X\n---\n\nBody.\n").unwrap();+ let mut registry = UserSkillRegistry::new(app.path());+ let mut payload = input("Ignored", "project", Some(app.path().to_str().unwrap()));+ payload.shape = Some("dir".into());+ let err = registry+ .import(source.to_str().unwrap(), payload)+ .unwrap_err()+ .to_string();+ assert!(+ err.contains("SKILL_INVALID") && err.contains("directory"),+ "err = {err}"+ );+}diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex f35174436..d783f394d 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1427,6 +1427,27 @@ filters disabled records, so a disabled project record still shadows a globalone. The desktop-only `mcp/test` IPC action forces one connection test andreturns its status to the MCP editor.+Desktop-only channels scan configuration written by other agent tools on the+same machine — Claude Desktop (`claude_desktop_config.json` on macOS, Windows+and Linux), Claude Code (`~/.claude.json` and `~/.claude/settings.json` merged),+Cursor global and per-project `mcp.json`, Codex (`~/.codex/config.toml`+`[mcp_servers.*]`), opencode (`~/.config/opencode/opencode.json` `mcp` map) —+so the user can review and batch-import into this app's MCP list. ChatGPT+desktop is listed as a placeholder because it has no public configuration path+yet.++- `pi-desktop/mcp/importScan` — `{ projectPath? }` →+ `{ candidates: ExternalMcpCandidate[], sources: ExternalMcpSourceReport[] }`.+ Missing files, ENOENT and parse errors surface on `sources[].error`; one bad+ source never fails the scan. Per-source de-duplication keeps the cross-source+ copies so the user can pick which install to import.+- `pi-desktop/mcp/importRun` — `{ items: ExternalMcpImportItem[] }` →+ `{ imported, skipped, failed }`. Main calls `mcp.upsert` once per item,+ omitting `disabled` from the server payload and following up with+ `mcp.setEnabled({ enabled: false })` when the source marked the server+ disabled. One failure never blocks the rest; conflicts land in `skipped`+ and every other error lands in `failed`.+```tstype McpServerStatus = {serverId: string@@ -1456,8 +1477,12 @@ one-liner.- `skills.list({ level, projectPath? })` → `{ skills: UserSkillRecord[] }`- `skills.active({ projectPath? })` → the effective runtime list- `skills.create(skill)`-- `skills.import({ path, level, projectPath? })` — one source file is physically- copied into the selected `.agents/skills` directory+- `skills.import({ path, level, projectPath?, shape?, mode?, id?, name?, description? })`+ — imports one Markdown skill. `shape` is `"file"` (default when `path` is a+ regular file) or `"dir"` (Anthropic-style `<name>/SKILL.md` plus resources).+ `mode` is `"copy"` (default, byte-for-byte replica so a moved or deleted+ source cannot break the skill) or `"link"` (symlink so external edits appear+ on the next scan; `SKILL_INVALID` if the OS or file system refuses a symlink).- `skills.update({ id, ...skill })`- `skills.read({ id, level?, projectPath? })` → `{ skill, body }`- `skills.remove({ id, level?, projectPath? })`@@ -1468,6 +1493,25 @@ Only the description enters the prompt, and the body is fetched when the modelinvokes `Skill` (D174). A missing file is removed from the list and its localstate is pruned during the next scan.+Desktop-only channels scan skill folders written by other agent tools on this+machine — `~/.claude/skills/`, `<project>/.claude/skills/`, and the app's own+`~/.agents/skills/` (or `PI_DESKTOP_AGENTS_DIR/skills/`) plus its project+equivalent — so the user can review candidates and batch-import them. Both the+single-file (`<id>.md`) and Anthropic-style directory (`<name>/SKILL.md`)+shapes are detected.++- `pi-desktop/skill/importScan` — `{ projectPath? }` →+ `{ candidates: ExternalSkillCandidate[], sources: ExternalSkillSourceReport[] }`.+ Missing directories and read errors surface on `sources[].error`; one failing+ source never aborts the scan. Candidates from `~/.agents/skills/` carry an+ "already in current registry" warning so the UI can filter or highlight them.+- `pi-desktop/skill/importRun` — `{ level, projectPath?, mode?, items }` →+ `{ imported, skipped, failed }`. Main calls `skills.import` once per item,+ passing `path = shape==="dir" ? rootDir : sourcePath` and forwarding `mode`+ and per-item `id`/`name`/`description`. A conflict lands in `skipped` and+ every other error lands in `failed`; one failure never blocks the rest. Batch+ import is still bounded by `MAX_SKILLS` (128 per level).+Desktop-only skill market channels (not host RPC) live on Electron IPC:- `pi-desktop/skill/market/search` — `{ query, sources[] }` →diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex dd72f5410..bb724a37a 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -686,6 +686,46 @@ sklm: {capabilityEnabled: "Enabled {{name}}",capabilityDisabled: "Disabled {{name}}",importSkill: "Import",+ importSkillFile: "Import file",+ importSkillDir: "Import folder",+ importSkillFromTools: "Scan other tools",+ importMcpFromTools: "Scan other tools",+ importAgentSkillsTitle: "Scan skills from other tools",+ importAgentSkillsDesc:+ "Find skill folders that Claude, Codex and other agents keep on this machine, then import the ones you want into the selected level.",+ importAgentMcpTitle: "Scan MCP servers from other tools",+ importAgentMcpDesc:+ "Find MCP configuration from Claude Desktop, Cursor, Codex, Claude Code and opencode on this machine, then add the ones you want to this MCP list.",+ importAgentScanNone: "Nothing to import was found on this machine.",+ importAgentScanFoundSkills: "Found {{count}} skills",+ importAgentScanFoundSkills_one: "Found 1 skill",+ importAgentScanFoundSkills_other: "Found {{count}} skills",+ importAgentScanFoundMcp: "Found {{count}} MCP servers",+ importAgentScanFoundMcp_one: "Found 1 MCP server",+ importAgentScanFoundMcp_other: "Found {{count}} MCP servers",+ importAgentScanMode: "Import mode",+ importAgentScanModeCopy: "Copy",+ importAgentScanModeLink: "Symlink",+ importAgentScanModeHint:+ "Copy places a private replica; symlink follows external edits on the next scan but breaks if the source is renamed or removed. Skills only.",+ importAgentScanResult:+ "Import done: {{imported}} imported, {{skipped}} skipped, {{failed}} failed",+ importAgentScanShapeFile: "File",+ importAgentScanShapeDir: "Folder",+ importAgentScanSourceClaudeDesktop: "Claude Desktop",+ importAgentScanSourceClaudeCode: "Claude Code",+ importAgentScanSourceClaudeUser: "Claude global",+ importAgentScanSourceClaudeProject: "Claude project",+ importAgentScanSourceCursorGlobal: "Cursor global",+ importAgentScanSourceCursorProject: "Cursor project",+ importAgentScanSourceCodex: "Codex",+ importAgentScanSourceOpenCode: "opencode",+ importAgentScanSourceChatgpt: "ChatGPT desktop",+ importAgentScanSourcePiUser: "PI global (already imported)",+ importAgentScanSourcePiProject: "PI project (already imported)",+ importAgentScanSourceUnavailable: "Not installed here, or the path did not match.",+ importAgentScanTransportStdio: "Local process",+ importAgentScanTransportHttp: "HTTP",imported: "Imported",skillImported: "Imported {{name}}",skillsEmpty: "No skills in this folder",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex aa8cb8357..bf468f36f 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -678,6 +678,46 @@ sklm: {capabilityEnabled: "已开启“{{name}}”",capabilityDisabled: "已关闭“{{name}}”",importSkill: "导入",+ importSkillFile: "导入文件",+ importSkillDir: "导入目录",+ importSkillFromTools: "从其他工具扫描",+ importMcpFromTools: "从其他工具扫描",+ importAgentSkillsTitle: "从其他工具扫描技能",+ importAgentSkillsDesc:+ "查找本机 Claude、Codex 等工具的 skill 目录,勾选后导入到当前级别。",+ importAgentMcpTitle: "从其他工具扫描 MCP",+ importAgentMcpDesc:+ "查找 Claude Desktop、Cursor、Codex、Claude Code、opencode 的 MCP 配置,勾选后写入本机 MCP 列表。",+ importAgentScanNone: "未在本机发现可导入的条目。",+ importAgentScanFoundSkills: "发现 {{count}} 个技能",+ importAgentScanFoundSkills_one: "发现 1 个技能",+ importAgentScanFoundSkills_other: "发现 {{count}} 个技能",+ importAgentScanFoundMcp: "发现 {{count}} 个 MCP 服务器",+ importAgentScanFoundMcp_one: "发现 1 个 MCP 服务器",+ importAgentScanFoundMcp_other: "发现 {{count}} 个 MCP 服务器",+ importAgentScanMode: "导入方式",+ importAgentScanModeCopy: "复制副本",+ importAgentScanModeLink: "软链接",+ importAgentScanModeHint:+ "复制:拷贝到本机后与源解耦;软链接:外部改动下次扫描自动生效,源被删除或移动会失效。仅对技能生效。",+ importAgentScanResult:+ "导入完成:成功 {{imported}},跳过 {{skipped}},失败 {{failed}}",+ importAgentScanShapeFile: "文件",+ importAgentScanShapeDir: "目录",+ importAgentScanSourceClaudeDesktop: "Claude Desktop",+ importAgentScanSourceClaudeCode: "Claude Code",+ importAgentScanSourceClaudeUser: "Claude 全局",+ importAgentScanSourceClaudeProject: "Claude 项目",+ importAgentScanSourceCursorGlobal: "Cursor 全局",+ importAgentScanSourceCursorProject: "Cursor 项目",+ importAgentScanSourceCodex: "Codex",+ importAgentScanSourceOpenCode: "opencode",+ importAgentScanSourceChatgpt: "ChatGPT 桌面版",+ importAgentScanSourcePiUser: "PI 全局(已导入)",+ importAgentScanSourcePiProject: "PI 项目(已导入)",+ importAgentScanSourceUnavailable: "此工具未在本机安装或路径未匹配。",+ importAgentScanTransportStdio: "本地程序",+ importAgentScanTransportHttp: "HTTP",imported: "已导入",skillImported: "已导入 {{name}}",skillsEmpty: "此目录中没有技能",diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 726742e68..23b0f87a5 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -212,10 +212,14 @@ export const IPC = {mcpTransfer: "pi-desktop/mcp/transfer",mcpTest: "pi-desktop/mcp/test",mcpImport: "pi-desktop/mcp/import",+ mcpImportScan: "pi-desktop/mcp/importScan",+ mcpImportRun: "pi-desktop/mcp/importRun",mcpMarketSearch: "pi-desktop/mcp/market/search",skillList: "pi-desktop/skill/list",skillCreate: "pi-desktop/skill/create",skillImport: "pi-desktop/skill/import",+ skillImportScan: "pi-desktop/skill/importScan",+ skillImportRun: "pi-desktop/skill/importRun",skillMarketSearch: "pi-desktop/skill/market/search",skillMarketFetch: "pi-desktop/skill/market/fetch",skillUpdate: "pi-desktop/skill/update",