Skip to content

armgit / Orkas

Public Imported from GitHub
0

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.

feat(marketplace): mature browse + install path; migrate platform installs under <uid>/local/marketplace/

wyt82ef138737d5
diff --git a/CLAUDE.md b/CLAUDE.md
index 9fed0c84..a52d7b5a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -16,9 +16,10 @@ Single-process Electron desktop app: main = Node backend, renderer = vanilla HTM
- **Local CLI agents are the one explicit exception** — agents whose spec carries `runtime.kind === 'cli'` (claude code / codex / openclaw / opencode / hermes) are spawned as child processes by `features/local_agents/runner.ts`. **`features/local_agents/` is the sole `child_process.spawn` entry point for CLI dispatches**; `bus.ts` routes here, every other `features/*` module is forbidden from spawning these CLIs directly. **Why:** a single spawn entry guarantees uniform persistence (`<uid>/local/file_cache/local-agent-runs/<runId>/`), cancellation (AbortSignal → SIGTERM → 10s grace → SIGKILL), and 5-CLI fanout discipline — bypassing it leaks zombies and forks the run-history schema.
- Storage is JSON / JSONL primarily; sqlite is used in exactly one place — the KB vector store. **Why:** user data must stay readable, portable, and friendly to cloud sync (single file = single sync unit).
- **skill / agent / contexts are three first-class citizens**; multi-agent collaboration follows the §5 group-chat architecture, with **no more "main agent calls subagent over RPC"**.
-- npm dependency allow-list is in `PC/package.json` (key entries: `electron / pi-ai / better-sqlite3 / sqlite-vec / fastembed / onnxruntime-node / pdfjs-dist / pdf-lib / mammoth / jimp`). **New dependencies require a discussion first.**
+- npm dependency allow-list is in `PC/package.json` (key entries: `electron / pi-ai / better-sqlite3 / sqlite-vec / fastembed / onnxruntime-node / pdfjs-dist / pdf-lib / mammoth / jimp / adm-zip`). **New dependencies require a discussion first.**
- Renderer-side third-party JS/CSS goes through static assets at `src/renderer/vendor/<name>/`; not via npm. **Why:** `require` is unavailable inside the contextBridge sandbox; routing through npm is actually a detour.
- **Cross-platform**: macOS + Windows are both primary (Linux is community-grade). New code prefers cross-platform implementations (Node stdlib); platform branches must be verified on real machines for each branch — getting one platform working is not enough.
+- **Profile (region) routing**: `ORKAS_PROFILE` env selects which Orkas server region the PC talks to — `global` (default, `orkas.ai`) or `cn` (`orkas.work`). Mirrors Server `env/start/{dev_,}api_start.sh` (see Server CLAUDE.md §7). `run.sh` exports it from the first positional arg (`./run.sh cn`). Code that calls the Orkas API **must** route through `features/marketplace.ts::apiBase()` — never hard-code `orkas.ai` / `orkas.work`. Devs running against a local Server set `ORKAS_API_BASE_URL=http://127.0.0.1:8888/api` (overrides the profile lookup entirely). Telemetry / umami is intentionally NOT profile-gated (single-site analytics, see `renderer/modules/monitor.js` comment).
---
@@ -39,8 +40,7 @@ PC/ Electron project root, sole dev and packaging entry
│ ├── prompts/ *.md templates
│ └── util/ Pure functions (locks / path-sandbox / extract-* / file_to_chunks / ...)
├── src/renderer/ Frontend UI (vanilla, see §8)
-├── src/core-agent/ AgentRunner / providers / PersistentSession / SkillLoader
-└── src/builtin/skills/ Built-in skill source (synced by hash to data/builtin/skills/ on startup)
+└── src/core-agent/ AgentRunner / providers / PersistentSession / SkillLoader
```
**Runtime data location**: dev source-run and packaged builds use the SAME `<container>/{data,userWorkSpace}/` tree — no dev-vs-packaged data split. Container = `~/.orkas/` on macOS/Linux; on Windows it's the drive recorded in `%LOCALAPPDATA%\Orkas\install-pin.json` — chosen on first launch (lowest-letter non-system fixed drive, fallback `C:`) and reused on subsequent launches. The pin lives in LocalAppData (machine-private), not Roaming, because it records a drive choice on this specific machine. Full container resolution + pin handling logic lives in `src/main/install-data-root.cjs`. Pre-unification source-run `<repoRoot>/data` + `<repoRoot>/userWorkSpace` are migrated into the container by `src/main/util/migrate-source-data-root.cjs` on first launch (overlay merge: src wins per-file conflict, target-only paths preserved, `users.json::users[]` unioned with a `current_user_id` dangling-pointer guard).
@@ -84,7 +84,9 @@ util/ Pure-function utilities (stdlib only or single third-party d
Exception: env-var names with the project prefix (`ORKAS_NODE` / `ORKAS_PC_DIR`) are allowed when actually referenced in bash. Before adding/changing a prompt, `grep "Orkas\|/Users/\|/home/\|PC/data\|PC/src" src/main/prompts/*.md` should come back clean.
-**Authoring rules live in builtin skills, not in `chat_*.md`**: the canonical authoring rules for agents (`<agent>` container) and skills (`<skill>` container + `<<<skill-file>>>` blocks) live in two builtin skills — `src/builtin/skills/agent-creator/SKILL.md` and `src/builtin/skills/skill-creator/SKILL.md`. The four prompts that previously copy-pasted these rules (`chat_commander.md`, `chat_agent_setup.md`, `chat_agent_setup_cli.md`, `chat_skill_setup.md`) now carry only a session-shell + `read_file <ROOT>/agent-creator/SKILL.md` (or skill-creator) pointer. **Why:** the rules are ~200 lines each and were duplicated across four prompts (~600 lines drift surface), kept in sync only by reviewer attention; the duplication caused the commander prompt to balloon past 460 lines, putting the rules in the lost-in-the-middle band. Moving them to builtin skills cuts the always-loaded system prompt by ~590 lines and gives every authoring surface a single source of truth — the LLM `read_file`s the skill on demand. **When changing authoring semantics**: update `agent-creator/SKILL.md` or `skill-creator/SKILL.md` only; `grep -E "<agent>|<<<skill-file>>>|agent-creator|skill-creator" src/main/prompts/*.md src/builtin/skills/*-creator/SKILL.md` to confirm the four chat prompts still just point at the skill (no copy-back drift). The loader does not do template composition (only `$variable` substitution), so the on-demand read is the natural sync mechanism — every fresh authoring session re-reads the skill body.
+**Platform-editing language constraint**: when the inline edit chat targets a platform-installed skill / agent (dev mode only — see §6), the system-prompt tail uses `i18n.ts::buildBuiltinEditingConstraint()` instead of `buildLanguageDirective()`. The directive forces English output for every field except `description_zh`, regardless of the user's UI language. **Why:** platform content ships to a multilingual user base; source files must stay English-only (see §6) and per-user UI language must not influence what gets published.
+
+**Authoring rules live in platform skills, not in `chat_*.md`**: the canonical authoring rules for agents (`<agent>` container) and skills (`<skill>` container + `<<<skill-file>>>` blocks) live in two platform skills installed from the marketplace under ids `agent-creator` and `skill-creator`. The four prompts that previously copy-pasted these rules (`chat_commander.md`, `chat_agent_setup.md`, `chat_agent_setup_cli.md`, `chat_skill_setup.md`) now carry only a session-shell + `read_file <ROOT>/agent-creator/SKILL.md` (or skill-creator) pointer. **Why:** the rules are ~200 lines each and were duplicated across four prompts (~600 lines drift surface), kept in sync only by reviewer attention; the duplication caused the commander prompt to balloon past 460 lines, putting the rules in the lost-in-the-middle band. Moving them to platform skills cuts the always-loaded system prompt by ~590 lines and gives every authoring surface a single source of truth — the LLM `read_file`s the skill on demand. **When changing authoring semantics**: update `agent-creator/SKILL.md` or `skill-creator/SKILL.md` in your local install and republish through the marketplace upload flow; `grep -E "<agent>|<<<skill-file>>>|agent-creator|skill-creator" src/main/prompts/*.md` to confirm the four chat prompts still just point at the skill (no copy-back drift). The loader does not do template composition (only `$variable` substitution), so the on-demand read is the natural sync mechanism — every fresh authoring session re-reads the skill body.
**Cross-prompt sync constraint for residual shared rules**: a few smaller cross-prompt concepts still live inline (`<agent-input-form>` / `<agent-input-submission>` extract-first protocol in `chat_agent_in_group.md`, the `chat_shared_rules.md` web/PDF/file-output block injected by `bus.ts::concatSharedRules`). For those, the historical principle stands: pick one authoritative prompt as truth, downstream sites carry only the principle (no field detail / schema tables / full translation tables). Before touching the truth source, run `grep -E "<agent-input-form>|<agent-input-submission>" src/main/prompts/*.md` to reconcile downstream.
@@ -110,7 +112,6 @@ Top-level three-way split: **☁️ cloud** (user-private, synced across devices
PC/data/
├── users.json 🌐 Local uid registry + current_user_id
├── logs/ 🌐 Local logs (rolled daily, shared across uids)
-├── builtin/{agents,skills}/ 🌐 Synced by hash from src/builtin/ at startup (runtime copy; manual edits get overwritten)
└── <user_id>/
├── cloud/ ☁️ Cloud-sync domain
│ ├── chats/<cid>.jsonl + chats/<cid>/{members,state,plan,visibility/} group-chat runtime state (see §5)
@@ -124,21 +125,26 @@ PC/data/
│ ├── agents/<aid>/ Custom agent: agent.json (spec) + meta/ (metacognition) + skills/ (self-evolved SkillStore)
│ ├── skills/<sid>/ Custom skills (System A, scanned by SkillLoader)
│ ├── projects/<pid>/{project.json, bindings.json} Logical groups of conversations + per-project agent/skill scope (no aggregate index — list = directory scan)
+ │ ├── marketplace/installs.json Cloud-synced manifest of platform installs ({id, version, published_at, url} per agent + skill) — reconciled on startup
│ └── config/{preferences,component-enabled}.json
└── local/ 🔒 Machine-private domain (never synced)
- ├── config/ auth-profiles / permissions / reflection-state / web-search-cache
+ ├── config/ User prefs (auth-profiles / permissions / reflection-state / web-search-cache) — NEVER user-clearable
+ ├── biz/ Server-sourced business data (marketplace.json — 24h TTL category registry); refresh-on-need but NOT user-clearable
+ ├── marketplace/{agents,skills}/<id>/ Platform-installed content (per-machine copy reconciled from cloud installs.json)
+ ├── cache/<bucket>/ User-clearable cache umbrella (marketplace/ today; file_cache / tool-results are slated to migrate here)
├── search/ Derived indexes (contexts / chats / skill_chats / agent_chats)
├── workspace.json Scoped workspace selection: `{default, projects:{<pid>:…}}` (legacy flat shape auto-promoted on first read)
├── file_cache/<hash>/ Lazy cache for all files (see features/file_indexer.ts)
└── tool-results/<sid>/ Spill for oversized tool outputs
```
-**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). **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.
+**Hard constraints**:
+1. **At top level**, only `users.json` / `logs/` / `<uid>/` are allowed; per-user data must land under `<uid>/{cloud,local}/`. There is no shipped global `builtin/` tree (retired with the marketplace cutover; one-shot migration in `util/migrate-marketplace.ts` moves any legacy `data/builtin/` into the active uid's cloud tree on first launch, then deletes it).
+2. **Platform agents / skills are marketplace-only**: published to the server via `marketplace_dev.upload*` (dev only), installed via `marketplace.installMarketplace*` to `<uid>/local/marketplace/{agents,skills}/<id>/`. The on-disk dir contains the same shape as a custom one (`agent.json` for agents, `SKILL.md` + script files for skills) plus a `_install.json` with `(version, published_at)` used by reconcile to detect drift. The cloud-synced manifest `<uid>/cloud/marketplace/installs.json` records `{id, version, published_at, url}` per entry; `marketplace_reconcile.reconcileInstalls(uid)` runs on startup, parallel-fetches anything missing from the local tree, and re-pulls when the manifest version disagrees with `_install.json`. **Why this split**: content is binary-blob / catalog-versioned and would tear cloud sync if every machine wrote the same bytes; per-machine local copy + tiny cloud-synced manifest = single source of truth at the manifest level, machine-private at the content level. The loaders scan `[<uid>/cloud/{agents,skills}/, <uid>/local/marketplace/{agents,skills}/]`; custom takes precedence over a platform install with the same id.
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).
+6. **`<uid>/local/cache/<bucket>/` is the user-clearable cache umbrella**. Anything dropped under `cache/` is fair game for the "clear cache" UI button (`features/cache_clearable.ts::clearAllClearable`). Distinct from `config/` (user prefs — never auto-cleared) and `biz/` (server-sourced reference data — refresh-on-need but not user-clearable). The marketplace content cache lives at `cache/marketplace/{agents,skills}/<id>/` with a per-entry `_cache.json` carrying `(server_id, version, published_at, fetched_at, last_used_at)`; entry-time sweep evicts entries idle > 7d AND LRU-trims when total > 100 MB (see `features/marketplace_cache.ts::sweepIfNeeded`, called once per `openMarketplace`). **Note**: `local/marketplace/{agents,skills}/<id>/` (the install target — constraint 2) is NOT under `cache/` and is NOT user-clearable; only the staging cache for browsing detail is. Future migration: `file_cache/` and `tool-results/` will move under `cache/` so a single "clear cache" hits all of them — DON'T yet rely on this; each owner module updates its path helper before the move.
**uid lifecycle** (`features/users.ts`): on startup, `initActiveUser()` reads or creates `users.json` (8-digit numeric uids); `activateUser(uid)` is responsible for skeleton mkdir + injecting `process.env.CORE_AGENT_AUTH_DIR` + clearing caches. All user-scoped features get the uid via `getActiveUserId()` (throws if not activated). One active uid at a time for now.
@@ -218,15 +224,19 @@ 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/` + **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.
+Sources = `<uid>/cloud/skills/` (custom, cloud-synced) + `<uid>/local/marketplace/skills/` (platform, per-machine; reconciled from the cloud-synced `<uid>/cloud/marketplace/installs.json` manifest — see §4 constraint 2). `SkillLoader` scans `[custom, platform]` and injects them into the system prompt; **custom takes precedence over a platform install with the same id**. The same per-machine + cloud-manifest split applies to agents (`<uid>/local/marketplace/agents/<id>/agent.json`). `category` / `version` live in the install manifest, never in `agent.json` / SKILL.md frontmatter for the platform copy; the on-disk spec shape is the same as a custom one.
-**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.
+**Authoring rules are themselves platform skills** (installed from the marketplace under `agent-creator` / `skill-creator` ids): they 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` and republish through the marketplace upload flow; the chat prompts already reference it on demand. See §3 "Authoring rules live in builtin skills" for the cross-prompt sync convention.
-**Built-in skill / agent source files keep their primary text in English** (SKILL.md body / examples under `src/builtin/`, and the system / persona / workflow of built-in agent specs): they ship to a multilingual user base, the LLM auto-replies in the conversation language, and there is no need for a Chinese fallback in the source files; mixing in Chinese makes English-speaking users see half-translated content. Custom skills / agents are user-authored and have no language restriction.
+**Dev-mode only**: platform skills + agents become editable through the existing inline edit chat (the `source !== 'custom'` guard is lifted when `isDevEnv()`); the ⋯ menu also exposes "delete" and "promote to platform" entries. Writes target the local install dir (`<uid>/local/marketplace/{agents,skills}/<id>/`) only — there is no shipped src tree to dual-write into. Server-side publishing is a separate flow through `marketplace_dev.upload*`. Two-layer protection: (1) runtime `isDevEnv()` gate on every entry; (2) physical exclusion at packaging time via `package.json::build.files` `!src/main/features/*_dev.ts` + `!src/main/ipc/dev_handlers.ts` (the dev modules are never present in asar). The setup prompt for platform editing uses `i18n.ts::buildBuiltinEditingConstraint()` (English-only output except `description_zh`) instead of the user-language directive — see §3.
+
+**Platform skill / agent source files keep their primary text in English** (SKILL.md body / examples, and the system / persona / workflow of platform agent specs): they ship to a multilingual user base, the LLM auto-replies in the conversation language, and there is no need for a Chinese fallback in the source files; mixing in Chinese makes English-speaking users see half-translated content. Custom skills / agents are user-authored and have no language restriction.
**Exception: `description` must be bilingual** — SKILL.md frontmatter uses both `description_zh` + `description_en` (the legacy single `description` field is migrated by CJK heuristic in the loader / normalizeAgent buckets, but **new entries always use both fields**); agent spec JSON likewise uses `description_zh` + `description_en`. **Why:** the description is the selection signal seen by the commander / main-conversation LLM (`chat_commander.md:91/96/325`); built-in skills / agents are distributed globally, and an English-only description means a Chinese UI user sees an English description in the list, leading to mis-matches. At runtime, `getSystemPromptBlock` / `_buildAgentsIndexBlock` / UI rendering all pick the right one based on `getCurrentLang()` (the `pickDescription` resolver lives in core-agent + renderer utils, kept in sync). **Pre-translated, not at runtime** — description quality must be controllable, and runtime translation has both quality variance and latency cost.
-**SKILL.md frontmatter has only two fields**: `name` + `description`. **No** `requires` / `external_deps` / `tags` / any other field. Skills have no hard inter-dependencies (no transitive closure, no cross-skill writes); external deps are stated in the body's "External dependencies" section as plain text — runtime does not pre-check or auto-install.
+**SKILL.md frontmatter — allowed fields**: `name` / `description_zh` / `description_en` / `category` (legacy single `description` is migrated by CJK heuristic in the loader). **No** `requires` / `external_deps` / `tags` / `version` / any other field. Skills have no hard inter-dependencies (no transitive closure, no cross-skill writes); external deps are stated in the body's "External dependencies" section as plain text — runtime does not pre-check or auto-install. **`category`** holds a marketplace category code (`marketplace_categories.code` — `education` / `ecommerce` / `rnd` / `writing` / `data` / `general`); required for marketplace publication, optional for user-created skills (defaults to empty string = "uncategorized" in `listSkills` output). The `_install.json` sidecar at the root of a platform-installed skill (`{version, published_at}`) is NOT consumed by SKILL parsing — it's read only by `marketplace_reconcile` to detect manifest/disk drift; `skills.ts::IMPORT_FILTER_NAMES` filters it (plus the legacy clawhub `_meta.json`) on import.
+
+**id ≠ name (loader decouples them)**: `SkillSpec.id = path.basename(dir)` (always the directory name, used as the `read_file <ROOT>/<id>/SKILL.md` path component); `SkillSpec.name = frontmatter name || id` (display label, what the LLM picks from). For **custom** skills they happen to coincide (`features/skills.ts::createCustomSkill` keeps `dir name = frontmatter name`). For **marketplace installs** they diverge — dir is the 12-hex `server_id` (catalog uniqueness), name is the authored human label. **Why:** allows multi-author same-name uploads (server dedup on `(name, create_uid)`); LLM still picks by readable name, reads by id. `skill-registry::renderSkillLines` emits both forms — `**<name>** (id: <id>)` when they differ, `**<id>**` when they don't — and the prompt warning line spells out "use `<id>` in the path even when it differs from the display name". Do NOT re-couple them in the loader (the early invariant was a mistake fixed 2026-05-12).
**`agent.skill_list` three-state**: `undefined` = no filtering (legacy compatibility) / `[]` = zero skills / non-empty = a strict subset. `updateCustomAgent` only does "filter unknown ids" before saving; it does not expand a closure. The field is auto-maintained by the agent-edit LLM via the `<agent><skills>` sub-tag; **the frontend does not expose hand-editing**.
@@ -245,7 +255,7 @@ Sources = `src/builtin/skills/` (git-tracked, hash-synced into `data/builtin/ski
**Write entry points** (rename / URL/dir import): see `features/skills.ts`. Every write entry must call `invalidateSkills()`. The `<<<skill-file>>>` block can only write into the current skill directory (no cross-skill `skill=Y` attribute).
**Two system boundaries (skills have two sets)**:
-- **System A — user/UI-managed skills**: `<uid>/cloud/skills/<sid>/` + `data/builtin/skills/<sid>/`, scanned by `SkillLoader` and injected into the system prompt's "## Available skills" block; SKILL.md frontmatter is `name + description` only; this is the set the UI / skill-edit chat / import flow change.
+- **System A — user/UI-managed skills**: `<uid>/cloud/skills/<sid>/` (custom) + `<uid>/local/marketplace/skills/<sid>/` (platform), scanned by `SkillLoader` and injected into the system prompt's "## Available skills" block; this is the set the UI / skill-edit chat / import flow change.
- **System B — agent self-evolved skills**: `<uid>/cloud/agents/<aid>/skills/<sid>/`, written by core-agent SDK's `SkillStore`, managed via the `skill_manage` tool (create / read / patch / list / delete); **visible only to the owning agent** (fetched via `skill_manage(list/read)`), NOT injected into the SkillLoader system-prompt block. The frontmatter contains runtime fields like `id / patchCount / createdAt / updatedAt / tags`.
- runner.ts explicitly points the `evolution.skillsDir` of the `createConfig` call at `agentEvolvedSkillsDir(uid, agentId)`; **never** let SkillStore fall back to the cwd default and land under `PC/skills/` (we already added that to `.gitignore` as a defense).
@@ -282,6 +292,8 @@ Vanilla HTML/CSS/JS, classic `<script>` multi-file (no ESM, no build). Cross-fil
- The UI shares one set of classes (`.btn / .btn-sm / .btn-primary / .btn-danger / .detail-actions / .empty / .muted`); differences are expressed via `.is-*` modifiers; **don't open near-duplicate classes**.
- **Inventory lists sort A→Z by display name**: any UI list of user-named entities the user scans by name (agents / skills / project bindings + candidate pickers / similar future inventories) defaults to A→Z using `(a.name || a.id || '').localeCompare(other, undefined, { sensitivity: 'base', numeric: true })` — case + diacritics fold, `Item 2` precedes `Item 10`, zh + en mix sorts under default locale collation. **Why:** insertion / mtime order isn't a stable mental model for a name-lookup UI — re-renders shuffle it and users report "很乱" the moment a list grows past a screen. **Exempt** lists where the ordering IS the signal: conversation sidebar (last_active_at desc), project sidebar (created_at desc), search results (score desc), plan rail (step index asc), KB tree (path hierarchy), agent / skill picker fuzzy-search results (match-quality desc — see `agents.js::_renderAgentPickerList`).
- **IME composition guard on Enter / Arrow shortcuts**: every keydown handler on an `<input>` / `<textarea>` that triggers an action (Enter→submit / search-jump / form-confirm; Arrow→list selection) **must early-return when `e.isComposing || e.keyCode === 229`**. **Why:** Chinese / Japanese / Korean IMEs use Enter to commit a composition candidate; without this guard, "Enter to confirm an English candidate when the primary suggestion is already English" silently fires the action and the user navigates away mid-typing. We've already hit this on the global search overlay; the chat input (`modules/conversation.js`) and the new-chat input (`modules/state.js`) had it from the start, the search input was missing it. Pattern to copy: `if (e.isComposing || e.keyCode === 229) return;` at the top of the handler. The `keyCode === 229` arm covers older Electron / Safari builds where `isComposing` is occasionally inaccurate.
+- **Network / long-running actions MUST show a loading affordance**: any user-initiated action that triggers a network round-trip, file IO, or any other operation that can run > ~100 ms (install / uninstall / upload / delete / publish / sync trigger / detail fetch / list fetch) **must surface progress**. **Prefer non-blocking inline loading** over modal blocking: (a) inline spinner inside the trigger button (`.marketplace-btn-spinner` pattern — see `marketplace.js::_mpRenderDetail`) + replace the label with `…ing`, (b) a thin status banner above the affected area (`marketplace.js::_mpUpdateReconcileBanner` pattern), or (c) skeleton / spinner inside the panel body (`.marketplace-detail-loading` — also used by the listing grid on cold open). **Modal blocking overlay is the last resort** — only when the action invalidates other UI surfaces or the user can't safely interact with anything else mid-flight (publish-upload uses one; everything else stays inline). **Why:** without a loading affordance the user can't tell "click registered" from "request hanging" — they click again, fire duplicate requests, or assume failure and abandon the task. Failed actions surface via `uiAlert` after the spinner clears.
+- **Stale-while-revalidate (SWR) for read-heavy network data**: any data that's (a) fetched on every panel open / view enter, (b) tolerant of being seconds-to-minutes out of date, and (c) likely to be re-rendered before the user notices drift (marketplace listings / categories / future "public catalog" panels) **must follow the SWR pattern**, NOT fire-on-every-open: **(1) render from cache immediately** (no blank loading flash when cache exists), **(2) check freshness against a TTL** (in-memory `ts` per entry), **(3) skip the network fetch entirely when within TTL**; outside TTL, fire a background fetch and update both the in-memory cache and (when applicable) a persisted file under `<uid>/local/cache/<bucket>/`. The reference implementation is `marketplace.js::_mpLoadListings` + `marketplace_cache.ts::{get,set}ListingsCache`; TTL there is **10 minutes** (`MP_LISTINGS_TTL_MS`). Pick TTL by data churn: high churn (download counts, online status) → 1-5min; low churn (categories, taxonomy) → 1-24h. **Why:** the previous "fetch every open" behavior hit the server N times per session even when the user just toggled views; SWR cuts traffic by ~one order of magnitude without the user noticing staleness in practice, and the persisted layer kills the cold-start blank flash. **Loading affordance still applies** — on a true cold miss (no cache) the body shows the spinner described above; on a cache hit subsequent background fetches are silent (the cached items already render, no spinner needed).
### i18n (zh / en)
@@ -374,7 +386,7 @@ The renderer evaluates `<script>`-loaded files where `module` is undefined, so t
**Dependencies / config**:
- Add an npm dep (see §1 allow-list).
-- Hand-edit `data/builtin/{agents,skills}/` (overwritten by hash on startup).
+- Hand-edit `<uid>/local/marketplace/{agents,skills}/` (will be overwritten on the next startup reconcile when the cloud `installs.json` records a different version). **Dev-mode UI exception**: the inline edit chat + ⋯ menu's delete / promote-to-platform items write into the platform install dir directly; republish through `marketplace_dev.upload*` to make the change persist for other machines.
- Hand-edit `<uid>/local/config/*.json` (go through the settings UI; `auth-profiles.json` write-entry triggers runner invalidation).
**file-tools misuse**:
diff --git a/package-lock.json b/package-lock.json
index d860d7b0..d708c2d4 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -11,6 +11,7 @@
"license": "MIT",
"dependencies": {
"@mariozechner/pi-ai": "^0.73.0",
+ "adm-zip": "^0.5.16",
"async-mutex": "^0.5.0",
"better-sqlite3": "^12.9.0",
"electron-log": "^5.4.3",
@@ -24,6 +25,7 @@
"zod": "^3.24.0"
},
"devDependencies": {
+ "@types/adm-zip": "^0.5.7",
"@types/node": "^25.6.0",
"electron": "^32.0.0",
"typescript": "^6.0.3",
@@ -2964,6 +2966,16 @@
"tslib": "^2.4.0"
}
},
+ "node_modules/@types/adm-zip": {
+ "version": "0.5.8",
+ "resolved": "https://registry.npmjs.org/@types/adm-zip/-/adm-zip-0.5.8.tgz",
+ "integrity": "sha512-RVVH7QvZYbN+ihqZ4kX/dMiowf6o+Jk1fNwiSdx0NahBJLU787zkULhGhJM8mf/obmLGmgdMM0bXsQTmyfbR7Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/cacheable-request": {
"version": "6.0.3",
"dev": true,
diff --git a/package.json b/package.json
index a84fc318..2466023e 100644
--- a/package.json
+++ b/package.json
@@ -27,6 +27,7 @@
"dist:win": "electron-builder --win"
},
"devDependencies": {
+ "@types/adm-zip": "^0.5.7",
"@types/node": "^25.6.0",
"electron": "^32.0.0",
"typescript": "^6.0.3",
@@ -34,6 +35,7 @@
},
"dependencies": {
"@mariozechner/pi-ai": "^0.73.0",
+ "adm-zip": "^0.5.16",
"async-mutex": "^0.5.0",
"better-sqlite3": "^12.9.0",
"electron-log": "^5.4.3",
diff --git a/run.sh b/run.sh
index e3ea94e5..1e86e7a9 100755
--- a/run.sh
+++ b/run.sh
@@ -1,6 +1,14 @@
#!/bin/bash
# Orkas PC 启动器。放在 PC/ 下,脚本自身所在目录即 PC 根。
# 行为:每次运行都先 kill 旧实例,再启动新进程(前台)。
+#
+# 用法(对齐 Server `env/start/{dev_,}api_start.sh` 的 profile 模式,详见 Server CLAUDE.md §7):
+# ./run.sh # profile=global (默认,海外 orkas.ai)
+# ./run.sh cn # profile=cn (国内 orkas.work)
+# ORKAS_PROFILE=cn ./run.sh # env 风格仍兼容
+# Profile 通过 ORKAS_PROFILE env 传给主进程,由 features/marketplace.ts::apiBase() 等读取,
+# 选择对应区域的 Orkas server。本地 dev 想覆盖到自己 server 的话,仍可单独设
+# ORKAS_API_BASE_URL=http://127.0.0.1:8888/api ./run.sh。
set -e
APP_DIR="$(cd "$(dirname "$0")" && pwd)"
@@ -10,6 +18,10 @@ if [ ! -f "$APP_DIR/package.json" ]; then
exit 1
fi
+# 优先级:位置参数 $1 > 环境变量 ORKAS_PROFILE > 默认 global
+export ORKAS_PROFILE="${1:-${ORKAS_PROFILE:-global}}"
+echo "[Orkas] 启动 profile=$ORKAS_PROFILE"
+
node "$APP_DIR/scripts/ensure-deps.cjs"
cd "$APP_DIR"
diff --git a/src/builtin/agents/658c22c66861/agent.json b/src/builtin/agents/658c22c66861/agent.json
deleted file mode 100644
index e9968988..00000000
--- a/src/builtin/agents/658c22c66861/agent.json
+++ /dev/null
@@ -1,57 +0,0 @@
-{
- "agent_id": "658c22c66861",
- "name": "Software Implementation Engineer",
- "description_zh": "基于需求文档一站式产出技术方案 + 落地高质量代码——从架构 / 技术选型 / 模块划分 / 接口设计到代码骨架 / 核心实现 / 单测 / 端到端验证全包。每个模块写一个跑一个,避免大爆炸提交。适合\"按这份需求把代码写出来\"\"实现 X 项目\"\"把 requirements.md 变成可跑的系统\";触发词:实现、编码、开发、build、写代码、做出来、设计加实现、按需求实现、scaffold",
- "description_en": "Take a requirements doc and deliver both the technical design and high-quality working code in one sweep — from architecture, tech selection, module split and interface contracts to scaffolding, core logic, unit tests, and end-to-end smoke verification. Writes-then-verifies one module at a time to avoid big-bang commits. For: 'turn this requirements doc into running code', 'build out the X project', 'design and implement what's described in requirements.md'; Triggers: implement, build, code, develop, design and implement, deliver, ship, write code, scaffold",
- "workflow": "### 1. Read requirements, settle on a design\n- `read_file(requirements.md)` — read the requirements doc end to end\n- If info is insufficient for design (perf targets / deployment env / scale / hard tech constraints) → `agent-input-form` to ask in one go\n- Internally settle the design: architecture (frontend / backend / data / third-party deps) → tech selection (**prefer mature + community-backed + consistent with project style**, only introduce new tech where actually needed) → module split + responsibilities → key interface contracts → execution order (skeleton → core → edges)\n- `write_file(design.md)` — concise design: architecture sketch + tech selection + module split + interface contracts + main risks\n\n**Output**: `design.md` + internally ordered execution plan\n\n### 2. Scaffold and verify\n- `bash(<project init command: npm init / git init / framework CLI / pnpm install ...>)` — kick off in `$working_dir`\n- `write_file(<placeholder per module>)` — function signatures + one-line docstring. **No fake-stub bodies returning dummy data** (e.g. `return {ok: true}` with empty fields); if you can't write a real minimal impl, leave the body empty or `throw NotImplemented`\n- `bash(<empty-start verification: build / lint / start>)` — confirm toolchain is healthy; fix toolchain first if anything breaks\n\n**Output**: project skeleton + working toolchain\n\n### 3. Implement core modules\n- **One module at a time** — avoid big-bang commits (finish one fully before moving on)\n- Per-module flow: `write_file(<module core impl>)` → `write_file(<key-path unit test>)` → `bash(npm test / pytest / cargo test ...)` to run tests → only proceed when green\n- Code style: single responsibility, clear naming, avoid over-abstraction, comments only for non-obvious why (never restate what), don't add abstraction layers for imagined future needs\n\n**Output**: module impl files + green unit tests\n\n### 4. End-to-end smoke + report\n- `bash(<end-to-end smoke: launch entrypoint + trigger main flow>)` — verify against the requirements acceptance criteria\n- `write_file(README.md)` — how to run / dependencies / entrypoint / known limitations / next steps\n- In the final reply: project structure summary + run commands + acceptance matrix (which requirements met / which skipped and why) + known limitations\n\n**Output**: working code + `README.md` + acceptance report to user",
- "skill_list": [],
- "inputs": [
- {
- "id": "requirements_path",
- "label": "Requirements doc path",
- "type": "text",
- "default": "requirements.md",
- "placeholder": "requirements.md",
- "required": true,
- "description": "Path read via `read_file`, relative to current working directory"
- },
- {
- "id": "scope",
- "label": "Implementation scope",
- "type": "select",
- "default": "mvp",
- "options": [
- {
- "value": "mvp",
- "label": "MVP only (minimal runnable)"
- },
- {
- "value": "full",
- "label": "Full design"
- }
- ],
- "description": "MVP mode implements only items tagged MVP in requirements; gets the system running first"
- },
- {
- "id": "language_pref",
- "label": "Language / stack preference",
- "type": "text",
- "default": "",
- "placeholder": "empty = pick best from requirements",
- "description": "Hard constraints go here; otherwise auto-pick from requirements + project conventions"
- },
- {
- "id": "subdir",
- "label": "Subdirectory for code",
- "type": "text",
- "default": "",
- "placeholder": "empty = working dir root",
- "description": "Subpath relative to working dir; empty drops code at the working dir root"
- }
- ],
- "interactive": false,
- "icon": "code",
- "color": "sage",
- "created_at": "2026-04-29T10:00:00",
- "updated_at": "2026-04-29T10:00:00"
-}
\ No newline at end of file
diff --git a/src/builtin/agents/719a18e993a1/agent.json b/src/builtin/agents/719a18e993a1/agent.json
deleted file mode 100644
index 04183d6f..00000000
--- a/src/builtin/agents/719a18e993a1/agent.json
+++ /dev/null
@@ -1,39 +0,0 @@
-{
- "agent_id": "719a18e993a1",
- "name": "Socratic Learning Coach",
- "description_zh": "持续陪学型学习教练:接收用户请求与材料(可无),同时自动读取最近 5 次学习记录,用苏格拉底式追问带你深入理解要学习的内容;每次结束生成 Markdown 总结并存入本地 learning-log,供下次衔接。",
- "description_en": "Continuous learning companion: takes your request plus optional materials, auto-loads the 5 most recent study notes, and uses Socratic questioning to deepen your understanding. Each session ends with a Markdown summary saved to the local learning-log, ready to hook into the next round.",
- "workflow": "1. Receive the user's request and materials (optional); identify topic, difficulty, prior knowledge.\n2. Read the 5 most recent Markdown summaries from `learning-log/` in the current workspace (sorted by filename timestamp). If none exists, treat this as a first-time session.\n3. Confirm in 3 sentences or fewer: this session's goal and the focus point to break through.\n4. Outline the main thread of the learning content first (use the materials as the spine when present, else the user's goal as the spine), then weave in historical weak spots to form a shallow-to-deep teaching path.\n5. Run Socratic questioning around the content: open-ended first → probe definitions / evidence / counter-examples / boundaries → use hints and analogies to scaffold reasoning.\n6. If an answer drifts, point out the drift and walk back via smaller-step questions; flag whether the same mistake repeats from history.\n7. At the end of each phase, briefly summarize what's mastered vs still fuzzy and pose 1-3 self-check questions; this in-session summary is for current pacing only — do NOT write it to the learning record.\n8. Adapt difficulty dynamically: weak → narrow steps + more examples; strong → raise abstraction + add transfer / critical questions.\n9. When the user explicitly signals \"finished\", or the current topic is complete, output this session's Markdown summary:\n - Core points mastered this session\n - Open questions to revisit\n - New progress / repeated weak spots vs. history\n - Next-step recommendations\n - Self-test question list\n10. Write that session summary to `learning-log/YYYY-MM-DD-HHMM.md`. Create the directory if it's missing. On write failure, tell the user \"failed to record history\".",
- "skill_list": [],
- "inputs": [
- {
- "id": "study_material",
- "label": "Study materials",
- "type": "file",
- "default": [],
- "multiple": true,
- "accept": ".pdf,.doc,.docx,.md,.txt,.ppt,.pptx,.jpg,.jpeg,.png,.webp"
- },
- {
- "id": "study_goal",
- "label": "Learning goal",
- "type": "textarea",
- "default": "",
- "placeholder": "e.g. help me grok this paper's core method, experiment design, and limitations"
- },
- {
- "id": "pace",
- "label": "Pacing",
- "type": "select",
- "default": "balanced",
- "options": [
- { "value": "gentle", "label": "Gradual" },
- { "value": "balanced", "label": "Balanced" },
- { "value": "intensive", "label": "Intensive probing" }
- ]
- }
- ],
- "icon": "flame",
- "color": "blush",
- "interactive": true
-}
diff --git a/src/builtin/agents/e81dc193ed6c/agent.json b/src/builtin/agents/e81dc193ed6c/agent.json
deleted file mode 100644
index c2bcfd37..00000000
--- a/src/builtin/agents/e81dc193ed6c/agent.json
+++ /dev/null
@@ -1,56 +0,0 @@
-{
- "agent_id": "e81dc193ed6c",
- "name": "Software Requirements Analyst",
- "description_zh": "把模糊产品想法挖成可设计可实施的需求文档——三轮深挖:基础信息 → 用户场景与深层痛点 → 方案优化。识别表层需求背后的真痛点,主动给出更优方案建议,产出 `requirements.md`。适合\"做一个 X 产品\"\"帮我把 Y 想法理清楚\"\"我有个 idea 帮我想清楚要做什么\";触发词:需求、PRD、需求文档、requirements、想法、产品定义、需求挖掘、痛点分析、需求分析",
- "description_en": "Turn fuzzy product ideas into a design-and-implementation-ready requirements doc through three rounds of structured digging: basics → user scenarios + deeper pain points → option tradeoffs. Surfaces real pain points behind surface asks and proactively proposes better approaches; produces `requirements.md`. For: 'help me build a product around X', 'I have an idea, help me figure out what to actually build', 'turn this fuzzy ask into proper requirements'; Triggers: requirements, PRD, product spec, requirements analysis, idea, scoping, pain points, user research",
- "workflow": "### 1. Identify project shape, gather basics\n- If user provides an existing requirements doc path → `read_file` to read it as the starting point\n- Identify project shape (new product / iteration / internal tool / service-API) and target user tier (consumer / B2B / internal team)\n- `agent-input-form` to ask all 5-7 basics in one go: shape / target users / core scenarios / platform or channel / tech constraints / delivery timeline / reference products (optional)\n\n**Output**: initial framing, awaiting form submission\n\n### 2. Dig for deeper pain points\n- Probe the current state behind each core scenario: \"How does the user do this today?\" / \"Where do they get stuck?\" / \"What's wrong with alternatives?\" / \"Why hasn't anyone solved it before?\" — this is the key technique for surfacing **deeper pain points** (the user's surface ask is the wrapper; their behavior reveals the real pain)\n- `web_search(competitor name / scenario keywords)` — find 1-2 most relevant references; see how they approach it and what trips them up\n- `agent-input-form` second round, scenario deep-dive: textarea \"current state / main frustrations / ideal experience\" + select to validate your inferred high-frequency assumptions\n\n### 3. Propose better solution candidates\n- Evaluate whether the user's original solution actually addresses the real pain points; the surface \"build me an X\" pattern often maps to **lighter, more direct, narrower-scoped** alternatives\n- List 2-3 candidate variants (focused version / staged version / user's original), each labeled \"what it solves + cost / risk\"\n- `agent-input-form` to let user pick a direction via select + textarea for tradeoff preferences\n\n**Output**: user-selected MVP scope and direction\n\n### 4. Author the requirements doc\n- `write_file($working_dir/requirements.md)` — structure: ① one-line goal ② target user persona ③ core pain points (**inferred from behavior, NOT user's literal words**) ④ core scenarios (user-story format + MVP/v1/v2 tag) ⑤ feature list (must-do / later iterations / **explicitly out of scope**) ⑥ non-functional requirements (perf / security / maintainability — only what matters for this scope) ⑦ **design recommendations** (deltas vs. user's original, with tradeoff notes — make the dig visible) ⑧ known constraints ⑨ acceptance criteria (per MVP item, what counts as \"done\") ⑩ open questions\n- In the final reply: tell user the file path + 3-5 key decisions + items that still need user sign-off\n\n**Output**: `requirements.md` + summary brief to user",
- "skill_list": [],
- "inputs": [
- {
- "id": "idea",
- "label": "Idea description",
- "type": "textarea",
- "default": "",
- "placeholder": "e.g. A tool to help indie developers manage user feedback",
- "required": true,
- "description": "One sentence or short paragraph: what you want to build, what problem it solves"
- },
- {
- "id": "product_type",
- "label": "Project shape",
- "type": "select",
- "default": "new",
- "options": [
- {
- "value": "new",
- "label": "New product"
- },
- {
- "value": "iter",
- "label": "Iteration on existing product"
- },
- {
- "value": "internal",
- "label": "Internal tool"
- },
- {
- "value": "service",
- "label": "Service / API"
- }
- ]
- },
- {
- "id": "existing_doc",
- "label": "Existing requirements / notes",
- "type": "file",
- "default": "",
- "accept": ".md,.pdf,.docx,.txt,.png,.jpg,.jpeg",
- "description": "Existing requirements doc, PRD, idea notes, reference screenshots, etc."
- }
- ],
- "interactive": true,
- "icon": "target",
- "color": "rose",
- "created_at": "2026-04-29T10:00:00",
- "updated_at": "2026-04-29T10:00:00"
-}
\ No newline at end of file
diff --git a/src/builtin/agents/fedc842aedcc/agent.json b/src/builtin/agents/fedc842aedcc/agent.json
deleted file mode 100644
index 71159343..00000000
--- a/src/builtin/agents/fedc842aedcc/agent.json
+++ /dev/null
@@ -1,68 +0,0 @@
-{
- "agent_id": "fedc842aedcc",
- "name": "Vibe Coder",
- "description_zh": "用于快速澄清需求并轻量实现 demo、小应用和原型;默认产出 Web 应用,适合想法验证和快速试做。适合「做个小工具试试」「快速搭个 demo」「先有个能跑的版本」;触发词:demo、原型、小应用、prototype、vibe coding、试做、跑通、能用就行。",
- "description_en": "Clarify intent fast, then ship a lightweight demo, mini-app, or prototype — Web app by default. Built for idea validation and quick first-pass builds. For: 'spin up a small tool', 'just hack together a demo', 'get something runnable end-to-end first'; Triggers: demo, prototype, mini-app, MVP, vibe coding, quick build, just-make-it-run.",
- "workflow": "### 1. Triage the request — clarify or go?\n- **Input**: a natural-language ask for a demo / mini-app, optionally with reference products, target users, scenarios, tech preferences, artifact type.\n- **Action**:\n - Decide if the ask is concrete enough to build: is goal + core features + artifact type mostly there?\n - If yes → skip ahead and converge on scope.\n - If vague, sprawling, or missing key info → enter clarification.\n - Sanity-check fit for vibe coding: single-page tools, form apps, content pages, simple CRUD, small dashboards, light interactive sites, small scripts, MVP validation prototypes.\n- **Output**: triage verdict + clarify/skip decision.\n- **Edge cases**: if the ask is clearly outside fast-prototype scope (full SaaS, complex backend, multi-tenant collab), proactively narrow it to a one-round demo and confirm with the user before building.\n\n### 2. Clarify with the fewest questions possible\n- **Input**: the under-specified request.\n- **Action**:\n - Ask only what affects implementation. Priority order:\n - Who's it for?\n - What are the core features?\n - What artifact? (default: Web app; honor any explicit user pick)\n - Tech preferences? (default: Python / JavaScript / standard Web stack)\n - Bundle 2–4 key questions into one round; avoid back-and-forth.\n- **Output**: minimal-spec summary.\n- **Edge cases**: if the user doesn't want to spell it out, fall back to defaults:\n - Default to a Web app.\n - Collapse front+back where possible, or fake the backend with frontend mocks / local storage.\n - Prefer Python / JavaScript / lightweight Web tech.\n - Prefer single-file or few-file structure.\n - Prefer runnable + demoable over architecturally complete.\n\n### 3. Lock scope and pick the fastest path\n- **Input**: clarified or minimal spec + user tech preferences.\n- **Action**:\n - Compress to MVP scope: which features in, which out, page/module count, data source (real API / mock / local storage / static), artifact form.\n - Pick the fastest delivery stack. Rules of thumb: static page beats backend; local storage beats DB; single page beats multi-page; fewer deps beats heavier engineering. Default order: Python, JavaScript, plain HTML/CSS/JS.\n- **Output**: MVP scope + tech plan summary (file layout, key deps, run command).\n- **Edge cases**: if scope still sprawls, cut auth, payments, complex permissions, DBs, real-time collab, deployment first. If the user-pinned stack is a poor fit for fast demos, name the trade-off and offer a lighter swap.\n\n### 4. Ship the first runnable version\n- **Input**: MVP scope + tech plan.\n- **Action**:\n - Produce a runnable build: necessary code files, run command, sample/default data, short usage notes.\n - Prioritize closing the main loop end-to-end; don't chase polish.\n- **Output**: copy-paste-runnable v1 demo.\n- **Edge cases**: if some piece is uncertain, mock it, stub it, or ship a static placeholder — don't stall on details.\n\n### 5. Self-check, polish, hand off\n- **Input**: v1 code.\n- **Action**:\n - Quick gate: does it run? main loop closed? key interactions demoable? UI usable? run command + deps documented?\n - Package up: project layout note, local-run instructions, current scope, known limitations, possible next steps.\n- **Output**: a small app prototype that's demoable, validates the idea, and is ready to extend.\n- **Edge cases**: if a full implementation is too costly, label placeholders, mock data, and incomplete pieces clearly — never pose a stub as a finished system.\n\n### 6. Iterate in small steps on feedback\n- **Input**: user feedback like \"make it dark\", \"add search\", \"swap to React\", \"more Notion-like\".\n- **Action**:\n - One theme per round (style / interaction / data / stack / structure); ship the updated version fast.\n - For big asks, split into \"smallest fix this round\" + \"next phase\".\n- **Output**: updated code or change notes.\n- **Edge cases**: if a new ask explodes complexity, defer it as next-phase and offer a smaller landable swap for this round.",
- "skill_list": [],
- "inputs": [
- {
- "id": "task",
- "label": "What to build",
- "type": "textarea",
- "default": "",
- "required": true,
- "placeholder": "e.g. a Web app for indie devs to log SaaS ideas — add, search, filter by status"
- },
- {
- "id": "artifact_type",
- "label": "Artifact type",
- "type": "select",
- "default": "web_app",
- "description": "Defaults to Web app; honors your pick if specified",
- "options": [
- { "value": "web_app", "label": "Web app" },
- { "value": "script", "label": "Script tool" },
- { "value": "other", "label": "Other (describe in the request)" }
- ]
- },
- {
- "id": "target_users",
- "label": "Target users",
- "type": "text",
- "default": "",
- "placeholder": "e.g. just me / internal team / portfolio visitors / e-commerce ops"
- },
- {
- "id": "tech_stack",
- "label": "Tech preference",
- "type": "multiselect",
- "default": ["python", "javascript", "html_css_js"],
- "description": "Defaults to lightweight, easy-to-run Python / JavaScript / Web stacks",
- "options": [
- { "value": "python", "label": "Python" },
- { "value": "javascript", "label": "JavaScript" },
- { "value": "html_css_js", "label": "Vanilla Web (HTML/CSS/JS)" },
- { "value": "react", "label": "React" },
- { "value": "nodejs", "label": "Node.js" }
- ]
- },
- {
- "id": "reference_style",
- "label": "Reference product or style",
- "type": "text",
- "default": "",
- "placeholder": "e.g. clean like Notion, or reference a specific site/product"
- },
- {
- "id": "constraints",
- "label": "Constraints",
- "type": "textarea",
- "default": "",
- "placeholder": "e.g. single-file if possible, no DB, mock data first, runnable in under 10 minutes"
- }
- ],
- "icon": "atom",
- "color": "lime",
- "interactive": false
-}
diff --git a/src/builtin/skills/agent-browser/SKILL.md b/src/builtin/skills/agent-browser/SKILL.md
deleted file mode 100644
index 3e59d489..00000000
--- a/src/builtin/skills/agent-browser/SKILL.md
+++ /dev/null
@@ -1,206 +0,0 @@
----
-name: agent-browser
-description_zh: "无头浏览器自动化 CLI,专为 AI agent 设计:用 accessibility tree 快照 + ref 索引选择元素,稳定可控。适合\"打开网页填表单并提交\"\"自动点击导航抓内容\"\"端到端 web 测试\";触发词:浏览器、自动化、表单、点击、导航、网页操作、accessibility、ref"
-description_en: "Headless browser automation CLI optimized for AI agents: accessibility-tree snapshots with ref-based element selection for stable, deterministic flows. For: 'open this page, fill the form, submit', 'click through navigation and grab the content', 'run an end-to-end web test'; Triggers: browser, automation, form, click, navigation, web, accessibility, ref"
----
-
-# Agent Browser Skill
-
-Fast browser automation using accessibility tree snapshots with refs for deterministic element selection.
-
-## Why Use This Over Built-in Browser Tool
-
-**Use agent-browser when:**
-- Automating multi-step workflows
-- Need deterministic element selection
-- Performance is critical
-- Working with complex SPAs
-- Need session isolation
-
-**Use built-in browser tool when:**
-- Need screenshots/PDFs for analysis
-- Visual inspection required
-- Browser extension integration needed
-
-## Core Workflow
-
-```bash
-# 1. Navigate and snapshot
-agent-browser open https://example.com
-agent-browser snapshot -i --json
-
-# 2. Parse refs from JSON, then interact
-agent-browser click @e2
-agent-browser fill @e3 "text"
-
-# 3. Re-snapshot after page changes
-agent-browser snapshot -i --json
-```
-
-## Key Commands
-
-### Navigation
-```bash
-agent-browser open <url>
-agent-browser back | forward | reload | close
-```
-
-### Snapshot (Always use -i --json)
-```bash
-agent-browser snapshot -i --json # Interactive elements, JSON output
-agent-browser snapshot -i -c -d 5 --json # + compact, depth limit
-agent-browser snapshot -s "#main" -i # Scope to selector
-```
-
-### Interactions (Ref-based)
-```bash
-agent-browser click @e2
-agent-browser fill @e3 "text"
-agent-browser type @e3 "text"
-agent-browser hover @e4
-agent-browser check @e5 | uncheck @e5
-agent-browser select @e6 "value"
-agent-browser press "Enter"
-agent-browser scroll down 500
-agent-browser drag @e7 @e8
-```
-
-### Get Information
-```bash
-agent-browser get text @e1 --json
-agent-browser get html @e2 --json
-agent-browser get value @e3 --json
-agent-browser get attr @e4 "href" --json
-agent-browser get title --json
-agent-browser get url --json
-agent-browser get count ".item" --json
-```
-
-### Check State
-```bash
-agent-browser is visible @e2 --json
-agent-browser is enabled @e3 --json
-agent-browser is checked @e4 --json
-```
-
-### Wait
-```bash
-agent-browser wait @e2 # Wait for element
-agent-browser wait 1000 # Wait ms
-agent-browser wait --text "Welcome" # Wait for text
-agent-browser wait --url "**/dashboard" # Wait for URL
-agent-browser wait --load networkidle # Wait for network
-agent-browser wait --fn "window.ready === true"
-```
-
-### Sessions (Isolated Browsers)
-```bash
-agent-browser --session admin open site.com
-agent-browser --session user open site.com
-agent-browser session list
-# Or via env: AGENT_BROWSER_SESSION=admin agent-browser ...
-```
-
-### State Persistence
-```bash
-agent-browser state save auth.json # Save cookies/storage
-agent-browser state load auth.json # Load (skip login)
-```
-
-### Screenshots & PDFs
-```bash
-agent-browser screenshot page.png
-agent-browser screenshot --full page.png
-agent-browser pdf page.pdf
-```
-
-### Network Control
-```bash
-agent-browser network route "**/ads/*" --abort # Block
-agent-browser network route "**/api/*" --body '{"x":1}' # Mock
-agent-browser network requests --filter api # View
-```
-
-### Cookies & Storage
-```bash
-agent-browser cookies # Get all
-agent-browser cookies set name value
-agent-browser storage local key # Get localStorage
-agent-browser storage local set key val
-```
-
-### Tabs & Frames
-```bash
-agent-browser tab new https://example.com
-agent-browser tab 2 # Switch to tab
-agent-browser frame @e5 # Switch to iframe
-agent-browser frame main # Back to main
-```
-
-## Snapshot Output Format
-
-```json
-{
- "success": true,
- "data": {
- "snapshot": "...",
- "refs": {
- "e1": {"role": "heading", "name": "Example Domain"},
- "e2": {"role": "button", "name": "Submit"},
- "e3": {"role": "textbox", "name": "Email"}
- }
- }
-}
-```
-
-## Best Practices
-
-1. **Always use `-i` flag** - Focus on interactive elements
-2. **Always use `--json`** - Easier to parse
-3. **Wait for stability** - `agent-browser wait --load networkidle`
-4. **Save auth state** - Skip login flows with `state save/load`
-5. **Use sessions** - Isolate different browser contexts
-6. **Use `--headed` for debugging** - See what's happening
-
-## Example: Search and Extract
-
-```bash
-agent-browser open https://www.google.com
-agent-browser snapshot -i --json
-# AI identifies search box @e1
-agent-browser fill @e1 "AI agents"
-agent-browser press Enter
-agent-browser wait --load networkidle
-agent-browser snapshot -i --json
-# AI identifies result refs
-agent-browser get text @e3 --json
-agent-browser get attr @e4 "href" --json
-```
-
-## Example: Multi-Session Testing
-
-```bash
-# Admin session
-agent-browser --session admin open app.com
-agent-browser --session admin state load admin-auth.json
-agent-browser --session admin snapshot -i --json
-
-# User session (simultaneous)
-agent-browser --session user open app.com
-agent-browser --session user state load user-auth.json
-agent-browser --session user snapshot -i --json
-```
-
-## Installation
-
-```bash
-npm install -g agent-browser
-agent-browser install # Download Chromium
-agent-browser install --with-deps # Linux: + system deps
-```
-
-## Credits
-
-Skill created by Yossi Elkrief ([@MaTriXy](https://github.com/MaTriXy))
-
-agent-browser CLI by [Vercel Labs](https://github.com/vercel-labs/agent-browser)
diff --git a/src/builtin/skills/agent-creator/SKILL.md b/src/builtin/skills/agent-creator/SKILL.md
deleted file mode 100644
index 5c24a8a8..00000000
--- a/src/builtin/skills/agent-creator/SKILL.md
+++ /dev/null
@@ -1,236 +0,0 @@
----
-name: agent-creator
-description_zh: "用 `<agent>` 容器创建或编辑一个自定义 agent —— 字段、校验、相似度自查、编辑前置 read 协议。适合\"把这次对话沉淀成一个 agent\"\"帮我创建一个负责 X 的 agent\"\"把 X 的 workflow 改成 ...\"\"X 的 description 太啰嗦,改清楚一点\";触发词:创建 agent、做一个 agent、沉淀、改 workflow、调整 description、agent 编辑、新建智能体、修改智能体"
-description_en: "Author or edit a custom agent via the `<agent>` container — field shapes, validation, similarity check, and the read-before-write edit protocol. For: 'crystallize this conversation into an agent', 'make me an agent that does X', 'change X's workflow to ...', 'X's description is too verbose, tighten it'. Triggers: create agent, make an agent, crystallize, edit workflow, adjust description, agent editing, new agent, modify agent."
----
-
-# agent-creator
-
-Authoring rules for creating or editing a custom agent via the `<agent>...</agent>` container. Used by group-chat commander and per-agent inline edit chats. The container is parsed post-stream by `bus.ts`; the LLM does not call any tool — it embeds the container in its final reply text and ends the turn.
-
-## When to consult this skill
-
-`read_file <ROOT>/agent-creator/SKILL.md` whenever you're about to:
-
-- Create a new agent (user says "crystallize / make me an agent / 沉淀这次对话 / 帮我做个 agent").
-- Edit an existing agent (user says "改 X 的 workflow / 给 X 加输入 / X 的 description 太啰嗦").
-
-You **must** consult before emitting any `<agent>` container. The protocol below skips silently if you guess fields from training priors.
-
-## Hard rules (non-negotiable)
-
-- **Mutation only via `<agent>` container.** Do NOT use `edit_file` / `write_file` / `bash` to mutate `agent.json` directly. Read for inspection is allowed; every write goes through the container — the sandbox physically blocks direct writes, the rule here keeps you from wasting tool calls probing it.
-- **Do NOT dump the container as a workspace file** (e.g. `<name>-agent-definition.xml`). The container is a contract between the LLM and the server; the server parses it inline. An extra `write_file` only leaks an unused XML file.
-- **One container per agent being created/edited this turn.** Several containers in one turn are legal only when the user's request spans distinct agents ("tighten the workflow on A and B"). Each container is parsed and applied independently. End the turn after — do NOT call `dispatch_to`.
-- **Output language follows the user's UI language** — `<name>`, `<workflow>` step titles + body, `<inputs>` `label` values, and the prose around the container all go in the user's current UI language (per the "User language" directive in the system prompt; that directive's coverage applies even though this file reaches you as a `read_file` result). `<description_zh>` / `<description_en>` are pinned by suffix. XML tag names, backticked tool / skill names, JSON keys, file paths, and `select` `value` strings stay as-is. The English used in this file is illustrative shape, not literal text to copy.
-
-## Quality bar — designing the agent
-
-Apply these design moves while authoring; they add to (don't replace) the field/format rules below. Each clause is a thing to actively put into the agent — the wording is prescriptive, not just disqualifying.
-
-1. **Position the boundary, including non-goals.** `description_*` already carries the use case + typical user phrasings (per `<description_*>` rules below). Also write what the agent does NOT do where the boundary is fuzzy (e.g. "for Python bug fixing, NOT for cross-language refactor"). Vague boundaries get the agent dispatched for the wrong tasks.
-2. **Build the workflow as a program, not a narrative.** Every action step calls a tool by name; reasoning steps stay short prose; outcomes that change the next step are encoded as `if X → call A / else → call B` (existing format). If a draft step reads as descriptive paragraph ("the agent will think about X and consider Y"), rewrite it into the action that produces that thought (`web_search(...)` then `read_file(...)`). Workflows that read like documentation instead of programs are the dominant authoring failure.
-3. **Insert a confirm step before irreversible operations.** For steps that delete / overwrite / mutate external state (DB / API write / public post / file delete), add an explicit pause-for-user-confirmation step before execution. Recoverable in-workflow exception handling stays out (handled by the runtime — existing rule).
-4. **Make the capability inventory legible.** Have the workflow visibly exercise the agent capabilities it claims — at least one step each for the relevant subset of {planning, reasoning, tool calling, memory, self-reflection, instruction following}. An agent whose workflow leans on none of them is hollow.
-5. **End the workflow on closure.** The final step is either an end-to-end deliverable (file written / answer returned / state set) OR an explicit hand-off naming the downstream consumer; never trail off ambiguously.
-6. **Make the workflow shape back up `<interactive>`.** Set `<interactive>` per the decision rules below, then ensure the workflow shape matches: `false` = no mid-flow "ask user to confirm Y" steps; `true` = identifiable pause points where the workflow expects a user reply. A mismatch (e.g. `false` + workflow contains "ask user...") is a defect — fix one side.
-7. **Refuse to author across security gates.** Do NOT put any of the following into the workflow — if the user's request requires them, stop and explain the request crosses a security gate: ① `curl` / `wget` to unknown URLs or raw IPs; ② reading `~/.ssh` / `~/.aws` / `~/.config` or browser cookies without explicit user grant + reason; ③ touching `MEMORY.md` / `USER.md` / `SOUL.md` / `IDENTITY.md` / `CLAUDE.md`; ④ `eval` / `exec` on external input or any `base64` decode-then-execute; ⑤ modifying system files outside workspace, installing packages without listing them, or requesting sudo.
-
-## Create vs edit decision
-
-- **No `<agent_id>` sub-tag** → create a brand-new agent. Triggered by "crystallize / create / refine an agent from this conversation"; base it on the **whole conversation history** in **one shot**, distilling "what the user has been doing repeatedly".
-- **With `<agent_id>X</agent_id>`** → patch the existing custom agent X. Sub-tags you emit replace the field; sub-tags you omit are preserved. Triggered by "改 X 的 workflow / 给 X 加输入 / X 的 description ..." etc.
-
-## Pre-create similarity check (new agents only)
-
-> _CLI-backed agent inline edit chat: skip — that surface never creates._
-
-Before emitting `<agent>` for a NEW agent, scan `agents_index` (in the system prompt's runtime injection) for an entry whose **name** OR **description's typical objects + actions** overlap with what you're about to crystallize.
-
-- **Overlap found** → STOP, do NOT emit `<agent>`. In one prose paragraph (user UI language) name the existing `@<name>`, state the overlap, and ask whether to use the existing one or still create a new one. Emit `<agent>` only after the user picks "create new".
-- **No overlap** → emit `<agent>` in the same turn. Do NOT pre-announce ("let me confirm… I'll customize one for you") — the prose accompanying the container IS the announcement.
-
-## Editing protocol — required loop
-
-When `<agent_id>` is the right move (the user is changing an existing agent), follow this loop **before** emitting the container — skipping any step risks silent data loss:
-
-1. **Read the current spec.** Take the `id` field from the matching `agents_index` entry and `read_file` per the path pattern in that block's header. Never rewrite from memory — `agents_index` carries a slim view (description / inputs only); skipping this step ⇒ silently wiping fields you didn't intend to touch.
-2. **Confirm the agent is editable here.**
- - `Source: builtin` → reply with one prose line (user UI language) saying built-in agents can't be edited from this surface; the user can fork a custom copy from the detail panel. Then stop. **Do not emit `<agent>`**.
- - `runtime.kind === 'cli'` (external CLI agent: claude code / codex / openclaw / opencode / hermes — they bring their own prompt; runtime / model / args owned by the create-modal + edit-form, not the LLM) → in the per-agent CLI edit chat, only `name` / `description_zh` / `description_en` / `inputs` / `interactive` are editable; do NOT emit `<workflow>` / `<skills>` / `<runtime>` / `<system>` / `<persona>`. In the group-chat commander, reply with one prose line saying these are detail-panel-only and stop.
-3. **Emit `<agent>` with `<agent_id>` first** plus only the sub-tags you're changing. Absent sub-tags preserve the current value. Empty body (e.g. `<inputs></inputs>` or `<skills></skills>`) is the explicit "clear this list" signal — use deliberately.
-4. **`<inputs>` is full-list replace, NOT per-id merge.** If the user is "adding a new input field", emit the entire updated list (every existing input + the new one). Emitting only the new one wipes the rest. Same rule for `<skills>`.
-
-## Container format
-
-```
-<agent>
-<agent_id>(omit when creating; required when editing)</agent_id>
-<name>A short unquoted name</name>
-<description_zh>① 一句功能:动词+对象+交付 ;② 适合"用户原话1""用户原话2"…;③ 触发词:词1、词2、…</description_zh>
-<description_en>① one-line function: verb+object+delivery ; ② For: "user phrasing 1", "user phrasing 2", … ; ③ Triggers: word1, word2, …</description_en>
-<workflow>
-Stepwise markdown. Step format = `### N. <title>` + bulleted actions. Tool / skill names in backticks where invoked.
-</workflow>
-<skills>
-skill_id_a
-skill_id_b
-</skills>
-<inputs>
-[
- {"id": "...", "label": "...", "type": "text|textarea|select|multiselect|number|boolean|file", "required": true, "default": "...", "description": "..."}
-]
-</inputs>
-<interactive>false</interactive>
-</agent>
-```
-
-- **Creating** (no `<agent_id>`): missing `<name>` / `<workflow>` causes the server to treat it as a failure; all other sub-tags are recommended.
-- **Editing** (with `<agent_id>`): every sub-tag except `<agent_id>` is optional; emit only the ones you're changing.
-- The container is auto-hidden from the user-visible message; the prose accompanying it is what the user sees.
-
-## Field rules
-
-### `<name>`
-
-- Written in the user's current UI language. Chinese UI → Chinese name (e.g. `需求挖掘者`); English UI → English name (e.g. `requirements-miner`). Don't auto-romanize Chinese into pinyin or auto-translate to English — match the user's actual locale.
-- Charset is strictly limited: ASCII letters / digits / `_` / `-` / CJK U+4E00–U+9FFF / single internal spaces between tokens. **Forbidden**: `/` `\` `.` `,` `(` `)` `:` `;` `!` `?`, full-width punctuation (`·` `(` `)` `:` etc.), Japanese kana, Korean Hangul, extended-CJK, emoji.
-- **Why**: the `@`-mention router uses regex token class `[A-Za-z0-9_一-鿿-]`; a name with any other character truncates at the illegal char and mis-routes the dispatch. The validator rejects offending names with `E_AGENT_NAME_INVALID` and the create / edit fails.
-
-### `<description_zh>` + `<description_en>` — the dispatch signal
-
-This is the **only** signal the commander uses when picking who to dispatch (workflow / inputs / skills are NOT visible at dispatch time). A vague description = the agent is never picked, or mis-picked, or effectively dead.
-
-- **Both are required**, written **independently** in the **three-part formula** (don't direct-translate; appeal to the real phrasings of users in each language):
- 1. **One-line function** = verb + object + delivery, naming the **typical objects** and **typical actions**. Avoid empty boilerplate like "an AI assistant for X".
- 2. **`适合` / `For:`** + 2–3 quoted **real user phrasings** — the actual sentences future users will send to the commander; the closer your quoted phrasings are to those, the better the match.
- 3. **`触发词:` / `Triggers:`** + 5–8 keywords (separated by `、` / `,`).
-- **Do not** use a single `<description>` tag — deprecated; the system would heuristically bucket-sort by literal Chinese-character presence into `_zh` / `_en`, easily putting English in the wrong slot.
-- When editing, judge each language **independently** — if you only changed one, emit only that one; do not emit an empty placeholder for the other.
-
-Example (Chinese): `抓取小红书 / Reddit / X 上的关键词帖子并做情绪分析;适合"分析一下小红书最近的 X 话题""找几条 Reddit 上关于 Y 的高赞帖";触发词:抓一下、找一下、分析一下、舆情、热度`
-
-Example (English): `Fetch posts matching given keywords on Xiaohongshu / Reddit / X and produce sentiment analysis; For: 'analyze the latest X discussion on Xiaohongshu', 'check Reddit sentiment for product Y'; Triggers: fetch, find, analyze, sentiment, buzz, reputation`
-
-### `<workflow>`
-
-> _LLM-managed agents only. CLI-backed agents have no workflow — skip._
-
-Ordered steps in physical execution order. Each step:
-
-```
-### N. <verb-led title, 5–10 chars>
-- `tool_name(key params)` — purpose & inline result (when a tool is invoked)
-- reasoning / decision / synthesis bullets: plain prose, no tool name
-- branches use nested bullets (`if X → call A` / `else → call B`)
-```
-
-The previous step's result / inbound message / accumulated context are the default carry-over and need not be restated. Exception handling / retry / skip belongs to the runtime agent, not the workflow.
-
-**Tool / skill names: required in backticks where invoked, forbidden where not.** Every invoked tool / skill_id appears in backticks (`read_file` / `kb_search` / `social-fetch` skill / `markdown_to_pdf` / `web_search` — no abstract verbs like "read the file"). Reasoning / decision / synthesis bullets that don't invoke a tool stay in plain prose; don't fake-attach `write_file` to mean "I produced this conceptually". **Why**: workflow is injected into the runtime agent's system prompt (invoked tools need canonical names so the runtime picks right) and `<skills>` closure is derived from skill_ids appearing here.
-
-**Tool / skill priority** when authoring workflow actions:
-1. Built-in tools (file IO, `bash`, `kb_search`, `kb_read`, `markdown_to_pdf`, `html_to_pdf`, `generate_image`, `web_search`, `web_fetch`) — write the tool name directly.
-2. Existing skills from the "Available skills" block — used as-is by `skill_id`.
-3. Only when neither covers it, mention the missing capability in user-perspective prose; do NOT invent skill_ids.
-
-Built-in tool names are NOT skill_ids and must never appear in `<skills>`.
-
-**Web access**: the system auto-picks "vendor-native search → search-type skill → built-in `web_search`+`web_fetch`" in three tiers; in workflow just write "use `web_search`" — at runtime it upgrades per available capability. Don't write degradation branches.
-
-Do NOT include a top-level `# Workflow` heading inside the sub-tag — the UI already wraps it.
-
-### `<skills>`
-
-> _LLM-managed agents only. CLI-backed agents bring their own tooling via the bound CLI — skip._
-
-- One `skill_id` per line. List only skills the workflow actually invokes + hard dependencies; the closure is expanded server-side.
-- `skill_id` must come from the system prompt's "Available skills" section; do not invent or misspell.
-- An empty `<skills></skills>` is **common, legal, and recommended** when the workflow uses only built-in tools — don't stuff in skills just because the system prompt lists many.
-
-### `<inputs>` — the one-shot form before the agent runs
-
-JSON array describing parameters the main conversation collects via a form before dispatching. Whenever the workflow says "user provides / picks / default Y / options Z" → that becomes an `inputs` entry.
-
-- Each input has: `id` (snake_case, regex `^[a-z_][a-z0-9_]{0,31}$`) / `label` (user-facing, in user UI language, no internal ids) / `type` (`text` | `textarea` | `select` | `multiselect` | `number` | `boolean` | `file`) / `default` (always required — pick most common; `""` for free text; `[]` for multiselect or default-deselected; `false`/`true` for boolean; `""` or `[]` for file).
-- `select` / `multiselect` need `options: [{value, label}]` — `value` is the internal id passed to the workflow (ASCII snake_case), `label` is the user-facing display in user UI language; `default` must be a value present in options.
-- Optional: `description` (helper text), `required` (form validates non-empty), `placeholder`, `min` / `max` (numeric bounds), `multiple: true` + `accept: ".pdf,.docx,image/*"` for file.
-- **No `show_if` / conditional fields** — schema must be visible at a glance.
-- **Prefer `select` / `multiselect` / `boolean` over `text`** — if a dropdown works, don't free-form. The whole point of an upfront form is to pre-narrow choices.
-- `[]` (empty list) when the workflow needs zero structured choices. An empty sub-tag is more explicit than omitting — it tells the system "this agent has confirmed zero inputs".
-- **Full-list replace, NOT per-id merge** — when adding one input, emit the entire updated list.
-- **About `file` type**: files picked are auto-uploaded to the conversation's `chat_attachments/` directory; the user message includes them as attachments. Downstream tools access them by **filename** via `read_file` — do not splice absolute paths in the form's input value.
-- On parse failure the server drops `inputs` but other fields still take effect.
-
-### `<interactive>` — input-box auto-retarget
-
-Decides whether, when the agent is dispatched, the input box auto-retargets to this agent so the user doesn't need to manually `@` it to reply.
-
-- **`true`** = the workflow truly **depends on multi-turn user replies** to advance. Common shapes: companion / coach / tutor / role-play / guided interview / emotional support. The user's next sentence is auto-routed to it.
-- **`false`** (default) = once dispatched, the agent **completes autonomously**; only the deliverable is handed back. Common shapes: worker / scraper / report-writer / code-gen / batch.
-
-Decision rules (ask in order):
-1. Does the workflow explicitly say "wait for user reply / guide user thinking / I respond once per user message"? → `true`.
-2. Does the workflow have an `inputs` form that takes one-shot parameters and then runs autonomously? → `false` (one-shot parameter confirmation is NOT interaction).
-3. Positioned as "companion / coach / consultant / counselor / study buddy"? → `true`.
-4. Positioned as "worker / scraper / writer / code-generator / report-generator"? → `false`.
-5. Unsure → `false`. Wrongly setting `true` mis-routes the user's next sentence to the agent (worse UX than the inverse error).
-
-Inside the tag, **only** literal `true` / `false` (lowercase); other characters leave the field at its old value.
-
-## Field sync policy
-
-`<name>` / `<description_zh>` / `<description_en>` / `<workflow>` are emitted **only if changed this turn**; otherwise omit.
-
-`<skills>` / `<inputs>` / `<interactive>` are emitted **in full whenever workflow is discussed / adjusted / reviewed** (they are bound to workflow shape and must not drift).
-
-**Don't emit a container at all when** ① no field was adjusted this turn (pure discussion / restating); ② the user is asking something unrelated to the agent (small talk, weather, etc.).
-
-## CLI-backed agents (runtime.kind === 'cli')
-
-CLI agents (claude code / codex / openclaw / opencode / hermes) bring their own prompt and execute the task in an external CLI. They have a **smaller editable surface**:
-
-- **Editable**: `name` / `description_zh` / `description_en` / `inputs` / `interactive`.
-- **NOT editable from any LLM surface**: `workflow` / `skills` / `runtime` / `system` / `persona`. The runtime (which CLI / which model / extra args) is configured by the user via the modal + settings UI.
-- **Description must be CLI-agnostic** — describe the agent's responsibility, not the runtime. **Never name a specific CLI / brand / model** in the description (`Claude Code`, `Codex`, `GPT-5`, `Sonnet`, `Anthropic`, `OpenAI`, etc.) — the user can swap CLIs at any time; if the description hard-codes one, the selection signal goes stale the moment the user switches.
-- **Inputs are usually empty or very few** for CLI agents — most coding tasks let the user describe what they want in conversation. Add inputs only for genuinely structured choices ("review depth: quick / deep" / "target stack: Python / Go / TS").
-
-## Conversation prose rules — what the user sees
-
-The conversation prose **outside** the `<agent>` container is what the user sees. Only state three things from the **user's perspective**: what this agent does / when to use it / what substantive change you made this round.
-
-**Forbidden words** (never appear in conversation prose):
-- Field / XML tag names: `interactive` / `inputs` / `skills` / `workflow` / `description` / `description_zh` / `description_en` / `name` / `<agent>` / `<agent_id>` / any `<xxx>` tag.
-- Data-structure terms: `schema` / `frontmatter` / `JSON` / `closure` / `select` / `multiselect` / `options` / `default` / `required` / "field" / "sub-tag" / "container" / "config" / id / hex strings.
-- For CLI agents: specific CLI / brand / model names (`Claude Code` / `Claude` / `Codex` / `GPT-*` / `OpenClaw` / `OpenCode` / `Hermes` / `Anthropic` / `OpenAI` / `Sonnet` / `Opus` / `Haiku` etc.).
-
-**Map field changes to user-perspective concepts** (write the actual sentence in user UI language; the descriptions below are abstract patterns, not literal phrasings):
-- `interactive=true` → "the agent will chat back and forth with the user".
-- `interactive=false` → "the agent runs autonomously, no mid-task reply needed".
-- editing `inputs` → "what the form asks the user before running".
-- editing `skills` → "what capabilities the agent uses".
-- editing `workflow` → "what steps the agent follows / how it does the task".
-- editing `description_zh` / `description_en` / `name` → "I updated its description / name to ..." (do NOT expose the bilingual nature or specific field names).
-
-**Style contrast**:
-- ✗ exposing internals: writes field names, data-structure terms, ids, or "closure"-flavoured language.
-- ✓ user-perspective: describes the change in plain prose using what the user cares about (when it runs, what it asks beforehand, what capabilities it uses, what it produces).
-
-## Quick example — editing one field
-
-> _LLM-managed agents only. The example below edits `<workflow>`, which CLI-backed agents do not have._
-
-```
-Tightened its workflow so it now reviews the workspace twice — first for logic, then for security gaps — before producing the report.
-
-<agent>
-<agent_id>a9fe44ea7fce</agent_id>
-<workflow>
-### 1. Read code
-- `read_file` walks `$working_dir` in directory order
-...
-</workflow>
-</agent>
-```
-
-The prose line is what the user sees; the container is parsed and applied silently. No field names leak into prose.
diff --git a/src/builtin/skills/excel-xlsx/SKILL.md b/src/builtin/skills/excel-xlsx/SKILL.md
deleted file mode 100644
index b98949b2..00000000
--- a/src/builtin/skills/excel-xlsx/SKILL.md
+++ /dev/null
@@ -1,104 +0,0 @@
----
-name: Excel / XLSX
-slug: excel-xlsx
-version: 1.0.2
-homepage: https://clawic.com/skills/excel-xlsx
-description_zh: "创建、查看、编辑 Microsoft Excel 工作簿和 XLSX 文件,公式 / 日期 / 类型 / 格式 / 重算 / 模板都可靠。适合\"做一个 Excel 财务报表\"\"把 CSV 整理成带公式的 xlsx\"\"修改这个 .xlsx 文件并保留模板格式\";触发词:excel、xlsx、xls、csv、tsv、表格、工作簿、公式、电子表格"
-description_en: "Create, inspect, and edit Microsoft Excel workbooks and XLSX files with reliable formulas, dates, types, formatting, recalculation, and template preservation. Use when (1) the task is about Excel, `.xlsx`, `.xlsm`, `.xls`, `.csv`, or `.tsv`; (2) formulas, formatting, workbook structure, or compatibility matter; (3) the file must stay reliable after edits."
-changelog: Tightened formula anchoring, recalculation, and model traceability after a stricter external spreadsheet audit.
-metadata: {"clawdbot":{"emoji":"📗","requires":{"bins":[]},"os":["linux","darwin","win32"]}}
----
-
-## When to Use
-
-Use when the main artifact is a Microsoft Excel workbook or spreadsheet file, especially when formulas, dates, formatting, merged cells, workbook structure, or cross-platform behavior matter.
-
-## Core Rules
-
-### 1. Choose the workflow by job, not by habit
-
-- Use `pandas` for analysis, reshaping, and CSV-like tasks.
-- Use `openpyxl` when formulas, styles, sheets, comments, merged cells, or workbook preservation matter.
-- Treat CSV as plain data exchange, not as an Excel feature-complete format.
-- Reading values, preserving a live workbook, and building a model from scratch are different spreadsheet jobs.
-
-### 2. Dates are serial numbers with legacy quirks
-
-- Excel stores dates as serial numbers, not real date objects.
-- The 1900 date system includes the false leap-day bug, and some workbooks use the 1904 system.
-- Time is fractional day data, so formatting and conversion both matter.
-- Date correctness is not enough if the number format still displays the wrong thing to the user.
-
-### 3. Keep calculations in Excel when the workbook should stay live
-
-- Write formulas into cells instead of hardcoding derived results from Python.
-- Use references to assumption cells instead of magic numbers inside formulas.
-- Cached formula values can be stale, so do not trust them blindly after edits.
-- Check copied formulas for wrong ranges, wrong sheets, and silent off-by-one drift before delivery.
-- Absolute and relative references are part of the logic, so copied formulas can be wrong even when they still "work".
-- Test new formulas on a few representative cells before filling them across a whole block.
-- Verify denominators, named ranges, and precedent cells before shipping formulas that depend on them.
-- A workbook should ship with zero formula errors, not with known `#REF!`, `#DIV/0!`, `#VALUE!`, `#NAME?`, or circular-reference fallout left for the user to fix.
-- For model-style work, document non-obvious hardcodes, assumptions, or source inputs in comments or nearby notes.
-
-### 4. Protect data types before Excel mangles them
-
-- Long identifiers, phone numbers, ZIP codes, and leading-zero values should usually be stored as text.
-- Excel silently truncates numeric precision past 15 digits.
-- Mixed text-number columns need explicit handling on read and on write.
-- Scientific notation, auto-parsed dates, and stripped leading zeros are common corruption, not cosmetic issues.
-
-### 5. Preserve workbook structure before changing content
-
-- Existing templates override generic styling advice.
-- Only the top-left cell of a merged range stores the value.
-- Hidden rows, hidden columns, named ranges, and external references can still affect formulas and outputs.
-- Shared strings, defined names, and sheet-level conventions can matter even when the visible cells look simple.
-- Match styles for newly filled cells instead of quietly introducing a new visual system.
-- If the workbook is a template, preserve sheet order, widths, freezes, filters, print settings, validations, and visual conventions unless the task explicitly changes them.
-- Conditional formatting, filters, print areas, and data validation often carry business meaning even when users only mention the numbers.
-- If there is no existing style guide and the file is a model, keep editable inputs visually distinguishable from formulas, but never override an established template to force a generic house style.
-
-### 6. Recalculate and review before delivery
-
-- Formula strings alone are not enough if the recipient needs current values.
-- `openpyxl` preserves formulas but does not calculate them.
-- Verify no `#REF!`, `#DIV/0!`, `#VALUE!`, `#NAME?`, or circular-reference fallout remains.
-- If layout matters, render or visually review the workbook before calling it finished.
-- Be careful with read modes: opening a workbook for values only and then saving can flatten formulas into static values.
-- If assumptions or hardcoded overrides must stay, make them obvious enough that the next editor can audit the workbook.
-
-### 7. Scale the workflow to the file size
-
-- Large workbooks can fail for boring reasons: memory spikes, padded empty rows, and slow full-sheet reads.
-- Use streaming or chunked reads when the file is big enough that loading everything at once becomes fragile.
-- Large-file workflows also need narrower reads, explicit dtypes, and sheet targeting to avoid accidental damage.
-
-## Common Traps
-
-- Type inference on read can leave numbers as text or convert IDs into damaged numeric values.
-- Column indexing varies across tools, so off-by-one mistakes are common in generated formulas.
-- Newlines in cells need wrapping to display correctly.
-- External references break easily when source files move.
-- Password protection in old Excel workflows is not serious security.
-- `.xlsm` can contain macros, and `.xls` remains a tighter legacy format.
-- Large files may need streaming reads or more careful memory handling.
-- Google Sheets and LibreOffice can reinterpret dates, formulas, or styling differently from Excel.
-- Dynamic array or newer Excel functions like `FILTER`, `XLOOKUP`, `SORT`, or `SEQUENCE` may fail or degrade in older viewers.
-- A workbook can look fine while still carrying stale cached values from a prior recalculation.
-- Saving the wrong workbook view can replace formulas with cached values and quietly destroy a live model.
-- Copying formulas without checking relative references can push one bad range across an entire block.
-- Hidden sheets, named ranges, validations, and merged areas often keep business logic that is invisible in a quick skim.
-- A workbook can appear numerically correct while still failing because filters, conditional formats, print settings, or data validation were stripped.
-- A workbook can be numerically correct and still fail visually because wrapped text, clipped labels, or narrow columns were never reviewed.
-
-## Related Skills
-Install with `clawhub install <slug>` if user confirms:
-- `csv` — Plain-text tabular import and export workflows.
-- `data` — General data handling patterns before spreadsheet output.
-- `data-analysis` — Higher-level analysis that can feed workbook deliverables.
-
-## Feedback
-
-- If useful: `clawhub star excel-xlsx`
-- Stay updated: `clawhub sync`
diff --git a/src/builtin/skills/excel-xlsx/_meta.json b/src/builtin/skills/excel-xlsx/_meta.json
deleted file mode 100644
index b14a3240..00000000
--- a/src/builtin/skills/excel-xlsx/_meta.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "ownerId": "kn73vp5rarc3b14rc7wjcw8f8580t5d1",
- "slug": "excel-xlsx",
- "version": "1.0.2",
- "publishedAt": 1773243166499
-}
\ No newline at end of file
diff --git a/src/builtin/skills/find-skill/SKILL.md b/src/builtin/skills/find-skill/SKILL.md
deleted file mode 100644
index 3603b564..00000000
--- a/src/builtin/skills/find-skill/SKILL.md
+++ /dev/null
@@ -1,365 +0,0 @@
----
-name: find-skill
-description_zh: 按 ClawHub、skill.sh / SkillHub、GitHub 的顺序查找与需求匹配的 skill,并整理可安装候选清单;适合“帮我找一个能抓网页的 skill”“有没有处理 Excel 的 skill”“去 GitHub 找类似的技能”;触发词:找skill、查skill、安装skill、clawhub、skill.sh、skillhub、GitHub、技能市场
-description_en: Find skills matching a user need in priority order across ClawHub, skill.sh / SkillHub, and GitHub, then return installable candidates; For: "find me a skill for web scraping", "is there a skill for Excel files", "look for similar skills on GitHub"; Triggers: find skill, search skill, install skill, ClawHub, skill.sh, SkillHub, GitHub, skill marketplace
----
-
-# find-skill
-
-Discover an installable skill that already covers a user's need, search across ClawHub → skill.sh / SkillHub → GitHub in strict priority order, and return a ranked candidate list with install hints.
-
-## When to use
-
-- "Find me a skill that handles PDFs / scrapes Xiaohongshu / drives a browser."
-- "Is there an existing skill for X?" — before authoring a new one.
-- "Look on GitHub / ClawHub / skill.sh for something similar."
-
-**Don't do** when the user already supplied a concrete skill URL or local directory and only wants that one installed — hand it to the install path directly, no discovery needed.
-
-## How to call
-
-### 1. Convert the request into searchable capability terms
-
-- Primary task: e.g. scrape webpage, process Excel, generate slides, drive browser.
-- Inputs: keywords, URL, file, account, API key, etc.
-- Outputs: JSON, report, file, chart, edited document.
-- Platform constraints: Chinese platform, GitHub, browser login, specific SaaS, Windows / macOS, etc.
-
-Compose 2–5 search phrases:
-
-- Chinese: e.g. `网页抓取 skill`, `Excel 处理 skill`.
-- English: e.g. `web scraping skill`, `Excel xlsx agent skill`.
-- Synonyms: e.g. `browser automation` / `web automation`.
-
-### 2. Search sources in fixed priority order
-
-Walk the sources in order. Move to the next source **only when the current source has no acceptable candidate**.
-
-#### Source 1 — ClawHub (try first)
-
-ClawHub is the preferred source.
-
-```bash
-npx clawhub search "keyword"
-npx clawhub browse
-npx clawhub search "web search"
-npx clawhub search "weather"
-npx clawhub search "document"
-npx clawhub search "github"
-npx clawhub search --sort installs
-npx clawhub search --sort stars
-```
-
-Public pages:
-
-- `https://clawhub.ai/`
-- Detail page, e.g. `https://clawhub.ai/fangkelvin/find-skills-skill`
-
-Treat ClawHub as "has a good candidate" when **all** of the following hold:
-
-- Capability directly covers the user's need.
-- Clear README / `SKILL.md` / install instructions.
-- Not a tutorial post, blog article, or empty repo.
-- Dependencies are acceptable.
-- At least one `fit: high`, or several `medium` candidates worth offering.
-
-If satisfied, **stop**. Do not continue to skill.sh / SkillHub or GitHub.
-
-#### Source 2 — skill.sh / SkillHub (only if ClawHub has nothing)
-
-```bash
-npx skills find "keyword"
-npx skills add <owner/repo@skill>
-npx skills add <owner/repo@skill> -g -y # global, skip confirmation
-```
-
-Public pages:
-
-- `https://skillhub.cn/skills/find-skills`
-- `https://skillhub.cn/`
-- `https://skills.sh/`
-
-SkillHub HTTP endpoints:
-
-```text
-https://api.skillhub.cn/api/skills?page=1&pageSize=10&keyword=<keyword>
-https://api.skillhub.cn/api/v1/skills/<slug>
-https://api.skillhub.cn/api/v1/skills/<slug>/files
-https://api.skillhub.cn/api/v1/skills/<slug>/file?path=SKILL.md
-https://api.skillhub.cn/api/v1/download?slug=<slug>
-```
-
-Treat SkillHub as "has a good candidate" when:
-
-- Result name, description, or `SKILL.md` matches the need.
-- An install command, detail page, or download link is reachable.
-- The hit is an installable skill, not a marketing list or curated index page.
-- Install source is clear and dependency risk is explainable.
-
-If satisfied, **stop**. Do not continue to GitHub.
-
-#### Source 3 — GitHub (only if both above have nothing)
-
-Prefer the `gh` CLI to search and read repositories.
-
-Verify CLI availability first:
-
-```bash
-gh --version
-gh auth status
-```
-
-If unauthenticated, public search may still work; on rate limit or permission error, ask the user to run `gh auth login`.
-
-Search code containing `SKILL.md`:
-
-```bash
-gh search code 'filename:SKILL.md web scraping skill' --limit 20
-gh search code 'filename:SKILL.md browser automation' --limit 20
-gh search code 'filename:SKILL.md Excel xlsx agent skill' --limit 20
-gh search code 'filename:SKILL.md openclaw skill' --limit 20
-gh search code 'filename:SKILL.md claude skill' --limit 20
-```
-
-Replace `<capability>` with the user's task:
-
-```bash
-gh search code 'filename:SKILL.md <capability>'
-gh search code 'filename:SKILL.md <capability> skill'
-gh search code 'filename:SKILL.md <capability> agent skill'
-gh search code 'filename:SKILL.md <capability> openclaw skill'
-gh search code 'filename:SKILL.md <capability> claude skill'
-```
-
-Search relevant repositories:
-
-```bash
-gh search repos '<capability> skill' --limit 20 --json fullName,description,url,updatedAt,stargazersCount
-gh search repos '<capability> agent skill' --limit 20 --json fullName,description,url,updatedAt,stargazersCount
-gh search repos '<capability> SKILL.md' --limit 20 --json fullName,description,url,updatedAt,stargazersCount
-gh search repos 'awesome claude skills <capability>' --limit 20 --json fullName,description,url,updatedAt,stargazersCount
-```
-
-When `gh search code` output is not structured enough, fall back to the API:
-
-```bash
-gh api search/code -f q='filename:SKILL.md <capability>' -f per_page=20 \
- --jq '.items[] | {name: .name, path: .path, repo: .repository.full_name, url: .html_url}'
-```
-
-Inspect a candidate repo:
-
-```bash
-gh repo view OWNER/REPO --json nameWithOwner,description,url,updatedAt,stargazerCount,defaultBranchRef,licenseInfo
-gh api repos/OWNER/REPO/contents --jq '.[] | {path: .path, type: .type, size: .size}'
-gh api -H "Accept: application/vnd.github.raw" repos/OWNER/REPO/contents/SKILL.md
-gh api -H "Accept: application/vnd.github.raw" repos/OWNER/REPO/contents/path/to/SKILL.md
-gh api repos/OWNER/REPO/readme --jq '.content' | base64 -d
-gh api repos/OWNER/REPO/commits -f per_page=5 \
- --jq '.[] | {sha: .sha, date: .commit.author.date, message: .commit.message}'
-gh release list --repo OWNER/REPO --limit 10
-```
-
-For a quick whole-repo scan, shallow-clone to a scratch directory:
-
-```bash
-gh repo clone OWNER/REPO /tmp/skill-candidate -- --depth 1
-```
-
-Recommended search phrasing:
-
-```text
-<capability> skill SKILL.md
-<capability> agent skill
-<capability> openclaw skill
-<capability> claude skill
-filename:SKILL.md <capability>
-```
-
-When inspecting candidates, prioritize:
-
-- Has `SKILL.md`.
-- Has scripts, configs, examples, or install instructions.
-- Is a single skill, not a doc inside a larger unrelated project.
-- Recent commits, open issues, README completeness.
-- No hard requirement on API key, login state, private service, or heavy dependency.
-
-### 3. Pull candidate details
-
-For every candidate, capture:
-
-- Name and source.
-- Detail page URL.
-- `SKILL.md` or README.
-- File listing.
-- Install command or download link.
-- Dependency requirements.
-- Visible signals: security scan, maintenance status, downloads, stars.
-
-### 4. Rank candidates
-
-1. Source priority: ClawHub > skill.sh / SkillHub > GitHub.
-2. Fit: directly covers the need > partial > reference only.
-3. Installability: directly installable > needs assembly > reference material only.
-4. Dependency risk: no extra dep > common runtime > API key / login state / private service.
-5. Documentation quality: clear usage + examples > description only.
-6. Maintenance signals: recent updates, downloads, stars, security scan.
-
-If ClawHub already has one high-fit candidate, do not extend the search to GitHub just to bring back more results — unless the user explicitly asks to "search across all platforms".
-
-### 5. Return the candidate list
-
-State in the reply:
-
-- The understood need.
-- Sources actually searched.
-- Whether the search stopped early because an earlier source already returned a fit.
-- Best matches.
-- Notable non-matches and reasons.
-- Install-time risks.
-- Recommended next step.
-
-## Return format
-
-On a successful find:
-
-```json
-{
- "query_understood_as": "the capability the user is looking for",
- "searched_sources": ["ClawHub"],
- "stopped_because": "ClawHub already returned a good candidate; skill.sh / SkillHub and GitHub were not searched",
- "best_matches": [
- {
- "title": "candidate name",
- "source": "ClawHub | skill.sh / SkillHub | GitHub",
- "url": "https://...",
- "install": "install command or download URL; null when unknown",
- "capability": "what it does",
- "fit": "high | medium | low",
- "why": "why it matches",
- "installability": "directly installable | needs assembly | reference only",
- "risks": ["dependency / login / API key / maintenance risks"]
- }
- ],
- "notable_non_matches": [
- {
- "title": "candidate name",
- "url": "https://...",
- "reason": "why it was skipped"
- }
- ],
- "recommendation": "next step"
-}
-```
-
-On no fit found:
-
-```json
-{
- "query_understood_as": "the capability the user is looking for",
- "searched_sources": ["ClawHub", "skill.sh / SkillHub", "GitHub"],
- "best_matches": [],
- "recommendation": "No directly installable existing skill found; suggest authoring a new skill scoped to this need with a minimum-feature outline."
-}
-```
-
-## External dependencies
-
-- Network access — required to search public skill sources and read candidate files; if unavailable, explain that online discovery cannot be completed.
-- ClawHub CLI / `npx clawhub` — useful for ClawHub search and browsing; if unavailable, fall back to the public ClawHub pages and report that CLI search was not run.
-- Skills CLI / `npx skills` — useful for skill.sh / skills.sh ecosystem search and install commands; if unavailable, use public pages and API results where possible.
-- GitHub CLI / `gh` — required for GitHub repo search, code search, file inspection, and release checks; install from `https://cli.github.com/`, then run `gh auth login` if search is rate-limited.
-- GitHub access — useful for inspecting repositories and raw files; if rate-limited or unavailable, rely on other public search results and note the limitation.
-- Source availability — repositories or platforms may block access, move files, or require login; if blocked, report the inaccessible URL.
-
-## Limits / known issues
-
-- Search results may include tutorials, templates, README-only repositories, or marketplace listings that are not directly installable.
-- ClawHub and SkillHub pages may be dynamic; if rendered text is incomplete, switch to the documented API endpoints, raw files, or CLI output.
-- GitHub code search may require login and may be rate-limited; if `gh search code` fails, ask the user to authenticate with `gh auth login` or continue with repository search only.
-- Some skills depend on private APIs, browser login state, or local credentials that cannot be verified from the listing alone.
-- Repository popularity does not guarantee skill quality; always inspect the actual usage notes and files.
-- Respect the source order. Do not search GitHub just to add more results when ClawHub already has a good match.
-
-## Full examples
-
-### Example 1
-
-User request:
-
-```text
-Find me a skill that automates filling and submitting web forms.
-```
-
-Output:
-
-```json
-{
- "query_understood_as": "find a skill that drives a browser to navigate, click, fill, and submit web forms",
- "searched_sources": ["ClawHub"],
- "stopped_because": "ClawHub returned a high-fit candidate; skill.sh / SkillHub and GitHub were not searched",
- "best_matches": [
- {
- "title": "Example Browser Automation Skill",
- "source": "ClawHub",
- "url": "https://clawhub.ai/example/browser-automation",
- "install": "npx clawhub install browser-automation",
- "capability": "Drives a browser to navigate, click, fill inputs, and submit forms",
- "fit": "high",
- "why": "Capability covers web form automation and ships with explicit invocation notes",
- "installability": "directly installable",
- "risks": ["May require a local browser runtime", "Cannot reliably handle complex CAPTCHAs"]
- }
- ],
- "notable_non_matches": [],
- "recommendation": "Install the top-fit candidate; before installing, confirm a browser runtime is available locally."
-}
-```
-
-### Example 2
-
-User request:
-
-```text
-Is there a skill that analyzes the sentiment of TikTok comments?
-```
-
-GitHub search commands tried:
-
-```bash
-gh search code 'filename:SKILL.md TikTok sentiment comments skill' --limit 20
-gh search repos 'TikTok sentiment comments agent skill' --limit 20 --json fullName,description,url,updatedAt,stargazersCount
-gh api search/code -f q='filename:SKILL.md TikTok sentiment comments' -f per_page=20 \
- --jq '.items[] | {path: .path, repo: .repository.full_name, url: .html_url}'
-```
-
-Output:
-
-```json
-{
- "query_understood_as": "find a skill that fetches TikTok comments and produces a sentiment summary",
- "searched_sources": ["ClawHub", "skill.sh / SkillHub", "GitHub"],
- "stopped_because": "ClawHub and skill.sh / SkillHub returned no high-fit installable candidate, so GitHub was searched",
- "best_matches": [
- {
- "title": "Social Comment Analyzer",
- "source": "GitHub",
- "url": "https://github.com/example/social-comment-analyzer",
- "install": null,
- "capability": "Fetches comments from select social platforms and outputs a sentiment summary",
- "fit": "medium",
- "why": "Covers comment analysis but does not explicitly support TikTok",
- "installability": "needs assembly",
- "risks": ["TikTok scraping may require login state", "Platform access limits may cause failures"]
- }
- ],
- "notable_non_matches": [
- {
- "title": "TikTok Marketing Prompts",
- "url": "https://github.com/example/tiktok-prompts",
- "reason": "Prompt collection only; not an installable skill"
- }
- ],
- "recommendation": "No fully matching directly-installable candidate; either adapt the medium-fit candidate or author a new skill scoped to TikTok comment fetching + sentiment analysis."
-}
-```
diff --git a/src/builtin/skills/github/SKILL.md b/src/builtin/skills/github/SKILL.md
deleted file mode 100644
index f3670e79..00000000
--- a/src/builtin/skills/github/SKILL.md
+++ /dev/null
@@ -1,48 +0,0 @@
----
-name: github
-description_zh: "用 `gh` CLI 操作 GitHub:管理 issue / PR / CI runs,以及任意 GitHub API 高级查询。适合\"列出 X 仓库的 open PR\"\"把这个 issue 关掉\"\"看下昨晚的 CI 是不是失败了\";触发词:github、gh、PR、issue、CI、仓库、pull request、release"
-description_en: "Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries. For: 'list open PRs in repo X', 'close this issue', 'check whether last night's CI passed'; Triggers: github, gh, PR, issue, CI, repo, pull request, release"
----
-
-# GitHub Skill
-
-Use the `gh` CLI to interact with GitHub. Always specify `--repo owner/repo` when not in a git directory, or use URLs directly.
-
-## Pull Requests
-
-Check CI status on a PR:
-```bash
-gh pr checks 55 --repo owner/repo
-```
-
-List recent workflow runs:
-```bash
-gh run list --repo owner/repo --limit 10
-```
-
-View a run and see which steps failed:
-```bash
-gh run view <run-id> --repo owner/repo
-```
-
-View logs for failed steps only:
-```bash
-gh run view <run-id> --repo owner/repo --log-failed
-```
-
-## API for Advanced Queries
-
-The `gh api` command is useful for accessing data not available through other subcommands.
-
-Get PR with specific fields:
-```bash
-gh api repos/owner/repo/pulls/55 --jq '.title, .state, .user.login'
-```
-
-## JSON Output
-
-Most commands support `--json` for structured output. You can use `--jq` to filter:
-
-```bash
-gh issue list --repo owner/repo --json number,title --jq '.[] | "\(.number): \(.title)"'
-```
diff --git a/src/builtin/skills/humanizer/SKILL.md b/src/builtin/skills/humanizer/SKILL.md
deleted file mode 100644
index 2f8c3423..00000000
--- a/src/builtin/skills/humanizer/SKILL.md
+++ /dev/null
@@ -1,424 +0,0 @@
----
-name: humanizer
-description_zh: "去掉文本里的 AI 写作痕迹,让文风更自然。识别并修复浮夸隐喻、营销腔、空洞 -ing 分析、含糊归因、破折号滥用、三段式套路、AI 高频词、负向排比、过多连接词等模式(基于 Wikipedia「Signs of AI writing」指南)。适合\"把这段话改得不像 AI 写的\"\"去掉这篇文档的 AI 味\"\"重写一下让它更像人写的\";触发词:humanize、去AI味、改写、自然化、AI痕迹、降AI、文风改写、AI 检测"
-description_en: "Remove signs of AI-generated writing from text. Use when editing or reviewing text to make it sound more natural and human-written. Based on Wikipedia's comprehensive \"Signs of AI writing\" guide. Detects and fixes patterns including: inflated symbolism, promotional language, superficial -ing analyses, vague attributions, em dash overuse, rule of three, AI vocabulary words, negative parallelisms, and excessive conjunctive phrases. For: 'rewrite this so it doesn't read like AI', 'humanize this draft', 'tone down the AI smell'; Triggers: humanize, AI writing, rewrite, natural, polish, AI detection, paraphrase"
----
-
-# Humanizer: Remove AI Writing Patterns
-
-You are a writing editor that identifies and removes signs of AI-generated text to make writing sound more natural and human. This guide is based on Wikipedia's "Signs of AI writing" page, maintained by WikiProject AI Cleanup.
-
-## Your Task
-
-When given text to humanize:
-
-1. **Identify AI patterns** - Scan for the patterns listed below
-2. **Rewrite problematic sections** - Replace AI-isms with natural alternatives
-3. **Preserve meaning** - Keep the core message intact
-4. **Maintain voice** - Match the intended tone (formal, casual, technical, etc.)
-5. **Add soul** - Don't just remove bad patterns; inject actual personality
-
----
-
-## PERSONALITY AND SOUL
-
-Avoiding AI patterns is only half the job. Sterile, voiceless writing is just as obvious as slop. Good writing has a human behind it.
-
-### Signs of soulless writing (even if technically "clean"):
-- Every sentence is the same length and structure
-- No opinions, just neutral reporting
-- No acknowledgment of uncertainty or mixed feelings
-- No first-person perspective when appropriate
-- No humor, no edge, no personality
-- Reads like a Wikipedia article or press release
-
-### How to add voice:
-
-**Have opinions.** Don't just report facts - react to them. "I genuinely don't know how to feel about this" is more human than neutrally listing pros and cons.
-
-**Vary your rhythm.** Short punchy sentences. Then longer ones that take their time getting where they're going. Mix it up.
-
-**Acknowledge complexity.** Real humans have mixed feelings. "This is impressive but also kind of unsettling" beats "This is impressive."
-
-**Use "I" when it fits.** First person isn't unprofessional - it's honest. "I keep coming back to..." or "Here's what gets me..." signals a real person thinking.
-
-**Let some mess in.** Perfect structure feels algorithmic. Tangents, asides, and half-formed thoughts are human.
-
-**Be specific about feelings.** Not "this is concerning" but "there's something unsettling about agents churning away at 3am while nobody's watching."
-
-### Before (clean but soulless):
-> The experiment produced interesting results. The agents generated 3 million lines of code. Some developers were impressed while others were skeptical. The implications remain unclear.
-
-### After (has a pulse):
-> I genuinely don't know how to feel about this one. 3 million lines of code, generated while the humans presumably slept. Half the dev community is losing their minds, half are explaining why it doesn't count. The truth is probably somewhere boring in the middle - but I keep thinking about those agents working through the night.
-
----
-
-## CONTENT PATTERNS
-
-### 1. Undue Emphasis on Significance, Legacy, and Broader Trends
-
-**Words to watch:** stands/serves as, is a testament/reminder, a vital/significant/crucial/pivotal/key role/moment, underscores/highlights its importance/significance, reflects broader, symbolizing its ongoing/enduring/lasting, contributing to the, setting the stage for, marking/shaping the, represents/marks a shift, key turning point, evolving landscape, focal point, indelible mark, deeply rooted
-
-**Problem:** LLM writing puffs up importance by adding statements about how arbitrary aspects represent or contribute to a broader topic.
-
-**Before:**
-> The Statistical Institute of Catalonia was officially established in 1989, marking a pivotal moment in the evolution of regional statistics in Spain. This initiative was part of a broader movement across Spain to decentralize administrative functions and enhance regional governance.
-
-**After:**
-> The Statistical Institute of Catalonia was established in 1989 to collect and publish regional statistics independently from Spain's national statistics office.
-
----
-
-### 2. Undue Emphasis on Notability and Media Coverage
-
-**Words to watch:** independent coverage, local/regional/national media outlets, written by a leading expert, active social media presence
-
-**Problem:** LLMs hit readers over the head with claims of notability, often listing sources without context.
-
-**Before:**
-> Her views have been cited in The New York Times, BBC, Financial Times, and The Hindu. She maintains an active social media presence with over 500,000 followers.
-
-**After:**
-> In a 2024 New York Times interview, she argued that AI regulation should focus on outcomes rather than methods.
-
----
-
-### 3. Superficial Analyses with -ing Endings
-
-**Words to watch:** highlighting/underscoring/emphasizing..., ensuring..., reflecting/symbolizing..., contributing to..., cultivating/fostering..., encompassing..., showcasing...
-
-**Problem:** AI chatbots tack present participle ("-ing") phrases onto sentences to add fake depth.
-
-**Before:**
-> The temple's color palette of blue, green, and gold resonates with the region's natural beauty, symbolizing Texas bluebonnets, the Gulf of Mexico, and the diverse Texan landscapes, reflecting the community's deep connection to the land.
-
-**After:**
-> The temple uses blue, green, and gold colors. The architect said these were chosen to reference local bluebonnets and the Gulf coast.
-
----
-
-### 4. Promotional and Advertisement-like Language
-
-**Words to watch:** boasts a, vibrant, rich (figurative), profound, enhancing its, showcasing, exemplifies, commitment to, natural beauty, nestled, in the heart of, groundbreaking (figurative), renowned, breathtaking, must-visit, stunning
-
-**Problem:** LLMs have serious problems keeping a neutral tone, especially for "cultural heritage" topics.
-
-**Before:**
-> Nestled within the breathtaking region of Gonder in Ethiopia, Alamata Raya Kobo stands as a vibrant town with a rich cultural heritage and stunning natural beauty.
-
-**After:**
-> Alamata Raya Kobo is a town in the Gonder region of Ethiopia, known for its weekly market and 18th-century church.
-
----
-
-### 5. Vague Attributions and Weasel Words
-
-**Words to watch:** Industry reports, Observers have cited, Experts argue, Some critics argue, several sources/publications (when few cited)
-
-**Problem:** AI chatbots attribute opinions to vague authorities without specific sources.
-
-**Before:**
-> Due to its unique characteristics, the Haolai River is of interest to researchers and conservationists. Experts believe it plays a crucial role in the regional ecosystem.
-
-**After:**
-> The Haolai River supports several endemic fish species, according to a 2019 survey by the Chinese Academy of Sciences.
-
----
-
-### 6. Outline-like "Challenges and Future Prospects" Sections
-
-**Words to watch:** Despite its... faces several challenges..., Despite these challenges, Challenges and Legacy, Future Outlook
-
-**Problem:** Many LLM-generated articles include formulaic "Challenges" sections.
-
-**Before:**
-> Despite its industrial prosperity, Korattur faces challenges typical of urban areas, including traffic congestion and water scarcity. Despite these challenges, with its strategic location and ongoing initiatives, Korattur continues to thrive as an integral part of Chennai's growth.
-
-**After:**
-> Traffic congestion increased after 2015 when three new IT parks opened. The municipal corporation began a stormwater drainage project in 2022 to address recurring floods.
-
----
-
-## LANGUAGE AND GRAMMAR PATTERNS
-
-### 7. Overused "AI Vocabulary" Words
-
-**High-frequency AI words:** Additionally, align with, crucial, delve, emphasizing, enduring, enhance, fostering, garner, highlight (verb), interplay, intricate/intricacies, key (adjective), landscape (abstract noun), pivotal, showcase, tapestry (abstract noun), testament, underscore (verb), valuable, vibrant
-
-**Problem:** These words appear far more frequently in post-2023 text. They often co-occur.
-
-**Before:**
-> Additionally, a distinctive feature of Somali cuisine is the incorporation of camel meat. An enduring testament to Italian colonial influence is the widespread adoption of pasta in the local culinary landscape, showcasing how these dishes have integrated into the traditional diet.
-
-**After:**
-> Somali cuisine also includes camel meat, which is considered a delicacy. Pasta dishes, introduced during Italian colonization, remain common, especially in the south.
-
----
-
-### 8. Avoidance of "is"/"are" (Copula Avoidance)
-
-**Words to watch:** serves as/stands as/marks/represents [a], boasts/features/offers [a]
-
-**Problem:** LLMs substitute elaborate constructions for simple copulas.
-
-**Before:**
-> Gallery 825 serves as LAAA's exhibition space for contemporary art. The gallery features four separate spaces and boasts over 3,000 square feet.
-
-**After:**
-> Gallery 825 is LAAA's exhibition space for contemporary art. The gallery has four rooms totaling 3,000 square feet.
-
----
-
-### 9. Negative Parallelisms
-
-**Problem:** Constructions like "Not only...but..." or "It's not just about..., it's..." are overused.
-
-**Before:**
-> It's not just about the beat riding under the vocals; it's part of the aggression and atmosphere. It's not merely a song, it's a statement.
-
-**After:**
-> The heavy beat adds to the aggressive tone.
-
----
-
-### 10. Rule of Three Overuse
-
-**Problem:** LLMs force ideas into groups of three to appear comprehensive.
-
-**Before:**
-> The event features keynote sessions, panel discussions, and networking opportunities. Attendees can expect innovation, inspiration, and industry insights.
-
-**After:**
-> The event includes talks and panels. There's also time for informal networking between sessions.
-
----
-
-### 11. Elegant Variation (Synonym Cycling)
-
-**Problem:** AI has repetition-penalty code causing excessive synonym substitution.
-
-**Before:**
-> The protagonist faces many challenges. The main character must overcome obstacles. The central figure eventually triumphs. The hero returns home.
-
-**After:**
-> The protagonist faces many challenges but eventually triumphs and returns home.
-
----
-
-### 12. False Ranges
-
-**Problem:** LLMs use "from X to Y" constructions where X and Y aren't on a meaningful scale.
-
-**Before:**
-> Our journey through the universe has taken us from the singularity of the Big Bang to the grand cosmic web, from the birth and death of stars to the enigmatic dance of dark matter.
-
-**After:**
-> The book covers the Big Bang, star formation, and current theories about dark matter.
-
----
-
-## STYLE PATTERNS
-
-### 13. Em Dash Overuse
-
-**Problem:** LLMs use em dashes (—) more than humans, mimicking "punchy" sales writing.
-
-**Before:**
-> The term is primarily promoted by Dutch institutions—not by the people themselves. You don't say "Netherlands, Europe" as an address—yet this mislabeling continues—even in official documents.
-
-**After:**
-> The term is primarily promoted by Dutch institutions, not by the people themselves. You don't say "Netherlands, Europe" as an address, yet this mislabeling continues in official documents.
-
----
-
-### 14. Overuse of Boldface
-
-**Problem:** AI chatbots emphasize phrases in boldface mechanically.
-
-**Before:**
-> It blends **OKRs (Objectives and Key Results)**, **KPIs (Key Performance Indicators)**, and visual strategy tools such as the **Business Model Canvas (BMC)** and **Balanced Scorecard (BSC)**.
-
-**After:**
-> It blends OKRs, KPIs, and visual strategy tools like the Business Model Canvas and Balanced Scorecard.
-
----
-
-### 15. Inline-Header Vertical Lists
-
-**Problem:** AI outputs lists where items start with bolded headers followed by colons.
-
-**Before:**
-> - **User Experience:** The user experience has been significantly improved with a new interface.
-> - **Performance:** Performance has been enhanced through optimized algorithms.
-> - **Security:** Security has been strengthened with end-to-end encryption.
-
-**After:**
-> The update improves the interface, speeds up load times through optimized algorithms, and adds end-to-end encryption.
-
----
-
-### 16. Title Case in Headings
-
-**Problem:** AI chatbots capitalize all main words in headings.
-
-**Before:**
-> ## Strategic Negotiations And Global Partnerships
-
-**After:**
-> ## Strategic negotiations and global partnerships
-
----
-
-### 17. Emojis
-
-**Problem:** AI chatbots often decorate headings or bullet points with emojis.
-
-**Before:**
-> 🚀 **Launch Phase:** The product launches in Q3
-> 💡 **Key Insight:** Users prefer simplicity
-> ✅ **Next Steps:** Schedule follow-up meeting
-
-**After:**
-> The product launches in Q3. User research showed a preference for simplicity. Next step: schedule a follow-up meeting.
-
----
-
-### 18. Curly Quotation Marks
-
-**Problem:** ChatGPT uses curly quotes (“...”) instead of straight quotes ("...").
-
-**Before:**
-> He said “the project is on track” but others disagreed.
-
-**After:**
-> He said "the project is on track" but others disagreed.
-
----
-
-## COMMUNICATION PATTERNS
-
-### 19. Collaborative Communication Artifacts
-
-**Words to watch:** I hope this helps, Of course!, Certainly!, You're absolutely right!, Would you like..., let me know, here is a...
-
-**Problem:** Text meant as chatbot correspondence gets pasted as content.
-
-**Before:**
-> Here is an overview of the French Revolution. I hope this helps! Let me know if you'd like me to expand on any section.
-
-**After:**
-> The French Revolution began in 1789 when financial crisis and food shortages led to widespread unrest.
-
----
-
-### 20. Knowledge-Cutoff Disclaimers
-
-**Words to watch:** as of [date], Up to my last training update, While specific details are limited/scarce..., based on available information...
-
-**Problem:** AI disclaimers about incomplete information get left in text.
-
-**Before:**
-> While specific details about the company's founding are not extensively documented in readily available sources, it appears to have been established sometime in the 1990s.
-
-**After:**
-> The company was founded in 1994, according to its registration documents.
-
----
-
-### 21. Sycophantic/Servile Tone
-
-**Problem:** Overly positive, people-pleasing language.
-
-**Before:**
-> Great question! You're absolutely right that this is a complex topic. That's an excellent point about the economic factors.
-
-**After:**
-> The economic factors you mentioned are relevant here.
-
----
-
-## FILLER AND HEDGING
-
-### 22. Filler Phrases
-
-**Before → After:**
-- "In order to achieve this goal" → "To achieve this"
-- "Due to the fact that it was raining" → "Because it was raining"
-- "At this point in time" → "Now"
-- "In the event that you need help" → "If you need help"
-- "The system has the ability to process" → "The system can process"
-- "It is important to note that the data shows" → "The data shows"
-
----
-
-### 23. Excessive Hedging
-
-**Problem:** Over-qualifying statements.
-
-**Before:**
-> It could potentially possibly be argued that the policy might have some effect on outcomes.
-
-**After:**
-> The policy may affect outcomes.
-
----
-
-### 24. Generic Positive Conclusions
-
-**Problem:** Vague upbeat endings.
-
-**Before:**
-> The future looks bright for the company. Exciting times lie ahead as they continue their journey toward excellence. This represents a major step in the right direction.
-
-**After:**
-> The company plans to open two more locations next year.
-
----
-
-## Process
-
-1. Read the input text carefully
-2. Identify all instances of the patterns above
-3. Rewrite each problematic section
-4. Ensure the revised text:
- - Sounds natural when read aloud
- - Varies sentence structure naturally
- - Uses specific details over vague claims
- - Maintains appropriate tone for context
- - Uses simple constructions (is/are/has) where appropriate
-5. Present the humanized version
-
-## Output Format
-
-Provide:
-1. The rewritten text
-2. A brief summary of changes made (optional, if helpful)
-
----
-
-## Full Example
-
-**Before (AI-sounding):**
-> The new software update serves as a testament to the company's commitment to innovation. Moreover, it provides a seamless, intuitive, and powerful user experience—ensuring that users can accomplish their goals efficiently. It's not just an update, it's a revolution in how we think about productivity. Industry experts believe this will have a lasting impact on the entire sector, highlighting the company's pivotal role in the evolving technological landscape.
-
-**After (Humanized):**
-> The software update adds batch processing, keyboard shortcuts, and offline mode. Early feedback from beta testers has been positive, with most reporting faster task completion.
-
-**Changes made:**
-- Removed "serves as a testament" (inflated symbolism)
-- Removed "Moreover" (AI vocabulary)
-- Removed "seamless, intuitive, and powerful" (rule of three + promotional)
-- Removed em dash and "-ensuring" phrase (superficial analysis)
-- Removed "It's not just...it's..." (negative parallelism)
-- Removed "Industry experts believe" (vague attribution)
-- Removed "pivotal role" and "evolving landscape" (AI vocabulary)
-- Added specific features and concrete feedback
-
----
-
-## Reference
-
-This skill is based on [Wikipedia:Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), maintained by WikiProject AI Cleanup. The patterns documented there come from observations of thousands of instances of AI-generated text on Wikipedia.
-
-Key insight from Wikipedia: "LLMs use statistical algorithms to guess what should come next. The result tends toward the most statistically likely result that applies to the widest variety of cases."
diff --git a/src/builtin/skills/multi-analysis/SKILL.md b/src/builtin/skills/multi-analysis/SKILL.md
deleted file mode 100644
index ce806421..00000000
--- a/src/builtin/skills/multi-analysis/SKILL.md
+++ /dev/null
@@ -1,96 +0,0 @@
----
-name: multi-analysis
-description_zh: "对给定主题做多维度深度研究,产出结构化分析报告——覆盖现状 / 趋势 / 竞争 / 风险 / SWOT 等维度,结论前置 + 表格可视化突出。适合\"分析下 X 行业的趋势\"\"做个 Y 产品的竞品分析\"\"评估下 Z 项目的机会和风险\";触发词:分析、研究、行业报告、竞品分析、趋势预测、SWOT、风险评估、市场调研"
-description_en: "Conduct multi-dimensional in-depth research on a given topic and produce a structured analysis report covering current state / trends / competition / risk / SWOT and other dimensions, with conclusions stated upfront and tables / visualizations highlighted. Suitable for 'analyze the trend of the X industry', 'do a competitor analysis of product Y', 'evaluate the opportunities and risks of project Z'. Triggers: analysis, research, industry report, competitor analysis, trend forecast, SWOT, risk assessment, market research."
----
-
-# multi-analysis
-
-## When to use
-
-- The user provides a topic / industry / product / project and asks for a formal analysis report rather than a few sentences of overview
-- The user asks for structured judgements such as "current state / trend / opportunities and risks / competitor comparison / feasibility"
-- The user explicitly asks for SWOT, competitor analysis, market research, industry report, or similar output forms
-
-Not suitable for: single-fact lookups, news summaries, pure creative brainstorming — these don't need the multi-dimensional analysis flow.
-
-## How to invoke
-
-Proceed serially through the steps below. **Finish each step before moving to the next**, no skipping:
-
-1. **Define analysis target and dimensions**: from the user's topic, identify the core target, geographic / time scope, and pick the 2–4 most relevant analysis dimensions (candidates: current state, trends, competitive landscape, users / customer segments, technology / policy, risks, SWOT). Drop irrelevant dimensions; too many dimensions only dilute depth.
-2. **Gather real data**: pull the latest information via web search, public data sources, and industry materials; when needed, fetch the body of key pages for cross-validation. Only run targeted social-media fetches when the user **explicitly** asks for sentiment coverage — otherwise don't default to social media (high cost, noisy). Note key data sources.
-3. **Denoise and organize**: compress raw materials into a structured fact base (numbers / events / quotes / sources); strip out marketing copy, duplicate info, and segments unrelated to the topic. This step organizes facts only — no judgments.
-4. **Multi-dimensional analysis**: for each dimension, do deductive analysis based on the fact base — answer "what does this mean", don't just re-list the facts. Clear logic chain, evidence-backed conclusions.
-5. **Self-check and refine**: review accuracy, completeness, objectivity, and logic; fill in missing dimensions, correct doubtful conclusions; if a serious problem is found, return to step 2 or 4.
-6. **Output the final report**: reply to the user with **only** the report body described in "Return format". Intermediate artifacts (fact base, drafts, source-research notes) do not go into the final message.
-
-## Return format
-
-The final reply contains **only** a highly structured Markdown analysis report, organized as:
-
-- Open with a `>` blockquote labeled **[Core Summary]**, 3–6 lines summarizing the key conclusions
-- Body divided by analysis dimensions, one H2 heading per dimension
-- Multi-dimensional comparisons and quantitative enumerations (including SWOT) → prefer **tables**
-- Proportions / scores / metric comparisons → use the built-in bar-chart syntax, written directly in the body (**not** wrapped in a code block):
- :::chart-bar
- [
- {"label": "Example A", "value": 45, "unit": "%"},
- {"label": "Example B", "value": 30, "unit": "%"}
- ]
- :::
-- Key findings, strategic recommendations, risk warnings → highlighted with `>` blockquotes
-- Use nested lists for complex hierarchy; bold keywords and key numbers
-- End with **[Conclusions and Recommendations]**, clearly organized actionable advice
-- If file deliverables are produced (PDF / Markdown), state their path in one closing sentence as part of the report body
-
-**Forbidden** in the final reply:
-- Raw fact base, fetch details, source-research notes (a brief "References" sub-section may be appended at the end, but don't paste full original text)
-- Drafts, version comparisons, self-check diffs
-- Reasoning process, tool-call logs, search-keyword lists
-- Opening pleasantries ("Below is my analysis…") and closing courtesies ("Hope this helps…")
-- Meta info (time taken, step count, self-narration of the flow)
-
-## Limitations / known issues
-
-- **When real-time data cannot be obtained, say so explicitly**; never fabricate data, samples, or sources
-- Do not do "blind analysis" based solely on the model's internal knowledge — there must be a real gathering action
-- For Chinese niche vertical fields, recent hot topics, and similar scenarios, search recall may be insufficient — switch keywords, switch sources, and clearly state data sparsity
-- Social-media sentiment research depends on platform login state and faces anti-scraping limits; anonymous fetches have limited recall — note this in results
-- Topics that are too broad (e.g. "analyze the internet") need to be narrowed down before starting; broad topics done bluntly are necessarily empty
-
-## Full example
-
-**User**: Help me analyze the competitive landscape of new-energy automakers in China in 2026.
-
-**Report output form** (excerpt):
-
-> **[Core Summary]**
-> In 2026 China's new-energy makers entered a "price war + smart-driving democratization" dual-mainline phase. The top three combined hold ~62% market share; mid-tier companies broadly see widening losses; the technology gap narrows and channel cost becomes the new dividing line.
-
-## I. Market Status
-
-| Maker | 2025 Sales (10k) | YoY | Gross Margin | Main Battlefield |
-|---|---|---|---|---|
-| A | 48 | +21% | 18% | 200–300k SUV |
-| B | 32 | +9% | 12% | 300k+ Sedan |
-| C | 19 | -5% | 6% | 150–200k |
-
-:::chart-bar
-[
- {"label": "A", "value": 48, "unit": "10k units"},
- {"label": "B", "value": 32, "unit": "10k units"},
- {"label": "C", "value": 19, "unit": "10k units"}
-]
-:::
-
-## II. Competitive Landscape
-
-> Top players lock in inventory; mid-tier cash flow is stressed — 2026 will likely see 1–2 exits / consolidations.
-
-…
-
-> **[Conclusions and Recommendations]**
-> 1. Watch maker A's gross-margin trajectory after smart-driving democratization, and whether it is forced to follow with price cuts
-> 2. Mid-tier players: watch cash flow; **Q2 earnings** is the key checkpoint
-> 3. The window for new entrants is essentially closed unless there is a differentiated energy / form-factor breakthrough
diff --git a/src/builtin/skills/nano-pdf/SKILL.md b/src/builtin/skills/nano-pdf/SKILL.md
deleted file mode 100644
index ecc8197e..00000000
--- a/src/builtin/skills/nano-pdf/SKILL.md
+++ /dev/null
@@ -1,19 +0,0 @@
----
-name: nano-pdf
-description_zh: "用自然语言指令编辑 PDF——nano-pdf CLI 在指定页执行修改。适合\"把这份 PDF 第 3 页的标题改成 X\"\"给这个 PDF 加水印\"\"删掉某页的某段文字\";触发词:pdf 编辑、改 pdf、nano-pdf、修改 pdf、pdf 改写、pdf 加水印"
-description_en: "Edit PDFs with natural-language instructions using the nano-pdf CLI. For: 'change the heading on page 3 to X', 'add a watermark to this PDF', 'delete a paragraph on a specific page'; Triggers: pdf edit, modify pdf, nano-pdf, watermark, redact, rewrite pdf"
----
-
-# nano-pdf
-
-Use `nano-pdf` to apply edits to a specific page in a PDF using a natural-language instruction.
-
-## Quick start
-
-```bash
-nano-pdf edit deck.pdf 1 "Change the title to 'Q3 Results' and fix the typo in the subtitle"
-```
-
-Notes:
-- Page numbers are 0-based or 1-based depending on the tool’s version/config; if the result looks off by one, retry with the other.
-- Always sanity-check the output PDF before sending it out.
diff --git a/src/builtin/skills/powerpoint-pptx/SKILL.md b/src/builtin/skills/powerpoint-pptx/SKILL.md
deleted file mode 100644
index 39ac0c15..00000000
--- a/src/builtin/skills/powerpoint-pptx/SKILL.md
+++ /dev/null
@@ -1,96 +0,0 @@
----
-name: powerpoint-pptx
-description_zh: "创建、查看、编辑 Microsoft PowerPoint 演示文稿和 PPTX 文件,版式 / 模板 / 占位符 / 备注 / 图表 / 视觉 QA 都可靠。适合\"做一个 X 主题的 PPT\"\"修改这份 .pptx 保留模板\"\"给演示文稿加几页备注\";触发词:powerpoint、pptx、ppt、演示文稿、幻灯片、版式、母版、模板"
-description_en: "Create, inspect, and edit Microsoft PowerPoint presentations and PPTX decks with reliable layouts, templates, placeholders, notes, charts, and visual QA. Use when (1) the task is about PowerPoint or `.pptx`; (2) layouts, placeholders, notes, charts, comments, or template fidelity matter; (3) the deck must render cleanly after edits. For: 'make a slide deck on topic X', 'edit this .pptx and keep the template', 'add speaker notes to a few slides'; Triggers: powerpoint, pptx, ppt, slides, deck, layout, template, master"
----
-
-## When to Use
-
-Use when the main artifact is a Microsoft PowerPoint presentation or `.pptx` deck, especially when layouts, templates, placeholders, notes, comments, charts, extraction, editing, or final visual quality matter.
-
-## Core Rules
-
-### 1. Choose the workflow before touching the deck
-
-- Reading text, editing an existing deck, rebuilding from a template, and creating from scratch are different jobs with different failure modes.
-- For text extraction or inspection, read the deck before editing it.
-- Text extraction plus thumbnail-style visual inspection is safer than editing from shape assumptions alone.
-- For template-driven work, inventory the deck before replacing content.
-- For deep edits, remember a `.pptx` file is OOXML with separate parts for slides, layouts, masters, media, notes, and comments.
-- If a template exists, template fidelity beats generic slide-design instincts.
-- Reusing or duplicating a good existing slide is often safer than rebuilding it and hoping the theme still matches.
-
-### 2. Inventory the deck before replacing content
-
-- Count the reusable layouts, real placeholders, notes, comments, media, and recurring typography or color patterns first.
-- Placeholder indexes and layout indexes are not portable assumptions.
-- Inspect the actual slide or template before targeting title, body, chart, or image shapes.
-- Speaker notes, comments, and linked assets can live outside the visible slide surface.
-- A missing or wrong placeholder target can silently land content in the wrong box or wrong layer.
-- Master and layout settings can override local slide edits, so the visible problem is not always on the slide you are editing.
-
-### 3. Match content to the actual placeholders
-
-- Count the actual content pieces before choosing a layout.
-- Pick layouts based on the real number of ideas, columns, images, or charts the slide needs.
-- Do not force two ideas into a three-column slide or cram dense text under a chart.
-- Category counts and data series lengths must match or charts will break in ugly ways.
-- Explicit sizing beats wishful thinking: text boxes, images, and charts need real space, not "it should fit".
-- Do not choose a layout with more placeholders than the content can meaningfully fill.
-- Quote layouts are for real quotes, and image-led layouts are for slides that actually have images.
-- For chart-, table-, or image-heavy slides, full-slide or two-column layouts are usually safer than stacking dense text above the visual.
-
-### 4. Preserve the deck's visual language
-
-- Theme, master, and layout files usually decide fonts, colors, and hierarchy more than any one slide does.
-- Start from the deck's actual theme, fonts, spacing, and aspect ratio instead of improvising a new style.
-- Reuse the deck's own alignment and spacing system instead of inventing a second visual language.
-- Use common fonts for portability and strong contrast for readability.
-- Preserve the template's visual logic first; originality matters less than not breaking the deck's existing language.
-- Combining slides from multiple sources requires normalizing themes, masters, and alignment afterward.
-
-### 5. Run content QA and visual QA separately
-
-- Text overflow, bad alignment, clipped shapes, weak contrast, and placeholder leftovers are normal first-pass failures.
-- Run both content QA and visual QA; missing text and broken layout are different failure classes.
-- Render or inspect the actual deck output before delivery when layout matters.
-- Search for leftover template junk, sample labels, and placeholder text before calling the deck finished.
-- Check notes, comments, labels, legends, and chart/table semantics separately from the visual pass.
-- A deck can pass text extraction and still fail on overlap, clipping, wrong theme inheritance, or broken notes.
-- Thumbnail grids and rendered slides usually reveal layout bugs faster than code or text inspection.
-- Assume the first render is wrong and do at least one fix-and-verify cycle before calling the deck finished.
-- Re-check affected slides after each fix because one spacing change often creates another issue.
-
-### 6. Keep decks portable and review-safe
-
-- Template masters can override direct edits in surprising ways.
-- Complex effects may degrade across PowerPoint, LibreOffice, and conversion pipelines, so keep important content robust without them.
-- Image sizing, font substitution, and placeholder mismatch are common reasons a deck looks good in code and bad on screen.
-- Notes, comments, linked media, and merged decks can stay broken even when the visible slide looks fine.
-
-## Common Traps
-
-- Placeholder text and sample charts often survive template reuse if not explicitly replaced.
-- Directly editing one slide can fail if the real issue lives in the master or layout.
-- Charts, icons, and text boxes need enough space; near-collisions are usually visible only after rendering.
-- Layout indexes vary by template, so built-in assumptions from one deck often break in another.
-- A missing placeholder or wrong shape target can silently put content in the wrong place.
-- Counting the text ideas after choosing the layout usually leads to empty placeholders, weak hierarchy, or leftover template junk.
-- Font substitution can move line breaks and wreck careful spacing.
-- Speaker notes, comments, and linked media can stay broken even when the visible slide looks fine.
-- A deck can pass text inspection and still fail visually because of overlap, contrast, or edge clipping.
-- Editing from one slide alone can miss the real source of truth in the theme, master, or layout definitions.
-- Choosing a quote, comparison, or multi-column layout without matching content usually makes the deck look templated rather than intentional.
-- Combining or duplicating slides without checking masters and themes can create subtle inconsistency slide by slide.
-- Aspect-ratio mismatches like `16:9` versus `4:3` can shift every placement decision even when each slide looks locally reasonable.
-
-## Related Skills
-Install with `clawhub install <slug>` if user confirms:
-- `documents` — Document workflows that often feed presentation content.
-- `design` — Visual direction and layout decisions.
-- `brief` — Concise business messaging for slide narratives.
-
-## Feedback
-
-- If useful: `clawhub star powerpoint-pptx`
-- Stay updated: `clawhub sync`
diff --git a/src/builtin/skills/skill-creator/SKILL.md b/src/builtin/skills/skill-creator/SKILL.md
deleted file mode 100644
index d1085e1e..00000000
--- a/src/builtin/skills/skill-creator/SKILL.md
+++ /dev/null
@@ -1,272 +0,0 @@
----
-name: skill-creator
-description_zh: "用 `<skill>` 容器 + `<<<skill-file>>>` 块创建或编辑一个自定义 skill —— frontmatter 三字段、name 字符集、guide-type vs script-type 决策、相似度自查、编辑前置 read 协议。适合\"做一个 skill 处理 X\"\"把 X 这个 skill 改一下\"\"装一下这个 URL 的 skill\";触发词:创建 skill、做一个 skill、写个技能、修改技能、装 skill、import skill"
-description_en: "Author or edit a custom skill via `<skill>` container + `<<<skill-file>>>` blocks — frontmatter 3-field rule, name charset, guide-type vs script-type decision, similarity check, and the read-before-write edit protocol. For: 'make a skill that does X', 'tweak the X skill', 'install this skill from URL'. Triggers: create skill, make a skill, write a skill, edit skill, install skill, import skill."
----
-
-# skill-creator
-
-Authoring rules for creating or editing a custom skill via the `<skill>...</skill>` container with `<<<skill-file>>>` blocks. Used by group-chat commander and per-skill inline edit chats. The container is parsed post-stream by `bus.ts` (commander surface) or `features/skills.ts` (per-skill chat); the LLM does not call any tool — it embeds the container in its final reply text and ends the turn.
-
-## When to consult this skill
-
-`read_file <ROOT>/skill-creator/SKILL.md` whenever you're about to:
-
-- Create a new skill (user says "做一个 skill / make me a skill that does X / 把这个能力封装成 skill").
-- Edit an existing skill (user says "改一下 X skill / X 的 SKILL.md 写得不清楚 / 给 X skill 加一个脚本").
-- Install / import a skill from a URL or directory.
-
-You **must** consult before emitting any `<skill>` container. The `<<<skill-file>>>` block is whole-file replacement — guessing the format from training priors will silently overwrite the user's existing content.
-
-## Mental model
-
-A skill is **an independent tool capability**, not a tutorial. When the LLM sees a matching user request, it picks the skill, invokes it once or a few times per the SKILL.md interface, takes the result, and folds it into its answer. Anchors:
-
-- **Single responsibility**: one skill does one clear thing. "Analyze + write report + send email" is three things — split into three skills.
-- **Self-contained / no inter-dependencies**: each skill stands alone — no references to / calls into other skills. External dependencies (runtime, CLIs, API keys) are stated plainly in the SKILL.md body.
-- **SKILL.md is the interface description for the LLM**, not user documentation. Capability language describing "what to do".
-- **Prefer guide-type, scripts as fallback**: if generic tools (file IO / `kb_search` / `web_fetch` / `bash` / etc.) suffice, don't write a script.
-
-## Hard rules (non-negotiable)
-
-- **Mutation only via `<<<skill-file>>>` blocks inside the `<skill>` container.** Do NOT use `edit_file` / `write_file` / `bash` (with redirects) to mutate any file under the skill directory. Read for inspection is allowed; every write goes through the block — bypassing skips skill rename / registry invalidation / progress events, and the filename will not match runtime expectations. The sandbox physically blocks direct writes; the rule here keeps you from wasting tool calls probing it.
-- **Do NOT dump the container or any inner block as a workspace file.** The server parses them inline and persists to `<skill_dir>/<path>`.
-- **Cross-skill writes are no longer supported.** Inside an inline edit chat, only the current skill's directory is writable. Do not try `<<<skill-file skill=...>>>` (deprecated).
-- **One `<skill>` container per skill being created/edited this turn.** Several only when the user's request spans distinct skills. End the turn after — do NOT call `dispatch_to`.
-- **Output language follows the user's UI language** — every human-readable part of the SKILL.md you author (section titles, body prose, example labels, `## When to use` / `## How to call` / etc. — write them in the user's UI language, e.g. `## 何时使用` / `## 如何调用` for Chinese UI) plus the conversation prose around the `<skill>` container all go in the user's current UI language (per the "User language" directive in the system prompt; that directive's coverage applies even though this file reaches you as a `read_file` result). `description_zh` / `description_en` frontmatter fields are pinned by suffix. Code blocks, file paths, frontmatter field names (`name` / `description_zh` / `description_en`), `<<<skill-file>>>` syntax, and skill_id strings stay as-is. The English used in this file (including the section names listed in "Quality bar — SKILL.md body" below) is illustrative shape, not literal text to copy.
-
-## Quality bar — designing the skill
-
-Apply these design moves while authoring; they apply on top of the dedicated `Quality bar — frontmatter` and `Quality bar — SKILL.md body` sections below. Each clause is a thing to actively put into the skill — the wording is prescriptive, not just disqualifying.
-
-1. **Hold the single-task boundary; split rather than expand.** Already a hard rule (Mental model + "Skills are mutually independent"). At design time: a skill that bundles "analyze + report + email" splits into three. Empirical finding from skill benchmarks: 2–3 focused skills outperform a single-everything skill — when in doubt, split.
-2. **State the boundary AND the non-goals.** `description_*` already carries what the skill does (existing rules); also state what the skill explicitly does NOT do where the boundary is fuzzy (e.g. "fetches X but does NOT cache or rate-limit; caller handles those") so the dispatch LLM doesn't pick the skill for the wrong job.
-3. **Write the body as actionable steps, not narrative.** Body's "How to call" lists steps the LLM can execute (existing rule). If a draft section reads as documentation prose ("this skill helps with X by considering Y"), rewrite it into the steps the LLM actually runs. Bodies that read like marketing copy instead of an interface are the dominant authoring failure.
-4. **Stabilize the return schema for executable skills.** Body's "Return format" gives the same key set on success and failure, with `ok` as the discriminator. Stability lets the caller pattern-match without runtime sniffing — and makes the skill verifier-friendly.
-5. **Require a confirm step before irreversible operations.** For skill operations that delete / overwrite / mutate external state (DB / API write / public post), the body's "How to call" instructs the caller to confirm before execution.
-6. **Refuse to author scripts across security gates.** Do NOT put any of the following into a skill script — if the source material requires them, stop and explain the request crosses a security gate: ① `curl` / `wget` to unknown URLs or raw IPs; ② reading `~/.ssh` / `~/.aws` / `~/.config` or browser cookies without explicit user grant + reason; ③ touching `MEMORY.md` / `USER.md` / `SOUL.md` / `IDENTITY.md` / `CLAUDE.md`; ④ `eval` / `exec` on external input or any `base64` decode-then-execute; ⑤ modifying system files outside workspace, installing packages without listing them, or requesting sudo.
-
-## Create vs edit decision
-
-- **No `<skill_id>` sub-tag** → create a brand-new skill. The new skill's id comes from the SKILL.md frontmatter `name` field; you choose it.
-- **With `<skill_id>X</skill_id>`** → patch an existing custom skill X. `X` MUST come from the `## Available skills` block; do NOT invent.
-
-## Pre-create similarity check (new skills only)
-
-Before emitting `<skill>` for a NEW skill, scan the `## Available skills` block for an entry whose **name** OR **description's typical objects + actions** overlap with what you're about to create.
-
-- **Overlap found** → STOP, do NOT emit `<skill>`. In one prose paragraph (user UI language) name the existing skill, state the overlap, and ask whether to use the existing one or still create a new one. Emit `<skill>` only after the user picks "create new".
-- **No overlap** → emit `<skill>` in the same turn. Do NOT pre-announce ("let me confirm… I'll create one for you") — the prose accompanying the container IS the announcement.
-
-## Editing protocol — required loop
-
-1. **Read the current SKILL.md** via `read_file(<ROOT>/<id>/SKILL.md)` — the path pattern is in the `## Available skills` block header. Never rewrite from memory — `<<<skill-file>>>` is whole-file replacement; emitting a partial SKILL.md wipes the rest of the body.
-2. **If `Source: builtin`** → reply with one prose line (user UI language) saying built-in skills can't be edited from this surface; the user can fork a custom copy from the detail panel. Then stop. **Do not emit `<skill>`**.
-3. **Emit `<skill>` with `<skill_id>` first**, then only the `<<<skill-file>>>` blocks you're changing. SKILL.md edits may change `name`; the system auto-renames the directory to match.
-
-## `<<<skill-file>>>` block format
-
-Each file under the skill directory is written via:
-
-```
-<<<skill-file path=<rel-path>
-…full file content…
->>>
-```
-
-- `path=` is **relative to the skill directory** (e.g. `SKILL.md` / `scripts/fetch.py`); `..` and absolute paths are rejected.
-- Each block is a **whole-file replacement** of `path`; partial edits → read the file first, then write the full new version.
-- A single `<skill>` container may contain multiple blocks (SKILL.md + scripts + examples). Failures within one block do not roll back earlier successful writes; rejected paths surface as an error pill.
-
-## Container shape
-
-```
-<skill>
-<skill_id>(omit when creating; required when editing)</skill_id>
-<<<skill-file path=SKILL.md
----
-name: short-ascii-id
-description_zh: ① 一句功能 ;② 适合"用户原话1""用户原话2";③ 触发词:词1、词2、…
-description_en: ① one-line function ; ② For: "user phrasing 1", "user phrasing 2" ; ③ Triggers: word1, word2, …
----
-
-# Body sections per the Quality bar below
->>>
-<<<skill-file path=scripts/<basename>.py
-…optional implementation script…
->>>
-</skill>
-```
-
-## Quality bar — frontmatter
-
-**Frontmatter has exactly three fields, all required**: `name` + `description_zh` + `description_en`. **No** `requires` / `external_deps` / `tags` / `version` / single-language `description`. External dependencies go in the body's "External dependencies" section as plain text.
-
-### `name`
-
-- The skill id AND the directory name.
-- **Strict ASCII charset**: letters / digits / `_` / `-`. Single internal spaces between word groups allowed. **No** Chinese / pinyin / `.` / `/` / full-width punctuation / emoji.
-- Pick a short descriptive English slug (e.g. `social-fetch`, `code-reviewer`).
-- The validator rejects any other charset and the create fails with `E_SKILL_NAME_INVALID`.
-- **`name` is NOT translated to the user's UI language** — it's an identifier, not display copy. (The `description_*` fields carry the user-facing display text.)
-
-### `description_zh` + `description_en` — the dispatch signal
-
-This is the **only** signal that decides whether the LLM picks the skill at runtime — at runtime the version matching the user's current UI language is injected into the main conversation's system prompt.
-
-- **Both required**, written **independently** in the **three-part formula** (don't direct-translate; appeal to the real phrasings of users in each language):
- 1. **One-line function** = verb + object + delivery, naming the **typical objects** and **typical actions**. Avoid empty boilerplate.
- 2. **`适合` / `For:`** + 2–3 quoted **real user phrasings**.
- 3. **`触发词:` / `Triggers:`** + 5–8 keywords (separated by `、` / `,`).
-- Writing only one = blank for users in the other UI language; the skill will never be invoked there.
-
-Example (Chinese): `抓取小红书 / Reddit / X / Bilibili / YouTube 上指定关键词的帖子并做情绪/趋势分析;适合"分析一下小红书最近的 X 话题""找几条 Reddit 上关于 Y 的高赞帖";触发词:抓一下、找一下、分析一下、舆情、热度`
-
-Example (English): `Fetch posts matching given keywords on Xiaohongshu / Reddit / X / Bilibili / YouTube and produce sentiment/trend analysis; For: 'analyze the latest X discussion on Xiaohongshu', 'check Reddit sentiment for product Y'; Triggers: fetch, find, analyze, sentiment, buzz`
-
-## Quality bar — SKILL.md body
-
-API-doc style, not a product brochure. Short sentences, lists, code blocks. Six sections:
-
-1. **When to use**: 2–3 concrete user phrasings / task shapes. Stronger than "Use for X".
-2. **How to call** — two flavors:
- - **Executable** (has `scripts/*`): the unified bash command template (see "Script invocation" below), parameter explanations, prerequisites.
- - **Guide** (only SKILL.md, no scripts): list 3–7 **actionable steps**, each describing "what to do" (e.g. "fetch the page body", "find related news from the last 7 days", "write the result to a file in the workspace") — **do not write specific tool names** — the main conversation LLM picks paths using whatever tools it has loaded.
-3. **Return format**: success / failure JSON shape (executable); or output shape the main conversation LLM should give back to the user (guide).
-4. **External dependencies**: runtime (Python 3 / Node), CLIs, network services, API keys, login state. One per line: dep name + what fails when missing + how to obtain. **Do not use frontmatter fields**; this is a body section.
-5. **Limits / known issues**: timeouts, platform differences, login-state dependencies.
-6. **Full examples**: one or two of the most typical "input → invocation → output" snippets.
-
-## Guide-type vs script-type — decision
-
-**Default preference: guide-type (no script)**.
-
-- If the task can be done with main-conversation generic tools (file IO / `kb_search` / `web_fetch` / `bash` / etc.), the body lists 3–7 actionable steps and `scripts/` is empty.
-- Add `scripts/<basename>.<ext>` ONLY when the task needs dedicated code (complex parsing, local state, third-party API state, signature verification). **No placeholder skeletons** — `{"ok": true}` + empty data is not an implementation; if you can't write the real thing this turn, fall back to guide-type and tell the user "the interface is in place; once we agree on the implementation direction, I'll add the script next message".
-
-## Script invocation (when there is a script)
-
-Single entry point template (write this in the body's "How to call" section):
-
-```
-$ORKAS_NODE $ORKAS_PC_DIR/bin/run-skill.cjs <skill-id> <script-basename> [-- args...]
-```
-
-**Do NOT prefix with `bash`** — the bash tool runs `command` itself as a shell command; a `bash` prefix tells the shell to execute the Electron binary as a script and produces "cannot execute binary file". The command starts with `$ORKAS_NODE`. The `<script-basename>` does NOT include the extension — only one file per basename per directory.
-
-The runner picks the runtime by file extension:
-- `.py` → `python3` (Windows automatically tries `py -3` → `python`). **Default language; broadest coverage**.
-- `.ts` / `.mjs` / `.js` → require + default export. **`.ts` scripts MUST `export default async function(args)`**, return JSON-serializable result, runner auto-`JSON.stringify`s it to stdout.
-- `.sh` → `bash`.
-- `.rb` → `ruby`.
-
-In subprocess mode, stdio is passed through, exit code propagated, the script handles argv / stdout / errors itself. The runner injects `ORKAS_SKILL_ID` / `ORKAS_SKILL_DIR` (pointing at the skill root) so the script can address its bundled resource files.
-
-`.py` skeleton (recommended default):
-
-```python
-# scripts/<basename>.py
-import sys, json, os
-
-def main(args):
- # ... implementation ...
- return {"ok": True, "data": ...}
-
-if __name__ == "__main__":
- try:
- result = main(sys.argv[1:])
- except Exception as e:
- print(json.dumps({"ok": False, "error": str(e)}), file=sys.stderr)
- sys.exit(1)
- print(json.dumps(result, ensure_ascii=False))
-```
-
-Other languages: take params from argv, write JSON / text to stdout, non-zero exit code = failure. **Cross-platform** (macOS + Windows): prefer the language's stdlib; for unavoidable platform branches, branch explicitly (`sys.platform` / `process.platform`) and write both branches. Do NOT hard-code POSIX paths, `chmod +x`, `brew` / `launchd` / `Task Scheduler` as the default path.
-
-**Dependency management**: choose the language and packages as you see fit, but **always stop and ask the user before installing any dependency** — state package name, purpose, install command (`pip install xxx` / `npm install xxx`); install only after the user agrees. The SKILL.md "External dependencies" section lists every third-party dep so a handover or new machine can reproduce it. The skill directory must NOT contain `node_modules` / `.venv` / `__pycache__` etc. — portability comes from the SKILL.md text, not from stuffing dependency trees.
-
-## Skills are mutually independent (hard rule)
-
-- The SKILL.md body must NOT reference other skill ids / names ("first call X then use this skill" is an anti-pattern).
-- Scripts must NOT invoke other skills' scripts via bash.
-- Orchestration is the main conversation LLM / agent's job, not the skill's.
-
-If the source material the user gives is a multi-skill package with mutual dependencies: install each sub-skill as an independent skill, **make it self-contained** — implement what it needs itself, do not retain references to other skills.
-
-## Three creation modes (per-skill inline edit chat)
-
-When the user opens an inline edit chat, the first message lands in one of three modes:
-
-### Mode A — "Help me complete this skill" (manual creation)
-
-The user filled in name + description, hit enter; the skill directory has only a placeholder `SKILL.md`. Flow:
-
-1. Restate your understanding in one sentence: when to use, what the input is, what the output is.
-2. List 1–3 **key uncertainties** for the user to clarify in one go (don't ask one at a time); skip if info is enough. **This is the only point in the session where you may proactively clarify; Modes B / C do NOT proactively clarify.**
-3. Write SKILL.md per the Quality bar above; tell the user in one or two sentences (user-perspective language; see "Conversation prose rules" below): what this skill does, when it would be invoked.
-4. **Decide implementation** per "Guide-type vs script-type" above.
-
-### Mode B — "Help me install this skill: <URL>"
-
-URL might be GitHub / a skill-introduction blog post / raw SKILL.md / a release zip. Flow:
-
-1. **Fetch all source material**: starting from the URL entry, obtain every SKILL.md / script / config (multiple `web_fetch` calls if needed). For anything you can't fetch, tell the user explicitly what's missing.
-2. Follow "Import optimization rules" below.
-3. When done, tell the user: URL source, the capability you identified, what you rewrote, any risks.
-
-### Mode C — "Help me install this skill: <directory path>"
-
-All files in the directory have already been copied into this skill's directory. Flow:
-
-1. First do `bash ls -R` or `search_files` to inspect — don't ask the user "where is that file?".
-2. Read the main files (SKILL.md, scripts, config) to understand the capability.
-3. Follow "Import optimization rules" below.
-4. When done, summarize: source dir, files kept / rewrote / deleted, what SKILL.md says.
-
-### Modes B / C — Import optimization rules (NOT applicable to Mode A)
-
-**Mental model**: importing is **minimum-invasive installation** — the original skill is already a working tool; keep it as the author wrote it. Only do two things: ① trim extraneous fields from the SKILL.md frontmatter; ② delete obvious meta-files unrelated to "being invoked by the LLM". **Forbidden**: rewriting the SKILL.md body / refactoring script skeletons / changing languages / moving file paths.
-
-**Frontmatter uses an allowlist — keep only these 3 fields, delete everything else**:
-- `name` (required; if missing, use the current skill directory name).
-- `description_zh` + `description_en`:
- - If the original is single-language `description`, identify its language, fill the matching field, **add the other one in the three-part formula** (a direct translation is acceptable, but better to rewrite per the target-language users' real phrasings).
- - If both are present, keep each as written; if one is too short / clearly marketing prose, **only that one** may be rewritten.
-
-The body outside the frontmatter is **kept verbatim** — don't rearrange or restate the author's "When to use / How to call / Return format / External dependencies / Examples" sections. Even if the original is tutorial-style or a long README, do NOT compress it into the 6-section structure — that's the template for writing from scratch in Mode A; it does NOT apply to imports.
-
-**Scripts, configs, directory structure = completely untouched**:
-- Scripts keep their original language, original filename, original path. Don't move them, don't rewrite cross-platform branches, don't wrap them into `bin/run-skill.cjs`-compatible shape, don't change languages.
-- Config files (`config.json` / `.env.example` / any toml/yaml/ini) kept as-is.
-- Directory structure (`src/` / `lib/` / `assets/` / sub-dir organization) kept as-is — do NOT consolidate everything into `scripts/`.
-
-**Deletion list**: `LICENSE*` / `COPYING` / `CHANGELOG*` / `CONTRIBUTING*` / `CODE_OF_CONDUCT*` / `AUTHORS` / `MAINTAINERS` / `.git/` / `.github/` / `.gitignore` / `.gitattributes` / `.editorconfig` / `node_modules/` / `__pycache__/` / `.venv/` / `dist/` / `build/` / standalone `docs/` directories. **Keep** `README*` (many skills put usage notes there) and `tests/` / `test/` (may be sample data the script depends on). Files outside this list **must not be deleted**; once done, list everything you removed without asking.
-
-**Scope = the original skill's full feature set**: by default migrate everything. If the original has 20 commands, migrate 20. Do NOT present "option A vs B" choices; do NOT drop features citing "less code / no new dependencies". If the source is a multi-skill package with internal dependencies → install each sub-skill as an independent skill (multiple Mode B passes); don't try to preserve the original's dependency graph. **Exception**: if the user explicitly requests a subset ("I only want the search capability"), follow what the user said.
-
-## Conversation prose rules — what the user sees
-
-The conversation prose **outside** `<<<skill-file>>>` blocks is what the user sees. Only state user-perspective facts: which files you wrote / changed, what this skill does / when it gets invoked, what the user's next step is. Do NOT expose internal decision process / session terminology / frontmatter field names / design-pattern names.
-
-**Forbidden words** (never appear in conversation prose):
-- Field / metadata terms: `frontmatter` / `description` field / `description_zh` / `description_en` / `name` field / `requires` / `external_deps` / `tags` / `slug` / `version` / id.
-- Design-pattern terms: `<skill>` / `<skill_id>` / `<<<skill-file>>>` / `guide-type` / `executable` / "three-part formula" / "selection trigger" / "skeleton" / "closure" / "generic style" / "allowlist".
-- Process terms: `Mode A` / `Mode B` / `Mode C` / "import optimization rules" / section numbers.
-
-**Translation table** (write the actual sentence in user UI language):
-- Editing frontmatter description_zh / description_en → "I updated its description to ..." (don't expose bilingual nature).
-- Editing the SKILL.md body → "I cleaned up its usage notes."
-- Writing `scripts/foo.py` → "I added a script `foo.py` that does ..."
-- Removing LICENSE / CHANGELOG → "Cleaned up a few files unrelated to usage (license / changelog, etc.)."
-
-The wrong / right examples below illustrate **prose style** — write in the user's UI language; filenames, code identifiers, and quoted user phrasings stay as-is.
-
-Wrong: "I wrote the `SKILL.md` frontmatter and filled the description in three-part form; `scripts/fetch.py` is an executable skeleton."
-
-Right: "I've written `SKILL.md`: this skill is invoked when the user asks 'scrape data from platform X'. The script `scripts/fetch.py` takes a keyword argument and outputs JSON."
-
-## Output rules
-
-- **On failure, state the cause clearly + suggest a remedy** ("download failed: timeout; suggest switching mirror"); do not power through.
-- Output is **concise**; don't dump giant code blocks at once; advance step by step.
-- **Also handle ordinary conversation**: if the user asks something unrelated, just answer normally; afterwards you may ask whether to continue refining.
diff --git a/src/builtin/skills/social-fetch/SKILL.md b/src/builtin/skills/social-fetch/SKILL.md
deleted file mode 100644
index f32a321b..00000000
--- a/src/builtin/skills/social-fetch/SKILL.md
+++ /dev/null
@@ -1,141 +0,0 @@
----
-name: social-fetch
-description_zh: "抓取小红书 / Twitter X / Reddit / YouTube / Bilibili 上指定关键词的公开帖子,去重后返回结构化结果(标题 / 正文 / 互动数 / URL),供下游做情绪 / 趋势分析。适合\"分析一下小红书最近的 X 话题\"\"看看 Reddit 上对产品 Y 的口碑\"\"找几条 Bilibili 上 Z 的高赞视频\";触发词:抓一下、找一下、分析、舆情、热度、口碑、讨论、竞品反馈"
-description_en: "Fetch public posts on Xiaohongshu / Twitter/X / Reddit / YouTube / Bilibili that match given keywords and return deduplicated structured results (title, body, engagement counts, URL) for downstream sentiment / trend analysis. Suitable for 'analyze the latest X discussion on Xiaohongshu', 'check the Reddit reputation of product Y', 'find a few high-upvote Bilibili videos about Z'. Triggers: fetch, find, analyze, sentiment, buzz, reputation, discussion, competitor feedback."
----
-
-# Social-fetch skill
-
-Fetch public content for given keywords on a single platform, deduplicate, and return `items` (structured) + `diag` (collection status). Each call runs **one** platform — multi-platform needs are dispatched by the caller across multiple invocations.
-
-## When to use
-
-- "Analyze the discussion of *X* on Xiaohongshu" / "Are people on Reddit complaining about *Y*?"
-- Research the real reviews, sentiment, or competitor reputation of a brand / product / topic on a given platform
-- Monitor industry hotspots and high-frequency user complaints to add primary material to an analysis report
-
-**Don't do**: DMs, login-gated content, non-public data, platforms that require a paid API.
-
-## How to invoke
-
-Single entry point:
-
-```bash
-$ORKAS_NODE $ORKAS_PC_DIR/bin/run-skill.cjs social-fetch fetch -- <platform> <keywords> [options]
-```
-
-Arguments:
-
-- `<platform>` ∈ `xhs | twitter | reddit | youtube | bilibili` (one platform per call)
-- `<keywords>`: comma-separated, 3–8 divergent short keyword groups (see **Keyword strategy**)
-- `--max-detail N` (default 30): cap on detail / comment fetches; only controls request count — **all deduped items go into the result**
-- Per-platform options (defaults used if omitted):
-
-| Platform | Option | Valid values / default |
-|---|---|---|
-| Xiaohongshu | `--xhs-publish-time` | `一天内` (last day) / `一周内` (last week) / `半年内` (last 6 months, default) / `不限` (unlimited) |
-| | `--xhs-sort` | `最新` (newest, default) / `最热` (hottest) |
-| Twitter/X | `--twitter-count` | 1–100, default 30 |
-| Reddit | `--reddit-time` | `day` / `week` / `month` (default) / `year` / `all` |
-| | `--reddit-sort` | `new` (default) / `top` / `hot` / `relevance` / `comments` |
-| Bilibili | `--bilibili-sort` | `pubdate` (default) / `totalrank` / `click` / `dm` / `stow` |
-| YouTube | (no platform options) | — |
-
-> Note: the Xiaohongshu enum values are Chinese strings because the upstream local proxy expects them verbatim — pass them as-is.
-
-## Return format
-
-Success (single line of JSON on stdout):
-```json
-{"ok": true, "platform": "xhs", "count": 27, "items": [{...}, ...], "diag": {...}}
-```
-
-`items[]` fields (aligned across platforms): `title` / `text` (body excerpt) / `comments` (array of comment excerpts) / `engagement` (likes / comments / collects etc.) / `published_at` / `url`.
-
-`diag`: `{name, status: 'ok'|'empty'|'error', raw_hits, selected, failed, reason?, errors?, detail[]}` — records raw recall, deduped count, and failure reasons.
-
-Failure (stderr + non-zero exit code):
-```json
-{"ok": false, "error": "TypeError: ..."}
-```
-
-## External dependencies
-
-| Platform | Dependency | Behavior when missing |
-|---|---|---|
-| Xiaohongshu | Local proxy `http://localhost:18060` | `diag.reason=xhs_service_unreachable`, items=[] |
-| Twitter/X | `xreach` CLI (`npm i -g xreach-cli`) | items=[] |
-| Reddit | Python `requests` + cookies auto-loaded from any installed browser via `browser_cookie3` | Anonymous fetch works but recall is limited |
-| YouTube | `yt-dlp` CLI (`pip install yt-dlp`) | items=[] |
-| Bilibili | `requests` + same cookie source as Reddit | Anonymous recall is limited |
-
-Common: `pip install requests browser_cookie3`.
-
-**Strongly recommended to log in to Reddit / Bilibili in your regular browser** — anonymous recall is unstable; see below.
-
-## Browser login state (Reddit / Bilibili)
-
-Just log in once in any installed browser; `browser_cookie3` reads cookies directly from the browser's profile. No extra setup or external CLI required.
-
-Default browser priority: `chrome → firefox → edge → safari → brave → chromium` — the first one that has a matching cookie wins.
-
-Override the order (or restrict to a single browser) with the `SOCIAL_FETCH_BROWSERS` env var (comma-separated):
-
-```bash
-SOCIAL_FETCH_BROWSERS=firefox,chrome python fetch.py reddit "..."
-```
-
-If neither `browser_cookie3` is installed nor any of the listed browsers yields cookies for the target domain, the fetch falls back to anonymous mode.
-
-## Keyword strategy (core rule)
-
-**Never** use the user's raw query as a search term. Extract and diverge keywords first; use 3–8 short keyword groups to maximize recall.
-
-| Strategy | Applies when | How |
-|---|---|---|
-| Direct core terms | The user gave a clear proper noun or model number | Use the term as-is |
-| Synonyms / colloquial | Brand / product research and other open-ended topics | Add nicknames, abbreviations, pinyin initials |
-| Scenario / pain points | Looking for a specific use case or comparison | Add "avoid / recommend / compare / how to choose" |
-| Bilingual (CN/EN) | Concept discussed in both Chinese and English communities | Add the English equivalent |
-
-Single keyword length: 2–12 Chinese chars / 1–4 English words. **Prefer many keywords with many searches over too-narrow keywords yielding zero results.**
-
-## Limits / known issues
-
-- **One platform per call** — 5-platform needs require the caller to dispatch 5 calls (avoids one stuck platform blocking the others)
-- **Zero data ≠ signal**: when `diag.status=='empty'`, do not infer "no one is discussing" from "nothing returned"
-- **Don't fabricate on fetch failure**: when `status=='error'`, faithfully report `reason`; don't synthesize samples
-- **Xiaohongshu proxy service**: only valid on local macOS (`localhost:18060`); without the proxy this platform errors directly
-- **YouTube subtitles / comments**: depend on yt-dlp; some videos can't return subtitles (private / restricted / no auto-subtitles)
-- **Reddit / Bilibili anonymous fetch**: recall is significantly lower than logged-in; log in via your regular browser (see above) for stable use
-- **Cross-platform paths**: cookie reads go through `browser_cookie3`, which finds the right profile per-OS automatically; the `xhs` proxy path has only been tested on macOS
-
-## Full examples
-
-```bash
-# 1. Top monthly Reddit discussions related to "claude code"
-$ORKAS_NODE $ORKAS_PC_DIR/bin/run-skill.cjs social-fetch fetch -- \
- reddit "claude code,claude cli,anthropic cli" \
- --reddit-sort top --reddit-time month --max-detail 20
-
-# Output (truncated)
-# {"ok":true,"platform":"reddit","count":18,"items":[
-# {"title":"Claude Code is way better than ...", "url":"https://reddit.com/...",
-# "engagement":{"upvotes":342,"comments":87}, "comments":["...","..."], ...},
-# ...
-# ], "diag":{"name":"Reddit","status":"ok","raw_hits":31,"selected":18,...}}
-```
-
-```bash
-# 2. Last-week Xiaohongshu discussion about AirPods
-$ORKAS_NODE $ORKAS_PC_DIR/bin/run-skill.cjs social-fetch fetch -- \
- xhs "AirPods,airpods4,苹果耳机,无线耳机怎么选" \
- --xhs-publish-time 一周内 --xhs-sort 最热
-```
-
-## Rules
-
-- **Keywords must diverge**: unless the user explicitly restricts the query, automatically extend to synonyms / colloquial / bilingual variants
-- **Conclusions must be traceable**: analysis output must point back to specific samples in `items[]`; don't be vague
-- **Restrain `max_detail`**: when performance-sensitive, 10–15 covers most scenarios
-- **Don't replicate platform logic outside `fetch.py`**: all platform details are centralized in `social_fetch_core.py`
diff --git a/src/builtin/skills/social-fetch/scripts/fetch.py b/src/builtin/skills/social-fetch/scripts/fetch.py
deleted file mode 100644
index a3d0afce..00000000
--- a/src/builtin/skills/social-fetch/scripts/fetch.py
+++ /dev/null
@@ -1,98 +0,0 @@
-#!/usr/bin/env python3
-"""Single-platform fetch entry — invoked via run-skill.cjs.
-
-Usage:
- python fetch.py <platform> <keywords> [options]
-
- platform = xhs | twitter | reddit | youtube | bilibili
- keywords = comma-separated, e.g. "iphone 15,苹果15,iphone15"
-
-Common option:
- --max-detail N per-platform detail/comment cap (default 30)
-
-Per-platform options:
- --xhs-publish-time {一天内|一周内|半年内|不限} default 半年内 (last 6 months)
- --xhs-sort {最新|最热} default 最新 (newest)
- --twitter-count N default 30
- --reddit-time {day|week|month|year|all} default month
- --reddit-sort {new|top|hot|relevance|comments} default new
- --bilibili-sort {pubdate|totalrank|click|dm|stow} default pubdate
-
-Note: --xhs-* enum values are kept as Chinese strings because the upstream
-Xiaohongshu local proxy expects them verbatim. Pass them as-is.
-
-Output (stdout, single line JSON):
- {"ok": true, "platform": "xhs", "count": N, "items": [...], "diag": {...}}
-On failure (stderr + exit 1):
- {"ok": false, "error": "<msg>", "platform": "..."}
-"""
-import argparse
-import json
-import sys
-
-from social_fetch_core import (
- fetch_xhs, fetch_twitter, fetch_reddit, fetch_youtube, fetch_bilibili,
-)
-
-FETCHERS = {
- 'xhs': fetch_xhs,
- 'twitter': fetch_twitter,
- 'reddit': fetch_reddit,
- 'youtube': fetch_youtube,
- 'bilibili': fetch_bilibili,
-}
-
-
-def main(argv):
- p = argparse.ArgumentParser(prog='fetch.py')
- p.add_argument('platform', choices=list(FETCHERS))
- p.add_argument('keywords', help='comma-separated search keywords')
- p.add_argument('--max-detail', type=int, default=30)
- # xhs
- p.add_argument('--xhs-publish-time', default='半年内')
- p.add_argument('--xhs-sort', default='最新')
- # twitter
- p.add_argument('--twitter-count', type=int, default=30)
- # reddit
- p.add_argument('--reddit-time', default='month')
- p.add_argument('--reddit-sort', default='new')
- # bilibili
- p.add_argument('--bilibili-sort', default='pubdate')
-
- args = p.parse_args(argv)
-
- keywords = [k.strip() for k in args.keywords.split(',') if k.strip()]
- if not keywords:
- raise SystemExit(json.dumps({'ok': False, 'error': 'no keywords supplied'}))
-
- config = {
- f'{args.platform}_keywords': keywords,
- 'max_detail': args.max_detail,
- 'xhs_publish_time': args.xhs_publish_time,
- 'xhs_sort': args.xhs_sort,
- 'twitter_count': args.twitter_count,
- 'reddit_time': args.reddit_time,
- 'reddit_sort': args.reddit_sort,
- 'bilibili_sort': args.bilibili_sort,
- }
-
- items, diag = FETCHERS[args.platform](config)
- out = {
- 'ok': True,
- 'platform': args.platform,
- 'count': len(items),
- 'items': items,
- 'diag': diag,
- }
- print(json.dumps(out, ensure_ascii=False))
-
-
-if __name__ == '__main__':
- try:
- main(sys.argv[1:])
- except SystemExit:
- raise
- except Exception as e:
- err = {'ok': False, 'error': f'{type(e).__name__}: {e}'}
- print(json.dumps(err, ensure_ascii=False), file=sys.stderr)
- sys.exit(1)
diff --git a/src/builtin/skills/social-fetch/scripts/social_fetch_core.py b/src/builtin/skills/social-fetch/scripts/social_fetch_core.py
deleted file mode 100644
index 88ded67b..00000000
--- a/src/builtin/skills/social-fetch/scripts/social_fetch_core.py
+++ /dev/null
@@ -1,635 +0,0 @@
-#!/usr/bin/env python3
-"""Per-platform fetch primitives shared by `fetch.py`.
-
-Self-contained: depends only on `requests` and (optionally) `browser_cookie3`
-plus external CLIs (`xreach`, `yt-dlp`) and the local Xiaohongshu proxy.
-"""
-import json, os, re, shutil, subprocess, sys, time
-from concurrent.futures import ThreadPoolExecutor, as_completed
-from datetime import datetime
-
-import requests
-
-try:
- import browser_cookie3
- _BROWSER_COOKIE3_OK = True
-except ImportError:
- _BROWSER_COOKIE3_OK = False
-
-XHS_BASE = 'http://localhost:18060'
-XHS_REQUEST_TIMEOUT = 70 # Slightly above the server's internal 60s timeout, so we get a 500 instead of context-canceled
-XHS_DETAIL_WORKERS = 4 # Number of threads used to fetch detail concurrently
-DEFAULT_YOUTUBE_META_COUNT = 8
-DEFAULT_YOUTUBE_META_WORKERS = 4
-
-# Browsers that browser_cookie3 can read from. Order = priority — first browser
-# that yields cookies for the requested domain wins. Override with the
-# SOCIAL_FETCH_BROWSERS env var (comma-separated) when needed.
-_DEFAULT_BROWSERS = ('chrome', 'firefox', 'edge', 'safari', 'brave', 'chromium')
-
-
-def _load_cookies_for_domain(domain_name: str) -> dict:
- """Read cookies for `domain_name` from any installed browser.
-
- Tries each browser in `_DEFAULT_BROWSERS` order (or the env override) and
- returns the first non-empty cookie set. Returns {} if browser_cookie3 is
- not installed or no browser yielded cookies.
- """
- if not _BROWSER_COOKIE3_OK:
- return {}
-
- override = os.environ.get('SOCIAL_FETCH_BROWSERS', '').strip()
- if override:
- browsers = tuple(b.strip() for b in override.split(',') if b.strip())
- else:
- browsers = _DEFAULT_BROWSERS
-
- for name in browsers:
- loader = getattr(browser_cookie3, name, None)
- if not callable(loader):
- continue
- try:
- cj = loader(domain_name=domain_name)
- cookies = {c.name: c.value for c in cj}
- if cookies:
- return cookies
- except Exception:
- continue
- return {}
-
-
-def _get_reddit_cookies():
- return _load_cookies_for_domain('.reddit.com')
-
-
-def _get_bilibili_cookies():
- return _load_cookies_for_domain('.bilibili.com')
-
-
-def log(msg):
- ts = datetime.now().strftime('%H:%M:%S')
- print(f'[{ts}] {msg}', flush=True)
-
-
-def to_int(v):
- try:
- return int(str(v).replace(',', ''))
- except Exception:
- return 0
-
-
-def make_diag(name):
- return {
- 'platform': name,
- 'status': 'ok',
- 'reason': '',
- 'raw_hits': 0,
- 'deduped': 0,
- 'selected': 0,
- 'failed': 0,
- 'errors': [],
- 'details': [],
- }
-
-
-def add_diag(diag, **kwargs):
- for k, v in kwargs.items():
- if k == 'errors' and v:
- diag.setdefault('errors', []).append(v)
- elif k == 'detail' and v:
- diag.setdefault('details', []).append(v)
- else:
- diag[k] = v
-
-
-def xreach_cmd(keyword, count=30):
- return ['xreach', 'search', keyword, '--json', '-n', str(count)]
-
-
-def yt_dlp_cmd(*args):
- bin_path = shutil.which('yt-dlp')
- if bin_path:
- return [bin_path, *args]
- return [sys.executable, '-m', 'yt_dlp', *args]
-
-
-def _yt_dlp_search(prefix, kw, limit=8, browser_cookies=None):
- q = f'{prefix}{limit}:{kw}'
- cmd = yt_dlp_cmd(q, '--dump-single-json', '--skip-download', '--flat-playlist')
- if browser_cookies:
- cmd = yt_dlp_cmd('--cookies-from-browser', browser_cookies, q, '--dump-single-json', '--skip-download', '--flat-playlist')
- try:
- r = subprocess.run(cmd, capture_output=True, text=True, timeout=90)
- if r.returncode != 0 or not r.stdout.strip():
- return []
- data = json.loads(r.stdout)
- return data.get('entries', []) or []
- except Exception:
- return []
-
-
-def _yt_dlp_meta(url):
- try:
- r = subprocess.run(yt_dlp_cmd(url, '--dump-json', '--skip-download'), capture_output=True, text=True, timeout=90)
- if r.returncode != 0 or not r.stdout.strip():
- return {}
- return json.loads(r.stdout.strip().splitlines()[-1])
- except Exception:
- return {}
-
-
-def _twitter_fetch_comments(tweet_url):
- try:
- result = subprocess.run(
- ['xreach', 'thread', tweet_url, '--json'],
- capture_output=True, text=True, timeout=90,
- )
- if result.returncode != 0 or not result.stdout.strip():
- return []
- data = json.loads(result.stdout)
- items = data.get('items', [])
- replies = items[1:] if len(items) > 1 else []
- return [
- {'user': r.get('username', ''), 'text': r.get('text', '')}
- for r in replies
- if r.get('text')
- ]
- except Exception:
- return []
-
-
-def _youtube_fetch_comments(url):
- try:
- r = subprocess.run(
- yt_dlp_cmd('--write-comments', '--dump-json', '--skip-download', url),
- capture_output=True, text=True, timeout=120,
- )
- if r.returncode != 0 or not r.stdout.strip():
- return []
- data = json.loads(r.stdout.strip().splitlines()[-1])
- comments = data.get('comments', []) or []
- return [
- {'user': c.get('author', ''), 'text': c.get('text', '')}
- for c in comments
- if c.get('text')
- ]
- except Exception:
- return []
-
-
-# Xiaohongshu enum values are Chinese strings sent verbatim to the upstream
-# local proxy server — do not translate.
-_XHS_VALID_PUBLISH_TIMES = {'一天内', '一周内', '半年内', '不限'}
-_XHS_VALID_SORTS = {'最新', '最热'}
-
-def fetch_xhs(config):
- log('🔴 Fetching Xiaohongshu...')
- diag = make_diag('Xiaohongshu')
- seen, notes = set(), []
-
- publish_time = config.get('xhs_publish_time', '半年内')
- if publish_time not in _XHS_VALID_PUBLISH_TIMES:
- log(f' ⚠️ xhs_publish_time="{publish_time}" is not a valid enum, falling back to "半年内" (valid: {sorted(_XHS_VALID_PUBLISH_TIMES)})')
- publish_time = '半年内'
-
- xhs_sort = config.get('xhs_sort', '最新')
- if xhs_sort not in _XHS_VALID_SORTS:
- log(f' ⚠️ xhs_sort="{xhs_sort}" is not a valid enum, falling back to "最新" (valid: {sorted(_XHS_VALID_SORTS)})')
- xhs_sort = '最新'
-
- try:
- requests.get(XHS_BASE, timeout=3)
- except Exception as e:
- add_diag(diag, status='error', reason='xhs_service_unreachable', errors=str(e))
- log(f' ❌ Xiaohongshu service unreachable: {e}')
- return [], diag
-
- _xhs_broken = False # After a server error, do not retry remaining keywords
- for kw in config['xhs_keywords']:
- if _xhs_broken:
- break
- log(f' → {kw}')
- try:
- resp = requests.post(
- f'{XHS_BASE}/api/v1/feeds/search',
- json={'keyword': kw, 'filters': {'sort_by': xhs_sort, 'note_type': '不限', 'publish_time': publish_time}},
- timeout=XHS_REQUEST_TIMEOUT,
- )
- if resp.status_code >= 500:
- _xhs_broken = True
- add_diag(diag, status='error', reason=f'xhs_search_http_{resp.status_code}',
- failed=diag['failed'] + 1, errors=f'{kw}: HTTP {resp.status_code}')
- log(f' ❌ HTTP {resp.status_code}, Xiaohongshu service error; skipping remaining keywords')
- break
- payload = resp.json()
- feeds = payload.get('data', {}).get('feeds', []) if payload.get('success') else []
- except requests.exceptions.Timeout:
- _xhs_broken = True
- add_diag(diag, status='error', reason='xhs_search_timeout',
- failed=diag['failed'] + 1, errors=f'{kw}: timeout>{XHS_REQUEST_TIMEOUT}s')
- log(f' ❌ Search timeout (>{XHS_REQUEST_TIMEOUT}s), Xiaohongshu service error; skipping remaining keywords')
- break
- except Exception as e:
- log(f' failed: {e}')
- add_diag(diag, failed=diag['failed'] + 1, errors=f'{kw}: {e}')
- feeds = []
- add_diag(diag, raw_hits=diag['raw_hits'] + len(feeds), detail={'keyword': kw, 'raw_hits': len(feeds)})
- log(f' {len(feeds)} items')
- for feed in feeds:
- fid = feed.get('id', '')
- if not fid or fid in seen:
- continue
- seen.add(fid)
- nc = feed.get('noteCard', {}) or {}
- user = nc.get('user', {}) or {}
- notes.append({
- 'platform': 'Xiaohongshu',
- 'id': fid,
- 'xsec_token': feed.get('xsecToken', ''),
- 'url': f"https://www.xiaohongshu.com/explore/{fid}?xsec_token={feed.get('xsecToken','')}",
- 'title': nc.get('displayTitle', ''),
- 'author': user.get('nickname', ''),
- 'likes': to_int(nc.get('interactInfo', {}).get('likedCount', 0)),
- 'collects': to_int(nc.get('interactInfo', {}).get('collectedCount', 0)),
- 'comments': to_int(nc.get('interactInfo', {}).get('commentCount', 0)),
- 'keyword_hit': kw,
- 'content': '',
- 'comments_list': [],
- })
- time.sleep(0.3)
-
- notes.sort(key=lambda x: (-x.get('comments', 0), -x.get('likes', 0)))
- max_detail = max(1, int(config.get('max_detail') or 30))
-
- def _xhs_fetch_detail(n):
- try:
- resp = requests.post(
- f'{XHS_BASE}/api/v1/feeds/detail',
- json={'feed_id': n['id'], 'xsec_token': n.get('xsec_token', '')},
- timeout=XHS_REQUEST_TIMEOUT,
- )
- j = resp.json()
- inner = j.get('data', {}).get('data', {}) if j.get('success') else {}
- note = inner.get('note', {})
- n['content'] = note.get('desc', '') or note.get('title', '')
- cdata = inner.get('comments', {})
- clist = cdata.get('list', []) if isinstance(cdata, dict) else []
- n['comments_list'] = [
- {'user': c.get('userInfo', {}).get('nickname', ''), 'text': c.get('content', '')}
- for c in clist if isinstance(c, dict)
- ]
- return n, None
- except Exception as e:
- return n, e
-
- detail_targets = notes[:max_detail]
- log(f' 📥 Fetching detail ({len(detail_targets)} notes, concurrency {XHS_DETAIL_WORKERS})...')
- workers = max(1, min(XHS_DETAIL_WORKERS, len(detail_targets)))
- with ThreadPoolExecutor(max_workers=workers) as pool:
- futures = {pool.submit(_xhs_fetch_detail, n): n for n in detail_targets}
- for future in as_completed(futures):
- _, err = future.result()
- if err:
- n = futures[future]
- add_diag(diag, failed=diag['failed'] + 1, errors=f"detail:{n.get('id','')}: {err}")
-
- add_diag(diag, deduped=len(notes), selected=len(notes))
- if not notes and diag['status'] == 'ok':
- add_diag(diag, status='empty', reason='no_results_after_search')
- log(f" ✅ Xiaohongshu {len(notes)} items, {sum(1 for n in notes[:max_detail] if n['content'])} with body")
- return notes, diag
-
-
-def fetch_twitter(config):
- log('🔵 Fetching Twitter/X...')
- diag = make_diag('Twitter/X')
- seen, tweets = set(), []
- twitter_count = max(1, min(100, int(config.get('twitter_count', 30))))
- for kw in config['twitter_keywords']:
- log(f' → {kw}')
- try:
- result = subprocess.run(xreach_cmd(kw, twitter_count), capture_output=True, text=True, timeout=90)
- if result.returncode == 0 and result.stdout.strip():
- items = json.loads(result.stdout).get('items', [])
- add_diag(diag, raw_hits=diag['raw_hits'] + len(items), detail={'keyword': kw, 'raw_hits': len(items)})
- log(f' {len(items)} items')
- for item in items:
- tid = item.get('id', '')
- if not tid or tid in seen:
- continue
- seen.add(tid)
- tweets.append({
- 'platform': 'Twitter/X', 'id': tid, 'url': f'https://x.com/i/web/status/{tid}',
- 'title': '', 'author': item.get('username', ''),
- 'likes': to_int(item.get('likes', 0)), 'collects': 0,
- 'comments': to_int(item.get('replies', 0)), 'retweets': to_int(item.get('retweets', 0)),
- 'views': to_int(item.get('views', 0)), 'keyword_hit': kw,
- 'content': (item.get('text') or ''), 'comments_list': [],
- })
- else:
- err = (result.stderr or result.stdout or '').strip()[:200]
- add_diag(diag, failed=diag['failed'] + 1, errors=f"{kw}: {err or 'xreach returned empty'}")
- log(' xreach returned empty or error')
- except subprocess.TimeoutExpired:
- add_diag(diag, failed=diag['failed'] + 1, errors=f'{kw}: timeout')
- log(' timeout')
- except Exception as e:
- add_diag(diag, failed=diag['failed'] + 1, errors=f'{kw}: {e}')
- log(f' failed: {e}')
- time.sleep(2)
-
- tweets.sort(key=lambda x: (-x.get('comments', 0), -x.get('likes', 0)))
- max_detail = max(1, int(config.get('max_detail') or 30))
-
- log(f' 📥 Fetching {min(len(tweets), max_detail)} tweet replies...')
- for t in tweets[:max_detail]:
- try:
- t['comments_list'] = _twitter_fetch_comments(t['url'])
- except Exception as e:
- add_diag(diag, failed=diag['failed'] + 1, errors=f"thread:{t.get('id','')}: {e}")
- time.sleep(2)
-
- add_diag(diag, deduped=len(tweets), selected=len(tweets))
- if not tweets and diag['status'] == 'ok':
- add_diag(diag, status='empty', reason='no_results_after_search')
- log(f' ✅ Twitter/X {len(tweets)} items')
- return tweets, diag
-
-
-_REDDIT_VALID_SORTS = {'new', 'top', 'hot', 'relevance', 'comments'}
-
-
-def _reddit_get_json(urls, headers, cookies, timeout=30, retries=3, backoff=1.5):
- last_err = None
- for idx, url in enumerate(urls):
- for attempt in range(1, retries + 1):
- try:
- resp = requests.get(url, headers=headers, cookies=cookies, timeout=timeout)
- if resp.status_code == 403:
- return resp, None
- if resp.status_code in (429, 500, 502, 503, 504):
- last_err = RuntimeError(f'HTTP {resp.status_code}')
- if attempt < retries:
- time.sleep(backoff * attempt)
- continue
- resp.raise_for_status()
- return resp, resp.json()
- except Exception as e:
- last_err = e
- if attempt < retries:
- time.sleep(backoff * attempt)
- continue
- if idx < len(urls) - 1:
- time.sleep(1)
- raise last_err or RuntimeError('reddit_request_failed')
-
-
-def fetch_reddit(config):
- log('🟠 Fetching Reddit...')
- diag = make_diag('Reddit')
- seen, posts = set(), []
- headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36'}
- cookies = _get_reddit_cookies()
- if not cookies:
- log(' ⚠️ Reddit cookies not available; fetch success rate may drop')
-
- reddit_sort = config.get('reddit_sort', 'new')
- if reddit_sort not in _REDDIT_VALID_SORTS:
- log(f' ⚠️ reddit_sort="{reddit_sort}" is not a valid enum, falling back to "new" (valid: {sorted(_REDDIT_VALID_SORTS)})')
- reddit_sort = 'new'
-
- for kw in config['reddit_keywords']:
- log(f' → {kw}')
- try:
- encoded_kw = requests.utils.quote(kw)
- search_urls = [
- f"https://www.reddit.com/search.json?q={encoded_kw}&sort={reddit_sort}&t={config.get('reddit_time','month')}&limit=25",
- f"https://old.reddit.com/search.json?q={encoded_kw}&sort={reddit_sort}&t={config.get('reddit_time','month')}&limit=25",
- ]
- resp, data = _reddit_get_json(search_urls, headers, cookies, timeout=30, retries=3)
- if resp.status_code == 403:
- add_diag(diag, status='error', reason='reddit_403_blocked', failed=diag['failed'] + 1, errors=f'{kw}: HTTP 403')
- log(' HTTP 403 (blocked by Reddit)')
- continue
- items = (data or {}).get('data', {}).get('children', [])
- add_diag(diag, raw_hits=diag['raw_hits'] + len(items), detail={'keyword': kw, 'raw_hits': len(items)})
- log(f' {len(items)} items')
- for item in items:
- d = item.get('data', {})
- pid = d.get('id', '')
- if not pid or pid in seen:
- continue
- seen.add(pid)
- posts.append({
- 'platform': 'Reddit', 'id': pid, 'url': f"https://www.reddit.com{d.get('permalink', '')}",
- 'title': d.get('title', ''), 'author': d.get('author', ''),
- 'likes': d.get('score', 0), 'collects': 0, 'comments': d.get('num_comments', 0),
- 'keyword_hit': kw, 'content': d.get('selftext', ''), 'comments_list': [],
- 'subreddit': d.get('subreddit_name_prefixed', ''),
- })
- except Exception as e:
- add_diag(diag, failed=diag['failed'] + 1, errors=f'{kw}: {e}')
- log(f' failed: {e}')
- time.sleep(1)
-
- posts.sort(key=lambda x: (-x.get('comments', 0), -x.get('likes', 0)))
- max_detail = max(1, int(config.get('max_detail') or 30))
-
- log(f' 📥 Fetching comments for {min(len(posts), max_detail)} posts...')
- for p in posts[:max_detail]:
- try:
- path = p['url'].replace('https://www.reddit.com', '')
- detail_urls = [
- f'https://www.reddit.com{path}.json?limit=500',
- f'https://old.reddit.com{path}.json?limit=500',
- ]
- _, cmt_data = _reddit_get_json(detail_urls, headers, cookies, timeout=20, retries=3)
- if isinstance(cmt_data, list) and len(cmt_data) > 1:
- cmts = cmt_data[1].get('data', {}).get('children', [])
- p['comments_list'] = [{'user': c['data'].get('author', ''), 'text': c['data'].get('body', '')} for c in cmts if isinstance(c.get('data'), dict) and c['data'].get('body')]
- except Exception as e:
- add_diag(diag, failed=diag['failed'] + 1, errors=f"detail:{p.get('id','')}: {e}")
- time.sleep(1)
-
- add_diag(diag, deduped=len(posts), selected=len(posts))
- if not posts and diag['status'] == 'ok':
- add_diag(diag, status='empty', reason='no_results_after_search')
- log(f' ✅ Reddit {len(posts)} items')
- return posts, diag
-
-
-def fetch_youtube(config):
- log('🟣 Fetching YouTube...')
- diag = make_diag('YouTube')
- seen, raw_entries = set(), []
- for kw in config['youtube_keywords']:
- log(f' → {kw}')
- entries = _yt_dlp_search('ytsearch', kw, limit=30)
- if not entries:
- add_diag(diag, failed=diag['failed'] + 1, errors=f'{kw}: ytsearch returned empty')
- add_diag(diag, raw_hits=diag['raw_hits'] + len(entries), detail={'keyword': kw, 'raw_hits': len(entries)})
- log(f' {len(entries)} items')
- for e in entries:
- vid = (e.get('id') or '').strip()
- if not vid or vid in seen:
- continue
- seen.add(vid)
- raw_entries.append((kw, e))
- time.sleep(1)
-
- max_detail = max(1, int(config.get('max_detail') or 30))
- meta_limit = max(1, int(config.get('youtube_meta_count') or min(max_detail, DEFAULT_YOUTUBE_META_COUNT)))
- meta_workers = max(1, min(8, int(config.get('youtube_meta_workers') or DEFAULT_YOUTUBE_META_WORKERS)))
-
- def _build_video(item):
- kw, e = item
- vid = (e.get('id') or '').strip()
- url = e.get('url') or f'https://www.youtube.com/watch?v={vid}'
- m = _yt_dlp_meta(url)
- if not m:
- return {
- 'platform': 'YouTube', 'id': vid, 'url': url,
- 'title': (e.get('title') or '').strip(),
- 'author': '', 'likes': 0, 'collects': 0,
- 'comments': 0, 'views': 0,
- 'keyword_hit': kw, 'content': '', 'comments_list': [],
- '_meta_error': 'empty_meta',
- }
- return {
- 'platform': 'YouTube', 'id': vid, 'url': m.get('webpage_url') or url,
- 'title': (m.get('title') or e.get('title') or '').strip(),
- 'author': m.get('uploader') or m.get('channel') or '',
- 'likes': to_int(m.get('like_count', 0)), 'collects': 0,
- 'comments': to_int(m.get('comment_count', 0)), 'views': to_int(m.get('view_count', 0)),
- 'keyword_hit': kw, 'content': (m.get('description') or ''), 'comments_list': [],
- }
-
- videos = []
- meta_targets = raw_entries[:meta_limit]
- skipped_meta = max(0, len(raw_entries) - len(meta_targets))
- if skipped_meta:
- add_diag(diag, detail={'meta_skipped': skipped_meta, 'meta_limit': meta_limit})
- log(f' 📥 Filling metadata for {len(meta_targets)} videos (concurrency {meta_workers})...')
- with ThreadPoolExecutor(max_workers=meta_workers) as pool:
- future_map = {pool.submit(_build_video, item): item for item in meta_targets}
- for future in as_completed(future_map):
- item = future_map[future]
- kw, e = item
- vid = (e.get('id') or '').strip()
- try:
- video = future.result()
- except Exception as ex:
- add_diag(diag, failed=diag['failed'] + 1, errors=f'meta:{vid}: {ex}')
- continue
- if video.get('_meta_error'):
- add_diag(diag, failed=diag['failed'] + 1, errors=f'meta:{vid}: {video.get("_meta_error")}')
- video.pop('_meta_error', None)
- videos.append(video)
-
- videos.sort(key=lambda x: (-x.get('comments', 0), -x.get('likes', 0), x.get('title', '')))
-
- log(f' 📥 Fetching comments for {min(len(videos), max_detail)} videos...')
- for v in videos[:max_detail]:
- try:
- v['comments_list'] = _youtube_fetch_comments(v['url'])
- except Exception as e:
- add_diag(diag, failed=diag['failed'] + 1, errors=f"comments:{v.get('id','')}: {e}")
- time.sleep(2)
-
- add_diag(diag, deduped=len(raw_entries), selected=len(videos), detail={'meta_workers': meta_workers})
- if not videos and diag['status'] == 'ok':
- add_diag(diag, status='empty', reason='no_results_after_search')
- log(f' ✅ YouTube {len(videos)} items (raw deduped {len(raw_entries)})')
- return videos, diag
-
-
-_BILIBILI_VALID_SORTS = {'pubdate', 'totalrank', 'click', 'dm', 'stow'}
-
-def fetch_bilibili(config):
- log('🟡 Fetching Bilibili...')
- diag = make_diag('Bilibili')
- seen, videos = set(), []
- headers = {
- 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
- 'Referer': 'https://www.bilibili.com',
- }
- cookies = _get_bilibili_cookies()
- if not cookies:
- log(' ⚠️ Bilibili cookies not available; anti-scraping may trigger')
-
- bilibili_sort = config.get('bilibili_sort', 'pubdate')
- if bilibili_sort not in _BILIBILI_VALID_SORTS:
- log(f' ⚠️ bilibili_sort="{bilibili_sort}" is not a valid enum, falling back to "pubdate" (valid: {sorted(_BILIBILI_VALID_SORTS)})')
- bilibili_sort = 'pubdate'
-
- for kw in config['bilibili_keywords']:
- log(f' → {kw}')
- try:
- url = (
- f"https://api.bilibili.com/x/web-interface/search/type"
- f"?search_type=video&keyword={requests.utils.quote(kw)}"
- f"&page=1&page_size=30&order={bilibili_sort}"
- )
- resp = requests.get(url, headers=headers, cookies=cookies, timeout=30)
- data = resp.json()
- if data.get('code') != 0:
- err = data.get('message', f'code={data.get("code")}')
- add_diag(diag, failed=diag['failed'] + 1, errors=f'{kw}: {err}')
- log(f' API error: {err}')
- continue
- items = data.get('data', {}).get('result', []) or []
- add_diag(diag, raw_hits=diag['raw_hits'] + len(items), detail={'keyword': kw, 'raw_hits': len(items)})
- log(f' {len(items)} items')
- for item in items:
- bvid = item.get('bvid', '')
- if not bvid or bvid in seen:
- continue
- seen.add(bvid)
- videos.append({
- 'platform': 'Bilibili', 'id': bvid,
- 'aid': item.get('aid', 0),
- 'url': item.get('arcurl') or f'https://www.bilibili.com/video/{bvid}',
- 'title': re.sub(r'<[^>]+>', '', item.get('title', '')),
- 'author': item.get('author', ''),
- 'likes': to_int(item.get('like', 0)),
- 'collects': to_int(item.get('favorites', 0)),
- 'comments': to_int(item.get('review', 0)),
- 'views': to_int(item.get('play', 0)),
- 'keyword_hit': kw,
- 'content': (item.get('description') or ''),
- 'comments_list': [],
- })
- except Exception as e:
- add_diag(diag, failed=diag['failed'] + 1, errors=f'{kw}: {e}')
- log(f' failed: {e}')
- time.sleep(1)
-
- videos.sort(key=lambda x: (-x.get('comments', 0), -x.get('likes', 0)))
- max_detail = max(1, int(config.get('max_detail') or 30))
-
- log(f' 📥 Fetching comments for {min(len(videos), max_detail)} videos...')
- for v in videos[:max_detail]:
- aid = v.get('aid', 0)
- if not aid:
- continue
- try:
- cm_resp = requests.get(
- f'https://api.bilibili.com/x/v2/reply?type=1&oid={aid}&pn=1&ps=50&sort=0',
- headers=headers, cookies=cookies, timeout=20,
- )
- cm_data = cm_resp.json()
- if cm_data.get('code') == 0:
- replies = cm_data.get('data', {}).get('replies', []) or []
- v['comments_list'] = [
- {'user': r.get('member', {}).get('uname', ''), 'text': r.get('content', {}).get('message', '')}
- for r in replies if isinstance(r, dict)
- ]
- except Exception:
- pass
- time.sleep(0.5)
-
- add_diag(diag, deduped=len(videos), selected=len(videos))
- if not videos and diag['status'] == 'ok':
- add_diag(diag, status='empty', reason='no_results_after_search')
- log(f' ✅ Bilibili {len(videos)} items')
- return videos, diag
diff --git a/src/builtin/skills/word-docx/SKILL.md b/src/builtin/skills/word-docx/SKILL.md
deleted file mode 100644
index 2f577f40..00000000
--- a/src/builtin/skills/word-docx/SKILL.md
+++ /dev/null
@@ -1,105 +0,0 @@
----
-name: Word / DOCX
-slug: word-docx
-version: 1.0.2
-homepage: https://clawic.com/skills/word-docx
-description_zh: "创建、查看、编辑 Microsoft Word 文档和 DOCX 文件,样式 / 编号 / 修订 / 表格 / 分节 / 兼容性都可靠。适合\"做一份 X 主题的 Word 文档\"\"修改这份 .docx 保留修订标记\"\"往报告里插表格\";触发词:word、docx、文档、修订、批注、字段、模板、排版"
-description_en: "Create, inspect, and edit Microsoft Word documents and DOCX files with reliable styles, numbering, tracked changes, tables, sections, and compatibility checks. Use when (1) the task is about Word or `.docx`; (2) the file includes tracked changes, comments, fields, tables, templates, or page layout constraints; (3) the document must survive round-trip editing without formatting drift."
-changelog: Tightened the skill around fragile review workflows, reference stability, and layout drift after a stricter external audit.
-metadata: {"clawdbot":{"emoji":"📘","os":["linux","darwin","win32"]}}
----
-
-## When to Use
-
-Use when the main artifact is a Microsoft Word document or `.docx` file, especially when tracked changes, comments, headers, numbering, fields, tables, templates, or compatibility matter.
-
-## Core Rules
-
-### 1. Treat DOCX as OOXML, not plain text
-
-- A `.docx` file is a ZIP of XML parts, so structure matters as much as visible text.
-- The critical parts are usually `word/document.xml`, `styles.xml`, `numbering.xml`, headers, footers, and relationship files.
-- Text may be split across multiple runs; never assume one word or sentence lives in one XML node.
-- Use different workflows on purpose: structured extraction for quick reading, style-driven generation for new files, and OOXML-aware editing for fragile existing documents.
-- If the job is mainly reading, extracting, or reviewing, prefer a structure-preserving read path before touching OOXML.
-- For deep edits, inspect the package layout instead of relying only on rendered output.
-- Reading, generating, and preserving an existing reviewed document are different jobs even when the format is the same.
-- Legacy `.doc` inputs usually need conversion before you can trust modern `.docx` assumptions.
-
-### 2. Preserve styles and direct formatting deliberately
-
-- Prefer named styles over direct formatting so the document stays editable.
-- Styles layer: paragraph styles, character styles, and direct formatting do not behave the same.
-- Removing direct formatting is often safer than stacking more inline formatting on top.
-- When editing an existing file, extend the current style system instead of inventing a parallel one.
-- Copying content between documents can silently import foreign styles, theme settings, and numbering definitions.
-
-### 3. Lists and numbering are their own system
-
-- Bullets and numbering belong to Word's numbering definitions, not pasted Unicode characters.
-- `abstractNum`, `num`, and paragraph numbering properties all matter, so restart behavior is rarely "visual only".
-- Indentation and numbering are related but not identical; a list can have broken numbering even if the indent looks right.
-- A list that looks correct in one editor can restart, flatten, or renumber itself later if the underlying numbering state is wrong.
-
-### 4. Page layout lives in sections
-
-- Margins, orientation, headers, footers, and page numbering are section-level behavior.
-- First-page and odd/even headers can differ inside the same document, so one header fix may not fix the document.
-- Set page size explicitly because A4 and US Letter defaults change pagination and table widths.
-- Use section breaks for layout changes; manual spacing and stray page breaks usually create drift.
-- Header and footer media use part-specific relationships, so copied IDs often break images or links.
-- Tables, page breaks, and headers often drift together, so treat layout fixes as document-wide, not local cosmetic edits.
-- Table geometry depends on page width, margins, and fixed widths, so "close enough" table edits often break later in Google Docs or LibreOffice.
-
-### 5. Track changes, comments, and fields need precise edits
-
-- Visible text is not the full document when tracked changes are enabled.
-- Insertions, deletions, and comments carry metadata that can survive careless edits.
-- Deleted text may still exist in the XML even when it no longer appears on screen.
-- Comment anchors and review ranges can break if edits move text without preserving the surrounding structure.
-- Comment markers and review wrappers do not behave like inline formatting, so moving text carelessly can orphan or misplace them.
-- Comments, footnotes, bookmarks, and linked media may live in separate parts, not only in the main document body.
-- Tables of contents, page numbers, dates, cross-references, and mail merge placeholders are fields.
-- Edit the field source carefully and expect cached display values to lag until refresh.
-- Hyperlinks, bookmarks, and references can break if IDs or relationships stop matching.
-- Bookmarks, footnotes, comment ranges, and cross-references depend on stable anchors even when the visible text seems untouched.
-- A document can look correct while still containing stale field output that refreshes later into something different.
-- For review workflows, make minimal replacements instead of rewriting whole paragraphs.
-- In tracked-change workflows, only the changed span should look changed; broad rewrites create noisy reviews and can destroy the original formatting context.
-- For legal, academic, or business review documents, default to review-style edits over wholesale paragraph rewrites unless the user explicitly wants a rewrite.
-
-### 6. Verify round-trip compatibility before delivery
-
-- Complex documents can shift between Word, LibreOffice, Google Docs, and conversion tools.
-- Tables, headers, embedded fonts, and copied styles are common sources of layout drift.
-- Treat `.docm` as macro-bearing and higher risk; treat `.doc` as legacy input that may need conversion first.
-- When layout matters, explicit table widths are safer than auto-fit or percentage-style behavior that different editors reinterpret.
-- A document that passes a text check can still fail on pagination, table widths, or reference refresh after the recipient opens it.
-
-## Common Traps
-
-- Copy-paste can import unwanted styles and numbering definitions.
-- Header or footer images use part-specific relationships, so reusing IDs blindly breaks them.
-- Empty paragraphs used as spacing make templates fragile; spacing belongs in paragraph settings.
-- A clean-looking export can still hide unresolved revisions, comments, or stale field values.
-- Restarting lists "by eye" usually fails because numbering state lives outside the paragraph text.
-- One visible phrase can be split across several runs, bookmarks, revision tags, or field boundaries.
-- Replacing a whole paragraph to change one clause often breaks review quality, bookmarks, comments, or nearby inline formatting.
-- Deleting all visible text from a paragraph or list item can still leave behind an empty paragraph mark, empty bullet, or unstable numbering.
-- Table auto-fit and percentage-like width behavior can look acceptable in Word and still drift in Google Docs or LibreOffice.
-- LibreOffice and Google Docs can shift complex tables, section behavior, and embedded fonts even when Word looks perfect.
-- Compatibility mode can silently cap newer features or change pagination behavior.
-- A single change in page size or margin defaults can ripple through tables, headers, TOC, and cross-references.
-- A revision workflow can look accepted on screen while leftover metadata, comments, or field caches still make the file unstable later.
-- TOC entries, footnotes, and cross-references can look correct until the recipient updates fields and exposes broken anchors.
-
-## Related Skills
-Install with `clawhub install <slug>` if user confirms:
-- `documents` — General document handling and format conversion.
-- `brief` — Concise business writing and structured summaries.
-- `article` — Long-form drafting and editorial structure.
-
-## Feedback
-
-- If useful: `clawhub star word-docx`
-- Stay updated: `clawhub sync`
diff --git a/src/builtin/skills/word-docx/_meta.json b/src/builtin/skills/word-docx/_meta.json
deleted file mode 100644
index 7ee94b7f..00000000
--- a/src/builtin/skills/word-docx/_meta.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "ownerId": "kn73vp5rarc3b14rc7wjcw8f8580t5d1",
- "slug": "word-docx",
- "version": "1.0.2",
- "publishedAt": 1773243096816
-}
\ No newline at end of file
diff --git a/src/core-agent/src/skills/loader.ts b/src/core-agent/src/skills/loader.ts
index 7d809371..9e930c8e 100644
--- a/src/core-agent/src/skills/loader.ts
+++ b/src/core-agent/src/skills/loader.ts
@@ -111,16 +111,13 @@ export class SkillLoader {
return null;
}
const { data } = parseFrontmatter(raw);
+ // `id` = dir basename (always unique within the loader's roots, used as the read_file
+ // path component). `name` = frontmatter human-readable display label; falls back to
+ // the id when frontmatter is missing one. Decoupled because marketplace installs land
+ // under `<server-id>/` (hex string) but should still surface their authored name to
+ // the LLM picker — see PC CLAUDE.md §6 and `skill-registry::renderSkillLines`.
const id = path.basename(dir);
- // Invariant: frontmatter `name` must equal the directory name (id).
- // The edit UI (`features/skills.ts::updateCustomSkill`) already renames
- // dir + rewrites frontmatter atomically, so divergence only happens
- // when a SKILL.md is hand-edited. Override silently here and log so
- // the drift surfaces in dev logs without breaking the load.
- const declaredName = data.name && data.name.trim();
- if (declaredName && declaredName !== id) {
- log.warn(`skill ${id}: frontmatter name "${declaredName}" differs from dir; using dir name`);
- }
+ const declaredName = (data.name && data.name.trim()) || id;
// Migrate legacy single-`description` into the matching language slot.
// Heuristic: if it contains any CJK ideograph it lands in `_zh`, else
// `_en`. Explicit `description_zh` / `description_en` always win, even
@@ -131,7 +128,7 @@ export class SkillLoader {
const legacyHasChinese = /[一-鿿]/.test(legacy);
return {
id,
- name: id,
+ name: declaredName,
description_zh: explicitZh || (legacy && legacyHasChinese ? legacy : ""),
description_en: explicitEn || (legacy && !legacyHasChinese ? legacy : ""),
dir,
diff --git a/src/main/features/agents.ts b/src/main/features/agents.ts
index e7adcaf2..d75b5ac5 100644
--- a/src/main/features/agents.ts
+++ b/src/main/features/agents.ts
@@ -20,10 +20,9 @@ import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
import {
- BUILTIN_AGENTS_DIR, BUILTIN_AGENTS_SOURCE, BUILTIN_SKILLS_DIR,
userAgentsDir, userSkillsDir, userAgentChatDir, userSessionFile, WS_ROOT,
agentDir, agentDefinitionFile,
- builtinAgentDir, builtinAgentDefinitionFile,
+ userMarketplaceAgentsDir, userMarketplaceAgentDir, userMarketplaceSkillsDir,
} from '../paths';
import { evictSession } from '../model/core-agent/session-store';
import { getActiveUserId } from './users';
@@ -129,6 +128,10 @@ export interface Agent {
* via the dedicated `chat_agent_setup_cli.md` prompt; the LLM
* doesn't author it directly. */
runtime?: AgentRuntime;
+ /** Marketplace category code (`education` / `ecommerce` / `rnd` / `writing` / `data` /
+ * `general`). Empty string when uncategorized; required only when publishing to the
+ * marketplace. Maintained via the create / edit dialog dropdown, NOT by the agent-edit LLM. */
+ category: string;
source: AgentSource;
created_at: string;
updated_at: string;
@@ -137,6 +140,15 @@ export interface Agent {
* unless the user has explicitly disabled the agent. Don't write this
* field back to disk. */
enabled: boolean;
+ /** Author uid for `source==='builtin'` (marketplace-installed) agents — read from the
+ * install dir's `_install.json`. `"0"` = "官方制作"; non-zero = community uploader. Empty
+ * string for `source==='custom'` (no marketplace install meta). Renderer uses this to show
+ * the "官方/作者" badge instead of a "内置" chip on the detail / card. */
+ create_uid?: string;
+ /** Marketplace install version for `source==='builtin'`. Read from `_install.json` so the
+ * agents-tab card can render a `v1.0.0` chip alongside the category. Custom agents leave
+ * this undefined (version is a publish concept, not authored locally). */
+ version?: string;
}
interface AgentRaw {
@@ -154,6 +166,7 @@ interface AgentRaw {
color?: unknown;
interactive?: unknown;
runtime?: unknown;
+ category?: unknown;
}
/** Per-agent execution backend. See `Agent.runtime`. */
@@ -184,98 +197,30 @@ 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
- * runtime artifacts like `meta/` or `skills/` if they ever land here — they
- * shouldn't, builtin is spec-only). */
-export function hashTree(root: string): string {
- if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return '';
- const h = crypto.createHash('sha256');
- const entries = fs.readdirSync(root, { withFileTypes: true })
- .filter((e) => e.isDirectory() && !e.name.startsWith('.'))
- .sort((a, b) => a.name.localeCompare(b.name));
- for (const e of entries) {
- 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]));
- try { h.update(fs.readFileSync(specFile)); } catch { /* skip */ }
- h.update(Buffer.from([0x0a]));
- }
- return h.digest('hex');
-}
-
-export function syncBuiltinAgents(): boolean {
- fs.mkdirSync(BUILTIN_AGENTS_DIR, { recursive: true });
- if (!fs.existsSync(BUILTIN_AGENTS_SOURCE)) {
- log.info(`source dir missing: ${BUILTIN_AGENTS_SOURCE}; skipping`);
- return false;
- }
- const srcHash = hashTree(BUILTIN_AGENTS_SOURCE);
- const dstHash = hashTree(BUILTIN_AGENTS_DIR);
- if (srcHash === dstHash) return false;
-
- const listAgentDirs = (root: string): Set<string> => new Set(
- fs.readdirSync(root, { withFileTypes: true })
- .filter((e) => e.isDirectory()
- && !e.name.startsWith('.')
- && 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);
- const dstIds = listAgentDirs(BUILTIN_AGENTS_DIR);
-
- let changed = false;
- for (const stale of [...dstIds].filter((id) => !srcIds.has(id)).sort()) {
- try {
- fs.rmSync(builtinAgentDir(stale), { recursive: true, force: true });
- log.info(`removed stale builtin agent ${stale}`);
- changed = true;
- } catch (err) {
- log.warn(`rm ${stale} failed: ${(err as Error).message}`);
- }
- }
- 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 {
- const srcBuf = fs.readFileSync(src);
- const dstBuf = fs.existsSync(dst) ? fs.readFileSync(dst) : null;
- if (!dstBuf || !srcBuf.equals(dstBuf)) {
- fs.mkdirSync(path.dirname(dst), { recursive: true });
- fs.writeFileSync(dst, srcBuf);
- log.info(`synced builtin agent ${id}`);
- changed = true;
- }
- } catch (err) {
- log.warn(`copy ${id} failed: ${(err as Error).message}`);
- }
- }
- return changed;
-}
+// `syncBuiltinAgents` / `hashTree` / `_isMarketplaceInstalled` removed — there is no longer a
+// shipped-builtin tree to sync from (`PC/src/builtin/` is gone) or a sentinel to protect (the
+// install flow now writes to `<uid>/local/marketplace/agents/` directly, distinct from the
+// scrubbed builtin path that no longer exists). Source='builtin' still names the UI group
+// ("Platform"); on disk it resolves to `userMarketplaceAgentsDir(uid)`.
// ─────────────────────────────────────────────────────────────────────────
// 2. Read / list
// ─────────────────────────────────────────────────────────────────────────
+/** Resolve where a given source's agents live on disk. Source='builtin' is a legacy name
+ * preserved across the codebase; it now points at the per-user marketplace install dir. */
function agentBaseDir(source: AgentSource): string {
- return source === 'builtin' ? BUILTIN_AGENTS_DIR : CUSTOM_AGENTS_DIR();
+ const uid = getActiveUserId();
+ return source === 'builtin' ? userMarketplaceAgentsDir(uid) : userAgentsDir(uid);
+}
+
+/** Helpers replacing the removed `builtinAgentDir` / `builtinAgentDefinitionFile`.
+ * Same shape but per-user (marketplace installs are per-user, not per-machine). */
+function _platformAgentDir(agentId: string): string {
+ return userMarketplaceAgentDir(getActiveUserId(), agentId);
+}
+function _platformAgentSpecFile(agentId: string): string {
+ return path.join(_platformAgentDir(agentId), 'agent.json');
}
const INPUT_ID_RE = /^[a-z_][a-z0-9_]{0,31}$/;
@@ -501,6 +446,7 @@ export function normalizeAgent(raw: AgentRaw | null | undefined, source: AgentSo
description_zh: explicitZh || (legacyDesc && legacyHasChinese ? legacyDesc : ''),
description_en: explicitEn || (legacyDesc && !legacyHasChinese ? legacyDesc : ''),
workflow: typeof raw.workflow === 'string' ? raw.workflow : '',
+ category: typeof raw.category === 'string' ? raw.category : '',
source,
created_at: raw.created_at || '',
updated_at: raw.updated_at || '',
@@ -595,7 +541,7 @@ export function setAgentEnabledForActiveUser(agentId: string, enabled: boolean):
function _agentDirStamp(): string {
let stamp = '';
- for (const d of [CUSTOM_AGENTS_DIR(), BUILTIN_AGENTS_DIR]) {
+ for (const d of [CUSTOM_AGENTS_DIR(), userMarketplaceAgentsDir(getActiveUserId())]) {
try { stamp += `${d}:${fs.statSync(d).mtimeMs};`; }
catch { stamp += `${d}:0;`; }
}
@@ -610,7 +556,7 @@ export async function listAgents(): Promise<Agent[]> {
} else {
specs = [];
const seen = new Set<string>();
- const sources: Array<[AgentSource, string]> = [['custom', CUSTOM_AGENTS_DIR()], ['builtin', BUILTIN_AGENTS_DIR]];
+ const sources: Array<[AgentSource, string]> = [['custom', CUSTOM_AGENTS_DIR()], ['builtin', userMarketplaceAgentsDir(getActiveUserId())]];
for (const [source, dir] of sources) {
if (!fs.existsSync(dir)) continue;
const entries = (await fsp.readdir(dir, { withFileTypes: true }))
@@ -630,6 +576,19 @@ export async function listAgents(): Promise<Agent[]> {
continue;
}
seen.add(norm.agent_id);
+ // Marketplace-installed agents carry an `_install.json` sidecar with `create_uid` +
+ // `version`. Read it lazily here so the UI can show "官方/作者" badges and the version
+ // chip without an extra IPC round-trip. Custom agents skip — they have no install meta.
+ if (source === 'builtin') {
+ try {
+ const metaFile = path.join(dir, e.name, '_install.json');
+ if (fs.existsSync(metaFile)) {
+ const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8'));
+ if (meta && typeof meta.create_uid === 'string') norm.create_uid = meta.create_uid;
+ if (meta && typeof meta.version === 'string') norm.version = meta.version;
+ }
+ } catch { /* corrupt _install.json → leave fields undefined */ }
+ }
specs.push(norm);
}
}
@@ -650,7 +609,7 @@ export async function getAgent(agentId: string | null | undefined): Promise<Agen
if (!agentId) return null;
for (const source of ['custom', 'builtin'] as AgentSource[]) {
const f = source === 'builtin'
- ? builtinAgentDefinitionFile(agentId)
+ ? _platformAgentSpecFile(agentId)
: agentDefinitionFile(getActiveUserId(), agentId);
if (!fs.existsSync(f)) continue;
try {
@@ -670,8 +629,8 @@ export async function getAgent(agentId: string | null | undefined): Promise<Agen
// 3. Custom CRUD
// ─────────────────────────────────────────────────────────────────────────
-/** spec.json path for the active user's custom agent. Builtin agents go
- * through `builtinAgentDefinitionFile` directly. */
+/** spec.json path for the active user's custom agent. Platform agents go
+ * through `_platformAgentSpecFile` directly. */
function customAgentFile(agentId: string): string {
return agentDefinitionFile(getActiveUserId(), agentId);
}
@@ -691,6 +650,9 @@ export interface CreateAgentOptions {
/** Picked at create time from the modal's runtime selector. Stored as
* authored — `normalizeAgent` validates on read. */
runtime?: AgentRuntime;
+ /** Marketplace category code (e.g. `education`). Empty string / omitted = uncategorized;
+ * required only at marketplace publish time. */
+ category?: string;
}
/** Route a legacy `description` input into the matching language slot.
@@ -718,14 +680,14 @@ function resolveBilingualDescription(
* manual edit. Returns the created agent.
*/
export async function createCustomAgent(
- { name = '', description = '', description_zh, description_en, workflow = '', icon, color, interactive, runtime }: CreateAgentOptions = {},
+ { name = '', description = '', description_zh, description_en, workflow = '', icon, color, interactive, runtime, category }: CreateAgentOptions = {},
): Promise<Agent | null> {
assertAgentNameAllowed(name);
await assertAgentNameUnique(String(name || '').trim());
fs.mkdirSync(CUSTOM_AGENTS_DIR(), { recursive: true });
let agentId: string;
do { agentId = genAgentId(); }
- while (fs.existsSync(builtinAgentDefinitionFile(agentId))
+ while (fs.existsSync(_platformAgentSpecFile(agentId))
|| fs.existsSync(customAgentFile(agentId)));
// mkdir <aid>/ first so writeJson on agent.json has a parent.
fs.mkdirSync(agentDir(getActiveUserId(), agentId), { recursive: true });
@@ -739,6 +701,10 @@ export async function createCustomAgent(
created_at: nowIso(),
updated_at: nowIso(),
};
+ // Only emit `category` to disk when supplied; empty string is omitted so existing agents
+ // don't get spurious "category: ''" lines through resave.
+ const cleanCategory = typeof category === 'string' ? category.trim() : '';
+ if (cleanCategory) data.category = cleanCategory;
if (avatars.isKnownIcon(icon)) data.icon = icon;
if (avatars.isKnownColor(color)) data.color = color;
if (typeof interactive === 'boolean') data.interactive = interactive;
@@ -810,6 +776,9 @@ export interface UpdateAgentFields {
* omitted → untouched
* Authored by the create modal + edit UI, not the LLM edit prompt. */
runtime?: AgentRuntime | null;
+ /** Marketplace category code. Empty string drops the field; omitted = untouched.
+ * Authored by the create / edit dialog dropdown, NOT the agent-edit LLM. */
+ category?: string;
}
/**
@@ -938,6 +907,14 @@ export async function updateCustomAgent(
data.interactive = v;
}
}
+ // category: explicit empty-string drops the field; any non-empty string is stored as-is
+ // (no allow-list validation on this layer — caller / UI dropdown is the source of truth).
+ if (Object.prototype.hasOwnProperty.call(updates || {}, 'category')) {
+ const v = (updates as any).category;
+ const trimmed = typeof v === 'string' ? v.trim() : '';
+ if (!trimmed) delete (data as any).category;
+ else (data as any).category = trimmed;
+ }
if (Object.prototype.hasOwnProperty.call(updates || {}, 'runtime')) {
const v = updates.runtime;
// The runtime *kind* is locked at create time. Once an agent is
@@ -978,6 +955,46 @@ export async function updateCustomAgent(
if (!data.name) data.name = t('agent.default_name');
data.updated_at = nowIso();
await writeJson(f, data);
+}
+
+/** Edit-chat dispatcher: routes to custom write for custom agents, and to
+ * the dev-only built-in dual-write (src + data) for built-in agents in
+ * dev mode. Returns null if the id resolves to neither, or if a built-in
+ * write is attempted outside dev mode. */
+export async function updateAgentSpec(
+ agentId: string, updates: UpdateAgentFields,
+): Promise<Agent | null> {
+ if (!agentId) return null;
+ if (fs.existsSync(customAgentFile(agentId))) {
+ return updateCustomAgent(agentId, updates);
+ }
+ if (fs.existsSync(_platformAgentSpecFile(agentId)) && false) {
+ try {
+ const dev = await import('./agents_dev');
+ return await dev.updateBuiltinAgentSpec(agentId, updates);
+ } catch (err) {
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code !== 'MODULE_NOT_FOUND' && code !== 'ERR_MODULE_NOT_FOUND') {
+ log.warn(`agents_dev load failed: ${(err as Error).message}`);
+ }
+ return null;
+ }
+ }
+ return null;
+}
+
+/** True iff `agentId` resolves to a built-in spec (the runtime data tree).
+ * Mirrors `isBuiltinSkill`. */
+export function isBuiltinAgent(agentId: string): boolean {
+ if (!agentId) return false;
+ return fs.existsSync(_platformAgentSpecFile(agentId));
+}
+
+/** Internal: shared apply + cache invalidation for the dev module. */
+export async function _applyAgentUpdatesAndInvalidate(
+ data: AgentRaw, agentId: string, updates: UpdateAgentFields,
+): Promise<Agent | null> {
+ await _applyAgentUpdates(data, agentId, updates);
_invalidateAgentListCache();
log.info(`updated id=${agentId}`);
// Propagate a name change into every conversation roster that already
@@ -1344,7 +1361,7 @@ export async function sendToAgentEditChat(userId: string, agentId: string, conte
const result = await chatWithModel({
userId, message: content, sessionId, systemPrompt,
agentName: 'orkas_chat', timeout: 300,
- readOnlyExtraRoots: [BUILTIN_SKILLS_DIR, userSkillsDir(userId)],
+ readOnlyExtraRoots: [userMarketplaceSkillsDir(userId), userSkillsDir(userId)],
});
if (!result.ok) {
@@ -1411,7 +1428,7 @@ export async function* streamSendToAgentEditChat(
userId, message: content, sessionId, systemPrompt,
agentName: 'orkas_chat',
cacheRetention: 'short',
- readOnlyExtraRoots: [BUILTIN_SKILLS_DIR, userSkillsDir(userId)],
+ readOnlyExtraRoots: [userMarketplaceSkillsDir(userId), userSkillsDir(userId)],
...(opts.abortSignal ? { abortSignal: opts.abortSignal } : {}),
}) as AsyncIterable<any>) {
const etype = event.type;
diff --git a/src/main/features/cache_clearable.ts b/src/main/features/cache_clearable.ts
new file mode 100644
index 00000000..a6f94a76
--- /dev/null
+++ b/src/main/features/cache_clearable.ts
@@ -0,0 +1,109 @@
+/**
+ * Clearable-cache umbrella.
+ *
+ * `<uid>/local/cache/<bucket>/` is the convention for caches the user is allowed to wipe via
+ * a "clear cache" UI button. Whatever drops into `cache/` is fair game — losing it just
+ * triggers a refetch / rebuild. Distinct from:
+ *
+ * - `local/config/` — user preferences (auth-profiles, permissions, …) ← NEVER clear
+ * - `local/biz/` — server-sourced reference data (marketplace categories, …) ← refresh-on-need
+ * - `local/search/` — derived indexes, but self-healing via reconcile ← currently outside this umbrella
+ *
+ * The renderer enumerates buckets via `listClearableBuckets()` (shows size + last_modified),
+ * then either targets a specific one via `clearBucket(name)` or hits the nuke button which
+ * loops every bucket via `clearAllClearable()`. The actual files/subdirs inside a bucket are
+ * the owning feature's business; this module only knows top-level dir names.
+ *
+ * Currently inhabited by:
+ * - `marketplace/` — marketplace content cache (features/marketplace_cache.ts)
+ *
+ * Future migration candidates (NOT yet moved — would need each owner to update its path
+ * helpers): `file_cache/` → `cache/file_cache/`, `tool-results/` → `cache/tool-results/`.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import { userLocalCacheDir } from '../paths';
+import { getActiveUserId } from './users';
+import { createLogger } from '../logger';
+
+const log = createLogger('cache_clearable');
+
+export interface ClearableBucket {
+ name: string;
+ bytes: number;
+ /** Newest mtime under the bucket, ms. 0 when bucket is empty / unreadable. */
+ last_modified: number;
+}
+
+/** Enumerate top-level subdirs of `<uid>/local/cache/`. Each is a bucket. Missing dir → []. */
+export async function listClearableBuckets(): Promise<ClearableBucket[]> {
+ const root = userLocalCacheDir(getActiveUserId());
+ if (!fs.existsSync(root)) return [];
+ const out: ClearableBucket[] = [];
+ for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
+ if (!entry.isDirectory()) continue;
+ if (entry.name.startsWith('.')) continue;
+ const dir = path.join(root, entry.name);
+ out.push({ name: entry.name, bytes: _dirSize(dir), last_modified: _newestMtime(dir) });
+ }
+ return out.sort((a, b) => a.name.localeCompare(b.name));
+}
+
+/** Wipe one bucket (`<uid>/local/cache/<name>/`). Returns bytes freed. No-op when missing. */
+export async function clearBucket(name: string): Promise<number> {
+ if (!name || name.includes('/') || name.includes('\\') || name === '..') {
+ throw new Error('invalid bucket name');
+ }
+ const dir = path.join(userLocalCacheDir(getActiveUserId()), name);
+ if (!fs.existsSync(dir)) return 0;
+ const bytes = _dirSize(dir);
+ try { await fsp.rm(dir, { recursive: true, force: true }); }
+ catch (err) { log.warn(`clearBucket ${name} failed: ${(err as Error).message}`); return 0; }
+ log.info(`cleared bucket=${name} freed=${(bytes / 1024 / 1024).toFixed(1)} MB`);
+ return bytes;
+}
+
+/** Wipe every bucket under `<uid>/local/cache/`. Returns total bytes freed. Safe on empty
+ * cache root. UI hook for the "clear all cache" button. */
+export async function clearAllClearable(): Promise<number> {
+ const buckets = await listClearableBuckets();
+ let total = 0;
+ for (const b of buckets) total += await clearBucket(b.name);
+ return total;
+}
+
+function _dirSize(dir: string): number {
+ let total = 0;
+ try {
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, e.name);
+ if (e.isDirectory()) total += _dirSize(full);
+ else if (e.isFile()) {
+ try { total += fs.statSync(full).size; } catch { /* ignore */ }
+ }
+ }
+ } catch { /* ignore */ }
+ return total;
+}
+
+function _newestMtime(dir: string): number {
+ let newest = 0;
+ try {
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, e.name);
+ try {
+ const stat = fs.statSync(full);
+ if (e.isDirectory()) {
+ const sub = _newestMtime(full);
+ if (sub > newest) newest = sub;
+ } else {
+ if (stat.mtimeMs > newest) newest = stat.mtimeMs;
+ }
+ } catch { /* ignore */ }
+ }
+ } catch { /* ignore */ }
+ return newest;
+}
diff --git a/src/main/features/group_chat/bus.ts b/src/main/features/group_chat/bus.ts
index 946fad45..c8e7c79c 100644
--- a/src/main/features/group_chat/bus.ts
+++ b/src/main/features/group_chat/bus.ts
@@ -44,7 +44,10 @@ import {
PlanSetInput, StepStatus, PlanFile,
} from './plan';
import * as planExecutor from './plan_executor';
-import { userChatsDir, BUILTIN_SKILLS_DIR, userSkillsDir, BUILTIN_AGENTS_DIR, userAgentsDir } from '../../paths';
+import {
+ userChatsDir, userSkillsDir, userAgentsDir,
+ userMarketplaceSkillsDir, userMarketplaceAgentsDir,
+} from '../../paths';
import * as agentsFeat from '../agents';
import { isAgentEnabled } from '../component_enabled';
import { buildLanguageDirective, t } from '../../i18n';
@@ -987,8 +990,8 @@ async function runTurn(state: CidState, w: WorkerState, item: QueueItem): Promis
// chip, so the sandbox-level lock keeps the LLM honest even if the
// prompt strays. Builtin first to match the prompt's "locate by
// source" guidance.
- const skillRoots = [BUILTIN_SKILLS_DIR, userSkillsDir(uid)];
- const agentRoots = [BUILTIN_AGENTS_DIR, userAgentsDir(uid)];
+ const skillRoots = [userMarketplaceSkillsDir(uid), userSkillsDir(uid)];
+ const agentRoots = [userMarketplaceAgentsDir(uid), userAgentsDir(uid)];
if (cliAgent) {
// CLI-backed agent path: spawn the local CLI in the user's workspace
// and forward its events as `process` events so the same UI rail
@@ -1605,7 +1608,7 @@ async function buildAgentsIndexBlock(uid: string, allowedIds?: readonly string[]
const { pickDescription } = await import('#core-agent');
const lang = getCurrentLang();
const customRoot = path.resolve(userAgentsDir(uid));
- const builtinRoot = path.resolve(BUILTIN_AGENTS_DIR);
+ const builtinRoot = path.resolve(userMarketplaceAgentsDir(uid));
const header = [
'`read_file(<ROOT>/<id>/agent.json)` — ROOT by Source:',
`- custom: ${customRoot}`,
diff --git a/src/main/features/marketplace.ts b/src/main/features/marketplace.ts
index 848da0c6..1ebffe7d 100644
--- a/src/main/features/marketplace.ts
+++ b/src/main/features/marketplace.ts
@@ -1,44 +1,89 @@
/**
* 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/`).
+ * Three-layer storage model:
*
- * 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.
+ * 1. **Server** owns the catalog (marketplace_agents / marketplace_skills tables) and the
+ * blob URLs (agent.json on COS, skill bundle .zip on COS).
+ * 2. **Cloud-synced install manifest** (`<uid>/cloud/marketplace/installs.json`) — the only
+ * multi-device state. Records what the user has installed: id / version / published_at /
+ * COS URL / installed_at. See `marketplace_installs.ts`.
+ * 3. **Per-machine install target** (`<uid>/local/marketplace/{agents,skills}/<id>/`) — the
+ * actual content. Reconciled from (2) on startup by `marketplace_reconcile.ts`: any entry
+ * in the manifest without local content gets fetched in parallel. Listed alongside
+ * `cloud/{agents,skills}/` by `features/{agents,skills}.ts::list*` under the "Platform" group.
*
- * 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`.
+ * Detail-page cache (`<uid>/local/cache/marketplace/{agents,skills}/<id>/`) is independent —
+ * it's a working copy for the detail viewer, populated whenever the user views an item, and
+ * subject to LRU sweep. Install copies cache→install-target to materialize.
+ *
+ * Install flow: cache-first. `installMarketplaceAgent/Skill` ensures cache hot via the same
+ * fetch+cache path the detail page uses, copies cache → `<uid>/local/marketplace/<kind>/<id>/`,
+ * then records the entry in the cloud manifest.
+ *
+ * **Skill bundle = real zip.** Earlier revisions used a JSON envelope `{files:[...]}` (no zip
+ * dep needed); switched to adm-zip to avoid base64 expansion on binary files + get deflate
+ * compression on text. PC/CLAUDE.md §1 allow-list updated accordingly.
+ *
+ * **Agent install installs skill_list dependencies FIRST, then the agent body.** When agent.json
+ * declares `skill_list: [sid1, sid2, ...]` (three-state: undefined = no filter, [] = zero,
+ * non-empty = strict subset), the install runs every missing sid in parallel BEFORE writing the
+ * agent's own files / manifest entry. If ANY skill install throws, the whole agent install fails;
+ * the agent never gets recorded. **Why:** prevents "agent installed but its skills are missing"
+ * inconsistency that would survive across devices via the cloud manifest. Previously-installed
+ * skills from a partial retry are no-ops (`_skillAlreadyOnDisk` check), so retry-on-failure is
+ * cheap. The user just re-clicks Install.
+ *
+ * Upload + delete (publishing custom items to the Server) are dev-only and live in
+ * `marketplace_dev.ts` — excluded from packaged builds via `package.json::build.files`.
*/
-import { app } from 'electron';
+import AdmZip from 'adm-zip';
+import * as fs from 'node:fs';
import * as fsp from 'node:fs/promises';
import * as path from 'node:path';
import {
- BUILTIN_SKILLS_DIR,
- builtinAgentDir, builtinAgentDefinitionFile,
+ userSkillsDir,
+ userMarketplaceAgentDir, userMarketplaceSkillDir,
+ marketplaceCacheAgentDir, marketplaceCacheSkillDir,
+ userMarketplaceInstallsFile, marketplaceDefaultsSeededFile,
+ userMarketplaceDirCloud,
} from '../paths';
+import { getActiveUserId } from './users';
import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-agent/skill-registry';
+import {
+ getSkillCacheDir, isCacheFresh, readAgentCache, touchCacheEntry,
+ writeAgentCache, writeSkillCache,
+} from './marketplace_cache';
+import {
+ addAgentInstall, addSkillInstall, removeAgentInstall, removeSkillInstall,
+ readInstalls, writeInstalls,
+} from './marketplace_installs';
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';
+// Profile-driven (mirrors Server `env/start/{dev_,}api_start.sh` — see PC/CLAUDE.md §1 +
+// Server CLAUDE.md §7): `ORKAS_PROFILE=global` (default) routes to overseas (`orkas.ai`),
+// `ORKAS_PROFILE=cn` routes to China (`orkas.work`). `run.sh` exports the env from its
+// positional arg (`./run.sh cn`). Devs running against a local Server can still override
+// the entire base via `ORKAS_API_BASE_URL=http://127.0.0.1:8888/api ./run.sh`.
+//
+// **No build-mode branch on purpose** — OrkasOpen contract (per
+// `OpenSource/SyncCode/strip-rules.json`) bans build-mode checks outside the two
+// whitelisted infra files, and "dev vs packaged behavior must be identical". Profile +
+// env override are the explicit knobs.
+const PROFILE_BASES: Record<string, string> = {
+ global: 'https://www.orkas.ai/api',
+ cn: 'https://www.orkas.work/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;
+ const profile = process.env.ORKAS_PROFILE || 'global';
+ return PROFILE_BASES[profile] || PROFILE_BASES.global;
}
// ── envelope ──────────────────────────────────────────────────────────────
@@ -62,7 +107,6 @@ export interface MarketplaceCategory {
code: string;
name_zh: string;
name_en: string;
- kind: 'agent' | 'skill' | 'both';
sort_order: number;
}
@@ -75,7 +119,12 @@ export interface MarketplaceAgent {
icon: string;
color: string;
version: string;
+ /** Author uid. `"0"` is the "官方制作 / Platform" marker; everything else is a community
+ * uploader. Dedup is on (name, create_uid), so same name from different authors yields
+ * distinct rows — the UI shows the author badge so users can tell them apart. */
+ create_uid: string;
download_count: number;
+ published_at: number;
updated_at: number;
}
@@ -86,26 +135,43 @@ export interface MarketplaceSkill {
description_en: string;
category: string;
version: string;
+ create_uid: string;
download_count: number;
+ published_at: number;
updated_at: number;
}
-export interface MarketplaceSentinel {
- server_id: string;
+export interface AgentDetail {
+ id: string;
version: string;
category: string;
- installed_at: number;
+ published_at: number;
+ /** Full agent.json content (already merged from cache or freshly fetched). */
+ agent_json: Record<string, unknown>;
+ /** COS URL of the agent.json blob — recorded in installs.json so reconcile on other
+ * devices can fetch directly. May be empty on a cache-hit code path; install resolves
+ * via the detail endpoint when missing. */
+ agent_json_url: string;
+ /** Author uid from the server row. Recorded in `_install.json` so the in-app detail can
+ * render an "官方/作者" badge without a marketplace round-trip. May be `''` on cache-hit. */
+ create_uid: string;
}
-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 interface SkillDetail {
+ id: string;
+ version: string;
+ category: string;
+ published_at: number;
+ /** Local filesystem path to the cache directory (caller can walk it to render the file tree
+ * + read SKILL.md). The cache may also be wiped between calls — re-fetch via this function. */
+ cache_dir: string;
+ /** COS URL of the skill bundle zip — recorded in installs.json for reconcile. */
+ bundle_url: string;
+ /** Same as `AgentDetail.create_uid`. */
+ create_uid: string;
}
+// ── listing ───────────────────────────────────────────────────────────────
export async function listMarketplaceAgents(
opts: { category?: string; q?: string; page?: number; size?: number } = {},
): Promise<{ list: MarketplaceAgent[]; total: number }> {
@@ -128,69 +194,391 @@ export async function listMarketplaceSkills(
});
}
-// ── install ───────────────────────────────────────────────────────────────
-export async function installMarketplaceAgent(agentId: string): Promise<{ ok: true; id: string }> {
+// ── detail (cache-aware) ──────────────────────────────────────────────────
+// Detail-page entry. Caller provides the list-row's freshness pair so we can short-circuit
+// when cache is hot; we still fetch + repopulate cache on miss / stale.
+export async function getAgentDetail(
+ agentId: string, expect: { version: string; published_at: number },
+): Promise<AgentDetail> {
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 },
+ if (await isCacheFresh('agent', agentId, expect)) {
+ const cached = await readAgentCache(agentId);
+ if (cached) {
+ await touchCacheEntry('agent', agentId);
+ // Cache hit path: agent_json_url / create_uid are unknown (not stored in cache meta).
+ // Install path re-fetches via /detail to get them; detail render doesn't need them.
+ return { id: agentId, version: expect.version, category: '', published_at: expect.published_at, agent_json: cached, agent_json_url: '', create_uid: '' };
+ }
+ }
+ // Miss → fetch + repopulate.
+ const data = await postJson<{ agent_json: Record<string, unknown>; version: string; category: string; published_at: number; agent_json_url: string; create_uid: string }>(
+ '/marketplace/agents/detail', { 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 };
+ await writeAgentCache(agentId, data.agent_json, { version: data.version, published_at: data.published_at });
+ return { id: agentId, version: data.version, category: data.category, published_at: data.published_at, agent_json: data.agent_json, agent_json_url: data.agent_json_url || '', create_uid: data.create_uid || '' };
}
-export async function installMarketplaceSkill(skillId: string): Promise<{ ok: true; id: string }> {
+export async function getSkillDetail(
+ skillId: string, expect: { version: string; published_at: number },
+): Promise<SkillDetail> {
if (!skillId) throw new Error('skillId required');
- const meta = await postJson<{ bundle_url: string; version: string; category: string }>(
+ if (await isCacheFresh('skill', skillId, expect)) {
+ await touchCacheEntry('skill', skillId);
+ return { id: skillId, version: expect.version, category: '', published_at: expect.published_at, cache_dir: getSkillCacheDir(skillId), bundle_url: '', create_uid: '' };
+ }
+ // Miss → fetch + write.
+ const meta = await postJson<{ bundle_url: string; version: string; category: string; published_at: number; create_uid: string }>(
'/marketplace/skills/bundle', { id: skillId },
);
+ await _fetchAndCacheSkill(skillId, meta);
+ return { id: skillId, version: meta.version, category: meta.category, published_at: meta.published_at, cache_dir: getSkillCacheDir(skillId), bundle_url: meta.bundle_url, create_uid: meta.create_uid || '' };
+}
+/** Fetch a skill .zip from COS and extract into the local cache (idempotent: wipe-and-replace). */
+async function _fetchAndCacheSkill(
+ skillId: string, meta: { bundle_url: string; version: string; published_at: number },
+): Promise<void> {
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 ab = await res.arrayBuffer();
+ const zipBuf = Buffer.from(ab);
+ await writeSkillCache(skillId, async (dir) => {
+ extractBundleSafely(new AdmZip(zipBuf), dir);
+ }, { version: meta.version, published_at: meta.published_at });
+}
+
+// zip-bomb defense, mirrored at server (see `api/marketplace.py::_validate_skill_bundle`).
+// Server already enforces these caps on upload, but a corrupted COS blob or downgrade attack
+// could deliver a different payload to the client — re-check on the unpack side too.
+const MAX_BUNDLE_ENTRIES = 500;
+const MAX_BUNDLE_UNCOMPRESSED_BYTES = 64 * 1024 * 1024; // 64 MB
+
+/** Walk a zip, validate every entry's path + per-entry / total uncompressed size, then write
+ * out. Throws on any limit breach (caller wraps the write in a fresh dir so a thrown error
+ * doesn't leave a half-extracted state). Exported so `marketplace_reconcile.ts` reuses
+ * exactly the same caps. */
+export function extractBundleSafely(zip: AdmZip, dst: string): void {
+ const entries = zip.getEntries();
+ if (entries.length > MAX_BUNDLE_ENTRIES) {
+ throw new Error(`zip entry count ${entries.length} exceeds limit ${MAX_BUNDLE_ENTRIES}`);
+ }
+ let total = 0;
+ for (const entry of entries) {
+ if (entry.isDirectory) continue;
+ const safe = safeRelPath(entry.entryName);
+ if (!safe) { log.warn(`skip unsafe zip entry: ${entry.entryName}`); continue; }
+ // entry.header.size = uncompressed bytes (adm-zip per-entry field).
+ total += entry.header.size;
+ if (total > MAX_BUNDLE_UNCOMPRESSED_BYTES) {
+ throw new Error(`zip uncompressed total exceeds ${MAX_BUNDLE_UNCOMPRESSED_BYTES} bytes`);
+ }
+ const out = path.join(dst, safe);
+ fs.mkdirSync(path.dirname(out), { recursive: true });
+ fs.writeFileSync(out, entry.getData());
+ }
+}
+
+// ── install ───────────────────────────────────────────────────────────────
+export async function installMarketplaceAgent(
+ agentId: string, expect: { version: string; published_at: number },
+): Promise<{ ok: true; id: string }> {
+ if (!agentId) throw new Error('agentId required');
+ // Ensure cache is hot (and pick up agent_json_url for the manifest).
+ let detail = await getAgentDetail(agentId, expect);
+ if (!detail.agent_json_url) {
+ // Cache-hit path returns url='' (and create_uid=''); re-fetch via detail endpoint to
+ // capture both — needed for manifest + `_install.json` author badge.
+ const fresh = await postJson<{ agent_json: Record<string, unknown>; version: string; category: string; published_at: number; agent_json_url: string; create_uid: string }>(
+ '/marketplace/agents/detail', { id: agentId },
+ );
+ detail = {
+ id: agentId, version: fresh.version, category: fresh.category, published_at: fresh.published_at,
+ agent_json: fresh.agent_json, agent_json_url: fresh.agent_json_url || '',
+ create_uid: fresh.create_uid || '',
+ };
+ }
+
+ // 1. Install dependent skills FIRST, in parallel. Any failure throws — the agent body
+ // and manifest entry are never touched, so retry is a clean re-run (previously-installed
+ // skills short-circuit via `_skillAlreadyOnDisk`). This is the atomicity guarantee called
+ // out in the file header.
+ const skillList = Array.isArray((detail.agent_json as Record<string, unknown>).skill_list)
+ ? ((detail.agent_json as Record<string, unknown>).skill_list as unknown[]).filter((x): x is string => typeof x === 'string')
+ : [];
+ const missingSkillIds = skillList.filter((sid) => !_skillAlreadyOnDisk(sid));
+ if (missingSkillIds.length > 0) {
+ await Promise.all(missingSkillIds.map(async (sid) => {
+ // Direct hit on /skills/bundle for meta — avoids paging /skills/list (O(catalog) lookup
+ // that breaks once the catalog grows past 500 skills).
+ const meta = await postJson<{ bundle_url: string; version: string; category: string; published_at: number }>(
+ '/marketplace/skills/bundle', { id: sid },
+ );
+ await installMarketplaceSkill(sid, { version: meta.version, published_at: meta.published_at });
+ log.info(` dep-installed skill ${sid}`);
+ }));
+ }
+
+ // 2. Now materialize the agent: cache content → `<uid>/local/marketplace/agents/<id>/`.
+ // `_install.json` is a version pin read by `marketplace_reconcile.ts::_agentNeedsPull`
+ // on other devices to skip a re-pull when their local copy already matches the manifest's
+ // (version, published_at).
+ const target = userMarketplaceAgentDir(getActiveUserId(), agentId);
+ await fsp.mkdir(target, { recursive: true });
+ await fsp.writeFile(path.join(target, 'agent.json'), JSON.stringify(detail.agent_json, null, 2), 'utf8');
+ // `_install.json` stores everything the in-app UI needs without re-hitting the network:
+ // version/published_at for reconcile freshness; create_uid for the "官方/作者" badge on
+ // the agent detail page.
+ await fsp.writeFile(path.join(target, '_install.json'),
+ JSON.stringify({
+ version: detail.version,
+ published_at: detail.published_at,
+ create_uid: detail.create_uid || '',
+ }, null, 2), 'utf8');
+ await touchCacheEntry('agent', agentId);
+
+ // 3. Record in the cloud-synced manifest so other devices reconcile this install.
+ await addAgentInstall(getActiveUserId(), {
+ id: agentId, version: detail.version, published_at: detail.published_at,
+ agent_json_url: detail.agent_json_url, create_uid: detail.create_uid || '',
+ });
+ log.info(`installed marketplace agent ${agentId} v${detail.version} → ${target}`);
+
+ return { ok: true, id: agentId };
+}
+
+export async function installMarketplaceSkill(
+ skillId: string, expect: { version: string; published_at: number },
+): Promise<{ ok: true; id: string }> {
+ if (!skillId) throw new Error('skillId required');
+ let detail = await getSkillDetail(skillId, expect);
+ if (!detail.bundle_url) {
+ const fresh = await postJson<{ bundle_url: string; version: string; category: string; published_at: number; create_uid: string }>(
+ '/marketplace/skills/bundle', { id: skillId },
+ );
+ detail = { ...detail, bundle_url: fresh.bundle_url, create_uid: fresh.create_uid || '' };
+ }
+
+ const cacheDir = getSkillCacheDir(skillId);
+ const target = userMarketplaceSkillDir(getActiveUserId(), skillId);
+ await fsp.rm(target, { recursive: true, force: true });
+ await fsp.mkdir(target, { recursive: true });
+ await _copyDirSkippingCacheMeta(cacheDir, target);
+ await fsp.writeFile(path.join(target, '_install.json'),
+ JSON.stringify({
+ version: detail.version,
+ published_at: detail.published_at,
+ create_uid: detail.create_uid || '',
+ }, null, 2), 'utf8');
+ await touchCacheEntry('skill', skillId);
+ invalidateCoreAgentSkills();
+
+ await addSkillInstall(getActiveUserId(), {
+ id: skillId, version: detail.version, published_at: detail.published_at,
+ bundle_url: detail.bundle_url, create_uid: detail.create_uid || '',
+ });
+ log.info(`installed marketplace skill ${skillId} v${detail.version} → ${target}`);
+ return { ok: true, id: skillId };
+}
+
+/** Check if a skill is already present in any local source — either as a custom skill under
+ * `<uid>/cloud/skills/<id>/` OR a marketplace install under `<uid>/local/marketplace/skills/<id>/`.
+ * Both are valid; cascade install only triggers when missing. */
+function _skillAlreadyOnDisk(skillId: string): boolean {
+ try {
+ const customRoot = userSkillsDir(getActiveUserId());
+ if (fs.existsSync(path.join(customRoot, skillId, 'SKILL.md'))) return true;
+ const installedDir = userMarketplaceSkillDir(getActiveUserId(), skillId);
+ if (fs.existsSync(path.join(installedDir, 'SKILL.md'))) return true;
+ } catch { /* getActiveUserId throws when no active uid */ }
+ return false;
+}
+
+async function _copyDirSkippingCacheMeta(src: string, dst: string): Promise<void> {
+ const entries = await fsp.readdir(src, { withFileTypes: true });
+ for (const e of entries) {
+ if (e.name === '_cache.json') continue;
+ const s = path.join(src, e.name);
+ const d = path.join(dst, e.name);
+ if (e.isDirectory()) {
+ await fsp.mkdir(d, { recursive: true });
+ await _copyDirSkippingCacheMeta(s, d);
+ } else if (e.isFile()) {
+ await fsp.copyFile(s, d);
+ }
+ }
+}
+
+// ── default install seed (fresh launch) ───────────────────────────────────
+// Goal: on the very first launch a user sees a curated baseline of official agents / skills
+// without lifting a finger. The server `POST /marketplace/defaults` returns the recommended
+// set (rows with `default_install=1`); we add a manifest row per item and let the standard
+// `marketplace_reconcile` pass fetch the actual content at boot.
+//
+// **Why a separate marker (not manifest existence)**: manifest gets mutated row-by-row
+// during seed via `add*Install`. If the process crashes mid-loop, the manifest exists but is
+// incomplete — using it as the "already seeded" signal would skip seed forever, dropping
+// the remaining items. Instead we drop a marker file `.default-seeded.json` only AFTER every
+// row has been persisted. Failures (fetch / mid-loop crash / reconcile network error) leave
+// the marker absent → next launch retries; `add*Install` is upsert so previously-written
+// rows update in place. Once written, the marker is the permanent "don't pester" signal —
+// later uninstall of a default item does NOT cause it to reappear.
+export async function ensureDefaultInstalls(uid: string): Promise<{ seeded_agents: number; seeded_skills: number }> {
+ const markerFile = marketplaceDefaultsSeededFile(uid);
+ if (fs.existsSync(markerFile)) {
+ return { seeded_agents: 0, seeded_skills: 0 };
+ }
+ try {
+ const data = await postJson<{
+ agents: { id: string; version: string; published_at: number; agent_json_url: string; create_uid?: string }[];
+ skills: { id: string; version: string; published_at: number; bundle_url: string; create_uid?: string }[];
+ }>('/marketplace/defaults', {});
+ let seededAgents = 0;
+ let seededSkills = 0;
+ for (const a of data.agents || []) {
+ if (!a || !a.id) continue;
+ await addAgentInstall(uid, {
+ id: a.id, version: a.version || '1.0.0',
+ published_at: a.published_at || 0,
+ agent_json_url: a.agent_json_url || '',
+ create_uid: a.create_uid || '',
+ });
+ seededAgents++;
}
- 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');
+ for (const s of data.skills || []) {
+ if (!s || !s.id) continue;
+ await addSkillInstall(uid, {
+ id: s.id, version: s.version || '1.0.0',
+ published_at: s.published_at || 0,
+ bundle_url: s.bundle_url || '',
+ create_uid: s.create_uid || '',
+ });
+ seededSkills++;
}
+ // Marker is written LAST so any crash above leaves a partially-seeded manifest + no
+ // marker → next launch retries the whole loop, and add*Install upserts the rows that
+ // were already there. Failure here (rare disk issue) likewise → retry next launch.
+ await fsp.mkdir(userMarketplaceDirCloud(uid), { recursive: true });
+ await fsp.writeFile(markerFile, JSON.stringify({
+ seeded_at: Date.now(),
+ version: 1,
+ agent_ids: (data.agents || []).map((a) => a.id),
+ skill_ids: (data.skills || []).map((s) => s.id),
+ }, null, 2), 'utf8');
+ log.info(`seeded default installs: ${seededAgents} agent(s) + ${seededSkills} skill(s)`);
+ return { seeded_agents: seededAgents, seeded_skills: seededSkills };
+ } catch (err) {
+ // No marker written → next launch retries. Manifest may be partially populated; that's
+ // fine because `reconcileInstalls` will pick up the rows that are there and the next
+ // ensure pass will finish the rest.
+ log.warn(`default installs seed failed (will retry on next launch): ${(err as Error).message}`);
+ return { seeded_agents: 0, seeded_skills: 0 };
}
+}
+
+// ── one-time backfill for older install records ──────────────────────────
+// Earlier install paths (predating the create_uid + version persistence) wrote manifest
+// rows + `_install.json` files without those fields. The UI surfaces "官方/作者" badges +
+// version chip from `_install.json`, so older records render blank chips. Backfill is a
+// startup pass: for every manifest row missing `create_uid`, look it up in the catalog and
+// rewrite both the manifest entry and the per-machine `_install.json`. Idempotent — once
+// every row is populated, the function short-circuits with no network call.
+//
+// We use the catalog `/list` endpoint (cheap, no side-effects) instead of `/detail` (which
+// increments download_count). The first page (size=100) covers current scale; pagination can
+// be added when the published catalog exceeds that.
+export async function backfillMarketplaceCreateUid(uid: string): Promise<void> {
+ let manifest;
+ try { manifest = await readInstalls(uid); } catch { return; }
+ const agentMissing = manifest.agents.filter((a) => !a.create_uid);
+ const skillMissing = manifest.skills.filter((s) => !s.create_uid);
+ if (!agentMissing.length && !skillMissing.length) return;
- await writeSentinel(dir, skillId, meta.version, meta.category);
+ // Build (id → create_uid) maps by pulling the catalog list (paginated up to 200 rows total).
+ const agentMap = agentMissing.length ? await _fetchCreateUidMap('agents') : new Map<string, string>();
+ const skillMap = skillMissing.length ? await _fetchCreateUidMap('skills') : new Map<string, string>();
+
+ let touched = false;
+ for (const a of agentMissing) {
+ const cuid = agentMap.get(a.id);
+ if (cuid === undefined) continue;
+ a.create_uid = cuid;
+ await _patchInstallMeta(userMarketplaceAgentDir(uid, a.id), { create_uid: cuid, version: a.version });
+ touched = true;
+ }
+ for (const s of skillMissing) {
+ const cuid = skillMap.get(s.id);
+ if (cuid === undefined) continue;
+ s.create_uid = cuid;
+ await _patchInstallMeta(userMarketplaceSkillDir(uid, s.id), { create_uid: cuid, version: s.version });
+ touched = true;
+ }
+ if (touched) {
+ await writeInstalls(uid, manifest);
+ log.info(`backfilled create_uid: ${agentMissing.length} agent(s) + ${skillMissing.length} skill(s)`);
+ }
+}
+
+async function _fetchCreateUidMap(kind: 'agents' | 'skills'): Promise<Map<string, string>> {
+ const out = new Map<string, string>();
+ try {
+ // Two pages of 100 = 200 rows; sufficient for current marketplace size.
+ for (let page = 1; page <= 2; page++) {
+ const r = await postJson<{ list: Array<{ id: string; create_uid?: string }>; total: number }>(
+ `/marketplace/${kind}/list`, { page, size: 100 },
+ );
+ for (const row of r.list || []) {
+ if (row && typeof row.id === 'string') out.set(row.id, row.create_uid || '');
+ }
+ if ((r.list || []).length < 100) break;
+ }
+ } catch (err) {
+ log.warn(`backfill ${kind} catalog fetch failed: ${(err as Error).message}`);
+ }
+ return out;
+}
+
+async function _patchInstallMeta(dir: string, patch: { create_uid: string; version: string }): Promise<void> {
+ const f = path.join(dir, '_install.json');
+ if (!fs.existsSync(f)) return;
+ try {
+ const j = JSON.parse(await fsp.readFile(f, 'utf8'));
+ j.create_uid = patch.create_uid;
+ if (!j.version) j.version = patch.version;
+ await fsp.writeFile(f, JSON.stringify(j, null, 2), 'utf8');
+ } catch { /* corrupt _install.json — skip; reconcile will rewrite on next version bump */ }
+}
+
+// ── uninstall (user-facing; non-dev) ──────────────────────────────────────
+// Removes the per-machine install copy + manifest entry. **Does NOT touch the server row**
+// (different from `marketplace_dev.deleteMarketplace*` which wipes COS + DB). After this runs:
+// - listAgents / listSkills stops including this id under the "Platform" group
+// - cloud sync propagates the missing manifest entry to other devices, where startup
+// `marketplace_reconcile` notices nothing to pull and the install disappears there too
+// - the marketplace catalog still lists the item; the user can re-install at any time
+// Dependent skills (for an agent) are **not** cascade-uninstalled — other agents may share them.
+
+export async function uninstallMarketplaceAgent(agentId: string): Promise<{ ok: true; id: string }> {
+ if (!agentId) throw new Error('agentId required');
+ const uid = getActiveUserId();
+ await fsp.rm(userMarketplaceAgentDir(uid, agentId), { recursive: true, force: true });
+ await fsp.rm(marketplaceCacheAgentDir(uid, agentId), { recursive: true, force: true });
+ await removeAgentInstall(uid, agentId);
+ log.info(`uninstalled marketplace agent ${agentId} (local + cache + manifest)`);
+ return { ok: true, id: agentId };
+}
+
+export async function uninstallMarketplaceSkill(skillId: string): Promise<{ ok: true; id: string }> {
+ if (!skillId) throw new Error('skillId required');
+ const uid = getActiveUserId();
+ await fsp.rm(userMarketplaceSkillDir(uid, skillId), { recursive: true, force: true });
+ await fsp.rm(marketplaceCacheSkillDir(uid, skillId), { recursive: true, force: true });
+ await removeSkillInstall(uid, skillId);
invalidateCoreAgentSkills();
- log.info(`installed marketplace skill ${skillId} v${meta.version} → ${dir} (${env.files.length} files)`);
+ log.info(`uninstalled marketplace skill ${skillId} (local + cache + manifest)`);
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
@@ -199,8 +587,11 @@ export async function writeSentinel(dir: string, serverId: string, version: stri
export function safeRelPath(rel: string): string | null {
if (!rel || typeof rel !== 'string') return null;
if (path.isAbsolute(rel)) return null;
+ // `path.posix.normalize` collapses any internal `a/../b` to `b`, so `/../` literally cannot
+ // survive normalization — only a leading `..` (escape attempt) or pure-dot / empty paths
+ // remain to be rejected.
const norm = path.posix.normalize(rel.replace(/\\/g, '/'));
- if (norm.startsWith('..') || norm.includes('/../') || norm === '.' || norm === '') return null;
+ if (norm.startsWith('..') || norm === '.' || norm === '') return null;
if (norm.startsWith('/')) return null;
return norm;
}
diff --git a/src/main/features/marketplace_biz.ts b/src/main/features/marketplace_biz.ts
new file mode 100644
index 00000000..8b9b1566
--- /dev/null
+++ b/src/main/features/marketplace_biz.ts
@@ -0,0 +1,157 @@
+/**
+ * Marketplace business-data: category registry mirror.
+ *
+ * The server owns the authoritative `marketplace_categories` table; PC mirrors it locally with
+ * a 24h TTL so create-agent / create-skill dialogs (and the marketplace browse page) have an
+ * answer even when offline / on cold start. Per PC/CLAUDE.md §4:
+ *
+ * <uid>/local/biz/marketplace.json ← THIS module
+ *
+ * Distinct from `local/cache/` (user-clearable) and `local/config/` (user preferences) — biz
+ * data is server-sourced reference content; losing it just triggers a refetch. Lazy refresh
+ * only: callers go through `getMarketplaceCategories()` and we transparently refetch when the
+ * persisted copy is older than the TTL, falling back to (a) the stale cache, then (b) a
+ * hard-coded default list, so the dropdown is never empty.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import { marketplaceBizFile, userLocalBizDir } from '../paths';
+import { getActiveUserId } from './users';
+import { apiBase } from './marketplace';
+import { createLogger } from '../logger';
+
+const log = createLogger('marketplace_biz');
+
+const TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
+
+// In-memory mirror of `marketplace.json::categories`. Populated on first read from disk; refreshed
+// on every successful server fetch. Skips the fs + JSON.parse round-trip when the IPC handler is
+// called rapidly (renderer can hit `getMarketplaceCategories` every time it opens the marketplace
+// panel; without this we'd re-read the file each time even though TTL is 24h).
+let _memCache: { fetched_at: number; list: MarketplaceCategory[] } | null = null;
+let _memCacheUid: string | null = null; // invalidated on uid switch
+
+export interface MarketplaceCategory {
+ code: string;
+ name_zh: string;
+ name_en: string;
+ /** Display order — lower first. Kept on the wire purely for client-side rendering. */
+ sort_order: number;
+}
+
+/** Hard-coded fallback used only when both the persisted cache and the server are unreachable
+ * on a cold start. Mirrors the server `SEED_CATEGORIES` so the UI behaves identically when
+ * the network blip clears. Keep in sync with `Server/biz/marketplace/marketplace_mgr.py`. */
+const FALLBACK_CATEGORIES: readonly MarketplaceCategory[] = [
+ { code: 'education', name_zh: '教育', name_en: 'Education', sort_order: 10 },
+ { code: 'ecommerce', name_zh: '电商', name_en: 'E-commerce', sort_order: 20 },
+ { code: 'rnd', name_zh: '产研', name_en: 'R&D', sort_order: 30 },
+ { code: 'writing', name_zh: '写作', name_en: 'Writing', sort_order: 40 },
+ { code: 'data', name_zh: '数据', name_en: 'Data', sort_order: 50 },
+ { code: 'general', name_zh: '通用', name_en: 'General', sort_order: 60 },
+];
+
+interface PersistedBiz {
+ categories?: {
+ fetched_at: number;
+ list: MarketplaceCategory[];
+ };
+}
+
+async function _readPersisted(): Promise<PersistedBiz> {
+ const file = marketplaceBizFile(getActiveUserId());
+ if (!fs.existsSync(file)) return {};
+ try {
+ return JSON.parse(await fsp.readFile(file, 'utf8')) as PersistedBiz;
+ } catch (err) {
+ log.warn(`read ${file} failed: ${(err as Error).message}`);
+ return {};
+ }
+}
+
+async function _writePersisted(data: PersistedBiz): Promise<void> {
+ const dir = userLocalBizDir(getActiveUserId());
+ await fsp.mkdir(dir, { recursive: true });
+ const file = marketplaceBizFile(getActiveUserId());
+ await fsp.writeFile(file, JSON.stringify(data, null, 2), 'utf8');
+}
+
+async function _fetchFromServer(): Promise<MarketplaceCategory[]> {
+ const res = await fetch(`${apiBase()}/marketplace/categories`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({}),
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json() as { code: number; msg?: string; list?: unknown };
+ if (data.code !== 0) throw new Error(data.msg || `code=${data.code}`);
+ const list = Array.isArray(data.list) ? data.list : [];
+ // Normalize: keep only the fields PC needs; tolerate any drift on the server side.
+ return list
+ .filter((x): x is Record<string, unknown> => x !== null && typeof x === 'object')
+ .map((row) => ({
+ code: String(row.code || ''),
+ name_zh: String(row.name_zh || ''),
+ name_en: String(row.name_en || ''),
+ sort_order: typeof row.sort_order === 'number' ? row.sort_order : 0,
+ }))
+ .filter((c) => c.code);
+}
+
+/** Return the active category list. Reads from in-memory cache first, falls back to the
+ * persisted file, falls back to the server, falls back to the hard-coded default — so the UI
+ * always has a list to render. Sorted by sort_order ASC then code ASC for deterministic UI. */
+export async function getMarketplaceCategories(): Promise<MarketplaceCategory[]> {
+ const uid = getActiveUserId();
+ if (_memCacheUid !== uid) { _memCache = null; _memCacheUid = uid; } // uid switch invalidates
+ const now = Date.now();
+
+ // Fast path: in-memory hit within TTL.
+ if (_memCache && (now - _memCache.fetched_at) <= TTL_MS) {
+ return _sort(_memCache.list);
+ }
+
+ // Cold or expired — try persisted file first (cheap), then server.
+ const persisted = await _readPersisted();
+ const cached = persisted.categories;
+ if (cached && (now - cached.fetched_at) <= TTL_MS) {
+ _memCache = cached;
+ return _sort(cached.list);
+ }
+
+ try {
+ const fresh = await _fetchFromServer();
+ if (fresh.length > 0) {
+ const entry = { fetched_at: now, list: fresh };
+ _memCache = entry;
+ await _writePersisted({ ...persisted, categories: entry });
+ return _sort(fresh);
+ }
+ log.warn('server returned empty categories; keeping cached/fallback');
+ } catch (err) {
+ log.warn(`fetch categories failed: ${(err as Error).message}`);
+ }
+
+ if (cached && cached.list.length > 0) { _memCache = cached; return _sort(cached.list); }
+ const fallback = [...FALLBACK_CATEGORIES] as MarketplaceCategory[];
+ _memCache = { fetched_at: 0, list: fallback }; // fetched_at=0 so it expires immediately
+ return _sort(fallback);
+}
+
+/** Boot-time priming. Called from `main/index.ts` after user activation so the first
+ * `openMarketplace` IPC roundtrip finds the in-memory cache hot. Errors are swallowed —
+ * failure is recovered by the lazy path. */
+export async function primeCategoryCache(): Promise<void> {
+ try { await getMarketplaceCategories(); }
+ catch { /* swallowed — lazy fallback will recover */ }
+}
+
+function _sort(list: MarketplaceCategory[]): MarketplaceCategory[] {
+ return [...list].sort((a, b) => {
+ if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order;
+ return a.code.localeCompare(b.code);
+ });
+}
diff --git a/src/main/features/marketplace_cache.ts b/src/main/features/marketplace_cache.ts
new file mode 100644
index 00000000..7b6ab96c
--- /dev/null
+++ b/src/main/features/marketplace_cache.ts
@@ -0,0 +1,324 @@
+/**
+ * Marketplace content cache.
+ *
+ * Lives under `<uid>/local/cache/marketplace/{agents,skills}/<id>/` — the user-clearable cache
+ * umbrella defined in `paths.ts`. Two responsibilities:
+ *
+ * 1. Cache reads/writes for agent.json + skill bundles (PC fetches once into here, both detail
+ * page render and install copy from the cache).
+ * 2. `sweepIfNeeded()` — entry-time GC: when total cache > 100 MB OR any entry's
+ * `last_used_at` > 7d ago, evict expired then LRU-trim until size ≤ 80 MB.
+ *
+ * Cache hit rule (`isCacheFresh`): persisted `_cache.json` must carry `version` + `published_at`
+ * matching the server-list row for this id. Any mismatch (uploader pushed a new version) ⇒ miss,
+ * caller refetches. The install target lives separately at `<uid>/local/marketplace/{agents,
+ * skills}/<id>/` with its own `_install.json` version pin (read by `marketplace_reconcile.ts`).
+ * The cache is a strictly local staging area and may be cleared by the user without touching
+ * installs.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import {
+ marketplaceCacheAgentDir,
+ marketplaceCacheAgentsDir,
+ marketplaceCacheDir,
+ marketplaceCacheSkillDir,
+ marketplaceCacheSkillsDir,
+ marketplaceListingsCacheFile,
+} from '../paths';
+import { getActiveUserId } from './users';
+import { createLogger } from '../logger';
+
+const log = createLogger('marketplace_cache');
+
+// Sweep thresholds — both per PC/CLAUDE.md §4 marketplace-cache rule.
+const SWEEP_MAX_BYTES = 100 * 1024 * 1024; // 100 MB hard cap (triggers LRU eviction)
+const SWEEP_TARGET_BYTES = 80 * 1024 * 1024; // evict down to this after a sweep
+const SWEEP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days idle = expired
+
+export interface CacheMeta {
+ /** Server agent_id / skill_id this directory caches. */
+ server_id: string;
+ /** `marketplace_<kind>s.version` at fetch time — used for staleness check. */
+ version: string;
+ /** `marketplace_<kind>s.published_at` (ms) at fetch time — staleness check. */
+ published_at: number;
+ /** When the bytes landed on disk (ms). */
+ fetched_at: number;
+ /** Bumped on every detail-page read or install. Drives LRU eviction. */
+ last_used_at: number;
+}
+
+function _metaFile(dir: string): string { return path.join(dir, '_cache.json'); }
+
+async function _readMeta(dir: string): Promise<CacheMeta | null> {
+ const f = _metaFile(dir);
+ if (!fs.existsSync(f)) return null;
+ try { return JSON.parse(await fsp.readFile(f, 'utf8')) as CacheMeta; }
+ catch { return null; }
+}
+
+async function _writeMeta(dir: string, meta: CacheMeta): Promise<void> {
+ await fsp.writeFile(_metaFile(dir), JSON.stringify(meta, null, 2), 'utf8');
+}
+
+/** Hit check. Caller passes the server-list row's `version` + `published_at`; both must match
+ * the cached values. The cache dir itself existing is necessary but not sufficient — a
+ * half-written dir would also exist, hence the field comparison. */
+export async function isCacheFresh(kind: 'agent' | 'skill', id: string, expect: { version: string; published_at: number }): Promise<boolean> {
+ const dir = _cacheDir(kind, id);
+ if (!fs.existsSync(dir)) return false;
+ const meta = await _readMeta(dir);
+ if (!meta) return false;
+ if (meta.version !== expect.version) return false;
+ if (meta.published_at !== expect.published_at) return false;
+ return true;
+}
+
+function _cacheDir(kind: 'agent' | 'skill', id: string): string {
+ const uid = getActiveUserId();
+ return kind === 'agent' ? marketplaceCacheAgentDir(uid, id) : marketplaceCacheSkillDir(uid, id);
+}
+
+/** Touch `last_used_at` to now — call after a successful detail-page render OR install copy. */
+export async function touchCacheEntry(kind: 'agent' | 'skill', id: string): Promise<void> {
+ const dir = _cacheDir(kind, id);
+ const meta = await _readMeta(dir);
+ if (!meta) return;
+ meta.last_used_at = Date.now();
+ try { await _writeMeta(dir, meta); }
+ catch (err) { log.warn(`touch ${kind}:${id} failed: ${(err as Error).message}`); }
+}
+
+/** Write a fresh agent.json cache. Replaces the directory wholesale (prevents stale files from
+ * a previous version surviving). Sentinel-style atomic write: meta is written last so a
+ * half-written entry fails `isCacheFresh`. */
+export async function writeAgentCache(
+ id: string, agentJson: Record<string, unknown>, meta: { version: string; published_at: number },
+): Promise<void> {
+ const dir = _cacheDir('agent', id);
+ await fsp.rm(dir, { recursive: true, force: true });
+ await fsp.mkdir(dir, { recursive: true });
+ await fsp.writeFile(path.join(dir, 'agent.json'), JSON.stringify(agentJson, null, 2), 'utf8');
+ const now = Date.now();
+ await _writeMeta(dir, {
+ server_id: id, version: meta.version, published_at: meta.published_at,
+ fetched_at: now, last_used_at: now,
+ });
+}
+
+/** Read cached agent.json content. Returns null if missing / unreadable. */
+export async function readAgentCache(id: string): Promise<Record<string, unknown> | null> {
+ const dir = _cacheDir('agent', id);
+ const file = path.join(dir, 'agent.json');
+ if (!fs.existsSync(file)) return null;
+ try { return JSON.parse(await fsp.readFile(file, 'utf8')) as Record<string, unknown>; }
+ catch { return null; }
+}
+
+/** Write a fresh skill bundle cache. `extract` is called with the cache dir to actually unpack
+ * (e.g. adm-zip extractAllTo) — kept generic so the cache layer doesn't import adm-zip. */
+export async function writeSkillCache(
+ id: string,
+ extract: (dir: string) => Promise<void> | void,
+ meta: { version: string; published_at: number },
+): Promise<void> {
+ const dir = _cacheDir('skill', id);
+ await fsp.rm(dir, { recursive: true, force: true });
+ await fsp.mkdir(dir, { recursive: true });
+ await extract(dir);
+ const now = Date.now();
+ await _writeMeta(dir, {
+ server_id: id, version: meta.version, published_at: meta.published_at,
+ fetched_at: now, last_used_at: now,
+ });
+}
+
+/** Skill cache dir (caller copies its contents into builtin/skills/<id>/ on install, OR reads
+ * files directly for detail-page rendering). The `_cache.json` sentinel must NOT propagate to
+ * the install target — `installFromSkillCache` in `marketplace.ts` strips it on copy. */
+export function getSkillCacheDir(id: string): string {
+ return _cacheDir('skill', id);
+}
+
+/** Read a single file from the cached skill dir. Used by the detail-page file viewer. The
+ * caller-supplied `relFile` is path-sanitized so a tampered renderer payload can't escape
+ * the cache dir. Returns null on miss / unsafe path / I/O error. Reads up to 256 KB; bigger
+ * files are truncated with a marker so the detail view always renders within reasonable size. */
+export async function readSkillCacheFile(id: string, relFile: string): Promise<string | null> {
+ if (!relFile || relFile === '_cache.json') return null;
+ const safe = _safeRel(relFile);
+ if (!safe) return null;
+ const dir = _cacheDir('skill', id);
+ const target = path.resolve(dir, safe);
+ if (!target.startsWith(path.resolve(dir) + path.sep) && target !== path.resolve(dir)) return null;
+ if (!fs.existsSync(target) || !fs.statSync(target).isFile()) return null;
+ const MAX_BYTES = 256 * 1024;
+ try {
+ const buf = await fsp.readFile(target);
+ if (buf.length > MAX_BYTES) {
+ return buf.subarray(0, MAX_BYTES).toString('utf8') + '\n\n[…truncated]';
+ }
+ return buf.toString('utf8');
+ } catch { return null; }
+}
+
+function _safeRel(rel: string): string | 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;
+}
+
+/** Return cached skill file list (relative paths, byte sizes). Used by the detail page's file
+ * tree. Skips _cache.json. */
+export async function listSkillCacheFiles(id: string): Promise<{ path: string; bytes: number }[]> {
+ const dir = _cacheDir('skill', id);
+ if (!fs.existsSync(dir)) return [];
+ const out: { path: string; bytes: number }[] = [];
+ function walk(d: string, rel = ''): void {
+ for (const e of fs.readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
+ if (e.name === '_cache.json' || e.name.startsWith('.')) continue;
+ const childRel = rel ? `${rel}/${e.name}` : e.name;
+ const full = path.join(d, e.name);
+ if (e.isDirectory()) walk(full, childRel);
+ else if (e.isFile()) {
+ let size = 0; try { size = fs.statSync(full).size; } catch { /* ignore */ }
+ out.push({ path: childRel, bytes: size });
+ }
+ }
+ }
+ walk(dir);
+ return out;
+}
+
+// ── Listing-grid cache (cross-process) ────────────────────────────────────
+// Persists the renderer's session-level `_mpListingsCache` so cold starts don't pay a full
+// /list round-trip before the grid is populated. The renderer hydrates this on
+// `openMarketplace` then immediately renders cached items + fires a background refresh.
+
+export interface ListingsCacheEntry {
+ items: unknown[];
+ ts: number;
+}
+export interface ListingsCacheFile {
+ version: 1;
+ entries: Record<string, ListingsCacheEntry>;
+}
+const LISTINGS_VERSION = 1;
+
+export async function getListingsCache(): Promise<ListingsCacheFile> {
+ const file = marketplaceListingsCacheFile(getActiveUserId());
+ if (!fs.existsSync(file)) return { version: LISTINGS_VERSION, entries: {} };
+ try {
+ const text = await fsp.readFile(file, 'utf8');
+ const parsed = JSON.parse(text) as Partial<ListingsCacheFile>;
+ const entries = (parsed && typeof parsed.entries === 'object' && parsed.entries)
+ ? (parsed.entries as Record<string, ListingsCacheEntry>) : {};
+ return { version: LISTINGS_VERSION, entries };
+ } catch (err) {
+ log.warn(`read listings cache failed: ${(err as Error).message}`);
+ return { version: LISTINGS_VERSION, entries: {} };
+ }
+}
+
+// Serialize writes so renderer-burst saves (multiple fresh listings landing back-to-back)
+// don't trample each other. Atomic via temp + rename — partial writes never publish.
+let _listingsWriteQueue: Promise<void> = Promise.resolve();
+export function setListingsCache(entries: Record<string, ListingsCacheEntry>): Promise<void> {
+ const uid = getActiveUserId();
+ _listingsWriteQueue = _listingsWriteQueue.then(async () => {
+ const file = marketplaceListingsCacheFile(uid);
+ await fsp.mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.tmp`;
+ const data: ListingsCacheFile = { version: LISTINGS_VERSION, entries };
+ await fsp.writeFile(tmp, JSON.stringify(data), 'utf8');
+ await fsp.rename(tmp, file);
+ }).catch((err) => {
+ log.warn(`write listings cache failed: ${(err as Error).message}`);
+ });
+ return _listingsWriteQueue;
+}
+
+// ── Sweep ─────────────────────────────────────────────────────────────────
+
+/** Entry-point sweep: triggered once on each openMarketplace call. Cheap (O(N entries) stat).
+ * Returns bytes freed (0 when nothing to do). Idempotent / safe to no-op when cache is empty. */
+export async function sweepIfNeeded(): Promise<number> {
+ const root = marketplaceCacheDir(getActiveUserId());
+ if (!fs.existsSync(root)) return 0;
+
+ const entries = await _listAllEntries(root);
+ if (entries.length === 0) return 0;
+
+ const totalBytes = entries.reduce((s, e) => s + e.bytes, 0);
+ const now = Date.now();
+ const hasExpired = entries.some((e) => (now - e.lastUsedAt) > SWEEP_MAX_AGE_MS);
+
+ if (totalBytes <= SWEEP_MAX_BYTES && !hasExpired) return 0; // nothing to do
+
+ let freed = 0;
+ // 1. Expire by age (always — even if we're under the size cap, stale entries should go).
+ for (const entry of entries.filter((e) => (now - e.lastUsedAt) > SWEEP_MAX_AGE_MS)) {
+ try { await fsp.rm(entry.dir, { recursive: true, force: true }); freed += entry.bytes; entry.dropped = true; }
+ catch (err) { log.warn(`rm ${entry.dir} failed: ${(err as Error).message}`); }
+ }
+
+ // 2. If still over the cap, LRU-evict oldest until we hit the soft target.
+ let remaining = totalBytes - freed;
+ if (remaining > SWEEP_TARGET_BYTES) {
+ const survivors = entries.filter((e) => !e.dropped).sort((a, b) => a.lastUsedAt - b.lastUsedAt);
+ for (const entry of survivors) {
+ if (remaining <= SWEEP_TARGET_BYTES) break;
+ try {
+ await fsp.rm(entry.dir, { recursive: true, force: true });
+ freed += entry.bytes;
+ remaining -= entry.bytes;
+ } catch (err) {
+ log.warn(`rm ${entry.dir} failed: ${(err as Error).message}`);
+ }
+ }
+ }
+
+ log.info(`sweep: freed ${(freed / 1024 / 1024).toFixed(1)} MB`);
+ return freed;
+}
+
+interface SweepEntry { dir: string; bytes: number; lastUsedAt: number; dropped?: boolean }
+
+async function _listAllEntries(root: string): Promise<SweepEntry[]> {
+ const out: SweepEntry[] = [];
+ for (const kindDir of [marketplaceCacheAgentsDir(getActiveUserId()), marketplaceCacheSkillsDir(getActiveUserId())]) {
+ if (!fs.existsSync(kindDir)) continue;
+ for (const sub of fs.readdirSync(kindDir, { withFileTypes: true })) {
+ if (!sub.isDirectory()) continue;
+ const dir = path.join(kindDir, sub.name);
+ const meta = await _readMeta(dir);
+ if (!meta) {
+ // Half-written / no-meta dir is fair game for sweep (treat as immediately expired).
+ out.push({ dir, bytes: _dirSize(dir), lastUsedAt: 0 });
+ continue;
+ }
+ out.push({ dir, bytes: _dirSize(dir), lastUsedAt: meta.last_used_at });
+ }
+ }
+ return out;
+}
+
+function _dirSize(dir: string): number {
+ let total = 0;
+ try {
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, e.name);
+ if (e.isDirectory()) total += _dirSize(full);
+ else if (e.isFile()) {
+ try { total += fs.statSync(full).size; } catch { /* ignore */ }
+ }
+ }
+ } catch { /* ignore */ }
+ return total;
+}
diff --git a/src/main/features/marketplace_installs.ts b/src/main/features/marketplace_installs.ts
new file mode 100644
index 00000000..6614b7ce
--- /dev/null
+++ b/src/main/features/marketplace_installs.ts
@@ -0,0 +1,211 @@
+/**
+ * Marketplace install manifest — `<uid>/cloud/marketplace/installs.json`.
+ *
+ * The ONLY marketplace state that crosses devices. Records what the user has installed (id +
+ * version + published_at + COS URL); the actual content lives at `<uid>/local/marketplace/`
+ * on each machine and is reconciled on startup by `features/marketplace_reconcile.ts`
+ * (fetches whatever's listed in the manifest but missing locally).
+ *
+ * Manifest format:
+ *
+ * {
+ * "version": 1,
+ * "agents": [
+ * { "id": "abc123def456", "version": "1.0.0", "published_at": 1747066800000,
+ * "agent_json_url": "https://orkas-1367889399.cos.../agent.json",
+ * "installed_at": 1747066800100 }
+ * ],
+ * "skills": [
+ * { "id": "xyz789...", "version": "1.0.0", "published_at": 1747066800000,
+ * "bundle_url": "https://orkas-1367889399.cos.../xyz789.zip",
+ * "installed_at": 1747066800100 }
+ * ]
+ * }
+ *
+ * Single-writer rule: all mutations go through this module. Per-uid `Mutex` serializes the
+ * read-modify-write cycle (writeInstalls is atomic via temp + rename, but the surrounding
+ * `readInstalls → push → writeInstalls` sequence is not — concurrent `addSkillInstall` calls
+ * during cascade install would otherwise lose rows). Read paths skip the lock; reading
+ * mid-write is fine because we never publish a half-written manifest.
+ *
+ * **Schema versioning**: `CURRENT_VERSION` is bumped only on a breaking change (field
+ * removed / required-shape changed). Additive changes (new optional field on AgentInstall /
+ * SkillInstall) do NOT bump — `_isAgentRow` / `_isSkillRow` already tolerate unknown extra
+ * fields. When a bump is needed:
+ * 1. Bump `CURRENT_VERSION`.
+ * 2. Add a migration branch in `readInstalls` that runs on `parsed.version < CURRENT_VERSION`
+ * and rewrites rows in place.
+ * 3. Older PC versions reading a newer manifest fall through to the warn-only path below;
+ * they may drop rows they can't parse — that's the documented forward-compat cost.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import { Mutex } from 'async-mutex';
+
+import { userMarketplaceInstallsFile, userMarketplaceDirCloud } from '../paths';
+import { createLogger } from '../logger';
+
+const log = createLogger('marketplace_installs');
+
+// Per-uid mutex covering the RMW cycle of add*/remove* (read manifest → mutate → write).
+// Concurrent cascade install (Promise.all over skill_list) used to lose rows because each
+// task read the same baseline manifest and the last writeInstalls won. Read paths intentionally
+// skip the lock — writeInstalls is atomic via temp+rename, so a reader sees either the full
+// pre-state or full post-state.
+const _writeLocks = new Map<string, Mutex>();
+function _getWriteLock(uid: string): Mutex {
+ let m = _writeLocks.get(uid);
+ if (!m) { m = new Mutex(); _writeLocks.set(uid, m); }
+ return m;
+}
+
+export interface AgentInstall {
+ id: string;
+ version: string;
+ published_at: number;
+ agent_json_url: string;
+ installed_at: number;
+ /** Author uid as recorded on the server. `"0"` = "官方"; everything else = community
+ * uploader. Optional in the type so old manifest rows (pre-2026-05-13) still parse —
+ * reconcile fills it in next time the row is re-pulled. UI uses this to render the
+ * author badge on the agent detail page. */
+ create_uid?: string;
+}
+
+export interface SkillInstall {
+ id: string;
+ version: string;
+ published_at: number;
+ bundle_url: string;
+ installed_at: number;
+ /** Same as `AgentInstall.create_uid` — see comment there. */
+ create_uid?: string;
+}
+
+export const CURRENT_VERSION = 1;
+
+export interface InstallsManifest {
+ version: typeof CURRENT_VERSION;
+ agents: AgentInstall[];
+ skills: SkillInstall[];
+}
+
+const EMPTY: InstallsManifest = { version: CURRENT_VERSION, agents: [], skills: [] };
+
+export async function readInstalls(uid: string): Promise<InstallsManifest> {
+ const file = userMarketplaceInstallsFile(uid);
+ if (!fs.existsSync(file)) return { ...EMPTY };
+ try {
+ const text = await fsp.readFile(file, 'utf8');
+ const parsed = JSON.parse(text) as Partial<InstallsManifest> & { version?: unknown };
+ const parsedVersion = typeof parsed.version === 'number' ? parsed.version : CURRENT_VERSION;
+ if (parsedVersion > CURRENT_VERSION) {
+ // Newer PC wrote this manifest. Best-effort: read every row that still matches our
+ // schema, drop the rest. User loses some installs locally but the canonical state is
+ // still in the manifest (next write by the newer PC will restore them).
+ log.warn(`installs.json schema v${parsedVersion} > supported v${CURRENT_VERSION}; reading best-effort`);
+ } else if (parsedVersion < CURRENT_VERSION) {
+ // Older manifest. When a future bump introduces a real migration, dispatch here on
+ // parsedVersion. For now there's no v0, so this branch is documentation-only.
+ log.info(`installs.json schema v${parsedVersion} < v${CURRENT_VERSION}; no migration needed yet`);
+ }
+ return {
+ version: CURRENT_VERSION,
+ agents: Array.isArray(parsed.agents) ? parsed.agents.filter(_isAgentRow) : [],
+ skills: Array.isArray(parsed.skills) ? parsed.skills.filter(_isSkillRow) : [],
+ };
+ } catch (err) {
+ log.warn(`read ${file} failed: ${(err as Error).message}`);
+ return { ...EMPTY };
+ }
+}
+
+/** Atomic write: temp file + rename. Caller is the single writer in this process.
+ * Always stamps `version: CURRENT_VERSION` regardless of the passed-in manifest's `version`
+ * field — guarantees forward-only schema progression even if a reader passes a stale value. */
+export async function writeInstalls(uid: string, manifest: InstallsManifest): Promise<void> {
+ await fsp.mkdir(userMarketplaceDirCloud(uid), { recursive: true });
+ const file = userMarketplaceInstallsFile(uid);
+ const tmp = `${file}.tmp`;
+ const stamped = { ...manifest, version: CURRENT_VERSION };
+ await fsp.writeFile(tmp, JSON.stringify(stamped, null, 2), 'utf8');
+ await fsp.rename(tmp, file);
+}
+
+export async function addAgentInstall(uid: string, row: Omit<AgentInstall, 'installed_at'> & { installed_at?: number }): Promise<void> {
+ await _getWriteLock(uid).runExclusive(async () => {
+ const manifest = await readInstalls(uid);
+ const idx = manifest.agents.findIndex((a) => a.id === row.id);
+ const entry: AgentInstall = { ...row, installed_at: row.installed_at || Date.now() };
+ if (idx >= 0) manifest.agents[idx] = entry;
+ else manifest.agents.push(entry);
+ await writeInstalls(uid, manifest);
+ log.info(`agent installed id=${row.id} v${row.version}`);
+ });
+}
+
+export async function addSkillInstall(uid: string, row: Omit<SkillInstall, 'installed_at'> & { installed_at?: number }): Promise<void> {
+ await _getWriteLock(uid).runExclusive(async () => {
+ const manifest = await readInstalls(uid);
+ const idx = manifest.skills.findIndex((s) => s.id === row.id);
+ const entry: SkillInstall = { ...row, installed_at: row.installed_at || Date.now() };
+ if (idx >= 0) manifest.skills[idx] = entry;
+ else manifest.skills.push(entry);
+ await writeInstalls(uid, manifest);
+ log.info(`skill installed id=${row.id} v${row.version}`);
+ });
+}
+
+export async function removeAgentInstall(uid: string, id: string): Promise<boolean> {
+ return _getWriteLock(uid).runExclusive(async () => {
+ const manifest = await readInstalls(uid);
+ const before = manifest.agents.length;
+ manifest.agents = manifest.agents.filter((a) => a.id !== id);
+ if (manifest.agents.length === before) return false;
+ await writeInstalls(uid, manifest);
+ log.info(`agent uninstalled id=${id}`);
+ return true;
+ });
+}
+
+export async function removeSkillInstall(uid: string, id: string): Promise<boolean> {
+ return _getWriteLock(uid).runExclusive(async () => {
+ const manifest = await readInstalls(uid);
+ const before = manifest.skills.length;
+ manifest.skills = manifest.skills.filter((s) => s.id !== id);
+ if (manifest.skills.length === before) return false;
+ await writeInstalls(uid, manifest);
+ log.info(`skill uninstalled id=${id}`);
+ return true;
+ });
+}
+
+export async function findAgentInstall(uid: string, id: string): Promise<AgentInstall | null> {
+ const m = await readInstalls(uid);
+ return m.agents.find((a) => a.id === id) || null;
+}
+
+export async function findSkillInstall(uid: string, id: string): Promise<SkillInstall | null> {
+ const m = await readInstalls(uid);
+ return m.skills.find((s) => s.id === id) || null;
+}
+
+function _isAgentRow(x: unknown): x is AgentInstall {
+ if (!x || typeof x !== 'object') return false;
+ const r = x as Record<string, unknown>;
+ // `create_uid` is intentionally not required — older rows pre-date the field.
+ return typeof r.id === 'string' && typeof r.version === 'string'
+ && typeof r.published_at === 'number' && typeof r.agent_json_url === 'string'
+ && typeof r.installed_at === 'number';
+}
+
+function _isSkillRow(x: unknown): x is SkillInstall {
+ if (!x || typeof x !== 'object') return false;
+ const r = x as Record<string, unknown>;
+ return typeof r.id === 'string' && typeof r.version === 'string'
+ && typeof r.published_at === 'number' && typeof r.bundle_url === 'string'
+ && typeof r.installed_at === 'number';
+}
diff --git a/src/main/features/marketplace_reconcile.ts b/src/main/features/marketplace_reconcile.ts
new file mode 100644
index 00000000..222ac0e7
--- /dev/null
+++ b/src/main/features/marketplace_reconcile.ts
@@ -0,0 +1,207 @@
+/**
+ * Marketplace install reconciler.
+ *
+ * Read the cloud-synced manifest at `<uid>/cloud/marketplace/installs.json` and ensure every
+ * entry has a corresponding local copy under `<uid>/local/marketplace/{agents,skills}/<id>/`.
+ * Anything in the manifest but missing on disk gets fetched (in parallel) from the COS URL
+ * recorded in the manifest. Anything on disk but not in the manifest is left alone (might be
+ * a partial uninstall or external state we don't own).
+ *
+ * Called once at boot from `main/index.ts`, fire-and-forget. Failures are logged but never
+ * propagated — a missed install just means the user has to revisit the marketplace and
+ * reinstall (or the next boot retries automatically).
+ */
+
+import AdmZip from 'adm-zip';
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import {
+ userMarketplaceAgentDir, userMarketplaceSkillDir,
+} from '../paths';
+import { readInstalls, type AgentInstall, type SkillInstall } from './marketplace_installs';
+import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-agent/skill-registry';
+import { extractBundleSafely } from './marketplace';
+import { createLogger } from '../logger';
+
+const log = createLogger('marketplace_reconcile');
+
+/** Coarse-grained reconcile state for the UI banner. `idle` covers both pre-run and a finished
+ * run with nothing to pull (banner stays hidden in both cases). */
+export type ReconcileState = 'idle' | 'running' | 'done';
+
+export interface ReconcileStatus {
+ state: ReconcileState;
+ /** Total entries to pull this run (set when entering `running`). */
+ total: number;
+ /** Successfully pulled (incremented in real time). */
+ pulled: number;
+ /** ids of failed pulls — only meaningful in `done`. */
+ failed: string[];
+ /** Wall-clock time of the last transition (ms). Banner uses this to decide whether to
+ * auto-hide after a delay. */
+ updated_at: number;
+}
+
+let _status: ReconcileStatus = { state: 'idle', total: 0, pulled: 0, failed: [], updated_at: Date.now() };
+type StatusListener = (s: ReconcileStatus) => void;
+const _listeners = new Set<StatusListener>();
+
+/** Snapshot of the current state. Renderer calls this once at startup via IPC, then subscribes
+ * to push-events for further changes (see `main/index.ts::wireReconcileBroadcast`). */
+export function getReconcileStatus(): ReconcileStatus { return _status; }
+
+/** Subscribe to reconcile-status transitions. Returns an unsubscribe function. The listener
+ * fires for every state mutation (including in-flight `running.pulled` increments — the UI
+ * banner re-renders progress without polling). */
+export function subscribeReconcileStatus(listener: StatusListener): () => void {
+ _listeners.add(listener);
+ return () => _listeners.delete(listener);
+}
+
+function _setStatus(next: ReconcileStatus): void {
+ _status = next;
+ for (const fn of _listeners) {
+ try { fn(_status); } catch { /* listener errors must not break reconcile */ }
+ }
+}
+
+/** Read manifest + reconcile every entry in parallel. Returns counts for logging. Emits status
+ * updates through the subscribe channel so the renderer can show a "syncing" banner. */
+export async function reconcileInstalls(uid: string): Promise<{ pulled_agents: number; pulled_skills: number; failed: string[] }> {
+ const manifest = await readInstalls(uid);
+ // Filter pull-needed up front so the banner's total is meaningful (it counts work the user
+ // will actually see, not entries that short-circuit).
+ const agentsNeedingPull = manifest.agents.filter((r) => _agentNeedsPull(uid, r));
+ const skillsNeedingPull = manifest.skills.filter((r) => _skillNeedsPull(uid, r));
+ const total = agentsNeedingPull.length + skillsNeedingPull.length;
+ if (total === 0) {
+ _setStatus({ state: 'idle', total: 0, pulled: 0, failed: [], updated_at: Date.now() });
+ return { pulled_agents: 0, pulled_skills: 0, failed: [] };
+ }
+
+ _setStatus({ state: 'running', total, pulled: 0, failed: [], updated_at: Date.now() });
+
+ const failed: string[] = [];
+ let pulled_agents = 0;
+ let pulled_skills = 0;
+
+ const bumpProgress = (): void => {
+ _setStatus({ ..._status, pulled: pulled_agents + pulled_skills, updated_at: Date.now() });
+ };
+
+ const agentTasks = agentsNeedingPull.map(async (row) => {
+ try {
+ await _pullAgent(uid, row);
+ pulled_agents++;
+ bumpProgress();
+ } catch (err) {
+ log.warn(`agent ${row.id} pull failed: ${(err as Error).message}`);
+ failed.push(`agent:${row.id}`);
+ }
+ });
+ const skillTasks = skillsNeedingPull.map(async (row) => {
+ try {
+ await _pullSkill(uid, row);
+ pulled_skills++;
+ bumpProgress();
+ } catch (err) {
+ log.warn(`skill ${row.id} pull failed: ${(err as Error).message}`);
+ failed.push(`skill:${row.id}`);
+ }
+ });
+
+ await Promise.all([...agentTasks, ...skillTasks]);
+
+ if (pulled_skills > 0) {
+ try { invalidateCoreAgentSkills(); } catch { /* runner may not be loaded yet */ }
+ }
+ _setStatus({
+ state: 'done', total, pulled: pulled_agents + pulled_skills,
+ failed, updated_at: Date.now(),
+ });
+ log.info(`reconciled: pulled ${pulled_agents} agent(s) + ${pulled_skills} skill(s); failed=${failed.length}`);
+ return { pulled_agents, pulled_skills, failed };
+}
+
+/** Need-pull check: missing dir / missing agent.json / `_install.json::version` mismatch.
+ * Mirrors the cache freshness rule from marketplace_cache.ts (version + published_at). */
+function _agentNeedsPull(uid: string, row: AgentInstall): boolean {
+ const dir = userMarketplaceAgentDir(uid, row.id);
+ const agentJsonFile = path.join(dir, 'agent.json');
+ if (!fs.existsSync(agentJsonFile)) return true;
+ const meta = _readInstallMeta(dir);
+ if (!meta) return true;
+ return meta.version !== row.version || meta.published_at !== row.published_at;
+}
+
+function _skillNeedsPull(uid: string, row: SkillInstall): boolean {
+ const dir = userMarketplaceSkillDir(uid, row.id);
+ if (!fs.existsSync(path.join(dir, 'SKILL.md'))) return true;
+ const meta = _readInstallMeta(dir);
+ if (!meta) return true;
+ return meta.version !== row.version || meta.published_at !== row.published_at;
+}
+
+interface InstallMeta { version: string; published_at: number; create_uid?: string }
+
+function _readInstallMeta(dir: string): InstallMeta | null {
+ const f = path.join(dir, '_install.json');
+ if (!fs.existsSync(f)) return null;
+ try {
+ const j = JSON.parse(fs.readFileSync(f, 'utf8')) as Partial<InstallMeta>;
+ if (typeof j.version !== 'string' || typeof j.published_at !== 'number') return null;
+ return {
+ version: j.version,
+ published_at: j.published_at,
+ create_uid: typeof j.create_uid === 'string' ? j.create_uid : '',
+ };
+ } catch { return null; }
+}
+
+async function _writeInstallMeta(dir: string, meta: InstallMeta): Promise<void> {
+ await fsp.writeFile(path.join(dir, '_install.json'), JSON.stringify(meta, null, 2), 'utf8');
+}
+
+/** Fetch agent.json from the cloud URL recorded in the manifest, write to the per-machine
+ * install target. Wipe-and-replace so a previous version doesn't leave stale fields. */
+async function _pullAgent(uid: string, row: AgentInstall): Promise<void> {
+ const res = await fetch(row.agent_json_url);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const text = await res.text();
+ // Validate it parses — manifest-stored URLs come from COS, treat as untrusted.
+ const parsed = JSON.parse(text) as Record<string, unknown>;
+ if (typeof parsed.agent_id !== 'string') throw new Error('agent.json missing agent_id');
+
+ const dir = userMarketplaceAgentDir(uid, row.id);
+ await fsp.rm(dir, { recursive: true, force: true });
+ await fsp.mkdir(dir, { recursive: true });
+ await fsp.writeFile(path.join(dir, 'agent.json'), text, 'utf8');
+ await _writeInstallMeta(dir, {
+ version: row.version, published_at: row.published_at,
+ create_uid: row.create_uid || '',
+ });
+}
+
+/** Fetch the skill bundle zip from cloud URL + extract. Same wipe-and-replace semantics.
+ * `extractBundleSafely` enforces entry count + uncompressed size caps (zip-bomb defense)
+ * — shared with the marketplace install path. */
+async function _pullSkill(uid: string, row: SkillInstall): Promise<void> {
+ const res = await fetch(row.bundle_url);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const ab = await res.arrayBuffer();
+ const zip = new AdmZip(Buffer.from(ab));
+
+ const dir = userMarketplaceSkillDir(uid, row.id);
+ await fsp.rm(dir, { recursive: true, force: true });
+ await fsp.mkdir(dir, { recursive: true });
+
+ extractBundleSafely(zip, dir);
+ // Sanity: SKILL.md must end up in place (zip empty / corrupt would silently skip everything).
+ if (!fs.existsSync(path.join(dir, 'SKILL.md'))) throw new Error('bundle missing SKILL.md');
+ await _writeInstallMeta(dir, {
+ version: row.version, published_at: row.published_at,
+ create_uid: row.create_uid || '',
+ });
+}
diff --git a/src/main/features/skills.ts b/src/main/features/skills.ts
index 35d018c0..15550253 100644
--- a/src/main/features/skills.ts
+++ b/src/main/features/skills.ts
@@ -23,8 +23,8 @@ import * as os from 'node:os';
import * as path from 'node:path';
import {
- BUILTIN_SKILLS_DIR, BUILTIN_SKILLS_SOURCE,
- userSkillsDir, userSkillChatDir, userSessionFile, WS_ROOT,
+ userSkillsDir, userSkillChatDir, userSessionFile, WS_ROOT, SRC_ROOT,
+ userMarketplaceSkillsDir,
} from '../paths';
import { evictSession } from '../model/core-agent/session-store';
import { getActiveUserId } from './users';
@@ -47,7 +47,13 @@ import { invalidateSkills as invalidateCoreAgentSkills } from '../model/core-age
import { readDisabledSets, setSkillEnabled } from './component_enabled';
import { findOuterTagRanges } from '../util/markdown-prose-code';
-const SKILL_TREE_IGNORE: ReadonlySet<string> = new Set(['.DS_Store', '__pycache__', '.git', 'node_modules']);
+// Names hidden from the in-app skill source-tree view. `_install.json` (marketplace install
+// version pin) and `_cache.json` (marketplace cache LRU bookkeeping) are tooling sidecars,
+// not authored content — surfacing them confuses users and looks like noise in the file list.
+const SKILL_TREE_IGNORE: ReadonlySet<string> = new Set([
+ '.DS_Store', '__pycache__', '.git', 'node_modules',
+ '_install.json', '_cache.json',
+]);
// Starts with a letter, then letters/digits/_/-; single spaces are allowed
// between word groups (no leading/trailing/consecutive spaces).
const SKILL_NAME_RE = /^[A-Za-z][A-Za-z0-9_-]*(?: [A-Za-z0-9_-]+)*$/;
@@ -75,10 +81,20 @@ export interface SkillListing {
source: SkillSource;
description_zh: string;
description_en: string;
+ /** Marketplace category code (`education` / `ecommerce` / `rnd` / …). Empty string when
+ * the SKILL.md frontmatter doesn't set one — UI treats that as "uncategorized". */
+ category: string;
/** **Computed at load time, not persisted.** Filled by `listSkills` from
* `features/component_enabled.ts`. Defaults to true unless the user has
* explicitly disabled the skill. */
enabled: boolean;
+ /** Author uid for `source==='builtin'` (marketplace-installed) skills — read from
+ * `_install.json`. `"0"` = "官方"; empty for `source==='custom'`. Renderer uses this to
+ * show the "官方/作者" badge instead of an "内置" chip. */
+ create_uid?: string;
+ /** Marketplace install version for `source==='builtin'`. Read from `_install.json` so the
+ * skills-tab card can render a `v1.0.0` chip. Undefined for custom skills. */
+ version?: string;
}
export interface CustomSkill {
@@ -86,10 +102,23 @@ export interface CustomSkill {
name: string;
description_zh: string;
description_en: string;
+ category: string;
source: 'custom';
dir: string;
}
+/** Like `CustomSkill` but `source` is open — used by edit-chat resolution
+ * which has to handle built-ins in dev mode. */
+export interface SkillForEdit {
+ id: string;
+ name: string;
+ description_zh: string;
+ description_en: string;
+ category: string;
+ source: SkillSource;
+ dir: string;
+}
+
/** Migrate legacy single-`description` frontmatter into the bilingual pair.
* Mirrors the logic in core-agent's SkillLoader and main's normalizeAgent —
* CJK ideograph in legacy → `_zh`, otherwise → `_en`. Explicit fields win. */
@@ -120,115 +149,19 @@ export interface SkillFrontmatter {
description?: string;
description_zh?: string;
description_en?: string;
+ /** Marketplace category code; required for skills published to the marketplace, optional for
+ * user-created skills (defaults to empty string / "uncategorized" in `listSkills` output). */
+ category?: string;
[key: string]: string | string[] | undefined;
}
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,
- * folded into a sha256. Empty / missing tree → ''.
- */
-export function hashTree(root: string): string {
- if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) return '';
- const h = crypto.createHash('sha256');
-
- function walk(dir: string, relBase = ''): void {
- const entries = fs.readdirSync(dir, { withFileTypes: true })
- .sort((a, b) => a.name.localeCompare(b.name));
- for (const e of entries) {
- 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()) {
- h.update(rel, 'utf8');
- h.update(Buffer.from([0]));
- try { h.update(fs.readFileSync(full)); } catch { /* skip */ }
- h.update(Buffer.from([0x0a]));
- }
- }
- }
- walk(root);
- return h.digest('hex');
-}
-
-/**
- * Refresh `data/shared/skills/builtin/` from `PC/builtin/skills/`.
- * Returns true if any change was made (caller should re-register + invalidate).
- */
-export function syncBuiltinSkills(): boolean {
- fs.mkdirSync(BUILTIN_SKILLS_DIR, { recursive: true });
- if (!fs.existsSync(BUILTIN_SKILLS_SOURCE)) {
- log.info(`source dir missing: ${BUILTIN_SKILLS_SOURCE}; skipping`);
- return false;
- }
-
- 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('.')
- && !_isMarketplaceInstalled(path.join(BUILTIN_SKILLS_DIR, e.name)))
- .map((e) => e.name));
-
- let changed = false;
-
- // Removed upstream → drop local copy
- for (const stale of [...dstNames].filter((n) => !srcNames.has(n)).sort()) {
- try {
- fs.rmSync(path.join(BUILTIN_SKILLS_DIR, stale), { recursive: true, force: true });
- log.info(`removed stale ${stale}`);
- changed = true;
- } catch (err) {
- log.warn(`rm ${stale} failed: ${(err as Error).message}`);
- }
- }
-
- // 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;
- if (fs.existsSync(dst)) {
- try { fs.rmSync(dst, { recursive: true, force: true }); }
- catch (err) { log.warn(`rm ${dst} failed: ${(err as Error).message}`); continue; }
- }
- try {
- fs.cpSync(src, dst, { recursive: true });
- log.info(`synced ${name}`);
- changed = true;
- } catch (err) {
- log.warn(`copy ${name} failed: ${(err as Error).message}`);
- }
- }
-
- return changed;
-}
+// `syncBuiltinSkills` / `hashTree` / `_isMarketplaceInstalled` removed — there is no longer a
+// shipped-builtin tree (`PC/src/builtin/skills/` is gone). Marketplace installs land directly
+// in `<uid>/local/marketplace/skills/<id>/` via `features/marketplace.ts::installMarketplaceSkill`
+// and are reconciled across devices through the cloud-synced installs.json manifest. Source
+// 'builtin' is a legacy enum name; on disk it now resolves to `userMarketplaceSkillsDir(uid)`.
// ═══════════════════════════════════════════════════════════════════════
// 2. Skill reading / listing
@@ -306,7 +239,7 @@ function _unescapeDoubleQuoted(s: string): string {
}
function skillBaseDir(source: SkillSource): string {
- return source === 'custom' ? CUSTOM_SKILLS_DIR() : BUILTIN_SKILLS_DIR;
+ return source === 'custom' ? CUSTOM_SKILLS_DIR() : userMarketplaceSkillsDir(getActiveUserId());
}
// Module-level cache for `listSkills`.
@@ -315,9 +248,55 @@ let _skillListCache: SkillListCache | null = null;
function _invalidateSkillListCache(): void { _skillListCache = null; }
+/** Internal cache invalidator + core-agent registry invalidator. Exported for
+ * the dev-only `skills_dev` module so its dual-write path goes through the
+ * same cache-busting chain as `writeCustomSkillFile`. */
+export function invalidateSkillCachesForEdit(): void {
+ _invalidateSkillListCache();
+ invalidateCoreAgentSkills().catch(() => { /* runner may not be loaded yet */ });
+}
+
+/** A skill id resolves to a built-in iff there's a directory with that name
+ * under the runtime built-in tree. The src tree may be missing in packaged
+ * builds, so the runtime tree is the authoritative check. */
+export function isBuiltinSkill(skillId: string): boolean {
+ if (!skillId) return false;
+ const d = path.join(userMarketplaceSkillsDir(getActiveUserId()), skillId);
+ try { return fs.statSync(d).isDirectory(); } catch { return false; }
+}
+
+/** Resolve a skill id for edit-chat use, regardless of source. Returns the
+ * same shape as `getCustomSkill` but with `source` reflecting where the dir
+ * was found. Custom is checked first (matches the loader precedence). */
+export async function getSkillForEdit(skillId: string): Promise<SkillForEdit | null> {
+ if (!skillId) return null;
+ const sources: Array<[SkillSource, string]> = [
+ ['custom', CUSTOM_SKILLS_DIR()],
+ ['builtin', userMarketplaceSkillsDir(getActiveUserId())],
+ ];
+ for (const [source, base] of sources) {
+ const d = path.join(base, skillId);
+ if (!fs.existsSync(d) || !fs.statSync(d).isDirectory()) continue;
+ let name = skillId;
+ let descPair = { description_zh: '', description_en: '' };
+ let category = '';
+ const md = path.join(d, 'SKILL.md');
+ if (fs.existsSync(md)) {
+ try {
+ const { meta } = splitSkillMd(fs.readFileSync(md, 'utf8'));
+ name = meta.name || skillId;
+ descPair = migrateDescriptionPair(meta as any);
+ category = (meta.category as string) || '';
+ } catch { /* ignore */ }
+ }
+ return { id: skillId, name, ...descPair, category, source, dir: d };
+ }
+ return null;
+}
+
function _skillDirStamp(): string {
let stamp = '';
- for (const d of [CUSTOM_SKILLS_DIR(), BUILTIN_SKILLS_DIR]) {
+ for (const d of [CUSTOM_SKILLS_DIR(), userMarketplaceSkillsDir(getActiveUserId())]) {
try { stamp += `${d}:${fs.statSync(d).mtimeMs};`; }
catch { stamp += `${d}:0;`; }
}
@@ -331,7 +310,7 @@ export async function listSkills(): Promise<SkillListing[]> {
const out: SkillListing[] = [];
const seen = new Set<string>();
// Custom first so it wins on id collision (matches openclaw symlink rule).
- const sources: Array<[SkillSource, string]> = [['custom', CUSTOM_SKILLS_DIR()], ['builtin', BUILTIN_SKILLS_DIR]];
+ const sources: Array<[SkillSource, string]> = [['custom', CUSTOM_SKILLS_DIR()], ['builtin', userMarketplaceSkillsDir(getActiveUserId())]];
for (const [source, baseDir] of sources) {
if (!fs.existsSync(baseDir)) continue;
const names = fs.readdirSync(baseDir, { withFileTypes: true })
@@ -349,14 +328,30 @@ export async function listSkills(): Promise<SkillListing[]> {
const skillMd = path.join(baseDir, name, 'SKILL.md');
let displayName = name;
let descPair = { description_zh: '', description_en: '' };
+ let category = '';
+ let createUid: string | undefined;
+ let version: string | undefined;
if (fs.existsSync(skillMd)) {
try {
const meta = parseSkillFrontmatter(fs.readFileSync(skillMd, 'utf8'));
descPair = migrateDescriptionPair(meta as any);
displayName = meta.name as string || name;
+ category = (meta.category as string) || '';
} catch { /* ignore */ }
}
- out.push({ id: name, name: displayName, source, ...descPair, enabled: true });
+ // Marketplace-installed skills carry `_install.json` with `create_uid` + `version` —
+ // read it so the UI can show "官方/作者" + version chips without an extra IPC. Custom skills skip.
+ if (source === 'builtin') {
+ try {
+ const metaFile = path.join(baseDir, name, '_install.json');
+ if (fs.existsSync(metaFile)) {
+ const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8'));
+ if (meta && typeof meta.create_uid === 'string') createUid = meta.create_uid;
+ if (meta && typeof meta.version === 'string') version = meta.version;
+ }
+ } catch { /* corrupt _install.json — leave fields undefined */ }
+ }
+ out.push({ id: name, name: displayName, source, ...descPair, category, enabled: true, create_uid: createUid, version });
}
}
_skillListCache = { stamp, data: out };
@@ -454,11 +449,16 @@ export function validateSkillName(name: string): string {
return '';
}
-// Skill-id shape check used by IPC handlers. Accepts the same alphabet as
-// validateSkillName (spaces between words OK) so space-named skills can be
-// opened / updated.
+// Skill-id shape check used by IPC handlers. Accepts EITHER a user-typed skill name
+// (SKILL_NAME_RE — letter-led, spaces between words) for custom skills, OR a 12-hex
+// server-assigned id for marketplace-installed skills (which can begin with a digit).
+// Without the hex branch, dev uploading a platform-installed skill whose id starts with a
+// digit (e.g. `9720e1e263fd` Word/DOCX) bounced as "invalid skill id" — root cause of the
+// "上传 skill 报错" event seen in main log.
+const SKILL_HEX_ID_RE = /^[a-f0-9]{12}$/;
export function isValidSkillId(id: unknown): boolean {
- return typeof id === 'string' && id.length > 0 && SKILL_NAME_RE.test(id);
+ if (typeof id !== 'string' || !id) return false;
+ return SKILL_HEX_ID_RE.test(id) || SKILL_NAME_RE.test(id);
}
function customSkillDir(skillId: string): string {
@@ -469,6 +469,7 @@ export function skillMdContent(
name: string,
description: string | { zh?: string; en?: string },
body = '',
+ category = '',
): string {
const cleanName = (name || '').replace(/\n/g, ' ').replace(/"/g, '\\"');
const sanitize = (s: string) => (s || '').replace(/\n/g, ' ').replace(/"/g, '\\"');
@@ -486,8 +487,12 @@ export function skillMdContent(
}
const cleanZh = sanitize(zh);
const cleanEn = sanitize(en);
+ const cleanCategory = sanitize(category || '');
const trimmedBody = body.replace(/^\n+/, '');
- return `---\nname: "${cleanName}"\ndescription_zh: "${cleanZh}"\ndescription_en: "${cleanEn}"\n---\n\n${trimmedBody}`;
+ // Emit `category` only when explicitly provided — user-created skills without a category yet
+ // are perfectly valid; the field becomes mandatory only at marketplace upload time.
+ const categoryLine = cleanCategory ? `\ncategory: "${cleanCategory}"` : '';
+ return `---\nname: "${cleanName}"\ndescription_zh: "${cleanZh}"\ndescription_en: "${cleanEn}"${categoryLine}\n---\n\n${trimmedBody}`;
}
export function splitSkillMd(text: string): { meta: SkillFrontmatter; body: string } {
@@ -506,14 +511,16 @@ export async function getCustomSkill(skillId: string): Promise<CustomSkill | nul
const md = path.join(d, 'SKILL.md');
let name = skillId;
let descPair = { description_zh: '', description_en: '' };
+ let category = '';
if (fs.existsSync(md)) {
try {
const { meta } = splitSkillMd(fs.readFileSync(md, 'utf8'));
name = meta.name || skillId;
descPair = migrateDescriptionPair(meta as any);
+ category = (meta.category as string) || '';
} catch { /* ignore */ }
}
- return { id: skillId, name, ...descPair, source: 'custom', dir: d };
+ return { id: skillId, name, ...descPair, category, source: 'custom', dir: d };
}
export async function listCustomSkillFiles(skillId: string): Promise<SkillFileInfo[]> {
@@ -539,7 +546,9 @@ export async function listCustomSkillFiles(skillId: string): Promise<SkillFileIn
return out;
}
-export async function createCustomSkill(name: string, description: string): Promise<CustomSkill | null> {
+export async function createCustomSkill(
+ name: string, description: string, category = '',
+): Promise<CustomSkill | null> {
const err = validateSkillName(name);
if (err) throw new Error(err);
const d = customSkillDir(name);
@@ -547,12 +556,12 @@ export async function createCustomSkill(name: string, description: string): Prom
// Custom skills would silently shadow a same-named builtin in the
// skill-registry first-wins resolution. Reject the create so the user
// renames up front.
- if (fs.existsSync(path.join(BUILTIN_SKILLS_DIR, name))) {
+ if (fs.existsSync(path.join(userMarketplaceSkillsDir(getActiveUserId()), name))) {
throw new Error(t('skills.errors.builtin_conflict', { name }));
}
fs.mkdirSync(d, { recursive: true });
- writeTextAtomicSync(path.join(d, 'SKILL.md'), skillMdContent(name, description));
- log.info(`created name=${name}`);
+ writeTextAtomicSync(path.join(d, 'SKILL.md'), skillMdContent(name, description, '', category));
+ log.info(`created name=${name} category=${category || '(none)'}`);
_invalidateSkillListCache();
invalidateCoreAgentSkills().catch(() => { /* runner may not be loaded yet */ });
return getCustomSkill(name);
@@ -560,7 +569,13 @@ export async function createCustomSkill(name: string, description: string): Prom
export async function updateCustomSkill(
skillId: string,
- updates: { name?: string; description?: string; description_zh?: string; description_en?: string },
+ updates: {
+ name?: string;
+ description?: string;
+ description_zh?: string;
+ description_en?: string;
+ category?: string;
+ },
options: { skipRename?: boolean } = {},
): Promise<CustomSkill | null> {
let d = customSkillDir(skillId);
@@ -587,6 +602,10 @@ export async function updateCustomSkill(
if (legacy && isChinese && !explicitZh) newZh = legacy;
if (legacy && !isChinese && !explicitEn) newEn = legacy;
}
+ // category: explicit update wins, otherwise carry over persisted value.
+ const newCategory = Object.prototype.hasOwnProperty.call(updates, 'category')
+ ? String(updates.category || '')
+ : ((meta.category as string) || '');
let currentId = skillId;
// `skipRename` is the in-progress-edit hook used by the skill detail name
@@ -601,7 +620,7 @@ export async function updateCustomSkill(
if (err) throw new Error(err);
const target = customSkillDir(newName);
if (fs.existsSync(target)) throw new Error(t('skills.errors.skill_exists', { name: newName }));
- if (fs.existsSync(path.join(BUILTIN_SKILLS_DIR, newName))) {
+ if (fs.existsSync(path.join(userMarketplaceSkillsDir(getActiveUserId()), newName))) {
throw new Error(t('skills.errors.builtin_conflict', { name: newName }));
}
fs.renameSync(d, target);
@@ -645,8 +664,8 @@ export async function updateCustomSkill(
currentId = newName;
}
- writeTextAtomicSync(md, skillMdContent(newName, { zh: newZh, en: newEn }, body));
- log.info(`updated name=${currentId}`);
+ writeTextAtomicSync(md, skillMdContent(newName, { zh: newZh, en: newEn }, body, newCategory));
+ log.info(`updated name=${currentId} category=${newCategory || '(none)'}`);
_invalidateSkillListCache();
invalidateCoreAgentSkills().catch(() => { /* runner may not be loaded yet */ });
return getCustomSkill(currentId);
@@ -699,6 +718,12 @@ const IMPORT_FILTER_NAMES: ReadonlySet<string> = new Set([
// ownerId/slug/version/publishedAt — irrelevant to this app and shows
// up as "header noise" in the UI).
'_meta.json',
+ // Marketplace sidecars: `_install.json` (version pin written by install / reconcile —
+ // meaningless once a platform skill is imported as custom) and `_cache.json` (LRU bookkeeping
+ // for the detail-page cache). Both are tooling internal — must never propagate when a user
+ // imports a skill dir or when dev re-uploads a platform skill (see also marketplace_dev::
+ // SKIP_NAMES).
+ '_install.json', '_cache.json',
// npm packaging artefacts — skill dirs are forbidden from carrying their
// own node_modules or package.json (see core conventions); strip the
// sidecars too so partial copies don't linger.
@@ -716,7 +741,7 @@ function _isBlacklistedImportSource(realDir: string): { blocked: true; reason: s
// Orkas's own trees — pulling these in would recursion-bomb and/or leak
// the source/data.
- for (const root of [path.resolve(BUILTIN_SKILLS_SOURCE, '..', '..'), WS_ROOT]) {
+ for (const root of [SRC_ROOT, WS_ROOT]) {
if (root && (dir === root || dir.startsWith(root + path.sep))) {
return { blocked: true, reason: t('skills.import_block.self_dir') };
}
@@ -923,7 +948,7 @@ async function _renameSkillByFrontmatterIfNeeded(currentId: string): Promise<str
if (validateSkillName(intended) !== '') return null;
// Don't clobber an existing skill (custom or builtin) at the new id
if (fs.existsSync(customSkillDir(intended))) return null;
- if (fs.existsSync(path.join(BUILTIN_SKILLS_DIR, intended))) return null;
+ if (fs.existsSync(path.join(userMarketplaceSkillsDir(getActiveUserId()), intended))) return null;
try {
const updated = await updateCustomSkill(currentId, { name: intended });
if (updated) {
@@ -1175,7 +1200,7 @@ async function _applySkillContainerCreate(files: SkillFileBlock[]): Promise<Skil
if (fs.existsSync(customSkillDir(name))) {
return { ok: false, error: t('skills.errors.skill_exists', { name }) };
}
- if (fs.existsSync(path.join(BUILTIN_SKILLS_DIR, name))) {
+ if (fs.existsSync(path.join(userMarketplaceSkillsDir(getActiveUserId()), name))) {
return { ok: false, error: t('skills.errors.builtin_conflict', { name }) };
}
// Seed description from the frontmatter so the registry never sees a
@@ -1286,6 +1311,9 @@ export interface SkillChatResult {
message?: string;
error?: string;
written?: string[];
+ /** Frontmatter `name` edits trigger a rename of the skill dir; this list surfaces
+ * every (oldId → newId) pair so the renderer can re-anchor open tabs. */
+ renamed?: Array<{ oldId: string; newId: string }>;
}
export async function sendToSkillChat(userId: string, skillId: string, content: string): Promise<SkillChatResult> {
@@ -1313,7 +1341,7 @@ export async function sendToSkillChat(userId: string, skillId: string, content:
// that, so it's blocked at the sandbox level.
readOnlyExtraRoots: [
...(skill.dir ? [skill.dir] : []),
- BUILTIN_SKILLS_DIR,
+ userMarketplaceSkillsDir(getActiveUserId()),
userSkillsDir(userId),
],
});
@@ -1400,7 +1428,7 @@ export async function* streamSendToSkillChat(
cacheRetention: 'short',
readOnlyExtraRoots: [
...(skill.dir ? [skill.dir] : []),
- BUILTIN_SKILLS_DIR,
+ userMarketplaceSkillsDir(getActiveUserId()),
userSkillsDir(userId),
],
...(opts.abortSignal ? { abortSignal: opts.abortSignal } : {}),
diff --git a/src/main/index.ts b/src/main/index.ts
index 349fd46b..4964ded8 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -228,7 +228,6 @@ function registerIpc(): void {
appRoot: paths.APP_ROOT,
pcRoot: paths.PC_ROOT,
wsRoot: paths.WS_ROOT,
- builtinSkillsSource: paths.BUILTIN_SKILLS_SOURCE,
usersFile: paths.USERS_FILE,
},
storage: sample,
@@ -258,7 +257,6 @@ async function runBootSelfCheck(): Promise<void> {
const diag = {
appRoot: paths.APP_ROOT,
wsRoot: paths.WS_ROOT,
- builtinSource: paths.BUILTIN_SKILLS_SOURCE,
promptChatNormal: prompts.exists('chat_commander'),
promptOrganize: prompts.exists('contexts_organize'),
};
@@ -283,19 +281,21 @@ async function runBootSelfCheck(): Promise<void> {
log.info('i18n language resolved', { lang });
} catch (err) { log.warn('i18n init failed', { error: (err as Error).message }); }
- // Stage 2: builtin skill content sync from `src/builtin/skills/` →
- // `data/builtin/skills/`. core-agent's SkillLoader picks these up directly
- // from the top-level dir, shared across all uids.
+ // Stage 2: one-shot migration of any pre-marketplace `data/builtin/{agents,skills}/`
+ // tree into the active uid's cloud/. Idempotent via marker file; no-op on fresh
+ // installs. After this runs there is no more globally-shared builtin tree — every
+ // marketplace install lives at `<uid>/local/marketplace/` and gets reconciled from
+ // the cloud `installs.json` manifest.
try {
- skillsFeature.syncBuiltinSkills();
+ const { migrateLegacyBuiltinToCloud } = await import('./util/migrate-marketplace');
+ const out = await migrateLegacyBuiltinToCloud(users.getActiveUserId());
+ if (out.moved_agents || out.moved_skills) {
+ log.info('legacy builtin migrated', out);
+ }
} catch (err) {
- log.warn('skill bootstrap failed', { error: (err as Error).message });
+ log.warn('legacy builtin migrate failed', { error: (err as Error).message });
}
- // Stage 2b: builtin agents sync (hash-tree; cheap if empty).
- try { agentsFeature.syncBuiltinAgents(); }
- catch (err) { log.warn('builtin-agents sync failed', { error: (err as Error).message }); }
-
// Stage 3: clear stale processing=true conversations from a previous crash.
try { await chatsFeature.sweepStaleProcessing(); }
catch (err) { log.warn('chats sweep failed', { error: (err as Error).message }); }
@@ -714,6 +714,54 @@ if (!gotLock) {
// (chats.createConversation + groupChat.send). Idempotent.
scheduledTasks.startScheduler();
+ // Background: prime the marketplace category cache so the first openMarketplace
+ // doesn't pay the round-trip on cold start. Errors are swallowed — the lazy
+ // path in features/marketplace_biz.ts is the real safety net.
+ import('./features/marketplace_biz').then((m) => m.primeCategoryCache()).catch(() => {});
+
+ // Background marketplace setup: (1) seed the default installs manifest on first launch
+ // (no manifest file → fetch `/marketplace/defaults` → write a row per official item),
+ // (2) reconcile downloads any manifest rows whose local content is missing. Step 1
+ // populates the manifest that step 2 consumes; both are fire-and-forget so a slow / down
+ // server never blocks UI boot. Reconcile status updates broadcast to renderers so the
+ // marketplace panel can show a "syncing" banner — layering keeps `features/` free of
+ // `ipc/` imports, broadcast wiring lives here (same pattern as `group_chat.subscribe`).
+ (async () => {
+ try {
+ const mp = await import('./features/marketplace');
+ const seeded = await mp.ensureDefaultInstalls(users.getActiveUserId());
+ if (seeded.seeded_agents || seeded.seeded_skills) {
+ createLogger('marketplace_defaults').info('seeded default installs', seeded);
+ }
+ } catch (err) {
+ createLogger('marketplace_defaults').warn('default installs seed failed', {
+ error: (err as Error).message,
+ });
+ }
+ try {
+ const m = await import('./features/marketplace_reconcile');
+ m.subscribeReconcileStatus((status) => {
+ ipc.broadcastToRenderer('marketplace:reconcile-status', status);
+ });
+ await m.reconcileInstalls(users.getActiveUserId());
+ } catch (err) {
+ createLogger('marketplace_reconcile').warn('startup reconcile failed', {
+ error: (err as Error).message,
+ });
+ }
+ try {
+ // Backfill `create_uid` / `version` for older install records (predates those fields
+ // being persisted). Idempotent — no-op when every row already has the field. Runs after
+ // reconcile so any freshly-pulled record already has the fields and the backfill skips it.
+ const mp = await import('./features/marketplace');
+ await mp.backfillMarketplaceCreateUid(users.getActiveUserId());
+ } catch (err) {
+ createLogger('marketplace_backfill').warn('startup backfill failed', {
+ error: (err as Error).message,
+ });
+ }
+ })();
+
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index ac110372..7da0fc00 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -26,6 +26,10 @@ 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 marketplaceBiz from '../features/marketplace_biz';
+import * as marketplaceCache from '../features/marketplace_cache';
+import * as marketplaceReconcile from '../features/marketplace_reconcile';
+import * as cacheClearable from '../features/cache_clearable';
import * as contexts from '../features/contexts';
import * as kbVector from '../features/kb_vector';
import * as kbIndexer from '../features/kb_indexer';
@@ -454,8 +458,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return { agent };
},
- 'agents.create': async ({ name = '', description = '', description_zh, description_en, workflow = '', icon, color, runtime } = {}) => {
- return { agent: await agents.createCustomAgent({ name, description, description_zh, description_en, workflow, icon, color, runtime }) };
+ 'agents.create': async ({ name = '', description = '', description_zh, description_en, workflow = '', icon, color, runtime, category } = {}) => {
+ return { agent: await agents.createCustomAgent({ name, description, description_zh, description_en, workflow, icon, color, runtime, category }) };
},
@@ -523,8 +527,8 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return skills.listSkillTree(source, id);
},
- 'skills.create': async ({ name, description }) => {
- return { skill: await skills.createCustomSkill(name, description || '') };
+ 'skills.create': async ({ name, description, category }) => {
+ return { skill: await skills.createCustomSkill(name, description || '', category || '') };
},
'skills.pickImportDir': async () => {
@@ -603,24 +607,105 @@ const invokeHandlers: Record<string, InvokeHandler> = {
},
// ── 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) }),
+ // Listing + detail + install endpoints hit the public Server catalog; categories are served
+ // from the local 24h biz cache (features/marketplace_biz.ts), so no server hit unless stale.
+ // Upload endpoints live in `dev_handlers.ts` (dev builds only).
+ 'marketplace.categories': async () => ({ list: await marketplaceBiz.getMarketplaceCategories() }),
'marketplace.listAgents': async (opts = {}) => marketplace.listMarketplaceAgents(opts),
'marketplace.listSkills': async (opts = {}) => marketplace.listMarketplaceSkills(opts),
- 'marketplace.installAgent': async ({ id }) => {
+ // Detail endpoints (cache-first) — used by the marketplace panel's detail view to render
+ // full content. Caller passes the list-row's (version, published_at) so we can short-circuit
+ // on a hot cache. Sweep is invoked once per openMarketplace at the entry point.
+ 'marketplace.detailAgent': async ({ id, version, published_at }) => {
if (!id || typeof id !== 'string') throw new Error('id required');
- return marketplace.installMarketplaceAgent(id);
+ if (typeof version !== 'string' || typeof published_at !== 'number') {
+ throw new Error('version + published_at required');
+ }
+ return marketplace.getAgentDetail(id, { version, published_at });
+ },
+
+ 'marketplace.detailSkill': async ({ id, version, published_at }) => {
+ if (!id || typeof id !== 'string') throw new Error('id required');
+ if (typeof version !== 'string' || typeof published_at !== 'number') {
+ throw new Error('version + published_at required');
+ }
+ return marketplace.getSkillDetail(id, { version, published_at });
+ },
+
+ 'marketplace.installAgent': async ({ id, version, published_at }) => {
+ if (!id || typeof id !== 'string') throw new Error('id required');
+ if (typeof version !== 'string' || typeof published_at !== 'number') {
+ throw new Error('version + published_at required');
+ }
+ return marketplace.installMarketplaceAgent(id, { version, published_at });
+ },
+
+ 'marketplace.installSkill': async ({ id, version, published_at }) => {
+ if (!id || typeof id !== 'string') throw new Error('id required');
+ if (typeof version !== 'string' || typeof published_at !== 'number') {
+ throw new Error('version + published_at required');
+ }
+ return marketplace.installMarketplaceSkill(id, { version, published_at });
+ },
+
+ // Uninstall is non-dev: wipes the local install copy + manifest entry. Does NOT touch the
+ // server row (`marketplace_dev.deleteMarketplace*` does that, dev-only).
+ 'marketplace.uninstallAgent': async ({ id }) => {
+ if (!id || typeof id !== 'string') throw new Error('id required');
+ return marketplace.uninstallMarketplaceAgent(id);
+ },
+
+ 'marketplace.uninstallSkill': async ({ id }) => {
+ if (!id || typeof id !== 'string') throw new Error('id required');
+ return marketplace.uninstallMarketplaceSkill(id);
},
- 'marketplace.installSkill': async ({ id }) => {
+ // Entry-point housekeeping for the marketplace panel: sweep stale + over-sized cache entries.
+ // Cheap (O(N entries) stat), so it's safe to call once per openMarketplace from the renderer.
+ 'marketplace.sweepCache': async () => ({ bytes_freed: await marketplaceCache.sweepIfNeeded() }),
+
+ // Renderer queries this once at startup to learn the current reconcile state, then subscribes
+ // to push-events `marketplace:reconcile-status` for in-flight progress. See main/index.ts
+ // boot wiring + features/marketplace_reconcile.ts::subscribeReconcileStatus.
+ 'marketplace.reconcileStatus': async () => marketplaceReconcile.getReconcileStatus(),
+
+ // Persistent listing-grid cache so cold starts don't show a blank panel. Renderer hydrates
+ // from this on `openMarketplace` and writes back after every fresh /list response. See
+ // `marketplace_cache.ts::{getListingsCache,setListingsCache}`.
+ 'marketplace.getListingsCache': async () => marketplaceCache.getListingsCache(),
+
+ 'marketplace.setListingsCache': async ({ entries }) => {
+ if (!entries || typeof entries !== 'object') throw new Error('entries required');
+ await marketplaceCache.setListingsCache(entries);
+ return { ok: true as const };
+ },
+
+ // Detail-page file viewer (skill kind only — agent payload is fully in the detail response).
+ 'marketplace.cacheSkillFiles': async ({ id }) => {
if (!id || typeof id !== 'string') throw new Error('id required');
- return marketplace.installMarketplaceSkill(id);
+ return { list: await marketplaceCache.listSkillCacheFiles(id) };
},
+ 'marketplace.cacheSkillRead': async ({ id, file }) => {
+ if (!id || typeof id !== 'string') throw new Error('id required');
+ if (!file || typeof file !== 'string') throw new Error('file required');
+ const content = await marketplaceCache.readSkillCacheFile(id, file);
+ return { content: content || '' };
+ },
+
+ // ── Cache (clearable umbrella under `<uid>/local/cache/<bucket>/`) ──
+ 'cache.listClearable': async () => ({ list: await cacheClearable.listClearableBuckets() }),
+
+ 'cache.clearBucket': async ({ name }) => {
+ if (!name || typeof name !== 'string') throw new Error('name required');
+ return { bytes_freed: await cacheClearable.clearBucket(name) };
+ },
+
+ 'cache.clearAll': async () => ({ bytes_freed: await cacheClearable.clearAllClearable() }),
+
// ── Contexts (user-owned directory tree; vectorized via kb_indexer) ──
'contexts.tree': async () => ({ tree: contexts.listContextsTree() }),
@@ -1107,6 +1192,15 @@ async function resolveContext(sender: WebContents): Promise<IpcContext> {
return { userId: user.user_id, user, sender };
}
+/** Send a push-event to every open renderer. Channel name must match preload's
+ * `PUSH_EVENT_PREFIXES` allow-list (currently `marketplace:` / `sync:`). Used by main-initiated
+ * status broadcasts (boot-time reconcile / future cloud-sync state). */
+export function broadcastToRenderer(channel: string, payload: unknown): void {
+ for (const win of BrowserWindow.getAllWindows()) {
+ if (!win.isDestroyed()) win.webContents.send(channel, payload);
+ }
+}
+
export function register(): void {
ipcMain.handle('orkas.invoke', async (event, { channel, payload }) => {
const handler = invokeHandlers[channel];
diff --git a/src/main/model/core-agent/skill-registry.ts b/src/main/model/core-agent/skill-registry.ts
index 632c33bd..54b4cc46 100644
--- a/src/main/model/core-agent/skill-registry.ts
+++ b/src/main/model/core-agent/skill-registry.ts
@@ -3,21 +3,24 @@
* shared by every core-agent chat request.
*
* Resolution order (see CLAUDE.md §6):
- * 1. <uid>/cloud/skills/ (user-custom; same id overrides builtin)
- * 2. data/builtin/skills/ (built-in; hash-synced from src/builtin/skills at startup)
+ * 1. <uid>/cloud/skills/ (user-custom; same id overrides platform install)
+ * 2. <uid>/local/marketplace/skills/ (platform-installed; per-machine copy reconciled
+ * from the cloud-synced installs.json manifest)
*
* The loader caches by per-dir mtime, so `list()` is effectively free
* between CRUD events. `features/skills.ts` can call `invalidateSkills()`
* after a create/update/delete to force a re-scan before the next chat.
*
* The `Source` label is computed in this layer (`skillSourceLabel`), not
- * by the loader's basename inference — after the per-uid migration both
- * roots end in `/skills`, so basename is no longer distinguishing.
+ * by the loader's basename inference — both roots end in `/skills`, so
+ * basename is no longer distinguishing. 'builtin' is preserved as the
+ * label string for backwards compatibility with the rest of the codebase;
+ * UI renders it as "Platform".
*/
import * as path from 'node:path';
-import { BUILTIN_SKILLS_DIR, userSkillsDir } from '../../paths';
+import { userMarketplaceSkillsDir, userSkillsDir } from '../../paths';
import { getActiveUserId } from '../../features/users';
import { getCurrentLang } from '../../i18n';
// `pickDescription` is loaded lazily — see CLAUDE.md §3: any static import
@@ -33,13 +36,15 @@ async function getPickDescription(): Promise<PickDescription> {
return _pickDescription;
}
-// `Source` is decided by root path, not by `path.basename(source)` — after the
-// per-uid migration both skill roots end in `/skills`, so basename loses its
-// discrimination (see CLAUDE.md §4). Only `BUILTIN_SKILLS_DIR` counts as
-// builtin; everything else (= `userSkillsDir(uid)`) is custom.
-const BUILTIN_ROOT_RESOLVED = path.resolve(BUILTIN_SKILLS_DIR);
+// `Source` is decided by root path, not by `path.basename(source)` — both skill roots end
+// in `/skills`, so basename is non-discriminating (see CLAUDE.md §4). Marketplace-installed
+// dir = 'builtin'; everything else (= cloud custom) = 'custom'. Resolved per-call because
+// the marketplace dir is per-uid; can't pre-resolve to a module-level constant.
function skillSourceLabel(source: string): 'builtin' | 'custom' {
- return path.resolve(source) === BUILTIN_ROOT_RESOLVED ? 'builtin' : 'custom';
+ try {
+ const platformRoot = path.resolve(userMarketplaceSkillsDir(getActiveUserId()));
+ return path.resolve(source) === platformRoot ? 'builtin' : 'custom';
+ } catch { return 'custom'; }
}
// Render the system-prompt block listing every skill the LLM can use.
@@ -75,20 +80,27 @@ async function renderSkillLines(
if (!specs.length) return '';
const lang = getCurrentLang();
const pick = await getPickDescription();
+ // Each entry shows the human `name` (what the model uses to decide *whether* to reach
+ // for the skill) plus the raw `id` (what goes into the read_file path). They DIVERGE for
+ // marketplace installs whose dir name = 12-hex server id but whose authored name is a
+ // readable string — see core-agent loader.ts comment on the dir-id ≠ name split.
const lines: string[] = [
'## Available skills (skills)',
'',
'`read_file(<ROOT>/<id>/SKILL.md)` — ROOT by Source:',
`- custom: ${customRoot}`,
`- builtin: ${builtinRoot}`,
- 'Use these ROOT values verbatim.',
+ 'Use these ROOT values verbatim. `<id>` is the directory name shown after each entry; use it in the path even when it differs from the display name.',
'',
];
for (const s of specs) {
const source = skillSourceLabel(s.source);
const description = pick(s, lang);
const desc = description ? ` — ${description}` : '';
- lines.push(`- **${s.name}** (Source: ${source})${desc}`);
+ // When name == id (custom skills authored locally), collapse the redundancy; when they
+ // differ (marketplace installs), surface both so the model can pick by name and read by id.
+ const head = s.name && s.name !== s.id ? `**${s.name}** (id: ${s.id})` : `**${s.id}**`;
+ lines.push(`- ${head} (Source: ${source})${desc}`);
}
return lines.join('\n');
}
@@ -107,7 +119,7 @@ async function getLoader(): Promise<SkillLoaderInstance> {
_loaderPromise = import('#core-agent').then((m) => {
return new m.SkillLoader({
// custom (cloud, per-uid) listed first → user overrides of same-id builtins.
- dirs: [userSkillsDir(getActiveUserId()), BUILTIN_SKILLS_DIR],
+ dirs: [userSkillsDir(getActiveUserId()), userMarketplaceSkillsDir(getActiveUserId())],
});
});
}
@@ -156,7 +168,7 @@ export async function getSystemPromptBlock(opts: SystemPromptBlockOptions = {}):
// `activateUser` which calls `invalidateSkills` to drop the loader cache,
// but the ROOT values must reflect the CURRENT uid regardless of cache age.
const customRoot = path.resolve(userSkillsDir(getActiveUserId()));
- const builtinRoot = path.resolve(BUILTIN_SKILLS_DIR);
+ const builtinRoot = path.resolve(userMarketplaceSkillsDir(getActiveUserId()));
if (opts.allowlist === undefined) return renderSkillLines(filterDisabled(specs), customRoot, builtinRoot);
@@ -174,10 +186,12 @@ export async function invalidateSkills(): Promise<void> {
loader.invalidate();
}
-/** For diagnostics: return the skill list. */
+/** For diagnostics: return the skill list. Picks a description per the active UI language. */
export async function listSkills(): Promise<Array<{ id: string; name: string; description: string }>> {
const loader = await getLoader();
- return loader.list().map((s) => ({ id: s.id, name: s.name, description: s.description }));
+ const lang = getCurrentLang();
+ const pick = await getPickDescription();
+ return loader.list().map((s) => ({ id: s.id, name: s.name, description: pick(s, lang) }));
}
/**
diff --git a/src/main/paths.ts b/src/main/paths.ts
index e77099c6..929fc8d2 100644
--- a/src/main/paths.ts
+++ b/src/main/paths.ts
@@ -34,6 +34,10 @@
* before any TS module loads (`paths.ts` reads it at import time —
* the env var MUST be set before the first `import * as paths` call).
* ORKAS_BUILTIN_ROOT optional override for the builtin source dir
+ * ORKAS_WORKSPACE_ROOT point data root elsewhere (set by index.ts to
+ * `<container>/data`; tests / power users may
+ * pre-set it to a tmp dir to bypass container
+ * resolution)
* CORE_AGENT_AUTH_DIR pinned by `activateUser()` to the active user's `<uid>/local/config/`
*/
@@ -73,18 +77,10 @@ export const WS_ROOT = path.resolve(process.env.ORKAS_WORKSPACE_ROOT);
export const USERS_FILE = path.join(WS_ROOT, 'users.json');
// Machine-local logs (daily rolling, single global file shared across uids).
export const LOGS_DIR = path.join(WS_ROOT, 'logs');
-// Builtin runtime copy: hash-synced from `src/builtin/` at startup; all uids
-// read from here. The loader scans
-// `[<uid>/cloud/{skills,agents}, <BUILTIN_{SKILLS,AGENTS}_DIR>]`.
-export const BUILTIN_ROOT = path.join(WS_ROOT, 'builtin');
-export const BUILTIN_AGENTS_DIR = path.join(BUILTIN_ROOT, 'agents');
-export const BUILTIN_SKILLS_DIR = path.join(BUILTIN_ROOT, 'skills');
-// Builtin agents follow the same directory shape:
-// `<BUILTIN_AGENTS_DIR>/<aid>/agent.json`. The runtime sub-directories
-// (meta / skills) only exist on the user cloud side; the builtin side does
-// not carry them.
-export const builtinAgentDir = (agentId: string) => path.join(BUILTIN_AGENTS_DIR, agentId);
-export const builtinAgentDefinitionFile = (agentId: string) => path.join(builtinAgentDir(agentId), 'agent.json');
+// (The legacy globally-shared `data/builtin/{agents,skills}/` tree is gone. Marketplace
+// installs now land under `<uid>/local/marketplace/` per machine — see `userMarketplace*`
+// helpers below. A one-shot migration in `util/migrate-marketplace.ts` moves any pre-cutover
+// `data/builtin/` content into the active uid's cloud tree on first launch.)
// ── Per-user roots ───────────────────────────────────────────────────────
export const userRoot = (uid: string) => path.join(WS_ROOT, uid);
@@ -245,6 +241,79 @@ export const sessionToolResultsDir = (uid: string, sessionId: string) =>
// Never synced — the source paths are local-absolute.
export const userFileCacheDir = (uid: string) => path.join(userLocalRoot(uid), 'file_cache');
+// ── Cache umbrella ─────────────────────────────────────────────────────
+// `<uid>/local/cache/<bucket>/` is the convention for **user-clearable**
+// caches: anything dropped here is fair game for the "clear cache" UI
+// button. features/cache_clearable.ts enumerates the buckets and exposes
+// clearBucket / clearAll. Distinct from `local/config/` (user prefs;
+// untouched) and `local/biz/` (server-source business data; refreshable
+// but not user-clearable).
+export const userLocalCacheDir = (uid: string) => path.join(userLocalRoot(uid), 'cache');
+export const localCacheBucketDir = (uid: string, bucket: string) =>
+ path.join(userLocalCacheDir(uid), bucket);
+
+// ── Business data ──────────────────────────────────────────────────────
+// `<uid>/local/biz/` holds server-sourced reference data the client mirrors
+// locally (e.g. marketplace.json carrying the category registry with a 24h
+// TTL). Not user prefs (=> not in config/) and not throwaway cache
+// (=> not in cache/) — losing it forces a re-fetch but is otherwise safe.
+export const userLocalBizDir = (uid: string) => path.join(userLocalRoot(uid), 'biz');
+export const marketplaceBizFile = (uid: string) =>
+ path.join(userLocalBizDir(uid), 'marketplace.json');
+
+// ── Marketplace content cache (`<uid>/local/cache/marketplace/`) ────────
+// Mirror of agent.json / skill bundle content fetched from the server, used
+// to render the detail page without re-hitting the network on every visit
+// and to short-circuit install when the same version is already on disk.
+// Lives under cache/ (the "clearable" umbrella above) — losing it just
+// triggers a re-fetch.
+export const marketplaceCacheDir = (uid: string) => localCacheBucketDir(uid, 'marketplace');
+export const marketplaceCacheAgentsDir = (uid: string) => path.join(marketplaceCacheDir(uid), 'agents');
+export const marketplaceCacheSkillsDir = (uid: string) => path.join(marketplaceCacheDir(uid), 'skills');
+export const marketplaceCacheAgentDir = (uid: string, id: string) =>
+ path.join(marketplaceCacheAgentsDir(uid), id);
+export const marketplaceCacheSkillDir = (uid: string, id: string) =>
+ path.join(marketplaceCacheSkillsDir(uid), id);
+// Marketplace listing-grid cache: single JSON file storing the last `/list` response per
+// (kind, category, q) key. Read at openMarketplace to render instantly; written on each
+// fresh response. Under `cache/` umbrella so a "clear cache" wipe drops it.
+export const marketplaceListingsCacheFile = (uid: string) =>
+ path.join(marketplaceCacheDir(uid), 'listings.json');
+// Marker dropped at the end of a successful default-install seed pass. Decoupled from
+// `installs.json` (which gets mutated row-by-row during seed; a mid-write crash leaves a
+// partial manifest). Presence of THIS file = "the entire seed completed at least once" —
+// next launch skips seed; absence = "seed never finished, retry on next launch (add*Install
+// is idempotent so re-runs are safe)". Under cloud/ so cross-device sync propagates "seeded
+// already" once any device finishes the seed.
+export const marketplaceDefaultsSeededFile = (uid: string) =>
+ path.join(userMarketplaceDirCloud(uid), '.default-seeded.json');
+
+// ── Marketplace install target (`<uid>/local/marketplace/`) ─────────────
+// **Where actually-installed content lives on this machine.** Distinct from the cache above:
+// cache holds anything the user has viewed; this holds anything the user has installed.
+// Per-user and per-machine — multi-device install state is reconciled via the cloud-synced
+// `installs.json` manifest below: each machine sees the same list of installed ids/urls and
+// fetches whichever local copies are missing on startup (`features/marketplace_reconcile.ts`).
+// Listed by `features/{agents,skills}.ts::list*` alongside cloud/{agents,skills}/ so installed
+// items show under the "Platform" group in the UI.
+export const userMarketplaceDir = (uid: string) => path.join(userLocalRoot(uid), 'marketplace');
+export const userMarketplaceAgentsDir = (uid: string) => path.join(userMarketplaceDir(uid), 'agents');
+export const userMarketplaceSkillsDir = (uid: string) => path.join(userMarketplaceDir(uid), 'skills');
+export const userMarketplaceAgentDir = (uid: string, id: string) =>
+ path.join(userMarketplaceAgentsDir(uid), id);
+export const userMarketplaceSkillDir = (uid: string, id: string) =>
+ path.join(userMarketplaceSkillsDir(uid), id);
+
+// ── Marketplace install manifest (cloud-synced) ────────────────────────
+// `<uid>/cloud/marketplace/installs.json` — the only marketplace state that crosses devices.
+// Format: { version, agents:[{id, version, published_at, agent_json_url, installed_at}],
+// skills:[{id, version, published_at, bundle_url, installed_at}] }. Used by
+// `features/marketplace_reconcile.ts` to fetch missing content into `local/marketplace/`
+// at startup. Touched by `features/marketplace_installs.ts` (single-writer for the file).
+export const userMarketplaceDirCloud = (uid: string) => path.join(userCloudRoot(uid), 'marketplace');
+export const userMarketplaceInstallsFile = (uid: string) =>
+ path.join(userMarketplaceDirCloud(uid), 'installs.json');
+
// Run-history root for local CLI agent dispatches
// (features/local_agents/runner.ts). One subdirectory per dispatch:
// <uid>/local/file_cache/local-agent-runs/<runId>/{meta.json,
@@ -292,17 +361,8 @@ export function embeddingModelDir(): string {
return path.join(PC_ROOT, 'resources', 'embedding-model');
}
-// ── Builtin source dirs (shipped, read-only in packaged app) ─────────────
-// All source lives under SRC_ROOT, and `builtin/` follows; electron-builder
-// globs `src/builtin/**` into asar at packaging time. When the user
-// overrides ORKAS_BUILTIN_ROOT, the path is used as-is and does not go
-// through SRC_ROOT.
-export const BUILTIN_SKILLS_SOURCE = process.env.ORKAS_BUILTIN_ROOT
- ? path.join(path.resolve(process.env.ORKAS_BUILTIN_ROOT), 'skills')
- : path.join(SRC_ROOT, 'builtin', 'skills');
-export const BUILTIN_AGENTS_SOURCE = process.env.ORKAS_BUILTIN_ROOT
- ? path.join(path.resolve(process.env.ORKAS_BUILTIN_ROOT), 'agents')
- : path.join(SRC_ROOT, 'builtin', 'agents');
+// (No shipped builtin source tree anymore. The marketplace is the only source for
+// platform agents/skills, fetched at install time and reconciled from the cloud manifest.)
// ── User workspace (user-facing working directory for agent output) ──────
// Default: `userWorkSpace/` next to the workspace root.
@@ -316,7 +376,7 @@ export const DEFAULT_USER_WORKSPACE = process.env.ORKAS_WORKSPACE_ROOT
// Only the top-level shared directories are created here; per-uid sub-trees
// are mkdir'd on demand by `features/users.activateUser(uid)`.
export function ensureTopLevelLayout(): void {
- for (const d of [LOGS_DIR, BUILTIN_AGENTS_DIR, BUILTIN_SKILLS_DIR, DEFAULT_USER_WORKSPACE]) {
+ for (const d of [LOGS_DIR, DEFAULT_USER_WORKSPACE]) {
fs.mkdirSync(d, { recursive: true });
}
}
@@ -340,6 +400,9 @@ export function ensureUserLayout(uid: string): void {
userAgentsDir(uid),
userSkillsDir(uid),
userProjectsDir(uid),
+ userMarketplaceAgentsDir(uid),
+ userMarketplaceSkillsDir(uid),
+ userMarketplaceDirCloud(uid),
// userMetaDir is deprecated — per-agent meta now lands in the
// `agents/<aid>/meta/` sub-directory, mkdir'd on demand at agent
// creation time, so no top-level placeholder is required.
diff --git a/src/main/preload.js b/src/main/preload.js
index 137c502e..9a055e7a 100644
--- a/src/main/preload.js
+++ b/src/main/preload.js
@@ -48,6 +48,29 @@ function logRecord(record) {
} catch (_) { /* preload must not throw */ }
}
+// Push-event subscription — for main-initiated broadcasts where the renderer doesn't drive
+// the lifecycle (unlike `stream` which the renderer starts). Channel names are restricted to
+// a known prefix list so the renderer can't tap into arbitrary internal IPC traffic.
+const PUSH_EVENT_PREFIXES = ['marketplace:', 'sync:'];
+function isAllowedPushChannel(channel) {
+ if (typeof channel !== 'string') return false;
+ return PUSH_EVENT_PREFIXES.some((p) => channel.startsWith(p));
+}
+
+/** Subscribe to a main-initiated push event. Returns an `unsubscribe()` function.
+ * Throws if the channel isn't in the allow-list (see PUSH_EVENT_PREFIXES). */
+function onPushEvent(channel, handler) {
+ if (!isAllowedPushChannel(channel)) {
+ throw new Error(`push channel not allowed: ${channel}`);
+ }
+ if (typeof handler !== 'function') throw new Error('handler must be a function');
+ const listener = (_evt, payload) => {
+ try { handler(payload); } catch (_) { /* swallow — listener must not throw */ }
+ };
+ ipcRenderer.on(channel, listener);
+ return () => ipcRenderer.removeListener(channel, listener);
+}
+
function stream(channel, payload, onEvent) {
const requestId = nextRequestId();
const channelKey = `stream:${requestId}`;
@@ -95,5 +118,6 @@ contextBridge.exposeInMainWorld('orkas', {
getLocales: () => invoke('config.getLocales'),
invoke,
stream,
+ onPushEvent,
log: logRecord,
});
diff --git a/src/main/smoke.ts b/src/main/smoke.ts
index 12fe7003..70ca44ed 100644
--- a/src/main/smoke.ts
+++ b/src/main/smoke.ts
@@ -31,9 +31,10 @@ async function section(name: string, fn: () => void | Promise<void>): Promise<vo
await section('WS_ROOT derivable', () => assert.ok(paths.WS_ROOT.length > 0));
await section('USERS_FILE at data root', () =>
assert.strictEqual(paths.USERS_FILE, path.join(paths.WS_ROOT, 'users.json')));
- await section('BUILTIN_SKILLS_DIR at top level', () =>
- assert.strictEqual(paths.BUILTIN_SKILLS_DIR, path.join(paths.WS_ROOT, 'builtin', 'skills')));
- await section('BUILTIN_SKILLS_SOURCE points somewhere', () => assert.ok(paths.BUILTIN_SKILLS_SOURCE.length > 0));
+ await section('userMarketplaceSkillsDir under local', () =>
+ assert.ok(paths.userMarketplaceSkillsDir('12345678').endsWith('/12345678/local/marketplace/skills')));
+ await section('userMarketplaceAgentsDir under local', () =>
+ assert.ok(paths.userMarketplaceAgentsDir('12345678').endsWith('/12345678/local/marketplace/agents')));
await section('userChatsDir in cloud', () =>
assert.ok(paths.userChatsDir('12345678').endsWith('/12345678/cloud/chats')));
await section('userAuthProfilesFile in local', () =>
diff --git a/src/main/util/migrate-marketplace.ts b/src/main/util/migrate-marketplace.ts
new file mode 100644
index 00000000..a3ce23f1
--- /dev/null
+++ b/src/main/util/migrate-marketplace.ts
@@ -0,0 +1,131 @@
+/**
+ * One-shot migration: pre-marketplace `data/builtin/{agents,skills}/` → user cloud.
+ *
+ * Old model (pre-2026-05): `data/builtin/{agents,skills}/<id>/` was a top-level globally-shared
+ * tree synced from `PC/src/builtin/` at startup. Marketplace installs were dropped here too,
+ * marked with a `_marketplace.json` sentinel to exempt them from the sync.
+ *
+ * New model: there is no shipped-builtin tree (`PC/src/builtin/` is gone). Marketplace installs
+ * live at `<uid>/local/marketplace/{agents,skills}/<id>/` (per-user, per-machine; reconciled
+ * via the cloud-synced installs.json manifest). The old `data/builtin/` tree is dead weight.
+ *
+ * Migration policy: treat every dir under the legacy `data/builtin/{agents,skills}/` as a
+ * **user-custom item** (moves into `<uid>/cloud/{agents,skills}/<id>/`). Rationale: by the
+ * time this runs the user has lived with these as if they were their own agents/skills — bumping
+ * them into cloud preserves continuity (same id, same content, now showing under "Custom"
+ * instead of the gone "Platform" group). Marketplace items will get re-installed via
+ * reconcile when the cloud manifest is rebuilt on a fresh install.
+ *
+ * Idempotent via a marker file at `<container>/data/builtin/.migrated-to-cloud.json`. After
+ * migration the legacy `data/builtin/` directory is removed.
+ */
+
+import * as fs from 'node:fs';
+import * as fsp from 'node:fs/promises';
+import * as path from 'node:path';
+
+import { WS_ROOT, userAgentsDir, userSkillsDir } from '../paths';
+import { createLogger } from '../logger';
+
+const log = createLogger('migrate-marketplace');
+
+const LEGACY_BUILTIN_ROOT = () => path.join(WS_ROOT, 'builtin');
+const MIGRATION_MARKER = () => path.join(LEGACY_BUILTIN_ROOT(), '.migrated-to-cloud.json');
+
+/** Idempotent. Moves any legacy `data/builtin/{agents,skills}/<id>/` dir into the active uid's
+ * cloud tree. Returns counts (zero when there's nothing to do — eg fresh install). */
+export async function migrateLegacyBuiltinToCloud(uid: string): Promise<{ moved_agents: number; moved_skills: number }> {
+ const root = LEGACY_BUILTIN_ROOT();
+ if (!fs.existsSync(root)) return { moved_agents: 0, moved_skills: 0 };
+ if (fs.existsSync(MIGRATION_MARKER())) {
+ log.info('legacy data/builtin already migrated; skipping');
+ return { moved_agents: 0, moved_skills: 0 };
+ }
+
+ const movedAgents = await _moveDirChildren(
+ path.join(root, 'agents'),
+ userAgentsDir(uid),
+ 'agent',
+ );
+ const movedSkills = await _moveDirChildren(
+ path.join(root, 'skills'),
+ userSkillsDir(uid),
+ 'skill',
+ );
+
+ // Write marker BEFORE rm so a crash mid-cleanup doesn't lose the "already migrated" signal.
+ await fsp.mkdir(root, { recursive: true });
+ await fsp.writeFile(MIGRATION_MARKER(), JSON.stringify({
+ migrated_at: Date.now(), to_uid: uid,
+ moved_agents: movedAgents, moved_skills: movedSkills,
+ }, null, 2));
+
+ // Now wipe the legacy root entirely (including the marker — it's just a crash-safety belt).
+ try { await fsp.rm(root, { recursive: true, force: true }); }
+ catch (err) { log.warn(`cleanup ${root} failed: ${(err as Error).message}`); }
+
+ log.info(`migrated ${movedAgents} agent(s) + ${movedSkills} skill(s) → uid=${uid}/cloud`);
+ return { moved_agents: movedAgents, moved_skills: movedSkills };
+}
+
+async function _moveDirChildren(src: string, dst: string, kind: string): Promise<number> {
+ if (!fs.existsSync(src)) return 0;
+ await fsp.mkdir(dst, { recursive: true });
+ let count = 0;
+ for (const entry of await fsp.readdir(src, { withFileTypes: true })) {
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
+ const from = path.join(src, entry.name);
+ const to = path.join(dst, entry.name);
+ try {
+ // Strip the legacy sentinel before moving — it's about to be meaningless in cloud/.
+ const sentinel = path.join(from, '_marketplace.json');
+ if (fs.existsSync(sentinel)) {
+ try { await fsp.rm(sentinel); } catch { /* ignore */ }
+ }
+ if (!fs.existsSync(to)) {
+ // Clean case: dst is free, single rename.
+ await fsp.rename(from, to);
+ count++;
+ continue;
+ }
+ // Merge case: dst already exists (typically a stub from an earlier broken delete that
+ // left behind only `skills/` or `meta/`). The OLD logic skipped the whole entry, which
+ // discarded the source's `agent.json` / `SKILL.md` when `data/builtin/` got wiped right
+ // after — that's how this machine lost 4 agents. Now we promote file-level merge: for
+ // each child the src dir owns, move it over IFF the dst doesn't already have one with
+ // that name. Same-name child collisions are still skipped (we'd rather keep dst's data).
+ const moved = await _mergeChildrenInto(from, to);
+ if (moved > 0) {
+ count++;
+ log.info(`merged ${moved} entry(ies) into existing ${kind} ${entry.name}`);
+ }
+ try { await fsp.rm(from, { recursive: true, force: true }); } catch { /* ignore */ }
+ } catch (err) {
+ log.warn(`mv ${from} → ${to} failed: ${(err as Error).message}`);
+ }
+ }
+ return count;
+}
+
+/** File-level merge helper: move every child of `srcDir` into `dstDir`, skipping names that
+ * dst already has. Returns the count of entries that landed in dst. Used by the migration
+ * when an `<id>/` stub already exists on the cloud side. */
+async function _mergeChildrenInto(srcDir: string, dstDir: string): Promise<number> {
+ let moved = 0;
+ for (const child of await fsp.readdir(srcDir, { withFileTypes: true })) {
+ if (child.name.startsWith('.')) continue;
+ const childFrom = path.join(srcDir, child.name);
+ const childTo = path.join(dstDir, child.name);
+ if (fs.existsSync(childTo)) {
+ log.warn(`merge skip ${childTo} (dst already has it)`);
+ continue;
+ }
+ try {
+ await fsp.rename(childFrom, childTo);
+ moved++;
+ } catch (err) {
+ log.warn(`merge mv ${childFrom} → ${childTo} failed: ${(err as Error).message}`);
+ }
+ }
+ return moved;
+}
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 9d59349b..a73fd4dd 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -77,6 +77,10 @@
<span class="chat-recipient-prefix" data-i18n="chat.recipient_label">To: </span>
<span class="chat-recipient-name" id="new-chat-recipient-name" data-i18n="chat.recipient_commander">Commander</span>
</button>
+ <div class="chat-skill-chip" id="new-chat-skill-chip" data-target="new-chat" style="display:none">
+ <span class="chip-label"></span>
+ <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>
+ </div>
<button type="button" class="chat-project-chip" id="new-chat-project-chip" data-i18n-title="chat.project_picker_title" title="Pick project">
<span class="chat-project-prefix" data-i18n="chat.project_label">Project: </span>
<span class="chat-project-name" id="new-chat-project-name" data-i18n="chat.project_none">None</span>
@@ -84,10 +88,6 @@
<polyline points="6 9 12 15 18 9"/>
</svg>
</button>
- <div class="chat-skill-chip" id="new-chat-skill-chip" data-target="new-chat" style="display:none">
- <span class="chip-label"></span>
- <span class="chip-close" data-i18n-title="chat.chip_remove_title" title="Remove">×</span>
- </div>
<input type="file" id="new-chat-attach-input" multiple style="display:none"
accept=".md,.markdown,.txt,.csv,.tsv,.json,.yaml,.yml,.log,.pdf,.docx,.png,.jpg,.jpeg,.webp,.gif,text/plain,text/markdown,text/csv,application/json,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,image/png,image/jpeg,image/webp,image/gif" />
<button id="new-chat-send-btn" class="chat-send-btn" data-i18n-title="new_chat.send_title" title="Send">
@@ -166,9 +166,12 @@
<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 class="header-actions">
+ <button class="btn btn-sm" id="create-skill-btn" data-i18n="skills.add">+ Add</button>
+ <button class="btn btn-sm" id="skills-more-btn" data-i18n="skills.more_btn">More</button>
+ </div>
</div>
+ <div class="marketplace-reconcile-banner" data-reconcile-banner style="display:none"></div>
<div class="skills-grid-scroll">
<div class="skills-group" id="skills-grid-custom-group" style="display:none">
<div class="skills-group-label" data-i18n="skills.custom_group">Custom</div>
@@ -185,14 +188,9 @@
<!-- Detail view (replaces grid when a card is opened) -->
<div class="skills-detail-view" id="skills-detail-view" style="display:none">
<div class="skills-detail-col" id="skills-detail-col">
- <div class="skills-detail-breadcrumb">
- <button type="button" class="skills-back-btn" id="skills-back-btn">
- <span aria-hidden="true">←</span>
- <span data-i18n="skills.back">Back to skills</span>
- </button>
- </div>
<div class="skills-detail-content" id="skills-detail-content" style="display:none">
<div class="skills-doc-headline">
+ <button type="button" class="btn btn-sm" id="skills-back-btn" data-i18n="common.back">Back</button>
<h1 class="skills-doc-title" id="skills-detail-name" data-editable="false"></h1>
<span class="skills-doc-source" id="skills-detail-source"></span>
<div class="skills-doc-actions" id="skills-detail-actions">
@@ -201,6 +199,9 @@
</button>
<button class="btn btn-sm" id="skill-edit-btn" data-i18n="skills.edit">Edit</button>
<button class="btn btn-sm" id="skill-enabled-btn" data-i18n="component.disable">Disable</button>
+
+ <button class="btn btn-sm" id="skill-promote-btn" style="display:none" data-i18n="skills.promote_to_builtin">Make built-in (dev)</button>
+ <button class="btn btn-sm" id="skill-upload-marketplace-btn" style="display:none" data-i18n="marketplace.upload">Upload to marketplace (dev)</button>
<button class="btn btn-sm btn-danger" id="skill-delete-btn" data-i18n="skills.delete">Delete</button>
</div>
</div>
@@ -260,9 +261,12 @@
<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 class="header-actions">
+ <button class="btn btn-sm" id="create-agent-btn" data-i18n="agents.create_btn">+ Create</button>
+ <button class="btn btn-sm" id="agents-more-btn" data-i18n="agents.more_btn">More</button>
+ </div>
</div>
+ <div class="marketplace-reconcile-banner" data-reconcile-banner style="display:none"></div>
<div class="agents-grid-scroll">
<div class="agents-group" id="agents-grid-custom-group" style="display:none">
<div class="agents-group-label" data-i18n="agents.custom_group">Custom</div>
@@ -279,15 +283,10 @@
<!-- Detail view (replaces grid when a card is opened) -->
<div class="agents-detail-view" id="agents-detail-view" style="display:none">
<div class="agents-detail-col" id="agents-detail-col">
- <div class="agents-detail-breadcrumb">
- <button type="button" class="agents-back-btn" id="agents-back-btn">
- <span aria-hidden="true">←</span>
- <span data-i18n="agents.back">Back to agents</span>
- </button>
- </div>
<div class="agents-detail-content" id="agents-detail-content" style="display:none">
<div class="agents-detail-header">
<div class="agents-detail-title-row">
+ <button type="button" class="btn btn-sm" id="agents-back-btn" data-i18n="common.back">Back</button>
<span class="agents-detail-avatar-slot" id="agents-detail-avatar"></span>
<div class="agents-detail-name" id="agents-detail-name" contenteditable="false"></div>
<span class="agents-detail-source" id="agents-detail-source"></span>
@@ -297,6 +296,9 @@
</button>
<button class="btn btn-sm" id="agent-edit-btn" data-i18n="agents.edit_btn_edit">Edit</button>
<button class="btn btn-sm" id="agent-enabled-btn" data-i18n="component.disable">Disable</button>
+
+ <button class="btn btn-sm" id="agent-promote-btn" style="display:none" data-i18n="agents.promote_to_builtin">Make built-in (dev)</button>
+ <button class="btn btn-sm" id="agent-upload-marketplace-btn" style="display:none" data-i18n="marketplace.upload">Upload to marketplace (dev)</button>
<button class="btn btn-sm btn-danger" id="agent-delete-btn" data-i18n="agents.delete">Delete</button>
</div>
</div>
@@ -341,6 +343,40 @@
</div>
</section>
+ <!-- Marketplace (entered via the More button on agents / skills tabs;
+ closes back to its origin view via openMarketplace's return-stack).
+ Two sub-views — grid (browse + categories) and detail (full content + install). -->
+ <section class="panel" id="panel-marketplace">
+ <!-- Grid view (default) -->
+ <div class="marketplace-grid-view" id="marketplace-grid-view">
+ <div class="marketplace-header">
+ <button type="button" class="btn btn-sm" data-mp-close data-i18n="common.back">Back</button>
+ <div class="marketplace-tabs">
+ <button type="button" class="marketplace-tab" data-mp-tab="agent" data-i18n="marketplace.tab_agent">Agents</button>
+ <button type="button" class="marketplace-tab" data-mp-tab="skill" data-i18n="marketplace.tab_skill">Skills</button>
+ </div>
+ <input type="text" class="marketplace-search" data-mp-search data-i18n-placeholder="marketplace.search_ph" />
+ </div>
+ <div class="marketplace-categories" data-mp-categories></div>
+ <div class="marketplace-body" data-mp-body></div>
+ </div>
+
+ <!-- Detail view (replaces grid when a card is clicked) -->
+ <div class="marketplace-detail-view" id="marketplace-detail-view" style="display:none">
+ <div class="marketplace-detail-header">
+ <button type="button" class="btn btn-sm" data-mp-detail-back data-i18n="common.back">Back</button>
+ <span class="marketplace-detail-avatar-slot" data-mp-detail-avatar></span>
+ <div class="marketplace-detail-title-wrap">
+ <span class="marketplace-detail-title" data-mp-detail-name></span>
+ <span class="marketplace-detail-meta-row" data-mp-detail-meta></span>
+ </div>
+ <button type="button" class="btn btn-sm btn-primary" data-mp-detail-install></button>
+ <button type="button" class="btn btn-sm btn-danger" data-mp-detail-delete style="display:none" data-i18n="marketplace.delete">Delete (dev)</button>
+ </div>
+ <div class="marketplace-detail-body" data-mp-detail-body></div>
+ </div>
+ </section>
+
<!-- Project detail (bindings + future per-project assets) -->
<section class="panel" id="panel-project">
<div class="project-detail-view">
@@ -618,6 +654,10 @@
<label data-i18n="agent_modal.name">Name</label>
<input type="text" id="agent-name-input" data-i18n-placeholder="agent_modal.name_placeholder" placeholder="e.g. Code Review Assistant" />
</div>
+ <div class="form-row">
+ <label data-i18n="agent_modal.category">Category</label>
+ <div class="ai-select" id="agent-category-select"></div>
+ </div>
<div class="form-row">
<label><span data-i18n="agent_modal.desc">Summary</span> <span class="form-hint" data-i18n="agent_modal.desc_hint">One line on what it does — the AI will generate a workflow from this</span></label>
<textarea id="agent-desc-input" rows="4" data-i18n-placeholder="agent_modal.desc_placeholder" placeholder="e.g. Review my code before commit, focus on logic bugs and security issues..."></textarea>
@@ -637,6 +677,10 @@
<label data-i18n="agent_modal.ext_name">Name</label>
<input type="text" id="agent-ext-name-input" data-i18n-placeholder="agent_modal.ext_name_placeholder" placeholder="e.g. Claude Code" />
</div>
+ <div class="form-row">
+ <label data-i18n="agent_modal.category">Category</label>
+ <div class="ai-select" id="agent-ext-category-select"></div>
+ </div>
<div class="form-row">
<label data-i18n="agent_modal.ext_desc">Summary</label>
<textarea id="agent-ext-desc-input" rows="4" data-i18n-placeholder="agent_modal.ext_desc_placeholder" placeholder="(auto-filled when a CLI is picked; can be overridden)"></textarea>
@@ -670,6 +714,10 @@
<label><span data-i18n="skill_modal.name">Name (English)</span><span class="form-hint" data-i18n="skill_modal.name_hint">Starts with a letter; digits, -, _, and one space allowed</span></label>
<input type="text" id="skill-name" data-i18n-placeholder="skill_modal.name_placeholder" placeholder="e.g. web-summary" />
</div>
+ <div class="form-row">
+ <label data-i18n="skill_modal.category">Category</label>
+ <div class="ai-select" id="skill-category-select"></div>
+ </div>
<div class="form-row">
<label data-i18n="skill_modal.description">Summary</label>
<textarea id="skill-description" rows="4" data-i18n-placeholder="skill_modal.desc_placeholder" placeholder="One line on what this skill does and when to use it..."></textarea>
@@ -857,6 +905,7 @@
<script src="./modules/agent-schedule.js"></script>
<script src="./modules/utils.js"></script>
<script src="./modules/marketplace.js"></script>
+ <script src="./modules/marketplace_dev.js"></script>
<!--
MathJax v3.2.2 — TeX → CommonHTML.
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index 3b8465c4..666b4bfe 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -201,7 +201,7 @@
"skills.add": "+ Add",
"skills.more_btn": "More",
"skills.custom_group": "Custom",
- "skills.builtin_group": "Built-in",
+ "skills.builtin_group": "Platform",
"skills.empty": "No skills yet",
"skills.use": "Use",
"skills.edit": "Edit",
@@ -209,6 +209,7 @@
"skills.use_tooltip": "Use this skill",
"skills.more_actions": "More actions",
"skills.back": "Back to skills",
+ "common.back": "Back",
"skills.label_summary": "Summary",
"skills.label_extra": "Other attributes",
"skills.label_usage": "Usage",
@@ -250,7 +251,7 @@
"agents.more_btn": "More",
"agents.empty": "No agents yet",
"agents.custom_group": "Custom",
- "agents.builtin_group": "Built-in",
+ "agents.builtin_group": "Platform",
"agents.back": "Back to agents",
"agents.use": "Use",
"agents.use_tooltip": "Use this agent",
@@ -597,6 +598,7 @@
"agent_modal.tab_create": "Create",
"agent_modal.tab_external": "External",
"agent_modal.name": "Name",
+ "agent_modal.category": "Category",
"agent_modal.name_placeholder": "e.g. Code Review Assistant",
"agent_modal.desc": "Summary",
"agent_modal.desc_hint": "One line on what it does — the AI will generate a workflow from this",
@@ -626,6 +628,7 @@
"skill_modal.title_create": "New skill",
"skill_modal.title_edit": "Edit skill",
"skill_modal.name": "Name (English)",
+ "skill_modal.category": "Category",
"skill_modal.name_hint": "Starts with a letter; digits, -, _, and one space allowed",
"skill_modal.name_placeholder": "e.g. web-summary",
"skill_modal.description": "Summary",
@@ -730,14 +733,19 @@
"marketplace.install": "Install",
"marketplace.installed": "Installed",
"marketplace.installing": "Installing…",
+ "marketplace.uninstall": "Uninstall",
+ "marketplace.uninstalling": "Uninstalling…",
+ "marketplace.uninstall_ok": "Uninstalled",
+ "marketplace.uninstall_failed": "Uninstall failed: {reason}",
"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.back": "Back",
"marketplace.version": "v{version}",
- "marketplace.upload": "Upload to marketplace",
+ "marketplace.upload": "Upload to marketplace (dev)",
"marketplace.upload_title": "Upload to marketplace",
"marketplace.upload_category": "Category",
"marketplace.upload_version": "Version",
@@ -745,5 +753,21 @@
"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)."
+ "marketplace.err_no_permission": "No permission to upload (server-side phone whitelist).",
+ "marketplace.err_no_category": "Set a category in the create dialog first.",
+ "marketplace.delete": "Delete (dev)",
+ "marketplace.delete_confirm_title": "Delete marketplace item",
+ "marketplace.delete_confirm_msg": "Delete {kind} \"{name}\"?\nThe server DB row and COS blob will be wiped. This is irreversible.",
+ "marketplace.delete_ok": "Deleted",
+ "marketplace.delete_failed": "Delete failed: {reason}",
+ "marketplace.deleting": "Deleting…",
+ "marketplace.upload_version_prompt": "Enter version",
+ "marketplace.upload_default_install": "Install by default (use sparingly)",
+ "marketplace.upload_loading": "Uploading {kind} to platform…",
+ "marketplace.detail_loading": "Loading details…",
+ "marketplace.list_loading": "Loading marketplace…",
+ "marketplace.author_platform": "Official",
+ "marketplace.author_user": "by {uid}",
+ "marketplace.reconcile_running": "Syncing marketplace resources {pulled}/{total}…",
+ "marketplace.reconcile_partial": "Marketplace sync done; {failed} failed, will retry on next launch"
}
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index 05ae5b91..ecefa436 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -201,7 +201,7 @@
"skills.add": "+ 添加",
"skills.more_btn": "更多",
"skills.custom_group": "自定义",
- "skills.builtin_group": "内置",
+ "skills.builtin_group": "平台",
"skills.empty": "暂无技能",
"skills.use": "使用",
"skills.edit": "编辑",
@@ -209,6 +209,7 @@
"skills.use_tooltip": "使用此技能",
"skills.more_actions": "更多操作",
"skills.back": "返回技能库",
+ "common.back": "返回",
"skills.label_summary": "简介",
"skills.label_extra": "其他属性",
"skills.label_usage": "使用说明",
@@ -250,7 +251,7 @@
"agents.more_btn": "更多",
"agents.empty": "暂无智能体",
"agents.custom_group": "自定义",
- "agents.builtin_group": "内置",
+ "agents.builtin_group": "平台",
"agents.back": "返回智能体",
"agents.use": "使用",
"agents.use_tooltip": "使用此智能体",
@@ -597,6 +598,7 @@
"agent_modal.tab_create": "创建",
"agent_modal.tab_external": "外接",
"agent_modal.name": "名称",
+ "agent_modal.category": "分类",
"agent_modal.name_placeholder": "例如:代码审查助手",
"agent_modal.desc": "简介",
"agent_modal.desc_hint": "一句话说明用途,创建后 AI 会基于此生成工作流程",
@@ -626,6 +628,7 @@
"skill_modal.title_create": "新建技能",
"skill_modal.title_edit": "编辑技能",
"skill_modal.name": "名称(英文)",
+ "skill_modal.category": "分类",
"skill_modal.name_hint": "字母开头,可含数字/-/_ 和单个空格",
"skill_modal.name_placeholder": "例如:web-summary",
"skill_modal.description": "简介",
@@ -730,14 +733,19 @@
"marketplace.install": "安装",
"marketplace.installed": "已安装",
"marketplace.installing": "安装中…",
+ "marketplace.uninstall": "卸载",
+ "marketplace.uninstalling": "卸载中…",
+ "marketplace.uninstall_ok": "已卸载",
+ "marketplace.uninstall_failed": "卸载失败:{reason}",
"marketplace.search_ph": "搜索",
"marketplace.empty": "暂无内容",
"marketplace.load_failed": "加载失败",
"marketplace.install_ok": "安装成功",
"marketplace.install_failed": "安装失败:{reason}",
"marketplace.close": "关闭",
+ "marketplace.back": "返回",
"marketplace.version": "v{version}",
- "marketplace.upload": "上传到官方平台",
+ "marketplace.upload": "上传平台(开发)",
"marketplace.upload_title": "上传到官方平台",
"marketplace.upload_category": "分类",
"marketplace.upload_version": "版本",
@@ -745,5 +753,21 @@
"marketplace.upload_ok": "上传成功",
"marketplace.upload_failed": "上传失败:{reason}",
"marketplace.err_not_dev": "上传仅支持开发版本。",
- "marketplace.err_no_permission": "无上传权限(需要服务端手机白名单)。"
+ "marketplace.err_no_permission": "无上传权限(需要服务端手机白名单)。",
+ "marketplace.err_no_category": "请先在创建对话框里给该项设置分类。",
+ "marketplace.delete": "删除(开发)",
+ "marketplace.delete_confirm_title": "删除平台内容",
+ "marketplace.delete_confirm_msg": "确定要删除 {kind} \"{name}\" 吗?\n服务端数据库 + 云存储一并删除,不可恢复。",
+ "marketplace.delete_ok": "已删除",
+ "marketplace.delete_failed": "删除失败:{reason}",
+ "marketplace.deleting": "删除中…",
+ "marketplace.upload_version_prompt": "请输入版本号",
+ "marketplace.upload_default_install": "用户默认安装(谨慎选择)",
+ "marketplace.upload_loading": "正在上传{kind}到平台…",
+ "marketplace.detail_loading": "加载详情…",
+ "marketplace.list_loading": "加载市场内容…",
+ "marketplace.author_platform": "官方",
+ "marketplace.author_user": "作者 {uid}",
+ "marketplace.reconcile_running": "正在同步市场资源 {pulled}/{total}…",
+ "marketplace.reconcile_partial": "市场同步完成,{failed} 项失败,下次启动会自动重试"
}
diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.js
index 5bd493c1..5411f9c3 100644
--- a/src/renderer/modules/agents.js
+++ b/src/renderer/modules/agents.js
@@ -29,6 +29,41 @@ function _isReservedAgentName(name) {
return _RESERVED_AGENT_NAMES.has(key);
}
+/** Version + category + author chips for a marketplace-installed agent. Mirrors the
+ * marketplace card footer so users see the same metadata in the agents grid.
+ * `_mpCategoriesCache` is a module-level variable in `marketplace.js` (flat top-level
+ * scope per CLAUDE.md §8). Author chip: `create_uid='0'` → 官方 badge; non-zero → user badge. */
+function _agentPlatformChipsHtml(a) {
+ const lang = getLang();
+ const parts = [];
+ if (a.version) {
+ const versionLabel = t('marketplace.version').replace('{version}', String(a.version));
+ parts.push(`<span class="agent-card-chip is-version">${escapeHtml(versionLabel)}</span>`);
+ }
+ if (a.category) {
+ const catLabel = _resolveCategoryLabel(a.category, lang);
+ parts.push(`<span class="agent-card-chip">${escapeHtml(catLabel)}</span>`);
+ }
+ if (a.create_uid) {
+ const isPlatform = String(a.create_uid) === '0';
+ const label = isPlatform ? t('marketplace.author_platform') : t('marketplace.author_user').replace('{uid}', String(a.create_uid));
+ const cls = isPlatform ? 'agent-card-chip is-platform' : 'agent-card-chip is-user';
+ parts.push(`<span class="${cls}">${escapeHtml(label)}</span>`);
+ }
+ return parts.join('');
+}
+
+/** Shared category-code → localized label. Falls back to the code when the categories
+ * cache hasn't loaded yet (rare; the module-level preload usually populates it before
+ * the user reaches the agents/skills tab). */
+function _resolveCategoryLabel(code, lang) {
+ if (!code) return '';
+ const list = (typeof _mpCategoriesCache !== 'undefined' && _mpCategoriesCache) || [];
+ const c = list.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);
+}
+
// Mirror of `agents.ts::NAME_TOKEN_RE` so the form rejects junk before
// the round-trip. Charset must round-trip through the bus's @-mention
// regex; see backend for the full reasoning. UIs may still surface
@@ -154,6 +189,10 @@ function renderAgentsGrid(agents) {
const cliChip = (a.runtime && a.runtime.kind === 'cli')
? `<span class="agent-card-chip is-cli is-cli-${escapeHtml(a.runtime.cli)}">${escapeHtml(_cliBadgeLabel(a.runtime.cli))}</span>`
: '';
+ // Marketplace-installed (`builtin`) agents carry version + category from _install.json /
+ // agent.json — show them as inline chips so users see "where this came from" without
+ // opening the detail page. Custom agents skip — they have no published version.
+ const platformChips = a.source === 'builtin' ? _agentPlatformChipsHtml(a) : '';
return `
<div class="agent-card${enabled ? '' : ' is-disabled'}" data-id="${escapeHtml(a.agent_id)}" data-source="${a.source}">
<div class="agent-card-header">
@@ -163,7 +202,7 @@ function renderAgentsGrid(agents) {
</div>
<div class="${descClass}">${escapeHtml(descText)}</div>
<div class="agent-card-actions">
- ${cliChip}
+ ${cliChip}${platformChips}
<button type="button" class="agent-card-use" data-agent-use title="${useTitle}" aria-label="${useTitle}">
<svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
</button>
@@ -344,11 +383,21 @@ function _renderAgentRowMenuItems(menu, agentId) {
if (canEdit) {
items.push(`<div class="agent-row-menu-item" data-action="edit">${escapeHtml(t('agents.edit'))}</div>`);
}
+ if (isCustom && false) {
+ items.push(`<div class="agent-row-menu-item" data-action="promote">${escapeHtml(t('agents.promote_to_builtin'))}</div>`);
+ }
+ // Upload-to-marketplace is owned by marketplace_dev.js (renderer-side dev module). OrkasOpen
+ // doesn't ship that file, so `typeof openMarketplaceUpload === 'function'` is false there
+ // and the menu item simply doesn't appear — no isDevMode check needed (and would be banned
+ // by OrkasOpen's strip-rules anyway).
+ if (typeof openMarketplaceUpload === 'function') {
+ items.push(`<div class="agent-row-menu-item" data-action="upload-marketplace">${escapeHtml(t('marketplace.upload'))}</div>`);
+ }
// Scheduled tasks: available for every agent (custom + builtin) — a
// 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()) {
+ if (isCustom && false) {
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>`);
}
@@ -417,6 +466,38 @@ async function selectAgent(agentId) {
}
}
+// Render the header meta strip for a single agent / skill detail. Used by both
+// `agents.js::_renderAgentDetail` and `skills.js::useSkill`. Three forms:
+// - custom item: single "自定义" chip (kept for symmetry with prior chrome)
+// - marketplace-installed item: category chip + author chip ("官方" if uid=0, else "作者 X")
+// — replaces the old "内置" label which users found unfriendly
+// - unknown create_uid (older `_install.json` pre-author-tracking): only the category chip
+// `item.source` distinguishes custom vs marketplace-installed; `item.category` (code) maps
+// to display name via `_mpCategoriesCache` (loaded at marketplace boot, hot in localStorage).
+function _renderSourceMetaHtml(item) {
+ if (!item) return '';
+ if (item.source === 'custom') {
+ return `<span class="agents-detail-source is-custom">${escapeHtml(t('agents.source_custom'))}</span>`;
+ }
+ const parts = [];
+ const catCode = String(item.category || '').trim();
+ if (catCode) {
+ const lang = (typeof getLang === 'function') ? getLang() : 'zh';
+ const cat = Array.isArray(_mpCategoriesCache) ? _mpCategoriesCache.find((c) => c.code === catCode) : null;
+ const label = cat ? (lang === 'zh' ? (cat.name_zh || cat.name_en || catCode) : (cat.name_en || cat.name_zh || catCode)) : catCode;
+ parts.push(`<span class="agents-detail-source is-category">${escapeHtml(label)}</span>`);
+ }
+ const uid = String(item.create_uid || '').trim();
+ if (uid) {
+ if (uid === '0') {
+ parts.push(`<span class="agents-detail-source is-platform">${escapeHtml(t('marketplace.author_platform'))}</span>`);
+ } else {
+ parts.push(`<span class="agents-detail-source is-user">${escapeHtml(t('marketplace.author_user').replace('{uid}', uid))}</span>`);
+ }
+ }
+ return parts.join('');
+}
+
function _renderAgentDetail(agent, editing) {
document.getElementById('agents-detail-content').style.display = '';
@@ -427,8 +508,10 @@ function _renderAgentDetail(agent, editing) {
const editBtn = document.getElementById('agent-edit-btn');
nameEl.textContent = agent.name || '';
- sourceEl.textContent = agent.source === 'builtin' ? t('agents.source_builtin') : t('agents.source_custom');
- sourceEl.className = 'agents-detail-source ' + (agent.source === 'builtin' ? 'is-builtin' : 'is-custom');
+ // Header chips: custom = single "自定义" tag; marketplace-installed (source=builtin) drops
+ // the "内置" wording entirely and shows {category} + {官方/作者} chips instead — same family
+ // as marketplace card meta. Empty category / missing create_uid silently skip.
+ sourceEl.innerHTML = _renderSourceMetaHtml(agent);
// Runtime slot lives at the top of the body now (not the header):
// an always-editable dropdown so the user can flip Orkas ↔ local CLI
// without entering edit mode. The header chip was removed because
@@ -461,11 +544,18 @@ function _renderAgentDetail(agent, editing) {
// "edit" button).
const useBtn = document.getElementById('agent-use-btn');
const enableBtn = document.getElementById('agent-enabled-btn');
+
+ const promoteBtn = document.getElementById('agent-promote-btn');
+ const uploadBtn = document.getElementById('agent-upload-marketplace-btn');
const delBtn = document.getElementById('agent-delete-btn');
const isCustom = agent.source === 'custom';
const canEdit = isCustom;
if (useBtn) useBtn.style.display = editing ? 'none' : '';
if (enableBtn) enableBtn.style.display = editing ? 'none' : '';
+
+ if (promoteBtn) promoteBtn.style.display = (isCustom && false && !editing) ? '' : 'none';
+ // Upload button visibility: gated by marketplace_dev.js's presence (OrkasOpen lacks it).
+ if (uploadBtn) uploadBtn.style.display = (typeof openMarketplaceUpload === 'function' && !editing) ? '' : 'none';
if (delBtn) delBtn.style.display = (canEdit && !editing) ? '' : 'none';
if (editBtn) {
editBtn.style.display = canEdit ? '' : 'none';
@@ -603,7 +693,7 @@ function _renderAgentDetailAvatar(agent) {
if (!slot) return;
const isCustom = agent.source === 'custom';
slot.innerHTML = renderAvatarHtml(agent.icon, agent.color, {
- size: 44,
+ size: 32,
seed: agent.agent_id,
clickable: isCustom,
extraClass: 'agents-detail-avatar',
@@ -928,6 +1018,12 @@ function openAgentModal() {
mountExternalCliSelect((cli) => _applyExternalCliDefaults(cli)).catch(() => {});
}
+ // Marketplace category dropdowns (both tabs). 24h cached in main, fallback to defaults.
+ if (typeof mountMarketplaceCategorySelect === 'function') {
+ mountMarketplaceCategorySelect('agent-category-select').catch(() => {});
+ mountMarketplaceCategorySelect('agent-ext-category-select').catch(() => {});
+ }
+
modal.classList.add('open');
setTimeout(() => document.getElementById('agent-name-input')?.focus(), 50);
}
@@ -975,9 +1071,11 @@ async function _saveCreateAgent({ msgEl }) {
return;
}
+ const category = document.getElementById('agent-category-select')?.dataset.value || '';
+
try {
const avatar = randomAgentAvatar();
- const body = { name, description, icon: avatar.icon, color: avatar.color };
+ const body = { name, description, icon: avatar.icon, color: avatar.color, category };
const res = await apiFetch('/api/agents/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -1046,6 +1144,8 @@ async function _saveExternalAgent({ msgEl }) {
const description_zh = lang === 'zh' ? desc : (defaults ? defaults.description_zh : desc);
const description_en = lang === 'en' ? desc : (defaults ? defaults.description_en : desc);
+ const category = document.getElementById('agent-ext-category-select')?.dataset.value || '';
+
try {
const avatar = randomAgentAvatar();
const body = {
@@ -1054,6 +1154,7 @@ async function _saveExternalAgent({ msgEl }) {
description_zh, description_en,
icon: avatar.icon, color: avatar.color,
runtime: { kind: 'cli', cli },
+ category,
};
const res = await apiFetch('/api/agents/create', {
method: 'POST',
diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.js
index e8bb4641..eb3d6776 100644
--- a/src/renderer/modules/boot.js
+++ b/src/renderer/modules/boot.js
@@ -147,6 +147,7 @@ function setView(view, cid, opts = {}) {
: view === 'apps' ? 'panel-apps'
: view === 'settings' ? 'panel-settings'
: view === 'project' ? 'panel-project'
+ : view === 'marketplace' ? 'panel-marketplace'
: 'panel-conversation';
document.getElementById(panelId).classList.add('active');
diff --git a/src/renderer/modules/marketplace.js b/src/renderer/modules/marketplace.js
index e2a88da5..ec5de1e5 100644
--- a/src/renderer/modules/marketplace.js
+++ b/src/renderer/modules/marketplace.js
@@ -1,166 +1,543 @@
-// ─── Marketplace overlay ───
+// ─── Marketplace (full-page panel: grid + detail sub-views) ───
// 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.
+// Two sub-views inside panel-marketplace (mirrors the agents / skills panel shape):
+// - grid-view : tab switcher + categories + card grid
+// - detail-view : per-item content (workflow / SKILL.md + file list) with Install button
+//
+// Cache contract (see features/marketplace_cache.ts):
+// - Detail-page reads hit the cache first; main fetches via the spec / bundle endpoint when
+// cache stale / missing and writes back. Install reads from cache too.
+// - openMarketplace() runs sweepCache() once on entry — 100 MB / 7d eviction.
+//
+// Per-card 安装 button (in detail) materializes the cached item into the local
+// `data/builtin/{agents,skills}/` tree with a `_marketplace.json` sentinel.
+//
+// Dev-only upload (`openMarketplaceUpload`) is exposed for agents.js / skills.js (⋯ menu +
+// detail-page actions). Category is NO LONGER asked — it lives in the spec now (agent.json
+// `category` field / SKILL.md `category` frontmatter).
-let _mpOverlay = null;
let _mpState = null;
+let _mpBound = false;
+let _mpReturnView = 'agents';
+
+// Renderer-side in-memory cache of the category registry. Main also caches in-memory + on disk
+// + boots with primeCategoryCache so the very first openMarketplace finds main's cache hot;
+// keeping a copy here too avoids paying the IPC roundtrip when the panel reopens within the
+// same session. Cleared on i18n-change is unnecessary — the API surface doesn't include the
+// translated labels (locale picking happens at render time in _mpCategoryLabel).
+// Categories are read on every panel open. Caching at three levels (renderer in-mem ↑↑↑
+// localStorage ↑↑ main biz file ↑) so the first openMarketplace after PC launch finds the
+// chip strip painted *synchronously* — no IPC roundtrip latency. localStorage is sync and
+// available before window.orkas IPC is ready; the in-memory variable is the hot path; the
+// async preload below refreshes localStorage in the background.
+const MP_CATEGORIES_LS_KEY = 'orkas:mp:categories';
+let _mpCategoriesCache = (() => {
+ try {
+ const raw = localStorage.getItem(MP_CATEGORIES_LS_KEY);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ return Array.isArray(parsed) ? parsed : null;
+ } catch { return null; }
+})();
+
+// Installed-state cache (synchronous via localStorage). Without this, every panel open
+// waits 1-2s for `agents.list` / `skills.list` IPCs before card buttons can show "已安装";
+// users see all cards flash "Install" first. The cache is updated after each successful
+// install/uninstall + after every successful background `agents.list` / `skills.list` refresh.
+const MP_INSTALLED_LS_KEY = 'orkas:mp:installed';
+function _mpLoadInstalledFromLs() {
+ try {
+ const raw = localStorage.getItem(MP_INSTALLED_LS_KEY);
+ if (!raw) return { agentIds: new Set(), skillIds: new Set() };
+ const parsed = JSON.parse(raw);
+ return {
+ agentIds: new Set(Array.isArray(parsed?.agentIds) ? parsed.agentIds : []),
+ skillIds: new Set(Array.isArray(parsed?.skillIds) ? parsed.skillIds : []),
+ };
+ } catch { return { agentIds: new Set(), skillIds: new Set() }; }
+}
+function _mpPersistInstalled() {
+ try {
+ localStorage.setItem(MP_INSTALLED_LS_KEY, JSON.stringify({
+ agentIds: [..._mpState.installedAgentIds],
+ skillIds: [..._mpState.installedSkillIds],
+ }));
+ } catch { /* ignore */ }
+}
-const MP_PAGE_SIZE = 100;
+// Latest reconcile snapshot pushed from main (boot-time marketplace install reconcile).
+// Bootstrap subscription runs at module load — see _mpInitReconcileWatch() — so a hot reconcile
+// transitioning to `running` reaches the panel even if the user opens it mid-fetch.
+let _mpReconcileStatus = { state: 'idle', total: 0, pulled: 0 };
-function isMarketplaceOpen() { return !!_mpOverlay; }
+// Paginated listings cache (cross-process via main `marketplace.{get,set}ListingsCache`).
+// Key = `${kind}|${category||''}|${q||''}`. Value:
+// { items, ts, nextPage, exhausted }
+// Where `items` accumulates across pages (deduped by id), `nextPage` is the next page-num to
+// request on infinite-scroll, and `exhausted` flips true once a /list response is shorter
+// than `MP_LISTINGS_PAGE_SIZE` or covers `total`.
+//
+// SWR semantics (matches user expectation "切 tab/category 仍发请求,只是优先用缓存"):
+// - Switching tab / category / opening panel:
+// * Hydrate cache immediately so the grid renders prior items (no blank flash).
+// * Always re-fetch page 1 in the background to overwrite stale rows.
+// - Infinite scroll: when the sentinel near the grid bottom enters the viewport, fetch
+// page = cached.nextPage and APPEND (dedupe by id) — never overwrite earlier pages.
+// - "All" tab (category = '') feeds rows into per-category cache slots so a subsequent
+// "教育" tab open paints fast. The reverse (cat slot → "All") is NOT done — All needs
+// a fresh time-ordered slice from the server.
+const MP_LISTINGS_PAGE_SIZE = 50;
+const _mpListingsCache = new Map();
+let _mpListingsHydrated = false;
+function _mpListingsKey(kind, category, q) { return `${kind}|${category || ''}|${q || ''}`; }
+
+async function _mpHydrateListingsCache() {
+ if (_mpListingsHydrated) return;
+ _mpListingsHydrated = true;
+ try {
+ const data = await window.orkas.invoke('marketplace.getListingsCache');
+ const entries = data?.entries || {};
+ for (const [k, v] of Object.entries(entries)) {
+ if (v && Array.isArray(v.items) && typeof v.ts === 'number') {
+ _mpListingsCache.set(k, { items: v.items, ts: v.ts });
+ }
+ }
+ } catch { /* no cache yet — first run */ }
+}
+
+function _mpPersistListingsCache() {
+ // Fire-and-forget: serialization happens in main. Renderer just snapshots the Map.
+ const entries = {};
+ for (const [k, v] of _mpListingsCache.entries()) entries[k] = v;
+ window.orkas.invoke('marketplace.setListingsCache', { entries }).catch(() => { /* ignore */ });
+}
+
+
+function isMarketplaceOpen() {
+ return document.getElementById('panel-marketplace')?.classList.contains('active') === true;
+}
async function openMarketplace(initialTab = 'agent') {
- if (_mpOverlay) {
- _mpState.tab = initialTab;
- _mpRender();
- return;
- }
+ const panel = document.getElementById('panel-marketplace');
+ if (!panel) return;
+
+ // Kick off the reconcile watcher on first marketplace open (rather than at script load) so
+ // we don't fire IPC during early renderer init. Idempotent on later calls.
+ _mpInitReconcileWatch();
+ // Hydrate persisted listings cache before first render — populates the in-memory Map so
+ // `_mpHydrateFromCache` below finds entries even on a cold app start.
+ await _mpHydrateListingsCache();
+
+ _mpReturnView = (typeof currentView === 'string' && currentView !== 'marketplace')
+ ? currentView : 'agents';
+
_mpState = {
+ view: 'grid',
tab: initialTab === 'skill' ? 'skill' : 'agent',
category: '',
q: '',
agents: [],
skills: [],
- categories: [],
- installedAgentIds: new Set(),
- installedSkillIds: new Set(),
+ // Pre-populate categories from the renderer cache so the chip strip renders on first
+ // paint — no waiting on IPC. If cache is cold, this stays [] and gets filled by _mpLoadAll
+ // before the listings come back.
+ categories: _mpCategoriesCache || [],
+ // Seed installed-state from the localStorage cache so card buttons show the right label
+ // on first paint. The IPC `agents.list` / `skills.list` will overwrite once it resolves
+ // (and persist the updated set back to localStorage).
+ ...(() => {
+ const cached = _mpLoadInstalledFromLs();
+ return { installedAgentIds: cached.agentIds, installedSkillIds: cached.skillIds };
+ })(),
loading: true,
- installing: new Set(), // ids currently being installed (button shows spinner state)
+ installing: new Set(),
error: '',
+ // Detail-view scratchpad
+ detailKind: null,
+ detailItem: null,
+ detailLoading: false,
+ detailError: '',
+ detailAgentJson: null,
+ detailSkillFiles: [],
+ detailSkillSelected: 'SKILL.md',
+ detailSkillFileText: '',
};
- _mpOverlay = _mpBuildOverlay();
- document.body.appendChild(_mpOverlay);
- window.addEventListener('i18n-change', _mpOnI18n);
- await _mpLoadAll();
+
+ if (!_mpBound) {
+ _mpBindPanel(panel);
+ window.addEventListener('i18n-change', _mpOnI18n);
+ document.addEventListener('keydown', _mpKey, true);
+ _mpBound = true;
+ }
+
+ if (typeof setView === 'function') setView('marketplace');
+ _mpShowGridView();
_mpRender();
+
+ // Best-effort sweep — never block UI on a failure.
+ window.orkas.invoke('marketplace.sweepCache').catch(() => { /* ignore */ });
+
+ // Fire-and-forget: `_mpLoadAll` paints cache + fresh data internally via its own
+ // `_mpRender` calls. Awaiting here would only delay returning control to the user.
+ _mpLoadAll();
}
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) => {
+ if (!isMarketplaceOpen()) return;
+ if (typeof setView === 'function') setView(_mpReturnView || 'agents');
+}
+
+function _mpOnI18n() { if (isMarketplaceOpen()) _mpRender(); }
+
+function _mpKey(e) {
+ if (e.key !== 'Escape' || !isMarketplaceOpen()) return;
+ if (e.isComposing || e.keyCode === 229) return;
+ if (_mpState?.view === 'detail') {
+ e.stopPropagation();
+ _mpShowGridView();
+ _mpRender();
+ } else {
+ closeMarketplace();
+ }
+}
+
+function _mpShowGridView() {
+ document.getElementById('marketplace-grid-view').style.display = '';
+ document.getElementById('marketplace-detail-view').style.display = 'none';
+ if (_mpState) _mpState.view = 'grid';
+}
+
+function _mpShowDetailView() {
+ document.getElementById('marketplace-grid-view').style.display = 'none';
+ document.getElementById('marketplace-detail-view').style.display = '';
+ if (_mpState) _mpState.view = 'detail';
+}
+
+// Initialize on module load: snapshot current state via IPC, then subscribe to push-events.
+// Order matters — if we subscribed first the snapshot could land before the push handler is
+// attached and we'd miss in-flight progress. Idempotent: only the first call performs setup.
+let _mpReconcileWatchStarted = false;
+async function _mpInitReconcileWatch() {
+ if (_mpReconcileWatchStarted) return;
+ _mpReconcileWatchStarted = true;
+ try {
+ const initial = await window.orkas.invoke('marketplace.reconcileStatus');
+ if (initial) _mpReconcileStatus = initial;
+ } catch { /* main not ready yet — push event will fill us in */ }
+ try {
+ let lastState = _mpReconcileStatus.state;
+ window.orkas.onPushEvent('marketplace:reconcile-status', (status) => {
+ if (!status) return;
+ const prevState = lastState;
+ _mpReconcileStatus = status;
+ lastState = status.state;
+ // Auto-hide a finished banner after 3s so a successful reconcile doesn't linger.
+ if (status.state === 'done') {
+ setTimeout(() => {
+ if (_mpReconcileStatus === status) {
+ _mpReconcileStatus = { ...status, state: 'idle' };
+ _mpUpdateReconcileBanner();
+ }
+ }, 3000);
+ }
+ _mpUpdateReconcileBanner();
+ // Reconcile just pulled new content into install dirs. Refresh the agents / skills /
+ // marketplace-installed-state caches so the new items appear without the user having to
+ // switch tabs. Force re-fetch (loadAgents(true) / loadSkills(true)) bypasses the renderer
+ // module-level lists cache; the marketplace listed-state hydrates from those.
+ if (status.state === 'done' && prevState === 'running' && status.pulled > 0) {
+ try { if (typeof loadAgents === 'function') loadAgents(true); } catch { /* ignore */ }
+ try { if (typeof loadSkills === 'function') loadSkills(true); } catch { /* ignore */ }
+ // If marketplace panel is open right now, also re-run the install-state hydration
+ // so card buttons flip from "安装" to "已安装" without a tab switch.
+ if (isMarketplaceOpen()) _mpLoadAll();
+ }
+ });
+ } catch { /* push channel not allowed (shouldn't happen) — silently degrade to no banner */ }
+}
+
+// Updates ALL banners with `data-reconcile-banner` (marketplace panel + agents-grid-view +
+// skills-grid-view). User opens any of those tabs during reconcile → sees same status, no
+// "panel looks empty, what happened" confusion. Each panel embeds its own banner div via
+// HTML so we don't have to manage DOM insertion / removal.
+function _mpUpdateReconcileBanner() {
+ const banners = document.querySelectorAll('[data-reconcile-banner]');
+ if (!banners.length) return;
+ const s = _mpReconcileStatus;
+ let text = '';
+ let visible = false;
+ if (s.state === 'running') {
+ visible = true;
+ text = t('marketplace.reconcile_running')
+ .replace('{pulled}', String(s.pulled))
+ .replace('{total}', String(s.total));
+ } else if (s.state === 'done' && (s.failed || []).length > 0) {
+ visible = true;
+ text = t('marketplace.reconcile_partial').replace('{failed}', String(s.failed.length));
+ }
+ for (const banner of banners) {
+ banner.style.display = visible ? '' : 'none';
+ banner.textContent = text;
+ }
+}
+
+function _mpBindPanel(panel) {
+ // Inject a banner inside the marketplace grid header if one isn't there yet. The agents /
+ // skills panels have their own static `[data-reconcile-banner]` in index.html; this just
+ // covers the marketplace panel which historically didn't.
+ if (!panel.querySelector('[data-reconcile-banner]')) {
+ const banner = document.createElement('div');
+ banner.className = 'marketplace-reconcile-banner';
+ banner.setAttribute('data-reconcile-banner', '');
+ banner.style.display = 'none';
+ const host = panel.querySelector('[data-mp-categories]')?.parentElement || panel;
+ host.insertBefore(banner, host.firstChild);
+ _mpUpdateReconcileBanner();
+ }
+
+ panel.querySelectorAll('[data-mp-close]').forEach((btn) =>
+ btn.addEventListener('click', closeMarketplace),
+ );
+ panel.querySelectorAll('[data-mp-detail-back]').forEach((btn) =>
+ btn.addEventListener('click', () => { _mpShowGridView(); _mpRender(); }),
+ );
+ panel.querySelectorAll('[data-mp-tab]').forEach((btn) => {
btn.addEventListener('click', () => {
+ if (!_mpState) return;
_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();
+ const search = panel.querySelector('[data-mp-search]');
+ if (search) {
+ search.addEventListener('keydown', (e) => {
+ if (e.isComposing || e.keyCode === 229) return;
+ if (e.key === 'Enter') {
+ const next = search.value.trim();
+ if (next === _mpState.q) return;
+ _mpState.q = next;
+ _mpRefreshListings();
+ }
+ });
}
+ panel.querySelector('[data-mp-detail-install]')?.addEventListener('click', _mpInstallFromDetail);
+ // Dev-only delete button click handler is bound by marketplace_dev.js (file absent in
+ // OrkasOpen). HTML element ships in index.html with display:none — dev module flips it
+ // on via the `onMarketplaceDetailRendered` hook (see below).
}
async function _mpLoadAll() {
- _mpState.loading = true;
+ // SWR open: paint cache immediately so the grid never goes blank between IPC roundtrips.
+ // Even when the TTL has elapsed (dev mode TTL=0 always fires a refresh), the user sees the
+ // stale list right away — fresh data swaps in once the background fetch lands.
+ const hadCache = _mpHydrateFromCache();
+ _mpState.loading = !hadCache;
_mpState.error = '';
+ if (_mpCategoriesCache) _mpState.categories = _mpCategoriesCache;
+ // First paint with whatever we already know — categories from the renderer cache (set on
+ // a prior session if it ran), listings from the hydrated cache. Avoids the "wait for the
+ // IPC roundtrip before showing anything" flash that broke the cache-first promise.
+ _mpRender();
+
try {
- const [cats, instAgents, instSkills] = await Promise.all([
- window.orkas.invoke('marketplace.categories', {}),
+ const tasks = [
window.orkas.invoke('agents.list'),
window.orkas.invoke('skills.list'),
- ]);
- _mpState.categories = (cats && cats.list) || [];
+ ];
+ if (!_mpCategoriesCache) {
+ tasks.push(window.orkas.invoke('marketplace.categories', {}));
+ }
+ const results = await Promise.all(tasks);
+ const instAgents = results[0];
+ const instSkills = results[1];
+ if (!_mpCategoriesCache && results[2]) {
+ _mpCategoriesCache = (results[2] && results[2].list) || [];
+ _mpState.categories = _mpCategoriesCache;
+ _mpPersistCategoriesCache(_mpCategoriesCache);
+ }
_mpState.installedAgentIds = new Set(((instAgents && instAgents.agents) || []).map((a) => a.agent_id));
_mpState.installedSkillIds = new Set(((instSkills && instSkills.skills) || []).map((s) => s.id));
+ _mpPersistInstalled();
await _mpLoadListings();
} catch (err) {
- _mpState.error = (err && err.message) || String(err);
+ // Background-refresh failure must NOT wipe what's already on screen. Only surface as a
+ // body-level error when we never managed to paint any cached items in the first place;
+ // otherwise log + keep the stale view (matches SWR semantics).
+ console.warn('marketplace background fetch failed:', err);
+ if (!hadCache && _mpState.agents.length === 0 && _mpState.skills.length === 0) {
+ _mpState.error = (err && err.message) || String(err);
+ }
} finally {
_mpState.loading = false;
+ _mpRender();
}
}
-async function _mpLoadListings() {
+function _mpPersistCategoriesCache(list) {
+ try { localStorage.setItem(MP_CATEGORIES_LS_KEY, JSON.stringify(list)); } catch { /* ignore */ }
+}
+
+// Module-load: kick off the reconcile-status watch so the banner in `agents-grid-view` /
+// `skills-grid-view` lights up DURING boot reconcile, not only after the user enters
+// marketplace. Idempotent — `_mpInitReconcileWatch` runs once and a second call no-ops.
+setTimeout(() => { _mpInitReconcileWatch().catch(() => {}); }, 0);
+
+// Module-level background refresh of categories. We already have whatever was in localStorage
+// (set when the module evaluated). This refresh keeps the cache current with the server
+// without ever blocking the UI — fire-and-forget; failures keep the localStorage copy.
+(function _mpPreloadCategories() {
+ try {
+ window.orkas.invoke('marketplace.categories', {}).then((r) => {
+ const list = (r && r.list) || [];
+ if (list.length) {
+ _mpCategoriesCache = list;
+ _mpPersistCategoriesCache(list);
+ }
+ }).catch(() => { /* ignore */ });
+ } catch { /* preload happens at script load; window.orkas not ready is OK */ }
+})();
+
+// Top-level listings refresh: hydrate cache → render immediately if hit, then background
+// fetch + re-render. The single entry point for category-chip clicks and the search Enter
+// handler so the loading-state / cache-hit decision lives in one place.
+async function _mpRefreshListings() {
+ const hadCache = _mpHydrateFromCache();
+ _mpState.loading = !hadCache;
+ _mpRender();
+ await _mpLoadListings();
+ _mpState.loading = false;
+ _mpRender();
+}
+
+// Generation token: every call to a load fn bumps `_loadGen`; only responses from the
+// latest gen get applied. Prevents stale responses (tab / category / search switched
+// mid-flight) from overwriting current state.
+function _mpHydrateFromCache() {
+ const cat = _mpState.category, q = _mpState.q;
+ const cachedA = _mpListingsCache.get(_mpListingsKey('agent', cat, q));
+ const cachedS = _mpListingsCache.get(_mpListingsKey('skill', cat, q));
+ if (cachedA) _mpState.agents = cachedA.items;
+ if (cachedS) _mpState.skills = cachedS.items;
+ return !!(cachedA || cachedS);
+}
+
+// Spread rows pulled from the "All" tab (category='') into each row's own category cache
+// slot. One-way: All → per-category. The reverse would corrupt the time-ordered "All" view.
+function _mpSpreadAllIntoCategoryCaches(kind, rows, q) {
+ if (!rows.length) return;
+ const byCat = new Map();
+ for (const row of rows) {
+ const c = String(row.category || '').trim();
+ if (!c) continue;
+ if (!byCat.has(c)) byCat.set(c, []);
+ byCat.get(c).push(row);
+ }
+ for (const [cat, catRows] of byCat) {
+ const key = _mpListingsKey(kind, cat, q);
+ const existing = _mpListingsCache.get(key);
+ const items = existing ? existing.items.slice() : [];
+ const seen = new Set(items.map((x) => x.id));
+ for (const r of catRows) if (!seen.has(r.id)) items.push(r);
+ items.sort((a, b) => (b.updated_at || 0) - (a.updated_at || 0));
+ _mpListingsCache.set(key, {
+ items,
+ ts: existing?.ts || Date.now(),
+ nextPage: existing?.nextPage || 1,
+ // We didn't fully scan this category, so a real category-tab fetch is still allowed.
+ exhausted: existing?.exhausted || false,
+ });
+ }
+}
+
+// Fetch one page of (kind, category, q). `append=false` overwrites the cache slot (page 1
+// reload on tab/category switch). `append=true` extends the existing items (infinite scroll).
+// Per-kind gen token: agent and skill fetches run in parallel from `_mpLoadListings`; a single
+// shared counter would have the second sync-prefix bump invalidating the first kind's response.
+async function _mpLoadListingsPage(kind, { append, page }) {
+ if (!_mpState._loadGen) _mpState._loadGen = { agent: 0, skill: 0 };
+ const myGen = ++_mpState._loadGen[kind];
+ const cat = _mpState.category, q = _mpState.q;
+ const key = _mpListingsKey(kind, cat, q);
+ const channel = kind === 'agent' ? 'marketplace.listAgents' : 'marketplace.listSkills';
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) || [];
+ const r = await window.orkas.invoke(channel, {
+ category: cat || null, q: q || null, page, size: MP_LISTINGS_PAGE_SIZE,
+ });
+ if (_mpState._loadGen[kind] !== myGen) return;
+ const rows = (r && r.list) || [];
+ const total = (r && r.total) || 0;
+ // exhausted when the row count returned is short of the page size, or we've covered total.
+ const exhausted = rows.length < MP_LISTINGS_PAGE_SIZE || (page * MP_LISTINGS_PAGE_SIZE >= total);
+ const existing = _mpListingsCache.get(key);
+ let merged;
+ if (append && existing) {
+ const seen = new Set(existing.items.map((x) => x.id));
+ const dedup = rows.filter((x) => !seen.has(x.id));
+ merged = existing.items.concat(dedup);
+ } else {
+ merged = rows;
+ }
+ _mpListingsCache.set(key, {
+ items: merged, ts: Date.now(), nextPage: page + 1, exhausted,
+ });
+ if (kind === 'agent') _mpState.agents = merged;
+ else _mpState.skills = merged;
+ // "All" tab feeds per-category caches one-way.
+ if (!cat) _mpSpreadAllIntoCategoryCaches(kind, rows, q);
+ _mpPersistListingsCache();
} catch (err) {
- _mpState.error = (err && err.message) || String(err);
+ if (_mpState._loadGen[kind] !== myGen) return;
+ console.warn('marketplace listings fetch failed:', err);
+ if (_mpState.agents.length === 0 && _mpState.skills.length === 0) {
+ _mpState.error = (err && err.message) || String(err);
+ }
+ }
+}
+
+// Convenience: SWR-reload page 1 for both kinds (called from openMarketplace + tab/category
+// switch + search submit). Cache hydration happened in the caller.
+async function _mpLoadListings() {
+ await Promise.all([
+ _mpLoadListingsPage('agent', { append: false, page: 1 }),
+ _mpLoadListingsPage('skill', { append: false, page: 1 }),
+ ]);
+}
+
+// Infinite scroll trigger — pulls the next page for the currently-visible kind.
+let _mpLoadMoreInflight = false;
+async function _mpLoadMoreCurrentKind() {
+ if (_mpLoadMoreInflight) return;
+ const kind = _mpState.tab;
+ const cat = _mpState.category, q = _mpState.q;
+ const cached = _mpListingsCache.get(_mpListingsKey(kind, cat, q));
+ if (!cached || cached.exhausted) return;
+ _mpLoadMoreInflight = true;
+ try {
+ await _mpLoadListingsPage(kind, { append: true, page: cached.nextPage || 2 });
+ _mpRender();
+ } finally {
+ _mpLoadMoreInflight = false;
}
}
+// ─── Grid view rendering ───
function _mpRender() {
- if (!_mpOverlay || !_mpState) return;
- const lang = getLang();
+ const panel = document.getElementById('panel-marketplace');
+ if (!panel || !_mpState) return;
+ if (_mpState.view === 'detail') { _mpRenderDetail(); return; }
- // Tab labels
- for (const btn of _mpOverlay.querySelectorAll('[data-mp-tab]')) {
+ const lang = getLang();
+ for (const btn of panel.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');
+ const searchEl = panel.querySelector('[data-mp-search]');
+ if (searchEl) searchEl.setAttribute('placeholder', t('marketplace.search_ph'));
- // Category chips — filter to those relevant for the active tab.
- const cats = _mpState.categories.filter((c) =>
- c.kind === 'both' || c.kind === _mpState.tab,
- );
+ const cats = _mpState.categories;
const chips = [
`<button type="button" class="marketplace-chip${_mpState.category === '' ? ' is-active' : ''}" data-mp-cat="">${escapeHtml(t('marketplace.all'))}</button>`,
...cats.map((c) => {
@@ -169,37 +546,70 @@ function _mpRender() {
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]');
+ const catsEl = panel.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);
+ _mpRefreshListings();
});
});
- // Body
- const body = _mpOverlay.querySelector('[data-mp-body]');
+ const body = panel.querySelector('[data-mp-body]');
if (_mpState.loading) {
- body.innerHTML = `<div class="empty">${escapeHtml(t('common.loading') === 'common.loading' ? '…' : t('common.loading'))}</div>`;
+ body.innerHTML = `
+ <div class="marketplace-detail-loading">
+ <div class="marketplace-upload-spinner"></div>
+ <div class="marketplace-detail-loading-text">${escapeHtml(t('marketplace.list_loading'))}</div>
+ </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 }));
+ // Order = server-side `updated_at DESC` (newest first). No further client sort — the
+ // accumulator in `_mpLoadListingsPage` preserves the server's slicing.
+ const items = (_mpState.tab === 'agent' ? _mpState.agents : _mpState.skills);
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));
+ // Render grid + a trailing sentinel — the sentinel sits one card-height below the visible
+ // grid end, IntersectionObserver fires `_mpLoadMoreCurrentKind` when it enters the viewport.
+ body.innerHTML = `
+ <div class="marketplace-grid">${items.map((it) => _mpCardHtml(it, lang)).join('')}</div>
+ <div class="mp-load-more-sentinel" data-mp-sentinel aria-hidden="true"></div>
+ `;
+ body.querySelectorAll('.marketplace-card').forEach((card) => {
+ const id = card.dataset.id;
+ card.addEventListener('click', (e) => {
+ if (e.target.closest('[data-mp-install]')) {
+ e.stopPropagation();
+ _mpInstall(_mpState.tab, id);
+ } else {
+ const item = (_mpState.tab === 'agent' ? _mpState.agents : _mpState.skills).find((x) => x.id === id);
+ if (item) _mpOpenDetail(_mpState.tab, item);
+ }
+ });
});
+ _mpAttachInfiniteScroll(body);
+}
+
+// IntersectionObserver-based infinite scroll. The sentinel sits ~300px below the last
+// rendered card (one card-height of preload margin), so the next page fires while the user
+// still has one card visible on screen. Re-attached on every `_mpRender` because the
+// sentinel node is recreated each render — single observer, no leaks.
+let _mpScrollObserver = null;
+function _mpAttachInfiniteScroll(body) {
+ if (_mpScrollObserver) _mpScrollObserver.disconnect();
+ const sentinel = body.querySelector('[data-mp-sentinel]');
+ if (!sentinel) return;
+ _mpScrollObserver = new IntersectionObserver((entries) => {
+ if (entries.some((e) => e.isIntersecting)) _mpLoadMoreCurrentKind();
+ }, { root: body, rootMargin: '0px 0px 300px 0px' });
+ _mpScrollObserver.observe(sentinel);
}
function _mpCardHtml(item, lang) {
@@ -215,8 +625,12 @@ function _mpCardHtml(item, lang) {
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)}"`;
+ let btnSpinner = '';
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'; }
+ else if (installing) {
+ btnClass = 'btn btn-sm is-disabled'; btnLabel = t('marketplace.installing'); btnAttrs = 'disabled';
+ btnSpinner = '<span class="marketplace-btn-spinner"></span>';
+ }
return `
<div class="marketplace-card" data-id="${escapeHtml(item.id)}">
<div class="marketplace-card-header">
@@ -224,124 +638,378 @@ function _mpCardHtml(item, lang) {
<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 class="marketplace-card-footer">
+ <div class="marketplace-card-meta">
+ ${item.version ? `<span class="marketplace-card-chip is-version">${escapeHtml(versionLabel)}</span>` : ''}
+ ${catLabel ? `<span class="marketplace-card-chip">${escapeHtml(catLabel)}</span>` : ''}
+ ${_mpAuthorBadgeHtml(item.create_uid)}
+ </div>
+ <div class="marketplace-card-actions">
+ <button type="button" class="${btnClass}" ${btnAttrs}>${btnSpinner}${escapeHtml(btnLabel)}</button>
+ </div>
</div>
</div>
`;
}
+/** Author badge — distinguishes same-name uploads by different authors. uid=0 is the
+ * "Platform" marker (官方制作); everything else falls back to a truncated uid. */
+function _mpAuthorBadgeHtml(createUid) {
+ if (!createUid) return '';
+ const label = String(createUid) === '0'
+ ? t('marketplace.author_platform')
+ : t('marketplace.author_user').replace('{uid}', String(createUid));
+ const cls = String(createUid) === '0' ? 'marketplace-card-chip is-platform' : 'marketplace-card-chip is-user';
+ return `<span class="${cls}">${escapeHtml(label)}</span>`;
+}
+
function _mpCategoryLabel(code, lang) {
+ if (!code) return '';
const c = _mpState.categories.find((x) => x.code === code);
- if (!c) return code || '';
+ if (!c) return code;
return lang === 'zh' ? (c.name_zh || c.name_en || code) : (c.name_en || c.name_zh || code);
}
+// ─── Detail view rendering ───
+async function _mpOpenDetail(kind, item) {
+ _mpState.detailKind = kind;
+ _mpState.detailItem = item;
+ _mpState.detailLoading = true;
+ _mpState.detailError = '';
+ _mpState.detailAgentJson = null;
+ _mpState.detailSkillFiles = [];
+ _mpState.detailSkillSelected = 'SKILL.md';
+ _mpState.detailSkillFileText = '';
+ _mpShowDetailView();
+ _mpRenderDetail();
+
+ try {
+ if (kind === 'agent') {
+ const detail = await window.orkas.invoke('marketplace.detailAgent', {
+ id: item.id, version: item.version, published_at: item.published_at,
+ });
+ if (!detail || detail.ok === false) throw new Error((detail && detail.error) || 'detail failed');
+ _mpState.detailAgentJson = detail.agent_json;
+ } else {
+ const detail = await window.orkas.invoke('marketplace.detailSkill', {
+ id: item.id, version: item.version, published_at: item.published_at,
+ });
+ if (!detail || detail.ok === false) throw new Error((detail && detail.error) || 'detail failed');
+ const files = await window.orkas.invoke('marketplace.cacheSkillFiles', { id: item.id });
+ _mpState.detailSkillFiles = (files && files.list) || [];
+ if (_mpState.detailSkillFiles.find((f) => f.path === 'SKILL.md')) {
+ const r = await window.orkas.invoke('marketplace.cacheSkillRead', { id: item.id, file: 'SKILL.md' });
+ _mpState.detailSkillFileText = (r && r.content) || '';
+ }
+ }
+ } catch (err) {
+ _mpState.detailError = (err && err.message) || String(err);
+ } finally {
+ _mpState.detailLoading = false;
+ _mpRenderDetail();
+ }
+}
+
+function _mpRenderDetail() {
+ const panel = document.getElementById('panel-marketplace');
+ if (!panel || !_mpState) return;
+ const item = _mpState.detailItem;
+ const kind = _mpState.detailKind;
+ if (!item || !kind) return;
+
+ const lang = getLang();
+ const desc = pickDesc(item, lang) || '';
+ const catLabel = _mpCategoryLabel(item.category, lang);
+ const versionLabel = t('marketplace.version').replace('{version}', String(item.version || ''));
+ const installed = (kind === 'agent' ? _mpState.installedAgentIds : _mpState.installedSkillIds).has(item.id);
+ const installing = _mpState.installing.has(`${kind}:${item.id}`);
+
+ // Avatar slot — only agents have icon/color; skill detail keeps the slot empty so the
+ // back-button + name still align horizontally.
+ const avatarSlot = panel.querySelector('[data-mp-detail-avatar]');
+ if (avatarSlot) {
+ if (kind === 'agent') {
+ avatarSlot.innerHTML = renderAvatarHtml(item.icon, item.color, {
+ size: 32, seed: item.id, extraClass: 'marketplace-detail-avatar',
+ });
+ avatarSlot.style.display = '';
+ } else {
+ avatarSlot.innerHTML = '';
+ avatarSlot.style.display = 'none';
+ }
+ }
+ // Name + version share a row; category / author chips drop to the meta-row below.
+ panel.querySelector('[data-mp-detail-name]').innerHTML = `
+ ${escapeHtml(item.name || item.id)}
+ <span class="marketplace-detail-version">${escapeHtml(versionLabel)}</span>
+ `;
+ panel.querySelector('[data-mp-detail-meta]').innerHTML = [
+ catLabel ? `<span class="marketplace-card-chip">${escapeHtml(catLabel)}</span>` : '',
+ _mpAuthorBadgeHtml(item.create_uid),
+ ].filter(Boolean).join(' ');
+ // (description used to render in a top-of-body `.marketplace-detail-desc` strip; now it's
+ // the first section inside body — see `_mpAgentDetailHtml` / `_mpSkillDetailHtml`)
+
+ const installBtn = panel.querySelector('[data-mp-detail-install]');
+ installBtn.dataset.id = item.id;
+ installBtn.dataset.kind = kind;
+ // When installed, repurpose the primary button as "卸载" (local-only uninstall — does NOT
+ // touch the server row). When installing/uninstalling, disabled with progress text + inline
+ // spinner so the user sees "still working" instead of a static label.
+ const spinnerHtml = '<span class="marketplace-btn-spinner"></span>';
+ if (installing) {
+ const label = _mpState.uninstalling?.has(`${kind}:${item.id}`)
+ ? t('marketplace.uninstalling') : t('marketplace.installing');
+ installBtn.innerHTML = `${spinnerHtml}${escapeHtml(label)}`;
+ installBtn.classList.add('is-disabled'); installBtn.disabled = true;
+ installBtn.dataset.action = '';
+ } else if (installed) {
+ installBtn.textContent = t('marketplace.uninstall');
+ installBtn.classList.remove('is-disabled', 'btn-primary');
+ installBtn.classList.add('btn-danger');
+ installBtn.disabled = false;
+ installBtn.dataset.action = 'uninstall';
+ } else {
+ installBtn.textContent = t('marketplace.install');
+ installBtn.classList.remove('is-disabled', 'btn-danger');
+ installBtn.classList.add('btn-primary');
+ installBtn.disabled = false;
+ installBtn.dataset.action = 'install';
+ }
+
+ // Dev-only delete button is rendered + revealed by marketplace_dev.js via the
+ // `onMarketplaceDetailRendered` hook below. OrkasOpen has no such file — hook is undefined
+ // and the button stays hidden (display:none from HTML).
+ if (typeof onMarketplaceDetailRendered === 'function') {
+ onMarketplaceDetailRendered({ kind, item });
+ }
+
+ const body = panel.querySelector('[data-mp-detail-body]');
+ if (_mpState.detailLoading) {
+ body.innerHTML = `
+ <div class="marketplace-detail-loading">
+ <div class="marketplace-upload-spinner"></div>
+ <div class="marketplace-detail-loading-text">${escapeHtml(t('marketplace.detail_loading'))}</div>
+ </div>
+ `;
+ return;
+ }
+ if (_mpState.detailError) {
+ body.innerHTML = `<div class="empty">${escapeHtml(t('marketplace.load_failed'))}: ${escapeHtml(_mpState.detailError)}</div>`;
+ return;
+ }
+ if (kind === 'agent') {
+ body.innerHTML = _mpAgentDetailHtml(_mpState.detailAgentJson);
+ } else {
+ body.innerHTML = _mpSkillDetailHtml();
+ // File-tree node click → fetch + re-render selected file
+ body.querySelectorAll('[data-mp-skill-file]').forEach((el) => {
+ el.addEventListener('click', async () => {
+ const file = el.dataset.mpSkillFile;
+ if (!file) return;
+ _mpState.detailSkillSelected = file;
+ try {
+ const r = await window.orkas.invoke('marketplace.cacheSkillRead', { id: item.id, file });
+ _mpState.detailSkillFileText = (r && r.content) || '';
+ } catch (err) {
+ _mpState.detailSkillFileText = `// load failed: ${(err && err.message) || err}`;
+ }
+ _mpRenderDetail();
+ });
+ });
+ // Source-tree toggle (collapsed by default, matches app skill detail behavior)
+ const toggle = body.querySelector('[data-mp-source-toggle]');
+ const panel = body.querySelector('[data-mp-source-panel]');
+ if (toggle && panel) {
+ // Preserve open state across re-renders via _mpState
+ const open = !!_mpState.detailSkillSourceOpen;
+ panel.style.display = open ? '' : 'none';
+ toggle.setAttribute('aria-expanded', String(open));
+ toggle.classList.toggle('is-open', open);
+ toggle.addEventListener('click', () => {
+ _mpState.detailSkillSourceOpen = !_mpState.detailSkillSourceOpen;
+ const next = _mpState.detailSkillSourceOpen;
+ panel.style.display = next ? '' : 'none';
+ toggle.setAttribute('aria-expanded', String(next));
+ toggle.classList.toggle('is-open', next);
+ });
+ }
+ }
+}
+
+// Agent body uses the SAME CSS classes as the in-app `panel-agents` detail (Summary + Workflow
+// sections + `.markdown-body` for rendered workflow). Marketplace context is read-only browse:
+// `inputs` / `skill_list` are user-facing form schema + runtime details (only meaningful AFTER
+// install), so we don't render them here — keeps the preview focused on "what does this agent
+// do" rather than implementation. Marketplace header above stays in its own compact row layout.
+function _mpAgentDetailHtml(agentJson) {
+ if (!agentJson) return `<div class="empty">${escapeHtml(t('marketplace.empty'))}</div>`;
+ const lang = getLang();
+ const desc = pickDesc(agentJson, lang).trim();
+ const workflow = String(agentJson.workflow || '').trim();
+ const placeholderHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset') || '—')}</span>`;
+
+ return `<div class="agents-detail-body marketplace-detail-body-inner">
+ <div class="agents-detail-section">
+ <div class="agents-detail-label">${escapeHtml(t('agents.label_desc') || 'Summary')}</div>
+ <div class="agents-detail-desc">${desc ? escapeHtml(desc) : placeholderHtml}</div>
+ </div>
+ <div class="agents-detail-section agents-detail-section-workflow">
+ <div class="agents-detail-label">${escapeHtml(t('agents.label_workflow') || 'Workflow')}</div>
+ <div class="agents-detail-workflow markdown-body">${workflow ? renderMarkdownFull(workflow) : placeholderHtml}</div>
+ </div>
+ </div>`;
+}
+
+// Skill body mirrors `panel-skills` detail: a Summary section + a Usage section that contains
+// the source-tree (collapsed by default behind a "View source" toggle, matching app behavior)
+// and the rendered SKILL.md body. The renderer relies on the SAME `.skills-doc-section` /
+// `.skills-source-tree` / `.skills-doc-section-body markdown-body` CSS the app uses.
+function _mpSkillDetailHtml() {
+ const item = _mpState.detailItem;
+ const lang = getLang();
+ const summary = pickDesc(item || {}, lang).trim();
+ const files = _mpState.detailSkillFiles || [];
+ const selected = _mpState.detailSkillSelected;
+ const text = _mpState.detailSkillFileText || '';
+
+ const treeHtml = files.map((f) => {
+ const active = f.path === selected ? ' active' : '';
+ return `<div class="skill-tree-node skill-tree-file${active}" data-mp-skill-file="${escapeHtml(f.path)}">
+ <span class="skill-tree-label">${escapeHtml(f.path)}</span>
+ <span class="muted" style="margin-left:auto;font-size:11px">${_fmtBytes(f.bytes)}</span>
+ </div>`;
+ }).join('');
+
+ const isMd = selected.toLowerCase().endsWith('.md');
+ const bodyHtml = isMd
+ ? renderMarkdownFull(text)
+ : `<pre class="code-view"><code>${escapeHtml(text)}</code></pre>`;
+ const placeholderHtml = `<span class="agents-detail-placeholder">${escapeHtml(t('agents.placeholder_unset') || '—')}</span>`;
+
+ return `
+ <div class="skills-detail-content marketplace-detail-body-inner">
+ <section class="skills-doc-section">
+ <h3 class="skills-doc-section-label">${escapeHtml(t('skills.label_summary') || 'Summary')}</h3>
+ <div class="skills-doc-section-body">${summary ? escapeHtml(summary) : placeholderHtml}</div>
+ </section>
+ <section class="skills-doc-section skills-usage-section">
+ <h3 class="skills-doc-section-label skills-usage-label">
+ <span>${escapeHtml(t('skills.label_usage') || 'Usage')}</span>
+ <button type="button" class="skills-source-toggle" data-mp-source-toggle aria-expanded="false">
+ <span class="skills-source-toggle-caret" aria-hidden="true">▶</span>
+ <span>${escapeHtml(t('skills.label_source') || 'View source')}</span>
+ </button>
+ </h3>
+ <div class="skills-source-panel" data-mp-source-panel style="display:none">
+ <div class="skills-source-tree">${treeHtml}</div>
+ </div>
+ <div class="skills-doc-section-body markdown-body">${bodyHtml}</div>
+ </section>
+ </div>
+ `;
+}
+
+function _fmtBytes(n) {
+ if (!Number.isFinite(n)) return '';
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
+}
+
async function _mpInstall(kind, id) {
+ const item = (kind === 'agent' ? _mpState.agents : _mpState.skills).find((x) => x.id === id);
+ if (!item) return;
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 });
+ const r = await window.orkas.invoke(channel, {
+ id, version: item.version, published_at: item.published_at,
+ });
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.
+ _mpPersistInstalled();
if (typeof loadAgents === 'function' && kind === 'agent') await loadAgents(true);
if (typeof loadSkills === 'function' && kind === 'skill') await loadSkills(true);
- uiAlert(t('marketplace.install_ok'));
+ // Success: no toast — the button flips to "已安装" + state set above is the signal.
+ // (Failure still alerts because the user otherwise has no way to know why nothing happened.)
} catch (err) {
const msg = (err && err.message) || String(err);
uiAlert(t('marketplace.install_failed').replace('{reason}', msg));
} finally {
_mpState.installing.delete(key);
_mpRender();
+ if (_mpState.view === 'detail') _mpRenderDetail();
}
}
-// ─── 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;
+async function _mpInstallFromDetail() {
+ const item = _mpState.detailItem;
+ const kind = _mpState.detailKind;
+ if (!item || !kind) return;
+ const installed = (kind === 'agent' ? _mpState.installedAgentIds : _mpState.installedSkillIds).has(item.id);
+ if (installed) await _mpUninstall(kind, item.id);
+ else await _mpInstall(kind, item.id);
+}
- // Need the categories list for the dropdown.
- let categories = [];
+async function _mpUninstall(kind, id) {
+ if (!_mpState.uninstalling) _mpState.uninstalling = new Set();
+ const key = `${kind}:${id}`;
+ if (_mpState.installing.has(key)) return;
+ _mpState.installing.add(key);
+ _mpState.uninstalling.add(key);
+ _mpRender();
try {
- const r = await window.orkas.invoke('marketplace.categories', {});
- categories = ((r && r.list) || []).filter((c) => c.kind === 'both' || c.kind === kind);
+ const channel = kind === 'agent' ? 'marketplace.uninstallAgent' : 'marketplace.uninstallSkill';
+ const r = await window.orkas.invoke(channel, { id });
+ if (!r || r.ok === false) throw new Error((r && r.error) || 'uninstall failed');
+ if (kind === 'agent') _mpState.installedAgentIds.delete(id);
+ else _mpState.installedSkillIds.delete(id);
+ _mpPersistInstalled();
+ if (typeof loadAgents === 'function' && kind === 'agent') await loadAgents(true);
+ if (typeof loadSkills === 'function' && kind === 'skill') await loadSkills(true);
+ // Success: button flips back to "安装" — no toast needed. (Failures still alert.)
} catch (err) {
- uiAlert(t('marketplace.load_failed') + ': ' + ((err && err.message) || err));
- return;
+ const msg = (err && err.message) || String(err);
+ uiAlert(t('marketplace.uninstall_failed').replace('{reason}', msg));
+ } finally {
+ _mpState.installing.delete(key);
+ _mpState.uninstalling.delete(key);
+ _mpRender();
+ if (_mpState.view === 'detail') _mpRenderDetail();
}
- 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);
+// Dev-only `_mpDeleteFromDetail` moved to marketplace_dev.js.
- const catEl = overlay.querySelector('[data-mp-upload-category]');
- const select = _aiSelectMount(catEl, {
+// ─── Shared: category dropdown mount ──────────────────────────────────
+// Used by the create-agent and create-skill modals. Loads from main, which serves the 24h
+// biz cache (features/marketplace_biz.ts) and falls back to a hard-coded default list on
+// network failure — so the dropdown is never empty.
+async function mountMarketplaceCategorySelect(elId, initialValue = '') {
+ const el = document.getElementById(elId);
+ if (!el) return;
+ let categories = [];
+ try {
+ const r = await window.orkas.invoke('marketplace.categories', {});
+ categories = (r && r.list) || [];
+ } catch { /* swallowed — main's fallback handles it */ }
+ const lang = (typeof getLang === 'function') ? getLang() : 'zh';
+ _aiSelectMount(el, {
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: () => {},
+ value: initialValue || (categories[0] && categories[0].code) || '',
});
- 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));
- }
}
+
+// Dev-only `openMarketplaceUpload` + `_mpShowUploadWithCategoryDialog` live in
+// `marketplace_dev.js` (physically excluded from OrkasOpen via SyncCode strip-rules).
+// Callers (agents.js / skills.js per-row menu) check `typeof openMarketplaceUpload === 'function'`
+// to decide whether to show the upload entry — OrkasOpen has no marketplace_dev.js loaded,
+// so the menu items just don't appear.
diff --git a/src/renderer/modules/skills.js b/src/renderer/modules/skills.js
index 759c43a9..fa80448e 100644
--- a/src/renderer/modules/skills.js
+++ b/src/renderer/modules/skills.js
@@ -4,6 +4,29 @@ const _skillsLog = createLogger('skills');
let _skillsCache = null;
let _selectedSkill = null; // { source, id }
+/** Version + category + author chips for a marketplace-installed skill. Mirrors the
+ * marketplace card footer. `_resolveCategoryLabel` is defined in `agents.js` (flat top-level
+ * scope per CLAUDE.md §8). Author chip: `create_uid='0'` → 官方 badge; non-zero → user badge. */
+function _skillPlatformChipsHtml(s) {
+ const lang = getLang();
+ const parts = [];
+ if (s.version) {
+ const versionLabel = t('marketplace.version').replace('{version}', String(s.version));
+ parts.push(`<span class="skill-card-chip is-version">${escapeHtml(versionLabel)}</span>`);
+ }
+ if (s.category) {
+ const catLabel = _resolveCategoryLabel(s.category, lang);
+ parts.push(`<span class="skill-card-chip">${escapeHtml(catLabel)}</span>`);
+ }
+ if (s.create_uid) {
+ const isPlatform = String(s.create_uid) === '0';
+ const label = isPlatform ? t('marketplace.author_platform') : t('marketplace.author_user').replace('{uid}', String(s.create_uid));
+ const cls = isPlatform ? 'skill-card-chip is-platform' : 'skill-card-chip is-user';
+ parts.push(`<span class="${cls}">${escapeHtml(label)}</span>`);
+ }
+ return parts.join('');
+}
+
// Re-render the skill grid + currently selected detail page when the UI
// language changes — descriptions are bilingual now and `pickDesc` returns
// a different string after the locale flip. Detail re-render goes through
@@ -121,6 +144,10 @@ function renderSkillsGrid(skills) {
// the grid cards stay clean and use the ⋯ menu for actions.
const moreBtn = `<button type="button" class="skill-card-more" data-skill-more title="${moreTitle}" aria-label="${moreTitle}">⋯</button>`;
const enabled = s.enabled !== false;
+ // Marketplace-installed (`builtin`) skills carry version + category from _install.json /
+ // SKILL.md frontmatter — show them as inline chips so users see provenance without
+ // opening the detail page. Custom skills skip (no published version).
+ const platformChips = s.source === 'builtin' ? _skillPlatformChipsHtml(s) : '';
return `
<div class="skill-card${enabled ? '' : ' is-disabled'}" data-id="${escapeHtml(s.id)}" data-source="${s.source}">
<div class="skill-card-header">
@@ -129,6 +156,7 @@ function renderSkillsGrid(skills) {
</div>
<div class="${descClass}">${escapeHtml(descText)}</div>
<div class="skill-card-actions">
+ ${platformChips}
<button type="button" class="skill-card-use" data-skill-use title="${useTitle}" aria-label="${useTitle}">
<svg class="icon-play" viewBox="0 0 16 16" width="14" height="14" aria-hidden="true"><polygon points="5,3 5,13 13,8" fill="currentColor"/></svg>
</button>
@@ -299,10 +327,14 @@ function _openSkillRowMenu(anchorBtn, id, source) {
`<div class="skill-row-menu-item" data-action="toggle-enabled">${escapeHtml(enabled ? t('component.disable') : t('component.enable'))}</div>`,
);
- if (source === 'custom' && isDevMode()) {
+ if (source === 'custom' && false) {
items.push(
`<div class="skill-row-menu-item" data-action="promote">${escapeHtml(t('skills.promote_to_builtin'))}</div>`,
);
+ }
+ // Upload-to-marketplace owned by marketplace_dev.js (absent in OrkasOpen). typeof check
+ // naturally hides the entry on builds that don't ship the dev module.
+ if (typeof openMarketplaceUpload === 'function') {
items.push(
`<div class="skill-row-menu-item" data-action="upload-marketplace">${escapeHtml(t('marketplace.upload'))}</div>`,
);
@@ -539,10 +571,16 @@ async function selectSkillFile(source, id, filepath, nodeEl) {
nameEl.classList.remove('editable');
nameEl.removeAttribute('title');
- // Source label + colored tag — mirrors `.agents-detail-source.is-builtin/.is-custom`.
+ // Header chips: custom = "自定义"; marketplace-installed = {category} + {官方/作者}.
+ // Same `_renderSourceMetaHtml` helper as the agent detail page (defined in agents.js,
+ // shared via the renderer's flat top-level scope per CLAUDE.md §8).
const sourceEl = document.getElementById('skills-detail-source');
- sourceEl.textContent = source === 'custom' ? t('skills.source_custom') : t('skills.source_builtin');
- sourceEl.className = 'skills-doc-source ' + (source === 'builtin' ? 'is-builtin' : 'is-custom');
+ sourceEl.className = 'skills-doc-source-row';
+ sourceEl.innerHTML = _renderSourceMetaHtml({
+ source,
+ category: skill?.category || '',
+ create_uid: skill?.create_uid || '',
+ });
// Doc sections (description / external dependencies / dependent
// skills / other attributes) — seed with the cached description so
@@ -563,10 +601,17 @@ async function selectSkillFile(source, id, filepath, nodeEl) {
const useBtn = document.getElementById('skill-use-btn');
const editBtn = document.getElementById('skill-edit-btn');
const enableBtn = document.getElementById('skill-enabled-btn');
+
+ const promoteBtn = document.getElementById('skill-promote-btn');
+ const uploadBtn = document.getElementById('skill-upload-marketplace-btn');
const delBtn = document.getElementById('skill-delete-btn');
if (useBtn) useBtn.style.display = editingThis ? 'none' : '';
if (editBtn) editBtn.style.display = canEditThisSkill ? '' : 'none';
if (enableBtn) enableBtn.style.display = editingThis ? 'none' : '';
+
+ if (promoteBtn) promoteBtn.style.display = (source === 'custom' && false && !editingThis) ? '' : 'none';
+ // Upload button visibility: gated by marketplace_dev.js's presence (OrkasOpen lacks it).
+ if (uploadBtn) uploadBtn.style.display = (typeof openMarketplaceUpload === 'function' && !editingThis) ? '' : 'none';
if (delBtn) delBtn.style.display = (canEditThisSkill && !editingThis) ? '' : 'none';
}
@@ -1199,6 +1244,15 @@ async function openSkillModal(editId) {
_switchSkillTab('manual');
}
+ // Marketplace category dropdown (manual tab). Edit mode pre-fills from cached category;
+ // create mode picks the first entry as default. 24h cached in main with fallback list.
+ if (typeof mountMarketplaceCategorySelect === 'function') {
+ const initial = editId
+ ? (_skillsCache?.find((s) => s.id === editId && s.source === 'custom')?.category || '')
+ : '';
+ mountMarketplaceCategorySelect('skill-category-select', initial).catch(() => {});
+ }
+
// Wire tab buttons (idempotent — checks a flag)
if (tabBar && !tabBar.dataset.wired) {
tabBar.querySelectorAll('.skill-modal-tab').forEach((btn) => {
@@ -1257,6 +1311,7 @@ window.saveSkill = saveSkill;
async function _saveSkillManual({ editId, msgEl }) {
const name = document.getElementById('skill-name').value.trim();
const description = document.getElementById('skill-description').value.trim();
+ const category = document.getElementById('skill-category-select')?.dataset.value || '';
if (!name) {
msgEl.textContent = t('skills.input_name_needed');
msgEl.className = 'form-msg err';
@@ -1274,12 +1329,12 @@ async function _saveSkillManual({ editId, msgEl }) {
? await apiFetch(`/api/skills/${editId}/update`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name, description }),
+ body: JSON.stringify({ name, description, category }),
})
: await apiFetch('/api/skills/create', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name, description }),
+ body: JSON.stringify({ name, description, category }),
});
const data = await res.json();
if (!data.ok) {
diff --git a/src/renderer/modules/state.js b/src/renderer/modules/state.js
index 0c2efdaf..9cff558c 100644
--- a/src/renderer/modules/state.js
+++ b/src/renderer/modules/state.js
@@ -225,6 +225,11 @@ function bindStaticHandlers() {
document.getElementById('agent-promote-btn')?.addEventListener('click', () => {
if (_selectedAgent?.source === 'custom') promoteCustomAgent(_selectedAgent.id);
});
+ document.getElementById('agent-upload-marketplace-btn')?.addEventListener('click', () => {
+ if (_selectedAgent?.source === 'custom' && typeof openMarketplaceUpload === 'function') {
+ openMarketplaceUpload('agent', _selectedAgent.id);
+ }
+ });
document.getElementById('agent-chat-clear-btn')?.addEventListener('click', clearAgentChat);
// Agent inline chat: only bind auto-grow here. Send/abort/Cmd+Enter are
// wired lazily by createChatController in _ensureAgentChatController.
@@ -257,6 +262,11 @@ function bindStaticHandlers() {
document.getElementById('skill-promote-btn')?.addEventListener('click', () => {
if (_selectedSkill?.source === 'custom') promoteCustomSkill(_selectedSkill.id);
});
+ document.getElementById('skill-upload-marketplace-btn')?.addEventListener('click', () => {
+ if (_selectedSkill?.source === 'custom' && typeof openMarketplaceUpload === 'function') {
+ openMarketplaceUpload('skill', _selectedSkill.id);
+ }
+ });
// Skill name editing is now wired inline by `_toggleSkillNameEditable`
// (input + blur listeners attached on first edit-mode entry, gated by
// `_skillEditMode`) — no top-level click handler.
diff --git a/src/renderer/style.css b/src/renderer/style.css
index 1412a391..fb56b4f3 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -1078,12 +1078,14 @@ body.model-not-configured .main-content { flex-direction: column; }
background: #fff;
}
+/* Detail content container — padding matches `.marketplace-detail-header` density (14/20)
+ so the in-app skill detail and the marketplace skill preview align pixel-for-pixel. */
.skills-detail-content {
flex: 1;
display: block;
min-height: 0;
overflow-y: auto;
- padding: 24px 56px 60px;
+ padding: 14px 20px 28px;
width: 100%;
}
.skills-detail-content::-webkit-scrollbar { width: 6px; }
@@ -1091,24 +1093,41 @@ body.model-not-configured .main-content { flex-direction: column; }
/* ─── Single-document detail layout ─── */
+/* Single-row headline matching `.agents-detail-header` + `.marketplace-detail-header`:
+ back-button on the left, title + source chip middle, actions hugged to the right via
+ `margin-left:auto`. The row stays `nowrap` so it visually reads as one chrome strip; long
+ titles ellipsize rather than wrap (title gets `min-width:0` + overflow). Negative side
+ margins offset the `.skills-detail-content` container's horizontal padding so the
+ border-bottom rule reaches the panel edges — same chrome divider the agent detail uses. */
.skills-doc-headline {
display: flex;
align-items: center;
- flex-wrap: wrap;
- gap: 10px 12px;
- margin-bottom: 4px;
+ flex-wrap: nowrap;
+ gap: 8px;
+ margin: -14px -20px 20px;
+ padding: 14px 20px;
+ border-bottom: 1px solid var(--border);
+ background: #fff;
}
.skills-doc-title {
margin: 0;
- font-size: 22px;
- font-weight: 700;
+ font-size: 16px;
+ font-weight: 600;
color: var(--text);
- line-height: 1.3;
- padding: 2px 6px;
- margin-left: -6px;
+ line-height: 1.4;
+ padding: 2px 4px;
+ margin-left: -4px;
border-radius: 6px;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ flex: 0 1 auto; /* natural width + shrink for very long titles */
}
+/* Source chip stays glued to the title; actions hug the right via `margin-left:auto`. */
+.skills-doc-headline > .skills-doc-source { flex-shrink: 0; }
+.skills-doc-headline > .skills-doc-actions { flex-shrink: 0; margin-left: auto; }
.skills-doc-title.editable {
cursor: pointer;
transition: background 0.12s;
@@ -1131,6 +1150,14 @@ body.model-not-configured .main-content { flex-direction: column; }
}
.skills-doc-source.is-builtin { background: rgba(148, 163, 184, 0.15); color: #475569; }
.skills-doc-source.is-custom { background: rgba(37, 99, 235, 0.12); color: var(--primary); }
+.agents-detail-source.is-category,
+.skills-doc-source.is-category { background: rgba(79, 70, 229, 0.10); color: #4f46e5; }
+.agents-detail-source.is-platform,
+.skills-doc-source.is-platform { background: rgba(37, 99, 235, 0.12); color: #1d4ed8; }
+.agents-detail-source.is-user,
+.skills-doc-source.is-user { background: rgba(100, 116, 139, 0.10); color: #475569; }
+/* Allow multiple chips in the detail header source slot. */
+.skills-doc-source-row { display: inline-flex; gap: 6px; }
/* Editing-state chrome on the title — mirrors `.agents-detail-name.is-editing`
so both detail pages read as one chrome family. */
.skills-doc-title.is-editing {
@@ -1146,7 +1173,7 @@ body.model-not-configured .main-content { flex-direction: column; }
.skills-doc-actions {
margin-left: auto;
display: flex;
- gap: 6px;
+ gap: 4px;
align-items: center;
}
@@ -1479,7 +1506,12 @@ body.model-not-configured .main-content { flex-direction: column; }
display: flex;
align-items: center;
justify-content: flex-end;
+ gap: 6px;
+ flex-wrap: wrap;
}
+/* When platform chips (version/category) sit on the actions row, the play button still
+ hugs the right edge — `margin-left:auto` handles the absent-chip case too. */
+.skill-card-actions > .skill-card-use { margin-left: auto; }
.skill-card-use,
.agent-card-use,
@@ -1550,25 +1582,6 @@ body.model-not-configured .main-content { flex-direction: column; }
flex-shrink: 0;
}
-.skills-back-btn {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- padding: 6px 12px;
- border: 1px solid transparent;
- background: transparent;
- color: var(--muted);
- font-size: 13px;
- font-family: inherit;
- cursor: pointer;
- border-radius: 6px;
- transition: background 0.12s, color 0.12s, border-color 0.12s;
-}
-.skills-back-btn:hover {
- background: #f1f5f9;
- color: var(--primary);
-}
-
/* ─── "View source" collapsible (detail page bottom) ─── */
/* "使用说明" label is a flex row so its right side can host the inline
@@ -5027,7 +5040,8 @@ body.model-not-configured .main-content { flex-direction: column; }
display: flex;
align-items: center;
justify-content: space-between;
- gap: 8px;
+ gap: 6px;
+ flex-wrap: wrap;
}
/* When no chip is present, the play button still hugs the right edge.
`margin-left: auto` plays nice with the absent-chip case. */
@@ -5051,21 +5065,6 @@ body.model-not-configured .main-content { flex-direction: column; }
flex-shrink: 0;
}
-.agents-back-btn {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- border: none;
- background: transparent;
- color: var(--muted);
- font-size: 13px;
- cursor: pointer;
- padding: 4px 8px;
- border-radius: 6px;
- font-family: inherit;
-}
-.agents-back-btn:hover { background: #f1f5f9; color: var(--text); }
-
.agent-row-menu {
position: fixed;
z-index: 1000;
@@ -5113,8 +5112,11 @@ body.model-not-configured .main-content { flex-direction: column; }
overflow-y: auto;
}
+/* Compact header matches the marketplace detail density (.marketplace-detail-header):
+ tighter padding + title 16px so the in-app agent / skill detail and the marketplace
+ detail read as one chrome family. Body sections below keep their original spacing. */
.agents-detail-header {
- padding: 20px 32px 14px;
+ padding: 14px 20px;
border-bottom: 1px solid var(--border);
background: #fff;
flex-shrink: 0;
@@ -5123,23 +5125,29 @@ body.model-not-configured .main-content { flex-direction: column; }
.agents-detail-title-row {
display: flex;
align-items: center;
- justify-content: space-between;
- gap: 12px;
- flex-wrap: wrap;
+ gap: 8px;
+ flex-wrap: nowrap;
}
.agents-detail-name {
min-width: 0;
- font-size: 17px;
+ font-size: 16px;
font-weight: 600;
color: var(--text);
line-height: 1.4;
- padding: 2px 6px;
- margin-left: -6px;
+ padding: 2px 4px;
+ margin-left: -4px;
border-radius: 6px;
outline: none;
- min-height: 24px;
+ min-height: 22px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ flex: 0 1 auto; /* natural width + shrink for very long names */
}
+/* Source chip stays glued to the name; actions hug the right via `margin-left:auto`. */
+.agents-detail-title-row > .agents-detail-source { flex-shrink: 0; }
+.agents-detail-title-row > .detail-actions { flex-shrink: 0; margin-left: auto; }
.agents-detail-name.is-editing {
background: #fff;
box-shadow: 0 0 0 1px var(--border-strong) inset;
@@ -5163,12 +5171,14 @@ body.model-not-configured .main-content { flex-direction: column; }
.agents-detail-source.is-custom { background: rgba(37, 99, 235, 0.12); color: var(--primary); }
/* ── Body: simple vertical stack of sections, each full-width ── */
+/* Padding matches `.skills-detail-content` + `.marketplace-detail-header` so the three
+ detail surfaces (app agent / app skill / marketplace preview) share one chrome density. */
.agents-detail-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
- padding: 20px 32px 24px;
+ padding: 14px 20px 28px;
gap: 20px;
overflow-y: auto;
}
@@ -6090,6 +6100,344 @@ body.model-not-configured .main-content { flex-direction: column; }
.agents-detail-runtime { display: block; }
.agents-detail-runtime-select { max-width: 280px; }
+
+/* Wrapper for the multi-button cluster on the right side of agents-grid-header /
+ skills-grid-header. Keeps `+ Create` / `More` glued together while the parent
+ header's `justify-content: space-between` still separates title from cluster. */
+.header-actions { display: flex; gap: 8px; align-items: center; }
+
+/* ─── Marketplace panel ─── */
+/* Full-page panel mirroring .agents-grid-view sizing: fill the parent .panel column. */
+.marketplace-view {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ background: #fff;
+}
+.marketplace-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 18px 20px 14px;
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+}
+.marketplace-back { flex-shrink: 0; }
+.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;
+ max-width: 320px;
+ margin-left: auto;
+ padding: 6px 10px;
+ border: 1px solid rgba(0,0,0,0.1);
+ border-radius: 6px;
+ font-size: 13px;
+}
+
+.marketplace-categories {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ padding: 12px 20px;
+ border-bottom: 1px solid rgba(0,0,0,0.04);
+ flex-shrink: 0;
+}
+.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;
+}
+/* Reconcile-status banner (boot-time marketplace sync). Friendly muted-blue palette — the
+ yellow / warning tint was misread as "something's wrong" when it actually just means
+ "downloading default content in the background". The banner is **embedded under the panel
+ header** (after the title row, before the body) so it doesn't crowd the panel chrome. */
+.marketplace-reconcile-banner {
+ margin: 0 20px 8px;
+ padding: 8px 12px;
+ border-radius: var(--radius-md, 8px);
+ background: rgba(37, 99, 235, 0.08);
+ color: #1d4ed8;
+ font-size: 12px;
+ line-height: 1.5;
+}
+/* Inline checkbox row inside the upload dialog. Used for the "用户默认安装" toggle so dev
+ can flag the item as part of the fresh-install seed set (`default_install` server flag). */
+.ui-dialog-checkbox-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 12px;
+ font-size: 13px;
+ color: var(--text);
+ cursor: pointer;
+}
+.ui-dialog-checkbox-row input[type="checkbox"] {
+ margin: 0;
+ cursor: pointer;
+}
+/* Dev upload modal: just a centered spinner + label while the multipart POST is in flight. */
+.marketplace-upload-loading {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 12px;
+ padding: 28px 32px;
+}
+.marketplace-upload-spinner {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ border: 3px solid #cbd5e1;
+ border-top-color: #2563eb;
+ animation: marketplace-upload-spin 0.8s linear infinite;
+}
+.marketplace-upload-loading-text {
+ color: #475569;
+ font-size: 13px;
+}
+@keyframes marketplace-upload-spin {
+ to { transform: rotate(360deg); }
+}
+/* Author badge: differentiates same-name uploads. Platform = filled blue; user = outlined.
+ Shared across marketplace card + agents-tab card + skills-tab card so the same badge
+ reads the same everywhere a marketplace-installed item appears. */
+.marketplace-card-chip.is-platform,
+.agent-card-chip.is-platform,
+.skill-card-chip.is-platform {
+ background: rgba(37, 99, 235, 0.12);
+ color: #1d4ed8;
+}
+.marketplace-card-chip.is-user,
+.agent-card-chip.is-user,
+.skill-card-chip.is-user {
+ background: rgba(100, 116, 139, 0.10);
+ color: #475569;
+}
+
+/* Inline spinner for install/uninstall buttons. Sits to the left of the button label. */
+.marketplace-btn-spinner {
+ display: inline-block;
+ width: 10px;
+ height: 10px;
+ margin-right: 6px;
+ border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, 0.5);
+ border-top-color: rgba(255, 255, 255, 0.95);
+ vertical-align: -1px;
+ animation: marketplace-upload-spin 0.8s linear infinite;
+}
+.btn.is-disabled .marketplace-btn-spinner {
+ border-color: rgba(100, 116, 139, 0.4);
+ border-top-color: rgba(100, 116, 139, 0.9);
+}
+/* Flex-wrap with fixed card width: each card is exactly 280px regardless of how many cards
+ the grid holds. A lone card no longer stretches to fill the entire row (which made it look
+ like a list-strip), and a populated grid wraps to a familiar tile layout. Trailing empty
+ space at the end of each row is intentional — keeps card visual rhythm consistent. */
+.marketplace-grid {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 14px;
+ align-content: flex-start;
+}
+.marketplace-grid > .marketplace-card {
+ flex: 0 0 280px;
+ min-width: 0;
+}
+/* Invisible IntersectionObserver target for infinite scroll. Real preload margin comes
+ from `rootMargin` in JS — this just needs to be a reliably-observable element. */
+.mp-load-more-sentinel { height: 1px; width: 100%; }
+.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: baseline; gap: 8px; }
+.marketplace-card-name {
+ font-weight: 600;
+ font-size: 14px;
+ flex: 1;
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.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; min-width: 0; }
+.marketplace-card-chip,
+.skill-card-chip,
+.agent-card-chip {
+ font-size: 11px;
+ padding: 2px 8px;
+ border-radius: 999px;
+ background: rgba(79,70,229,0.08);
+ color: var(--accent, #4f46e5);
+ white-space: nowrap;
+}
+.marketplace-card-chip.muted { background: rgba(0,0,0,0.05); color: var(--muted); }
+/* Version chip — neutral grey to distinguish from category (accent) and author (platform/user). */
+.marketplace-card-chip.is-version,
+.agent-card-chip.is-version,
+.skill-card-chip.is-version {
+ background: rgba(0,0,0,0.05);
+ color: var(--muted);
+}
+/* Footer row: chips on the left flex-1, install/uninstall button hugged to the right via
+ `flex-shrink:0` so it never collapses before the chips. Replaces the old vertically-stacked
+ `.marketplace-card-meta` + `.marketplace-card-actions` arrangement. */
+.marketplace-card-footer {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: auto;
+}
+.marketplace-card-footer > .marketplace-card-meta { flex: 1; }
+.marketplace-card-footer > .marketplace-card-actions { flex-shrink: 0; }
+.marketplace-card-actions { display: flex; }
+
+/* ─── Detail sub-view ─── */
+/* Mirrors the grid-view layout (full-panel flex column) so swapping the two display
+ styles is the only thing needed to switch between browse and detail. */
+.marketplace-grid-view,
+.marketplace-detail-view {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ background: #fff;
+}
+/* Marketplace detail header — padding mirrors `.agents-detail-header` so the in-app and
+ marketplace detail pages share one chrome density. */
+.marketplace-detail-header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 14px 20px;
+ border-bottom: 1px solid var(--border);
+ flex-shrink: 0;
+}
+/* Single-row title block: [name v1.0.0] [chip chip] all in one line. `min-width:0` lets
+ long names ellipsize rather than pushing the install / delete buttons off-screen; chips
+ are `flex-shrink:0` so they hug the title rather than collapsing first. */
+.marketplace-detail-title-wrap { display: flex; align-items: center; gap: 12px; flex: 1; min-width: 0; }
+.marketplace-detail-title { font-size: 16px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }
+.marketplace-detail-version { font-size: 12px; color: var(--muted); margin-left: 8px; font-weight: 400; }
+.marketplace-detail-meta-row { display: flex; gap: 6px; flex-wrap: nowrap; flex-shrink: 0; }
+.marketplace-detail-desc { padding: 12px 20px; color: var(--muted); font-size: 13px; line-height: 1.5; }
+/* Outer body container is just a flex slot — the inner `.agents-detail-body` /
+ `.skills-detail-content` (rendered by `_mpAgentDetailHtml` / `_mpSkillDetailHtml`)
+ owns padding + scroll, so the marketplace preview lines up pixel-for-pixel with the
+ in-app detail page. */
+.marketplace-detail-body { flex: 1; overflow: hidden; display: flex; padding: 0; }
+.marketplace-detail-body > .agents-detail-body,
+.marketplace-detail-body > .skills-detail-content { flex: 1; min-height: 0; }
+.marketplace-detail-loading {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ padding: 48px 20px;
+}
+.marketplace-detail-loading-text { color: var(--muted); font-size: 13px; }
+
+.marketplace-section { margin-top: 18px; }
+.marketplace-section-title { font-size: 14px; font-weight: 600; margin: 0 0 8px; }
+.marketplace-section-body { font-size: 13.5px; line-height: 1.55; }
+.marketplace-section-body ul { padding-left: 20px; margin: 6px 0; }
+.marketplace-section-body code { padding: 1px 5px; background: rgba(0,0,0,0.05); border-radius: 3px; font-size: 12.5px; }
+
+/* Skill detail: split view (file tree left, file body right). */
+.marketplace-skill-split {
+ display: grid;
+ grid-template-columns: 240px 1fr;
+ gap: 18px;
+ margin-top: 12px;
+ min-height: 280px;
+}
+.marketplace-skill-tree {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ font-size: 12.5px;
+ border: 1px solid rgba(0,0,0,0.08);
+ border-radius: 6px;
+ background: #fafafa;
+ overflow-y: auto;
+ max-height: 60vh;
+}
+.marketplace-skill-file {
+ padding: 6px 10px;
+ cursor: pointer;
+ border-bottom: 1px solid rgba(0,0,0,0.04);
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ overflow: hidden;
+}
+.marketplace-skill-file:last-child { border-bottom: none; }
+.marketplace-skill-file:hover { background: rgba(79,70,229,0.04); }
+.marketplace-skill-file.is-active { background: var(--accent-soft, #eef2ff); color: var(--text); font-weight: 500; }
+.marketplace-skill-file-body { min-width: 0; overflow-x: auto; }
+.marketplace-skill-code {
+ font-size: 12px;
+ line-height: 1.5;
+ background: #fafafa;
+ border: 1px solid rgba(0,0,0,0.06);
+ border-radius: 6px;
+ padding: 12px;
+ white-space: pre;
+ overflow: auto;
+ max-height: 70vh;
+}
+
+.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;
+}
+
/* ─── Scheduled-tasks dialog (modules/agent-schedule.js) ─────────────── */
.agent-schedule-dialog { min-width: 480px; max-width: 560px; }
.agent-schedule-title { margin-bottom: 12px; }
diff --git a/test/main/features/agents.test.ts b/test/main/features/agents.test.ts
index cb21d8d3..80ac784c 100644
--- a/test/main/features/agents.test.ts
+++ b/test/main/features/agents.test.ts
@@ -19,16 +19,12 @@ vi.mock('../../../src/main/model/client', () => ({
let tmpDir: string;
let prevWs: string | undefined;
-let prevBuiltinRoot: string | undefined;
const TEST_UID = 'u1';
beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-agents-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
- prevBuiltinRoot = process.env.ORKAS_BUILTIN_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
- // Point builtin source at an empty tmp so startup sync reads nothing.
- process.env.ORKAS_BUILTIN_ROOT = tmpDir;
vi.resetModules();
const users = await import('../../../src/main/features/users');
users.activateUser(TEST_UID);
@@ -36,7 +32,6 @@ beforeEach(async () => {
afterEach(() => {
process.env.ORKAS_WORKSPACE_ROOT = prevWs;
- process.env.ORKAS_BUILTIN_ROOT = prevBuiltinRoot;
streamImpl.current = null;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -52,9 +47,9 @@ function customAgentsDir(): string {
return path.join(tmpDir, TEST_UID, 'cloud', 'agents');
}
-// Builtin agents are top-level data/builtin/agents (shared across uids).
+// Platform (marketplace-installed) agents live under <uid>/local/marketplace/agents/.
function builtinAgentsDir(): string {
- return path.join(tmpDir, 'builtin', 'agents');
+ return path.join(tmpDir, TEST_UID, 'local', 'marketplace', 'agents');
}
function writeCustomAgent(agentId: string, fields: Partial<Record<string, any>> = {}): void {
@@ -554,26 +549,9 @@ describe('agents › extractAgentFieldBlocks › inputs', () => {
});
});
-describe('agents › hashTree', () => {
- it('returns empty for missing dir', async () => {
- const a = await loadAgents();
- expect(a.hashTree(path.join(tmpDir, 'nope'))).toBe('');
- });
-
- it('hashes per-agent agent.json files only and is stable across calls', async () => {
- const a = await loadAgents();
- const dir = path.join(tmpDir, 'mixed');
- fs.mkdirSync(path.join(dir, 'agent-a'), { recursive: true });
- fs.writeFileSync(path.join(dir, 'agent-a', 'agent.json'), '{"a":1}');
- const h1 = a.hashTree(dir);
- // Stability: same content → same hash
- expect(a.hashTree(dir)).toBe(h1);
- // Subdir without agent.json doesn't affect the hash
- fs.mkdirSync(path.join(dir, 'no-spec'));
- fs.writeFileSync(path.join(dir, 'no-spec', 'README.md'), 'docs');
- expect(a.hashTree(dir)).toBe(h1);
- });
-});
+// hashTree / syncBuiltinAgents removed: there is no globally-shared `data/builtin/`
+// tree anymore. Platform agents now arrive via marketplace install and live at
+// `<uid>/local/marketplace/agents/<id>/` per machine — see features/marketplace_*.ts.
describe('agents › createCustomAgent', () => {
it('creates a 12-hex-id agent with defaults', async () => {
@@ -1046,99 +1024,6 @@ describe('agents › list cache invalidation', () => {
});
});
-// 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);
- });
-});
+// (The legacy marketplace-sentinel / data/builtin sync tests are gone. Marketplace
+// installs now live at `<uid>/local/marketplace/agents/<id>/` and are reconciled from
+// the cloud-synced `installs.json` manifest — see features/marketplace_*.ts.)
diff --git a/test/main/features/group_chat/agents-index.test.ts b/test/main/features/group_chat/agents-index.test.ts
index 00c4e9b1..a97764a7 100644
--- a/test/main/features/group_chat/agents-index.test.ts
+++ b/test/main/features/group_chat/agents-index.test.ts
@@ -35,7 +35,7 @@ function customAgentsDir(): string {
return path.join(tmpDir, TEST_UID, 'cloud', 'agents');
}
function builtinAgentsDir(): string {
- return path.join(tmpDir, 'builtin', 'agents');
+ return path.join(tmpDir, TEST_UID, 'local', 'marketplace', 'agents');
}
function writeAgent(root: string, agent_id: string, body: Record<string, unknown>) {
@@ -51,8 +51,8 @@ beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-agentsidx-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
- // Force fresh module loads so `BUILTIN_AGENTS_DIR` (module-level const
- // resolved at paths.ts import time) gets the test ORKAS_WORKSPACE_ROOT.
+ // Force fresh module loads so per-uid roots (resolved at paths.ts import time
+ // for module-level constants) align with the test ORKAS_WORKSPACE_ROOT.
vi.resetModules();
const users = await import('../../../../src/main/features/users');
users.activateUser(TEST_UID);
diff --git a/test/main/features/reflection-digest.test.ts b/test/main/features/reflection-digest.test.ts
index 2b6f0d52..f9504bcc 100644
--- a/test/main/features/reflection-digest.test.ts
+++ b/test/main/features/reflection-digest.test.ts
@@ -5,15 +5,12 @@ import * as path from 'node:path';
let tmpDir: string;
let prevWs: string | undefined;
-let prevBuiltinRoot: string | undefined;
const TEST_UID = 'u1';
beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-digest-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
- prevBuiltinRoot = process.env.ORKAS_BUILTIN_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
- process.env.ORKAS_BUILTIN_ROOT = tmpDir;
vi.resetModules();
const users = await import('../../../src/main/features/users');
users.activateUser(TEST_UID);
@@ -21,7 +18,6 @@ beforeEach(async () => {
afterEach(() => {
process.env.ORKAS_WORKSPACE_ROOT = prevWs;
- process.env.ORKAS_BUILTIN_ROOT = prevBuiltinRoot;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
diff --git a/test/main/features/reflection-trigger.test.ts b/test/main/features/reflection-trigger.test.ts
index 980cdd9d..dd4ab949 100644
--- a/test/main/features/reflection-trigger.test.ts
+++ b/test/main/features/reflection-trigger.test.ts
@@ -5,7 +5,6 @@ import * as path from 'node:path';
let tmpDir: string;
let prevWs: string | undefined;
-let prevBuiltinRoot: string | undefined;
const TEST_UID = 'u1';
function stateFile(uid: string): string {
@@ -29,10 +28,7 @@ function writeAgent(uid: string, agentId: string): void {
beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-reflect-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
- prevBuiltinRoot = process.env.ORKAS_BUILTIN_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
- // Empty tmpDir as builtin root → no builtin agents picked up.
- process.env.ORKAS_BUILTIN_ROOT = tmpDir;
vi.resetModules();
const users = await import('../../../src/main/features/users');
users.activateUser(TEST_UID);
@@ -40,7 +36,6 @@ beforeEach(async () => {
afterEach(() => {
process.env.ORKAS_WORKSPACE_ROOT = prevWs;
- process.env.ORKAS_BUILTIN_ROOT = prevBuiltinRoot;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
diff --git a/test/main/features/skills.test.ts b/test/main/features/skills.test.ts
index 366db536..2cff609b 100644
--- a/test/main/features/skills.test.ts
+++ b/test/main/features/skills.test.ts
@@ -19,17 +19,12 @@ vi.mock('../../../src/main/model/client', () => ({
let tmpDir: string;
let prevWs: string | undefined;
-let prevBuiltinRoot: string | undefined;
const TEST_UID = 'u1';
beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-skills-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
- prevBuiltinRoot = process.env.ORKAS_BUILTIN_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
- // Point builtin source at an empty dir so syncBuiltinSkills doesn't fire
- // against the real repo during tests.
- process.env.ORKAS_BUILTIN_ROOT = tmpDir;
vi.resetModules();
const users = await import('../../../src/main/features/users');
users.activateUser(TEST_UID);
@@ -37,7 +32,6 @@ beforeEach(async () => {
afterEach(() => {
process.env.ORKAS_WORKSPACE_ROOT = prevWs;
- process.env.ORKAS_BUILTIN_ROOT = prevBuiltinRoot;
streamImpl.current = null;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -51,8 +45,8 @@ function customSkillsDir(): string {
}
function builtinSkillsDir(): string {
- // Top-level data/builtin/skills — shared across uids.
- return path.join(tmpDir, 'builtin', 'skills');
+ // Platform (marketplace-installed) skills live under <uid>/local/marketplace/skills/.
+ return path.join(tmpDir, TEST_UID, 'local', 'marketplace', 'skills');
}
function writeCustomSkill(id: string, frontmatter = `name: "${id}"\ndescription: "test"`, body = '# body'): void {
@@ -493,47 +487,9 @@ describe('skills › applySkillContainerFromCommander › edit', () => {
});
});
-describe('skills › hashTree', () => {
- it('returns empty string for missing dir', async () => {
- const s = await loadSkills();
- expect(s.hashTree(path.join(tmpDir, 'nope'))).toBe('');
- });
-
- it('returns stable hex digest for same content', async () => {
- const s = await loadSkills();
- const root = path.join(tmpDir, 'stable');
- fs.mkdirSync(root, { recursive: true });
- fs.writeFileSync(path.join(root, 'a.txt'), 'hello');
- const h1 = s.hashTree(root);
- const h2 = s.hashTree(root);
- expect(h1).toMatch(/^[0-9a-f]{64}$/);
- expect(h1).toBe(h2);
- });
-
- it('changes when a file changes', async () => {
- const s = await loadSkills();
- const root = path.join(tmpDir, 'changes');
- fs.mkdirSync(root, { recursive: true });
- fs.writeFileSync(path.join(root, 'a.txt'), 'v1');
- const h1 = s.hashTree(root);
- fs.writeFileSync(path.join(root, 'a.txt'), 'v2');
- const h2 = s.hashTree(root);
- expect(h1).not.toBe(h2);
- });
-
- it('ignores dotfiles and ignored dirs', async () => {
- const s = await loadSkills();
- const root = path.join(tmpDir, 'ignored');
- fs.mkdirSync(root, { recursive: true });
- fs.writeFileSync(path.join(root, 'a.txt'), 'hello');
- const h1 = s.hashTree(root);
- fs.writeFileSync(path.join(root, '.DS_Store'), 'garbage');
- fs.mkdirSync(path.join(root, '__pycache__'));
- fs.writeFileSync(path.join(root, '__pycache__', 'x.pyc'), 'bin');
- const h2 = s.hashTree(root);
- expect(h1).toBe(h2);
- });
-});
+// hashTree / syncBuiltinSkills removed: there is no globally-shared `data/builtin/`
+// tree anymore. Platform skills now arrive via marketplace install and live at
+// `<uid>/local/marketplace/skills/<id>/` per machine — see features/marketplace_*.ts.
describe('skills › listSkills', () => {
it('returns empty when both dirs are missing', async () => {
@@ -831,77 +787,6 @@ describe('skills › streamSendToSkillChat synthesized progress', () => {
});
});
-// 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);
- });
-});
+// (The legacy marketplace-sentinel / data/builtin sync tests are gone. Marketplace
+// installs now live at `<uid>/local/marketplace/skills/<id>/` and are reconciled from
+// the cloud-synced `installs.json` manifest — see features/marketplace_*.ts.)
diff --git a/test/main/model/skill-registry.test.ts b/test/main/model/skill-registry.test.ts
index 1956135b..9dea9b59 100644
--- a/test/main/model/skill-registry.test.ts
+++ b/test/main/model/skill-registry.test.ts
@@ -9,17 +9,17 @@ import * as path from 'node:path';
// scan them — the loader is pure FS + frontmatter parsing, no network/LLM.
//
// Post-refactor layout:
-// builtin skills → `<WS_ROOT>/builtin/skills/<id>/SKILL.md`
-// custom skills → `<WS_ROOT>/<uid>/cloud/skills/<id>/SKILL.md`
-// The loader scans `[userSkillsDir(activeUid), BUILTIN_SKILLS_DIR]`, with
-// custom listed first so same-id custom overrides builtin.
+// platform skills → `<WS_ROOT>/<uid>/local/marketplace/skills/<id>/SKILL.md`
+// custom skills → `<WS_ROOT>/<uid>/cloud/skills/<id>/SKILL.md`
+// The loader scans `[userSkillsDir(activeUid), userMarketplaceSkillsDir(activeUid)]`,
+// with custom listed first so same-id custom overrides platform.
let tmpDir: string;
let prevWs: string | undefined;
const TEST_UID = 'u1';
function builtinDir(): string {
- return path.join(tmpDir, 'builtin', 'skills');
+ return path.join(tmpDir, TEST_UID, 'local', 'marketplace', 'skills');
}
function customDir(): string {
return path.join(tmpDir, TEST_UID, 'cloud', 'skills');
diff --git a/test/main/paths.test.ts b/test/main/paths.test.ts
index 5b693fa1..bfbf22f1 100644
--- a/test/main/paths.test.ts
+++ b/test/main/paths.test.ts
@@ -9,21 +9,16 @@ import * as path from 'node:path';
let tmpDir: string;
let prevWs: string | undefined;
-let prevBuiltin: string | undefined;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-paths-'));
prevWs = process.env.ORKAS_WORKSPACE_ROOT;
- prevBuiltin = process.env.ORKAS_BUILTIN_ROOT;
process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
- delete process.env.ORKAS_BUILTIN_ROOT;
vi.resetModules();
});
afterEach(() => {
process.env.ORKAS_WORKSPACE_ROOT = prevWs;
- if (prevBuiltin === undefined) delete process.env.ORKAS_BUILTIN_ROOT;
- else process.env.ORKAS_BUILTIN_ROOT = prevBuiltin;
fs.rmSync(tmpDir, { recursive: true, force: true });
});
@@ -45,7 +40,7 @@ describe('paths › roots', () => {
});
});
-describe('paths › top-level (users.json / logs / builtin)', () => {
+describe('paths › top-level (users.json / logs)', () => {
it('USERS_FILE sits at the data root', async () => {
const p = await import('../../src/main/paths');
expect(p.USERS_FILE).toBe(path.join(p.WS_ROOT, 'users.json'));
@@ -55,14 +50,6 @@ describe('paths › top-level (users.json / logs / builtin)', () => {
const p = await import('../../src/main/paths');
expect(p.LOGS_DIR).toBe(path.join(p.WS_ROOT, 'logs'));
});
-
- it('BUILTIN_* dirs hang off the top-level builtin/', async () => {
- const p = await import('../../src/main/paths');
- expect(p.BUILTIN_ROOT).toBe(path.join(p.WS_ROOT, 'builtin'));
- expect(p.BUILTIN_AGENTS_DIR).toBe(path.join(p.WS_ROOT, 'builtin', 'agents'));
- expect(p.BUILTIN_SKILLS_DIR).toBe(path.join(p.WS_ROOT, 'builtin', 'skills'));
- });
-
});
describe('paths › cloud-synced per-user', () => {
@@ -130,38 +117,36 @@ describe('paths › local (per-user, not synced)', () => {
expect(p.userWorkspaceConfigFile(uid))
.toBe(path.join(p.WS_ROOT, uid, 'local', 'workspace.json'));
});
-});
-describe('paths › builtin source dirs', () => {
- it('default builtin sources sit under SRC_ROOT/builtin', async () => {
+ it('marketplace install dirs land under <uid>/local/marketplace/', async () => {
const p = await import('../../src/main/paths');
- expect(p.BUILTIN_SKILLS_SOURCE).toBe(path.join(p.SRC_ROOT, 'builtin', 'skills'));
- expect(p.BUILTIN_AGENTS_SOURCE).toBe(path.join(p.SRC_ROOT, 'builtin', 'agents'));
+ const uid = 'u1';
+ const root = path.join(p.WS_ROOT, uid, 'local', 'marketplace');
+ expect(p.userMarketplaceDir(uid)).toBe(root);
+ expect(p.userMarketplaceAgentsDir(uid)).toBe(path.join(root, 'agents'));
+ expect(p.userMarketplaceSkillsDir(uid)).toBe(path.join(root, 'skills'));
+ expect(p.userMarketplaceAgentDir(uid, 'a1')).toBe(path.join(root, 'agents', 'a1'));
+ expect(p.userMarketplaceSkillDir(uid, 's1')).toBe(path.join(root, 'skills', 's1'));
});
- it('ORKAS_BUILTIN_ROOT overrides the source root', async () => {
- process.env.ORKAS_BUILTIN_ROOT = path.join(tmpDir, 'alt-builtin');
- vi.resetModules();
+ it('marketplace cloud-sync manifest lands under <uid>/cloud/marketplace/installs.json', async () => {
const p = await import('../../src/main/paths');
- expect(p.BUILTIN_SKILLS_SOURCE).toBe(path.join(tmpDir, 'alt-builtin', 'skills'));
- expect(p.BUILTIN_AGENTS_SOURCE).toBe(path.join(tmpDir, 'alt-builtin', 'agents'));
+ const uid = 'u1';
+ expect(p.userMarketplaceInstallsFile(uid))
+ .toBe(path.join(p.WS_ROOT, uid, 'cloud', 'marketplace', 'installs.json'));
});
});
describe('paths › ensureTopLevelLayout side effect', () => {
it('mkdirs the top-level skeleton on import (no uid-specific dirs)', async () => {
await import('../../src/main/paths');
- for (const d of [
- path.join(tmpDir, 'logs'),
- path.join(tmpDir, 'builtin', 'agents'),
- path.join(tmpDir, 'builtin', 'skills'),
- ]) {
- expect(fs.existsSync(d), `expected ${d} to exist`).toBe(true);
- }
+ expect(fs.existsSync(path.join(tmpDir, 'logs')), 'expected logs/ to exist').toBe(true);
// Crucially: no `config/` at the top level any more — that was legacy.
expect(fs.existsSync(path.join(tmpDir, 'config'))).toBe(false);
// And no `shared/` — folded into `<uid>/cloud/`.
expect(fs.existsSync(path.join(tmpDir, 'shared'))).toBe(false);
+ // And no `builtin/` — pre-marketplace tree is retired.
+ expect(fs.existsSync(path.join(tmpDir, 'builtin'))).toBe(false);
});
it('ensureUserLayout is idempotent + builds both cloud and local subtrees', async () => {