Skip to content

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

feat(hooks): hook packages follow the model context, and user_prompt runs on every prompt (#891)

Yaowei Zheng12aeb69dd0d9
diff --git a/changelog/unreleased/2026-09-29-backward-compatibility.md b/changelog/unreleased/2026-09-29-backward-compatibility.md
new file mode 100644
index 00000000..6127eeed
--- /dev/null
+++ b/changelog/unreleased/2026-09-29-backward-compatibility.md
@@ -0,0 +1,31 @@
+# Backward compatibility: `user_prompt` commands of hook packages from before 2026.09.29.1
+
+- **Date:** 2026-09-29
+- **Type:** process
+- **Scope:** `core`, `plugins`
+- **PR:** [#891](https://github.com/Prism-Shadow/penguin-harness/pull/891)
+
+[中文版](2026-09-29-backward-compatibility.zh.md)
+
+[Hook packages follow the model context, and `user_prompt` hooks run on every prompt](2026-09-29-hooks-per-context-and-every-prompt.md) changed what a `user_prompt` command that names no `trigger` means: it had run only when a host started it by name, and it runs on every prompt the user submits after the change. The `goal` package already installed on agents names no trigger on its `start.mjs`, and that script starts a goal with no budget whenever it runs without one, so read the new way it would have turned every ordinary message into an unbudgeted goal.
+
+## What is tolerated
+
+`userPromptTrigger(manifestVersion, command)` in `packages/core/src/plugins/index.ts` reads a manifest whose `version` is a plugin version older than `USER_PROMPT_EVERY_PROMPT_SINCE` (`2026.09.29.1`), in either spelling (`YYYY.MM.DD.N` or the older `YYYY-MM-DD.N`), the old way: its `user_prompt` commands that name no `trigger` are read as `trigger: "host"`. Those commands stay out of the every-prompt consult, and the goal start still finds its command through `Session.runUserPromptHook`. A `trigger` that a command names always wins, and a manifest with no version, or with one that is not a plugin version, is read the new way. Core writes one stderr line per process per package directory when it reads a package this way (`remindToUpdate` in `packages/core/src/agent.ts`).
+
+## Scope
+
+Every installed hook package whose manifest carries such a version and has a `user_prompt` command without a `trigger`. In practice that is the `goal` package installed from the plugin library at `2026.09.01.1` or earlier, which `default_agent` gets preinstalled. `continual-learning` has no `user_prompt` command and is unaffected. A package written by hand is affected only when it copied a version number from before `2026.09.29.1`.
+
+## What users need to do
+
+Update the `goal` plugin from the plugin library; the library's update notice offers it, because the plugin moved to `2026.09.29.1`. Nothing breaks until then: the old package keeps starting goals as before and never runs on an ordinary prompt. Whoever edits an older package by hand, a person or an agent, gives each `user_prompt` command an explicit `trigger`, or raises the `version` when the commands should run on every prompt.
+
+## When it can be removed
+
+At the 0.3.0 release preparation, by whoever prepares that release. Precondition: the 0.3.0 release notes require updating the `goal` plugin, so an install still on the old package is told to update before the reading goes away. The removal takes out:
+
+- `predatesEveryPromptHooks`, `USER_PROMPT_EVERY_PROMPT_SINCE` and the version fallback in `userPromptTrigger` (`packages/core/src/plugins/index.ts`), leaving an absent `trigger` to mean `"prompt"`;
+- `remindToUpdate` in `packages/core/src/agent.ts`;
+- the legacy case in `packages/core/test/hook-packages.test.ts`;
+- the note on the legacy reading in the Skills & Plugins docs page (`skills.en.md` and `skills.zh.md`), the matching sentence in the agent-initialization skill's `reference/hooks.md`, and the compatibility paragraph in the design spec's Hook section.
diff --git a/changelog/unreleased/2026-09-29-backward-compatibility.zh.md b/changelog/unreleased/2026-09-29-backward-compatibility.zh.md
new file mode 100644
index 00000000..b8f4c6ec
--- /dev/null
+++ b/changelog/unreleased/2026-09-29-backward-compatibility.zh.md
@@ -0,0 +1,31 @@
+# 向后兼容:2026.09.29.1 之前的钩子包中的 `user_prompt` 命令
+
+- **Date:** 2026-09-29
+- **Type:** process
+- **Scope:** `core`, `plugins`
+- **PR:** [#891](https://github.com/Prism-Shadow/penguin-harness/pull/891)
+
+[English](2026-09-29-backward-compatibility.md)
+
+[钩子包随模型上下文读取,`user_prompt` 钩子在每条 Prompt 上运行](2026-09-29-hooks-per-context-and-every-prompt.zh.md)改变了未写 `trigger` 的 `user_prompt` 命令的含义:此前它只在宿主按名启动时运行,改动之后则在用户每次提交 Prompt 时运行。各 Agent 上已安装的 `goal` 包,其 `start.mjs` 没有写 trigger,而这个脚本在缺少预算时会启动一个不设预算的目标;若按新的读法,每条普通消息都会变成一次不设预算的目标。
+
+## 兼容的旧形态
+
+`packages/core/src/plugins/index.ts` 中的 `userPromptTrigger(manifestVersion, command)` 对 `version` 为早于 `USER_PROMPT_EVERY_PROMPT_SINCE`(`2026.09.29.1`)的插件版本(`YYYY.MM.DD.N` 或旧写法 `YYYY-MM-DD.N` 均可)的清单沿用旧读法:其中没有写 `trigger` 的 `user_prompt` 命令一律按 `trigger: "host"` 读取。这些命令不参与每条 Prompt 的咨询,goal 的启动仍能经 `Session.runUserPromptHook` 找到它的命令。命令显式写出的 `trigger` 始终优先;没有版本、或版本不是插件版本格式的清单按新读法读取。core 以这种方式读取某个包时,每个进程对每个包目录向 stderr 写一行提示(`packages/core/src/agent.ts` 中的 `remindToUpdate`)。
+
+## 生效范围
+
+清单带有这类版本、且含未写 `trigger` 的 `user_prompt` 命令的每个已安装钩子包。实际上就是从插件库安装的 `2026.09.01.1` 及更早版本的 `goal` 包,`default_agent` 预装的正是它。`continual-learning` 没有 `user_prompt` 命令,不受影响。手写的钩子包只有照抄了 `2026.09.29.1` 之前的版本号时才受影响。
+
+## 用户需要做什么
+
+从插件库更新 `goal` 插件;插件已升至 `2026.09.29.1`,插件库的更新提示会给出这项更新。在此之前不会出现任何问题:旧包照常启动目标,也不会在普通 Prompt 上运行。无论是人还是 Agent,手工修改旧包时,给每条 `user_prompt` 命令写上明确的 `trigger`;要让这些命令在每条 Prompt 上运行,则提高 `version`。
+
+## 何时可以移除
+
+在 0.3.0 发布准备时,由负责该次发布的人移除。前提:0.3.0 的发布说明要求更新 `goal` 插件,让仍在使用旧包的安装在这一读法移除之前得到更新提示。移除的内容:
+
+- `packages/core/src/plugins/index.ts` 中的 `predatesEveryPromptHooks`、`USER_PROMPT_EVERY_PROMPT_SINCE` 与 `userPromptTrigger` 里按版本回退的分支,此后缺省的 `trigger` 即表示 `"prompt"`;
+- `packages/core/src/agent.ts` 中的 `remindToUpdate`;
+- `packages/core/test/hook-packages.test.ts` 中针对旧清单的用例;
+- 技能与插件文档页(`skills.en.md` 与 `skills.zh.md`)中关于旧读法的提示、agent-initialization Skill 的 `reference/hooks.md` 中对应的一句,以及设计文档 Hook 一节中的兼容段落。
diff --git a/changelog/unreleased/2026-09-29-hooks-per-context-and-every-prompt.md b/changelog/unreleased/2026-09-29-hooks-per-context-and-every-prompt.md
new file mode 100644
index 00000000..f74300ac
--- /dev/null
+++ b/changelog/unreleased/2026-09-29-hooks-per-context-and-every-prompt.md
@@ -0,0 +1,28 @@
+# Hook packages follow the model context, and `user_prompt` hooks run on every prompt
+
+- **Date:** 2026-09-29
+- **Type:** feature
+- **Scope:** `core`, `server`, `cli`, `plugins`, `docs`
+- **PR:** [#891](https://github.com/Prism-Shadow/penguin-harness/pull/891)
+- **Breaking:** yes — an in-process `user_prompt` hook (`SessionConfig.hooks.userPrompt`) runs on every prompt unless it is marked `trigger: "host"`, and `Session.runUserPromptHook` finds only hooks so marked
+
+[中文版](2026-09-29-hooks-per-context-and-every-prompt.zh.md)
+
+Hook packages became part of what a model context is assembled from, read again each time a context opens, and the `user_prompt` hook point started running on every prompt the user submits. The change let a package that an agent writes into its own `agent_state/hooks/` during a conversation take effect at that conversation's next compaction instead of in the next conversation, and the agent-initialization skill was rewritten to teach an agent how to create, install and import Skills and hook packages.
+
+## Details
+
+- **Hooks follow the model context.** `Agent.assembleContext` read `agent_state/hooks/` and `hooks.enabled` whenever a context opened: at Session creation, in the context a compaction opens, and on resume. `openNextContext` returned the new context's hooks as `SessionOpenedContext.hooks`, and the Session replaced its whole set with them (`adoptHooks`), empty lists included, so uninstalling the last package reached a running conversation too. Every consult read the Session's hooks when it happened, so a compaction inside one `run` call handed the rest of the call to the new context's hooks. The server kept invalidating an agent's cached runtimes when a hook package was installed, imported or uninstalled through the API or `hooks.enabled` was written, which is what brought a library install into an open conversation on its next Task.
+- **`user_prompt` on every prompt.** The engine gained a consult seam, `RunOptions.userPrompt` (`UserPromptFn`), which `Session.run` wired for the call's first Task. It fired when the run's input carried a user text whose `sender` was absent or `user`; `server`, `harness` and `parent_agent` inputs, stop-hook continuations and steering did not fire it. Hooks ran in package-name order, then manifest order, with `{ hook: "user_prompt", session_id, trace_path, scratchpad_dir, prompt }` on stdin (`trace_path` was new to this hook point; `prompt` is the user's texts joined by newlines, leading marker blocks stripped) and `{ "context": "…" }` on stdout.
+- **Where a context goes.** Each non-empty context became a user text stamped `sender: "harness"`: yielded on the stream, written to the Trace right behind the Prompt and ahead of the first run's bootstrap records, and appended to the first request's input. A success left no `hook` event. A failure — a non-zero exit, stdout that is not JSON, a timeout or a throw — was recorded at the same position as a `hook` event with `hook: "user_prompt"` and the error as its `reason`, and otherwise ignored; `HookPayload.hook` gained `"user_prompt"`.
+- **Host-triggered commands.** A `user_prompt` command took an optional `trigger`: `"prompt"` (the default) or `"host"`. A host command stayed out of the every-prompt consult and ran only through `Session.runUserPromptHook(name, prompt, extras)`, which found a package's `trigger: "host"` hook only, returned null otherwise, and passed the Session's Trace path as well. The zip import route (`POST …/hooks/archive`) rejected any other `trigger` value. A manifest written before this change is read under a compatibility rule; see [backward compatibility](2026-09-29-backward-compatibility.md).
+- **Hand-written manifests.** `hooks.json` was read tolerantly (`readHookManifest` / `readHookCommands` in core's `state/agent-state.ts`), because a package is any directory under `agent_state/hooks/` that carries one: a hook point the manifest leaves out reads as `[]`; an entry without a string `command`, or whose command resolves outside the package directory, is dropped, and so are a `timeout` that is not a positive number and an unknown `trigger`; a manifest that is not a JSON object makes the directory no hook package; and display fields that are not strings read as absent. `GET …/hooks` stopped answering 500 for a manifest that lists only `user_prompt`.
+- **Goal rounds.** Core exported `isHookContinue(msg)`, which recognizes a stop hook's `continue` event. The server's goal tap (`goal_round` events) and the CLI's goal rendering counted a harness-stamped input as a round only when a `continue` event announced it; round 1 stayed the seeded input on the server and the first hook input in the CLI. Another package's context riding a goal start therefore opened no round.
+- **Plugins.** `goal` moved to `2026.09.29.1` with its `start.mjs` marked `trigger: "host"`. `continual-learning` moved to `2026.09.29.1`: its task window opened at the first record of the input batch — the user's message, its images, and the harness texts right behind it — so the excerpt kept what the user asked. `agent-tuning` shipped a rewritten `agent-initialization` skill that teaches an agent how to create, install and import Skills and hook packages.
+- **Web App and docs.** The Hooks tab's chat-import prompt named the optional `trigger`, let an unused hook point be left out, and gave the `user_prompt` stdin with `trace_path`. The Agent Loop, Skills & Plugins, Goal Mode, The OmniMessage Protocol, Core Interfaces, Sessions & Traces and Configuration Reference pages described the new contract.
+
+## Compatibility
+
+- An in-process `UserPromptHook` registered through `SessionConfig.hooks.userPrompt` runs on every prompt the user submits, and `Session.runUserPromptHook` returns null for a hook that is not marked `trigger: "host"`. An embedder whose hook belongs to a flow it starts itself adds `trigger: "host"` to that hook.
+- A hand-written `hooks.json` whose `user_prompt` command must run only when a host starts it adds `"trigger": "host"` to the command.
+- Hook packages installed before this change keep their old reading until they are updated; see [backward compatibility](2026-09-29-backward-compatibility.md). Update the `goal` plugin from the plugin library.
diff --git a/changelog/unreleased/2026-09-29-hooks-per-context-and-every-prompt.zh.md b/changelog/unreleased/2026-09-29-hooks-per-context-and-every-prompt.zh.md
new file mode 100644
index 00000000..7bbdc1bf
--- /dev/null
+++ b/changelog/unreleased/2026-09-29-hooks-per-context-and-every-prompt.zh.md
@@ -0,0 +1,28 @@
+# 钩子包随模型上下文读取,`user_prompt` 钩子在每条 Prompt 上运行
+
+- **Date:** 2026-09-29
+- **Type:** feature
+- **Scope:** `core`, `server`, `cli`, `plugins`, `docs`
+- **PR:** [#891](https://github.com/Prism-Shadow/penguin-harness/pull/891)
+- **Breaking:** yes — 进程内的 `user_prompt` 钩子(`SessionConfig.hooks.userPrompt`)除非标记 `trigger: "host"`,否则在每条 Prompt 上运行;`Session.runUserPromptHook` 只找得到这样标记的钩子
+
+[English](2026-09-29-hooks-per-context-and-every-prompt.md)
+
+钩子包成为模型上下文装配内容的一部分,每次开启上下文都重新读取;`user_prompt` 钩子点改为在用户每次提交 Prompt 时运行。这一改动让 Agent 在对话中写进自己 `agent_state/hooks/` 的钩子包在该对话的下一次压缩时生效,而不必等到下一个对话;agent-initialization Skill 也经过重写,教 Agent 如何创建、安装和导入 Skill 与钩子包。
+
+## 细节
+
+- **钩子随模型上下文读取。** `Agent.assembleContext` 在每次开启上下文时读取 `agent_state/hooks/` 与 `hooks.enabled`:创建 Session 时、压缩开启的上下文中,以及恢复时。`openNextContext` 以 `SessionOpenedContext.hooks` 交回新上下文的钩子,Session 用它整体替换自己的钩子(`adoptHooks`),空列表也不例外,因此卸载最后一个包同样能作用到运行中的对话。每次咨询都在发生时读取 Session 当时的钩子,所以一次 `run` 调用中途的压缩会把这次调用的剩余部分交给新上下文的钩子。经 API 安装、导入或卸载钩子包,或写入 `hooks.enabled` 时,服务端仍使该 Agent 缓存的运行时失效,插件库的安装正是靠这一点在已打开对话的下一个 Task 生效。
+- **每条 Prompt 都运行 `user_prompt`。** 引擎新增咨询缝 `RunOptions.userPrompt`(`UserPromptFn`),由 `Session.run` 为本次调用的第一个 Task 接上。`run` 的输入含 `sender` 缺省或为 `user` 的 user 文本时触发;`server`、`harness` 与 `parent_agent` 输入、stop hook 的续跑输入以及插话都不触发。钩子按包名顺序、再按清单顺序运行,stdin 为 `{ hook: "user_prompt", session_id, trace_path, scratchpad_dir, prompt }`(`trace_path` 是这个钩子点新增的字段;`prompt` 是用户的各条文本以换行相连、剥离开头标记块后的结果),stdout 为 `{ "context": "…" }`。
+- **context 的去处。** 每个非空 context 成为一条带 `sender: "harness"` 标记的 user 文本:推到流上,紧随 Prompt 写入 Trace(排在首次运行的 bootstrap 记录之前),并追加到首个请求的输入中。成功不留 `hook` 事件。失败(退出码非零、stdout 不是 JSON、超时或抛错)在同一位置记为一条 `hook: "user_prompt"` 的 `hook` 事件,以错误信息为 `reason`,除此之外按无意见处理;`HookPayload.hook` 因此新增 `"user_prompt"`。
+- **宿主触发的命令。** `user_prompt` 命令新增可选字段 `trigger`:`"prompt"`(缺省)或 `"host"`。`host` 命令不参与每条 Prompt 的咨询,只经 `Session.runUserPromptHook(name, prompt, extras)` 运行;该方法只找包里 `trigger: "host"` 的钩子,找不到时返回 null,并且同样传入 Session 的 Trace 路径。zip 导入路由(`POST …/hooks/archive`)拒绝这两个取值之外的 `trigger`。此次改动之前写下的清单按一条兼容规则读取,见[向后兼容](2026-09-29-backward-compatibility.zh.md)。
+- **手写清单。** `hooks.json` 改为宽容读取(core 的 `state/agent-state.ts` 中的 `readHookManifest` / `readHookCommands`),因为 `agent_state/hooks/` 下任何带清单的目录都是钩子包:清单没有列出的钩子点读作 `[]`;没有字符串 `command` 的条目、或命令解析到包目录之外的条目被丢弃,不是正数的 `timeout` 与未知的 `trigger` 同样丢弃;清单不是 JSON 对象的目录不算钩子包;不是字符串的展示字段读作缺省。对只列出 `user_prompt` 的清单,`GET …/hooks` 不再返回 500。
+- **goal 的轮次。** core 导出 `isHookContinue(msg)`,用于识别 stop 钩子的 `continue` 事件。服务端的 goal 旁听(`goal_round` 事件)与 CLI 的 goal 渲染,只在 `continue` 事件预告之后才把带 harness 标记的输入计为一轮;第 1 轮在服务端仍是种入的输入,在 CLI 仍是第一条钩子输入。因此,随 goal 启动而来的其他钩子包的 context 不会开启新的一轮。
+- **插件。** `goal` 升至 `2026.09.29.1`,其 `start.mjs` 标记为 `trigger: "host"`。`continual-learning` 升至 `2026.09.29.1`:它的任务窗口从这批输入的第一条记录开始——用户消息、随附的图片,以及紧随其后的 harness 文本——因此摘录保留了用户的原始请求。`agent-tuning` 附带重写后的 `agent-initialization` Skill,教 Agent 如何创建、安装和导入 Skill 与钩子包。
+- **Web App 与文档。** 钩子标签页的对话导入 Prompt 写明了可选的 `trigger`,允许省略用不到的钩子点,并给出带 `trace_path` 的 `user_prompt` stdin。Agent 运行循环、技能与插件、目标模式、OmniMessage 协议、核心接口、Session 与 Trace 以及配置参考各页描述了新的约定。
+
+## 兼容性
+
+- 经 `SessionConfig.hooks.userPrompt` 注册的进程内 `UserPromptHook` 会在用户每次提交 Prompt 时运行;对没有标记 `trigger: "host"` 的钩子,`Session.runUserPromptHook` 返回 null。钩子属于嵌入方自己发起的流程时,给它加上 `trigger: "host"`。
+- 手写的 `hooks.json` 中,只应在宿主启动时运行的 `user_prompt` 命令,给该命令加上 `"trigger": "host"`。
+- 此次改动之前安装的钩子包在更新之前沿用旧的读法,见[向后兼容](2026-09-29-backward-compatibility.zh.md)。请从插件库更新 `goal` 插件。
diff --git a/packages/cli/src/server-task.ts b/packages/cli/src/server-task.ts
index 395fdbdd..a2039679 100644
--- a/packages/cli/src/server-task.ts
+++ b/packages/cli/src/server-task.ts
@@ -14,7 +14,12 @@
* with it on a dropped connection; `resync_required` (buffer evicted) prints a dim
* notice — the messages endpoint still holds the full history for `penguin logs`.
*/
-import { isEventMessage, isHookInput, isModelMessage } from "@prismshadow/penguin-core";
+import {
+ isEventMessage,
+ isHookContinue,
+ isHookInput,
+ isModelMessage,
+} from "@prismshadow/penguin-core";
import type { ApprovalDecision, OmniMessage, ToolCallPayload } from "@prismshadow/penguin-core";
import type { GoalServerEvent } from "@prismshadow/penguin-server/api";
import { ServerClient } from "./client.js";
@@ -195,6 +200,8 @@ export async function watchTask(
let timedOut = false;
let outcome: GoalOutcome | undefined;
let round = 0;
+ // Set by a stop hook's `continue` event, spent by the input that follows it.
+ let continued = false;
let segmentStartedAt = Date.now();
// Approval prompts serialize on a promise chain: concurrent requests (parent +
// subagent) must not interleave their Q&A on one stdin.
@@ -255,9 +262,12 @@ export async function watchTask(
}
if (opts.goal) {
// A hook's input is a round boundary: round 1's protocol message (sent right behind
- // the objective), then every stop-hook continue — the same predicate as the server's
- // goal_round events.
- if (isHookInput(msg)) {
+ // the objective), then every stop-hook continue, each announced by the hook's
+ // `continue` event — the same rule as the server's goal_round events. Any other
+ // harness-stamped input is another package's user_prompt context, not a round.
+ if (isHookContinue(msg)) continued = true;
+ if (isHookInput(msg) && (round === 0 || continued)) {
+ continued = false;
if (round > 0) renderer?.endTask(Date.now() - segmentStartedAt);
round++;
segmentStartedAt = Date.now();
diff --git a/packages/cli/test/server-commands.test.ts b/packages/cli/test/server-commands.test.ts
index 36a9a0b8..ddfb6254 100644
--- a/packages/cli/test/server-commands.test.ts
+++ b/packages/cli/test/server-commands.test.ts
@@ -1,11 +1,17 @@
/**
* Server-backed command wiring, driven through `cli()` in-process against the fake
- * server: run (foreground/background/json/goal exit codes), ls, input (steer vs task),
- * logs, agent ls/create, project ls, cost, schedule ls.
+ * server: run (foreground/background/json, goal exit codes and round lines), ls, input
+ * (steer vs task), logs, agent ls/create, project ls, cost, schedule ls.
*/
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { assistantText, partialText, type OmniMessage } from "@prismshadow/penguin-core";
+import {
+ assistantText,
+ hookEvent,
+ partialText,
+ userText,
+ type OmniMessage,
+} from "@prismshadow/penguin-core";
import { cli } from "../src/index.js";
import { getMessages } from "../src/i18n.js";
import { FakeServer } from "./fake-server.js";
@@ -105,6 +111,24 @@ describe("penguin run", () => {
expect(session.tasks[0]!.goal).toEqual({ budget: 500_000 });
});
+ it("a goal run prints one line per round: another package's context riding round 1 is not a round", async () => {
+ // The stream of a goal on an Agent with a second user_prompt package: the objective and
+ // the goal protocol (both published by the server), the other package's context (core
+ // sends it right behind them), round 1's work, the goal hook's `continue`, round 2.
+ server.onTask = () => [
+ userText("raise coverage"),
+ userText("goal protocol for the first pass", "harness"),
+ userText("The local time is 10:00.", "harness"),
+ ...streamedText("first pass done"),
+ hookEvent({ hook: "stop", name: "goal", decision: "continue" }),
+ userText("goal protocol for the second pass", "harness"),
+ ...streamedText("second pass done"),
+ ];
+ await cli(["run", "-m", "raise coverage", "--goal", "500k"]);
+ const printed = (round: number) => out().split(t.goalRound(round)).length - 1;
+ expect([1, 2, 3].map(printed)).toEqual([1, 1, 0]);
+ });
+
it("--thinking pins the Session before the task (a PATCH); the task body carries no level", async () => {
await cli(["run", "-m", "q", "--thinking", "high"]);
const session = [...server.sessions.values()][0]!;
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 822ca53d..162e331e 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -37,6 +37,7 @@ import {
tracesDir,
type AgentState,
type CompactionConfig,
+ type InstalledHook,
type ModelRef,
type ModelEntry,
type ProjectConfig,
@@ -59,7 +60,8 @@ import {
import { Session } from "./session.js";
import { scriptPreToolUseHook, scriptStopHook, scriptUserPromptHook } from "./hooks/script-hook.js";
import type { HookSubagentRequest, SessionHooks } from "./hooks/stop-hook.js";
-import type { SessionConfig } from "./session.js";
+import { predatesEveryPromptHooks, userPromptTrigger } from "./plugins/index.js";
+import type { SessionConfig, SessionOpenedContext } from "./session.js";
import {
createTempWorkspace,
formatSessionId,
@@ -83,11 +85,7 @@ import type {
} from "./omnimessage/index.js";
import { SUBAGENT_NAME } from "./environment/tools/run-subagent.js";
import { INPUT_SUBAGENT_NAME } from "./environment/tools/input-subagent.js";
-import type {
- CompactionSettings,
- OpenContextOptions,
- OpenedContext,
-} from "./engine/context-engine.js";
+import type { CompactionSettings, OpenContextOptions } from "./engine/context-engine.js";
import type {
ApproveFn,
CommandPolicyConfig,
@@ -289,9 +287,9 @@ interface SessionRuntime {
* Opens the context that follows a completed compaction (see ContextEngineDeps.openNextContext):
* the whole configuration assembled anew from the Agent State, the Environment re-equipped
* with it, then the same opening procedure as `bootstrap` — and the session_meta recording
- * the context alongside its engine settings.
+ * the context alongside its engine settings, with the hooks the context runs with.
*/
- openNextContext: (opts: OpenContextOptions) => Promise<OpenedContext>;
+ openNextContext: (opts: OpenContextOptions) => Promise<SessionOpenedContext>;
/** The running context's command policy — follows the rotation (see SessionConfig.commandPolicy). */
commandPolicy: () => CommandPolicyConfig | undefined;
@@ -318,6 +316,14 @@ interface AssembledContext {
/** `system_config.max_turns`; the engine treats absent as unlimited (-1). */
maxTurns: number | undefined;
compaction: CompactionSettings;
+ /**
+ * The hook packages this context consults: the ones installed in `agent_state/hooks/`
+ * when it opened. Empty with `hooks.enabled: false` — the one switch over all of them,
+ * the packages stay installed — and for a child Session, which carries no hooks: a
+ * subagent's work belongs to its parent's Trace, and a child could not spawn a subagent
+ * anyway.
+ */
+ hookPackages: InstalledHook[];
/** The session_meta describing this context: the prompt it runs with, and the Session-fixed facts. */
meta: SessionMetaPayload;
}
@@ -430,8 +436,9 @@ export class Agent {
* Assembles what a model context runs with, from the Agent State as it is on disk **now**:
* `system_config.yaml` in full — the prompt template with its section prompts and toggles,
* the builtin tool entries and MCP Servers, the compaction settings, `max_turns`, the
- * model defaults — plus `AGENTS.md`, the vault, the installed Skills' metadata, the Memory
- * indexes, the schedule roster and the Environment values (the date included). Every
+ * model defaults — plus `AGENTS.md`, the vault, the installed Skills' metadata, the
+ * installed hook packages, the Memory indexes, the schedule roster and the Environment
+ * values (the date included). Every
* context opener goes through here — createSession, the context a completed compaction
* opens (buildRuntime's openNextContext) and a resume that finds its context closed — so an
* edit made during one context, by the user or by the model working on its own
@@ -461,6 +468,13 @@ export class Agent {
// the one on disk at its open.
const projectConfig = await loadProjectConfig(root, projectId);
const commandPolicy = projectConfig.command_policy;
+ // Hook packages are not part of the request prefix, and are read on the same schedule
+ // all the same: a package the model wrote during one context is consulted from the next.
+ const child = spec.subagentDepth > 0 || spec.source === "subagent";
+ const hookPackages =
+ child || state.systemConfig.hooks?.enabled === false
+ ? []
+ : await listInstalledHooks(root, projectId, agentId);
let systemPrompt = opts.systemPrompt;
if (systemPrompt === undefined) {
const installedSkills = await listInstalledSkills(root, projectId, agentId);
@@ -566,6 +580,7 @@ export class Agent {
// Max turns is an Agent runtime parameter (system_config), not a Session option.
maxTurns: state.systemConfig.max_turns,
compaction,
+ hookPackages,
meta,
};
}
@@ -651,17 +666,12 @@ export class Agent {
const context = await this.assembleContext(spec);
const rt = this.buildRuntime(spec, context);
- const hooks = await this.sessionHooks(
- rt.subagentRunner,
- spec.subagentDepth > 0 || opts.source === "subagent",
- );
-
const trace = new Writer({
tracesDir: tracesDir(this.state.root, this.state.projectId, this.state.agentId),
sessionId,
});
- return this.newSession(spec, context, rt, trace, { ...(hooks ? { hooks } : {}) });
+ return this.newSession(spec, context, rt, trace);
}
/**
@@ -784,8 +794,6 @@ export class Agent {
return r;
};
- const hooks = await this.sessionHooks(rt.subagentRunner, meta.source === "subagent");
-
// Continue writing to the original Trace file (the Trace only records real messages; synthesized paired placeholders are re-emitted in memory alongside carry-over).
const trace = new Writer({
tracesDir: dir,
@@ -815,7 +823,6 @@ export class Agent {
return this.newSession(spec, context, rt, trace, {
bootstrap,
- ...(hooks ? { hooks } : {}),
// session_meta is already in the original Trace file, so it isn't rewritten; on the first write after a compaction-triggered rotation, the file is split first.
metaAlreadyWritten: true,
initialEngineState: {
@@ -898,6 +905,8 @@ export class Agent {
environment: rt.environment,
trace,
openNextContext: rt.openNextContext,
+ // The first context's hooks; each context `openNextContext` opens brings its own.
+ hooks: this.sessionHooks(rt.subagentRunner, context.hookPackages),
createBareLLM: rt.createBareLLM,
compaction: context.compaction,
@@ -1297,7 +1306,7 @@ export class Agent {
// records live and writes them at the head of the rotated Trace file. An Agent State
// that cannot be assembled (a config that no longer parses) throws: the run fails with
// that error and the engine keeps the old context.
- const openNextContext = async ({ emit }: OpenContextOptions): Promise<OpenedContext> => {
+ const openNextContext = async ({ emit }: OpenContextOptions): Promise<SessionOpenedContext> => {
const next = await this.assembleContext(spec);
current = next;
environment.reconfigure({ toolConfig: next.toolConfig, vault: next.vault });
@@ -1307,6 +1316,7 @@ export class Agent {
sessionMeta: sessionMeta(next.meta),
maxTurns: next.maxTurns ?? -1,
compaction: next.compaction,
+ hooks: this.sessionHooks(subagentRunner, next.hookPackages),
};
};
@@ -1364,29 +1374,17 @@ 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 —
- * 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.
+ * The hooks a model context runs with, built from the hook packages it was assembled with
+ * (see AssembledContext.hookPackages): each command run as a script (hooks/script-hook.ts),
+ * plus the spawner that honors a stop 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.
*
- * `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.
+ * Always a whole set, empty lists included: the Session replaces its hooks with it when
+ * the context opens, which is how uninstalling the last package reaches a conversation
+ * that is running. 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 { 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);
+ private sessionHooks(runner: SubagentRunner, installed: readonly InstalledHook[]): SessionHooks {
// 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
@@ -1402,16 +1400,23 @@ export class Agent {
scriptPreToolUseHook(hook.name, hook.dir, cmd.command, cmd.timeout, pathPrepend),
),
);
- const userPrompt = installed.flatMap((hook) =>
- hook.user_prompt.map((cmd) =>
- scriptUserPromptHook(hook.name, hook.dir, cmd.command, cmd.timeout, pathPrepend),
- ),
- );
- if (stop.length === 0 && preToolUse.length === 0 && userPrompt.length === 0) return undefined;
+ const userPrompt = installed.flatMap((hook) => {
+ remindToUpdate(hook);
+ return hook.user_prompt.map((cmd) =>
+ scriptUserPromptHook(
+ hook.name,
+ hook.dir,
+ cmd.command,
+ cmd.timeout,
+ pathPrepend,
+ userPromptTrigger(hook.version, cmd),
+ ),
+ );
+ });
return {
- ...(stop.length > 0 ? { stop } : {}),
- ...(preToolUse.length > 0 ? { preToolUse } : {}),
- ...(userPrompt.length > 0 ? { userPrompt } : {}),
+ stop,
+ preToolUse,
+ userPrompt,
spawnSubagent: async (request: HookSubagentRequest, approve?: ApproveFn) => {
const handle = await runner.spawn({
...(request.agentId !== undefined ? { agentId: request.agentId } : {}),
@@ -1428,6 +1433,26 @@ export class Agent {
}
}
+/** Package directories already named by {@link remindToUpdate} in this process. */
+const remindedPackages = new Set<string>();
+
+/**
+ * COMPAT (remove at 0.3.0 release preparation, together with the rule it reports — see
+ * plugins' userPromptTrigger): says once per process, per package directory, that an
+ * installed package predates `user_prompt` commands running on every Prompt and is being
+ * read the old way. The user-facing reminder is the plugin library's update notice; this
+ * line is for whoever reads the host's log.
+ */
+function remindToUpdate(hook: InstalledHook): void {
+ if (!predatesEveryPromptHooks(hook.version)) return;
+ if (!hook.user_prompt.some((cmd) => cmd.trigger === undefined)) return;
+ if (remindedPackages.has(hook.dir)) return;
+ remindedPackages.add(hook.dir);
+ process.stderr.write(
+ `[hooks] ${hook.name} ${hook.version} (${hook.dir}) predates user_prompt hooks running on every prompt: its user_prompt commands run only when the host starts them by name. Update the package from the plugin library; this compatibility reading ends with 0.3.0.\n`,
+ );
+}
+
/** Drives a hook-spawned child to completion in the background, dropping its stream (its own Trace is the record), and releases it. */
function runDetached(handle: SubagentHandle, messages: OmniMessage[], approve?: ApproveFn): void {
void (async () => {
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index bced2eab..85980636 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -38,6 +38,7 @@ import {
addTokenCounts,
emptyTokenCounts,
isCompleteModelMessage,
+ isModelMessage,
isSessionMeta,
partialText,
requestBegin,
@@ -79,6 +80,8 @@ import type {
ApproveFn,
PreToolUseFn,
PreToolUseOutcome,
+ UserPromptFn,
+ UserPromptOutcome,
EnvironmentInterface,
LLMInterface,
LLMOutcome,
@@ -172,6 +175,8 @@ export interface RunOptions {
approve?: ApproveFn;
/** Pre-tool-use hook consult, called before `approve` for each complete tool_call; its events are recorded on the stream, its decision applied (see {@link PreToolUseFn}). */
preToolUse?: PreToolUseFn;
+ /** User-prompt hook consult, called once with this call's Prompt after it is written and before the first request; its records follow the Prompt on the stream and in the Trace, and the user texts among them join the request input (see {@link UserPromptFn}). */
+ userPrompt?: UserPromptFn;
}
/**
@@ -710,7 +715,7 @@ export class ContextEngine {
const carryOver = this.pendingCarryOver;
this.pendingCarryOver = [];
const prefix = summary ? [summary, ...carryOver] : carryOver;
- const input = prefix.length ? [...prefix, ...newMessages] : newMessages;
+ let input = prefix.length ? [...prefix, ...newMessages] : newMessages;
// Input is written to Trace (Prompt record, incl. audit trail) but not replayed to
// the render layer. carry-over is not written to Trace: real messages (tool outputs etc.)
@@ -721,6 +726,27 @@ export class ContextEngine {
// context's first input record, is written as usual.
if (summary) await this.write(summary);
for (const msg of newMessages) await this.write(msg);
+ // User-prompt hooks (RunOptions.userPrompt, wired by the Session from the Agent's
+ // installed hook packages): consulted once per Prompt, here, so what they answer lands
+ // right behind the user's message — on the stream, in the Trace and in the request
+ // input alike. A throw collapses to nothing to add: a broken hook must not cost the
+ // user their Prompt.
+ if (opts?.userPrompt && !signal?.aborted) {
+ let expanded: UserPromptOutcome | null = null;
+ try {
+ expanded = await opts.userPrompt(newMessages, signal);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ process.stderr.write(`[penguin] userPrompt consult threw: ${message}; ignoring.\n`);
+ }
+ const contexts: OmniMessage[] = [];
+ for (const record of expanded?.records ?? []) {
+ yield record;
+ await this.write(record);
+ if (isModelMessage(record)) contexts.push(record);
+ }
+ if (contexts.length > 0) input = [...input, ...contexts];
+ }
if (this.pendingBootstrapRecords) {
// First run only: the connect pair, then the toolset record, follow the input into
// the Trace (see ContextEngineDeps.bootstrapRecords for the ordering rationale).
diff --git a/packages/core/src/hooks/index.ts b/packages/core/src/hooks/index.ts
index f82a8c8a..0ea6905b 100644
--- a/packages/core/src/hooks/index.ts
+++ b/packages/core/src/hooks/index.ts
@@ -1,10 +1,10 @@
/**
* Hooks — functions the Session runs at fixed points of the agent loop. Three points exist
* today: `stop` (after every Task of a `run` call; stop-hook.ts), `pre_tool_use` (before
- * each tool call's approval; tool-hook.ts) and `user_prompt` (prompt expansion, run via
- * `Session.runUserPromptHook`; prompt-hook.ts). script-hook.ts runs the hook packages
+ * each tool call's approval; tool-hook.ts) and `user_prompt` (prompt expansion, every time
+ * the user submits a Prompt; prompt-hook.ts). script-hook.ts runs the hook packages
* installed into an Agent's `agent_state/hooks/` as subprocesses — hooks run in core and
- * nowhere else; hosts trigger them through Session APIs.
+ * nowhere else; a host reaches a flow of its own through a Session API.
*/
export { runStopHooks } from "./stop-hook.js";
export type {
@@ -19,6 +19,7 @@ export type {
} from "./stop-hook.js";
export { runPreToolUseHooks } from "./tool-hook.js";
export type { PreToolUseHook, PreToolUseHookInput, PreToolUseHookResult } from "./tool-hook.js";
+export { runUserPromptHooks } from "./prompt-hook.js";
export type { UserPromptHook, UserPromptHookInput, UserPromptHookResult } from "./prompt-hook.js";
export {
DEFAULT_HOOK_TIMEOUT_S,
diff --git a/packages/core/src/hooks/prompt-hook.ts b/packages/core/src/hooks/prompt-hook.ts
index 361488d6..4804f8fe 100644
--- a/packages/core/src/hooks/prompt-hook.ts
+++ b/packages/core/src/hooks/prompt-hook.ts
@@ -1,17 +1,38 @@
/**
- * User-prompt hooks — the prompt-expansion point. Core runs them (hooks never run anywhere
- * else); the host triggers the run through `Session.runUserPromptHook` when it accepts a
- * user prompt for the flow the hook's package owns — goal mode's start is the shipped use:
+ * User-prompt hooks — the prompt-expansion point: consulted every time the user submits a
+ * Prompt. A hook is told the prompt text plus where the Session's record and scratchpad
+ * are, and answers with a `context`: text the Session sends right behind the user's own
+ * message as a user text stamped `sender: "harness"`, in hook order. That message is the
+ * record — a successful answer leaves no `hook` event; a hook that fails is recorded as one,
+ * with the error as its reason, and treated as having nothing to add, so a broken hook
+ * never takes the run down.
+ *
+ * The consult rides the engine's seam (`RunOptions.userPrompt`), which places the records
+ * right behind the Prompt on the stream and in the Trace, and runs for a `run` whose input
+ * carries text of the user's own: a harness, server or parent-agent input is not a Prompt
+ * the user submitted, and neither is a stop hook's continuation.
+ *
+ * A hook marked `trigger: "host"` stays out of that consult. It belongs to a flow the host
+ * starts by name through `Session.runUserPromptHook` — goal mode's start is the shipped use:
* the server asks the Session to run the goal package's hook with the objective and budget,
- * and sends the answered `context` right behind the user's own message, stamped
- * `sender: "harness"`. The expansion message itself is the record; no `hook` event is
- * written for this point.
+ * and sends the answered `context` itself.
+ *
+ * Hooks installed into an Agent's `agent_state/hooks/` are scripts run through
+ * script-hook.ts; the in-process interface here is what SDK embedders and tests register
+ * directly. Docs: /docs/agent-loop § "User-prompt hooks".
*/
+import { hookEvent, userText } from "../omnimessage/index.js";
+import type { UserPromptOutcome } from "../interfaces/index.js";
+import type { UserPromptTrigger } from "../plugins/index.js";
+import { failedAnswer } from "./answer.js";
+
export interface UserPromptHookInput {
sessionId: string;
+ /** Absolute path of the Trace file being written (absent for a Trace-less Session). */
+ tracePath?: string;
/** The Session's scratchpad directory (where a hook keeps per-session state, e.g. GOAL.json). */
scratchpadDir: string;
- /** The user's prompt text (for goal mode: the objective, leading marker blocks stripped). */
+ /** The user's prompt text, leading marker blocks stripped (for goal mode: the objective). */
prompt: string;
/** Flow-specific scalar fields the host adds beside the fixed ones (goal mode: `budget`). */
extras?: Record<string, string | number | boolean>;
@@ -26,5 +47,38 @@ export interface UserPromptHookResult {
/** A named user-prompt hook (the name is its package's). */
export interface UserPromptHook {
name: string;
+ /** When the hook runs; absent = `prompt`, on every Prompt the user submits. */
+ trigger?: UserPromptTrigger;
run(input: UserPromptHookInput): Promise<UserPromptHookResult | void>;
}
+
+/**
+ * Runs the user-prompt hooks in registration order and turns what they answered into
+ * records: a harness-stamped user text for every non-empty `context`, a `hook` event for
+ * every hook that threw. An aborted signal ends the pass — what a killed script reports is
+ * the interruption, not a failure of the hook.
+ */
+export async function runUserPromptHooks(
+ hooks: readonly UserPromptHook[],
+ input: UserPromptHookInput,
+): Promise<UserPromptOutcome> {
+ const outcome: UserPromptOutcome = { records: [] };
+ for (const hook of hooks) {
+ if (input.signal?.aborted) break;
+ let result: UserPromptHookResult | void;
+ try {
+ result = await hook.run(input);
+ } catch (err) {
+ if (input.signal?.aborted) break;
+ outcome.records.push(
+ hookEvent({ hook: "user_prompt", name: hook.name, ...failedAnswer(err) }),
+ );
+ continue;
+ }
+ const context = result?.context;
+ if (typeof context === "string" && context.trim() !== "") {
+ outcome.records.push(userText(context, "harness"));
+ }
+ }
+ return outcome;
+}
diff --git a/packages/core/src/hooks/script-hook.ts b/packages/core/src/hooks/script-hook.ts
index 8a9373ac..6beed1b5 100644
--- a/packages/core/src/hooks/script-hook.ts
+++ b/packages/core/src/hooks/script-hook.ts
@@ -8,15 +8,17 @@
* stdin: `{ "hook": "stop", "session_id": "…", "trace_path": "/abs/…_001.jsonl" }` for a
* stop hook (`trace_path` absent for a Trace-less Session); a pre_tool_use hook
* additionally gets `tool_name`, `tool_call_id` and `arguments` (the raw argument
- * JSON string); a user_prompt hook gets `scratchpad_dir`, `prompt` and the host's
- * flow extras instead of `trace_path`.
+ * JSON string); a user_prompt hook additionally gets `scratchpad_dir` and `prompt`,
+ * plus the host's flow extras when the host started it by name.
* stdout: empty = no opinion; otherwise the point's result as JSON — a StopHookResult
- * (`decision` continue/stop, `input`, `reason`, `output`, `subagent`) or a
- * PreToolUseHookResult (`decision` allow/deny, `reason`, `output`).
+ * (`decision` continue/stop, `input`, `reason`, `output`, `subagent`), a
+ * PreToolUseHookResult (`decision` allow/deny, `reason`, `output`) or a
+ * UserPromptHookResult (`context`).
* exit: non-zero = failure (stderr's tail becomes the reason).
*
- * Hooks run in core and nowhere else — hosts trigger them through Session APIs (the goal
- * start goes through `Session.runUserPromptHook`), never by spawning scripts themselves.
+ * Hooks run in core and nowhere else — the Session consults them at their points, and a
+ * host reaches a flow of its own through a Session API (the goal start goes through
+ * `Session.runUserPromptHook`), never by spawning scripts itself.
* `runHookScript` is the generic runner behind the adapters (`scriptStopHook` /
* `scriptPreToolUseHook` / `scriptUserPromptHook`), each turning one installed command into
* the point's in-process interface.
@@ -27,6 +29,7 @@ import { prependPathEnv } from "../environment/tools/command/path-prepend.js";
import type { StopHook, StopHookInput, StopHookResult } from "./stop-hook.js";
import type { PreToolUseHook, PreToolUseHookInput, PreToolUseHookResult } from "./tool-hook.js";
import type { UserPromptHook, UserPromptHookInput, UserPromptHookResult } from "./prompt-hook.js";
+import type { UserPromptTrigger } from "../plugins/index.js";
/** Seconds a script may run before it is killed, when its manifest names none. */
export const DEFAULT_HOOK_TIMEOUT_S = 60;
@@ -202,23 +205,26 @@ function scriptRunner(
});
}
-/** One installed user-prompt command as a UserPromptHook. */
+/** One installed user-prompt command as a UserPromptHook; `trigger` is the command's resolved one (see plugins' userPromptTrigger). */
export function scriptUserPromptHook(
name: string,
dir: string,
command: string,
timeoutS?: number,
pathPrepend?: () => string[],
+ trigger?: UserPromptTrigger,
): UserPromptHook {
const run = scriptRunner(dir, command, timeoutS, pathPrepend);
return {
name,
+ ...(trigger !== undefined ? { trigger } : {}),
async run(input: UserPromptHookInput): Promise<UserPromptHookResult | undefined> {
return parseUserPromptResult(
await run(
{
hook: "user_prompt",
session_id: input.sessionId,
+ trace_path: input.tracePath,
scratchpad_dir: input.scratchpadDir,
prompt: input.prompt,
...input.extras,
diff --git a/packages/core/src/hooks/stop-hook.ts b/packages/core/src/hooks/stop-hook.ts
index 6a636c85..d38c0a8e 100644
--- a/packages/core/src/hooks/stop-hook.ts
+++ b/packages/core/src/hooks/stop-hook.ts
@@ -89,7 +89,7 @@ export interface SessionHooks {
stop?: StopHook[];
/** Consulted by the engine before each tool call's approval (see tool-hook.ts). */
preToolUse?: PreToolUseHook[];
- /** Run by `Session.runUserPromptHook` when the host accepts a prompt for a package's flow (see prompt-hook.ts). */
+ /** Consulted every time the user submits a Prompt; the ones marked `trigger: "host"` run only through `Session.runUserPromptHook` (see prompt-hook.ts). */
userPrompt?: UserPromptHook[];
/** How a `subagent` answer is honored; without it the request is recorded as unhonored. */
spawnSubagent?: HookSubagentSpawner;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 66cf6cb8..620d9292 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -49,7 +49,7 @@ export type {
TraceSink,
} from "./engine/context-engine.js";
export { Session } from "./session.js";
-export type { SessionConfig } from "./session.js";
+export type { SessionConfig, SessionOpenedContext } from "./session.js";
export type { AgentAssembly, ModelRequestContext, PromptSection } from "./agent.js";
// Session-title generation lives in internal/ (an assembly detail of Session.generateTitle);
// only its narrow public surface is re-exported: the result type (part of
diff --git a/packages/core/src/interfaces/shared.ts b/packages/core/src/interfaces/shared.ts
index e66f4c4f..f18ed042 100644
--- a/packages/core/src/interfaces/shared.ts
+++ b/packages/core/src/interfaces/shared.ts
@@ -80,6 +80,30 @@ export type PreToolUseFn = (
toolCall: OmniMessage<ToolCallPayload>,
) => Promise<PreToolUseOutcome | null>;
+/**
+ * What one pass over the user-prompt hooks produced, handed to `context_engine` by the
+ * Session-wired {@link UserPromptFn}: the records in hook order — one harness-stamped user
+ * text per non-empty `context` a hook answered, one `hook` event per hook that failed. The
+ * engine yields and writes them right behind the Prompt; the user texts join the Task's
+ * first request input.
+ */
+export interface UserPromptOutcome {
+ records: OmniMessage[];
+}
+
+/**
+ * User-prompt hook consult: called by `context_engine` once at the start of a run, after
+ * the Prompt is written and before the first request, with the run's new input. Wired by
+ * the Session from the Agent's installed hook packages (`hooks.json` `user_prompt`
+ * commands); answers null when the input carries no text of the user's own or no hook is
+ * due, and the engine then sends the Prompt as it is.
+ * Docs: /docs/agent-loop § "User-prompt hooks".
+ */
+export type UserPromptFn = (
+ input: OmniMessage[],
+ signal?: AbortSignal,
+) => Promise<UserPromptOutcome | null>;
+
/**
* One command-policy deny rule — plain project-editable data: a name (identifies the rule
* in the settings UI), a regex source tested against the whitespace-normalized command, an
diff --git a/packages/core/src/omnimessage/markers/origin-blocks.ts b/packages/core/src/omnimessage/markers/origin-blocks.ts
index 6d3a7612..632dcc2f 100644
--- a/packages/core/src/omnimessage/markers/origin-blocks.ts
+++ b/packages/core/src/omnimessage/markers/origin-blocks.ts
@@ -524,12 +524,27 @@ export function isWholeOriginBlock(text: string): boolean {
/**
* Whether a message is a user text a hook put into the loop: a stop hook's `continue`
- * input, or a user_prompt hook's expansion context the host sent behind the user's message
- * (goal mode's round protocol) — the harness-stamped inputs that open a round of their own.
- * A background-task completion notice shares the stamp but is a report riding inside a
- * round, so it is excluded by its block.
+ * input, or a user_prompt hook's expansion context sent behind the user's message (goal
+ * mode's round-1 protocol among them). A background-task completion notice shares the stamp
+ * but is a report riding inside a round, so it is excluded by its block.
+ *
+ * Not every such message opens a round: an expansion context belongs to the Prompt it
+ * follows. A consumer counting rounds takes the first one of a run and, after that, only
+ * the ones a stop hook's `continue` event announced (see {@link isHookContinue}).
*/
export function isHookInput(msg: OmniMessage): boolean {
if (!isHarnessInput(msg)) return false;
return parseBackgroundTaskDoneMessage((msg.payload as { text: string }).text) === null;
}
+
+/**
+ * Whether a message is a main-session stop hook's `continue` event: the record the Session
+ * puts on the stream right before the input it injects for the next Task. What follows it
+ * is a round boundary; a harness-stamped input nothing announced is not.
+ */
+export function isHookContinue(msg: OmniMessage): boolean {
+ if (msg.origin && msg.origin.length > 0) return false;
+ if (msg.type !== "event_msg") return false;
+ const p = msg.payload as { type?: string; hook?: string; decision?: string };
+ return p.type === "hook" && p.hook === "stop" && p.decision === "continue";
+}
diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.ts
index d3a39560..5dbe4a1a 100644
--- a/packages/core/src/omnimessage/types.ts
+++ b/packages/core/src/omnimessage/types.ts
@@ -446,7 +446,9 @@ export type HookDecision = "continue" | "stop" | "allow" | "deny";
/**
* Hook result event: one per non-void answer a hook gave at a hook point — `stop`,
* consulted after every Task of a `run` call (see hooks/stop-hook.ts), or `pre_tool_use`,
- * consulted before each tool call's approval (see hooks/tool-hook.ts). Produced by the
+ * consulted before each tool call's approval (see hooks/tool-hook.ts). The `user_prompt`
+ * point (see hooks/prompt-hook.ts) leaves one only for a hook that failed: what a hook
+ * answered there is the harness-stamped user message itself. Produced by the
* Session, streamed live and written to the Trace best-effort. `name` is the hook's
* registered name (`goal`, `continual-learning`, …); `decision` is absent when the hook only
* left a record; `output` is the hook's own structured record, scalars only — the goal hook
@@ -457,7 +459,7 @@ export type HookDecision = "continue" | "stop" | "allow" | "deny";
export interface HookPayload {
type: "hook";
/** The hook point that fired. */
- hook: "stop" | "pre_tool_use";
+ hook: "stop" | "pre_tool_use" | "user_prompt";
name: string;
decision?: HookDecision;
/** One line for people, as the hook wrote it. */
@@ -621,8 +623,8 @@ export function isEventMessage(msg: OmniMessage): msg is EventMessage {
/**
* Whether this is a main-session user text the harness injected (`sender: "harness"`) — a
- * stop hook's `continue` input, a host-composed companion message such as the goal plugin's
- * round protocol, or a background-task completion notice. Hosts key origin display on this
+ * stop hook's `continue` input, a user_prompt hook's expansion context (the goal plugin's
+ * round-1 protocol included), or a background-task completion notice. Hosts key origin display on this
* stamp; a consumer that means only the loop-driving injections (round boundaries)
* additionally excludes the notices by their `[background_task_done]` block.
*/
diff --git a/packages/core/src/plugins/index.ts b/packages/core/src/plugins/index.ts
index 441fe349..137031a4 100644
--- a/packages/core/src/plugins/index.ts
+++ b/packages/core/src/plugins/index.ts
@@ -59,10 +59,18 @@ export interface LibrarySkill extends SkillMetadata {
files?: Record<string, string>;
}
-/** One hook script entry: `command` is a path relative to the plugin's `hooks/` directory, run with Node; `timeout` in seconds (core's default applies when absent). */
+/**
+ * When a `user_prompt` command runs: `prompt` on every Prompt the user submits, `host` only
+ * when the host starts the package's flow by name (`Session.runUserPromptHook` — goal mode's
+ * start). Meaningless at the other hook points.
+ */
+export type UserPromptTrigger = "prompt" | "host";
+
+/** One hook script entry: `command` is a path relative to the plugin's `hooks/` directory, run with Node; `timeout` in seconds (core's default applies when absent); `trigger` says when a `user_prompt` command runs (see {@link userPromptTrigger} for the default). */
export interface HookCommand {
command: string;
timeout?: number;
+ trigger?: UserPromptTrigger;
}
/**
@@ -82,7 +90,7 @@ export interface HookManifest {
stop: HookCommand[];
/** Pre-tool-use commands, consulted before each tool call's approval. */
pre_tool_use: HookCommand[];
- /** User-prompt expansion commands, run by the host when it accepts a prompt for the flow the package owns (goal mode's start). */
+ /** User-prompt expansion commands: run on every Prompt the user submits, or — `trigger: "host"` — only when the host starts the flow the package owns (goal mode's start). */
user_prompt: HookCommand[];
}
@@ -167,6 +175,40 @@ export function comparePluginVersions(a: string, b: string): number {
return va.seq - vb.seq;
}
+/**
+ * The first manifest version written for a harness that runs `user_prompt` commands on every
+ * Prompt. See {@link userPromptTrigger}.
+ */
+export const USER_PROMPT_EVERY_PROMPT_SINCE = "2026.09.29.1";
+
+/**
+ * When one `user_prompt` command of a manifest runs. A command that says so decides; one
+ * that does not runs on every Prompt.
+ *
+ * COMPAT (remove at 0.3.0 release preparation; the release notes must first require
+ * updating the goal plugin): the point used to be reached by name only, and the goal
+ * package installed before this version starts an unbudgeted goal whenever its `start.mjs`
+ * runs without a budget. A manifest carrying a real plugin version older than
+ * {@link USER_PROMPT_EVERY_PROMPT_SINCE} therefore keeps the by-name reading for the
+ * commands that name no trigger. A manifest with no version, or one that is not a plugin
+ * version (a hand-written package), is not affected.
+ */
+export function userPromptTrigger(
+ manifestVersion: string,
+ command: HookCommand,
+): UserPromptTrigger {
+ if (command.trigger !== undefined) return command.trigger;
+ return predatesEveryPromptHooks(manifestVersion) ? "host" : "prompt";
+}
+
+/** Whether a manifest version is a real plugin version from before `user_prompt` commands ran on every Prompt (the compatibility rule of {@link userPromptTrigger}). */
+export function predatesEveryPromptHooks(manifestVersion: string): boolean {
+ return (
+ parsePluginVersion(manifestVersion) !== null &&
+ comparePluginVersions(manifestVersion, USER_PROMPT_EVERY_PROMPT_SINCE) < 0
+ );
+}
+
/**
* Parses the frontmatter at the start of SKILL.md: only recognizes `key: value` lines inside the
* first `---` block (split on the first colon, value trimmed, values may themselves contain colons);
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index f6d3ca82..cc147ddc 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -25,11 +25,13 @@ import {
userText,
} from "./omnimessage/index.js";
import type { OmniMessage, SessionMetaPayload } from "./omnimessage/index.js";
+import { stripLeadingMarkerBlocks } from "./omnimessage/markers/index.js";
import { imagesToScratchpadPaths } from "./internal/session-support.js";
import { runStopHooks } from "./hooks/stop-hook.js";
import type { HookSubagentSpawner, SessionHooks, StopHook } from "./hooks/stop-hook.js";
import { runPreToolUseHooks } from "./hooks/tool-hook.js";
import type { PreToolUseHook } from "./hooks/tool-hook.js";
+import { runUserPromptHooks } from "./hooks/prompt-hook.js";
import type { UserPromptHook, UserPromptHookResult } from "./hooks/prompt-hook.js";
import { pumpOpener } from "./internal/merge-queue.js";
import type {
@@ -61,6 +63,17 @@ import type {
TraceSink,
} from "./engine/context-engine.js";
+/**
+ * A context as the composition layer opens it for a Session: the engine's
+ * {@link OpenedContext}, plus the hooks that context runs with. Hook packages are read when
+ * a model context opens, like the rest of the Agent State, so a rotation brings its own
+ * set; the engine never sees them.
+ */
+export interface SessionOpenedContext extends OpenedContext {
+ /** The opened context's hooks, replacing the Session's whole set. Absent = the Session keeps the ones it has (an embedder that registered in-process hooks and rotates without re-reading any). */
+ hooks?: SessionHooks;
+}
+
export interface SessionConfig {
/** Session metadata: the first context's runtime configuration (session_id / provider / model_id / model_context_window / system_prompt / agent_state / workspace / source) — a context a compaction opens brings its own through `openNextContext`; the toolset travels separately as the first run's tool_list_ready event. */
meta: SessionMetaPayload;
@@ -91,9 +104,12 @@ export interface SessionConfig {
* The Session adopts the meta as its current one (`metaMessage`); the engine yields the
* records live, writes meta and records at the head of the rotated Trace file, and seeds
* the new LLM's cumulative session counts itself. Context compaction is unavailable if not
- * provided.
+ * provided. The hooks it answers with become the Session's (see
+ * {@link SessionOpenedContext}).
*/
- openNextContext?: (opts: OpenContextOptions) => OpenedContext | Promise<OpenedContext>;
+ openNextContext?: (
+ opts: OpenContextOptions,
+ ) => SessionOpenedContext | Promise<SessionOpenedContext>;
/**
* Factory for the bare LLM used by out-of-band, one-off requests (same Model/credential as
@@ -124,8 +140,9 @@ export interface SessionConfig {
*/
modelHasVision: boolean;
/**
- * Stop hooks consulted after every Task of a `run` call, and the spawner that honors a
- * hook's `subagent` answer (see hooks/stop-hook.ts). Absent = none.
+ * The first context's hooks — one list per hook point, and the spawner that honors a stop
+ * hook's `subagent` answer (see hooks/stop-hook.ts). Absent = none. A context
+ * `openNextContext` opens may bring its own.
*/
hooks?: SessionHooks;
/**
@@ -276,11 +293,17 @@ export class Session {
private level?: ThinkingLevelName;
private readonly imagesDir: string;
private readonly modelHasVision: boolean;
- /** Stop hooks every `run` of this Session consults, and the spawner for their subagent answers (see SessionConfig.hooks). */
- private readonly stopHooks: readonly StopHook[];
- private readonly preToolUseHooks: readonly PreToolUseHook[];
- private readonly userPromptHooks: readonly UserPromptHook[];
- private readonly spawnSubagent?: HookSubagentSpawner;
+ /**
+ * The hooks of the context that is running, and the spawner for a stop hook's subagent
+ * answer: the first context's at construction, replaced whole by each context
+ * `openNextContext` opens with a set of its own (see `adoptHooks`). Every consult reads
+ * these fields when it happens, so a rotation in the middle of a `run` call hands the
+ * rest of that call to the new context's hooks.
+ */
+ private stopHooks: readonly StopHook[] = [];
+ private preToolUseHooks: readonly PreToolUseHook[] = [];
+ private userPromptHooks: readonly UserPromptHook[] = [];
+ private spawnSubagent: HookSubagentSpawner | undefined;
private readonly commandPolicy?: CommandPolicySource;
private metaWritten = false;
/**
@@ -326,10 +349,7 @@ export class Session {
this.imagesDir = config.imagesDir;
this.modelHasVision = config.modelHasVision;
- this.stopHooks = config.hooks?.stop ?? [];
- this.preToolUseHooks = config.hooks?.preToolUse ?? [];
- this.userPromptHooks = config.hooks?.userPrompt ?? [];
- if (config.hooks?.spawnSubagent) this.spawnSubagent = config.hooks.spawnSubagent;
+ if (config.hooks) this.adoptHooks(config.hooks);
if (config.commandPolicy) this.commandPolicy = config.commandPolicy;
this.bootstrap = config.bootstrap;
this.cancelBootstrap = config.cancelBootstrap;
@@ -346,8 +366,9 @@ export class Session {
...(config.openNextContext
? {
openNextContext: async (opts: OpenContextOptions): Promise<OpenedContext> => {
- const opened = await config.openNextContext!(opts);
+ const { hooks, ...opened } = await config.openNextContext!(opts);
if (opened.sessionMeta) this.meta = opened.sessionMeta;
+ if (hooks) this.adoptHooks(hooks);
return opened;
},
}
@@ -381,6 +402,77 @@ export class Session {
config.environment.setBackgroundMessageListener?.((msg) => this.bgMessageListener?.(msg));
}
+ /**
+ * Runs the named package's host-triggered `user_prompt` hook (`trigger: "host"`) — hooks
+ * run in core and nowhere else; the host calls this when it accepts a user prompt for the
+ * flow the package owns (the server does for a goal start, with `extras: { budget }`).
+ * The Session supplies its own id, Trace path and scratchpad directory; the answer's
+ * `context` is the text the host sends right behind the user's message, stamped
+ * `sender: "harness"`. Returns null when the package is not installed or names no such
+ * command (the host's cue to refuse the flow); an empty answer is `{}`. No `hook` event
+ * is recorded — the expansion message is the record.
+ */
+ async runUserPromptHook(
+ name: string,
+ prompt: string,
+ extras?: Record<string, string | number | boolean>,
+ ): Promise<UserPromptHookResult | null> {
+ const hook = this.userPromptHooks.find((h) => h.name === name && h.trigger === "host");
+ if (!hook) return null;
+ const tracePath = this.trace?.currentPath?.();
+ const result = await hook.run({
+ sessionId: this.sessionId,
+ ...(tracePath !== undefined ? { tracePath } : {}),
+ scratchpadDir: this.imagesDir,
+ prompt,
+ ...(extras !== undefined ? { extras } : {}),
+ });
+ return result ?? {};
+ }
+
+ /** Takes a context's hooks as the Session's own, whole: a point the set does not list has none. */
+ private adoptHooks(hooks: SessionHooks): void {
+ this.stopHooks = hooks.stop ?? [];
+ this.preToolUseHooks = hooks.preToolUse ?? [];
+ this.userPromptHooks = hooks.userPrompt ?? [];
+ this.spawnSubagent = hooks.spawnSubagent;
+ }
+
+ /**
+ * The user-prompt consult of one Prompt (the engine's `RunOptions.userPrompt` seam): runs
+ * the hooks due on every Prompt against the text of the user's own in `input`, and
+ * returns their records. Null — nothing to consult — when no such hook is installed or
+ * the input carries no user text without a sender: an input the harness, the server or a
+ * parent agent wrote is not a Prompt the user submitted.
+ */
+ private async consultUserPromptHooks(
+ input: OmniMessage[],
+ signal?: AbortSignal,
+ ): Promise<{ records: OmniMessage[] } | null> {
+ const hooks = this.userPromptHooks.filter((h) => h.trigger !== "host");
+ if (hooks.length === 0) return null;
+ const texts: string[] = [];
+ for (const msg of input) {
+ if (msg.type !== "model_msg" || (msg.origin && msg.origin.length > 0)) continue;
+ const p = msg.payload as { type?: string; role?: string; text?: string; sender?: string };
+ if (p.type !== "text" || p.role !== "user" || typeof p.text !== "string") continue;
+ if (p.sender !== undefined && p.sender !== "user") continue;
+ texts.push(p.text);
+ }
+ if (texts.length === 0) return null;
+ const text = texts.join("\n");
+ const tracePath = this.trace?.currentPath?.();
+ return runUserPromptHooks(hooks, {
+ sessionId: this.sessionId,
+ ...(tracePath !== undefined ? { tracePath } : {}),
+ scratchpadDir: this.imagesDir,
+ // The user's own words: a skill invocation or an origin note in front of them is the
+ // host's framing, the same reading the goal start gives its objective.
+ prompt: stripLeadingMarkerBlocks(text).trim() || text,
+ ...(signal ? { signal } : {}),
+ });
+ }
+
/**
* Runs a Task to completion and streams out OmniMessage. `newMessages` is this call's Prompt
* (only the newly added input); `opts` carries the abort signal `signal` and the per-call
@@ -392,6 +484,11 @@ export class Session {
* until a turn no longer produces a tool_call (Task ends) or it's aborted.
* Docs: /docs/agent-loop § "The loop at a glance".
*
+ * A Prompt carrying text of the user's own is first put to the user-prompt hooks (see
+ * hooks/prompt-hook.ts): each `context` they answer follows the Prompt as a user text
+ * stamped `sender: "harness"` — yielded, since the host has not seen it, written to the
+ * Trace and sent with the Prompt in the Task's first request.
+ *
* When the Task ends, the Session's stop hooks are consulted (see hooks/stop-hook.ts):
* every answer is recorded as a `hook` event on the stream and in the Trace, and the first
* `continue` drives another Task inside this same call — its input is yielded first, as a
@@ -400,31 +497,6 @@ export class Session {
* max_turns cap) or an aborted signal ends the call; the return value is the last Task's
* cutoff, exactly as for a single Task.
*/
- /**
- * Runs the named package's `user_prompt` hook — hooks run in core and nowhere else; the
- * host calls this when it accepts a user prompt for the flow the package owns (the server
- * does for a goal start, with `extras: { budget }`). The Session supplies its own id and
- * scratchpad directory; the answer's `context` is the text the host sends right behind
- * the user's message, stamped `sender: "harness"`. Returns null when the package is not
- * installed or names no `user_prompt` command (the host's cue to refuse the flow); an
- * empty answer is `{}`. No `hook` event is recorded — the expansion message is the record.
- */
- async runUserPromptHook(
- name: string,
- prompt: string,
- extras?: Record<string, string | number | boolean>,
- ): Promise<UserPromptHookResult | null> {
- const hook = this.userPromptHooks.find((h) => h.name === name);
- if (!hook) return null;
- const result = await hook.run({
- sessionId: this.sessionId,
- scratchpadDir: this.imagesDir,
- prompt,
- ...(extras !== undefined ? { extras } : {}),
- });
- return result ?? {};
- }
-
async *run(
newMessages: OmniMessage[],
opts?: SessionRunOptions,
@@ -444,12 +516,15 @@ export class Session {
// a hook `allow` never overrides the policy — hook packages sit in agent-writable
// state, the policy is Project-owned security config — so a policy-vetoed allow is
// downgraded to no decision and the approval chain (policy outermost) answers.
- if (this.preToolUseHooks.length > 0) {
- const hooks = this.preToolUseHooks;
+ // The hooks are read at each consult rather than captured here: a compaction inside
+ // this call opens a context with hooks of its own, and the calls after it are theirs.
+ {
const signal = opts?.signal;
opts = {
...opts,
preToolUse: async (tc) => {
+ const hooks = this.preToolUseHooks;
+ if (hooks.length === 0) return null;
const p = tc.payload;
const tracePath = this.trace?.currentPath?.();
const outcome = await runPreToolUseHooks(hooks, {
@@ -471,12 +546,19 @@ export class Session {
};
}
const approve = opts?.approve;
- const spawn = this.spawnSubagent;
+ // User-prompt hooks ride the engine's consult seam too (RunOptions.userPrompt), for the
+ // call's own Prompt only: a Task a stop hook continues into starts from the hook's
+ // input, which no user submitted.
+ let taskOpts: SessionRunOptions | undefined = {
+ ...opts,
+ userPrompt: (prompt, signal) => this.consultUserPromptHooks(prompt, signal),
+ };
let input = newMessages;
for (;;) {
// Manual iteration (not for-await) so the engine's return value — how the Task ended —
// is read: a cutoff means the model never finished, which no `continue` may override.
- const it = this.runTask(input, opts);
+ const it = this.runTask(input, taskOpts);
+ taskOpts = opts;
let cutoff: RunCutoff | null = null;
for (;;) {
const res = await it.next();
@@ -488,6 +570,7 @@ export class Session {
}
if (this.stopHooks.length === 0) return cutoff;
const tracePath = this.trace?.currentPath?.();
+ const spawn = this.spawnSubagent;
const outcome = await runStopHooks(
this.stopHooks,
{
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index afe7816f..0397ce2e 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -17,6 +17,7 @@ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import {
loadPreinstalledPlugins,
parseSkillFrontmatter,
+ type HookCommand,
type HookManifest,
type LibraryPlugin,
type SkillMetadata,
@@ -662,13 +663,58 @@ 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). */
+/**
+ * One hook point's command list as a manifest on disk spells it, read tolerantly: anything
+ * but an array is no commands, and an entry is kept only when it names a script inside the
+ * package directory `dir`. A `timeout` that is not a positive number and a `trigger` that is
+ * not one of the two known values are dropped rather than failing the entry.
+ */
+function readHookCommands(dir: string, value: unknown): HookCommand[] {
+ if (!Array.isArray(value)) return [];
+ const commands: HookCommand[] = [];
+ for (const entry of value as unknown[]) {
+ if (entry === null || typeof entry !== "object") continue;
+ const { command, timeout, trigger } = entry as Record<string, unknown>;
+ if (typeof command !== "string" || command === "") continue;
+ const relative = path.relative(dir, path.resolve(dir, command));
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) continue;
+ commands.push({
+ command,
+ ...(typeof timeout === "number" && timeout > 0 ? { timeout } : {}),
+ ...(trigger === "prompt" || trigger === "host" ? { trigger } : {}),
+ });
+ }
+ return commands;
+}
+
+/**
+ * The manifest of the hook package directory `dir`, or null when `hooks.json` is missing or
+ * is not a JSON object (then it is not a hook package). Read tolerantly, because a package
+ * is not only what an installer writes: an Agent or a person may have written the directory
+ * by hand. A hook point the manifest does not list has no commands, display fields that are
+ * not strings read as absent, and unknown keys are left behind — every reader downstream
+ * finds the three lists as arrays.
+ */
async function readHookManifest(dir: string): Promise<HookManifest | null> {
+ let raw: unknown;
try {
- return JSON.parse(await fs.readFile(path.join(dir, "hooks.json"), "utf8")) as HookManifest;
+ raw = JSON.parse(await fs.readFile(path.join(dir, "hooks.json"), "utf8"));
} catch {
return null;
}
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const manifest = raw as Record<string, unknown>;
+ return {
+ name: typeof manifest.name === "string" ? manifest.name : "",
+ description: typeof manifest.description === "string" ? manifest.description : "",
+ ...(typeof manifest.description_zh === "string"
+ ? { description_zh: manifest.description_zh }
+ : {}),
+ version: typeof manifest.version === "string" ? manifest.version : "",
+ stop: readHookCommands(dir, manifest.stop),
+ pre_tool_use: readHookCommands(dir, manifest.pre_tool_use),
+ user_prompt: readHookCommands(dir, manifest.user_prompt),
+ };
}
/** Serializes a manifest the way every writer of `hooks.json` does (pretty-printed, trailing newline). */
@@ -729,10 +775,11 @@ export interface InstalledHook extends HookManifest {
/**
* Lists the hook packages installed on the target Agent: scans `hooks/<name>/hooks.json` and
- * reads the optional icon.svg beside it. The manifest is the installer's own output
- * (installHook writes a HookManifest), so it is read back as one; a directory without a
- * hooks.json is not a hook package, and the directory name is the identity (a manifest
- * naming something else is corrected). Sorted by name; [] when hooks/ doesn't exist.
+ * reads the optional icon.svg beside it. A package is whatever directory carries a manifest —
+ * an installer's output or one written by hand — so the manifest is read tolerantly (see
+ * readHookManifest); a directory without a readable hooks.json is not a hook package, and
+ * the directory name is the identity (a manifest naming something else is corrected).
+ * Sorted by name; [] when hooks/ doesn't exist.
*/
export async function listInstalledHooks(
root: string,
diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.ts
index 3bbe7c04..e29723fe 100644
--- a/packages/core/test/agent.test.ts
+++ b/packages/core/test/agent.test.ts
@@ -17,7 +17,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
import type { OmniMessage } from "../src/omnimessage/index.js";
import type { OpenContextOptions, OpenedContext, SystemConfig } from "../src/index.js";
-import { agentsMdPath, projectConfigPath, systemConfigPath } from "../src/state/paths.js";
+import {
+ agentsMdPath,
+ hooksDir,
+ projectConfigPath,
+ skillsDir,
+ systemConfigPath,
+} from "../src/state/paths.js";
import {
addModel,
createAgent,
@@ -1007,6 +1013,67 @@ describe("Agent model contexts are assembled from the Agent State on disk, at ev
}
});
+ it("a Skill and a hook package written during the old context are the next context's", async () => {
+ const agent = await createAgent();
+ const ws = path.join(tmpRoot, "ws-authored");
+ await fs.mkdir(ws, { recursive: true });
+ const session = await agent.createSession({ workspaceDir: ws });
+ const skillDir = path.join(
+ skillsDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID),
+ "clock-reading",
+ );
+ const hookDir = path.join(hooksDir(tmpRoot, DEFAULT_PROJECT_ID, DEFAULT_AGENT_ID), "flow");
+ try {
+ await bootstrapped(session);
+
+ // Written as plain files, the way a model working on its own configuration does it:
+ // no installer, and a manifest that lists only the point it uses. The command is
+ // host-triggered so the Session can be asked for it by name.
+ await fs.mkdir(skillDir, { recursive: true });
+ await fs.writeFile(
+ path.join(skillDir, "SKILL.md"),
+ "---\nname: clock-reading\ndescription: Reads analog clocks.\n---\n\nLook at the hands.\n",
+ );
+ await fs.mkdir(hookDir, { recursive: true });
+ await fs.writeFile(
+ path.join(hookDir, "hooks.json"),
+ JSON.stringify({ user_prompt: [{ command: "start.mjs", trigger: "host" }] }),
+ );
+ await fs.writeFile(
+ path.join(hookDir, "start.mjs"),
+ 'process.stdout.write(JSON.stringify({ context: "started" }));\n',
+ );
+
+ // Nothing changes in the middle of a context.
+ expect(promptOf(session)).not.toContain("clock-reading");
+ expect(await session.runUserPromptHook("flow", "go")).toBeNull();
+
+ await openNext(session);
+ expect(promptOf(session)).toContain("`clock-reading` — Reads analog clocks.");
+ expect(await session.runUserPromptHook("flow", "go")).toEqual({ context: "started" });
+
+ // The one switch over every package is read on the same schedule…
+ await patchSystemConfig((cfg) => {
+ cfg.hooks = { enabled: false };
+ });
+ expect(await session.runUserPromptHook("flow", "go")).toEqual({ context: "started" });
+ await openNext(session);
+ expect(await session.runUserPromptHook("flow", "go")).toBeNull();
+
+ // …and so is a package's removal.
+ await patchSystemConfig((cfg) => {
+ cfg.hooks = { enabled: true };
+ });
+ await openNext(session);
+ expect(await session.runUserPromptHook("flow", "go")).toEqual({ context: "started" });
+ await fs.rm(hookDir, { recursive: true, force: true });
+ await openNext(session);
+ expect(await session.runUserPromptHook("flow", "go")).toBeNull();
+ } finally {
+ session.dispose();
+ }
+ });
+
it("session_meta records no level; the config default and a null pin shape only the LLM base", async () => {
const agent = await createAgent();
const ws = path.join(tmpRoot, "ws-thinking-meta");
diff --git a/packages/core/test/continual-learning-hook.test.ts b/packages/core/test/continual-learning-hook.test.ts
index 1a15b113..acb075f4 100644
--- a/packages/core/test/continual-learning-hook.test.ts
+++ b/packages/core/test/continual-learning-hook.test.ts
@@ -59,6 +59,20 @@ const user = (text: string) => ({
type: "model_msg",
payload: { type: "text", role: "user", text },
});
+// A user text the harness sent, e.g. a user_prompt hook's context written right behind the Prompt.
+const harness = (text: string) => ({
+ type: "model_msg",
+ payload: { type: "text", role: "user", text, sender: "harness" },
+});
+const image = () => ({
+ type: "model_msg",
+ payload: {
+ type: "image_url",
+ role: "user",
+ image_url: "data:image/png;base64,aGk=",
+ stop_reason: "completed",
+ },
+});
const assistant = (text: string) => ({
type: "model_msg",
payload: { type: "text", role: "assistant", text },
@@ -141,6 +155,35 @@ describe("continual-learning stop.mjs", () => {
expect(stop()).toBeUndefined();
});
+ it("opens the window at the user's own message when the harness sent a context right behind it", async () => {
+ // The Task's input is a batch: the user's message, then a user_prompt hook's context.
+ await append([meta(), user("big refactor")]);
+ for (let i = 1; i <= 35; i++) await append(turn(i));
+ await append([
+ user("[use_skills]\nskills: web-design\n[/use_skills]\n\nport the parser"),
+ harness("The local time is 10:00."),
+ ]);
+ for (let i = 1; i <= 31; i++) await append(turn(i));
+ const res = stop();
+ expect(res).toMatchObject({ output: { turns: 31 } });
+ const prompt = res!.subagent!.prompt;
+ expect(prompt).toContain("Skills invoked in this task: web-design");
+ expect(prompt.indexOf("[user] port the parser")).toBeGreaterThan(-1);
+ expect(prompt.indexOf("[user] port the parser")).toBeLessThan(
+ prompt.indexOf("[user] The local time is 10:00."),
+ );
+ // The window is still this Task's own: the one before it stays out.
+ expect(prompt).not.toContain("big refactor");
+ });
+
+ it("keeps an image sent with the message inside the batch", async () => {
+ await append([meta(), user("match this mockup"), image(), harness("The local time is 10:00.")]);
+ for (let i = 1; i <= 31; i++) await append(turn(i));
+ const res = stop();
+ expect(res).toMatchObject({ output: { turns: 31 } });
+ expect(res!.subagent!.prompt).toContain("[user] match this mockup");
+ });
+
it("mid-task deliveries do not reset the window: steering and steered notices ride inside", async () => {
await append([meta(), user("long task")]);
for (let i = 1; i <= 25; i++) await append(turn(i));
diff --git a/packages/core/test/hook-packages.test.ts b/packages/core/test/hook-packages.test.ts
index aec338da..f1bfb269 100644
--- a/packages/core/test/hook-packages.test.ts
+++ b/packages/core/test/hook-packages.test.ts
@@ -3,12 +3,15 @@
* `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.
+ *
+ * A package is any directory carrying a manifest, so one written by hand loads too: what it
+ * leaves out reads as empty, and what it gets wrong is dropped entry by entry.
*/
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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
DEFAULT_AGENT_ID,
DEFAULT_PROJECT_ID,
@@ -16,7 +19,9 @@ import {
hooksDir,
installHook,
listInstalledHooks,
+ predatesEveryPromptHooks,
systemConfigPath,
+ userPromptTrigger,
} from "../src/index.js";
import type { HookManifest, SystemConfig } from "../src/index.js";
import { stubProviderKeys } from "./provider-keys.js";
@@ -74,6 +79,139 @@ describe("installed hook packages", () => {
});
});
+describe("a hook package written by hand", () => {
+ /** Writes `hooks/<name>/hooks.json` as given, plus the scripts beside it. */
+ async function writePackage(
+ name: string,
+ manifest: unknown,
+ files: Record<string, string> = {},
+ ): Promise<void> {
+ const dir = path.join(hooksDir(tmpRoot, ...ids), name);
+ await fs.mkdir(dir, { recursive: true });
+ await fs.writeFile(path.join(dir, "hooks.json"), JSON.stringify(manifest));
+ for (const [rel, text] of Object.entries(files)) await fs.writeFile(path.join(dir, rel), text);
+ }
+
+ it("loads with only the hook point it uses, the rest reading as empty", async () => {
+ await createAgent();
+ await writePackage(
+ "append-time",
+ { name: "append-time", user_prompt: [{ command: "time.mjs", timeout: 10 }] },
+ { "time.mjs": FILES["expand.mjs"] },
+ );
+
+ const [hook] = await listInstalledHooks(tmpRoot, ...ids);
+ expect(hook).toMatchObject({
+ name: "append-time",
+ description: "",
+ version: "",
+ stop: [],
+ pre_tool_use: [],
+ user_prompt: [{ command: "time.mjs", timeout: 10 }],
+ });
+ });
+
+ it("drops the entries it cannot run and keeps the ones it can", async () => {
+ await createAgent();
+ await writePackage("mixed", {
+ description: 7,
+ version: "2026.09.29.1",
+ stop: "stop.mjs",
+ pre_tool_use: [{ command: 5 }, "guard.mjs", null, { timeout: 3 }],
+ user_prompt: [
+ { command: "../outside.mjs" },
+ { command: "/etc/passwd" },
+ { command: "ok.mjs", timeout: -1, trigger: "sometimes" },
+ { command: "flow/start.mjs", timeout: 5, trigger: "host" },
+ ],
+ });
+ // Not a JSON object: not a package.
+ await writePackage("a-list", [{ command: "x.mjs" }]);
+
+ const listed = await listInstalledHooks(tmpRoot, ...ids);
+ expect(listed.map((h) => h.name)).not.toContain("a-list");
+ const mixed = listed.find((h) => h.name === "mixed");
+ expect(mixed).toMatchObject({ description: "", version: "2026.09.29.1" });
+ expect(mixed?.stop).toEqual([]);
+ expect(mixed?.pre_tool_use).toEqual([]);
+ expect(mixed?.user_prompt).toEqual([
+ { command: "ok.mjs" },
+ { command: "flow/start.mjs", timeout: 5, trigger: "host" },
+ ]);
+ });
+
+ it("gives a Session a hook that runs on every Prompt, not one a host starts by name", async () => {
+ const agent = await createAgent();
+ await writePackage(
+ "append-time",
+ { user_prompt: [{ command: "time.mjs" }] },
+ { "time.mjs": FILES["expand.mjs"] },
+ );
+ const ws = path.join(tmpRoot, "ws");
+ await fs.mkdir(ws, { recursive: true });
+
+ const session = await agent.createSession({ workspaceDir: ws });
+ try {
+ expect(await session.runUserPromptHook("append-time", "hi")).toBeNull();
+ } finally {
+ session.dispose();
+ }
+ });
+});
+
+describe("when a user_prompt command runs", () => {
+ it("is what the command says, and every Prompt when it says nothing", () => {
+ expect(userPromptTrigger("2026.09.29.1", { command: "a.mjs" })).toBe("prompt");
+ expect(userPromptTrigger("2026.09.29.1", { command: "a.mjs", trigger: "host" })).toBe("host");
+ // A package written by hand carries no version, or one of its own making.
+ expect(userPromptTrigger("", { command: "a.mjs" })).toBe("prompt");
+ expect(userPromptTrigger("1.0.0", { command: "a.mjs" })).toBe("prompt");
+ });
+
+ it("stays by-name for a manifest from before the point ran on every Prompt", () => {
+ expect(userPromptTrigger("2026.09.01.1", { command: "start.mjs" })).toBe("host");
+ expect(userPromptTrigger("2026-09-01.1", { command: "start.mjs" })).toBe("host");
+ expect(userPromptTrigger("2026.09.01.1", { command: "a.mjs", trigger: "prompt" })).toBe(
+ "prompt",
+ );
+ expect(predatesEveryPromptHooks("2026.09.28.9")).toBe(true);
+ expect(predatesEveryPromptHooks("2026.09.29.1")).toBe(false);
+ expect(predatesEveryPromptHooks("")).toBe(false);
+ });
+});
+
+describe("a package from before user_prompt hooks ran on every Prompt", () => {
+ it("is still reached by name, and named once in the log however many Sessions read it", async () => {
+ const agent = await createAgent();
+ await installHook(tmpRoot, ...ids, MANIFEST, FILES);
+ const ws = path.join(tmpRoot, "ws");
+ await fs.mkdir(ws, { recursive: true });
+ const lines: string[] = [];
+ const stderr = vi.spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ lines.push(String(chunk));
+ return true;
+ });
+ try {
+ for (let i = 0; i < 2; i++) {
+ const session = await agent.createSession({ workspaceDir: ws });
+ try {
+ expect(await session.runUserPromptHook("expander", "hi")).toEqual({
+ context: "expanded",
+ });
+ } finally {
+ session.dispose();
+ }
+ }
+ } finally {
+ stderr.mockRestore();
+ }
+ const dir = path.join(hooksDir(tmpRoot, ...ids), "expander");
+ const reminders = lines.filter((line) => line.startsWith("[hooks]") && line.includes(dir));
+ expect(reminders).toHaveLength(1);
+ expect(reminders[0]).toContain("expander 2026.09.02.1");
+ });
+});
+
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();
diff --git a/packages/core/test/hooks.test.ts b/packages/core/test/hooks.test.ts
index e992293d..e44f88c8 100644
--- a/packages/core/test/hooks.test.ts
+++ b/packages/core/test/hooks.test.ts
@@ -277,7 +277,7 @@ describe("Session user-prompt hook", () => {
await rmEventually(dir);
});
- it("runs the named package's hook with the Session's own id and scratchpad, null when absent", async () => {
+ it("runs the named package's host-triggered hook with the Session's own id and scratchpad, null when absent", async () => {
const script = path.join(dir, "expand.mjs");
await fs.writeFile(
script,
@@ -314,7 +314,9 @@ describe("Session user-prompt hook", () => {
},
imagesDir: scratchpad,
modelHasVision: true,
- hooks: { userPrompt: [scriptUserPromptHook("goal", dir, "expand.mjs")] },
+ hooks: {
+ userPrompt: [scriptUserPromptHook("goal", dir, "expand.mjs", undefined, undefined, "host")],
+ },
});
const result = await session.runUserPromptHook("goal", "ship it", { budget: 500 });
expect(result?.context).toBe(`user_prompt/session-1/ship it/500 @ ${scratchpad}`);
diff --git a/packages/core/test/plugins.test.ts b/packages/core/test/plugins.test.ts
index 6b8a346e..dce8d444 100644
--- a/packages/core/test/plugins.test.ts
+++ b/packages/core/test/plugins.test.ts
@@ -101,14 +101,14 @@ describe("loadLibraryPlugins", () => {
expect(Object.keys(files).some((rel) => rel.startsWith("reference/"))).toBe(true);
});
- it("a hook plugin carries a manifest naming its stop scripts and the hooks/ files to install", () => {
+ it("a hook plugin carries a manifest naming its scripts and the hooks/ files to install; goal's start runs only when the host starts a goal", () => {
const goal = libraryPlugin("goal");
expect(goal?.hooks?.manifest).toMatchObject({
name: "goal",
version: goal!.version,
stop: [{ command: "stop.mjs", timeout: 60 }],
pre_tool_use: [],
- user_prompt: [{ command: "start.mjs", timeout: 60 }],
+ user_prompt: [{ command: "start.mjs", timeout: 60, trigger: "host" }],
});
expect(goal!.hooks!.manifest.description_zh).toBeDefined();
expect(Object.keys(goal!.hooks!.files).sort()).toEqual(["lib.mjs", "start.mjs", "stop.mjs"]);
diff --git a/packages/core/test/user-prompt-hooks.test.ts b/packages/core/test/user-prompt-hooks.test.ts
new file mode 100644
index 00000000..0edcc256
--- /dev/null
+++ b/packages/core/test/user-prompt-hooks.test.ts
@@ -0,0 +1,403 @@
+/**
+ * The user_prompt hook point: consulted every time the user submits a Prompt.
+ *
+ * - What the hooks answer follows the Prompt as harness-stamped user texts — on the stream,
+ * in the Trace and in the Task's first request — and a hook that fails leaves a `hook`
+ * event in the same place instead.
+ * - Only a Prompt carrying text of the user's own is put to them: an input the server, the
+ * harness or a parent agent wrote is not one, and neither is a stop hook's continuation.
+ * - A hook marked `trigger: "host"` stays out of that consult and is reached by name.
+ * - The hooks are those of the context that is running: a context a compaction opens brings
+ * its own set, and the Session consults that one from then on.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { rmEventually } from "./rm-eventually.js";
+import {
+ Session,
+ assistantText,
+ isHookContinue,
+ isHookInput,
+ runUserPromptHooks,
+ tokenUsage,
+ userText,
+} from "../src/index.js";
+import type {
+ CompactionSettings,
+ EnvironmentInterface,
+ HookPayload,
+ LLMInterface,
+ LLMOutcome,
+ OmniMessage,
+ SessionHooks,
+ SessionMetaPayload,
+ SessionOpenedContext,
+ StopHook,
+ TextPayload,
+ TraceSink,
+ UserPromptHook,
+ UserPromptHookInput,
+} from "../src/index.js";
+
+const fakeEnvironment: EnvironmentInterface = {
+ listTools: async () => [],
+ // eslint-disable-next-line require-yield
+ executeTool: async function* () {
+ throw new Error("not used");
+ },
+ toolPermission: () => undefined,
+};
+
+/** Builds a token_usage: request.total is the context-usage figure, session.total the cumulative one. */
+const usage = (requestTotal: number, sessionTotal: number): OmniMessage =>
+ tokenUsage(
+ { cache_read: 0, cache_write: 0, output: 0, total: sessionTotal },
+ { cache_read: 0, cache_write: 0, output: 0, total: requestTotal },
+ );
+
+/** Answers each request from a script, recording the input it was sent. */
+class ScriptedLLM implements LLMInterface {
+ calls: OmniMessage[][] = [];
+ constructor(private readonly responses: OmniMessage[][]) {}
+
+ async *streamGenerate({
+ newMessages,
+ }: {
+ newMessages: OmniMessage[];
+ }): AsyncGenerator<OmniMessage, LLMOutcome> {
+ this.calls.push(newMessages);
+ const next = this.responses.shift();
+ if (!next) return { status: "retryable", errorMessage: "no scripted response" };
+ for (const msg of next) yield msg;
+ return { status: "completed" };
+ }
+}
+
+/** One short final reply per request, as many as asked for. */
+const replies = (n: number): OmniMessage[][] =>
+ Array.from({ length: n }, (_, i) => [assistantText(`answer ${i + 1}`), usage(20, 20 * (i + 1))]);
+
+async function collect(gen: AsyncGenerator<OmniMessage, unknown>): Promise<OmniMessage[]> {
+ const all: OmniMessage[] = [];
+ for (;;) {
+ const res = await gen.next();
+ if (res.done) return all;
+ all.push(res.value);
+ }
+}
+
+/** A record as the assertions read it: a text's `sender:text`, anything else its payload type. */
+function shape(msg: OmniMessage): string {
+ const p = msg.payload as { type?: string; role?: string; sender?: string; text?: string };
+ if (msg.type === "session_meta") return "session_meta";
+ if (p.type === "text")
+ return `${p.role === "user" ? (p.sender ?? "user") : "assistant"}:${p.text}`;
+ if (p.type === "hook") {
+ const h = msg.payload as HookPayload;
+ return `hook:${h.hook}:${h.name}`;
+ }
+ return p.type ?? msg.type;
+}
+
+const textsOf = (msgs: OmniMessage[]): string[] => msgs.map((m) => (m.payload as TextPayload).text);
+
+/** A hook answering `context`, counting its runs and keeping what it was told. */
+function answering(
+ name: string,
+ context: string,
+ over: Partial<UserPromptHook> = {},
+): UserPromptHook & { seen: UserPromptHookInput[] } {
+ const seen: UserPromptHookInput[] = [];
+ return {
+ name,
+ seen,
+ run: async (input) => {
+ seen.push(input);
+ return { context };
+ },
+ ...over,
+ };
+}
+
+describe("runUserPromptHooks", () => {
+ const input: UserPromptHookInput = { sessionId: "s1", scratchpadDir: "/scratch", prompt: "hi" };
+
+ it("turns each context into a harness-stamped user text, in hook order, and drops the empty ones", async () => {
+ const { records } = await runUserPromptHooks(
+ [
+ answering("first", "one"),
+ { name: "void", run: async () => undefined },
+ answering("blank", " \n"),
+ { name: "empty", run: async () => ({}) },
+ answering("last", "two"),
+ ],
+ input,
+ );
+ expect(records.map(shape)).toEqual(["harness:one", "harness:two"]);
+ expect(records.every(isHookInput)).toBe(true);
+ });
+
+ it("records a hook that throws as a hook event and carries on with the rest", async () => {
+ const { records } = await runUserPromptHooks(
+ [
+ { name: "broken", run: async () => Promise.reject(new Error("boom")) },
+ answering("after", "still here"),
+ ],
+ input,
+ );
+ expect(records.map(shape)).toEqual(["hook:user_prompt:broken", "harness:still here"]);
+ expect(records[0]!.payload).toEqual({
+ type: "hook",
+ hook: "user_prompt",
+ name: "broken",
+ reason: "hook failed: boom",
+ });
+ });
+
+ it("ends the pass once the signal is aborted, without blaming the hook that was cut off", async () => {
+ const ac = new AbortController();
+ const later = answering("later", "never");
+ const { records } = await runUserPromptHooks(
+ [
+ {
+ name: "cut-off",
+ run: async () => {
+ ac.abort();
+ throw new Error("aborted");
+ },
+ },
+ later,
+ ],
+ { ...input, signal: ac.signal },
+ );
+ expect(records).toEqual([]);
+ expect(later.seen).toHaveLength(0);
+ });
+});
+
+describe("Session user-prompt hooks", () => {
+ let dir: string;
+ beforeEach(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-user-prompt-"));
+ });
+ afterEach(async () => {
+ await rmEventually(dir);
+ });
+
+ const meta = (): SessionMetaPayload => ({
+ session_id: "session-1",
+ provider: "custom",
+ model_id: "m1",
+ model_context_window: 1000,
+ system_prompt: "sp",
+ agent_state: dir,
+ workspace: dir,
+ });
+
+ /** A Trace sink that keeps what it is handed, in order. */
+ function recordingTrace(): TraceSink & { written: OmniMessage[] } {
+ const written: OmniMessage[] = [];
+ return {
+ written,
+ write: async (msg) => {
+ written.push(msg);
+ },
+ currentPath: () => path.join(dir, "trace_001.jsonl"),
+ };
+ }
+
+ function makeSession(
+ hooks: SessionHooks,
+ llm: LLMInterface,
+ extra: {
+ trace?: TraceSink;
+ compaction?: CompactionSettings;
+ openNextContext?: () => Promise<SessionOpenedContext>;
+ } = {},
+ ): Session {
+ return new Session({
+ meta: meta(),
+ bootstrap: async () => ({ llm }),
+ environment: fakeEnvironment,
+ imagesDir: path.join(dir, "scratchpad", "session-1"),
+ modelHasVision: true,
+ hooks,
+ ...(extra.trace ? { trace: extra.trace } : {}),
+ ...(extra.compaction ? { compaction: extra.compaction } : {}),
+ ...(extra.openNextContext ? { openNextContext: extra.openNextContext } : {}),
+ });
+ }
+
+ it("sends what the hooks answer right behind the Prompt: on the stream, in the Trace and in the request", async () => {
+ const first = answering("a-first", "ctx A");
+ const host = answering("d-host", "never", { trigger: "host" });
+ const last = answering("e-last", "ctx E");
+ const llm = new ScriptedLLM(replies(1));
+ const trace = recordingTrace();
+ const session = makeSession(
+ {
+ userPrompt: [
+ first,
+ { name: "b-broken", run: async () => Promise.reject(new Error("boom")) },
+ answering("c-blank", " "),
+ host,
+ last,
+ ],
+ },
+ llm,
+ { trace },
+ );
+ const prompt = "[use_skills]\nskills: clock\n[/use_skills]\n\nwhat time is it";
+
+ const out = await collect(session.run([userText(prompt)]));
+
+ // The Prompt itself is never yielded; what the hooks made of it is, ahead of the reply.
+ expect(out.map(shape).slice(0, 3)).toEqual([
+ "harness:ctx A",
+ "hook:user_prompt:b-broken",
+ "harness:ctx E",
+ ]);
+ expect(trace.written.map(shape).slice(0, 5)).toEqual([
+ "session_meta",
+ `user:${prompt}`,
+ "harness:ctx A",
+ "hook:user_prompt:b-broken",
+ "harness:ctx E",
+ ]);
+ // The model reads the contexts behind the Prompt, and never the failure.
+ expect(textsOf(llm.calls[0]!)).toEqual([prompt, "ctx A", "ctx E"]);
+ // A hook is told the user's own words, and where the Session keeps its record and state.
+ expect(first.seen).toEqual([
+ {
+ sessionId: "session-1",
+ tracePath: path.join(dir, "trace_001.jsonl"),
+ scratchpadDir: path.join(dir, "scratchpad", "session-1"),
+ prompt: "what time is it",
+ },
+ ]);
+ expect(host.seen).toHaveLength(0);
+ });
+
+ it("reaches a host-triggered hook by name only, and no other hook that way", async () => {
+ const host = answering("goal", "round one", { trigger: "host" });
+ const session = makeSession(
+ { userPrompt: [answering("clock", "tick"), host] },
+ new ScriptedLLM([]),
+ );
+ expect(await session.runUserPromptHook("goal", "ship it", { budget: 500 })).toEqual({
+ context: "round one",
+ });
+ expect(host.seen[0]).toMatchObject({ prompt: "ship it", extras: { budget: 500 } });
+ expect(await session.runUserPromptHook("clock", "x")).toBeNull();
+ expect(await session.runUserPromptHook("not-installed", "x")).toBeNull();
+ });
+
+ it("does not consult them for an input the user did not write", async () => {
+ const hook = answering("clock", "tick");
+ const llm = new ScriptedLLM(replies(3));
+ const session = makeSession({ userPrompt: [hook] }, llm);
+
+ await collect(
+ session.run([userText("[scheduled_task]\nname: x\n[/scheduled_task]\ngo", "server")]),
+ );
+ await collect(session.run([userText("carry on", "harness")]));
+ await collect(session.run([userText("do this", "parent_agent")]));
+
+ expect(hook.seen).toHaveLength(0);
+ expect(llm.calls.map(textsOf).map((texts) => texts.length)).toEqual([1, 1, 1]);
+ });
+
+ it("consults them for the Prompt a host flow expanded, behind the flow's own message", async () => {
+ const hook = answering("clock", "tick");
+ const llm = new ScriptedLLM(replies(1));
+ const session = makeSession({ userPrompt: [hook] }, llm);
+
+ const out = await collect(
+ session.run([userText("raise coverage"), userText("goal protocol", "harness")]),
+ );
+
+ expect(hook.seen.map((i) => i.prompt)).toEqual(["raise coverage"]);
+ expect(textsOf(llm.calls[0]!)).toEqual(["raise coverage", "goal protocol", "tick"]);
+ // Nothing announced it, so a round counter does not take it for a round.
+ expect(out.filter(isHookInput).map(shape)).toEqual(["harness:tick"]);
+ expect(out.some(isHookContinue)).toBe(false);
+ });
+
+ it("consults them once per run: a Task a stop hook continues into starts from the hook's input", async () => {
+ const hook = answering("clock", "tick");
+ let asked = 0;
+ const once: StopHook = {
+ name: "once",
+ run: async () => (asked++ === 0 ? { decision: "continue", input: "again" } : undefined),
+ };
+ const llm = new ScriptedLLM(replies(2));
+ const session = makeSession({ userPrompt: [hook], stop: [once] }, llm);
+
+ const out = await collect(session.run([userText("start")]));
+
+ expect(hook.seen).toHaveLength(1);
+ expect(llm.calls.map(textsOf)).toEqual([["start", "tick"], ["again"]]);
+ // The continuation is the one input a `continue` event announces.
+ const announced = out.findIndex(isHookContinue);
+ expect(shape(out[announced + 1]!)).toBe("harness:again");
+ });
+
+ describe("across a rotation", () => {
+ const settings: CompactionSettings = {
+ maxContextLength: 100,
+ maxSessionTurns: -1,
+ mode: "summarize",
+ prompt: "COMPACT NOW",
+ };
+ /** Task one fills the context, so its end compacts and opens the next one. */
+ const filling = (): ScriptedLLM =>
+ new ScriptedLLM([
+ [assistantText("answer one"), usage(150, 150)],
+ [assistantText("[summary]so far[/summary]"), usage(160, 310)],
+ ]);
+
+ it("takes the hooks of the context that opened, whole", async () => {
+ const before = answering("before", "old context");
+ const after = answering("after", "new context");
+ const stops: string[] = [];
+ const stop = (name: string): StopHook => ({
+ name,
+ run: async () => {
+ stops.push(name);
+ },
+ });
+ const next = new ScriptedLLM(replies(1));
+ const session = makeSession({ userPrompt: [before], stop: [stop("old-stop")] }, filling(), {
+ compaction: settings,
+ openNextContext: async () => ({ llm: next, hooks: { userPrompt: [after] } }),
+ });
+
+ await collect(session.run([userText("task one")]));
+ // Task one ran under the first context's hooks; by its end the next context is the one
+ // that is running, and it lists no stop hook.
+ expect(before.seen).toHaveLength(1);
+ expect(stops).toEqual([]);
+
+ await collect(session.run([userText("task two")]));
+ expect(before.seen).toHaveLength(1);
+ expect(after.seen.map((i) => i.prompt)).toEqual(["task two"]);
+ expect(textsOf(next.calls[0]!).slice(-2)).toEqual(["task two", "new context"]);
+ });
+
+ it("keeps its hooks when the opened context brings none of its own", async () => {
+ const kept = answering("kept", "still here");
+ const next = new ScriptedLLM(replies(1));
+ const session = makeSession({ userPrompt: [kept] }, filling(), {
+ compaction: settings,
+ openNextContext: async () => ({ llm: next }),
+ });
+
+ await collect(session.run([userText("task one")]));
+ await collect(session.run([userText("task two")]));
+
+ expect(kept.seen.map((i) => i.prompt)).toEqual(["task one", "task two"]);
+ });
+ });
+});
diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.md
index fdecbe6f..ee21e3b9 100644
--- a/packages/docs/content/agent-loop.en.md
+++ b/packages/docs/content/agent-loop.en.md
@@ -14,6 +14,7 @@ The diagram traces one `run` call from entry to return.
```text
session.run(newMessages, { approve, signal })
│ carry-over from a previous interrupt? → prepend to this run's input
+ │ the user's own Prompt? → user_prompt hooks; each context follows it
▼
┌── turn loop (≤ max_turns; default -1 = no cap) ───────────────┐
│ │
@@ -68,10 +69,11 @@ interface RunOptions {
signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
approve?: ApproveFn; // per-tool approval; denies everything when omitted (conservative default)
preToolUse?: PreToolUseFn; // pre-tool-use hook consult, called before approve for each complete tool_call
+ userPrompt?: UserPromptFn; // user-prompt hook consult, called once with the Prompt before the first request
}
```
-The Session fills in `preToolUse` itself from the agent's installed hook packages (see [Pre-tool-use hooks](#pre-tool-use-hooks)).
+The Session fills in `preToolUse` and `userPrompt` itself from the agent's installed hook packages (see [Pre-tool-use hooks](#pre-tool-use-hooks) and [User-prompt hooks](#user-prompt-hooks)).
The generator's return value says how the run ended: `null` when it ran to completion, otherwise a `RunCutoff`:
@@ -127,9 +129,9 @@ A **hook** is a function the Session runs at a fixed point of the loop. Three po
| --- | --- | --- |
| `stop` | The moment a Task ends: the model's final reply with no tool call, or a cutoff — user abort, LLM failure, or the `max_turns` cap | [Stop hooks](#stop-hooks) |
| `pre_tool_use` | Before each tool call's approval | [Pre-tool-use hooks](#pre-tool-use-hooks) |
-| `user_prompt` | When a prompt is submitted | [User-prompt hooks](#user-prompt-hooks) |
+| `user_prompt` | Every time the user submits a prompt, before the Task's first request | [User-prompt hooks](#user-prompt-hooks) |
-The hooks a Session consults are the hook packages installed in the agent's `agent_state/hooks/` directory. A [plugin](/skills#hook-packages) ships such packages, and the Session reads them fresh per Session, like Skills. SDK embedders can also register in-process functions through `SessionConfig.hooks.stop` / `.preToolUse` / `.userPrompt`.
+The hooks a Session consults are the hook packages installed in the agent's `agent_state/hooks/` directory, whether a [plugin](/skills#hook-packages) shipped them or someone wrote them there by hand, the agent included. Like Skills, they are read from disk, together with the `hooks.enabled` switch, each time a model context opens: when the Session is created, after each compaction, and on resume. The new context's hooks replace the old ones whole, so a package written during a conversation is consulted from the next context on. SDK embedders can also register in-process functions through `SessionConfig.hooks.stop` / `.preToolUse` / `.userPrompt`.
An installed hook is a plain Node script, run as a subprocess the way Claude Code runs its command hooks. The script is told only where to look; it derives everything else from the Trace: Token usage, turn counts, how the Task ended, and its own state file. A non-zero exit is a failure, and the tail of stderr becomes the reason. A timeout kills the script; the timeout comes from the manifest's `timeout` field and defaults to 60 s.
@@ -187,16 +189,24 @@ No built-in plugin ships one. The point exists for custom guards: a project-spec
### User-prompt hooks
-The third point, `user_prompt`, expands a submitted prompt. These hooks run in core and nowhere else. The host triggers the point through `Session.runUserPromptHook(name, prompt, extras)` when it accepts a user prompt for the flow that the package owns. The Session supplies its own id and scratchpad directory.
+The third point, `user_prompt`, runs **every time the user submits a prompt**, that is, for a `run` whose input carries text of the user's own: a user text whose `sender` is absent or `"user"`. Input someone else wrote does not fire it: a `server` input such as a scheduled task or a company-mode trigger, a subagent's `parent_agent` input, a stop hook's continuation, a background-task report, or mid-run steering. The engine consults the hooks once, after the Prompt is written to the Trace and before the Task's first request. Packages run in name order, and each package's commands in manifest order.
```text
-stdin { "hook": "user_prompt", "session_id", "scratchpad_dir", "prompt", …host extras (goal: "budget") }
-stdout { "context": "<text appended after the user's message>" }
+stdin { "hook": "user_prompt", "session_id", "trace_path", "scratchpad_dir", "prompt" }
+stdout nothing = nothing to add; otherwise
+ { "context": "<text sent right behind the user's message>" }
+exit non-zero = failure (stderr's tail becomes the reason); a timeout (default 60 s) kills it
```
-The answer's `context` is sent right behind the user's own message as a harness-stamped message, which hosts render as a compact collapsed card. The call returns `null` when the package is not installed or names no `user_prompt` command. It records no `hook` event; the expansion message is the record.
+`prompt` is the user's text with its leading marker blocks, such as `[use_skills]`, stripped; several texts are joined with newlines. `trace_path` is absent for a Session without a Trace.
+
+Each non-empty `context` becomes a user text stamped [`sender: "harness"`](/omni-message#modelmsg-complete-payloads), right behind the user's own message and in hook order. It is yielded onto the stream, written to the Trace right behind the Prompt, and sent with the Prompt in the Task's first request; hosts render it as a compact collapsed card. That message is the record: a hook that succeeds leaves no `hook` event. A hook that fails — it exits non-zero, prints something that is not JSON, times out, or throws — is recorded at the same position as a `hook` event with `hook: "user_prompt"` and the error as its `reason`, and treated as having nothing to add. It never takes the run down.
+
+The scripts run on the hot path of every prompt. Keep them fast, set a tight `timeout` in the manifest, and keep the context short: the model reads it with every prompt.
+
+**Host-triggered commands.** A `user_prompt` command can carry `"trigger": "host"` in `hooks.json`; the default is `"prompt"`. Such a command stays out of the consult above and runs only when a host starts the package's own flow by name, through `Session.runUserPromptHook(name, prompt, extras)`. The Session supplies its own id, Trace path and scratchpad directory, and the host's `extras` join the stdin fields. The call returns the hook's answer, `{}` for an empty one, or `null` when the package is not installed or has no host-triggered command. The host then sends the `context` itself, stamped `sender: "harness"` right behind the user's message, as ordinary Task input; this path records no `hook` event either. An in-process `UserPromptHook` takes the same optional `trigger` field.
-[Goal mode](/goal-mode) is the one shipped use. The goal plugin's `start.mjs` is its `user_prompt` command. The Server asks the Session to run it for `goal: { budget }`; the command writes `GOAL.json` and answers with round 1's protocol message.
+[Goal mode](/goal-mode) is the one shipped `host` use: the goal plugin's `start.mjs` is marked `"trigger": "host"`. The Server runs it through `runUserPromptHook` for `goal: { budget }`, with `budget` added to its stdin; the script writes `GOAL.json` and answers with round 1's protocol message. The prompt that starts a goal is still a prompt the user submitted, so other packages' `user_prompt` hooks run on it as usual, and their contexts follow the goal's protocol message.
## Mid-run steering
@@ -365,6 +375,7 @@ The new context is **assembled from the Agent State as it is at that moment**, e
- `AGENTS.md`;
- the vault;
- the installed Skills' metadata;
+- the installed hook packages, with the `hooks.enabled` switch;
- the Memory indexes;
- the schedule roster;
- the Environment's date.
diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.md
index f923eb3a..b0d0ee45 100644
--- a/packages/docs/content/agent-loop.zh.md
+++ b/packages/docs/content/agent-loop.zh.md
@@ -14,6 +14,7 @@ SDK 唯一的执行入口是 `session.run(newMessages, opts?)`:输入是本次
```text
session.run(newMessages, { approve, signal })
│ carry-over from a previous interrupt? → prepend to this run's input
+ │ the user's own Prompt? → user_prompt hooks; each context follows it
▼
┌── turn loop (≤ max_turns; default -1 = no cap) ───────────────┐
│ │
@@ -68,10 +69,11 @@ interface RunOptions {
signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
approve?: ApproveFn; // per-tool approval; denies everything when omitted (conservative default)
preToolUse?: PreToolUseFn; // pre-tool-use hook consult, called before approve for each complete tool_call
+ userPrompt?: UserPromptFn; // user-prompt hook consult, called once with the Prompt before the first request
}
```
-`preToolUse` 由 Session 根据 Agent 已安装的钩子包自行填入(见 [Pre-tool-use hook](#pre-tool-use-hook))。
+`preToolUse` 与 `userPrompt` 由 Session 根据 Agent 已安装的钩子包自行填入(见 [Pre-tool-use hook](#pre-tool-use-hook) 与 [User-prompt hook](#user-prompt-hook))。
生成器的返回值说明本次运行如何结束:正常跑完为 `null`,否则是一个 `RunCutoff`:
@@ -127,9 +129,9 @@ Task 由若干连续的 Request(轮)组成。每一轮:
| --- | --- | --- |
| `stop` | 一个 Task 结束的那一刻:模型给出不含工具调用的最终答复,或被掐断(用户中断、LLM 失败、达到 `max_turns` 上限) | [Stop hook](#stop-hook) |
| `pre_tool_use` | 每个工具调用审批之前 | [Pre-tool-use hook](#pre-tool-use-hook) |
-| `user_prompt` | 用户提交 Prompt 时 | [User-prompt hook](#user-prompt-hook) |
+| `user_prompt` | 用户每次提交 Prompt 时,在 Task 的首个请求之前 | [User-prompt hook](#user-prompt-hook) |
-Session 咨询的钩子,就是安装在 Agent 的 `agent_state/hooks/` 目录里的钩子包,由[插件](/skills#钩子包)携带,像 Skill 一样每个 Session 都重新读取。SDK 嵌入方也可以经 `SessionConfig.hooks.stop` / `.preToolUse` / `.userPrompt` 注册进程内函数。
+Session 咨询的钩子,就是安装在 Agent 的 `agent_state/hooks/` 目录里的钩子包,无论是[插件](/skills#钩子包)携带的,还是有人(包括 Agent 自己)手写进去的。它们像 Skill 一样,连同 `hooks.enabled` 开关,在每个模型上下文开启时从磁盘读取:创建 Session 时、每次压缩之后,以及恢复时。新上下文的钩子整体替换旧的,因此对话中写入的钩子包从下一个上下文起生效。SDK 嵌入方也可以经 `SessionConfig.hooks.stop` / `.preToolUse` / `.userPrompt` 注册进程内函数。
已安装的钩子是纯 Node 脚本,像 Claude Code 运行 command hook 那样以子进程运行。它只被告知去哪里看,其余一切都由它从 Trace 推导:Token 用量、轮数、Task 的结束方式,以及它自己的状态文件。退出码非零即为失败,stderr 的末尾成为 reason;超时的脚本会被终止,超时时长取清单里的 `timeout`,缺省 60 秒。
@@ -187,16 +189,24 @@ stdout nothing = no opinion; otherwise
### User-prompt hook
-第三个钩子点 `user_prompt` 用来扩展提交的 Prompt。钩子只在 core 里运行:宿主接受某个包所负责流程的用户 Prompt 时,经 `Session.runUserPromptHook(name, prompt, extras)` 触发它,Session 自己补上 id 与 scratchpad 目录。
+第三个钩子点 `user_prompt` 在**用户每次提交 Prompt 时**运行:`run` 的输入含用户本人的文本(`sender` 缺省或为 `"user"` 的 user 文本)即触发。别人写下的输入不触发:定时任务、公司模式触发这类 `server` 输入,子 Agent 收到的 `parent_agent` 输入,stop hook 的续跑输入,后台任务的完成回报,以及运行中插话。引擎在 Prompt 写入 Trace 之后、Task 的首个请求之前咨询一次,钩子包按包名顺序执行,同一个包的命令按清单顺序执行。
```text
-stdin { "hook": "user_prompt", "session_id", "scratchpad_dir", "prompt", …host extras (goal: "budget") }
-stdout { "context": "<text appended after the user's message>" }
+stdin { "hook": "user_prompt", "session_id", "trace_path", "scratchpad_dir", "prompt" }
+stdout nothing = nothing to add; otherwise
+ { "context": "<text sent right behind the user's message>" }
+exit non-zero = failure (stderr's tail becomes the reason); a timeout (default 60 s) kills it
```
-回答里的 `context` 紧随用户自己的消息之后、以 harness 标记发出,渲染为紧凑的折叠卡片。包未安装、或没有声明 `user_prompt` 命令时,调用返回 `null`。这个钩子点不记 `hook` 事件,扩展出的那条消息本身就是记录。
+`prompt` 是用户的文本,开头的标记块(例如 `[use_skills]`)已剥离,多条文本以换行相连。没有 Trace 的 Session 不带 `trace_path`。
+
+每个非空的 `context` 成为一条带 [`sender: "harness"`](/omni-message#modelmsg完整消息) 标记的 user 文本,按钩子顺序紧随用户自己的消息:推到流上,紧随 Prompt 写入 Trace,并与 Prompt 一起在 Task 的首个请求中发出;宿主把它渲染为紧凑的折叠卡片。这条消息本身就是记录,成功的钩子不留 `hook` 事件。钩子失败(退出码非零、打印的不是 JSON、超时或抛错)时,在同一位置记为一条 `hook: "user_prompt"` 的 `hook` 事件,以错误信息为 `reason`,并按无意见处理,永远不会拖垮运行。
+
+脚本跑在每条 Prompt 的热路径上:要轻快,在清单里设置较小的 `timeout`,context 也要简短,因为每条 Prompt 模型都要读它。
+
+**宿主触发的命令。** `user_prompt` 命令可以在 `hooks.json` 里带 `"trigger": "host"`,缺省为 `"prompt"`。这样的命令不参与上述咨询,只在宿主按包名启动该包自己的流程时,经 `Session.runUserPromptHook(name, prompt, extras)` 运行:Session 自己补上 id、Trace 路径与 scratchpad 目录,宿主的 `extras` 并入 stdin 字段。调用返回钩子的回答(空回答为 `{}`);包未安装、或没有宿主触发的命令时返回 `null`。随后由宿主自己把 `context` 以 `sender: "harness"` 标记紧随用户消息、作为普通的 Task 输入发出;这条路径同样不记 `hook` 事件。进程内的 `UserPromptHook` 也有同一个可选字段 `trigger`。
-[目标模式](/goal-mode)的启动是唯一的内置用途:goal 插件的 `start.mjs` 就是它的 `user_prompt` 命令。服务端收到 `goal: { budget }` 时请 Session 运行它,它写下 `GOAL.json`,并以第 1 轮的协议消息作答。
+[目标模式](/goal-mode)是 `host` 的唯一内置用途:goal 插件的 `start.mjs` 标记为 `"trigger": "host"`。服务端收到 `goal: { budget }` 时经 `runUserPromptHook` 运行它,并在 stdin 里附上 `budget`;脚本写下 `GOAL.json`,并以第 1 轮的协议消息作答。启动目标的那条 Prompt 仍是用户提交的 Prompt,因此其他钩子包的 `user_prompt` 钩子照常运行,它们的 context 排在 goal 的协议消息之后。
## 运行中插话
@@ -365,6 +375,7 @@ interface CompactionSettings {
- `AGENTS.md`;
- vault;
- 已装 Skill 的元数据;
+- 已装钩子包,连同 `hooks.enabled` 开关;
- Memory 索引;
- 定时任务名单;
- 环境字段中的日期。
diff --git a/packages/docs/content/configuration.en.md b/packages/docs/content/configuration.en.md
index 7439849f..a289860c 100644
--- a/packages/docs/content/configuration.en.md
+++ b/packages/docs/content/configuration.en.md
@@ -288,7 +288,7 @@ What the policy does buy: a destructive one-liner does not run by accident, thro
| `skills.prompt` | Built-in template | The `{{SKILLS}}` block; carries `{{SKILL_METADATA}}` |
| `schedules.enabled` | `true` | Whether the scheduled-tasks section enters the context |
| `schedules.prompt` | Built-in template | The `{{SCHEDULES}}` block, which teaches 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 |
+| `hooks.enabled` | `true` | Whether the installed hook packages run at the loop's hook points |
| `tools.builtin` | The full default toolset when omitted | Tool entries; once written, replaces the default list wholesale |
| `tools.mcpServers` | `[]` | MCP Server configuration (`name` + `config`) |
diff --git a/packages/docs/content/configuration.zh.md b/packages/docs/content/configuration.zh.md
index b417e8db..830e8e4d 100644
--- a/packages/docs/content/configuration.zh.md
+++ b/packages/docs/content/configuration.zh.md
@@ -288,7 +288,7 @@ enabled = false
| `skills.prompt` | 内置模板 | `{{SKILLS}}` 块;包含 `{{SKILL_METADATA}}` |
| `schedules.enabled` | `true` | 定时任务小节是否进入上下文 |
| `schedules.prompt` | 内置模板 | `{{SCHEDULES}}` 块,讲解基于文件的任务管理;包含 `{{SCHEDULE_LIST}}` |
-| `hooks.enabled` | `true` | 新 Session 是否在循环的钩子点运行已安装的钩子包 |
+| `hooks.enabled` | `true` | 是否在循环的钩子点运行已安装的钩子包 |
| `tools.builtin` | 省略时为完整默认工具集 | 工具条目;一旦写入,就整体替换默认列表 |
| `tools.mcpServers` | `[]` | MCP Server 配置(`name` + `config`) |
diff --git a/packages/docs/content/goal-mode.en.md b/packages/docs/content/goal-mode.en.md
index e2c33ec4..92322a61 100644
--- a/packages/docs/content/goal-mode.en.md
+++ b/packages/docs/content/goal-mode.en.md
@@ -148,17 +148,19 @@ Deleting the Session deletes its scratchpad, and `GOAL.json` with it.
Goal mode is not built into the core. The `goal` plugin is a [hook package](/skills#hook-packages) with two scripts:
-- `start.mjs` is its [`user_prompt` hook](/agent-loop#user-prompt-hooks). It writes the goal file and answers the submitted prompt with round 1's protocol message as its expansion `context`.
+- `start.mjs` is its host-triggered [`user_prompt` hook](/agent-loop#user-prompt-hooks), marked `"trigger": "host"`: it runs when a goal starts, never on an ordinary prompt. It writes the goal file and answers with round 1's protocol message as its expansion `context`.
- `stop.mjs` is a [stop hook](/agent-loop#stop-hooks). After every Task it reads the Session's Trace and answers `continue` with the next round's message, or `stop`.
Nothing in the core SDK knows what a goal is. The loop that consults hooks is generic.
### Starting a goal
-The server asks the Session to run the goal package's `user_prompt` hook: the installed `agent_state/hooks/goal/start.mjs`, which receives `{ hook: "user_prompt", session_id, scratchpad_dir, prompt, budget }` on stdin. The server then starts the goal run with your message exactly as typed, followed by the `{ context }` the script prints, stamped `sender: "harness"`. The stop hook takes it from there.
+The server asks the Session to run the goal package's host-triggered `user_prompt` command through `Session.runUserPromptHook("goal", prompt, { budget })`: the installed `agent_state/hooks/goal/start.mjs`, which receives `{ hook: "user_prompt", session_id, trace_path, scratchpad_dir, prompt, budget }` on stdin. The server then starts the goal run with your message exactly as typed, followed by the `{ context }` the script prints, stamped `sender: "harness"`. The stop hook takes it from there.
In the SDK, a goal is therefore a plain `session.run` on an agent with the plugin installed. You start it by writing the goal file the same way: call `Session.runUserPromptHook("goal", …)`, or run the script directly.
+The prompt that starts a goal is still a prompt you submitted, so other packages' `user_prompt` hooks run on it as on any other. Their contexts follow the goal's protocol message, and none of them counts as a round: a round starts only with round 1's protocol message or with the input a stop hook's `continue` injects.
+
### Counting and recording
For each round, the hook adds `request.total − cache_read` from every `token_usage` record since the round's harness-injected input.
diff --git a/packages/docs/content/goal-mode.zh.md b/packages/docs/content/goal-mode.zh.md
index 5c6c5cfa..6cbca4e6 100644
--- a/packages/docs/content/goal-mode.zh.md
+++ b/packages/docs/content/goal-mode.zh.md
@@ -148,17 +148,19 @@ Task 结束后,stop 钩子读取 Trace 和目标文件,按下面的顺序逐
目标模式并不内置在核心里。`goal` 插件是一个[钩子包](/skills#钩子包),包含两个脚本:
-- `start.mjs` 是它的 [`user_prompt` 钩子](/agent-loop#user-prompt-hook):写入目标文件,并以第 1 轮的协议消息作为扩展 `context`,应答提交的 Prompt。
+- `start.mjs` 是它由宿主触发的 [`user_prompt` 钩子](/agent-loop#user-prompt-hook),标记为 `"trigger": "host"`:只在目标启动时运行,普通的 Prompt 不会触发它。它写入目标文件,并以第 1 轮的协议消息作为扩展 `context` 作答。
- `stop.mjs` 是一个 [stop 钩子](/agent-loop#stop-hook):每个 Task 结束后读取 Session 的 Trace,应答 `continue` 并附上下一轮的消息,或者应答 `stop`。
核心 SDK 完全不知道目标是什么,询问钩子的那个循环是通用的。
### 启动流程
-服务端让 Session 运行 goal 包的 `user_prompt` 钩子,也就是已安装的 `agent_state/hooks/goal/start.mjs`,脚本从 stdin 收到 `{ hook: "user_prompt", session_id, scratchpad_dir, prompt, budget }`。随后服务端启动目标运行:先原样发送你输入的消息,再发送脚本打印的 `{ context }`,这条消息带 `sender: "harness"` 标记。之后由 stop 钩子接手。
+服务端经 `Session.runUserPromptHook("goal", prompt, { budget })` 让 Session 运行 goal 包由宿主触发的 `user_prompt` 命令,也就是已安装的 `agent_state/hooks/goal/start.mjs`,脚本从 stdin 收到 `{ hook: "user_prompt", session_id, trace_path, scratchpad_dir, prompt, budget }`。随后服务端启动目标运行:先原样发送你输入的消息,再发送脚本打印的 `{ context }`,这条消息带 `sender: "harness"` 标记。之后由 stop 钩子接手。
因此在 SDK 里,目标就是装了插件的 Agent 上一次普通的 `session.run`,启动时用同样的方式写好目标文件:调用 `Session.runUserPromptHook("goal", …)`,或者直接运行脚本。
+启动目标的那条 Prompt 仍是你提交的 Prompt,所以其他钩子包的 `user_prompt` 钩子照常在它上面运行。它们的 context 排在 goal 的协议消息之后,都不算作一轮:轮次只从第 1 轮的协议消息、或 stop 钩子 `continue` 注入的输入开始。
+
### 计数与记录
每一轮,钩子把自本轮 harness 注入的输入以来每条 `token_usage` 记录的 `request.total − cache_read` 累加起来。
diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.md
index a5e0fd07..c518d303 100644
--- a/packages/docs/content/interfaces.en.md
+++ b/packages/docs/content/interfaces.en.md
@@ -77,6 +77,7 @@ interface RunOptions {
signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
approve?: ApproveFn; // per-tool approval; denies everything when omitted
preToolUse?: PreToolUseFn; // pre-tool-use hook consult; the Session wires it from installed hook packages
+ userPrompt?: UserPromptFn; // user-prompt hook consult; the Session wires it from installed hook packages
}
interface RunCutoff { // how a run was cut off early
diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.md
index f1a57d3c..a6c95975 100644
--- a/packages/docs/content/interfaces.zh.md
+++ b/packages/docs/content/interfaces.zh.md
@@ -77,6 +77,7 @@ interface RunOptions {
signal?: AbortSignal; // interrupt (e.g. Ctrl-C)
approve?: ApproveFn; // per-tool approval; denies everything when omitted
preToolUse?: PreToolUseFn; // pre-tool-use hook consult; the Session wires it from installed hook packages
+ userPrompt?: UserPromptFn; // user-prompt hook consult; the Session wires it from installed hook packages
}
interface RunCutoff { // how a run was cut off early
diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.md
index 511de66d..8d9f2854 100644
--- a/packages/docs/content/omni-message.en.md
+++ b/packages/docs/content/omni-message.en.md
@@ -129,7 +129,7 @@ interface InlineDataPayload {
}
```
-`sender` separates the human user (`user`) from the parent agent driving a subagent (`parent_agent`), the harness's automatic injections such as background-task completion reports and hook continues (`harness`), and the server's own triggers such as scheduled tasks (`server`). It is never sent to the provider.
+`sender` separates the human user (`user`) from the parent agent driving a subagent (`parent_agent`), the harness's automatic injections such as background-task completion reports, stop-hook continues and user-prompt hook contexts (`harness`), and the server's own triggers such as scheduled tasks (`server`). It is never sent to the provider.
`tool_call` and `tool_call_output` pair strictly via `tool_call_id`. The calls of a turn form one batch, and outputs are re-fed in the original call order (see [The Agent Loop](/agent-loop)).
@@ -356,7 +356,8 @@ interface SubagentPayload {
interface HookPayload {
type: "hook";
- hook: "stop" | "pre_tool_use"; // the hook point that fired (see the agent loop's hooks)
+ hook: "stop" | "pre_tool_use" // the hook point that fired (see the agent loop's hooks)
+ | "user_prompt"; // user_prompt: only for a hook that failed
name: string; // the hook's name: "goal", "continual-learning", …
decision?: "continue" | "stop" // stop point
| "allow" | "deny"; // pre_tool_use point; absent when the hook only left a record
diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.md
index 2ac10dd1..260381c6 100644
--- a/packages/docs/content/omni-message.zh.md
+++ b/packages/docs/content/omni-message.zh.md
@@ -129,7 +129,7 @@ interface InlineDataPayload {
}
```
-`sender` 区分 user 角色文本的来源:真人用户(`user`)、驱动子 Agent 的父 Agent(`parent_agent`)、harness 的自动注入(`harness`,例如后台任务的完成回报和钩子 `continue` 注入的输入),以及 Server 自己的触发(`server`,例如定时任务)。这个字段不会发给供应商。
+`sender` 区分 user 角色文本的来源:真人用户(`user`)、驱动子 Agent 的父 Agent(`parent_agent`)、harness 的自动注入(`harness`,例如后台任务的完成回报、stop 钩子 `continue` 注入的输入,以及 `user_prompt` 钩子补充的 context),以及 Server 自己的触发(`server`,例如定时任务)。这个字段不会发给供应商。
`tool_call` 与 `tool_call_output` 通过 `tool_call_id` 严格配对。一轮内的调用构成一个批次,输出按原始调用顺序回填(见 [Agent 运行循环](/agent-loop))。
@@ -356,7 +356,8 @@ interface SubagentPayload {
interface HookPayload {
type: "hook";
- hook: "stop" | "pre_tool_use"; // the hook point that fired (see the agent loop's hooks)
+ hook: "stop" | "pre_tool_use" // the hook point that fired (see the agent loop's hooks)
+ | "user_prompt"; // user_prompt: only for a hook that failed
name: string; // the hook's name: "goal", "continual-learning", …
decision?: "continue" | "stop" // stop point
| "allow" | "deny"; // pre_tool_use point; absent when the hook only left a record
diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.md
index 84f57dfb..89468358 100644
--- a/packages/docs/content/sessions-and-traces.en.md
+++ b/packages/docs/content/sessions-and-traces.en.md
@@ -70,6 +70,7 @@ See `packages/core/src/trace/writer.ts` for the implementation.
An illustrative Trace head follows, one OmniMessage envelope per line. Note the order:
- The user's input is written before the `request_begin` it is sent with.
+- What the [user-prompt hooks](/agent-loop#user-prompt-hooks) answer follows the user's input directly: a harness-stamped user text per context, or a `hook` event for a hook that failed.
- On the first run, the toolset follows the input as a `tool_list_ready` event, after an `mcp_connect_begin` / `mcp_connect_end` pair when MCP servers are configured. `session_meta` does not carry the tool definitions.
```jsonl
diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.md
index 4255b99c..8e215f24 100644
--- a/packages/docs/content/sessions-and-traces.zh.md
+++ b/packages/docs/content/sessions-and-traces.zh.md
@@ -70,6 +70,7 @@ Trace 是只追加的 JSON Lines 文件,每行是一个 OmniMessage 信封,
下面是一个示意性的 Trace 开头,每行一个 OmniMessage 信封。注意顺序:
- 用户输入先写入,之后才是与它一起发送的 `request_begin`。
+- [User-prompt hook](/agent-loop#user-prompt-hook) 的回答紧跟在用户输入之后:每个 context 一条带 harness 标记的 user 文本,失败的钩子则是一条 `hook` 事件。
- 首次运行时,工具集以 `tool_list_ready` 事件跟在输入之后;如果配置了 MCP Server,在这之前还有一对 `mcp_connect_begin` / `mcp_connect_end`。`session_meta` 不携带工具定义。
```jsonl
diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.md
index 6a6ca350..3144e361 100644
--- a/packages/docs/content/skills.en.md
+++ b/packages/docs/content/skills.en.md
@@ -37,7 +37,7 @@ The buttons on the right of a card:
1. On the **Plugins** page, select **Manage installs** on the plugin's card. The dialog lists every agent in the current Project.
2. Next to the agent, select **Install**.
-The whole plugin is installed: all of its Skills and its hook package. New conversations pick it up right away; running ones pick it up after their next compaction.
+The whole plugin is installed: all of its Skills and its hook package. New conversations pick it up right away. In a conversation already open, the hook package applies from the next turn and the Skills after the next compaction.
To uninstall a plugin, point at **Installed** next to the agent, select **Uninstall**, and confirm. Uninstalling deletes the installed Skill and hook files, including any local edits.
@@ -114,11 +114,15 @@ A zip file can be up to 14 MB, with at most 200 files, 5 MB per file and 20 MB i
## Hook packages
-A hook package runs scripts at the agent loop's [hook points](/agent-loop#stop-hooks): when you send a message, before a tool call, and when a Task ends. For example, the `goal` plugin's hook package drives [goal mode](/goal-mode). Hook packages usually come with a plugin from the library.
+A hook package runs scripts at the agent loop's [hook points](/agent-loop#hooks): every time you send a message, before a tool call, and when a Task ends. For example, the `goal` plugin's hook package drives [goal mode](/goal-mode).
+
+Hook packages usually come with a plugin from the library, but any directory under the agent's `agent_state/hooks/<name>/` that carries a `hooks.json` is one: installed from the library, imported from a zip, or written by hand, by you or by the agent itself. The directory name is the package name, and a hand-written manifest is read tolerantly; see [Hook package manifest](#hook-package-manifest).
+
+A conversation reads the installed packages each time it opens a model context: when it starts, after each compaction, and when it resumes. A package written into the directory therefore runs in new conversations at once, and in a conversation already open from its next compaction. An install, zip import or uninstall through the Web App or the API reaches open conversations sooner, from their next turn, because the server rebuilds the agent's runtimes once they are idle.
To manage one agent's hook packages, open **Agents**, select the agent, and open the **Hooks** tab.
-- **Enable hooks** turns hooks on or off for the whole agent, not one package at a time. With it on, every Session the agent starts runs all installed hook packages. With it off, new Sessions run no hooks, and the packages stay installed. The change takes effect from the next turn; a Task that is already running keeps the setting it started with. Only the Project owner can change this switch.
+- **Enable hooks** turns hooks on or off for the whole agent, not one package at a time. With it on, every Session the agent starts runs all installed hook packages. With it off, no Session runs hooks, and the packages stay installed. The change takes effect from the next turn, in open conversations too; a Task that is already running keeps its hooks unless a compaction opens a new context before the Task ends. Only the Project owner can change this switch.
- Each row shows a package's name, the hook points it runs at, its description and version, with **Export** and **Uninstall**.
### Import a hook package
@@ -231,7 +235,7 @@ plugins/<plugin>/
| `version` | `YYYY.MM.DD.N`: the date plus a sequence number for that day |
| `category` | One of `office-productivity`, `software-development`, `ai-app-development`, `agent-company`; a missing or unknown category lands in "Other" |
| `preinstall` | Optional; `false` keeps the plugin out of `default_agent`'s preinstalled set, so it is installed only manually from the library |
-| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | The hook package's commands per [hook point](/agent-loop#stop-hooks): `[{ "command": "stop.mjs", "timeout": 60 }]`, paths relative to `hooks/`, timeout in seconds |
+| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | The hook package's commands per [hook point](/agent-loop#stop-hooks): `[{ "command": "stop.mjs", "timeout": 60 }]`, paths relative to `hooks/`, timeout in seconds. A `user_prompt` command may add `"trigger"`: `"prompt"` (the default) runs it on every prompt the user submits, `"host"` only when a host starts the package's flow by name |
### Plugin naming and versioning
@@ -265,16 +269,26 @@ An installed hook package is the plugin's `hooks/` directory, installed as `agen
"name": "goal",
"description": "Goal mode: …",
"description_zh": "目标模式:…",
- "version": "2026.09.01.1",
+ "version": "2026.09.29.1",
"stop": [{ "command": "stop.mjs", "timeout": 60 }],
"pre_tool_use": [],
- "user_prompt": [{ "command": "start.mjs", "timeout": 60 }]
+ "user_prompt": [{ "command": "start.mjs", "timeout": 60, "trigger": "host" }]
}
```
The scripts are plain Node that uses only built-in modules, so they run wherever the harness runs. Each runs as a subprocess that reads JSON on stdin and writes a JSON answer to stdout; [The Agent Loop](/agent-loop#stop-hooks) describes the contract. Every top-level Session of the agent consults the installed hook packages at the loop's hook points. The `hooks.enabled` key in the agent's `system_config.yaml` holds the **Enable hooks** switch; when the key is absent, hooks are on.
-A hook package's other scripts are for the host to call by convention. For example, the `goal` plugin's `start.mjs` is what the server runs when a user starts a goal; see [Goal Mode](/goal-mode).
+A `user_prompt` command runs on every prompt the user submits unless it carries `"trigger": "host"`. A host-triggered command runs only when a host starts the package's own flow by name, through `Session.runUserPromptHook`. The `goal` plugin's `start.mjs` is one: the server runs it when a user starts a goal. See [User-prompt hooks](/agent-loop#user-prompt-hooks) and [Goal Mode](/goal-mode).
+
+A package is not only what an installer writes, so a manifest is read tolerantly:
+
+- A hook point the manifest leaves out has no commands, the same as `[]`.
+- An entry without a string `command`, or whose command resolves outside the package directory, is dropped. A `timeout` that is not a positive number falls back to the default, and so does a `trigger` other than `"prompt"` or `"host"`.
+- Display fields that are not strings read as empty, and the directory name is the package name whatever `name` says.
+- A directory whose `hooks.json` is missing or is not a JSON object is not a hook package.
+
+> [!NOTE]
+> A manifest whose `version` is a plugin version older than `2026.09.29.1` predates `user_prompt` commands running on every prompt, so its `user_prompt` commands that name no `trigger` are read as `"host"`. This keeps a `goal` package installed before then from starting a goal on every message; [updating the plugin](#update-installed-plugins) replaces it. When you edit such a package by hand, give each `user_prompt` command an explicit `trigger`, or raise the `version` when the commands should run on every prompt. This reading is kept until 0.3.0.
### Progressive loading
@@ -292,5 +306,5 @@ Installed Skills live under `agent_state/skills/<name>/`, and hook packages unde
- Installing a hook package writes `hooks.json`, the plugin's `icon.svg`, and every file under the plugin's `hooks/`.
- Each install replaces the whole directory, so reinstalling drops files a newer version no longer ships. Reinstalling is how an installed copy is updated.
- Uninstalling deletes the whole `skills/<name>/` or `hooks/<name>/` directory.
-- A running Session keeps the hook packages it was built with. After a hook package is installed or removed, or the **Enable hooks** switch changes, the server rebuilds the agent's cached runtimes the next time they are idle.
+- A running Session keeps the hook packages its current model context opened with; the next context, after a compaction or on resume, reads them again. After a hook package is installed, imported or removed through the Web App or the API, or the **Enable hooks** switch changes, the server rebuilds the agent's cached runtimes the next time they are idle, so open conversations pick up the change from their next turn.
- Besides the Web App, plugins can be installed through the SDK.
diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.md
index 264738c8..c6242035 100644
--- a/packages/docs/content/skills.zh.md
+++ b/packages/docs/content/skills.zh.md
@@ -37,7 +37,7 @@ description: 浏览插件,为 Agent 安装 Skill 和钩子包,为 Project
1. 在**插件市场**页面,点击插件卡片上的**管理安装**。对话框会列出当前 Project 里的所有 Agent。
2. 在 Agent 旁边点击**安装**。
-安装的是整个插件:包括全部 Skill 和钩子包。新对话立即生效;正在运行的对话在下一次压缩后生效。
+安装的是整个插件:包括全部 Skill 和钩子包。新对话立即生效。已经打开的对话里,钩子包从下一轮起生效,Skill 在下一次压缩后生效。
卸载插件:把鼠标移到 Agent 旁的**已安装**上,点击**卸载**并确认。卸载会删除已安装的 Skill 和钩子文件,包括本地做过的修改。
@@ -114,11 +114,15 @@ zip 文件最大 14 MB,最多 200 个文件;解压后单个文件不超过 5
## 钩子包
-钩子包在 Agent 循环的[钩子点](/agent-loop#stop-hook)运行脚本:你发送消息时、工具调用之前,以及 Task 结束时。比如[目标模式](/goal-mode)就由 `goal` 插件的钩子包驱动。钩子包通常随插件库里的插件一起安装。
+钩子包在 Agent 循环的[钩子点](/agent-loop#钩子)运行脚本:你每次发送消息时、工具调用之前,以及 Task 结束时。比如[目标模式](/goal-mode)就由 `goal` 插件的钩子包驱动。
+
+钩子包通常随插件库里的插件一起安装,但 Agent 的 `agent_state/hooks/<name>/` 下任何带 `hooks.json` 的目录都是钩子包:从插件库安装的、从 zip 导入的,或者由你或 Agent 自己手写的。目录名就是包名,手写的清单会被宽容地读取,见[钩子包清单](#钩子包清单)。
+
+对话在每次开启模型上下文时读取已安装的钩子包:开始时、每次压缩之后,以及恢复时。因此写进目录的钩子包在新对话里立即生效,在已经打开的对话里从下一次压缩起生效。经 Web App 或 API 安装、导入 zip 或卸载时,已经打开的对话生效得更早,从下一轮开始,因为服务端会在 Agent 的运行时空闲时重建它们。
要管理某个 Agent 的钩子包,打开**智能体**,选中这个 Agent,然后打开**钩子**标签页。
-- **启用钩子**是整个 Agent 的钩子总开关,不能按包单独开关。开启时,这个 Agent 启动的每个 Session 都会运行全部已安装的钩子包;关闭时,新 Session 不运行任何钩子,已安装的包仍然保留。改动从下一轮开始生效,已经在运行的 Task 沿用它开始时的设置。只有 Project owner 能改这个开关。
+- **启用钩子**是整个 Agent 的钩子总开关,不能按包单独开关。开启时,这个 Agent 启动的每个 Session 都会运行全部已安装的钩子包;关闭时,任何 Session 都不运行钩子,已安装的包仍然保留。改动从下一轮开始生效,已经打开的对话也是如此;已经在运行的 Task 沿用它的钩子,除非 Task 结束之前压缩开启了新的上下文。只有 Project owner 能改这个开关。
- 每行显示包的名称、运行的钩子点、描述和版本,附**打包导出**和**卸载**两个操作。
### 导入钩子包
@@ -231,7 +235,7 @@ plugins/<plugin>/
| `version` | `YYYY.MM.DD.N`:日期加当天的序号 |
| `category` | `office-productivity`、`software-development`、`ai-app-development`、`agent-company` 之一;缺失或未知的分类归入「其他」 |
| `preinstall` | 可选;设为 `false` 的插件不进入 `default_agent` 的预装集合,只能从插件库手动安装 |
-| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | 钩子包在各个[钩子点](/agent-loop#stop-hook)运行的命令:`[{ "command": "stop.mjs", "timeout": 60 }]`,路径以 `hooks/` 为起点,timeout 单位为秒 |
+| `hooks.stop` / `hooks.pre_tool_use` / `hooks.user_prompt` | 钩子包在各个[钩子点](/agent-loop#stop-hook)运行的命令:`[{ "command": "stop.mjs", "timeout": 60 }]`,路径以 `hooks/` 为起点,timeout 单位为秒。`user_prompt` 命令可以另加 `"trigger"`:`"prompt"`(缺省)表示用户每次提交 Prompt 时运行,`"host"` 表示只在宿主按包名启动该包的流程时运行 |
### 插件命名与版本
@@ -265,16 +269,26 @@ Skill 的目录名是权威名称,必须匹配 `^[A-Za-z0-9_-]+$`,并覆盖
"name": "goal",
"description": "Goal mode: …",
"description_zh": "目标模式:…",
- "version": "2026.09.01.1",
+ "version": "2026.09.29.1",
"stop": [{ "command": "stop.mjs", "timeout": 60 }],
"pre_tool_use": [],
- "user_prompt": [{ "command": "start.mjs", "timeout": 60 }]
+ "user_prompt": [{ "command": "start.mjs", "timeout": 60, "trigger": "host" }]
}
```
脚本是只用内置模块的纯 Node 代码,harness 能运行的地方它们就能运行。每个脚本以子进程方式运行:从 stdin 读取 JSON,向 stdout 写回 JSON 应答;[Agent 循环](/agent-loop#stop-hook)描述了这套约定。Agent 的每个顶层 Session 都会在循环的各个钩子点查询已安装的钩子包。**启用钩子**开关保存在 Agent 的 `system_config.yaml` 的 `hooks.enabled` 键里;这个键不存在时,钩子处于开启状态。
-钩子包的其他脚本供宿主按约定调用。例如,用户发起目标时,服务端运行的就是 `goal` 插件的 `start.mjs`;参见[目标模式](/goal-mode)。
+`user_prompt` 命令在用户每次提交 Prompt 时运行,除非它带 `"trigger": "host"`。宿主触发的命令只在宿主按包名启动该包自己的流程时,经 `Session.runUserPromptHook` 运行。`goal` 插件的 `start.mjs` 就是这样的命令:用户发起目标时由服务端运行它。参见 [User-prompt hook](/agent-loop#user-prompt-hook) 与[目标模式](/goal-mode)。
+
+钩子包不只来自安装器,因此清单的读取是宽容的:
+
+- 清单没有列出的钩子点没有命令,等同于 `[]`。
+- 没有字符串 `command` 的条目、或命令解析到包目录之外的条目会被丢弃。不是正数的 `timeout` 取缺省值,`"prompt"`、`"host"` 之外的 `trigger` 同样取缺省值。
+- 不是字符串的展示字段读作空值;无论 `name` 写的是什么,目录名都是包名。
+- `hooks.json` 缺失或不是 JSON 对象的目录不算钩子包。
+
+> [!NOTE]
+> 清单的 `version` 若是早于 `2026.09.29.1` 的插件版本,说明它写于 `user_prompt` 命令在每条 Prompt 上运行之前,因此其中没有写 `trigger` 的 `user_prompt` 命令一律按 `"host"` 读取。这样,在那之前安装的 `goal` 包不会在每条消息上都启动一次目标;[更新插件](#更新已安装的插件)即可替换它。手工修改这样的包时,给每条 `user_prompt` 命令写上明确的 `trigger`;要让这些命令在每条 Prompt 上运行,则提高 `version`。这一读法保留到 0.3.0。
### 渐进加载
@@ -292,5 +306,5 @@ Skill 分两步加载:先加载索引,正文按需读取。
- 安装钩子包时,会写入 `hooks.json`、插件的 `icon.svg`,以及插件 `hooks/` 目录下的所有文件。
- 每次安装都会整体替换目录,所以重新安装会清掉新版本不再包含的文件。已安装的副本就是靠重新安装来更新的。
- 卸载会删除整个 `skills/<name>/` 或 `hooks/<name>/` 目录。
-- 运行中的 Session 沿用创建时加载的钩子包。安装或卸载钩子包、或者**启用钩子**开关变动之后,服务端会在 Agent 缓存的运行时下次空闲时重建它们。
+- 运行中的 Session 沿用当前模型上下文开启时读到的钩子包;下一个上下文(压缩之后或恢复时)会重新读取。经 Web App 或 API 安装、导入或卸载钩子包,或者**启用钩子**开关变动之后,服务端会在 Agent 缓存的运行时下次空闲时重建它们,因此已经打开的对话从下一轮起生效。
- 除 Web App 外,插件也可以通过 SDK 安装。
diff --git a/packages/server/src/http/routes/agent-config.ts b/packages/server/src/http/routes/agent-config.ts
index ef764c88..244b7792 100644
--- a/packages/server/src/http/routes/agent-config.ts
+++ b/packages/server/src/http/routes/agent-config.ts
@@ -66,8 +66,9 @@ export function agentConfigRoutes(deps: AgentConfigRouteDeps): 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.
+ // context itself, the hook switch included. The switch is still the exception: its
+ // saved feedback promises the next turn, and a conversation that is running would
+ // otherwise keep its hooks until its next compaction.
if (req.config?.hooks !== undefined) {
deps.manager.invalidateAgentRuntimes(projectId, agentId);
}
@@ -165,7 +166,8 @@ export function agentConfigRoutes(deps: AgentConfigRouteDeps): Hono<AppEnv> {
deps.access.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).
+ // runtimes are rebuilt for the same reason a switch write rebuilds them (see the PUT
+ // above).
deps.manager.invalidateAgentRuntimes(projectId, agentId);
const view = await deps.agentConfigService.getConfig(projectId, agentId);
return c.json({
diff --git a/packages/server/src/http/routes/hooks.ts b/packages/server/src/http/routes/hooks.ts
index 6945f5c0..da02b562 100644
--- a/packages/server/src/http/routes/hooks.ts
+++ b/packages/server/src/http/routes/hooks.ts
@@ -11,9 +11,10 @@
* 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.
+ * invalidates the Agent's cached runtimes: core reads hook packages when a model context
+ * opens, so a conversation that is running would otherwise keep the old set until its next
+ * compaction. Rebuilding the runtime re-reads them on the next Task instead — which is what
+ * lets a package installed from this page start a goal in the conversation already open.
*/
import fs from "node:fs/promises";
import path from "node:path";
@@ -114,6 +115,9 @@ function normalizeHookManifest(
if (cmd.timeout !== undefined && !(typeof cmd.timeout === "number" && cmd.timeout > 0)) {
throw badRequest(`hooks.json ${point} timeout must be a positive number of seconds.`);
}
+ if (cmd.trigger !== undefined && cmd.trigger !== "prompt" && cmd.trigger !== "host") {
+ throw badRequest(`hooks.json ${point} trigger must be "prompt" or "host".`);
+ }
commands += 1;
}
lists[point] = list as HookCommand[];
diff --git a/packages/server/src/http/routes/plugins.ts b/packages/server/src/http/routes/plugins.ts
index e2321eef..d543579e 100644
--- a/packages/server/src/http/routes/plugins.ts
+++ b/packages/server/src/http/routes/plugins.ts
@@ -105,9 +105,9 @@ export function agentPluginsRoutes(deps: PluginsRouteDeps): Hono<AppEnv> {
for (const plugin of plugins) {
await installPlugin(deps.config.root, projectId, agentId, plugin);
}
- // Hook packages are bound when a core Session is built (skills are read from disk on
- // demand, hooks are not): a runtime cached for this Agent would keep running the old
- // set — or none — until it was evicted, so its next idle access re-resumes it.
+ // Core reads hook packages when a model context opens: a conversation that is running
+ // would keep the old set — or none — until its next compaction. Rebuilding the runtime
+ // re-reads them on its next idle access, so the plugin works from the next Task.
deps.manager.invalidateAgentRuntimes(projectId, agentId);
const [skills, hooks] = await Promise.all([
listInstalledSkills(deps.config.root, projectId, agentId),
diff --git a/packages/server/src/runtime/goal-events.ts b/packages/server/src/runtime/goal-events.ts
index 54ae9c31..8062a86c 100644
--- a/packages/server/src/runtime/goal-events.ts
+++ b/packages/server/src/runtime/goal-events.ts
@@ -3,7 +3,8 @@
* event named `goal` whose `output` carries the goal file's state (status, round, tokens_used,
* budget). The manager maps them to goal_round / goal_finished server events; the CLI reads
* those server events rather than the hook events, so this is the only place the plugin's
- * record shape is interpreted. Round boundaries are core's `isHookInput`.
+ * record shape is interpreted. Round boundaries are core's: an `isHookInput` that an
+ * `isHookContinue` event announced.
*/
import { isEventMessage } from "@prismshadow/penguin-core";
import type { OmniMessage } from "@prismshadow/penguin-core";
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index 986a2416..13ce10f7 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -36,6 +36,7 @@ import path from "node:path";
import {
createAgent,
findLatestTraceFile,
+ isHookContinue,
isHookInput,
isSessionMeta,
parseUserSteeringText,
@@ -1130,7 +1131,9 @@ export class SessionManager {
* Taps a goal run's stream for `drive`: round boundaries become goal_round events —
* round 1 from the seeded input (core never yields a run's initial input, so it is
* counted here, where startGoal published it), later rounds from the stop-hook continues
- * core yields — and the goal hook's `stop` event becomes the
+ * core yields, each announced by the hook's `continue` event; a harness-stamped input
+ * nothing announced is another package's user_prompt context riding behind the
+ * objective, not a round — and the goal hook's `stop` event becomes the
* goal_finished server event. `used` is what the hook last recorded in its event's
* `output` — the same number its budget check used — so the UI never shows a different
* figure. A stream that ends without the hook's terminal event (a cut-off run, an
@@ -1165,9 +1168,13 @@ export class SessionManager {
});
}
}
+ // Set by a stop hook's `continue` event, spent by the input that follows it.
+ let continued = false;
try {
for await (const msg of gen) {
- if (isHookInput(msg)) {
+ if (isHookContinue(msg)) continued = true;
+ if (continued && isHookInput(msg)) {
+ continued = false;
round++;
this.publishEvent(entry, {
type: "goal_round",
diff --git a/packages/server/test/goals.test.ts b/packages/server/test/goals.test.ts
index be7d36a3..0df07c79 100644
--- a/packages/server/test/goals.test.ts
+++ b/packages/server/test/goals.test.ts
@@ -1,18 +1,33 @@
/**
- * Goal-mode server tests: SessionManager.startGoal running the goal plugin's user_prompt hook
- * on a fake Session (no real LLM requests, no scripts) and driving one `session.run` — the
- * round and terminal server events derived from the stream's harness-injected inputs and
- * goal hook events.
+ * Goal-mode server tests.
+ *
+ * - SessionManager.startGoal running the goal plugin's user_prompt hook on a fake Session
+ * (no real LLM requests, no scripts) and driving one `session.run` — the round and
+ * terminal server events derived from the stream's harness-injected inputs and goal hook
+ * events.
+ * - A real core Session that runs the installed scripts against a loopback model endpoint,
+ * with a hand-written every-prompt package beside the goal package: on a goal start that
+ * package's context rides round 1 without counting as a round, and an ordinary Task starts
+ * no goal — for the goal package the library ships and for one installed before
+ * user_prompt commands ran on every Prompt.
*/
+import fs from "node:fs/promises";
+import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { wire } from "@prismshadow/penguin-core/kernel";
import type { DatabaseSync } from "node:sqlite";
import {
assistantText,
buildSkillsMessage,
+ createAgent,
emptyTokenCounts,
hookEvent,
+ hooksDir,
imageUrlMessage,
+ installPlugin,
+ libraryPlugin,
+ saveProjectConfig,
+ sessionScratchpadDir,
tokenUsage,
userText,
} from "@prismshadow/penguin-core";
@@ -22,10 +37,19 @@ import { SessionsRepo } from "../src/db/repos/sessions.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
import { ChannelHub } from "../src/runtime/channel.js";
import type { ChannelEvent } from "../src/runtime/channel.js";
-import { SessionManager } from "../src/runtime/session-manager.js";
+import { SessionManager, createCoreSessionLoader } from "../src/runtime/session-manager.js";
import type { RuntimeSession } from "../src/runtime/session-manager.js";
import { SessionSources } from "../src/runtime/session-sources.js";
-import { waitFor } from "./helpers.js";
+import { makeTempRoot, waitFor } from "./helpers.js";
+import {
+ MOCK_MODEL_ID,
+ clockContext,
+ requestText,
+ startMockLLM,
+ userTexts,
+ writeClockPackage,
+} from "./live-session.js";
+import type { MockLLM } from "./live-session.js";
const ROW: SessionRow = {
sessionId: "session-1",
@@ -65,6 +89,12 @@ function goalHook(
});
}
+function serverEvents(events: ChannelEvent[]) {
+ return events
+ .filter((e) => e.event === "server_event")
+ .map((e) => JSON.parse(e.data) as { type: string; [k: string]: unknown });
+}
+
describe("SessionManager.startGoal", () => {
let db: DatabaseSync;
let sessions: SessionsRepo;
@@ -134,12 +164,6 @@ describe("SessionManager.startGoal", () => {
});
}
- function serverEvents(events: ChannelEvent[]) {
- return events
- .filter((e) => e.event === "server_event")
- .map((e) => JSON.parse(e.data) as { type: string; [k: string]: unknown });
- }
-
it("drives one goal-mode run, mapping the round inputs and the hook's answers to goal events", async () => {
const text = buildSkillsMessage(["web-design"], "make it work");
const session = goalFakeSession(() => [
@@ -351,3 +375,172 @@ describe("SessionManager.startGoal", () => {
expect(emptyTokenCounts().total).toBe(0);
});
});
+
+/**
+ * The goal package as the library installed it before user_prompt commands ran on every
+ * Prompt: an older version, and no `trigger` on start.mjs.
+ */
+const LEGACY_GOAL_MANIFEST = {
+ name: "goal",
+ description: "Goal mode",
+ version: "2026.09.01.1",
+ stop: [{ command: "stop.mjs", timeout: 60 }],
+ pre_tool_use: [],
+ user_prompt: [{ command: "start.mjs", timeout: 60 }],
+};
+
+for (const { installed, legacy } of [
+ { installed: "the goal package the library ships", legacy: false },
+ { installed: "a goal package from before user_prompt ran on every prompt", legacy: true },
+]) {
+ describe(
+ `a real Session with ${installed} and an every-prompt package`,
+ { timeout: 30_000 },
+ () => {
+ const PROJECT = "p1";
+ const AGENT = "goal_agent";
+ let root: string;
+ let mock: MockLLM;
+ let db: DatabaseSync;
+ let channels: ChannelHub;
+ let manager: SessionManager;
+ let sessionId: string;
+ let events: ChannelEvent[];
+
+ beforeEach(async () => {
+ root = await makeTempRoot();
+ mock = await startMockLLM();
+ // Saved first: an Agent reads its Project's models when it is created.
+ await saveProjectConfig(root, PROJECT, {
+ default_model: { provider: "custom", model_id: MOCK_MODEL_ID },
+ models: [
+ {
+ provider: "custom",
+ model_id: MOCK_MODEL_ID,
+ context_window: 200_000,
+ api_key: "sk-mock",
+ base_url: mock.url,
+ },
+ ],
+ });
+ const agent = await createAgent({ root, projectId: PROJECT, agentId: AGENT });
+ await installPlugin(root, PROJECT, AGENT, libraryPlugin("goal")!);
+ const hooks = hooksDir(root, PROJECT, AGENT);
+ if (legacy) {
+ await fs.writeFile(
+ path.join(hooks, "goal", "hooks.json"),
+ `${JSON.stringify(LEGACY_GOAL_MANIFEST, null, 2)}\n`,
+ );
+ }
+ await writeClockPackage(hooks);
+ const workspace = path.join(root, "workspace");
+ await fs.mkdir(workspace);
+ // Created and handed to the manager the way POST /sessions does it; its first context
+ // reads the packages as it opens.
+ const session = await agent.createSession({ workspaceDir: workspace });
+ sessionId = session.sessionId;
+ const now = new Date().toISOString();
+ const row: SessionRow = {
+ sessionId,
+ projectId: PROJECT,
+ agentId: AGENT,
+ modelId: MOCK_MODEL_ID,
+ provider: "custom",
+ workspace,
+ approvalMode: "allow-all",
+ title: null,
+ createdAt: now,
+ lastActiveAt: now,
+ };
+ db = openDatabase(":memory:");
+ const sessions = wire(SessionsRepo, { db: db });
+ sessions.insert(row);
+ channels = new ChannelHub();
+ manager = new SessionManager({
+ sessions,
+ channels,
+ sources: new SessionSources(),
+ loader: createCoreSessionLoader(root),
+ recorder: { record: async () => {} },
+ log: () => {},
+ });
+ manager.adopt(row, session);
+ events = [];
+ channels.get(sessionId).subscribe((e) => events.push(e));
+ });
+ afterEach(async () => {
+ await manager.shutdown();
+ channels.dispose();
+ db.close();
+ await mock.close();
+ await fs.rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ });
+
+ const idle = () => waitFor(() => manager.statusOf(sessionId) === "idle", 20_000);
+ /** The user texts published on the session's message stream, in order. */
+ const published = () =>
+ userTexts(
+ events.filter((e) => e.event === undefined).map((e) => JSON.parse(e.data) as OmniMessage),
+ );
+ const goalFile = () =>
+ path.join(sessionScratchpadDir(root, PROJECT, AGENT, sessionId), "GOAL.json");
+
+ it("a goal start runs the goal's start by name; the other package's context rides round 1 without counting as a round", async () => {
+ await manager.startGoal(sessionId, {
+ messages: [userText("raise coverage")],
+ objective: "raise coverage",
+ budget: 1,
+ });
+ await idle();
+
+ // start.mjs wrote the goal file; round 1 spent the budget, so round 2 was the wrap-up.
+ expect(JSON.parse(await fs.readFile(goalFile(), "utf8"))).toMatchObject({
+ objective: "raise coverage",
+ budget: 1,
+ round: 2,
+ status: "budget_limited",
+ });
+ const texts = published();
+ expect(texts.map((m) => m.sender)).toEqual(["user", "harness", "harness", "harness"]);
+ expect(texts[0]!.text).toBe("raise coverage");
+ expect(texts[1]!.text).toContain("sent automatically by goal mode");
+ expect(texts[2]!.text).toBe(clockContext("raise coverage"));
+ expect(texts[3]!.text).toContain("reached its token budget");
+
+ const server = serverEvents(events);
+ expect(server.filter((e) => e.type === "goal_round").map((e) => e.round)).toEqual([1, 2]);
+ expect(server.find((e) => e.type === "goal_finished")).toMatchObject({
+ outcome: "budget_limited",
+ rounds: 2,
+ });
+
+ // Round 1's request carries the three in that order. The wrap-up round starts from the
+ // goal hook's input, which no user submitted: the package is not asked again.
+ expect(mock.requests).toHaveLength(2);
+ const first = requestText(mock.requests[0]!);
+ const at = [
+ "raise coverage",
+ "sent automatically by goal mode",
+ clockContext("raise coverage"),
+ ].map((text) => first.indexOf(text));
+ expect(at.every((i) => i >= 0)).toBe(true);
+ expect(at).toEqual([...at].sort((a, b) => a - b));
+ });
+
+ it("an ordinary task starts no goal: the goal's start is not among the Prompt's hooks, the other package's is", async () => {
+ await manager.startTask(sessionId, [userText("fix the typo")]);
+ await idle();
+
+ expect(published()).toEqual([
+ { sender: "user", text: "fix the typo" },
+ { sender: "harness", text: clockContext("fix the typo") },
+ ]);
+ // No goal file and one request: nothing started a goal, so the goal's stop hook found
+ // none to drive into another round.
+ await expect(fs.access(goalFile())).rejects.toThrow();
+ expect(mock.requests).toHaveLength(1);
+ expect(serverEvents(events).filter((e) => e.type.startsWith("goal_"))).toEqual([]);
+ });
+ },
+ );
+}
diff --git a/packages/server/test/hooks.test.ts b/packages/server/test/hooks.test.ts
index f1ff7763..f13fc5dd 100644
--- a/packages/server/test/hooks.test.ts
+++ b/packages/server/test/hooks.test.ts
@@ -1,17 +1,39 @@
/**
- * 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).
+ * Integration tests for the hook package routes: the installed list (a package written by
+ * hand included), the zip archive install (layouts, manifest validation, zip-slip, 409
+ * hook_exists + overwrite, a user_prompt command's trigger) 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).
+ *
+ * The last block drives real Sessions against a loopback model endpoint: what an
+ * every-prompt package adds to a conversation, and an install or uninstall through these
+ * routes reaching a conversation that is already open.
*/
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 { OmniMessage } from "@prismshadow/penguin-core";
+import type {
+ AgentHooksResponse,
+ MessagesResponse,
+ ProjectCreateResponse,
+ SessionCreateResponse,
+} from "../src/api/types.js";
+import type { ChannelEvent } from "../src/runtime/channel.js";
+import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
+import {
+ MOCK_MODEL_ID,
+ clockContext,
+ clockPackageFiles,
+ requestText,
+ startMockLLM,
+ userTexts,
+ writeClockPackage,
+} from "./live-session.js";
+import type { MockLLM } from "./live-session.js";
describe("hooks api", () => {
let t: TestApp;
@@ -114,6 +136,16 @@ describe("hooks api", () => {
expect("enabled" in manifest).toBe(false);
});
+ it("lists a package written by hand whose manifest names only the hook point it uses", async () => {
+ await createPlainAgent("hand_agent");
+ await writeClockPackage(hooksDir(t.root, projectId, "hand_agent"));
+ const res = await member.get(base("hand_agent"));
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as AgentHooksResponse).hooks).toEqual([
+ { name: "clock", description: "", version: "", events: ["user_prompt"] },
+ ]);
+ });
+
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`;
@@ -217,6 +249,17 @@ describe("hooks api", () => {
],
["no commands at all", packageFiles("h", { ...MANIFEST, stop: [] })],
["a non-string description", packageFiles("h", { ...MANIFEST, description: 1 })],
+ [
+ "an unknown trigger",
+ packageFiles("h", {
+ ...MANIFEST,
+ user_prompt: [{ command: "stop.mjs", trigger: "later" }],
+ }),
+ ],
+ [
+ "a non-string trigger",
+ packageFiles("h", { ...MANIFEST, user_prompt: [{ command: "stop.mjs", trigger: true }] }),
+ ],
];
for (const [label, files] of cases) {
const res = await member.post(url, { dataBase64: zipB64(files) });
@@ -228,6 +271,31 @@ describe("hooks api", () => {
expect(list.hooks).toEqual([]);
});
+ it("archive: a user_prompt command's trigger, host or prompt, is kept in the written manifest", async () => {
+ await createPlainAgent("zip_trigger_agent");
+ const userPrompt = [
+ { command: "start.mjs", timeout: 60, trigger: "host" },
+ { command: "note.mjs", trigger: "prompt" },
+ ];
+ const res = await member.post(`${base("zip_trigger_agent")}/archive`, {
+ dataBase64: zipB64({
+ "flow/hooks.json": strToU8(
+ manifestText({ ...MANIFEST, name: "flow", stop: [], user_prompt: userPrompt }),
+ ),
+ "flow/start.mjs": strToU8(STOP_MJS),
+ "flow/note.mjs": strToU8(STOP_MJS),
+ }),
+ });
+ expect(res.status).toBe(201);
+ expect(((await res.json()) as AgentHooksResponse).hooks).toMatchObject([
+ { name: "flow", events: ["user_prompt"] },
+ ]);
+ const written = JSON.parse(
+ await fs.readFile(manifestFile("zip_trigger_agent", "flow"), "utf8"),
+ );
+ expect(written.user_prompt).toEqual(userPrompt);
+ });
+
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`;
@@ -387,3 +455,117 @@ describe("hooks api", () => {
);
});
});
+
+describe("hook packages in a conversation", { timeout: 30_000 }, () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let mock: MockLLM;
+ const hooks = () => `/api/projects/${projectId}/agents/default_agent/hooks`;
+
+ beforeEach(async () => {
+ mock = await startMockLLM();
+ // The app's own loader builds a real core Session per conversation. Titles stay off, so
+ // the model is asked for the Tasks alone.
+ t = await createTestApp({ titles: { maybeGenerate: () => {} } });
+ const { cookie } = await provisionUser(t.app, "clock_user");
+ api = apiClient(t.app, cookie);
+ const created = (await (
+ await api.post("/api/projects", { projectId: "clock_user-hooks", name: "clock project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ const models = await api.put(`/api/projects/${projectId}/models`, {
+ defaultModel: { provider: "custom", modelId: MOCK_MODEL_ID },
+ models: [
+ {
+ provider: "custom",
+ modelId: MOCK_MODEL_ID,
+ apiKey: "sk-mock",
+ baseUrl: mock.url,
+ contextWindow: 200_000,
+ },
+ ],
+ });
+ expect(models.status).toBe(200);
+ });
+ afterEach(async () => {
+ await t.deps.manager.shutdown();
+ await t.cleanup();
+ await mock.close();
+ });
+
+ /** Opens a conversation with default_agent and collects what its channel publishes. */
+ async function openConversation(): Promise<{ sessionId: string; events: ChannelEvent[] }> {
+ const res = await api.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {});
+ expect(res.status).toBe(201);
+ const { session } = (await res.json()) as SessionCreateResponse;
+ const events: ChannelEvent[] = [];
+ t.deps.channels.get(session.sessionId).subscribe((e) => events.push(e));
+ return { sessionId: session.sessionId, events };
+ }
+
+ async function runTask(sessionId: string, text: string): Promise<void> {
+ const res = await api.post(`/api/sessions/${sessionId}/tasks`, {
+ input: [{ type: "text", text }],
+ });
+ expect(res.status).toBe(202);
+ await waitFor(() => t.deps.manager.statusOf(sessionId) === "idle", 20_000);
+ }
+
+ const streamed = (events: ChannelEvent[]): OmniMessage[] =>
+ events.filter((e) => e.event === undefined).map((e) => JSON.parse(e.data) as OmniMessage);
+
+ it("an ordinary task: a hand-written every-prompt package's context follows the user's message, stamped harness, live and in the history", async () => {
+ await writeClockPackage(hooksDir(t.root, projectId, "default_agent"));
+ const { sessionId, events } = await openConversation();
+
+ await runTask(sessionId, "what time is it");
+
+ const expected = [
+ { sender: "user", text: "what time is it" },
+ { sender: "harness", text: clockContext("what time is it") },
+ ];
+ expect(userTexts(streamed(events))).toEqual(expected);
+ const history = (await (
+ await api.get(`/api/sessions/${sessionId}/messages`)
+ ).json()) as MessagesResponse;
+ expect(userTexts(history.messages)).toEqual(expected);
+ // And the model read it right behind the question.
+ expect(mock.requests).toHaveLength(1);
+ const sent = requestText(mock.requests[0]!);
+ expect(sent.indexOf("what time is it")).toBeGreaterThan(-1);
+ expect(sent.indexOf("what time is it")).toBeLessThan(
+ sent.indexOf(clockContext("what time is it")),
+ );
+ });
+
+ it("a package installed or uninstalled through the routes reaches the open conversation on its next task", async () => {
+ const { sessionId, events } = await openConversation();
+ await runTask(sessionId, "first");
+
+ const install = await api.post(`${hooks()}/archive`, {
+ dataBase64: Buffer.from(
+ zipSync(
+ Object.fromEntries(
+ Object.entries(clockPackageFiles()).map(([rel, text]) => [
+ `clock/${rel}`,
+ strToU8(text),
+ ]),
+ ),
+ ),
+ ).toString("base64"),
+ });
+ expect(install.status).toBe(201);
+ await runTask(sessionId, "second");
+
+ expect((await api.delete(`${hooks()}/clock`)).status).toBe(204);
+ await runTask(sessionId, "third");
+
+ expect(userTexts(streamed(events))).toEqual([
+ { sender: "user", text: "first" },
+ { sender: "user", text: "second" },
+ { sender: "harness", text: clockContext("second") },
+ { sender: "user", text: "third" },
+ ]);
+ });
+});
diff --git a/packages/server/test/live-session.ts b/packages/server/test/live-session.ts
new file mode 100644
index 00000000..b320a469
--- /dev/null
+++ b/packages/server/test/live-session.ts
@@ -0,0 +1,146 @@
+/**
+ * What a suite needs to drive a real core Session rather than a fake: a loopback model
+ * endpoint and a hook package written by hand.
+ *
+ * The endpoint answers every request with one streamed text reply in the Anthropic Messages
+ * wire format — what the `custom` provider's `claude-4-8` is read with — and records each
+ * request body, so a test can check what the model was sent. Point a model entry's
+ * `base_url` at its `url`.
+ */
+import fs from "node:fs/promises";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import path from "node:path";
+import type { OmniMessage, TextPayload } from "@prismshadow/penguin-core";
+
+/** The model id the endpoint stands in for (routed to the Anthropic Messages client). */
+export const MOCK_MODEL_ID = "claude-4-8";
+
+export interface MockLLM {
+ url: string;
+ /** Every request body, parsed, in arrival order. */
+ requests: Array<{ messages?: unknown[] }>;
+ close(): Promise<void>;
+}
+
+/** Starts the endpoint; `reply` is the text of the n-th answer (1-based). */
+export async function startMockLLM(
+ reply: (n: number) => string = (n) => `reply ${n}`,
+): Promise<MockLLM> {
+ const requests: MockLLM["requests"] = [];
+ const server = http.createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk: Buffer) => (body += chunk.toString("utf8")));
+ req.on("end", () => {
+ try {
+ requests.push(JSON.parse(body) as MockLLM["requests"][number]);
+ } catch {
+ requests.push({});
+ }
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
+ const send = (data: { type: string; [key: string]: unknown }): void => {
+ res.write(`event: ${data.type}\ndata: ${JSON.stringify(data)}\n\n`);
+ };
+ send({
+ type: "message_start",
+ message: {
+ id: `msg_${requests.length}`,
+ type: "message",
+ role: "assistant",
+ model: MOCK_MODEL_ID,
+ content: [],
+ stop_reason: null,
+ stop_sequence: null,
+ usage: {
+ input_tokens: 40,
+ output_tokens: 0,
+ cache_read_input_tokens: 0,
+ cache_creation_input_tokens: 0,
+ },
+ },
+ });
+ send({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } });
+ send({
+ type: "content_block_delta",
+ index: 0,
+ delta: { type: "text_delta", text: reply(requests.length) },
+ });
+ send({ type: "content_block_stop", index: 0 });
+ send({
+ type: "message_delta",
+ delta: { stop_reason: "end_turn", stop_sequence: null },
+ usage: { output_tokens: 5 },
+ });
+ send({ type: "message_stop" });
+ res.end();
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const { port } = server.address() as AddressInfo;
+ return {
+ url: `http://127.0.0.1:${port}`,
+ requests,
+ close: () =>
+ new Promise<void>((resolve) => {
+ server.closeAllConnections();
+ server.close(() => resolve());
+ }),
+ };
+}
+
+/** A recorded request's messages as one string, for order and count checks. */
+export function requestText(request: { messages?: unknown[] }): string {
+ return JSON.stringify(request.messages ?? []);
+}
+
+/** What the clock package answers for a prompt. */
+export const clockContext = (prompt: string): string =>
+ `The local time is 10:00 (asked: ${prompt}).`;
+
+/** The clock package's one script: answers every prompt with a context naming what it was asked. */
+const CLOCK_SCRIPT = [
+ "let raw = '';",
+ "process.stdin.on('data', (chunk) => (raw += chunk));",
+ "process.stdin.on('end', () => {",
+ " const { prompt } = JSON.parse(raw);",
+ " const context = 'The local time is 10:00 (asked: ' + prompt + ').';",
+ " process.stdout.write(JSON.stringify({ context }));",
+ "});",
+ "",
+].join("\n");
+
+/**
+ * The clock package's files, keyed by path inside the package directory, as a person or an
+ * Agent writes them by hand: a manifest naming only the hook point it uses — no name, no
+ * version — and its script.
+ */
+export function clockPackageFiles(): Record<string, string> {
+ return {
+ "hooks.json": `${JSON.stringify({ user_prompt: [{ command: "clock.mjs" }] }, null, 2)}\n`,
+ "clock.mjs": CLOCK_SCRIPT,
+ };
+}
+
+/** Writes the clock package into `hooksRoot` (an Agent's `agent_state/hooks/`) as `clock/`. */
+export async function writeClockPackage(hooksRoot: string): Promise<void> {
+ const dir = path.join(hooksRoot, "clock");
+ await fs.mkdir(dir, { recursive: true });
+ for (const [rel, text] of Object.entries(clockPackageFiles())) {
+ await fs.writeFile(path.join(dir, rel), text);
+ }
+}
+
+/** The main-session user texts among `messages`, as their sender and text. */
+export function userTexts(
+ messages: readonly OmniMessage[],
+): Array<{ sender: string; text: string }> {
+ return messages
+ .filter((m) => {
+ const p = m.payload as { type?: string; role?: string };
+ return m.type === "model_msg" && !m.origin?.length && p.type === "text" && p.role === "user";
+ })
+ .map((m) => {
+ const p = m.payload as TextPayload;
+ return { sender: p.sender ?? "user", text: p.text };
+ });
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 85854539..f2db8a9f 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -2000,8 +2000,8 @@ export const en: Strings = {
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.',
+ '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. A hook point the package does not use may be left out or []; a user_prompt entry may add "trigger": "prompt" (every prompt the user submits, the default) or "host" (only when the host starts the package\'s flow by name).',
+ '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 trace_path, scratchpad_dir and prompt (the user\'s message text). 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" }, which is sent right behind the user\'s message on every prompt. 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}`,
@@ -2013,7 +2013,7 @@ export const en: Strings = {
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.",
+ "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 until its context is compacted.",
savedToast: "Saved — takes effect from the next turn",
},
},
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index e8b9f433..263ab0a9 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2035,8 +2035,8 @@ export const zh = {
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 或超时都按失败记录、不采纳。',
+ '然后产出一个 PenguinHarness 钩子包:一份 hooks.json(name、description、description_zh、version(格式 YYYY.MM.DD.N),以及各钩子点的命令列表 stop / pre_tool_use / user_prompt,每项为 { "command": "<脚本相对路径>", "timeout": <秒> })加上纯 Node 的 .mjs 脚本(只用内置模块)。用不到的钩子点可以省略或写成 [];user_prompt 的条目可以另加 "trigger": "prompt"(缺省:用户每次提交 Prompt 时运行)或 "host"(只在宿主按包名启动该包的流程时运行)。',
+ '脚本契约: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 点带 trace_path、scratchpad_dir 与 prompt(用户的消息文本);stdout 为空即无意见,否则一份 JSON 回答——stop 点 { "decision": "continue" | "stop", "input", "reason", "output", "subagent"? },pre_tool_use 点 { "decision": "allow" | "deny", "reason", "output" },user_prompt 点 { "context" },它在每条 Prompt 中紧随用户消息发出;退出码非零、stdout 不是 JSON 或超时都按失败记录、不采纳。',
`把它安装到 Project「${projectId}」中 Agent「${agentId}」的 agent_state/hooks/<name>/ 目录(目录名即包名,须匹配 ^[A-Za-z0-9_-]+$),最后向我说明它做什么、在哪个钩子点触发。`,
].join("\n"),
uninstallConfirmTitle: (name: string): string => `卸载 ${name}`,
@@ -2047,7 +2047,7 @@ export const zh = {
injection: {
enable: "启用钩子",
enableHint:
- "开启后,该 Agent 新建的 Session 会在钩子点运行全部已安装的钩子包;关闭后新建的 Session 不运行任何钩子,已安装的包仍保留在磁盘上。进行中的 Task 保持开始时的设置。",
+ "开启后,该 Agent 新建的 Session 会在钩子点运行全部已安装的钩子包;关闭后新建的 Session 不运行任何钩子,已安装的包仍保留在磁盘上。进行中的 Task 保持开始时的设置,直到其上下文被压缩。",
savedToast: "已保存,自下一轮对话起生效",
},
},
diff --git a/packages/web/test/hook-import.test.ts b/packages/web/test/hook-import.test.ts
index 9dbb087c..9fd8bb64 100644
--- a/packages/web/test/hook-import.test.ts
+++ b/packages/web/test/hook-import.test.ts
@@ -31,6 +31,8 @@ const CONTRACT = [
'"continue" | "stop"',
'"allow" | "deny"',
'"context"',
+ '"trigger"',
+ '"host"',
"^[A-Za-z0-9_-]+$",
];
diff --git a/plugins/README.md b/plugins/README.md
index f2805a2b..5cad190d 100644
--- a/plugins/README.md
+++ b/plugins/README.md
@@ -13,7 +13,7 @@ Included plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plugins
| AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` |
| Agent Company | `agent-company` |
-`humanizer`, `use-claude-code`, `continual-learning` and `agent-company` carry `preinstall: false`, so `default_agent` does not get them at initialization — they are installed from the library on demand (`agent-company` by the organization itself, when it creates the CEO and hires employees, or by hand onto any Agent that should be able to create one). `goal` is the stop hook behind goal mode: its `start.mjs` writes the Session's `GOAL.json` and composes round 1, its `stop.mjs` reads the Trace after every Task and injects the next round or ends the goal. `continual-learning` hands a long task's condensed excerpt to a background subagent that folds the findings into the agent's skills.
+`humanizer`, `use-claude-code`, `continual-learning` and `agent-company` carry `preinstall: false`, so `default_agent` does not get them at initialization — they are installed from the library on demand (`agent-company` by the organization itself, when it creates the CEO and hires employees, or by hand onto any Agent that should be able to create one). `goal` is the stop hook behind goal mode: its `start.mjs`, a `user_prompt` command marked `"trigger": "host"` so that it runs only when a goal starts, writes the Session's `GOAL.json` and composes round 1; its `stop.mjs` reads the Trace after every Task and injects the next round or ends the goal. `continual-learning` hands a long task's condensed excerpt to a background subagent that folds the findings into the agent's skills.
`browser-automation` drives the desktop app's built-in browser through `penguin browser`: GenericAgent's scan → act → check loop over simplified HTML, trusted clicks and typing, and sign-ins imported from the system browser, with Amazon orders as the worked example.
diff --git a/plugins/agent-tuning/plugin.json b/plugins/agent-tuning/plugin.json
index 8e5307de..bbfb5e38 100644
--- a/plugins/agent-tuning/plugin.json
+++ b/plugins/agent-tuning/plugin.json
@@ -3,6 +3,6 @@
"description_zh": "闭环的 Agent 调优:依据需求初始化 Agent、设计并校准能力 Benchmark、隔离执行与评分、再根据测得结果改进 Agent。",
"short_description": "Initialize, benchmark, evaluate and improve agents.",
"short_description_zh": "初始化、评测、评分与改进 Agent。",
- "version": "2026.09.15.1",
+ "version": "2026.09.29.1",
"category": "ai-app-development"
}
diff --git a/plugins/agent-tuning/skills/agent-initialization/SKILL.md b/plugins/agent-tuning/skills/agent-initialization/SKILL.md
index 3a910aee..15d05163 100644
--- a/plugins/agent-tuning/skills/agent-initialization/SKILL.md
+++ b/plugins/agent-tuning/skills/agent-initialization/SKILL.md
@@ -1,11 +1,11 @@
---
name: agent-initialization
-description: Initialize an Agent's settings from a user requirement by writing AGENTS.md, setting identity metadata, and installing only needed Skills.
+description: Initialize or extend an Agent from a user requirement - write AGENTS.md, set identity metadata, and create, install or import Skills and hook packages (scripts the harness runs on every prompt, before tool calls, or after a task).
---
# Agent Initialization
-This skill initializes an agent's settings from a user requirement — plain files in the target agent's directory.
+This skill initializes an agent's settings from a user requirement — plain files in the target agent's directory. It is also the reference for giving an agent, yourself included, a new Skill or a new hook: both are directories you write, and the harness picks them up from disk.
## Before you start
@@ -30,7 +30,9 @@ ls "$APP_DATA_DIR/agents" # existing agents (each is a folder here)
TARGET="$APP_DATA_DIR/agents/<agent_id>" # the agent to configure
```
-An agent directory contains `agent_state/` (`system_config.yaml`, `AGENTS.md`, `skills/`, `memory/`, `tools/`) plus `scratchpad/` — and `traces/`, which appears once the agent has run at least once.
+An agent directory contains `agent_state/` (`system_config.yaml`, `AGENTS.md`, `skills/`, `hooks/`, `memory/`, `tools/`) plus `scratchpad/` — and `traces/`, which appears once the agent has run at least once. `hooks/` exists once a hook package is installed; create it when you need it.
+
+To extend the agent you are running as, the target is your own directory: `<app_data_dir>/agents/<agent_id>` with the Agent ID from your Environment section.
## Write AGENTS.md
@@ -41,28 +43,31 @@ An agent directory contains `agent_state/` (`system_config.yaml`, `AGENTS.md`, `
Be concise: AGENTS.md is prompt context, not documentation. For a domain expert that answers from a knowledge base, a good AGENTS.md is a few lines: the role sentence, "answer strictly from the provided context blocks", citation rules ("cite blocks inline as [1][2]"), a refusal rule for questions the context cannot answer, and "answer in the language of the question".
-## Install skills
+## Skills
-A skill is a directory `agent_state/skills/<skill_name>/` containing a `SKILL.md`:
+A Skill is a directory `agent_state/skills/<skill_name>/` containing a `SKILL.md`. The directory name is the Skill's name (letters, digits, `_`, `-`); nothing else registers it.
```md
---
name: <skill_name>
-description: <skill_description>
-version: <natural number — bump it on every content change>
-updated: <ISO 8601 timestamp — move it together with version>
+description: <one line: what it does and when to use it>
+version: <YYYY.MM.DD.N, e.g. 2026.09.29.1 - today's date, N counts that day's changes>
---
<skill_instructions>
```
-The frontmatter may also carry optional `short_description` and `short_description_zh` lines (a short UI blurb and its Chinese variant) — the UI prefers them for display, while prompt injection always uses the English `description`.
+The `description` line is what the target agent sees in its system prompt, so it has to say when the Skill applies; the body is read only once the agent decides to use it. Optional `short_description` and `short_description_zh` lines give the UI a short blurb. Files the body refers to go beside it (`reference/<topic>.md`, scripts), linked by relative path.
+
+There are three ways to get one in place:
-Installing is all it takes: the frontmatter metadata of every `SKILL.md` under `skills/` is injected into the target agent's system prompt automatically — do not register skills in AGENTS.md.
+- **Create.** Write the directory yourself. Keep the body to what a capable agent would not already know: the steps, the commands, the traps.
+- **Install from the library.** Copy the whole `skills/<skill_name>/` directory from an agent that has it — `default_agent` ships the whole library. The user can also install from the Web App's Plugins page.
+- **Import.** Fetch a Skill from a URL, a repository or a local path (`curl`, `git clone`, `unzip`), then place it under `skills/`. A Skill written for another tool usually needs only the frontmatter above. Read everything you fetched in full before installing, and tell the user what it does: a Skill becomes instructions the agent follows in every future session.
-Write skills yourself, or fetch existing ones from the internet with shell commands (`curl`, `git clone`) and place them under `skills/`. Anything fetched from the internet must be read in full and reviewed before installing — a skill becomes durable instructions the target agent will follow in every future session; never install one you have not read, and tell the user what it does.
+Do not register Skills in AGENTS.md; the frontmatter is injected automatically.
-Library skills can be copied from any agent that already has them (e.g. `default_agent`, which ships the whole library) — copy the entire `skills/<skill_name>/` directory. Common bundles, so you don't under-equip the target:
+Common library bundles, so you don't under-equip the target:
- **App builder** (builds apps or web frontends): `penguin-sdk`, `web-design`, `agenthub-models`.
- **Knowledge expert** (answers questions over a document set): usually **no** harness agent is needed — build a RAG app with the penguin-sdk skill instead, and configure the app's embedded agent (below).
@@ -70,6 +75,69 @@ Library skills can be copied from any agent that already has them (e.g. `default
When creating a Test Agent, install only the capabilities it needs to solve ordinary tasks.
+## Hook packages
+
+A hook is a script the harness itself runs at a fixed point of the agent loop. Use one when something must happen every time, whether or not the model remembers: adding context to every prompt, vetting a tool call, deciding that a finished task should continue. A rule the model can simply follow belongs in AGENTS.md or a Skill instead.
+
+A hook package is a directory `agent_state/hooks/<package_name>/` holding a `hooks.json` and the scripts it names:
+
+```json
+{
+ "name": "append-time",
+ "description": "Adds the current local time to every prompt.",
+ "description_zh": "为每条 Prompt 附上当前本地时间。",
+ "version": "2026.09.29.1",
+ "user_prompt": [{ "command": "time.mjs", "timeout": 10 }]
+}
+```
+
+```js
+// time.mjs - answers every prompt with the current local time.
+const now = new Date();
+const pad = (n) => String(n).padStart(2, "0");
+const offset = -now.getTimezoneOffset();
+const stamp =
+ `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ` +
+ `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
+const utc = `UTC${offset < 0 ? "-" : "+"}${pad(Math.floor(Math.abs(offset) / 60))}:${pad(Math.abs(offset) % 60)}`;
+const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+process.stdout.write(`${JSON.stringify({ context: `Current time: ${stamp} ${zone} (${utc})` })}\n`);
+```
+
+The three hook points, one command list each in `hooks.json` (leave out the ones you do not use):
+
+| Key | Runs | The script answers |
+| --- | --- | --- |
+| `user_prompt` | Every time the user submits a prompt | `{ "context": "<text>" }` — sent to the model right behind the user's message |
+| `pre_tool_use` | Before each tool call is approved | `{ "decision": "allow" \| "deny", "reason": "<one line>" }` |
+| `stop` | After every task ends | `{ "decision": "continue", "input": "<next user message>" }` to keep going, or `{ "decision": "stop" }` |
+
+Every script is plain Node (`.mjs`, builtin modules only), run as `node <script>` with the package directory as its working directory. It receives one JSON object on stdin and prints one JSON object on stdout; printing nothing means no opinion. A non-zero exit, output that is not JSON, or running past `timeout` seconds (default 60) counts as a failure: it is recorded and ignored, and never stops the run. The full contract — every stdin field, the remaining answer fields, `trigger`, and how to convert another tool's hooks — is in [`reference/hooks.md`](reference/hooks.md); read it before writing a `pre_tool_use` or `stop` hook.
+
+The same three ways apply:
+
+- **Create.** Write the directory. Give `user_prompt` and `pre_tool_use` commands a small `timeout`: they run on the hot path.
+- **Install from the library.** Copy the whole `hooks/<package_name>/` directory from an agent that has it, or have the user install the plugin from the Web App's Plugins page.
+- **Import.** Fetch the source, read every script in full and review it for anything that exfiltrates data, touches files outside its purpose or runs unknown commands, then convert it to the layout above. Another tool's hook configuration (the `hooks` block of a Claude Code `settings.json`, for instance) maps point by point; `reference/hooks.md` has the table.
+
+Test a script by hand before you rely on it — feed it the input it will get and check the exit code and the output:
+
+```bash
+cd "$TARGET/agent_state/hooks/append-time"
+echo '{"hook":"user_prompt","session_id":"test","scratchpad_dir":"/tmp","prompt":"hello"}' | node time.mjs; echo "exit $?"
+```
+
+A hook runs on the user's machine with the harness's own permissions, on every prompt, tool call or task. Tell the user what each hook you install does and at which point it fires. One switch turns all of an agent's hooks off without uninstalling them: `hooks.enabled: false` in `system_config.yaml`.
+
+## When a change takes effect
+
+The harness reads an agent's configuration from disk each time a model context opens — AGENTS.md, `system_config.yaml`, Skills and hook packages alike:
+
+- a **new conversation** starts with everything you wrote;
+- a **conversation already running** — the one you are in, if you are changing yourself — picks the change up when its context is next compacted. The user can force that with `/compact`.
+
+Nothing changes in the middle of a context, so a hook you just wrote will not fire on the next message of this conversation, and a Skill you just wrote is not in your own system prompt yet. You can still read a new SKILL.md directly and follow it now. Say which of the two cases applies when you report.
+
## Set name and description
In the target's `agent_state/system_config.yaml`, set the top-level `name:` and `description:` fields so the agent is recognizable in lists. For an existing Agent, edit only these two fields unless the user explicitly requested a `thinking_level` change.
@@ -81,11 +149,11 @@ Prefer configuring an agent the user already created. If the user requires a new
After confirming that the target is absent, pick a short id using letters, digits, `_`, or `-`, copy the default Agent's `system_config.yaml` as the base, and create the layout described above:
```bash
-mkdir -p "$TARGET/agent_state/skills" "$TARGET/agent_state/memory" "$TARGET/agent_state/tools" "$TARGET/scratchpad"
+mkdir -p "$TARGET/agent_state/skills" "$TARGET/agent_state/hooks" "$TARGET/agent_state/memory" "$TARGET/agent_state/tools" "$TARGET/scratchpad"
cp "$APP_DATA_DIR/agents/default_agent/agent_state/system_config.yaml" "$TARGET/agent_state/"
```
-Then set the top-level `name`, `description`, and `version: 1`, set `model.thinking_level` to the resolved value, write `agent_state/AGENTS.md` (it lives under `agent_state/`, not at the agent directory root), and install only the Skills required by the user's requirement. Do not persist the resolved provider/model pair in the Agent State.
+Then set the top-level `name`, `description`, and `version: 1`, set `model.thinking_level` to the resolved value, write `agent_state/AGENTS.md` (it lives under `agent_state/`, not at the agent directory root), and install only the Skills and hook packages required by the user's requirement. Do not persist the resolved provider/model pair in the Agent State.
## Validate and report
@@ -94,9 +162,10 @@ Before finishing:
- parse `agent_state/system_config.yaml` and confirm `name`, `description`, a positive integer `version`, and the expected `model.thinking_level`;
- confirm `agent_state/AGENTS.md` exists and is non-empty;
- confirm every installed Skill has a parseable `SKILL.md`, and its `name` matches its directory;
+- confirm every installed hook package has a `hooks.json` that parses, that each command it lists is a file inside the package, and that each script ran by hand exits 0 and prints JSON or nothing;
- confirm no Agent outside `TARGET` was changed.
-Report the target path, whether an existing Agent was configured or a new Agent was created, assumptions, installed Skills, the resolved runtime and whether each value was user-specified or inherited, and validation results.
+Report the target path, whether an existing Agent was configured or a new Agent was created, assumptions, installed Skills and hook packages (for each hook: what it does and at which point it fires), when the change takes effect, the resolved runtime and whether each value was user-specified or inherited, and validation results.
## The embedded agent of an SDK app
diff --git a/plugins/agent-tuning/skills/agent-initialization/reference/hooks.md b/plugins/agent-tuning/skills/agent-initialization/reference/hooks.md
new file mode 100644
index 00000000..e00a5ab3
--- /dev/null
+++ b/plugins/agent-tuning/skills/agent-initialization/reference/hooks.md
@@ -0,0 +1,112 @@
+# Hook packages: the full contract
+
+A hook package is `agent_state/hooks/<package_name>/`: a `hooks.json` manifest and the scripts it names. The directory name is the package's name (letters, digits, `_`, `-`) and wins over the manifest's `name`.
+
+## `hooks.json`
+
+```json
+{
+ "name": "<package_name>",
+ "description": "<one line, English>",
+ "description_zh": "<one line, Chinese - optional>",
+ "version": "<YYYY.MM.DD.N>",
+ "user_prompt": [{ "command": "prompt.mjs", "timeout": 10 }],
+ "pre_tool_use": [{ "command": "guard.mjs", "timeout": 5 }],
+ "stop": [{ "command": "stop.mjs", "timeout": 60 }]
+}
+```
+
+- A hook point you do not use may be left out or given `[]`.
+- `command` is a path relative to the package directory and must stay inside it. An entry without one is ignored.
+- `timeout` is in seconds; 60 when absent.
+- `version` is today's date plus a counter, `2026.09.29.1`. Raise it whenever you change the package.
+- Commands of one point run in the order listed; packages run in name order.
+
+### `trigger` (on `user_prompt` commands only)
+
+| Value | The command runs |
+| --- | --- |
+| `"prompt"` (default) | On every prompt the user submits |
+| `"host"` | Only when the host starts the package's own flow by name. Goal mode's start script is the shipped example; an ordinary hook never needs it |
+
+Write `trigger` explicitly only for `"host"`. One thing to know when editing an older package: a manifest whose `version` is older than `2026.09.29.1` has its unmarked `user_prompt` commands read as `"host"`, so raise the version when you want them to run on every prompt.
+
+## What a script receives and answers
+
+Every script gets one JSON object on stdin with these fields, plus the ones of its point:
+
+| Field | Meaning |
+| --- | --- |
+| `hook` | The point: `user_prompt`, `pre_tool_use` or `stop` |
+| `session_id` | The Session's id |
+| `trace_path` | Absolute path of the Trace file being written — a JSONL record of the conversation so far. Absent when the Session keeps no Trace |
+
+stdout is one JSON object, or nothing for "no opinion". Unknown fields are dropped.
+
+### `user_prompt`
+
+Runs when a task starts from a message the user wrote. It does not run for messages the harness or the server injects: scheduled tasks, a `stop` hook's continuation, background-task reports, mid-run steering.
+
+| stdin | |
+| --- | --- |
+| `prompt` | The user's text, with leading marker blocks (a skill invocation, an origin note) stripped |
+| `scratchpad_dir` | The Session's scratchpad directory — the place for state the hook keeps between prompts |
+
+| stdout | |
+| --- | --- |
+| `context` | Text for the model. It is sent as its own message right behind the user's, marked as harness-injected, and shown to the user as a collapsed card. Empty or absent adds nothing |
+
+The context is appended after the user's message, so it never invalidates the prompt cache of the conversation before it. Keep it short: it is paid for on every prompt.
+
+### `pre_tool_use`
+
+Runs once per tool call, before the approval step.
+
+| stdin | |
+| --- | --- |
+| `tool_name` | The tool being called, e.g. `exec_command` |
+| `tool_call_id` | The call's id |
+| `arguments` | The call's arguments as the raw JSON string the model wrote — parse it yourself |
+
+| stdout | |
+| --- | --- |
+| `decision` | `"deny"` refuses the call and the model reads `reason`; `"allow"` approves it without asking the user; absent leaves the call to the normal approval |
+| `reason` | One line for people |
+| `output` | Your own record: an object of string, number or boolean values |
+
+The first decision among all hooks wins. An `allow` never overrides the Project's command policy: a command the policy forbids stays forbidden.
+
+### `stop`
+
+Runs after every task: the model's final reply, or a cutoff (the user's abort, a failed request, the turn cap).
+
+| stdout | |
+| --- | --- |
+| `decision` | `"continue"` starts another task with `input` as its user message; `"stop"` lets the run end |
+| `input` | Required with `continue`: the next task's input text |
+| `reason` | One line for people |
+| `output` | Your own record: an object of string, number or boolean values |
+| `subagent` | `{ "prompt": "<text>", "agent_id": "<optional>" }` — hands work to a detached background session |
+
+The first `continue` wins. After a cutoff a `continue` is recorded but not run: the user's interruption outranks every hook. A `stop` hook that always continues never lets the agent finish — decide from state (the Trace, a file in the scratchpad), and make sure the state eventually says stop.
+
+## Failures
+
+A non-zero exit, stdout that is not JSON, or a timeout is a failure. The harness records it as a `hook` event carrying the error (the tail of stderr for a non-zero exit) and carries on as if the hook had no opinion. To debug a hook that seems not to fire, look for `"type":"hook"` records in the Trace file, and run the script by hand:
+
+```bash
+echo '{"hook":"stop","session_id":"test","trace_path":"/path/to/trace.jsonl"}' | node stop.mjs; echo "exit $?"
+```
+
+Check three more things when nothing happens: the agent's `hooks.enabled` is not `false`, the conversation has opened a new context since you wrote the package (see "When a change takes effect" in SKILL.md), and the session is not a subagent's — child sessions run no hooks.
+
+## Converting hooks from Claude Code
+
+| Claude Code | Here |
+| --- | --- |
+| `UserPromptSubmit` | `user_prompt` — print `{ "context": … }` instead of plain text |
+| `PreToolUse` | `pre_tool_use` — `permissionDecision` becomes `decision`; filter on `tool_name` inside the script, there is no `matcher` |
+| `Stop` | `stop` — `{"decision":"block","reason":…}` becomes `{"decision":"continue","input":…}` |
+| `PostToolUse`, `SessionStart`, `Notification`, others | No counterpart. Say so rather than approximating |
+
+A Claude Code hook is a shell command; here a command is a Node script. Wrap a shell command with `node:child_process` (`execFileSync`) when you need one, and keep the JSON on stdout yours.
diff --git a/plugins/continual-learning/hooks/stop.mjs b/plugins/continual-learning/hooks/stop.mjs
index a4f1eb06..f59cbe3b 100644
--- a/plugins/continual-learning/hooks/stop.mjs
+++ b/plugins/continual-learning/hooks/stop.mjs
@@ -63,12 +63,25 @@ function isTaskStart(r) {
return true;
}
-/** The just-ended Task's records: everything after the last Task-starting input — the whole file when none is in it (a compaction rotated the file mid-Task). */
+/** Whether a record belongs to a Task's input: a Task-starting user text, or an image sent with one. */
+function isTaskInput(r) {
+ if (isTaskStart(r)) return true;
+ return isMain(r) && r.type === "model_msg" && !!r.payload && r.payload.type === "image_url";
+}
+
+/**
+ * The just-ended Task's records: everything from its input on — the whole file when no input
+ * is in it (a compaction rotated the file mid-Task). An input is a batch: the user's message,
+ * its images, and what the harness sent right behind it (a user_prompt hook's context, goal
+ * mode's round-1 protocol). The window opens at the batch's first record, so the excerpt
+ * keeps what the user asked.
+ */
function taskWindow(records) {
let start = 0;
records.forEach((r, i) => {
if (isTaskStart(r)) start = i;
});
+ while (start > 0 && isTaskInput(records[start - 1])) start -= 1;
return records.slice(start);
}
diff --git a/plugins/continual-learning/plugin.json b/plugins/continual-learning/plugin.json
index b91be6af..8e79a080 100644
--- a/plugins/continual-learning/plugin.json
+++ b/plugins/continual-learning/plugin.json
@@ -3,7 +3,7 @@
"description_zh": "持续学习:一个 stop hook,刚结束的任务跑了超过 30 个完成的轮次时,就把该任务的浓缩摘录交给一个后台子会话,由它把值得沉淀的发现写进 Agent 自己的 Skill。",
"short_description": "Fold a long task's findings back into the agent's skills.",
"short_description_zh": "把长任务的发现回流进 Agent 的 Skill。",
- "version": "2026.09.10.1",
+ "version": "2026.09.29.1",
"category": "office-productivity",
"preinstall": false,
"hooks": {
diff --git a/plugins/goal/hooks/start.mjs b/plugins/goal/hooks/start.mjs
index f85ea369..142f1f12 100644
--- a/plugins/goal/hooks/start.mjs
+++ b/plugins/goal/hooks/start.mjs
@@ -1,8 +1,10 @@
#!/usr/bin/env node
// Starts a goal — the plugin's user_prompt hook: writes the Session's GOAL.json and prints
-// the round-1 protocol message as the prompt's expansion context.
+// the round-1 protocol message as the prompt's expansion context. The manifest marks it
+// `trigger: "host"`: it runs when the host starts a goal, never on an ordinary prompt.
//
-// stdin: { "hook": "user_prompt", "session_id", "scratchpad_dir", "prompt", "budget" }
+// stdin: { "hook": "user_prompt", "session_id", "trace_path", "scratchpad_dir", "prompt",
+// "budget" }
// prompt = the user's text with leading marker blocks stripped (the objective later
// rounds restate and the file records); budget = tokens for the whole goal, -1 or
// absent = none.
diff --git a/plugins/goal/plugin.json b/plugins/goal/plugin.json
index 4695352c..f8e6fb1c 100644
--- a/plugins/goal/plugin.json
+++ b/plugins/goal/plugin.json
@@ -3,13 +3,14 @@
"description_zh": "目标模式:一个 stop hook,让会话持续朝目标工作——每轮重新注入目标并检查目标文件——直到目标完成、受阻或 token 预算耗尽。",
"short_description": "Loop the session on an objective until it is done.",
"short_description_zh": "让会话循环推进一个目标直到完成。",
- "version": "2026.09.01.1",
+ "version": "2026.09.29.1",
"category": "office-productivity",
"hooks": {
"user_prompt": [
{
"command": "start.mjs",
- "timeout": 60
+ "timeout": 60,
+ "trigger": "host"
}
],
"stop": [