From 22a8aa0734aa8e87bb18d0fc2d25a1e7d3b617c9 Mon Sep 17 00:00:00 2001 From: Khalil Gharbaoui Date: Sat, 14 Nov 2026 22:55:11 +0100 Subject: [PATCH 1/6] Fail a turn whose prompt a hook blocked A UserPromptSubmit hook that ends a message now fails the turn under a prompt blocked note quoting the hook's reason, instead of an empty reply saying nothing failed. A blocked history replay drops its empty session, so the next message replays again rather than going on without it. Also registers REFUSAL_FALLBACK_MARKER in PLUGIN_NOTE_MARKERS and adds a test that scans src/ for any marker missing from the list. h #g314 --- AGENTS.md | 4 +- TODO.md | 34 +-- docs/agents-history.md | 72 +++++ docs/troubleshooting/symptoms.md | 1 + skills/claude-code-plugin/SKILL.md | 14 + src/claude-code-language-model.ts | 31 +- src/cli-events.ts | 118 ++++++++ src/diagnostic-bundle.ts | 4 + src/log-messages.ts | 2 + src/message-builder.ts | 4 + src/stream-parser.ts | 72 ++++- src/turn-state.ts | 12 + src/types.ts | 10 + test/prompt-blocked.test.ts | 437 +++++++++++++++++++++++++++++ test/turn-stats.test.ts | 37 ++- 15 files changed, 825 insertions(+), 27 deletions(-) create mode 100644 test/prompt-blocked.test.ts diff --git a/AGENTS.md b/AGENTS.md index af41e10..850beb2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -213,12 +213,13 @@ changing, reverting or "simplifying" a rule. - **`resumeAfterRestart` is ON by default, and every refusal is what makes that safe** (`src/session-resume-store.ts`). Without it the first turn of an existing conversation in a new opencode process replayed the whole thread (3 replays in the retained log, mean 648,653 characters, max 981,109). A record is written only after a `result` with `is_error !== true`, never on compaction, and is forgotten wherever the in-memory id is (`deleteClaudeSessionId`, a session-id error on stderr), so a conversation one process abandoned is never resumed by the next. **A child exiting with a non-zero code is NOT one of those any more** (h #g215): measured on 2.1.288, a headless child SIGKILLed mid-answer and one killed at its `system`/`init` frame were both resumed afterwards with the conversation intact, and the transcript exists from `init` onward, which is also the first moment this plugin has an id to keep. Forgetting there turned every crash into a full replay (issue #91); the stderr `No conversation found` forget is the backstop for an id that really is unusable. A lookup runs only where the replay was about to happen, and requires the SAME session key, the same `cliPath` (#g98), the transcript file present under `configDir/projects//`, and `continuesRecordedConversation` (the fork rule: recorded chain an exact prefix, only reply content past it, no tool result in the trailing segment). A hit just calls `setClaudeSessionId`, so the existing `--resume` in `buildCliArgs` and the interactive spawn's `resumeSessionId` do the rest. It shares `forkSessions`' system-prompt-snapshot caveat (#g187) exactly as idle-eviction resume always has, which is why it is not opt-in. **The `test` script gives every run a `mktemp -d` `XDG_STATE_HOME`**, for the #g116 reason: fake-CLI turns finish successfully and would otherwise write the operator's real store; `test/isolate.ts` gives every test process its own as well, which also covers a focused run (h #g283). Live on 1.18.34 and 2.0.22. `test/session-resume.test.ts`. (h #g197) **A digest leaves out opencode-dcp's message references, and a record says which way its digests were built** (`DIGEST_VERSION`, `src/session-fork.ts`, h #g258): dcp appends `m0004` to every user text part and completed tool output it hands a provider, numbers in memory, never reuses a number and renumbers from `m0001` when opencode restarts, so after an undo (which removes a message dcp had already numbered) every later message came back under a lower number and the conversation was refused as `conversation-changed`. Measured on opencode 1.19.3 + dcp 3.2.0 with a fake `claude`: an undone conversation started a fresh Claude session after the restart on master and resumed its own on the fix, while a plain one and a compacted one resumed on both. Version 2 strips the XML tag (any attributes, `m`/`b` refs, `BLOCKED`) and the `compact` form's last `@12@` line that dcp's opencode 2 path writes (measured on opencode 2.0.31 with the same fake `claude`, h #g259: an undone message went out as `@4@` before the restart and `@3@` after it, v0.60.1 refused the conversation as `conversation-changed` and the fix resumed it). **A record with no `version` is compared as version 1**, which is why the field exists: without it every dcp conversation would replay once on the restart that installs the upgrade. A message with no reference hashes identically under both, so a non-dcp install's records are unaffected. The in-memory chains (fork fingerprints, `conversation-gap.ts`) are always the current version. **Version 3 leaves out dcp's `` block as well, and the block is also what made `rewound` misfire** (h #g262): dcp appends its MAX CONTEXT LIMIT warning to a message that is ALREADY in the history and goes on appending it to later ones, so a user message goes out on its own turn as the operator wrote it and comes back on the next turn 1,091 characters longer. Measured over 99 of this plugin's Claude CLI transcripts: 32 distinct user messages were seen both with the block and without it (the pair, read off the wire: 141 characters at 21:25:00, 1,232 at 21:27 and three times after), against 15 that differed only by a `` value and **zero by any opencode-authored block**. **Removing a block has to level the gap it leaves**, because which blocks a message carries changes per turn: one copy ends in `\n\n` and the other in `\n\n\n\n`, so when anything was removed the blank-line runs are collapsed and the ends trimmed, bounded and linear (the leading `\s*` is still avoided for #g258's reason). That levelling runs ONLY when a dcp block was actually removed, which is what keeps a dcp-free message hashing identically under versions 2 and 3. - **`resumeAcrossModelChanges` is ON by default and is the other half of the same bug: the model is in the session key too, so changing it mid-conversation replayed the thread exactly as an effort change did** (issue #91, at least 18 replays in one ~15-hour session). `findSiblingResumePoint` reads the record `resumeAfterRestart` already writes, so `resumeAfterRestart: false` turns this off as well and nothing new is persisted. A sibling is matched on `modelSiblingSignature`, the key with its model segment blanked, its `effort=` tail dropped by NAME rather than by position and its context blob cut to `[provider, agent]` (`withoutSpawnSettings`, the same cut `spawnIdentity` makes), which is the exact opposite selection to `forkSiblingSignature`: a fork is another opencode session continuing the same content, this is the same opencode session continuing its own, so cwd, scope, affinity, provider and agent must all match and only the model, the effort and the blob's spawn settings (prompt-cache TTL, `maxTurns=`, `maxBudgetUsd=`, h #g275) may differ (and, since (h #g226), the context blob's PROVIDER element, when an account-provider map is passed in). **A `maxBudgetUsd` change carries too, and that is honest**: `--max-budget-usd` counts per process and starts again on every `--resume` (h #g245), so the carried process gets the new cap from zero, exactly as the in-process carry (h #g270) and a replay into a fresh session would, the replay at a replay's cost. Widening the signature also widens `findForeignAccountSibling`, the `accountGroups` guard's detector, which is the safe direction: before it, a TTL set on one account's provider and not another's hid a cross-group sibling from the guard. **The caller TRANSFERS, never shares**: it kills the sibling's child first and `transferClaudeSession` moves the id, so one Claude conversation has exactly one owner and two children can never append to one transcript. **After an opencode restart (or a handover, h #g269) the sibling's id is in its resume record only**, so the carry passes the id `findSiblingResumePoint` accepted as `transferClaudeSession`'s `recorded` argument (an id in memory still wins), and the record moves with it; and `invalidateOtherSpawnVariants`, with the carry on, no longer forgets the resume record of a stale key this process never held in memory (`forgetClaudeSessionInMemory`, not `deleteClaudeSessionId`), so the lookup can take it past every refusal. Measured on master before the fix: the first model change after a restart replayed as `sibling-carry-over-failed`, and the first effort change as `no-sibling-recorded`, because the old effort's record was deleted before the lookup ran. `test/restart-sibling-carry.test.ts`. (h #g274) Every `findResumePoint` refusal holds (`cliPath` #g98, the transcript on disk) plus two of its own, a sibling that may still be written to (`claudeSessionIsWriting`, never `getActiveProcess`, which touches LRU order) and a key that is not a sibling at all; compaction is out on both sides and a failover switch never takes one. **What it compares is a SECOND chain, `shape`, and the strict one can never match across a model change**: measured on 1.18.35, opencode hands a provider an assistant message's stored reasoning as a `reasoning` part for the model that produced it and FLATTENS it into a leading `text` part for every other model, and a flattened reasoning part is indistinguishable from reply text, so no content rule sees through it. `conversationDigests(prompt, { assistantContent: false })` hashes every user and tool message by content and every assistant message by position alone; `recordResumePoint` writes both and only this lookup reads `shape`. Do not make it the default: the strict chain is what `forkSessions` and `findResumePoint` compare and the only thing that catches regenerated replies under an unchanged prompt. A pre-upgrade record has no `shape` and is simply no candidate. `--resume --model ` is measured on 2.1.288: the resumed conversation answers under the new model and still knows what it was told under the old one. `test/session-model-switch.test.ts`. (h #g215) - **A turn that replays the thread as text says so once, at NOTICE, naming what it refused on**, because the replay is the lossy, expensive path and before this it was invisible unless the operator read DEBUG. The reason is a kebab TOKEN, not a sentence (`no-session-recorded`, `sibling-still-writing`, `transcript-gone`), because `/claude-code-doctor bundle`'s `reason` key is allowlisted as an `enum` and `SAFE_ENUM` forbids spaces: a sentence would arrive redacted. The replay prefix in `src/message-builder.ts` no longer says the previous session "couldn't be resumed", which read as session corruption; it says the conversation is replayed as text because no Claude session was available to continue it. `test/session-model-switch.test.ts`, `test/get-claude-user-message.test.ts`. (h #g215) -- **Every `▌`-led text part the plugin writes must be registered in `PLUGIN_NOTE_MARKERS`** (aside, `TURN_STATS_MARKER`, self-compaction, rate limit, failed result, doctor, `UNATTENDED_REPLAY_MARKER`, `USAGE_LIMIT_MARKER`): none was ever Claude's output. The strip is **part-level and anchored at the start**, so each note needs its **own** text part. A marker nothing writes any more stays on the list (`RATE_LIMIT_MARKER`), because a conversation opened before the upgrade still holds blocks led by it. `test/turn-stats.test.ts` asserts every marker on the list, not only the footer that file is named for. (h #g108, #g194) +- **Every `▌`-led text part the plugin writes must be registered in `PLUGIN_NOTE_MARKERS`** (aside, `TURN_STATS_MARKER`, self-compaction, rate limit, failed result, doctor, `UNATTENDED_REPLAY_MARKER`, `USAGE_LIMIT_MARKER`): none was ever Claude's output. The strip is **part-level and anchored at the start**, so each note needs its **own** text part. A marker nothing writes any more stays on the list (`RATE_LIMIT_MARKER`), because a conversation opened before the upgrade still holds blocks led by it. `test/turn-stats.test.ts` asserts every marker on the list, not only the footer that file is named for, and **scans `src/` for every `export const *_MARKER = "▌` and fails on one missing from the list**: `REFUSAL_FALLBACK_MARKER` shipped in h #g300 unregistered, so its note was replayed as Claude's own words until h #g314. (h #g108, #g194, #g314) - **What a reused child said between turns is replayed led by `UNATTENDED_REPLAY_MARKER` (`▌ **between turns:**`), never as bare text.** The replay itself is right (PR #35's proxy-detach case), but unmarked it read as this turn's answer and a rebuilt transcript handed it back as Claude's reply to the wrong message. The other measured way in: a CLI-side background task finishing after the terminal `result` makes the CLI continue the conversation on its own, so **a single `-p` invocation can emit two `result` frames** (`result_index` 0 then 1, on 2.1.280 as well as 2.1.286), which corrects (h #g104)'s "exactly one terminal `result`". A default install cannot reach that route, because `Bash` and `Task` are proxied. **The block is written only when something renders** (h #g253): a buffer of frames with no narration, which is what a `/btw` asked during a parked proxy call leaves (a status frame for the side call, measured on 2.0.31), used to write the marker over nothing. Dropped lines still get their note, and the `result` handling in the loop runs either way. `test/unattended-replay.test.ts`. (h #g189) - **Auto-continue never fires on current Claude Code CLI**, because the CLI always emits a `stop_reason` and `shouldAutoContinueIncompleteTurn` treats it as authoritative, so `"smart"` behaves as `off`. Do not delete that guard, and do not delete the keyword heuristic below it: it is the fallback for CLIs that omit `stop_reason`. `test/auto-continue.test.ts`. (h #g104) - The one exception is `isTruncationStopReason` (`max_tokens`, plus the `max_output_tokens` alias), authoritative in the other direction and bounded by the attempt and elapsed rails, because a truncated prose answer dies at the `no-activity` gate. - The nudge itself is `runAutoContinue` in `src/turn-controller.ts`, and it owns both log lines: the nudge and the one that says the nudging stopped. **A compaction turn must never be nudged**: `AUTO_CONTINUE_PROMPT` is the inverse of a `/compact` turn's job and the text would land in the stored summary. `autoContinueEnabledFor(compactionMode, configured)` gates it; add a compaction case to any future change here. - **A turn that ends with no text and no tool call gets the `▌ **no reply:**` note and deliberately no nudge**: measured zero silent turns in the whole retained `plugin.log` pair, and a nudge would need a second exception to the `stop_reason` guard. `isSilentTurn`, fired in `completeResult` after the failover return. `test/silent-turn.test.ts`. (h #g157) +- **A message a `UserPromptSubmit` hook ended is a failed turn with a `▌ **prompt blocked:**` note, never an empty reply, and a blocked REPLAY drops its empty session** (`parsePromptBlock`, `formatPromptBlockedNote`, `TurnState.promptBlock` / `ownPromptBlocked`, h #g314). Measured on 2.1.314 and 2.1.322: one `system`/`informational` frame with `prompt_submit_outcome: {kind, prompt_kept, reason}` and `prevent_continuation: true`, then a `success` result with `num_turns: 0` and no API call; 2.1.293 sends the frame with no outcome and a `content` starting `UserPromptSubmit operation blocked by hook`, which is read as `blocked_by_hook`. **The frame's `content` and the result's `result` repeat the whole original prompt**, which is the text a guard refused, so only the outcome and `content`'s first words are read: the note quotes the hook's reason (one line, capped at 300), the WARN carries `kind`, `promptKept` and `reasonChars`, and nothing logs either text. `num_turns === 0` is what makes it this turn's own message: the turn finishes `{unified:"error", raw:}`, no `no reply` note, no `turnStats` footer, no checkpoint. A message steered into a running turn gets the same frame mid-turn while the turn goes on (`num_turns: 2`, measured), and gets the note only. **When the blocked envelope was a replay into a session with none of the conversation (`includeHistoryContext`), `completeResult` kills the child and calls `deleteClaudeSessionId` before recording anything**, so the next message replays again instead of going to an empty session: that is what lost a session's history after a model switch on 2026-11-14 while the `no reply` note said nothing failed. The hook judges the next replay the same way, which is deliberate: relaxing a guard is the operator's call, and the plugin never sets a hook's own bypass variable. Any other blocked message keeps the session and IS recorded as asked, because re-sending it would only be blocked again. A blocked compaction writes no text and ends on its error part (h #g214). The interactive transport does not read the TUI's `promptSubmitEnding` record yet (unmeasured). `test/prompt-blocked.test.ts`. - Its snapshot is **stream-scoped, never the `SinceContinue` counters**, which reset on every nudge. `compactionMode`, `isError` and `enabled === false` each fail a case on their own; `sawQuestion` is redundant only while `content_block_start` counts `AskUserQuestion` as tool activity, so do not "tidy" it away. - **`turnStats` is off by default and must never fire on a compaction turn or a failed one** (summary corruption; the bill belongs with the error). Use the **turn totals** (`msg.usage`) so the line matches `total_cost_usd`, and pass `permission_denials` as **names and ids only**. `test/turn-stats.test.ts`. (h #g109) **The cost the footer prints is the turn's DELTA, not the CLI's total** (h #g257): a headless `total_cost_usd` is the Claude session's running total (h #g245), so until then every footer after a process's first printed the session's spend so far. `takeResultCost` (`src/budget-ledger.ts`) is read ONCE per `result` in the parser and shared with the budget ledger, because it moves the session's baseline; `footerCostUsd` leaves the cost out when there is no baseline AND the process was spawned with `--resume` (a restart's first turn, a fork), because `--resume` restores the running total and the figure may hold every earlier turn. The INFO line keeps the CLI's `costUsd` and adds `turnCostUsd`; `providerMetadata` keeps the CLI's total. Do not "fix" anything by summing totals: that counts every earlier turn again. - **A finish's usage is context occupancy to opencode, so its input side is the turn's LAST real API call, never `result.usage`**, which sums every call: a 14-call turn at 180K real context reported 2,050,806 cache read and opencode auto-compacted. Every finish reporting a result's usage goes through `lastCallContextUsage(state.lastCallUsage, …)`; `lastCallUsage` is the newest `assistant` frame's `message.usage` with non-zero input + cache (a `` frame never overwrites it), output stays the turn total, and `result.usage.iterations` is the last response's server-side field, not a per-call breakdown. `anthropic.cacheCreationInputTokens` must equal the reported cache write, because opencode falls back to it when the usage says 0. A tool-call finish with no `result` yet stays zeros, **and that is measured now, not a precaution** (h #g225): with real context reported there, opencode 1.18.35 and 2.0.22 both auto-compact in the middle of the turn while the CLI is parked in the proxied call, and the call is lost (1.x: rejected as orphaned, and the model tells the operator a permission was denied) or run twice (2.x: the step restarts on a fresh child). Do not "fill in" these zeros for a live context gauge. `turnStats` and `providerMetadata["claude-code"]` keep the turn totals. `test/context-usage.test.ts`. (h #g169) @@ -512,6 +513,7 @@ Opt-in. `spawnInteractiveProcess` returns an `ActiveProcess`-shaped shim so doSt - CLI stream-event parsers and their dedup (`parseRateLimitEvent`, `describeRateLimit`, `parseSystemInit`, `apiKeySourceWarning`, `parseCompactBoundary`, `describeResultFailure`, `parseMcpServerErrors`, `describeMcpServerError`, `snapshotMcpServerErrors`, `parseUnrecognizedModel`, `reportUnrecognizedModel`, `describePluginLoadFailure`, `snapshotPluginLoadFailures`, `parseRefusalFallback`, `formatRefusalFallbackNote`, `reportRefusalFallback`, a between-turns compaction's note): `test/cli-events.test.ts`; the same events through a fake CLI and a real `doStream`, including that a skipped MCP entry warns and changes nothing else about the turn, and a 529 the CLI gave up on (`success` with `is_error`, from the `` reply or from the result alone) ending as an error with its sentence shown once and no footer: `test/cli-events-stream.test.ts`. - The wire-inactivity watchdog's visible note (`formatStreamTimeoutNote`, `CLAUDE_CODE_RESULT_FALLBACK_MS`): `test/result-fallback.test.ts`. - The silent-turn note (`isSilentTurn`, `formatSilentTurnNote`) and every turn it must stay out of: `test/silent-turn.test.ts`. +- A message a `UserPromptSubmit` hook ended (`parsePromptBlock` over 2.1.322's and 2.1.293's frames and the frames that are not a block, the reason's fold and cap, `formatPromptBlockedNote`'s shapes; then a fake CLI driving real `doStream` turns: this turn's own message failing as `blocked_by_hook` with the note and no footer, the session kept and the next message bare, a blocked replay dropping the child and session id and the next message replaying again, the legacy frame, a steered message blocked inside a turn that went on, a blocked compaction ending on its error part with no text, and a secret-like string in the prompt reaching neither the reply nor the log): `test/prompt-blocked.test.ts`. - `/claude-code-doctor` (report formatter, command-registration guard, `checkProxyAuth`, transcript strip, `describeSessionKey`, the skipped-MCP, not-loaded-plugin and background-subagent sections, and the plan-usage opt-in with `wantsPlanUsage`, `parsePlanUsage` and `fetchPlanUsage`): `test/doctor.test.ts`. - `/claude-code-doctor bundle` (the message-allowlist drift guard against `src/`, the pinned list of messages built at runtime, every kind's character class, the key-name sanitizer, `sanitizeArgv`, `sanitizeUrl`, the caps, `readLogTail`, file logging off, and above all the adversarial fixtures that put a fake system prompt, a user prompt, a tool input, an `sk-ant-` key, a bearer token, an `authToken`, an `ANTHROPIC_API_KEY=` value, an MCP env var, a `?token=` URL and the home path into every position a line has and assert none survives): `test/diagnostic-bundle.test.ts`. It uses in-memory fixtures and a stubbed tail read, so it can never append to a live `plugin.log` (h #g116). - The subagent dispatch form (`isSubagentDispatchActive` and every refusal, the one-question first form, the per-type and per-task forms, the `Per type…` account rows and the one third form they share with `Per task…`, the three account widths and their precedence, a per-type account row overriding an account typed on the type's own row, the group restriction on every offered and typed path, `parseCustomChoice` with and without candidates, `parseQuestionAnswers` over the live-measured sentence shapes, the claim store including two concurrent same-type children and the parent check, the TTL, `dispatchAccountCandidates` with and without the cross-group flag, a remembered choice read back after a simulated restart, a remembered model or account that went away, the delete through `deleteActiveProcessesForSession`, and the transcript strip): `test/subagent-dispatch.test.ts`. The file behind `Same as last time` (round trip, restart, two writers merging, a malformed file, a record of the wrong shape, the age cutoff, both caps, the `0600` mode and the fact that nothing but the three strings is written): `test/dispatch-choice-store.test.ts`. The same through a real `doStream` and a fake CLI (the option off, the argv unchanged when it is on, the hold, the release, the child's own `--model` / `CLAUDE_CODE_EFFORT_LEVEL` / account wrapper, two agent types spawning under two different accounts, `Same as last time` surviving a simulated restart, and the dismissal note): `test/subagent-dispatch-stream.test.ts`. diff --git a/TODO.md b/TODO.md index eaca668..b13929c 100644 --- a/TODO.md +++ b/TODO.md @@ -72,25 +72,15 @@ ## Backlog -- 2026-11-14 (evening), diagnosed, not fixed: a replayed thread blocked by a `UserPromptSubmit` hook - ends as a `no reply` turn and the history is lost. Two turns of session - `ses_e324dbf7bffeRHQIz10AIxm7dT` (after a switch from appical Opus 5.5 to default Fable 5.2, and - again after an opencode restart) logged `replaying the conversation as text ... reason: - sibling-conversation-changed` (20:42:45Z, 20:48:39Z; envelopes of 187,540 and 196,636 characters), - then `claude finished the turn without a reply` about 9 s later. Claude Code 2.1.322's transcript - (`~/.claude/projects/-Users-khalil-code-Private-opencode-claude-code-plugin/8ded207b-3255-4627-8a30-70cf0eb0773d.jsonl`, - first 12 records) shows why: the prompt was dequeued and never became a `user` record; the CLI wrote - `system`/`informational` "UserPromptSubmit operation blocked by hook: agent-guard: blocked user - prompt: it contains secret-like values" (`promptSubmitEnding.ending.kind: "blocked_by_hook"`, - `promptKept: false`, `preventContinuation: true`, `AGENT_GUARD_PROMPT_GUARD_MODE` controls it), made - no API call and ended the turn. The plugin wrote the `no reply` note ("Nothing failed and nothing is - pending"), counted the replay as delivered, and ran the next message on the same process with - `includeHistoryContext: false`, so that Claude session never had the conversation. To do: read what a - blocked prompt looks like on the headless stream (the frames before the `result`), name the hook and - its reason in the note, finish as an error, and do not count the replay as delivered. This is a - likely cause of the location-switch empty turn below (a new cwd is a new key, so its next step - replays): check that session's Claude transcript for the same `blocked_by_hook` record before - building anything on the session-key theory. +- 2026-11-14 (evening), the blocked replay: FIXED on `fix/blocked-prompt` (h #g314). A message a + `UserPromptSubmit` hook ends now fails the turn under a `▌ **prompt blocked:**` note quoting the + hook's reason, and a blocked replay drops its empty session so the next message replays again. + Still open from it: (1) why the Opus 5.5 (appical) to Fable 5.2 (default) switch in session + `ses_e324dbf7bffeRHQIz10AIxm7dT` was refused as `sibling-conversation-changed` at all, which is + what made the replay happen; (2) the interactive transport does not read the TUI's + `promptSubmitEnding` record, and how a blocked prompt ends a PTY turn is unmeasured; (3) the + location-switch empty turn below may be the same block: check that session's Claude transcript for + a `blocked_by_hook` record before building anything on the session-key theory. - 2026-11-14 (evening), measured, not fixed: the wire-inactivity watchdog ended a turn while the child lived on, unattached. The Mac idle-slept 21:10:23 to 21:20:56 CET (`pmset -g log`) during a designer subagent's turn (`ses_e24dd447bffe3jnporpawTFbxI`, Claude session `3e7cd878`, about 777K tokens of @@ -208,9 +198,9 @@ them ran in this directory. Questions the maintainer still owes an answer on. Written here the turn they are raised, so they survive context compaction; removed when answered, done or dropped. -- 2026-11-14: the blocked replay (Backlog, 2026-11-14 evening): fix the plugin side now, later, or - drop? Separate from that, agent-guard's prompt guard blocks any replay that quotes a secret-like - value: keep it blocking, or set `AGENT_GUARD_PROMPT_GUARD_MODE` for the plugin's spawns? +- 2026-11-14: agent-guard's prompt guard blocks any replay that quotes a secret-like value (the plugin + side is fixed, h #g314, and never sets the guard's variable itself): keep it blocking, or set + `AGENT_GUARD_PROMPT_GUARD_MODE` for opencode's environment? Your config, not the plugin's. - 2026-11-14: watchdog follow-up, offered by an earlier turn of session `ses_e324dbf7bffeRHQIz10AIxm7dT` (its reasoning went with that session's history): "should the plugin wait a little longer after the CLI reports an API error before it closes the turn? Now, diff --git a/docs/agents-history.md b/docs/agents-history.md index 0908830..99e78fb 100644 --- a/docs/agents-history.md +++ b/docs/agents-history.md @@ -12872,3 +12872,75 @@ Shipped as v0.73.3 on 2026-11-14 (PR #187), a patch, together with h #g312: CI g Windows on the PR head `0167bda`, on the merge commit `436cb0d` before the tag and on the release commit `0a0d534`, the publish confirmed by the `Publish package` step's tail and the version document's shasum (`702fc31b`), with a GitHub Release. + + +## A message a UserPromptSubmit hook blocked read as an empty reply, and a blocked replay lost the history (2026-11-14) + +h #g314. Found on 2026-11-14 in the maintainer's own session `ses_e324dbf7bffeRHQIz10AIxm7dT` +(opencode 2, Claude Code 2.1.322), after a switch from the appical account's Opus 5.5 to the +default account's Fable 5.2. Two turns logged `replaying the conversation as text ... reason: +sibling-conversation-changed` (20:42:45Z and, after an opencode restart, 20:48:39Z; envelopes of +187,540 and 196,636 characters), then `claude finished the turn without a reply` about 9 s later, +and the reply was a `▌ **no reply:**` note saying nothing failed. The next message ran on the same +process with `includeHistoryContext: false`, so that Claude session never had the conversation, and +the model answered a "?" with a status report it had rebuilt from disk. + +Claude Code's transcript (first 12 records, read for their types only) shows why: the prompt was +dequeued and never became a `user` record; the CLI wrote a `system`/`informational` record +"UserPromptSubmit operation blocked by hook: agent-guard: blocked user prompt: it contains +secret-like values" (`promptSubmitEnding.ending.kind: "blocked_by_hook"`, `promptKept: false`), +made no API call and ended the turn. The plugin's log has the result: `numTurns: 0`, `costUsd: 0`, +`isError: false`, `subtype: "success"`. + +Measured with a scratch `UserPromptSubmit` hook (`--setting-sources ""` plus `--settings`, no API +call is made for a blocked prompt): + +- 2.1.314 and 2.1.322, a hook exiting 2 and a hook answering `{"decision":"block"}` alike: one + `system`/`informational` frame, `level: "warning"`, `prevent_continuation: true`, + `prompt_submit_outcome: {kind: "blocked_by_hook", prompt_kept: false, reason: }`, then `result` `success`, `is_error: false`, `num_turns: 0`, `stop_reason: null`. +- 2.1.293: the same frame with no `prompt_submit_outcome`. +- Every version: the frame's `content` is "UserPromptSubmit operation blocked by hook:\n[]: \n\n\nOriginal prompt: ", and the result's `result` text + repeats it. The plugin never rendered it (it renders `result` only when `is_error`), and nothing + here may read past its first words: that prompt is the text the guard refused. +- A message queued while a turn runs (the plugin's forwarded user messages beside a proxied tool + result) is judged too: with a hook that blocks only `BLOCKME`, a first message ran a 8-second + Bash call, a second message sent 4 s in was blocked by the same frame mid-turn, and the turn went + on and answered (`num_turns: 2`). So `num_turns === 0` is what says it was this turn's own + message. +- The CLI's own list of kinds (2.1.322's schema): `blocked_by_hook` (a hook answered with a block), + `stopped_by_hook` (a hook answered `continue: false`), `dropped_by_hook` and `not_passed_on` (a + plugin's code module), `no_verdict` (no hook gave a verdict and Claude Code ended the prompt). + +What changed: + +- `parsePromptBlock` reads the outcome (or the 2.1.293 shape) and nothing else; the WARN carries + `kind`, `promptKept` and `reasonChars`, and the note quotes the reason on one line, capped at 300 + characters. +- This turn's own message blocked: the turn finishes `{unified: "error", raw: }` under a + `▌ **prompt blocked:**` note, with no `no reply` note and no `turnStats` footer. The session is + kept and the message is recorded as asked, so the next message goes to the same process bare; + sending the blocked one again would only be blocked again. +- A blocked REPLAY (the envelope carried the history into a session that had none): the child is + killed and `deleteClaudeSessionId` drops the id, the served chain and the resume record before + anything is recorded, so the next message replays the history again. The hook judges that replay + the same way, which is deliberate: a guard's verdict is the operator's to change, and the plugin + sets no hook's bypass variable. The note says so and names the way out (switch back to the model + or account that answered before, or let the hook pass the replay). +- A steered message blocked inside a turn that went on: the note only, the turn served. +- A blocked compaction writes no text and ends on its error part, as every failed compaction does + (h #g214). + +Found on the way: `REFUSAL_FALLBACK_MARKER` (h #g300) was never added to `PLUGIN_NOTE_MARKERS`, +so a `▌ **refusal fallback:**` note was replayed to Claude as its own words, while AGENTS.md said it +was on the list. Both markers are on it now, and `test/turn-stats.test.ts` scans `src/` for every +`export const *_MARKER = "▌` and fails on one that is not. + +Not done: the interactive transport does not read the TUI's `promptSubmitEnding` record, and how a +blocked prompt ends a PTY turn is unmeasured. Not diagnosed here: why the sibling carry was refused +as `sibling-conversation-changed` in the first place, which is what made the replay happen. + +Tests: `test/prompt-blocked.test.ts` (the parser, the note, and a fake CLI replaying the measured +frames through real `doStream` turns, with a secret-like string in the prompt that must reach +neither the reply nor the log), and the marker scan in `test/turn-stats.test.ts`. diff --git a/docs/troubleshooting/symptoms.md b/docs/troubleshooting/symptoms.md index c6609b9..3ce7787 100644 --- a/docs/troubleshooting/symptoms.md +++ b/docs/troubleshooting/symptoms.md @@ -55,6 +55,7 @@ Four checks answer almost everything. Run them in this order, and stop as soon a | `▌ **model fallback:**` on a turn you expected to run on a specific model | The note itself, which names the model that failed and why | Working as configured: your [`fallbackModels`](../configuration/subagents.md#fallback-model-chain) chain moved the turn. `model_not_found` means fix the first id. `out of usage on this account` means that account's cap, and the reason you got a chain rather than the [account failover](../configuration/accounts.md#account-failover) form is that the form is off (its default) or had no other account to offer. The chain never changes account, only model. | | A reply that is only *"API Error: Opus 5.5's safeguards flagged this session…"*, finished as an error | The model the conversation is on | A safety classifier stopped the reply twice. Claude Code's own fallback to another model is off by default (`CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK`), so the turn ends here: rephrase, or pick another model. See [Claude Code's own fallbacks](../configuration/subagents.md#claude-codes-own-fallbacks). | | `▌ **refusal fallback:**` in a reply, and the sidebar names a model you did not pick | Whether `CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK=0` is in opencode's environment | Working as configured: you kept Claude Code's refusal fallback, so it answered on the model the note names and stays on it until the process restarts. Unset the variable to have a refusal end the turn instead. | +| `▌ **prompt blocked:**` instead of an answer, the turn marked as failed | The quoted reason in the note, and which of your Claude Code `UserPromptSubmit` hooks wrote it | Working as designed: one of your own Claude Code hooks (agent-guard, for one, refuses a prompt that looks like it holds a secret) ended the message before the model saw it, and no model was called. Send it again without what the hook objected to, or change the hook. When the note says the message carried the conversation's earlier messages, it was the replay of the history after a model or account switch: that history did not reach Claude, so the next message replays it again, and the hook will judge it the same way. Switch back to the model or account that answered before to keep the history, or let the hook pass the replay. A message you sent while Claude was working gets the same note under an answer that did not see it. Older plugins showed `▌ **no reply:**` for all of this, said nothing failed, and after a blocked replay sent every later message to a Claude session that held none of the conversation. | | A turn that called a tool and then stopped with no answer and no error | The `plugin` version in `/claude-code-doctor`, and `rendering a reply claude code sent without streaming` in the log | Upgrade. Claude Code had resent the call without streaming (a 404 on the streaming endpoint, or a stream cut early), and its whole-message reply was dropped. Now it is shown. | | A chain is declared but a refused model still kills the turn | Grep `plugin.log` for `fallback model refused: unknown model` | Every entry has to be a model id this plugin registers; an unknown one is skipped with that warning, and a chain whose entries are all unknown is an empty chain. The other empty-chain case is a list containing only the model the turn already runs on, which is dropped from its own chain. Compaction turns, title stubs and the interactive transport never fall back at all. | | On opencode 2, a subagent you asked for on a particular model ran on another | The subagent's tool row: does its input carry a `model`? | No `model` there means Claude did not pass one, so opencode picked the model as usual. Name the model by its id in your message, such as `claude-sonnet-5-5`, or by its full reference for another account; see [A model you name in the conversation](../configuration/subagents.md#a-model-you-name-in-the-conversation-opencode-2). Before 0.60.0 the plugin's `task` tool had no `model` at all. If the row does carry one and the subagent's sidebar row shows a different model, that is a bug: attach `/claude-code-doctor bundle` to the report. | diff --git a/skills/claude-code-plugin/SKILL.md b/skills/claude-code-plugin/SKILL.md index 9c7da16..483f08e 100644 --- a/skills/claude-code-plugin/SKILL.md +++ b/skills/claude-code-plugin/SKILL.md @@ -1506,6 +1506,20 @@ at 200 characters, because its stdout is spliced into the model's context. The p never passes `--include-hook-events`, so only `SessionStart` (and `Setup`) hooks are reported at all; `cancelled` is not a failure, since an abort produces it. +A `UserPromptSubmit` hook that ends a message is not in the doctor: it is a +`▌ **prompt blocked:**` note in the reply, quoting the hook's reason (h #g314). Claude +Code reports it as a `success` with no API call, so older plugins showed +`▌ **no reply:**` instead. The turn now finishes as an error (`blocked_by_hook`, or the +CLI's other kinds: `stopped_by_hook`, `dropped_by_hook`, `not_passed_on`, `no_verdict`). +When the blocked message was the replay of the history after a model or account switch, +the empty Claude session is dropped, so the next message replays the history again rather +than continuing without it; the hook judges that replay the same way, so the user's +choices are to switch back to the model or account that answered before, to change the +hook, or to start a new session. A message steered into a running turn that a hook +blocks gets the note under an answer that did not see it, and the turn is not failed. +The plugin never sets or suggests a hook's own bypass variable (agent-guard's +`AGENT_GUARD_PROMPT_GUARD_MODE`, say): relaxing a guard is the user's decision. + A **Background subagents** section is always printed: first `running now: N (of M started by this process)`, then whether `background` was offered to Claude and `task_status` / `task_cancel` registered, the opencode major, what decided diff --git a/src/claude-code-language-model.ts b/src/claude-code-language-model.ts index 44b90f8..2df3b4c 100644 --- a/src/claude-code-language-model.ts +++ b/src/claude-code-language-model.ts @@ -4398,12 +4398,33 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { const completeResult = (msg: ClaudeStreamMessage) => { if (state.controllerClosed) return + // A hook ended the replay of this conversation's history into a + // session that had none of it (h #g314). The session is empty, but + // everything below would record it as the one that continues the + // conversation, and the next message would go to it bare: that is + // how a model switch lost a session's history without a word. So + // nothing is recorded, and the child and its session id go, which + // makes the next message replay the history again. + const blockedReplay = + state.ownPromptBlocked && + state.promptBlock?.promptKept === false && + includeHistoryContext && + !compactionMode + if (blockedReplay) { + deleteActiveProcess(sk) + deleteClaudeSessionId(sk) + log.notice("a hook ended the replayed history; the empty claude session was dropped", { + sessionKey: sk, + kind: state.promptBlock?.kind, + }) + } // Which Claude session answered this conversation, for the next // opencode process. Only after a turn that was served: a failed one // may leave a transcript the plugin itself would not resume. if ( self.config.resumeAfterRestart !== false && !compactionMode && + !blockedReplay && msg.is_error !== true && typeof msg.session_id === "string" ) { @@ -4421,14 +4442,19 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { // elsewhere in between (h #g239). On every `result`, served or not: // the CLI received the envelope either way, and a turn it refused is // in its transcript as a question without an answer, so replaying - // that question later would hand it the same message twice. + // that question later would hand it the same message twice. A + // message a hook ended counts as asked too, though the CLI dropped it + // (h #g314): sending it again would only be ended again. // // A served turn also leaves its checkpoint: the transcript entry its // reply ended on, which an undo or edit later cuts a copy of the // session at (h #g282). Only a reply that ended on Claude's own // words, in the session this result names: a turn that failed, or // whose last record is a tool call, is no place to cut. - if (!compactionMode) { + // + // Not after a blocked replay: the CLI never received that envelope + // (`prompt_kept: false`), and the session it went to is gone. + if (!compactionMode && !blockedReplay) { const reply = state.lastReplyEntry const checkpoint = msg.is_error !== true && @@ -4841,6 +4867,7 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { fastMode, planModeQuestionActive, interactive: useInteractive, + replayCarried: includeHistoryContext && !compactionMode, sourceAccount: limitAccount, usageAccount: spawnedAccount, // The config dir of the account that ran, so an account-block note diff --git a/src/cli-events.ts b/src/cli-events.ts index a539049..89dca1b 100644 --- a/src/cli-events.ts +++ b/src/cli-events.ts @@ -1119,6 +1119,124 @@ export function formatSilentTurnNote(hadReasoning: boolean): string { ) } +// --------------------------------------------------------------------------- +// a message a UserPromptSubmit hook kept from Claude +// --------------------------------------------------------------------------- + +export const PROMPT_BLOCKED_MARKER = "▌ **prompt blocked:**" + +/** + * How Claude Code ended a message before the model saw it. `kind` is the CLI's + * own word (`blocked_by_hook`, `stopped_by_hook`, `dropped_by_hook`, + * `not_passed_on`, `no_verdict` in 2.1.322), `promptKept` says whether the + * message is in its transcript anyway, and `reason` is the hook's own sentence. + */ +export interface PromptBlock { + kind: string + promptKept: boolean + reason?: string +} + +/** What 2.1.293 and older start the frame's `content` with; they send no outcome. */ +const LEGACY_PROMPT_BLOCKED_PREFIX = "UserPromptSubmit operation blocked by hook" + +/** Long enough for a hook's sentence, short enough to sit in one note. */ +const PROMPT_BLOCK_REASON_MAX = 300 + +/** + * The `system`/`informational` frame Claude Code writes when a + * `UserPromptSubmit` hook (or a plugin's code module) ends a message: measured + * on 2.1.314 and 2.1.322 as `prompt_submit_outcome: {kind, prompt_kept, + * reason}` beside `prevent_continuation: true`, and on 2.1.293 as the same + * frame with only `prevent_continuation` and a `content` naming the block. The + * frame's `content`, and the `result` text after it, repeat the WHOLE original + * prompt, so neither is ever read past its first words: a prompt a guard + * blocked is exactly the text that must not reach a log. (h #g314) + */ +export function parsePromptBlock(msg: ClaudeStreamMessage): PromptBlock | null { + if (msg.type !== "system" || msg.subtype !== "informational") return null + const outcome = msg.prompt_submit_outcome + if (isRecord(outcome)) { + const kind = str(outcome.kind) + if (!kind) return null + const reason = str(outcome.reason)?.replace(/\s+/g, " ").trim() + return { + kind, + promptKept: outcome.prompt_kept === true, + ...(reason + ? { + reason: + reason.length > PROMPT_BLOCK_REASON_MAX + ? `${reason.slice(0, PROMPT_BLOCK_REASON_MAX - 3)}...` + : reason, + } + : {}), + } + } + if ( + msg.prevent_continuation === true && + typeof msg.content === "string" && + msg.content.startsWith(LEGACY_PROMPT_BLOCKED_PREFIX) + ) { + return { kind: "blocked_by_hook", promptKept: false } + } + return null +} + +function describePromptBlockKind(kind: string, subject: string): string { + switch (kind) { + case "blocked_by_hook": + return `A UserPromptSubmit hook blocked ${subject}` + case "stopped_by_hook": + return `A UserPromptSubmit hook stopped the turn on ${subject}` + case "dropped_by_hook": + case "not_passed_on": + return `A Claude Code plugin did not pass ${subject} on` + case "no_verdict": + return `Claude Code ended ${subject} because no UserPromptSubmit hook gave a verdict` + default: + return `Claude Code did not send ${subject} on (${kind})` + } +} + +/** + * The note for a message Claude never answered because a hook ended it. Three + * shapes: the turn's own message (`midTurn` false), which fails the turn; a + * message steered into a turn that went on and answered (`midTurn`), which does + * not; and the turn's own message when it carried the conversation's replayed + * history into a session that had none (`carriedHistory`), where the session is + * dropped so the next message replays again rather than going on without it. + * The hook's reason is quoted, never the message. + */ +export function formatPromptBlockedNote( + block: PromptBlock, + options: { midTurn: boolean; carriedHistory: boolean }, +): string { + const subject = options.midTurn + ? "a message sent while Claude was working" + : "this message" + const reason = block.reason ? ` ("${block.reason}")` : "" + let after: string + if (options.midTurn) { + after = + ", so it never reached Claude; the answer above did not see it. Send it again without what " + + "the hook objected to." + } else if (options.carriedHistory) { + after = + ". It carried this conversation's earlier messages, replayed as text because no Claude " + + "session could continue them, so Claude has none of them, and no model was called. The next " + + "message replays them again and the hook will judge it the same way. To keep the history, " + + "switch back to the model or account that answered before, or let the hook pass the replay." + } else if (block.promptKept) { + after = " before Claude answered, and no model was called." + } else { + after = + ", so nothing reached Claude and no model was called. Send it again without what the hook " + + "objected to." + } + return `\n${PROMPT_BLOCKED_MARKER} ${describePromptBlockKind(block.kind, subject)}${reason}${after}\n` +} + // --------------------------------------------------------------------------- // output the child wrote while no turn was listening // --------------------------------------------------------------------------- diff --git a/src/diagnostic-bundle.ts b/src/diagnostic-bundle.ts index fd96c2a..70d53e2 100644 --- a/src/diagnostic-bundle.ts +++ b/src/diagnostic-bundle.ts @@ -145,6 +145,8 @@ export const BUNDLE_DATA_ALLOWLIST: Readonly> = anthropicApiKeyInEnv: "flag", includeHistoryContext: "flag", resumable: "flag", + // Whether a message a hook ended is in Claude's transcript anyway (h #g314). + promptKept: "flag", interactive: "flag", interactiveTransport: "flag", isError: "flag", @@ -183,6 +185,8 @@ export const BUNDLE_DATA_ALLOWLIST: Readonly> = cacheWriteTokens: "count", code: "count", count: "count", + // The length of a hook's reason, never its text (h #g314). + reasonChars: "count", dropped: "count", exitCode: "count", historyLength: "count", diff --git a/src/log-messages.ts b/src/log-messages.ts index 2fcc13d..1c6a870 100644 --- a/src/log-messages.ts +++ b/src/log-messages.ts @@ -16,6 +16,7 @@ export const PLUGIN_LOG_MESSAGES: ReadonlySet = new Set([ "Code Mode execute not forwarded: read-only permission preset", "MCP server asked for operator input and was declined: a headless Claude Code session cannot prompt, so its elicitation can only be refused. Run that server's flow in Claude Code directly, or configure it not to elicit.", "MCP tool not routed through the proxy: another proxy tool already holds that name, and it keeps it", + "a hook ended the replayed history; the empty claude session was dropped", "a remembered subagent dispatch account is no longer available", "account failover declined; ending the turn", "accountGroups must be an object mapping an account name to a group name; ignoring it", @@ -57,6 +58,7 @@ export const PLUGIN_LOG_MESSAGES: ReadonlySet = new Set([ "claude cli < 2.1.142 detected; Opus 4.7 thinking summaries unavailable. Run `npm i -g @anthropic-ai/claude-code` to upgrade.", "claude cli does not support --plugin-dir; opencode skills will not be bridged. Run `npm i -g @anthropic-ai/claude-code` to upgrade.", "claude code compacted its own context", + "claude code ended a message before the model saw it", "claude code moved the conversation to another model after a refusal", "claude code reset its conversation", "claude could not compact the conversation; no summary was stored", diff --git a/src/message-builder.ts b/src/message-builder.ts index 3c945b7..5982eef 100644 --- a/src/message-builder.ts +++ b/src/message-builder.ts @@ -17,7 +17,9 @@ import { INLINE_ASIDE_MARKER, LEGACY_INLINE_ASIDE_MARKERS } from "./btw-command. import { COMPACT_BOUNDARY_MARKER, CONVERSATION_RESET_MARKER, + PROMPT_BLOCKED_MARKER, RATE_LIMIT_MARKER, + REFUSAL_FALLBACK_MARKER, RESULT_ERROR_MARKER, SILENT_TURN_MARKER, STREAM_TIMEOUT_MARKER, @@ -67,6 +69,8 @@ const PLUGIN_NOTE_MARKERS = [ STALE_BUILD_MARKER, SUBAGENT_DISPATCH_MARKER, BUDGET_MARKER, + REFUSAL_FALLBACK_MARKER, + PROMPT_BLOCKED_MARKER, ] function isPluginNote(part: any): boolean { diff --git a/src/stream-parser.ts b/src/stream-parser.ts index 1ce6792..7f2c92f 100644 --- a/src/stream-parser.ts +++ b/src/stream-parser.ts @@ -15,10 +15,12 @@ import { forgetConversationCheckpoints } from "./conversation-gap.js" import { reportFastModeState } from "./fast-mode.js" import { describeResultFailure, + formatPromptBlockedNote, formatRefusalFallbackNote, formatResultFailureNote, isRateLimitRejected, parseCredentialExpiresAt, + parsePromptBlock, parseRateLimitEvent, parseRefusalFallback, reportCompactBoundary, @@ -112,6 +114,12 @@ export interface StreamParserContext { planModeQuestionActive: boolean /** The interactive transport, whose TUI parks on `ExitPlanMode`'s dialog. */ interactive: boolean + /** + * This turn's envelope replays the conversation's history as text into a + * session that held none of it, so a hook ending it leaves that session + * empty (h #g314). + */ + replayCarried: boolean /** The account this turn spawned on; the account-block note names it. */ sourceAccount: string /** @@ -344,6 +352,25 @@ export function createLineHandler( reportHookEvent(msg) } + // A `UserPromptSubmit` hook (or a Claude plugin's code module) ended a + // message before the model saw it. This turn's own message then ends the + // turn on a `success` result with no API call, which read as an empty + // reply under a `no reply` note saying nothing failed; one steered into a + // running turn is dropped while the turn goes on. Which of the two it was + // is decided at the `result`. Only the outcome is read: the frame's + // `content` repeats the whole prompt the hook refused. (h #g314) + const promptBlock = parsePromptBlock(msg) + if (promptBlock) { + state.promptBlock = promptBlock + log.warn("claude code ended a message before the model saw it", { + sessionKey: state.sessionKey, + kind: promptBlock.kind, + promptKept: promptBlock.promptKept, + reasonChars: promptBlock.reason?.length ?? 0, + }) + return + } + // The CLI is still inside a tool it is running itself. Nothing is // enqueued: the watchdog reset this frame is worth already happened // at the top of the handler, and the rest is a log line naming the @@ -1396,6 +1423,42 @@ export function createLineHandler( : "error") } + // A hook ended this turn's own message (h #g314): Claude Code made no + // API call and still labels the result `success` (its text repeats the + // whole prompt, so it is never rendered). The turn finishes as an error + // named for how the message ended, under a note quoting the hook's + // reason; `completeResult` drops the session when the message was a + // replay of the history into a session that had none. A message steered + // into a turn that went on and answered gets the note only. A + // compaction turn writes no note, because what it says is stored as the + // summary; its error part names the cause instead (h #g214). + if (state.promptBlock) { + const block = state.promptBlock + state.ownPromptBlocked = + typeof msg.num_turns === "number" + ? msg.num_turns === 0 + : !state.sawVisibleText && !state.sawToolActivity && !state.sawProxyActivity + if (state.ownPromptBlocked) { + state.resultFailure ??= block.kind + if (ctx.compactionMode) { + state.compactionFailureText ??= block.reason + ? `A UserPromptSubmit hook ended the request: ${block.reason}` + : "A UserPromptSubmit hook ended the request." + } + } + if (!ctx.compactionMode) { + state.controller.enqueue({ + type: "text-delta", + id: state.startTextBlock(), + delta: formatPromptBlockedNote(block, { + midTurn: !state.ownPromptBlocked, + carriedHistory: state.ownPromptBlocked && !block.promptKept && ctx.replayCarried, + }), + }) + state.endTextBlock() + } + } + // Some CLI failures only include user-readable text in // `result.result` (no prior assistant text blocks). Emit it so // opencode users don't see a blank turn. The one exception is a limit @@ -1521,7 +1584,14 @@ export function createLineHandler( // Never on a compaction turn (the footer would be appended to // what opencode stores as the summary) and never on a failed // one (the error is the thing to read, not the bill). - if (ctx.config.turnStats && !ctx.compactionMode && !msg.is_error && !failure) { + if ( + ctx.config.turnStats && + !ctx.compactionMode && + !msg.is_error && + !failure && + // A message a hook ended was not served either (h #g314). + !state.ownPromptBlocked + ) { const footer = formatTurnStatsBlock({ ...turnStats, costUsd: footerCostUsd( diff --git a/src/turn-state.ts b/src/turn-state.ts index 5f1c578..1f492e4 100644 --- a/src/turn-state.ts +++ b/src/turn-state.ts @@ -11,6 +11,7 @@ import type { PendingProxyCall } from "./proxy-broker.js" import type { AutoContinueState } from "./auto-continue.js" import type { ModelRefusal } from "./model-fallback.js" import type { AccountBlockKind } from "./account-failover.js" +import type { PromptBlock } from "./cli-events.js" /** * The turn's own mutable state, lifted out of `doStreamForHost`'s `start()` @@ -313,6 +314,15 @@ export interface TurnState { accountBlock: AccountBlockKind | null /** Set only when a fallback is armed, so a turn with no chain is unchanged. */ modelRefusal: ModelRefusal | null + /** + * A message Claude Code ended before the model saw it (a `UserPromptSubmit` + * hook), from its `system`/`informational` frame. Whether it was this turn's + * own message or one steered into a turn that went on is only known at the + * `result`, which sets `ownPromptBlocked`. (h #g314) + */ + promptBlock: PromptBlock | null + /** This turn's own message was ended: no API call, nothing answered. */ + ownPromptBlocked: boolean // ---- The batched drain -------------------------------------------------- @@ -503,6 +513,8 @@ export function createTurnState(init: TurnStateInit): TurnState { compactionFailureText: null, accountBlock: null, modelRefusal: null, + promptBlock: null, + ownPromptBlocked: false, subagentDispatchForm: null, drainBuffer: [], diff --git a/src/types.ts b/src/types.ts index 4ef42e9..a16bb8e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1267,6 +1267,16 @@ export interface ClaudeStreamMessage { api_refusal_category?: string | null retracted_message_uuids?: unknown + /** + * On a `system`/`informational` that ends a message before the model saw it + * (a `UserPromptSubmit` hook, Claude Code 2.1.314 and later): how it ended. + * `content` beside it repeats the whole original prompt, so only its first + * words are ever read. Read by `parsePromptBlock` (h #g314). + */ + prompt_submit_outcome?: unknown + prevent_continuation?: boolean + content?: unknown + message?: { role?: string model?: string diff --git a/test/prompt-blocked.test.ts b/test/prompt-blocked.test.ts new file mode 100644 index 0000000..59b47aa --- /dev/null +++ b/test/prompt-blocked.test.ts @@ -0,0 +1,437 @@ +/** + * A message a `UserPromptSubmit` hook ended before the model saw it (h #g314). + * + * Claude Code writes one `system`/`informational` frame for it and then a + * `success` result with no API call, so until this the plugin filed the turn + * as an empty reply under a `no reply` note that said nothing failed. When the + * blocked message was the replay of a conversation's history into a session + * that had none, the session was recorded as the one that continues the + * conversation, and every later message went to it with no history at all. + * + * The frames below are the ones measured on Claude Code 2.1.322 (and 2.1.314) + * and 2.1.293 with a hook that blocks, copied in shape: the frame's `content` + * and the result's `result` repeat the whole prompt, which is why every test + * checks that a secret-like string in the prompt reaches neither the reply nor + * the log. + * + * Usage: npx tsx --test test/prompt-blocked.test.ts + */ +import "./isolate.js" +import assert from "node:assert/strict" +import { after, test } from "node:test" +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +import type { LanguageModelV3CallOptions } from "@ai-sdk/provider" +import { + PROMPT_BLOCKED_MARKER, + SILENT_TURN_MARKER, + formatPromptBlockedNote, + parsePromptBlock, +} from "../src/cli-events.js" +import { _resetServedConversations } from "../src/conversation-gap.js" +import { createClaudeCode } from "../src/index.js" +import { _resetLoggerForTests, configureLogger } from "../src/logger.js" +import { + deleteClaudeSessionId, + getActiveProcess, + getClaudeSessionId, + killAllActiveProcesses, + sessionKey, +} from "../src/session-manager.js" +import { TURN_STATS_MARKER } from "../src/turn-stats.js" + +after(() => { + killAllActiveProcesses() +}) + +const SECRET = "FAKESECRET-0123456789abcdef" +const REASON = "probe-guard: blocked user prompt: it contains secret-like values" + +const u = (text: string) => ({ role: "user" as const, content: [{ type: "text" as const, text }] }) +const a = (text: string) => ({ + role: "assistant" as const, + content: [{ type: "text" as const, text }], +}) + +// --------------------------------------------------------------------------- +// The frame +// --------------------------------------------------------------------------- + +/** 2.1.322's frame for `exit 2` from a hook, as measured. */ +const blockedFrame = (prompt: string) => ({ + type: "system", + subtype: "informational", + content: + "UserPromptSubmit operation blocked by hook:\n[/hooks/guard.sh]: " + + REASON + + "\n\n\nOriginal prompt: " + + prompt, + level: "warning", + prevent_continuation: true, + prompt_submit_outcome: { kind: "blocked_by_hook", prompt_kept: false, reason: REASON }, +}) + +test("the 2.1.314+ frame is read off its outcome, never off its content", () => { + const block = parsePromptBlock(blockedFrame(`hello ${SECRET}`) as any) + assert.deepEqual(block, { kind: "blocked_by_hook", promptKept: false, reason: REASON }) + assert.doesNotMatch(JSON.stringify(block), new RegExp(SECRET)) +}) + +test("2.1.293's frame, which carries no outcome, still reads as a block", () => { + const frame: any = blockedFrame(`hello ${SECRET}`) + delete frame.prompt_submit_outcome + assert.deepEqual(parsePromptBlock(frame), { kind: "blocked_by_hook", promptKept: false }) +}) + +test("every other frame is not a block", () => { + assert.equal(parsePromptBlock({ type: "system", subtype: "init" } as any), null) + assert.equal( + parsePromptBlock({ type: "system", subtype: "informational", content: "Compacting" } as any), + null, + ) + assert.equal( + parsePromptBlock({ + type: "system", + subtype: "informational", + prevent_continuation: true, + content: "A Stop hook ended the turn", + } as any), + null, + ) + assert.equal( + parsePromptBlock({ type: "system", subtype: "informational", prompt_submit_outcome: {} } as any), + null, + ) + assert.equal(parsePromptBlock({ type: "result", subtype: "success" } as any), null) +}) + +test("a hook's reason is folded to one line and capped", () => { + const long = parsePromptBlock({ + type: "system", + subtype: "informational", + prompt_submit_outcome: { kind: "blocked_by_hook", prompt_kept: false, reason: `a\n\n b ${"x".repeat(500)}` }, + } as any) + assert.ok(long?.reason) + assert.ok(long.reason.startsWith("a b x")) + assert.equal(long.reason.length, 300) + assert.ok(long.reason.endsWith("...")) +}) + +test("a hook that stopped the turn kept the prompt, and says so", () => { + const block = parsePromptBlock({ + type: "system", + subtype: "informational", + prompt_submit_outcome: { kind: "stopped_by_hook", prompt_kept: true }, + } as any) + assert.deepEqual(block, { kind: "stopped_by_hook", promptKept: true }) + const note = formatPromptBlockedNote(block!, { midTurn: false, carriedHistory: false }) + assert.match(note, /stopped the turn on this message before Claude answered/) +}) + +test("the note has one shape per case and never an em dash", () => { + const block = { kind: "blocked_by_hook", promptKept: false, reason: REASON } + const own = formatPromptBlockedNote(block, { midTurn: false, carriedHistory: false }) + const replay = formatPromptBlockedNote(block, { midTurn: false, carriedHistory: true }) + const steered = formatPromptBlockedNote(block, { midTurn: true, carriedHistory: false }) + for (const note of [own, replay, steered]) { + assert.ok(note.trimStart().startsWith(PROMPT_BLOCKED_MARKER), note) + assert.match(note, new RegExp(REASON)) + assert.doesNotMatch(note, /—/) + } + assert.match(own, /nothing reached Claude and no model was called/) + assert.match(replay, /earlier messages/) + assert.match(replay, /next message replays them again/) + assert.match(steered, /a message sent while Claude was working/) + assert.match(steered, /the answer above did not see it/) + const dropped = formatPromptBlockedNote( + { kind: "dropped_by_hook", promptKept: false }, + { midTurn: false, carriedHistory: false }, + ) + assert.match(dropped, /A Claude Code plugin did not pass this message on/) + assert.doesNotMatch(dropped, /\("/, "no reason, no quote") +}) + +// --------------------------------------------------------------------------- +// Through a real doStream +// --------------------------------------------------------------------------- + +function fixture(settings: Record = {}) { + const cwd = mkdtempSync(join(tmpdir(), "opencode-prompt-blocked-")) + const cliPath = join(cwd, "fake-claude.cjs") + const record = join(cwd, "envelopes.jsonl") + const allow = join(cwd, "allow") + writeFileSync( + cliPath, + `#!${process.execPath} +const fs = require("node:fs") +const readline = require("node:readline") +if (process.argv.includes("--version")) { + console.log("2.1.322") + process.exit(0) +} +const session = "session-" + process.pid +const emit = (message) => console.log(JSON.stringify({ session_id: session, ...message })) +const REASON = ${JSON.stringify(REASON)} +const blockedContent = (prompt) => + "UserPromptSubmit operation blocked by hook:\\n[/hooks/guard.sh]: " + REASON + + "\\n\\n\\nOriginal prompt: " + prompt +const result = (turns, text) => emit({ type: "result", subtype: "success", is_error: false, + num_turns: turns, result: text, total_cost_usd: turns ? 0.001 : 0, + usage: { input_tokens: turns, output_tokens: turns } }) +const say = (text) => emit({ type: "assistant", message: { role: "assistant", + stop_reason: "end_turn", content: [{ type: "text", text }] } }) +let started = false +readline.createInterface({ input: process.stdin }).on("line", (line) => { + const envelope = JSON.parse(line) + if (envelope.type !== "user") return + fs.appendFileSync(${JSON.stringify(record)}, JSON.stringify({ + pid: process.pid, argv: process.argv.slice(2), stdin: line, + }) + "\\n") + if (!started) { + started = true + emit({ type: "system", subtype: "init" }) + } + const prompt = envelope.message.content.map((part) => part.text ?? "").join("\\n") + const allowed = fs.existsSync(${JSON.stringify(allow)}) + if (prompt.includes("BLOCKME") && !allowed) { + const content = blockedContent(prompt) + emit({ type: "system", subtype: "informational", content, level: "warning", + prevent_continuation: true, + prompt_submit_outcome: { kind: "blocked_by_hook", prompt_kept: false, reason: REASON } }) + return result(0, content) + } + if (prompt.includes("LEGACYBLOCK")) { + const content = blockedContent(prompt) + emit({ type: "system", subtype: "informational", content, level: "warning", + prevent_continuation: true }) + return result(0, content) + } + if (prompt.includes("STEER")) { + say("working") + emit({ type: "system", subtype: "informational", content: blockedContent("BLOCKME steered"), + level: "warning", prevent_continuation: true, + prompt_submit_outcome: { kind: "blocked_by_hook", prompt_kept: false, reason: REASON } }) + say("done after the steer") + return result(2, "done after the steer") + } + say("answered by " + process.pid) + result(1, "answered by " + process.pid) +}) +`, + { mode: 0o755 }, + ) + const modelId = "claude-haiku-4-5" + const provider = createClaudeCode({ + cwd, + cliPath, + bridgeOpencodeMcp: false, + proxyOpencodeMcpTools: false, + proxyTools: [], + interactive: false, + autoContinueIncompleteTurns: false, + resumeAfterRestart: false, + turnStats: true, + ...settings, + }) + const key = sessionKey(cwd, `${modelId}::tools::conversation::context=["claude-code","build"]`) + const turn = async (prompt: unknown[], agent = "build") => { + const options: LanguageModelV3CallOptions = { + tools: [{ type: "function", name: "read", inputSchema: { type: "object" } }], + providerOptions: { + "claude-code": { opencodeSessionID: "conversation", opencodeAgent: agent }, + }, + prompt: prompt as any, + } + const response = await provider.languageModel(modelId).doStream(options) + const parts: any[] = [] + for await (const part of response.stream) parts.push(part) + const text = parts + .filter((part) => part.type === "text-delta") + .map((part) => part.delta) + .join("") + const finish = parts.find((part) => part.type === "finish") + const errors = parts.filter((part) => part.type === "error") + return { text, finish, errors } + } + const envelopes = (): Array<{ pid: number; argv: string[]; stdin: string }> => + existsSync(record) + ? readFileSync(record, "utf8") + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line)) + : [] + const cleanup = () => { + killAllActiveProcesses() + deleteClaudeSessionId(key) + _resetServedConversations() + rmSync(cwd, { recursive: true, force: true }) + } + return { cwd, key, turn, envelopes, allowReplay: () => writeFileSync(allow, ""), cleanup } +} + +const historyBlock = (stdin: string): string | null => { + const start = stdin.indexOf("") + if (start < 0) return null + return stdin.slice(start, stdin.indexOf("")) +} + +const lastText = (stdin: string): string => { + const texts = JSON.parse(stdin).message.content.map((part: any) => part.text) + return texts[texts.length - 1] +} + +test("a blocked message fails the turn, names the hook, and the session goes on", { + timeout: 60_000, +}, async () => { + _resetServedConversations() + const f = fixture() + const logDir = mkdtempSync(join(tmpdir(), "opencode-prompt-blocked-log-")) + const priorFile = process.env.OPENCODE_CLAUDE_CODE_LOG_FILE + const priorDir = process.env.OPENCODE_CLAUDE_CODE_LOG_DIR + try { + process.env.OPENCODE_CLAUDE_CODE_LOG_FILE = "1" + process.env.OPENCODE_CLAUDE_CODE_LOG_DIR = logDir + configureLogger({ file: true, dir: logDir, level: "info", mode: "silent" }) + const blocked = await f.turn([u(`hello BLOCKME ${SECRET}`)]) + + assert.deepEqual(blocked.finish.finishReason, { unified: "error", raw: "blocked_by_hook" }) + assert.equal(blocked.errors.length, 0, "the note is the account of it, not an error part") + assert.ok(blocked.text.includes(PROMPT_BLOCKED_MARKER), blocked.text) + assert.ok(blocked.text.includes(REASON), blocked.text) + assert.match(blocked.text, /nothing reached Claude/) + assert.ok(!blocked.text.includes(SILENT_TURN_MARKER), "not an empty reply") + assert.ok(!blocked.text.includes(TURN_STATS_MARKER), "nothing was served, so no footer") + assert.ok(!blocked.text.includes(SECRET), "the prompt is never echoed") + assert.ok(!blocked.text.includes("Original prompt")) + + // The session had nothing to lose, so it stays: the next message goes to + // the same process, bare, and the blocked one is not sent again. + const sessionId = getClaudeSessionId(f.key) + assert.ok(sessionId) + const next = await f.turn([u(`hello BLOCKME ${SECRET}`), a(blocked.text), u("next")]) + assert.match(next.text, /answered by/) + assert.deepEqual(next.finish.finishReason, { unified: "stop", raw: "stop" }) + const sent = f.envelopes() + assert.equal(sent.length, 2) + assert.equal(sent[1].pid, sent[0].pid, "the same process answered it") + assert.equal(lastText(sent[1].stdin), "next") + assert.equal(historyBlock(sent[1].stdin), null) + assert.doesNotMatch(sent[1].stdin, /BLOCKME/) + } finally { + if (priorFile === undefined) delete process.env.OPENCODE_CLAUDE_CODE_LOG_FILE + else process.env.OPENCODE_CLAUDE_CODE_LOG_FILE = priorFile + if (priorDir === undefined) delete process.env.OPENCODE_CLAUDE_CODE_LOG_DIR + else process.env.OPENCODE_CLAUDE_CODE_LOG_DIR = priorDir + _resetLoggerForTests() + f.cleanup() + } + const written = join(logDir, "plugin.log") + const log = existsSync(written) ? readFileSync(written, "utf8") : "" + rmSync(logDir, { recursive: true, force: true }) + const warned = log.split("\n").filter((line) => line.includes("before the model saw it")) + assert.equal(warned.length, 1, log) + assert.match(warned[0], /WARN/) + assert.match(warned[0], /"kind":"blocked_by_hook"/) + assert.ok(!log.includes(SECRET), "the prompt never reaches the log") + assert.ok(!log.includes(REASON), "nor the hook's sentence") +}) + +test("a blocked replay drops the empty session, so the next message replays again", { + timeout: 60_000, +}, async () => { + _resetServedConversations() + const f = fixture() + try { + // A key with no session and a conversation behind it: the thread is + // replayed as text, and the hook blocks the replay. + const history = [u(`one BLOCKME ${SECRET}`), a("A1"), u("two")] + const blocked = await f.turn(history) + const first = f.envelopes()[0] + assert.ok(historyBlock(first.stdin), "the envelope was a replay") + assert.deepEqual(blocked.finish.finishReason, { unified: "error", raw: "blocked_by_hook" }) + assert.ok(blocked.text.includes(PROMPT_BLOCKED_MARKER), blocked.text) + assert.match(blocked.text, /earlier messages/) + assert.match(blocked.text, /next message replays them again/) + assert.ok(!blocked.text.includes(SECRET)) + + // Nothing is left to record that session as the one that continues it. + assert.equal(getClaudeSessionId(f.key), undefined) + assert.equal(getActiveProcess(f.key), undefined) + + // The operator lets the replay through: the next message carries the + // history again, into a fresh process. + f.allowReplay() + const next = await f.turn([...history, a(blocked.text), u("three")]) + assert.match(next.text, /answered by/) + const sent = f.envelopes() + assert.equal(sent.length, 2) + assert.notEqual(sent[1].pid, first.pid, "a fresh process") + const replay = historyBlock(sent[1].stdin) + assert.ok(replay, sent[1].stdin.slice(0, 400)) + assert.match(replay, /User: one/) + assert.match(replay, /Assistant: A1/) + assert.ok(!replay.includes(PROMPT_BLOCKED_MARKER), "the note is never replayed as Claude's") + assert.equal(lastText(sent[1].stdin), "three") + } finally { + f.cleanup() + } +}) + +test("before 2.1.314 the frame has no outcome, and the turn still fails", { + timeout: 60_000, +}, async () => { + _resetServedConversations() + const f = fixture() + try { + const blocked = await f.turn([u(`LEGACYBLOCK ${SECRET}`)]) + assert.deepEqual(blocked.finish.finishReason, { unified: "error", raw: "blocked_by_hook" }) + assert.ok(blocked.text.includes(PROMPT_BLOCKED_MARKER), blocked.text) + assert.ok(!blocked.text.includes('("'), "no reason to quote") + assert.ok(!blocked.text.includes(SECRET)) + } finally { + f.cleanup() + } +}) + +test("a message blocked inside a turn that went on gets a note, not a failure", { + timeout: 60_000, +}, async () => { + _resetServedConversations() + const f = fixture() + try { + const steered = await f.turn([u("STEER please")]) + assert.deepEqual(steered.finish.finishReason, { unified: "stop", raw: "stop" }) + assert.match(steered.text, /working/) + assert.match(steered.text, /done after the steer/) + assert.ok(steered.text.includes(PROMPT_BLOCKED_MARKER), steered.text) + assert.match(steered.text, /a message sent while Claude was working/) + assert.ok(steered.text.includes(TURN_STATS_MARKER), "the turn was served") + assert.ok(getClaudeSessionId(f.key), "the session is kept") + } finally { + f.cleanup() + } +}) + +test("a blocked compaction writes no text and ends on an error", { + timeout: 60_000, +}, async () => { + _resetServedConversations() + const f = fixture() + try { + const compacted = await f.turn( + [u(`one BLOCKME ${SECRET}`), a("A1"), u("Summarise the conversation.")], + "compaction", + ) + assert.equal(compacted.finish.finishReason.unified, "error") + assert.equal(compacted.finish.finishReason.raw, "blocked_by_hook") + assert.equal(compacted.text, "", "a compaction's text is stored as the summary") + assert.equal(compacted.errors.length, 1) + assert.match(String(compacted.errors[0].error.message), /could not compact/) + assert.match(String(compacted.errors[0].error.message), /UserPromptSubmit hook/) + assert.ok(!String(compacted.errors[0].error.message).includes(SECRET)) + } finally { + f.cleanup() + } +}) diff --git a/test/turn-stats.test.ts b/test/turn-stats.test.ts index 2855865..831d4ad 100644 --- a/test/turn-stats.test.ts +++ b/test/turn-stats.test.ts @@ -6,10 +6,18 @@ */ import "./isolate.js" import assert from "node:assert/strict" -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs" +import { + chmodSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs" import { tmpdir } from "node:os" import { join } from "node:path" import { test } from "node:test" +import { fileURLToPath } from "node:url" import { ACCOUNT_BLOCK_MARKER, FAILOVER_MARKER, @@ -18,7 +26,9 @@ import { import { COMPACT_BOUNDARY_MARKER, CONVERSATION_RESET_MARKER, + PROMPT_BLOCKED_MARKER, RATE_LIMIT_MARKER, + REFUSAL_FALLBACK_MARKER, RESULT_ERROR_MARKER, SILENT_TURN_MARKER, STREAM_TIMEOUT_MARKER, @@ -178,6 +188,8 @@ test("every ▌ marker the plugin writes is stripped from a rebuilt transcript", `${CONVERSATION_REWOUND_MARKER} the thread was edited or undone.`, `${TURN_STATS_MARKER} $0.0001`, `${BUDGET_MARKER} this conversation has spent $0.50, 50% of its $1.00 \`maxBudgetUsd\`.`, + `${REFUSAL_FALLBACK_MARKER} claude-opus-5-5's safety classifier stopped the reply.`, + `${PROMPT_BLOCKED_MARKER} A UserPromptSubmit hook blocked this message.`, ] for (const note of notes) { const prompt = [ @@ -200,6 +212,29 @@ test("every ▌ marker the plugin writes is stripped from a rebuilt transcript", } }) +test("every ▌ marker declared in src/ is on the strip list", () => { + // The list above is only as good as the memory of whoever adds a note: + // `REFUSAL_FALLBACK_MARKER` shipped in h #g300 and was never added, so its + // note came back to Claude as its own words until h #g314. Read the source + // instead, so a new marker fails here the day it is written. + const srcDir = fileURLToPath(new URL("../src/", import.meta.url)) + const declared = new Set() + for (const file of readdirSync(srcDir).filter((name) => name.endsWith(".ts"))) { + const source = readFileSync(join(srcDir, file), "utf8") + for (const match of source.matchAll(/export const ([A-Z_]+_MARKER)\s*=\s*"▌/g)) { + declared.add(match[1]) + } + } + const builder = readFileSync(join(srcDir, "message-builder.ts"), "utf8") + const list = builder.slice( + builder.indexOf("const PLUGIN_NOTE_MARKERS = ["), + builder.indexOf("]", builder.indexOf("const PLUGIN_NOTE_MARKERS = [")), + ) + assert.ok(declared.size >= 20, `found only ${declared.size} markers`) + const missing = [...declared].filter((name) => !new RegExp(`\\b${name}\\b`).test(list)) + assert.deepEqual(missing, []) +}) + test("turnStats is off unless the provider option asks for it", () => { assert.equal((createClaudeCode({})("claude-sonnet-5") as any).config.turnStats, false) assert.equal( From a43680b2ddb824a5347be66d4a6c0b6752b5e1d9 Mon Sep 17 00:00:00 2001 From: Khalil Gharbaoui Date: Sat, 14 Nov 2026 23:09:50 +0100 Subject: [PATCH 2/6] Keep the resume record after a usage limit A turn that failed on a usage limit or an account block, answered by the CLI's own failure reply, leaves a session that holds its message, so its resume record is written. Before, a by-hand switch to another account after a limit replayed the whole thread (sibling-conversation-changed), and so did a restart. Other failures keep the replay. h #g315 --- AGENTS.md | 4 +- TODO.md | 13 ++--- docs/agents-history.md | 42 ++++++++++++++++- docs/configuration/options.md | 2 +- docs/troubleshooting/symptoms.md | 1 + skills/claude-code-plugin/SKILL.md | 2 +- src/claude-code-language-model.ts | 19 ++++++-- src/stream-parser.ts | 5 ++ src/turn-state.ts | 9 ++++ test/account-groups.test.ts | 76 ++++++++++++++++++++++++++++++ 10 files changed, 158 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 850beb2..b4717fd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -210,7 +210,7 @@ changing, reverting or "simplifying" a rule. - **A fork is never a subagent on either major, and `src/session-fork.ts` matches on CONTENT because that is the only rule both majors answer**: 1.18.34 copies every message with fresh ids and sets **no `parentID`**, leaving only the renameable title ` (fork #N)`, so `fetchSessionParentId` and the failover child-session refusal are untouched; 2.0.16 copies nothing (it is event-sourced) and records the source in `fork_session_id` / `fork_boundary`, exposed as `Session.fork = { sessionID, boundary }` beside an unset `parentID`, which `toV1Session` would pass through. The V2 field is a better signal and is deliberately unused: it is V2-only and it names a session, not a session KEY. The digest chain excludes every id, because opencode re-keys everything it copies. - **Every refusal is load-bearing**: a sibling key only (the key with its affinity blanked, which pins cwd, model, scope, agent, cache TTL and effort at once, and leaves compaction keys out because they have no fifth segment), the same `cliPath` (#g98), not busy via `claudeSessionIsBusy` and never `getActiveProcess` (a scan must not touch LRU order), the whole recorded chain a prefix of this history with only assistant or tool content past it, and no tool result in the trailing segment (that is a parked proxy call, and the issue-#29 gate stays empty for a new key). - **A fork spawn's argv resumes ANOTHER key's conversation, so `appendResumeIfNeeded` rewrites it on respawn**: once the key has its own id the target becomes that id and `--fork-session` is dropped, and a rewound thread's `--resume-session-at ` with it (h #g282), or the watchdog branches the parent twice (#g84). The 19,625-write mid cut measured here was 2.1.280; from 2.1.288 a cut reads the kept turns from the cache, which is what `forkOnRewind` uses. A mid-conversation fork of a NEW opencode session (`forkSessions`) still stays on the replay, because no checkpoint maps a fork's boundary to an entry. -- **`resumeAfterRestart` is ON by default, and every refusal is what makes that safe** (`src/session-resume-store.ts`). Without it the first turn of an existing conversation in a new opencode process replayed the whole thread (3 replays in the retained log, mean 648,653 characters, max 981,109). A record is written only after a `result` with `is_error !== true`, never on compaction, and is forgotten wherever the in-memory id is (`deleteClaudeSessionId`, a session-id error on stderr), so a conversation one process abandoned is never resumed by the next. **A child exiting with a non-zero code is NOT one of those any more** (h #g215): measured on 2.1.288, a headless child SIGKILLed mid-answer and one killed at its `system`/`init` frame were both resumed afterwards with the conversation intact, and the transcript exists from `init` onward, which is also the first moment this plugin has an id to keep. Forgetting there turned every crash into a full replay (issue #91); the stderr `No conversation found` forget is the backstop for an id that really is unusable. A lookup runs only where the replay was about to happen, and requires the SAME session key, the same `cliPath` (#g98), the transcript file present under `configDir/projects//`, and `continuesRecordedConversation` (the fork rule: recorded chain an exact prefix, only reply content past it, no tool result in the trailing segment). A hit just calls `setClaudeSessionId`, so the existing `--resume` in `buildCliArgs` and the interactive spawn's `resumeSessionId` do the rest. It shares `forkSessions`' system-prompt-snapshot caveat (#g187) exactly as idle-eviction resume always has, which is why it is not opt-in. **The `test` script gives every run a `mktemp -d` `XDG_STATE_HOME`**, for the #g116 reason: fake-CLI turns finish successfully and would otherwise write the operator's real store; `test/isolate.ts` gives every test process its own as well, which also covers a focused run (h #g283). Live on 1.18.34 and 2.0.22. `test/session-resume.test.ts`. (h #g197) **A digest leaves out opencode-dcp's message references, and a record says which way its digests were built** (`DIGEST_VERSION`, `src/session-fork.ts`, h #g258): dcp appends `m0004` to every user text part and completed tool output it hands a provider, numbers in memory, never reuses a number and renumbers from `m0001` when opencode restarts, so after an undo (which removes a message dcp had already numbered) every later message came back under a lower number and the conversation was refused as `conversation-changed`. Measured on opencode 1.19.3 + dcp 3.2.0 with a fake `claude`: an undone conversation started a fresh Claude session after the restart on master and resumed its own on the fix, while a plain one and a compacted one resumed on both. Version 2 strips the XML tag (any attributes, `m`/`b` refs, `BLOCKED`) and the `compact` form's last `@12@` line that dcp's opencode 2 path writes (measured on opencode 2.0.31 with the same fake `claude`, h #g259: an undone message went out as `@4@` before the restart and `@3@` after it, v0.60.1 refused the conversation as `conversation-changed` and the fix resumed it). **A record with no `version` is compared as version 1**, which is why the field exists: without it every dcp conversation would replay once on the restart that installs the upgrade. A message with no reference hashes identically under both, so a non-dcp install's records are unaffected. The in-memory chains (fork fingerprints, `conversation-gap.ts`) are always the current version. **Version 3 leaves out dcp's `` block as well, and the block is also what made `rewound` misfire** (h #g262): dcp appends its MAX CONTEXT LIMIT warning to a message that is ALREADY in the history and goes on appending it to later ones, so a user message goes out on its own turn as the operator wrote it and comes back on the next turn 1,091 characters longer. Measured over 99 of this plugin's Claude CLI transcripts: 32 distinct user messages were seen both with the block and without it (the pair, read off the wire: 141 characters at 21:25:00, 1,232 at 21:27 and three times after), against 15 that differed only by a `` value and **zero by any opencode-authored block**. **Removing a block has to level the gap it leaves**, because which blocks a message carries changes per turn: one copy ends in `\n\n` and the other in `\n\n\n\n`, so when anything was removed the blank-line runs are collapsed and the ends trimmed, bounded and linear (the leading `\s*` is still avoided for #g258's reason). That levelling runs ONLY when a dcp block was actually removed, which is what keeps a dcp-free message hashing identically under versions 2 and 3. +- **`resumeAfterRestart` is ON by default, and every refusal is what makes that safe** (`src/session-resume-store.ts`). Without it the first turn of an existing conversation in a new opencode process replayed the whole thread (3 replays in the retained log, mean 648,653 characters, max 981,109). A record is written only after a `result` with `is_error !== true`, never on compaction, and is forgotten wherever the in-memory id is (`deleteClaudeSessionId`, a session-id error on stderr), so a conversation one process abandoned is never resumed by the next. **The one failed turn that IS recorded is a usage limit or an account block the CLI answered with its own `` failure reply** (`TurnState.cliFailureReply`, h #g315): read off 2.1.322's transcript of a limited session, the turn's `user` record and the `rate_limit` reply are both in it, so the session is intact and holds the message. Leaving the record a turn behind is what made the by-hand switch an operator makes BECAUSE of a limit replay the whole thread (`sibling-conversation-changed`, the limited message past the record) on 2026-11-14, and a restart after a limit replay it the same way. Every other failure keeps the old rule (a too-long prompt, say, leaves a session that no model may take), and `test/account-groups.test.ts` pins both: the switch after a limit carries, the switch after a 529 replays. **A child exiting with a non-zero code is NOT one of those any more** (h #g215): measured on 2.1.288, a headless child SIGKILLed mid-answer and one killed at its `system`/`init` frame were both resumed afterwards with the conversation intact, and the transcript exists from `init` onward, which is also the first moment this plugin has an id to keep. Forgetting there turned every crash into a full replay (issue #91); the stderr `No conversation found` forget is the backstop for an id that really is unusable. A lookup runs only where the replay was about to happen, and requires the SAME session key, the same `cliPath` (#g98), the transcript file present under `configDir/projects//`, and `continuesRecordedConversation` (the fork rule: recorded chain an exact prefix, only reply content past it, no tool result in the trailing segment). A hit just calls `setClaudeSessionId`, so the existing `--resume` in `buildCliArgs` and the interactive spawn's `resumeSessionId` do the rest. It shares `forkSessions`' system-prompt-snapshot caveat (#g187) exactly as idle-eviction resume always has, which is why it is not opt-in. **The `test` script gives every run a `mktemp -d` `XDG_STATE_HOME`**, for the #g116 reason: fake-CLI turns finish successfully and would otherwise write the operator's real store; `test/isolate.ts` gives every test process its own as well, which also covers a focused run (h #g283). Live on 1.18.34 and 2.0.22. `test/session-resume.test.ts`. (h #g197) **A digest leaves out opencode-dcp's message references, and a record says which way its digests were built** (`DIGEST_VERSION`, `src/session-fork.ts`, h #g258): dcp appends `m0004` to every user text part and completed tool output it hands a provider, numbers in memory, never reuses a number and renumbers from `m0001` when opencode restarts, so after an undo (which removes a message dcp had already numbered) every later message came back under a lower number and the conversation was refused as `conversation-changed`. Measured on opencode 1.19.3 + dcp 3.2.0 with a fake `claude`: an undone conversation started a fresh Claude session after the restart on master and resumed its own on the fix, while a plain one and a compacted one resumed on both. Version 2 strips the XML tag (any attributes, `m`/`b` refs, `BLOCKED`) and the `compact` form's last `@12@` line that dcp's opencode 2 path writes (measured on opencode 2.0.31 with the same fake `claude`, h #g259: an undone message went out as `@4@` before the restart and `@3@` after it, v0.60.1 refused the conversation as `conversation-changed` and the fix resumed it). **A record with no `version` is compared as version 1**, which is why the field exists: without it every dcp conversation would replay once on the restart that installs the upgrade. A message with no reference hashes identically under both, so a non-dcp install's records are unaffected. The in-memory chains (fork fingerprints, `conversation-gap.ts`) are always the current version. **Version 3 leaves out dcp's `` block as well, and the block is also what made `rewound` misfire** (h #g262): dcp appends its MAX CONTEXT LIMIT warning to a message that is ALREADY in the history and goes on appending it to later ones, so a user message goes out on its own turn as the operator wrote it and comes back on the next turn 1,091 characters longer. Measured over 99 of this plugin's Claude CLI transcripts: 32 distinct user messages were seen both with the block and without it (the pair, read off the wire: 141 characters at 21:25:00, 1,232 at 21:27 and three times after), against 15 that differed only by a `` value and **zero by any opencode-authored block**. **Removing a block has to level the gap it leaves**, because which blocks a message carries changes per turn: one copy ends in `\n\n` and the other in `\n\n\n\n`, so when anything was removed the blank-line runs are collapsed and the ends trimmed, bounded and linear (the leading `\s*` is still avoided for #g258's reason). That levelling runs ONLY when a dcp block was actually removed, which is what keeps a dcp-free message hashing identically under versions 2 and 3. - **`resumeAcrossModelChanges` is ON by default and is the other half of the same bug: the model is in the session key too, so changing it mid-conversation replayed the thread exactly as an effort change did** (issue #91, at least 18 replays in one ~15-hour session). `findSiblingResumePoint` reads the record `resumeAfterRestart` already writes, so `resumeAfterRestart: false` turns this off as well and nothing new is persisted. A sibling is matched on `modelSiblingSignature`, the key with its model segment blanked, its `effort=` tail dropped by NAME rather than by position and its context blob cut to `[provider, agent]` (`withoutSpawnSettings`, the same cut `spawnIdentity` makes), which is the exact opposite selection to `forkSiblingSignature`: a fork is another opencode session continuing the same content, this is the same opencode session continuing its own, so cwd, scope, affinity, provider and agent must all match and only the model, the effort and the blob's spawn settings (prompt-cache TTL, `maxTurns=`, `maxBudgetUsd=`, h #g275) may differ (and, since (h #g226), the context blob's PROVIDER element, when an account-provider map is passed in). **A `maxBudgetUsd` change carries too, and that is honest**: `--max-budget-usd` counts per process and starts again on every `--resume` (h #g245), so the carried process gets the new cap from zero, exactly as the in-process carry (h #g270) and a replay into a fresh session would, the replay at a replay's cost. Widening the signature also widens `findForeignAccountSibling`, the `accountGroups` guard's detector, which is the safe direction: before it, a TTL set on one account's provider and not another's hid a cross-group sibling from the guard. **The caller TRANSFERS, never shares**: it kills the sibling's child first and `transferClaudeSession` moves the id, so one Claude conversation has exactly one owner and two children can never append to one transcript. **After an opencode restart (or a handover, h #g269) the sibling's id is in its resume record only**, so the carry passes the id `findSiblingResumePoint` accepted as `transferClaudeSession`'s `recorded` argument (an id in memory still wins), and the record moves with it; and `invalidateOtherSpawnVariants`, with the carry on, no longer forgets the resume record of a stale key this process never held in memory (`forgetClaudeSessionInMemory`, not `deleteClaudeSessionId`), so the lookup can take it past every refusal. Measured on master before the fix: the first model change after a restart replayed as `sibling-carry-over-failed`, and the first effort change as `no-sibling-recorded`, because the old effort's record was deleted before the lookup ran. `test/restart-sibling-carry.test.ts`. (h #g274) Every `findResumePoint` refusal holds (`cliPath` #g98, the transcript on disk) plus two of its own, a sibling that may still be written to (`claudeSessionIsWriting`, never `getActiveProcess`, which touches LRU order) and a key that is not a sibling at all; compaction is out on both sides and a failover switch never takes one. **What it compares is a SECOND chain, `shape`, and the strict one can never match across a model change**: measured on 1.18.35, opencode hands a provider an assistant message's stored reasoning as a `reasoning` part for the model that produced it and FLATTENS it into a leading `text` part for every other model, and a flattened reasoning part is indistinguishable from reply text, so no content rule sees through it. `conversationDigests(prompt, { assistantContent: false })` hashes every user and tool message by content and every assistant message by position alone; `recordResumePoint` writes both and only this lookup reads `shape`. Do not make it the default: the strict chain is what `forkSessions` and `findResumePoint` compare and the only thing that catches regenerated replies under an unchanged prompt. A pre-upgrade record has no `shape` and is simply no candidate. `--resume --model ` is measured on 2.1.288: the resumed conversation answers under the new model and still knows what it was told under the old one. `test/session-model-switch.test.ts`. (h #g215) - **A turn that replays the thread as text says so once, at NOTICE, naming what it refused on**, because the replay is the lossy, expensive path and before this it was invisible unless the operator read DEBUG. The reason is a kebab TOKEN, not a sentence (`no-session-recorded`, `sibling-still-writing`, `transcript-gone`), because `/claude-code-doctor bundle`'s `reason` key is allowlisted as an `enum` and `SAFE_ENUM` forbids spaces: a sentence would arrive redacted. The replay prefix in `src/message-builder.ts` no longer says the previous session "couldn't be resumed", which read as session corruption; it says the conversation is replayed as text because no Claude session was available to continue it. `test/session-model-switch.test.ts`, `test/get-claude-user-message.test.ts`. (h #g215) - **Every `▌`-led text part the plugin writes must be registered in `PLUGIN_NOTE_MARKERS`** (aside, `TURN_STATS_MARKER`, self-compaction, rate limit, failed result, doctor, `UNATTENDED_REPLAY_MARKER`, `USAGE_LIMIT_MARKER`): none was ever Claude's output. The strip is **part-level and anchored at the start**, so each note needs its **own** text part. A marker nothing writes any more stays on the list (`RATE_LIMIT_MARKER`), because a conversation opened before the upgrade still holds blocks led by it. `test/turn-stats.test.ts` asserts every marker on the list, not only the footer that file is named for, and **scans `src/` for every `export const *_MARKER = "▌` and fails on one missing from the list**: `REFUSAL_FALLBACK_MARKER` shipped in h #g300 unregistered, so its note was replayed as Claude's own words until h #g314. (h #g108, #g194, #g314) @@ -484,7 +484,7 @@ Opt-in. `spawnInteractiveProcess` returns an `ActiveProcess`-shaped shim so doSt - What the control channel answers for everything that is not `can_use_tool` (the `elicitation` decline, its once-per-server WARN, and the empty ack the unreachable subtypes keep): `test/control-request.test.ts`. - Plan-mode approval bridge (`isPlanModeQuestionActive`, `createExitPlanModeQuestionCall`, `consumeExitPlanModeQuestionResult`): `test/exit-plan-mode-question.test.ts`. - Account failover (detection and its negative cases, the override and its expiry clamp, `resolveFailoverSpawn`, the form and its `"ask"`-only gate, every answer classification including opencode-dcp's trailing `` tag through both the failover form and the plan-mode bridge and opencode 2's measured `content`-array answer, the transcript strip and continuation prompt, `formatUsageLimitNote` in all four shapes, `describeOtherAccounts`, `rememberAccountLimit` / `recallAccountLimit`, both branches of `formatAccountBlockNote`, `describeRateLimit` being log-only, plus a fake CLI through ask / switch / stop and, for the note, a limited turn with the form off, a second limited turn on the same process with no event of its own, one configured account, a turn served despite a rejected event, and a compaction turn, plus the switch carrying a planted transcript with `--resume` and no replay, and `crossAccountResume: false` keeping the replay; the form's switch note saying carried or replayed and naming a block, and PR #115's leftovers through the same fake (h #g257): a limited `doGenerate` turn erroring under `"off"` and `"ask"`, a cancel interrupting the CLI under both, the form after an override naming the account that failed and offering neither it nor the provider's, a pick still keyed on the provider's account, an expired login after an override naming that account's login, and an `"auto"` chain ending on a second expired login; and `"auto"` through a scripted per-account fake CLI: limit, block, a three-account chain, exhaustion, the known-unavailable skip and both expiries, never on a server error, a served-after-rejected turn, a title or a compaction, precedence over `fallbackModels`, `accountGroups`, carry, replay, abort, `doGenerate` and its exhaustion, a runtime that cannot be prepared, a limit learned mid-turn and `reader.cancel()`; and on the Windows plan (`_setAccountRuntimePlatform`) a `default` conversation switched to a named account and back, each spawn getting that account's config dir or none, h #g293): `test/account-failover.test.ts`. -- One conversation across any account, and the `accountGroups` guard (`resolveAccountGroups` and every refusal, `accountGroup` / `accountsShareGroup` / `accountsInGroupOf` / `describeAccountGroups`, `accountProviderMap` / `sessionKeyProvider` / `sessionKeyAccount` / `blankAccountProvider`, `modelSiblingSignature` with and without the map, `findSiblingResumePoint`'s cross-account hit and its three new refusals, `findForeignAccountSibling` over the store and the in-memory keys, `failoverCandidates` with groups, the note and its strip, `findForeignAccountSibling`'s `only` predicate finding a cross-group account past a same-group one, plus a fake CLI driving real `doStream` turns over two account providers in one opencode session for the carry's argv, the switch back taking a fresh id off the longer copy, `crossAccountResume: false`, a cross-group switch asserting NO `--resume`, no transcript copied, no earlier message text in the envelope and the note present, and the way back: a cross-group exchange kept out of the catch-up with the session intact, kept out of a rewound replay with the session dropped and the account-group note instead of the rewound one, a cross-group rewind never forking even where a checkpoint matches while the same sequence in one group does, and still caught up on between two accounts in one group): `test/account-groups.test.ts`. The PTY half of the by-hand carry: `test/interactive-pty.test.ts`. +- One conversation across any account, and the `accountGroups` guard (`resolveAccountGroups` and every refusal, `accountGroup` / `accountsShareGroup` / `accountsInGroupOf` / `describeAccountGroups`, `accountProviderMap` / `sessionKeyProvider` / `sessionKeyAccount` / `blankAccountProvider`, `modelSiblingSignature` with and without the map, `findSiblingResumePoint`'s cross-account hit and its three new refusals, `findForeignAccountSibling` over the store and the in-memory keys, `failoverCandidates` with groups, the note and its strip, `findForeignAccountSibling`'s `only` predicate finding a cross-group account past a same-group one, plus a fake CLI driving real `doStream` turns over two account providers in one opencode session for the carry's argv, the switch back taking a fresh id off the longer copy, `crossAccountResume: false`, a cross-group switch asserting NO `--resume`, no transcript copied, no earlier message text in the envelope and the note present, and the way back: a cross-group exchange kept out of the catch-up with the session intact, kept out of a rewound replay with the session dropped and the account-group note instead of the rewound one, a cross-group rewind never forking even where a checkpoint matches while the same sequence in one group does, and still caught up on between two accounts in one group; a by-hand switch after a usage limit carrying the session, and one after a 529 replaying, h #g315): `test/account-groups.test.ts`. The PTY half of the by-hand carry: `test/interactive-pty.test.ts`. - Carrying one conversation's Claude transcript between account config dirs (`carryTranscriptToAccount`: the copy's path, mode and the created directory's, the untouched source, `already-there`, the stale copy at the target taking a fresh id, the longest candidate winning, nothing to carry, a symlink and a directory at the target, and a copy the filesystem refuses): `test/account-transcript.test.ts`. - Compress tool (interceptor path, compression store, note selection), `resolveProxyOpencodeToolDefs` and both layers of the `compress` name collision: `test/compress-tool.test.ts`. - Permission presets (`resolvePermissionPreset`, `applyPermissionPreset`, the read-only branch of `buildCliArgs`, both new version gates): `test/permission-presets.test.ts`. diff --git a/TODO.md b/TODO.md index b13929c..7bed9b4 100644 --- a/TODO.md +++ b/TODO.md @@ -75,12 +75,13 @@ - 2026-11-14 (evening), the blocked replay: FIXED on `fix/blocked-prompt` (h #g314). A message a `UserPromptSubmit` hook ends now fails the turn under a `▌ **prompt blocked:**` note quoting the hook's reason, and a blocked replay drops its empty session so the next message replays again. - Still open from it: (1) why the Opus 5.5 (appical) to Fable 5.2 (default) switch in session - `ses_e324dbf7bffeRHQIz10AIxm7dT` was refused as `sibling-conversation-changed` at all, which is - what made the replay happen; (2) the interactive transport does not read the TUI's - `promptSubmitEnding` record, and how a blocked prompt ends a PTY turn is unmeasured; (3) the - location-switch empty turn below may be the same block: check that session's Claude transcript for - a `blocked_by_hook` record before building anything on the session-key theory. + Why the switch replayed at all is fixed on the same branch (h #g315): the appical session's two + usage-limited turns never moved its resume record, so the by-hand switch to the default account + found their messages past it and refused the carry (`sibling-conversation-changed`). Still open: + (1) the interactive transport does not read the TUI's `promptSubmitEnding` record, and how a + blocked prompt ends a PTY turn is unmeasured; (2) the location-switch empty turn below may be the + same block: check that session's Claude transcript for a `blocked_by_hook` record before building + anything on the session-key theory. - 2026-11-14 (evening), measured, not fixed: the wire-inactivity watchdog ended a turn while the child lived on, unattached. The Mac idle-slept 21:10:23 to 21:20:56 CET (`pmset -g log`) during a designer subagent's turn (`ses_e24dd447bffe3jnporpawTFbxI`, Claude session `3e7cd878`, about 777K tokens of diff --git a/docs/agents-history.md b/docs/agents-history.md index 99e78fb..4167b96 100644 --- a/docs/agents-history.md +++ b/docs/agents-history.md @@ -12938,9 +12938,47 @@ was on the list. Both markers are on it now, and `test/turn-stats.test.ts` scans `export const *_MARKER = "▌` and fails on one that is not. Not done: the interactive transport does not read the TUI's `promptSubmitEnding` record, and how a -blocked prompt ends a PTY turn is unmeasured. Not diagnosed here: why the sibling carry was refused -as `sibling-conversation-changed` in the first place, which is what made the replay happen. +blocked prompt ends a PTY turn is unmeasured. Why the replay happened at all is h #g315. Tests: `test/prompt-blocked.test.ts` (the parser, the note, and a fake CLI replaying the measured frames through real `doStream` turns, with a secret-like string in the prompt that must reach neither the reply nor the log), and the marker scan in `test/turn-stats.test.ts`. + + +## A by-hand switch after a usage limit replayed the thread instead of carrying it (2026-11-14) + +h #g315. The other half of h #g314's incident: why the switch from the appical account's Opus 5.5 +to the default account's Fable 5.2 replayed the thread at all. The plugin log names it +(`replaying the conversation as text ... reason: sibling-conversation-changed`), and the resume +store and the log together say why: + +- The resume record for the appical key (`claude-opus-5-5@appical::...::["claude-code-appical", + "build"]`, Claude session `3b917453`) was last written at 19:36:45Z, covering 241 messages. +- That key's next two turns, 20:21:42Z and 20:23:44Z, both ended on the account's 5-hour limit + (`Claude Code rejected this request: you are out of usage in the 5-hour window`, `isError: true`). + A record was only ever written after a `result` with `is_error !== true`, so neither moved it. +- At 20:42:45Z the operator picked a model under the default account. `findSiblingResumePoint` found + the appical record, but the two limited turns' user messages sat past it, and + `continuesRecordedConversation` refuses a user message past the record: `sibling-conversation- + changed`, a replay of 248 messages, which agent-guard then blocked (h #g314). + +Claude Code's transcript of `3b917453` (its tail, read for record types only) holds both limited +turns: a `user` record, an `api-request`, and a `` assistant reply with +`error: "rate_limit"`, twice. So the session was intact and held those messages, and carrying it +would have been right. The rule "a failed turn may leave a transcript the plugin would not resume" +is true of failures in general and false of this one, and this one is the failure that makes an +operator switch accounts. + +What changed: `TurnState.cliFailureReply` is set when the CLI answers with its own failure reply +(`is_api_error_message`, or an `error` kind, which is all an account block's reply carries), and +`completeResult` writes the resume record after a failed turn when that reply came and the failure +was a usage limit or an account block. Every other failure keeps the old rule: an overloaded API +or a too-long prompt is not trusted to have left a session worth carrying, and a too-long one would +fail again wherever it was carried. The same record serves an opencode restart, which after a limit +replayed for the same reason and now resumes. + +Tests, in `test/account-groups.test.ts` beside the by-hand switch tests, whose fake CLI now answers +a `LIMITME` message the way 2.1.322 answers a usage limit and a `SERVERERR` one with a 529: a switch +after a limit resumes the first account's session from the second account's config dir with no +replay and without re-sending the limited message (it fails without the change: the switch +replays), and a switch after the 529 still replays. diff --git a/docs/configuration/options.md b/docs/configuration/options.md index 6de4abb..384ec1e 100644 --- a/docs/configuration/options.md +++ b/docs/configuration/options.md @@ -84,7 +84,7 @@ The minimum config is just the `plugin` entry above. Everything below is optiona | `forkCompaction` | boolean | `false` | Run `/compact` inside a fork of the chat's own Claude session (`--resume --fork-session`) on the chat's own model, so the summary reads that session's prompt cache and sees the whole thread, instead of a text transcript on `compactionModel`. Cheaper and more faithful on a warm cache with an inexpensive chat model, about even on Opus, dearer on a cold cache. Headless only; falls back to the transcript whenever it cannot fork. See [Compaction on a fork](../guides/compaction-and-thinking.md#compaction-on-a-fork). | | `forkOnRewind` | boolean | `true` | After an `/undo`, an edited message or a regenerated reply, continue a copy of the chat's Claude session cut at the last turn both versions of the thread share (`--resume --resume-session-at --fork-session`), instead of ending the session and replaying the shorter thread as text. Each answered turn records where its reply ended in Claude's transcript, and the copy holds exactly the turns that are left; the old transcript is never changed. Measured on Claude Code 2.1.288, 2.1.293 and 2.1.314 on a four-turn thread: 38 to 121 tokens written to the prompt cache against 11,152 to 20,659 for the replay, 6.9 to 9.7 times cheaper, faster every time, and the model kept a document line and a tool result that the replay's clipping had dropped. Anything it cannot match falls back to the replay: no recorded turn that the thread now ends on, a transcript or entry that is gone, the interactive transport (Claude Code takes the cut in print mode only), Claude Code older than 2.1.288, an account in another `accountGroups` group, and compaction. Like any `--resume`, the copy keeps the system prompt the conversation started with. See [Sessions](../internals/how-a-turn-works.md#sessions). | | `forkFromCheckpoint` | boolean | `true` | When a new chat is forked from another one ("Fork from here", `/fork`), continue a copy of the parent's Claude session cut at the turn the fork was taken from (`--resume --resume-session-at --fork-session`), instead of replaying the inherited thread as text into a fresh session. The fork is recognised by content, on both opencode majors: its history has to match, reply for reply, a turn another chat in the same project served on the same model, agent and effort in this opencode process, and end on that turn's reply. The parent's transcript is never changed. Measured through opencode 2.2.6 and Claude Code 2.1.322 on Haiku 5.5, a 22 KB document and two codewords, forked before a third: 30 to 39 tokens written to the prompt cache against about 25,000 for the replay, 7.3 times cheaper (5.4 on opencode 1.19.4), and the fork quoted a line of the document that the replay's clipping had dropped. Like any `--resume`, the copy keeps the system prompt the parent started with; a chat in the same project on the same agent gets the same prompt (byte-identical in the measurement), so what can differ is the date line and an instruction file edited since. Anything it cannot match falls back to the replay: an opencode restart since the parent's turn, a turn that ended on a tool call, the parent mid-turn, another account, a transcript that is gone, the interactive transport and Claude Code older than 2.1.288. See [Sessions](../internals/how-a-turn-works.md#sessions). | -| `resumeAfterRestart` | boolean | `true` | After opencode restarts, resume a conversation's Claude session with `--resume` instead of replaying the whole thread as text into a fresh one. After each successful turn the session id and a digest of the conversation are kept in `$XDG_STATE_HOME/opencode-claude-code-plugin/claude-sessions.json` (`0600`, at most 256 conversations, 30 days). It resumes only for the same opencode session, model, agent and account, when the transcript is still on disk and the conversation is exactly the one recorded plus Claude's reply; an edit, revert or compaction replays as before. [opencode-dcp](https://github.com/Opencode-DCP/opencode-dynamic-context-pruning)'s own additions to a message are left out of the digest: its `` references, because dcp renumbers them when opencode restarts and a conversation that had an undo in it would otherwise never resume, and its `` context-limit warning, because dcp appends that to messages already in the history and the message would otherwise look edited on the next turn. A digest written by an earlier plugin version is still compared the way it was written. opencode's own `` blocks are stored with the message, so they stay part of the digest. Like any `--resume`, the conversation keeps the system prompt it started with. `false` never reads or writes the file. | +| `resumeAfterRestart` | boolean | `true` | After opencode restarts, resume a conversation's Claude session with `--resume` instead of replaying the whole thread as text into a fresh one. After each successful turn, and after one that failed on a usage limit or an expired login (Claude Code keeps that message in the session), the session id and a digest of the conversation are kept in `$XDG_STATE_HOME/opencode-claude-code-plugin/claude-sessions.json` (`0600`, at most 256 conversations, 30 days). It resumes only for the same opencode session, model, agent and account, when the transcript is still on disk and the conversation is exactly the one recorded plus Claude's reply; an edit, revert or compaction replays as before. [opencode-dcp](https://github.com/Opencode-DCP/opencode-dynamic-context-pruning)'s own additions to a message are left out of the digest: its `` references, because dcp renumbers them when opencode restarts and a conversation that had an undo in it would otherwise never resume, and its `` context-limit warning, because dcp appends that to messages already in the history and the message would otherwise look edited on the next turn. A digest written by an earlier plugin version is still compared the way it was written. opencode's own `` blocks are stored with the message, so they stay part of the digest. Like any `--resume`, the conversation keeps the system prompt it started with. `false` never reads or writes the file. | | `liveModelSwitch` | boolean | `true` | Apply a model or reasoning effort change to the conversation's running `claude` process, with Claude Code's own `set_model` and `apply_flag_settings` control requests, instead of stopping it and starting another with `--resume`. The conversation and the prompt cache are the same either way (measured on Claude Code 2.1.288 and 2.1.314); what it saves is starting a process, which took 4.6 to 6.6 seconds per change on a real install, against about 0.7 s for a model change and well under a second for an effort change. So that an effort change can apply, a headless spawn on Claude Code 2.1.288 or newer passes the effort as `--effort` and leaves `CLAUDE_CODE_EFFORT_LEVEL` out of the child's environment, because that variable would silently override a live change. It applies only when the process is idle and the change is to the model (on the same account and in the same fast mode) or between two explicit effort levels; a change that arrives while a turn is still running applies from the next turn, as before. Anything else, a refusal, or no answer within `CLAUDE_CODE_LIVE_SWITCH_TIMEOUT_MS`, falls back to the respawn. The interactive transport always respawns. Needs `resumeAcrossModelChanges`; `false` restores the respawn and the environment-variable effort exactly. | | `resumeAcrossModelChanges` | boolean | `true` | When you change a conversation's model or reasoning effort mid-conversation, continue the same Claude session (`--resume --model `) instead of replaying the whole thread as text. Both the model and the effort level are part of the session key, so changing either used to land a live conversation on a key nothing had answered; neither needs a new Claude conversation, because `--model` and `CLAUDE_CODE_EFFORT_LEVEL` are both applied at spawn time and the CLI accepts either on a transcript it resumes. The Claude session is moved off the old key rather than shared, so one conversation always has one owner. It refuses on everything `resumeAfterRestart` refuses on, plus a sibling whose transcript may still be written to (that turn finishes on the old process, and the change applies from the next one) and anything that is not the same working directory, request scope, opencode session and agent. A change to an agent's prompt-cache TTL, `maxTurns` or `maxBudgetUsd` carries the conversation the same way; the new `maxBudgetUsd` counts from zero in the new process, as it does after any resume. Never on a compaction turn or an account switch. It reads the record `resumeAfterRestart` writes, which is also what carries the first change after an opencode restart, so `resumeAfterRestart: false` disables it too. | | `crossAccountResume` | boolean | `true` | On an account switch, whether you pick another account's model by hand in the same session or through the [switch form](./accounts.md), and only between accounts in the same `accountGroups` group, continue the same Claude conversation on the other account instead of replaying the whole thread as text into a fresh session there. An account is a `CLAUDE_CONFIG_DIR` and a conversation is one transcript file inside it, so the switch copies that file into the target account's own `projects//` (`0600`, never overwriting, never through a symlink) and spawns it with the `--resume` that already exists. Claude Code 2.1.288 resumes a copied transcript with its context intact and resolves a session by filename, so an older copy already sitting at the target path makes the carry take a fresh session id rather than overwrite it. The source transcript is never moved, emptied or written to. Any refusal falls back to the replay and says which in the log. Does nothing on a single-account install. | diff --git a/docs/troubleshooting/symptoms.md b/docs/troubleshooting/symptoms.md index 3ce7787..b30c028 100644 --- a/docs/troubleshooting/symptoms.md +++ b/docs/troubleshooting/symptoms.md @@ -55,6 +55,7 @@ Four checks answer almost everything. Run them in this order, and stop as soon a | `▌ **model fallback:**` on a turn you expected to run on a specific model | The note itself, which names the model that failed and why | Working as configured: your [`fallbackModels`](../configuration/subagents.md#fallback-model-chain) chain moved the turn. `model_not_found` means fix the first id. `out of usage on this account` means that account's cap, and the reason you got a chain rather than the [account failover](../configuration/accounts.md#account-failover) form is that the form is off (its default) or had no other account to offer. The chain never changes account, only model. | | A reply that is only *"API Error: Opus 5.5's safeguards flagged this session…"*, finished as an error | The model the conversation is on | A safety classifier stopped the reply twice. Claude Code's own fallback to another model is off by default (`CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK`), so the turn ends here: rephrase, or pick another model. See [Claude Code's own fallbacks](../configuration/subagents.md#claude-codes-own-fallbacks). | | `▌ **refusal fallback:**` in a reply, and the sidebar names a model you did not pick | Whether `CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK=0` is in opencode's environment | Working as configured: you kept Claude Code's refusal fallback, so it answered on the model the note names and stays on it until the process restarts. Unset the variable to have a refusal end the turn instead. | +| After a usage limit you picked a model under another account, and Claude no longer knows the conversation | `replaying the conversation as text` with `sibling-conversation-changed` in the log | Upgrade. The record that lets a switch carry the conversation to the other account was only written after a turn that was answered, so the limited turn's message sat past it and the switch replayed the whole thread as text instead (bounded, so the oldest messages were dropped, and a guard hook may refuse the replay outright). A limited turn's message is in Claude's own transcript, so it is recorded now and the switch carries the session as it does at any other time. A restart after a limit replayed for the same reason and now resumes. | | `▌ **prompt blocked:**` instead of an answer, the turn marked as failed | The quoted reason in the note, and which of your Claude Code `UserPromptSubmit` hooks wrote it | Working as designed: one of your own Claude Code hooks (agent-guard, for one, refuses a prompt that looks like it holds a secret) ended the message before the model saw it, and no model was called. Send it again without what the hook objected to, or change the hook. When the note says the message carried the conversation's earlier messages, it was the replay of the history after a model or account switch: that history did not reach Claude, so the next message replays it again, and the hook will judge it the same way. Switch back to the model or account that answered before to keep the history, or let the hook pass the replay. A message you sent while Claude was working gets the same note under an answer that did not see it. Older plugins showed `▌ **no reply:**` for all of this, said nothing failed, and after a blocked replay sent every later message to a Claude session that held none of the conversation. | | A turn that called a tool and then stopped with no answer and no error | The `plugin` version in `/claude-code-doctor`, and `rendering a reply claude code sent without streaming` in the log | Upgrade. Claude Code had resent the call without streaming (a 404 on the streaming endpoint, or a stream cut early), and its whole-message reply was dropped. Now it is shown. | | A chain is declared but a refused model still kills the turn | Grep `plugin.log` for `fallback model refused: unknown model` | Every entry has to be a model id this plugin registers; an unknown one is skipped with that warning, and a chain whose entries are all unknown is an empty chain. The other empty-chain case is a list containing only the model the turn already runs on, which is dropped from its own chain. Compaction turns, title stubs and the interactive transport never fall back at all. | diff --git a/skills/claude-code-plugin/SKILL.md b/skills/claude-code-plugin/SKILL.md index 483f08e..8e5465d 100644 --- a/skills/claude-code-plugin/SKILL.md +++ b/skills/claude-code-plugin/SKILL.md @@ -186,7 +186,7 @@ Defaults below describe normal headless opencode use when the key is absent. | `forkCompaction` | boolean | `false` | Headless `/compact` on a fork of the conversation's own Claude session: `--resume --fork-session` with the conversation's spawn args minus every MCP server, the skip flag (replaced by `--permission-mode dontAsk`, a read-only spawn keeps `--restricted`), its prompt file, caps and effort, on the conversation's own model. The fork reads that model's prompt cache, which keys on the model and the built-in tool set (h #g284). `compactionModel` is ignored when it fires. Measured on 2.1.314: 136k-token Haiku 5.5 thread $0.013 / 10 of 10 facts against $0.122 / 4 of 10 for the Haiku 4.5 transcript; 81k-token Opus 5.5 thread $0.054 against $0.055, same facts. Not strictly cheaper (chat-model prices, cold-cache rewrite), hence off. Falls back to the transcript, with one INFO `compacting from a transcript instead of a fork` and a `reason` token, on: interactive transport, `default` affinity, no matching served conversation in this cwd and session, no Claude session or no live process for it, a turn or proxied call in flight, another binary, transcript gone, CLI without `--fork-session` or `dontAsk`. The fork's transcript copy is deleted afterwards; the conversation's own is never touched. | | `forkOnRewind` | boolean | `true` | After an opencode `/undo`, an edited message or a regenerated reply (the `rewound` verdict), continue a copy of the conversation's Claude session cut at the last turn both versions of the thread share, `claude --resume --resume-session-at --fork-session`, instead of ending the session and replaying the shorter thread as text. Every served headless turn records a checkpoint (the uuid of its reply's last transcript entry, read off the `assistant` frames, against the conversation up to the turn's last user message); the fork is a NEW Claude session holding exactly the turns that are left, the old transcript byte-identical. Measured on 2.1.288 / 2.1.293 / 2.1.314 on a four-turn thread cut after its second turn: 99 / 121 / 38 tokens written to the prompt cache against the replay's 11,152 / 20,659 / 19,924 to 20,484, 6.9 to 9.7 times cheaper, faster in every run, and correct where the replay's clipping lost a document line and a tool result. Falls back to the replay, with a `forkRefused` token in the NOTICE, on: `option-off`, `interactive-transport` (`--resume-session-at` is print-mode only), `no-checkpoint` (the thread ends on a turn another agent or model answered, a failed turn, a turn from before the CLI's own `compact_boundary`, or more than 64 turns back), `cli-too-old` (below 2.1.288; hidden flag, so a version gate), `transcript-gone`, `entry-gone`. A cross-group account (`accountGroups`) keeps its fresh start with nothing replayed and no fork; compaction is never classified. The fork keeps the system prompt the conversation started with, like any `--resume`. A fork's first `total_cost_usd` carries its parent's running total, so the budget ledger and the `turnStats` footer take the parent's last total as its baseline. Log: `forking the claude session at the last turn the edited thread still has` (NOTICE). | | `forkFromCheckpoint` | boolean | `true` | When a new opencode session is a fork of a turn another session served ("Fork from here", `/fork`, a `session.fork` with a `before` boundary), continue a copy of that session's Claude conversation cut at the turn, `claude --resume --resume-session-at --fork-session`, instead of replaying the inherited thread as text. Uses `forkOnRewind`'s checkpoints, matched STRICTLY across sessions (h #g305): a sibling key only (same cwd, model, scope, provider, agent, spawn settings and effort), the checkpoint's own `cliPath`, a parent not busy (`claudeSessionIsWriting`), no tool result past the last reply, the history up to the turn's user message equal with assistant content included, and the reply the thread ends on equal to the last text block Claude wrote for that turn. The parent's checkpoints up to the cut are carried onto the fork, so an undo there to before the fork point cuts the parent's session. Only where the turn was about to replay: the key's own session, `resumeAfterRestart`, a model-or-effort sibling and `forkSessions` come first. Measured through opencode 2.2.6 + Claude Code 2.1.322 on Haiku 5.5: 30 to 39 written / about 64,100 read and $0.00075 to $0.00081 against the replay's 25,024 to 25,077 written and $0.00554 to $0.00559 (7.3x); opencode 1.19.4: $0.00103 against $0.00560 (5.4x); the fork quoted a document line the replay's clipping dropped, every run. The copy answers under the system prompt the parent started with (measured on 2.1.322: a cut under a different appended prompt answered with the parent's); for a sibling the forwarded prompt was byte-identical, so the residual is the date line and instruction edits, as for `resumeAfterRestart`. Falls back to the replay with the replay NOTICE's usual `reason`, typically `no-sibling-recorded`, when nothing matched ( an opencode restart, a turn that ended on a tool call or failed, another model, agent or effort, the parent busy) or `fork-` (`fork-interactive-transport`, `fork-cli-too-old`, `fork-transcript-gone`, `fork-entry-gone`). Log: `found the turn this forked conversation was cut from` (INFO), `forking the claude session of the turn this conversation was forked from instead of replaying it` (NOTICE). | -| `resumeAfterRestart` | boolean | `true` | After an opencode restart, resume the conversation's Claude session (`--resume`) instead of replaying the thread as text. Persists session id + conversation digest per session key in `$XDG_STATE_HOME/opencode-claude-code-plugin/claude-sessions.json` (0600, 256 entries, 30 days) after each successful turn. Resumes only on the same session key and binary, with the transcript on disk and the history equal to the recorded conversation plus Claude's reply; anything else (edit, revert, compaction, account switch, open tool round trip) replays. opencode-dcp's `` references (and its `@12@` compact form) are not part of the digest: dcp renumbers them on every opencode restart, so after an undo the same message came back under another number and the conversation was refused as `conversation-changed`. Records carry a digest `version`; one without it (written by an older plugin) is compared the old way. Not on compaction. Log: `resuming the claude session from before the restart` (NOTICE) or `not resuming ...` with a reason (INFO). `false` disables reading and writing. | +| `resumeAfterRestart` | boolean | `true` | After an opencode restart, resume the conversation's Claude session (`--resume`) instead of replaying the thread as text. Persists session id + conversation digest per session key in `$XDG_STATE_HOME/opencode-claude-code-plugin/claude-sessions.json` (0600, 256 entries, 30 days) after each successful turn, and after one that failed on a usage limit or an account block, whose message Claude Code keeps in the session (h #g315). Resumes only on the same session key and binary, with the transcript on disk and the history equal to the recorded conversation plus Claude's reply; anything else (edit, revert, compaction, account switch, open tool round trip) replays. opencode-dcp's `` references (and its `@12@` compact form) are not part of the digest: dcp renumbers them on every opencode restart, so after an undo the same message came back under another number and the conversation was refused as `conversation-changed`. Records carry a digest `version`; one without it (written by an older plugin) is compared the old way. Not on compaction. Log: `resuming the claude session from before the restart` (NOTICE) or `not resuming ...` with a reason (INFO). `false` disables reading and writing. | | `liveModelSwitch` | boolean | `true` | Apply a model or reasoning effort change to the conversation's RUNNING `claude` with the CLI's own control requests (`set_model`, `apply_flag_settings {effortLevel}`) instead of stopping it and spawning another with `--resume`. Measured on 2.1.288 and 2.1.314 (h #g278): the conversation is kept, the next request goes out under the new model or effort, and prompt cache reads and writes match the respawn's; what it saves is the respawn, 4.6 to 6.6 s to `system`/`init` on a real install, against 0.5 to 0.7 s for `set_model` and about 25 to 140 ms for an effort change. So that an effort change can apply, a headless spawn on a CLI that can switch (2.1.288+) passes `--effort ` and drops `CLAUDE_CODE_EFFORT_LEVEL` from the child's env: the variable beats `apply_flag_settings` silently (a `success` answer and an unchanged request). Only on an IDLE headless child of the same conversation whose key differs in nothing but the model name (same `@account`, same fast mode) and the effort; an effort changes live only between two explicit levels. A change that lands mid-turn still finishes that turn on the old settings (h #g271) and applies at the next turn. Never across accounts, never on the interactive transport (no control channel; it keeps respawning), never on compaction. A refused or unanswered request (`CLAUDE_CODE_LIVE_SWITCH_TIMEOUT_MS`, default 10000) stops the child and falls back to the respawn. Needs `resumeAcrossModelChanges`. `false` restores the respawn and the env-var effort exactly. Log: `switched the live claude process to the new model or effort instead of respawning it` (NOTICE), `could not switch the live claude process; respawning it instead` (NOTICE, with `step` and `reason`). | | `resumeAcrossModelChanges` | boolean | `true` | When the operator changes a conversation's model or reasoning effort mid-conversation, continue the same Claude session (`--resume --model `) instead of replaying the thread as text. Both are in the session key, so changing either used to start a fresh Claude conversation (issue #91); neither needs one, because `--model` and `CLAUDE_CODE_EFFORT_LEVEL` are spawn-time and the CLI applies either to a resumed transcript (measured on 2.1.288). The session is MOVED off the old key, so one Claude conversation has exactly one owner. Refused on every term `resumeAfterRestart` is refused on (another account, a transcript that is gone, a conversation that changed) plus two more: a sibling whose transcript may still be written to (that turn is served on the sibling instead and the change applies at the next turn that finds it idle, h #g271), and anything that is not the same cwd, request scope, opencode session and agent. An agent's prompt-cache TTL, `maxTurns` and `maxBudgetUsd` are spawn settings like the effort, so a change to one carries the conversation too, after a restart as well (h #g275); `--max-budget-usd` counts per process, so the carried process starts the new cap from zero, as any `--resume` does. Not on compaction, not on an account-failover switch. It reads the record `resumeAfterRestart` writes, which is also what carries the first change after an opencode restart (h #g274), so `resumeAfterRestart: false` turns it off too. Log: `continuing this conversation's claude session under the new model or effort` (NOTICE). | | `crossAccountResume` | boolean | `true` | On any account switch (a by-hand pick of another account's model in the same session, the switch form, and the switch back when the override expires), and only between accounts in the same `accountGroups` group, continue the same Claude conversation on the other account instead of replaying the thread as text. An account is a `CLAUDE_CONFIG_DIR` and a conversation is one `projects//.jsonl` inside it, so the switch copies that file into the target account's own projects dir (0600, dir 0700) and keeps the session id for the `--resume` both transports already build. Measured on CLI 2.1.288: a copied transcript resumes under another config dir with its context intact, the CLI resolves a session by FILENAME (not the `sessionId` in the records), it appends to the copy it found rather than to the cwd's path, the source comes out byte-identical, and no record holds a user, org or account id. Never overwrites: an older copy already at the target path (what a switch back finds) makes the carry take a fresh session id, and the live copy is the longest one. Refuses on nothing to carry, a non-file at the target path, or a failed copy, and each refusal falls back to the replay. Not on compaction, and inert with one account. Log: `carried this conversation's claude transcript to the other account` or `replaying this conversation as text on the other account` with a reason (both NOTICE). What is NOT verified live is a different Anthropic login answering another's conversation; `false` keeps the replay. | diff --git a/src/claude-code-language-model.ts b/src/claude-code-language-model.ts index 2df3b4c..3e484e4 100644 --- a/src/claude-code-language-model.ts +++ b/src/claude-code-language-model.ts @@ -4419,13 +4419,26 @@ export class ClaudeCodeLanguageModel implements LanguageModelV3 { }) } // Which Claude session answered this conversation, for the next - // opencode process. Only after a turn that was served: a failed one - // may leave a transcript the plugin itself would not resume. + // opencode process, and for a by-hand switch to another model or + // account. After a turn that was served, and after one that failed + // on a usage limit or an account block with the CLI's own failure + // reply (h #g315): measured on 2.1.322, that turn's message and the + // `` reply are both in the transcript, so the session is + // intact and holds the message. Leaving the record a turn behind is + // what made the switch an operator makes BECAUSE of a limit replay + // the whole thread instead of carrying it (`sibling-conversation- + // changed`: the limited turn's message sat past the record). Every + // other failure may leave a transcript the plugin would not resume, + // or one too long to carry anywhere, and keeps the replay. + const failedTurnKeptSession = + msg.is_error === true && + state.cliFailureReply && + (!!state.accountLimitHit || !!state.accountBlock) if ( self.config.resumeAfterRestart !== false && !compactionMode && !blockedReplay && - msg.is_error !== true && + (msg.is_error !== true || failedTurnKeptSession) && typeof msg.session_id === "string" ) { // Where the transcript was written, and whose account that is, so diff --git a/src/stream-parser.ts b/src/stream-parser.ts index 7f2c92f..46d33da 100644 --- a/src/stream-parser.ts +++ b/src/stream-parser.ts @@ -943,6 +943,11 @@ export function createLineHandler( // makes the note certain to fire at the result. (h #g194) const apiErrorReply = (msg as { is_api_error_message?: unknown }) .is_api_error_message === true + // Either signal means the CLI wrote its own failure reply after the + // user's message, so the session holds that message (h #g315). + if (apiErrorReply || typeof (msg as { error?: unknown }).error === "string") { + state.cliFailureReply = true + } // The limit itself, whichever of the note or the switch form answers // it: the interactive transport has no `rate_limit_event`, so this // reply is the only signal it gets (h #g209). diff --git a/src/turn-state.ts b/src/turn-state.ts index 1f492e4..81f651c 100644 --- a/src/turn-state.ts +++ b/src/turn-state.ts @@ -323,6 +323,14 @@ export interface TurnState { promptBlock: PromptBlock | null /** This turn's own message was ended: no API call, nothing answered. */ ownPromptBlocked: boolean + /** + * The CLI answered this turn with its own failure reply (a `` + * assistant frame, `is_api_error_message` or an `error` kind), which it + * writes to the transcript right after the user's message. A turn that + * failed this way on a usage limit or an account block left a session that + * holds the message, so its resume record is written (h #g315). + */ + cliFailureReply: boolean // ---- The batched drain -------------------------------------------------- @@ -515,6 +523,7 @@ export function createTurnState(init: TurnStateInit): TurnState { modelRefusal: null, promptBlock: null, ownPromptBlocked: false, + cliFailureReply: false, subagentDispatchForm: null, drainBuffer: [], diff --git a/test/account-groups.test.ts b/test/account-groups.test.ts index e57d413..6c78801 100644 --- a/test/account-groups.test.ts +++ b/test/account-groups.test.ts @@ -503,6 +503,20 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => { const envelope = JSON.parse(line) if (envelope.type !== "user") return record({ type: "input", sessionId, envelope }) + // A turn the CLI answers with its own failure reply, as 2.1.322 does: a + // \`\` frame after the user's message, then an \`is_error\` result. + // A usage limit, and an overloaded API as the control (h #g315). + const said = JSON.stringify(envelope) + const failure = said.includes("LIMITME") + ? { error: "rate_limit", text: "You've hit your session limit · resets 11pm" } + : said.includes("SERVERERR") + ? { error: "server_error", text: "API Error: 529 Overloaded." } + : null + if (failure) { + emit({ type: "assistant", uuid: sessionId + "-a" + (++replies), session_id: sessionId, error: failure.error, is_api_error_message: true, message: { role: "assistant", model: "", stop_reason: "stop_sequence", content: [{ type: "text", text: failure.text }] } }) + emit({ type: "result", subtype: "success", session_id: sessionId, is_error: true, num_turns: 1, result: failure.text, usage: { input_tokens: 0, output_tokens: 0 } }) + return + } // A uuid per reply, as the real CLI's frames carry: each served turn leaves // a checkpoint an undo could cut at (h #g282). emit({ type: "assistant", uuid: sessionId + "-a" + (++replies), session_id: sessionId, message: { role: "assistant", stop_reason: "end_turn", content: [{ type: "text", text: "MARLIN" }] } }) @@ -667,6 +681,68 @@ test("a by-hand account switch carries the conversation instead of replaying it" } }) +test("a by-hand switch AFTER a usage limit still carries the conversation", E2E, async () => { + // Measured on 2026-11-14 (h #g315): the appical account hit its 5-hour + // limit twice, the operator picked a model under the default account, and + // the switch replayed the whole thread as `sibling-conversation-changed`, + // because the resume record was only ever written after a SERVED turn and + // the limited turns' messages sat past it. + const fake = await createSwitchFixture() + try { + await fake.warm() + await fake.turn("alpha", MODEL, [...BEFORE]) + fake.writeTranscript("alpha", "claude-on-alpha") + const LIMITED = [...BEFORE, assistantText("OK"), userText("LIMITME what next?")] as any + const limited = await fake.turn("alpha", MODEL, LIMITED) + const finish = limited.find((part) => part.type === "finish") as any + assert.equal(finish.finishReason.unified, "error", "the limited turn failed") + + await fake.turn("beta", MODEL, [ + ...LIMITED, + assistantText(deltas(limited)), + userText("What is the codename?"), + ]) + + const args: string[] = fake.spawns().at(-1)!.args + const at = args.indexOf("--resume") + assert.deepEqual( + args.slice(at, at + 2), + ["--resume", "claude-on-alpha"], + `the switch carries the limited conversation: ${JSON.stringify(args)}`, + ) + assert.equal(fake.spawns().at(-1)!.configDir, fake.configDir("beta")) + const sent = fake.lastInput() + assert.ok(!sent.includes("conversation_history"), sent.slice(0, 400)) + assert.ok(!sent.includes("LIMITME"), "the limited message is already in the session") + } finally { + await fake.cleanup() + } +}) + +test("a switch after any other failed turn still replays, as before", E2E, async () => { + // The control: a failure that is not the account's (an overloaded API) is + // not trusted to have left a session worth carrying. + const fake = await createSwitchFixture() + try { + await fake.warm() + await fake.turn("alpha", MODEL, [...BEFORE]) + fake.writeTranscript("alpha", "claude-on-alpha") + const FAILED = [...BEFORE, assistantText("OK"), userText("SERVERERR what next?")] as any + const failed = await fake.turn("alpha", MODEL, FAILED) + + await fake.turn("beta", MODEL, [ + ...FAILED, + assistantText(deltas(failed)), + userText("What is the codename?"), + ]) + + assert.ok(!fake.spawns().at(-1)!.args.includes("--resume")) + assert.ok(fake.lastInput().includes("conversation_history")) + } finally { + await fake.cleanup() + } +}) + test("switching back carries the conversation home again", E2E, async () => { const fake = await createSwitchFixture() try { From 27516b02e11a722e5f0bdd9a48e9f4978426f3b3 Mon Sep 17 00:00:00 2001 From: Khalil Gharbaoui Date: Sat, 14 Nov 2026 23:11:30 +0100 Subject: [PATCH 3/6] Skip the blocked-prompt fake CLI on Windows --- AGENTS.md | 2 +- test/prompt-blocked.test.ts | 30 +++++++++++++++--------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b4717fd..4f58a26 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -513,7 +513,7 @@ Opt-in. `spawnInteractiveProcess` returns an `ActiveProcess`-shaped shim so doSt - CLI stream-event parsers and their dedup (`parseRateLimitEvent`, `describeRateLimit`, `parseSystemInit`, `apiKeySourceWarning`, `parseCompactBoundary`, `describeResultFailure`, `parseMcpServerErrors`, `describeMcpServerError`, `snapshotMcpServerErrors`, `parseUnrecognizedModel`, `reportUnrecognizedModel`, `describePluginLoadFailure`, `snapshotPluginLoadFailures`, `parseRefusalFallback`, `formatRefusalFallbackNote`, `reportRefusalFallback`, a between-turns compaction's note): `test/cli-events.test.ts`; the same events through a fake CLI and a real `doStream`, including that a skipped MCP entry warns and changes nothing else about the turn, and a 529 the CLI gave up on (`success` with `is_error`, from the `` reply or from the result alone) ending as an error with its sentence shown once and no footer: `test/cli-events-stream.test.ts`. - The wire-inactivity watchdog's visible note (`formatStreamTimeoutNote`, `CLAUDE_CODE_RESULT_FALLBACK_MS`): `test/result-fallback.test.ts`. - The silent-turn note (`isSilentTurn`, `formatSilentTurnNote`) and every turn it must stay out of: `test/silent-turn.test.ts`. -- A message a `UserPromptSubmit` hook ended (`parsePromptBlock` over 2.1.322's and 2.1.293's frames and the frames that are not a block, the reason's fold and cap, `formatPromptBlockedNote`'s shapes; then a fake CLI driving real `doStream` turns: this turn's own message failing as `blocked_by_hook` with the note and no footer, the session kept and the next message bare, a blocked replay dropping the child and session id and the next message replaying again, the legacy frame, a steered message blocked inside a turn that went on, a blocked compaction ending on its error part with no text, and a secret-like string in the prompt reaching neither the reply nor the log): `test/prompt-blocked.test.ts`. +- A message a `UserPromptSubmit` hook ended (`parsePromptBlock` over 2.1.322's and 2.1.293's frames and the frames that are not a block, the reason's fold and cap, `formatPromptBlockedNote`'s shapes; then a fake CLI driving real `doStream` turns: this turn's own message failing as `blocked_by_hook` with the note and no footer, the session kept and the next message bare, a blocked replay dropping the child and session id and the next message replaying again, the legacy frame, a steered message blocked inside a turn that went on, a blocked compaction ending on its error part with no text, and a secret-like string in the prompt reaching neither the reply nor the log; the fake-CLI half is POSIX only): `test/prompt-blocked.test.ts`. - `/claude-code-doctor` (report formatter, command-registration guard, `checkProxyAuth`, transcript strip, `describeSessionKey`, the skipped-MCP, not-loaded-plugin and background-subagent sections, and the plan-usage opt-in with `wantsPlanUsage`, `parsePlanUsage` and `fetchPlanUsage`): `test/doctor.test.ts`. - `/claude-code-doctor bundle` (the message-allowlist drift guard against `src/`, the pinned list of messages built at runtime, every kind's character class, the key-name sanitizer, `sanitizeArgv`, `sanitizeUrl`, the caps, `readLogTail`, file logging off, and above all the adversarial fixtures that put a fake system prompt, a user prompt, a tool input, an `sk-ant-` key, a bearer token, an `authToken`, an `ANTHROPIC_API_KEY=` value, an MCP env var, a `?token=` URL and the home path into every position a line has and assert none survives): `test/diagnostic-bundle.test.ts`. It uses in-memory fixtures and a stubbed tail read, so it can never append to a live `plugin.log` (h #g116). - The subagent dispatch form (`isSubagentDispatchActive` and every refusal, the one-question first form, the per-type and per-task forms, the `Per type…` account rows and the one third form they share with `Per task…`, the three account widths and their precedence, a per-type account row overriding an account typed on the type's own row, the group restriction on every offered and typed path, `parseCustomChoice` with and without candidates, `parseQuestionAnswers` over the live-measured sentence shapes, the claim store including two concurrent same-type children and the parent check, the TTL, `dispatchAccountCandidates` with and without the cross-group flag, a remembered choice read back after a simulated restart, a remembered model or account that went away, the delete through `deleteActiveProcessesForSession`, and the transcript strip): `test/subagent-dispatch.test.ts`. The file behind `Same as last time` (round trip, restart, two writers merging, a malformed file, a record of the wrong shape, the age cutoff, both caps, the `0600` mode and the fact that nothing but the three strings is written): `test/dispatch-choice-store.test.ts`. The same through a real `doStream` and a fake CLI (the option off, the argv unchanged when it is on, the hold, the release, the child's own `--model` / `CLAUDE_CODE_EFFORT_LEVEL` / account wrapper, two agent types spawning under two different accounts, `Same as last time` surviving a simulated restart, and the dismissal note): `test/subagent-dispatch-stream.test.ts`. diff --git a/test/prompt-blocked.test.ts b/test/prompt-blocked.test.ts index 59b47aa..1d76058 100644 --- a/test/prompt-blocked.test.ts +++ b/test/prompt-blocked.test.ts @@ -157,6 +157,16 @@ test("the note has one shape per case and never an em dash", () => { // Through a real doStream // --------------------------------------------------------------------------- +/** + * The fake CLI is a `.cjs` file run through its shebang, which Windows cannot + * execute. Only the harness is POSIX-only: the parser and the note above are + * portable and run on the Windows CI job. + */ +const E2E = { + timeout: 60_000, + skip: process.platform === "win32" ? "the fake-CLI harness is POSIX-only" : false, +} as const + function fixture(settings: Record = {}) { const cwd = mkdtempSync(join(tmpdir(), "opencode-prompt-blocked-")) const cliPath = join(cwd, "fake-claude.cjs") @@ -282,9 +292,7 @@ const lastText = (stdin: string): string => { return texts[texts.length - 1] } -test("a blocked message fails the turn, names the hook, and the session goes on", { - timeout: 60_000, -}, async () => { +test("a blocked message fails the turn, names the hook, and the session goes on", E2E, async () => { _resetServedConversations() const f = fixture() const logDir = mkdtempSync(join(tmpdir(), "opencode-prompt-blocked-log-")) @@ -338,9 +346,7 @@ test("a blocked message fails the turn, names the hook, and the session goes on" assert.ok(!log.includes(REASON), "nor the hook's sentence") }) -test("a blocked replay drops the empty session, so the next message replays again", { - timeout: 60_000, -}, async () => { +test("a blocked replay drops the empty session, so the next message replays again", E2E, async () => { _resetServedConversations() const f = fixture() try { @@ -379,9 +385,7 @@ test("a blocked replay drops the empty session, so the next message replays agai } }) -test("before 2.1.314 the frame has no outcome, and the turn still fails", { - timeout: 60_000, -}, async () => { +test("before 2.1.314 the frame has no outcome, and the turn still fails", E2E, async () => { _resetServedConversations() const f = fixture() try { @@ -395,9 +399,7 @@ test("before 2.1.314 the frame has no outcome, and the turn still fails", { } }) -test("a message blocked inside a turn that went on gets a note, not a failure", { - timeout: 60_000, -}, async () => { +test("a message blocked inside a turn that went on gets a note, not a failure", E2E, async () => { _resetServedConversations() const f = fixture() try { @@ -414,9 +416,7 @@ test("a message blocked inside a turn that went on gets a note, not a failure", } }) -test("a blocked compaction writes no text and ends on an error", { - timeout: 60_000, -}, async () => { +test("a blocked compaction writes no text and ends on an error", E2E, async () => { _resetServedConversations() const f = fixture() try { From 325ebe6fe4de66c7323db51518cca625d0ba34c8 Mon Sep 17 00:00:00 2001 From: Khalil Gharbaoui Date: Sat, 14 Nov 2026 23:25:09 +0100 Subject: [PATCH 4/6] Re-arm a watchdog that fired late, interrupt on close The wire-inactivity watchdog counts wall-clock time, sleep included, so a sleeping Mac read as a silent CLI and closed a subagent's turn while its CLI only waited for the network; the CLI then ran on unattended for 28 minutes. A fire well past its deadline now waits a fresh delay, and a fire that closes the turn interrupts the CLI. h #g316 --- AGENTS.md | 2 + TODO.md | 26 ++-- docs/agents-history.md | 47 ++++++++ docs/guides/tool-proxy.md | 2 +- skills/claude-code-plugin/SKILL.md | 2 +- src/turn-controller.ts | 40 ++++++ test/result-fallback-sleep.test.ts | 187 +++++++++++++++++++++++++++++ 7 files changed, 286 insertions(+), 20 deletions(-) create mode 100644 test/result-fallback-sleep.test.ts diff --git a/AGENTS.md b/AGENTS.md index 4f58a26..35c7d86 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,6 +75,7 @@ changing, reverting or "simplifying" a rule. - **An abort that lands while a turn is being PREPARED must stop it, and the only thing that can see it is a watch created before the prologue's first await** (`watchTurnAbort`, `src/turn-abort.ts`): `addEventListener("abort")` on a signal that already aborted never fires, so the stream's own handler, which cannot exist until the prologue has finished, missed every stop in that window and the turn spawned, wrote and billed anyway (measured: a turn alive at 5,874 ms against a 5,000 ms signal). The handler is registered through `onAbort` in the **synchronous** part of `start()` now, never inside `setup()`, and `TurnState.cliAskedForWork` (set at exactly two places, the envelope write and the top of the tool-result branch) selects a new FIRST branch in front of the existing ones: close the stream, discard a proxy MCP server this turn created but never handed to a child, send **no** `interrupt` (a reused process's last turn is not this doStream's to stop) and leave an earlier step's pending proxy calls untouched, so #g26 and #g82 still own how they end. Three prologue checks, plus `stoppedBeforeWork()` on entry to `setup()`, at both spawn sites and after `interruptTurn`. **The raced `detectCliVersion` is left running on purpose**, because its answer is cached process-wide and cancelling it would be #g181 again; only the MCP connect wait takes the signal (`getRuntimeMcpStatus({ signal })`), because its poll loop is ours. `test/prologue-abort.test.ts`. (h #g182) - **A proxy deadline must not count the operator's time on a permission prompt.** Both timers go through `armProxyDeadline` and its `ProxyDeadlineGuard`; `isProxyCallStillServed` keeps a call only when `emitted` **and** the session reads `busy`, rechecking every `PROXY_DEADLINE_RECHECK_MS`. No guard, a throwing guard or `unknown` end it as before. `test/broker.test.ts`. (h #g27) **Live on opencode 2.0.22 with a real prompt in the way (h #g219)**: with the host config asking for `write`/`edit`, a proxied `write` was queued, the step drained, opencode raised a permission request, the call sat parked for the twelve seconds the operator took, and `POST /api/session/{id}/permission/{requestID}/reply {"decision":"once"}` resolved it in the same step (`resolved pending proxy call`) and the file was written. Every V2 probe before this ran with `--auto`, so the prompt path had never been exercised there. **Before (h #g253) the guard itself could never keep a call on V2**: its `busy` read had no route there, and `unknown` ends the call at its deadline. It reads the event-fed run state now, and live on 2.0.31 a proxied `write` with a 5-second deadline waited out a 15-second permission hold (`proxy call past its deadline, but opencode is still serving it; waiting`) and was written, where v0.58.0 timed it out twice and Claude told the operator the tool kept failing. `test/v2-session-events.test.ts`. - **Abort sends the CLI an `interrupt` control request** (`interruptTurn`), or the turn runs on and bills. `noteTurnStarted` marks in flight at every stdin write asking for work, and the terminal `result` clears it inside the `rl` handler, **never** a permanent `lineEmitter` listener. `test/session-manager.test.ts`. (h #g59) **Live end to end on Claude Code 2.1.288 + opencode 1.18.35 (h #g219)**: `POST /session/{id}/abort` mid-reply logged `abort signal received mid-turn, starting grace period`, the CLI answered 21 ms later with a `result` of `error_during_execution` carrying `costUsd: 0` and `outputTokens: 0`, `interrupt sent for aborted turn {idle: true}` followed, and **the CLI's own transcript recorded a `[Request interrupted by user]` user record** right after the truncated assistant record (`stop_reason: null`). The next turn **reused the same process and the same Claude session id** and answered normally, so the interrupt ends the turn without ending the conversation. +- **The wire-inactivity watchdog counts wall-clock time, sleep included, so a late fire re-arms and a closing fire interrupts the CLI** (`startResultFallback`, `RESULT_FALLBACK_LATE_SLACK_MS` 5 s, h #g316). Measured on 2026-11-14 from a subagent's own transcript and `pmset -g log`: the stream was still delivering thinking at 20:09:42Z, the Mac slept 20:10:23Z to 20:20:56Z with a dark wake at 20:15:28Z, and the 60 s timer fired at 20:15:31Z, 3 s into the dark wake, with at most 41 s of awake time behind it, so ten minutes of sleep read as ten minutes of a silent CLI. A fire more than the slack past its deadline means this process was not running (a sleep, or an event-loop stall with the CLI's output possibly unread in the pipe), so it waits a fresh full delay; the fire that does close the turn sends `interruptTurn`, exactly as an abort does (h #g59), because that CLI retried after the wake and ran on unattached for 28 minutes, its proxied calls each waiting out their 10-minute deadline. A proxied call queued with no stream attached is deliberately NOT rejected at once: that is the late-result recovery path (h #g82, h #g119), and the interrupt removes the cause. The start watchdog has the same clock and is unchanged (unmeasured). `test/result-fallback-sleep.test.ts` fakes the sleep through `_setResultFallbackClock`, never by blocking the loop. - **`idleProcessTimeoutMs` is off unless set** (`resolveIdleProcessTimeoutMs`, so unset and `0` both arm nothing). Unref'd, cancelled by every get/set/detach/spawn/exit, deleting only the same process object; a process found `turnInFlight` is re-armed, never killed. `test/session-manager.test.ts`. (h #g60) - **The child's stdin needs its own `error` listener, and `proc.on("error")` is not it**: an `error` on a listener-less stream throws inside **opencode's** process. `spawnClaudeProcess` attaches one, logs at WARN, calls `settleTurn`, and deliberately does not end the turn. `test/session-manager.test.ts`. (h #g61) - **LRU eviction must never take a process that is mid-turn**: `evictIfNeeded` walks insertion order for the first with `turnInFlight !== true`, and when all are busy evicts **nothing** and warns. Do not "restore" the one-liner. Cap is **16**, and idle eviction stays off unless `idleProcessTimeoutMs` is set, so the cap is the only bound on a default install. `test/session-manager.test.ts`. (h #g62, #g179) @@ -512,6 +513,7 @@ Opt-in. `spawnInteractiveProcess` returns an `ActiveProcess`-shaped shim so doSt - The usage a finish reports (`lastCallContextUsage`: the last call's context, not the turn sum, at the main and tool-call finishes, the synthetic-frame guard, zeros at a mid-turn proxied boundary): `test/context-usage.test.ts`. - CLI stream-event parsers and their dedup (`parseRateLimitEvent`, `describeRateLimit`, `parseSystemInit`, `apiKeySourceWarning`, `parseCompactBoundary`, `describeResultFailure`, `parseMcpServerErrors`, `describeMcpServerError`, `snapshotMcpServerErrors`, `parseUnrecognizedModel`, `reportUnrecognizedModel`, `describePluginLoadFailure`, `snapshotPluginLoadFailures`, `parseRefusalFallback`, `formatRefusalFallbackNote`, `reportRefusalFallback`, a between-turns compaction's note): `test/cli-events.test.ts`; the same events through a fake CLI and a real `doStream`, including that a skipped MCP entry warns and changes nothing else about the turn, and a 529 the CLI gave up on (`success` with `is_error`, from the `` reply or from the result alone) ending as an error with its sentence shown once and no footer: `test/cli-events-stream.test.ts`. - The wire-inactivity watchdog's visible note (`formatStreamTimeoutNote`, `CLAUDE_CODE_RESULT_FALLBACK_MS`): `test/result-fallback.test.ts`. +- The same watchdog after a sleep (a fire ten minutes late re-arming and the CLI answering inside the fresh delay, and a closing fire sending the CLI one `interrupt`; POSIX only): `test/result-fallback-sleep.test.ts`. - The silent-turn note (`isSilentTurn`, `formatSilentTurnNote`) and every turn it must stay out of: `test/silent-turn.test.ts`. - A message a `UserPromptSubmit` hook ended (`parsePromptBlock` over 2.1.322's and 2.1.293's frames and the frames that are not a block, the reason's fold and cap, `formatPromptBlockedNote`'s shapes; then a fake CLI driving real `doStream` turns: this turn's own message failing as `blocked_by_hook` with the note and no footer, the session kept and the next message bare, a blocked replay dropping the child and session id and the next message replaying again, the legacy frame, a steered message blocked inside a turn that went on, a blocked compaction ending on its error part with no text, and a secret-like string in the prompt reaching neither the reply nor the log; the fake-CLI half is POSIX only): `test/prompt-blocked.test.ts`. - `/claude-code-doctor` (report formatter, command-registration guard, `checkProxyAuth`, transcript strip, `describeSessionKey`, the skipped-MCP, not-loaded-plugin and background-subagent sections, and the plan-usage opt-in with `wantsPlanUsage`, `parsePlanUsage` and `fetchPlanUsage`): `test/doctor.test.ts`. diff --git a/TODO.md b/TODO.md index 7bed9b4..1304bb3 100644 --- a/TODO.md +++ b/TODO.md @@ -82,20 +82,10 @@ blocked prompt ends a PTY turn is unmeasured; (2) the location-switch empty turn below may be the same block: check that session's Claude transcript for a `blocked_by_hook` record before building anything on the session-key theory. -- 2026-11-14 (evening), measured, not fixed: the wire-inactivity watchdog ended a turn while the child - lived on, unattached. The Mac idle-slept 21:10:23 to 21:20:56 CET (`pmset -g log`) during a designer - subagent's turn (`ses_e24dd447bffe3jnporpawTFbxI`, Claude session `3e7cd878`, about 777K tokens of - context). `result fallback timer fired` at 20:15:31Z, inside a dark wake; the turn ended as - `provider.unknown` and the subagent was reported failed. The CLI recorded `api_error` - `StreamSuspended` ("Connection lost while your computer was asleep") at 20:21:03Z, retried on its own - and carried on: a proxied `write` (20:22:46Z) and a proxied `bash` (20:32:56Z) each waited out the - 10-minute deadline with no opencode step to serve them, a third call was parked at 20:43:52Z, and the - child died only when opencode restarted (about 20:48Z). That is about 28 minutes of a 777K-context - child nobody was listening to, drawn from the account's window, and its finished file never reached - the disk. Questions: should the watchdog interrupt or stop the child when it closes the turn; should - a system suspend (the CLI's own `StreamSuspended`, or a timer firing late after a sleep) hold the - watchdog rather than fire it; should a call queued with no stream attached be rejected at once - rather than at its deadline. +- 2026-11-14 (evening), the watchdog that closed a turn during a sleep: FIXED on `fix/blocked-prompt` + (h #g316). It counts wall-clock time, sleep included, so a fire well past its deadline now waits + again, and a fire that closes the turn interrupts the CLI. Left alone on purpose: a proxied call + queued with no stream attached (late-result recovery) and the start watchdog (unmeasured). - 2026-11-14, found while fixing h #g312, not fixed (not in that PR's scope): dcp's `compact` message reference (`\n@1044@`) is not stripped in two places that strip its XML form. @@ -203,10 +193,10 @@ raised, so they survive context compaction; removed when answered, done or dropp side is fixed, h #g314, and never sets the guard's variable itself): keep it blocking, or set `AGENT_GUARD_PROMPT_GUARD_MODE` for opencode's environment? Your config, not the plugin's. - 2026-11-14: watchdog follow-up, offered by an earlier turn of session - `ses_e324dbf7bffeRHQIz10AIxm7dT` (its reasoning went with that session's history): "should the - plugin wait a little longer after the CLI reports an API error before it closes the turn? Now, - later, or drop?" The sleep incident (Backlog, 2026-11-14 evening) is a second case and adds the - unattached child: now, later, or drop? + `ses_e324dbf7bffeRHQIz10AIxm7dT`: "should the plugin wait a little longer after the CLI reports an + API error before it closes the turn?" The sleep case is fixed (h #g316: a late fire waits again, + a closing fire interrupts the CLI). The API-error case itself has no evidence on record (its + reasoning went with that session's history): keep it open until it happens again, or drop? - 2026-11-10: what to build next from Future Features (doctor warnings for setups that fail silently, model aliases such as `opus`, a `task_send` to steer a background subagent, continuing a terminal `claude` session in opencode): pick any, or hold. diff --git a/docs/agents-history.md b/docs/agents-history.md index 4167b96..752b56f 100644 --- a/docs/agents-history.md +++ b/docs/agents-history.md @@ -12982,3 +12982,50 @@ a `LIMITME` message the way 2.1.322 answers a usage limit and a `SERVERERR` one after a limit resumes the first account's session from the second account's config dir with no replay and without re-sending the limited message (it fails without the change: the switch replays), and a switch after the 529 still replays. + + +## The inactivity watchdog read a sleeping Mac as a silent CLI, and left the CLI running (2026-11-14) + +h #g316. The second finding recorded in TODO.md on 2026-11-14: a designer subagent +(`ses_e24dd447bffe3jnporpawTFbxI`, Claude session `3e7cd878`, about 777K tokens of context) was +reported failed after the Mac idle-slept, and its CLI ran on for about 28 minutes with nobody +listening. + +Measured, from the subagent's own Claude transcript (record types and timestamps only) and +`pmset -g log`: + +- The stream was live: an `api-request` at 20:09:22Z and a thinking record at 20:09:42Z, so the + watchdog was last reset at or after 20:09:42Z. +- The Mac slept at 21:10:23 CET (20:10:23Z), had a dark wake at 21:15:28 that ended in sleep at + 21:15:39, and woke at 21:20:56. +- `result fallback timer fired` at 20:15:31Z, 3 s into the dark wake. A 60 s timer counting awake + time could not have fired then (at most 41 s of awake time before the sleep, 3 s after), so the + timer counts wall-clock time, sleep included, and fired at the first moment the process ran. +- The turn ended as a stream timeout (`provider.unknown`, the subagent reported failed). The CLI + logged `api_error` (`Connection error`, Claude Code's `StreamSuspended`) at 20:21:03Z, retried on + its own and carried on: an assistant reply and a proxied call at 20:22:46Z. A message written + to its stdin 0.5 s after the fire ("Your response above was cut off mid-stream. Resume directly + from where...", source unknown: not in opencode's binaries or plugin caches) was what it went on + with. Its proxied calls each waited out the 10-minute deadline, and it died only when opencode + restarted. + +What changed in `startResultFallback`: + +- A fire more than `RESULT_FALLBACK_LATE_SLACK_MS` (5 s) past its deadline re-arms for a fresh + full delay instead of closing the turn, with an INFO line. A late fire means the process was not + running, so the silence was never observed; an event-loop stall is the same case, where the + CLI's output can be sitting unread in the pipe while the timer phase runs first. Repeated + sleeps re-arm each time; once awake, the CLI's next line resets the watchdog as always. +- A fire that does close the turn sends `interruptTurn` to the CLI, exactly as an abort does + (h #g59), so the turn stops instead of running on unattached. Not on an aborted turn, whose own + path already interrupts. +- Not changed: a proxied call that arrives with no stream attached still waits for the next turn + or its deadline, because that is the late-result recovery path (h #g82, h #g119), and with the + interrupt the cause is gone. The start watchdog shares the clock and is unchanged; nothing + measured shows it firing across a sleep. + +Tests: `test/result-fallback-sleep.test.ts` (POSIX). The sleep is faked with +`_setResultFallbackClock`, which jumps ten minutes when the first text arrives: the fire at 2 s +re-arms and the CLI's answer at 3 s lands (with the re-arm switched off the turn closes as a +stream timeout). A CLI that never finishes gets exactly one `interrupt` control request after the +close (with the interrupt switched off, none). diff --git a/docs/guides/tool-proxy.md b/docs/guides/tool-proxy.md index 61a5142..f31997a 100644 --- a/docs/guides/tool-proxy.md +++ b/docs/guides/tool-proxy.md @@ -224,7 +224,7 @@ A deadline does not count time opencode is still spending on the call. When it p `question` keeps 30 minutes because it blocks on a human reading a form, and a form nobody answers is not an event. A positive `task` override restores a wall-clock backstop for operators who want one; if it fires, the error tells Claude not to "schedule a wake-up": that is a Claude Code affordance which cannot fire in this headless/proxy context, so deferring silently loses the work. -Two watchdogs are a different thing again and are unchanged: the start watchdog (90 s of complete silence after a turn is written, 150 s for a new process still waiting on its MCP servers, respawn then error, see `CLAUDE_CODE_START_WATCHDOG_MS`) and the wire-inactivity watchdog (60 s of silence after content, see `CLAUDE_CODE_RESULT_FALLBACK_MS`; when it fires the reply gets a `▌ **stream timeout:**` note so the turn does not just stop). Those exist because a process that is alive but wedged emits no event to listen to, and a proxy call is never what they are waiting on: a CLI parked inside a proxied tool is producing nothing on purpose, and both watchdogs know that. +Two watchdogs are a different thing again and are unchanged: the start watchdog (90 s of complete silence after a turn is written, 150 s for a new process still waiting on its MCP servers, respawn then error, see `CLAUDE_CODE_START_WATCHDOG_MS`) and the wire-inactivity watchdog (60 s of silence after content, see `CLAUDE_CODE_RESULT_FALLBACK_MS`; when it fires the reply gets a `▌ **stream timeout:**` note so the turn does not just stop, and the CLI's turn is interrupted so it does not run on with nobody listening; a fire that comes well past its deadline because the machine slept waits a fresh 60 s instead). Those exist because a process that is alive but wedged emits no event to listen to, and a proxy call is never what they are waiting on: a CLI parked inside a proxied tool is producing nothing on purpose, and both watchdogs know that. If Claude nevertheless abandons the HTTP call, the plugin preserves narration emitted while opencode was running the tool, renders it on return, and delivers the late completion as a plain-text continuation naming the original call. It tells Claude not to run the tool again. A silent post-tool continuation gets one resumed-process retry, preserving the original model, account, effort, and proxy configuration; a second failure ends with an error rather than an indefinite hang. Buffered narration is capped at 500 lines and 2 MiB, with a warning if output was dropped. diff --git a/skills/claude-code-plugin/SKILL.md b/skills/claude-code-plugin/SKILL.md index 8e5465d..d1f44e1 100644 --- a/skills/claude-code-plugin/SKILL.md +++ b/skills/claude-code-plugin/SKILL.md @@ -262,7 +262,7 @@ their secret values. Arbitrary MCP `{env:NAME}` placeholders are outside this li | `CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS` | Set to `0` for the interactive TUI unless the operator set it, so a proxied call past 120 s stays in the foreground as on headless. `CLAUDE_CODE_DISABLE_MCP_TASK_BACKGROUND` is not set: it covers MCP-task servers only, which the proxy never is, and at `0` the CLI asks no server for a task. | | `CLAUDE_CODE_START_WATCHDOG_MS` | Positive integer ms before a headless start or proxy-result continuation is considered silent; default 90000 for missing/invalid/nonpositive values. First expiry respawns, second errors. Bookkeeping-only output is not progress. A process that has not sent its first `system`/`init` yet gets at least its `MCP_TIMEOUT` plus 30 s (150 s by default), since the CLI sends `init` only after its MCP servers connect or time out; the log's `beforeInit` says which delay fired. Keep within timer range; do not lower for routine config checks. | | `CLAUDE_CODE_LIVE_SWITCH_TIMEOUT_MS` | Positive integer ms one `set_model` or `apply_flag_settings` may take before a live model or effort switch gives up, stops the child and falls back to the respawn; default 10000 for missing/invalid/nonpositive values. Measured answers: 0.5 to 0.7 s and 20 to 140 ms. | -| `CLAUDE_CODE_RESULT_FALLBACK_MS` | Positive integer ms of stdout silence, after the CLI has produced output, before the turn is closed with no `result`; default 60000 for missing/invalid/nonpositive values. The close is announced in the reply as a `▌ **stream timeout:**` note, which is stripped from any rebuilt transcript. An aborted turn gets no note. | +| `CLAUDE_CODE_RESULT_FALLBACK_MS` | Positive integer ms of stdout silence, after the CLI has produced output, before the turn is closed with no `result`; default 60000 for missing/invalid/nonpositive values. The close is announced in the reply as a `▌ **stream timeout:**` note, which is stripped from any rebuilt transcript, and interrupts the CLI's turn so it does not run on unattended. An aborted turn gets no note. A fire more than 5 s past its deadline (the machine slept, or the event loop stalled) waits a fresh full delay instead, because that silence was never observed (h #g316). | | `OPENCODE_CLAUDE_CODE_LOG_FILE` | Overrides `logging.file`: trimmed `0/false/no/off` are false; any other nonempty value is true; empty falls back to config. Prefer `1` or `0`. | | `OPENCODE_CLAUDE_CODE_LOG_DIR` | Overrides `logging.dir`. | | `OPENCODE_CLAUDE_CODE_MODEL_PROBE` | `0` or `false` stops the background model probe for this environment (the `npm test` script sets it); the stored answer is still registered. `cliModelCatalog: false` is the config switch and also ignores the stored answer. | diff --git a/src/turn-controller.ts b/src/turn-controller.ts index 7b2a376..ef30191 100644 --- a/src/turn-controller.ts +++ b/src/turn-controller.ts @@ -7,6 +7,7 @@ import { effectiveSpawnMcpTimeoutMs } from "./cli-version.js" import { deleteActiveProcess, deleteClaudeSessionId, + interruptTurn, noteTurnStarted, respawnActiveProcess, } from "./session-manager.js" @@ -81,6 +82,20 @@ export function clearFallbackTimer(state: TurnState): void { } } +/** How far past its deadline the inactivity watchdog may fire and still close. */ +const RESULT_FALLBACK_LATE_SLACK_MS = 5_000 + +let resultFallbackLateSlackMs = RESULT_FALLBACK_LATE_SLACK_MS +let watchdogNow: () => number = () => Date.now() + +/** Test seams: a clock that can jump, as a sleep makes it, and the slack. `null` restores. */ +export function _setResultFallbackClock(now: (() => number) | null): void { + watchdogNow = now ?? (() => Date.now()) +} +export function _setResultFallbackLateSlackMs(ms: number | null): void { + resultFallbackLateSlackMs = ms ?? RESULT_FALLBACK_LATE_SLACK_MS +} + /** * Wire-inactivity watchdog. Resets on every line received from the CLI; only * fires if the CLI has emitted content and then gone silent on stdout for @@ -89,6 +104,17 @@ export function clearFallbackTimer(state: TurnState): void { * (most visibly with sonnet between text-end and the next tool_use_start). * Tunable for reproduces and for the regression test, the same seam * CLAUDE_CODE_START_WATCHDOG_MS gives the start watchdog below. + * + * A fire that comes well past its deadline re-arms instead of closing (h #g316): + * the timer counts wall-clock time, sleep included (measured on 2026-11-14: it + * fired 3 s into a dark wake, five minutes after it was due, with at most 41 s + * of awake time behind it), so ten minutes of a sleeping Mac read as ten + * minutes of a silent CLI and the turn was closed while the CLI was only + * waiting for the network. A late fire means this process was not running, so + * the silence was never observed; an event-loop stall is the same case, with + * the CLI's output possibly unread in the pipe. A fire that does close the turn + * also interrupts the CLI, as an abort does (h #g59): closed here, nobody reads + * what it does next, and one child ran on unattached for 28 minutes. */ export function startResultFallback( state: TurnState, @@ -96,11 +122,25 @@ export function startResultFallback( ): void { clearFallbackTimer(state) if ((!state.hasReceivedContent && !state.hasReceivedProgress) || state.controllerClosed) return + const armedAt = watchdogNow() state.resultFallbackTimer = setTimeout(() => { if (state.controllerClosed) return + const lateMs = watchdogNow() - armedAt - delayMs + if (lateMs > resultFallbackLateSlackMs) { + log.info("result fallback timer fired late; the process was not running, so it waits again", { + delayMs, + lateMs, + }) + startResultFallback(state, delayMs) + return + } log.warn("result fallback timer fired — closing stream without result event", { delayMs, }) + const child = state.activeProcess + if (child && !state.autoContinueState.aborted) { + void interruptTurn(child).catch(() => undefined) + } // Closing on a log line alone left the operator with a reply that // just stopped. An abort is exempt: they asked for it, and the // short grace period there is not a silent CLI. diff --git a/test/result-fallback-sleep.test.ts b/test/result-fallback-sleep.test.ts new file mode 100644 index 0000000..f9e8ef5 --- /dev/null +++ b/test/result-fallback-sleep.test.ts @@ -0,0 +1,187 @@ +/** + * The wire-inactivity watchdog and a machine that slept (h #g316). + * + * On 2026-11-14 the watchdog fired 3 s into a dark wake, five minutes after it + * was due: it counts wall-clock time, sleep included, so the Mac's sleep read + * as a silent CLI and a subagent's turn was closed while its CLI was only + * waiting for the network. The CLI then retried on its own and ran on for 28 + * minutes with nobody listening. A late fire now waits again, and a fire that + * does close the turn interrupts the CLI. + * + * The sleep is faked by moving the watchdog's clock, never by blocking the + * event loop, so nothing here races a deadline (h #g181). + * + * Usage: npx tsx --test test/result-fallback-sleep.test.ts + */ +import "./isolate.js" +import assert from "node:assert/strict" +import { afterEach, test } from "node:test" +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" + +import { STREAM_TIMEOUT_MARKER } from "../src/cli-events.js" +import { createClaudeCode } from "../src/index.js" +import { deleteActiveProcess, sessionKey } from "../src/session-manager.js" +import { + _setResultFallbackClock, + _setResultFallbackLateSlackMs, +} from "../src/turn-controller.js" + +afterEach(() => { + _setResultFallbackClock(null) + _setResultFallbackLateSlackMs(null) +}) + +/** + * A `claude` that writes half an answer, goes silent, and finishes after + * `finishAfterMs` (or never, for `null`). It records every stdin line, so a + * test can see the interrupt the plugin sends. + */ +function createFakeCli(finishAfterMs: number | null) { + const cwd = mkdtempSync(join(tmpdir(), "opencode-result-fallback-sleep-")) + const cliPath = join(cwd, "fake-claude.cjs") + const record = join(cwd, "stdin.jsonl") + writeFileSync( + cliPath, + `#!${process.execPath} +const fs = require("node:fs") +const readline = require("node:readline") +if (process.argv.includes("--version")) { + process.stdout.write("2.1.322\\n") + process.exit(0) +} +const emit = (message) => process.stdout.write(JSON.stringify({ session_id: "fake-session", ...message }) + "\\n") +const text = (body) => emit({ type: "stream_event", event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: body } } }) +let answered = false +readline.createInterface({ input: process.stdin }).on("line", (line) => { + fs.appendFileSync(${JSON.stringify(record)}, line + "\\n") + if (answered) return + answered = true + emit({ type: "system", subtype: "init", tools: ["Read"] }) + text("half an answer") + const after = ${JSON.stringify(finishAfterMs)} + if (after === null) return + setTimeout(() => { + text(" and the rest") + emit({ type: "result", subtype: "success", is_error: false, num_turns: 1, result: "done", + usage: { input_tokens: 1, output_tokens: 1 } }) + }, after) +}) +`, + { mode: 0o755 }, + ) + return { + cwd, + cliPath, + stdinLines: (): any[] => + existsSync(record) + ? readFileSync(record, "utf8") + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line)) + : [], + } +} + +async function runTurn( + fake: ReturnType, + fallbackMs: number, + onFirstText?: () => void, +): Promise<{ parts: any[]; key: string }> { + const modelId = "claude-test-result-fallback-sleep" + const key = sessionKey(fake.cwd, `${modelId}::tools::default::context=["claude-code",null]`) + const previous = process.env.CLAUDE_CODE_RESULT_FALLBACK_MS + process.env.CLAUDE_CODE_RESULT_FALLBACK_MS = String(fallbackMs) + try { + const model = createClaudeCode({ + cliPath: fake.cliPath, + cwd: fake.cwd, + bridgeOpencodeMcp: false, + proxyOpencodeMcpTools: false, + proxyTools: [], + autoContinueIncompleteTurns: false, + }).languageModel(modelId) + const response = await model.doStream({ + prompt: [{ role: "user", content: [{ type: "text", text: "go" }] }], + tools: [ + { type: "function", name: "read", description: "Read", inputSchema: { type: "object", properties: {} } }, + ], + abortSignal: AbortSignal.timeout(60_000), + } as any) + const parts: any[] = [] + let sawText = false + for await (const part of response.stream) { + parts.push(part) + if (!sawText && part.type === "text-delta") { + sawText = true + onFirstText?.() + } + } + return { parts, key } + } finally { + if (previous === undefined) delete process.env.CLAUDE_CODE_RESULT_FALLBACK_MS + else process.env.CLAUDE_CODE_RESULT_FALLBACK_MS = previous + } +} + +const POSIX = { + timeout: 60_000, + skip: process.platform === "win32" ? "the fake-CLI harness is POSIX-only" : false, +} as const + +const body = (parts: any[]) => + parts + .filter((part) => part.type === "text-delta") + .map((part) => part.delta) + .join("") + +test("a watchdog that fires after a sleep waits again instead of closing the turn", POSIX, async () => { + // Due at 2 s; the CLI finishes at 3 s. The clock jumps ten minutes the + // moment the first text arrives, as a sleep makes it, so the fire at 2 s + // looks ten minutes late and must wait a fresh 2 s, which the CLI beats. + const fake = createFakeCli(3_000) + let key = "" + try { + _setResultFallbackLateSlackMs(500) + const turn = await runTurn(fake, 2_000, () => { + const jump = 10 * 60_000 + _setResultFallbackClock(() => Date.now() + jump) + }) + key = turn.key + const said = body(turn.parts) + assert.ok(!said.includes(STREAM_TIMEOUT_MARKER), said) + assert.match(said, /half an answer and the rest/) + const finish = turn.parts.find((part) => part.type === "finish") + assert.deepEqual(finish.finishReason, { unified: "stop", raw: "stop" }) + assert.ok( + !fake.stdinLines().some((line) => line.request?.subtype === "interrupt"), + "nothing was interrupted", + ) + } finally { + if (key) deleteActiveProcess(key) + rmSync(fake.cwd, { recursive: true, force: true }) + } +}) + +test("a watchdog that closes the turn interrupts the CLI it stopped listening to", POSIX, async () => { + const fake = createFakeCli(null) + let key = "" + try { + const turn = await runTurn(fake, 500) + key = turn.key + assert.ok(body(turn.parts).includes(STREAM_TIMEOUT_MARKER)) + + let interrupts: any[] = [] + for (let waited = 0; waited < 10_000 && interrupts.length === 0; waited += 50) { + await new Promise((resolve) => setTimeout(resolve, 50)) + interrupts = fake + .stdinLines() + .filter((line) => line.type === "control_request" && line.request?.subtype === "interrupt") + } + assert.equal(interrupts.length, 1, JSON.stringify(fake.stdinLines())) + } finally { + if (key) deleteActiveProcess(key) + rmSync(fake.cwd, { recursive: true, force: true }) + } +}) From ef0cc542de66d376112e8b65c53991b115bcb440 Mon Sep 17 00:00:00 2001 From: Khalil Gharbaoui Date: Sun, 15 Nov 2026 00:08:00 +0100 Subject: [PATCH 5/6] Hold both watchdogs for an announced retry An api_retry frame says how long the CLI will wait before its next attempt; whichever watchdog is armed now waits that much longer, so a long backoff neither closes the turn nor respawns a working child. The start watchdog also re-arms on a late fire, like the inactivity one. h #g316 --- AGENTS.md | 4 +- TODO.md | 14 ++-- docs/agents-history.md | 32 ++++++-- skills/claude-code-plugin/SKILL.md | 2 +- src/stream-parser.ts | 8 ++ src/turn-controller.ts | 53 ++++++++++--- test/result-fallback-sleep.test.ts | 123 +++++++++++++++++++++++------ 7 files changed, 189 insertions(+), 47 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 35c7d86..7bf3d93 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -75,7 +75,7 @@ changing, reverting or "simplifying" a rule. - **An abort that lands while a turn is being PREPARED must stop it, and the only thing that can see it is a watch created before the prologue's first await** (`watchTurnAbort`, `src/turn-abort.ts`): `addEventListener("abort")` on a signal that already aborted never fires, so the stream's own handler, which cannot exist until the prologue has finished, missed every stop in that window and the turn spawned, wrote and billed anyway (measured: a turn alive at 5,874 ms against a 5,000 ms signal). The handler is registered through `onAbort` in the **synchronous** part of `start()` now, never inside `setup()`, and `TurnState.cliAskedForWork` (set at exactly two places, the envelope write and the top of the tool-result branch) selects a new FIRST branch in front of the existing ones: close the stream, discard a proxy MCP server this turn created but never handed to a child, send **no** `interrupt` (a reused process's last turn is not this doStream's to stop) and leave an earlier step's pending proxy calls untouched, so #g26 and #g82 still own how they end. Three prologue checks, plus `stoppedBeforeWork()` on entry to `setup()`, at both spawn sites and after `interruptTurn`. **The raced `detectCliVersion` is left running on purpose**, because its answer is cached process-wide and cancelling it would be #g181 again; only the MCP connect wait takes the signal (`getRuntimeMcpStatus({ signal })`), because its poll loop is ours. `test/prologue-abort.test.ts`. (h #g182) - **A proxy deadline must not count the operator's time on a permission prompt.** Both timers go through `armProxyDeadline` and its `ProxyDeadlineGuard`; `isProxyCallStillServed` keeps a call only when `emitted` **and** the session reads `busy`, rechecking every `PROXY_DEADLINE_RECHECK_MS`. No guard, a throwing guard or `unknown` end it as before. `test/broker.test.ts`. (h #g27) **Live on opencode 2.0.22 with a real prompt in the way (h #g219)**: with the host config asking for `write`/`edit`, a proxied `write` was queued, the step drained, opencode raised a permission request, the call sat parked for the twelve seconds the operator took, and `POST /api/session/{id}/permission/{requestID}/reply {"decision":"once"}` resolved it in the same step (`resolved pending proxy call`) and the file was written. Every V2 probe before this ran with `--auto`, so the prompt path had never been exercised there. **Before (h #g253) the guard itself could never keep a call on V2**: its `busy` read had no route there, and `unknown` ends the call at its deadline. It reads the event-fed run state now, and live on 2.0.31 a proxied `write` with a 5-second deadline waited out a 15-second permission hold (`proxy call past its deadline, but opencode is still serving it; waiting`) and was written, where v0.58.0 timed it out twice and Claude told the operator the tool kept failing. `test/v2-session-events.test.ts`. - **Abort sends the CLI an `interrupt` control request** (`interruptTurn`), or the turn runs on and bills. `noteTurnStarted` marks in flight at every stdin write asking for work, and the terminal `result` clears it inside the `rl` handler, **never** a permanent `lineEmitter` listener. `test/session-manager.test.ts`. (h #g59) **Live end to end on Claude Code 2.1.288 + opencode 1.18.35 (h #g219)**: `POST /session/{id}/abort` mid-reply logged `abort signal received mid-turn, starting grace period`, the CLI answered 21 ms later with a `result` of `error_during_execution` carrying `costUsd: 0` and `outputTokens: 0`, `interrupt sent for aborted turn {idle: true}` followed, and **the CLI's own transcript recorded a `[Request interrupted by user]` user record** right after the truncated assistant record (`stop_reason: null`). The next turn **reused the same process and the same Claude session id** and answered normally, so the interrupt ends the turn without ending the conversation. -- **The wire-inactivity watchdog counts wall-clock time, sleep included, so a late fire re-arms and a closing fire interrupts the CLI** (`startResultFallback`, `RESULT_FALLBACK_LATE_SLACK_MS` 5 s, h #g316). Measured on 2026-11-14 from a subagent's own transcript and `pmset -g log`: the stream was still delivering thinking at 20:09:42Z, the Mac slept 20:10:23Z to 20:20:56Z with a dark wake at 20:15:28Z, and the 60 s timer fired at 20:15:31Z, 3 s into the dark wake, with at most 41 s of awake time behind it, so ten minutes of sleep read as ten minutes of a silent CLI. A fire more than the slack past its deadline means this process was not running (a sleep, or an event-loop stall with the CLI's output possibly unread in the pipe), so it waits a fresh full delay; the fire that does close the turn sends `interruptTurn`, exactly as an abort does (h #g59), because that CLI retried after the wake and ran on unattached for 28 minutes, its proxied calls each waiting out their 10-minute deadline. A proxied call queued with no stream attached is deliberately NOT rejected at once: that is the late-result recovery path (h #g82, h #g119), and the interrupt removes the cause. The start watchdog has the same clock and is unchanged (unmeasured). `test/result-fallback-sleep.test.ts` fakes the sleep through `_setResultFallbackClock`, never by blocking the loop. +- **The wire-inactivity watchdog counts wall-clock time, sleep included, so a late fire re-arms and a closing fire interrupts the CLI** (`startResultFallback`, `RESULT_FALLBACK_LATE_SLACK_MS` 5 s, h #g316). Measured on 2026-11-14 from a subagent's own transcript and `pmset -g log`: the stream was still delivering thinking at 20:09:42Z, the Mac slept 20:10:23Z to 20:20:56Z with a dark wake at 20:15:28Z, and the 60 s timer fired at 20:15:31Z, 3 s into the dark wake, with at most 41 s of awake time behind it, so ten minutes of sleep read as ten minutes of a silent CLI. A fire more than the slack past its deadline means this process was not running (a sleep, or an event-loop stall with the CLI's output possibly unread in the pipe), so it waits a fresh full delay; the fire that does close the turn sends `interruptTurn`, exactly as an abort does (h #g59), because that CLI retried after the wake and ran on unattached for 28 minutes, its proxied calls each waiting out their 10-minute deadline. A proxied call queued with no stream attached is deliberately NOT rejected at once: that is the late-result recovery path (h #g82, h #g119), and the interrupt removes the cause. **The start watchdog gets the same late-fire rule** (a late fire re-arms instead of respawning), **and both watchdogs wait out a backoff the CLI announces** (`noteAnnouncedRetry`): measured on 2.1.322 against a local server answering 529 with `retry-after: 4`, the `system`/`api_retry` frame arrives 60 ms after the failed request with `retry_delay_ms: 4000` and the next request follows 4.0 s later, so whichever watchdog is armed waits that much longer (capped at 30 minutes; the CLI's own `max_retries` bounds how often). Without it a backoff longer than the window closed the turn (and, with the interrupt, would now stop the retrying CLI) or respawned a child that was working as designed. `api_retry` frames do not count as model progress. `test/result-fallback-sleep.test.ts` fakes the sleep through `_setResultFallbackClock`, never by blocking the loop, and jumps the clock only once the fake CLI holds the envelope, which is after the arm. - **`idleProcessTimeoutMs` is off unless set** (`resolveIdleProcessTimeoutMs`, so unset and `0` both arm nothing). Unref'd, cancelled by every get/set/detach/spawn/exit, deleting only the same process object; a process found `turnInFlight` is re-armed, never killed. `test/session-manager.test.ts`. (h #g60) - **The child's stdin needs its own `error` listener, and `proc.on("error")` is not it**: an `error` on a listener-less stream throws inside **opencode's** process. `spawnClaudeProcess` attaches one, logs at WARN, calls `settleTurn`, and deliberately does not end the turn. `test/session-manager.test.ts`. (h #g61) - **LRU eviction must never take a process that is mid-turn**: `evictIfNeeded` walks insertion order for the first with `turnInFlight !== true`, and when all are busy evicts **nothing** and warns. Do not "restore" the one-liner. Cap is **16**, and idle eviction stays off unless `idleProcessTimeoutMs` is set, so the cap is the only bound on a default install. `test/session-manager.test.ts`. (h #g62, #g179) @@ -513,7 +513,7 @@ Opt-in. `spawnInteractiveProcess` returns an `ActiveProcess`-shaped shim so doSt - The usage a finish reports (`lastCallContextUsage`: the last call's context, not the turn sum, at the main and tool-call finishes, the synthetic-frame guard, zeros at a mid-turn proxied boundary): `test/context-usage.test.ts`. - CLI stream-event parsers and their dedup (`parseRateLimitEvent`, `describeRateLimit`, `parseSystemInit`, `apiKeySourceWarning`, `parseCompactBoundary`, `describeResultFailure`, `parseMcpServerErrors`, `describeMcpServerError`, `snapshotMcpServerErrors`, `parseUnrecognizedModel`, `reportUnrecognizedModel`, `describePluginLoadFailure`, `snapshotPluginLoadFailures`, `parseRefusalFallback`, `formatRefusalFallbackNote`, `reportRefusalFallback`, a between-turns compaction's note): `test/cli-events.test.ts`; the same events through a fake CLI and a real `doStream`, including that a skipped MCP entry warns and changes nothing else about the turn, and a 529 the CLI gave up on (`success` with `is_error`, from the `` reply or from the result alone) ending as an error with its sentence shown once and no footer: `test/cli-events-stream.test.ts`. - The wire-inactivity watchdog's visible note (`formatStreamTimeoutNote`, `CLAUDE_CODE_RESULT_FALLBACK_MS`): `test/result-fallback.test.ts`. -- The same watchdog after a sleep (a fire ten minutes late re-arming and the CLI answering inside the fresh delay, and a closing fire sending the CLI one `interrupt`; POSIX only): `test/result-fallback-sleep.test.ts`. +- Both watchdogs after a sleep and across a retry the CLI announces (a fire ten minutes late re-arming and the CLI answering inside the fresh delay, a closing fire sending the CLI one `interrupt`, an `api_retry` frame holding the inactivity watchdog and the start watchdog for its `retry_delay_ms`, and a late start-watchdog fire not respawning; POSIX only): `test/result-fallback-sleep.test.ts`. - The silent-turn note (`isSilentTurn`, `formatSilentTurnNote`) and every turn it must stay out of: `test/silent-turn.test.ts`. - A message a `UserPromptSubmit` hook ended (`parsePromptBlock` over 2.1.322's and 2.1.293's frames and the frames that are not a block, the reason's fold and cap, `formatPromptBlockedNote`'s shapes; then a fake CLI driving real `doStream` turns: this turn's own message failing as `blocked_by_hook` with the note and no footer, the session kept and the next message bare, a blocked replay dropping the child and session id and the next message replaying again, the legacy frame, a steered message blocked inside a turn that went on, a blocked compaction ending on its error part with no text, and a secret-like string in the prompt reaching neither the reply nor the log; the fake-CLI half is POSIX only): `test/prompt-blocked.test.ts`. - `/claude-code-doctor` (report formatter, command-registration guard, `checkProxyAuth`, transcript strip, `describeSessionKey`, the skipped-MCP, not-loaded-plugin and background-subagent sections, and the plan-usage opt-in with `wantsPlanUsage`, `parsePlanUsage` and `fetchPlanUsage`): `test/doctor.test.ts`. diff --git a/TODO.md b/TODO.md index 1304bb3..5f2cf2a 100644 --- a/TODO.md +++ b/TODO.md @@ -84,8 +84,9 @@ anything on the session-key theory. - 2026-11-14 (evening), the watchdog that closed a turn during a sleep: FIXED on `fix/blocked-prompt` (h #g316). It counts wall-clock time, sleep included, so a fire well past its deadline now waits - again, and a fire that closes the turn interrupts the CLI. Left alone on purpose: a proxied call - queued with no stream attached (late-result recovery) and the start watchdog (unmeasured). + again, and a fire that closes the turn interrupts the CLI. The start watchdog follows the same + late-fire rule, and both watchdogs wait out the backoff an `api_retry` frame announces. Left alone + on purpose: a proxied call queued with no stream attached (the late-result recovery path). - 2026-11-14, found while fixing h #g312, not fixed (not in that PR's scope): dcp's `compact` message reference (`\n@1044@`) is not stripped in two places that strip its XML form. @@ -192,14 +193,16 @@ raised, so they survive context compaction; removed when answered, done or dropp - 2026-11-14: agent-guard's prompt guard blocks any replay that quotes a secret-like value (the plugin side is fixed, h #g314, and never sets the guard's variable itself): keep it blocking, or set `AGENT_GUARD_PROMPT_GUARD_MODE` for opencode's environment? Your config, not the plugin's. + Deferred by the maintainer, 2026-11-15. - 2026-11-14: watchdog follow-up, offered by an earlier turn of session `ses_e324dbf7bffeRHQIz10AIxm7dT`: "should the plugin wait a little longer after the CLI reports an - API error before it closes the turn?" The sleep case is fixed (h #g316: a late fire waits again, - a closing fire interrupts the CLI). The API-error case itself has no evidence on record (its - reasoning went with that session's history): keep it open until it happens again, or drop? + API error before it closes the turn?" The sleep case is fixed, and both watchdogs now wait out the + backoff the CLI announces in its `api_retry` frame (h #g316). Deferred (2026-11-15): whether to wait + any longer than the CLI announces; the original case has no evidence on record. - 2026-11-10: what to build next from Future Features (doctor warnings for setups that fail silently, model aliases such as `opus`, a `task_send` to steer a background subagent, continuing a terminal `claude` session in opencode): pick any, or hold. + Deferred again by the maintainer, 2026-11-15. - 2026-10-08: subagent startup (~25 s). Maintainer: "do 1 but not fully just comment it out, 2 pin it, 3 lets try 1 and 2 and see if 3 is needed". Done: `slack` parked under `_parkedMcpServers` in both Claude accounts' `.claude.json` (pinned 1.3.0), opencode's slack pinned to 1.3.0 (backups `*.bak-slack-20261008-214042`). @@ -221,6 +224,7 @@ raised, so they survive context compaction; removed when answered, done or dropp Verification still owed, copied from the vault's `Future Features.md` "Next up" on 2026-10-24 (maintainer: "do the most recommended for all in 1 go"), because they are checks, not features. + Deferred again by the maintainer, 2026-11-15. - Around 2026-11-08: review the progress estimate again, once the busy keys have 30+ samples. The 2026-10-25 review (one week, read-only) found a forward test of 44 to 45% in band against a 50% target, estimates about 13% long on the median, a typical miss of x2.2, worst on diff --git a/docs/agents-history.md b/docs/agents-history.md index 752b56f..beda9db 100644 --- a/docs/agents-history.md +++ b/docs/agents-history.md @@ -13021,11 +13021,31 @@ What changed in `startResultFallback`: path already interrupts. - Not changed: a proxied call that arrives with no stream attached still waits for the next turn or its deadline, because that is the late-result recovery path (h #g82, h #g119), and with the - interrupt the cause is gone. The start watchdog shares the clock and is unchanged; nothing - measured shows it firing across a sleep. + interrupt the cause is gone. + +Added before the release, at the maintainer's request to cover what the first version left out, +and because the interrupt made one edge worse: a watchdog that fires while the CLI waits out its +own retry backoff used to leave the CLI to carry on, and would now stop it. + +- Measured on 2.1.322 against a local server answering every request with 529 and + `retry-after: 4` (`--bare`, a fake key, `CLAUDE_CODE_MAX_RETRIES=2`): the `system`/`api_retry` + frame arrived 60 ms after the failed request with `retry_delay_ms: 4000`, and the next request + followed 4.0 s later, twice. So the frame announces the wait before it starts. +- `noteAnnouncedRetry` adds that wait to whichever watchdog is armed (capped at 30 minutes; the + CLI's `max_retries` bounds how often). Before, a backoff longer than the 60 s window closed the + turn, and before any content one longer than the start watchdog's window respawned a child that + was retrying as designed: `api_retry` frames do not count as model progress. +- The start watchdog shares the wall clock, so it gets the same late-fire rule: a late fire + re-arms instead of respawning. + +Two of the new tests were wrong before they were right, and both lessons are about the harness: +the fake counted the plugin's own `claude --help` probe as a spawn, and a clock jump on a timer +started with the test landed before the watchdog was armed (the plugin's probes and spawn take +longer than half a second), so the jump now waits until the fake holds the envelope. Tests: `test/result-fallback-sleep.test.ts` (POSIX). The sleep is faked with -`_setResultFallbackClock`, which jumps ten minutes when the first text arrives: the fire at 2 s -re-arms and the CLI's answer at 3 s lands (with the re-arm switched off the turn closes as a -stream timeout). A CLI that never finishes gets exactly one `interrupt` control request after the -close (with the interrupt switched off, none). +`_setResultFallbackClock`, which jumps ten minutes: the inactivity watchdog's fire re-arms and the +CLI's answer lands; a CLI that never finishes gets exactly one `interrupt` after the close; an +announced 3 s retry holds the inactivity watchdog and, before any content, the start watchdog, with +no respawn; a late start-watchdog fire re-arms with no respawn. Each fails with its change switched +off. diff --git a/skills/claude-code-plugin/SKILL.md b/skills/claude-code-plugin/SKILL.md index d1f44e1..4235607 100644 --- a/skills/claude-code-plugin/SKILL.md +++ b/skills/claude-code-plugin/SKILL.md @@ -262,7 +262,7 @@ their secret values. Arbitrary MCP `{env:NAME}` placeholders are outside this li | `CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS` | Set to `0` for the interactive TUI unless the operator set it, so a proxied call past 120 s stays in the foreground as on headless. `CLAUDE_CODE_DISABLE_MCP_TASK_BACKGROUND` is not set: it covers MCP-task servers only, which the proxy never is, and at `0` the CLI asks no server for a task. | | `CLAUDE_CODE_START_WATCHDOG_MS` | Positive integer ms before a headless start or proxy-result continuation is considered silent; default 90000 for missing/invalid/nonpositive values. First expiry respawns, second errors. Bookkeeping-only output is not progress. A process that has not sent its first `system`/`init` yet gets at least its `MCP_TIMEOUT` plus 30 s (150 s by default), since the CLI sends `init` only after its MCP servers connect or time out; the log's `beforeInit` says which delay fired. Keep within timer range; do not lower for routine config checks. | | `CLAUDE_CODE_LIVE_SWITCH_TIMEOUT_MS` | Positive integer ms one `set_model` or `apply_flag_settings` may take before a live model or effort switch gives up, stops the child and falls back to the respawn; default 10000 for missing/invalid/nonpositive values. Measured answers: 0.5 to 0.7 s and 20 to 140 ms. | -| `CLAUDE_CODE_RESULT_FALLBACK_MS` | Positive integer ms of stdout silence, after the CLI has produced output, before the turn is closed with no `result`; default 60000 for missing/invalid/nonpositive values. The close is announced in the reply as a `▌ **stream timeout:**` note, which is stripped from any rebuilt transcript, and interrupts the CLI's turn so it does not run on unattended. An aborted turn gets no note. A fire more than 5 s past its deadline (the machine slept, or the event loop stalled) waits a fresh full delay instead, because that silence was never observed (h #g316). | +| `CLAUDE_CODE_RESULT_FALLBACK_MS` | Positive integer ms of stdout silence, after the CLI has produced output, before the turn is closed with no `result`; default 60000 for missing/invalid/nonpositive values. The close is announced in the reply as a `▌ **stream timeout:**` note, which is stripped from any rebuilt transcript, and interrupts the CLI's turn so it does not run on unattended. An aborted turn gets no note. A fire more than 5 s past its deadline (the machine slept, or the event loop stalled) waits a fresh full delay instead, because that silence was never observed, and an `api_retry` frame adds the `retry_delay_ms` the CLI announces (h #g316). The start watchdog (`CLAUDE_CODE_START_WATCHDOG_MS`) follows the same two rules. | | `OPENCODE_CLAUDE_CODE_LOG_FILE` | Overrides `logging.file`: trimmed `0/false/no/off` are false; any other nonempty value is true; empty falls back to config. Prefer `1` or `0`. | | `OPENCODE_CLAUDE_CODE_LOG_DIR` | Overrides `logging.dir`. | | `OPENCODE_CLAUDE_CODE_MODEL_PROBE` | `0` or `false` stops the background model probe for this environment (the `npm test` script sets it); the stored answer is still registered. `cliModelCatalog: false` is the config switch and also ignores the stored answer. | diff --git a/src/stream-parser.ts b/src/stream-parser.ts index 46d33da..5627b77 100644 --- a/src/stream-parser.ts +++ b/src/stream-parser.ts @@ -75,6 +75,7 @@ import { deliverPendingCompletions, finishWithQuestionCall, finishAwaitingPlanApproval, + noteAnnouncedRetry, noteProxyActivity, noteReasoning, noteStartWatchdogInit, @@ -352,6 +353,13 @@ export function createLineHandler( reportHookEvent(msg) } + // The CLI failed an API attempt and says how long it will wait before + // the next one; neither watchdog may take that backoff for silence + // (h #g316). + if (msg.type === "system" && msg.subtype === "api_retry") { + noteAnnouncedRetry(state, msg) + } + // A `UserPromptSubmit` hook (or a Claude plugin's code module) ended a // message before the model saw it. This turn's own message then ends the // turn on a `success` result with no API call, which read as an empty diff --git a/src/turn-controller.ts b/src/turn-controller.ts index ef30191..d4ff9a1 100644 --- a/src/turn-controller.ts +++ b/src/turn-controller.ts @@ -299,21 +299,56 @@ export function startWatchdogDelayMs( : configuredMs } -export function armStartWatchdog(state: TurnState): void { +/** + * `extraMs` is a wait the CLI announced itself (an `api_retry` frame's + * `retry_delay_ms`), added so a CLI that is only backing off before its next + * attempt is not taken for a silent one. A late fire re-arms, as the + * inactivity watchdog's does: the clock counts sleep (h #g316). + */ +export function armStartWatchdog(state: TurnState, extraMs = 0): void { clearStartWatchdog(state) if (state.controllerClosed) return const ap = state.activeProcess // The interactive shim never respawns from here (see the fire handler), so // it keeps the configured delay. state.startWatchdogBeforeInit = !ap?.interactiveControl && ap?.initSeen !== true - state.startWatchdogArmedMs = startWatchdogDelayMs( - state.startWatchdogMs, - state.startWatchdogBeforeInit, - ) - state.startWatchdog = setTimeout( - () => onStartWatchdogFire(state), - state.startWatchdogArmedMs, - ) + state.startWatchdogArmedMs = + startWatchdogDelayMs(state.startWatchdogMs, state.startWatchdogBeforeInit) + extraMs + const armedAt = watchdogNow() + const delayMs = state.startWatchdogArmedMs + state.startWatchdog = setTimeout(() => { + const lateMs = watchdogNow() - armedAt - delayMs + if (lateMs > resultFallbackLateSlackMs && !state.controllerClosed) { + log.info("start watchdog fired late; the process was not running, so it waits again", { + delayMs, + lateMs, + }) + armStartWatchdog(state) + return + } + onStartWatchdogFire(state) + }, delayMs) +} + +/** Longest wait an `api_retry` frame may add to a watchdog (h #g316). */ +const MAX_ANNOUNCED_RETRY_WAIT_MS = 30 * 60_000 + +/** + * The CLI said it will wait before its next attempt: measured on 2.1.322 + * against a server answering 529, the `system`/`api_retry` frame arrives as the + * attempt fails, with `retry_delay_ms` equal to the gap before the next request + * (`retry-after: 4` gave 4000 and a request 4.0 s later). Whichever watchdog is + * armed waits that much longer, so a backoff longer than its window neither + * closes the turn (and, since h #g316, interrupts the CLI) nor respawns a child + * that is working as designed. The CLI's own `max_retries` bounds how often. + */ +export function noteAnnouncedRetry(state: TurnState, msg: ClaudeStreamMessage): void { + const announced = (msg as { retry_delay_ms?: unknown }).retry_delay_ms + if (typeof announced !== "number" || !Number.isFinite(announced) || announced <= 0) return + const waitMs = Math.min(announced, MAX_ANNOUNCED_RETRY_WAIT_MS) + log.info("claude code is retrying the API request; the watchdogs wait for it", { waitMs }) + if (state.resultFallbackTimer) startResultFallback(state, state.resultFallbackMs + waitMs) + if (state.startWatchdog) armStartWatchdog(state, waitMs) } /** diff --git a/test/result-fallback-sleep.test.ts b/test/result-fallback-sleep.test.ts index f9e8ef5..3a94f42 100644 --- a/test/result-fallback-sleep.test.ts +++ b/test/result-fallback-sleep.test.ts @@ -33,15 +33,23 @@ afterEach(() => { _setResultFallbackLateSlackMs(null) }) +type Step = + | { text: string } + | { retry: number } + | { wait: number } + | { result: true } + /** - * A `claude` that writes half an answer, goes silent, and finishes after - * `finishAfterMs` (or never, for `null`). It records every stdin line, so a - * test can see the interrupt the plugin sends. + * A `claude` that plays `steps` on its first message: text deltas, `api_retry` + * frames shaped as 2.1.322 writes them, waits, and a `result`. A script with + * no `result` goes silent for good. It records every stdin line and every + * spawn, so a test can see an interrupt or a respawn. */ -function createFakeCli(finishAfterMs: number | null) { +function createFakeCli(steps: Step[]) { const cwd = mkdtempSync(join(tmpdir(), "opencode-result-fallback-sleep-")) const cliPath = join(cwd, "fake-claude.cjs") const record = join(cwd, "stdin.jsonl") + const spawns = join(cwd, "spawns.txt") writeFileSync( cliPath, `#!${process.execPath} @@ -51,36 +59,32 @@ if (process.argv.includes("--version")) { process.stdout.write("2.1.322\\n") process.exit(0) } +if (process.argv.includes("--help")) process.exit(0) +fs.appendFileSync(${JSON.stringify(spawns)}, process.pid + "\\n") const emit = (message) => process.stdout.write(JSON.stringify({ session_id: "fake-session", ...message }) + "\\n") -const text = (body) => emit({ type: "stream_event", event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: body } } }) +emit({ type: "system", subtype: "init", tools: ["Read"] }) +const STEPS = ${JSON.stringify(steps)} let answered = false -readline.createInterface({ input: process.stdin }).on("line", (line) => { +readline.createInterface({ input: process.stdin }).on("line", async (line) => { fs.appendFileSync(${JSON.stringify(record)}, line + "\\n") if (answered) return answered = true - emit({ type: "system", subtype: "init", tools: ["Read"] }) - text("half an answer") - const after = ${JSON.stringify(finishAfterMs)} - if (after === null) return - setTimeout(() => { - text(" and the rest") - emit({ type: "result", subtype: "success", is_error: false, num_turns: 1, result: "done", - usage: { input_tokens: 1, output_tokens: 1 } }) - }, after) + for (const step of STEPS) { + if ("text" in step) emit({ type: "stream_event", event: { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: step.text } } }) + if ("retry" in step) emit({ type: "system", subtype: "api_retry", attempt: 1, max_retries: 10, retry_delay_ms: step.retry, error_status: 529, error: "overloaded" }) + if ("wait" in step) await new Promise((resolve) => setTimeout(resolve, step.wait)) + if ("result" in step) emit({ type: "result", subtype: "success", is_error: false, num_turns: 1, result: "done", usage: { input_tokens: 1, output_tokens: 1 } }) + } }) `, { mode: 0o755 }, ) + const read = (file: string) => (existsSync(file) ? readFileSync(file, "utf8").split("\n").filter(Boolean) : []) return { cwd, cliPath, - stdinLines: (): any[] => - existsSync(record) - ? readFileSync(record, "utf8") - .split("\n") - .filter(Boolean) - .map((line) => JSON.parse(line)) - : [], + stdinLines: (): any[] => read(record).map((line) => JSON.parse(line)), + spawnCount: (): number => read(spawns).length, } } @@ -88,11 +92,14 @@ async function runTurn( fake: ReturnType, fallbackMs: number, onFirstText?: () => void, + startWatchdogMs?: number, ): Promise<{ parts: any[]; key: string }> { const modelId = "claude-test-result-fallback-sleep" const key = sessionKey(fake.cwd, `${modelId}::tools::default::context=["claude-code",null]`) const previous = process.env.CLAUDE_CODE_RESULT_FALLBACK_MS + const previousStart = process.env.CLAUDE_CODE_START_WATCHDOG_MS process.env.CLAUDE_CODE_RESULT_FALLBACK_MS = String(fallbackMs) + if (startWatchdogMs !== undefined) process.env.CLAUDE_CODE_START_WATCHDOG_MS = String(startWatchdogMs) try { const model = createClaudeCode({ cliPath: fake.cliPath, @@ -122,6 +129,8 @@ async function runTurn( } finally { if (previous === undefined) delete process.env.CLAUDE_CODE_RESULT_FALLBACK_MS else process.env.CLAUDE_CODE_RESULT_FALLBACK_MS = previous + if (previousStart === undefined) delete process.env.CLAUDE_CODE_START_WATCHDOG_MS + else process.env.CLAUDE_CODE_START_WATCHDOG_MS = previousStart } } @@ -140,7 +149,7 @@ test("a watchdog that fires after a sleep waits again instead of closing the tur // Due at 2 s; the CLI finishes at 3 s. The clock jumps ten minutes the // moment the first text arrives, as a sleep makes it, so the fire at 2 s // looks ten minutes late and must wait a fresh 2 s, which the CLI beats. - const fake = createFakeCli(3_000) + const fake = createFakeCli([{ text: "half an answer" }, { wait: 3_000 }, { text: " and the rest" }, { result: true }]) let key = "" try { _setResultFallbackLateSlackMs(500) @@ -165,7 +174,7 @@ test("a watchdog that fires after a sleep waits again instead of closing the tur }) test("a watchdog that closes the turn interrupts the CLI it stopped listening to", POSIX, async () => { - const fake = createFakeCli(null) + const fake = createFakeCli([{ text: "half an answer" }]) let key = "" try { const turn = await runTurn(fake, 500) @@ -185,3 +194,69 @@ test("a watchdog that closes the turn interrupts the CLI it stopped listening to rmSync(fake.cwd, { recursive: true, force: true }) } }) + +test("a retry the CLI announces holds the inactivity watchdog for that long", POSIX, async () => { + // Due 1.5 s after the last line; the CLI says it will wait 3 s and answers + // at 3.5 s. Without the announced wait the turn closes at 1.5 s. + const fake = createFakeCli([ + { text: "half an answer" }, + { retry: 3_000 }, + { wait: 3_500 }, + { text: " and the rest" }, + { result: true }, + ]) + let key = "" + try { + const turn = await runTurn(fake, 1_500) + key = turn.key + const said = body(turn.parts) + assert.ok(!said.includes(STREAM_TIMEOUT_MARKER), said) + assert.match(said, /half an answer and the rest/) + } finally { + if (key) deleteActiveProcess(key) + rmSync(fake.cwd, { recursive: true, force: true }) + } +}) + +test("a retry the CLI announces holds the start watchdog too, so nothing is respawned", POSIX, async () => { + // No content yet, so only the start watchdog is armed: 1.5 s after the + // envelope. The CLI announces a 3 s wait and answers at 3.5 s. Without the + // announced wait the child is respawned at 1.5 s. + const fake = createFakeCli([{ retry: 3_000 }, { wait: 3_500 }, { text: "the answer" }, { result: true }]) + let key = "" + try { + const turn = await runTurn(fake, 60_000, undefined, 1_500) + key = turn.key + assert.match(body(turn.parts), /the answer/) + assert.equal(fake.spawnCount(), 1, "the child was never respawned") + } finally { + if (key) deleteActiveProcess(key) + rmSync(fake.cwd, { recursive: true, force: true }) + } +}) + +test("a start watchdog that fires after a sleep waits again instead of respawning", POSIX, async () => { + // Due 2 s after the envelope; the CLI answers 3 s after it. The clock jumps + // ten minutes once the CLI has the envelope (so after the watchdog was + // armed), as a sleep makes it, so the fire at 2 s looks late and waits a + // fresh 2 s, to 4 s, which the answer beats by a second. + const fake = createFakeCli([{ wait: 3_000 }, { text: "the answer" }, { result: true }]) + let key = "" + const jump = setInterval(() => { + if (fake.stdinLines().length === 0) return + clearInterval(jump) + const offset = 10 * 60_000 + _setResultFallbackClock(() => Date.now() + offset) + }, 20) + try { + _setResultFallbackLateSlackMs(500) + const turn = await runTurn(fake, 60_000, undefined, 2_000) + key = turn.key + assert.match(body(turn.parts), /the answer/) + assert.equal(fake.spawnCount(), 1, "the child was never respawned") + } finally { + clearInterval(jump) + if (key) deleteActiveProcess(key) + rmSync(fake.cwd, { recursive: true, force: true }) + } +}) From eb00f1cb7c5b7bb5f0354b7c30d9d2a1540d1c43 Mon Sep 17 00:00:00 2001 From: Khalil Gharbaoui Date: Sun, 15 Nov 2026 02:39:30 +0100 Subject: [PATCH 6/6] Read a blocked prompt on the interactive transport The TUI records a prompt a UserPromptSubmit hook ends as a system/informational record with promptSubmitEnding and nothing after it, so a PTY turn waited out its whole timeout, and it hands the text back to its input box, where the next paste joined it. End the turn on that record, clear the box with one Ctrl+C before the next paste, and hand the parser headless's frame and result so the note, the error finish and the blocked-replay drop are shared. Measured under a PTY on Claude Code 2.1.322 (h #g314). --- AGENTS.md | 4 +- TODO.md | 18 ++- docs/agents-history.md | 38 ++++- docs/guides/interactive-transport.md | 1 + skills/claude-code-plugin/SKILL.md | 3 + src/claude-session-bun.ts | 49 ++++++- src/claude-session-wrapper.ts | 41 ++++++ test/interactive-pty.test.ts | 212 ++++++++++++++++++++++++++- 8 files changed, 353 insertions(+), 13 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7bf3d93..9f13429 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -220,7 +220,7 @@ changing, reverting or "simplifying" a rule. - The one exception is `isTruncationStopReason` (`max_tokens`, plus the `max_output_tokens` alias), authoritative in the other direction and bounded by the attempt and elapsed rails, because a truncated prose answer dies at the `no-activity` gate. - The nudge itself is `runAutoContinue` in `src/turn-controller.ts`, and it owns both log lines: the nudge and the one that says the nudging stopped. **A compaction turn must never be nudged**: `AUTO_CONTINUE_PROMPT` is the inverse of a `/compact` turn's job and the text would land in the stored summary. `autoContinueEnabledFor(compactionMode, configured)` gates it; add a compaction case to any future change here. - **A turn that ends with no text and no tool call gets the `▌ **no reply:**` note and deliberately no nudge**: measured zero silent turns in the whole retained `plugin.log` pair, and a nudge would need a second exception to the `stop_reason` guard. `isSilentTurn`, fired in `completeResult` after the failover return. `test/silent-turn.test.ts`. (h #g157) -- **A message a `UserPromptSubmit` hook ended is a failed turn with a `▌ **prompt blocked:**` note, never an empty reply, and a blocked REPLAY drops its empty session** (`parsePromptBlock`, `formatPromptBlockedNote`, `TurnState.promptBlock` / `ownPromptBlocked`, h #g314). Measured on 2.1.314 and 2.1.322: one `system`/`informational` frame with `prompt_submit_outcome: {kind, prompt_kept, reason}` and `prevent_continuation: true`, then a `success` result with `num_turns: 0` and no API call; 2.1.293 sends the frame with no outcome and a `content` starting `UserPromptSubmit operation blocked by hook`, which is read as `blocked_by_hook`. **The frame's `content` and the result's `result` repeat the whole original prompt**, which is the text a guard refused, so only the outcome and `content`'s first words are read: the note quotes the hook's reason (one line, capped at 300), the WARN carries `kind`, `promptKept` and `reasonChars`, and nothing logs either text. `num_turns === 0` is what makes it this turn's own message: the turn finishes `{unified:"error", raw:}`, no `no reply` note, no `turnStats` footer, no checkpoint. A message steered into a running turn gets the same frame mid-turn while the turn goes on (`num_turns: 2`, measured), and gets the note only. **When the blocked envelope was a replay into a session with none of the conversation (`includeHistoryContext`), `completeResult` kills the child and calls `deleteClaudeSessionId` before recording anything**, so the next message replays again instead of going to an empty session: that is what lost a session's history after a model switch on 2026-11-14 while the `no reply` note said nothing failed. The hook judges the next replay the same way, which is deliberate: relaxing a guard is the operator's call, and the plugin never sets a hook's own bypass variable. Any other blocked message keeps the session and IS recorded as asked, because re-sending it would only be blocked again. A blocked compaction writes no text and ends on its error part (h #g214). The interactive transport does not read the TUI's `promptSubmitEnding` record yet (unmeasured). `test/prompt-blocked.test.ts`. +- **A message a `UserPromptSubmit` hook ended is a failed turn with a `▌ **prompt blocked:**` note, never an empty reply, and a blocked REPLAY drops its empty session** (`parsePromptBlock`, `formatPromptBlockedNote`, `TurnState.promptBlock` / `ownPromptBlocked`, h #g314). Measured on 2.1.314 and 2.1.322: one `system`/`informational` frame with `prompt_submit_outcome: {kind, prompt_kept, reason}` and `prevent_continuation: true`, then a `success` result with `num_turns: 0` and no API call; 2.1.293 sends the frame with no outcome and a `content` starting `UserPromptSubmit operation blocked by hook`, which is read as `blocked_by_hook`. **The frame's `content` and the result's `result` repeat the whole original prompt**, which is the text a guard refused, so only the outcome and `content`'s first words are read: the note quotes the hook's reason (one line, capped at 300), the WARN carries `kind`, `promptKept` and `reasonChars`, and nothing logs either text. `num_turns === 0` is what makes it this turn's own message: the turn finishes `{unified:"error", raw:}`, no `no reply` note, no `turnStats` footer, no checkpoint. A message steered into a running turn gets the same frame mid-turn while the turn goes on (`num_turns: 2`, measured), and gets the note only. **When the blocked envelope was a replay into a session with none of the conversation (`includeHistoryContext`), `completeResult` kills the child and calls `deleteClaudeSessionId` before recording anything**, so the next message replays again instead of going to an empty session: that is what lost a session's history after a model switch on 2026-11-14 while the `no reply` note said nothing failed. The hook judges the next replay the same way, which is deliberate: relaxing a guard is the operator's call, and the plugin never sets a hook's own bypass variable. Any other blocked message keeps the session and IS recorded as asked, because re-sending it would only be blocked again. A blocked compaction writes no text and ends on its error part (h #g214). **On the interactive transport the same outcome is a transcript record with another spelling, and the TUI hands the dropped text back to its input box** (measured on 2.1.322 under a PTY): `system`/`informational` with `promptSubmitEnding: {ending: {kind, reason}, promptKept}` and no `user` or `assistant` record after it, so the turn waited out its whole timeout, and the next paste joined the handed-back text (a blocked replay's 40 lines rode into the next message, where the hook blocked it again). `isPromptEndingRecord` ends the turn as `blocked` when it precedes the turn's own `user` record, the next turn sends ONE Ctrl+C before its paste and never while a turn runs (measured: only the new message recorded, TUI up; Ctrl+U clears one line), `streamFrameFromRecord` renames it to `prompt_submit_outcome` and drops `content`, and `interactiveResultFrame` writes headless's `num_turns: 0` success, so the parser, the note and the replay drop are shared. `test/prompt-blocked.test.ts`, `test/interactive-pty.test.ts`. - Its snapshot is **stream-scoped, never the `SinceContinue` counters**, which reset on every nudge. `compactionMode`, `isError` and `enabled === false` each fail a case on their own; `sawQuestion` is redundant only while `content_block_start` counts `AskUserQuestion` as tool activity, so do not "tidy" it away. - **`turnStats` is off by default and must never fire on a compaction turn or a failed one** (summary corruption; the bill belongs with the error). Use the **turn totals** (`msg.usage`) so the line matches `total_cost_usd`, and pass `permission_denials` as **names and ids only**. `test/turn-stats.test.ts`. (h #g109) **The cost the footer prints is the turn's DELTA, not the CLI's total** (h #g257): a headless `total_cost_usd` is the Claude session's running total (h #g245), so until then every footer after a process's first printed the session's spend so far. `takeResultCost` (`src/budget-ledger.ts`) is read ONCE per `result` in the parser and shared with the budget ledger, because it moves the session's baseline; `footerCostUsd` leaves the cost out when there is no baseline AND the process was spawned with `--resume` (a restart's first turn, a fork), because `--resume` restores the running total and the figure may hold every earlier turn. The INFO line keeps the CLI's `costUsd` and adds `turnCostUsd`; `providerMetadata` keeps the CLI's total. Do not "fix" anything by summing totals: that counts every earlier turn again. - **A finish's usage is context occupancy to opencode, so its input side is the turn's LAST real API call, never `result.usage`**, which sums every call: a 14-call turn at 180K real context reported 2,050,806 cache read and opencode auto-compacted. Every finish reporting a result's usage goes through `lastCallContextUsage(state.lastCallUsage, …)`; `lastCallUsage` is the newest `assistant` frame's `message.usage` with non-zero input + cache (a `` frame never overwrites it), output stays the turn total, and `result.usage.iterations` is the last response's server-side field, not a per-call breakdown. `anthropic.cacheCreationInputTokens` must equal the reported cache write, because opencode falls back to it when the usage says 0. A tool-call finish with no `result` yet stays zeros, **and that is measured now, not a precaution** (h #g225): with real context reported there, opencode 1.18.35 and 2.0.22 both auto-compact in the middle of the turn while the CLI is parked in the proxied call, and the call is lost (1.x: rejected as orphaned, and the model tells the operator a permission was denied) or run twice (2.x: the step restarts on a fresh child). Do not "fill in" these zeros for a live context gauge. `turnStats` and `providerMetadata["claude-code"]` keep the turn totals. `test/context-usage.test.ts`. (h #g169) @@ -515,7 +515,7 @@ Opt-in. `spawnInteractiveProcess` returns an `ActiveProcess`-shaped shim so doSt - The wire-inactivity watchdog's visible note (`formatStreamTimeoutNote`, `CLAUDE_CODE_RESULT_FALLBACK_MS`): `test/result-fallback.test.ts`. - Both watchdogs after a sleep and across a retry the CLI announces (a fire ten minutes late re-arming and the CLI answering inside the fresh delay, a closing fire sending the CLI one `interrupt`, an `api_retry` frame holding the inactivity watchdog and the start watchdog for its `retry_delay_ms`, and a late start-watchdog fire not respawning; POSIX only): `test/result-fallback-sleep.test.ts`. - The silent-turn note (`isSilentTurn`, `formatSilentTurnNote`) and every turn it must stay out of: `test/silent-turn.test.ts`. -- A message a `UserPromptSubmit` hook ended (`parsePromptBlock` over 2.1.322's and 2.1.293's frames and the frames that are not a block, the reason's fold and cap, `formatPromptBlockedNote`'s shapes; then a fake CLI driving real `doStream` turns: this turn's own message failing as `blocked_by_hook` with the note and no footer, the session kept and the next message bare, a blocked replay dropping the child and session id and the next message replaying again, the legacy frame, a steered message blocked inside a turn that went on, a blocked compaction ending on its error part with no text, and a secret-like string in the prompt reaching neither the reply nor the log; the fake-CLI half is POSIX only): `test/prompt-blocked.test.ts`. +- A message a `UserPromptSubmit` hook ended (`parsePromptBlock` over 2.1.322's and 2.1.293's frames and the frames that are not a block, the reason's fold and cap, `formatPromptBlockedNote`'s shapes; then a fake CLI driving real `doStream` turns: this turn's own message failing as `blocked_by_hook` with the note and no footer, the session kept and the next message bare, a blocked replay dropping the child and session id and the next message replaying again, the legacy frame, a steered message blocked inside a turn that went on, a blocked compaction ending on its error part with no text, and a secret-like string in the prompt reaching neither the reply nor the log; the fake-CLI half is POSIX only): `test/prompt-blocked.test.ts`. The PTY half (the TUI's record and its stream frame, the synthesized result, a turn ended at once and one Ctrl+C before the next paste, `ask` failing, a queued message leaving its turn running, and `doStream` turns for the note and a blocked replay dropping its session): `test/interactive-pty.test.ts`. - `/claude-code-doctor` (report formatter, command-registration guard, `checkProxyAuth`, transcript strip, `describeSessionKey`, the skipped-MCP, not-loaded-plugin and background-subagent sections, and the plan-usage opt-in with `wantsPlanUsage`, `parsePlanUsage` and `fetchPlanUsage`): `test/doctor.test.ts`. - `/claude-code-doctor bundle` (the message-allowlist drift guard against `src/`, the pinned list of messages built at runtime, every kind's character class, the key-name sanitizer, `sanitizeArgv`, `sanitizeUrl`, the caps, `readLogTail`, file logging off, and above all the adversarial fixtures that put a fake system prompt, a user prompt, a tool input, an `sk-ant-` key, a bearer token, an `authToken`, an `ANTHROPIC_API_KEY=` value, an MCP env var, a `?token=` URL and the home path into every position a line has and assert none survives): `test/diagnostic-bundle.test.ts`. It uses in-memory fixtures and a stubbed tail read, so it can never append to a live `plugin.log` (h #g116). - The subagent dispatch form (`isSubagentDispatchActive` and every refusal, the one-question first form, the per-type and per-task forms, the `Per type…` account rows and the one third form they share with `Per task…`, the three account widths and their precedence, a per-type account row overriding an account typed on the type's own row, the group restriction on every offered and typed path, `parseCustomChoice` with and without candidates, `parseQuestionAnswers` over the live-measured sentence shapes, the claim store including two concurrent same-type children and the parent check, the TTL, `dispatchAccountCandidates` with and without the cross-group flag, a remembered choice read back after a simulated restart, a remembered model or account that went away, the delete through `deleteActiveProcessesForSession`, and the transcript strip): `test/subagent-dispatch.test.ts`. The file behind `Same as last time` (round trip, restart, two writers merging, a malformed file, a record of the wrong shape, the age cutoff, both caps, the `0600` mode and the fact that nothing but the three strings is written): `test/dispatch-choice-store.test.ts`. The same through a real `doStream` and a fake CLI (the option off, the argv unchanged when it is on, the hold, the release, the child's own `--model` / `CLAUDE_CODE_EFFORT_LEVEL` / account wrapper, two agent types spawning under two different accounts, `Same as last time` surviving a simulated restart, and the dismissal note): `test/subagent-dispatch-stream.test.ts`. diff --git a/TODO.md b/TODO.md index 5f2cf2a..e08c64f 100644 --- a/TODO.md +++ b/TODO.md @@ -77,11 +77,11 @@ hook's reason, and a blocked replay drops its empty session so the next message replays again. Why the switch replayed at all is fixed on the same branch (h #g315): the appical session's two usage-limited turns never moved its resume record, so the by-hand switch to the default account - found their messages past it and refused the carry (`sibling-conversation-changed`). Still open: - (1) the interactive transport does not read the TUI's `promptSubmitEnding` record, and how a - blocked prompt ends a PTY turn is unmeasured; (2) the location-switch empty turn below may be the - same block: check that session's Claude transcript for a `blocked_by_hook` record before building - anything on the session-key theory. + found their messages past it and refused the carry (`sibling-conversation-changed`). The + interactive transport is done on the same branch (2026-11-15, measured under a PTY on 2.1.322): + it reads the TUI's `promptSubmitEnding` record, ends the turn at once, and clears the text the TUI + hands back to its input box. The location-switch empty turn below was the same block (checked + 2026-11-15, see that entry). - 2026-11-14 (evening), the watchdog that closed a turn during a sleep: FIXED on `fix/blocked-prompt` (h #g316). It counts wall-clock time, sleep included, so a fire well past its deadline now waits again, and a fire that closes the turn interrupts the CLI. The start watchdog follows the same @@ -110,6 +110,14 @@ tool, so the lane stopped. Session `ses_e2898d33effeo0ojQzfvfWVOJK` (opencode.db), 2026-11-14. Check whether a location switch mid-turn changes the session key (the cwd is in it) so the step after the proxied `execute` result lands on a new key with no parked call and a fresh spawn. + 2026-11-15, the empty turn is explained: the step started at 00:14:21Z (opencode.db seq 34, after + `location-switched` at 00:14:18Z) and at 00:14:27.770Z Claude Code recorded `blocked_by_hook` + ("agent-guard: the prompt exceeds the assignment-probe scan cap ...", `promptKept: false`) in the + worktree cwd's transcript `a9e1ac0c-416d-4644-bd57-e70eae20aae6.jsonl`, so the new key replayed the + history and the guard refused it by size. h #g314 turns that into a `prompt blocked` note and an + error. Still open: that a location switch replays the thread at all (a new cwd is a new session key, + and Claude's transcript lives under the old cwd's directory). The `fix/session-move` worktree + (no commits yet) is where that would go. - 2026-11-10, found by the pr173 lane (h #g295), not measured: Claude Code 2.1.322 adds fast mode on Vertex, while `docs/models.md` says fast mode excludes Bedrock, Vertex and Foundry. Check on a Vertex diff --git a/docs/agents-history.md b/docs/agents-history.md index beda9db..62b1e0f 100644 --- a/docs/agents-history.md +++ b/docs/agents-history.md @@ -12937,12 +12937,44 @@ so a `▌ **refusal fallback:**` note was replayed to Claude as its own words, w was on the list. Both markers are on it now, and `test/turn-stats.test.ts` scans `src/` for every `export const *_MARKER = "▌` and fails on one that is not. -Not done: the interactive transport does not read the TUI's `promptSubmitEnding` record, and how a -blocked prompt ends a PTY turn is unmeasured. Why the replay happened at all is h #g315. +The interactive transport, measured on 2026-11-15 under a PTY (Claude Code 2.1.322, a scratch +`UserPromptSubmit` hook blocking `BLOCKME` through `--settings`, `--setting-sources ""`, Haiku 5.5, +`ClaudeSession` driven directly): + +- The TUI writes the same outcome into the transcript under another spelling: a + `system`/`informational` record, `level: "warning"`, `preventContinuation: true`, + `promptSubmitEnding: {ending: {kind: "blocked_by_hook", reason}, promptKept: false}`, and a + `content` that repeats the whole prompt after the hook's line. No `user` record and no + `assistant` record follow, so the turn loop, which ends on a terminal stop or a `turn_duration` + after a `user` record, waited out the whole turn timeout. +- It hands the dropped text back to the input box. The next paste lands after it: the next turn's + `user` record held the 40 blocked lines and the new message (1,425 characters), and a blocked + replay would carry into every following message, where the same hook blocks it again (the first + probe recorded two `blocked_by_hook` records and no `user` record). With one Ctrl+C before the + next paste, the record held only the new message (35 characters) and the TUI stayed up. Ctrl+U + clears one line of it, so it is not the key. + +What changed for the PTY: `scanTranscript` ends the turn as `blocked` on that record when it comes +before the turn's own `user` record (a message queued into a running turn is judged after it and +leaves the turn running, as on headless), and marks the box as holding handed-back text when +`promptKept` is false; the next turn sends one Ctrl+C before its paste, never while a turn runs. +`streamFrameFromRecord` renames the record into the stream's `prompt_submit_outcome` shape and +drops `content`, so `parsePromptBlock` reads both transports alike and the refused prompt is never +carried on. `interactiveResultFrame` synthesizes headless's result for it (`success`, not an +error, `num_turns: 0`, no `result` text), so the stream parser's `num_turns === 0` rule, the note, +the error finish and the blocked-replay drop are the headless code unchanged. `ask` (the `/btw` +fork) throws rather than waiting. Not measured: a queued message a hook drops on the PTY, which is +marked as handed back the same way; one Ctrl+C on an empty box only draws the TUI's exit hint. + +Why the replay happened at all is h #g315. Tests: `test/prompt-blocked.test.ts` (the parser, the note, and a fake CLI replaying the measured frames through real `doStream` turns, with a secret-like string in the prompt that must reach -neither the reply nor the log), and the marker scan in `test/turn-stats.test.ts`. +neither the reply nor the log), the marker scan in `test/turn-stats.test.ts`, and in +`test/interactive-pty.test.ts` a scripted TUI that ends a prompt the measured way: the record and +its stream frame, the synthesized result, a turn ended at once and the next paste starting from an +empty box, `ask` failing, a queued message leaving its turn running, and real `doStream` turns for +the note and for a blocked replay dropping its session. ## A by-hand switch after a usage limit replayed the thread instead of carrying it (2026-11-14) diff --git a/docs/guides/interactive-transport.md b/docs/guides/interactive-transport.md index 4f913e7..80040a2 100644 --- a/docs/guides/interactive-transport.md +++ b/docs/guides/interactive-transport.md @@ -83,6 +83,7 @@ The plan approval dialog is the one it does **not** answer: it waits for your de - **Long tool calls and long thinking** keep the turn alive: while the TUI is visibly working and the transcript is quiet, the transport reports progress every 30 seconds the way the headless CLI's own `tool_progress` heartbeat does. A slow first answer (measured: one first call took 185 seconds inside the CLI) no longer trips the start watchdog. - **A turn ends** on a terminal stop reason once that API call's last record is in (a call is written as several records, and the reply text is the last of them), on the TUI's interrupt marker, or on the `turn_duration` record 2.1.288 writes after every turn. As a safeguard for a future Claude Code that writes neither, a turn that has its reply also ends once the TUI and its transcript have both been silent for 20 seconds; measured on 2.1.288 the TUI never stays quiet for more than about 200 ms while Claude is working. Such a turn is reported as having ended without a stop reason, not as a clean reply. - **Following the transcript costs the same on a long conversation as on a new one.** The transport polls the session JSONL four times a second while a turn runs, and it reads only the bytes appended since the last poll: a poll that finds nothing new is one `stat` and no read at all, and a record the CLI is part way through writing is completed by the next poll rather than read twice. It used to re-read and re-split the whole file every poll, which on a 29.5 MB transcript measured 31 MB and 79 ms of CPU per poll, so a quiet turn spent most of a core on bytes it already had. The same measurement after the change: 16 bytes and 0.12 ms per poll. `scripts/bench-transcript-poll.ts` is the benchmark. +- **A message one of your `UserPromptSubmit` hooks ends** fails the turn under the same `▌ **prompt blocked:**` note as on headless, at once: the TUI records the block and nothing else, which used to leave the turn waiting out `turnTimeoutMs`. The TUI also puts the blocked text back in its input box, where your next message would be appended to it (and be blocked again), so the transport clears the box with one Ctrl+C before it pastes the next message. See [the symptom table](../troubleshooting/symptoms.md). - **A message you send while a proxied tool runs** (or a notice opencode delivers then) reaches Claude in the same turn: the transport types it into the TUI's own input queue, as Claude Code does with a message typed mid-turn, and Claude answers it after the tool result. - **The account's login is the one `claude` uses on its own.** `CLAUDE_CONFIG_DIR` reaches the TUI only for an account you configured: measured on 2.1.288, setting it even to the default `~/.claude` makes the CLI report itself logged out, which made every default-account interactive turn fail. - **Idle eviction and MCP hot reload work as on headless:** with `idleProcessTimeoutMs` set an idle TUI is closed and your next message starts a new one with `--resume`, and with `hotReloadMcp` a server that joined or left since the spawn replaces the TUI the same way, at the same safe boundaries. diff --git a/skills/claude-code-plugin/SKILL.md b/skills/claude-code-plugin/SKILL.md index 4235607..7c3f0ff 100644 --- a/skills/claude-code-plugin/SKILL.md +++ b/skills/claude-code-plugin/SKILL.md @@ -1517,6 +1517,9 @@ than continuing without it; the hook judges that replay the same way, so the use choices are to switch back to the model or account that answered before, to change the hook, or to start a new session. A message steered into a running turn that a hook blocks gets the note under an answer that did not see it, and the turn is not failed. +Both transports behave alike: on the interactive one the TUI puts the blocked text back +in its input box, and the plugin clears it before the next message so it never rides +along (older builds waited out `turnTimeoutMs` there instead). The plugin never sets or suggests a hook's own bypass variable (agent-guard's `AGENT_GUARD_PROMPT_GUARD_MODE`, say): relaxing a guard is the user's decision. diff --git a/src/claude-session-bun.ts b/src/claude-session-bun.ts index f97469b..b28eb40 100644 --- a/src/claude-session-bun.ts +++ b/src/claude-session-bun.ts @@ -687,6 +687,24 @@ export function isTurnDurationRecord(rec: any): boolean { return rec?.type === "system" && rec.subtype === "turn_duration" } +/** + * The TUI's own record of a hook ending a message before the model saw it + * (h #g314). Measured on 2.1.322 under a PTY with a blocking `UserPromptSubmit` + * hook: a `system`/`informational` record with `promptSubmitEnding: {ending: + * {kind, reason}, promptKept}` and `preventContinuation: true`, and no `user` + * or `assistant` record, so a turn waiting for either waited out its whole + * timeout. Its `content` repeats the whole prompt and is never read. + */ +export function isPromptEndingRecord(rec: any): boolean { + return ( + rec?.type === "system" && + rec.subtype === "informational" && + rec.promptSubmitEnding !== null && + typeof rec.promptSubmitEnding === "object" && + typeof rec.promptSubmitEnding.ending?.kind === "string" + ) +} + /** * A `compact_boundary` record the TUI wrote while no turn was running, marked * `betweenTurns` for the stream parser's note; null for any other line. The @@ -921,6 +939,8 @@ export type TurnEnd = | "interrupted" /** The TUI wrote `turn_duration` without a terminal assistant record. */ | "ended" + /** A hook ended the turn's own message before the model saw it (h #g314). */ + | "blocked" export interface TailTurnResult { stopReason: string | null @@ -987,6 +1007,14 @@ export class ClaudeSession { /** A fork whose first turn has not started: its transcript opens with the * parent's copied conversation, which belongs to no turn of this session. */ private forkPending = false + /** + * A hook dropped a message (`promptKept: false`) and the TUI put its text + * back in the input box, where the next paste would be appended to it + * (measured on 2.1.322: the next turn's record held both messages, and a + * blocked replay's 40 lines leaked into the next message). Cleared with one + * Ctrl+C before the next paste, when no turn runs (h #g314). + */ + private inputHandedBack = false private readonly env?: Record private readonly onScreen?: (event: ScreenEvent) => void private readonly onExit?: (code: number | null) => void @@ -1442,6 +1470,17 @@ export class ClaudeSession { this.turn = new Promise((resolve) => (settle = resolve)) this.turnDenied = [] this.abandonTurn = false + // A message a hook dropped is back in the input box. One Ctrl+C clears a + // box that holds text (measured on 2.1.322: the next record held only the + // new message, and the TUI stayed up); safe only here, with no turn + // running, where it cannot interrupt one. Ctrl+U clears one line of it. + if (this.inputHandedBack) { + this.inputHandedBack = false + this.proc.terminal.write("\x03") + await delay(150) + const until = Date.now() + 3_000 + while (Date.now() < until && Date.now() - this.lastDataAt < 300) await delay(50) + } // Records written between turns (a late `turn_duration`, an interrupt // marker) belong to the turn before, never to this one. A compaction is // the exception: the TUI compacts a long conversation on its own while it @@ -1584,6 +1623,11 @@ export class ClaudeSession { } else if (rec.type === "user") { if (scan.sawUserRecord && isInterruptRecord(rec)) scan.end = "interrupted" scan.sawUserRecord = true + } else if (isPromptEndingRecord(rec)) { + // The turn's own message, ended before it became a `user` record: + // the turn is over. One queued into a running turn leaves it running. + if (rec.promptSubmitEnding.promptKept === false) this.inputHandedBack = true + if (!scan.sawUserRecord) scan.end = "blocked" } else if ((scan.sawUserRecord || scan.stopReason) && isTurnDurationRecord(rec)) { scan.end = scan.stopReason ? "stop" : "ended" } @@ -1739,7 +1783,7 @@ export class ClaudeSession { const t0 = Date.now() const collected: string[] = [] const usage = new TurnUsageAccumulator() - const { stopReason } = await this.runTurnLoop( + const { stopReason, end } = await this.runTurnLoop( prompt, (_raw, rec) => { if (rec?.type !== "assistant" || !rec.message) return @@ -1753,6 +1797,9 @@ export class ClaudeSession { timeout, ) + if (end === "blocked") { + throw new Error(this.failureMessage("a UserPromptSubmit hook ended the prompt before the model saw it")) + } if (!stopReason) { throw new Error( this.failureMessage( diff --git a/src/claude-session-wrapper.ts b/src/claude-session-wrapper.ts index 1116c9f..89a1545 100644 --- a/src/claude-session-wrapper.ts +++ b/src/claude-session-wrapper.ts @@ -435,6 +435,24 @@ export function interactiveResultFrame(opts: { /** The CLI's own API-error reply the turn ended on (`TailTurnResult`). */ apiError?: { text: string; status?: number } | null }): string { + // What headless writes for a message a hook ended (h #g314): `success`, no + // error, no API call. Its `result` there repeats the whole prompt, so none + // is carried here; the parser reads `num_turns: 0` and the outcome frame. + if (opts.end === "blocked") { + return JSON.stringify({ + type: "result", + subtype: "success", + is_error: false, + num_turns: 0, + stop_reason: null, + terminal_reason: "blocked", + session_id: opts.sessionId, + usage: opts.usage ?? {}, + permission_denials: opts.denials ?? [], + total_cost_usd: 0, + duration_ms: opts.durationMs ?? 0, + }) + } const completed = opts.end === "stop" && !!opts.stopReason // A turn that ended on the CLI's own API-error reply finished, but failed: // a headless `result` for it says `subtype: "success"` with `is_error: true` @@ -511,6 +529,29 @@ export function interactiveSpawnEnv( * passes through byte-identical (h #g208). */ export function streamFrameFromRecord(raw: string): string { + // A hook ended a message (h #g314): the transcript spells the outcome + // `promptSubmitEnding: {ending: {kind, reason}, promptKept}`, the stream + // `prompt_submit_outcome: {kind, prompt_kept, reason}`, and the parser reads + // the stream's. `content` (the whole prompt) is dropped, never carried on. + if (raw.includes('"promptSubmitEnding"')) { + try { + const rec = JSON.parse(raw) + const ending = rec?.promptSubmitEnding + if (rec?.type === "system" && typeof ending?.ending?.kind === "string") { + const { content: _prompt, promptSubmitEnding: _ending, ...rest } = rec + return JSON.stringify({ + ...rest, + prevent_continuation: rec.preventContinuation === true, + prompt_submit_outcome: { + kind: ending.ending.kind, + prompt_kept: ending.promptKept === true, + ...(typeof ending.ending.reason === "string" ? { reason: ending.ending.reason } : {}), + }, + }) + } + } catch {} + return raw + } if (!raw.includes('"isApiErrorMessage":true')) return raw try { const rec = JSON.parse(raw) diff --git a/test/interactive-pty.test.ts b/test/interactive-pty.test.ts index 9aa9a62..e484c6d 100644 --- a/test/interactive-pty.test.ts +++ b/test/interactive-pty.test.ts @@ -25,6 +25,7 @@ import { highlightedChoice, interactiveTranscriptPath, isInterruptRecord, + isPromptEndingRecord, isTurnDurationRecord, planApprovalKeys, resumeQuotaChoice, @@ -45,7 +46,13 @@ import { } from "../src/claude-session-wrapper.js" import { REJECTED_EXIT_PLAN_MODE_PREFIX } from "../src/plan-mode-question.js" import { _setAccountUsageStorePathForTests, snapshotAccountUsage } from "../src/account-usage.js" -import { describeResultFailure, parseToolProgress } from "../src/cli-events.js" +import { + PROMPT_BLOCKED_MARKER, + SILENT_TURN_MARKER, + describeResultFailure, + parsePromptBlock, + parseToolProgress, +} from "../src/cli-events.js" import { deleteActiveProcess, getActiveProcess, @@ -95,6 +102,23 @@ function assistantRecord(id: string, stopReason: string, block: any): any { const textBlock = (text: string) => ({ type: "text", text }) const toolBlock = (id: string, name: string) => ({ type: "tool_use", id, name, input: {} }) +/** + * What 2.1.322's TUI writes when a `UserPromptSubmit` hook ends a prompt + * (h #g314), measured under a PTY with a blocking hook; ids, paths and + * timestamps dropped. `content` repeats the whole prompt after the hook's line. + */ +function promptEndingRecord(text: string, reason: string, promptKept = false): any { + return { + type: "system", + subtype: "informational", + level: "warning", + isMeta: false, + preventContinuation: true, + content: `UserPromptSubmit operation blocked by hook:\n[/hooks/guard.sh]: ${reason}\n\n\nOriginal prompt: ${text}`, + promptSubmitEnding: { ending: { kind: "blocked_by_hook", reason }, promptKept }, + } +} + type TurnScript = (tui: FakeTui) => void class FakeTui { @@ -111,10 +135,20 @@ class FakeTui { /** Drawn the moment the child starts. */ bootScreen = "" exitCode: number | null | undefined = undefined + /** + * A `UserPromptSubmit` hook: a reason ends the prompt the way 2.1.322 does + * (h #g314): no `user` record, an `informational` record instead, no turn + * script run, and the text handed back to the input box. + */ + blockPrompt?: (text: string) => string | null + /** Every prompt the TUI recorded as submitted, after any handed-back text. */ + submittedTexts: string[] = [] private draw: (text: string) => void = () => {} private resolveExit: (code: number | null) => void = () => {} private pasted = false private pastedText = "" + /** Text a hook dropped, back in the input box until Ctrl+C clears it. */ + private handedBack = "" /** A fork's parent transcript, copied in ahead of the first prompt as the * CLI does with `--fork-session`. */ private forkSource: string | null = null @@ -159,7 +193,9 @@ class FakeTui { this.writes.push(data) if (data.startsWith("\x1b[200~")) { this.pasted = true - this.pastedText = data.slice("\x1b[200~".length, -"\x1b[201~".length) + // A paste lands after whatever the box still holds. + this.pastedText = this.handedBack + data.slice("\x1b[200~".length, -"\x1b[201~".length) + this.handedBack = "" return } if (data === "\r" && this.pasted) { @@ -167,10 +203,18 @@ class FakeTui { if (this.forkSource && this.submitted === 0 && fs.existsSync(this.forkSource)) { fs.appendFileSync(this.transcript, fs.readFileSync(this.forkSource, "utf8")) } + this.submittedTexts.push(this.pastedText) + const reason = this.blockPrompt?.(this.pastedText) ?? null + if (reason !== null) { + this.append(promptEndingRecord(this.pastedText, reason)) + this.handedBack = this.pastedText + return + } this.append(userRecord(this.pastedText)) this.turns[this.submitted++]?.(this) return } + if (data === "\x03") this.handedBack = "" if (data === "\x1b") this.onEsc(this) } @@ -1780,6 +1824,7 @@ async function runFakeBunTurn( options: Record = {}, prompt: any[] = [{ role: "user", content: [{ type: "text", text: "reply" }] }], providerOptions?: Record, + configure?: (tui: FakeTui) => void, ): Promise<{ parts: any[]; children: FakeTui[] }> { const previousBun = Object.getOwnPropertyDescriptor(globalThis, "Bun") const children: FakeTui[] = [] @@ -1792,6 +1837,7 @@ async function runFakeBunTurn( }) => { const tui = new FakeTui() tui.turns = [turn] + configure?.(tui) children.push(tui) return tui.spawner(argv, { ...spawnOptions, ...spawnOptions.terminal, onData: (text) => spawnOptions.terminal.data(undefined, Buffer.from(text)), @@ -1967,6 +2013,168 @@ test("an expired login on the PTY gets the account note that names the login com // parent's Claude conversation with `--fork-session` instead of replaying it. // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// A prompt a `UserPromptSubmit` hook ends (h #g314). The TUI writes no `user` +// record for it, so a turn waiting for one waited out its whole timeout, and +// it hands the text back to the input box, where the next paste joined it. +// --------------------------------------------------------------------------- + +const GUARD_REASON = "probe-guard: blocked user prompt: BLOCKME seen" +const blockOnMarker = (tui: FakeTui) => { + tui.blockPrompt = (text) => (text.includes("BLOCKME") ? GUARD_REASON : null) +} + +test("the TUI's prompt-ending record reaches the parser in the stream's shape, without the prompt", () => { + const record = promptEndingRecord("hello BLOCKME", GUARD_REASON) + assert.equal(isPromptEndingRecord(record), true) + assert.equal(isPromptEndingRecord({ type: "system", subtype: "informational", content: "x" }), false) + assert.equal(isPromptEndingRecord(userRecord("hi")), false) + const frame = JSON.parse(streamFrameFromRecord(JSON.stringify(record))) + assert.deepEqual(frame.prompt_submit_outcome, { + kind: "blocked_by_hook", + prompt_kept: false, + reason: GUARD_REASON, + }) + assert.equal(frame.prevent_continuation, true) + assert.equal(frame.content, undefined, "the prompt the hook refused is not carried on") + assert.equal(frame.promptSubmitEnding, undefined) + assert.deepEqual(parsePromptBlock(frame), { kind: "blocked_by_hook", promptKept: false, reason: GUARD_REASON }) +}) + +test("a blocked turn's synthesized result is headless's: success, no API call, no prompt text", () => { + const frame = JSON.parse(interactiveResultFrame({ sessionId: "s", end: "blocked", stopReason: null })) + assert.equal(frame.subtype, "success") + assert.equal(frame.is_error, false) + assert.equal(frame.num_turns, 0) + assert.equal(frame.total_cost_usd, 0) + assert.equal(frame.result, undefined) + assert.equal(frame.session_id, "s") +}) + +test("a prompt a hook ends ends the turn at once, and the next paste starts from an empty box", async () => { + const tui = new FakeTui() + blockOnMarker(tui) + tui.turns.push((t) => t.append(assistantRecord("m1", "end_turn", textBlock("PINEAPPLE")))) + await withSession(tui, async (session) => { + await session.start() + const lines: string[] = [] + const started = Date.now() + const blocked = await session.tailTurn("line 0 of a replayed history\nBLOCKME", (raw) => lines.push(raw), 20_000) + assert.equal(blocked.end, "blocked") + assert.equal(blocked.stopReason, null) + assert.ok(Date.now() - started < 10_000, "ended on the record, not at the turn timeout") + assert.ok(lines.some((line) => line.includes('"promptSubmitEnding"'))) + assert.ok(!tui.writes.includes("\x03"), "nothing is cleared while the turn runs") + + const next = await session.tailTurn("Reply with only the word PINEAPPLE.", () => {}) + assert.equal(next.end, "stop") + const clear = tui.writes.indexOf("\x03") + const paste = tui.writes.findLastIndex((write) => write.startsWith("\x1b[200~")) + assert.ok(clear >= 0 && clear < paste, "one Ctrl+C before the next paste") + assert.equal(tui.writes.filter((write) => write === "\x03").length, 1) + assert.equal( + tui.submittedTexts.at(-1), + "Reply with only the word PINEAPPLE.", + "nothing of the blocked prompt joined the next message", + ) + + // A turn after an ordinary one sends no Ctrl+C. + tui.turns.push((t) => t.append(assistantRecord("m2", "end_turn", textBlock("again")))) + await session.tailTurn("again", () => {}) + assert.equal(tui.writes.filter((write) => write === "\x03").length, 1) + }) +}) + +test("ask fails a prompt a hook ends instead of waiting out its timeout", async () => { + const tui = new FakeTui() + blockOnMarker(tui) + await withSession(tui, async (session) => { + await session.start() + const started = Date.now() + await assert.rejects(session.ask("BLOCKME", 20_000), /UserPromptSubmit hook ended the prompt/) + assert.ok(Date.now() - started < 10_000) + }) +}) + +test("a message a hook ends while the turn runs leaves the turn running", async () => { + // A queued message is ended after the turn's own `user` record, so it is + // not this turn's prompt: the turn goes on to its reply. + const tui = new FakeTui() + tui.turns.push((t) => { + t.append(promptEndingRecord("steered BLOCKME", GUARD_REASON)) + t.later(20, () => t.append(assistantRecord("m1", "end_turn", textBlock("the answer")))) + }) + await withSession(tui, async (session) => { + await session.start() + const lines: string[] = [] + const result = await session.tailTurn("hi", (raw) => lines.push(raw)) + assert.equal(result.end, "stop") + assert.ok(lines.some((line) => line.includes("the answer"))) + }) +}) + +test("a blocked prompt on the PTY fails the turn under the plugin's note naming the hook", async () => { + const dirs = scratch() + const modelId = "claude-test-pty-blocked" + const key = sessionKey(dirs.cwd, `${modelId}::tools::default::context=["claude-code",null]`) + try { + const { parts } = await runFakeBunTurn( + dirs, + modelId, + () => {}, + {}, + [{ role: "user", content: [{ type: "text", text: "hello BLOCKME" }] }], + undefined, + blockOnMarker, + ) + const text = textOf(parts) + assert.ok(text.includes(PROMPT_BLOCKED_MARKER), text) + assert.ok(text.includes(GUARD_REASON), text) + assert.match(text, /nothing reached Claude/) + assert.ok(!text.includes(SILENT_TURN_MARKER), "not an empty reply") + assert.ok(!text.includes("Original prompt"), "the record's copy of the prompt is never rendered") + assert(!parts.some((part) => part.type === "error"), "the note is the account of it") + const finish = parts.find((part) => part.type === "finish") + assert.deepEqual(finish.finishReason, { unified: "error", raw: "blocked_by_hook" }) + assert.ok(getClaudeSessionId(key), "an ordinary message's session is kept") + } finally { + deleteClaudeSessionId(key) + dirs.cleanup() + } +}) + +test("a blocked replay on the PTY drops the empty session, so the next message replays again", async () => { + const dirs = scratch() + const modelId = "claude-test-pty-blocked-replay" + const key = sessionKey(dirs.cwd, `${modelId}::tools::default::context=["claude-code",null]`) + try { + const { parts, children } = await runFakeBunTurn( + dirs, + modelId, + () => {}, + {}, + [ + { role: "user", content: [{ type: "text", text: "one BLOCKME" }] }, + { role: "assistant", content: [{ type: "text", text: "A1" }] }, + { role: "user", content: [{ type: "text", text: "two" }] }, + ], + undefined, + blockOnMarker, + ) + const pasted = children[0].submittedTexts[0] + assert.match(pasted, /one BLOCKME/, "the envelope was a replay") + const text = textOf(parts) + assert.ok(text.includes(PROMPT_BLOCKED_MARKER), text) + assert.match(text, /next message replays them again/) + const finish = parts.find((part) => part.type === "finish") + assert.deepEqual(finish.finishReason, { unified: "error", raw: "blocked_by_hook" }) + assert.equal(getClaudeSessionId(key), undefined, "the session that holds none of it is dropped") + } finally { + deleteClaudeSessionId(key) + dirs.cleanup() + } +}) + test("a forked opencode session branches the parent's conversation on the PTY", async () => { _resetForkFingerprints() const previousBun = Object.getOwnPropertyDescriptor(globalThis, "Bun")