Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(skills,core): remote-claude-code skill, preinstall:false manual-install marker (#247)

Yaowei Zhengd2b2fd0a9eaf
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index f3a95e8a..120edba0 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -15,7 +15,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import {
- loadLibrarySkills,
+ loadPreinstalledSkills,
parseSkillFrontmatter,
type SkillMetadata,
} from "@prismshadow/penguin-skills";
@@ -163,15 +163,15 @@ export async function loadOrInitAgentState(opts?: {
};
agentsMd = preset?.agentsMd ?? defaultAgentsMd();
// Only installs the Skills specified by preset (a plain newly created Agent gets none
- // pre-installed). A default_agent with no
- // preset (e.g. created on first CLI run) still gets every Skill in the library pre-installed
- // — the install policy follows Agent identity, not whether creation came from the server or
+ // pre-installed). A default_agent with no preset (e.g. created on first CLI run) still gets
+ // the library's preinstalled set (Skills marked `preinstall: false` stay manual-install) —
+ // the install policy follows Agent identity, not whether creation came from the server or
// was done directly via SDK/CLI.
// Skills have no dedicated tool: metadata is injected via {{SKILL_METADATA}}, and the model
// reads SKILL.md with shell and follows it.
const skills =
opts?.preset === undefined && agentId === DEFAULT_AGENT_ID
- ? loadLibrarySkills()
+ ? loadPreinstalledSkills()
: (opts?.preset?.skills ?? []);
await Promise.all([
fs.writeFile(mdPath, agentsMd, "utf8"),
@@ -269,34 +269,66 @@ function vaultKeysList(keys: string[]): string {
return keys.map((key) => `- ${key}`).join("\n");
}
+/**
+ * Guards a Skill auxiliary-file path (relative to the skill directory) before it's written:
+ * rejects empty, absolute, backslash-bearing, and any `..`-segment path so a file entry can never
+ * escape `skills/<name>/`. Mirrors the archive route's zip-slip check for the library-install path.
+ */
+function assertSafeSkillFile(rel: string): void {
+ if (
+ rel.length === 0 ||
+ path.isAbsolute(rel) ||
+ rel.includes("\\") ||
+ rel.split("/").some((segment) => segment === "..")
+ ) {
+ throw new Error(
+ `Invalid skill file path ${JSON.stringify(rel)}: it must stay within the skill directory.`,
+ );
+ }
+}
+
/**
* Installs a Skill into the target Agent: writes `skills/<name>/SKILL.md` verbatim (the full
- * SKILL.md content including frontmatter, ensuring a trailing newline); if the directory
- * already exists, it's overwritten (reinstalling = updating to the latest content). An optional
- * icon.svg is written alongside SKILL.md; if this install doesn't
- * include an icon, any old icon.svg is removed, preserving "overwrite update" semantics (the
- * directory content matches the Skill being installed).
+ * SKILL.md content including frontmatter, ensuring a trailing newline). An optional icon.svg and
+ * any auxiliary `files` the SKILL.md references (e.g. `reference/API.md`, subdirectories
+ * preserved) are written alongside it. The directory is replaced wholesale first, so reinstalling
+ * updates to the latest content and drops files the new version no longer ships — the directory
+ * content always matches the Skill being installed. Each file path is checked to stay within the
+ * skill directory before anything is written.
* Docs: /docs/skills § "Installation and storage".
*/
export async function installSkill(
root: string,
projectId: string,
agentId: string,
- skill: { name: string; content: string; icon?: string },
+ skill: { name: string; content: string; icon?: string; files?: Record<string, string> },
): Promise<void> {
assertValidId("project_id", projectId);
assertValidId("agent_id", agentId);
assertValidId("skill_name", skill.name);
+ const auxiliary = Object.entries(skill.files ?? {});
+ for (const [rel] of auxiliary) assertSafeSkillFile(rel);
const dir = path.join(skillsDir(root, projectId, agentId), skill.name);
+ // Clean replace: drop the old directory so no stale file survives a reinstall (same semantics
+ // as the archive route), then write SKILL.md, the optional icon, and every auxiliary file.
+ await fs.rm(dir, { recursive: true, force: true });
await fs.mkdir(dir, { recursive: true });
const content = skill.content.endsWith("\n") ? skill.content : `${skill.content}\n`;
- const iconPath = path.join(dir, "icon.svg");
- await Promise.all([
+ const writes: Array<Promise<unknown>> = [
fs.writeFile(path.join(dir, "SKILL.md"), content, "utf8"),
- skill.icon !== undefined
- ? fs.writeFile(iconPath, skill.icon, "utf8")
- : fs.rm(iconPath, { force: true }),
- ]);
+ ];
+ if (skill.icon !== undefined) {
+ writes.push(fs.writeFile(path.join(dir, "icon.svg"), skill.icon, "utf8"));
+ }
+ for (const [rel, data] of auxiliary) {
+ const file = path.join(dir, rel);
+ writes.push(
+ fs
+ .mkdir(path.dirname(file), { recursive: true })
+ .then(() => fs.writeFile(file, data, "utf8")),
+ );
+ }
+ await Promise.all(writes);
}
/** Uninstalls a Skill: deletes the entire `skills/<name>/` directory; idempotent, no error if it doesn't exist. */
diff --git a/packages/core/src/state/builtin-agents.ts b/packages/core/src/state/builtin-agents.ts
index bf76a41e..13f5c990 100644
--- a/packages/core/src/state/builtin-agents.ts
+++ b/packages/core/src/state/builtin-agents.ts
@@ -3,15 +3,16 @@
* (the library files are read live when building the preset).
*
* - Every Project comes with a single builtin Agent: `default_agent` (the General Agent, the
- * default conversational Agent), which has every Skill in the library installed at
- * initialization. Dedicated capabilities (creating an Agent, optimizing an Agent, etc.)
+ * default conversational Agent), which has the library's preinstalled Skill set installed at
+ * initialization (Skills marked `preinstall: false` are excluded and stay manual-install).
+ * Dedicated capabilities (creating an Agent, optimizing an Agent, etc.)
* are carried by Skills rather than dedicated builtin Agents.
* - The preset carries no AGENTS.md: the default AGENTS.md is empty, with delegation and task
* conventions living in the default template's Suggested Workflows section.
* - Skill metadata is auto-injected into the system Prompt via the `{{SKILL_METADATA}}`
* placeholder; it's not registered in AGENTS.md.
*/
-import { loadLibrarySkills, type LibrarySkill } from "@prismshadow/penguin-skills";
+import { loadPreinstalledSkills, type LibrarySkill } from "@prismshadow/penguin-skills";
import { DEFAULT_AGENT_ID } from "./paths.js";
/** The set of Project builtin Agent ids (supplied along with the Project, cannot be deleted from Web). */
@@ -32,7 +33,7 @@ export interface AgentPreset {
/**
* The preset list for a Project's builtin Agents (each initialized in turn when the Project is
* created; an existing Agent is never overwritten). The only builtin Agent is default_agent:
- * installs every Skill in the library, with no preset AGENTS.md.
+ * installs the library's preinstalled Skills, with no preset AGENTS.md.
*/
export function builtinProjectAgentPresets(): Array<{ agentId: string; preset: AgentPreset }> {
return [
@@ -41,7 +42,7 @@ export function builtinProjectAgentPresets(): Array<{ agentId: string; preset: A
preset: {
name: "General Agent",
description: "General-purpose agent that completes the user's requests with its tools.",
- skills: loadLibrarySkills(),
+ skills: loadPreinstalledSkills(),
},
},
];
diff --git a/packages/core/test/agent-skills.test.ts b/packages/core/test/agent-skills.test.ts
index ca12f8d7..75de5c79 100644
--- a/packages/core/test/agent-skills.test.ts
+++ b/packages/core/test/agent-skills.test.ts
@@ -80,6 +80,41 @@ describe("installSkill / removeSkill", () => {
);
});
+ it("writes auxiliary files a SKILL.md references (subdirs preserved), and a reinstall drops ones the new version omits", async () => {
+ await installSkill(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID, {
+ name: "multi",
+ content: "---\nname: multi\n---\nBody\n",
+ files: { "reference/API.md": "# API\n", "reference/nested/notes.txt": "notes\n" },
+ });
+ expect(await fs.readFile(skillFile("multi", "reference/API.md"), "utf8")).toBe("# API\n");
+ expect(await fs.readFile(skillFile("multi", "reference/nested/notes.txt"), "utf8")).toBe(
+ "notes\n",
+ );
+
+ // Reinstall with a smaller file set: the whole directory is replaced, so the dropped file is gone.
+ await installSkill(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID, {
+ name: "multi",
+ content: "---\nname: multi\n---\nBody\n",
+ files: { "reference/API.md": "# API v2\n" },
+ });
+ expect(await fs.readFile(skillFile("multi", "reference/API.md"), "utf8")).toBe("# API v2\n");
+ await expect(fs.access(skillFile("multi", "reference/nested/notes.txt"))).rejects.toThrow();
+ });
+
+ it("rejects auxiliary file paths that escape the skill directory, writing nothing", async () => {
+ for (const bad of ["../evil.md", "/abs.md", "a\\b.md", "ref/../../x.md", ""]) {
+ await expect(
+ installSkill(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID, {
+ name: "guarded",
+ content: "---\nname: guarded\n---\nBody\n",
+ files: { [bad]: "x" },
+ }),
+ ).rejects.toThrow(/skill file path/);
+ // The guard runs before any write: the skill directory is never created.
+ await expect(fs.access(skillMd("guarded"))).rejects.toThrow();
+ }
+ });
+
it("removeSkill deletes the whole skill directory and is idempotent", async () => {
const skill = librarySkill("penguin-sdk")!;
await install(skill.name, skill.content);
diff --git a/packages/core/test/builtin-agents.test.ts b/packages/core/test/builtin-agents.test.ts
index 83a4446c..12399bd1 100644
--- a/packages/core/test/builtin-agents.test.ts
+++ b/packages/core/test/builtin-agents.test.ts
@@ -1,14 +1,15 @@
/**
* Built-in agent provisioning and skill library install policy: the sole built-in agent
- * default_agent comes pre-installed with every skill in the library, an ordinary newly created
- * agent starts with zero skills, and the default AGENTS.md is an empty file; provisionProjectAgents
- * is idempotent and never overwrites existing config.
+ * default_agent comes pre-installed with the library's preinstalled skill set (skills marked
+ * `preinstall: false` stay manual-install), an ordinary newly created agent starts with zero
+ * skills, and the default AGENTS.md is an empty file; provisionProjectAgents is idempotent and
+ * never overwrites existing config.
*/
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { librarySkill, loadLibrarySkills } from "@prismshadow/penguin-skills";
+import { librarySkill, loadPreinstalledSkills } from "@prismshadow/penguin-skills";
import {
agentsMdPath,
assembleSystemPrompt,
@@ -58,17 +59,20 @@ describe("Skill installation policy", () => {
expect(onDisk).toBe("");
});
- it("a default_agent created directly without a preset (e.g. first CLI run) likewise preinstalls every Skill in the library", async () => {
+ it("a default_agent created directly without a preset (e.g. first CLI run) likewise gets the library's preinstalled set", async () => {
await loadOrInitAgentState({ agentId: DEFAULT_AGENT_ID });
const names = (await listInstalledSkills(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID)).map(
(s) => s.name,
);
- expect(names).toEqual(loadLibrarySkills().map((s) => s.name));
+ expect(names).toEqual(loadPreinstalledSkills().map((s) => s.name));
+ // A `preinstall: false` library skill stays out of the preinstalled set (manual install only).
+ expect(librarySkill("remote-claude-code")?.preinstall).toBe(false);
+ expect(names).not.toContain("remote-claude-code");
});
});
describe("provisionProjectAgents", () => {
- it("the only built-in Agent default_agent: installs every Skill in the library, AGENTS.md is empty", async () => {
+ it("the only built-in Agent default_agent: installs the library's preinstalled Skills, AGENTS.md is empty", async () => {
const ids = await provisionProjectAgents();
expect(ids).toEqual([DEFAULT_AGENT_ID]);
expect(BUILTIN_AGENT_IDS).toEqual([DEFAULT_AGENT_ID]);
@@ -80,7 +84,9 @@ describe("provisionProjectAgents", () => {
expect(state.agentsMd).toBe("");
const installed = await listInstalledSkills(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
- expect(installed.map((s) => s.name).sort()).toEqual(loadLibrarySkills().map((s) => s.name));
+ expect(installed.map((s) => s.name).sort()).toEqual(
+ loadPreinstalledSkills().map((s) => s.name),
+ );
// On-disk content matches the library's SKILL.md verbatim (install copies the full text).
const sdkMd = await fs.readFile(skillMdPath(DEFAULT_AGENT_ID, "penguin-sdk"), "utf8");
expect(sdkMd).toBe(librarySkill("penguin-sdk")!.content);
@@ -96,7 +102,9 @@ describe("provisionProjectAgents", () => {
);
expect(md).toBe("");
const installed = await listInstalledSkills(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID);
- expect(installed.map((s) => s.name).sort()).toEqual(loadLibrarySkills().map((s) => s.name));
+ expect(installed.map((s) => s.name).sort()).toEqual(
+ loadPreinstalledSkills().map((s) => s.name),
+ );
});
it("an existing Agent is not overwritten (the preset only applies at initialization)", async () => {
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index f1945ce3..33e77994 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -5,7 +5,7 @@ description: Skills package reusable instructions as directories with a SKILL.md
## Anatomy of a Skill
-A Skill is a directory containing a `SKILL.md`, optionally with a custom `icon.svg`. The directory name is the authoritative skill name and must match `^[A-Za-z0-9_-]+$`; a `name` in the frontmatter is overridden by it.
+A Skill is a directory containing a `SKILL.md`, optionally with a custom `icon.svg` and any other files the `SKILL.md` references (for example a `reference/` subtree it links to). The directory name is the authoritative skill name and must match `^[A-Za-z0-9_-]+$`; a `name` in the frontmatter is overridden by it.
Frontmatter fields:
@@ -14,6 +14,7 @@ Frontmatter fields:
| `name` | Skill name, matching the directory name |
| `description` | English one-liner injected into the system prompt |
| `short_description` / `short_description_zh` | UI labels for compact spots such as cards; not injected into the prompt |
+| `preinstall` | Optional; `false` keeps the Skill out of default_agent's preinstalled set — install it manually from the library |
| `version` | Natural-number version, default 1 |
| `updated` | Update date |
@@ -32,7 +33,7 @@ updated: 2026-07-17
Concrete steps, boundaries and acceptance criteria...
```
-Parsing is tolerant: only `key: value` scalar lines inside the first `---` block are recognized; a `version` that is not a natural number falls back to 1, and a missing `updated` defaults to empty.
+Parsing is tolerant: only `key: value` scalar lines inside the first `---` block are recognized; a `version` that is not a natural number falls back to 1, and a missing `updated` defaults to empty. For `preinstall`, only the literal `false` is recognized.
## Progressive loading
@@ -46,9 +47,9 @@ If a message only names a skill without a concrete task, the model is instructed
Installed Skills live under `agent_state/skills/<name>/` inside the Agent State. The files are the source of truth: every read goes straight to disk with no cache, which makes Skills naturally editable.
-- The built-in Agent `default_agent` gets the whole library installed at initialization;
+- The built-in Agent `default_agent` gets the whole library installed at initialization, except Skills marked `preinstall: false` — those are only ever installed manually;
- other Agents install on demand — through the Web UI's Skill library page, or via the SDK;
-- installing writes the library `SKILL.md` verbatim (frontmatter included) and copies any `icon.svg` alongside it.
+- installing writes the library `SKILL.md` verbatim (frontmatter included) and copies any `icon.svg` and other files in the skill directory (subdirectories preserved) alongside it; each install replaces the whole directory, so reinstalling drops files a newer version no longer ships.
The library ships as the npm package `@prismshadow/penguin-skills`, carrying the raw `skills/` directory in the tarball; at runtime the package's `skills/<name>/SKILL.md` files are likewise the source of truth for library content.
@@ -63,6 +64,7 @@ The built-in Skills, by group (the group manifest is `SKILL_GROUPS` in `packages
| | `bento-slides` | Author and edit Bento presentations: single-file `.bento.html` decks whose document is JSON, mapping material to charts, morph transitions and state slides |
| Software Development | `web-design` | Penguin visual language for generated web pages and app UIs: design tokens, components, light/dark themes and chat layouts |
| | `software-engineering` | Complete software-engineering tasks: investigate and review code, implement fixes, features and refactors with minimal scope, validate changes, and report verified outcomes |
+| | `remote-claude-code` | Run Claude Code on a remote host over SSH — a persistent expect session, headless `-p` with the stdin fix, a tmux-driven interactive TUI and multi-turn continuity (not preinstalled: install from the library when needed) |
| AI App Development | `penguin-sdk` | Build AI and RAG apps on the SDK: the createSession/run streaming loop plus a complete retrieval recipe with chunk-revealing citations |
| | `penguin-cli` | Manage model API keys, default models and per-agent Vault secrets with the penguin CLI |
| | `agenthub-models` | Call model APIs through `@prismshadow/agenthub`: streaming text, image generation, speech synthesis and embeddings |
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index d816028b..60c68c6a 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -5,7 +5,7 @@ description: Skill 以目录加 SKILL.md 承载可复用指令,元数据先行
## Skill 的形态
-一个 Skill 就是一个目录:内含一份 `SKILL.md`,可选附带一个 `icon.svg` 自定义图标。目录名即权威的 Skill 名,须匹配 `^[A-Za-z0-9_-]+$`;frontmatter 中的 `name` 以目录名为准。
+一个 Skill 就是一个目录:内含一份 `SKILL.md`,可选附带一个 `icon.svg` 自定义图标,以及 `SKILL.md` 引用的其他文件(例如它链接到的 `reference/` 子目录)。目录名即权威的 Skill 名,须匹配 `^[A-Za-z0-9_-]+$`;frontmatter 中的 `name` 以目录名为准。
frontmatter 字段:
@@ -14,6 +14,7 @@ frontmatter 字段:
| `name` | Skill 名,与目录名一致 |
| `description` | 英文单行描述,注入系统 Prompt |
| `short_description` / `short_description_zh` | UI 短标签(卡片等紧凑位置用),不注入 Prompt |
+| `preinstall` | 可选;`false` 表示不进入 default_agent 的预装集合,仅可从技能库手动安装 |
| `version` | 自然数版本号,默认 1 |
| `updated` | 更新日期 |
@@ -32,7 +33,7 @@ updated: 2026-07-17
具体的步骤、边界与验收标准……
```
-解析是容错的:只识别首个 `---` 块内的 `key: value` 标量行;`version` 不是自然数时回退为 1,`updated` 缺省为空。
+解析是容错的:只识别首个 `---` 块内的 `key: value` 标量行;`version` 不是自然数时回退为 1,`updated` 缺省为空;`preinstall` 仅识别字面量 `false`。
## 渐进式加载
@@ -46,9 +47,9 @@ Skill 采用「先索引、后正文」的设计:系统 Prompt 经 `{{SKILL_ME
已安装的 Skill 位于 Agent State 的 `agent_state/skills/<name>/`。文件即事实源:每次读取直接读文件、不设缓存,因此 Skill 天然可编辑。
-- 内置 Agent `default_agent` 在初始化时安装完整 Skill 库;
+- 内置 Agent `default_agent` 在初始化时安装完整 Skill 库(标记 `preinstall: false` 的 Skill 除外,仅手动安装);
- 其他 Agent 按需安装:经 Web 界面的 Skill 库页,或经 SDK;
-- 安装即把库里的 `SKILL.md` 原样写入(含 frontmatter),目录内的 `icon.svg` 一并拷贝。
+- 安装即把库里的 `SKILL.md` 原样写入(含 frontmatter),目录内的 `icon.svg` 与其他文件(保留子目录)一并拷贝;每次安装整目录替换,因此重装会丢弃新版本不再携带的文件。
Skill 库以 npm 包 `@prismshadow/penguin-skills` 发布,tarball 直接携带原始 `skills/` 目录;运行时库内容的事实源同样是包内的 `skills/<name>/SKILL.md` 文件。
@@ -63,6 +64,7 @@ Skill 库以 npm 包 `@prismshadow/penguin-skills` 发布,tarball 直接携带
| | `bento-slides` | 制作与编辑 Bento 演示文稿:单文件 `.bento.html`、文档即 JSON,把素材映射到图表、morph 转场与状态页 |
| 软件开发 | `web-design` | 生成网页与应用界面的 Penguin 视觉语言:设计令牌、组件配方、明暗主题与聊天布局 |
| | `software-engineering` | 完成软件工程任务:调查与审查代码,以最小改动实现修复、特性与重构,验证改动并报告经过确认的结果 |
+| | `remote-claude-code` | 通过 SSH 在远程主机上驱动 Claude Code:expect 持久会话、headless `-p` 的 stdin 修正、tmux 驱动的交互 TUI 与多轮续接(不预装,按需从技能库安装) |
| AI 应用开发 | `penguin-sdk` | 基于 SDK 构建 AI 与 RAG 应用:createSession/run 流式循环,外加带可溯源引用的完整检索配方 |
| | `penguin-cli` | 用 penguin CLI 管理模型 API Key、默认模型与各 Agent 的 Vault 密钥 |
| | `agenthub-models` | 经 `@prismshadow/agenthub` 调用模型 API:流式文本、图像生成、语音合成与 Embedding |
diff --git a/packages/server/test/builtin-agents.test.ts b/packages/server/test/builtin-agents.test.ts
index 73af9df3..c0fe9643 100644
--- a/packages/server/test/builtin-agents.test.ts
+++ b/packages/server/test/builtin-agents.test.ts
@@ -1,13 +1,14 @@
/**
* Project built-in Agent provisioning: the only built-in Agent is default_agent
- * (pre-installed with every Skill in the library, empty AGENTS.md, cannot be deleted).
+ * (pre-installed with the library's preinstalled Skill set — `preinstall: false` skills
+ * excluded — empty AGENTS.md, cannot be deleted).
* Specialized capabilities are now carried by Skills — agent_creator / agent_optimizer
* are no longer built-in Agents: neither provisioned nor deletion-protected.
*/
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { loadLibrarySkills } from "@prismshadow/penguin-skills";
+import { loadPreinstalledSkills } from "@prismshadow/penguin-skills";
import type { BenchmarksResponse } from "../src/api/types.js";
import { apiClient, createTestApp, provisionUser, type TestApp } from "./helpers.js";
@@ -45,12 +46,15 @@ describe("built-in Agent provisioning", () => {
expect(ids).not.toContain("agent_optimizer");
expect(list.agents.find((a) => a.agentId === "default_agent")?.name).toBe("General Agent");
- // Install policy: default_agent is pre-installed with every Skill currently in the library.
+ // Install policy: default_agent is pre-installed with the library's preinstalled set
+ // (skills marked `preinstall: false`, e.g. remote-claude-code, stay manual-install only).
const skillsOf = async (agentId: string) =>
(
await fs.readdir(path.join(t.root, projectId, "agents", agentId, "agent_state", "skills"))
).sort();
- expect(await skillsOf("default_agent")).toEqual(loadLibrarySkills().map((skill) => skill.name));
+ expect(await skillsOf("default_agent")).toEqual(
+ loadPreinstalledSkills().map((skill) => skill.name),
+ );
// The default AGENTS.md is empty: it carries no preset guidance (delegation and task
// conventions live in the default template's Suggested workflows section).
diff --git a/packages/server/test/skills.test.ts b/packages/server/test/skills.test.ts
index f3766606..00c78d54 100644
--- a/packages/server/test/skills.test.ts
+++ b/packages/server/test/skills.test.ts
@@ -2,8 +2,9 @@
* Integration tests for the Skill routes: library catalog structure (any logged-in user), member
* install/uninstall with 404 for outsiders, 404 for unknown skills, installed
* files matching the library content, idempotent update on reinstall, the
- * directory disappearing after uninstall, default_agent starting with all
- * skills installed while a newly created plain Agent has none, and the zip
+ * directory disappearing after uninstall, default_agent starting with the
+ * preinstalled library set (preinstall: false skills stay manual-install)
+ * while a newly created plain Agent has none, and the zip
* archive install/export (layouts, zip-slip and limit rejections, 409
* skill_exists + overwrite replace, byte-identical export round-trip).
*/
@@ -12,7 +13,7 @@ import path from "node:path";
import { strToU8, unzipSync, zipSync } from "fflate";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { skillsDir } from "@prismshadow/penguin-core";
-import { librarySkill, loadLibrarySkills } from "@prismshadow/penguin-skills";
+import { librarySkill, loadPreinstalledSkills } from "@prismshadow/penguin-skills";
import type {
AgentSkillsResponse,
ProjectCreateResponse,
@@ -81,6 +82,7 @@ describe("skills api", () => {
expect(body.groups[1]!.skills.map((s) => s.name)).toEqual([
"web-design",
"software-engineering",
+ "remote-claude-code",
]);
expect(body.groups[2]!.skills.map((s) => s.name)).toEqual([
"penguin-sdk",
@@ -203,12 +205,14 @@ describe("skills api", () => {
expect((await member.get(base("no_such_agent"))).status).toBe(404);
});
- it("default_agent starts with every library skill installed; a new plain Agent has none", async () => {
+ it("default_agent starts with the preinstalled library set; preinstall:false skills stay manual-install", async () => {
const res = await member.get(base("default_agent"));
expect(res.status).toBe(200);
const body = (await res.json()) as AgentSkillsResponse;
- // loadLibrarySkills itself sorts by name, matching the installed-list ordering.
- expect(body.skills.map((s) => s.name)).toEqual(loadLibrarySkills().map((s) => s.name));
+ // loadPreinstalledSkills keeps loadLibrarySkills' name sort, matching the installed-list ordering.
+ expect(body.skills.map((s) => s.name)).toEqual(loadPreinstalledSkills().map((s) => s.name));
+ // remote-claude-code ships in the library marked `preinstall: false`: not present here.
+ expect(body.skills.map((s) => s.name)).not.toContain("remote-claude-code");
// The installed list likewise passes through the Chinese description and the
// short description/icon (listInstalledSkills parses these from the on-disk
// frontmatter and icon.svg).
@@ -218,6 +222,24 @@ describe("skills api", () => {
expect(skill.icon, skill.name).toContain("<svg");
}
+ // Manual install from the library still works for a preinstall:false skill.
+ const manual = await member.post(base("default_agent"), { names: ["remote-claude-code"] });
+ expect(manual.status).toBe(201);
+ const withManual = (await manual.json()) as AgentSkillsResponse;
+ expect(withManual.skills.map((s) => s.name)).toContain("remote-claude-code");
+ // A multi-file skill: the file its SKILL.md references is installed alongside SKILL.md,
+ // byte-identical to the library source (subdirectory preserved).
+ const aux = "reference/persistent-session.md";
+ const refPath = path.join(
+ skillsDir(t.root, projectId, "default_agent"),
+ "remote-claude-code",
+ "reference",
+ "persistent-session.md",
+ );
+ expect(await fs.readFile(refPath, "utf8")).toBe(
+ librarySkill("remote-claude-code")!.files![aux],
+ );
+
await createPlainAgent("fresh_agent");
const fresh = (await (await member.get(base("fresh_agent"))).json()) as AgentSkillsResponse;
expect(fresh.skills).toEqual([]);
diff --git a/packages/skills/skills/remote-claude-code/SKILL.md b/packages/skills/skills/remote-claude-code/SKILL.md
new file mode 100644
index 00000000..3e1c8296
--- /dev/null
+++ b/packages/skills/skills/remote-claude-code/SKILL.md
@@ -0,0 +1,130 @@
+---
+name: remote-claude-code
+description: Run Claude Code on a remote host over SSH — a persistent expect-driven login session, headless claude -p with the stdin fix, the interactive TUI inside a remote tmux driven by send-keys/capture-pane, and multi-turn continuity via --session-id/--resume or stream-json; hosts and credentials are placeholders resolved at runtime from the user or the vault, never hardcoded.
+short_description: Run Claude Code on remote hosts over SSH.
+short_description_zh: 在远程主机上通过 SSH 运行 Claude Code(持久会话 / headless / tmux 交互 / 多轮续接)。
+preinstall: false
+version: 1
+updated: 2026-08-10T00:00:00Z
+---
+
+# Remote Claude Code
+
+Drive Claude Code on a remote Linux host over SSH. Three modes, in increasing interactivity:
+
+1. **Persistent SSH session** — one long-lived expect-driven connection you keep feeding commands across turns.
+2. **Headless (`claude -p`)** — one-shot or scripted calls, with the stdin fix that naive invocations need.
+3. **Interactive TUI** — the real Claude Code UI inside a remote `tmux` session, driven with `tmux send-keys` / `tmux capture-pane`. tmux is the way to do interactive use.
+
+Reach for this skill when the user wants to run or drive Claude Code on a server, keep an SSH connection open across turns, or hold a continuous conversation with Claude Code on a remote box.
+
+## Before you start
+
+If the user's message only invokes this skill without a concrete task, ask what they want — at minimum the remote host, the SSH user, and what Claude Code should do there.
+
+Credential rules — non-negotiable:
+
+- This document contains **no real credentials**: `<ssh-user>`, `<remote-host>`, `<target-user>`, `<sess>` are placeholders you substitute at runtime from what the user provides or from this agent's **key vault** (suggested keys: `REMOTE_SSH_HOST`, `REMOTE_SSH_USER`, `REMOTE_SSH_PASSWORD`). Vault values reach your shell environment on the next task — check with `[ -n "$REMOTE_SSH_PASSWORD" ] && echo ok || echo missing`, and if missing ask the user to add the keys to the key vault (gear icon on the agent card → settings → key vault tab) or to provide the values in chat.
+- **Never hardcode a password** into scripts left on disk, deliverables, or your final answer. Have expect read it from the environment (`$env(...)`); if the user pasted it in chat, export it only into the running process's environment, scrub it from logs and replies, and delete any temp file that embeds it as soon as the session is done.
+- Prefer SSH keys when they are already set up — then no password tooling is needed at all.
+- Back up remote config before modifying it, and never copy remote credential stores (`~/.claude/.credentials.json`, OAuth fields of `~/.claude.json`, private keys) anywhere.
+
+## 1. Persistent SSH session (expect)
+
+One long-lived connection with password auto-login and an optional user switch, held open by `interact`. `expect` ships with macOS and is a one-command install on Linux; `sshpass` is usually absent, so expect is the password-interactive tool of choice.
+
+The full expect template plus its operating notes live in [`reference/persistent-session.md`](reference/persistent-session.md) — read that file when setting up this mode. In short: write the template to your scratchpad, fill the placeholders at runtime (the password comes from `$env(REMOTE_SSH_PASSWORD)`, never hardcoded), start it with `exec_command`, and drive the held-open connection through its `process_id` with `input_command`. Reuse this one session for most remote commands rather than opening a new connection each time.
+
+## 2. Headless Claude Code (`claude -p`) — the stdin gotcha
+
+`claude -p "<prompt>"` hangs forever when its stdin is an open pipe that never closes — which is exactly what agent harnesses and the expect session above provide. The process idles with no output and no network connections. Fix: redirect stdin from `/dev/null`:
+
+```bash
+claude -p "Reply with exactly: all good" < /dev/null
+```
+
+Same for `--resume`, `--session-id`, `--output-format stream-json`, and the rest. Exception: when input is _meant_ to come from stdin (`--input-format stream-json`), feed it through a pipe that closes (`echo '<json>' | claude ...`) and do **not** add `< /dev/null` — that would override the pipe.
+
+Symptom checklist: process running + no output + no TCP connections → stdin starvation; add `< /dev/null`.
+
+## 3. Interactive TUI — tmux is the way
+
+Launching `claude` interactively inside the expect/pipe session renders the welcome screen, but pipe input is treated as a **paste**: text lands in the input box and Enter (`\r`) is inserted literally, so the message is never submitted (the remote transcript `~/.claude/projects/<dir>/*.jsonl` gains no user entry). Run Claude Code inside a remote `tmux` session instead and drive it with `tmux send-keys`, which delivers discrete keypresses:
+
+```bash
+# start detached, then read the screen
+TERM=xterm-256color tmux new-session -d -s <sess> "claude"
+sleep 8
+tmux capture-pane -t <sess> -p | tail -25
+
+# converse: send a message, wait for the turn, read the screen again
+tmux send-keys -t <sess> "Introduce yourself in one sentence" Enter
+sleep 20
+tmux capture-pane -t <sess> -p | tail -30
+```
+
+- Workspace trust dialog: it shows on the first launch in each project directory (`-p` mode skips it; `--dangerously-skip-permissions` does **not**). Answer it once via `tmux send-keys -t <sess> Enter`, or pre-accept it by setting `hasTrustDialogAccepted: true` for that project path in the remote `~/.claude.json` — back the file up first (`cp ~/.claude.json ~/.claude.json.bak-$(date +%s)`) and rewrite it with a JSON-aware tool (python), not sed.
+- Tool-permission prompts: answer them through `send-keys` as they appear; launch with `--dangerously-skip-permissions` only when the user explicitly wants unattended runs on that host.
+- `TERM=xterm-256color` must be visible to the tmux **server** (prefix the `tmux new-session` call that starts it), or the TUI renders garbled and colorless.
+- Continuity is real: within one tmux session, follow-ups remember earlier turns ("what was my first question?" gets the right answer).
+- The user can join from their own terminal at any time: `ssh <ssh-user>@<remote-host>` → `su - <target-user>` → `tmux attach -t <sess>`.
+
+### 3.1 Waiting out a long turn — don't hold SSH open
+
+A Claude Code turn can run for ten-plus minutes. Instead of keeping an SSH connection open to poll, place a **detached watcher** on the remote (`setsid nohup`, so it outlives the launching SSH session): it polls `tmux capture-pane` every 10s, and once the turn has been idle for 3 consecutive checks — the footer no longer shows `esc to interrupt` — it writes the final screen plus a `DONE` marker (or `TIMEOUT` past a cap). A blocking SSH loop then waits for the marker and returns the final screen, so the tool call effectively hangs until the turn is done. The full watcher script and the wait loop are in [`reference/completion-watcher.md`](reference/completion-watcher.md) — read it when you need this.
+
+### 3.2 Input-line text may be a suggestion, not real input
+
+When an idle Claude Code TUI shows text on the input line (after `❯`), that is often a **Claude-generated suggested next message**, not text the user typed and left pending. `tmux send-keys` only ever adds new text — it does not edit or "complete" that suggestion, and Enter submits what _you_ sent, not the suggestion. So don't try to clear or edit the input line: just send your full instruction and submit it. Send arbitrary message text literally with `-l` (so punctuation and words like `Enter` aren't parsed as key names), then send Enter as its own keypress:
+
+```bash
+tmux send-keys -t <sess> -l "Your full message, punctuation and all"
+tmux send-keys -t <sess> Enter
+```
+
+Then `capture-pane` to confirm your text landed on the input line and the turn started.
+
+## 4. Continuous (multi-turn) conversation
+
+Three verified ways to keep context across calls:
+
+**a) Same session across headless invocations (simplest):**
+
+```bash
+SID=$(uuidgen)
+claude -p "Remember: my name is Alex." --session-id "$SID" < /dev/null
+claude -p "What is my name?" --resume "$SID" < /dev/null # answers: Alex
+```
+
+**b) stream-json real-time protocol (programmatic):**
+
+```bash
+echo '{"type":"user","message":{"role":"user","content":"Hello"}}' \
+ | claude -p --verbose --input-format stream-json --output-format stream-json
+```
+
+Returns `system/init` (carrying the `session_id`), `assistant`, and `result` events; reuse the `session_id` to continue. `--output-format stream-json` requires `--verbose`.
+
+**c) The interactive tmux session (section 3)** — the true REPL-style continuous conversation.
+
+## 5. Troubleshooting
+
+| Symptom | Cause / fix |
+| ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
+| `claude -p` runs forever, no output, no TCP connections | stdin pipe never closes → add `< /dev/null` |
+| TUI renders once then ignores keys; Enter shows up literally | pipe input treated as a paste → drive it with tmux `send-keys` |
+| Trust dialog on every launch | `hasTrustDialogAccepted` unset for that project dir → set it to true (back up `~/.claude.json` first) |
+| TUI garbled / no colors | `TERM=dumb` → set `xterm-256color` at expect spawn or tmux launch |
+| expect stuck producing no output | a prompt regex never matched → replace it with `sleep` + fixed sends |
+| `Connection timed out during banner exchange` | busy server / transient → wait a few seconds and retry; keep one persistent session instead of hammering new ones |
+| New SSH connections crawl while old ones work | connection pressure → route commands through the persistent session |
+| Input line shows text you didn't type | it's a Claude Code suggestion, not real input (see §3.2) → don't edit it; `send-keys -l "<message>"` then `Enter` |
+| Want to wait out a long turn without holding SSH open | run a detached watcher on the remote (see §3.1) that polls `capture-pane` until idle and writes a `DONE`/`TIMEOUT` marker, then block on an SSH loop until it appears |
+
+## 6. Verification checklist
+
+- Persistent session: the probe returns `whoami`/`hostname`/`pwd`, and the prompt comes back after each command.
+- Headless: `claude -p "..." < /dev/null` prints the answer and exits.
+- Interactive: `capture-pane` shows your message on the input line, then the response, then the prompt again.
+- Continuity: a follow-up that requires memory answers correctly (or the remote `~/.claude/projects/**/*.jsonl` shows the user entry).
+- Sanitization: no real host, user, or password appears in temp scripts left on disk or in your final answer — real values only ever come from the user or the vault at runtime.
diff --git a/packages/skills/skills/remote-claude-code/icon.svg b/packages/skills/skills/remote-claude-code/icon.svg
new file mode 100644
index 00000000..65e0448e
--- /dev/null
+++ b/packages/skills/skills/remote-claude-code/icon.svg
@@ -0,0 +1,7 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
+ <rect x="3" y="8" width="14" height="12" rx="2" />
+ <path d="M6.3 12.2l2.7 2.3-2.7 2.3" />
+ <path d="M11 17.2h3.2" />
+ <path d="M17.5 5.2a3 3 0 0 1 3 3" />
+ <path d="M17.5 2.7a5.5 5.5 0 0 1 5.5 5.5" />
+</svg>
diff --git a/packages/skills/skills/remote-claude-code/reference/completion-watcher.md b/packages/skills/skills/remote-claude-code/reference/completion-watcher.md
new file mode 100644
index 00000000..6321c690
--- /dev/null
+++ b/packages/skills/skills/remote-claude-code/reference/completion-watcher.md
@@ -0,0 +1,69 @@
+# Waiting out a long turn — remote completion watcher
+
+A single Claude Code turn can run for ten-plus minutes. Rather than hold an SSH connection open
+polling `tmux capture-pane`, place a **detached watcher** on the remote (`setsid nohup`, so it
+outlives the SSH session that launched it). It polls the pane every 10s and, once the turn has been
+idle for 3 consecutive checks — the footer no longer shows the working indicator `esc to interrupt`
+(rendered as e.g. `✳ Cultivating… (esc to interrupt)` while a turn runs) — writes the final screen
+to a file with a `DONE` marker; past a hard cap it writes `TIMEOUT` instead. A blocking SSH loop
+then waits for the marker and returns the final screen, so the tool call "hangs until done".
+
+Replace `<sess>` with your tmux session name. `esc to interrupt` is the stable part of the working
+footer; the gerunds (`Cultivating`, `Improvising`, …) are flavor text that varies by version, so
+key detection on `esc to interrupt` and treat the rest as backup.
+
+## 1. Install and start the watcher (detached)
+
+```bash
+ssh <ssh-user>@<remote-host> 'cat > ~/cc-watch.sh <<'"'"'EOF'"'"'
+#!/usr/bin/env bash
+LOG=~/cc-watch.log; OUT=~/cc-final.txt
+rm -f "$LOG" "$OUT"
+busy_seen=0; idle_count=0; max_wait=7200; start=$(date +%s)
+echo "WATCHER START $(date)" >> "$LOG"
+while :; do
+ now=$(date +%s)
+ if (( now - start > max_wait )); then
+ tmux capture-pane -t <sess> -p > "$OUT"; echo "TIMEOUT $(date)" >> "$LOG"; exit 0
+ fi
+ live=$(tmux capture-pane -t <sess> -p 2>/dev/null | tail -30)
+ if printf "%s\n" "$live" | grep -qE "esc to interrupt|Cultivating|Improvising|Running "; then
+ busy_seen=1; idle_count=0
+ elif [ "$busy_seen" = 1 ]; then
+ idle_count=$((idle_count+1))
+ if [ "$idle_count" -ge 3 ]; then
+ tmux capture-pane -t <sess> -p > "$OUT"; echo "DONE $(date) after $(( now - start ))s" >> "$LOG"; exit 0
+ fi
+ fi
+ sleep 10
+done
+EOF
+chmod +x ~/cc-watch.sh
+setsid nohup bash ~/cc-watch.sh >/dev/null 2>&1 < /dev/null &
+sleep 2; ps aux | grep -v grep | grep cc-watch.sh'
+```
+
+## 2. Block until the marker appears, then return the final screen
+
+```bash
+ssh <ssh-user>@<remote-host> '
+for i in $(seq 1 900); do
+ if grep -qE "DONE|TIMEOUT" ~/cc-watch.log 2>/dev/null; then
+ echo "=== WATCHER LOG ==="; cat ~/cc-watch.log
+ echo; echo "=== FINAL CAPTURE ==="; cat ~/cc-final.txt 2>/dev/null
+ exit 0
+ fi
+ sleep 10
+done'
+```
+
+If the blocking loop times out before the marker appears, run it again (or, on a persistent
+session, poll again with `input_command`) — the watcher keeps running on the remote regardless.
+
+## Notes
+
+- `tail -30` inspects only the live bottom region of the pane, so an old `Cultivating` line scrolled
+ up into history can't be misread as "still busy".
+- Requiring 3 consecutive idle checks avoids a false "done" during a brief pause between tool calls
+ within one turn.
+- The user can read the result themselves at any time: `cat ~/cc-final.txt`.
diff --git a/packages/skills/skills/remote-claude-code/reference/persistent-session.md b/packages/skills/skills/remote-claude-code/reference/persistent-session.md
new file mode 100644
index 00000000..80b363b5
--- /dev/null
+++ b/packages/skills/skills/remote-claude-code/reference/persistent-session.md
@@ -0,0 +1,46 @@
+# Persistent SSH session — expect template
+
+Full template for mode 1 (persistent SSH session). Write it to your scratchpad
+(`<app_data_dir>/agents/<agent_id>/scratchpad/remote_shell.exp`) and fill the placeholders at
+runtime — never commit real values, and have expect read the password from the environment rather
+than baking it into the file.
+
+```expect
+#!/usr/bin/expect -f
+set timeout 30
+log_user 0
+set env(TERM) xterm-256color ;# must be set before spawn — see the TERM note below
+spawn ssh -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 \
+ -o ServerAliveCountMax=3 -o ConnectTimeout=15 <ssh-user>@<remote-host>
+expect {
+ "yes/no" { send "yes\r"; exp_continue }
+ "password:" { send "$env(REMOTE_SSH_PASSWORD)\r"; exp_continue }
+ eof { puts "\n=== SSH CLOSED ==="; exit 1 }
+}
+sleep 2
+send "su - <target-user>\r" ;# drop this block when no user switch is needed
+expect {
+ "Password:" { send "$env(REMOTE_SSH_PASSWORD)\r"; exp_continue }
+ timeout { }
+}
+sleep 1
+send "echo PERSISTENT_SESSION_READY; whoami; hostname; pwd\r"
+expect "PERSISTENT_SESSION_READY"
+log_user 1
+set timeout -1
+interact
+```
+
+## Operating notes
+
+- Start it with `exec_command` and let it keep running — the closing `interact` holds the
+ connection open, and its `process_id` is your handle: send remote commands with `input_command`
+ (write to stdin) and poll the same session for new output.
+- The `sleep`-based waits replace prompt-regex matching on purpose: matching shell prompts
+ (`[$#] $` and friends) breaks on MOTD/ANSI noise and leaves the script stuck in `expect`.
+- `set env(TERM) xterm-256color` before `spawn`, or the remote shell sees `TERM=dumb` and TUIs
+ render badly.
+- Probe before relying on the session (`echo PING; whoami`), and reuse it for most remote commands
+ — open extra one-shot connections sparingly.
+- When finished: stop the expect process you started (and its ssh child; leave other people's
+ sessions alone) and delete the script from the scratchpad.
diff --git a/packages/skills/src/index.ts b/packages/skills/src/index.ts
index d512a278..bc8eb86e 100644
--- a/packages/skills/src/index.ts
+++ b/packages/skills/src/index.ts
@@ -14,7 +14,7 @@ import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
-/** Skill's frontmatter metadata (four fields: name / description / version / updated; description itself is English-only, may also carry description_zh and short_description(_zh)). */
+/** Skill's frontmatter metadata (four core fields: name / description / version / updated; may also carry short_description(_zh) and `preinstall`; description itself is English-only). */
export interface SkillMetadata {
/** Skill name (matches its containing directory name). */
name: string;
@@ -24,6 +24,8 @@ export interface SkillMetadata {
shortDescription?: string;
/** Chinese short description (frontmatter `short_description_zh`, optional). */
shortDescriptionZh?: string;
+ /** Preinstall marker (frontmatter `preinstall`, optional): false keeps the Skill out of default_agent's preinstalled set (library install stays manual); omitted means preinstalled. */
+ preinstall?: boolean;
/** Version number (natural number); falls back to 1 on parse failure. */
version: number;
/** Update date (YYYY-MM-DD); defaults to "". */
@@ -35,6 +37,14 @@ export interface LibrarySkill extends SkillMetadata {
content: string;
/** Optional raw `icon.svg` content in the directory (custom icon, the file is the sole source, copied alongside SKILL.md on install); absent means none (frontend falls back to the default book icon). */
icon?: string;
+ /**
+ * Optional auxiliary files the SKILL.md references (e.g. `reference/API.md`), keyed by
+ * POSIX-relative path within the skill directory; every entry except the top-level SKILL.md and
+ * icon.svg, which have their own fields. Written alongside SKILL.md on install (subdirectories
+ * preserved). Read as UTF-8 text — library content is committed text (reference docs, templates,
+ * snippets); the field is omitted when a skill has no extra files.
+ */
+ files?: Record<string, string>;
}
/** Skill group manifest entry: group id, title (optionally with a Chinese title, displayed per UI language), and member Skill names. */
@@ -57,7 +67,8 @@ export interface ResolvedSkillGroup extends Omit<SkillGroupInfo, "skills"> {
* first `---` block (split on the first colon, value trimmed, values may themselves contain colons);
* all fields are scalars, no YAML dependency needed.
* Error tolerance: returns null if the `---` block or name is missing; version falls back to 1 if
- * it isn't a natural number; updated defaults to "".
+ * it isn't a natural number; updated defaults to ""; preinstall is recognized only as the
+ * literal `false` (anything else, or absence, means the default: preinstalled).
*/
export function parseSkillFrontmatter(content: string): SkillMetadata | null {
// Strip a possible UTF-8 BOM (may be introduced by editors when manually editing an installed SKILL.md); CRLF is handled by \r?\n.
@@ -81,6 +92,8 @@ export function parseSkillFrontmatter(content: string): SkillMetadata | null {
// short_description(_zh) is optional: omitted when absent (undefined keys aren't set).
...(shortDescription !== undefined ? { shortDescription } : {}),
...(shortDescriptionZh !== undefined ? { shortDescriptionZh } : {}),
+ // preinstall is meaningful only as the literal `false` (skip default_agent preinstall).
+ ...(fields["preinstall"] === "false" ? { preinstall: false } : {}),
version: Number.isInteger(version) && version >= 1 ? version : 1,
updated: fields["updated"] ?? "",
};
@@ -92,12 +105,38 @@ const SKILLS_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "
/** Character rule for Skill names (directory names): prevents path traversal (exported for the server's archive-install validation). */
export const SKILL_NAME_PATTERN = /^[A-Za-z0-9_-]+$/;
+/**
+ * Recursively collects a skill directory's auxiliary files — every regular file except the
+ * top-level SKILL.md and icon.svg, which are carried by dedicated fields — keyed by POSIX-relative
+ * path. These are resources a SKILL.md may reference (e.g. `reference/API.md`), installed alongside
+ * it. Read as UTF-8 text; symlinks and other non-regular entries are skipped. Returns undefined
+ * when the directory has no such files.
+ */
+function readSkillFiles(dir: string): Record<string, string> | undefined {
+ const files: Record<string, string> = {};
+ const walk = (abs: string, rel: string): void => {
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
+ const childRel = rel ? `${rel}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) {
+ walk(path.join(abs, entry.name), childRel);
+ } else if (entry.isFile()) {
+ // SKILL.md and icon.svg at the root are carried by the content / icon fields.
+ if (rel === "" && (entry.name === "SKILL.md" || entry.name === "icon.svg")) continue;
+ files[childRel] = fs.readFileSync(path.join(abs, entry.name), "utf8");
+ }
+ }
+ };
+ walk(dir, "");
+ return Object.keys(files).length > 0 ? files : undefined;
+}
+
/**
* Reads a single library directory to construct a LibrarySkill; returns undefined if SKILL.md
* doesn't exist. name is taken from the directory name (overriding frontmatter); falls back to
* empty metadata if frontmatter parsing fails.
* The optional icon.svg in the directory is read alongside it (as a raw string); the icon field
- * is omitted if missing.
+ * is omitted if missing. Any other files in the directory (e.g. a `reference/` subtree the
+ * SKILL.md links to) are collected into `files`, omitted when there are none.
*/
function readSkillDir(name: string): LibrarySkill | undefined {
const dir = path.join(SKILLS_ROOT, name);
@@ -113,13 +152,20 @@ function readSkillDir(name: string): LibrarySkill | undefined {
} catch {
// icon.svg is optional: no custom icon if missing.
}
+ const files = readSkillFiles(dir);
const meta = parseSkillFrontmatter(content) ?? {
name,
description: "",
version: 1,
updated: "",
};
- return { ...meta, name, content, ...(icon !== undefined ? { icon } : {}) };
+ return {
+ ...meta,
+ name,
+ content,
+ ...(icon !== undefined ? { icon } : {}),
+ ...(files !== undefined ? { files } : {}),
+ };
}
/** Reads all Skills in the library (one per subdirectory under `skills/`), sorted by name. */
@@ -133,6 +179,15 @@ export function loadLibrarySkills(): LibrarySkill[] {
return skills.sort((a, b) => a.name.localeCompare(b.name));
}
+/**
+ * Reads the library Skills that default_agent preinstalls at initialization: every library
+ * Skill except those whose frontmatter sets `preinstall: false` (those stay in the library
+ * for manual install only).
+ */
+export function loadPreinstalledSkills(): LibrarySkill[] {
+ return loadLibrarySkills().filter((skill) => skill.preinstall !== false);
+}
+
/**
* Skill group manifest; members are library directory names.
* Docs: /docs/skills § "Built-in library".
@@ -148,7 +203,7 @@ export const SKILL_GROUPS: SkillGroupInfo[] = [
id: "software-development",
title: "Software Development",
titleZh: "软件开发",
- skills: ["web-design", "software-engineering"],
+ skills: ["web-design", "software-engineering", "remote-claude-code"],
},
{
id: "ai-app-development",
diff --git a/packages/skills/test/skills.test.ts b/packages/skills/test/skills.test.ts
index 7058115b..9ab6990f 100644
--- a/packages/skills/test/skills.test.ts
+++ b/packages/skills/test/skills.test.ts
@@ -1,6 +1,7 @@
/**
* Tests for the Skill library file source of truth and its parser: loadLibrarySkills reading
- * files into a manifest, loadSkillGroups grouping, groupSkills' Other group and missing-member
+ * files into a manifest (including auxiliary files a SKILL.md references), loadPreinstalledSkills'
+ * preinstall filter, loadSkillGroups grouping, groupSkills' Other group and missing-member
* tolerance, librarySkill's traversal-name rejection, doc conventions (`## Before you start` is
* mandatory), and parseSkillFrontmatter's error tolerance.
*/
@@ -12,6 +13,7 @@ import {
groupSkills,
librarySkill,
loadLibrarySkills,
+ loadPreinstalledSkills,
loadSkillGroups,
parseSkillFrontmatter,
type LibrarySkill,
@@ -83,6 +85,39 @@ describe("loadLibrarySkills", () => {
expect(skill.content, skill.name).toContain("## Before you start");
}
});
+
+ it("collects auxiliary files a SKILL.md references (reference/*), excluding SKILL.md and icon.svg", async () => {
+ // remote-claude-code is a multi-file skill: its SKILL.md links to a reference/ document.
+ const skill = librarySkill("remote-claude-code")!;
+ const aux = "reference/persistent-session.md";
+ expect(skill.files, "remote-claude-code carries files").toBeDefined();
+ expect(Object.keys(skill.files!)).toContain(aux);
+ // Read verbatim from disk, and the SKILL.md really links to it.
+ expect(skill.files![aux]).toBe(
+ await fs.readFile(path.join(skillsRoot, skill.name, aux), "utf8"),
+ );
+ expect(skill.content).toContain(aux);
+ // SKILL.md and icon.svg are carried by their own fields, never duplicated into files.
+ for (const key of Object.keys(skill.files!)) {
+ expect(key).not.toBe("SKILL.md");
+ expect(key).not.toBe("icon.svg");
+ }
+ // A skill that ships only SKILL.md + icon.svg omits the field entirely.
+ expect("files" in librarySkill("firecrawl")!).toBe(false);
+ });
+});
+
+describe("loadPreinstalledSkills", () => {
+ it("excludes skills whose frontmatter sets preinstall: false and keeps everything else", () => {
+ const all = loadLibrarySkills();
+ const preinstalled = loadPreinstalledSkills().map((s) => s.name);
+ expect(preinstalled).toEqual(all.filter((s) => s.preinstall !== false).map((s) => s.name));
+ // remote-claude-code is the library's manual-install skill: in the library, not preinstalled.
+ expect(all.map((s) => s.name)).toContain("remote-claude-code");
+ expect(librarySkill("remote-claude-code")?.preinstall).toBe(false);
+ expect(preinstalled).not.toContain("remote-claude-code");
+ expect(preinstalled.length).toBeGreaterThan(0);
+ });
});
describe("loadSkillGroups / groupSkills", () => {
@@ -101,7 +136,11 @@ describe("loadSkillGroups / groupSkills", () => {
]);
expect(groups[0]!.title).toBe("Office Productivity");
expect(groups[0]!.titleZh).toBe("办公效率");
- expect(groups[1]!.skills.map((s) => s.name)).toEqual(["web-design", "software-engineering"]);
+ expect(groups[1]!.skills.map((s) => s.name)).toEqual([
+ "web-design",
+ "software-engineering",
+ "remote-claude-code",
+ ]);
expect(groups[1]!.title).toBe("Software Development");
expect(groups[1]!.titleZh).toBe("软件开发");
expect(groups[2]!.skills.map((s) => s.name)).toEqual([
@@ -164,7 +203,10 @@ describe("loadSkillGroups / groupSkills", () => {
it("SKILL_GROUPS hardcodes member names (sole group info source outside library files)", () => {
expect(SKILL_GROUPS.map((g) => ({ id: g.id, skills: g.skills }))).toEqual([
{ id: "office-productivity", skills: ["data-analysis", "firecrawl", "bento-slides"] },
- { id: "software-development", skills: ["web-design", "software-engineering"] },
+ {
+ id: "software-development",
+ skills: ["web-design", "software-engineering", "remote-claude-code"],
+ },
{
id: "ai-app-development",
skills: [
@@ -420,6 +462,17 @@ describe("parseSkillFrontmatter", () => {
expect(without && "shortDescriptionZh" in without).toBe(false);
});
+ it("preinstall is recognized only as the literal false; other values or absence omit the field", () => {
+ const off = parseSkillFrontmatter("---\nname: demo\npreinstall: false\n---\nBody");
+ expect(off?.preinstall).toBe(false);
+ for (const value of ["true", "no", "0", "False"]) {
+ const meta = parseSkillFrontmatter(`---\nname: demo\npreinstall: ${value}\n---\nBody`);
+ expect(meta && "preinstall" in meta, value).toBe(false);
+ }
+ const absent = parseSkillFrontmatter("---\nname: demo\n---\nBody");
+ expect(absent && "preinstall" in absent).toBe(false);
+ });
+
it("parses UTF-8 BOM and CRLF newlines normally (hand-edited files may introduce them)", () => {
const bom = parseSkillFrontmatter("\uFEFF---\nname: demo\ndescription: Do x\n---\nBody");
expect(bom?.name).toBe("demo");
diff --git a/packages/web/e2e/skills.spec.mjs b/packages/web/e2e/skills.spec.mjs
index 2ad1edb4..5b0f1222 100644
--- a/packages/web/e2e/skills.spec.mjs
+++ b/packages/web/e2e/skills.spec.mjs
@@ -9,6 +9,9 @@
* number badge);
* - the "Manage installation" Modal: an Agent row + Install / Installed (hover flips to
* Uninstall) button, with optimistic updates on install/uninstall;
+ * - Quick invoke is gated on the currently selected agent having the skill installed (here the
+ * current agent is default_agent; its button is disabled for a preinstall:false skill like
+ * remote-claude-code the current agent lacks);
* - "Quick invoke" navigates to /chat/new (default_agent), **prefilling** the invoke text in the
* UI language (zh: "使用 X 技能") and preselecting that skill — the toolbar's skill dropdown
* button shows a count badge of 1, and that item shows as selected in the menu;
@@ -108,6 +111,13 @@ test("skills: library groups and cards -> manage-install Modal -> quick-invoke p
// Card metadata is worded semantically: version + usage count (default_agent has all skills preinstalled -> at least 1 in use).
await expect(page.getByText(/v\d+ · .*Agent 在用/).first()).toBeVisible();
+ // Quick invoke opens a draft on the currently selected Agent (default_agent here), so it's
+ // gated on that Agent having the skill: default_agent ships every preinstalled skill
+ // (agent-creation is enabled), while remote-claude-code is preinstall:false and absent from it,
+ // so its button is disabled.
+ await expect(page.getByRole("button", { name: "快捷调用 agent-creation" })).toBeEnabled();
+ await expect(page.getByRole("button", { name: "快捷调用 remote-claude-code" })).toBeDisabled();
+
// Card icon: the DTO icon (icon.svg in the skill's directory) is sanitized and rendered
// inline (an aria-hidden wrapper + svg); builtin skills each carry a custom icon, not the book
// fallback. The card root = the nearest rounded-md ancestor of the name element (the new card
diff --git a/packages/web/src/features/skills/skills-page.tsx b/packages/web/src/features/skills/skills-page.tsx
index 29dc228a..439de376 100644
--- a/packages/web/src/features/skills/skills-page.tsx
+++ b/packages/web/src/features/skills/skills-page.tsx
@@ -23,9 +23,12 @@
* (install-again-is-update semantics), with a single success toast; the
* manage-installs Modal marks outdated rows with an accent "Update" button
* doing the same per Agent (through the same confirm);
- * - Paper plane "quick invoke": enters /chat/new draft mode with default_agent,
- * pre-selects the skill, and pre-fills the invocation text per UI language
+ * - Paper plane "quick invoke": enters /chat/new draft mode on the currently selected
+ * agent, pre-selects the skill, and pre-fills the invocation text per UI language
* ("use the X skill" in the active dictionary, overwriting any existing draft body);
+ * disabled unless that agent has the skill installed — quick invoke opens the draft
+ * there, so it can't pre-select a skill the current agent lacks (e.g. a preinstall:false
+ * skill like remote-claude-code on an agent that hasn't installed it);
* - Download "manage installs": a Modal listing every Agent in the current
* Project — not-installed shows "Install", installed shows "Installed"
* (hover switches to "Uninstall", click to uninstall); any member can
@@ -91,7 +94,7 @@ export function SkillsPage() {
const navigate = useNavigate();
const { locale } = useLocale();
const userId = useAuth().user?.userId ?? null;
- const { currentProject, agents, setCurrentAgentId } = useProject();
+ const { currentProject, agents, currentAgent, setCurrentAgentId } = useProject();
const projectId = currentProject?.projectId ?? null;
const [groups, setGroups] = useState<SkillGroupItem[] | null>(null);
@@ -224,14 +227,15 @@ export function SkillsPage() {
* field, used by ChatInput as its initial selection on mount), pre-fills
* the invocation text per UI language (overwriting any existing draft
* body — quick invoke's intent is unambiguous, and leftover draft text
- * would only be noise here), and points the Agent to default_agent before
- * entering draft mode — the route state explicitly carries agentId
- * (overriding whatever was last selected in the cache). handoffAgentId
+ * would only be noise here), and opens the draft on the currently selected
+ * Agent — the route state carries its agentId explicitly. handoffAgentId
* must be cleared: a leftover handoff target would forward the whole skill
- * invocation to a different Agent — quick invoke must always start a new
- * conversation with default_agent.
+ * invocation to a different Agent. The button is gated on the current Agent
+ * having the skill (see SkillCard.canQuickInvoke), so agentId is present here.
*/
const quickInvoke = (name: string) => {
+ const agentId = currentAgent?.agentId;
+ if (!agentId) return;
if (userId && projectId) {
// Typed-but-unsent draft text becomes a parked draft conversation instead of being
// clobbered by the canned invocation body (draft-sessions.ts).
@@ -239,14 +243,14 @@ export function SkillsPage() {
const key = draftKey(userId, projectId);
saveDraft(key, {
...loadDraft(key),
- agentId: "default_agent",
+ agentId,
text: S.skills.quickInvokeText(name),
skills: [name],
handoffAgentId: undefined,
});
}
- setCurrentAgentId("default_agent");
- navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId: "default_agent" } });
+ setCurrentAgentId(agentId);
+ navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });
};
return (
@@ -358,7 +362,7 @@ function SkillCard({
onUpdateOutdated: (name: string, agentIds: string[]) => Promise<void>;
}) {
const { locale } = useLocale();
- const { agents } = useProject();
+ const { agents, currentAgent } = useProject();
const [installOpen, setInstallOpen] = useState(false);
// Agents pending an update confirmation (null = none): an update is an overwriting reinstall, so it needs a confirm + a per-agent version list before it runs.
const [pendingUpdate, setPendingUpdate] = useState<string[] | null>(null);
@@ -387,6 +391,11 @@ function SkillCard({
skill.name,
skill.version,
);
+ // Quick invoke opens a draft on the currently selected Agent, so it's only offered once that
+ // Agent has this skill installed — otherwise quick invoke would pre-select a skill it lacks
+ // (e.g. a preinstall:false skill like remote-claude-code on an Agent that hasn't installed it).
+ const canQuickInvoke =
+ currentAgent !== null && (installed.get(currentAgent.agentId)?.has(skill.name) ?? false);
// Short description takes priority, falling back to the full description
// when missing (per UI language); title carries the full description for hover reading.
@@ -451,7 +460,8 @@ function SkillCard({
size="sm"
className="h-8 w-8 shrink-0 justify-center p-0"
aria-label={`${S.skills.quickInvoke} ${skill.name}`}
- title={S.skills.quickInvoke}
+ title={canQuickInvoke ? S.skills.quickInvoke : S.skills.quickInvokeNeedsInstall}
+ disabled={!canQuickInvoke}
onClick={() => onQuickInvoke(skill.name)}
>
<GlyphIcon d={SEND_ICON} size={15} />
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 1c988c1d..c376e512 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -544,6 +544,8 @@ export const en: Strings = {
pageDesc: "Built-in skill library: browse, quick-start a chat, or install to agents.",
quickInvoke: "Quick start",
quickInvokeText: (name: string): string => `use the ${name} skill`,
+ /** Title on a disabled quick-start button: quick start opens a draft on the currently selected agent, so a skill it hasn't installed (e.g. a preinstall:false skill like remote-claude-code) can't be quick-started until it's installed on that agent. */
+ quickInvokeNeedsInstall: "Install this skill on the current agent first to quick-start",
manageInstall: "Manage installs",
manageInstallTitle: (name: string): string => `Manage installs: ${name}`,
install: "Install",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index ba13c4d8..248ede5b 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -527,6 +527,8 @@ export const zh = {
quickInvoke: "快捷调用",
/** Pre-filled body for quick invoke (per UI language; English is `use the <name> skill`). */
quickInvokeText: (name: string): string => `使用 ${name} 技能`,
+ /** Title on a disabled quick-invoke button: quick invoke opens a draft on the currently selected agent, so a skill it hasn't installed (e.g. preinstall:false skills like remote-claude-code) can't be quick-invoked until it's installed on that agent. */
+ quickInvokeNeedsInstall: "先在当前 Agent 安装该技能后才能快捷调用",
manageInstall: "管理安装",
manageInstallTitle: (name: string): string => `管理安装:${name}`,
install: "安装",