Shows pasted text in full in the prompt box and the transcript, and previews pasted images above the prompt and under the sent message.

Skills, mods, hooks and a status line for Claude Code, plus a sync engine that keeps your Claude Code config the same on all your computers. Every part is tested on macOS, Linux and Windows on each change.
Every part is a plugin of this repo's marketplace. Add it once, then install the parts you want, from Claude Code:
/plugin marketplace add robinalexandre/claude-code-kit
# Every day, for anyone
/plugin install team@claude-code-kit
/plugin install statusline@claude-code-kit
/plugin install file-tools-guard@claude-code-kit
/plugin install recent-prompts@claude-code-kit
/plugin install dnd@claude-code-kit
/plugin install paste-preview@claude-code-kit
/plugin install recent-activity@claude-code-kit
/plugin install session-registry@claude-code-kit
/plugin install drift-check@claude-code-kit
/plugin install drift-check-hook@claude-code-kit
/plugin install nocturne-notify@claude-code-kit
# Development work
/plugin install git-identity-guard@claude-code-kit
/plugin install pr-watch@claude-code-kit
/plugin install pr-pane@claude-code-kit
/plugin install test-evidence@claude-code-kit
/plugin install ci-review@claude-code-kit
/plugin install capability-builder@claude-code-kit
/plugin install learn@claude-code-kit
/plugin install kb@claude-code-kit
# Several computers
/plugin install config-sync@claude-code-kit
/plugin install handoff@claude-code-kit
/plugin install daily-sync@claude-code-kit
/plugin install reminders@claude-code-kit
/plugin install reminders-handoffs@claude-code-kit
# Not dev
/plugin install video-montage@claude-code-kit
/plugin install insta360-montage@claude-code-kit
From a terminal it's the same with claude plugin marketplace add … and claude plugin install …; or /plugin alone to browse the parts. What a part needs comes with it: pr-pane brings pr-watch; reminders brings daily-sync, which brings config-sync. Start a new session afterwards.
Keep them up to date: Claude Code doesn't auto-update a marketplace other than Anthropic's own unless you turn it on, once: /plugin → Marketplaces → claude-code-kit → Enable auto-update. It then updates the parts in the background after a session starts (and asks for a restart). Or set it in ~/.claude/settings.json:
"extraKnownMarketplaces": {
"claude-code-kit": { "source": { "source": "github", "repo": "robinalexandre/claude-code-kit" }, "autoUpdate": true }
}
By hand: claude plugin marketplace update claude-code-kit, then claude plugin update <part>@claude-code-kit.
Setup: a part that needs a few answers (the status line in your settings, the emails for the email guard, where pr-watch looks, the phone for reminders, your private repo for config-sync, the zsh line for session-registry) says so at the first session after install, and Claude gives you the command to run in your terminal; it stops asking once it's done or you say no. Options: the language of the team rules and the opening text of drift-check are asked when you install from /plugin, and changed with claude plugin configure <part>@claude-code-kit.
The installer copies the parts you pick into ~/.claude instead. Use it to pick from a checklist, to install without a marketplace, or to edit your copies. A part already installed as a plugin is skipped.
Keep them up to date: the installer also adds a small session-start check (kit-update-check). Once a day, in the background, it fetches the clone you installed from. When that clone has changes for the parts you installed, or new parts you could add, Claude tells you at the next session start what changed and offers to update. ./install.sh --update pulls the clone and installs the changed parts again, without asking their setup questions again; ./install.sh --update <new part>… adds new ones too. Each new part is mentioned once. Turn the check off with bash ~/.claude/hooks/kit-update-check.sh off (on to resume). What came from where is recorded in ~/.claude/kit-install.json.
git clone https://github.com/robinalexandre/claude-code-kit.git
cd claude-code-kit
./install.sh # a checklist: arrows, Enter to pick, → for what each part does, then Install
./install.sh --plain # the same as one question per part
./install.sh --list # lists the parts
./install.sh --all # installs every part offered on this computer
./install.sh statusline file-tools-guard # installs the named parts
./install.sh --update # pulls, then installs again the parts that changed
On Windows, from Git Bash the same, or from PowerShell: powershell -ExecutionPolicy Bypass -File .\install.ps1 (it installs git and jq with winget when missing, then runs install.sh in Git Bash).
The installer shows the parts as a checklist by group (every day, development, several computers, not dev): ↑↓ to move, Enter or Space to pick a part or a whole group, → or Tab to unfold why, what, when and who for a part, a for all, then Install at the bottom. It greys out what doesn't apply to this computer, adds what a picked part needs (pr-pane brings pr-watch, reminders brings daily-sync), then sets up each part it installed: the emails for the email guard, where pr-watch looks for your PRs, the phone for reminders, the browser tool for test-evidence. Run a part's setup again any time with bash ~/.claude/<part>/setup.sh (hooks: bash ~/.claude/hooks/setup/<hook>.sh). It copies each part into ~/.claude, adds its hooks to ~/.claude/settings.json and saves whatever it replaces in ~/.claude/backups/before-kit-<date>/. Running it again is safe. Start a new Claude Code session afterwards. Needs jq.
To try it first without touching your own setup, tests/install-sandbox.sh runs the installer in a throwaway home folder, shows what it left and checks your files are unchanged; --claude <sandbox> then opens a first Claude Code session there.
The sync engine is a part too (./install.sh config-sync), added on its own when you pick handoff, daily-sync or reminders: the installer asks for the clone URL of an empty private git repo of your own (any host), clones it to ~/.claude-sync and sets it up; on your next computer, give the same URL. By hand: sync/README.md.
A new computer like another one: on a computer whose config isn't synced yet, the installer first asks whether it is synced from another computer, and if so sets up the sync before anything else. Each computer records its answers to the kit's questions in ~/.claude/kit-answers.txt (never a secret, such as the ntfy topic), and the sync shares them with the parts it installed. So the new computer can be set up:
~/.zshrc line, the status line it has.A part's setup run later (a plugin's, at its first session) uses the same choice, kept in ~/.claude/kit-reuse.txt; delete that file to be asked again.
rules/team.md is the base of everything here: Claude and you work as one team that builds, thinks things through and challenges each other. It asks before touching production or shared infrastructure (in two lines, not twenty), before each commit, push and PR, and before decisions that need context only you have, with the options and a recommendation. It proposes a skill, mod or hook when you keep asking for the same thing, and an AI review step with proof (screenshots, videos) on the CI of repos that don't have one. The team plugin hands them to Claude at each session start, in the language you pick in its options, so they update with the plugin; install.sh asks for the language and adds them to ~/.claude/CLAUDE.md once instead. A capability can use another language when you say so.
| Skill | What it does | Needs |
|---|---|---|
| test-evidence | Captures proof that a ticket works locally: browser screenshots, a short video of the flow, the network requests and console behind it (through the chrome-devtools MCP), or one app window or screen region, never the whole screen unless asked. Masks tokens and cookies, writes a short test report and, after your yes, attaches it to the Jira issue or as a resolved comment on the Azure DevOps PR; on GitHub, it gives you the comment and the files to drop in. | chrome-devtools MCP, jq, perl; video needs ffmpeg |
| ci-review | Proposes, once per repo, an AI review step on the CI and sets it up with you: an agent reads each PR/MR's diff and its proof (what test-evidence captures) and posts a verdict (works / doesn't / can't tell, with what to capture). Templates for anthropics/claude-code-action, the CLI in headless mode (claude -p) on GitHub Actions and GitLab CI, and cloud providers; the review prompt is a plain file any agent CLI can take. | an API key or a cloud provider account, set as a CI secret |
| capability-builder | Turns a request you keep making into a capability: picks the right kind (rule, skill, hook, mod or plain script), interviews you, scaffolds it with its tests and setup, checks it against a macOS / Linux / Windows checklist, and runs the publish checklist (nothing personal, tool-agnostic) before it goes to a kit. How this kit's own parts are built. | |
| handoff | Writes a handoff note so you can continue the current work on your other computer, and picks it up there. A note picked up or canceled moves to done/, kept 60 days; reminders-handoffs lists them. | the sync engine |
| daily-sync | Schedules a sync every morning (09:00 by default) with launchd, cron or the Windows Task Scheduler, so each computer gets what the others left even with no session open. Other skills can hook a morning.sh onto it. | the sync engine |
| reminders | "Remind me tomorrow to…": leaves a global or repo-specific reminder that every new session, on any of your computers, brings up first thing, without slowing the start: what the background sync brings arrives with your next message. A reminder can repeat ("every Friday": at 09:00 unless it says a time), be for one computer, and be filed under a group (an organization, a client); done closes a repeating one for the day, stop ends it, and closed ones stay listed as past for 60 days. Due reminders also go to the desktop and, through ntfy, to your phone every morning and at the first session of the day. | daily-sync; curl for the phone |
| kb | A personal knowledge base. Notes are Markdown files with a front matter (type, trust, topics, validity dates) and [[links]], in your config sync (so every computer and your other agents get them) or in ~/.claude/knowledge; the kb command indexes them in SQLite for full-text search (accents folded), semantic search in any language (a local multilingual model, no API) and the link graph (kb related, as a list or a Mermaid mind map). At session start Claude is told which notes mention the repository or the branch, beyond the repository's own memory; on each prompt, which notes hold most of its words. Every morning (through daily-sync), Claude reads the previous day's Claude Code transcripts of this computer, reduced to prompts, replies and files touched with secrets redacted, and proposes notes to create or merge; the code checks them (names, dates, secrets, no overwrite) and writes them with a report, each marked as the curator's. kb serve and its Dockerfile give the same index over HTTP, behind a token, to an agent of yours. Notes a third party wrote (trust: third-party) stay data, never instructions. | Python 3.12+, jq; the curation needs daily-sync and the Claude Code CLI signed in; the semantic search downloads a 500 MB model once |
| pr-watch | Tracks the PRs you and Claude open or push together until they are merged: new comments (bots marked apart), votes, CI results (required checks drive green or failed) and the merge itself, which drops the PR from the list. Also lists the open PRs waiting for your review (GitHub review requests, Azure DevOps reviewer with no vote) and reports each new one; approve votes or submits an approving review on your yes, then tracks the PR as reviewed until it is merged; merge merges a PR on your yes; park keeps a PR you won't merge tracked but quiet, out of what needs you, until unpark. Also finds your pipeline runs: those you launched by hand (Azure DevOps manual builds, GitHub workflows you dispatched) and the CI your own pushes start on a branch with no PR, a push to main included (in the projects and repos of your PRs, the GitHub repos you pushed to lately, plus those listed in its config), so a packaging or a deploy started with Claude shows up on its own, and reports each one that ended since the last check; details <build URL> lists every step with its job and state, the error lines of those with issues included, rerun <build URL> launches the run again on your yes. Also follows your GitHub issues: those you opened, commented on or were mentioned or assigned in, in any repo, active in the last 30 days, and those you subscribed to in your own repos; open ones and those closed in the last 7 days, reporting new comments by others, a close or reopen and label changes since you last looked. What it watches (open, parked and merged PRs, review requests, how many runs per repo, issues) follows pr-pane's settings, or its config.json: what is off is neither fetched nor reported. Claude proposes a reply or a fix for each change, never posts one without your yes. Checks at each session start in the background and silently (the session starts at once; each PR keeps what changed as unread, which pr-pane shows until you unfold that PR), hourly in a session (a durable scheduled task) and every morning through daily-sync, with a desktop or phone notification. The list lives in the sync repo, so it follows you on every computer and never touches the project repos. With the sync repo on GitHub (recommended), what one computer fetches is shared with the others on a branch of it that never grows, read with one conditional request: each host is asked by one computer only, again once its share is older than 2 minutes while a CI runs or 10 otherwise (asked at setup), the pane opens at once, and a host one computer cannot reach (a company's Azure DevOps from home) is still shown from another. Azure DevOps (az login or a PAT) and GitHub (a token, gh, or anonymous for public repos). | Python 3.9+; the sync engine to share the list across computers |
Mods change Claude Code's own interface. They install as plugins like the other parts; install.sh loads its copies through CLAUDE_CODE_PLUGIN_DIRS. Run a mod's tests with claude plugin test mods/<name>.
| Mod | What it does |
|---|---|
| paste-preview | Shows pasted text in full in the prompt box and the transcript, and previews pasted images above the prompt and under the sent message (macOS, Windows). On Windows, paste an image with Alt+V: in some terminals (Ghostty) Ctrl+V pastes text only. |
| pr-pane | A Dev activity button at the top right of the band above the prompt, whose number counts only what needs you (a PR or a run in red, not acknowledged), colored by what you have to do (red and marked !: something needs you; yellow: · k to review or · k running; green: a PR is ready to merge; dim: everything waits for others) and /prs open a pane of the PRs pr-watch tracks, by priority. At the top, a collapsible "Pipeline runs" section lists your runs (a packaging or a deploy launched by hand, the CI of your pushes outside a PR, marked push to <branch>), one block per repo: the running ones first, then those ended in the last day, each with its pipeline, branch, status, time and duration, open by default while one runs; a run whose host did not answer keeps its last known state, marked cached. A run unfolds from its line: rerun (press twice: a new run of the same pipeline, branch and parameters on Azure DevOps, a re-run on GitHub), diagnose with Claude when it did not succeed (asks the session to read the steps and logs and propose the fix), then every step of the run grouped by job in pipeline order, each job folded unless a step had a problem, each step's messages and log lines under their own toggle. Then, under a red title and one open block per repo, the PRs that need you: a failed or expired CI, a merge conflict, changes requested, or a new comment since the last check (unfolding the PR marks its changes read: the button clears, the PR stays where it is until the session ends). Then the PRs waiting for your review, per repo too, each with review with Claude (a quick review by a subagent, nothing posted) and approve (press twice; it reads approving… while it runs). Then a collapsible "Waiting for others" section with your other open PRs, one collapsible block per repo in merge order (a stacked PR under the one it targets). Then "Issues I follow", per repo with unfollow all (press twice): each issue on one line (yellow when it moved since you last looked, with · n issues updated on the band), unfolding to who opened it, its labels and comments and what changed, which marks it read, with unfollow. A PR you park (its park button, under its details) leaves the red list and the band for a folded "Parked, kept but quiet" section, with unpark. Last, before the recent list, a collapsible "Approved, waiting for the merge" section holds the PRs you approved and your own PRs that only wait for the merge, grouped per repo the same way, each with a merge button (press twice; merging… while it runs; squash on GitHub when the repo allows it, complete on Azure DevOps). Every section and repo block wears the worst color of what it holds (red, then yellow, then green), so a folded one still says where to look. A red PR or run can be acknowledged (ack): it turns blue, leaves the count and the colors above it, and comes back when it changes; ack + remind asks Claude for a reminder and acks until its date, shown beside it. Every PR is one line, a colored dot (red: you have to act, yellow: someone or something else, green: only the merge is left), its number, title and what it waits for; its details fold under it: status, CI, votes, conflicts, the PR's description and the changes since the last check. A PR whose CI runs, and the repo block and section around it, open by default so a CI you just launched is on screen (a folded block hiding one says CI running); what you fold stays folded. Each PR's CI checks fold under it, open while they run or when a required one failed, refreshed every minute until they end; a failed check has details (its failed steps and error lines) and rerun (press twice: re-queue on Azure DevOps, rerun failed jobs on GitHub). A merge conflict is shown in red with a fix with Claude button that asks the session to rebase and resolve it (it asks you before pushing). PRs merged or closed in the last 7 days stay listed at the bottom. An error shared by several PRs and lists (a host this computer cannot reach or sign in to) is shown once, with what it hit. Click a PR to open it in the browser; refresh (or r) fetches them live and lists what changed since the last check, without marking it seen. Its settings, in the Configuration pane or claude plugin configure, turn each section on or off (open PRs, parked, merged and closed, review requests, issues), set how many pipeline runs to show per repo (0 hides them), how long an issue stays followed without moving, how often each part is refreshed by itself, and follow the kit's low power mode (see configuration); pr-watch follows them too, so what is off is no longer fetched or reported. Needs pr-watch. |
| reminders-handoffs | One pane for whichever of reminders and handoff you have, a tab each when you have both. A button at the right of the band above the prompt, named after them (Reminders 1 now · Handoffs 1, yellow when a reminder is due or a note from your other computer waits), /reminders-pane and /handoffs-pane open it. Reminders come in three foldable sections, Now, Upcoming (with when each shows next, repeating ones included) and Past; handoff notes in Open and Done. Several groups in a section (a reminder's group, else its folder, else its computer; a note's repo) each get a foldable title. Each item is one line that unfolds to its dates, repo, branch and text, with pick (hands the reminder or the note to this session now), done (done today on a repeating reminder), stop, cancel and delete (press twice), and restore on a past one (back as it was, dates and repeat days included). |
| recent-prompts | Shows your last two messages above the prompt, and a searchable history pane; click one to scroll the transcript to it. With the learn mod, the history also lists each 💡 lesson between the messages it answered. |
| dnd | Do not disturb for the recent-prompts, pr-pane and reminders-handoffs panes. A profile hides a pane (its band button too), or keeps only some repos, reminder groups or handoff repos, @here being the session's own repo; counts and colors follow what is kept. Turn one on by hand with /dnd work 1h or by asking Claude, for this session, this computer or all computers (asked when you don't say; the status line shows 🔕 work · session while one is on), or let a rule turn it on: a Wi-Fi network, days and hours (days=weekend, from=19:00 to=08:00), a folder (a repo shows only its own). /dnd, or its button in the Configuration pane, opens the Do not disturb pane: a press per profile asks until when and where, then Activate turns it on; a name creates one, and each profile unfolds to what it keeps (a checklist) and the rules that turn it on; dnd.sh edit <profile> is the same checklist on a terminal, with the installer's keys. Profiles live in the sync repo when there is one, so every computer gets them. Offered only beside one of those panes. |
| configuration | A Configuration button at the right of the band and /configuration open the Configuration pane: every mod's settings, grouped per mod (a toggle, a choice, or a number or text typed and saved with Enter), changed for all computers or, with a private sync, for this computer only; a setting kept for this computer says the value the other computers use. Its own setting is the kit's low power mode: on, off, or on battery (the default: while the computer runs on its battery or in its low power mode, read on macOS, Linux and Windows), everything that fetches by itself (the dev activity pane and pr-watch, the reminders and handoffs pane, do not disturb) does it five times less often, and
hooks/register.tsx 549 lines1import { atom, memberOf, read, update } from 'claude-code'
2import type { Elements, EngineInterface, PromptEditResult, Register } from 'claude-code'
3
4import type { Picture } from '../types'
5
6type Block = { type: string; [field: string]: unknown }
7type ImageSource = { type?: string; media_type?: string; data?: string }
8type Size = { width: number; height: number }
9type Ran = { exitCode: number | null; stdout: string }
10
11// The hooks environment has the TC39 base64 helpers; TypeScript's es2023 lib does not declare them yet.
12const fromBase64 = (base64: string) =>
13 (Uint8Array as unknown as { fromBase64: (text: string) => Uint8Array }).fromBase64(base64)
14const toBase64 = (bytes: Uint8Array) => (bytes as unknown as { toBase64: () => string }).toBase64()
15
16const MAX_COLUMNS = 40
17const MAX_ROWS = 12
18const UPPER_HALF = 0x2580
19const LOWER_HALF = 0x2584
20const SPACE = 0x20
21const DEFAULT_COLOR = 0x01000000
22
23const PASTE_ONLY = /^\[Pasted text #\d+[^\]]*\]$/
24const HAS_PASTE = /\[Pasted text #\d+[^\]]*\]/
25const PASTES = /\[Pasted text #\d+[^\]]*\]/g
26const PASTE_LINES = /\+(\d+) lines?\]$/
27const IMAGES = /\[Image #(\d+)\]/g
28
29const CLIPBOARD_TO_PNG = [
30 'on run argv',
31 'set outFile to open for access (POSIX file (item 1 of argv)) with write permission',
32 'try',
33 'set eof outFile to 0',
34 'write (the clipboard as «class PNGf») to outFile',
35 'close access outFile',
36 'on error errorText',
37 'close access outFile',
38 'error errorText',
39 'end try',
40 'end run',
41].flatMap(line => ['-e', line])
42
43const SAVE_AS_PNG = '[Drawing.Imaging.ImageFormat]::Png'
44
45const draft = atom({ plugin: 'paste-preview', key: 'draft' } as const, [])
46const sent = atom({ plugin: 'paste-preview', key: 'sent' } as const, [])
47const fullText = atom({ plugin: 'paste-preview', key: 'fullText' } as const, '')
48
49const triedLabels = new Set<string>()
50const triedPastes = new Set<string>()
51let isWindowsHost: Promise<boolean> | undefined
52let workDirectory: Promise<string> | undefined
53let isSyncing = false
54let isExpanding = false
55
56const succeeded = async (run: Promise<Ran>) => (await run).exitCode === 0
57
58const sizeOf = (width?: string, height?: string): Size | null => {
59 const size = { width: Number(width ?? 0), height: Number(height ?? 0) }
60
61 return size.width > 0 && size.height > 0 ? size : null
62}
63
64const quoted = (text: string) => `'${text.replace(/'/g, "''")}'`
65
66const powershell = ($: EngineInterface, lines: string[], stdin?: string) =>
67 $.process.run(
68 [
69 'powershell.exe',
70 '-NoProfile',
71 '-NonInteractive',
72 '-STA',
73 '-Command',
74 ["$ErrorActionPreference = 'Stop'", 'Add-Type -AssemblyName System.Drawing, System.Windows.Forms', ...lines].join('; '),
75 ],
76 stdin === undefined ? {} : { stdin },
77 )
78
79const isWindows = ($: EngineInterface) => (isWindowsHost ??= $.env.get('OS').then(os => os === 'Windows_NT'))
80
81const makeDirectory = async ($: EngineInterface, path: string) =>
82 (await isWindows($))
83 ? succeeded(powershell($, [`New-Item -ItemType Directory -Force -Path ${quoted(path)} | Out-Null`]))
84 : succeeded($.process.run(['/bin/mkdir', '-p', path]))
85
86// On Windows the text crosses PowerShell's stdout as base64 of its UTF-8 bytes: the console code page would mangle accents.
87const clipboardText = async ($: EngineInterface) => {
88 if (await isWindows($)) {
89 const { exitCode, stdout } = await powershell($, [
90 '$text = [Windows.Forms.Clipboard]::GetText()',
91 '[Console]::Out.Write([Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($text)))',
92 ])
93
94 return exitCode === 0 ? new TextDecoder().decode(fromBase64(stdout.trim())) : ''
95 }
96
97 const { exitCode, stdout } = await $.process.run(['/usr/bin/pbpaste'])
98
99 return exitCode === 0 ? stdout : ''
100}
101
102const clipboardPng = async ($: EngineInterface, png: string) =>
103 (await isWindows($))
104 ? succeeded(
105 powershell($, [
106 '$image = [Windows.Forms.Clipboard]::GetImage()',
107 'if ($null -eq $image) { exit 1 }',
108 `$image.Save(${quoted(png)}, ${SAVE_AS_PNG})`,
109 ]),
110 )
111 : succeeded($.process.run(['/usr/bin/osascript', ...CLIPBOARD_TO_PNG, png]))
112
113const savePng = async ($: EngineInterface, png: string, base64: string, mediaType: string) => {
114 if (await isWindows($)) {
115 return succeeded(
116 powershell(
117 $,
118 [
119 '$bytes = [Convert]::FromBase64String([Console]::In.ReadToEnd())',
120 `[Drawing.Image]::FromStream([IO.MemoryStream]::new($bytes)).Save(${quoted(png)}, ${SAVE_AS_PNG})`,
121 ],
122 base64,
123 ),
124 )
125 }
126
127 const raw = png.replace(/\.png$/, `.${mediaType.split('/')[1] ?? 'png'}`)
128 const isDecoded = await succeeded($.process.run(['/usr/bin/base64', '-d', '-o', raw], { stdin: base64 }))
129
130 return isDecoded && (raw === png || (await succeeded($.process.run(['/usr/bin/sips', '-s', 'format', 'png', raw, '--out', png]))))
131}
132
133const imageSize = async ($: EngineInterface, image: string) => {
134 if (await isWindows($)) {
135 const { exitCode, stdout } = await powershell($, [
136 `$image = [Drawing.Image]::FromFile(${quoted(image)})`,
137 '[Console]::Out.Write("$($image.Width) $($image.Height)")',
138 ])
139 const match = /^(\d+) (\d+)/.exec(stdout.trim())
140
141 return exitCode === 0 ? sizeOf(match?.[1], match?.[2]) : null
142 }
143
144 const { exitCode, stdout } = await $.process.run(['/usr/bin/sips', '-g', 'pixelWidth', '-g', 'pixelHeight', image])
145
146 return exitCode === 0 ? sizeOf(/pixelWidth: (\d+)/.exec(stdout)?.[1], /pixelHeight: (\d+)/.exec(stdout)?.[1]) : null
147}
148
149const toBmp = async ($: EngineInterface, png: string, bmp: string, width: number, height: number) =>
150 (await isWindows($))
151 ? succeeded(
152 powershell($, [
153 `$image = [Drawing.Image]::FromFile(${quoted(png)})`,
154 `$bitmap = [Drawing.Bitmap]::new(${width}, ${height}, [Drawing.Imaging.PixelFormat]::Format24bppRgb)`,
155 '$graphics = [Drawing.Graphics]::FromImage($bitmap)',
156 '$graphics.InterpolationMode = [Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic',
157 `$graphics.DrawImage($image, 0, 0, ${width}, ${height})`,
158 `$bitmap.Save(${quoted(bmp)}, [Drawing.Imaging.ImageFormat]::Bmp)`,
159 ]),
160 )
161 : succeeded(
162 $.process.run(['/usr/bin/sips', '-s', 'format', 'bmp', '-z', String(height), String(width), png, '--out', bmp]),
163 )
164
165const directory = ($: EngineInterface) =>
166 (workDirectory ??= (async () => {
167 const tmp = ((await isWindows($)) ? await $.env.get('TEMP') : await $.env.get('TMPDIR')) ?? '/tmp'
168 const path = `${tmp.replace(/[\\/]+$/, '')}/claude-paste-preview`
169
170 if (!(await makeDirectory($, path))) {
171 workDirectory = undefined
172 }
173
174 return path
175 })())
176
177// The Windows builds of these terminals do not draw kitty graphics: the half-block raster shows everywhere.
178const hasKittyGraphics = async ($: EngineInterface) => {
179 const program = (await $.env.get('TERM_PROGRAM')) ?? ''
180 const isKittyWindow = (await $.env.get('KITTY_WINDOW_ID')) !== undefined
181
182 return (await isWindows($)) ? isKittyWindow : ['ghostty', 'kitty', 'WezTerm'].includes(program) || isKittyWindow
183}
184
185const isPerson = (kind: string) => kind === 'composer' || kind === 'bridge'
186
187const lowestBit = (mask: number) => (mask === 0 ? 0 : 31 - Math.clz32(mask & -mask))
188
189// sips writes 32-bit BMPs with channel masks (BGRA, top-down); System.Drawing writes 24-bit BGR, bottom-up.
190const decodeBmp = (bytes: Uint8Array) => {
191 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
192
193 if (bytes.byteLength < 54 || view.getUint16(0, true) !== 0x4d42) {
194 return null
195 }
196
197 const offset = view.getUint32(10, true)
198 const width = view.getInt32(18, true)
199 const rawHeight = view.getInt32(22, true)
200 const bitsPerPixel = view.getUint16(28, true)
201 const hasMasks = view.getUint32(30, true) === 3 && bytes.byteLength >= 70
202 const height = Math.abs(rawHeight)
203 const stride = Math.ceil((width * bitsPerPixel) / 32) * 4
204 const masks = hasMasks
205 ? [view.getUint32(54, true), view.getUint32(58, true), view.getUint32(62, true), view.getUint32(66, true)]
206 : [0xff0000, 0xff00, 0xff, bitsPerPixel === 32 ? 0xff000000 : 0]
207
208 if (bitsPerPixel !== 24 && bitsPerPixel !== 32) {
209 return null
210 }
211
212 return (x: number, y: number) => {
213 const line = rawHeight > 0 ? height - 1 - y : y
214 const at = offset + line * stride + (x * bitsPerPixel) / 8
215
216 if (at + bitsPerPixel / 8 > bytes.byteLength) {
217 return DEFAULT_COLOR
218 }
219
220 const pixel =
221 bitsPerPixel === 32
222 ? view.getUint32(at, true)
223 : ((bytes[at + 2] ?? 0) << 16) | ((bytes[at + 1] ?? 0) << 8) | (bytes[at] ?? 0)
224 const [red, green, blue, alpha] = masks.map(mask => ((pixel & mask) >>> lowestBit(mask)) & 0xff) as [
225 number,
226 number,
227 number,
228 number,
229 ]
230 const isTransparent = masks[3] !== 0 && alpha < 128
231
232 return isTransparent ? DEFAULT_COLOR : (red << 16) | (green << 8) | blue
233 }
234}
235
236const rasterCells = async ($: EngineInterface, png: string, columns: number, rows: number) => {
237 const bmp = png.replace(/\.png$/, `-${columns}x${rows}.bmp`)
238
239 if (!(await toBmp($, png, bmp, columns, rows * 2))) {
240 return null
241 }
242
243 const { base64 } = await $.fs.read(bmp, { as: 'bytes' })
244 const pixelAt = decodeBmp(fromBase64(base64))
245
246 if (pixelAt === null) {
247 return null
248 }
249
250 const words = new Uint32Array(columns * rows * 3)
251
252 for (let row = 0; row < rows; row++) {
253 for (let column = 0; column < columns; column++) {
254 const top = pixelAt(column, row * 2)
255 const bottom = pixelAt(column, row * 2 + 1)
256 const at = (row * columns + column) * 3
257
258 if (top === DEFAULT_COLOR && bottom === DEFAULT_COLOR) {
259 words.set([SPACE, DEFAULT_COLOR, DEFAULT_COLOR], at)
260 } else if (top === DEFAULT_COLOR) {
261 words.set([LOWER_HALF, bottom, DEFAULT_COLOR], at)
262 } else {
263 words.set([UPPER_HALF, top, bottom], at)
264 }
265 }
266 }
267
268 return toBase64(new Uint8Array(words.buffer))
269}
270
271const picture = async ($: EngineInterface, png: string, label: string): Promise<Picture | null> => {
272 const size = await imageSize($, png)
273
274 if (size === null) {
275 return null
276 }
277
278 let columns = Math.min(MAX_COLUMNS, size.width)
279 let rows = Math.max(1, Math.round((columns * size.height) / size.width / 2))
280
281 if (rows > MAX_ROWS) {
282 rows = MAX_ROWS
283 columns = Math.max(1, Math.min(MAX_COLUMNS, Math.round((rows * 2 * size.width) / size.height)))
284 }
285
286 return { label, path: png, columns, rows, cells: await rasterCells($, png, columns, rows) }
287}
288
289const syncDraft = async ($: EngineInterface, text: string) => {
290 if (isSyncing) {
291 return
292 }
293
294 isSyncing = true
295
296 try {
297 const wanted = [...text.matchAll(IMAGES)].map(match => `Image #${match[1]}`)
298 const current = await read($, draft)
299 const missing = wanted.filter(label => !triedLabels.has(label) && !current.some(one => one.label === label))
300 const isStale = current.some(one => !wanted.includes(one.label))
301
302 if (missing.length === 0 && !isStale) {
303 return
304 }
305
306 missing.forEach(label => triedLabels.add(label))
307 const newest = missing.at(-1)
308 let added: Picture | null = null
309
310 if (newest !== undefined) {
311 const png = `${await directory($)}/draft-${crypto.randomUUID()}.png`
312 added = (await clipboardPng($, png)) ? await picture($, png, newest) : null
313 }
314
315 await update($, draft, list => [
316 ...list.filter(one => wanted.includes(one.label)),
317 ...(added === null ? [] : [added]),
318 ])
319 } finally {
320 isSyncing = false
321 }
322}
323
324// The preview made while typing is reused, so the message row has its pictures from its first draw.
325const sentPictures = async ($: EngineInterface, uuid: string, text: string, images: Block[], drafts: Picture[]) => {
326 const numbers = [...text.matchAll(IMAGES)].map(match => match[1])
327 const pictures: Picture[] = []
328
329 for (const [index, block] of images.entries()) {
330 const label = `Image #${numbers[index] ?? index + 1}`
331 const drafted = drafts.find(one => one.label === label)
332 const source = block.source as ImageSource | undefined
333
334 if (drafted !== undefined) {
335 pictures.push(drafted)
336 } else if (source?.type === 'base64' && typeof source.data === 'string') {
337 const png = `${await directory($)}/${uuid}-${index}.png`
338 const isSaved = await savePng($, png, source.data, source.media_type ?? 'image/png')
339 const one = isSaved ? await picture($, png, label) : null
340
341 if (one !== null) {
342 pictures.push(one)
343 }
344 }
345 }
346
347 return pictures
348}
349
350// On Windows a long paste reaches the box already collapsed, with no prompt.edit for it. The clipboard
351// only stands in for it when its line count matches the placeholder's, so a later copy is never pasted.
352const expandInBox = async ($: EngineInterface) => {
353 if (isExpanding) {
354 return
355 }
356
357 const { text } = await $.prompt.read()
358 const fresh = (text.match(PASTES) ?? []).find(one => !triedPastes.has(one))
359
360 if (fresh === undefined) {
361 return
362 }
363
364 isExpanding = true
365
366 try {
367 triedPastes.add(fresh)
368 const clip = (await clipboardText($)).replace(/\r\n?/g, '\n')
369 const lines = Number(PASTE_LINES.exec(fresh)?.[1])
370 const newlines = clip.split('\n').length - 1
371
372 if (clip.trim() === '' || !(Math.abs(newlines - lines) <= 1)) {
373 return
374 }
375
376 const now = await $.prompt.read()
377 const at = now.text.indexOf(fresh)
378
379 if (at !== -1) {
380 await $.prompt.fill({ text: now.text.slice(0, at) + clip + now.text.slice(at + fresh.length) })
381 }
382 } finally {
383 isExpanding = false
384 }
385}
386
387const expandCollapsed = (before: string, box: PromptEditResult, pasted: string): PromptEditResult => {
388 if (HAS_PASTE.test(pasted)) {
389 return box
390 }
391
392 const previous = new Set(before.match(PASTES) ?? [])
393 const fresh = (box.text.match(PASTES) ?? []).find(one => !previous.has(one))
394
395 if (fresh === undefined) {
396 return box
397 }
398
399 const at = box.text.indexOf(fresh)
400
401 return {
402 text: box.text.slice(0, at) + pasted + box.text.slice(at + fresh.length),
403 cursor: at + pasted.length,
404 }
405}
406
407const pictureRow = (ui: Elements['terminal'], pictures: Picture[], isKitty: boolean) => {
408 const { Box, Text, Image, Raster } = ui
409
410 return (
411 <Box flexDirection="row" gap={2}>
412 {pictures.map(one => (
413 <Box key={one.path} flexDirection="column">
414 <Text dimColor>{one.label}</Text>
415 {isKitty || one.cells === null ? (
416 <Image source={{ file: one.path, format: 'png' }} columns={one.columns} rows={one.rows} alt={one.label} />
417 ) : (
418 <Raster key={one.path} columns={one.columns} rows={one.rows} cells={one.cells} />
419 )}
420 </Box>
421 ))}
422 </Box>
423 )
424}
425
426export const register: Register = on => {
427 on('session.start', async ($, e, next) => {
428 $.clock.every(1000, () => {
429 void $.prompt.read().then(box => syncDraft($, box.text))
430 void expandInBox($)
431 })
432
433 return next(e)
434 })
435
436 on('prompt.edit', async ($, e, next) => {
437 const isPaste = e.key === undefined && e.inputText !== ''
438 const clip = isPaste && PASTE_ONLY.test(e.inputText.trim()) ? await clipboardText($) : ''
439 const pasted = clip.trim() === '' ? e.inputText : clip.replace(/\r\n?/g, '\n')
440 const box = await next(pasted === e.inputText ? e : { ...e, inputText: pasted })
441 const result = isPaste ? expandCollapsed(e.text, box, pasted) : box
442 // Not awaited: on Windows each image step is a PowerShell call, and typing must not wait for them.
443 void syncDraft($, result.text)
444
445 return result
446 }).catch(($, e, next) => next(e))
447
448 on('session.append', { door: 'prompt' }, async ($, e, next) => {
449 const stored = await next(e)
450
451 if (!isPerson(e.origin.kind) || e.agentId !== undefined || stored.uuid === undefined) {
452 return stored
453 }
454
455 const uuid = stored.uuid
456 const blocks: Block[] = stored.message.content
457 const first = blocks.find(block => block.type === 'text')
458 const text = typeof first?.text === 'string' ? first.text : ''
459 const images = blocks.filter(block => block.type === 'image')
460 const drafts = await read($, draft)
461
462 await update($, memberOf(fullText, { requestId: uuid }), () => text)
463 await update($, draft, () => [])
464 triedLabels.clear()
465 triedPastes.clear()
466
467 if (images.length > 0) {
468 const pictures = await sentPictures($, uuid, text, images, drafts)
469
470 if (pictures.length > 0) {
471 await update($, memberOf(sent, { requestId: uuid }), () => pictures)
472 }
473 }
474
475 return stored
476 }).catch(($, e, next) => next(e))
477
478 on('session.append', { door: 'attachment' }, async ($, e, next) => {
479 const stored = await next(e)
480
481 if (stored.uuid === undefined || stored.message.name !== 'queued_command' || e.agentId !== undefined) {
482 return stored
483 }
484
485 const uuid = stored.uuid
486 const blocks: Block[] = e.message.content
487 const images = blocks.filter(block => block.type === 'image')
488
489 if (images.length > 0) {
490 const text = blocks.flatMap(block => (typeof block.text === 'string' ? [block.text] : [])).join('\n')
491 const pictures = await sentPictures($, uuid, text, images, await read($, draft))
492
493 if (pictures.length > 0) {
494 await update($, memberOf(sent, { requestId: uuid }), () => pictures)
495 }
496 }
497
498 return stored
499 }).catch(($, e, next) => next(e))
500
501 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
502 const beneath = await next(e)
503
504 if (e.surface !== 'terminal' || e.props.hasSurvey) {
505 return beneath
506 }
507
508 const pictures = await read($, draft)
509
510 if (pictures.length === 0) {
511 return beneath
512 }
513
514 const ui = $.ui.resolve(e)
515 const { Box } = ui
516
517 return (
518 <Box flexDirection="column">
519 {beneath}
520 {pictureRow(ui, pictures, await hasKittyGraphics($))}
521 </Box>
522 )
523 })
524
525 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
526 if (!isPerson(e.props.origin.kind)) {
527 return next(e)
528 }
529
530 const full = HAS_PASTE.test(e.props.text) ? await read($, memberOf(fullText, e)) : ''
531 const pictures = await read($, memberOf(sent, e))
532 const row = await next(full === '' ? e : { ...e, props: { ...e.props, text: full } })
533
534 if (e.surface !== 'terminal' || pictures.length === 0) {
535 return row
536 }
537
538 const ui = $.ui.resolve(e)
539 const { Box } = ui
540
541 return (
542 <Box flexDirection="column">
543 {row}
544 {pictureRow(ui, pictures, await hasKittyGraphics($))}
545 </Box>
546 )
547 })
548}
549types/index.d.ts 18 lines1export type Picture = {
2 label: string
3 path: string
4 columns: number
5 rows: number
6 cells: string | null
7}
8
9declare module 'claude-code' {
10 interface PluginState {
11 'paste-preview': {
12 draft: Picture[]
13 sent: StateFamily<Picture[]>
14 fullText: StateFamily<string>
15 }
16 }
17}
18