Reports Claude Code session activity to the Workbench desktop app

A desktop terminal manager built with Tauri v2 and Svelte 5. Add local project folders, and each project gets a tabbed workspace with real shell terminals, Claude Code + Codex integration, and git worktree support.
The public landing page lives in site/ and deploys to GitHub Pages. See landing page development.
Download the latest release from the Releases page:
Workbench_x.x.x_universal.dmgOpen the .dmg and drag Workbench to your Applications folder.
macOS is the primary target. Linux and Windows support is planned.
Workbench tracks Claude session activity with its own Claude Code plugin (plugins/workbench), which it loads into every Claude process it starts, so there's nothing to install. It isn't published as a marketplace plugin: Workbench always injects the current copy, and at startup uninstalls an older marketplace install (workbench@workbench) with claude plugin uninstall and claude plugin marketplace remove.
portable-pty + xterm.js~/.workbench/portable-pty (terminal emulation)bun install
bun run dev
This runs tauri dev, which starts the Vite dev server on port 1420 and opens the Tauri window.
| Command | Description |
|---|---|
bun install | Install dependencies |
bun run dev | Start dev server + Tauri window |
bun run build | Build production .app and .dmg |
bun run check | Run svelte-check type checking |
bun run lint | Run Prettier + ESLint checks |
bun run format | Auto-format with Prettier |
bun run test | Run all tests (frontend + Rust) |
bun run test:unit | Run frontend unit tests only |
bun run test:component | Run frontend component tests only |
Rust tests can be run separately:
cargo test --manifest-path src-tauri/Cargo.toml
src/ # Svelte frontend
lib/
components/ # Shared UI components (shadcn-svelte)
features/ # Feature modules (projects, workspaces, terminal, claude, worktrees)
stores/ # Svelte context-based stores
utils/ # Shared utilities
types/ # TypeScript type definitions
src-tauri/ # Rust backend
src/
commands.rs # Tauri IPC command handlers
config.rs # Project/workspace persistence
codex.rs # Codex session discovery and config
claude_sessions.rs # Claude session discovery and hooks
git.rs # Git CLI wrappers (branches, worktrees)
settings.rs # Claude Code settings CRUD
paths.rs # Path helpers and atomic file writes
This project is licensed under the GNU Affero General Public License v3.0.
hooks/register.ts 96 lines1import type { EngineInterface, Register } from 'claude-code';
2import {
3 noteBackgroundTasks,
4 notePermissionMode,
5 noteTitle,
6 promptTitle,
7 register as registerChat
8} from './chat';
9
10const REFRESH_TOOLS = new Set(['Bash', 'Write', 'Edit', 'NotebookEdit']);
11
12// How long a hook waits on the desktop's hook bridge, and how long it then
13// doesn't wait at all once the bridge didn't answer in time.
14const BRIDGE_MS = 3_000;
15const BRIDGE_PAUSE_MS = 30_000;
16let bridgeSlowUntil = 0;
17
18// Workbench sets both variables on every shell and chat process it starts;
19// outside Workbench they are unset and the plugin does nothing. The socket is
20// `host:port#secret`, the secret proving the post comes from a process
21// Workbench started. Awaiting the POST (the bridge answers once it has
22// handled the event) keeps events in order; the classic hooks it runs in gate
23// the prompt, and a `$` call doesn't spend their budget, so a hung fetch is
24// raced against a clock wait (which does, at most `BRIDGE_MS`); after one
25// that ran out, events are still sent but not waited on for a while, rather
26// than costing every prompt the wait.
27async function forward<R>(
28 $: EngineInterface,
29 e: { permission_mode?: string; [field: string]: unknown },
30 next: () => Promise<R>
31): Promise<R> {
32 notePermissionMode(e.permission_mode);
33 const socket = await $.env.get('WORKBENCH_HOOK_SOCKET');
34 const paneId = await $.env.get('WORKBENCH_PANE_ID');
35 if (socket && paneId) {
36 const [address, secret = ''] = socket.split('#');
37 const post = $.http
38 .fetch(`http://${address}/hook`, {
39 method: 'POST',
40 headers: { 'content-type': 'application/json', 'x-workbench-hook-secret': secret },
41 body: JSON.stringify({ pane_id: paneId, hook: e })
42 })
43 .then(
44 () => true,
45 () => true
46 );
47 if (Date.now() >= bridgeSlowUntil) {
48 const waited = new AbortController();
49 const answered = await Promise.race([
50 post,
51 $.clock.sleep(BRIDGE_MS, { signal: waited.signal }).then(
52 () => false,
53 () => true
54 )
55 ]);
56 waited.abort();
57 if (!answered) bridgeSlowUntil = Date.now() + BRIDGE_PAUSE_MS;
58 }
59 }
60 return next();
61}
62
63export const register: Register = (on, options) => {
64 registerChat(on, options);
65 // Both carry the session's title: a generated one reaches chat at the next prompt.
66 on('classic.SessionStart', ($, e, next) => {
67 noteTitle(e.session_title);
68 return forward($, e, () => next(e));
69 });
70 on('classic.UserPromptSubmit', ($, e, next) => {
71 const generated = promptTitle(e.session_title);
72 return forward($, e, async () => {
73 const result = await next(e);
74 return generated ? { ...result, sessionTitle: generated } : result;
75 });
76 });
77 on('classic.Stop', ($, e, next) => {
78 noteBackgroundTasks(e.background_tasks);
79 return forward($, e, () => next(e));
80 });
81 // Approvals and MCP forms reach both devices through the mod link (the
82 // desktop isn't sent Notification).
83 on('classic.Notification', ($, e, next) => {
84 notePermissionMode(e.permission_mode);
85 return next(e);
86 });
87 // The bridge only needs the tool and a Bash command; a Write's input and any
88 // tool's response can be whole files.
89 on('classic.PostToolUse', ($, e, next) => {
90 if (!REFRESH_TOOLS.has(e.tool_name)) return next(e);
91 const command = (e.tool_input as { command?: unknown } | undefined)?.command;
92 const { tool_response: _response, ...rest } = e;
93 return forward($, { ...rest, tool_input: { command } }, () => next(e));
94 });
95};
96hooks/chat.ts 1426 lines1import type {
2 PermissionRequestDecision,
3 PromptSubmitResult,
4 Register,
5 TurnStepInput
6} from 'claude-code';
7import * as server from './link';
8import { PendingAsks } from './asks';
9import { notifiedJobs, startJob, stoppedJobs } from './jobs';
10import { RUN_TOOL_SPEC, runInput, runResult } from './run';
11import { Titles, TITLE_SYSTEM } from './titles';
12import {
13 askLine,
14 attachedFiles,
15 commandRowOutput,
16 KEEPALIVE_PROMPT,
17 midTurn,
18 modelOption,
19 promptText,
20 QUEUED_NUDGE,
21 QUEUED_PREFIX,
22 rateLimitLine,
23 slimResult,
24 slashCommand,
25 withAttachments,
26 type Line
27} from './lines';
28
29// Runs this interactive `claude` as a Workbench chat too: what `claude -p`
30// would print as stream-json is posted to the server (`/mod/out`), and what it
31// would read is long-polled (`/mod/in`), so the chat view and the terminal are
32// one process. Workbench sets both variables on terminal shells it starts;
33// outside Workbench the module does nothing.
34
35const { emit } = server;
36
37let polling = false;
38let model = '';
39// The model and effort last reported, so a change is sent once.
40let lastSettings = '';
41// The live permission mode, and the one the chat was last told.
42let liveMode: string | undefined;
43let reportedMode = '';
44// Minted ids carry this load's own prefix: Claude Code reloads a plugin
45// mid-session (its files change, a worktree switch), and a restarted count
46// alone would mint ids the session already used, replacing those chat items.
47const load = Math.random().toString(36).slice(2, 8);
48let messageSeq = 0;
49let currentMessage = '';
50const startedBlocks = new Set<number>();
51let askSeq = 0;
52// Effort picked in chat; applied to each main-thread model request until the
53// TUI picks another, which then wins as the later pick does in the TUI.
54let effort: TurnStepInput['effort'];
55// The effort the engine resolved on its own when the chat's was applied first.
56let effortBase: { value: TurnStepInput['effort'] } | undefined;
57// Model picked in chat, for this session only: the resolved id each
58// main-thread request names, the pick as the chat shows it, the effort levels
59// that model takes (absent: unknown), and the model the engine names on its
60// own (`base`, from the first request after the pick). A request naming
61// another (a fallback) keeps it. A pick in the TUI (`/model`, `/config`) clears it.
62let modelPick: { id: string; choice: string; effortLevels?: string[]; base?: string } | undefined;
63// The slash commands the chat was last sent, to send a changed list once.
64let commandList = '';
65// The session title the chat was last sent.
66let title: string | undefined;
67const titles = new Titles();
68// The running turn answers the server's cache keep-alive: its reply names nothing.
69let keepAliveTurn = false;
70// The running main-thread turn, for an interrupt from chat.
71let runningTurn: string | undefined;
72// The live model's context window, from the latest measurement.
73let contextWindow: number | undefined;
74// The window the chat was last sent outside a `result`; a model switch
75// clears the chat's, so it's sent again.
76let sentWindow: number | undefined;
77// Why the last turn failed (StopFailure), and the id of the `result` that
78// reported it, whose notice takes the reason when StopFailure comes after.
79let failure: string | undefined;
80let failedResult: string | undefined;
81// The parts of tool results the transcript row doesn't carry (an edit's patch,
82// an Artifact's link), by call id, until the row and the result have met.
83const toolResults = new Map<string, Line>();
84const toolRows = new Map<string, Line>();
85const callsRunning = new Set<string>();
86const TOOL_RESULTS_KEPT = 50;
87// Main-thread Agent calls still running (task ids = tool call ids); progress
88// goes to the only one when a subagent wasn't linked.
89const runningAgents = new Set<string>();
90// Running subagents: agent id <-> task id, for progress and their output file.
91const agentTasks = new Map<string, string>();
92const taskAgents = new Map<string, string>();
93// Background agents: their Agent call returned at launch, so their own
94// `turn.complete` ends the task.
95const asyncAgents = new Set<string>();
96// Teammates (a named Agent call) idle after each turn until a message wakes
97// them: each turn's end ends the task, and the next turn's start resumes it.
98const teammates = new Set<string>();
99// Agents whose task this load ended itself: their notification, which comes
100// after, isn't reported again (the oldest are forgotten).
101const endedAgents = new Set<string>();
102const ENDED_AGENTS_KEPT = 200;
103// Background agents the chat's Stop asked to end. No call stops one, so each ends
104// at its next model request or tool call (`endedByStop`), and then its "finished"
105// notification starts no turn. One that answered first keeps its notification.
106const stoppedAgents = new Set<string>();
107const endedByStop = new Set<string>();
108// Main-thread Skill calls still running: call id → the skill and the agents
109// there were before it. A forked skill's agent has no `agent.spawn`: the first
110// call of an agent new since then names it, and its Skill call is its task.
111const runningSkills = new Map<string, { skill: string; before: Set<string> }>();
112// Whether the latest prompt came from a chat: what it asks waits for a chat's
113// answer even before one has it open (a phone in the background).
114let chatTurn = false;
115// Marks a turn this plugin submits for the chat as the chat's: its own
116// `prompt.submit` hook doesn't see the submit it raises. A refused one isn't.
117// Chat prompts submitted whose turn hasn't started yet.
118let submitting = 0;
119const chatSubmit = (submitted: Promise<PromptSubmitResult>) => {
120 submitting++;
121 return submitted
122 .then((r) => {
123 if (r.drop === undefined) chatTurn = true;
124 return r;
125 })
126 .finally(() => submitting--);
127};
128// The chat's latest command: whether it started a turn or compaction or got its
129// `result` (`answered`), and whether `$.command.run` has resolved (`settled`).
130type ChatCommand = { answered: boolean; settled: boolean };
131let chatCommand: ChatCommand | undefined;
132const PANEL_WAIT_MS = 3000;
133/** How long Send now waits for the turn to end before sending into it anyway. */
134const SEND_NOW_ABORT_MS = 3000;
135/** The turn Send now is ending: its end sends no `result`, so the chat stays busy into the next. */
136let replacing: string | undefined;
137/** A replaced turn's `result` is owed until the next turn starts. */
138let owedResult = false;
139/** Send now's abort and prompt, which later chat prompts wait behind. */
140let sendingNow: Promise<void> | undefined;
141/** A turn Send now's abort didn't end in time: the prompt went into it, so its end answers it. */
142let sentInto: string | undefined;
143const LIVE_AGENT = new Set(['pending', 'running', 'waiting']);
144// Chat prompts appended into the running turn that no request has read yet.
145let injected: string[] = [];
146// Prompts the plugin submitted itself, kept out of the chat (each echoes once).
147const echoed = new Set<string>();
148// What the latest command printed, through its `text` or its transcript row,
149// whichever came first: the other isn't shown again.
150const printed = new Set<string>();
151
152// A question is asked from `tool.call` and its answer is the call's result:
153// since 2.1.292 a plugin's `allow` doesn't dismiss the dialog of a tool that
154// requires the person. A plan is approved in the terminal (PermissionRequest).
155const ASKED_IN_CALL = 'AskUserQuestion';
156// `mcp__<plugin>__run_in_terminal`, once registered (`run.ts`).
157let runTool: string | undefined;
158const pendingAsks = new PendingAsks();
159// Approvals the terminal's own dialog asks (no chat was open): tool call id →
160// request id, and whether the main thread asked it (a background agent's
161// outlives the turn).
162const askedInTerminal = new Map<string, { requestId: string; main: boolean }>();
163// MCP elicitations the terminal shows, by server and elicitation id, oldest first.
164const terminalElicitations = new Map<string, string[]>();
165// Model switches the person made (`/model`, `/config`, the chat's pick); an
166// automatic fallback or a resume keeps the pick the chat shows.
167const PICKED_MODEL = new Set(['command', 'picker', 'sdk']);
168
169// Without `model`: the TUI names the bare id, and resending it would drop
170// the `[1m]` the chat's model carries.
171function sendWindow(window: number | undefined) {
172 if (window === undefined || window === sentWindow) return;
173 sentWindow = window;
174 emit({ type: 'system', subtype: 'init', contextWindow: window });
175}
176
177function reply(requestId: unknown, error?: string, response: Line = {}) {
178 emit({
179 type: 'control_response',
180 response: error
181 ? { subtype: 'error', request_id: requestId, error }
182 : { subtype: 'success', request_id: requestId, response }
183 });
184}
185
186/**
187 * A chat prompt that started no turn: the chat shows why and goes idle. Mid-turn
188 * (a turn typed at the terminal) that turn's own `result` ends the wait.
189 */
190function promptFailed(why: string) {
191 const uuid = `wbmod-failed-${load}-${++askSeq}`;
192 if (!runningTurn) emit({ type: 'result', subtype: 'error', is_error: true, result: why, uuid });
193 else emit({ type: 'system', subtype: 'local_command_output', content: why, uuid });
194}
195
196function linkAgent(agent: string, task: string) {
197 agentTasks.set(agent, task);
198 taskAgents.set(task, agent);
199}
200
201// What a command printed, and the agents it started (a forked skill's has no
202// `agent.spawn`): each joins the tasks panel, and its own `turn.complete` ends it.
203function commandRan(
204 command: string,
205 args: string,
206 text: string | undefined,
207 agents: readonly {
208 id: string;
209 parentId?: string;
210 description?: string;
211 type?: string;
212 status: string;
213 }[],
214 before: Set<string>
215) {
216 for (const agent of agents) {
217 // A finished one is a turn's that ran while the command waited, not the command's.
218 if (before.has(agent.id) || agent.parentId || agentTasks.has(agent.id)) continue;
219 if (!LIVE_AGENT.has(agent.status)) continue;
220 linkAgent(agent.id, agent.id);
221 asyncAgents.add(agent.id);
222 emit(
223 {
224 type: 'system',
225 subtype: 'task_started',
226 task_id: agent.id,
227 description: agent.description || `/${command}`,
228 subagent_type: agent.type,
229 task_type: 'local_agent',
230 is_backgrounded: true,
231 uuid: `wbmod-task-${agent.id}`
232 },
233 {
234 type: 'system',
235 subtype: 'task_updated',
236 task_id: agent.id,
237 output_id: agent.id,
238 uuid: `wbmod-task-out-${agent.id}`
239 }
240 );
241 }
242 // Written to the JSONL only: the chat would see it on its next load.
243 if (command === 'rename') noteTitle(args);
244 if (text !== undefined) printOnce(text);
245}
246
247function printOnce(text: string) {
248 const key = text.trim();
249 if (printed.has(key)) return;
250 printed.add(key);
251 commandOutput(text);
252}
253
254function commandOutput(content: string, inTerminal = false) {
255 emit({
256 type: 'system',
257 subtype: 'local_command_output',
258 content,
259 ...(inTerminal && { workbench_in_terminal: true }),
260 uuid: `wbmod-command-${load}-${++askSeq}`
261 });
262}
263
264// The `result` a chat's command that ran no turn ends with, once.
265function answerCommand(command: ChatCommand, failed = false) {
266 command.answered = true;
267 emit(
268 failed
269 ? { type: 'result', subtype: 'error_during_execution', is_error: true }
270 : { type: 'result', subtype: 'success', is_error: false }
271 );
272}
273
274function startSkillTask(task: string, agent: string) {
275 linkAgent(agent, task);
276 emit(
277 {
278 type: 'system',
279 subtype: 'task_started',
280 task_id: task,
281 tool_use_id: task,
282 description: `/${runningSkills.get(task)?.skill ?? 'skill'}`,
283 task_type: 'local_agent',
284 uuid: `wbmod-task-${task}`
285 },
286 {
287 type: 'system',
288 subtype: 'task_updated',
289 task_id: task,
290 output_id: agent,
291 uuid: `wbmod-task-out-${task}`
292 }
293 );
294}
295
296function unlinkTask(task: string) {
297 const agent = taskAgents.get(task);
298 taskAgents.delete(task);
299 if (agent) {
300 asyncAgents.delete(agent);
301 teammates.delete(agent);
302 endedAgents.add(agent);
303 if (endedAgents.size > ENDED_AGENTS_KEPT)
304 endedAgents.delete(endedAgents.values().next().value!);
305 }
306 // The task's own agent and any it spawned (see `agent.spawn`).
307 for (const [a, t] of agentTasks) if (t === task) agentTasks.delete(a);
308}
309
310const elicitationKey = (e: { mcp_server_name: string; elicitation_id?: string }) =>
311 `${e.mcp_server_name}\0${e.elicitation_id ?? ''}`;
312
313/**
314 * The session's live permission mode, from a classic hook's input: the
315 * `/config` row holds only the settings default (`defaultMode`), not a mode
316 * the session was launched in or switched to.
317 */
318export function notePermissionMode(mode: string | undefined) {
319 if (!mode) return;
320 liveMode = mode;
321 if (!server.current() || mode === reportedMode) return;
322 reportedMode = mode;
323 emit({ type: 'permission-mode', permissionMode: mode });
324}
325
326/** Report background jobs that finished; called from the Stop hook with its job list. */
327export function noteBackgroundTasks(tasks: readonly { id: string; status: string }[] = []) {
328 if (server.current()) emit(...stoppedJobs(tasks));
329}
330
331/**
332 * The session's title (a `/rename`, or the generated one) as a hook input
333 * carries it; the chat folds it as the JSONL's rename.
334 */
335export function noteTitle(next: string | undefined) {
336 const trimmed = next?.trim();
337 if (!trimmed || trimmed === title || !server.current()) return;
338 title = trimmed;
339 emit({ type: 'custom-title', customTitle: trimmed });
340}
341
342/**
343 * The title for a prompt's `sessionTitle`: one generated since the last prompt
344 * (shown in chat at once, made the engine's own here), else the engine's.
345 */
346export function promptTitle(current: string | undefined): string | undefined {
347 const generated = titles.takePending();
348 noteTitle(generated ?? current);
349 return generated;
350}
351
352function commandsLine(commands: readonly { name: string; description: string }[]) {
353 const list = commands.map((c) => ({ name: c.name, description: c.description }));
354 const text = JSON.stringify(list);
355 if (text === commandList) return undefined;
356 commandList = text;
357 return { type: 'workbench_commands', commands: list };
358}
359
360export const register: Register = (on) => {
361 on('session.start', async ($, e, next) => {
362 const result = await next(e);
363 const url = await $.env.get('WORKBENCH_MOD_URL');
364 const token = await $.env.get('WORKBENCH_MOD_TOKEN');
365 if (!url || !token) return result;
366 const sessionId = await $.session.id();
367 model = await $.session.model();
368 // Set for this process only: a hot reload finds it, a new `claude` doesn't,
369 // so the server can tell the two apart.
370 let process = await $.env.get('WORKBENCH_MOD_PROCESS').catch(() => undefined);
371 if (!process) {
372 const minted = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
373 process = await $.env.set('WORKBENCH_MOD_PROCESS', minted).then(
374 // Since 2.1.301 a refused write resolves `{ deny }` instead of rejecting.
375 (r) => (r?.deny ? undefined : minted),
376 () => undefined
377 );
378 }
379 server.open({ url, token, sessionId, process });
380 runTool = (await $.tool.register(RUN_TOOL_SPEC).catch(() => undefined))?.tool;
381 const fetch = (u: string, i: Parameters<typeof $.http.fetch>[1]) => $.http.fetch(u, i);
382 const after: server.After = (ms, fn) => $.clock.after(ms, fn);
383 // Bounded: `claude` waits on this hook before its first prompt. A failed
384 // hello (the server is down, or another terminal still holds the session)
385 // is said again from the timer below, so the session still becomes a chat.
386 await server.attach(fetch, false, after);
387
388 // A chat prompt. A plugin's submit waits for the turn to end, so
389 // mid-turn it joins the running turn the way a typed prompt would.
390 const chatPrompt = async (line: Line, sentNow = false) => {
391 const message = line.message as { content?: unknown } | undefined;
392 const text = promptText(message?.content);
393 const files = attachedFiles(line);
394 if (!text) return;
395 if (sendingNow && !sentNow) await sendingNow;
396 // Send now (the TUI's ctrl+enter): the running turn ends, its running
397 // Bash moves to the background, and this prompt (or command) comes next.
398 // The abort runs off the poll loop, which answers approvals and stops;
399 // a prompt sent meanwhile waits behind it.
400 if (line.workbench_now === true && runningTurn !== undefined) {
401 const turnId = runningTurn;
402 replacing = turnId;
403 const after = { ...line, workbench_now: false };
404 sendingNow = (async () => {
405 await Promise.race([
406 $.turn.abort({ turnId }).catch(() => {}),
407 $.clock.sleep(SEND_NOW_ABORT_MS)
408 ]);
409 // Still running: it ends on its own, with its own `result`, and
410 // this prompt joins it as any mid-turn prompt does. The abort may
411 // still land: that end then asks for this prompt's answer.
412 if (replacing === turnId) {
413 replacing = undefined;
414 sentInto = turnId;
415 }
416 await chatPrompt(after, true);
417 })().finally(() => (sendingNow = undefined));
418 return;
419 }
420 // A plugin's submit refuses a leading `/`, so a known command runs as one
421 // (queued until idle); `/tmp is full` stays a prompt. A command that starts
422 // no turn (a forked skill, `/rename`) resolves to nothing for the model, so
423 // the chat gets its `result` here; a prompt-type one's turn ends with its own.
424 const slash = slashCommand(text);
425 if (slash && (await $.command.list()).some((c) => c.name === slash.command)) {
426 const before = new Set((await $.agent.list()).map((a) => a.id));
427 const command: ChatCommand = { answered: false, settled: false };
428 chatCommand = command;
429 printed.clear();
430 // Queued behind a turn typed at the terminal, it isn't that turn's to ask for.
431 if (!runningTurn) chatTurn = true;
432 const idle = (async () => {
433 while (runningTurn) await $.clock.sleep(250);
434 })();
435 const args = withAttachments(slash.args, files);
436 void $.command.run({ command: slash.command, args }).then(
437 async (result) => {
438 command.settled = true;
439 if (!server.current()) return;
440 await server.rekey(() => $.session.id());
441 commandRan(slash.command, slash.args, result.text, await $.agent.list(), before);
442 if (slash.command === 'rename' && slash.args.trim())
443 await titles.nameByPerson({
444 get: (k) => $.store.get(k),
445 set: (k, v) => $.store.set(k, v)
446 });
447 // Notes for the model may start a turn a moment later (`/goal`),
448 // whose `result` ends the command; a `/rename`'s start none.
449 for (let i = 0; result.context?.length && i < 4; i++) {
450 if (command.answered || runningTurn) break;
451 await $.clock.sleep(250);
452 }
453 if (!command.answered && !runningTurn) answerCommand(command);
454 },
455 (err: unknown) => {
456 command.settled = true;
457 if (!server.current()) return;
458 commandOutput(`/${slash.command} failed: ${String(err)}`);
459 if (!command.answered) answerCommand(command, true);
460 }
461 );
462 // A panel (`/usage`, `/config`) resolves only once it's closed in the TUI,
463 // and nothing tells it from a slow command: the chat is told where it is.
464 void (async () => {
465 await idle;
466 await $.clock.sleep(PANEL_WAIT_MS);
467 if (command.settled || command.answered || runningTurn || !server.current()) return;
468 commandOutput(
469 `/${slash.command} opened in the terminal: switch to Terminal to use or close it.`,
470 true
471 );
472 answerCommand(command);
473 })();
474 return;
475 }
476 // The running turn keeps the cache warm itself, and a keep-alive put
477 // into it would hide its reply: its `result` ends the chat's wait.
478 if (text === KEEPALIVE_PROMPT && runningTurn) return;
479 const appended = runningTurn
480 ? await $.session
481 .append({
482 message: { type: 'user', content: [{ type: 'text', text: midTurn(text, files) }] }
483 })
484 .catch((err: unknown) => ({ deny: String(err) }))
485 : undefined;
486 if (appended && !appended.deny && runningTurn) {
487 injected.push(text);
488 emit({
489 type: 'user',
490 uuid: `wbmod-queued-${load}-${++askSeq}`,
491 workbench_queued: true,
492 session_id: server.current()?.sessionId,
493 message: { role: 'user', content: text }
494 });
495 } else {
496 // Refused (a hook's drop) or failed: no turn starts, so none ends the
497 // chat's wait. A replaced turn sent no `result` either; it's owed now.
498 const refused = (why: string) => {
499 if (owedResult && !runningTurn) owedResult = false;
500 promptFailed(why);
501 };
502 // Not awaited: it resolves when its turn starts, and polling must go
503 // on meanwhile (approval answers, interrupts).
504 void chatSubmit($.prompt.submit({ text: withAttachments(text, files), asUser: true })).then(
505 (r) => r.drop !== undefined && refused(r.drop || 'The prompt was not sent.'),
506 (err: unknown) => refused(`The prompt was not sent: ${String(err)}`)
507 );
508 }
509 };
510
511 const controlRequest = async (line: Line) => {
512 const req = (line.request ?? {}) as {
513 subtype?: string;
514 model?: string;
515 resolvedModel?: string;
516 effortLevels?: string[];
517 settings?: { effortLevel?: string };
518 };
519 const sub = req.subtype;
520 if (sub === 'interrupt') {
521 if (runningTurn) await $.turn.abort({ turnId: runningTurn }).catch(() => {});
522 // No turn runs or is about to (the chat lost track, or this load never
523 // saw it start): Stop still ends the chat's wait.
524 else if (submitting === 0) emit({ type: 'result', subtype: 'success', is_error: false });
525 // A background agent, and the agents it spawned.
526 for (const agent of await $.agent.list().catch(() => [])) {
527 const task = agentTasks.get(agent.id);
528 const root = task && taskAgents.get(task);
529 if (root && asyncAgents.has(root) && LIVE_AGENT.has(agent.status))
530 stoppedAgents.add(agent.id);
531 }
532 reply(line.request_id);
533 } else if (sub === 'initialize') {
534 // A fallback list: the server replaces it with the CLI's own.
535 const row = (await $.config.list()).find((r) => r.key === 'model');
536 const models = (row?.options ?? []).map(modelOption);
537 const commands = (await $.command.list()).map((c) => ({
538 name: c.name,
539 description: c.description
540 }));
541 commandList = JSON.stringify(commands);
542 const modelChoice =
543 modelPick?.choice ?? (typeof row?.value === 'string' ? row.value : undefined);
544 reply(line.request_id, undefined, { models, commands, modelChoice });
545 } else if (sub === 'set_model' && req.model) {
546 // `turn.step` takes an id, not an alias: the server resolves the pick.
547 if (!req.resolvedModel) {
548 reply(line.request_id, `Model: ${req.model} isn't in Claude's model list.`);
549 return;
550 }
551 modelPick = { id: req.resolvedModel, choice: req.model, effortLevels: req.effortLevels };
552 model = req.resolvedModel;
553 sentWindow = undefined;
554 reply(line.request_id);
555 emit({ type: 'system', subtype: 'init', model, modelChoice: req.model });
556 } else if (sub === 'apply_flag_settings' && req.settings?.effortLevel) {
557 effort = req.settings.effortLevel as TurnStepInput['effort'];
558 effortBase = undefined;
559 reply(line.request_id);
560 } else {
561 reply(line.request_id, `${sub ?? 'This'} isn't available in a terminal session yet.`);
562 }
563 };
564
565 $.clock.every(50, () => {
566 server.tick();
567 if (!server.isFlushing()) void server.flush(fetch);
568 });
569 $.clock.every(300, () => {
570 if (polling || !server.current()) return;
571 polling = true;
572 void (async () => {
573 await server.rekey(() => $.session.id());
574 if (server.hello.needed) {
575 if (Date.now() - server.hello.last < server.HELLO_EVERY_MS) return;
576 if (await server.attach(fetch, true, after)) await reattached();
577 return;
578 }
579 for (const line of await server.poll(fetch)) {
580 try {
581 if (line.type === 'user') await chatPrompt(line);
582 else if (line.type === 'control_request') await controlRequest(line);
583 } catch (err) {
584 // Not run again: a line that fails would fail every time. The chat
585 // hears why, rather than wait on a turn that never starts.
586 if (line.type === 'user')
587 promptFailed(`Workbench couldn't send the prompt: ${String(err)}`);
588 else if (line.type === 'control_request') reply(line.request_id, String(err));
589 } finally {
590 server.handled(line);
591 }
592 }
593 })()
594 .catch(() => {})
595 .finally(() => (polling = false));
596 });
597
598 // The server lost the session and loaded it again from its file: what it
599 // was told outside the history is told again.
600 const reattached = async () => {
601 lastSettings = '';
602 reportedMode = '';
603 sentWindow = undefined;
604 notePermissionMode(liveMode);
605 if (title) emit({ type: 'custom-title', customTitle: title });
606 // A restarted server has no plan usage reading until a window moves.
607 const usage = await $.session.usage().catch(() => undefined);
608 const limits = usage && rateLimitLine(usage.rateLimits);
609 if (limits) emit(limits);
610 sendWindow(contextWindow ?? usage?.context.window);
611 };
612
613 // No hook has named the live mode yet: the one Workbench started `claude`
614 // in beats the settings default.
615 liveMode ??= (await $.env.get('WORKBENCH_PERMISSION_MODE')) || undefined;
616 const rows = await $.config.list().catch(() => []);
617 const configMode = rows.find((r) => r.key === 'permissionMode')?.value;
618 const permissionMode = liveMode ?? (typeof configMode === 'string' ? configMode : undefined);
619 reportedMode = permissionMode ?? '';
620 emit({ type: 'system', subtype: 'init', session_id: sessionId, model, permissionMode });
621 const usage = await $.session.usage().catch(() => undefined);
622 const limits = usage && rateLimitLine(usage.rateLimits);
623 if (limits) emit(limits);
624 // A measurement taken meanwhile is newer.
625 contextWindow ??= usage?.context.window;
626 sentWindow = undefined;
627 sendWindow(contextWindow);
628 return result;
629 });
630
631 on('session.end', async ($, e, next) => {
632 const link = server.current();
633 if (link && (e.reason === 'clear' || e.reason === 'resume')) {
634 server.expectRekey(e.reason);
635 titles.reset();
636 for (const task of [...taskAgents.keys()]) unlinkTask(task);
637 stoppedAgents.clear();
638 endedByStop.clear();
639 return next(e);
640 }
641 if (link) {
642 // One request, inside the short bound an exit gets.
643 const bye = server.init('POST', server.takeOutbox());
644 server.open(null);
645 const left = Math.max(0, next.budget.remainingMs - 100);
646 await Promise.race([
647 (async () => {
648 await server.flush((u, i) => $.http.fetch(u, i));
649 await $.http.fetch(`${link.url}/mod/bye`, bye).catch(() => {});
650 })(),
651 $.clock.sleep(left)
652 ]);
653 }
654 return next(e);
655 });
656
657 on('session.measure', ($, e, next) => {
658 if (server.current()) {
659 contextWindow = e.context.window;
660 sendWindow(contextWindow);
661 const limit = e.changed.includes('rateLimits') ? rateLimitLine(e.rateLimits) : undefined;
662 if (limit) emit(limit);
663 }
664 return next(e);
665 });
666
667 // Subagents' and teammates' turns raise it too (CLI 2.1.299+), with an
668 // `agentId`: only the main thread's turn is the chat's. Commands come and go
669 // (a plugin or skill loaded), so the chat's list is re-read here.
670 on('turn.start', async ($, e, next) => {
671 if (e.agentId) {
672 const task = teammates.has(e.agentId) ? agentTasks.get(e.agentId) : undefined;
673 if (task && server.current())
674 emit({
675 type: 'system',
676 subtype: 'task_updated',
677 task_id: task,
678 patch: { status: 'running' },
679 uuid: `wbmod-task-wake-${load}-${++askSeq}`
680 });
681 return next(e);
682 }
683 runningTurn = e.turnId;
684 owedResult = false;
685 // A prompt-type command's turn ends with its own `result`.
686 if (chatCommand) chatCommand.answered = true;
687 failure = undefined;
688 failedResult = undefined;
689 const result = await next(e);
690 const commands = server.current() ? commandsLine(await $.command.list()) : undefined;
691 if (commands) emit(commands);
692 return result;
693 });
694
695 on('turn.step', async function* ($, e, next) {
696 if (e.agentId && stoppedAgents.has(e.agentId)) {
697 endedByStop.add(e.agentId);
698 return {
699 turnId: e.turnId,
700 index: e.index,
701 answer: '',
702 toolUses: [],
703 stopReason: 'end_turn',
704 usage: null
705 };
706 }
707 if (!server.current() || e.agentId) return yield* next(e);
708 await server.rekey(() => $.session.id());
709 const sessionId = server.current()?.sessionId ?? '';
710 // This request carries every row appended so far.
711 if (injected.length > 0) emit({ type: 'workbench_queued_read' });
712 injected = [];
713 // The TUI picked another effort: the chat's is dropped (and the server forgets it).
714 let effortCleared = false;
715 if (effort) {
716 if (!effortBase) effortBase = { value: e.effort };
717 else if (e.effort !== effortBase.value) {
718 effort = effortBase = undefined;
719 effortCleared = true;
720 }
721 }
722 if (modelPick && modelPick.base === undefined) modelPick.base = e.model;
723 const pick = modelPick && e.model === modelPick.base ? modelPick : undefined;
724 // What this request really runs with: the engine resolved both. A picked
725 // model that doesn't take the effort goes without.
726 let sent = effort ?? e.effort;
727 if (pick?.effortLevels && !(typeof sent === 'string' && pick.effortLevels.includes(sent)))
728 sent = undefined;
729 const step = { ...e, ...(pick ? { model: pick.id } : {}) };
730 if (sent !== e.effort) step.effort = sent;
731 const stream = next(step);
732 currentMessage = `wbmod-${sessionId.slice(0, 8)}-${load}-${++messageSeq}`;
733 startedBlocks.clear();
734 model = step.model || model;
735 const settings = `${model} ${sent ?? ''}`;
736 if (settings !== lastSettings) {
737 lastSettings = settings;
738 emit({
739 type: 'system',
740 subtype: 'init',
741 model,
742 // `null`: this model runs without effort.
743 effort: typeof sent === 'string' ? sent : null,
744 ...(effortCleared ? { effortCleared } : {})
745 });
746 }
747 emit({
748 type: 'stream_event',
749 event: { type: 'message_start', message: { id: currentMessage, model } }
750 });
751 for await (const chunk of stream) {
752 if (chunk.kind === 'text' || chunk.kind === 'thinking') {
753 if (!startedBlocks.has(chunk.index)) {
754 startedBlocks.add(chunk.index);
755 emit({
756 type: 'stream_event',
757 event: {
758 type: 'content_block_start',
759 index: chunk.index,
760 content_block: { type: chunk.kind, text: '' }
761 }
762 });
763 }
764 emit({
765 type: 'stream_event',
766 event: {
767 type: 'content_block_delta',
768 index: chunk.index,
769 delta:
770 chunk.kind === 'text'
771 ? { type: 'text_delta', text: chunk.text }
772 : { type: 'thinking_delta', thinking: chunk.text }
773 }
774 });
775 } else if (chunk.kind === 'tool') {
776 emit({
777 type: 'stream_event',
778 event: {
779 type: 'content_block_start',
780 index: chunk.index,
781 content_block: { type: 'tool_use', id: chunk.id, name: chunk.name, input: {} }
782 }
783 });
784 } else if (chunk.kind === 'stop') {
785 if (chunk.usage?.model) model = chunk.usage.model;
786 // The response's rows were appended block by block before its usage
787 // was known: the context size and cache timer read it from here.
788 if (chunk.usage)
789 emit({
790 type: 'assistant',
791 uuid: `${currentMessage}-usage`,
792 session_id: sessionId,
793 message: { id: currentMessage, model, content: [], usage: chunk.usage }
794 });
795 }
796 yield chunk;
797 }
798 return stream.result;
799 });
800
801 on('session.append', async ($, e, next) => {
802 const m = e.message;
803 if (!server.current() || e.agentId) return next(e);
804 await server.rekey(() => $.session.id());
805 const sessionId = server.current()?.sessionId;
806 if (!sessionId) return next(e);
807 if (m.type === 'attachment' && m.name === 'goal_status') {
808 // The hook's view has none of its fields: the server reads the row
809 // from the session file, written once `next` returns.
810 const result = await next(e);
811 emit({ type: 'workbench_goal_status', uuid: e.uuid });
812 return result;
813 }
814 if (e.door === 'command') {
815 // A command's own rows: its name, the chat's echo of a command it sent,
816 // and what it printed, which `$.command.run` and the `command.run` hook
817 // may not return as `text` (`/goal`, `/rename`).
818 const text = promptText(m.content);
819 const out = commandRowOutput(text);
820 if (text.includes('<command-name>'))
821 emit({
822 type: 'user',
823 uuid: e.uuid,
824 session_id: sessionId,
825 message: { role: 'user', content: text }
826 });
827 else if (out) printOnce(out);
828 return next(e);
829 }
830 if (m.type === 'attachment' && m.name === 'queued_command') {
831 // A prompt typed in the terminal while a turn ran, folded into that
832 // turn. Only a prompt is framed so (history shows only those too).
833 const text = promptText(m.content);
834 if (text.startsWith(QUEUED_PREFIX)) {
835 emit({
836 type: 'user',
837 uuid: e.uuid,
838 session_id: sessionId,
839 message: { role: 'user', content: text }
840 });
841 await titles.use(sessionId, (k) => $.store.get(k));
842 titles.notePrompt(text.slice(QUEUED_PREFIX.length));
843 }
844 } else if (m.isMeta) {
845 return next(e);
846 } else if (m.type === 'assistant' && e.door === 'response') {
847 if (!keepAliveTurn) titles.noteReply(promptText(m.content));
848 emit({
849 type: 'assistant',
850 uuid: e.uuid,
851 session_id: sessionId,
852 message: { ...m, id: currentMessage || `wbmod-${e.uuid}`, model }
853 });
854 } else if (m.type === 'user' && e.door === 'prompt') {
855 const text = promptText(m.content);
856 keepAliveTurn = text === KEEPALIVE_PROMPT;
857 if (!keepAliveTurn && text !== QUEUED_NUDGE) {
858 await titles.use(sessionId, (k) => $.store.get(k));
859 titles.notePrompt(text);
860 }
861 if (echoed.delete(text)) return next(e);
862 emit({ type: 'user', uuid: e.uuid, session_id: sessionId, message: m });
863 } else if (m.type === 'user' && e.door === 'tool-result') {
864 const row: Line = { type: 'user', uuid: e.uuid, session_id: sessionId, message: m };
865 const id = (m.content as { tool_use_id?: string }[] | undefined)?.find(
866 (b) => b.tool_use_id
867 )?.tool_use_id;
868 const result = id ? toolResults.get(id) : undefined;
869 if (id) toolResults.delete(id);
870 // Still running: its structured result is sent with the row once it returns.
871 if (id && result === undefined && callsRunning.has(id)) toolRows.set(id, row);
872 emit(result === undefined ? row : { ...row, tool_use_result: result });
873 }
874 return next(e);
875 });
876
877 on('prompt.suggest', async ($, e, next) => {
878 const shown = await next(e);
879 if (server.current()) emit({ type: 'prompt_suggestion', suggestion: e.text });
880 return shown;
881 });
882
883 on('turn.complete', ($, e, next) => {
884 const linked = server.current() !== null;
885 const task = e.agentId && asyncAgents.has(e.agentId) ? agentTasks.get(e.agentId) : undefined;
886 if (e.agentId) stoppedAgents.delete(e.agentId);
887 // An agent a subagent spawned is done with its root task (`agent.spawn`).
888 const root = e.agentId && agentTasks.get(e.agentId);
889 if (root && taskAgents.get(root) !== e.agentId) agentTasks.delete(e.agentId!);
890 if (linked && task && e.agentId) {
891 const teammate = teammates.has(e.agentId);
892 if (!teammate) unlinkTask(task);
893 emit({
894 type: 'system',
895 subtype: 'task_notification',
896 task_id: task,
897 status:
898 e.reason === 'aborted' || endedByStop.has(e.agentId)
899 ? 'stopped'
900 : e.reason === 'answer'
901 ? 'completed'
902 : 'failed',
903 uuid: teammate ? `wbmod-done-${task}-${load}-${++askSeq}` : `wbmod-done-${task}`
904 });
905 }
906 // A call denied in the terminal's dialog never reaches `tool.call`.
907 if (!e.agentId)
908 for (const [id, asked] of askedInTerminal) if (asked.main) askedInTerminal.delete(id);
909 if (linked && !e.agentId) {
910 runningTurn = undefined;
911 if (e.reason === 'refusal')
912 emit({
913 type: 'system',
914 subtype: 'model_refusal_no_fallback',
915 original_model: model,
916 api_refusal_explanation: e.refusal.explanation,
917 uuid: `wbmod-refusal-${load}-${++askSeq}`
918 });
919 const modelUsage = contextWindow ? { [model]: { contextWindow } } : undefined;
920 const replaced = e.reason === 'aborted' && e.turnId === replacing;
921 if (replaced) {
922 // Send now's next turn follows at once: no idle flash, no "finished" alert.
923 replacing = undefined;
924 owedResult = true;
925 } else if (e.reason === 'error') {
926 failedResult = `wbmod-result-${load}-${++askSeq}`;
927 emit({
928 type: 'result',
929 subtype: 'error_during_execution',
930 is_error: true,
931 result: failure ?? 'The turn failed.',
932 uuid: failedResult,
933 modelUsage
934 });
935 } else {
936 emit({ type: 'result', subtype: 'success', is_error: false, modelUsage });
937 }
938 keepAliveTurn = false;
939 // Not awaited: the title follows the turn, nothing waits on it.
940 if (e.reason === 'answer')
941 void titles
942 .retitle(
943 title,
944 (prompt) =>
945 $.model
946 .complete({
947 model: 'haiku',
948 system: TITLE_SYSTEM,
949 prompt,
950 maxTokens: 40,
951 effort: 'low',
952 timeoutMs: 20_000
953 })
954 .then((r) => (r.isAnswered ? r.text : undefined)),
955 {
956 get: (k) => $.store.get(k),
957 set: (k, v) => $.store.set(k, v),
958 keys: () => $.store.keys(),
959 delete: (k) => $.store.delete(k)
960 }
961 )
962 .then((generated) => generated && noteTitle(generated))
963 .catch(() => {});
964 const unread = injected.length > 0;
965 injected = [];
966 // Entries live one turn at most, so a stale one can't hide a later prompt.
967 echoed.clear();
968 const lateSendNow = e.turnId === sentInto;
969 sentInto = undefined;
970 // Stopped: the prompt stays in the chat, as an interrupted CLI leaves it,
971 // unless it was Send now's, which went in as the abort ended the turn.
972 if ((e.reason === 'aborted' && !lateSendNow) || !unread) return next(e);
973 // The unread prompts are in the conversation already; only ask for an answer.
974 echoed.add(QUEUED_NUDGE);
975 void chatSubmit($.prompt.submit({ text: QUEUED_NUDGE, asUser: true })).catch(() => {});
976 }
977 return next(e);
978 });
979
980 // An API error ended the turn: the chat says why instead of a bare failure.
981 on('classic.StopFailure', ($, e, next) => {
982 if (server.current()) {
983 failure = e.error_details || `The turn failed: ${e.error.replace(/_/g, ' ')}.`;
984 // The turn's `result` went out already: only its notice takes the reason.
985 if (failedResult)
986 emit({
987 type: 'system',
988 subtype: 'local_command_output',
989 content: failure,
990 uuid: failedResult
991 });
992 }
993 return next(e);
994 });
995
996 on('classic.PostModelSwitch', ($, e, next) => {
997 // The later pick wins, as it does in the TUI.
998 if (PICKED_MODEL.has(e.source)) modelPick = undefined;
999 if (server.current()) {
1000 model = e.to_model;
1001 sentWindow = undefined;
1002 emit({
1003 type: 'system',
1004 subtype: 'init',
1005 model: e.to_model,
1006 ...(PICKED_MODEL.has(e.source) ? { modelChoice: e.requested_model ?? 'default' } : {})
1007 });
1008 }
1009 return next(e);
1010 });
1011
1012 // Fires when auto mode's classifier denies a call.
1013 on('classic.PermissionDenied', ($, e, next) => {
1014 notePermissionMode(e.permission_mode);
1015 pendingAsks.drop(e.tool_use_id);
1016 if (server.current() && !e.agent_id)
1017 emit({
1018 type: 'system',
1019 subtype: 'permission_denied',
1020 tool_name: e.tool_name,
1021 tool_use_id: e.tool_use_id,
1022 decision_reason_type: 'classifier',
1023 decision_reason: e.reason,
1024 uuid: `wbmod-denied-${e.tool_use_id}`
1025 });
1026 return next(e);
1027 });
1028
1029 // An MCP server asks for input. The terminal's dialog answers it; the chat
1030 // shows a read-only card, and the session waits on it until it's answered.
1031 on('classic.Elicitation', ($, e, next) => {
1032 if (server.current()) {
1033 const id = `wbmod-elicit-${load}-${++askSeq}`;
1034 const key = elicitationKey(e);
1035 terminalElicitations.set(key, [...(terminalElicitations.get(key) ?? []), id]);
1036 emit({
1037 type: 'workbench_terminal_elicitation',
1038 id,
1039 mcp_server_name: e.mcp_server_name,
1040 message: e.message,
1041 mode: e.mode,
1042 url: e.url,
1043 requested_schema: e.requested_schema
1044 });
1045 }
1046 return next(e);
1047 });
1048
1049 on('classic.ElicitationResult', ($, e, next) => {
1050 const key = elicitationKey(e);
1051 const id = terminalElicitations.get(key)?.shift();
1052 if (terminalElicitations.get(key)?.length === 0) terminalElicitations.delete(key);
1053 if (server.current() && id)
1054 emit({ type: 'workbench_terminal_elicitation_result', id, action: e.action });
1055 return next(e);
1056 });
1057
1058 // A command typed at the terminal. A chat's runs through `$.command.run`, which
1059 // skips this plugin's own hook, so `chatPrompt` does the same itself.
1060 on('command.run', async ($, e, next) => {
1061 if (e.origin.kind === 'composer') chatTurn = false;
1062 if (!server.current()) return next(e);
1063 await server.rekey(() => $.session.id());
1064 printed.clear();
1065 const before = new Set((await $.agent.list()).map((a) => a.id));
1066 const result = await next(e);
1067 if (!server.current()) return result;
1068 await server.rekey(() => $.session.id());
1069 commandRan(e.command, e.args, result.text, await $.agent.list(), before);
1070 // A bare `/rename` asks the engine for a name: not a person's.
1071 if (e.command === 'rename' && e.args.trim()) {
1072 const id = server.current()?.sessionId;
1073 if (id) await titles.use(id, (k) => $.store.get(k));
1074 await titles.nameByPerson({ get: (k) => $.store.get(k), set: (k, v) => $.store.set(k, v) });
1075 }
1076 return result;
1077 });
1078
1079 // `/compact` and Claude Code's idle compaction run no turn: the chat needs the
1080 // boundary and a `result`. Auto compaction mid-turn ends with the turn's own.
1081 on('session.compact', async ($, e, next) => {
1082 const ours = !e.agentId && e.trigger !== 'precompute';
1083 // The chat's `/compact` running: not a panel waiting to be closed, however long it takes.
1084 if (ours && e.trigger === 'manual' && chatCommand) chatCommand.answered = true;
1085 // The chat's "Compacting" bar: the engine reports no progress, only the start and end.
1086 const status = (s: 'compacting' | null) =>
1087 ours && server.current() && emit({ type: 'system', subtype: 'status', status: s });
1088 status('compacting');
1089 let result: Awaited<ReturnType<typeof next>>;
1090 try {
1091 result = await next(e);
1092 } finally {
1093 status(null);
1094 }
1095 if (!server.current() || !ours) return result;
1096 if (!result.messages) {
1097 emit({
1098 type: 'system',
1099 subtype: 'local_command_output',
1100 content: result.skip,
1101 uuid: `wbmod-compact-${load}-${++askSeq}`
1102 });
1103 } else {
1104 emit({
1105 type: 'system',
1106 subtype: 'compact_boundary',
1107 compact_metadata: { trigger: e.trigger, pre_tokens: result.tokensBefore },
1108 uuid: `wbmod-compact-${load}-${++askSeq}`
1109 });
1110 }
1111 if (!runningTurn) emit({ type: 'result', subtype: 'success', is_error: false });
1112 return result;
1113 });
1114
1115 // A chat's prompt reaches the session through this plugin's own submit;
1116 // one typed at the terminal hands what the turn asks back to the terminal.
1117 // A background task's notification comes through here, dequeued at idle or
1118 // delivered into the running turn: it names how each task ended (a killed one
1119 // too); the Stop hook's job list can only tell running from gone.
1120 on('prompt.submit', async ($, e, next) => {
1121 const notified = e.origin.kind === 'task-notification';
1122 if (notified && server.current())
1123 emit(
1124 ...notifiedJobs(
1125 e.text,
1126 (id) => agentTasks.has(id) || endedAgents.has(id) || endedByStop.has(id)
1127 )
1128 );
1129 const tasks = notified
1130 ? [...e.text.matchAll(/<task-id>([^<]+)<\/task-id>/g)].map((m) => m[1] ?? '')
1131 : [];
1132 if (tasks.length && tasks.every((t) => endedByStop.has(t))) {
1133 for (const t of tasks) endedByStop.delete(t);
1134 return { drop: 'Stopped in Workbench chat' };
1135 }
1136 if (e.origin.kind === 'plugin') chatTurn = e.origin.name === $.plugin.name;
1137 else if (e.origin.kind === 'composer') chatTurn = false;
1138 return next(e);
1139 });
1140
1141 // Structured results (an Artifact's link) and subagents for the tasks panel.
1142 on('tool.call', async ($, e, next) => {
1143 if (e.agentId && stoppedAgents.has(e.agentId)) return { deny: 'Stopped in Workbench chat' };
1144 const id = e.tool_use_id;
1145 // A command for the person: the chat's card answers it (Run, then Done or Skip).
1146 if (runTool && e.tool === runTool) {
1147 const run = runInput(e);
1148 if (typeof run === 'string') return { deny: run };
1149 if (!server.current() || !id) return { result: runResult(run.command, null) };
1150 const requestId = `wbmod-ask-${load}-${++askSeq}`;
1151 const answer = await server.askInChat(
1152 (u, i) => $.http.fetch(u, i),
1153 (ms, fn) => $.clock.after(ms, fn),
1154 requestId,
1155 askLine(requestId, e.tool, run, id),
1156 next.signal,
1157 chatTurn
1158 );
1159 return { result: runResult(run.command, answer, next.signal.aborted) };
1160 }
1161 if (!server.current()) return next(e);
1162 // Approved in the terminal's dialog: it no longer waits, however long the call runs.
1163 // The call goes ahead: whatever settled it, it no longer waits on a dialog.
1164 if (id) pendingAsks.drop(id);
1165 const asked = id ? askedInTerminal.get(id) : undefined;
1166 if (id && asked) {
1167 askedInTerminal.delete(id);
1168 emit({ type: 'control_cancel_request', request_id: asked.requestId });
1169 }
1170 if (e.tool === ASKED_IN_CALL && !e.agentId && id) {
1171 const { tool: _tool, tool_use_id: _id, agentId: _agent, ...input } = e;
1172 const requestId = `wbmod-ask-${load}-${++askSeq}`;
1173 const answer = await server.askInChat(
1174 (u, i) => $.http.fetch(u, i),
1175 (ms, fn) => $.clock.after(ms, fn),
1176 requestId,
1177 askLine(requestId, e.tool, input, id),
1178 next.signal,
1179 chatTurn
1180 );
1181 if (answer) {
1182 if (answer.behavior !== 'allow')
1183 return { deny: answer.message || 'Declined in Workbench chat' };
1184 const answered = { ...e, ...(answer.updatedInput ?? {}) } as typeof e;
1185 return {
1186 result: {
1187 questions: answered.questions,
1188 answers: answered.answers ?? {},
1189 ...(answered.annotations ? { annotations: answered.annotations } : {})
1190 }
1191 };
1192 }
1193 }
1194 const input = e as unknown as { description?: string; subagent_type?: string };
1195 const isAgent = !e.agentId && e.tool === 'Agent';
1196 const isSkill = !e.agentId && e.tool === 'Skill';
1197 if (isSkill && id) {
1198 const before = new Set((await $.agent.list()).map((a) => a.id));
1199 runningSkills.set(id, {
1200 skill: (e as unknown as { skill?: string }).skill ?? 'skill',hooks/link.ts 395 lines1import type { EngineInterface, Timer } from 'claude-code';
2import { askAnswer, type Answer, type Line } from './lines';
3
4// The session's link to the Workbench server: lines go out through a queue
5// (`/mod/out`), approvals are held open (`/mod/ask`), and the server's lines
6// are long-polled (`/mod/in`). The hooks module hands in the engine calls it
7// needs, spelled there.
8//
9// Both directions are numbered so a lost reply costs nothing: every line this
10// side sends carries its number (`seqs`, and `seq` the first line's for an
11// older server) and stays queued until a reply confirms it, so each request
12// resends all the unconfirmed ones from the oldest and the server folds a
13// number once; the server keeps each `/mod/in` line until a later poll
14// acknowledges it (`ack`).
15// The numbering is this worker's (`epoch`): a restarted worker (a hot reload)
16// starts again at 1 and the server counts afresh from its hello.
17
18type Fetch = EngineInterface['http']['fetch'];
19/** `$.clock.after`, spelled in the hook: a bound that holds without the session's timer. */
20export type After = (ms: number, fn: () => void) => Timer;
21
22// The host's fetch takes no signal and has been seen never to settle, so every
23// request is given up after a bound: a hung post must not hold the queue (and
24// the whole chat) forever. The server holds `/mod/ask` and `/mod/in` up to 20 s.
25const POST_MS = 10_000;
26const ASK_MS = 30_000;
27const POLL_MS = 30_000;
28export const HELLO_MS = 5_000;
29// Failed `/mod/ask` calls in a row before the terminal's dialog takes over.
30const ASK_TRIES = 3;
31// A failed post is retried after this, not on every tick with a growing body.
32const RETRY_MS = 1_000;
33// Lines kept while the server can't take them (it's down): streamed text goes
34// first (the reply's final row carries it whole), then the oldest.
35const OUTBOX_KEPT = 5_000;
36// What a session the server loads afresh already has from its history file
37// (a reset: it loaded the new id's); the rest (tasks, notices, the goal) only
38// ever reaches it as a line. A request's start stays, so the chat shows the
39// turn still running.
40const inHistory = (line: Line) =>
41 ['user', 'assistant', 'conversation_reset'].includes(String(line.type)) ||
42 (line.type === 'stream_event' &&
43 (line.event as { type?: unknown } | undefined)?.type !== 'message_start');
44/** Between hellos while the server doesn't know the session. */
45export const HELLO_EVERY_MS = 5_000;
46
47interface Link {
48 url: string;
49 token: string;
50 sessionId: string;
51 /** The `claude` process this runs in, the same across hot reloads. */
52 process?: string;
53}
54
55let link: Link | null = null;
56const epoch = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
57let outbox: { seq: number; line: Line }[] = [];
58let lastSeq = 0;
59// The newest `/mod/in` line handled, acknowledged on the next poll.
60let inSeq = 0;
61let flushing: Promise<void> | null = null;
62let retryAt = 0;
63// `/clear` or `/resume` ended the session and the process carries on under another id.
64let rekeyPending: 'clear' | 'resume' | undefined;
65
66/** The server doesn't know this session (it restarted, a stop detached it, the first hello failed). */
67export const hello = { needed: false, last: 0 };
68
69/** The time deadlines are read against; tests move it. */
70export const clock = { now: () => Date.now() };
71
72export function current(): Link | null {
73 return link;
74}
75
76export function open(next: Link | null) {
77 link = next;
78}
79
80export function init(method: string, body?: unknown) {
81 return {
82 method,
83 headers: { 'content-type': 'application/json', 'x-workbench-mod-token': link?.token ?? '' },
84 body: body === undefined ? undefined : JSON.stringify(body)
85 };
86}
87
88export function sessionQuery() {
89 return `sessionId=${encodeURIComponent(link?.sessionId ?? '')}`;
90}
91
92const isDelta = (line: Line) =>
93 line.type === 'stream_event' &&
94 (line.event as { type?: unknown } | undefined)?.type === 'content_block_delta';
95
96// Queued, then posted in order (see the top).
97export function emit(...lines: Line[]) {
98 if (!link) return;
99 for (const line of lines) outbox.push({ seq: ++lastSeq, line });
100 if (outbox.length > OUTBOX_KEPT) outbox = outbox.filter((e) => !isDelta(e.line));
101 if (outbox.length > OUTBOX_KEPT) outbox.splice(0, outbox.length - OUTBOX_KEPT);
102 tick();
103}
104
105type Batch = { seq?: number; seqs?: number[]; lines: Line[] };
106
107/** Every unconfirmed line, as a request carries them. */
108function unconfirmed(): Batch & { epoch: string } {
109 return {
110 epoch,
111 seq: outbox[0]?.seq,
112 seqs: outbox.map((e) => e.seq),
113 lines: outbox.map((e) => e.line)
114 };
115}
116
117/** A reply showed the server has `batch`. */
118function confirm(batch: Batch) {
119 const last = batch.seqs?.at(-1);
120 if (last !== undefined) outbox = outbox.filter((e) => e.seq > last);
121}
122
123/** The server doesn't know the session (404), or another worker holds it (409). */
124const helloAgain = (status: number | undefined) => status === 404 || status === 409;
125
126/** Everything queued, for the last request a session sends (`/mod/bye`). */
127export function takeOutbox() {
128 const batch = unconfirmed();
129 outbox = [];
130 return { sessionId: link?.sessionId, ...batch };
131}
132
133export function isFlushing() {
134 return flushing !== null;
135}
136
137// Deadlines read the wall clock: `Date.now()` advances in the hooks
138// environment, unlike a `$.clock.sleep`, which would spend the waiting hook's
139// budget (an approval may be held for minutes). They're checked on the
140// session's timer, on every line queued and whenever a bounded request
141// settles; one that must hold even if the timer stops also gets an `After`.
142const deadlines = new Set<{ at: number; done: () => void }>();
143
144export function tick() {
145 const now = clock.now();
146 for (const d of deadlines) if (d.at <= now) d.done();
147}
148
149/** `work`, or `undefined` once `ms` have passed. */
150export function within<T>(ms: number, work: Promise<T>, after?: After): Promise<T | undefined> {
151 let done = () => {};
152 const timeout = new Promise<undefined>((resolve) => (done = () => resolve(undefined)));
153 const deadline = { at: clock.now() + ms, done };
154 deadlines.add(deadline);
155 let timer: Timer | undefined;
156 try {
157 timer = after?.(ms, done);
158 } catch {
159 // The tick still bounds it.
160 }
161 return Promise.race([work, timeout]).finally(() => {
162 deadlines.delete(deadline);
163 timer?.cancel();
164 tick();
165 });
166}
167
168/** Post what is queued, after any post in flight. */
169export async function flush(fetch: Fetch) {
170 while (flushing) await flushing;
171 if (outbox.length === 0 || !link || hello.needed || clock.now() < retryAt) return;
172 const batch = unconfirmed();
173 const post = fetch(`${link.url}/mod/out`, init('POST', { sessionId: link.sessionId, ...batch }));
174 flushing = within(POST_MS, post)
175 .then((res) => {
176 if (helloAgain(res?.status)) hello.needed = true;
177 if (res?.ok) confirm(batch);
178 else retryAt = clock.now() + RETRY_MS;
179 })
180 .catch(() => {
181 retryAt = clock.now() + RETRY_MS;
182 })
183 .finally(() => (flushing = null));
184 await flushing;
185}
186
187/**
188 * Attach the session (`/mod/hello`). When the server loaded it afresh (it had
189 * lost it), the history it read holds the rows queued meanwhile: those lines
190 * go, the rest (tasks, notices) stay. A session it still had (an earlier
191 * hello's reply was lost) keeps them all.
192 */
193export async function attach(fetch: Fetch, again: boolean, after?: After): Promise<boolean> {
194 if (!link) return false;
195 const queued = lastSeq;
196 hello.last = clock.now();
197 const res = await within(
198 HELLO_MS,
199 fetch(
200 `${link.url}/mod/hello`,
201 init('POST', { sessionId: link.sessionId, epoch, process: link.process })
202 ).catch(() => null),
203 after
204 );
205 if (!res?.ok) {
206 hello.needed = true;
207 return false;
208 }
209 hello.needed = false;
210 retryAt = 0;
211 const reply = helloReply(res.text);
212 // Where the server's lines stand: a new link starts at 0; one it still had
213 // counts from the newest this worker (or the one before it) acknowledged.
214 inSeq = reply.loaded ? reply.inSeq : Math.max(inSeq, reply.inSeq);
215 if (again && reply.loaded) outbox = outbox.filter((e) => e.seq > queued || !inHistory(e.line));
216 return true;
217}
218
219/** An older server answers nothing: every hello loaded the session. */
220function helloReply(text: string): { inSeq: number; loaded: boolean } {
221 try {
222 const reply = JSON.parse(text) as { inSeq?: unknown; loaded?: unknown };
223 return {
224 inSeq: typeof reply.inSeq === 'number' ? reply.inSeq : 0,
225 loaded: reply.loaded !== false
226 };
227 } catch {
228 return { inSeq: 0, loaded: true };
229 }
230}
231
232/**
233 * The server's lines for this session (a chat's prompts and requests) not
234 * yet handled; each is acknowledged with `handled` once it has run.
235 */
236export async function poll(fetch: Fetch): Promise<Line[]> {
237 if (!link || hello.needed) return [];
238 const res = await within(
239 POLL_MS,
240 fetch(`${link.url}/mod/in?${sessionQuery()}&ack=${inSeq}`, init('GET')).catch(() => null)
241 );
242 if (res?.status === 404) hello.needed = true;
243 if (!res?.ok) return [];
244 let lines: unknown;
245 try {
246 lines = JSON.parse(res.text || '[]');
247 } catch {
248 return [];
249 }
250 if (!Array.isArray(lines)) return [];
251 // An older server numbers nothing.
252 return (lines as unknown[]).filter((line): line is Line => {
253 if (!line || typeof line !== 'object') return false;
254 const seq = (line as Line).wbSeq;
255 return typeof seq !== 'number' || seq > inSeq;
256 });
257}
258
259/** `line` from `poll` has run (or failed): the next poll acknowledges it. */
260export function handled(line: Line) {
261 if (typeof line.wbSeq === 'number') inSeq = Math.max(inSeq, line.wbSeq);
262}
263
264/**
265 * Withdraw a chat card at once, past a queue a hung post may hold.
266 * `inTerminal`: the terminal's dialog asks it now, so the chat says so.
267 */
268function withdraw(fetch: Fetch, requestId: string, inTerminal = false) {
269 if (!link) return;
270 const lines = [
271 {
272 type: 'control_cancel_request',
273 request_id: requestId,
274 ...(inTerminal && { workbench_in_terminal: true })
275 }
276 ];
277 void within(
278 POST_MS,
279 fetch(`${link.url}/mod/out`, init('POST', { sessionId: link.sessionId, lines }))
280 ).catch(() => {});
281}
282
283/** The session ended (`clear`, `resume`) and the process goes on under another id. */
284export function expectRekey(reason: 'clear' | 'resume') {
285 rekeyPending = reason;
286}
287
288/** After `/clear` or `/resume` the server hears of the new id before any of its lines. */
289export async function rekey(sessionId: () => Promise<string>) {
290 if (!rekeyPending || !link) return;
291 const id = await sessionId();
292 if (!rekeyPending || !link || id === link.sessionId) return;
293 const resumed = rekeyPending === 'resume';
294 rekeyPending = undefined;
295 // The server finds the session by token until the reset re-keys it.
296 emit({
297 type: 'conversation_reset',
298 new_conversation_id: id,
299 session_id: link.sessionId,
300 ...(resumed ? { resumed } : {})
301 });
302 link = { ...link, sessionId: id };
303}
304
305/** `work`, or `undefined` as soon as `signal` aborts. */
306function untilAborted<T>(signal: AbortSignal, work: Promise<T>): Promise<T | undefined> {
307 return Promise.race([
308 work,
309 new Promise<undefined>((resolve) =>
310 signal.addEventListener('abort', () => resolve(undefined), { once: true })
311 )
312 ]);
313}
314
315/**
316 * Ask in chat and hold until a client answers: `null` falls back to the
317 * terminal's dialog. `hold` keeps it a chat's even before one has it open.
318 * An abort (Esc) withdraws the card at once.
319 */
320export async function askInChat(
321 fetch: Fetch,
322 after: After | undefined,
323 requestId: string,
324 line: Line,
325 signal: AbortSignal,
326 hold: boolean
327): Promise<Answer | null> {
328 // The tool's card reaches the chat before its approval does: the queued
329 // lines go with the request, as waiting on the queue's post, a `$` call of
330 // another context, would spend this hook's budget.
331 // Sent until a reply shows the server has it (it ignores a repeat).
332 let first: Line | undefined = line;
333 let answer: Answer | null | undefined;
334 let failed = 0;
335 while (answer === undefined && link && !signal.aborted) {
336 const batch = unconfirmed();
337 const res = await untilAborted(
338 signal,
339 within(
340 ASK_MS,
341 fetch(
342 `${link.url}/mod/ask`,
343 init('POST', { sessionId: link.sessionId, requestId, line: first, ...batch, hold })
344 ).catch(() => null),
345 after
346 )
347 );
348 if (signal.aborted) break;
349 // A lost reply is asked again: the server keeps an answer until its call has a result.
350 if (!res?.ok) {
351 if (helloAgain(res?.status)) hello.needed = true;
352 if (++failed < ASK_TRIES) continue;
353 // The chat's card would stay answerable with nobody waiting on it.
354 withdraw(fetch, requestId, true);
355 return null;
356 }
357 try {
358 answer = askAnswer(res.text);
359 } catch {
360 // Not the server's reply, so its lines stay queued; the terminal's dialog asks.
361 withdraw(fetch, requestId, true);
362 return null;
363 }
364 confirm(batch);
365 failed = 0;
366 first = undefined;
367 }
368 if (signal.aborted) withdraw(fetch, requestId);
369 return answer ?? null;
370}
371
372/**
373 * A request only the terminal's dialog can answer: the server shows the
374 * session waiting on it there (and says so to phone and desktop) without a
375 * card. The queued lines go first, as with `askInChat`.
376 */
377export async function askInTerminal(
378 fetch: Fetch,
379 after: After | undefined,
380 requestId: string,
381 line: Line
382) {
383 if (!link) return;
384 const batch = unconfirmed();
385 const res = await within(
386 POST_MS,
387 fetch(
388 `${link.url}/mod/ask`,
389 init('POST', { sessionId: link.sessionId, requestId, line, ...batch, terminal: true })
390 ).catch(() => null),
391 after
392 );
393 if (res?.ok) confirm(batch);
394}
395hooks/asks.ts 57 lines1// Calls core put to the mode's decider, by tool and input: the decider's
2// dialog (`PermissionRequest`) names no call. A rule, the mode or auto mode's
3// classifier settles most without one, so only the newest are kept.
4// Identical calls made in parallel queue under one key, oldest first; a call
5// that goes ahead (`tool.call`) or is denied leaves the queue (`drop`).
6
7export type PendingAsk = { id: string; reason?: string };
8
9const KEPT = 50;
10
11export class PendingAsks {
12 private byKey = new Map<string, PendingAsk[]>();
13 private size = 0;
14
15 private static key(tool: string, input: unknown) {
16 return `${tool}\0${JSON.stringify(input)}`;
17 }
18
19 note(tool: string, input: unknown, ask: PendingAsk) {
20 const key = PendingAsks.key(tool, input);
21 const before = this.byKey.get(key) ?? [];
22 const list = [...before.filter((a) => a.id !== ask.id), ask];
23 // The newest key goes last, so the oldest is dropped first.
24 this.byKey.delete(key);
25 this.byKey.set(key, list);
26 this.size += list.length - before.length;
27 while (this.size > KEPT) {
28 const [oldest, asks] = this.byKey.entries().next().value!;
29 asks.shift();
30 this.size--;
31 if (asks.length === 0) this.byKey.delete(oldest);
32 }
33 }
34
35 /** Call `id` was settled without a dialog. */
36 drop(id: string) {
37 for (const [key, asks] of this.byKey) {
38 const kept = asks.filter((a) => a.id !== id);
39 if (kept.length === asks.length) continue;
40 this.size -= asks.length - kept.length;
41 if (kept.length) this.byKey.set(key, kept);
42 else this.byKey.delete(key);
43 return;
44 }
45 }
46
47 /** The oldest pending call a `PermissionRequest` for this tool and input is about. */
48 take(tool: string, input: unknown): PendingAsk | undefined {
49 const key = PendingAsks.key(tool, input);
50 const asks = this.byKey.get(key);
51 const ask = asks?.shift();
52 if (ask) this.size--;
53 if (asks?.length === 0) this.byKey.delete(key);
54 return ask;
55 }
56}
57hooks/jobs.ts 71 lines1import { taskNotification, taskStatus, type Line } from './lines';
2
3// Background jobs (`run_in_background` Bash) in the tasks panel, by id, with
4// the status last reported. A job's own notification says how it ended; the
5// Stop hook's job list is the fallback when no notification names it.
6
7const jobs = new Map<string, string>();
8// Ended jobs are kept only so a repeated report is said once: the oldest go.
9export const ENDED_KEPT = 200;
10
11function prune() {
12 let ended = [...jobs.values()].filter((status) => status !== 'running').length;
13 for (const [id, status] of jobs) {
14 if (ended <= ENDED_KEPT) return;
15 if (status !== 'running') {
16 jobs.delete(id);
17 ended--;
18 }
19 }
20}
21
22/** A job just went to the background; false if it was reported already. */
23export function startJob(id: string): boolean {
24 if (jobs.has(id)) return false;
25 jobs.set(id, 'running');
26 return true;
27}
28
29function report(id: string, status: string, summary?: string): Line | undefined {
30 if (jobs.get(id) === status) return undefined;
31 jobs.set(id, status);
32 if (status === 'running') return undefined;
33 prune();
34 return {
35 type: 'system',
36 subtype: 'task_notification',
37 task_id: id,
38 status,
39 ...(summary ? { summary } : {}),
40 uuid: `wbmod-bg-done-${id}`
41 };
42}
43
44/**
45 * A `task-notification` delivery: the real outcome (completed, failed, killed)
46 * of each task it names (one delivery can batch several). Sent for any task,
47 * even one this load didn't start: a plugin reload forgets its jobs. `tracked`
48 * names the subagents whose task this load ends itself, so their notification
49 * can't override that (a chat's Stop).
50 */
51export function notifiedJobs(text: string, tracked: (id: string) => boolean = () => false): Line[] {
52 return [...text.matchAll(/<task-notification>([\s\S]*?)<\/task-notification>/g)]
53 .map((block) => taskNotification(block[1] ?? ''))
54 .map((note) =>
55 note && !tracked(note.id) ? report(note.id, note.status, note.summary) : undefined
56 )
57 .filter((line): line is Line => line !== undefined);
58}
59
60/**
61 * The Stop hook's job list. A running job missing from it has ended; it's
62 * called completed until its notification (if one comes) says otherwise.
63 */
64export function stoppedJobs(tasks: readonly { id: string; status: string }[]): Line[] {
65 const live = new Map(tasks.map((t) => [t.id, t.status]));
66 return [...jobs]
67 .filter(([, status]) => status === 'running')
68 .map(([id]) => report(id, taskStatus(live.get(id) ?? 'completed')))
69 .filter((line): line is Line => line !== undefined);
70}
71hooks/run.ts 64 lines1// The `run_in_terminal` tool: Claude hands the person a shell command to run
2// themselves (an interactive login, anything needing a browser or a TTY). The
3// chat shows it with Run, which opens a new Workbench terminal running it, and
4// Done or Skip, which answer the call so Claude carries on by itself.
5
6export const RUN_TOOL_NAME = 'run_in_terminal';
7
8export const RUN_TOOL_SPEC = {
9 name: RUN_TOOL_NAME,
10 description:
11 'Ask the person to run a shell command themselves, in a new Workbench terminal they open with one click. ' +
12 'Use it instead of telling them to type `! <command>` whenever they must run something you cannot: ' +
13 'interactive logins (`stripe login`, `gh auth login`, `gcloud auth login`), anything that opens a browser, ' +
14 'prompts for a password or needs a TTY. Waits until they mark it done or skip it, then returns which. ' +
15 "You do not see the command's output: check its effect yourself afterwards if it matters.",
16 inputSchema: {
17 type: 'object',
18 properties: {
19 command: { type: 'string', description: 'One shell command line, exactly as it should run.' },
20 reason: { type: 'string', description: 'Why they need to run it, in one short sentence.' }
21 },
22 required: ['command'],
23 additionalProperties: false
24 },
25 // In the prompt's tool list, not behind ToolSearch: Claude must know of it
26 // before it reaches for `! <command>`.
27 isDeferred: false
28};
29
30export type RunInput = { command: string; reason?: string };
31
32/** The call's input when it is one usable command line; else why not. */
33export function runInput(input: unknown): RunInput | string {
34 const { command, reason } = (input ?? {}) as { command?: unknown; reason?: unknown };
35 if (typeof command !== 'string' || !command.trim()) return 'No command given.';
36 if (/[\r\n]/.test(command.trim()))
37 return 'Give one command line; chain steps with && or ask for each in turn.';
38 return {
39 command: command.trim(),
40 ...(typeof reason === 'string' && reason.trim() ? { reason: reason.trim() } : {})
41 };
42}
43
44/**
45 * What Claude reads: the chat's answer; else (no chat showed it, or the chat
46 * couldn't be reached) a request for the old way, unless the call was stopped.
47 */
48export function runResult(
49 command: string,
50 answer: { behavior?: string } | null,
51 stopped = false
52): string {
53 if (stopped) return `Stopped before the person answered; \`${command}\` was not run.`;
54 if (!answer)
55 return (
56 "No Workbench chat could show this request (none is open, or it couldn't be reached). " +
57 `Ask the person to run it themselves: \`! ${command}\``
58 );
59 return answer.behavior === 'allow'
60 ? `The person ran \`${command}\` in a Workbench terminal and marked it done. ` +
61 'Its output is not visible to you: check its effect if it matters.'
62 : `The person chose not to run \`${command}\`. Ask before trying another way.`;
63}
64hooks/titles.ts 187 lines1// Keeps the session's title fitting the conversation: after an answered turn
2// a small model reads the opening prompt, the latest ones and the reply, and
3// names it. A title someone gave (`/rename`) is theirs and stays. What it
4// knows of a session is kept in the plugin's store under the session's id, so
5// a restart (a mode switch, a rewind, the app) carries on where it was.
6
7/** One completion, spelled in the hook (`$.model.complete`). */
8export type Complete = (prompt: string) => Promise<string | undefined>;
9
10/** `$.store`, spelled in the hook. */
11export interface Store {
12 get: (key: string) => Promise<unknown>;
13 set: (key: string, value: unknown) => Promise<void>;
14 keys?: () => Promise<string[]>;
15 delete?: (key: string) => Promise<void>;
16}
17
18interface Saved {
19 first?: string;
20 recent: string[];
21 prompts: number;
22 named: boolean;
23}
24
25const RECENT_PROMPTS = 3;
26const PROMPT_CHARS = 600;
27const REPLY_CHARS = 800;
28const TITLE_CHARS = 60;
29/** Every prompt names the session at first, then every `RETITLE_EVERY`th. */
30const EARLY_PROMPTS = 3;
31const RETITLE_EVERY = 5;
32const SESSIONS_KEPT = 200;
33const KEY = 'title:';
34
35export const TITLE_SYSTEM =
36 'You name coding-assistant conversations for a sidebar. Reply with the title only: ' +
37 '3 to 6 words, sentence case, no quotes or trailing punctuation, naming the task ' +
38 "(e.g. 'Fix stale chat after tool calls'). If the current title still fits, reply with it unchanged.";
39
40const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);
41
42const fresh = (): Saved => ({ recent: [], prompts: 0, named: false });
43
44export class Titles {
45 private session: string | undefined;
46 private loading: Promise<void> = Promise.resolve();
47 private saved: Saved = fresh();
48 private reply = '';
49 /** A prompt came since the last title was asked for. */
50 private due = false;
51 private generating = false;
52 /** Bumped when the conversation changes, so a title asked before it is dropped. */
53 private epoch = 0;
54 /** Generated, and not yet handed to the engine (`sessionTitle`). */
55 private pending: string | undefined;
56
57 /** Work on `sessionId`'s state, read from the store the first time. */
58 use(sessionId: string, get: Store['get']): Promise<void> {
59 if (sessionId !== this.session) {
60 this.forget();
61 this.session = sessionId;
62 this.loading = get(KEY + sessionId)
63 .then((value) => {
64 if (this.session === sessionId && isSaved(value)) this.saved = value;
65 })
66 .catch(() => {});
67 }
68 return this.loading;
69 }
70
71 /** `/clear` or `/resume`: another conversation, read afresh on its first use. */
72 reset() {
73 this.forget();
74 this.session = undefined;
75 }
76
77 private forget() {
78 this.epoch++;
79 this.saved = fresh();
80 this.reply = '';
81 this.due = false;
82 this.pending = undefined;
83 }
84
85 /** A prompt the person (or chat) sent; Workbench's own prompts are skipped by the caller. */
86 notePrompt(text: string) {
87 const trimmed = text.trim();
88 if (!trimmed || trimmed.startsWith('<command-')) return;
89 const s = this.saved;
90 s.first ??= trimmed;
91 s.recent = [...s.recent, trimmed].slice(-RECENT_PROMPTS);
92 s.prompts++;
93 this.due = s.prompts <= EARLY_PROMPTS || s.prompts % RETITLE_EVERY === 0;
94 }
95
96 noteReply(text: string) {
97 if (text.trim()) this.reply = text.trim();
98 }
99
100 /** Someone named the session (`/rename <name>`): no more automatic titles for it. */
101 async nameByPerson(store: Store) {
102 this.saved.named = true;
103 this.pending = undefined;
104 await this.save(store);
105 }
106
107 /** The title to hand the engine with the next prompt, once. */
108 takePending(): string | undefined {
109 const title = this.pending;
110 this.pending = undefined;
111 return title;
112 }
113
114 /** After an answered turn: a new title, or `undefined` to keep `current`. */
115 async retitle(
116 current: string | undefined,
117 complete: Complete,
118 store: Store
119 ): Promise<string | undefined> {
120 const { first, recent, named } = this.saved;
121 if (named || this.generating || !this.due || !first) return undefined;
122 this.generating = true;
123 this.due = false;
124 const epoch = this.epoch;
125 try {
126 const later = recent.filter((p) => p !== first);
127 const prompt = [
128 `Current title: ${current ?? '(none)'}`,
129 `Opening request:\n${clip(first, PROMPT_CHARS)}`,
130 later.length > 0 &&
131 `Latest requests:\n${later.map((p) => `- ${clip(p, PROMPT_CHARS)}`).join('\n')}`,
132 this.reply && `Latest reply:\n${clip(this.reply, REPLY_CHARS)}`
133 ]
134 .filter(Boolean)
135 .join('\n\n');
136 const title = clean(await complete(prompt).catch(() => undefined));
137 // The conversation changed, or a rename landed, while the model answered.
138 if (epoch !== this.epoch) return undefined;
139 await this.save(store, true);
140 if (!title || this.saved.named || title === current) return undefined;
141 this.pending = title;
142 return title;
143 } finally {
144 this.generating = false;
145 }
146 }
147
148 private async save(store: Store, prune = false) {
149 const session = this.session;
150 if (!session) return;
151 try {
152 await store.set(KEY + session, this.saved);
153 if (!prune || !store.keys || !store.delete) return;
154 const keys = (await store.keys()).filter((k) => k.startsWith(KEY));
155 for (const key of keys.slice(0, Math.max(0, keys.length - SESSIONS_KEPT)))
156 await store.delete(key);
157 } catch {
158 // A store that can't be written costs only the memory across restarts.
159 }
160 }
161}
162
163function isSaved(value: unknown): value is Saved {
164 const v = value as Saved | null;
165 return (
166 typeof v === 'object' &&
167 v !== null &&
168 Array.isArray(v.recent) &&
169 typeof v.prompts === 'number' &&
170 typeof v.named === 'boolean'
171 );
172}
173
174/** The first line, without wrapping quotes or a closing full stop, cut at a word. */
175export function clean(text: string | undefined): string | undefined {
176 const line = text?.trim().split('\n')[0] ?? '';
177 const title = line
178 .replace(/^["'`“”‘’]+|["`“”‘’]+$/g, '')
179 .replace(/\.+$/, '')
180 .trim();
181 if (!title) return undefined;
182 if (title.length <= TITLE_CHARS) return title;
183 const cut = title.slice(0, TITLE_CHARS);
184 const space = cut.lastIndexOf(' ');
185 return space > 0 ? cut.slice(0, space) : cut;
186}
187hooks/lines.ts 198 lines1import type { PermissionRequestDecision, SessionRateLimit } from 'claude-code';
2
3// The stream-json lines the chat folds and the text the plugin frames: no
4// engine calls here, those stay in the hooks module.
5
6export type Line = Record<string, unknown>;
7export type Answer = {
8 behavior?: string;
9 message?: string;
10 updatedInput?: Record<string, unknown>;
11 updatedPermissions?: Extract<
12 PermissionRequestDecision,
13 { behavior: 'allow' }
14 >['updatedPermissions'];
15};
16
17/**
18 * Sent when chat prompts put into a turn were never read by it: the model
19 * finds them in the conversation already. Core's `QUEUED_NUDGE` hides it.
20 */
21export const QUEUED_NUDGE = 'Please answer the message I sent while you were working.';
22/** The server's prompt-cache ping; core's `KEEPALIVE_PROMPT`. */
23export const KEEPALIVE_PROMPT = 'Workbench cache keep-alive. Reply with only "ok".';
24/** How the CLI frames a prompt typed while a turn runs; core's `QUEUED_PROMPT_PREFIX`. */
25export const QUEUED_PREFIX = 'The user sent a new message while you were working:\n';
26const ATTACHED_FILES = '\n\nAttached files (read each with the Read tool):\n';
27
28const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
29
30/** A `/config` model value as the chat's picker shows it. */
31export function modelOption(value: string) {
32 const wide = value.endsWith('[1m]');
33 const base = value.replace('[1m]', '');
34 const name = base === 'opusplan' ? 'Opus Plan' : base.charAt(0).toUpperCase() + base.slice(1);
35 return {
36 value,
37 displayName: wide ? `${name} (1M context)` : name,
38 ...(base === 'haiku' ? {} : { supportedEffortLevels: EFFORT_LEVELS })
39 };
40}
41
42// The server turns attachments into `@path` mentions, so a prompt is text.
43export function promptText(content: unknown): string {
44 if (typeof content === 'string') return content;
45 const blocks = Array.isArray(content) ? (content as { type?: string; text?: string }[]) : [];
46 return blocks
47 .filter((b) => b.type === 'text')
48 .map((b) => b.text ?? '')
49 .join('\n');
50}
51
52/** What a command's transcript row printed (`Goal set: …`), if it's an output row. */
53export function commandRowOutput(text: string): string | undefined {
54 const out = /^<local-command-(stdout|stderr)>([\s\S]*)<\/local-command-\1>$/.exec(text.trim());
55 return out?.[2]?.trim() || undefined;
56}
57
58// What the transcript reads of a tool's structured result: an edit's patch,
59// an Artifact's link. The rest (whole files, outputs) stays off the wire.
60const RESULT_KEYS = [
61 'structuredPatch',
62 'url',
63 'title',
64 'version',
65 'created_from_type',
66 'updated',
67 'opened'
68];
69
70export function slimResult(result: unknown): Line | undefined {
71 if (!result || typeof result !== 'object') return undefined;
72 const kept = Object.entries(result).filter(([k]) => RESULT_KEYS.includes(k));
73 return kept.length ? Object.fromEntries(kept) : undefined;
74}
75
76export function askLine(
77 requestId: string,
78 tool: string,
79 input: unknown,
80 toolUseId?: string,
81 reason?: string,
82 suggestions?: unknown
83): Line {
84 return {
85 type: 'control_request',
86 request_id: requestId,
87 request: {
88 subtype: 'can_use_tool',
89 tool_name: tool,
90 input,
91 tool_use_id: toolUseId,
92 description: reason,
93 permission_suggestions: suggestions
94 }
95 };
96}
97
98/**
99 * The files the server saved for a chat prompt (`workbench_attachments`);
100 * `undefined` from a server that only puts them in the text as `@` mentions.
101 */
102export function attachedFiles(line: Line): string[] | undefined {
103 const files = line.workbench_attachments;
104 return Array.isArray(files)
105 ? files.filter((f): f is string => typeof f === 'string' && f.length > 0)
106 : undefined;
107}
108
109/**
110 * A prompt naming files to Read: a plugin's prompt never has its `@` mentions
111 * (chat images and files) expanded, submitted or appended. Only the files the
112 * server attached are listed; `@scope/pkg` in prose is no file. Without that
113 * list (an older server) every mention counts, as it did.
114 */
115export function withAttachments(text: string, files?: readonly string[]): string {
116 const listed =
117 files ?? [...text.matchAll(/(?:^|\s)@(?:"([^"]+)"|(\S+))/g)].map((m) => m[1] ?? m[2]);
118 return listed.length ? `${text}${ATTACHED_FILES}${listed.map((f) => `- ${f}`).join('\n')}` : text;
119}
120
121/** `/name args` as `$.command.run` takes it; a path like `/Users/x` is no command. */
122export function slashCommand(text: string): { command: string; args: string } | undefined {
123 const m = /^\/([\w:.-]+)(?:\s+([\s\S]*))?$/.exec(text.trim());
124 return m ? { command: m[1], args: m[2]?.trim() ?? '' } : undefined;
125}
126
127/** A chat prompt put into a running turn, framed as the CLI frames a typed one. */
128export function midTurn(text: string, files?: readonly string[]): string {
129 return `${QUEUED_PREFIX}${withAttachments(text, files)}\n\nIMPORTANT: After completing your current task, you MUST address the user's message above. Do not ignore it.`;
130}
131
132/**
133 * One `/mod/ask` reply: the answer, `null` to fall back to the terminal (no
134 * chat open), or `undefined` to keep waiting.
135 */
136export function askAnswer(text: string): Answer | null | undefined {
137 const reply = JSON.parse(text) as {
138 answer?: { response?: { subtype?: string; response?: Answer; error?: string } };
139 fallback?: boolean;
140 } | null;
141 if (!reply || typeof reply !== 'object' || Array.isArray(reply)) throw new Error('not an answer');
142 if (reply.fallback) return null;
143 const response = reply.answer?.response;
144 if (!response) return undefined;
145 return response.subtype === 'error'
146 ? { behavior: 'deny', message: response.error }
147 : (response.response ?? { behavior: 'deny' });
148}
149
150const unixSeconds = (iso: string | undefined) => {
151 const ms = iso ? Date.parse(iso) : NaN;
152 return Number.isNaN(ms) ? undefined : Math.floor(ms / 1000);
153};
154
155/**
156 * The most used rate-limit window, as the SDK's `rate_limit_event` reports one,
157 * plus every window (`windows`): the server answers plan usage from them.
158 */
159export function rateLimitLine(windows: readonly SessionRateLimit[]): Line | undefined {
160 const top = [...windows].sort((a, b) => b.percentUsed - a.percentUsed)[0];
161 if (!top) return undefined;
162 // The SDK warns past its own thresholds; 90% is where the chat starts to.
163 const status =
164 top.percentUsed >= 100 ? 'rejected' : top.percentUsed >= 90 ? 'allowed_warning' : 'allowed';
165 const resetsAt = unixSeconds(top.resetsAt);
166 return {
167 type: 'rate_limit_event',
168 rate_limit_info: {
169 status,
170 rateLimitType: top.kind,
171 utilization: top.percentUsed / 100,
172 ...(resetsAt === undefined ? {} : { resetsAt })
173 },
174 windows: windows.map((w) => ({
175 kind: w.kind,
176 percentUsed: w.percentUsed,
177 resetsAt: unixSeconds(w.resetsAt)
178 }))
179 };
180}
181
182/** A task status as the SDK's `task_notification` names an end, or `running`. */
183export function taskStatus(status: string): string {
184 if (status === 'running' || status === 'pending') return 'running';
185 if (status === 'killed' || status === 'stopped') return 'stopped';
186 return status === 'failed' ? 'failed' : 'completed';
187}
188
189/** The task and outcome a `<task-notification>` delivery names. */
190export function taskNotification(
191 text: string
192): { id: string; status: string; summary?: string } | undefined {
193 const tag = (name: string) => new RegExp(`<${name}>([^<]*)</${name}>`).exec(text)?.[1]?.trim();
194 const id = tag('task-id');
195 const status = tag('status');
196 return id && status ? { id, status: taskStatus(status), summary: tag('summary') } : undefined;
197}
198