Skip to content

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

Hooks tab: bare hook-point chips beside the name, an enable switch, zip import/export and AI import (#592)

Yaowei Zheng929007ea1165
diff --git a/changelog/unreleased/2026-09-02-hooks-enable-import-export.md b/changelog/unreleased/2026-09-02-hooks-enable-import-export.md
new file mode 100644
index 00000000..d2e7cd8b
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-hooks-enable-import-export.md
@@ -0,0 +1,17 @@
+# Hooks: one Agent-level switch, zip import/export and a chat import on the Hooks tab
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#592](https://github.com/Prism-Shadow/penguin-harness/pull/592)
+
+[中文版](2026-09-02-hooks-enable-import-export.zh.md)
+
+Hooks gained an on/off switch, the way Skills have one: a single Agent-level setting rather than a flag per installed package. The Agent settings Hooks tab also gained what the Skills tab already had — export as a zip, and the Skills tab's import dialog, a recommended chat import above a zip upload. The hook-point chips now read the bare point name and sit beside the package name.
+
+## Details
+
+- `hooks.enabled` is a new section of `system_config.yaml` (absent means on) with no prompt half — a hook package is scripts run at the loop's hook points, not text in the context. With it off, a Session created from then on assembles no hooks at all and every installed package stays on disk, listed and exportable. Core reads it fresh when it builds a Session, beside the packages themselves.
+- Server: the switch rides on the Agent config route (`PUT …/config` with `{ config: { hooks: { enabled } } }`, echoed by GET as `config.hooks`), and a config write that carries it invalidates the Agent's cached runtimes — hook packages are bound when a Session is built, so a cached runtime would otherwise keep the set it was built with. New hook routes: `POST …/hooks/archive` (a zip with hooks.json and the scripts at the root or in one top-level directory; the manifest's name, display fields and every hook-point command are validated — a command must name a file inside the archive; 409 `hook_exists` unless `overwrite`) and `GET …/hooks/:name/archive` (the installed directory as a zip, re-importable byte-compatibly). The hooks routes moved from `routes/plugins.ts` to `routes/hooks.ts`.
+- Web: the Hooks tab opens with the enable-switch card the Skills tab has (Project owner only; members see the state), then a row per package showing the hook-point chips (`stop`, `user_prompt`, `pre_tool_use`) right after the package name, the description below, and the version, export and uninstall in the trailing slot. "Import hook" opens the Skills tab's dialog shape: the recommended chat import leads with a hook source field (a URL, a repository, a local path, a description, or another tool's hooks config — the pasted config is why the field is a textarea), previews the prompt it generates (the source's lead sentence plus a fixed tail stating the review step, the package format, the script contract and the install target), and offers "Copy prompt" and "Open a new chat" with this agent, both greyed while the source is empty; the zip upload sits below it. The Skills dialog's "Open a new chat" is now greyed together with its "Copy prompt" for the same reason — an empty source used to open a blank chat and drop the prompt. The plugin detail Modal's chips lost their "hook" suffix too, and `S.plugins.hookBadge` is gone. The archive download the Skills tab used became `archive-download.ts`, shared by both tabs.
+- Docs: the skills page's hook-package section, the configuration table, the Web App's Hooks row and the server API table describe the switch, the import dialog and the archive routes.
diff --git a/changelog/unreleased/2026-09-02-hooks-enable-import-export.zh.md b/changelog/unreleased/2026-09-02-hooks-enable-import-export.zh.md
new file mode 100644
index 00000000..bef30da8
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-hooks-enable-import-export.zh.md
@@ -0,0 +1,17 @@
+# 钩子:一个 Agent 级总开关、zip 导入导出与钩子标签页的对话导入
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `docs`
+- **PR:** [#592](https://github.com/Prism-Shadow/penguin-harness/pull/592)
+
+[English](2026-09-02-hooks-enable-import-export.md)
+
+钩子有了启停开关,口径与技能一致:一个 Agent 级的总开关,而不是每个已装包各有一个标记。Agent 设置页的钩子标签页同时补齐了技能标签页已有的能力:打包导出为 zip,以及与导入技能同款的导入弹窗——推荐的对话导入在上,zip 上传在下。钩子点胶囊改为只写钩子点名,并紧挨着包名显示。
+
+## 细节
+
+- `system_config.yaml` 新增 `hooks.enabled` 小节(缺省即启用),且没有 prompt 的一半——钩子包是在循环钩子点上运行的脚本,不是进入上下文的文本。关闭后,此后新建的 Session 不组装任何钩子,已安装的包全部留在磁盘上,照常列出、照常可导出。core 在构建 Session 时与钩子包一并新鲜读取该值。
+- 服务端:开关走 Agent 配置路由(`PUT …/config`,body 为 `{ config: { hooks: { enabled } } }`;GET 以 `config.hooks` 回报),带该字段的配置写入会使该 Agent 已缓存的运行时失效——钩子包在 Session 构建时绑定,否则已缓存的运行时会一直沿用构建时的那套。新增钩子路由:`POST …/hooks/archive`(zip 内 hooks.json 与脚本在根目录或唯一顶层目录内;校验清单的名称、展示字段与各钩子点的每条命令——命令必须指向压缩包内的文件;同名已装且未带 `overwrite` 时 409 `hook_exists`)与 `GET …/hooks/:name/archive`(已装目录打包为 zip,可字节一致地导回)。钩子路由从 `routes/plugins.ts` 移到 `routes/hooks.ts`。
+- Web:钩子标签页顶部是与技能标签页同款的启停开关卡片(仅 Project owner,成员只见状态);其下每个包一行,包名之后紧跟钩子点胶囊(`stop`、`user_prompt`、`pre_tool_use`),其下为描述,行尾依次是版本、导出与卸载。「导入钩子」改用技能标签页的弹窗形态:推荐的对话导入在上,先是钩子来源字段(URL / 仓库 / 本地路径 / 一段描述,或其他工具的钩子配置——粘贴整段配置正是它用多行输入框的原因),其下实时预览生成的 Prompt(按来源给出的首句加上固定尾注:审查步骤、包格式、脚本契约与安装目标),再是「复制 Prompt」与在该 Agent 上「打开新对话」,来源为空时两者一同置灰;zip 上传排在其下。技能导入弹窗的「打开新对话」也随「复制 Prompt」一同置灰——此前来源为空时它会打开一个空白对话,把刚生成的 Prompt 丢掉。插件详情弹窗的胶囊同样去掉了「钩子」后缀,`S.plugins.hookBadge` 随之删除。技能标签页原有的打包下载逻辑抽成 `archive-download.ts`,两个标签页共用。
+- 文档:技能页的钩子包一节、配置表、Web App 的 Hooks 行与服务端 API 表描述了开关、导入弹窗与打包路由。
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 887e75f1..6dce8363 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -1238,23 +1238,28 @@ export class Agent {
/**
* The hooks of a top-level Session: every hook package installed in the Agent's
- * `agent_state/hooks/` (read fresh per Session, like skills), each command run as a
- * script (hooks/script-hook.ts), plus the spawner that honors a hook's `subagent` answer —
+ * `agent_state/hooks/` (read fresh per Session, like skills), each command run as a script
+ * (hooks/script-hook.ts), plus the spawner that honors a hook's `subagent` answer —
* a detached child Session of this Agent (or the one it names) whose stream is dropped (its
* own Trace is the record) and which inherits the run's approval callback. Child Sessions —
* spawned or revived subagents — carry no hooks: a subagent's work belongs to its parent's
* Trace, and a child could not spawn a subagent anyway.
+ *
+ * `hooks.enabled: false` in the Agent's config switches all of them off at once: the
+ * packages stay installed, and this is the one place a Session's hooks are assembled.
*/
private async sessionHooks(
runner: SubagentRunner,
child: boolean,
): Promise<SessionHooks | undefined> {
if (child) return undefined;
- const installed = await listInstalledHooks(
- this.state.root,
- this.state.projectId,
- this.state.agentId,
- );
+ const { root, projectId, agentId } = this.state;
+ // Read from disk rather than from this Agent object's load-time snapshot: a long-lived
+ // Agent would otherwise keep building Sessions on a config edited since it was loaded
+ // (the same reason assembleContext re-loads the state).
+ const { systemConfig } = await loadAgentState({ root, projectId, agentId });
+ if (systemConfig.hooks?.enabled === false) return undefined;
+ const installed = await listInstalledHooks(root, projectId, agentId);
// Hook scripts get the same PATH front as commands do (see
// CreateAgentOptions.pathPrepend). Only the environment half applies: a hook is run as
// `node <script>` directly, with no shell and so no login profile to re-prepend
diff --git a/packages/core/src/plugins/index.ts b/packages/core/src/plugins/index.ts
index 418f2138..0027ffd7 100644
--- a/packages/core/src/plugins/index.ts
+++ b/packages/core/src/plugins/index.ts
@@ -67,9 +67,11 @@ export interface HookCommand {
/**
* The manifest an installed hook package carries (`agent_state/hooks/<plugin>/hooks.json`),
- * generated by the installer from plugin.json: identity and display fields, plus one script
- * list per hook point (`stop`, `pre_tool_use`, `user_prompt`). The plugin's icon is not part
- * of it: the installer writes `icon.svg` beside the manifest instead.
+ * generated by the installer from plugin.json: identity and display fields plus one script
+ * list per hook point (`stop`, `pre_tool_use`, `user_prompt`). Whether a Session runs hooks
+ * at all is an Agent-level decision (`hooks.enabled` in system_config.yaml), not a per-package
+ * one. The plugin's icon is not part of it: the installer writes `icon.svg` beside the
+ * manifest instead. Unknown keys are ignored rather than rejected.
*/
export interface HookManifest {
name: string;
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index 1145d424..5d435c0a 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -647,6 +647,20 @@ export async function installPlugin(
}
}
+/** The manifest of the hook package directory `dir`, or null when there is no parseable `hooks.json` (then it is not a hook package). */
+async function readHookManifest(dir: string): Promise<HookManifest | null> {
+ try {
+ return JSON.parse(await fs.readFile(path.join(dir, "hooks.json"), "utf8")) as HookManifest;
+ } catch {
+ return null;
+ }
+}
+
+/** Serializes a manifest the way every writer of `hooks.json` does (pretty-printed, trailing newline). */
+function hookManifestText(manifest: HookManifest): string {
+ return `${JSON.stringify(manifest, null, 2)}\n`;
+}
+
/**
* Installs a hook package as `hooks/<name>/`: the manifest as `hooks.json`, the plugin's
* `icon.svg` when it has one (the installed package shows its plugin's icon, the way an
@@ -669,7 +683,7 @@ export async function installHook(
for (const rel of Object.keys(files)) assertSafeSkillFile(rel);
const dir = path.join(hooksDir(root, projectId, agentId), manifest.name);
await replaceSkillDirectory(dir, [
- ["hooks.json", `${JSON.stringify(manifest, null, 2)}\n`],
+ ["hooks.json", hookManifestText(manifest)],
...(icon !== undefined ? ([["icon.svg", icon]] as Array<[string, string]>) : []),
...Object.entries(files),
]);
@@ -723,14 +737,8 @@ export async function listInstalledHooks(
for (const entry of entries) {
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
const dir = path.join(base, entry.name);
- let manifest: HookManifest;
- try {
- manifest = JSON.parse(
- await fs.readFile(path.join(dir, "hooks.json"), "utf8"),
- ) as HookManifest;
- } catch {
- continue;
- }
+ const manifest = await readHookManifest(dir);
+ if (manifest === null) continue;
let icon: string | undefined;
try {
icon = await fs.readFile(path.join(dir, "icon.svg"), "utf8");
diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.ts
index 54f496c6..cd12a847 100644
--- a/packages/core/src/state/default-config.ts
+++ b/packages/core/src/state/default-config.ts
@@ -186,6 +186,18 @@ export interface SchedulesConfig {
prompt?: string;
}
+/**
+ * Hook config (the `hooks` section of `system_config.yaml`). One Agent-level switch, toggled
+ * on the Web App's Hooks tab. No prompt: a hook package is scripts run at the loop's hook
+ * points, not text injected into the context. With it off the packages stay installed — listed
+ * and exportable — and a Session created from then on assembles no hooks at all.
+ * Docs: /docs/skills § "Hook packages".
+ */
+export interface HooksConfig {
+ /** Whether a new Session consults the installed hook packages; defaults to true. */
+ enabled?: boolean;
+}
+
/** Stands in for an index placeholder when the `MEMORY.md` does not exist yet or is blank — the model is told the store is empty rather than being handed nothing. */
export const MEMORY_INDEX_EMPTY_NOTE = "(the index is empty — nothing has been saved yet)";
@@ -397,6 +409,8 @@ export interface SystemConfig {
skills?: SkillsConfig;
/** Scheduled-tasks section injection (enabled by default; only reaches the prompt through `{{SCHEDULES}}`). */
schedules?: SchedulesConfig;
+ /** Whether new Sessions run the installed hook packages (enabled by default; nothing prompt-side). */
+ hooks?: HooksConfig;
tools?: {
/** Built-in system tool configuration (per-entry fields incl. the `call_description` toggle live on ToolDefinitionConfig). */
builtin?: ToolDefinitionConfig[];
diff --git a/packages/core/test/hook-packages.test.ts b/packages/core/test/hook-packages.test.ts
new file mode 100644
index 00000000..599e762e
--- /dev/null
+++ b/packages/core/test/hook-packages.test.ts
@@ -0,0 +1,111 @@
+/**
+ * The Agent-level hook switch — `hooks.enabled` in `system_config.yaml`. Absent means on, and
+ * `false` leaves a new Session with no hooks at all while the packages stay installed. The
+ * manifest loader is tolerant of a stray `enabled` key (a package exported while the switch
+ * was per-package): it loads, and nothing reads the field.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ DEFAULT_AGENT_ID,
+ DEFAULT_PROJECT_ID,
+ createAgent,
+ hooksDir,
+ installHook,
+ listInstalledHooks,
+ systemConfigPath,
+} from "../src/index.js";
+import type { HookManifest, SystemConfig } from "../src/index.js";
+import { stubProviderKeys } from "./provider-keys.js";
+
+let tmpRoot: string;
+let prevHome: string | undefined;
+let restoreKeys: () => void;
+
+beforeEach(async () => {
+ prevHome = process.env.PENGUIN_HOME;
+ tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-harness-hooks-"));
+ process.env.PENGUIN_HOME = tmpRoot;
+ restoreKeys = stubProviderKeys();
+});
+
+afterEach(async () => {
+ if (prevHome === undefined) delete process.env.PENGUIN_HOME;
+ else process.env.PENGUIN_HOME = prevHome;
+ restoreKeys();
+ await fs.rm(tmpRoot, { recursive: true, force: true });
+});
+
+const MANIFEST: HookManifest = {
+ name: "expander",
+ description: "Answers at the user_prompt point.",
+ version: "2026-09-02.1",
+ stop: [],
+ pre_tool_use: [],
+ user_prompt: [{ command: "expand.mjs", timeout: 5 }],
+};
+const FILES = {
+ "expand.mjs": 'process.stdout.write(JSON.stringify({ context: "expanded" }));\n',
+};
+const ids = [DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID] as const;
+
+/** Writes the Agent's `hooks.enabled` (a Session reads the config on disk, not a snapshot). */
+async function setHooksEnabled(enabled: boolean): Promise<void> {
+ const file = systemConfigPath(tmpRoot, ...ids);
+ const cfg = parseYaml(await fs.readFile(file, "utf8")) as SystemConfig;
+ cfg.hooks = { enabled };
+ await fs.writeFile(file, stringifyYaml(cfg), "utf8");
+}
+
+describe("installed hook packages", () => {
+ it("loads a manifest carrying a stray enabled field and ignores it", async () => {
+ await createAgent();
+ await installHook(tmpRoot, ...ids, MANIFEST, FILES);
+ // Written by hand: the installer never emits the field, but a package exported while the
+ // switch was per-package still carries it, and such a directory must keep loading.
+ const file = path.join(hooksDir(tmpRoot, ...ids), "expander", "hooks.json");
+ await fs.writeFile(file, `${JSON.stringify({ ...MANIFEST, enabled: false }, null, 2)}\n`);
+
+ const listed = await listInstalledHooks(tmpRoot, ...ids);
+ expect(listed.map((h) => h.name)).toContain("expander");
+ });
+});
+
+describe("the Agent-level hook switch", () => {
+ it("gives a new Session no hooks while it is off, and the packages back once it is on", async () => {
+ const agent = await createAgent();
+ await installHook(tmpRoot, ...ids, MANIFEST, FILES);
+ const ws = path.join(tmpRoot, "ws");
+ await fs.mkdir(ws, { recursive: true });
+
+ // Absent section: hooks are on.
+ const on = await agent.createSession({ workspaceDir: ws });
+ try {
+ expect(await on.runUserPromptHook("expander", "hi")).toEqual({ context: "expanded" });
+ } finally {
+ on.dispose();
+ }
+
+ await setHooksEnabled(false);
+ const off = await agent.createSession({ workspaceDir: ws });
+ try {
+ // Off reads to a Session exactly like nothing installed: no such hook.
+ expect(await off.runUserPromptHook("expander", "hi")).toBeNull();
+ } finally {
+ off.dispose();
+ }
+ // The package itself is untouched.
+ expect((await listInstalledHooks(tmpRoot, ...ids)).map((h) => h.name)).toContain("expander");
+
+ await setHooksEnabled(true);
+ const again = await agent.createSession({ workspaceDir: ws });
+ try {
+ expect(await again.runUserPromptHook("expander", "hi")).toEqual({ context: "expanded" });
+ } finally {
+ again.dispose();
+ }
+ });
+});
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index c1a234d1..324ab0e0 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -168,6 +168,7 @@ The four `compaction.*` fields are the one part of this file a running conversat
| `skills.prompt` | built-in template | The `{{SKILLS}}` block, editable on the Skills tab — carries `{{SKILL_METADATA}}` |
| `schedules.enabled` | `true` | Whether the scheduled-tasks section enters the context (with it off, the server still fires tasks — the model just isn't taught the task system) |
| `schedules.prompt` | built-in template | The `{{SCHEDULES}}` block, editable on the Schedules tab — teaches the model file-based task management, carries `{{SCHEDULE_LIST}}` |
+| `hooks.enabled` | `true` | Whether a new Session runs the installed hook packages at the loop's hook points (with it off the packages stay installed and nothing consults them). The one section with no prompt half: hook packages are scripts, not context text |
| `tools.builtin` | full default toolset when omitted | Tool entries: `name` / `description` / `parameters` / `permission` (`r` or `rw`) / `forModel` / `timeoutMs` / `maxOutputLength` / `call_description` (per-tool toggle for the `description` call argument, required while on; missing = kept); once written it replaces the default list wholesale |
| `tools.mcpServers` | `[]` | MCP Server configuration (`name` + `config`): transport is `stdio` / `http` / `sse`, and discovered tools join the toolset as `mcp__<server>__<tool>`; `config.permission` (`auto` / `r` / `rw`, default `auto`) fixes the approval level of every tool of that Server instead of trusting its `readOnlyHint`; see the MCP Servers section of [Tools & Approval](/tools) |
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index e58164c5..c8e476ff 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -168,6 +168,7 @@ enabled = false
| `skills.prompt` | 内置模板 | `{{SKILLS}}` 区块内容,可在技能标签页编辑——含 `{{SKILL_METADATA}}` |
| `schedules.enabled` | `true` | 定时任务小节是否进入上下文(关闭后 server 照常触发任务,只是模型不了解任务体系) |
| `schedules.prompt` | 内置模板 | `{{SCHEDULES}}` 区块内容,可在定时任务标签页编辑——教模型用文件工具管理任务,含 `{{SCHEDULE_LIST}}` |
+| `hooks.enabled` | `true` | 新建的 Session 是否在循环的钩子点运行已安装的钩子包(关闭后包仍在磁盘上,只是无人咨询)。唯一没有 prompt 一半的小节:钩子包是脚本,不是上下文文本 |
| `tools.builtin` | 缺省时为完整默认工具集 | 工具条目:`name` / `description` / `parameters` / `permission`(`r` 或 `rw`)/ `forModel` / `timeoutMs` / `maxOutputLength` / `call_description`(条目级开关:控制 `description` 调用参数,开启时为必填,缺省保留);一旦写出即整体替换默认列表 |
| `tools.mcpServers` | `[]` | MCP Server 配置(`name` + `config`):transport 取 `stdio` / `http` / `sse`,工具以 `mcp__<server>__<tool>` 并入工具集;`config.permission`(`auto` / `r` / `rw`,缺省 `auto`)固定该 Server 全部工具的审批等级,不再采信其 `readOnlyHint`;详见[工具与审批](/tools)的 MCP Server 一节 |
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 5db1d10f..c3f7a933 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -220,6 +220,8 @@ The paths below omit the `/api/projects/:projectId` prefix.
| DELETE | /agents/:agentId/skills/:name | Uninstall a Skill |
| POST | /agents/:agentId/plugins | Install library plugins by name — each one's skills and hook package; reinstalling updates. `{ names }` → 201 `{ skills, hooks }`; 404 `unknown_plugin` writes nothing |
| GET | /agents/:agentId/hooks | Installed hook packages: name, description, version, hook points, the plugin's icon |
+| POST | /agents/:agentId/hooks/archive | Install a hook package from a zip: `{dataBase64, overwrite?}` — hooks.json and its scripts at the root or in one top-level directory, every listed command naming a file inside; 409 `hook_exists` without overwrite |
+| GET | /agents/:agentId/hooks/:name/archive | Export an installed hook package as a zip (round-trips through the POST) |
| GET | `/api/plugins` (global) | The plugin library by category — every plugin with its skills' metadata and hook points (any logged-in user) |
| GET | `/api/plugins/:plugin/files` (global) | Everything one library plugin ships as text keyed by path — each skill's installable SKILL.md and reference files under `skills/<name>/`, the hook scripts under `hooks/` — for the plugin detail view's file browser (any logged-in user) |
| DELETE | /agents/:agentId/hooks/:name | Uninstall a hook package |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index e17283ae..f7beb90d 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -220,6 +220,8 @@ PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不
| DELETE | /agents/:agentId/skills/:name | 卸载 Skill |
| POST | /agents/:agentId/plugins | 按名称安装库内插件——各自的 Skill 与钩子包,重装即更新。`{ names }` → 201 `{ skills, hooks }`;404 `unknown_plugin` 时什么都不写 |
| GET | /agents/:agentId/hooks | 已安装钩子包:名称、描述、版本、钩子点、所属插件的图标 |
+| POST | /agents/:agentId/hooks/archive | 从 zip 安装钩子包:`{dataBase64, overwrite?}`——hooks.json 与脚本在根目录或唯一顶层目录内,清单列出的每条命令都须指向包内文件;未带 overwrite 而同名已装时 409 `hook_exists` |
+| GET | /agents/:agentId/hooks/:name/archive | 把已安装的钩子包导出为 zip(可原样经 POST 导回) |
| GET | `/api/plugins`(全局) | 按分类列出插件库——每个插件带其 Skill 元数据与钩子点(任意已登录用户) |
| GET | `/api/plugins/:plugin/files`(全局) | 单个库内插件携带的全部文件,按路径键入的文本——各 Skill 的可安装 SKILL.md 与参考文件在 `skills/<name>/` 下,钩子脚本在 `hooks/` 下——供插件详情弹窗的文件浏览器使用(任意已登录用户) |
| DELETE | /agents/:agentId/hooks/:name | 卸载钩子包 |
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index 3a9e95dc..311ba2b1 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -78,7 +78,7 @@ A hook package is the plugin's `hooks/` directory installed as `agent_state/hook
}
```
-Installed is active: every top-level Session of the Agent consults its installed hook packages at the loop's hook points (a Session already running keeps the set it was built with; the server rebuilds an Agent's cached runtimes on the next idle access after a hook package is installed or removed). The scripts are plain Node with builtins only — they run wherever the harness runs, as subprocesses with JSON on stdin and a JSON answer on stdout; the contract is on [The Agent Loop](/agent-loop#stop-hooks). A hook package's other scripts are the host's to call by convention: the goal plugin's `start.mjs` is what the server runs when a user starts a goal ([Goal Mode](/goal-mode)).
+Installed is active: every top-level Session of the Agent consults its installed hook packages at the loop's hook points (a Session already running keeps the set it was built with; the server rebuilds an Agent's cached runtimes on the next idle access after a hook package is installed or removed, or after the switch below is flipped). Hooks are switched as a whole, not one package at a time: `hooks.enabled` in `system_config.yaml` (absent means on) is flipped by the Hooks tab's switch (Project owner only), and with it off a Session created from then on assembles no hooks at all while every package stays on disk. The same tab exports an installed package as a zip and imports one back — `hooks.json` and the scripts at the zip root, or in exactly one top-level directory; every command the manifest lists must name a file inside the archive — or hands the import to an agent, which reads the source and reviews the scripts before installing. The scripts are plain Node with builtins only — they run wherever the harness runs, as subprocesses with JSON on stdin and a JSON answer on stdout; the contract is on [The Agent Loop](/agent-loop#stop-hooks). A hook package's other scripts are the host's to call by convention: the goal plugin's `start.mjs` is what the server runs when a user starts a goal ([Goal Mode](/goal-mode)).
## Installation and storage
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index a92f6db4..1d33e521 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -78,7 +78,7 @@ Skill 采用「先索引、后正文」的设计:系统 Prompt 经 `{{SKILL_ME
}
```
-装了即生效:Agent 的每个顶层 Session 都会在循环的钩子点上咨询已安装的钩子包(正在运行的 Session 保持构建时的那套;安装或卸载钩子包后,服务端会在该 Agent 已缓存的运行时下次空闲访问时重建它们)。脚本是只用内置模块的纯 Node——harness 跑在哪它就跑在哪,以子进程方式运行,stdin 进 JSON、stdout 出 JSON 回答;契约见[运行循环](/agent-loop#stop-hook)。钩子包里的其他脚本由宿主按约定调用:goal 插件的 `start.mjs` 就是用户发起目标时服务端运行的那个([目标模式](/goal-mode))。
+装了即生效:Agent 的每个顶层 Session 都会在循环的钩子点上咨询已安装的钩子包(正在运行的 Session 保持构建时的那套;安装或卸载钩子包、以及下述开关变动后,服务端会在该 Agent 已缓存的运行时下次空闲访问时重建它们)。钩子的启停是整体的,不按单个包:`system_config.yaml` 的 `hooks.enabled`(缺省即启用)由 Hooks 标签页的开关(仅 Project owner)写入,关闭后新建的 Session 不组装任何钩子,已安装的包仍全部留在磁盘上。同一标签页可以把已装钩子包打包导出为 zip、再把这样的 zip 导入回来——`hooks.json` 与脚本在 zip 根目录,或在唯一的顶层目录内;清单列出的每条命令都必须指向压缩包内的文件——也可以把导入交给 Agent,由它通读来源、审查脚本后再安装。脚本是只用内置模块的纯 Node——harness 跑在哪它就跑在哪,以子进程方式运行,stdin 进 JSON、stdout 出 JSON 回答;契约见[运行循环](/agent-loop#stop-hook)。钩子包里的其他脚本由宿主按约定调用:goal 插件的 `start.mjs` 就是用户发起目标时服务端运行的那个([目标模式](/goal-mode))。
## 安装与存放
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index e8f244be..4b9599e8 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -103,7 +103,7 @@ The scheduled tasks panel lists the tasks bound to the current conversation (tas
## Create with AI
-Everything the Web App creates from a form — an agent, a model group, a Benchmark, a scheduled task, a vault secret, a hook import, an app, an agent import — can also be described to an agent instead. Each page offers two buttons side by side: **Create with AI** with the magic wand, and **Create manually** with the hand, so both paths are visible at once. The prompt box comes with clickable examples that fill the draft, and a folded **Full prompt** preview shows the fixed instructions that travel with what you typed, with a copy button. There is one way out, **Edit in a new conversation**: it opens a new conversation with the Project's `default_agent` (the first agent when there is none) and prefills the composer with the prompt — whether to send it is yours to decide. A prefilled prompt is not something the browser holds on to: leave the page without editing or sending it and it is dropped, so it cannot resurface in a later conversation. Type into it and it becomes an ordinary draft, kept like anything else you write.
+Everything the Web App creates from a form — an agent, a model group, a Benchmark, a scheduled task, a vault secret, an app, an agent import — can also be described to an agent instead. Each page offers two buttons side by side: **Create with AI** with the magic wand, and **Create manually** with the hand, so both paths are visible at once. The prompt box comes with clickable examples that fill the draft, and a folded **Full prompt** preview shows the fixed instructions that travel with what you typed, with a copy button. There is one way out, **Edit in a new conversation**: it opens a new conversation with the Project's `default_agent` (the first agent when there is none) and prefills the composer with the prompt — whether to send it is yours to decide. A prefilled prompt is not something the browser holds on to: leave the page without editing or sending it and it is dropped, so it cannot resurface in a later conversation. Type into it and it becomes an ordinary draft, kept like anything else you write.
## Agent Management (/agents)
@@ -116,7 +116,7 @@ The list page creates and deletes Agents — the create dialog can initialize th
| Memory | The Agent-level switch, then every memory grouped by scope — user memory first, then one group per Workspace, each group collapsible with add, export and import entries — with view / delete / edit-via-chat actions per row |
| Runtime | Runtime parameters such as max_turns, model.*, compaction.* |
| Tools | Built-in tool table (incl. per-tool call_description switches) and MCP Server management: a table plus an add/edit form whose fields follow the transport (http by default; changes save immediately; full transport validation server-side; a permission control fixes the approval level of that server's tools at `auto` / `r` / `rw`, and the table shows each server's effective level); connectivity testing mirrors the models page — a standalone button in the form probes the current entry (toast with tool count and latency), and a section-level button tests every server in turn with a result badge on each row |
-| Hooks | Installed hook packages (agent_state/hooks/): name, description, version and the hook points each answers at; uninstall. Installing happens on the plugin library page |
+| Hooks | An **Enable hooks** switch at the top (owner only; members see the state) decides whether a Session this agent starts from now on runs its hook packages at all — with it off a new Session runs none of them and every package stays on disk. Below it, the installed hook packages (agent_state/hooks/): each row leads with the package name and the hook points it answers at right beside it (bare point names such as `stop`), the description below, then the version, export as a zip and uninstall. **Import hook** opens the skill import dialog's shape: the recommended path lets the agent import it in chat — a hook source field (a URL, a GitHub repository, a local path, a description, or another tool's hooks config) with a live preview of the prompt, where **Copy prompt** and **Open a new chat** are greyed together while the source is empty; below it, a hook package zip can be uploaded directly (asking before it overwrites an installed name). Library installs still happen on the plugin library page |
| Vault | Environment-variable entries with masked values |
| Schedule | Scheduled tasks (TOML-defined): create — with AI or manually — edit, toggle, delete; suggestions stand in for an empty list |
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 6f98ae3e..cef75c10 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -102,7 +102,7 @@ Agent 写的是同一个 Workspace,你编辑期间文件可能被改动。每
## 用 AI 创建
-Web App 里凡是通过表单创建的对象——Agent、模型分组、Benchmark、定时任务、密钥保险柜条目、钩子导入、应用、Agent 导入——都可以改为向 Agent 描述。每个页面并排给出两个按钮:带魔法棒的**用 AI 创建**与带手形的**手动创建**,两条路径同时可见。提示词框自带可点击的示例,点一下即填入草稿;折叠的**完整提示词**预览展示随你的输入一起发送的固定说明,并带复制按钮。唯一的出口是**在新对话中编辑**:以 Project 的 `default_agent`(没有时取第一个 Agent)开启新对话,把提示词预填进输入框,发不发送由你决定。预填的提示词不会被浏览器留下:不作修改也不发送就离开该页面,它随即被丢弃,不会在之后的对话里再冒出来;一旦动手编辑,它就成为普通草稿,与你自己写的内容一样保留。
+Web App 里凡是通过表单创建的对象——Agent、模型分组、Benchmark、定时任务、密钥保险柜条目、应用、Agent 导入——都可以改为向 Agent 描述。每个页面并排给出两个按钮:带魔法棒的**用 AI 创建**与带手形的**手动创建**,两条路径同时可见。提示词框自带可点击的示例,点一下即填入草稿;折叠的**完整提示词**预览展示随你的输入一起发送的固定说明,并带复制按钮。唯一的出口是**在新对话中编辑**:以 Project 的 `default_agent`(没有时取第一个 Agent)开启新对话,把提示词预填进输入框,发不发送由你决定。预填的提示词不会被浏览器留下:不作修改也不发送就离开该页面,它随即被丢弃,不会在之后的对话里再冒出来;一旦动手编辑,它就成为普通草稿,与你自己写的内容一样保留。
## Agent 管理(/agents)
@@ -115,7 +115,7 @@ Web App 里凡是通过表单创建的对象——Agent、模型分组、Benchma
| Memory | Agent 级开关,以及按作用域分组的全部记忆——用户记忆在前、每个 Workspace 一组,分组可折叠并带添加、导出与导入入口——每行提供查看 / 删除 / 对话编辑 |
| Runtime | max_turns、model.*、compaction.* 等运行参数 |
| Tools | 内置工具表格(含条目级 call_description 开关)与 MCP Server 管理:表格 + 添加/编辑表单(默认 http,字段随 transport 切换,改动即时保存,服务端按 transport 完整校验;permission 控件把该 Server 工具的审批等级固定为 `auto` / `r` / `rw`,表格列出各 Server 的生效等级);测试连接与模型页同款——表单内独立按钮测当前条目(toast 报工具数与耗时),区块级按钮逐一测试全部 Server 并在各行显示结果徽标 |
-| Hooks | 已安装的钩子包(agent_state/hooks/):名称、描述、版本与各自应答的钩子点;可卸载。安装在插件库页完成 |
+| Hooks | 顶部一个**启用钩子**开关(仅 owner,成员只见状态)决定该 Agent 此后新建的 Session 是否运行钩子包——关闭后新建的 Session 一个钩子都不运行,已安装的包仍全部留在磁盘上。其下是已安装的钩子包(agent_state/hooks/):每行以包名加紧随其后的钩子点胶囊(只写钩子点名,如 `stop`)开头,其下描述,行尾版本、打包导出与卸载。**导入钩子**弹窗与导入技能同款:推荐路径是让 Agent 在对话中导入——填入钩子来源(URL / GitHub 仓库 / 本地路径 / 一段描述,或其他工具的钩子配置),弹窗实时预览发送给 Agent 的 Prompt,**复制 Prompt**与**打开新对话**在来源为空时一同置灰;其下可直接上传钩子包 zip(同名已装先确认覆盖)。从插件库安装仍在插件库页完成 |
| Vault | 环境变量条目,值以掩码显示 |
| Schedule | 定时任务(TOML 定义):创建(用 AI 创建或手动创建)、编辑、启停、删除;列表为空时展示建议 |
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 6904c006..4cbbcca7 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -968,6 +968,17 @@ export interface AgentSchedulesConfigDto {
templateHasPlaceholder: boolean;
}
+/**
+ * Hook config, edited on the Hooks tab. One Agent-level switch and no prompt: hook packages
+ * are scripts run at the loop's hook points, not text injected into the context. `enabled`
+ * reports the effective value (a config with no `hooks` section reads as enabled, matching
+ * core).
+ */
+export interface AgentHooksConfigDto {
+ /** Whether a Session created from now on runs the installed hook packages (they stay installed either way). */
+ enabled: boolean;
+}
+
/** Structured view of system_config.yaml (for the edit form). */
export interface AgentConfigDto {
name?: string;
@@ -988,6 +999,7 @@ export interface AgentConfigDto {
vault: AgentVaultConfigDto;
skills: AgentSkillsConfigDto;
schedules: AgentSchedulesConfigDto;
+ hooks: AgentHooksConfigDto;
toolsBuiltin: ToolDefinitionConfig[];
mcpServers: MCPServerConfig[];
}
@@ -1042,6 +1054,8 @@ export interface AgentConfigUpdateRequest {
vault?: { enabled?: boolean; prompt?: string };
skills?: { enabled?: boolean; prompt?: string };
schedules?: { enabled?: boolean; prompt?: string };
+ /** The Agent-level hook switch; it has no prompt half. */
+ hooks?: { enabled?: boolean };
toolsBuiltin?: ToolDefinitionConfig[];
mcpServers?: MCPServerConfig[];
};
@@ -3243,6 +3257,21 @@ export interface AgentHooksResponse {
hooks: HookItem[];
}
+/**
+ * POST /api/projects/:p/agents/:a/hooks/archive: install one hook package from an uploaded zip.
+ * Layout: hooks.json and its scripts at the zip root, or exactly one top-level directory
+ * containing them (the directory name is then the package name). 201 returns the refreshed
+ * installed list (AgentHooksResponse); an already-installed name without `overwrite` is 409
+ * `hook_exists`. GET …/hooks/:name/archive is the matching export: the installed directory as
+ * a zip attachment, which round-trips through this POST.
+ */
+export interface HookArchiveInstallRequest {
+ /** Base64-encoded zip archive (decoded size capped at 14MB, like the skill archive). */
+ dataBase64: string;
+ /** Replace an installed package of the same name instead of answering 409. */
+ overwrite?: boolean;
+}
+
/**
* POST /api/projects/:p/agents/:a/skills/archive: install one Skill from an uploaded zip.
* Layout: SKILL.md at the zip root, or exactly one top-level directory containing SKILL.md
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 474243e6..420be8f8 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -150,11 +150,8 @@ import { memoryRoutes } from "./http/routes/memory.js";
import { scheduleRoutes } from "./http/routes/schedules.js";
import { benchmarksRoutes } from "./http/routes/benchmarks.js";
import { agentSkillsRoutes } from "./http/routes/skills.js";
-import {
- agentHooksRoutes,
- agentPluginsRoutes,
- pluginLibraryRoutes,
-} from "./http/routes/plugins.js";
+import { agentHooksRoutes } from "./http/routes/hooks.js";
+import { agentPluginsRoutes, pluginLibraryRoutes } from "./http/routes/plugins.js";
import { agentTransferRoutes } from "./http/routes/agent-transfer.js";
import { agentsRoutes } from "./http/routes/agents.js";
import { dirsRoutes } from "./http/routes/dirs.js";
diff --git a/packages/server/src/http/routes/agent-config.ts b/packages/server/src/http/routes/agent-config.ts
index d13bd6a2..a1f0e35d 100644
--- a/packages/server/src/http/routes/agent-config.ts
+++ b/packages/server/src/http/routes/agent-config.ts
@@ -56,6 +56,12 @@ export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {
}
// Fine-grained validation (numeric ranges / enums) is done inside agent-config-service.
await deps.agentConfigService.updateConfig(projectId, agentId, req);
+ // Agent State normally needs no invalidation — core re-reads it into the next model
+ // context itself. The hook switch is the exception: hook packages are bound when a
+ // Session is built, so a cached runtime would keep the set it was built with.
+ if (req.config?.hooks !== undefined) {
+ deps.manager.invalidateAgentRuntimes(projectId, agentId);
+ }
const view = await deps.agentConfigService.getConfig(projectId, agentId);
return c.json({
...view,
@@ -149,6 +155,9 @@ export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {
const agentId = requireValidId(c, "agentId");
deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.resetConfig(projectId, agentId);
+ // The defaults carry no `hooks` section, so a reset can switch hooks back on; cached
+ // runtimes hold the set they were built with (see the PUT above).
+ deps.manager.invalidateAgentRuntimes(projectId, agentId);
const view = await deps.agentConfigService.getConfig(projectId, agentId);
return c.json({
...view,
diff --git a/packages/server/src/http/routes/hooks.ts b/packages/server/src/http/routes/hooks.ts
new file mode 100644
index 00000000..e621e36c
--- /dev/null
+++ b/packages/server/src/http/routes/hooks.ts
@@ -0,0 +1,371 @@
+/**
+ * An Agent's installed hook packages:
+ * GET /api/projects/:p/agents/:a/hooks # installed packages (any member)
+ * POST /api/projects/:p/agents/:a/hooks/archive # install one package from an uploaded zip (any member)
+ * GET /api/projects/:p/agents/:a/hooks/:name/archive # export one installed package as a zip (any member)
+ * DELETE /api/projects/:p/agents/:a/hooks/:name # uninstall (any member)
+ * Whether a Session runs hooks at all is not decided here: that is the Agent-level
+ * `hooks.enabled` switch, written through the config route.
+ * Installing from the library goes through the plugin routes (plugins.ts), which write a
+ * plugin's hook package to agent_state/hooks/<plugin>/ (hooks.json + scripts). The archive
+ * routes are the skills routes' pair: POST writes every zip file under hooks/<name>/ (replace
+ * semantics with `overwrite`), GET packs the whole directory back under a single top-level
+ * <name>/ so the download round-trips through the POST unchanged. Every mutation here
+ * invalidates the Agent's cached runtimes: hook packages are bound when a core Session is
+ * built (skills are read from disk on demand, hooks are not), so a runtime that outlived the
+ * change would keep running the old set until it was evicted.
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { unzipSync, strFromU8, zipSync } from "fflate";
+import { Hono } from "hono";
+import {
+ PLUGIN_NAME_PATTERN,
+ PLUGIN_VERSION_PATTERN,
+ hooksDir,
+ listInstalledHooks,
+ removeHook,
+ replaceSkillDirectory,
+} from "@prismshadow/penguin-core";
+import type { HookCommand, HookManifest } from "@prismshadow/penguin-core";
+import type { AgentHooksResponse, HookItem } from "../../api/types.js";
+import type { AppEnv } from "../../auth/middleware.js";
+import type { AppDeps } from "../../app.js";
+import { HttpError } from "../errors.js";
+import { badRequest, readJson, requireString, requireValidId } from "../validate.js";
+import { toHookItem } from "../../services/plugin-library.js";
+import {
+ MAX_ARCHIVE_FILES,
+ MAX_FILE_BYTES,
+ MAX_TOTAL_BYTES,
+} from "../../services/skill-import-limits.js";
+import { MAX_ARCHIVE_BYTES, assertSafeEntryPath } from "./skills.js";
+
+/** The hook points a manifest lists commands for. */
+const HOOK_POINTS = ["stop", "pre_tool_use", "user_prompt"] as const;
+
+/** A hook package decoded from an uploaded zip: its name and every file keyed by path relative to the package directory. */
+interface ArchiveHook {
+ name: string;
+ files: Map<string, Uint8Array>;
+}
+
+/** A command path as hooks.json may list it: relative, "/"-separated, no empty or ".." segment — so it resolves inside the package directory. */
+function isSafeCommandPath(command: string): boolean {
+ return (
+ command.length > 0 &&
+ !command.startsWith("/") &&
+ !/^[A-Za-z]:/.test(command) &&
+ !command.includes("\\") &&
+ !command.split("/").some((segment) => segment === "" || segment === "..")
+ );
+}
+
+/**
+ * Validates an uploaded manifest against the files beside it and returns the one that is
+ * written: the upload with its unknown fields kept (an export re-imports as it was), `name`
+ * set to the package's name, and the hook-point lists defaulted so the loader and the Session
+ * always find arrays. What is checked is what those readers rely on: a name in the
+ * directory-name character set, string display fields, and every command a relative path to a
+ * file inside the archive — a package whose scripts are missing or point outside its directory
+ * is refused. A stray `enabled` (a package exported while the per-package switch existed) is
+ * dropped: hooks are switched at the Agent level now, and the field means nothing on disk.
+ */
+function normalizeHookManifest(
+ raw: unknown,
+ name: string | undefined,
+ files: ReadonlySet<string>,
+): HookManifest {
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
+ throw badRequest("hooks.json must be a JSON object.");
+ }
+ const manifest = raw as Record<string, unknown>;
+ const resolved = name ?? manifest.name;
+ if (typeof resolved !== "string" || !PLUGIN_NAME_PATTERN.test(resolved)) {
+ throw badRequest(
+ `Invalid hook package name ${JSON.stringify(resolved)}: only letters, digits, "_" and "-" are allowed.`,
+ );
+ }
+ for (const key of ["description", "description_zh", "version"] as const) {
+ if (manifest[key] !== undefined && typeof manifest[key] !== "string") {
+ throw badRequest(`hooks.json ${key} must be a string.`);
+ }
+ }
+ const lists: Record<(typeof HOOK_POINTS)[number], HookCommand[]> = {
+ stop: [],
+ pre_tool_use: [],
+ user_prompt: [],
+ };
+ let commands = 0;
+ for (const point of HOOK_POINTS) {
+ const list = manifest[point];
+ if (list === undefined) continue;
+ if (!Array.isArray(list)) throw badRequest(`hooks.json ${point} must be an array.`);
+ for (const entry of list as unknown[]) {
+ const cmd = entry as Partial<HookCommand> | null;
+ if (cmd === null || typeof cmd !== "object" || typeof cmd.command !== "string") {
+ throw badRequest(`hooks.json ${point} entries must be { command, timeout? } objects.`);
+ }
+ if (!isSafeCommandPath(cmd.command) || !files.has(cmd.command)) {
+ throw badRequest(
+ `hooks.json ${point} command ${JSON.stringify(cmd.command)} must name a file inside the package.`,
+ );
+ }
+ if (cmd.timeout !== undefined && !(typeof cmd.timeout === "number" && cmd.timeout > 0)) {
+ throw badRequest(`hooks.json ${point} timeout must be a positive number of seconds.`);
+ }
+ commands += 1;
+ }
+ lists[point] = list as HookCommand[];
+ }
+ if (commands === 0) throw badRequest("hooks.json lists no hook-point commands.");
+ const { enabled: _dropped, ...rest } = manifest;
+ return {
+ ...rest,
+ name: resolved,
+ description: typeof manifest.description === "string" ? manifest.description : "",
+ version: typeof manifest.version === "string" ? manifest.version : "",
+ ...lists,
+ } as HookManifest;
+}
+
+/**
+ * Decodes and validates an uploaded hook package zip. Accepted layouts: hooks.json at the zip
+ * root (the name comes from the manifest), or exactly one top-level directory containing
+ * hooks.json (the directory name is the package name, consistent with listInstalledHooks
+ * where the directory name always wins). Directory entries are ignored (paths recreate
+ * them); every file path is zip-slip-checked and the count/size limits enforced before
+ * anything is returned. The manifest comes back normalized (see normalizeHookManifest) in
+ * place of the uploaded bytes.
+ *
+ * The path and size checks run in unzipSync's `filter`, i.e. off the central directory's
+ * DECLARED sizes and before a byte is inflated. A cap read off the inflated result bounds
+ * nothing, in two separate ways. Honest entries: 256KB of deflated zeros — three orders of
+ * magnitude under the request cap — is already 256MB on the heap by the time such a cap runs.
+ * Lying entries are worse: unzipSync allocates the declared size and inflates into it, so a
+ * 123-byte archive whose 5-byte entry declares 512MB allocates 512MB, and what comes back is
+ * a 5-byte VIEW of that buffer — a check on the returned bytes sees 5 and installs it.
+ */
+function parseHookArchive(archive: Buffer): ArchiveHook {
+ let count = 0;
+ let total = 0;
+ let entries: Record<string, Uint8Array>;
+ try {
+ entries = unzipSync(new Uint8Array(archive), {
+ filter: (file) => {
+ if (file.name.endsWith("/")) return false;
+ assertSafeEntryPath(file.name);
+ count += 1;
+ if (count > MAX_ARCHIVE_FILES) {
+ throw badRequest(`The zip archive exceeds the ${MAX_ARCHIVE_FILES}-file limit.`);
+ }
+ if (file.originalSize > MAX_FILE_BYTES) {
+ throw badRequest(`Zip entry exceeds the 5MB uncompressed limit: ${file.name}`);
+ }
+ total += file.originalSize;
+ if (total > MAX_TOTAL_BYTES) {
+ throw badRequest("The zip archive exceeds the 20MB uncompressed limit.");
+ }
+ return true;
+ },
+ });
+ } catch (err) {
+ // A cap the filter tripped is the answer; anything else means the bytes are not a zip.
+ if (err instanceof HttpError) throw err;
+ throw badRequest("dataBase64 is not a valid zip archive.");
+ }
+ const files = Object.entries(entries);
+ if (files.length === 0) throw badRequest("The zip archive contains no files.");
+ const names = files.map(([name]) => name);
+ let prefix = "";
+ let dirName: string | undefined;
+ if (!names.includes("hooks.json")) {
+ const topLevels = new Set(names.map((name) => name.split("/", 1)[0]!));
+ dirName = topLevels.size === 1 ? [...topLevels][0] : undefined;
+ if (dirName === undefined || !names.includes(`${dirName}/hooks.json`)) {
+ throw badRequest(
+ "The zip must contain hooks.json at its root, or exactly one top-level directory containing hooks.json.",
+ );
+ }
+ prefix = `${dirName}/`;
+ // A file entry named exactly `<dirName>` (no slash) shares the single top level with the
+ // directory: stripping the prefix would leave an empty relative path, and writing it would
+ // hit the staging directory itself (EISDIR) after validation had already passed.
+ if (names.includes(dirName)) {
+ throw badRequest(`Invalid zip entry path (it is the package directory): ${dirName}`);
+ }
+ }
+ const relative = new Map(files.map(([n, data]) => [n.slice(prefix.length), data]));
+ let raw: unknown;
+ try {
+ raw = JSON.parse(strFromU8(relative.get("hooks.json")!));
+ } catch {
+ throw badRequest("hooks.json is not valid JSON.");
+ }
+ const manifest = normalizeHookManifest(raw, dirName, new Set(relative.keys()));
+ relative.set("hooks.json", new TextEncoder().encode(`${JSON.stringify(manifest, null, 2)}\n`));
+ return { name: manifest.name, files: relative };
+}
+
+/**
+ * Collects an installed package directory as zip entries under a single top-level `<name>/`
+ * (subpaths preserved, "/" separators), so the export round-trips through the POST archive
+ * route unchanged. Symlinks and other non-regular entries are skipped (nothing outside the
+ * directory can leak). The import caps apply on the way out too — a directory exceeding them
+ * could not be re-imported anyway.
+ */
+async function collectHookArchive(dir: string, name: string): Promise<Record<string, Uint8Array>> {
+ const out: Record<string, Uint8Array> = {};
+ let count = 0;
+ let total = 0;
+ const walk = async (abs: string, rel: string): Promise<void> => {
+ for (const entry of await fs.readdir(abs, { withFileTypes: true })) {
+ const absChild = path.join(abs, entry.name);
+ const relChild = `${rel}/${entry.name}`;
+ if (entry.isDirectory()) {
+ await walk(absChild, relChild);
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ count += 1;
+ const data = new Uint8Array(await fs.readFile(absChild));
+ total += data.byteLength;
+ if (
+ count > MAX_ARCHIVE_FILES ||
+ data.byteLength > MAX_FILE_BYTES ||
+ total > MAX_TOTAL_BYTES
+ ) {
+ throw new HttpError(
+ 413,
+ "hook_too_large",
+ `Hook package exceeds the archive limits (${MAX_ARCHIVE_FILES} files, 5MB per file, 20MB total).`,
+ );
+ }
+ out[relChild] = data;
+ }
+ };
+ await walk(dir, name);
+ return out;
+}
+
+/** /api/projects/:p/agents/:a/hooks: read, import/export and uninstall are all Project-member operations. */
+export function agentHooksRoutes(deps: AppDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ const installedItems = async (projectId: string, agentId: string): Promise<HookItem[]> =>
+ (await listInstalledHooks(deps.config.root, projectId, agentId)).map(toHookItem);
+
+ /** The install criterion every per-package route shares, the one listInstalledHooks uses: hooks/<name>/hooks.json exists. Returns the package directory. */
+ const requireInstalled = async (
+ projectId: string,
+ agentId: string,
+ name: string,
+ ): Promise<string> => {
+ const dir = path.join(hooksDir(deps.config.root, projectId, agentId), name);
+ try {
+ await fs.access(path.join(dir, "hooks.json"));
+ } catch {
+ throw new HttpError(404, "not_found", `Hook package is not installed: ${name}`);
+ }
+ return dir;
+ };
+
+ app.get("/", async (c) => {
+ // Defensive id validation happens before any path construction: prevents path traversal for cross-Project privilege escalation.
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ await deps.agentConfigService.requireExists(projectId, agentId);
+ return c.json({ hooks: await installedItems(projectId, agentId) } satisfies AgentHooksResponse);
+ });
+
+ // Install one package from an uploaded zip (member-level, like the skills archive route).
+ app.post("/archive", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ await deps.agentConfigService.requireExists(projectId, agentId);
+ const body = await readJson(c);
+ const dataBase64 = requireString(body, "dataBase64", { minLen: 1, maxLen: 20 * 1024 * 1024 });
+ const overwrite = body.overwrite === true;
+ let archive: Buffer;
+ try {
+ archive = Buffer.from(dataBase64, "base64");
+ } catch {
+ throw badRequest("dataBase64 is not valid base64.");
+ }
+ if (archive.byteLength === 0) throw badRequest("The zip archive is empty.");
+ if (archive.byteLength > MAX_ARCHIVE_BYTES) {
+ throw badRequest("The zip archive exceeds the 14MB limit.");
+ }
+ const hook = parseHookArchive(archive);
+ const dir = path.join(hooksDir(deps.config.root, projectId, agentId), hook.name);
+ if (!overwrite) {
+ const installed = await fs.access(path.join(dir, "hooks.json")).then(
+ () => true,
+ () => false,
+ );
+ if (installed) {
+ // The name sits at the end of the message: the web tab reads it from there for the
+ // overwrite confirmation copy.
+ throw new HttpError(409, "hook_exists", `Hook package is already installed: ${hook.name}`);
+ }
+ }
+ // Replace semantics (the same as reinstalling from the library): the archive's files are
+ // staged and swapped in, so no stale file survives and an interrupted import leaves no
+ // half-written package behind.
+ await replaceSkillDirectory(dir, hook.files);
+ deps.manager.invalidateAgentRuntimes(projectId, agentId);
+ return c.json(
+ { hooks: await installedItems(projectId, agentId) } satisfies AgentHooksResponse,
+ 201,
+ );
+ });
+
+ // Export one installed package as a zip: a direct binary attachment (the shape of the skill
+ // export), re-importable byte-compatibly through the POST archive route.
+ app.get("/:name/archive", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ const name = requireValidId(c, "name");
+ const dir = await requireInstalled(projectId, agentId, name);
+ const archiveFiles = await collectHookArchive(dir, name);
+ // A -v<version> suffix only when the manifest carries a real version (the header is the
+ // authority on the filename — the web tab reads it from Content-Disposition).
+ let version = "";
+ try {
+ const manifest = JSON.parse(strFromU8(archiveFiles[`${name}/hooks.json`]!)) as {
+ version?: unknown;
+ };
+ if (typeof manifest.version === "string") version = manifest.version;
+ } catch {
+ // An unparseable manifest still exports (the files are what the user asked for); it just gets the bare filename.
+ }
+ const fileName = PLUGIN_VERSION_PATTERN.test(version)
+ ? `${name}-v${version}.zip`
+ : `${name}.zip`;
+ const zip = zipSync(archiveFiles);
+ return new Response(new Uint8Array(zip), {
+ headers: {
+ "Content-Type": "application/zip",
+ // The name is id-validated ([A-Za-z0-9_-]+), so the encoded filename is itself.
+ "Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`,
+ "X-Content-Type-Options": "nosniff",
+ },
+ });
+ });
+
+ app.delete("/:name", async (c) => {
+ const projectId = requireValidId(c, "projectId");
+ const agentId = requireValidId(c, "agentId");
+ deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ const name = requireValidId(c, "name");
+ await requireInstalled(projectId, agentId, name);
+ await removeHook(deps.config.root, projectId, agentId, name);
+ deps.manager.invalidateAgentRuntimes(projectId, agentId);
+ return c.body(null, 204);
+ });
+
+ return app;
+}
diff --git a/packages/server/src/http/routes/plugins.ts b/packages/server/src/http/routes/plugins.ts
index 21c5d1ca..9b95dbfd 100644
--- a/packages/server/src/http/routes/plugins.ts
+++ b/packages/server/src/http/routes/plugins.ts
@@ -1,28 +1,22 @@
/**
- * Plugin library & Agent-installed hook packages:
+ * Plugin library & installing from it:
* GET /api/plugins # the library by category (any logged-in user)
* GET /api/plugins/:plugin/files # the files a plugin ships, for the detail view's browser (any logged-in user)
* POST /api/projects/:p/agents/:a/plugins # install plugins from the library (any member)
- * GET /api/projects/:p/agents/:a/hooks # installed hook packages (any member)
- * DELETE /api/projects/:p/agents/:a/hooks/:name # uninstall one (any member)
* Installing a plugin writes each of its skills to agent_state/skills/<name>/ and its hook
* package to agent_state/hooks/<plugin>/ (hooks.json + scripts); reinstalling overwrites with
- * library content (i.e. an update). Installed skills keep their own routes (skills.ts).
+ * library content (i.e. an update). Installed skills and hook packages keep their own routes
+ * (skills.ts, hooks.ts).
*/
-import fs from "node:fs/promises";
-import path from "node:path";
import { Hono } from "hono";
import {
- hooksDir,
installPlugin,
listInstalledHooks,
listInstalledSkills,
- removeHook,
libraryPlugin,
loadPluginGroups,
} from "@prismshadow/penguin-core";
import type {
- AgentHooksResponse,
AgentPluginsInstallResponse,
PluginFilesResponse,
PluginLibraryResponse,
@@ -104,37 +98,3 @@ export function agentPluginsRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
-
-/** /api/projects/:p/agents/:a/hooks: read and uninstall are Project-member operations. */
-export function agentHooksRoutes(deps: AppDeps): Hono<AppEnv> {
- const app = new Hono<AppEnv>();
-
- app.get("/", async (c) => {
- const projectId = requireValidId(c, "projectId");
- const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
- await deps.agentConfigService.requireExists(projectId, agentId);
- const hooks = await listInstalledHooks(deps.config.root, projectId, agentId);
- return c.json({ hooks: hooks.map(toHookItem) } satisfies AgentHooksResponse);
- });
-
- app.delete("/:name", async (c) => {
- const projectId = requireValidId(c, "projectId");
- const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
- const name = requireValidId(c, "name");
- // Installed-check uses the same criterion as listInstalledHooks: hooks/<name>/hooks.json exists.
- try {
- await fs.access(
- path.join(hooksDir(deps.config.root, projectId, agentId), name, "hooks.json"),
- );
- } catch {
- throw new HttpError(404, "not_found", `Hook package is not installed: ${name}`);
- }
- await removeHook(deps.config.root, projectId, agentId, name);
- deps.manager.invalidateAgentRuntimes(projectId, agentId);
- return c.body(null, 204);
- });
-
- return app;
-}
diff --git a/packages/server/src/http/routes/skills.ts b/packages/server/src/http/routes/skills.ts
index 081b0d66..b81fa2a2 100644
--- a/packages/server/src/http/routes/skills.ts
+++ b/packages/server/src/http/routes/skills.ts
@@ -38,15 +38,15 @@ import {
unzipBounded,
} from "../../services/skill-import-limits.js";
-/** Decoded zip cap: aligned with the Agent snapshot import (stays within the 20MB body limit after base64). */
-const MAX_ARCHIVE_BYTES = 14 * 1024 * 1024;
+/** Decoded zip cap: aligned with the Agent snapshot import (stays within the 20MB body limit after base64). Shared with the hooks archive routes. */
+export const MAX_ARCHIVE_BYTES = 14 * 1024 * 1024;
/**
* Validates one zip entry path (zip-slip guard): rejects absolute paths (leading "/" or a
* drive letter), backslashes and any ".." segment — a malicious archive must never write
- * outside the target Skill directory.
+ * outside the target Skill directory. Shared with the hooks archive routes.
*/
-function assertSafeEntryPath(name: string): void {
+export function assertSafeEntryPath(name: string): void {
if (name.includes("\\")) throw badRequest(`Invalid zip entry path (backslash): ${name}`);
if (name.startsWith("/") || /^[A-Za-z]:/.test(name)) {
throw badRequest(`Invalid zip entry path (absolute): ${name}`);
diff --git a/packages/server/src/services/agent-config-service.ts b/packages/server/src/services/agent-config-service.ts
index d75934d4..f7579fe8 100644
--- a/packages/server/src/services/agent-config-service.ts
+++ b/packages/server/src/services/agent-config-service.ts
@@ -51,6 +51,7 @@ import type {
AgentModelConfigDto,
AgentCompactionConfigDto,
AgentMemoryConfigDto,
+ AgentHooksConfigDto,
AgentSchedulesConfigDto,
AgentSkillsConfigDto,
AgentVaultConfigDto,
@@ -149,6 +150,7 @@ export class AgentConfigService {
const vault = asRecord(parsed.vault);
const skills = asRecord(parsed.skills);
const schedules = asRecord(parsed.schedules);
+ const hooks = asRecord(parsed.hooks);
const tools = asRecord(parsed.tools);
let agentsMd = "";
@@ -212,6 +214,9 @@ export class AgentConfigService {
prompt: typeof schedules.prompt === "string" ? schedules.prompt : DEFAULT_SCHEDULES_PROMPT,
templateHasPlaceholder: hasSchedulesPlaceholder(systemPrompt),
};
+ // The hook switch has no prompt half and no template fact: hook packages are scripts run
+ // at the loop's hook points, never text in the context.
+ const hooksDto: AgentHooksConfigDto = { enabled: hooks.enabled !== false };
// Kernel stamp: reported literally (null = predates the mechanism), with the current
// generation and the outdated verdict beside it, so the client renders the update hint
// without knowing core's KERNEL_VERSION.
@@ -231,6 +236,7 @@ export class AgentConfigService {
vault: vaultDto,
skills: skillsDto,
schedules: schedulesDto,
+ hooks: hooksDto,
toolsBuiltin: Array.isArray(tools.builtin) ? (tools.builtin as ToolDefinitionConfig[]) : [],
mcpServers: Array.isArray(tools.mcpServers) ? (tools.mcpServers as MCPServerConfig[]) : [],
};
@@ -371,6 +377,11 @@ export class AgentConfigService {
setIfProvided(["schedules", "enabled"], optionalBoolean(schedules, "enabled"));
setIfProvided(["schedules", "prompt"], optionalString(schedules, "prompt"));
}
+ // The hook switch is the one section that governs behavior rather than the context: with
+ // it off a new Session assembles no hooks, while the packages stay installed on disk.
+ if (cfg.hooks !== undefined) {
+ setIfProvided(["hooks", "enabled"], optionalBoolean(asRecord(cfg.hooks), "enabled"));
+ }
if (cfg.toolsBuiltin !== undefined) {
doc.setIn(["tools", "builtin"], validateToolsBuiltin(cfg.toolsBuiltin));
}
diff --git a/packages/server/test/hooks.test.ts b/packages/server/test/hooks.test.ts
new file mode 100644
index 00000000..eeec791f
--- /dev/null
+++ b/packages/server/test/hooks.test.ts
@@ -0,0 +1,389 @@
+/**
+ * Integration tests for the hook package routes: the installed list, the zip archive install
+ * (layouts, manifest validation, zip-slip, 409 hook_exists + overwrite) and the byte-identical
+ * export round-trip. Whether Sessions run hooks at all is the Agent-level `hooks.enabled`
+ * switch, tested with the rest of the Agent config (prompt-sections.test.ts).
+ */
+import fs from "node:fs/promises";
+import path from "node:path";
+import { strToU8, unzipSync, zipSync } from "fflate";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { hooksDir } from "@prismshadow/penguin-core";
+import type { AgentHooksResponse, ProjectCreateResponse } from "../src/api/types.js";
+import { apiClient, createTestApp, provisionUser } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+describe("hooks api", () => {
+ let t: TestApp;
+ let owner: ReturnType<typeof apiClient>;
+ let member: ReturnType<typeof apiClient>;
+ let outsider: ReturnType<typeof apiClient>;
+ let projectId: string;
+ const base = (agentId: string) => `/api/projects/${projectId}/agents/${agentId}/hooks`;
+ const plugins = (agentId: string) => `/api/projects/${projectId}/agents/${agentId}/plugins`;
+ const manifestFile = (agentId: string, name: string) =>
+ path.join(hooksDir(t.root, projectId, agentId), name, "hooks.json");
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ const a = await provisionUser(t.app, "owner_h");
+ const b = await provisionUser(t.app, "member_h");
+ const c = await provisionUser(t.app, "outsider_h");
+ owner = apiClient(t.app, a.cookie);
+ member = apiClient(t.app, b.cookie);
+ outsider = apiClient(t.app, c.cookie);
+ const created = (await (
+ await owner.post("/api/projects", { projectId: "owner_h-hooks", name: "hooks project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ expect(
+ (await owner.post(`/api/projects/${projectId}/members`, { userId: "member_h" })).status,
+ ).toBe(201);
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ /** Creates a plain Agent with no plugins preinstalled. */
+ async function createPlainAgent(agentId: string): Promise<void> {
+ const res = await owner.post(`/api/projects/${projectId}/agents`, { agentId });
+ expect(res.status).toBe(201);
+ }
+
+ /** A canonical manifest, in the field order the installer writes, so an upload of it re-exports byte-identically. */
+ const MANIFEST = {
+ name: "zip-hook",
+ description: "Zip demo hook",
+ description_zh: "示例钩子",
+ version: "2026-09-02.1",
+ stop: [{ command: "stop.mjs", timeout: 5 }],
+ pre_tool_use: [],
+ user_prompt: [],
+ };
+ const STOP_MJS = "process.stdout.write('{}');\n";
+ const manifestText = (manifest: unknown): string => `${JSON.stringify(manifest, null, 2)}\n`;
+ /** Builds an in-memory zip and returns it base64-encoded (the request wire format). */
+ const zipB64 = (files: Record<string, Uint8Array>): string =>
+ Buffer.from(zipSync(files)).toString("base64");
+ /** A package under one top-level directory: the manifest plus its one script. */
+ const packageFiles = (
+ dir = "zip-hook",
+ manifest: unknown = MANIFEST,
+ ): Record<string, Uint8Array> => ({
+ [`${dir}/hooks.json`]: strToU8(manifestText(manifest)),
+ [`${dir}/stop.mjs`]: strToU8(STOP_MJS),
+ });
+ /**
+ * Rewrites one entry's declared uncompressed size in both the local and the central header
+ * (fflate reads the central one) and reports that record's compression method. No zip writer
+ * produces this; a hand-rolled archive does, and the declared size is what unzipSync
+ * allocates — but only on the deflate path: a stored entry (method 0) is sliced at its
+ * compressed size and never reads the declared one, so a fixture that stored its payload
+ * would reproduce nothing. The caller asserts the method for that reason.
+ */
+ const declareSize = (
+ zip: Uint8Array,
+ entry: string,
+ declared: number,
+ ): { zip: Uint8Array; method: number } => {
+ const want = strToU8(entry);
+ const dv = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);
+ const nameAt = (off: number): boolean => want.every((b, k) => zip[off + k] === b);
+ let method = -1;
+ for (let i = 0; i + 46 <= zip.length; i++) {
+ const sig = dv.getUint32(i, true);
+ // Local file header: method at +8, uncompressed size at +22, name length at +26, name at +30.
+ if (sig === 0x04034b50 && dv.getUint16(i + 26, true) === want.length && nameAt(i + 30)) {
+ dv.setUint32(i + 22, declared, true);
+ }
+ // Central directory header: method at +10, uncompressed size at +24, name length at +28, name at +46.
+ if (sig === 0x02014b50 && dv.getUint16(i + 28, true) === want.length && nameAt(i + 46)) {
+ method = dv.getUint16(i + 10, true);
+ dv.setUint32(i + 24, declared, true);
+ }
+ }
+ return { zip, method };
+ };
+
+ it("lists what a library install wrote, and the installer writes no switch into the manifest", async () => {
+ await createPlainAgent("sw_agent");
+ expect((await member.post(plugins("sw_agent"), { names: ["goal"] })).status).toBe(201);
+ const list = (await (await member.get(base("sw_agent"))).json()) as AgentHooksResponse;
+ expect(list.hooks.map((h) => [h.name, h.events])).toEqual([["goal", ["user_prompt", "stop"]]]);
+ const manifest = JSON.parse(await fs.readFile(manifestFile("sw_agent", "goal"), "utf8"));
+ expect("enabled" in manifest).toBe(false);
+ });
+
+ it("archive: the single-top-dir layout installs under the directory name, the root layout under the manifest's; uninstall works on it", async () => {
+ await createPlainAgent("zip_agent");
+ const url = `${base("zip_agent")}/archive`;
+ // The manifest says zip-hook, but the top-level directory is dir-hook: the directory
+ // name is the identity (the rule listInstalledHooks applies), and the written manifest
+ // says so too. The explicit directory entry ("dir-hook/") is ignored, not read as a file.
+ const res = await member.post(url, {
+ dataBase64: zipB64({
+ "dir-hook/": new Uint8Array(0),
+ ...packageFiles("dir-hook"),
+ "dir-hook/lib/util.mjs": strToU8("export const x = 1;\n"),
+ }),
+ });
+ expect(res.status).toBe(201);
+ const body = (await res.json()) as AgentHooksResponse;
+ expect(body.hooks.map((h) => [h.name, h.version, h.events])).toEqual([
+ ["dir-hook", "2026-09-02.1", ["stop"]],
+ ]);
+ expect(body.hooks[0]!.descriptionZh).toBe("示例钩子");
+ const dir = path.join(hooksDir(t.root, projectId, "zip_agent"), "dir-hook");
+ expect(JSON.parse(await fs.readFile(path.join(dir, "hooks.json"), "utf8"))).toMatchObject({
+ name: "dir-hook",
+ stop: [{ command: "stop.mjs", timeout: 5 }],
+ });
+ expect(await fs.readFile(path.join(dir, "stop.mjs"), "utf8")).toBe(STOP_MJS);
+ expect(await fs.readFile(path.join(dir, "lib", "util.mjs"), "utf8")).toBe(
+ "export const x = 1;\n",
+ );
+
+ // Root layout: the name comes from the manifest; the point lists it omits are written
+ // as empty arrays, so the loader and the Session always find arrays.
+ const root = await member.post(url, {
+ dataBase64: zipB64({
+ "hooks.json": strToU8(
+ manifestText({
+ name: "root-hook",
+ version: "2026-09-02.2",
+ user_prompt: [{ command: "expand.mjs" }],
+ }),
+ ),
+ "expand.mjs": strToU8(STOP_MJS),
+ }),
+ });
+ expect(root.status).toBe(201);
+ const both = (await root.json()) as AgentHooksResponse;
+ expect(both.hooks.map((h) => h.name)).toEqual(["dir-hook", "root-hook"]);
+ expect(both.hooks[1]).toMatchObject({ description: "", events: ["user_prompt"] });
+ expect(JSON.parse(await fs.readFile(manifestFile("zip_agent", "root-hook"), "utf8"))).toEqual({
+ name: "root-hook",
+ version: "2026-09-02.2",
+ user_prompt: [{ command: "expand.mjs" }],
+ description: "",
+ stop: [],
+ pre_tool_use: [],
+ });
+
+ // Uninstall goes through the same DELETE as library packages: 204, directory gone.
+ expect((await member.delete(`${base("zip_agent")}/root-hook`)).status).toBe(204);
+ await expect(
+ fs.access(path.join(hooksDir(t.root, projectId, "zip_agent"), "root-hook")),
+ ).rejects.toThrow();
+ // Outsiders never reach the archive routes.
+ expect((await outsider.post(url, { dataBase64: "AAAA" })).status).toBe(404);
+ expect((await outsider.get(`${base("zip_agent")}/dir-hook/archive`)).status).toBe(404);
+ });
+
+ it("archive: manifest validation rejects what the loader and the Session could not run, writing nothing", async () => {
+ await createPlainAgent("zip_manifest_agent");
+ const url = `${base("zip_manifest_agent")}/archive`;
+ const cases: Array<[string, Record<string, Uint8Array>]> = [
+ ["not JSON", { "h/hooks.json": strToU8("{"), "h/stop.mjs": strToU8(STOP_MJS) }],
+ ["an array", { "h/hooks.json": strToU8("[]"), "h/stop.mjs": strToU8(STOP_MJS) }],
+ [
+ "an invalid name (root layout)",
+ {
+ "hooks.json": strToU8(manifestText({ ...MANIFEST, name: "bad name!" })),
+ "stop.mjs": strToU8(STOP_MJS),
+ },
+ ],
+ [
+ "an invalid directory name",
+ {
+ "bad name!/hooks.json": strToU8(manifestText(MANIFEST)),
+ "bad name!/stop.mjs": strToU8(STOP_MJS),
+ },
+ ],
+ [
+ "a command missing from the archive",
+ packageFiles("h", { ...MANIFEST, stop: [{ command: "missing.mjs" }] }),
+ ],
+ [
+ "a command pointing outside the package",
+ { ...packageFiles("h", { ...MANIFEST, stop: [{ command: "../stop.mjs" }] }) },
+ ],
+ ["an absolute command", packageFiles("h", { ...MANIFEST, stop: [{ command: "/stop.mjs" }] })],
+ ["a non-object command", packageFiles("h", { ...MANIFEST, stop: ["stop.mjs"] })],
+ ["a non-array point list", packageFiles("h", { ...MANIFEST, stop: { command: "stop.mjs" } })],
+ [
+ "a non-positive timeout",
+ packageFiles("h", { ...MANIFEST, stop: [{ command: "stop.mjs", timeout: 0 }] }),
+ ],
+ ["no commands at all", packageFiles("h", { ...MANIFEST, stop: [] })],
+ ["a non-string description", packageFiles("h", { ...MANIFEST, description: 1 })],
+ ];
+ for (const [label, files] of cases) {
+ const res = await member.post(url, { dataBase64: zipB64(files) });
+ expect(res.status, label).toBe(400);
+ }
+ const list = (await (
+ await member.get(base("zip_manifest_agent"))
+ ).json()) as AgentHooksResponse;
+ expect(list.hooks).toEqual([]);
+ });
+
+ it("archive: zip-slip entry paths and malformed bodies are rejected with 400, nothing written", async () => {
+ await createPlainAgent("zip_shape_agent");
+ const url = `${base("zip_shape_agent")}/archive`;
+ for (const entry of ["../evil.mjs", "/abs/hooks.json", "C:/x/hooks.json", "h\\hooks.json"]) {
+ const res = await member.post(url, {
+ dataBase64: zipB64({ ...packageFiles("h"), [entry]: strToU8("x") }),
+ });
+ expect(res.status, entry).toBe(400);
+ }
+ // Not base64 / not a zip / empty / no manifest / two top-level directories.
+ expect((await member.post(url, { dataBase64: "" })).status).toBe(400);
+ expect((await member.post(url, { dataBase64: "AAAA" })).status).toBe(400);
+ expect((await member.post(url, { dataBase64: zipB64({}) })).status).toBe(400);
+ expect(
+ (await member.post(url, { dataBase64: zipB64({ "h/stop.mjs": strToU8(STOP_MJS) }) })).status,
+ ).toBe(400);
+ expect(
+ (
+ await member.post(url, {
+ dataBase64: zipB64({ ...packageFiles("a"), ...packageFiles("b") }),
+ })
+ ).status,
+ ).toBe(400);
+ // A file entry named exactly like the single top level: its relative path would be empty,
+ // and writing it would land on the staging directory itself.
+ expect(
+ (await member.post(url, { dataBase64: zipB64({ ...packageFiles("h"), h: strToU8("x") }) }))
+ .status,
+ ).toBe(400);
+ await expect(fs.readdir(hooksDir(t.root, projectId, "zip_shape_agent"))).resolves.toEqual([]);
+ });
+
+ it("archive: an entry over the per-file cap is refused however small the archive is", async () => {
+ await createPlainAgent("zip_bomb_agent");
+ const url = `${base("zip_bomb_agent")}/archive`;
+ // 8MB of zeros deflate to a few KB, so the request caps never see it coming: the only
+ // thing between this upload and 8MB of heap is where the per-file cap is applied.
+ const zip = zipSync({ ...packageFiles("h"), "h/pad.bin": new Uint8Array(8 * 1024 * 1024) });
+ expect(zip.byteLength).toBeLessThan(64 * 1024);
+ const res = await member.post(url, { dataBase64: Buffer.from(zip).toString("base64") });
+ expect(res.status).toBe(400);
+ // Naming the entry pins the refusal to the per-file declared-size branch, rather than to
+ // some total measured later; the sub-64KB archive is the proof nothing post-inflation
+ // could have done it without first putting the 8MB on the heap.
+ expect(((await res.json()) as { error: { message: string } }).error.message).toContain(
+ "5MB uncompressed limit: h/pad.bin",
+ );
+ await expect(fs.readdir(hooksDir(t.root, projectId, "zip_bomb_agent"))).resolves.toEqual([]);
+ });
+
+ it("archive: an entry that lies about its uncompressed size is refused, not installed", async () => {
+ await createPlainAgent("zip_lie_agent");
+ const url = `${base("zip_lie_agent")}/archive`;
+ // The other half of the bomb, and the one a cap on the inflated bytes cannot see at all:
+ // unzipSync allocates the DECLARED size and inflates into it, then hands back a view of
+ // the real length. So a sub-kilobyte archive whose 5-byte entry declares 512MB takes
+ // 512MB of heap and returns 5 bytes — a check on the returned bytes reads 5 and installs
+ // the package (pre-fix this route answered 201 here).
+ const { zip, method } = declareSize(
+ zipSync({ ...packageFiles("h"), "h/pad.bin": strToU8("hello") }),
+ "h/pad.bin",
+ 512 * 1024 * 1024,
+ );
+ // Deflate, not stored: a stored entry is sliced at its compressed size and never reads
+ // the declared one, which would make this fixture prove nothing.
+ expect(method).toBe(8);
+ expect(zip.byteLength).toBeLessThan(1024);
+ const res = await member.post(url, { dataBase64: Buffer.from(zip).toString("base64") });
+ expect(res.status).toBe(400);
+ expect(((await res.json()) as { error: { message: string } }).error.message).toContain(
+ "5MB uncompressed limit: h/pad.bin",
+ );
+ await expect(fs.readdir(hooksDir(t.root, projectId, "zip_lie_agent"))).resolves.toEqual([]);
+ });
+
+ it("archive: already installed is 409 hook_exists; overwrite replaces the directory (stale files removed)", async () => {
+ await createPlainAgent("zip_over_agent");
+ const url = `${base("zip_over_agent")}/archive`;
+ const first = await member.post(url, {
+ dataBase64: zipB64({ ...packageFiles(), "zip-hook/old.txt": strToU8("old\n") }),
+ });
+ expect(first.status).toBe(201);
+
+ // Same name again without overwrite: 409 with the name at the end of the message (the
+ // web tab reads it from there for the overwrite confirmation copy).
+ const again = await member.post(url, { dataBase64: zipB64(packageFiles()) });
+ expect(again.status).toBe(409);
+ const err = (await again.json()) as { error: { code: string; message: string } };
+ expect(err.error.code).toBe("hook_exists");
+ expect(err.error.message).toMatch(/: zip-hook$/);
+
+ // overwrite: true replaces the whole directory: old.txt is gone, new.txt appears.
+ const res = await member.post(url, {
+ dataBase64: zipB64({
+ ...packageFiles("zip-hook", { ...MANIFEST, version: "2026-09-02.3" }),
+ "zip-hook/new.txt": strToU8("new\n"),
+ }),
+ overwrite: true,
+ });
+ expect(res.status).toBe(201);
+ const body = (await res.json()) as AgentHooksResponse;
+ expect(body.hooks.find((h) => h.name === "zip-hook")!.version).toBe("2026-09-02.3");
+ const dir = path.join(hooksDir(t.root, projectId, "zip_over_agent"), "zip-hook");
+ expect(await fs.readFile(path.join(dir, "new.txt"), "utf8")).toBe("new\n");
+ await expect(fs.access(path.join(dir, "old.txt"))).rejects.toThrow();
+ });
+
+ it("archive export: a single-top-dir zip round-trips byte-identically; a non-installed name is 404", async () => {
+ await createPlainAgent("zip_export_agent");
+ const url = base("zip_export_agent");
+ const files: Record<string, Uint8Array> = {
+ ...packageFiles(),
+ "zip-hook/icon.svg": strToU8('<svg viewBox="0 0 24 24"><path d="M2 2h20"/></svg>\n'),
+ "zip-hook/lib/util.mjs": strToU8("export const x = 1;\n"),
+ };
+ expect((await member.post(`${url}/archive`, { dataBase64: zipB64(files) })).status).toBe(201);
+
+ // A direct binary attachment (application/zip); the manifest's version names the file.
+ const res = await member.get(`${url}/zip-hook/archive`);
+ expect(res.status).toBe(200);
+ expect(res.headers.get("content-type")).toBe("application/zip");
+ expect(res.headers.get("content-disposition")).toBe(
+ "attachment; filename*=UTF-8''zip-hook-v2026-09-02.1.zip",
+ );
+ const entries = unzipSync(new Uint8Array(await res.arrayBuffer()));
+ const fileNames = Object.keys(entries).filter((n) => !n.endsWith("/"));
+ expect(fileNames.sort()).toEqual(Object.keys(files).sort());
+ for (const [name, data] of Object.entries(files)) {
+ expect(Buffer.from(entries[name]!), name).toEqual(Buffer.from(data));
+ }
+
+ // The export re-imports on another Agent unchanged.
+ await createPlainAgent("zip_import_agent");
+ const moved = await member.post(`${base("zip_import_agent")}/archive`, {
+ dataBase64: Buffer.from(
+ await (await member.get(`${url}/zip-hook/archive`)).arrayBuffer(),
+ ).toString("base64"),
+ });
+ expect(moved.status).toBe(201);
+ expect(((await moved.json()) as AgentHooksResponse).hooks).toMatchObject([
+ { name: "zip-hook" },
+ ]);
+
+ // Not installed → 404 (the same criterion as uninstall); no real version → bare filename.
+ expect((await member.get(`${url}/no-such-hook/archive`)).status).toBe(404);
+ expect(
+ (
+ await member.post(`${url}/archive`, {
+ dataBase64: zipB64(packageFiles("nover-hook", { ...MANIFEST, version: "v1" })),
+ })
+ ).status,
+ ).toBe(201);
+ const plain = await member.get(`${url}/nover-hook/archive`);
+ expect(plain.status).toBe(200);
+ expect(plain.headers.get("content-disposition")).toBe(
+ "attachment; filename*=UTF-8''nover-hook.zip",
+ );
+ });
+});
diff --git a/packages/server/test/prompt-sections.test.ts b/packages/server/test/prompt-sections.test.ts
index e9161bd9..2892c1eb 100644
--- a/packages/server/test/prompt-sections.test.ts
+++ b/packages/server/test/prompt-sections.test.ts
@@ -5,7 +5,8 @@
* toggles and prompts round-trip through PUT …/config, and each feature's
* POST …/template-placeholder inserts — or, for a legacy hardcoded section, migrates to —
* its placeholder, with the routers' own permission models (skills member-level,
- * vault/schedules owner-only).
+ * vault/schedules owner-only). The Hooks tab's switch rides on the same config route with no
+ * prompt half — `hooks.enabled` decides whether a new Session runs the installed hook packages.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { LEGACY_SKILLS_SECTION, LEGACY_VAULT_SECTION } from "@prismshadow/penguin-core";
@@ -78,6 +79,16 @@ describe("prompt-injection config (vault / skills / schedules)", () => {
}
});
+ it("round-trips the hook switch, which carries no prompt", async () => {
+ expect((await getConfig()).config.hooks).toEqual({ enabled: true });
+ const off = await owner.put(configPath, { config: { hooks: { enabled: false } } });
+ expect(off.status).toBe(200);
+ expect(((await off.json()) as AgentConfigResponse).config.hooks.enabled).toBe(false);
+ expect((await getConfig()).config.hooks.enabled).toBe(false);
+ const on = await owner.put(configPath, { config: { hooks: { enabled: true } } });
+ expect(((await on.json()) as AgentConfigResponse).config.hooks.enabled).toBe(true);
+ });
+
it("round-trips a custom prompt, leaving the other sections untouched", async () => {
const put = await owner.put(configPath, {
config: { vault: { prompt: "# Vault\ncustom {{VAULT_KEYS}}" } },
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 92b71074..37fd38d6 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -132,6 +132,7 @@ import type {
UpdateJobStatus,
RestartResponse,
DesktopUpdateStatusResponse,
+ HookArchiveInstallRequest,
UsageErrorKind,
UsageErrorsClearResponse,
UsageErrorsPage,
@@ -1096,6 +1097,23 @@ export const uninstallAgentHook = (projectId: string, agentId: string, name: str
{ method: "DELETE" },
);
+/** Installs one hook package from an uploaded zip (base64); 409 hook_exists unless overwrite; 201 returns the latest installed list. */
+export const installAgentHookArchive = (
+ projectId: string,
+ agentId: string,
+ body: HookArchiveInstallRequest,
+) =>
+ apiFetch<AgentHooksResponse>(
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` +
+ `/hooks/archive`,
+ { method: "POST", body },
+ );
+
+/** Zip download URL for one installed hook package (server sets Content-Disposition attachment); the export round-trips through installAgentHookArchive. */
+export const agentHookArchiveUrl = (projectId: string, agentId: string, name: string): string =>
+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` +
+ `/hooks/${encodeURIComponent(name)}/archive`;
+
/** Installs one skill from an uploaded zip (base64); 409 skill_exists unless overwrite; 201 returns the latest installed list. */
export const installAgentSkillArchive = (
projectId: string,
diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsx
index fbb94bc3..fcf4f7fb 100644
--- a/packages/web/src/features/agents/agent-settings-page.tsx
+++ b/packages/web/src/features/agents/agent-settings-page.tsx
@@ -300,7 +300,7 @@ export function AgentSettingsPage() {
</div>
)}
{tab === "skills" && <SkillsTab agentId={agentId} onConfigChanged={refreshConfig} />}
- {tab === "hooks" && <HooksTab agentId={agentId} />}
+ {tab === "hooks" && <HooksTab agentId={agentId} onConfigChanged={refreshConfig} />}
{tab === "vault" && <VaultTab agentId={agentId} onConfigChanged={refreshConfig} />}
{tab === "schedules" && (
<SchedulesTab agentId={agentId} onConfigChanged={refreshConfig} />
diff --git a/packages/web/src/features/agents/archive-download.ts b/packages/web/src/features/agents/archive-download.ts
new file mode 100644
index 00000000..6bd2b931
--- /dev/null
+++ b/packages/web/src/features/agents/archive-download.ts
@@ -0,0 +1,37 @@
+/**
+ * "Export as zip" for the Skills and Hooks tabs: fetch the archive, then save it through a
+ * temporary object-URL anchor. The codebase's other downloads are bare `<a href download>`
+ * anchors (snapshot export, trace download), but a bare anchor would save the error JSON as a
+ * file when the request fails — fetching first lets a failure surface as a toast instead. The
+ * JSON-only api client can't carry binary, hence the raw fetch (errors re-wrapped as ApiError
+ * so apiErrorText localizes by code as usual). The server's Content-Disposition is the
+ * authority on the filename (it appends -v<version> when the installed copy declares one);
+ * `<fallbackName>.zip` covers a missing or unparseable header.
+ */
+import { ApiError } from "../../api/client";
+import { S } from "../../lib/strings";
+
+export async function downloadArchive(url: string, fallbackName: string): Promise<void> {
+ const res = await fetch(url);
+ if (!res.ok) {
+ const body = (await res.json().catch(() => null)) as {
+ error?: { code?: string; message?: string };
+ } | null;
+ throw new ApiError(
+ res.status,
+ body?.error?.code ?? "unknown",
+ body?.error?.message ?? S.common.unknownError,
+ );
+ }
+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(
+ res.headers.get("content-disposition") ?? "",
+ )?.[1];
+ const objectUrl = URL.createObjectURL(await res.blob());
+ const anchor = document.createElement("a");
+ anchor.href = objectUrl;
+ anchor.download = encoded ? decodeURIComponent(encoded) : `${fallbackName}.zip`;
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+ URL.revokeObjectURL(objectUrl);
+}
diff --git a/packages/web/src/features/agents/hook-import.ts b/packages/web/src/features/agents/hook-import.ts
new file mode 100644
index 00000000..2973d1f3
--- /dev/null
+++ b/packages/web/src/features/agents/hook-import.ts
@@ -0,0 +1,36 @@
+/**
+ * The prompt behind the Hooks tab's chat import (pure logic, unit tested): the lead sentence
+ * derived from the pasted source, and the fixed instruction tail joined after it. The tail
+ * carries what the agent cannot guess — the review step, the hook package format, the script
+ * contract and where to install — and names the destination by Project and Agent id. Reads S
+ * at call time (live binding), so both follow language switches like every other string
+ * consumer.
+ */
+import { S } from "../../lib/strings";
+import { composeAiPrompt } from "../ai-create";
+import { classifyImportSource } from "./skill-import-source";
+
+/**
+ * Lead sentence for one source. A URL, repository or local path is something to fetch, so it
+ * is wrapped in an import instruction; anything else is already free text the user wrote (a
+ * description of the hook, or a hooks config block pasted from another tool) and is passed
+ * through verbatim.
+ */
+export function hookImportLead(input: string): string {
+ const source = input.trim();
+ const kind = classifyImportSource(source);
+ if (kind === "webUrl" || kind === "repoUrl" || kind === "localPath") {
+ return S.hooks.importPromptLead(source);
+ }
+ return source;
+}
+
+/** The fixed tail for installing into `agentId` of `projectId` (shown in the dialog's prompt preview). */
+export function hookImportTail(projectId: string, agentId: string): string {
+ return S.hooks.importPromptTail(projectId, agentId);
+}
+
+/** The whole prompt that is sent: the lead, then the tail after one blank line. */
+export function buildHookImportPrompt(input: string, projectId: string, agentId: string): string {
+ return composeAiPrompt(hookImportLead(input), hookImportTail(projectId, agentId));
+}
diff --git a/packages/web/src/features/agents/hooks-tab.tsx b/packages/web/src/features/agents/hooks-tab.tsx
index 172f674e..6681f2cb 100644
--- a/packages/web/src/features/agents/hooks-tab.tsx
+++ b/packages/web/src/features/agents/hooks-tab.tsx
@@ -4,15 +4,26 @@
* hook points, e.g. after every Task). The files are the single source of truth, so the list
* is re-fetched from the API after every mutation instead of trusting client state, the way
* the Skills tab does. Rows lead with the icon of the plugin the package came from (the hook
- * glyph when it has none), then the package name, its localized description, the hook points
- * it answers at (one chip each) and its version; uninstall confirms first
- * (it deletes the whole package directory, local edits included). Installing happens through
- * the plugin library — a hook package is part of a plugin, installed with it — so there is no
- * import entry here. Read and mutate are both member-level, matching the hooks routes.
+ * glyph when it has none), then the package name with the hook points it answers at right
+ * beside it (one bare chip each — `stop`, `user_prompt` — wrapping with the name), its
+ * localized description below, and the trailing slot: the version, export and uninstall.
+ * Export downloads the installed directory as a zip; the "Import hook" modal offers the
+ * Skills tab's two paths: the recommended chat import (a source field taking a URL / repo /
+ * local path / description / another tool's hooks config, whose generated review-then-install
+ * prompt — hook-import.ts — can be copied or prefilled into a new chat with this Agent) and a
+ * zip upload that takes such a package back (409 hook_exists asks before overwriting). Read,
+ * import/export and uninstall are member-level, matching the hooks routes.
+ *
+ * The Agent-level switch card sits at the top (usePromptInjection, the Skills tab's slot):
+ * `hooks.enabled` in system_config.yaml decides whether a new Session assembles any hooks at
+ * all — the packages are never touched by it. It is the owner's, like the Vault and Schedules
+ * switches; members see the state. Hooks have no prompt half, so the card comes alone.
*/
import { useCallback, useEffect, useState } from "react";
+import type { ChangeEvent } from "react";
import type { HookItem } from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
+import { ApiError } from "../../api/client";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { useLocale } from "../../state/locale";
@@ -20,20 +31,51 @@ import { agentDisplayName, useProject } from "../../state/project";
import { Badge } from "../../components/ui/badge";
import { Button } from "../../components/ui/button";
import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { CopiedStatus, CopyCheckGlyph, useCopied } from "../../components/ui/copy-button";
import { SettingsEmpty } from "../../components/ui/empty-state";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { HelpFold } from "../../components/ui/help-fold";
-import { HOOK_ICON } from "../../components/ui/icons";
+import { HiddenFileInput } from "../../components/ui/hidden-file-input";
+import { DownloadIcon, HOOK_ICON } from "../../components/ui/icons";
+import { Textarea } from "../../components/ui/input";
+import { Modal } from "../../components/ui/modal";
import { SkeletonList } from "../../components/ui/skeleton";
import { toastError, toastSuccess } from "../../components/ui/toast";
import { localizedText } from "../chat/skill-use";
import { SkillTile } from "../skills/skill-icon-view";
-import { TRASH_ICON } from "./skills-tab";
+import { useAiBridge } from "../ai-create";
+import { downloadArchive } from "./archive-download";
+import { buildHookImportPrompt } from "./hook-import";
+import { usePromptInjection } from "./prompt-injection-controls";
+import { TRASH_ICON, UPLOAD_LABEL_CLASS } from "./skills-tab";
-export function HooksTab({ agentId }: { agentId: string }) {
+/** Zip pending an overwrite confirmation: the payload to resend with overwrite: true plus the package name for the confirm copy. */
+interface PendingOverwrite {
+ dataBase64: string;
+ name: string;
+}
+
+export function HooksTab({
+ agentId,
+ onConfigChanged,
+}: {
+ agentId: string;
+ /** The switch writes the Agent config directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert it. */
+ onConfigChanged?: () => void;
+}) {
const { locale } = useLocale();
const { currentProject, agents, reloadAgents } = useProject();
+ const { openAiChat } = useAiBridge();
const projectId = currentProject?.projectId ?? null;
+ const isOwner = currentProject?.role === "owner";
+ // The Agent-level hook switch: owner-only, like the Vault and Schedules switches.
+ const { applyConfig, toggleCard } = usePromptInjection({
+ agentId,
+ feature: "hooks",
+ strings: S.hooks.injection,
+ canEdit: isOwner,
+ onConfigChanged,
+ });
const [hooks, setHooks] = useState<HookItem[] | null>(null);
// Tab-level error is only the initial list load failure; row actions report via toast.
@@ -41,18 +83,30 @@ export function HooksTab({ agentId }: { agentId: string }) {
const [busy, setBusy] = useState(false);
// Package name pending uninstall confirmation (non-null shows the confirm modal).
const [removing, setRemoving] = useState<string | null>(null);
+ // Import modal: the source for the chat-import prompt + upload state travel with the modal.
+ const [importOpen, setImportOpen] = useState(false);
+ const [source, setSource] = useState("");
+ const [uploading, setUploading] = useState(false);
+ const [uploadError, setUploadError] = useState<string | null>(null);
+ // Non-null shows the overwrite confirm (the archive POST answered 409 hook_exists).
+ const [overwriting, setOverwriting] = useState<PendingOverwrite | null>(null);
const load = useCallback(async () => {
if (!projectId || !agentId) return;
setHooks(null);
setError(null);
try {
- const res = await api.getAgentHooks(projectId, agentId);
+ // The switch card's state loads in parallel with the tab's own list.
+ const [res, configView] = await Promise.all([
+ api.getAgentHooks(projectId, agentId),
+ api.getAgentConfig(projectId, agentId),
+ ]);
setHooks(res.hooks);
+ applyConfig(configView.config);
} catch (e) {
setError(apiErrorText(e));
}
- }, [projectId, agentId]);
+ }, [projectId, agentId, applyConfig]);
useEffect(() => {
void load();
@@ -62,6 +116,16 @@ export function HooksTab({ agentId }: { agentId: string }) {
const agent = agents.find((a) => a.agentId === agentId);
const agentName = agent ? agentDisplayName(agent) : agentId;
+ /** "Export as zip": the shared archive download (archive-download.ts); a failure surfaces as a toast. */
+ const exportHook = async (name: string) => {
+ if (!projectId) return;
+ try {
+ await downloadArchive(api.agentHookArchiveUrl(projectId, agentId, name), name);
+ } catch (e) {
+ toastError(apiErrorText(e));
+ }
+ };
+
/** Confirm modal's "Confirm": uninstall, then always re-fetch the list from disk. */
const confirmRemove = async () => {
if (!projectId || removing === null) return;
@@ -80,12 +144,104 @@ export function HooksTab({ agentId }: { agentId: string }) {
}
};
+ /** Open the import modal (reset the form and upload state). */
+ const openImport = () => {
+ setSource("");
+ setUploadError(null);
+ setOverwriting(null);
+ setImportOpen(true);
+ };
+
+ /**
+ * POST the zip to the archive endpoint. A 409 hook_exists pops the overwrite confirm (the
+ * package name is read from the server's fixed message tail, pinned by the route tests;
+ * `fallbackName` — the picked file's stem — covers a parse miss). Success closes the modal
+ * and re-fetches the list.
+ */
+ const upload = async (dataBase64: string, fallbackName: string, overwrite: boolean) => {
+ if (!projectId) return;
+ setUploading(true);
+ setUploadError(null);
+ try {
+ await api.installAgentHookArchive(projectId, agentId, {
+ dataBase64,
+ ...(overwrite ? { overwrite: true } : {}),
+ });
+ setOverwriting(null);
+ setImportOpen(false);
+ toastSuccess(S.hooks.importDoneToast);
+ await load();
+ // The agent card's hook count changed; refresh the list provider too.
+ void reloadAgents();
+ } catch (e) {
+ if (e instanceof ApiError && e.status === 409 && e.code === "hook_exists") {
+ const name = /:\s*([A-Za-z0-9_-]+)$/.exec(e.message)?.[1] ?? fallbackName;
+ setOverwriting({ dataBase64, name });
+ } else {
+ setOverwriting(null);
+ setUploadError(apiErrorText(e));
+ }
+ } finally {
+ setUploading(false);
+ }
+ };
+
+ const onPickFile = (e: ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ e.target.value = "";
+ if (!file) return;
+ setUploadError(null);
+ const fallbackName = file.name.replace(/\.zip$/i, "");
+ const reader = new FileReader();
+ reader.onload = () => {
+ const dataUrl = reader.result as string;
+ void upload(dataUrl.slice(dataUrl.indexOf(",") + 1), fallbackName, false); // strip the data:...;base64, prefix
+ };
+ reader.onerror = () => setUploadError(S.common.unknownError);
+ reader.readAsDataURL(file);
+ };
+
+ // A URL / repo / path source gets an import lead sentence, free text is the lead itself (see
+ // hook-import.ts); the preview substitutes a placeholder token until something is entered.
+ const trimmedSource = source.trim();
+ const chatPrompt =
+ projectId !== null
+ ? buildHookImportPrompt(trimmedSource || S.hooks.importSourceToken, projectId, agentId)
+ : "";
+ // Copy feedback lives at the button (the shared copy convention): its glyph flips to the
+ // check while copied — no toast, and the button label never changes.
+ const promptCopy = useCopied();
+
+ /**
+ * "Open a new chat" with this Agent: the AI bridge prefills the composer with the generated
+ * import prompt (parking typed-but-unsent draft text first) and clears a stale handoff
+ * target and skill pre-selection along with it.
+ */
+ const openChat = () => {
+ if (projectId === null || trimmedSource === "") return;
+ openAiChat({ agentId, text: buildHookImportPrompt(trimmedSource, projectId, agentId) });
+ setImportOpen(false);
+ };
+
if (!projectId) return null;
return (
<div className="space-y-4">
{/* Tab-level description: no title in the panel to anchor a "?" to (see help-fold.tsx). */}
- <HelpFold label={S.agent.tabHooks}>{S.hooks.agentTabDesc}</HelpFold>
+ <HelpFold label={S.agent.tabHooks}>
+ {S.hooks.agentTabDesc}
+ {!isOwner && <span className="mt-1.5 block">{S.hooks.readOnlyHint}</span>}
+ </HelpFold>
+
+ {toggleCard}
+
+ {/* Import entry point at the head of the installed list, right-aligned — the Skills tab's
+ slot. It renders in every list state so the action never shifts. */}
+ <div className="flex justify-end">
+ <Button size="sm" variant="primary" disabled={hooks === null} onClick={openImport}>
+ {S.hooks.importHook}
+ </Button>
+ </div>
{hooks === null ? (
<SkeletonList rows={3} />
@@ -108,12 +264,19 @@ export function HooksTab({ agentId }: { agentId: string }) {
glyph={20}
/>
<div className="min-w-0 flex-1">
- <span
- className="block truncate font-mono text-[13px] font-semibold"
- title={hook.name}
- >
- {hook.name}
- </span>
+ {/* Title row: the name with the hook points it answers at right beside it — bare
+ point names, wrapping onto a second line rather than truncating. */}
+ <div className="flex flex-wrap items-center gap-x-1.5 gap-y-1">
+ <span
+ className="max-w-full truncate font-mono text-[13px] font-semibold"
+ title={hook.name}
+ >
+ {hook.name}
+ </span>
+ {hook.events.map((event) => (
+ <Badge key={event}>{event}</Badge>
+ ))}
+ </div>
{/* Description truncates to one line (the full text goes into title for hover reading). */}
<p
className="mt-0.5 truncate text-xs text-gray-500 dark:text-gray-400"
@@ -122,12 +285,6 @@ export function HooksTab({ agentId }: { agentId: string }) {
{description}
</p>
</div>
- {/* The hook points the package answers at, one chip each (the same wording as the library card's badges). */}
- <span className="hidden shrink-0 items-center gap-1 sm:flex">
- {hook.events.map((event) => (
- <Badge key={event}>{S.plugins.hookBadge(event)}</Badge>
- ))}
- </span>
{hook.version !== "" && (
<span
className="hidden shrink-0 text-[11px] text-gray-400 sm:block dark:text-gray-500"
@@ -136,7 +293,17 @@ export function HooksTab({ agentId }: { agentId: string }) {
{hook.version}
</span>
)}
- {/* Icon-only row action (same affordance as the Skills tab's delete: danger variant with red text/hover); the tooltip + aria-label carry the wording. */}
+ {/* Icon-only row actions (the Skills tab's pair: neutral bordered icon for export,
+ danger variant with red text/hover for delete); the tooltip + aria-label carry the wording. */}
+ <Button
+ size="icon"
+ title={S.hooks.exportHook}
+ aria-label={`${S.hooks.exportHook} ${hook.name}`}
+ disabled={busy}
+ onClick={() => void exportHook(hook.name)}
+ >
+ <DownloadIcon size={14} className="text-gray-600 dark:text-gray-300" />
+ </Button>
<Button
size="icon"
variant="danger"
@@ -153,6 +320,96 @@ export function HooksTab({ agentId }: { agentId: string }) {
</div>
)}
+ {/* Import modal: recommended chat import on top, zip upload below (the Skills tab's shape). */}
+ <Modal
+ open={importOpen}
+ title={S.hooks.importHook}
+ onClose={() => setImportOpen(false)}
+ widthClass="sm:max-w-lg"
+ >
+ <div className="space-y-4">
+ <section>
+ <p className="text-sm font-medium">{S.hooks.importChatTitle}</p>
+ <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
+ {S.hooks.importChatWhy}
+ </p>
+ <div className="mt-2.5 space-y-2.5">
+ {/* A source may be a whole pasted hooks config block, so the field is multi-line. */}
+ <Textarea
+ label={S.hooks.importSourceLabel}
+ hint={S.hooks.importSourceHint}
+ size="sm"
+ rows={3}
+ value={source}
+ onChange={(e) => setSource(e.target.value)}
+ placeholder={S.hooks.importSourcePlaceholder}
+ />
+ <Textarea
+ label={S.hooks.importPromptLabel}
+ size="sm"
+ rows={5}
+ readOnly
+ value={chatPrompt}
+ className="text-gray-600 dark:text-gray-300"
+ />
+ <div className="flex gap-2">
+ <Button
+ size="sm"
+ disabled={trimmedSource === ""}
+ onClick={() =>
+ promptCopy.flash(buildHookImportPrompt(trimmedSource, projectId, agentId))
+ }
+ >
+ <CopyCheckGlyph copied={promptCopy.copied} size={12} />
+ {S.hooks.importCopyPrompt}
+ </Button>
+ <CopiedStatus copied={promptCopy.copied} />
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={trimmedSource === ""}
+ onClick={openChat}
+ >
+ {S.hooks.importOpenChat}
+ </Button>
+ </div>
+ </div>
+ </section>
+
+ <section className="border-t border-gray-200 pt-4 dark:border-gray-800">
+ <p className="text-sm font-medium">{S.hooks.importUploadTitle}</p>
+ <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
+ {S.hooks.importUploadDesc}
+ </p>
+ <label
+ className={`${UPLOAD_LABEL_CLASS} mt-2.5 ${uploading ? "pointer-events-none opacity-60" : ""}`}
+ >
+ <HiddenFileInput accept=".zip" disabled={uploading} onChange={onPickFile} />
+ {uploading ? S.hooks.importUploading : S.hooks.importUploadAction}
+ </label>
+ {uploadError && (
+ <p className="mt-1.5 text-xs text-red-600 dark:text-red-400">{uploadError}</p>
+ )}
+ </section>
+ </div>
+ </Modal>
+
+ {/* Overwrite confirmation: the import modal stays underneath, so cancel returns to it; confirm resends the same zip with overwrite: true. */}
+ <ConfirmModal
+ open={overwriting !== null}
+ title={S.hooks.importOverwriteTitle}
+ confirmLabel={S.hooks.importOverwriteAction}
+ busy={uploading}
+ onClose={() => setOverwriting(null)}
+ onConfirm={() => {
+ if (overwriting !== null) void upload(overwriting.dataBase64, overwriting.name, true);
+ }}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {overwriting !== null ? S.hooks.importOverwriteBody(overwriting.name) : ""}
+ </p>
+ </ConfirmModal>
+
{/* Uninstall confirmation (shared ConfirmModal, the Skills tab's pattern). */}
<ConfirmModal
open={removing !== null}
diff --git a/packages/web/src/features/agents/prompt-injection-controls.tsx b/packages/web/src/features/agents/prompt-injection-controls.tsx
index e531a71f..32df1ceb 100644
--- a/packages/web/src/features/agents/prompt-injection-controls.tsx
+++ b/packages/web/src/features/agents/prompt-injection-controls.tsx
@@ -1,24 +1,29 @@
/**
- * Shared prompt-injection controls for the Skills / Vault / Schedules tabs, mirroring the
- * Memory tab's layout: an enable-switch card (label + switch, the memory tab's exact card
- * shape) that writes immediately (so toggling never drags an unfinished prompt edit along),
- * an amber alert when the template lacks the feature's section placeholder — with one-click
- * insert, or one-click migration when the template still carries the legacy hardcoded
- * section — and an editable prompt section (mono textarea + placeholder-chip reference +
- * confirm-first save). The toggle and prompt govern prompt injection only — the feature
- * itself keeps working with the switch off (vault values still reach subprocesses, tasks
- * still fire, skills stay invocable).
+ * Shared enable-switch (and, where the feature has one, prompt) controls for the Skills /
+ * Vault / Schedules / Hooks tabs, mirroring the Memory tab's layout: an enable-switch card
+ * (label + switch, the memory tab's exact card shape) that writes immediately (so toggling
+ * never drags an unfinished prompt edit along), an amber alert when the template lacks the
+ * feature's section placeholder — with one-click insert, or one-click migration when the
+ * template still carries the legacy hardcoded section — and an editable prompt section (mono
+ * textarea + placeholder-chip reference + confirm-first save). On the three prompt features
+ * the toggle and prompt govern prompt injection only — the feature itself keeps working with
+ * the switch off (vault values still reach subprocesses, tasks still fire, skills stay
+ * invocable). Hooks is the one switch-only feature: its packages are scripts run at the loop's
+ * hook points rather than text in the context, so it supplies no prompt strings and gets the
+ * card alone — and its switch does govern behavior, deciding whether a new Session assembles
+ * any hooks at all.
*
* Exposed as a hook returning render slots (the useSaveConfirm convention) because the pieces
* straddle the host tab's own content: the switch and alert sit above it, the prompt editor
* below. The hook owns the config state; the tab seeds it via `applyConfig` from the
* getAgentConfig response it loads in parallel with its own data. `canEdit` carries the host
- * tab's permission model (member-level on Skills, owner-only on Vault / Schedules).
+ * tab's permission model (member-level on Skills, owner-only on Vault / Schedules / Hooks).
*/
import { useCallback, useRef, useState } from "react";
import type { ReactNode, RefObject } from "react";
import type {
AgentConfigDto,
+ AgentHooksConfigDto,
AgentSchedulesConfigDto,
AgentSkillsConfigDto,
AgentVaultConfigDto,
@@ -35,11 +40,19 @@ import { toastError, toastSuccess } from "../../components/ui/toast";
import { toneStrip } from "../../lib/tone";
import { InfoPopover } from "../../components/ui/info-popover";
-export type PromptInjectionFeature = "skills" | "vault" | "schedules";
+export type PromptInjectionFeature = "skills" | "vault" | "schedules" | "hooks";
-/** The strings each feature section supplies (S.skills / S.vault / S.schedule); migrate/legacyTemplate exist only where a legacy hardcoded section does. */
-interface PromptInjectionStrings {
+/** What every feature supplies: the switch card's label, plus the two strings a switch-only feature needs in place of the prompt section's own wording. */
+interface ToggleStrings {
enable: string;
+ /** Disclosed beside the label ("?"): what the switch decides and when a change lands. Omitted where the tab's own description already says it. */
+ enableHint?: string;
+ /** Toast after a successful flip; defaults to the agent-config wording, whose compaction clause only fits a prompt section. */
+ savedToast?: string;
+}
+
+/** Adds what a feature with an editable prompt supplies (S.skills / S.vault / S.schedule); migrate/legacyTemplate exist only where a legacy hardcoded section does. */
+interface PromptInjectionStrings extends ToggleStrings {
templateMissing: string;
legacyTemplate?: string;
insertPlaceholder: string;
@@ -50,11 +63,11 @@ interface PromptInjectionStrings {
promptPlaceholders: ReadonlyArray<readonly [string, string]>;
}
-/** The three feature DTOs share this shape; `legacySectionPresent` is absent on schedules (it never had a hardcoded section). */
+/** The feature DTOs share this shape; everything but `enabled` is absent on the switch-only feature, and `legacySectionPresent` also on schedules (it never had a hardcoded section). */
interface SectionConfigState {
enabled: boolean;
- prompt: string;
- templateHasPlaceholder: boolean;
+ prompt?: string;
+ templateHasPlaceholder?: boolean;
legacySectionPresent?: boolean;
}
@@ -91,7 +104,7 @@ export function usePromptInjection({
}: {
agentId: string;
feature: PromptInjectionFeature;
- strings: PromptInjectionStrings;
+ strings: ToggleStrings | PromptInjectionStrings;
/** The host tab's permission model: false renders everything read-only (switch disabled, buttons hidden, prompt not saveable). */
canEdit: boolean;
/** Config writes happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them. */
@@ -112,13 +125,18 @@ export function usePromptInjection({
const promptRef = useRef<HTMLTextAreaElement>(null);
const { requestSave, element: saveConfirm } = useSaveConfirm();
+ // A switch-only feature supplies no prompt strings: it renders neither the template alert
+ // nor the prompt editor, and there is nothing for the placeholder endpoints to insert.
+ const promptStrings: PromptInjectionStrings | null = "promptSection" in strings ? strings : null;
+
// Stable so the host tab's load() can list it as a dependency without re-triggering itself.
const applyConfig = useCallback(
(config: AgentConfigDto) => {
- const dto: AgentVaultConfigDto | AgentSkillsConfigDto | AgentSchedulesConfigDto =
+ const dto:
+ AgentVaultConfigDto | AgentSkillsConfigDto | AgentSchedulesConfigDto | AgentHooksConfigDto =
config[feature];
setState(dto);
- setPrompt(dto.prompt);
+ setPrompt("prompt" in dto ? dto.prompt : "");
},
[feature],
);
@@ -129,7 +147,9 @@ export function usePromptInjection({
? { config: { skills: patch } }
: feature === "vault"
? { config: { vault: patch } }
- : { config: { schedules: patch } };
+ : feature === "schedules"
+ ? { config: { schedules: patch } }
+ : { config: { hooks: { enabled: patch.enabled } } };
const toggleEnabled = async (next: boolean) => {
if (!projectId) return;
@@ -137,7 +157,7 @@ export function usePromptInjection({
try {
const res = await api.putAgentConfig(projectId, agentId, featurePatch({ enabled: next }));
applyConfig(res.config);
- toastSuccess(S.agent.savedTakesEffect);
+ toastSuccess(strings.savedToast ?? S.agent.savedTakesEffect);
onConfigChanged?.();
} catch (e) {
toastError(apiErrorText(e));
@@ -154,7 +174,11 @@ export function usePromptInjection({
? api.insertSkillsPlaceholder
: feature === "vault"
? api.insertVaultPlaceholder
- : api.insertSchedulesPlaceholder;
+ : feature === "schedules"
+ ? api.insertSchedulesPlaceholder
+ : null;
+ // Only the alert strip calls this, and a switch-only feature has no alert strip.
+ if (insert === null) return;
try {
const dto = await insert(projectId, agentId);
setState(dto);
@@ -182,7 +206,13 @@ export function usePromptInjection({
const toggleCard = state !== null && (
<div className="flex items-center justify-between gap-4 rounded-lg border border-gray-200 px-4 py-3 dark:border-gray-800">
- <p className="text-sm font-medium text-gray-800 dark:text-gray-200">{strings.enable}</p>
+ {/* The "?" sits inside the label so it modifies a title rather than standing alone (see info-popover.tsx). */}
+ <p className="flex items-center gap-1.5 text-sm font-medium text-gray-800 dark:text-gray-200">
+ {strings.enable}
+ {strings.enableHint !== undefined && (
+ <InfoPopover label={strings.enable}>{strings.enableHint}</InfoPopover>
+ )}
+ </p>
<Switch
checked={state.enabled}
onChange={(v) => void toggleEnabled(v)}
@@ -194,30 +224,36 @@ export function usePromptInjection({
// Legacy templates get the migration wording (and the legacy strings always exist for the
// features that can report legacySectionPresent); everything else gets the plain insert.
const legacy = state?.legacySectionPresent === true;
- const alertStrip = state !== null && !state.templateHasPlaceholder && (
+ const alertStrip = promptStrings !== null && state !== null && !state.templateHasPlaceholder && (
<div
className={`flex items-center justify-between gap-4 rounded-lg border px-4 py-3 ${toneStrip.attention}`}
>
<p className="text-xs">
- {legacy ? (strings.legacyTemplate ?? strings.templateMissing) : strings.templateMissing}
+ {legacy
+ ? (promptStrings.legacyTemplate ?? promptStrings.templateMissing)
+ : promptStrings.templateMissing}
</p>
{canEdit && (
<Button size="sm" className="shrink-0" onClick={() => void insertPlaceholder()}>
- {legacy ? (strings.migrate ?? strings.insertPlaceholder) : strings.insertPlaceholder}
+ {legacy
+ ? (promptStrings.migrate ?? promptStrings.insertPlaceholder)
+ : promptStrings.insertPlaceholder}
</Button>
)}
</div>
);
- const promptSection = state !== null && (
+ const promptSection = promptStrings !== null && state !== null && (
<section className="space-y-2.5 rounded-lg border border-gray-200 p-3.5 dark:border-gray-800">
<h3 className="flex items-center gap-1.5 text-sm font-semibold text-gray-800 dark:text-gray-200">
- {strings.promptSection}
- <InfoPopover label={strings.promptSection}>{strings.promptSectionHint}</InfoPopover>
+ {promptStrings.promptSection}
+ <InfoPopover label={promptStrings.promptSection}>
+ {promptStrings.promptSectionHint}
+ </InfoPopover>
</h3>
<Textarea
ref={promptRef}
- label={strings.promptLabel}
+ label={promptStrings.promptLabel}
mono
size="sm"
rows={12}
@@ -229,7 +265,7 @@ export function usePromptInjection({
<div className="rounded-md border border-gray-200 bg-gray-50 p-3 dark:border-gray-800 dark:bg-gray-900">
<p className="mb-2 text-xs font-semibold text-gray-500">{S.agent.placeholdersTitle}</p>
<ul className="space-y-1">
- {strings.promptPlaceholders.map(([token, desc]) => (
+ {promptStrings.promptPlaceholders.map(([token, desc]) => (
<li key={token} className="flex items-center gap-3 text-xs">
<button
type="button"
diff --git a/packages/web/src/features/agents/skills-tab.tsx b/packages/web/src/features/agents/skills-tab.tsx
index 7d2e8925..3b46db80 100644
--- a/packages/web/src/features/agents/skills-tab.tsx
+++ b/packages/web/src/features/agents/skills-tab.tsx
@@ -19,7 +19,6 @@
*/
import { useCallback, useEffect, useState } from "react";
import type { ChangeEvent } from "react";
-import { useNavigate } from "react-router";
import type { SkillMetadataItem } from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { ApiError } from "../../api/client";
@@ -40,14 +39,14 @@ import { SkeletonList } from "../../components/ui/skeleton";
import { toastError, toastSuccess } from "../../components/ui/toast";
import { SkillTile } from "../skills/skill-icon-view";
import { localizedShortText } from "../chat/skill-use";
-import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { useAiBridge } from "../ai-create";
+import { downloadArchive } from "./archive-download";
import { buildImportPrompt } from "./skill-import-source";
import { usePromptInjection } from "./prompt-injection-controls";
import { HelpFold } from "../../components/ui/help-fold";
-/** <label> version of the button look (matches Button secondary sm; the Button component only renders <button>) — same as the Overview tab's snapshot-import label. */
-const UPLOAD_LABEL_CLASS =
+/** <label> version of the button look (matches Button secondary sm; the Button component only renders <button>) — same as the Overview tab's snapshot-import label; the Hooks tab's upload label borrows it. */
+export const UPLOAD_LABEL_CLASS =
"inline-flex cursor-pointer items-center justify-center gap-1 rounded-md border border-gray-300 " +
"bg-white px-2.5 py-1 text-xs font-medium text-gray-800 transition-colors duration-150 " +
"hover:bg-gray-50 focus-within:ring-2 focus-within:ring-gray-400/30 " +
@@ -71,10 +70,9 @@ export function SkillsTab({
/** Config writes (toggle / prompt / placeholder insert) happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them. */
onConfigChanged?: () => void;
}) {
- const navigate = useNavigate();
const { openAiChat } = useAiBridge();
const { locale } = useLocale();
- const { currentProject, agents, setCurrentAgentId, reloadAgents } = useProject();
+ const { currentProject, agents, reloadAgents } = useProject();
const projectId = currentProject?.projectId ?? null;
// Prompt-injection controls (toggle / template alert / prompt editor): member-level like
// every other mutation on this tab.
@@ -125,42 +123,11 @@ export function SkillsTab({
const agent = agents.find((a) => a.agentId === agentId);
const agentName = agent ? agentDisplayName(agent) : agentId;
- /**
- * "Export as zip": fetch the archive and save it via a temporary object-URL anchor.
- * The codebase's other downloads are bare `<a href download>` anchors (snapshot export,
- * trace download), but a bare anchor would save the error JSON as a file when the
- * request fails — fetching first lets failures surface as a toast instead. The JSON-only
- * api client can't carry binary, hence the raw fetch (errors re-wrapped as ApiError so
- * apiErrorText localizes by code as usual).
- */
+ /** "Export as zip": the shared archive download (archive-download.ts); a failure surfaces as a toast. */
const exportSkill = async (name: string) => {
if (!projectId) return;
try {
- const res = await fetch(api.agentSkillArchiveUrl(projectId, agentId, name));
- if (!res.ok) {
- const body = (await res.json().catch(() => null)) as {
- error?: { code?: string; message?: string };
- } | null;
- throw new ApiError(
- res.status,
- body?.error?.code ?? "unknown",
- body?.error?.message ?? S.common.unknownError,
- );
- }
- // The server's Content-Disposition is the authority on the filename (it appends
- // -v<version> when the frontmatter declares one explicitly); <name>.zip is only
- // the fallback for a missing/unparseable header.
- const encoded = /filename\*=UTF-8''([^;]+)/i.exec(
- res.headers.get("content-disposition") ?? "",
- )?.[1];
- const url = URL.createObjectURL(await res.blob());
- const anchor = document.createElement("a");
- anchor.href = url;
- anchor.download = encoded ? decodeURIComponent(encoded) : `${name}.zip`;
- document.body.appendChild(anchor);
- anchor.click();
- anchor.remove();
- URL.revokeObjectURL(url);
+ await downloadArchive(api.agentSkillArchiveUrl(projectId, agentId, name), name);
} catch (e) {
toastError(apiErrorText(e));
}
@@ -203,18 +170,14 @@ export function SkillsTab({
const promptCopy = useCopied();
/**
- * "Open a new chat" with this Agent: the same draft-state entry as the agents page
- * "New Chat" button. A non-empty source goes through the AI bridge instead, which prefills
- * the composer with the generated install prompt (parking typed-but-unsent draft text
- * first) and clears a stale handoff target and skill pre-selection along with it.
+ * "Open a new chat" with this Agent: the AI bridge prefills the composer with the generated
+ * install prompt (parking typed-but-unsent draft text first) and clears a stale handoff
+ * target and skill pre-selection along with it. Disabled without a source, like the copy
+ * button — a blank chat would drop the prompt the dialog just built.
*/
const openChat = () => {
- if (trimmedSource) {
- openAiChat({ agentId, text: buildImportPrompt(trimmedSource) });
- return;
- }
- setCurrentAgentId(agentId);
- navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });
+ if (trimmedSource === "") return;
+ openAiChat({ agentId, text: buildImportPrompt(trimmedSource) });
};
/**
@@ -394,7 +357,12 @@ export function SkillsTab({
{S.skills.importCopyPrompt}
</Button>
<CopiedStatus copied={promptCopy.copied} />
- <Button size="sm" variant="primary" onClick={openChat}>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={trimmedSource === ""}
+ onClick={openChat}
+ >
{S.skills.importOpenChat}
</Button>
</div>
diff --git a/packages/web/src/features/plugins/plugin-detail.tsx b/packages/web/src/features/plugins/plugin-detail.tsx
index 48f7b217..7fcdc07d 100644
--- a/packages/web/src/features/plugins/plugin-detail.tsx
+++ b/packages/web/src/features/plugins/plugin-detail.tsx
@@ -166,10 +166,11 @@ export function PluginDetailModal({
{localizedText(locale, plugin.description, plugin.descriptionZh)}
</p>
<p className="mt-1.5 text-[11px] text-gray-400 dark:text-gray-500">{meta}</p>
+ {/* The hook points the package answers at: bare point names (`stop`, `user_prompt`) — identifiers, not copy. */}
{plugin.hooks.length > 0 && (
<div className="mt-2 flex flex-wrap gap-1.5">
{plugin.hooks.map((event) => (
- <Badge key={event}>{S.plugins.hookBadge(event)}</Badge>
+ <Badge key={event}>{event}</Badge>
))}
</div>
)}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index ac285795..98ef195a 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1289,8 +1289,6 @@ export const en: Strings = {
pageDesc:
"Built-in plugin library: each plugin ships skills and/or a hook package — browse, quick-start a chat, or install to agents.",
pluginCount: (n: number): string => (n === 1 ? "1 plugin" : `${n} plugins`),
- /** Content badge for each hook point a plugin's hook package answers at (e.g. "stop hook"); also the chips on the settings Hooks tab. */
- hookBadge: (event: string): string => `${event} hook`,
searchPlaceholder: "Search plugins",
/** Section labels of the plugin detail Modal. */
detailSkills: "Skills",
@@ -1314,18 +1312,62 @@ export const en: Strings = {
`Uninstall ${plugin} from ${agent}? Its installed skill and hook files (local edits included) will be deleted.`,
},
- /** Agent settings "Hooks" tab (features/agents/hooks-tab.tsx): the hook packages installed on one agent. */
+ /** Agent settings "Hooks" tab (features/agents/hooks-tab.tsx): the hook packages installed on one agent — the list with its enable switch, the import modal (chat import / zip upload) and the export. The hook-point chips carry the bare point name (`stop`, `user_prompt`) and need no string. */
hooks: {
agentTabDesc:
- "Hook packages installed on this agent (agent_state/hooks/) — scripts the harness runs at the loop's hook points, e.g. after every Task; uninstalling deletes the whole package directory.",
+ "Hook packages installed on this agent (agent_state/hooks/) — scripts the harness runs at the loop's hook points, e.g. after every Task. Uninstalling deletes the whole package directory.",
agentTabEmpty: "No hook packages installed yet",
+ /** Members see the switch state but cannot flip it (appended to the tab description). */
+ readOnlyHint: "Only the Project owner can switch hooks on or off.",
/** The agents page's hook-count stat (hover title / accessible name). */
hookCount: (n: number): string => (n === 1 ? "1 hook package" : `${n} hook packages`),
+ exportHook: "Export",
+ importHook: "Import hook",
+ importChatTitle: "Recommended: import it by chatting with the agent",
+ importChatWhy:
+ "The agent reads the source in full, reviews every script and installs the package on this agent — more reliable than a bare upload.",
+ importSourceLabel: "Hook source",
+ importSourceHint:
+ "A URL, a GitHub repository, a local path, a description, or another tool's hook config (such as the hooks block of a Claude Code settings.json)",
+ importSourcePlaceholder:
+ 'https://…, /path/to/hooks, or "write a stop hook that runs after every task…"',
+ /** Preview placeholder shown in the generated prompt before a source is entered. */
+ importSourceToken: "<source>",
+ importPromptLabel: "Prompt to send to the agent (preview)",
+ /** Lead sentence for a URL / repo / path source; free text (a description, a pasted hooks config) is used verbatim as the lead instead. Composed with importPromptTail by buildHookImportPrompt (features/agents/hook-import.ts). */
+ importPromptLead: (s: string): string => `Import ${s} as a hook package.`,
+ importCopyPrompt: "Copy prompt",
+ importOpenChat: "Open a new chat",
+ importUploadTitle: "Upload a hook package zip",
+ importUploadDesc:
+ "hooks.json and the scripts at the zip root, or exactly one top-level directory containing them. An import takes effect at once: while this agent has hooks on, its scripts run on this machine at every hook point, so import only what you trust.",
+ importUploadAction: "Choose zip file",
+ importUploading: "Uploading…",
+ importDoneToast: "Hook package installed",
+ importOverwriteTitle: "Overwrite installed hook package",
+ importOverwriteBody: (name: string): string =>
+ `The hook package "${name}" is already installed. Overwriting replaces all of its files (local edits included) and cannot be undone. Continue?`,
+ importOverwriteAction: "Overwrite",
+ /** The fixed tail joined after the lead (features/agents/hook-import.ts): the review step, the package format, the script contract and the install target, named by Project and Agent id. */
+ importPromptTail: (projectId: string, agentId: string): string =>
+ [
+ "Read the source in full first and review every script for malicious behavior (exfiltrating data, touching files outside its source, running unknown commands); continue only once it is safe.",
+ 'Then produce a PenguinHarness hook package: a hooks.json (name, description, description_zh, version in the YYYY-MM-DD.N format, and one command list per hook point — stop / pre_tool_use / user_prompt — each entry { "command": "<script path relative to the package>", "timeout": <seconds> }) plus plain Node .mjs scripts using builtin modules only.',
+ 'Script contract: stdin carries one JSON object — at the stop point { "hook": "stop", "session_id", "trace_path" } (trace_path is the Trace file the Session is writing, absent without a Trace); the pre_tool_use point adds tool_name, tool_call_id and arguments (the raw argument JSON string); the user_prompt point carries scratchpad_dir and prompt instead. Empty stdout means no opinion; otherwise stdout is one JSON answer — stop: { "decision": "continue" | "stop", "input", "reason", "output", "subagent"? }, pre_tool_use: { "decision": "allow" | "deny", "reason", "output" }, user_prompt: { "context" }. A non-zero exit, non-JSON stdout or a timeout is recorded as a failure and ignored.',
+ `Install it into agent_state/hooks/<name>/ of agent "${agentId}" in Project "${projectId}" (the directory name is the package name and must match ^[A-Za-z0-9_-]+$), then tell me what it does and at which hook point it fires.`,
+ ].join("\n"),
uninstallConfirmTitle: (name: string): string => `Uninstall ${name}`,
uninstallConfirmBody: (name: string, agent: string): string =>
`Uninstall the ${name} hook package from ${agent}? All of its scripts (local edits included) will be deleted.`,
uninstalledToast: (name: string, agent: string): string =>
`Uninstalled the ${name} hook package from ${agent}`,
+ /** The Agent-level switch card at the top of the tab (usePromptInjection); hooks have no prompt half. */
+ injection: {
+ enable: "Enable hooks",
+ enableHint:
+ "With it on, every Session this agent starts runs all installed hook packages at the loop's hook points. With it off, a new Session runs no hooks at all and the installed packages stay on disk. A Task already running keeps the setting it started with.",
+ savedToast: "Saved — takes effect from the next turn",
+ },
},
skills: {
@@ -2638,8 +2680,9 @@ Scenarios:
unknown_skill: "This skill is not in the selected directory.",
unknown_plugin: "This plugin is not in the plugin library.",
goal_plugin_not_installed:
- "Goal mode needs the goal plugin — install it on this agent from the plugin library.",
+ "Goal mode needs the goal plugin — install it on this agent from the plugin library, and switch its hook package on.",
skill_too_large: "This skill directory exceeds the import limits.",
+ hook_too_large: "This hook package exceeds the import limits.",
file_not_found: "This file no longer exists.",
not_pending: "This steering message already reached the model and can no longer be recalled.",
follow_up_started: "This follow-up already started and can no longer be recalled.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 402ed20b..9c469778 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1264,8 +1264,6 @@ export const zh = {
pageDesc: "内置插件库:每个插件带有技能和/或钩子包,可浏览、快捷调用,或安装到 Agent。",
/** Plugin count in the group header (small text to the right of the category name). */
pluginCount: (n: number): string => `${n} 个插件`,
- /** Content badge for each hook point a plugin's hook package answers at (e.g. "stop 钩子"); also the chips on the settings Hooks tab. */
- hookBadge: (event: string): string => `${event} 钩子`,
/** Search box of the create dialog's plugin picker. */
searchPlaceholder: "搜索插件",
/** Usage count in the card metadata (shows "unused" instead of a bare 0). */
@@ -1290,17 +1288,60 @@ export const zh = {
`确定从 ${agent} 卸载 ${plugin} 吗?其已安装的技能与钩子文件(含本地改动)将被删除。`,
},
- /** Agent settings "Hooks" tab (features/agents/hooks-tab.tsx): the hook packages installed on one Agent. */
+ /** Agent settings "Hooks" tab (features/agents/hooks-tab.tsx): the hook packages installed on one Agent — the list with its enable switch, the import modal (chat import / zip upload) and the export. The hook-point chips carry the bare point name (`stop`, `user_prompt`) and need no string. */
hooks: {
agentTabDesc:
- "该 Agent 已安装的钩子包(agent_state/hooks/):harness 在循环的钩子点运行的脚本,例如每个 Task 结束后;卸载会删除整个钩子包目录。",
+ "该 Agent 已安装的钩子包(agent_state/hooks/):harness 在循环的钩子点运行的脚本,例如每个 Task 结束后。卸载会删除整个钩子包目录。",
agentTabEmpty: "尚未安装任何钩子包",
+ /** Members see the switch state but cannot flip it (appended to the tab description). */
+ readOnlyHint: "启用钩子的开关仅 Project owner 可用。",
/** The agents page's hook-count stat (hover title / accessible name). */
hookCount: (n: number): string => `${n} 个钩子包`,
+ exportHook: "打包导出",
+ importHook: "导入钩子",
+ importChatTitle: "推荐:让 Agent 在对话中导入",
+ importChatWhy:
+ "Agent 会通读来源、逐个审查脚本,再把钩子包安装到该 Agent 上,比直接上传更可靠。",
+ importSourceLabel: "钩子来源",
+ importSourceHint:
+ "支持 URL / GitHub 仓库 / 本地路径 / 一段描述,或其他工具的钩子配置(如 Claude Code settings.json 的 hooks 块)",
+ importSourcePlaceholder: "https://…、/path/to/hooks,或「写一个 stop 钩子:每次任务结束后…」",
+ /** Preview placeholder shown in the generated prompt before a source is entered. */
+ importSourceToken: "<来源>",
+ importPromptLabel: "发送给 Agent 的 Prompt(预览)",
+ /** Lead sentence for a URL / repo / path source; free text (a description, a pasted hooks config) is used verbatim as the lead instead. Composed with importPromptTail by buildHookImportPrompt (features/agents/hook-import.ts). */
+ importPromptLead: (s: string): string => `把 ${s} 导入为钩子包。`,
+ importCopyPrompt: "复制 Prompt",
+ importOpenChat: "打开新对话",
+ importUploadTitle: "上传钩子包 zip",
+ importUploadDesc:
+ "zip 根目录为 hooks.json 与脚本,或仅含一个内含它们的顶层目录。导入即生效:只要该 Agent 启用了钩子,其脚本就会在本机的钩子点运行,请只导入可信的包。",
+ importUploadAction: "选择 zip 文件",
+ importUploading: "上传中…",
+ importDoneToast: "钩子包已安装",
+ importOverwriteTitle: "覆盖已安装钩子包",
+ importOverwriteBody: (name: string): string =>
+ `钩子包「${name}」已存在,覆盖安装将替换其全部文件(含本地改动),不可恢复。确认继续?`,
+ importOverwriteAction: "覆盖安装",
+ /** The fixed tail joined after the lead (features/agents/hook-import.ts): the review step, the package format, the script contract and the install target, named by Project and Agent id. */
+ importPromptTail: (projectId: string, agentId: string): string =>
+ [
+ "先完整阅读来源,逐个审查脚本有没有恶意行为(外传数据、改动来源之外的文件、执行来路不明的命令等),确认安全后再继续。",
+ '然后产出一个 PenguinHarness 钩子包:一份 hooks.json(name、description、description_zh、version(格式 YYYY-MM-DD.N),以及各钩子点的命令列表 stop / pre_tool_use / user_prompt,每项为 { "command": "<脚本相对路径>", "timeout": <秒> })加上纯 Node 的 .mjs 脚本(只用内置模块)。',
+ '脚本契约:stdin 收到一份 JSON——stop 点为 { "hook": "stop", "session_id", "trace_path" }(trace_path 是 Session 正在写入的 Trace 文件,无 Trace 时缺省),pre_tool_use 点另有 tool_name、tool_call_id、arguments(原始参数 JSON 串),user_prompt 点则是 scratchpad_dir 与 prompt;stdout 为空即无意见,否则一份 JSON 回答——stop 点 { "decision": "continue" | "stop", "input", "reason", "output", "subagent"? },pre_tool_use 点 { "decision": "allow" | "deny", "reason", "output" },user_prompt 点 { "context" };退出码非零、stdout 不是 JSON 或超时都按失败记录、不采纳。',
+ `把它安装到 Project「${projectId}」中 Agent「${agentId}」的 agent_state/hooks/<name>/ 目录(目录名即包名,须匹配 ^[A-Za-z0-9_-]+$),最后向我说明它做什么、在哪个钩子点触发。`,
+ ].join("\n"),
uninstallConfirmTitle: (name: string): string => `卸载 ${name}`,
uninstallConfirmBody: (name: string, agent: string): string =>
`确定从 ${agent} 卸载钩子包 ${name} 吗?其全部脚本(含本地改动)将被删除。`,
uninstalledToast: (name: string, agent: string): string => `已从 ${agent} 卸载钩子包 ${name}`,
+ /** The Agent-level switch card at the top of the tab (usePromptInjection); hooks have no prompt half. */
+ injection: {
+ enable: "启用钩子",
+ enableHint:
+ "开启后,该 Agent 新建的 Session 会在钩子点运行全部已安装的钩子包;关闭后新建的 Session 不运行任何钩子,已安装的包仍保留在磁盘上。进行中的 Task 保持开始时的设置。",
+ savedToast: "已保存,自下一轮对话起生效",
+ },
},
skills: {
@@ -2598,8 +2639,10 @@ Benchmark:
schedule_not_found: "该定时任务已不存在。",
unknown_skill: "所选目录下没有这个技能。",
unknown_plugin: "该插件不在插件库中。",
- goal_plugin_not_installed: "目标模式需要 goal 插件——请先在插件库中为该 Agent 安装。",
+ goal_plugin_not_installed:
+ "目标模式需要 goal 插件——请先在插件库中为该 Agent 安装,并确认其钩子包已启用。",
skill_too_large: "该技能目录过大,超出了导入限制。",
+ hook_too_large: "该钩子包过大,超出了导入限制。",
file_not_found: "该文件已不存在。",
not_pending: "该插话已随本轮送达模型,无法撤回。",
follow_up_started: "该跟进消息已开始发送,无法撤回。",
diff --git a/packages/web/test/hook-import.test.ts b/packages/web/test/hook-import.test.ts
new file mode 100644
index 00000000..28e1b126
--- /dev/null
+++ b/packages/web/test/hook-import.test.ts
@@ -0,0 +1,84 @@
+/**
+ * hook-import unit tests (src/features/agents/hook-import.ts): the lead sentence wraps a
+ * fetchable source (URL / repo / local path) in an import instruction and passes free text
+ * through verbatim; the tail names the install target by Project and Agent id and states the
+ * script contract the agent writes against, identically in both dictionaries, so a language
+ * switch never changes what the agent is told.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ buildHookImportPrompt,
+ hookImportLead,
+ hookImportTail,
+} from "../src/features/agents/hook-import";
+import { setActiveStrings, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+/** What the agent has to get right, whichever language the tail is in. */
+const CONTRACT = [
+ "hooks.json",
+ "agent_state/hooks/<name>/",
+ "YYYY-MM-DD.N",
+ "stop",
+ "pre_tool_use",
+ "user_prompt",
+ "session_id",
+ "trace_path",
+ "tool_name",
+ "tool_call_id",
+ "arguments",
+ "scratchpad_dir",
+ '"continue" | "stop"',
+ '"allow" | "deny"',
+ '"context"',
+ "^[A-Za-z0-9_-]+$",
+];
+
+describe("hookImportTail", () => {
+ it("names the install target and states the script contract", () => {
+ const tail = hookImportTail("proj_1", "writer");
+ expect(tail).toContain("proj_1");
+ expect(tail).toContain("writer");
+ for (const token of CONTRACT) expect(tail, token).toContain(token);
+ });
+
+ it("carries the same contract in both dictionaries", () => {
+ for (const dict of [zh, en]) {
+ const tail = dict.hooks.importPromptTail("p", "a");
+ for (const token of CONTRACT) expect(tail, token).toContain(token);
+ }
+ });
+});
+
+describe("hookImportLead", () => {
+ afterEach(() => setActiveStrings(zh));
+
+ it("wraps a fetchable source in the import sentence, in either language", () => {
+ for (const dict of [zh, en]) {
+ setActiveStrings(dict);
+ for (const source of [
+ "https://example.com/hooks",
+ "https://github.com/org/my-hooks",
+ "/path/to/hooks",
+ ]) {
+ expect(hookImportLead(source), source).toBe(dict.hooks.importPromptLead(source));
+ }
+ }
+ });
+
+ it("uses free text as the lead verbatim", () => {
+ const description = "write a stop hook that appends changed files to CHANGELOG-agent.md";
+ expect(hookImportLead(` ${description} `)).toBe(description);
+ // A pasted config block is free text too, and must not be rewritten.
+ const config = '{ "hooks": { "Stop": [] } }';
+ expect(hookImportLead(config)).toBe(config);
+ });
+});
+
+describe("buildHookImportPrompt", () => {
+ it("joins the trimmed lead and the tail with one blank line", () => {
+ const prompt = buildHookImportPrompt(" Import my hooks \n", "p", "a");
+ expect(prompt.startsWith("Import my hooks\n\n")).toBe(true);
+ expect(prompt.endsWith(hookImportTail("p", "a"))).toBe(true);
+ });
+});