Nudges /handoff at 80% of the compaction limit (toast, plus a get-ready note on the next tool result or prompt) and, in place of auto-compaction, checks idle…

Complete setup guide to reproduce this Claude Code environment on Windows 11.
| Tool | Version | Install |
|---|---|---|
| NVM for Windows | 1.2.2 | winget install CoreyButler.NVMforWindows |
| Node.js | 24.13.0 | nvm install 24.13.0 && nvm use 24.13.0 |
| pnpm | latest | corepack enable && corepack prepare pnpm@latest --activate |
| Python | 3.14+ | winget install Python.Python.3.14 |
| uv | 0.10+ | pip install uv or winget install astral-sh.uv |
| GitHub CLI | latest | winget install GitHub.cli |
| Git | latest | winget install Git.Git |
irm https://claude.ai/install.ps1 | iex
Verify: claude --version (should show 2.1.x)
Repo: rtk-ai/rtk | Website: rtk-ai.app
RTK is a CLI proxy written in Rust that filters and compresses command outputs before they reach your LLM context, saving 60-90% of tokens on common dev commands (git, cargo, vitest, tsc, eslint, etc.).
Option A: Pre-built binary (recommended for Windows)
# 1. Download the Windows binary from GitHub Releases
# https://github.com/rtk-ai/rtk/releases
# Get: rtk-x86_64-pc-windows-msvc.zip
# 2. Extract and place in ~/bin
mkdir "$HOME\bin" -Force
# Extract rtk.exe to ~/bin/
# 3. Add ~/bin to PATH (one-time)
[Environment]::SetEnvironmentVariable("PATH", "$env:PATH;$HOME\bin", "User")
Option B: Cargo install (requires Rust toolchain)
cargo install --git https://github.com/rtk-ai/rtk
Option C: Quick install script (Linux/macOS)
curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh
Post-install: Initialize for Claude Code
rtk init --global
This installs the hook and creates RTK.md with instructions for settings.json.
Verify: rtk --version (should show rtk 0.15.0+) and rtk gain (must show token savings stats)
Name collision warning: If
rtk gainfails, you may havereachingforthejack/rtk(Rust Type Kit) installed instead. Uninstall it first.
Repo: sparfenyuk/mcp-proxy | PyPI: mcp-proxy
mcp-proxy bridges between stdio and SSE/Streamable HTTP transports for MCP servers. In aggregation mode it exposes multiple MCP servers behind a single HTTP endpoint.
Option A: uv (recommended)
uv tool install mcp-proxy
Option B: Docker (from v0.3.2+)
docker run --rm -t ghcr.io/sparfenyuk/mcp-proxy:latest --help
Update an existing install:
uv tool upgrade --reinstall mcp-proxy
Verify: where mcp-proxy (should show ~/.local/bin/mcp-proxy.exe)
GitHub access goes through the gh CLI (no GitHub MCP server):
gh auth login
/login
The main Claude Code settings file. Key sections:
{
// Git Bash doesn't obey .gitignore — disable for correct file access
"respectGitignore": false,
// Environment variables
"env": {
"BASH_MAX_TIMEOUT_MS": "1800000", // 30-minute bash timeout
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1", // Enable native agent teams
},
// Disable co-authored-by in commits
"includeCoAuthoredBy": false,
// Permission allow/deny lists
"permissions": {
"allow": [
"Bash(find:*)",
"Bash(ls:*)",
"Bash(mkdir:*)",
"WebFetch(domain:github.com)",
"WebFetch(domain:www.typescriptlang.org)",
"Bash(git log:*)",
"Bash(gh issue list:*)",
"Bash(gh issue view:*)",
"Bash(npx prettier:*)",
"Bash(nx prepush:*)",
"Bash(pnpm commit:*)",
"Bash(rg:*)",
"mcp__nx__nx_docs",
"mcp__nx__nx_workspace",
"mcp__nx__nx_project_details",
"Bash(nx show projects:*)",
"Bash(nx run-many:*)",
"Bash(nx run:*)",
"Bash(nx affected:*)",
"Bash(nx lint:*)",
"Bash(nx test:*)",
"Bash(nx build:*)",
"Bash(nx documentation:*)",
],
"deny": [
"Bash(git push origin main:*)",
"Bash(git push origin master:*)",
"Bash(rm -rf:*)",
"Bash(curl:*)",
"Bash(wget:*)",
],
},
// Auto-discover .mcp.json in projects
"enableAllProjectMcpServers": true,
// Status line — provided by the claude-hud plugin (see HUD section)
"statusLine": {
"type": "command",
"command": "node <resolved claude-hud plugin>/dist/index.js",
},
// Enabled plugins
"enabledPlugins": {
"typescript-lsp@claude-plugins-official": true,
"marksman-lsp": true,
"lua-lsp@claude-plugins-official": true,
"rust-analyzer-lsp@claude-plugins-official": true,
"claude-hud@claude-hud": true,
},
// Hooks — nul-guard + RTK auto-rewrite and suggest
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "node C:/Users/<YOUR_USERNAME>/.claude/hooks/nul-guard.js",
},
{
"type": "command",
"command": "node C:/Users/<YOUR_USERNAME>/.claude/hooks/rtk/rtk-rewrite.js",
},
{
"type": "command",
"command": "node C:/Users/<YOUR_USERNAME>/.claude/hooks/rtk/rtk-suggest.js",
},
],
},
],
},
}
Copy from mcp-proxy-servers.example.json and fill in your API keys:
Copy-Item mcp-proxy-servers.example.json mcp-proxy-servers.json
# Then edit mcp-proxy-servers.json with your actual keys
The proxy config defines these MCP servers:
| Server | Package / Binary | Requires |
|---|---|---|
| codex-cli | pnpm dlx @cexll/codex-mcp-server | OPENAI_API_KEY (env) |
| gemini-cli | pnpm dlx gemini-mcp-tool | GEMINI_API_KEY (env) |
| angular-cli | pnpm dlx @angular/cli mcp | - |
| context7 | pnpm dlx @upstash/context7-mcp | CONTEXT7_API_KEY |
| exa | pnpm dlx exa-mcp-server | EXA_API_KEY |
| filesystem | pnpm dlx @modelcontextprotocol/server-filesystem D:\ | - |
| greb-mcp | greb-mcp-js (from cheetah-greb) | GREB_API_KEY |
| taigaApi | uv run src/server.py (from D:/pytaiga-mcp) | - |
All pnpm dlx servers run on-demand (no global install needed) as long as pnpm is on PATH. The proxy launches them automatically. You only need to install the standalone binaries and obtain API keys.
Repo: cexll/codex-mcp-server | npm: @cexll/codex-mcp-server
MCP server that connects to OpenAI's Codex CLI for code analysis, refactoring, and automation. Runs on-demand via pnpm dlx (no global install needed).
# Quick add to Claude Code:
claude mcp add codex-cli -- npx -y @cexll/codex-mcp-server
# Or global install:
npm install -g @cexll/codex-mcp-server
Prerequisite: OpenAI Codex CLI installed and authenticated.
Repo: jamubc/gemini-mcp-tool | npm: gemini-mcp-tool
MCP server that connects to Google's Gemini CLI, leveraging Gemini's 1M token window for large file analysis and codebase understanding. Runs on-demand via pnpm dlx.
# Quick add to Claude Code:
claude mcp add gemini-cli -- npx -y gemini-mcp-tool
# Or global install:
npm install -g gemini-mcp-tool
Prerequisite: Google Gemini CLI installed and configured.
Repo: angular/angular-cli | npm: @angular/cli
Built-in MCP server in Angular CLI for project introspection, documentation, and best practices. No API key required.
# Verify it works standalone:
pnpm dlx @angular/cli mcp --help
Repo: upstash/context7-mcp | npm: @upstash/context7-mcp
Provides up-to-date code documentation for LLMs, avoiding hallucinated APIs and outdated examples. Works without a key (rate-limited) or with a free API key for higher limits.
# Quick add to Claude Code:
claude mcp add --scope user context7 -- npx -y @upstash/context7-mcp --api-key YOUR_API_KEY
Get a free API key at: https://context7.com/dashboard
Add to mcp-proxy-servers.json:
"env": { "CONTEXT7_API_KEY": "ctx7sk-..." }
Repo: exa-labs/exa-mcp-server | npm: exa-mcp-server
Web search and crawling MCP server powered by Exa's neural search. Runs on-demand via pnpm dlx.
# Quick add to Claude Code:
claude mcp add --transport http exa https://mcp.exa.ai/mcp
Get an API key at: https://dashboard.exa.ai/api-keys
Add to mcp-proxy-servers.json:
"env": { "EXA_API_KEY": "..." }
The config uses --tools=web_search_advanced_exa,crawling_exa to expose only search and crawling tools.
Repo: modelcontextprotocol/servers | npm: @modelcontextprotocol/server-filesystem
Node.js filesystem operations server with directory access controls. No API key required. Runs on-demand via pnpm dlx. The D:\ argument grants read/write access to the D: drive.
# Verify it works standalone:
pnpm dlx @modelcontextprotocol/server-filesystem D:\
Security note: This grants the MCP server access to the entire D: drive. Adjust the path argument to limit scope if needed.
Repo: VaibhavRaina/greb | npm: cheetah-greb | Website: grebmcp.com
Semantic code search via MCP using natural language queries. Searches your codebase with AI-powered ranking — no indexing required. Works with Claude Code, Cursor, Windsurf, and other MCP clients.
pnpm install -g cheetah-greb
This installs the greb-mcp-js binary globally.
Get an API key at: https://grebmcp.com/dashboard/api-keys
Add to mcp-proxy-servers.json:
"env": { "GREB_API_KEY": "grb_..." }
Repo: talhaorak/pytaiga-mcp
MCP server for Taiga project management. Provides access to projects, user stories, tasks, issues, sprints, and more. Runs locally via uv.
# 1. Clone the repo to D:\
git clone https://github.com/talhaorak/pytaiga-mcp.git D:\pytaiga-mcp
# 2. Install dependencies
uv --directory D:\pytaiga-mcp sync
# 3. Configure your Taiga instance — create D:\pytaiga-mcp\.env
# TAIGA_URL=https://your-taiga-instance.com
# TAIGA_USERNAME=your-username
# TAIGA_PASSWORD=your-password
The proxy launches the server automatically via uv --directory D:/pytaiga-mcp run src/server.py. No API key needed in the proxy config — authentication is handled by the .env file in the repo.
Claude Code connects to the MCP servers through the proxy. Add this mcpServers block to ~/.claude.json:
{
"mcpServers": {
"codex-cli": {
"type": "stdio",
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8808/servers/codex-cli/sse"]
},
"gemini-cli": {
"type": "stdio",
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8808/servers/gemini-cli/sse"]
},
"angular-cli": {
"type": "stdio",
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8808/servers/angular-cli/sse"]
},
"context7": {
"type": "stdio",
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8808/servers/context7/sse"]
},
"exa": {
"type": "stdio",
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8808/servers/exa/sse"]
},
"filesystem": {
"type": "stdio",
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8808/servers/filesystem/sse"]
},
"greb-mcp": {
"type": "stdio",
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8808/servers/greb-mcp/sse"]
},
"taigaApi": {
"type": "stdio",
"command": "mcp-proxy",
"args": ["http://127.0.0.1:8808/servers/taigaApi/sse"]
}
}
}
Each entry uses mcp-proxy as a stdio-to-SSE bridge, pointing at the aggregation server. The proxy must be running first (see below).
Use the slash command inside Claude Code:
/start-mcp-proxy
Or manually via PowerShell:
mcp-proxy --port 8808 --pass-environment --named-server-config "$HOME\.claude\mcp-proxy-servers.json"
Status: http://127.0.0.1:8808/status Servers: http://127.0.0.1:8808/servers/<name>/sse
hooks/nul-guard.js)A PreToolUse:Bash hook that prevents creation of literal nul files on Windows. The model sometimes emits 2>nul (Windows CMD syntax) in bash, which creates a file named "nul" instead of discarding output.
Rewrites:
2>nul -> 2>/dev/null>nul -> >/dev/null1>nul -> 1>/dev/null2>>nul -> 2>>/dev/nullUses word-boundary matching (\bnul\b) so it won't affect null, nulcheck.log, etc.
hooks/rtk/rtk-rewrite.js)A PreToolUse:Bash hook that transparently rewrites commands to RTK equivalents before execution. Covers:
git status/diff/log/add/commit/push/pull/branch/fetch/stash/showgh pr/issue/runvitest, tsc, eslint, prettier, playwright, prismacargo test/build/clippycat -> rtk read, rg/grep -> rtk grep, ls -> rtk lsdocker ps/images/logs, kubectl get/logspytest, ruff, pipgo test/build/vet, golangci-linthooks/rtk/rtk-suggest.js)Same pattern matching as rewrite, but emits a systemMessage suggestion instead of modifying the command. Acts as a fallback awareness layer.
| Command | Description |
|---|---|
/clean-claude | Cleanup ~/.claude (debug logs, transcripts, cache). Runs scripts/clean-claude.mjs |
/delete-nul | Delete Windows reserved nul files via PowerShell \\?\ path prefix |
/start-mcp-proxy | Start/verify the mcp-proxy aggregation server on port 8808 |
agents/code-reviewer.mdCustom agent triggered after major project steps are completed. Reviews implementation against the original plan for:
code-review skill: blast-radius classification, proof audit, and that skill's output format and verdicts| Skill | Description |
|---|---|
dotnet | .NET 10 development with clean architecture, Minimal APIs, SignalR |
systematic-debugging | Root-cause tracing, defense-in-depth, condition-based waiting |
test-driven-development | TDD workflow with anti-pattern detection |
| Skill | Description |
|---|---|
brainstorming | Creative exploration before implementation |
code-review-receiving | Technical rigor when receiving review feedback |
dispatching-parallel-agents | Parallelization of independent tasks |
finishing-a-development-branch | Merge/PR/cleanup decision guide |
frontend-design | Production-grade web component design |
nextjs-best-practices | Next.js App Router patterns |
prompt-engineer | LLM prompt design and evaluation |
skills-creating | Create and edit skills |
subagent-driven-development | Multi-agent implementation with spec review |
using-git-worktrees | Isolated feature work via git worktrees |
scripts/clean-claude.mjsNode.js cleanup utility targeting bloated ~/.claude directories:
node ~/.claude/scripts/clean-claude.mjs # dry-run report
node ~/.claude/scripts/clean-claude.mjs --apply # execute cleanup
node ~/.claude/scripts/clean-claude.mjs --deep # also prune JSONL content
node ~/.claude/scripts/clean-claude.mjs --days 7 # override max age
Targets: debug/, transcripts/, projects/, file-history/, shell-snapshots/, todos/, cache/, paste-cache/. Deep mode truncates bloated JSONL fields (normalizedMessages, agent_progress, bash_progress, toolUseResult, thinking blocks).
Claude Code uses Git Bash internally for all Bash() tool calls, but most Windows tools (pnpm globals, Python, LSP servers, etc.) are installed into Windows-style PATH entries that Git Bash doesn't inherit by default. This causes "command not found" errors for tools that work fine in PowerShell.
The solution has two parts:
profiles/bash_profile — syncs the full Windows PATH (Machine + User) into Git Bash at startup using cygpath to convert paths. This ensures pnpm, rtk, mcp-proxy, python, uv, and all global npm packages are findable.settings.json: "respectGitignore": false — Git Bash doesn't handle .gitignore the same way, so this prevents file access issues.To install the bash profile:
# Copy to Git Bash's profile location
Copy-Item "$HOME\.claude\profiles\bash_profile" "$HOME\.bash_profile" -Force
How it works:
# Reads Windows PATH via powershell.exe, splits on ";", converts each
# entry to Unix-style path via cygpath, and appends missing entries
_sync_win_path() {
local win_path
win_path=$(powershell.exe -NoProfile -NonInteractive -Command \
'([Environment]::GetEnvironmentVariable("PATH","Machine") + ";" + [Environment]::GetEnvironmentVariable("PATH","User")).TrimEnd(";")' \
2>/dev/null | tr -d '\r')
# ... converts and appends each missing entry to $PATH
}
Without this, Claude Code's bash shell won't find globally installed tools like typescript-language-server, pnpm, rtk, etc.
profiles/Microsoft.PowerShell_profile.ps1)Copy to your PowerShell profile location:
Copy-Item "$HOME\.claude\profiles\Microsoft.PowerShell_profile.ps1" $PROFILE -Force
Features:
D:\ (skipped in VS Code and Claude Code via $env:TERM_PROGRAM / $env:CLAUDECODE guards)ls/dir for fast startup)cc -> claudegcm (checkout master), gcb (checkout -b), gc (checkout), gp (pull), gpm (pull master), gfm (fetch --prune), gs (status -sb)rmnm - recursively remove node_modules, .nx, .angular, dist, tmp, coverage, and lockfilesprofiles/terminal-defaults.md)All terminals open in D:\ by default:
profiles/set-shortcut.ps1HKCU\Software\Microsoft\Command Processor\Autorun = cd /d D:\Set-Location D:\ guarded for non-VS-Code/Claude CodeThe status line is provided by the claude-hud plugin — it shows real-time info in Claude Code's status bar (model, context usage, cost, git branch, etc.).
Install it from its marketplace:
/plugin marketplace add jarrodwatts/claude-hud
/plugin install claude-hud
The statusLine.command in settings.json resolves the latest installed claude-hud version under ~/.claude/plugins/cache/*/claude-hud/*/dist/index.js and runs it with the active node binary. The plugin ships the renderer — no standalone wrapper script is needed.
To configure layout, presets, and which elements to display:
/claude-hud:setup # set claude-hud as your status line
/claude-hud:configure # adjust display options
~/bin DirectoryStandalone binaries on PATH:
| Binary | Purpose |
|---|---|
rtk.exe | RTK - Rust Token Killer (CLI proxy for token savings) |
jq.exe | JSON processor |
marksman.exe | Markdown LSP server |
Installed LSP servers used by the typescript-lsp plugin:
| Server | Binary | Extensions | Install |
|---|---|---|---|
| TypeScript | typescript-language-server | .ts, .tsx, .js, .jsx, .mts, .cts, .mjs, .cjs | pnpm add -g typescript-language-server typescript |
| JSON | vscode-json-language-server | .json, .jsonc | pnpm add -g vscode-langservers-extracted |
| HTML | vscode-html-language-server | .html, .htm | pnpm add -g vscode-langservers-extracted |
| CSS | vscode-css-language-server | .css, .scss, .less | `pnpm add -g v
hooks/register.ts 128 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import { idle } from './idle'
4
5// Shares of autoCompactThreshold (autoCompactWindow minus the output reserve
6// and the compaction buffer), not of the model's window. With auto-compaction
7// off it falls back to the window.
8// ponytail: constants, not userConfig; promote them if they need tuning per machine.
9const NUDGE_AT = 80
10
11export const warning = (percent: number) =>
12 `Handoff-trigger mod: context is at ${percent}% of the compaction limit. ` +
13 'At the limit, /handoff runs in place of auto-compaction, then /clear, and the work continues from the handoff. ' +
14 'Get ready: finish or checkpoint the current step, and keep the state needed to resume in files or the handoff.'
15
16async function percentOfLimit($: EngineInterface) {
17 const { context } = await $.session.usage({ breakdown: 'summary' })
18 const limit = context.breakdown?.autoCompactThreshold ?? context.window
19
20 return Math.round((100 * (context.tokens ?? 0)) / limit)
21}
22
23const nudge = (percent: number) =>
24 `Context at ${percent}% of the compaction limit: consider /handoff (runs itself before auto-compaction)`
25
26export const register: Register = on => {
27 idle(on)
28
29 // One nudge per fill cycle; a cycle ends when the context drops below
30 // NUDGE_AT again (after /clear or a compaction). The handoff itself runs in
31 // place of auto-compaction (idle.ts).
32 let isNudged = false
33 // The warning rides the next thing the model reads anyway (a tool result
34 // or a prompt): sending it on its own would cost a full-context request.
35 let warnAt: number | undefined
36
37 // True on the first look past NUDGE_AT in a fill cycle; it arms the warning.
38 function isCrossing(percent: number) {
39 if (percent < NUDGE_AT) {
40 isNudged = false
41 warnAt = undefined
42
43 return false
44 }
45 if (isNudged) {
46 return false
47 }
48
49 isNudged = true
50 warnAt = percent
51
52 return true
53 }
54
55 function takeWarning(context: readonly string[] = []) {
56 const percent = warnAt
57 warnAt = undefined
58
59 return percent === undefined ? [...context] : [...context, warning(percent)]
60 }
61
62 // A subagent's turn, an interrupt or an error is not the end of the
63 // person's turn. The matcher also lets idle.ts hook every turn: the engine
64 // takes one unmatched hook per event per plugin.
65 on('turn.complete', { reason: 'answer' }, async ($, e, next) => {
66 const result = await next(e)
67 if (e.agentId) {
68 return result
69 }
70
71 const percent = await percentOfLimit($)
72 if (isCrossing(percent)) {
73 $.ui.toast(nudge(percent))
74 }
75
76 return result
77 })
78
79 // A turn that works on without a prompt: the warning lands after the first
80 // main-agent tool result past NUDGE_AT, inside the turn.
81 // ponytail: one usage read per tool call; throttle if it shows in timings.
82 on('tool.call', async ($, e, next) => {
83 const result = await next(e)
84 if (e.agentId || 'deny' in result) {
85 return result
86 }
87
88 const percent = await percentOfLimit($)
89 if (isCrossing(percent)) {
90 $.ui.toast(nudge(percent))
91 }
92 if (warnAt === undefined) {
93 return result
94 }
95
96 return { ...result, context: takeWarning(result.context) }
97 })
98
99 // A turn that answered without tools: the next prompt carries it, whoever
100 // sent it (a notification, a loop, a peer), except a plugin's own (this
101 // mod's pings and continues). Matched on `wait`, both values, because
102 // idle.ts holds the unmatched hook.
103 for (const wait of [false, true]) {
104 on('prompt.submit', { wait }, async ($, e, next) => {
105 if (warnAt === undefined || e.command || e.origin.kind === 'plugin') {
106 return next(e)
107 }
108
109 // Look again: a /clear, /resume or /compact since the warning was armed
110 // ran no turn, and the fresh context must not be told it is full.
111 isCrossing(await percentOfLimit($))
112 if (warnAt === undefined) {
113 return next(e)
114 }
115
116 const percent = warnAt
117 const result = await next({ ...e, context: takeWarning(e.context) })
118 // Dropped beneath this hook (a settings hook, the engine): nothing went
119 // in. idle.ts's drops never reach here; its hook is outermost.
120 if ('drop' in result) {
121 warnAt = percent
122 }
123
124 return result
125 })
126 }
127}
128hooks/idle.ts 817 lines1import type { AgentInfo, AgentStatus, EngineInterface, On, SessionCompactInput, SessionCompactSkipped, SessionEndInput, TurnCompleteInput, TurnCompleteReason, TurnStartInput } from 'claude-code'
2
3// ponytail: the prompt-cache TTL is assumed 1h, not detected. A mod can't read
4// it ($.fs.read stops at 4 MiB, $.session.usage has no TTL breakdown); on a 5m
5// TTL session the first ping spends cold-cache's one stop (see the spec).
6const TTL_MS = 60 * 60_000
7const LEAD_MS = 5 * 60_000
8const MIN_TOKENS = 50_000
9const DUP_MS = 5 * 60_000
10const PINGS = 2
11
12// A reply is needed: the harness rejects a turn with no visible output.
13export const PING_TEXT = 'Prompt-cache keepalive ping from the handoff-trigger mod. Reply with one line of at most five words saying the cache is kept warm, and do nothing else: no tools, no work.'
14// Without it the handoff skill copies the last user prompts, pings included,
15// and lets the latest one win.
16export const HANDOFF_ARGS = "The handoff-trigger mod's keepalive pings are not user prompts: leave them out of the last user prompts, and they do not change the task."
17
18// A handoff path as the handoff skill replies with it (`~/…` or `C:\…`); the
19// lookbehind keeps leading markdown (`**`, `(`, `[`) out of the match.
20const HANDOFF_PATH = /(?<=^|[\s`'"(\[*])(?:[A-Za-z]:|~)?[^\s`'"()\[\]*]*[\\/]\.claude[\\/]handoffs[\\/][^\s`'"()\[\]*]+\.md/g
21
22// A cold prompt between its drop and continueFresh's submit; re-sends append.
23type Pending = {
24 text: string
25 readonly handoffPath: string
26 readonly sessionId: string
27}
28
29// The last resubmitted text, so a re-send within DUP_MS doesn't run twice.
30type Resent = {
31 readonly text: string
32 readonly until: number
33}
34
35// The idle path's module state, one per Claude Code process; /clear and
36// /resume keep it.
37let lastResponseAt: number | undefined
38let handoffPath: string | undefined
39let cancelTimer: (() => void) | undefined
40let turnStartedAt: number | undefined
41let isPromptInTurn = false
42let hasFired = false
43let pings = 0
44let spell = 0
45let pending: Pending | undefined
46let resent: Resent | undefined
47// Set right before the idle /handoff runs; the next main turn's settle reads
48// and clears it.
49let isIdleHandoff = false
50// The hands-free chain cap: 1 after one continue, until a person prompt.
51// session.end keeps it, so the mod's own /clear does too.
52let unattended: 0 | 1 = 0
53// Bumped on every person prompt, commands too: a warm /cost moves neither
54// spell nor handoffPath.
55let personSeen = 0
56
57// --- Handoff in place of auto-compaction: state ---
58// In this file, not its own module: the loader follows $ only into functions
59// declared in the same file as the hook, never across an import.
60
61const FLOW_MS = 10 * 60_000
62// How long the done check waits for answers after its first send.
63const CHECK_MS = 90_000
64const DONE_CHECK = 'Handoff check from the handoff-trigger mod: is the task you were given finished? Reply with exactly DONE if it is, or NOT DONE: <one line on what is left>. Do nothing else.'
65// Agents that hand back one report and are done once idle: stopped without a
66// done check, whose answer turn rebuilds a cold context (38 of 119 checks in
67// the week of 2026-10-19 went to these).
68const REPORT_TYPES = new Set(['critic', 'code-reviewer', 'quality-reviewer', 'security-reviewer', 'performance-reviewer', 'architect', 'verifier', 'Explore'])
69// At or past this share of the model window an auto compaction is a prompt
70// too long: vetoing it would leave the session unable to answer.
71const WINDOW_SHARE = 0.9
72const SKIP_REASON = 'handoff-trigger: handing off instead of compacting'
73const FAILED_TOAST = 'Handoff failed; auto-compaction allowed again'
74// The first line of the /handoff args; the turn whose text has it fails fast.
75const MARKER = '[handoff-trigger:compact]'
76const ALIVE_HEADER = 'Alive agents (they survive /clear; their notices arrive in the new session; reach one with SendMessage <id>):'
77const ALIVE_STATUSES: AgentStatus[] = ['pending', 'running', 'waiting', 'idle']
78
79// off → vetoed → checking → handing-off → clearing → off, plus failed: the
80// next auto compaction after a failure runs.
81type FlowState = 'off' | 'vetoed' | 'checking' | 'handing-off' | 'clearing' | 'failed'
82
83const ACTIVE: FlowState[] = ['vetoed', 'checking', 'handing-off', 'clearing']
84
85// One idle agent asked by the done check: its first reply, and the note it is
86// kept with. Settled once it has a note or is in stopped. `agent` is kept
87// from the check's list, so a stopped agent stays listed after it drops off.
88type Asked = {
89 readonly agent: AgentInfo
90 readonly reply?: string
91 readonly note?: string
92}
93
94// The flow's state, one per process too; any session.end but the mod's own
95// /clear resets it.
96let flowState: FlowState = 'off'
97// 0 until the check starts: a veto alone has no deadline.
98let deadline = 0
99let asked = new Map<string, Asked>()
100let stopped: AgentInfo[] = []
101let handoffTurnId: string | undefined
102// Moves on every reset: a timer or continuation from an older flow does nothing.
103let flowId = 0
104let isMainTurnRunning = false
105// The flow whose settled check waits for the running main turn to end.
106let handOffFlow: number | undefined
107// Set while the mod's own /clear runs: its session.end leaves the flow alone.
108let isOwnClear = false
109// personSeen at an idle veto, undefined at a mid-turn one: only an idle flow's
110// continue, with no person prompt since, takes the unattended cap.
111let idleVetoSeen: number | undefined
112
113export function idle(on: On): void {
114 lastResponseAt = undefined
115 handoffPath = undefined
116 cancelTimer = undefined
117 turnStartedAt = undefined
118 isPromptInTurn = false
119 hasFired = false
120 pings = 0
121 spell = 0
122 pending = undefined
123 resent = undefined
124 isIdleHandoff = false
125 unattended = 0
126 personSeen = 0
127 flowState = 'off'
128 deadline = 0
129 asked = new Map()
130 stopped = []
131 handoffTurnId = undefined
132 flowId = 0
133 isMainTurnRunning = false
134 handOffFlow = undefined
135 isOwnClear = false
136 idleVetoSeen = undefined
137
138 // Keeps pending: the mod's own /clear ends the session mid-flight.
139 on('session.end', async ($, e, next) => {
140 stopTimer()
141 lastResponseAt = undefined
142 handoffPath = undefined
143 isPromptInTurn = false
144 hasFired = false
145 pings = 0
146 spell += 1
147 isIdleHandoff = false
148 await onSessionEnd($, e)
149
150 return next(e)
151 })
152
153 on('turn.start', async ($, e, next) => {
154 stopTimer()
155 spell += 1
156 turnStartedAt = await $.clock.now()
157 await onTurnStart($, e)
158
159 return next(e)
160 })
161
162 on('turn.complete', async ($, e, next) => {
163 // Before any await: a turn.start landing in one moves spell, and this
164 // turn's wake must not arm inside the next turn.
165 const turnSpell = spell
166 const result = await next(e)
167 // Before the agentId guard: the done check reads agent turns too.
168 await onTurnComplete($, e)
169 if (e.agentId) return result
170
171 // Any end of a turn closes check 3's window: a later same text is a new
172 // prompt, also a retry after the resubmitted turn failed.
173 resent = undefined
174
175 // A person prompt resets pings, so pings > 0 means this is the ping's own
176 // turn. It refreshed nothing: lastResponseAt stays, the handoff runs now.
177 const isFailed = e.reason === 'error' || e.reason === 'refusal'
178 const isFailedPing = isFailed && pings > 0 && !hasFired
179 if (isFailedPing) {
180 pings = PINGS
181 arm($, 0)
182
183 return result
184 }
185
186 await settleTurn($, e.answer, e.reason, turnSpell)
187
188 return result
189 })
190
191 on('prompt.submit', async ($, e, next) => {
192 const isPerson = e.origin.kind === 'composer' || e.origin.kind === 'bridge'
193 if (!isPerson) return next(e)
194
195 // The person is back, even for a command: the cap resets, and a hands-free
196 // continue still waiting for its tick goes stale.
197 unattended = 0
198 personSeen += 1
199 isIdleHandoff = false
200
201 // Both reads before check 2; no await from there to setting pending, so
202 // two overlapping person prompts can't both reach check 5.
203 const now = await $.clock.now()
204 const sessionId = await $.session.id()
205
206 if (pending) {
207 if (e.text !== pending.text) pending.text += `\n\n${e.text}`
208 const appended = { drop: 'Added to your prompt that is being continued from the handoff.' }
209
210 return appended
211 }
212
213 const duplicate = { drop: 'Already sent after clearing.' }
214 const isResent = resent !== undefined && now < resent.until && e.text.trim() === resent.text.trim()
215 if (isResent) return duplicate
216
217 const path = handoffPath
218 const isCommand = e.text.startsWith('/')
219 const hasAttachments = (e.attachments?.length ?? 0) > 0
220 // A prompt typed into a running turn: that turn keeps the cache warm.
221 const isInTurn = e.turnId !== undefined
222 const isWarm = isInTurn || lastResponseAt === undefined || now - lastResponseAt < TTL_MS
223 const isPassing = isCommand || hasAttachments || path === undefined || isWarm
224 if (isPassing) {
225 hasFired = false
226 pings = 0
227 if (!isCommand) spell += 1
228 if (e.turnId) isPromptInTurn = true
229
230 return next(e)
231 }
232
233 stopTimer()
234 hasFired = false
235 pings = 0
236 spell += 1
237 pending = { text: e.text, handoffPath: path, sessionId }
238 handoffPath = undefined
239 // A command can't run inside a hook the turn is waiting on.
240 $.clock.after(0, () => continueFresh($))
241 const cleared = { drop: 'Cache cold: clearing and continuing from the handoff with your prompt.' }
242
243 return cleared
244 })
245
246 on('session.compact', async ($, e, next) => {
247 const isSkipped = await isVetoing($, e)
248 const skipped: SessionCompactSkipped = { skip: SKIP_REASON }
249 if (isSkipped) return skipped
250
251 return next(e)
252 })
253
254 // Only records an agent's reply to the done check; the send goes on as it is.
255 on('session.send', async ($, e, next) => {
256 if (e.agentId) answer($, e.agentId, e.text)
257
258 return next(e)
259 })
260}
261
262// The cold return: /clear, then the dropped prompt resubmitted as the user's
263// own with the handoff to read first. Any failure shows the prompt in a toast.
264async function continueFresh($: EngineInterface): Promise<void> {
265 // The same object check 2 appends to, until pending is cleared below.
266 const sent = pending
267 if (!sent) return
268
269 try {
270 await $.command.run({ command: 'clear' })
271 const sessionId = await $.session.id()
272 // Submitting now would land in the cold session.
273 if (sessionId === sent.sessionId) throw new Error('/clear kept the session')
274
275 const now = await $.clock.now()
276 // Before the submit: a re-send while it is in flight meets check 3.
277 pending = undefined
278 resent = { text: sent.text, until: now + DUP_MS }
279 const request = `Continue from the handoff in ${sent.handoffPath}: read it and run its Verify command, then\n`
280 + `act on my new request below. It overrides the handoff's Next step.\n\n${sent.text}`
281 const { drop } = await $.prompt.submit({ asUser: true, text: request })
282 if (drop) throw new Error(drop)
283 } catch {
284 $.ui.toast(`Couldn't continue from the handoff. Your prompt: ${sent.text}`)
285 resent = undefined
286 } finally {
287 pending = undefined
288 }
289}
290
291// The idle return: /clear, then the handoff's Next step as the user's own.
292// Leaves handoffPath alone: a kept session still has it for the cold path, and
293// a good clear's session.end has wiped it.
294async function continueIdle($: EngineInterface, path: string, seenAtSettle: number): Promise<void> {
295 const request = `Continue from the handoff in ${path}: read it, run its Verify command, then do its Next step.`
296 try {
297 const sessionId = await $.session.id()
298 await $.command.run({ command: 'clear' })
299 const clearedId = await $.session.id()
300 if (clearedId === sessionId) throw new Error('/clear kept the session')
301 // A person prompt during the /clear is in the new session already: no
302 // unattended Next step behind it, and the cap stays theirs.
303 if (personSeen !== seenAtSettle) throw new Error('a person prompt came first')
304
305 const { drop } = await $.prompt.submit({ asUser: true, text: request })
306 if (drop) throw new Error(drop)
307
308 unattended = 1
309 } catch {
310 $.ui.toast(`Couldn't continue from the handoff. To continue, paste: ${request}`)
311 }
312}
313
314// turn.complete steps 1-4: record a handoff written this turn, continue from
315// the idle one hands-free, or arm the wake.
316async function settleTurn($: EngineInterface, answer: string, reason: TurnCompleteReason, turnSpell: number): Promise<void> {
317 // Before any await: a person prompt landing in one clears the flag itself.
318 const wasIdleHandoff = isIdleHandoff
319 isIdleHandoff = false
320 const seenAtSettle = personSeen
321 const path = await freshHandoff($, answer)
322 handoffPath = path
323 lastResponseAt = await $.clock.now()
324 isPromptInTurn = false
325 stopTimer()
326
327 const isHandsFree = wasIdleHandoff && reason === 'answer' && path !== undefined && isUnattendedAllowed() && !isFlowActive()
328 if (isHandsFree) {
329 // Checked before the /clear, which moves spell itself: a person prompt or
330 // command, a queued turn, or the compaction flow that came first wins.
331 const continueIfCurrent = async (): Promise<void> => {
332 const isStale = spell !== turnSpell || handoffPath !== path || personSeen !== seenAtSettle || isFlowActive()
333 if (isStale) return
334
335 await continueIdle($, path, seenAtSettle)
336 }
337 // A command can't run inside a hook the turn is waiting on.
338 $.clock.after(0, continueIfCurrent)
339 }
340
341 const isArmable = reason === 'answer' && !hasFired && path === undefined
342 if (!isArmable) return
343
344 const { context } = await $.session.usage()
345 const tokens = context.tokens ?? 0
346 const hasMovedOn = spell !== turnSpell
347 if (tokens < MIN_TOKENS || hasMovedOn) return
348
349 arm($, TTL_MS - LEAD_MS)
350}
351
352// The first handoff path in the reply whose file was written during this turn;
353// a reply that only quotes an older handoff, or (the cold path's rule, off for
354// the compaction flow) answered a prompt typed into the turn, has none.
355async function freshHandoff($: EngineInterface, answer: string, isTypedPromptVoiding = true): Promise<string | undefined> {
356 const startedAt = turnStartedAt
357 if (startedAt === undefined || (isTypedPromptVoiding && isPromptInTurn)) return undefined
358
359 for (const [spelled] of answer.matchAll(HANDOFF_PATH)) {
360 const path = await expandHome($, spelled)
361 const stat = await $.fs.stat(path).catch(() => undefined)
362 if (stat && stat.mtimeMs >= startedAt) return path
363 }
364
365 return undefined
366}
367
368async function expandHome($: EngineInterface, path: string): Promise<string> {
369 if (!path.startsWith('~')) return path
370
371 const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
372
373 if (home === undefined) return path
374
375 return home + path.slice(1)
376}
377
378function arm($: EngineInterface, delayMs: number): void {
379 stopTimer()
380 const armedSpell = spell
381 const timer = $.clock.after(delayMs, () => fire($, armedSpell))
382 cancelTimer = () => timer.cancel()
383}
384
385function stopTimer(): void {
386 cancelTimer?.()
387 cancelTimer = undefined
388}
389
390// The idle wake: a refresh ping for the first PINGS wakes, then /handoff while
391// the cache is still warm. A spell that moved on since arming sends nothing.
392async function fire($: EngineInterface, armedSpell: number): Promise<void> {
393 const now = await $.clock.now()
394 if (spell !== armedSpell) return
395
396 // Sleep guard: a late timer (the machine slept) finds the cache cold already.
397 const isLate = lastResponseAt === undefined || now - lastResponseAt >= TTL_MS
398 if (isLate) return
399 // A handoff in place of compaction is running: the next main turn re-arms.
400 // Vetoed with no main turn running (the veto turn ended aborted) waits for
401 // the person, so the cache is kept warm as usual.
402 const isWaitingVeto = flowState === 'vetoed' && !isMainTurnRunning
403 if (isFlowActive() && !isWaitingVeto) return
404
405 if (pings < PINGS) {
406 pings += 1
407 $.ui.toast(`Keeping the prompt cache warm (${pings}/${PINGS})`)
408 const { drop } = await $.prompt.submit({ text: PING_TEXT }).catch(() => ({ drop: 'rejected' }))
409 // A person prompt during the submit owns the spell now.
410 if (spell !== armedSpell) return
411 if (!drop) return
412
413 // cold-cache's block reason, maybe behind an engine prefix: the cache is
414 // cold, so a handoff would pay the re-cache with nobody there.
415 if (drop.includes('Prompt cache expired:')) {
416 hasFired = true
417
418 return
419 }
420 }
421
422 hasFired = true
423 $.ui.toast('Idle: writing a handoff while the cache is warm')
424 isIdleHandoff = true
425 await $.command.run({ command: 'handoff', args: HANDOFF_ARGS }).catch(() => {
426 // No handoff turn follows: a later unrelated one must not continue.
427 isIdleHandoff = false
428 $.ui.toast('Idle: /handoff could not run')
429 })
430}
431
432// --- Handoff in place of auto-compaction: flow ---
433
434// Called from idle's turn.start hook (one registration per event per plugin).
435// A subagent's run raises no turn.start: every one here is a main turn.
436async function onTurnStart($: EngineInterface, e: TurnStartInput): Promise<void> {
437 isMainTurnRunning = true
438 // S5's fast fail, best effort: the engine may not show the args in e.text.
439 const isMarked = flowState === 'handing-off' && e.text.includes(MARKER)
440 if (isMarked) handoffTurnId = e.turnId
441}
442
443// Called from idle's turn.complete hook, for main and agent turns alike.
444async function onTurnComplete($: EngineInterface, e: TurnCompleteInput): Promise<void> {
445 if (e.agentId) {
446 answer($, e.agentId, e.answer)
447
448 return
449 }
450
451 isMainTurnRunning = false
452 const flow = flowId
453 // S4: the check settled during this turn; it may hand off now it has ended.
454 if (handOffFlow === flow) {
455 handOffFlow = undefined
456 $.clock.after(0, () => runHandoff($, flow))
457 }
458
459 if (flowState === 'handing-off') {
460 await findHandoffTurn($, e, flow).catch(() => fail($, flow))
461
462 return
463 }
464
465 // S2: a veto turn ending aborted, error or refusal waits for the next answer.
466 const isStart = e.reason === 'answer' && flowState === 'vetoed'
467 if (!isStart) return
468
469 // Now, not in check: a second answer turn before the tick starts no second check.
470 flowState = 'checking'
471 // agent.list and the sends wait for the tick: the turn is waiting on this hook.
472 $.clock.after(0, () => check($, flow).catch(() => fail($, flow)))
473 // FLOW_MS starts with the check, not the veto: a long veto turn outlives it.
474 const now = await $.clock.now()
475 if (flow !== flowId) return
476
477 deadline = now + FLOW_MS
478 $.clock.after(FLOW_MS, () => timeOut($, flow))
479}
480
481// Called from idle's session.end hook. S7: the mod's own /clear leaves the flow
482// to clearAndContinue; any other end (a person's /clear, the cold path's,
483// /resume, exit) cancels it, a failed one too.
484async function onSessionEnd($: EngineInterface, e: SessionEndInput): Promise<void> {
485 if (isOwnClear) return
486
487 reset('off')
488}
489
490// Any rejection after the veto: the next auto compaction runs.
491function fail($: EngineInterface, flow: number): void {
492 if (flow !== flowId) return
493
494 reset('failed')
495 $.ui.toast(FAILED_TOAST)
496}
497
498// One unattended continue per person prompt, for the idle path and for the
499// flow while idle.
500function isUnattendedAllowed(): boolean {
501 return unattended === 0
502}
503
504function isFlowActive(): boolean {
505 return ACTIVE.includes(flowState)
506}
507
508// Any error deciding fails open: compaction runs as it would without the mod.
509async function isVetoing($: EngineInterface, e: SessionCompactInput): Promise<boolean> {
510 try {
511 return await veto($, e)
512 } catch {
513 // Clearing: the old conversation may be gone; clearAndContinue owns the outcome.
514 if (flowState !== 'clearing') reset('failed')
515
516 return false
517 }
518}
519
520// S1: only the main conversation's auto compaction is ever vetoed.
521async function veto($: EngineInterface, e: SessionCompactInput): Promise<boolean> {
522 const isMainAuto = e.trigger === 'auto' && e.agentId === undefined
523 if (!isMainAuto) return false
524
525 // Reads first: no await after them, so the decision sees the current state.
526 const { context } = await $.session.usage({ breakdown: 'summary' })
527 const now = await $.clock.now()
528 // In use now, a paste since the last response included; context.tokens is
529 // only what the last response was answered over.
530 const tokens = context.breakdown?.totalTokens ?? context.tokens ?? 0
531 const isActive = isFlowActive()
532 const isTooLong = tokens >= WINDOW_SHARE * context.window
533 // deadline 0: still vetoed, no check yet, so only isTooLong ends the veto.
534 const isOverdue = isActive && deadline > 0 && now > deadline
535 // clearAndContinue owns the outcome: the old conversation may be gone already.
536 if (flowState === 'clearing') return !isTooLong
537
538 if (isTooLong || isOverdue) {
539 // Compaction runs now, so the next fill cycle's auto is vetoed again.
540 reset('off')
541
542 return false
543 }
544
545 if (flowState === 'failed') {
546 reset('off')
547
548 return false
549 }
550
551 if (isActive) return true
552
553 // An unattended continue came first and nothing is working: compaction runs,
554 // no second chain. The engine's idle compaction never fires mid-turn, and a
555 // ping's turn is no work; a long run's mid-turn compactions still hand off.
556 const isIdle = !isMainTurnRunning || pings > 0
557 if (isIdle && !isUnattendedAllowed()) return false
558
559 // No deadline yet: onTurnComplete starts it with the check.
560 flowState = 'vetoed'
561 idleVetoSeen = isIdle ? personSeen : undefined
562 $.ui.toast('Handing off instead of compacting')
563
564 return true
565}
566
567function timeOut($: EngineInterface, flow: number): void {
568 // Clearing: clearAndContinue owns the outcome, since the old conversation may
569 // be gone already. A clear that hangs still lets veto's isTooLong pass through.
570 if (flow !== flowId || flowState === 'clearing') return
571
572 reset('failed')
573 $.ui.toast('Handoff timed out; auto-compaction allowed again')
574}
575
576function reset(to: 'off' | 'failed'): void {
577 flowState = to
578 deadline = 0
579 asked.clear()
580 stopped = []
581 handoffTurnId = undefined
582 flowId += 1
583}
584
585// S3: ask each idle agent whether it is done; the answers arrive at answer().
586async function check($: EngineInterface, flow: number): Promise<void> {
587 if (flow !== flowId) return
588
589 const agents = await $.agent.list()
590 if (flow !== flowId) return
591
592 const idleAgents = agents.filter((agent) => agent.status === 'idle')
593 // All in asked before the first send: a reply may land while later sends run.
594 for (const agent of idleAgents) asked.set(agent.id, { agent })
595 if (idleAgents.length === 0) {
596 settle($)
597
598 return
599 }
600
601 $.clock.after(CHECK_MS, () => expire($, flow))
602 const reporters = idleAgents.filter((agent) => REPORT_TYPES.has(agent.type))
603 for (const agent of reporters) {
604 asked.set(agent.id, { agent, reply: 'report agent, stopped without a check' })
605 await stop($, flow, agent)
606 if (flow !== flowId) return
607 }
608
609 for (const agent of idleAgents.filter((agent) => !REPORT_TYPES.has(agent.type))) {
610 const sent = await $.session.send({ to: { agentId: agent.id }, text: DONE_CHECK })
611 if (flow !== flowId) return
612 if (!sent.isDelivered) keep($, agent.id, `not delivered: ${sent.reason}`)
613 }
614}
615
616// An asked agent's first reply: DONE stops it, anything else keeps it.
617function answer($: EngineInterface, agentId: string, reply: string): void {
618 const entry = asked.get(agentId)
619 const isOpen = entry !== undefined && entry.reply === undefined && entry.note === undefined
620 if (!isOpen || reply.trim() === '') return
621
622 const line = reply.trim().split('\n')[0].trim()
623 if (line.toUpperCase().startsWith('NOT DONE')) {
624 asked.set(agentId, { ...entry, reply, note: line.slice('NOT DONE'.length).replace(/^[\s:]+/, '') })
625 settle($)
626
627 return
628 }
629
630 // A bare DONE only: TaskStop can't be undone, and "Done with X; Y fails" is
631 // not done.
632 if (/^DONE[.!]?$/i.test(line)) {
633 asked.set(agentId, { ...entry, reply })
634 const flow = flowId
635 // The reply may come inside a hook the turn waits on.
636 $.clock.after(0, () => stop($, flow, entry.agent))
637
638 return
639 }
640
641 asked.set(agentId, { ...entry, reply, note: `unclear reply: ${line.slice(0, 80)}` })
642 settle($)
643}
644
645// An asked agent with no reply yet is kept with the note.
646function keep($: EngineInterface, agentId: string, note: string): void {
647 const entry = asked.get(agentId)
648 const isOpen = entry !== undefined && entry.reply === undefined && entry.note === undefined
649 if (!isOpen) return
650
651 asked.set(agentId, { ...entry, note })
652 settle($)
653}
654
655// A tool error, a refusal or a rejection keeps the agent with a note.
656async function stop($: EngineInterface, flow: number, agent: AgentInfo): Promise<void> {
657 if (flow !== flowId) return
658
659 const result = await $.tool.call({ tool: 'TaskStop', task_id: agent.id }).catch(() => undefined)
660 if (flow !== flowId) return
661
662 const isStopped = result !== undefined && !result.isError && result.deny === undefined
663 if (isStopped) {
664 stopped.push(agent)
665 } else {
666 const entry = asked.get(agent.id)
667 if (entry) asked.set(agent.id, { ...entry, note: 'stop failed' })
668 }
669 settle($)
670}
671
672// CHECK_MS after the first send, every agent still without a reply is kept.
673function expire($: EngineInterface, flow: number): void {
674 if (flow !== flowId) return
675
676 for (const agentId of asked.keys()) keep($, agentId, 'no answer to the done check')
677}
678
679// Runs after every change to asked or stopped. The one change that settles
680// the last agent hands off; asked keeps its notes for the /handoff args.
681function settle($: EngineInterface): void {
682 const isSettled = [...asked.values()].every((entry) => entry.note !== undefined || stopped.includes(entry.agent))
683 if (!isSettled || flowState !== 'checking') return
684
685 handOff($)
686}
687
688// S4, the state still checking. The settle may come inside a hook the turn
689// waits on, and a running main turn hands off only once it ends.
690function handOff($: EngineInterface): void {
691 const flow = flowId
692 if (isMainTurnRunning) {
693 handOffFlow = flow
694
695 return
696 }
697
698 $.clock.after(0, () => runHandoff($, flow))
699}
700
701async function runHandoff($: EngineInterface, flow: number): Promise<void> {
702 // A second settle before the tick runs no second /handoff.
703 if (flow !== flowId || flowState !== 'checking') return
704
705 flowState = 'handing-off'
706 try {
707 const agents = await $.agent.list()
708 if (flow !== flowId) return
709
710 await $.command.run({ command: 'handoff', args: handoffArgs(agents) })
711 } catch {
712 fail($, flow)
713 }
714}
715
716// The marker, the alive and ended agents from the re-read list plus every
717// stopped one (by id, once), then HANDOFF_ARGS.
718function handoffArgs(agents: AgentInfo[]): string {
719 const isStopped = (agent: AgentInfo): boolean => stopped.some((entry) => entry.id === agent.id)
720 const isListed = (agent: AgentInfo): boolean => agents.some((entry) => entry.id === agent.id)
721 const isAlive = (agent: AgentInfo): boolean => ALIVE_STATUSES.includes(agent.status) && !isStopped(agent)
722 const alive = agents.filter(isAlive)
723 const unlisted = stopped.filter((agent) => !isListed(agent))
724 const ended = agents.filter((agent) => !isAlive(agent)).concat(unlisted)
725 const aliveLines = alive.map(aliveLine)
726 const endedLines = ended.map((agent) => endedLine(agent, isStopped(agent)))
727 const listed = [ALIVE_HEADER, ...orNone(aliveLines), 'Ended agents:', ...orNone(endedLines)]
728 const lines = ended.length + alive.length > 0 ? listed : ['No agents.']
729
730 return [MARKER, ...lines, HANDOFF_ARGS].join('\n')
731}
732
733function aliveLine(agent: AgentInfo): string {
734 // || not ??: a bare NOT DONE leaves the note ''.
735 const note = asked.get(agent.id)?.note || '-'
736
737 return `${agent.id} · ${oneLine(agent.name ?? '') || '-'} · ${agent.type} · ${agent.status} · "${oneLine(agent.description)}" · ${note}`
738}
739
740function endedLine(agent: AgentInfo, isStopped: boolean): string {
741 // A stopped agent the list dropped, or still shows alive, reads stopped.
742 const status = isStopped && ALIVE_STATUSES.includes(agent.status) ? 'stopped' : agent.status
743 const line = `${agent.id} · ${agent.type} · ${status} · "${oneLine(agent.description)}"`
744
745 return isStopped ? `${line} · stopped by the handoff check` : line
746}
747
748// The handoff skill copies each agent line verbatim: a newline would split it.
749function oneLine(text: string): string {
750 return text.replace(/\s+/g, ' ').trim()
751}
752
753function orNone(lines: string[]): string[] {
754 return lines.length > 0 ? lines : ['none']
755}
756
757// S5: the first main answer turn whose reply names a fresh handoff file is the
758// handoff turn; a notice turn names none. The marked turn ending without one fails.
759async function findHandoffTurn($: EngineInterface, e: TurnCompleteInput, flow: number): Promise<void> {
760 const isMarked = e.turnId === handoffTurnId
761 // A person's prompt typed into the /handoff turn doesn't void its file.
762 const path = e.reason === 'answer' ? await freshHandoff($, e.answer, false) : undefined
763 if (flow !== flowId) return
764
765 if (path === undefined) {
766 if (isMarked) fail($, flow)
767
768 return
769 }
770
771 flowState = 'clearing'
772 const sessionId = await $.session.id()
773 if (flow !== flowId) return
774
775 const clearIfCurrent = async (): Promise<void> => {
776 if (flow === flowId) await clearAndContinue($, path, sessionId)
777 }
778 // The clear waits for the tick: the turn is waiting on this hook.
779 $.clock.after(0, clearIfCurrent)
780}
781
782// S6: the mod's own /clear, then the continue prompt as the user's own. Not
783// cleared → the full session stays, so the flow fails and the next auto runs.
784async function clearAndContinue($: EngineInterface, path: string, sessionId: string): Promise<void> {
785 const flow = flowId
786 const request = `Continue from the handoff in ${path}: read it, run its Verify command, then do its Next step.`
787 let isCleared = false
788 isOwnClear = true
789 try {
790 await $.command.run({ command: 'clear' })
791 // Its session.end has passed: a person's /clear from here cancels the flow.
792 isOwnClear = false
793 if (flow !== flowId) return
794
795 const clearedId = await $.session.id()
796 if (flow !== flowId) return
797 if (clearedId === sessionId) throw new Error('/clear kept the session')
798
799 isCleared = true
800 const { drop } = await $.prompt.submit({ asUser: true, text: request })
801 if (flow !== flowId) return
802 if (drop) throw new Error(drop)
803
804 if (idleVetoSeen === personSeen) unattended = 1
805 reset('off')
806 } catch {
807 if (flow !== flowId) return
808
809 // Cleared: the new session is small, so the flow ends off.
810 const failure = isCleared ? `Couldn't continue from the handoff` : FAILED_TOAST
811 reset(isCleared ? 'off' : 'failed')
812 $.ui.toast(`${failure}. To continue, paste: ${request}`)
813 } finally {
814 isOwnClear = false
815 }
816}
817