From 48deef01352a53c36bb3f388cf4bfaf79ce0c879 Mon Sep 17 00:00:00 2001 From: Andrii Vasyliev Date: Mon, 30 Nov 2026 20:46:25 +0000 Subject: [PATCH] fix(claude-local): fail runs whose prompt a UserPromptSubmit hook blocked (#17766) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The `claude_local` adapter runs the Claude Code CLI and turns its stream-json output into a run result > - A project can define a `UserPromptSubmit` hook, and that hook can block the prompt > - When the hook blocks the prompt, the CLI runs no turn, exits 0 and reports a successful `result` whose text echoes the whole prompt > - The adapter returned that echo as the agent's reply, the server posted it as a comment, and the next wake carried that comment in the task history > - So each retry doubled the prompt, and the run looked successful > - This pull request detects the blocked prompt and fails the run with a specific error code and no echoed reply > - The benefit is that a hook rejection is visible as a failed run, and the prompt stops growing ## Linked Issues or Issue Description No public issue exists for this. I searched open and closed issues and pull requests for `UserPromptSubmit`, `blocked_by_hook`, `prompt_submit_outcome` and "hook blocked prompt". Related, but different: #15417 (pass-through of hooks-only settings for managed connections), #11976 / #16443 (Hermes prompt echo). **What happened?** A project `UserPromptSubmit` hook blocked the wake prompt. Claude Code emitted a `system` event with subtype `informational` and `prompt_submit_outcome.kind = "blocked_by_hook"`, then a `result` event with `subtype: "success"`, `is_error: false`, `num_turns: 0` and `result` equal to `UserPromptSubmit operation blocked by hook: … Original prompt: `. The process exited with code 0. The adapter treated the run as successful and used the echoed text as the summary. The server posted the echo as the agent's comment. The next wake included that comment in the task history, so the prompt grew on each retry. We observed a wake prompt of about 3.6 MB. **Expected behavior** A prompt that a hook blocked is a failed run. The run must not post the echoed prompt as a reply. The run error must say that a hook blocked the prompt and give the hook reason. **Steps to reproduce** 1. In an empty directory, create `.claude/settings.json` with `{"hooks":{"UserPromptSubmit":[{"hooks":[{"type":"command","command":"echo 'blocked by policy hook' >&2; exit 2"}]}]}}`. 2. Run `claude -p --output-format stream-json --verbose "say hi" < /dev/null`. 3. See the `informational` event with `prompt_submit_outcome: {"kind":"blocked_by_hook","prompt_kept":false,"reason":"blocked by policy hook"}`, then a `result` event with `subtype: "success"`, `num_turns: 0` and the echoed prompt, and exit code 0 (seen with Claude Code 2.1.309). 4. Use the same project for a `claude_local` agent and wake it. Before this change, the run succeeds and its summary is the echoed prompt. **Paperclip version or commit** Seen on v2026.1023.0. The patch base is `master` at `a67a18c171`. **Deployment mode** Self-hosted, `claude_local` with `engine: cli`. ## What Changed - `createClaudeStreamParser` records the reason from a `system`/`informational` event whose `prompt_submit_outcome.kind` is `blocked_by_hook`, and returns it as `promptBlockedReason`. - `execute` sets `errorMessage` to `Claude prompt was blocked by a UserPromptSubmit hook: `, `errorCode` to `claude_prompt_blocked_by_hook`, `stopReason` to `prompt_blocked_by_hook`, an empty summary and `result: null` in `resultJson`. A non-null `errorMessage` makes the server record the run as failed. - The new error code is not a transient code, so the bounded transient retry does not repeat the blocked prompt. - Add an execute regression test with a fake CLI that emits the real event sequence. ## Verification - `npx vitest run server/src/__tests__/claude-local-execute.test.ts`: 35 passed. - The new test fails on `master` without the source change (`expected null to be 'claude_prompt_blocked_by_hook'`). - `tsc --noEmit` in `packages/adapters/claude-local`: no errors. `tsc --noEmit` in `server` gives the same error list as unchanged `master` in the same environment (the only errors come from the unbuilt `@paperclipai/paperclip-runner` package). - Manual check of the CLI event shape with Claude Code 2.1.309, as in the steps above. ## Risks - Low risk. The new branch runs only when the CLI reports `prompt_submit_outcome.kind === "blocked_by_hook"`. - If a future CLI version changes this event shape, the adapter falls back to the current behavior. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used AI-assisted with Claude Code and OpenAI Codex coding agents; exact model versions are not listed. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [ ] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes (none needed: no documented behavior or setup changes) - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude --- .../claude-local/src/server/execute.ts | 10 +++- .../adapters/claude-local/src/server/parse.ts | 11 ++++ .../__tests__/claude-local-execute.test.ts | 59 +++++++++++++++++++ 3 files changed, 78 insertions(+), 2 deletions(-) diff --git a/packages/adapters/claude-local/src/server/execute.ts b/packages/adapters/claude-local/src/server/execute.ts index 67c1194edda..19295a3d5f7 100644 --- a/packages/adapters/claude-local/src/server/execute.ts +++ b/packages/adapters/claude-local/src/server/execute.ts @@ -1181,6 +1181,7 @@ export async function execute(ctx: AdapterExecutionContext): Promise) : null; - const errorMessage = failed + const errorMessage = promptBlockedReason + ? `Claude prompt was blocked by a UserPromptSubmit hook: ${promptBlockedReason}` + : failed ? describeClaudeFailure(parsed) ?? `Claude exited with code ${proc.exitCode ?? -1}` : null; const providerQuota = @@ -1274,6 +1277,8 @@ export async function execute(ctx: AdapterExecutionContext): Promise | null = null; + let promptBlockedReason: string | null = null; const assistantTexts: string[] = []; const messageUsage = new Map(); let anonymousMessage = 0; @@ -94,6 +95,14 @@ export function createClaudeStreamParser() { continue; } + if (type === "system" && asString(event.subtype, "") === "informational") { + const outcome = parseObject(event.prompt_submit_outcome); + if (asString(outcome.kind, "") === "blocked_by_hook") { + promptBlockedReason = asString(outcome.reason, "").trim() || "blocked by hook"; + } + continue; + } + if (type === "assistant") { sessionId = asString(event.session_id, sessionId ?? "") || sessionId; const message = parseObject(event.message); @@ -138,6 +147,7 @@ export function createClaudeStreamParser() { usageBasis: "per_run" as const, summary: assistantTexts.join("\n\n").trim(), resultJson: null as Record | null, + promptBlockedReason, }; } @@ -162,6 +172,7 @@ export function createClaudeStreamParser() { usageBasis: "per_run" as const, summary, resultJson: finalResult, + promptBlockedReason, }; }; } diff --git a/server/src/__tests__/claude-local-execute.test.ts b/server/src/__tests__/claude-local-execute.test.ts index 006f5780496..a11c3de60bf 100644 --- a/server/src/__tests__/claude-local-execute.test.ts +++ b/server/src/__tests__/claude-local-execute.test.ts @@ -1734,6 +1734,65 @@ describe("claude execute", () => { } }); + it("fails a hook-blocked prompt instead of returning the echoed prompt as the reply", async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-claude-execute-prompt-blocked-")); + const workspace = path.join(root, "workspace"); + const commandPath = path.join(root, "claude"); + await fs.mkdir(workspace, { recursive: true }); + const reason = "The prompt was rejected by a project policy hook."; + const echoed = `UserPromptSubmit operation blocked by hook:\n${reason}\n\nOriginal prompt: ## Paperclip Wake Payload`; + await writeTextFailingClaudeCommand(commandPath, { + exitCode: 0, + stdout: [ + { type: "system", subtype: "init", session_id: "11111111-1111-4111-8111-111111111111", model: "claude-test" }, + { type: "system", subtype: "informational", content: echoed, level: "warning", prevent_continuation: true, + prompt_submit_outcome: { kind: "blocked_by_hook", prompt_kept: false, reason } }, + { type: "result", subtype: "success", is_error: false, num_turns: 0, result: echoed, + session_id: "11111111-1111-4111-8111-111111111111", usage: { input_tokens: 0, output_tokens: 0 } }, + ].map((event) => JSON.stringify(event)).join("\n") + "\n", + }); + + const previousHome = process.env.HOME; + process.env.HOME = root; + + try { + const result = await execute({ + runId: "run-claude-prompt-blocked", + agent: { + id: "agent-1", + companyId: "company-1", + name: "Claude Coder", + adapterType: "claude_local", + adapterConfig: { engine: "cli" }, + }, + runtime: { + sessionId: null, + sessionParams: null, + sessionDisplayId: null, + taskKey: null, + }, + config: { + engine: "cli", + command: commandPath, + cwd: workspace, + promptTemplate: "Follow the paperclip heartbeat.", + }, + context: {}, + authToken: "run-jwt-token", + onLog: async () => {}, + }); + + expect(result.errorCode).toBe("claude_prompt_blocked_by_hook"); + expect(result.errorMessage).toContain(reason); + expect(result.summary).toBe(""); + expect(JSON.stringify(result.resultJson)).not.toContain("Paperclip Wake Payload"); + } finally { + if (previousHome === undefined) delete process.env.HOME; + else process.env.HOME = previousHome; + await fs.rm(root, { recursive: true, force: true }); + } + }); + it("classifies rate-limit / overloaded failures without reset metadata as transient", async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-claude-execute-rate-limit-")); const workspace = path.join(root, "workspace");