Runs this Claude Code session as a client of a Leverage session

<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-3f3f46?labelColor=0a0a0a" alt="MIT license"></a> <a href="https://github.com/leverage-computer/claude-plugin/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/leverage-computer/claude-plugin/ci.yml?branch=main&label=CI&labelColor=0a0a0a&color=3f3f46" alt="CI status"></a> <a href=".claude-plugin/plugin.json"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fleverage-computer%2Fclaude-plugin%2Fmain%2F.claude-plugin%2Fplugin.json&query=%24.version&label=Version&labelColor=0a0a0a&color=3f3f46" alt="Plugin version"></a> <a href="#requirements"><img src="https://img.shields.io/badge/Claude%20Code-%E2%89%A52.1.286-3f3f46?labelColor=0a0a0a" alt="Claude Code 2.1.286 or later"></a>
Install · Usage · Features · leverage.computer
claude plugin marketplace add leverage-computer/claude-plugin
claude plugin install leverage@leverage
Claude Desktop's Code tab runs Claude Code, so the plugin works there too. Add it from Claude Desktop's plugin directory:
leverage-computer/claude-plugin and click Sync./leverage login: sign in, and approve in the browser./leverage: open the pane.To start a new session in a space, use the Leverage CLI:
leverage claude <space>
/leverage opens the pane again./leverage help lists the actions you can do with Leverage mod.Nix gives the shell Node and pnpm, and lints each commit with Biome and nixfmt: nix develop, or direnv allow once. Then:
pnpm install # Claude Code 2.1.286, the oldest it supports, included
pnpm test # claude plugin test .
pnpm coverage # how much of hooks/ the tests run
hooks/register.ts 960 lines1import type { EngineInterface, HookFailure, Register } from "claude-code";
2import { update } from "claude-code";
3
4import type { Room, WorkspaceTree } from "../types";
5import {
6 accessPath,
7 cliConfigPath,
8 connectedBy,
9 connectKept,
10 connectLaunched,
11 connectSaved,
12 drawn,
13 follow,
14 here,
15 isClient,
16 isReachable,
17 LEVERAGE_TOOLS,
18 leverageRequest,
19 MIRRORED,
20 replay,
21 space,
22} from "./client";
23import { registerCommands } from "./commands";
24import { PANE, registerPane } from "./pane";
25import { registerPeople } from "./people";
26
27// Makes this Claude Code session a client of one Leverage session. The turn
28// runs in the Leverage sandbox. This process draws it and never calls a model.
29
30type Block =
31 | { kind: "text"; text: string }
32 | { kind: "thinking"; text: string }
33 | {
34 kind: "tool";
35 id: string;
36 name: string;
37 input: Record<string, unknown>;
38 /** The Leverage subagent the call started. */
39 agent?: {
40 task: string;
41 description: string;
42 prompt: string;
43 type: string | null;
44 };
45 };
46type Waiting = {
47 writable: boolean;
48 approvals: { id: string; tool: string; input: unknown }[];
49 question: string | null;
50};
51type Step =
52 | {
53 blocks: Block[];
54 stop: "tool_use" | "end_turn";
55 cursor: number;
56 turnId: string | null;
57 /** The tokens the Leverage session's context holds. */
58 context: number | null;
59 question: string | null;
60 }
61 | {
62 pending: true;
63 waiting?: Waiting;
64 /** The text the agent is writing, which no row holds yet. */
65 live?: { id: string; kind: "text" | "reasoning"; text: string }[];
66 };
67type Result =
68 | { content: string; isError: boolean }
69 | { pending: true; progress?: string; seen?: number };
70
71// Remote tools with a local twin whose output shape the mod can build.
72const NATIVE = new Set(["Bash", "Read", "Edit", "Write"]);
73const usage = (context: number | null) => ({
74 input_tokens: context ?? 0,
75 output_tokens: 0,
76 cache_creation_input_tokens: 0,
77 cache_read_input_tokens: 0,
78 model: "leverage",
79});
80/** The window's status line: the session's title, or its space. */
81let shown = "Leverage";
82/** The rows already shown as notices, by session and position. */
83const noticed = new Set<string>();
84/** A turn a session ran before this window opened it, to be drawn again. */
85type Replay = { session: string; text: string; steers: string[] };
86/** Replayed turns submitted to Claude Code's queue, oldest first, until each starts. */
87const replays: Replay[] = [];
88/** The replayed turn that runs, by its id. */
89let replaying: string | null = null;
90/** Turns of a session the window has since left, which draw nothing. */
91const stale = new Set<string>();
92/** Notices of rows the replay has yet to reach, oldest first. */
93const later: { session: string; seq: number; text: string }[] = [];
94/** The replay's prompt poll still runs, so no other one reads the same rows. */
95let isReading = false;
96/** The background commands still running, by task id. */
97const running = new Set<string>();
98/** The people the last prompt poll saw, as sent, so an unchanged room draws nothing. */
99let seenRoom = "";
100/** Prompts asked to wait, still in Claude Code's queue, oldest first. */
101const waiting: { text: string; skills: { name: string }[]; pasted: boolean }[] =
102 [];
103
104/** The subagents Claude Code is starting for Leverage, until each has its id. */
105const spawning = new Set<Promise<unknown>>();
106
107/** The status line: the session, its turns left to draw, and what runs in the background. */
108function line(): string {
109 const left =
110 replays.filter((one) => one.session === here.id).length +
111 (replaying ? 1 : 0);
112 return [
113 shown,
114 ...(left > 0 ? [`drawing ${left} earlier turn${left > 1 ? "s" : ""}`] : []),
115 ...(running.size > 0 ? [`${running.size} in the background`] : []),
116 ].join(" · ");
117}
118
119/** Whether the session's earlier turns are still to be read or drawn. */
120function isReplaying(): boolean {
121 return (
122 here.replay ||
123 replaying !== null ||
124 replays.some((one) => one.session === here.id)
125 );
126}
127const CHOICES = ["Once", "This session", "Always", "Reject"];
128const DECISIONS: Record<string, string> = {
129 Once: "once",
130 "This session": "session",
131 Always: "always",
132 Reject: "reject",
133};
134
135async function call<T>(
136 $: EngineInterface,
137 path: string,
138 body?: unknown,
139): Promise<T> {
140 const res = await $.http.fetch(...leverageRequest(path, body));
141 if (!res.ok) {
142 throw new Error(
143 res.status === 401
144 ? connectedBy() === "launched"
145 ? "Leverage refused this Claude Code token. Run leverage claude again."
146 : "Leverage refused this Claude Code token. /leverage login signs in again."
147 : `Leverage answered ${res.status}: ${res.text}`,
148 );
149 }
150 return JSON.parse(res.text) as T;
151}
152
153// The session's title, or its space until the first prompt starts one.
154async function showLabel($: EngineInterface) {
155 let label = "";
156 if (here.id) {
157 label = (await call<{ title: string }>($, `/sessions/${here.id}`)).title;
158 } else if (space()) {
159 const tree = await call<WorkspaceTree>($, "/workspace");
160 const channel = tree.channels.find((one) => one.id === space());
161 label = channel ? `#${channel.name}` : "";
162 }
163 // The engine shows the plugin name before the line.
164 shown = label || "Leverage";
165 $.ui.status(line());
166}
167
168// Asks each call that waits on this person, in Claude Code's own dialog.
169async function askApprovals($: EngineInterface, waiting: Waiting) {
170 for (const pending of waiting.approvals) {
171 if (here.known.has(pending.id)) continue;
172 here.known.add(pending.id);
173 if (!waiting.writable) {
174 $.ui.status(`${shown} · waiting for approval of ${pending.tool}`);
175 continue;
176 }
177 let answer: string;
178 try {
179 answer = await $.ui.ask(
180 `Allow ${pending.tool} to run in Leverage? ${JSON.stringify(pending.input).slice(0, 300)}`,
181 { header: "Approval", options: CHOICES },
182 );
183 } catch {
184 $.ui.toast("Not decided. /leverage approvals asks again.");
185 continue;
186 }
187 // Text typed under Other rejects the call, and Leverage passes it on.
188 const decision = DECISIONS[answer] ?? "reject";
189 await call($, `/approvals/${pending.id}`, {
190 decision,
191 ...(DECISIONS[answer] ? {} : { reason: answer }),
192 });
193 }
194}
195
196/** A line in the transcript that the model never reads. */
197async function note($: EngineInterface, text: string) {
198 await $.session
199 .append({ message: { type: "system", content: [{ type: "text", text }] } })
200 .catch(() => {});
201}
202
203/** A Leverage prompt as this window shows it. */
204function framed(prompt: { author: string; text: string; images: number }) {
205 // Claude Code takes no image from a plugin, so the prompt says it has some.
206 const images =
207 prompt.images > 0
208 ? ` [${prompt.images} image${prompt.images > 1 ? "s" : ""} in Leverage]`
209 : "";
210 return `${prompt.author} (in Leverage): ${prompt.text}${images}`;
211}
212
213/** Shows the notices of the rows the replay has drawn, up to `cursor`. */
214async function flush($: EngineInterface, cursor = Number.POSITIVE_INFINITY) {
215 while (later.length > 0 && later[0]!.seq <= cursor) {
216 const notice = later.shift()!;
217 if (notice.session === here.id) await note($, notice.text);
218 }
219}
220
221/** Once the session's earlier turns are all drawn, the notices left show. */
222async function settle($: EngineInterface) {
223 if (isReplaying()) return;
224 // A turn no prompt started has no turn here: the next prompt's reads past it.
225 here.cursor = Math.max(here.cursor, here.newest);
226 await flush($);
227 $.ui.status(line());
228}
229
230// Turns started from another client open a turn here, so both show it. A
231// window that opens a session reads it from its first row: each earlier
232// prompt starts a turn here, whose steps come from Leverage as a live turn's.
233async function poll($: EngineInterface) {
234 const id = here.id;
235 const isReplay = here.replay;
236 const { prompts, notices, last, viewers, typing } = await call<
237 {
238 prompts: {
239 uuid: string;
240 author: string;
241 text: string;
242 images: number;
243 steer: boolean;
244 }[];
245 notices: {
246 seq: number;
247 text: string;
248 task?: { id: string; running: boolean };
249 }[];
250 last: number;
251 } & Room
252 >($, `/sessions/${id}/prompts?after=${here.polled}`);
253 // The window moved to another session meanwhile.
254 if (here.id !== id) return;
255 here.replay = false;
256 here.polled = Math.max(here.polled, last);
257 // An older Leverage sends no room.
258 const room: Room = { viewers: viewers ?? [], typing: typing ?? [] };
259 if (JSON.stringify(room) !== seenRoom) {
260 seenRoom = JSON.stringify(room);
261 await update($, { plugin: "leverage", key: "people" }, () => room);
262 }
263 if (isReplay) {
264 running.clear();
265 later.length = 0;
266 await showLabel($);
267 }
268 // A row the window does not draw, as a compaction, shows as a notice.
269 // While earlier turns draw, it waits until the turns before it are drawn.
270 const isBehind = isReplay || isReplaying();
271 for (const notice of notices) {
272 const key = `${id}:${notice.seq}`;
273 if (noticed.has(key) && !isReplay) continue;
274 noticed.add(key);
275 if (notice.task?.running) running.add(notice.task.id);
276 else if (notice.task) running.delete(notice.task.id);
277 $.ui.status(line());
278 if (isBehind)
279 later.push({ session: id, seq: notice.seq, text: notice.text });
280 else await note($, notice.text);
281 }
282 later.sort((a, b) => a.seq - b.seq);
283 const turns: Replay[] = [];
284 for (const p of prompts) {
285 if (drawn.has(p.uuid) && !isReplay) continue;
286 drawn.add(p.uuid);
287 // A teammate's steer joins the running turn; Claude Code only shows it.
288 if (p.steer) {
289 const steer = `${p.author} (in Leverage) adds: ${p.text}`;
290 const turn = turns.at(-1);
291 if (isReplay && turn) turn.steers.push(steer);
292 else await note($, steer);
293 continue;
294 }
295 if (isReplay) {
296 turns.push({ session: id, text: framed(p), steers: [] });
297 continue;
298 }
299 await $.prompt.submit({ text: framed(p), asUser: true });
300 }
301 if (!isReplay) return;
302 // All queued at once, so a prompt typed meanwhile runs after them.
303 replays.push(...turns);
304 for (const turn of turns) {
305 void $.prompt.submit({ text: turn.text, asUser: true }).catch(async () => {
306 const at = replays.indexOf(turn);
307 if (at >= 0) replays.splice(at, 1);
308 await settle($);
309 });
310 }
311 await settle($);
312}
313
314// Sends a prompt of this window. The first one starts the session, named
315// here so a retried start makes no second one.
316async function send(
317 $: EngineInterface,
318 prompt: {
319 text: string;
320 images: { filename: string; dataUrl: string }[];
321 skills: { name: string }[];
322 steer?: boolean;
323 },
324) {
325 const uuid = crypto.randomUUID();
326 drawn.add(uuid);
327 if (here.id) {
328 await call($, `/sessions/${here.id}/messages`, { ...prompt, uuid });
329 return;
330 }
331 const { steer: _, ...first } = prompt;
332 const started = await call<{ id: string; cursor: number }>($, "/sessions", {
333 id: crypto.randomUUID(),
334 channelId: space(),
335 ...first,
336 uuid,
337 });
338 follow(started.id, started.cursor);
339 await showLabel($);
340}
341
342function localName(name: string): string {
343 // Claude Code asks it in its own dialog.
344 if (NATIVE.has(name) || name === "AskUserQuestion") return name;
345 const short = name.replace(/^mcp__leverage__/, "");
346 return MIRRORED.includes(short)
347 ? `mcp__leverage__${short}`
348 : "mcp__leverage__remote_tool";
349}
350
351function localInput(name: string, block: Extract<Block, { kind: "tool" }>) {
352 return localName(name) === "mcp__leverage__remote_tool"
353 ? { name: block.name, input: block.input }
354 : block.input;
355}
356
357function lines(text: string): string[] {
358 return text === "" ? [] : text.split("\n");
359}
360
361// The images of the prompt just added to this session, as data URLs.
362async function lastImages($: EngineInterface) {
363 const messages = await $.session.messages({ as: "api" });
364 const prompt = [...messages]
365 .reverse()
366 .find((message) => message.role === "user");
367 return (prompt?.content ?? []).flatMap((block, index) => {
368 const source = block.source as
369 | { type?: string; media_type?: string; data?: string }
370 | undefined;
371 if (block.type !== "image" || source?.type !== "base64") return [];
372 return [
373 {
374 filename: `image-${index + 1}.${source.media_type?.split("/")[1] ?? "png"}`,
375 dataUrl: `data:${source.media_type};base64,${source.data}`,
376 },
377 ];
378 });
379}
380
381// Where an edit's new text starts in its file, read back from the session.
382async function editLine($: EngineInterface, input: Record<string, unknown>) {
383 const path = String(input.file_path ?? "");
384 const after = String(input.new_string ?? "");
385 if (!path.startsWith("/work/") || !after) return 1;
386 try {
387 const file = await call<{ content?: string }>(
388 $,
389 `/sessions/${here.id}/file?path=${encodeURIComponent(path.slice("/work/".length))}`,
390 );
391 const at = file.content?.indexOf(after) ?? -1;
392 return at < 0 ? 1 : (file.content ?? "").slice(0, at).split("\n").length;
393 } catch {
394 return 1;
395 }
396}
397
398/** Above this many line pairs an edit draws as all removed, then all added. */
399const DIFF_LIMIT = 250_000;
400
401// The lines both sides keep show as context; the rest as removed and added.
402function lineDiff(before: string[], after: string[]): string[] {
403 const n = before.length;
404 const m = after.length;
405 if (n * m > DIFF_LIMIT) {
406 return [...before.map((l) => `-${l}`), ...after.map((l) => `+${l}`)];
407 }
408 // kept[i][j]: how many lines the rest of both sides have in common.
409 const kept = Array.from({ length: n + 1 }, () =>
410 new Array<number>(m + 1).fill(0),
411 );
412 for (let i = n - 1; i >= 0; i--) {
413 for (let j = m - 1; j >= 0; j--) {
414 kept[i]![j] =
415 before[i] === after[j]
416 ? kept[i + 1]![j + 1]! + 1
417 : Math.max(kept[i + 1]![j]!, kept[i]![j + 1]!);
418 }
419 }
420 const out: string[] = [];
421 let i = 0;
422 let j = 0;
423 while (i < n || j < m) {
424 if (i < n && j < m && before[i] === after[j]) {
425 out.push(` ${before[i]}`);
426 i++;
427 j++;
428 } else if (i < n && (j === m || kept[i + 1]![j]! >= kept[i]![j + 1]!)) {
429 out.push(`-${before[i]}`);
430 i++;
431 } else {
432 out.push(`+${after[j]}`);
433 j++;
434 }
435 }
436 return out;
437}
438
439// Builds the output shape each native tool's schema demands. `line` is where
440// an edit starts in its file.
441function nativeResult(
442 tool: string,
443 input: Record<string, unknown>,
444 content: string,
445 line = 1,
446) {
447 const path = String(input.file_path ?? "");
448 switch (tool) {
449 case "Bash":
450 return { stdout: content, stderr: "", interrupted: false };
451 case "Read": {
452 const body = content.replace(/^\s*\d+\t/gm, "");
453 const count = lines(body).length;
454 return {
455 type: "text",
456 file: {
457 filePath: path,
458 content: body,
459 numLines: count,
460 startLine: Number(input.offset ?? 1),
461 totalLines: count,
462 },
463 };
464 }
465 case "Edit": {
466 const before = lines(String(input.old_string ?? ""));
467 const after = lines(String(input.new_string ?? ""));
468 return {
469 filePath: path,
470 oldString: String(input.old_string ?? ""),
471 newString: String(input.new_string ?? ""),
472 originalFile: null,
473 structuredPatch: [
474 {
475 oldStart: line,
476 oldLines: before.length,
477 newStart: line,
478 newLines: after.length,
479 lines: lineDiff(before, after),
480 },
481 ],
482 userModified: false,
483 replaceAll: input.replace_all === true,
484 };
485 }
486 case "Write":
487 return {
488 type: "create",
489 filePath: path,
490 content: String(input.content ?? ""),
491 structuredPatch: [],
492 originalFile: null,
493 };
494 }
495 return content;
496}
497
498/** Why a hook failed, as the line its `.catch` answers with says it. */
499function why(error: HookFailure): string {
500 if (error.message) return error.message;
501 return error.kind === "timeout" ? "no answer in time" : "no answer";
502}
503
504/** The token `/leverage login` keeps in Claude Code's config; or "{}". */
505async function savedAccess($: EngineInterface): Promise<string> {
506 const file = accessPath(
507 await $.env.get("CLAUDE_CONFIG_DIR"),
508 await $.env.get("HOME"),
509 );
510 return file ? $.fs.read(file).catch(() => "{}") : "{}";
511}
512
513/** The Leverage CLI's config, where it keeps its Claude Code token; or "{}". */
514async function keptConfig($: EngineInterface): Promise<string> {
515 const file = cliConfigPath(
516 await $.env.get("LEVERAGE_CONFIG_DIR"),
517 await $.env.get("XDG_CONFIG_HOME"),
518 await $.env.get("HOME"),
519 );
520 return file ? $.fs.read(file).catch(() => "{}") : "{}";
521}
522
523export const register: Register = (on) => {
524 registerPane(on);
525 registerCommands(on);
526 registerPeople(on);
527
528 on("session.start", async ($, e, next) => {
529 const result = await next(e);
530 await $.command.register({
531 name: "leverage",
532 description: "The Leverage session: pane, approvals, files, model…",
533 argumentHint: "[help]",
534 });
535 const launched = connectLaunched({
536 url: await $.env.get("LEVERAGE_CLAUDE_URL"),
537 token: await $.env.get("LEVERAGE_CLAUDE_TOKEN"),
538 space: await $.env.get("LEVERAGE_CLAUDE_SPACE"),
539 session: await $.env.get("LEVERAGE_CLAUDE_SESSION"),
540 });
541 // Any other window, as Claude Desktop's, takes the token /leverage login
542 // keeps, or the one the Leverage CLI keeps.
543 if (!launched && !connectSaved(await savedAccess($)))
544 connectKept(await keptConfig($));
545 if (launched) {
546 for (const tool of LEVERAGE_TOOLS) await $.tool.register(tool);
547 // A window opened on a session draws it from its first turn.
548 if (here.id) {
549 const opened = await call<{ id: string; cursor: number }>(
550 $,
551 `/sessions/${here.id}`,
552 );
553 replay(opened.id, opened.cursor);
554 await call($, `/sessions/${here.id}/read`, {});
555 }
556 await showLabel($);
557 }
558 if (isReachable()) void $.ui.open({ id: PANE, title: "Leverage" });
559 // The poll runs from the start, so a later /leverage login needs no restart.
560 $.clock.every(1500, async () => {
561 if (!isClient() || !here.id || isReading) return;
562 isReading = here.replay;
563 try {
564 await poll($);
565 } finally {
566 isReading = false;
567 }
568 });
569 return result;
570 });
571
572 on("prompt.submit", async ($, e, next) => {
573 if (!isClient()) return next(e);
574 // Only what a person writes goes to Leverage. A plugin's prompt is a
575 // teammate's, already sent, unless it carries a skill.
576 const person = e.origin.kind === "composer" || e.origin.kind === "bridge";
577 // Leverage's turn took a subagent's report already; no turn reads it here.
578 const report =
579 [...here.loops.keys()].some((id) =>
580 e.text.includes(`<agent-message from="${id}">`),
581 ) ||
582 [...here.agents.keys()].some((id) =>
583 e.text.includes(`<tool-use-id>${id}</tool-use-id>`),
584 );
585 if (!person && report) {
586 return { drop: "Leverage's turn has the subagent's report." };
587 }
588 if (!person && !(e.origin.kind === "plugin" && here.skill)) {
589 return next(e);
590 }
591 // Until the session's earlier prompts are queued, this one would run first.
592 if (here.replay) {
593 void $.prompt.fill({ text: e.text }).catch(() => {});
594 return {
595 drop: "Leverage is still reading this session's earlier turns. Send it again in a moment.",
596 };
597 }
598 const skills = here.skill ? [{ name: here.skill }] : [];
599 here.skill = null;
600 // A sent prompt ends the typing the others see.
601 if (here.typedAt && here.id) {
602 here.typedAt = 0;
603 void call($, `/sessions/${here.id}/typing`, { active: false }).catch(
604 () => {},
605 );
606 }
607 const pasted =
608 e.attachments?.some((item) => item.type === "image") ?? false;
609 // Asked to wait (ctrl+x enter), it stays in Claude Code's queue, where it
610 // can be taken back, and goes to Leverage when its own turn starts. So
611 // does one typed while the session's earlier turns draw, after them.
612 if ((e.turnId && e.wait) || isReplaying()) {
613 waiting.push({ text: e.text, skills, pasted });
614 return next(e);
615 }
616 // Typed over a running turn, it steers that turn in Leverage too. Its
617 // images enter the session only later, so a steer goes without them.
618 const steer = Boolean(e.turnId);
619 const result = pasted && !steer ? await next(e) : null;
620 const images = pasted && !steer ? await lastImages($) : [];
621 await send($, { text: e.text, images, skills, steer });
622 return result ?? next(e);
623 }).catch(async ($, e, next) => {
624 if (next.called || !isClient()) return next(e);
625 // Sent nowhere, the prompt would start a turn that waits on Leverage.
626 void $.prompt.fill({ text: e.text }).catch(() => {});
627 return { drop: `Not sent to Leverage: ${why(next.error)}` };
628 });
629
630 // A prompt that waited in Claude Code's queue goes when its turn starts.
631 on("turn.start", async ($, e, next) => {
632 // A replayed prompt's turn, oldest first: those queued before it never ran.
633 const replayed = isClient()
634 ? replays.findIndex((one) => one.text === e.text)
635 : -1;
636 const turn = replays.splice(0, replayed + 1).at(-1);
637 // Queued for a session the window has since left, it draws nothing.
638 if (turn && turn.session !== here.id) stale.add(e.turnId);
639 else if (turn) replaying = e.turnId;
640 const result = await next(e);
641 if (!isClient()) return result;
642 if (stale.has(e.turnId)) {
643 await $.turn.abort({ turnId: e.turnId }).catch(() => {});
644 return result;
645 }
646 if (turn) {
647 $.ui.status(line());
648 for (const steer of turn.steers) await note($, steer);
649 return result;
650 }
651 const at = waiting.findIndex((one) => one.text === e.text);
652 if (at < 0) return result;
653 const [prompt] = waiting.splice(at, 1);
654 if (!prompt) return result;
655 const images = prompt.pasted ? await lastImages($) : [];
656 await send($, { text: prompt.text, images, skills: prompt.skills });
657 return result;
658 });
659
660 // Esc here stops the turn in the sandbox too.
661 on("turn.complete", async ($, e, next) => {
662 if (stale.delete(e.turnId)) return next(e);
663 const replayed = !e.agentId && e.turnId === replaying;
664 if (replayed) replaying = null;
665 if (isClient() && here.id && e.reason === "aborted") {
666 here.skip = here.turnId;
667 // A replayed turn ran long ago; only the session's last may run still.
668 if (!replayed || !isReplaying())
669 await call($, `/sessions/${here.id}/stop`, {});
670 }
671 if (replayed) await settle($);
672 return next(e);
673 });
674
675 // The Leverage session holds the context, so it compacts, not this window.
676 on("session.compact", async ($, e, next) => {
677 if (!isClient()) return next(e);
678 if (e.trigger !== "manual" || !here.id) {
679 return { skip: "The Leverage session compacts itself." };
680 }
681 await call($, `/sessions/${here.id}/compact`, {});
682 return { skip: "Leverage is compacting this session." };
683 }).catch(async ($, e, next) =>
684 // Compacted here, the window's copy would call a model of its own.
685 next.called || !isClient()
686 ? next(e)
687 : { skip: `Leverage did not compact this session: ${why(next.error)}` },
688 );
689
690 // One window shows one Leverage session, so these act on Leverage.
691 on("command.run", { command: "rename" }, async ($, e, next) => {
692 if (!isClient() || !here.id) return next(e);
693 const title = e.args.trim();
694 if (!title) return { text: "Name the session: /rename <title>" };
695 await call($, `/sessions/${here.id}/rename`, { title });
696 await showLabel($);
697 return { text: `Renamed the Leverage session to ${title}.` };
698 }).catch(async ($, e, next) =>
699 next.called || !isClient() || !here.id
700 ? next(e)
701 : { text: `Leverage did not rename the session: ${why(next.error)}` },
702 );
703 const resume = "/leverage opens another Leverage session in this window.";
704 on("command.run", { command: "resume" }, ($, e, next) =>
705 isClient() ? { text: resume } : next(e),
706 ).catch(async ($, e, next) => (isClient() ? { text: resume } : next(e)));
707
708 // Claude Code runs a Leverage subagent as its own agent. Its steps come
709 // from the subagent's rows in Leverage.
710 on("agent.spawn", async ($, e, next) => {
711 const subagent = here.agents.get(e.tool_use_id);
712 if (!isClient() || !subagent) return next(e);
713 // In the foreground, as in Leverage: the turn goes on once it ends.
714 const started = next({ ...e, background: false });
715 spawning.add(started);
716 try {
717 const spawned = await started;
718 if (spawned.agentId) here.loops.set(spawned.agentId, subagent);
719 return spawned;
720 } finally {
721 spawning.delete(started);
722 }
723 }).catch(async ($, e, next) =>
724 // Started without its rows, a subagent's steps would call a model here.
725 next.called || !isClient() || !here.agents.has(e.tool_use_id)
726 ? next(e)
727 : { deny: `Leverage's subagent did not start here: ${why(next.error)}` },
728 );
729
730 // Leverage ran the subagent already, so Claude Code asks nobody about it.
731 // Failed, the check is Claude Code's own, which asks.
732 on("tool.check", { tool: "Agent" }, ($, e, next) =>
733 isClient() && here.agents.has(e.tool_use_id ?? "")
734 ? { decision: "allow" }
735 : next(e),
736 ).catch(($, e, next) => next(e));
737
738 on("turn.step", async function* ($, e, next) {
739 if (!isClient()) return yield* next(e);
740 // Another session's replayed turn reads none of this one's rows.
741 if (stale.has(e.turnId)) {
742 yield { kind: "stop", stopReason: "end_turn", usage: usage(null) };
743 return {
744 turnId: e.turnId,
745 index: e.index,
746 answer: "",
747 toolUses: [],
748 stopReason: "end_turn",
749 usage: usage(null),
750 };
751 }
752 // A subagent's first step can come before its spawn names it.
753 if (e.agentId && !here.loops.has(e.agentId))
754 await Promise.allSettled([...spawning]);
755 const subagent = e.agentId ? here.loops.get(e.agentId) : undefined;
756 if (e.agentId && !subagent) return yield* next(e);
757 let step: Exclude<Step, { pending: true }>;
758 // Each message drawn as it arrives, at the block index it took.
759 const streamed: {
760 id: string;
761 kind: "text" | "thinking";
762 text: string;
763 index: number;
764 }[] = [];
765 let index = 0;
766 for (;;) {
767 if (next.signal.aborted) throw new Error("aborted");
768 const skip = here.skip ? `&skip=${here.skip}` : "";
769 const known =
770 here.known.size > 0 ? `&known=${[...here.known].join(",")}` : "";
771 const drawn = streamed.map((entry) => `${entry.id}:${entry.text.length}`);
772 const shown =
773 drawn.length > 0 ? `&shown=${encodeURIComponent(drawn.join(","))}` : "";
774 // A subagent's rows are stored whole, so its steps do not stream.
775 const answer = await call<Step>(
776 $,
777 subagent
778 ? `/sessions/${here.id}/step?after=${subagent.cursor}&task=${encodeURIComponent(subagent.task)}${known}`
779 : `/sessions/${here.id}/step?after=${here.cursor}&stream=true${skip}${known}${shown}`,
780 );
781 if (!("pending" in answer)) {
782 step = answer;
783 break;
784 }
785 if (answer.waiting) await askApprovals($, answer.waiting);
786 for (const live of answer.live ?? []) {
787 let entry = streamed.find((one) => one.id === live.id);
788 if (!entry) {
789 const kind = live.kind === "reasoning" ? "thinking" : "text";
790 entry = { id: live.id, kind, text: "", index: index++ };
791 streamed.push(entry);
792 }
793 if (!live.text.startsWith(entry.text)) continue;
794 const piece = live.text.slice(entry.text.length);
795 entry.text = live.text;
796 if (piece) yield { kind: entry.kind, index: entry.index, text: piece };
797 }
798 }
799 if (subagent) {
800 subagent.cursor = step.cursor;
801 if (step.question) here.question = step.question;
802 } else {
803 here.cursor = step.cursor;
804 here.turnId = step.turnId;
805 here.question = step.question;
806 // A replay's notices show once it reaches their rows.
807 await flush($, step.cursor);
808 // A first turn names the session.
809 if (step.stop === "end_turn") void showLabel($);
810 }
811 let answer = "";
812 const toolUses: { name: string; input: unknown }[] = [];
813 let matched = 0;
814 for (const block of step.blocks) {
815 if (block.kind === "text" || block.kind === "thinking") {
816 if (block.kind === "text") answer += block.text;
817 // A message streamed already gets the rest of its text.
818 const rest = streamed.slice(matched);
819 const entry = rest.find((one) => one.kind === block.kind);
820 if (entry && block.text.startsWith(entry.text)) {
821 matched = streamed.indexOf(entry) + 1;
822 const piece = block.text.slice(entry.text.length);
823 if (piece)
824 yield { kind: block.kind, index: entry.index, text: piece };
825 } else {
826 yield { kind: block.kind, index: index++, text: block.text };
827 }
828 } else {
829 const name = block.agent ? "Agent" : localName(block.name);
830 const input = block.agent
831 ? {
832 description: block.agent.description || "Leverage subagent",
833 prompt: block.agent.prompt,
834 // Explore runs in the background; Leverage's subagents block their turn.
835 subagent_type: "general-purpose",
836 }
837 : localInput(name, block);
838 if (block.agent) {
839 here.agents.set(block.id, {
840 task: block.agent.task,
841 cursor: step.cursor,
842 });
843 }
844 here.calls.add(block.id);
845 toolUses.push({ name, input });
846 yield { kind: "tool", index, id: block.id, name };
847 yield { kind: "input", index: index++, json: JSON.stringify(input) };
848 }
849 }
850 // A subagent ends its run in Claude Code by handing its report back.
851 let stop = step.stop;
852 if (subagent && stop === "end_turn") {
853 const input = { message: answer || "Done." };
854 toolUses.push({ name: "SubagentHandback", input });
855 const id = `toolu_handback_${subagent.task.replace(/\W/g, "_")}`;
856 yield { kind: "tool", index, id, name: "SubagentHandback" };
857 yield { kind: "input", index: index++, json: JSON.stringify(input) };
858 stop = "tool_use";
859 }
860 yield { kind: "stop", stopReason: stop, usage: usage(step.context) };
861 return {
862 turnId: e.turnId,
863 index: e.index,
864 answer,
865 toolUses,
866 stopReason: stop,
867 usage: usage(step.context),
868 };
869 });
870
871 on("tool.call", async ($, e, next) => {
872 const id = e.tool_use_id ?? "";
873 // Registered tools stay offered after logout; none runs then.
874 if (!isClient() && e.tool.startsWith("mcp__leverage__"))
875 return { deny: "This window is not connected to Leverage." };
876 if (!isClient() || !here.calls.has(id)) return next(e);
877 // Claude Code runs the subagent; its steps come from Leverage.
878 if (here.agents.has(id)) return next(e);
879 const asked = here.question === id;
880 if (asked) here.question = null;
881 if (e.tool === "AskUserQuestion" && asked) {
882 // Claude Code asks it; Leverage takes the answers as the web app does.
883 const answered = await next(e);
884 const answers =
885 (answered as { result?: { answers?: Record<string, string> } }).result
886 ?.answers ?? {};
887 // Answered in another app meanwhile: Leverage keeps that answer.
888 await call($, `/sessions/${here.id}/answers`, {
889 toolUseId: id,
890 answers,
891 }).catch(() => {});
892 return answered;
893 }
894 if (e.tool === "mcp__leverage__ExitPlanMode" && asked) {
895 const answer = await $.ui
896 .ask("Approve this plan?", {
897 header: "Plan",
898 options: ["Approve", "Request changes"],
899 })
900 .catch(() => "");
901 if (answer) {
902 const plan = answer === "Approve" ? "approved" : "changes_requested";
903 await call($, `/sessions/${here.id}/answers`, {
904 toolUseId: id,
905 answers: { plan },
906 });
907 }
908 }
909 const name = String(e.tool).replace(/^mcp__leverage__/, "");
910 $.ui.status(`${line()} · ${name} runs in Leverage`);
911 // The tool's own progress shows on the status line until its result.
912 let seen = 0;
913 let result: Exclude<Result, { pending: true }>;
914 for (;;) {
915 if (next.signal.aborted) throw new Error("aborted");
916 const answer = await call<Result>(
917 $,
918 `/sessions/${here.id}/results/${encodeURIComponent(id)}?stream=true&seen=${seen}`,
919 );
920 if (!("pending" in answer)) {
921 result = answer;
922 break;
923 }
924 if (answer.progress !== undefined) {
925 seen = answer.seen ?? seen;
926 const progress = answer.progress.trim().split("\n").at(-1) ?? "";
927 $.ui.status(`${line()} · ${name}: ${progress.slice(0, 120)}`);
928 }
929 }
930 $.ui.status(line());
931 if (e.tool === "AskUserQuestion") {
932 // Answered in another app: the answers read as that app's reply.
933 const input = e as { questions?: unknown[] };
934 return {
935 result: {
936 questions: input.questions ?? [],
937 answers: {},
938 response: result.content,
939 } as never,
940 };
941 }
942 if (result.isError) return { deny: result.content };
943 const { tool, tool_use_id: _, ...input } = e as Record<string, unknown>;
944 const startLine = tool === "Edit" ? await editLine($, input) : 1;
945 const shaped = NATIVE.has(String(tool))
946 ? nativeResult(String(tool), input, result.content, startLine)
947 : result.content;
948 return { result: shaped as never };
949 }).catch(async ($, e, next) => {
950 const id = e.tool_use_id ?? "";
951 const isLeverage =
952 e.tool.startsWith("mcp__leverage__") ||
953 (here.calls.has(id) && !here.agents.has(id));
954 // Leverage's call never runs here, whatever failed.
955 if (next.called || !isLeverage) return next(e);
956 const reason = why(next.error);
957 return { deny: `Leverage did not return this call's result: ${reason}` };
958 });
959};
960hooks/client.ts 284 lines1import type { HttpInit } from "claude-code";
2
3// Where this window reaches Leverage, shared by the plugin's modules. Each
4// module calls $.http.fetch itself: the engine follows $ only within one file.
5
6export type Connection = {
7 /** The app origin. The plugin's routes are under `/api/claude`. */
8 url: string;
9 /** A Claude Code token, which names the person and the workspace. */
10 token: string;
11 /** The space whose first prompt starts a session. */
12 space: string | null;
13};
14
15/** Where Leverage is, unless LEVERAGE_HOST names another. */
16const PRODUCTION = "https://app.leverage.computer";
17
18let connection: Connection | null = null;
19/** Where the connection came from: `leverage claude`, `/leverage login` or the CLI's config. */
20let source: "launched" | "saved" | "kept" | null = null;
21
22/** The session this window shows, and the last row it read. */
23export const here = {
24 id: "",
25 cursor: 0,
26 turnId: null as string | null,
27 /** A turn stopped here. Its remaining rows are not drawn. */
28 skip: null as string | null,
29 /** Approvals this window already asked, so none is asked twice. */
30 known: new Set<string>(),
31 /** The question this person answers in Claude Code's own dialog. */
32 question: null as string | null,
33 /** The tool calls the remote turn made. Any other call runs here. */
34 calls: new Set<string>(),
35 /** The last row the prompt and notice poll read. */
36 polled: 0,
37 /** A skill the next prompt sent from this window loads. */
38 skill: null as string | null,
39 /** When this person last told Leverage they type; 0 when they do not. */
40 typedAt: 0,
41 /** Each Leverage subagent and the last row of it drawn, by its Agent call. */
42 agents: new Map<string, Subagent>(),
43 /** The same subagents, by the Claude Code agent that runs each. */
44 loops: new Map<string, Subagent>(),
45 /** The session's turns so far are still to be drawn, from its first row. */
46 replay: false,
47 /** The session's newest row when the window opened it, where a replay ends. */
48 newest: 0,
49};
50
51/** A Leverage subagent that Claude Code runs as its own agent. */
52export type Subagent = { task: string; cursor: number };
53
54/** The prompts this window sent or already drew. */
55export const drawn = new Set<string>();
56
57/** Whether this window runs a Leverage session's turns, not only the pane. */
58let isClientWindow = false;
59
60/**
61 * Takes the connection `leverage claude` starts Claude Code with. Such a
62 * window runs a session's turns at once.
63 */
64export function connectLaunched(env: {
65 url: string | undefined;
66 token: string | undefined;
67 space: string | undefined;
68 session: string | undefined;
69}): boolean {
70 if (!env.url || !env.token) return false;
71 connection = {
72 url: env.url.replace(/\/+$/, ""),
73 token: env.token,
74 space: env.space || null,
75 };
76 if (env.session) here.id = env.session;
77 source = "launched";
78 isClientWindow = true;
79 return true;
80}
81
82/**
83 * Takes the Claude Code token the Leverage CLI keeps in its config, so any
84 * window, as Claude Desktop's, lists the sessions in the pane. The window
85 * runs a session's turns only once the person opens one there.
86 */
87export function connectKept(config: string): boolean {
88 const kept = keptToken(config);
89 if (!kept) return false;
90 connection = { ...kept, space: null };
91 source = "kept";
92 return true;
93}
94
95/** The Claude Code token in the Leverage CLI's config, and its host; or null. */
96export function keptToken(
97 config: string,
98): { url: string; token: string } | null {
99 let parsed: {
100 currentHost?: string;
101 hosts?: Record<
102 string,
103 {
104 workspaceId?: string;
105 accessTokens?: Record<string, Record<string, string>>;
106 }
107 >;
108 };
109 try {
110 parsed = JSON.parse(config);
111 } catch {
112 return null;
113 }
114 const hosts = parsed.hosts ?? {};
115 // The signed-in host first, then any other that keeps one.
116 for (const host of [parsed.currentHost, ...Object.keys(hosts)]) {
117 if (!host) continue;
118 const profile = hosts[host];
119 const token = profile?.workspaceId
120 ? profile.accessTokens?.claude?.[profile.workspaceId]
121 : undefined;
122 if (!token) continue;
123 return { url: host.replace(/\/+$/, ""), token };
124 }
125 return null;
126}
127
128/**
129 * Takes the token `/leverage login` saved in Claude Code's config. Like the
130 * CLI's, it lists the sessions in the pane until the person opens one.
131 */
132export function connectSaved(saved: string): boolean {
133 let parsed: { url?: string; token?: string };
134 try {
135 parsed = JSON.parse(saved);
136 } catch {
137 return false;
138 }
139 if (!parsed.url || !parsed.token) return false;
140 connection = {
141 url: parsed.url.replace(/\/+$/, ""),
142 token: parsed.token,
143 space: null,
144 };
145 source = "saved";
146 return true;
147}
148
149const isAbsolute = (path: string) => /^(\/|[A-Za-z]:[\\/])/.test(path);
150
151/**
152 * The file `/leverage login` keeps its token in, in Claude Code's config; or
153 * null with no home folder, so no token is ever read from or left in a project.
154 */
155export function accessPath(
156 configDir: string | undefined,
157 home: string | undefined,
158): string | null {
159 const dir = configDir || (home ? `${home}/.claude` : "");
160 return isAbsolute(dir) ? `${dir}/leverage.json` : null;
161}
162
163/** The Leverage CLI's config file; or null with no home folder. */
164export function cliConfigPath(
165 configDir: string | undefined,
166 xdg: string | undefined,
167 home: string | undefined,
168): string | null {
169 const dir =
170 configDir ||
171 (xdg ? `${xdg}/leverage` : home ? `${home}/.config/leverage` : "");
172 return isAbsolute(dir) ? `${dir}/config.json` : null;
173}
174
175/** The Leverage `/leverage login` signs in to: LEVERAGE_HOST's, or the app. */
176export function leverageHost(named: string | undefined): string {
177 const host = named?.trim();
178 if (!host) return PRODUCTION;
179 try {
180 const url = new URL(/^[a-z]+:\/\//i.test(host) ? host : `https://${host}`);
181 return /^https?:$/.test(url.protocol) ? url.origin : PRODUCTION;
182 } catch {
183 return PRODUCTION;
184 }
185}
186
187/** Leaves Leverage: this window is Claude Code's own again. */
188export function disconnect() {
189 connection = null;
190 source = null;
191 isClientWindow = false;
192 follow("", 0);
193}
194
195/** From now on, this window runs the turns of the session it follows. */
196export function becomeClient() {
197 isClientWindow = true;
198}
199
200// Remote tools drawn as tools of this mod. Others go to `remote_tool`.
201export const MIRRORED = [
202 "Grep",
203 "Glob",
204 "Task",
205 "Agent",
206 "TodoWrite",
207 "WebFetch",
208 "WebSearch",
209 "NotebookEdit",
210 "Skill",
211 "ExitPlanMode",
212 "ToolSearch",
213 "leverage_execute",
214];
215
216/** The tools a window that runs Leverage's turns registers, as registered. */
217export const LEVERAGE_TOOLS = [...MIRRORED, "remote_tool"].map((name) => ({
218 name,
219 description: `${name}, run by the Leverage session.`,
220 inputSchema: { type: "object" as const, additionalProperties: true },
221}));
222
223/** Whether the pane and /leverage can reach Leverage. */
224export function isReachable(): boolean {
225 return connection !== null;
226}
227
228export function connectedBy() {
229 return source;
230}
231
232/** Whether this window runs a Leverage session's turns. */
233export function isClient(): boolean {
234 return connection !== null && isClientWindow;
235}
236
237export function space(): string | null {
238 return connection?.space ?? null;
239}
240
241/** Moves this window to a session. Later steps read after `cursor`. */
242export function follow(id: string, cursor: number) {
243 here.id = id;
244 here.cursor = cursor;
245 here.polled = cursor;
246 here.turnId = null;
247 here.skip = null;
248 here.known.clear();
249 here.question = null;
250 here.typedAt = 0;
251 here.agents.clear();
252 here.loops.clear();
253 here.replay = false;
254 here.newest = cursor;
255}
256
257/**
258 * Moves this window to a session from its first row, so its turns so far draw
259 * again as this window's own: prompts, text, thinking, tool calls and results.
260 */
261export function replay(id: string, newest: number) {
262 follow(id, 0);
263 here.replay = true;
264 here.newest = newest;
265}
266
267export function leverageRequest(
268 path: string,
269 body?: unknown,
270): [string, HttpInit] {
271 if (!connection) throw new Error("This window is not connected to Leverage.");
272 return [
273 `${connection.url}/api/claude${path}`,
274 {
275 method: body === undefined ? "GET" : "POST",
276 headers: {
277 authorization: `Bearer ${connection.token}`,
278 "content-type": "application/json",
279 },
280 body: body === undefined ? undefined : JSON.stringify(body),
281 },
282 ];
283}
284hooks/commands.ts 636 lines1import type { EngineInterface, HttpResponse, On, Timer } from "claude-code";
2import { update } from "claude-code";
3
4import {
5 accessPath,
6 cliConfigPath,
7 connectedBy,
8 connectSaved,
9 disconnect,
10 here,
11 isReachable,
12 keptToken,
13 leverageHost,
14 leverageRequest,
15 space,
16} from "./client";
17import { PANE } from "./pane";
18
19// `/leverage <action>`: what the other Leverage apps do with a session,
20// done on the session this window shows. Bare, it opens the pane.
21
22const HELP = `/leverage open the pane: spaces and their sessions
23/leverage login [workspace] sign in in the browser
24/leverage logout forget the token here
25/leverage approvals ask again for calls that wait on you
26/leverage rename <title> rename this session (/rename does too)
27/leverage archive archive this session; restore brings it back
28/leverage model [id] [effort] show or pick the session's model
29/leverage queue prompts other apps queued for this session
30/leverage queue take <n> take a waiting prompt back
31/leverage queue send <n> send a waiting prompt now
32/leverage outputs files the last turn wrote
33/leverage files [path] this session's files, or the space's
34/leverage find <name> find a file of this session by name
35/leverage read <path> show a file of this session
36/leverage save <path> save a file of this session here
37/leverage run <command> run a shell command in the session's sandbox
38/leverage changes each repository's changes and pull request
39/leverage skills the skills this session can load
40/leverage skill <name> <prompt> send a prompt that loads a skill
41/leverage connectors the workspace's connectors`;
42
43/** The most a file shows in the transcript. */
44const SHOWN_CHARS = 20_000;
45
46async function call<T>(
47 $: EngineInterface,
48 path: string,
49 body?: unknown,
50): Promise<T> {
51 const res = await $.http.fetch(...leverageRequest(path, body));
52 if (res.status === 401)
53 throw new Error(
54 connectedBy() === "launched"
55 ? "Leverage refused this token. Run leverage claude again."
56 : "Leverage refused this token. /leverage login signs in again.",
57 );
58 if (!res.ok) {
59 const reason = (() => {
60 try {
61 return (JSON.parse(res.text) as { error?: string }).error;
62 } catch {
63 return undefined;
64 }
65 })();
66 throw new Error(reason ?? `Leverage answered ${res.status}`);
67 }
68 return JSON.parse(res.text) as T;
69}
70
71type Approval = { id: string; tool: string; input: unknown };
72type Waiting = { writable: boolean; approvals: Approval[] };
73type Model = { id: string; label: string; efforts: string[] };
74type Entry = { path: string; type?: string };
75type FileRead = { content?: string; isBinary?: boolean; truncated?: boolean };
76
77const quoted = (path: string) => encodeURIComponent(path);
78
79async function approvals($: EngineInterface): Promise<string> {
80 const waiting = await call<Waiting>($, `/sessions/${here.id}/waiting`);
81 if (waiting.approvals.length === 0) return "No call waits for approval.";
82 if (!waiting.writable) return "Calls wait for the session owner's approval.";
83 for (const pending of waiting.approvals) {
84 const answer = await $.ui
85 .ask(
86 `Allow ${pending.tool} to run in Leverage? ${JSON.stringify(pending.input).slice(0, 300)}`,
87 {
88 header: "Approval",
89 options: ["Once", "This session", "Always", "Reject"],
90 },
91 )
92 .catch(() => "");
93 if (!answer) continue;
94 here.known.add(pending.id);
95 const decision =
96 { Once: "once", "This session": "session", Always: "always" }[answer] ??
97 "reject";
98 await call($, `/approvals/${pending.id}`, {
99 decision,
100 ...(answer === "Reject" || decision !== "reject"
101 ? {}
102 : { reason: answer }),
103 });
104 }
105 return "Decided.";
106}
107
108async function model($: EngineInterface, args: string[]): Promise<string> {
109 const [id, effort] = args;
110 if (id) {
111 await call($, `/sessions/${here.id}/model`, {
112 model: id,
113 ...(effort ? { effort } : {}),
114 });
115 return `The session runs ${id}${effort ? ` at ${effort}` : ""} from the next turn.`;
116 }
117 const [models, session] = await Promise.all([
118 call<Model[]>($, "/models"),
119 call<{ model: string | null; effort: string | null }>(
120 $,
121 `/sessions/${here.id}`,
122 ),
123 ]);
124 const lines = models.map(
125 (one) =>
126 `${one.id === session.model ? "●" : "○"} ${one.id} ${one.label}${one.efforts.length ? ` (${one.efforts.join(", ")})` : ""}`,
127 );
128 return [
129 `Now: ${session.model ?? "the space's default"}${session.effort ? ` at ${session.effort}` : ""}`,
130 ...lines,
131 "Pick one: /leverage model <id> [effort]",
132 ].join("\n");
133}
134
135async function queue($: EngineInterface, args: string[]): Promise<string> {
136 const items = await call<{ uuid: string; text: string }[]>(
137 $,
138 `/sessions/${here.id}/queue`,
139 );
140 const [action, number] = args;
141 if (!action) {
142 if (items.length === 0) return "No prompt waits.";
143 return items
144 .map((item, index) => `${index + 1}. ${item.text.slice(0, 120)}`)
145 .join("\n");
146 }
147 const item = items[Number(number) - 1];
148 if (!item) return `No waiting prompt ${number ?? ""}.`;
149 if (action === "take") {
150 await call($, `/sessions/${here.id}/queue/${item.uuid}/cancel`, {});
151 return "Taken back.";
152 }
153 if (action === "send") {
154 await call($, `/sessions/${here.id}/queue/${item.uuid}/send`, {});
155 return "Sent now.";
156 }
157 return "Use: /leverage queue [take|send] <n>";
158}
159
160async function files($: EngineInterface, path: string): Promise<string> {
161 const at = here.id
162 ? `/sessions/${here.id}/files?path=${quoted(path)}`
163 : `/spaces/${space()}/files?path=${quoted(path)}`;
164 const listed = await call<{ entries: Entry[]; truncated?: boolean }>($, at);
165 if (listed.entries.length === 0) return "No files here.";
166 const lines = listed.entries.map(
167 (entry) => `${entry.path}${entry.type === "dir" ? "/" : ""}`,
168 );
169 return [...lines, ...(listed.truncated ? ["…more"] : [])].join("\n");
170}
171
172// A file of the session, or of the space before a session starts.
173async function readFile($: EngineInterface, path: string): Promise<FileRead> {
174 return call<FileRead>(
175 $,
176 here.id
177 ? `/sessions/${here.id}/file?path=${quoted(path)}`
178 : `/spaces/${space()}/file?path=${quoted(path)}`,
179 );
180}
181
182// Shows a file in the transcript, or saves it in the working folder.
183async function readOrSave(
184 $: EngineInterface,
185 action: "read" | "save",
186 path: string,
187): Promise<string> {
188 if (!path) return `Name the file: /leverage ${action} <path>`;
189 const file = await readFile($, path);
190 if (action === "save") {
191 if (file.content === undefined) return "Leverage cannot read that file.";
192 const name = path.split("/").at(-1) ?? "output";
193 await $.fs.write(name, file.content);
194 return `Saved ${name}.`;
195 }
196 if (file.isBinary || file.content === undefined)
197 return "Not a text file. /leverage save keeps it here.";
198 return file.content.length > SHOWN_CHARS
199 ? `${file.content.slice(0, SHOWN_CHARS)}\n…`
200 : file.content;
201}
202
203async function run($: EngineInterface, args: string): Promise<string> {
204 const [action = "", ...rest] = args.trim().split(/\s+/);
205 const tail = args.trim().slice(action.length).trim();
206 if (action === "help") return HELP;
207 if (action === "connectors") {
208 const connectors = await call<{ name: string; disabled: boolean }[]>(
209 $,
210 "/connectors",
211 );
212 return connectors.length === 0
213 ? "No connectors in this workspace."
214 : connectors
215 .map((one) => `${one.disabled ? "○" : "●"} ${one.name}`)
216 .join("\n");
217 }
218 if (!here.id && action === "files") return files($, tail);
219 if (!here.id && (action === "read" || action === "save"))
220 return readOrSave($, action, tail);
221 if (!here.id) return "Send a first prompt, or open a session with /leverage.";
222 switch (action) {
223 case "approvals":
224 return approvals($);
225 case "rename":
226 if (!tail) return "Name the session: /leverage rename <title>";
227 await call($, `/sessions/${here.id}/rename`, { title: tail });
228 $.ui.status(tail);
229 return `Renamed the session to ${tail}.`;
230 case "archive":
231 await call($, `/sessions/${here.id}/archive`, {});
232 return "Archived. /leverage restore brings it back.";
233 case "restore":
234 await call($, `/sessions/${here.id}/restore`, {});
235 return "Restored.";
236 case "model":
237 return model($, rest);
238 case "queue":
239 return queue($, rest);
240 case "outputs": {
241 const outputs = await call<string[]>($, `/sessions/${here.id}/outputs`);
242 return outputs.length === 0
243 ? "The last turn wrote no files."
244 : `${outputs.join("\n")}\n/leverage read <path> shows one; /leverage save <path> keeps it here.`;
245 }
246 case "files":
247 return files($, tail);
248 case "find": {
249 if (!tail) return "Name part of the file: /leverage find <name>";
250 const found = await call<string[]>(
251 $,
252 `/sessions/${here.id}/find?name=${quoted(tail)}`,
253 );
254 return found.length === 0 ? "No file matches." : found.join("\n");
255 }
256 case "read":
257 case "save":
258 return readOrSave($, action, tail);
259 case "run": {
260 if (!tail) return "Name the command: /leverage run <command>";
261 const ran = await call<{ exitCode: number; output: string }>(
262 $,
263 `/sessions/${here.id}/run`,
264 { command: tail },
265 );
266 const output =
267 ran.output.length > SHOWN_CHARS
268 ? `${ran.output.slice(-SHOWN_CHARS)}`
269 : ran.output;
270 return `${output}${output.endsWith("\n") || !output ? "" : "\n"}exit ${ran.exitCode}`;
271 }
272 case "changes": {
273 const repos = await call<
274 {
275 name: string;
276 branch: string | null;
277 changes: {
278 path: string;
279 state: string;
280 additions: number;
281 deletions: number;
282 }[];
283 unpublished: number;
284 pullRequest: {
285 number: number;
286 url: string;
287 state: string;
288 draft: boolean;
289 } | null;
290 }[]
291 >($, `/sessions/${here.id}/changes`);
292 if (repos.length === 0) return "This session has no repository.";
293 return repos
294 .map((repo) => {
295 const head = `${repo.name}${repo.branch ? ` (${repo.branch})` : ""}`;
296 const pr = repo.pullRequest
297 ? `PR #${repo.pullRequest.number} ${repo.pullRequest.draft ? "draft" : repo.pullRequest.state}: ${repo.pullRequest.url}`
298 : "No pull request.";
299 const changed = repo.changes.map(
300 (change) =>
301 ` ${change.state} ${change.path} +${change.additions} -${change.deletions}`,
302 );
303 const unpublished =
304 repo.unpublished > 0
305 ? [` ${repo.unpublished} change(s) not in the pull request`]
306 : [];
307 return [
308 head,
309 ...(changed.length ? changed : [" no changes"]),
310 ...unpublished,
311 pr,
312 ].join("\n");
313 })
314 .join("\n\n");
315 }
316 case "skills": {
317 const skills = await call<{ name: string; description: string }[]>(
318 $,
319 `/sessions/${here.id}/skills`,
320 );
321 return skills.length === 0
322 ? "No skills."
323 : `${skills.map((one) => `${one.name} ${one.description}`).join("\n")}\n/leverage skill <name> <prompt> sends a prompt that loads one.`;
324 }
325 case "skill": {
326 const [name, ...words] = rest;
327 const prompt = words.join(" ");
328 if (!name || !prompt) return "Use: /leverage skill <name> <prompt>";
329 // The prompt goes through this window, so Claude Code draws its turn.
330 here.skill = name;
331 await $.prompt.submit({ text: prompt, asUser: true });
332 return `Sent with the ${name} skill.`;
333 }
334 }
335 return HELP;
336}
337
338// `/leverage login` and `/leverage logout`: the token this plugin keeps in
339// Claude Code's config. Login signs in in the browser, as `leverage login`
340// does, and trades that sign-in for a Claude Code token of one workspace.
341
342type Grant = {
343 device_code: string;
344 user_code: string;
345 expires_in: number;
346 interval: number;
347};
348type Workspace = { id: string; slug: string; name: string };
349
350/** The browser sign-in that waits for its approval, if one does. */
351let waiting: Timer | null = null;
352/** Counts sign-ins; login and logout move it on, so an older one keeps nothing. */
353let attempt = 0;
354
355function stopWaiting() {
356 waiting?.cancel();
357 waiting = null;
358 attempt++;
359}
360
361async function accessFile($: EngineInterface): Promise<string | null> {
362 return accessPath(
363 await $.env.get("CLAUDE_CONFIG_DIR"),
364 await $.env.get("HOME"),
365 );
366}
367
368async function cliHasToken($: EngineInterface): Promise<boolean> {
369 const file = cliConfigPath(
370 await $.env.get("LEVERAGE_CONFIG_DIR"),
371 await $.env.get("XDG_CONFIG_HOME"),
372 await $.env.get("HOME"),
373 );
374 const config = file ? await $.fs.read(file).catch(() => "{}") : "{}";
375 return keptToken(config) !== null;
376}
377
378function send(
379 $: EngineInterface,
380 url: string,
381 body?: unknown,
382 token?: string,
383): Promise<HttpResponse> {
384 return $.http.fetch(url, {
385 method: body === undefined ? "GET" : "POST",
386 headers: {
387 "content-type": "application/json",
388 ...(token ? { authorization: `Bearer ${token}` } : {}),
389 },
390 body: body === undefined ? undefined : JSON.stringify(body),
391 });
392}
393
394// Opens the approval page. Where no browser opens, the reply has the link.
395async function browse($: EngineInterface, link: string) {
396 for (const opener of ["open", "xdg-open"]) {
397 const opened = await $.process
398 .run([opener, link], { timeoutMs: 5000 })
399 .catch(() => null);
400 if (opened?.exitCode === 0) return;
401 }
402}
403
404// Keeps the token where only this person reads it, and connects this window.
405async function keep(
406 $: EngineInterface,
407 url: string,
408 token: string,
409 live: () => boolean,
410): Promise<string> {
411 const checked = await send(
412 $,
413 `${url}/api/claude/workspace`,
414 undefined,
415 token,
416 );
417 if (checked.status === 401) return "Leverage refused that token.";
418 if (!checked.ok) return `Leverage answered ${checked.status}.`;
419 const { workspace } = JSON.parse(checked.text) as { workspace: string };
420 const file = await accessFile($);
421 if (!file) return "No home folder to keep the token in.";
422 if (!live()) return "";
423 const saved = `${JSON.stringify({ url, token }, null, "\t")}\n`;
424 // Windows keeps a profile's files to its owner, and has no sh.
425 const written = /^[A-Za-z]:/.test(file)
426 ? await $.fs.write(file, saved).then(
427 () => ({ exitCode: 0 }),
428 () => null,
429 )
430 : await $.process
431 .run(
432 [
433 "/bin/sh",
434 "-c",
435 'umask 077 && mkdir -p "$(dirname "$1")" && cat > "$1" && chmod 600 "$1"',
436 "sh",
437 file,
438 ],
439 { stdin: saved },
440 )
441 .catch(() => null);
442 if (written?.exitCode !== 0) return `Could not keep the token in ${file}.`;
443 if (!live()) {
444 await $.process.run(["rm", "-f", file]).catch(() => null);
445 return "";
446 }
447 // A new token may name another workspace: nothing of the last one stays.
448 disconnect();
449 await update($, { plugin: "leverage", key: "tree" }, () => null);
450 connectSaved(saved);
451 void $.ui.open({ id: PANE, title: "Leverage" });
452 return `Signed in to ${workspace}. /leverage opens the pane.`;
453}
454
455// The workspace named, the only one, or the one the person picks.
456async function choose(
457 $: EngineInterface,
458 workspaces: Workspace[],
459 named: string,
460): Promise<Workspace | string> {
461 if (named) {
462 const found =
463 workspaces.find((one) => one.slug === named) ??
464 workspaces.find((one) => one.name === named);
465 return found ?? `No workspace ${named}.`;
466 }
467 if (workspaces.length === 1) return workspaces[0] as Workspace;
468 // Claude Code's dialog shows four at most.
469 if (workspaces.length > 4) {
470 const slugs = workspaces.map((one) => one.slug).join(", ");
471 return `Name the workspace: /leverage login <workspace>. Yours: ${slugs}.`;
472 }
473 // Two workspaces may share a name, never a slug.
474 const labels = workspaces.map((one) =>
475 workspaces.filter((other) => other.name === one.name).length > 1
476 ? `${one.name} (${one.slug})`
477 : one.name,
478 );
479 const picked = await $.ui
480 .ask("Which Leverage workspace?", { header: "Leverage", options: labels })
481 .catch(() => "");
482 return workspaces[labels.indexOf(picked)] ?? "Sign-in stopped.";
483}
484
485// Trades the browser sign-in for a Claude Code token of one workspace.
486async function trade(
487 $: EngineInterface,
488 url: string,
489 access: string,
490 named: string,
491 live: () => boolean,
492): Promise<string> {
493 const listed = await send($, `${url}/api/workspaces`, undefined, access);
494 if (!listed.ok) return `Leverage answered ${listed.status}.`;
495 const workspaces = JSON.parse(listed.text) as Workspace[];
496 if (workspaces.length === 0)
497 return "Your Leverage account has no workspace yet.";
498 const chosen = await choose($, workspaces, named);
499 if (typeof chosen === "string") return chosen;
500 if (!live()) return "";
501 const minted = await send(
502 $,
503 `${url}/api/workspaces/${chosen.id}/claude/token`,
504 {},
505 access,
506 );
507 if (!minted.ok) return `Leverage answered ${minted.status}.`;
508 return keep(
509 $,
510 url,
511 (JSON.parse(minted.text) as { token: string }).token,
512 live,
513 );
514}
515
516// Asks every few seconds whether the person approved the code.
517function awaitApproval(
518 $: EngineInterface,
519 url: string,
520 grant: Grant,
521 named: string,
522) {
523 let asked = 0;
524 let skip = 0;
525 let busy = false;
526 const mine = attempt;
527 const live = () => mine === attempt;
528 const end = (text: string) => {
529 timer.cancel();
530 if (waiting === timer) waiting = null;
531 if (live() && text) $.ui.toast(text, { timeoutMs: 8000 });
532 };
533 const timer = $.clock.every(grant.interval * 1000, async () => {
534 if (busy) return;
535 if (skip > 0) {
536 skip--;
537 return;
538 }
539 if (++asked * grant.interval > grant.expires_in)
540 return end("The sign-in code expired. /leverage login starts again.");
541 busy = true;
542 try {
543 // A code is good once, so its answer is always read to the end. A
544 // network error leaves the code waiting: the next tick asks again.
545 const res = await send($, `${url}/api/cli/auth/token`, {
546 device_code: grant.device_code,
547 }).catch(() => null);
548 if (!res) return;
549 // Not approved yet, or Leverage is busy: ask again later.
550 if (res.status === 428 || res.status >= 500) return;
551 if (res.status === 429) {
552 skip = 1;
553 return;
554 }
555 if (res.status === 410 && res.text.includes("denied"))
556 return end("Sign-in denied.");
557 if (res.status === 410 || res.status === 404)
558 return end("The sign-in code expired. /leverage login starts again.");
559 if (!res.ok) return end(`Leverage answered ${res.status}.`);
560 timer.cancel();
561 const { access_token } = JSON.parse(res.text) as {
562 access_token: string;
563 };
564 end(await trade($, url, access_token, named, live));
565 } catch (error) {
566 end(`Leverage: ${(error as Error).message}`);
567 } finally {
568 busy = false;
569 }
570 });
571 waiting = timer;
572}
573
574/** `/leverage login [workspace]`. A token is never typed: the transcript keeps commands. */
575async function login($: EngineInterface, arg: string): Promise<string> {
576 if (connectedBy() === "launched")
577 return "This window runs with the token leverage claude started it with.";
578 stopWaiting();
579 if (!(await accessFile($))) return "No home folder to keep the token in.";
580 const url = leverageHost(await $.env.get("LEVERAGE_HOST"));
581 const started = await send($, `${url}/api/cli/auth/device`, {
582 client_name: "Claude Code",
583 });
584 if (started.status === 429)
585 return "Leverage asks you to wait a minute, then sign in again.";
586 if (!started.ok) return `Leverage answered ${started.status}.`;
587 const grant = JSON.parse(started.text) as Grant;
588 const link = `${url}/device?user_code=${encodeURIComponent(grant.user_code)}`;
589 await browse($, link);
590 awaitApproval($, url, grant, arg);
591 return `Confirm ${grant.user_code} in the browser: ${link}`;
592}
593
594/** `/leverage logout`: forgets the token and leaves Leverage in this window. */
595async function logout($: EngineInterface): Promise<string> {
596 if (connectedBy() === "launched")
597 return "This window runs with the token leverage claude started it with.";
598 stopWaiting();
599 const file = await accessFile($);
600 if (file && (await $.fs.exists(file).catch(() => false))) {
601 const removed = await $.process.run(["rm", "-f", file]).catch(() => null);
602 if (removed?.exitCode !== 0) await $.fs.write(file, "{}\n");
603 }
604 disconnect();
605 await $.ui.close({ id: PANE }).catch(() => {});
606 $.ui.status(undefined);
607 // The token itself ends only when Leverage revokes it.
608 const revoke = "Leverage Settings → Integrations revokes the token.";
609 return (await cliHasToken($))
610 ? `Signed out here. ${revoke} The Leverage CLI keeps its own: leverage logout ends it.`
611 : `Signed out. ${revoke}`;
612}
613
614export function registerCommands(on: On) {
615 on("command.run", { command: "leverage" }, async ($, e) => {
616 const [action = "", ...rest] = e.args.trim().split(/\s+/);
617 try {
618 if (action === "login") return { text: await login($, rest.join(" ")) };
619 if (action === "logout") return { text: await logout($) };
620 } catch (error) {
621 return { text: `Leverage: ${(error as Error).message}` };
622 }
623 if (!isReachable())
624 return { text: "Not signed in to Leverage. /leverage login signs in." };
625 if (!e.args.trim()) {
626 await $.ui.open({ id: PANE, title: "Leverage" });
627 return { text: "Leverage pane opened. /leverage help lists the rest." };
628 }
629 try {
630 return { text: await run($, e.args) };
631 } catch (error) {
632 return { text: `Leverage: ${(error as Error).message}` };
633 }
634 });
635}
636hooks/pane.tsx 236 lines1import type { EngineInterface, On } from "claude-code";
2import { atom, read, update } from "claude-code";
3
4import type { PaneSession, WorkspaceTree } from "../types";
5import {
6 becomeClient,
7 here,
8 isClient,
9 isReachable,
10 LEVERAGE_TOOLS,
11 leverageRequest,
12 replay,
13} from "./client";
14
15// The Leverage pane, drawn as Claude's session sidebar: the workspace's
16// channels and their sessions. A press on a session moves this window to
17// that session.
18
19export const PANE = "leverage";
20let isRefreshing = false;
21const tree = atom({ plugin: "leverage", key: "tree" } as const, null);
22/** The text the session titles must hold; empty lists them all. */
23const search = atom({ plugin: "leverage", key: "search" } as const, "");
24/** The spaces that list all their sessions, not the first few. */
25const more = atom({ plugin: "leverage", key: "more" } as const, [] as string[]);
26/** How many sessions a space lists before its "more" row. */
27const FEW = 8;
28
29// As in Claude's sidebar, only a session that works or waits shows a mark.
30const MARK: Record<string, string> = {
31 active: "claude",
32 running: "claude",
33 awaiting_input: "permission",
34};
35
36async function call<T>(
37 $: EngineInterface,
38 path: string,
39 body?: unknown,
40): Promise<T> {
41 const res = await $.http.fetch(...leverageRequest(path, body));
42 if (!res.ok) {
43 const reason = (() => {
44 try {
45 return (JSON.parse(res.text) as { error?: string }).error;
46 } catch {
47 return undefined;
48 }
49 })();
50 throw new Error(reason ?? `Leverage answered ${res.status}`);
51 }
52 return JSON.parse(res.text) as T;
53}
54
55async function refresh($: EngineInterface) {
56 if (!isReachable()) return;
57 const asked = await read($, search);
58 const next = await call<Omit<WorkspaceTree, "attached">>(
59 $,
60 `/workspace${asked ? `?query=${encodeURIComponent(asked)}` : ""}`,
61 );
62 await update($, tree, () => ({ ...next, attached: here.id }));
63}
64
65/** A row's fill when it is the session here, or under the pointer. */
66const LIT: Record<string, string> = {
67 terminal: "userMessageBackground",
68 other: "promptBorderShimmer",
69};
70/** No color: a row's border that only rounds its fill. */
71const CLEAR = "#00000000";
72
73export function registerPane(on: On) {
74 on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
75 const elements = $.ui.resolve(e);
76 const { Box, Text, Button } = elements;
77 const isTerminal = e.surface === "terminal";
78 // A phone has no text field: it lists every session.
79 const Input = "Input" in elements ? elements.Input : null;
80 const lit = isTerminal ? LIT.terminal : LIT.other;
81 const asked = await read($, search);
82 const open = await read($, more);
83 // The first drawing starts the refresh. A timer outlives this dispatch.
84 if (!isRefreshing) {
85 isRefreshing = true;
86 void refresh($);
87 $.clock.every(5000, () => refresh($));
88 }
89 const data = await read($, tree);
90 if (!data) {
91 return (
92 <Text dimColor wrap="wrap">
93 Connecting to Leverage… If it never does, /leverage login signs in.
94 </Text>
95 );
96 }
97
98 const attach = async (session: PaneSession) => {
99 if (session.id === data.attached) return;
100 const opened = await call<{ id: string; cursor: number }>(
101 $,
102 `/sessions/${session.id}`,
103 );
104 // From here the window runs the session's turns in Leverage.
105 if (!isClient()) {
106 for (const tool of LEVERAGE_TOOLS) await $.tool.register(tool);
107 becomeClient();
108 }
109 // One window mirrors one session, so the old transcript goes.
110 await $.command.run({ command: "clear" });
111 // The window draws the session from its first turn, as Leverage shows it.
112 replay(opened.id, opened.cursor);
113 $.ui.status(session.title);
114 // Opened, it reads as read.
115 await call($, `/sessions/${session.id}/read`, {});
116 await refresh($);
117 };
118
119 /** A one-column mark in a theme color, or the room for one. */
120 const mark = (key: string, color: string | undefined, glyph = "●") => (
121 <Box key={key} width={1} flexShrink={0}>
122 {color ? <Text color={color}>{glyph}</Text> : null}
123 </Box>
124 );
125
126 const row = (session: PaneSession) => {
127 const isHere = session.id === data.attached;
128 return (
129 <Box
130 key={`row-${session.id}`}
131 flexDirection="row"
132 alignItems="center"
133 gap={1}
134 paddingX={1}
135 {...(isTerminal
136 ? {}
137 : {
138 minHeight: 1.5,
139 borderStyle: "round",
140 borderColor: CLEAR,
141 paddingY: 0,
142 })}
143 {...(isHere ? { backgroundColor: lit } : {})}
144 hover={{ backgroundColor: lit }}
145 >
146 {mark(`mark-${session.id}`, MARK[session.status])}
147 <Box flexGrow={1} flexShrink={1} minWidth={0}>
148 <Button
149 key={isHere ? `here-${session.id}` : `s-${session.id}`}
150 plain
151 label={session.title}
152 hover={{ backgroundColor: CLEAR }}
153 onPress={() => (isHere ? refresh($) : attach(session))}
154 />
155 </Box>
156 </Box>
157 );
158 };
159
160 const sessions = (owner: string, list: PaneSession[]) => {
161 const listed = open.includes(owner) ? list : list.slice(0, FEW);
162 return [
163 ...listed.map(row),
164 ...(list.length > listed.length
165 ? [
166 <Box key={`more-row-${owner}`} paddingLeft={4}>
167 <Button
168 key={`more-${owner}`}
169 label={`${list.length - listed.length} more`}
170 plain
171 dimColor
172 onPress={() =>
173 void update($, more, (ids) => [...(ids ?? []), owner])
174 }
175 />
176 </Box>,
177 ]
178 : []),
179 ];
180 };
181
182 /** A space's name. */
183 const heading = (key: string, name: string) => (
184 <Box key={key} paddingX={1} marginTop={1}>
185 <Text dimColor bold>
186 {name}
187 </Text>
188 </Box>
189 );
190
191 return (
192 <Box flexDirection="column">
193 <Box
194 flexDirection="row"
195 alignItems="center"
196 justifyContent="space-between"
197 gap={2}
198 paddingX={1}
199 >
200 <Text bold wrap="truncate">
201 {data.workspace}
202 </Text>
203 {Input ? (
204 <Input
205 key="search"
206 placeholder="Search sessions"
207 value={asked}
208 onSubmit={async (value: string) => {
209 await update($, search, () => value.trim());
210 await refresh($);
211 }}
212 />
213 ) : null}
214 </Box>
215 {data.channels.map((channel) => (
216 <Box key={channel.id} flexDirection="column">
217 {heading(`heading-${channel.id}`, `#${channel.name}`)}
218 {sessions(channel.id, channel.sessions)}
219 {channel.sessions.length === 0 ? (
220 <Box paddingLeft={4}>
221 <Text dimColor>No sessions yet</Text>
222 </Box>
223 ) : null}
224 </Box>
225 ))}
226 {data.direct.length > 0 && (
227 <Box flexDirection="column">
228 {heading("heading-direct", "Private")}
229 {sessions("direct", data.direct)}
230 </Box>
231 )}
232 </Box>
233 );
234 });
235}
236hooks/people.tsx 99 lines1import type { EngineInterface, On } from "claude-code";
2import { atom, read } from "claude-code";
3
4import type { Room, Viewer } from "../types";
5import { here, isClient, leverageRequest } from "./client";
6
7// Who else is in the Leverage session, and who types there, above the prompt.
8// The others see this person type, as in their own apps.
9
10/** What the last prompt poll saw. */
11const people = atom(
12 { plugin: "leverage", key: "people" } as const,
13 {
14 viewers: [],
15 typing: [],
16 } as Room,
17);
18
19/** Leverage forgets a typing signal after 5 s, so a typist sends it again sooner. */
20const TYPING_MS = 3_000;
21
22const APP: Record<string, string> = {
23 "leverage/web": "web",
24 "leverage/desktop": "desktop app",
25 "leverage/mobile": "phone",
26 "leverage/cli": "terminal",
27 codex: "Codex",
28 opencode: "OpenCode",
29 claude: "Claude Code",
30};
31
32/** What shows after a name: " (idle, on web & Codex)". The web alone is not said. */
33function about(viewer: Viewer): string {
34 const apps = viewer.apps.filter((app) => Object.hasOwn(APP, app));
35 const where = apps.some((app) => app !== "leverage/web")
36 ? `on ${apps.map((app) => APP[app]).join(" & ")}`
37 : "";
38 const parts = [viewer.state === "idle" ? "idle" : "", where].filter(Boolean);
39 return parts.length > 0 ? ` (${parts.join(", ")})` : "";
40}
41
42function typingLine(names: string[]): string {
43 if (names.length === 1) return `${names[0]} is typing…`;
44 return `${names.slice(0, -1).join(", ")} and ${names.at(-1)} are typing…`;
45}
46
47async function signal($: EngineInterface, active: boolean) {
48 if (!here.id) return;
49 await $.http
50 .fetch(...leverageRequest(`/sessions/${here.id}/typing`, { active }))
51 .catch(() => {});
52}
53
54export function registerPeople(on: On) {
55 on("prompt.edit", async ($, e, next) => {
56 const box = await next(e);
57 if (!isClient() || !here.id) return box;
58 const now = await $.clock.now();
59 if (!box.text.trim()) {
60 if (here.typedAt) void signal($, false);
61 here.typedAt = 0;
62 } else if (now - here.typedAt > TYPING_MS) {
63 here.typedAt = now;
64 void signal($, true);
65 }
66 return box;
67 });
68
69 on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
70 if (!isClient() || e.props.hasSurvey) return next(e);
71 const { viewers, typing } = await read($, people);
72 if (viewers.length === 0 && typing.length === 0) return next(e);
73 const { Box, Text } = $.ui.resolve(e);
74 return (
75 <Box flexDirection="column">
76 {viewers.length > 0 ? (
77 <Text wrap="truncate">
78 {viewers.map((viewer, at) => (
79 <Text key={viewer.name}>
80 {at > 0 ? " · " : ""}
81 <Text color={viewer.state === "idle" ? "warning" : "success"}>
82 {viewer.state === "idle" ? "◐" : "●"}
83 </Text>{" "}
84 {viewer.name}
85 <Text dimColor>{about(viewer)}</Text>
86 </Text>
87 ))}
88 </Text>
89 ) : null}
90 {typing.length > 0 ? (
91 <Text dimColor italic>
92 {typingLine(typing)}
93 </Text>
94 ) : null}
95 </Box>
96 );
97 });
98}
99types/index.d.ts 29 lines1/** Someone else who has the Leverage session open, and the apps they use. */
2export type Viewer = { name: string; state: "active" | "idle"; apps: string[] };
3/** Who else has the session open, and the names of those who type in it. */
4export type Room = { viewers: Viewer[]; typing: string[] };
5
6export type PaneSession = { id: string; title: string; status: string };
7export type PaneChannel = {
8 id: string;
9 name: string;
10 sessions: PaneSession[];
11};
12export type WorkspaceTree = {
13 workspace: string;
14 attached: string;
15 channels: PaneChannel[];
16 direct: PaneSession[];
17};
18
19declare module "claude-code" {
20 interface PluginState {
21 leverage: {
22 tree: WorkspaceTree | null;
23 search: string;
24 more: string[];
25 people: Room;
26 };
27 }
28}
29