Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
feat(marketplace): add agent / skill marketplace — listing + install + categories
wyta530e610c8db
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0ec81dc5..9fed0c84 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -135,7 +135,7 @@ PC/data/**Five hard constraints**:1. **At top level**, only `users.json` / `logs/` / `builtin/` / `<uid>/` are allowed; per-user data must land under `<uid>/{cloud,local}/`.-2. **`data/builtin/{agents,skills}/` is a runtime copy**: synced by hash from `src/builtin/` at startup. Agents are directories (`<aid>/agent.json`); skills are directories (`<sid>/SKILL.md`). The loader scans `[<uid>/cloud/, data/builtin/]`; custom takes precedence over a builtin with the same id. `kind` is decided by the spec's root (there is **no** `custom/` / `builtin/` layer inside the directory).+2. **`data/builtin/{agents,skills}/` is a runtime copy**: synced by hash from `src/builtin/` at startup. Agents are directories (`<aid>/agent.json`); skills are directories (`<sid>/SKILL.md`). The loader scans `[<uid>/cloud/, data/builtin/]`; custom takes precedence over a builtin with the same id. `kind` is decided by the spec's root (there is **no** `custom/` / `builtin/` layer inside the directory). **Marketplace exemption**: dirs that carry a top-level `_marketplace.json` sentinel are out-of-band installs from the marketplace (see §6); `syncBuiltin{Agents,Skills}` excludes them from the hash and from the stale-removal pass, and a same-id `src/builtin/` ship does NOT overwrite a marketplace install (the sentinel signals a user-driven choice). The sentinel file itself is never injected into the SkillLoader prompt or read by the agent loader — it's metadata for the sync layer only.3. **Agent directory shape (per-agent asset aggregation)**: `<uid>/cloud/agents/<aid>/` contains `agent.json` (the sole UI display source — pure spec) + `meta/` (metacognition: COMPETENCE.md + LEARNING_STRATEGIES.md) + `skills/` (SkillStore self-evolved skills, visible only to this agent, not injected into the SkillLoader system-prompt block). Deleting an agent = `rm -rf <aid>/`, no cascade. See `docs/plans/agent-as-directory.md`. **Do not** revert to the old top-level `meta/` or `PC/skills/` (the SkillStore default cwd).4. **`search/` indexes are purely derived**: never synced; mtime+size reconcile self-heals before each query; 1-second debounced flush + force flush on `before-quit`; rebuild automatically on schema change or corruption.5. **The KB vector store is part of cloud sync**: on conflict take the newer mtime; the loser's startup `kb_indexer.reconcile(uid)` reconciles by sha1. **Journal mode is DELETE, not WAL** (avoiding `.db-wal` / `.db-shm` sidecar files that would themselves need syncing — empirically that tears).@@ -218,7 +218,7 @@ The artifact card's header collapses into one `⋯` popover: **reload** / **open## 6. Skills-Sources = `src/builtin/skills/` (git-tracked, hash-synced into `data/builtin/skills/` at startup) + `<uid>/cloud/skills/`. `SkillLoader` scans `[user, builtin]` and injects them into the system prompt; **custom takes precedence over a builtin with the same id**. Built-ins are not editable.+Sources = `src/builtin/skills/` (git-tracked, hash-synced into `data/builtin/skills/` at startup) + `<uid>/cloud/skills/` + **marketplace installs** (also land under `data/builtin/skills/<id>/` but with a `_marketplace.json` sentinel — see `features/marketplace.ts`; the sentinel is what makes the startup sync leave them alone, per §4 constraint 2). `SkillLoader` scans `[user, builtin]` and injects them into the system prompt; **custom takes precedence over a builtin with the same id**. Built-ins are read-only in packaged builds. The same marketplace mechanism applies to agents (`data/builtin/agents/<id>/agent.json` + `_marketplace.json`); the on-disk spec shape is unchanged — `category` / `version` live in the sentinel only, never in `agent.json` / SKILL.md frontmatter.**Authoring rules are themselves builtin skills**: `src/builtin/skills/agent-creator/SKILL.md` and `src/builtin/skills/skill-creator/SKILL.md` carry the canonical authoring rules for `<agent>` and `<skill>` containers. The four chat prompts (`chat_commander.md` + the three inline edit chats) point at them via `read_file <ROOT>/agent-creator/SKILL.md`. When changing authoring semantics — field shapes, validation rules, similarity-check protocol, edit-loop, prose forbidden words — update **only** the matching `*-creator/SKILL.md`; the chat prompts already reference it on demand. See §3 "Authoring rules live in builtin skills" for the cross-prompt sync convention.diff --git a/src/main/features/agents.ts b/src/main/features/agents.tsindex 4c8bba8c..e7adcaf2 100644--- a/src/main/features/agents.ts+++ b/src/main/features/agents.ts@@ -184,6 +184,15 @@ export interface AgentChatMeta { session_id?: string; [k: string]: unknown }// 1. Builtin agent sync (startup)// ─────────────────────────────────────────────────────────────────────────+/** A dir is marketplace-installed iff it carries a `_marketplace.json` sentinel — see+ * `features/marketplace.ts::writeSentinel`. Such dirs are owned by the user via the marketplace+ * install flow, NOT by `PC/src/builtin/`, so the startup sync must ignore them: they don't+ * contribute to the hash (otherwise the per-startup short-circuit would never fire when any+ * marketplace item is installed), and they're never garbage-collected. */+function _isMarketplaceInstalled(dir: string): boolean {+ return fs.existsSync(path.join(dir, '_marketplace.json'));+}+/** Hash all agent definitions under `root` (directory form: `<aid>/agent.json`).* Used by `syncBuiltinAgents` to detect upstream changes. Skipped: dot-prefixed* dirs and any subdir without `agent.json` (so the hash is stable against@@ -196,7 +205,9 @@ export function hashTree(root: string): string {.filter((e) => e.isDirectory() && !e.name.startsWith('.')).sort((a, b) => a.name.localeCompare(b.name));for (const e of entries) {- const specFile = path.join(root, e.name, 'agent.json');+ const dir = path.join(root, e.name);+ if (_isMarketplaceInstalled(dir)) continue;+ const specFile = path.join(dir, 'agent.json');if (!fs.existsSync(specFile)) continue;h.update(e.name, 'utf8');h.update(Buffer.from([0]));@@ -220,7 +231,8 @@ export function syncBuiltinAgents(): boolean {fs.readdirSync(root, { withFileTypes: true }).filter((e) => e.isDirectory()&& !e.name.startsWith('.')- && fs.existsSync(path.join(root, e.name, 'agent.json')))+ && fs.existsSync(path.join(root, e.name, 'agent.json'))+ && !_isMarketplaceInstalled(path.join(root, e.name))).map((e) => e.name),);const srcIds = listAgentDirs(BUILTIN_AGENTS_SOURCE);@@ -237,6 +249,9 @@ export function syncBuiltinAgents(): boolean {}}for (const id of [...srcIds].sort()) {+ // Marketplace install of the same id wins (the sentinel signals a user-driven choice that+ // overrides the shipped built-in — same contract as skills.ts::syncBuiltinSkills).+ if (_isMarketplaceInstalled(builtinAgentDir(id))) continue;const src = path.join(BUILTIN_AGENTS_SOURCE, id, 'agent.json');const dst = builtinAgentDefinitionFile(id);try {diff --git a/src/main/features/marketplace.ts b/src/main/features/marketplace.tsnew file mode 100644index 00000000..848da0c6--- /dev/null+++ b/src/main/features/marketplace.ts@@ -0,0 +1,206 @@+/**+ * Marketplace — browse + install official agents / skills from the Orkas Server.+ *+ * Installed items are dropped into the same `data/builtin/{agents,skills}/<id>/` tree as the+ * shipped built-ins so they surface under the existing "Built-in" group in the UI; we mark each+ * installed directory with a `_marketplace.json` sentinel so the startup hash-sync in+ * `agents.ts::syncBuiltinAgents` / `skills.ts::syncBuiltinSkills` doesn't garbage-collect them+ * (they aren't in `PC/src/builtin/`).+ *+ * Skill bundles travel as a single JSON envelope `{files:[{path, encoding, content}]}` so we don't+ * need a zip dependency (per PC/CLAUDE.md §1, every new npm dep needs a discussion). The envelope+ * is small in practice (SKILL.md + a couple of scripts) and the Server caps it at 8 MB.+ *+ * Upload (publishing custom items to the Server) is dev-only and lives in `marketplace_dev.ts`+ * so that file can be excluded from packaged builds via `package.json::build.files` — same+ * physical-exclusion pattern as `features/skills_dev.ts`.+ */++import { app } from 'electron';+import * as fsp from 'node:fs/promises';+import * as path from 'node:path';++import {+ BUILTIN_SKILLS_DIR,+ builtinAgentDir, builtinAgentDefinitionFile,+} from '../paths';+import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-agent/skill-registry';+import { createLogger } from '../logger';++const log = createLogger('marketplace');++// ── server URL ────────────────────────────────────────────────────────────+// Default to production. Devs running against a local Server set ORKAS_API_BASE_URL.+// The `app.isPackaged` fallback below is purely a dev-ergonomics default — packaged users always+// hit prod, unpackaged dev runs default to localhost. The catalog endpoint behaves identically+// either way.+const PROD_BASE = 'https://www.aiservice.fun/api';+const DEV_DEFAULT_BASE = 'http://127.0.0.1:8888/api';+export function apiBase(): string {+ if (process.env.ORKAS_API_BASE_URL) return process.env.ORKAS_API_BASE_URL.replace(/\/+$/, '');+ return app.isPackaged ? PROD_BASE : DEV_DEFAULT_BASE;+}++// ── envelope ──────────────────────────────────────────────────────────────+interface Envelope { code: number; msg?: string; [k: string]: unknown }++async function postJson<T>(p: string, body: unknown): Promise<T> {+ const res = await fetch(`${apiBase()}${p}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body || {}),+ });+ const text = await res.text();+ let data: Envelope;+ try { data = JSON.parse(text); } catch { throw new Error(`bad response (${res.status}): ${text.slice(0, 200)}`); }+ if (data.code !== 0) throw new Error(data.msg || `marketplace ${p} failed (code=${data.code})`);+ return data as unknown as T;+}++// ── types ─────────────────────────────────────────────────────────────────+export interface MarketplaceCategory {+ code: string;+ name_zh: string;+ name_en: string;+ kind: 'agent' | 'skill' | 'both';+ sort_order: number;+}++export interface MarketplaceAgent {+ id: string;+ name: string;+ description_zh: string;+ description_en: string;+ category: string;+ icon: string;+ color: string;+ version: string;+ download_count: number;+ updated_at: number;+}++export interface MarketplaceSkill {+ id: string;+ name: string;+ description_zh: string;+ description_en: string;+ category: string;+ version: string;+ download_count: number;+ updated_at: number;+}++export interface MarketplaceSentinel {+ server_id: string;+ version: string;+ category: string;+ installed_at: number;+}++interface BundleFile { path: string; encoding: 'utf8' | 'base64'; content: string }+interface BundleEnvelope { files: BundleFile[] }++// ── listing ───────────────────────────────────────────────────────────────+export async function listCategories(kind?: 'agent' | 'skill'): Promise<MarketplaceCategory[]> {+ const data = await postJson<{ list: MarketplaceCategory[] }>('/marketplace/categories', { kind });+ return data.list || [];+}++export async function listMarketplaceAgents(+ opts: { category?: string; q?: string; page?: number; size?: number } = {},+): Promise<{ list: MarketplaceAgent[]; total: number }> {+ return await postJson('/marketplace/agents/list', {+ category: opts.category || null,+ q: opts.q || null,+ page: opts.page || 1,+ size: opts.size || 50,+ });+}++export async function listMarketplaceSkills(+ opts: { category?: string; q?: string; page?: number; size?: number } = {},+): Promise<{ list: MarketplaceSkill[]; total: number }> {+ return await postJson('/marketplace/skills/list', {+ category: opts.category || null,+ q: opts.q || null,+ page: opts.page || 1,+ size: opts.size || 50,+ });+}++// ── install ───────────────────────────────────────────────────────────────+export async function installMarketplaceAgent(agentId: string): Promise<{ ok: true; id: string }> {+ if (!agentId) throw new Error('agentId required');+ const data = await postJson<{ spec_json: Record<string, unknown>; version: string; category: string }>(+ '/marketplace/agents/spec', { id: agentId },+ );++ const dir = builtinAgentDir(agentId);+ await fsp.mkdir(dir, { recursive: true });+ await fsp.writeFile(builtinAgentDefinitionFile(agentId), JSON.stringify(data.spec_json, null, 2), 'utf8');+ await writeSentinel(dir, agentId, data.version, data.category);+ log.info(`installed marketplace agent ${agentId} v${data.version} → ${dir}`);+ return { ok: true, id: agentId };+}++export async function installMarketplaceSkill(skillId: string): Promise<{ ok: true; id: string }> {+ if (!skillId) throw new Error('skillId required');+ const meta = await postJson<{ bundle_url: string; version: string; category: string }>(+ '/marketplace/skills/bundle', { id: skillId },+ );++ const res = await fetch(meta.bundle_url);+ if (!res.ok) throw new Error(`download bundle failed (${res.status})`);+ const envText = await res.text();+ let env: BundleEnvelope;+ try { env = JSON.parse(envText); } catch { throw new Error('bundle not JSON'); }+ if (!env.files || !Array.isArray(env.files)) throw new Error('bundle missing files[]');++ const dir = path.join(BUILTIN_SKILLS_DIR, skillId);+ await fsp.rm(dir, { recursive: true, force: true });+ await fsp.mkdir(dir, { recursive: true });++ for (const f of env.files) {+ const safe = safeRelPath(f.path);+ if (!safe) {+ log.warn(`skip bundle entry with unsafe path: ${f.path}`);+ continue;+ }+ const dst = path.join(dir, safe);+ await fsp.mkdir(path.dirname(dst), { recursive: true });+ if (f.encoding === 'base64') {+ await fsp.writeFile(dst, Buffer.from(f.content, 'base64'));+ } else {+ await fsp.writeFile(dst, f.content, 'utf8');+ }+ }++ await writeSentinel(dir, skillId, meta.version, meta.category);+ invalidateCoreAgentSkills();+ log.info(`installed marketplace skill ${skillId} v${meta.version} → ${dir} (${env.files.length} files)`);+ return { ok: true, id: skillId };+}++// ── helpers (exported for marketplace_dev.ts) ─────────────────────────────+export async function writeSentinel(dir: string, serverId: string, version: string, category: string): Promise<void> {+ const sentinel: MarketplaceSentinel = {+ server_id: serverId,+ version: version || '1.0.0',+ category: category || '',+ installed_at: Date.now(),+ };+ await fsp.writeFile(path.join(dir, '_marketplace.json'), JSON.stringify(sentinel, null, 2), 'utf8');+}++/** A path is safe if it's a relative POSIX-style path inside the target dir — no absolute,+ * no `..` segments, no empty / dot paths. Used both when materializing a marketplace skill+ * bundle and when packing one (defense in depth — bundles travel through COS, which is+ * outside our trust boundary). */+export function safeRelPath(rel: string): string | null {+ if (!rel || typeof rel !== 'string') return null;+ if (path.isAbsolute(rel)) return null;+ const norm = path.posix.normalize(rel.replace(/\\/g, '/'));+ if (norm.startsWith('..') || norm.includes('/../') || norm === '.' || norm === '') return null;+ if (norm.startsWith('/')) return null;+ return norm;+}diff --git a/src/main/features/skills.ts b/src/main/features/skills.tsindex 6010e295..35d018c0 100644--- a/src/main/features/skills.ts+++ b/src/main/features/skills.ts@@ -129,6 +129,16 @@ export interface SkillChatMeta { session_id?: string; [k: string]: unknown }// 1. Builtin skill sync (startup)// ═══════════════════════════════════════════════════════════════════════+/** A skill dir is marketplace-installed iff it carries a `_marketplace.json` sentinel — see+ * `features/marketplace.ts::writeSentinel`. Marketplace items aren't in `src/builtin/skills/`,+ * so the startup sync must leave them alone: they're filtered out of the stale-removal step,+ * and a marketplace install of the same id wins over a same-named built-in (built-in does NOT+ * overwrite). The sentinel itself is also excluded from `hashTree` so it doesn't trip the+ * per-startup short-circuit. */+function _isMarketplaceInstalled(dir: string): boolean {+ return fs.existsSync(path.join(dir, '_marketplace.json'));+}+/*** Stable content hash of every file under `root`. Mirrors the Python* `_hash_tree`: relative posix paths + NUL + bytes + newline per file,@@ -145,6 +155,7 @@ export function hashTree(root: string): string {const rel = relBase ? `${relBase}/${e.name}` : e.name;const parts = rel.split('/');if (parts.some((p) => SKILL_TREE_IGNORE.has(p) || p.startsWith('.'))) continue;+ if (e.name === '_marketplace.json') continue;const full = path.join(dir, e.name);if (e.isDirectory()) walk(full, rel);else if (e.isFile()) {@@ -173,8 +184,13 @@ export function syncBuiltinSkills(): boolean {const srcNames = new Set(fs.readdirSync(BUILTIN_SKILLS_SOURCE, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith('.')).map((e) => e.name));+ // Marketplace-installed dirs are filtered out so they neither contribute to "stale" detection+ // (would be deleted because src/builtin doesn't ship them) nor get overwritten by a same-named+ // built-in during the content-diff pass.const dstNames = new Set(fs.readdirSync(BUILTIN_SKILLS_DIR, { withFileTypes: true })- .filter((e) => e.isDirectory() && !e.name.startsWith('.'))+ .filter((e) => e.isDirectory()+ && !e.name.startsWith('.')+ && !_isMarketplaceInstalled(path.join(BUILTIN_SKILLS_DIR, e.name))).map((e) => e.name));let changed = false;@@ -190,10 +206,11 @@ export function syncBuiltinSkills(): boolean {}}- // Content-diff sync+ // Content-diff sync. Skip names where dst is a marketplace install (preserve user choice).for (const name of [...srcNames].sort()) {const src = path.join(BUILTIN_SKILLS_SOURCE, name);const dst = path.join(BUILTIN_SKILLS_DIR, name);+ if (fs.existsSync(dst) && _isMarketplaceInstalled(dst)) continue;const srcHash = hashTree(src);const dstHash = fs.existsSync(dst) && fs.statSync(dst).isDirectory() ? hashTree(dst) : '';if (srcHash === dstHash) continue;diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex f9041f6d..ac110372 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -25,6 +25,7 @@ import * as agents from '../features/agents';import * as scheduledTasks from '../features/scheduled_tasks';import { isAgentEnabled } from '../features/component_enabled';import * as skills from '../features/skills';+import * as marketplace from '../features/marketplace';import * as contexts from '../features/contexts';import * as kbVector from '../features/kb_vector';import * as kbIndexer from '../features/kb_indexer';@@ -601,6 +602,25 @@ const invokeHandlers: Record<string, InvokeHandler> = {return skills.sendToSkillChat(ctx.userId, id, text);},+ // ── Marketplace ──+ // Listing + install endpoints hit the public Server catalog; no auth wiring needed on the+ // client side. Upload endpoints live in `dev_handlers.ts` (dev builds only).+ 'marketplace.categories': async ({ kind } = {}) => ({ list: await marketplace.listCategories(kind) }),++ 'marketplace.listAgents': async (opts = {}) => marketplace.listMarketplaceAgents(opts),++ 'marketplace.listSkills': async (opts = {}) => marketplace.listMarketplaceSkills(opts),++ 'marketplace.installAgent': async ({ id }) => {+ if (!id || typeof id !== 'string') throw new Error('id required');+ return marketplace.installMarketplaceAgent(id);+ },++ 'marketplace.installSkill': async ({ id }) => {+ if (!id || typeof id !== 'string') throw new Error('id required');+ return marketplace.installMarketplaceSkill(id);+ },+// ── Contexts (user-owned directory tree; vectorized via kb_indexer) ──'contexts.tree': async () => ({ tree: contexts.listContextsTree() }),diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex 517945b0..9d59349b 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -166,6 +166,7 @@<div class="skills-grid-view" id="skills-grid-view"><div class="skills-grid-header"><span data-i18n="skills.title">Skills</span>+ <button class="btn btn-sm" id="skills-more-btn" data-i18n="skills.more_btn">More</button><button class="btn btn-sm" id="create-skill-btn" data-i18n="skills.add">+ Add</button></div><div class="skills-grid-scroll">@@ -259,6 +260,7 @@<div class="agents-grid-view" id="agents-grid-view"><div class="agents-grid-header"><span data-i18n="agents.title">Agents</span>+ <button class="btn btn-sm" id="agents-more-btn" data-i18n="agents.more_btn">More</button><button class="btn btn-sm" id="create-agent-btn" data-i18n="agents.create_btn">+ Create</button></div><div class="agents-grid-scroll">@@ -854,6 +856,7 @@<script src="./modules/saved-apps.js"></script><script src="./modules/agent-schedule.js"></script><script src="./modules/utils.js"></script>+ <script src="./modules/marketplace.js"></script><!--MathJax v3.2.2 — TeX → CommonHTML.diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex 0cfcc8a3..3b8465c4 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -199,6 +199,7 @@"chat.skill_file_streaming_placeholder_unknown": "Writing file…","skills.title": "Skills","skills.add": "+ Add",+ "skills.more_btn": "More","skills.custom_group": "Custom","skills.builtin_group": "Built-in","skills.empty": "No skills yet",@@ -246,6 +247,7 @@"skills.delete_failed_with": "Delete failed: {reason}","agents.title": "Agents","agents.create_btn": "+ Create",+ "agents.more_btn": "More","agents.empty": "No agents yet","agents.custom_group": "Custom","agents.builtin_group": "Built-in",@@ -720,5 +722,28 @@"search.role.ai": "AI","model_guard.banner": "No model configured — all features are disabled. Add an API key or sign in first in Settings.","model_guard.cta": "Open Settings",- "model_guard.modal": "No model configured, so this feature is not available.\n\nAdd an API key or sign in first in Settings."+ "model_guard.modal": "No model configured, so this feature is not available.\n\nAdd an API key or sign in first in Settings.",+ "marketplace.title": "Marketplace",+ "marketplace.tab_agent": "Agents",+ "marketplace.tab_skill": "Skills",+ "marketplace.all": "All",+ "marketplace.install": "Install",+ "marketplace.installed": "Installed",+ "marketplace.installing": "Installing…",+ "marketplace.search_ph": "Search",+ "marketplace.empty": "Nothing here yet",+ "marketplace.load_failed": "Failed to load marketplace",+ "marketplace.install_ok": "Installed",+ "marketplace.install_failed": "Install failed: {reason}",+ "marketplace.close": "Close",+ "marketplace.version": "v{version}",+ "marketplace.upload": "Upload to marketplace",+ "marketplace.upload_title": "Upload to marketplace",+ "marketplace.upload_category": "Category",+ "marketplace.upload_version": "Version",+ "marketplace.upload_submit": "Upload",+ "marketplace.upload_ok": "Uploaded",+ "marketplace.upload_failed": "Upload failed: {reason}",+ "marketplace.err_not_dev": "Upload is only available in development builds.",+ "marketplace.err_no_permission": "No permission to upload (server-side phone whitelist)."}diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex cfafc01e..05ae5b91 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -199,6 +199,7 @@"chat.skill_file_streaming_placeholder_unknown": "正在写入文件…","skills.title": "技能库","skills.add": "+ 添加",+ "skills.more_btn": "更多","skills.custom_group": "自定义","skills.builtin_group": "内置","skills.empty": "暂无技能",@@ -246,6 +247,7 @@"skills.delete_failed_with": "删除失败:{reason}","agents.title": "智能体","agents.create_btn": "+ 创建",+ "agents.more_btn": "更多","agents.empty": "暂无智能体","agents.custom_group": "自定义","agents.builtin_group": "内置",@@ -720,5 +722,28 @@"search.role.ai": "AI","model_guard.banner": "尚未配置模型,所有功能均不可用。请先在设置中添加一个 API 密钥或登录账号。","model_guard.cta": "前往设置",- "model_guard.modal": "尚未配置模型,此功能暂不可用。\n\n请先在设置中添加一个 API 密钥或登录账号。"+ "model_guard.modal": "尚未配置模型,此功能暂不可用。\n\n请先在设置中添加一个 API 密钥或登录账号。",+ "marketplace.title": "官方平台",+ "marketplace.tab_agent": "智能体",+ "marketplace.tab_skill": "技能",+ "marketplace.all": "全部",+ "marketplace.install": "安装",+ "marketplace.installed": "已安装",+ "marketplace.installing": "安装中…",+ "marketplace.search_ph": "搜索",+ "marketplace.empty": "暂无内容",+ "marketplace.load_failed": "加载失败",+ "marketplace.install_ok": "安装成功",+ "marketplace.install_failed": "安装失败:{reason}",+ "marketplace.close": "关闭",+ "marketplace.version": "v{version}",+ "marketplace.upload": "上传到官方平台",+ "marketplace.upload_title": "上传到官方平台",+ "marketplace.upload_category": "分类",+ "marketplace.upload_version": "版本",+ "marketplace.upload_submit": "上传",+ "marketplace.upload_ok": "上传成功",+ "marketplace.upload_failed": "上传失败:{reason}",+ "marketplace.err_not_dev": "上传仅支持开发版本。",+ "marketplace.err_no_permission": "无上传权限(需要服务端手机白名单)。"}diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.jsindex ddae6b5d..5bd493c1 100644--- a/src/renderer/modules/agents.js+++ b/src/renderer/modules/agents.js@@ -348,6 +348,10 @@ function _renderAgentRowMenuItems(menu, agentId) {// schedule is a user-orchestration concern that only references the// agent and doesn't mutate its spec.items.push(`<div class="agent-row-menu-item" data-action="schedule">${escapeHtml(t('agents.schedule.menu'))}</div>`);+ if (isCustom && isDevMode()) {+ items.push(`<div class="agent-row-menu-item" data-action="promote">${escapeHtml(t('agents.promote_to_builtin'))}</div>`);+ items.push(`<div class="agent-row-menu-item" data-action="upload-marketplace">${escapeHtml(t('marketplace.upload'))}</div>`);+ }items.push(`<div class="agent-row-menu-item" data-action="toggle-enabled">${escapeHtml(toggleLabel)}</div>`);if (canEdit) {items.push(`<div class="agent-row-menu-item is-danger" data-action="delete">${escapeHtml(t('agents.delete'))}</div>`);@@ -366,6 +370,11 @@ function _renderAgentRowMenuItems(menu, agentId) {} else if (action === 'delete') {if (_selectedAgent?.id !== aid) await selectAgent(aid);await deleteSelectedAgent();++ } else if (action === 'promote') {+ await promoteCustomAgent(aid);+ } else if (action === 'upload-marketplace') {+ if (typeof openMarketplaceUpload === 'function') await openMarketplaceUpload('agent', aid);} else if (action === 'toggle-enabled') {await _flipAgentEnabledFromMenu(aid);} else if (action === 'schedule') {diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.jsindex 36d0ccf4..d7c23fa1 100644--- a/src/renderer/modules/ipc-shim.js+++ b/src/renderer/modules/ipc-shim.js@@ -51,6 +51,11 @@ const _IPC_ROUTES = [['POST', '/api/kb/reconcile', 'kb.reconcile'],['POST', '/api/kb/reprocess', 'kb.reprocess'],['POST', '/api/kb/events/stream', 'kb.events', null, { stream: true }],+ ['POST', '/api/marketplace/categories', 'marketplace.categories'],+ ['POST', '/api/marketplace/agents/list', 'marketplace.listAgents'],+ ['POST', '/api/marketplace/skills/list', 'marketplace.listSkills'],+ ['POST', '/api/marketplace/agents/install', 'marketplace.installAgent'],+ ['POST', '/api/marketplace/skills/install', 'marketplace.installSkill'],// Pattern routes (with path parameters)['DELETE', /^\/api\/conversations\/([^/]+)$/, 'conversations.delete', ['cid']],diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.jsnew file mode 100644index 00000000..e2a88da5--- /dev/null+++ b/src/renderer/modules/marketplace.js@@ -0,0 +1,347 @@+// ─── Marketplace overlay ───+// Browse + install official agents / skills from the Orkas Server. Entered via the "More"+// button on the agents / skills tabs (#agents-more-btn / #skills-more-btn — wired in state.js).+// Per-card 安装 button materializes the item into the local `data/builtin/{agents,skills}/`+// tree with a `_marketplace.json` sentinel so the startup hash-sync leaves it alone.+//+// Dev-only upload (`openMarketplaceUpload`) is exposed for agents.js / skills.js to wire into+// their per-row ⋯ menus on custom items. Visibility of that menu item is gated by+// `app.isDevEnv` (main returns the runtime flag); the upload IPC handler in `dev_handlers.ts`+// also enforces the gate as deep defense.++let _mpOverlay = null;+let _mpState = null;++const MP_PAGE_SIZE = 100;++function isMarketplaceOpen() { return !!_mpOverlay; }++async function openMarketplace(initialTab = 'agent') {+ if (_mpOverlay) {+ _mpState.tab = initialTab;+ _mpRender();+ return;+ }+ _mpState = {+ tab: initialTab === 'skill' ? 'skill' : 'agent',+ category: '',+ q: '',+ agents: [],+ skills: [],+ categories: [],+ installedAgentIds: new Set(),+ installedSkillIds: new Set(),+ loading: true,+ installing: new Set(), // ids currently being installed (button shows spinner state)+ error: '',+ };+ _mpOverlay = _mpBuildOverlay();+ document.body.appendChild(_mpOverlay);+ window.addEventListener('i18n-change', _mpOnI18n);+ await _mpLoadAll();+ _mpRender();+}++function closeMarketplace() {+ if (!_mpOverlay) return;+ window.removeEventListener('i18n-change', _mpOnI18n);+ _mpOverlay.remove();+ _mpOverlay = null;+ _mpState = null;+}++function _mpOnI18n() { if (_mpOverlay) _mpRender(); }++function _mpBuildOverlay() {+ const overlay = document.createElement('div');+ overlay.className = 'modal-overlay marketplace-overlay open';+ overlay.innerHTML = `+ <div class="modal marketplace-modal" role="dialog" aria-modal="true">+ <div class="marketplace-header">+ <div class="marketplace-tabs">+ <button type="button" class="marketplace-tab" data-mp-tab="agent"></button>+ <button type="button" class="marketplace-tab" data-mp-tab="skill"></button>+ </div>+ <input type="text" class="marketplace-search" data-mp-search />+ <button type="button" class="btn btn-sm marketplace-close" data-mp-close></button>+ </div>+ <div class="marketplace-categories" data-mp-categories></div>+ <div class="marketplace-body" data-mp-body></div>+ </div>+ `;+ overlay.addEventListener('click', (e) => { if (e.target === overlay) closeMarketplace(); });+ overlay.querySelector('[data-mp-close]').addEventListener('click', closeMarketplace);+ overlay.querySelectorAll('[data-mp-tab]').forEach((btn) => {+ btn.addEventListener('click', () => {+ _mpState.tab = btn.dataset.mpTab;+ _mpState.category = '';+ _mpRender();+ });+ });+ const search = overlay.querySelector('[data-mp-search]');+ search.addEventListener('keydown', (e) => {+ // IME guard (CLAUDE.md §8) — Enter while composing must commit the candidate, not search.+ if (e.isComposing || e.keyCode === 229) return;+ if (e.key === 'Enter') {+ _mpState.q = search.value.trim();+ _mpLoadListings().then(_mpRender);+ } else if (e.key === 'Escape') {+ closeMarketplace();+ }+ });+ // Esc anywhere closes.+ document.addEventListener('keydown', _mpKey, true);+ return overlay;+}++function _mpKey(e) {+ if (e.key === 'Escape' && _mpOverlay && !e.defaultPrevented) {+ // Don't swallow Esc when focus is in an IME composition.+ if (e.isComposing || e.keyCode === 229) return;+ closeMarketplace();+ }+}++async function _mpLoadAll() {+ _mpState.loading = true;+ _mpState.error = '';+ try {+ const [cats, instAgents, instSkills] = await Promise.all([+ window.orkas.invoke('marketplace.categories', {}),+ window.orkas.invoke('agents.list'),+ window.orkas.invoke('skills.list'),+ ]);+ _mpState.categories = (cats && cats.list) || [];+ _mpState.installedAgentIds = new Set(((instAgents && instAgents.agents) || []).map((a) => a.agent_id));+ _mpState.installedSkillIds = new Set(((instSkills && instSkills.skills) || []).map((s) => s.id));+ await _mpLoadListings();+ } catch (err) {+ _mpState.error = (err && err.message) || String(err);+ } finally {+ _mpState.loading = false;+ }+}++async function _mpLoadListings() {+ try {+ const [agents, skills] = await Promise.all([+ window.orkas.invoke('marketplace.listAgents', {+ category: _mpState.category || null,+ q: _mpState.q || null,+ page: 1,+ size: MP_PAGE_SIZE,+ }),+ window.orkas.invoke('marketplace.listSkills', {+ category: _mpState.category || null,+ q: _mpState.q || null,+ page: 1,+ size: MP_PAGE_SIZE,+ }),+ ]);+ _mpState.agents = (agents && agents.list) || [];+ _mpState.skills = (skills && skills.list) || [];+ } catch (err) {+ _mpState.error = (err && err.message) || String(err);+ }+}++function _mpRender() {+ if (!_mpOverlay || !_mpState) return;+ const lang = getLang();++ // Tab labels+ for (const btn of _mpOverlay.querySelectorAll('[data-mp-tab]')) {+ btn.textContent = btn.dataset.mpTab === 'agent' ? t('marketplace.tab_agent') : t('marketplace.tab_skill');+ btn.classList.toggle('is-active', btn.dataset.mpTab === _mpState.tab);+ }+ _mpOverlay.querySelector('[data-mp-search]').setAttribute('placeholder', t('marketplace.search_ph'));+ _mpOverlay.querySelector('[data-mp-close]').textContent = t('marketplace.close');++ // Category chips — filter to those relevant for the active tab.+ const cats = _mpState.categories.filter((c) =>+ c.kind === 'both' || c.kind === _mpState.tab,+ );+ const chips = [+ `<button type="button" class="marketplace-chip${_mpState.category === '' ? ' is-active' : ''}" data-mp-cat="">${escapeHtml(t('marketplace.all'))}</button>`,+ ...cats.map((c) => {+ const label = lang === 'zh' ? (c.name_zh || c.name_en || c.code) : (c.name_en || c.name_zh || c.code);+ const active = _mpState.category === c.code ? ' is-active' : '';+ return `<button type="button" class="marketplace-chip${active}" data-mp-cat="${escapeHtml(c.code)}">${escapeHtml(label)}</button>`;+ }),+ ].join('');+ const catsEl = _mpOverlay.querySelector('[data-mp-categories]');+ catsEl.innerHTML = chips;+ catsEl.querySelectorAll('[data-mp-cat]').forEach((btn) => {+ btn.addEventListener('click', () => {+ _mpState.category = btn.dataset.mpCat || '';+ _mpLoadListings().then(_mpRender);+ });+ });++ // Body+ const body = _mpOverlay.querySelector('[data-mp-body]');+ if (_mpState.loading) {+ body.innerHTML = `<div class="empty">${escapeHtml(t('common.loading') === 'common.loading' ? '…' : t('common.loading'))}</div>`;+ return;+ }+ if (_mpState.error) {+ body.innerHTML = `<div class="empty">${escapeHtml(t('marketplace.load_failed'))}: ${escapeHtml(_mpState.error)}</div>`;+ return;+ }++ const items = (_mpState.tab === 'agent' ? _mpState.agents : _mpState.skills).slice();+ items.sort((a, b) => (a.name || a.id || '').localeCompare(b.name || b.id || '', undefined, { sensitivity: 'base', numeric: true }));+ if (items.length === 0) {+ body.innerHTML = `<div class="empty">${escapeHtml(t('marketplace.empty'))}</div>`;+ return;+ }++ body.innerHTML = `<div class="marketplace-grid">${items.map((it) => _mpCardHtml(it, lang)).join('')}</div>`;+ body.querySelectorAll('[data-mp-install]').forEach((btn) => {+ btn.addEventListener('click', () => _mpInstall(btn.dataset.mpInstall, btn.dataset.mpId));+ });+}++function _mpCardHtml(item, lang) {+ const kind = _mpState.tab;+ const installed = (kind === 'agent' ? _mpState.installedAgentIds : _mpState.installedSkillIds).has(item.id);+ const installing = _mpState.installing.has(`${kind}:${item.id}`);+ const desc = pickDesc(item, lang) || '';+ const catLabel = _mpCategoryLabel(item.category, lang);+ const versionLabel = t('marketplace.version').replace('{version}', String(item.version || ''));+ const avatar = kind === 'agent'+ ? renderAvatarHtml(item.icon, item.color, { size: 32, seed: item.id, extraClass: 'marketplace-card-avatar' })+ : '';+ let btnClass = 'btn btn-sm btn-primary';+ let btnLabel = t('marketplace.install');+ let btnAttrs = `data-mp-install="${escapeHtml(kind)}" data-mp-id="${escapeHtml(item.id)}"`;+ if (installed) { btnClass = 'btn btn-sm is-disabled'; btnLabel = t('marketplace.installed'); btnAttrs = 'disabled'; }+ else if (installing) { btnClass = 'btn btn-sm is-disabled'; btnLabel = t('marketplace.installing'); btnAttrs = 'disabled'; }+ return `+ <div class="marketplace-card" data-id="${escapeHtml(item.id)}">+ <div class="marketplace-card-header">+ ${avatar}+ <span class="marketplace-card-name">${escapeHtml(item.name || item.id)}</span>+ </div>+ <div class="marketplace-card-desc">${escapeHtml(desc)}</div>+ <div class="marketplace-card-meta">+ <span class="marketplace-card-chip">${escapeHtml(catLabel)}</span>+ <span class="marketplace-card-chip muted">${escapeHtml(versionLabel)}</span>+ </div>+ <div class="marketplace-card-actions">+ <button type="button" class="${btnClass}" ${btnAttrs}>${escapeHtml(btnLabel)}</button>+ </div>+ </div>+ `;+}++function _mpCategoryLabel(code, lang) {+ const c = _mpState.categories.find((x) => x.code === code);+ if (!c) return code || '';+ return lang === 'zh' ? (c.name_zh || c.name_en || code) : (c.name_en || c.name_zh || code);+}++async function _mpInstall(kind, id) {+ const key = `${kind}:${id}`;+ if (_mpState.installing.has(key)) return;+ _mpState.installing.add(key);+ _mpRender();+ try {+ const channel = kind === 'agent' ? 'marketplace.installAgent' : 'marketplace.installSkill';+ const r = await window.orkas.invoke(channel, { id });+ if (!r || r.ok === false) throw new Error((r && r.error) || 'install failed');+ if (kind === 'agent') _mpState.installedAgentIds.add(id);+ else _mpState.installedSkillIds.add(id);+ // Refresh the underlying agents / skills tab so the installed item appears under Built-in.+ if (typeof loadAgents === 'function' && kind === 'agent') await loadAgents(true);+ if (typeof loadSkills === 'function' && kind === 'skill') await loadSkills(true);+ uiAlert(t('marketplace.install_ok'));+ } catch (err) {+ const msg = (err && err.message) || String(err);+ uiAlert(t('marketplace.install_failed').replace('{reason}', msg));+ } finally {+ _mpState.installing.delete(key);+ _mpRender();+ }+}++// ─── Upload dialog (dev only) ─────────────────────────────────────────────+// Callable from agents.js / skills.js per-row menus. Caller passes the custom item's id ++// kind ('agent' | 'skill'); we show a small dialog (category + version) and POST to the dev+// upload endpoint. Visibility of the menu item that calls us is gated by app.isDevEnv in+// agents.js / skills.js; this function ALSO refuses if isDevEnv is false (deep defense).+async function openMarketplaceUpload(kind, id) {+ if (!isDevMode()) { uiAlert(t('marketplace.err_not_dev')); return; }+ if (kind !== 'agent' && kind !== 'skill') return;++ // Need the categories list for the dropdown.+ let categories = [];+ try {+ const r = await window.orkas.invoke('marketplace.categories', {});+ categories = ((r && r.list) || []).filter((c) => c.kind === 'both' || c.kind === kind);+ } catch (err) {+ uiAlert(t('marketplace.load_failed') + ': ' + ((err && err.message) || err));+ return;+ }+ if (categories.length === 0) { uiAlert(t('marketplace.load_failed')); return; }++ const lang = getLang();+ const overlay = document.createElement('div');+ overlay.className = 'modal-overlay ui-dialog-overlay open';+ overlay.innerHTML = `+ <div class="modal ui-dialog" role="dialog" aria-modal="true">+ <div class="ui-dialog-title">${escapeHtml(t('marketplace.upload_title'))}</div>+ <div class="ui-dialog-form">+ <label class="ui-dialog-label">${escapeHtml(t('marketplace.upload_category'))}</label>+ <div data-mp-upload-category></div>+ <label class="ui-dialog-label">${escapeHtml(t('marketplace.upload_version'))}</label>+ <input type="text" class="ui-dialog-input" data-mp-upload-version value="1.0.0" />+ </div>+ <div class="modal-actions">+ <button class="btn" data-act="cancel">${escapeHtml(t('common.cancel') !== 'common.cancel' ? t('common.cancel') : 'Cancel')}</button>+ <button class="btn btn-primary" data-act="ok">${escapeHtml(t('marketplace.upload_submit'))}</button>+ </div>+ </div>+ `;+ document.body.appendChild(overlay);++ const catEl = overlay.querySelector('[data-mp-upload-category]');+ const select = _aiSelectMount(catEl, {+ options: categories.map((c) => ({+ value: c.code,+ label: lang === 'zh' ? (c.name_zh || c.name_en || c.code) : (c.name_en || c.name_zh || c.code),+ })),+ value: categories[0].code,+ onChange: () => {},+ });+ const versionEl = overlay.querySelector('[data-mp-upload-version]');+ versionEl.addEventListener('keydown', (e) => {+ if (e.isComposing || e.keyCode === 229) return;+ if (e.key === 'Escape') finish(false);+ });++ const finish = (val) => { overlay.remove(); resolve(val); };+ let resolve;+ const decision = new Promise((r) => { resolve = r; });+ overlay.querySelector('[data-act="cancel"]').addEventListener('click', () => finish(false));+ overlay.querySelector('[data-act="ok"]').addEventListener('click', () => finish(true));+ overlay.addEventListener('click', (e) => { if (e.target === overlay) finish(false); });++ const ok = await decision;+ if (!ok) return;++ const category = catEl.dataset.value || categories[0].code;+ const version = (versionEl.value || '').trim() || '1.0.0';+ try {+ const channel = kind === 'agent' ? 'marketplace.uploadAgent' : 'marketplace.uploadSkill';+ const payload = kind === 'agent' ? { agent_id: id, category, version } : { id, category, version };+ const r = await window.orkas.invoke(channel, payload);+ if (!r || r.ok === false) throw new Error((r && r.error) || 'upload failed');+ uiAlert(t('marketplace.upload_ok'));+ } catch (err) {+ const msg = (err && err.message) || String(err);+ if (msg === 'E_NOT_DEV') uiAlert(t('marketplace.err_not_dev'));+ else if (/50001|50002|未登录|登录态失效/.test(msg)) uiAlert(t('marketplace.err_no_permission'));+ else uiAlert(t('marketplace.upload_failed').replace('{reason}', msg));+ }+}diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.jsindex 75acd9e9..759c43a9 100644--- a/src/renderer/modules/skills.js+++ b/src/renderer/modules/skills.js@@ -298,6 +298,15 @@ function _openSkillRowMenu(anchorBtn, id, source) {items.push(`<div class="skill-row-menu-item" data-action="toggle-enabled">${escapeHtml(enabled ? t('component.disable') : t('component.enable'))}</div>`,);++ if (source === 'custom' && isDevMode()) {+ items.push(+ `<div class="skill-row-menu-item" data-action="promote">${escapeHtml(t('skills.promote_to_builtin'))}</div>`,+ );+ items.push(+ `<div class="skill-row-menu-item" data-action="upload-marketplace">${escapeHtml(t('marketplace.upload'))}</div>`,+ );+ }if (canEdit) {items.push(`<div class="skill-row-menu-item is-danger" data-action="delete">${escapeHtml(t('skills.delete'))}</div>`);}@@ -320,6 +329,11 @@ function _openSkillRowMenu(anchorBtn, id, source) {// Mimic the existing delete flow (from detail page) but for any card._selectedSkill = { source, id, filepath: 'SKILL.md', name: '' };await deleteSelectedSkill();++ } else if (action === 'promote') {+ await promoteCustomSkill(id);+ } else if (action === 'upload-marketplace') {+ if (typeof openMarketplaceUpload === 'function') await openMarketplaceUpload('skill', id);} else if (action === 'toggle-enabled') {const cur = _skillsCache?.find((s) => s.id === id && s.source === source);const nextEnabled = !(cur ? cur.enabled !== false : true);diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.jsindex a86f0f6c..0c2efdaf 100644--- a/src/renderer/modules/state.js+++ b/src/renderer/modules/state.js@@ -215,6 +215,7 @@ function bindStaticHandlers() {// Agents (grid + detail)// "Done" button (only visible while editing) — exits edit mode.document.getElementById('create-agent-btn')?.addEventListener('click', () => openAgentModal());+ document.getElementById('agents-more-btn')?.addEventListener('click', () => openMarketplace('agent'));document.getElementById('agents-back-btn')?.addEventListener('click', () => _showAgentsGridView());document.getElementById('agent-use-btn')?.addEventListener('click', () => {if (_selectedAgent) useAgent(_selectedAgent.id);@@ -247,6 +248,7 @@ function bindStaticHandlers() {// Skill buttonsdocument.getElementById('create-skill-btn')?.addEventListener('click', () => openSkillModal());+ document.getElementById('skills-more-btn')?.addEventListener('click', () => openMarketplace('skill'));document.getElementById('skill-use-btn')?.addEventListener('click', () => {if (_selectedSkill) useSkill(_selectedSkill.id, _selectedSkill.name);});diff --git a/src/renderer/style.css b/src/renderer/style.cssindex 3b96b84d..1412a391 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -6231,3 +6231,114 @@ body.model-not-configured .main-content { flex-direction: column; }font-weight: 500 !important;margin-bottom: 0 !important;}++/* ─── Marketplace overlay ─── */+/* Wider modal so the card grid breathes; reuse .modal padding / shadow / radius. */+.marketplace-modal {+ max-width: 880px;+ width: 92vw;+ max-height: 86vh;+ display: flex;+ flex-direction: column;+ padding: 0;+}+.marketplace-header {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 16px 20px 12px;+ border-bottom: 1px solid rgba(0,0,0,0.06);+}+.marketplace-tabs { display: flex; gap: 4px; }+.marketplace-tab {+ background: transparent;+ border: none;+ padding: 6px 14px;+ font-size: 14px;+ font-weight: 500;+ color: var(--muted);+ border-radius: 6px;+ cursor: pointer;+}+.marketplace-tab.is-active { background: var(--accent-soft, #eef2ff); color: var(--text); }+.marketplace-search {+ flex: 1;+ padding: 6px 10px;+ border: 1px solid rgba(0,0,0,0.1);+ border-radius: 6px;+ font-size: 13px;+}+.marketplace-close { margin-left: auto; }++.marketplace-categories {+ display: flex;+ gap: 6px;+ flex-wrap: wrap;+ padding: 10px 20px;+ border-bottom: 1px solid rgba(0,0,0,0.04);+}+.marketplace-chip {+ background: transparent;+ border: 1px solid rgba(0,0,0,0.1);+ padding: 4px 12px;+ font-size: 12px;+ border-radius: 999px;+ cursor: pointer;+ color: var(--text);+}+.marketplace-chip.is-active {+ background: var(--accent, #4f46e5);+ border-color: transparent;+ color: #fff;+}++.marketplace-body {+ flex: 1;+ overflow-y: auto;+ padding: 16px 20px 20px;+}+.marketplace-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));+ gap: 14px;+}+.marketplace-card {+ border: 1px solid rgba(0,0,0,0.08);+ border-radius: var(--radius-md, 8px);+ padding: 14px 14px 12px;+ display: flex;+ flex-direction: column;+ gap: 8px;+ background: #fff;+}+.marketplace-card-header { display: flex; align-items: center; gap: 10px; }+.marketplace-card-name { font-weight: 600; font-size: 14px; flex: 1; }+.marketplace-card-desc {+ font-size: 12.5px;+ color: var(--muted);+ line-height: 1.45;+ flex: 1;+ display: -webkit-box;+ -webkit-line-clamp: 3;+ -webkit-box-orient: vertical;+ overflow: hidden;+}+.marketplace-card-meta { display: flex; gap: 6px; flex-wrap: wrap; }+.marketplace-card-chip {+ font-size: 11px;+ padding: 2px 8px;+ border-radius: 999px;+ background: rgba(79,70,229,0.08);+ color: var(--accent, #4f46e5);+}+.marketplace-card-chip.muted { background: rgba(0,0,0,0.05); color: var(--muted); }+.marketplace-card-actions { display: flex; justify-content: flex-end; }++.ui-dialog-form { display: flex; flex-direction: column; gap: 8px; margin: 12px 0; }+.ui-dialog-label { font-size: 12px; color: var(--muted); }+.ui-dialog-input {+ padding: 6px 10px;+ border: 1px solid rgba(0,0,0,0.1);+ border-radius: 6px;+ font-size: 13px;+}diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.tsindex e53bfad9..cb21d8d3 100644--- a/test/main/features/agents.test.ts+++ b/test/main/features/agents.test.ts@@ -1045,3 +1045,100 @@ describe('agents › list cache invalidation', () => {expect(list[0].name).toBe('V2');});});++// Marketplace-installed agents land in the same BUILTIN_AGENTS_DIR as shipped built-ins,+// distinguished only by the `_marketplace.json` sentinel inside the dir. The sync routines+// must (a) leave them alone during the stale-removal pass, and (b) exclude them from the+// hashTree short-circuit so adding/removing a built-in upstream still triggers a re-sync.+describe('agents › marketplace sentinel', () => {+ function writeMarketplaceAgent(id: string): string {+ const dir = path.join(builtinAgentsDir(), id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'agent.json'), JSON.stringify({ agent_id: id, name: id }));+ fs.writeFileSync(path.join(dir, '_marketplace.json'), JSON.stringify({+ server_id: id, version: '1.0.0', category: 'general', installed_at: 1700000000000,+ }));+ return dir;+ }+ // The plain built-in equivalent — dir under BUILTIN_AGENTS_DIR with just agent.json, no+ // sentinel. Used to verify the stale-removal pass still works on non-marketplace dirs.+ function writePlainBuiltinAgent(id: string): string {+ const dir = path.join(builtinAgentsDir(), id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'agent.json'), JSON.stringify({ agent_id: id, name: id }));+ return dir;+ }+ function builtinSrcAgentsDir(): string {+ // `ORKAS_BUILTIN_ROOT` is set to tmpDir, so the SOURCE side resolves to `tmpDir/agents`.+ return path.join(tmpDir, 'agents');+ }+ function writeSrcBuiltinAgent(id: string): void {+ const dir = path.join(builtinSrcAgentsDir(), id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'agent.json'), JSON.stringify({ agent_id: id, name: id }));+ }++ it('hashTree excludes marketplace-installed dirs (sentinel-bearing)', async () => {+ const a = await loadAgents();+ const dir = path.join(tmpDir, 'mixed-mp');+ // Plain built-in+ fs.mkdirSync(path.join(dir, 'plain'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'plain', 'agent.json'), '{"a":1}');+ const baseline = a.hashTree(dir);++ // Add a marketplace install — should NOT change the hash.+ fs.mkdirSync(path.join(dir, 'mp1'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'mp1', 'agent.json'), '{"a":2}');+ fs.writeFileSync(path.join(dir, 'mp1', '_marketplace.json'), '{}');+ expect(a.hashTree(dir)).toBe(baseline);++ // Remove the sentinel — now the dir is "really" a stray built-in and DOES change the hash.+ fs.rmSync(path.join(dir, 'mp1', '_marketplace.json'));+ expect(a.hashTree(dir)).not.toBe(baseline);+ });++ it('syncBuiltinAgents preserves marketplace dirs but still removes plain stale dirs', async () => {+ const a = await loadAgents();+ fs.mkdirSync(builtinAgentsDir(), { recursive: true });+ fs.mkdirSync(builtinSrcAgentsDir(), { recursive: true });++ // Two dirs in dst, neither present in src: one marketplace, one plain stale.+ const mpDir = writeMarketplaceAgent('mp-agent-1');+ const plainDir = writePlainBuiltinAgent('stale-agent-1');++ a.syncBuiltinAgents();++ expect(fs.existsSync(mpDir)).toBe(true);+ expect(fs.existsSync(path.join(mpDir, '_marketplace.json'))).toBe(true);+ expect(fs.existsSync(plainDir)).toBe(false);+ });++ it('syncBuiltinAgents does not overwrite a marketplace dir even when a same-id built-in ships', async () => {+ // The src side ships agent `X`; dst has the same id installed from the marketplace with+ // different content. Marketplace wins (the stale-removal pass skipped it, and the+ // hashTree-based short-circuit should kick in because the marketplace dir is excluded from+ // the hash — both sides see the same hash for the plain set).+ const a = await loadAgents();+ fs.mkdirSync(builtinAgentsDir(), { recursive: true });+ fs.mkdirSync(builtinSrcAgentsDir(), { recursive: true });+ const id = 'shared-id';+ // Src ships content "from-builtin"+ fs.mkdirSync(path.join(builtinSrcAgentsDir(), id), { recursive: true });+ fs.writeFileSync(path.join(builtinSrcAgentsDir(), id, 'agent.json'), '{"v":"from-builtin"}');+ // Dst has a marketplace install with different content+ fs.mkdirSync(path.join(builtinAgentsDir(), id), { recursive: true });+ fs.writeFileSync(path.join(builtinAgentsDir(), id, 'agent.json'), '{"v":"from-marketplace"}');+ fs.writeFileSync(path.join(builtinAgentsDir(), id, '_marketplace.json'), '{}');++ a.syncBuiltinAgents();++ const dst = fs.readFileSync(path.join(builtinAgentsDir(), id, 'agent.json'), 'utf8');+ expect(dst).toBe('{"v":"from-marketplace"}');+ expect(fs.existsSync(path.join(builtinAgentsDir(), id, '_marketplace.json'))).toBe(true);++ // Sanity: a normal src-only id still syncs through unchanged.+ writeSrcBuiltinAgent('plain-src-only');+ a.syncBuiltinAgents();+ expect(fs.existsSync(path.join(builtinAgentsDir(), 'plain-src-only', 'agent.json'))).toBe(true);+ });+});diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.tsindex 537fd6ca..366db536 100644--- a/test/main/features/skills.test.ts+++ b/test/main/features/skills.test.ts@@ -830,3 +830,78 @@ describe('skills › streamSendToSkillChat synthesized progress', () => {expect(events.filter((e) => e.type === 'progress')).toHaveLength(0);});});++// Marketplace-installed skills share BUILTIN_SKILLS_DIR with shipped built-ins, distinguished by+// a top-level `_marketplace.json` sentinel. Sync must leave them alone and the sentinel itself+// must not influence the hash.+describe('skills › marketplace sentinel', () => {+ function builtinSrcSkillsDir(): string {+ return path.join(tmpDir, 'skills'); // ORKAS_BUILTIN_ROOT = tmpDir, so SRC = tmpDir/skills+ }+ function writeMarketplaceSkill(id: string, body = '# from marketplace'): string {+ const dir = path.join(builtinSkillsDir(), id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'SKILL.md'), `---\nname: ${id}\ndescription: mp\n---\n${body}`);+ fs.writeFileSync(path.join(dir, '_marketplace.json'), JSON.stringify({+ server_id: id, version: '1.0.0', category: 'general', installed_at: 1700000000000,+ }));+ return dir;+ }+ function writePlainBuiltinSkillDst(id: string): string {+ const dir = path.join(builtinSkillsDir(), id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'SKILL.md'), `---\nname: ${id}\ndescription: plain\n---\n`);+ return dir;+ }+ function writeSrcBuiltinSkill(id: string, body = '# from src builtin'): void {+ const dir = path.join(builtinSrcSkillsDir(), id);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, 'SKILL.md'), `---\nname: ${id}\ndescription: shipped\n---\n${body}`);+ }++ it('hashTree ignores _marketplace.json at any level', async () => {+ const s = await loadSkills();+ const root = path.join(tmpDir, 'mp-hash');+ fs.mkdirSync(root, { recursive: true });+ fs.writeFileSync(path.join(root, 'SKILL.md'), 'baseline');+ const baseline = s.hashTree(root);++ // Adding the sentinel must NOT change the hash (otherwise every startup would re-sync).+ fs.writeFileSync(path.join(root, '_marketplace.json'), '{"v":"1.0.0"}');+ expect(s.hashTree(root)).toBe(baseline);++ // Mutating SKILL.md still does change it (sanity).+ fs.writeFileSync(path.join(root, 'SKILL.md'), 'baseline-modified');+ expect(s.hashTree(root)).not.toBe(baseline);+ });++ it('syncBuiltinSkills preserves marketplace dirs but still removes plain stale dirs', async () => {+ const s = await loadSkills();+ fs.mkdirSync(builtinSkillsDir(), { recursive: true });+ fs.mkdirSync(builtinSrcSkillsDir(), { recursive: true });++ const mpDir = writeMarketplaceSkill('mp-skill-1');+ const plainDir = writePlainBuiltinSkillDst('stale-skill-1');++ s.syncBuiltinSkills();++ expect(fs.existsSync(mpDir)).toBe(true);+ expect(fs.existsSync(path.join(mpDir, '_marketplace.json'))).toBe(true);+ expect(fs.existsSync(plainDir)).toBe(false);+ });++ it('syncBuiltinSkills does not overwrite a marketplace dir with a same-name shipped skill', async () => {+ const s = await loadSkills();+ fs.mkdirSync(builtinSkillsDir(), { recursive: true });+ fs.mkdirSync(builtinSrcSkillsDir(), { recursive: true });+ const id = 'shared-id';+ writeSrcBuiltinSkill(id, '# from src builtin');+ writeMarketplaceSkill(id, '# from marketplace');++ s.syncBuiltinSkills();++ const dst = fs.readFileSync(path.join(builtinSkillsDir(), id, 'SKILL.md'), 'utf8');+ expect(dst).toContain('from marketplace');+ expect(fs.existsSync(path.join(builtinSkillsDir(), id, '_marketplace.json'))).toBe(true);+ });+});