/rp attaches a ReadyRig project to the session: its AGENTS.md, CLAUDE.md and skills, until /rp detach; /rp link attaches it whenever Claude Code starts in this…

rp is a Claude Code mod (a plugin of function hooks). It adds a /rp command that lists the approved projects on every ReadyRig computer, grouped by machine. The project you pick is attached to the session: Claude gets its AGENTS.md, CLAUDE.md and skills, and works in it until you detach it. Link a folder to a project with /rp link, and every Claude Code session you start in that folder attaches the project by itself. Claude can also show you an image from the project with its show_image tool: it is drawn in your terminal, with a button that opens it in Preview on the Mac.
jiangdailins-MacBook-Pro.local (darwin)
agent_workspace /Users/jo32/agent_workspace
● computer-use-server /Users/jo32/Projects/computer-use-server
tvbox /Users/jo32/Projects/tvbox
jo32-machine-linux (linux)
agent_workspace /root/agent_workspace
mcp__readyrig__list_computers and mcp__readyrig__call_computer_tool are available. /mcp shows whether it is connected.offline, without projects.From GitHub, at the Claude Code prompt in a terminal:
/plugin install rp --marketplace jo32/readyrig
Answer y to add the marketplace, then pick a scope (user scope loads it in every session). This repository's .claude-plugin/marketplace.json lists the mod.
From a local clone:
claude plugin marketplace add /path/to/readyrig
claude plugin install rp@readyrig
To try it without installing, or while changing it, load the folder for one session. Saving a file reloads the mod:
claude --plugin-dir /path/to/readyrig/integrations/claude-code/rp
| Command | What it does |
|---|---|
/rp | Opens a pane with every machine and its projects, and a search box at the top. Type to narrow the list, then press Enter to attach the first match. Or move with Tab or the arrow keys, press Enter on a project to attach it, or Esc to close the pane. |
/rp detach | Detaches the project (/rp clear does the same). The pane also has a detach button while a project is attached. |
/rp link | Links the folder Claude Code runs in to the attached project. With nothing attached, it opens the pane: the project you pick is attached and linked. The pane also has a link to this folder button. |
/rp unlink | Removes the folder's link. The project stays attached to the session until you detach it. |
When you pick a project, the pane shows each step as it runs:
Attaching OpenWorkBuddy2 @ jiangdailins-MacBook-Pro.local
✓ AGENTS.md 43 lines
– CLAUDE.md none
… .agents/skills reading 3 skills
– .claude/skills none
· Add to the conversation
The status line counts the steps too, so you can close the pane with Esc and keep working while it loads. When it is done, the pane closes, a toast says what was found, and the status line shows rp: <project> @ <machine> · AGENTS.md · 3 skills for as long as the project stays attached (· linked at the end when the folder is linked to it).
What Claude gets:
computer_id and the project id to pass to the ReadyRig tools. The folder's path is left out, since it can include your user name.AGENTS.md (the agents.md standard) and CLAUDE.md from the project's root, each in full up to 40,000 characters. A CLAUDE.md that only says @AGENTS.md is skipped. Claude is also told to look for an AGENTS.md or CLAUDE.md in subfolders, where the nearest one wins.SKILL.md in .agents/skills/ (the universal location) and .claude/skills/, including linked folders. Only the name and description from each skill's front matter go in. Claude reads the whole SKILL.md when a task matches. If both folders have a skill with the same name, the one in .agents/skills/ wins.All of this goes in once, as a hidden note at the end of the conversation. It doesn't go into the system prompt, so attaching or detaching doesn't invalidate the prompt cache for the conversation so far. Your prompts are sent as you typed them. If /compact or /clear drops the note, it is added again before your next prompt. Attaching another project replaces the first one. Detaching adds a short note that tells Claude the project no longer applies.
A link ties a folder on the computer that runs Claude Code (the session's project root, such as ~/tvbox) to one ReadyRig project. When Claude Code starts in that folder, or in a folder below it, the mod attaches the linked project while Claude Code starts. The nearest linked folder wins. Your first prompt waits up to 8 seconds for the attach to finish, so Claude has the project's note before it answers. If the ReadyRig MCP server isn't connected yet, the mod tries again every 2 seconds for up to 30 seconds. If the machine is offline, the project is gone, or you deny the ReadyRig call, a toast says why and nothing is attached. Starting Claude Code may ask you to allow mcp__readyrig__list_computers and mcp__readyrig__call_computer_tool.
Links are kept in the mod's own store, so they last across sessions. Each folder has at most one link; linking it again replaces the link. Detaching doesn't remove the link, so the next session attaches the project again. Use /rp unlink to stop that.
The search matches project names, paths and machine names, ignoring case. With several words, a project must match all of them (mac tvbox). Machines with no match are hidden while you search.
The pane lines up project names in one column. When the pane is too narrow for the name and path side by side, each path goes on its own indented line under the name.
The mod gives Claude a show_image tool (mcp__rp__show_image). Ask Claude to show you a screenshot or any image in the attached project, and it calls the tool with the file's path, relative to the project:
rp - show_image (MCP)(path: "website/public/brand/social-icon.png")
[the picture]
website/public/brand/social-icon.png · 1200×630 · Macbook-m3max · [ Open in Preview ]
open_in_preview does the same.sips turns PNG, JPEG, GIF, WebP, HEIC, TIFF and BMP into a PNG of at most 1200 pixels a side (never enlarged), made smaller until it fits the terminal's 2 MiB limit. On a computer without sips only PNG files can be shown. read_file reads inside the project only, so the PNG copy is written to .rr-preview/ in the project and removed, folder and all, as soon as it has been read.read_file when it needs to look at it./rp calls the ReadyRig MCP tools through Claude Code, the same way Claude would: list_computers, then list_projects on each online computer through call_computer_tool. Attaching uses read_file and list_directory on the project. show_image uses exec_command (for sips, removing the copy and open -a Preview) and read_file. These calls go through Claude Code's normal permission checks, so you may be asked to allow them the first time.
| File | Purpose |
|---|---|
.claude-plugin/plugin.json | Manifest |
hooks/hooks.json | Points Claude Code at the hooks module |
hooks/register.tsx | The /rp command, the pane, attaching and detaching, linking folders, the prompt hook that restores the note, and the show_image tool and its row |
types/index.d.ts | Types for the values the mod keeps in session state |
tests/rp.test.ts | Attaches projects using fake ReadyRig answers, then checks the note, the progress steps, search, re-adding the note after compaction, detach, and linking folders; and show_image's conversion, the row it draws, Open in Preview and the paths it refuses |
claude plugin validate integrations/claude-code/rp
claude plugin test integrations/claude-code/rp
After Claude Code has loaded the mod once, .claude-plugin/types/ holds the API types (it is git-ignored), and tsc -p integrations/claude-code/rp type-checks it.
hooks/register.tsx 989 lines1import { atom, memberOf, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type {
5 RpAttached,
6 RpImage,
7 RpLink,
8 RpMachine,
9 RpPick,
10 RpProgress,
11 RpProject,
12 RpSkill,
13 RpStep,
14} from '../types'
15
16const PANE = 'rp'
17const machines = atom({ plugin: 'rp', key: 'machines' } as const, [])
18const isLoading = atom({ plugin: 'rp', key: 'isLoading' } as const, false)
19const error = atom({ plugin: 'rp', key: 'error' } as const, null)
20const attached = atom({ plugin: 'rp', key: 'attached' } as const, null)
21const progress = atom({ plugin: 'rp', key: 'progress' } as const, null)
22const needsNote = atom({ plugin: 'rp', key: 'needsNote' } as const, false)
23const query = atom({ plugin: 'rp', key: 'query' } as const, '')
24const link = atom({ plugin: 'rp', key: 'link' } as const, null)
25const isLinking = atom({ plugin: 'rp', key: 'isLinking' } as const, false)
26// One per show_image call, by its tool_use_id: what its result row draws.
27const images = atom({ plugin: 'rp', key: 'image' } as const, null)
28
29// $.store key of the links, folder → project, kept across sessions.
30const LINKS = 'links'
31// While Claude Code starts, the ReadyRig MCP server may not be connected yet.
32const CONNECT_TRIES = 15
33const CONNECT_WAIT_MS = 2_000
34// How long the first prompt waits for that attach.
35const LINK_WAIT_MS = 8_000
36
37// The AGENTS.md standard (agents.md) and the universal skills folder first,
38// then Claude Code's own. A skill name found in both folders is listed once.
39const INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md']
40const SKILL_DIRS = ['.agents/skills', '.claude/skills']
41// Past this the note says where to read the rest, so one huge file can't fill the context.
42const INSTRUCTIONS_MAX = 40_000
43const NOTE_STEP = 'note'
44
45// show_image: a picture from the attached project, drawn in its tool row.
46const SHOW_IMAGE = 'show_image'
47const SHOW_IMAGE_TOOL = 'mcp__rp__show_image'
48const IMAGE_EXT = /\.(png|jpe?g|gif|webp|heic|heif|tiff?|bmp)$/i
49// read_file reads inside the project only, so the PNG copy passes through a
50// folder there; it is removed as soon as it has been read.
51const PREVIEW_DIR = '.rr-preview'
52// The terminal's Image takes a PNG of at most 2 MiB.
53const IMAGE_MAX_BYTES = 2 * 1024 * 1024
54const IMAGE_MAX_SIDE = 1200
55const IMAGE_MIN_SIDE = 200
56// Pictures kept for redrawing rows; an older row draws its text alone.
57const IMAGES_KEPT = 12
58// A terminal cell is about twice as tall as it is wide.
59const IMAGE_COLUMNS = 60
60const IMAGE_ROWS = 30
61const CELL_PX = 9
62
63type ProjectFile = { path: string; text: string; isTruncated: boolean }
64
65// The ReadyRig MCP tools answer JSON text; pull the object out of it.
66function parseJson(text: string | undefined): any {
67 if (!text) throw new Error('empty answer')
68 const start = text.indexOf('{')
69 const end = text.lastIndexOf('}')
70 if (start < 0 || end < start) throw new Error(text.slice(0, 200))
71 return JSON.parse(text.slice(start, end + 1))
72}
73
74async function callTool($: EngineInterface, args: Record<string, unknown>) {
75 return answerOf(await $.tool.call(args as any))
76}
77
78function answerOf(ran: any) {
79 if (ran.deny) throw new Error(ran.deny)
80 if (ran.isError) throw new Error(ran.text ?? 'tool failed')
81 return parseJson(ran.text)
82}
83
84// One tool of a ReadyRig computer; a missing file and the like reject.
85async function callComputer(
86 $: EngineInterface,
87 machineId: string,
88 toolName: string,
89 args: Record<string, unknown>,
90) {
91 const out = await callTool($, {
92 tool: 'mcp__readyrig__call_computer_tool',
93 computer_id: machineId,
94 tool_name: toolName,
95 arguments: args,
96 })
97 if (out.status === 'error' || out.error) throw new Error(String(out.error || 'tool failed'))
98 return out.result ?? {}
99}
100
101async function loadMachine($: EngineInterface, c: any): Promise<RpMachine> {
102 const machine: RpMachine = {
103 id: c.id,
104 name: c.name,
105 platform: c.platform,
106 online: Boolean(c.online),
107 projects: [],
108 }
109 if (!machine.online) return { ...machine, error: 'offline' }
110 try {
111 const out = await callComputer($, c.id, 'list_projects', {})
112 const projects: RpProject[] = (out.projects ?? []).map((p: any) => ({
113 id: String(p.id),
114 name: String(p.name),
115 path: String(p.path),
116 }))
117 return { ...machine, projects }
118 } catch (err) {
119 return { ...machine, error: String((err as Error).message ?? err) }
120 }
121}
122
123async function load($: EngineInterface) {
124 await update($, isLoading, () => true)
125 await update($, error, () => null)
126 try {
127 const out = await callTool($, { tool: 'mcp__readyrig__list_computers' })
128 const list = await Promise.all(
129 (out.computers ?? []).map((c: any) => loadMachine($, c)),
130 )
131 await update($, machines, () => list)
132 } catch (err) {
133 await update($, error, () => String((err as Error).message ?? err))
134 }
135 await update($, isLoading, () => false)
136}
137
138// Every word of the search must appear in the project's name or path, or in
139// its machine's name. With a search, machines left without a match are hidden.
140function filterMachines(list: RpMachine[], text: string): RpMachine[] {
141 const words = text.toLowerCase().split(/\s+/).filter(Boolean)
142 if (words.length === 0) return list
143 return list
144 .map(m => ({
145 ...m,
146 projects: m.projects.filter(p => {
147 const hay = `${p.name} ${p.path} ${m.name}`.toLowerCase()
148 return words.every(w => hay.includes(w))
149 }),
150 }))
151 .filter(m => m.projects.length > 0)
152}
153
154// A project file's text, or null when it is missing or unreadable.
155async function readText(
156 $: EngineInterface,
157 p: RpPick,
158 path: string,
159 limit?: number,
160): Promise<ProjectFile | null> {
161 try {
162 const out = await callComputer($, p.machineId, 'read_file', {
163 project: p.project.id,
164 path,
165 ...(limit ? { limit } : {}),
166 })
167 if (typeof out.content !== 'string') return null
168 return { path, text: out.content, isTruncated: Boolean(out.truncated) }
169 } catch {
170 return null
171 }
172}
173
174// The name and description lines of a SKILL.md's YAML front matter. Enough
175// YAML for skills: plain or quoted values, and folded or indented ones.
176export function frontMatter(text: string): Record<string, string> {
177 const lines = text.split(/\r?\n/)
178 if (lines[0]?.trim() !== '---') return {}
179 const out: Record<string, string> = {}
180 let key: string | null = null
181 for (const line of lines.slice(1)) {
182 if (line.trim() === '---') break
183 const m = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line)
184 if (m) {
185 const [, name = '', raw = ''] = m
186 const value = raw.trim()
187 key = name
188 out[key] = /^[>|][+-]?$/.test(value) ? '' : value.replace(/^(["'])(.*)\1$/, '$2')
189 } else if (key && /^\s/.test(line)) {
190 out[key] = `${out[key]} ${line.trim()}`.trim()
191 }
192 }
193 return out
194}
195
196function plural(n: number, word: string): string {
197 return `${n} ${word}${n === 1 ? '' : 's'}`
198}
199
200// The pane's list of steps, and the count on the status line, as they run.
201async function setStep($: EngineInterface, id: string, patch: Partial<RpStep>) {
202 const next = await update($, progress, cur =>
203 cur && { ...cur, steps: cur.steps.map(s => (s.id === id ? { ...s, ...patch } : s)) },
204 )
205 if (next) showProgress($, next)
206}
207
208// Claude Code puts the plugin's name before its status line itself.
209function showProgress($: EngineInterface, p: RpProgress) {
210 const finished = p.steps.filter(s => s.state !== 'waiting' && s.state !== 'running').length
211 $.ui.status(`attaching ${p.projectName} @ ${p.machineName}… ${finished}/${p.steps.length}`)
212}
213
214// AGENTS.md or CLAUDE.md at the project's root. A CLAUDE.md that only
215// imports AGENTS.md (`@AGENTS.md`) adds nothing, so it counts as none.
216async function loadInstruction($: EngineInterface, p: RpPick, path: string) {
217 const file = await readText($, p, path)
218 const isEmpty =
219 !file ||
220 file.text.trim() === '' ||
221 (path === 'CLAUDE.md' && /^(\s*@(\.\/)?AGENTS\.md\s*)+$/.test(file.text))
222 if (isEmpty) {
223 await setStep($, path, { state: 'none', detail: file ? 'only imports AGENTS.md' : 'none' })
224 return null
225 }
226 const lines = file.text.split('\n').length
227 await setStep($, path, { state: 'done', detail: plural(lines, 'line') })
228 return file
229}
230
231// Each folder (or link to one) in a skills folder that holds a SKILL.md.
232async function loadSkills($: EngineInterface, p: RpPick, dir: string): Promise<RpSkill[]> {
233 let entries: any[]
234 try {
235 const out = await callComputer($, p.machineId, 'list_directory', {
236 project: p.project.id,
237 path: dir,
238 })
239 entries = out.entries ?? []
240 } catch {
241 await setStep($, dir, { state: 'none', detail: 'none' })
242 return []
243 }
244 const folders = entries
245 .filter(e => (e.directory || e.symlink) && !String(e.name).startsWith('.'))
246 .map(e => String(e.name))
247 await setStep($, dir, { detail: `reading ${plural(folders.length, 'skill')}` })
248 const skills = await Promise.all(
249 folders.map(async (folder): Promise<RpSkill | null> => {
250 const path = `${dir}/${folder}/SKILL.md`
251 const file = await readText($, p, path, 40)
252 if (!file) return null
253 const fm = frontMatter(file.text)
254 return { name: fm.name || folder, description: fm.description || '', path }
255 }),
256 )
257 const found = skills.filter((s): s is RpSkill => s !== null)
258 await setStep($, dir, {
259 state: found.length > 0 ? 'done' : 'none',
260 detail: found.length > 0 ? found.map(s => s.name).join(', ') : 'none',
261 })
262 return found
263}
264
265function markerOf(kind: 'attached' | 'detached', p: RpPick): string {
266 return `[rp:${kind} ${p.machineId}/${p.project.id}]`
267}
268
269// The folder's path stays out of the note: it can name the user, and the
270// project argument is all the tools need. Relative paths resolve inside it.
271function attachNote(
272 p: RpPick,
273 files: ProjectFile[],
274 skills: RpSkill[],
275 isLinked: boolean,
276): string {
277 const who = isLinked
278 ? `The person linked this session's folder to the ReadyRig project ` +
279 `"${p.project.name}" on machine "${p.machineName}" (computer_id: ` +
280 `${p.machineId}), so it was attached when the session started`
281 : `The person attached the ReadyRig project "${p.project.name}" on machine ` +
282 `"${p.machineName}" (computer_id: ${p.machineId}) to this session`
283 const parts = [
284 markerOf('attached', p),
285 `${who}, in place of any project attached before. Until they detach it, work in this project ` +
286 `unless they say otherwise: call mcp__readyrig__call_computer_tool with ` +
287 `computer_id "${p.machineId}", pass project: "${p.project.id}" in the tool's ` +
288 `arguments, and use paths relative to the project.`,
289 '## Project instructions',
290 ]
291 const names = INSTRUCTION_FILES.join(' or ')
292 if (files.length > 0) {
293 parts.push(
294 `From ${files.map(f => f.path).join(' and ')} at the project's root. Follow ` +
295 `them for work in this project. A subfolder may hold its own ${names}: ` +
296 `before changing files in a subfolder, look for one; the file nearest to ` +
297 `what you change wins, and what the person asks wins over all of them. ` +
298 `A line \`@path\` imports that file: read it with read_file when it matters.`,
299 )
300 for (const f of files) {
301 const isCut = f.isTruncated || f.text.length > INSTRUCTIONS_MAX
302 parts.push(
303 `<project_file path="${f.path}">\n${f.text.slice(0, INSTRUCTIONS_MAX).trimEnd()}\n` +
304 (isCut ? `[cut short here: read the rest with read_file]\n` : '') +
305 `</project_file>`,
306 )
307 }
308 } else {
309 parts.push(
310 `The project has no ${names} at its root. A subfolder may hold one: ` +
311 `before changing files in a subfolder, look for one and follow it.`,
312 )
313 }
314 parts.push('## Project skills')
315 if (skills.length > 0) {
316 parts.push(
317 `From ${SKILL_DIRS.join(' and ')}. When a task matches a skill's ` +
318 `description, read that whole SKILL.md with read_file on this computer ` +
319 `and project before you start, then follow it. Paths a skill names are ` +
320 `relative to its folder.`,
321 skills
322 .map(s => `- ${s.name}: ${s.description || '(no description)'} (${s.path})`)
323 .join('\n'),
324 )
325 } else {
326 parts.push(`The project has no skills in ${SKILL_DIRS.join(' or ')}.`)
327 }
328 return parts.join('\n\n')
329}
330
331function detachNote(p: RpPick): string {
332 return (
333 `${markerOf('detached', p)}\n` +
334 `The person detached the ReadyRig project "${p.project.name}" on machine ` +
335 `"${p.machineName}". Its instructions and skills no longer apply, and the ` +
336 `session has no attached project: don't work in it unless they ask.`
337 )
338}
339
340async function appendNote($: EngineInterface, text: string) {
341 const out = await $.session.append({
342 message: { type: 'user', content: [{ type: 'text', text }] },
343 })
344 if (out.deny) throw new Error(out.deny)
345}
346
347function summary(a: Pick<RpAttached, 'instructionFiles' | 'skills'>): string {
348 return [...a.instructionFiles, plural(a.skills.length, 'skill')].join(' · ')
349}
350
351function isSame(a: RpPick | null, b: RpPick | null): boolean {
352 return Boolean(a && b && a.machineId === b.machineId && a.project.id === b.project.id)
353}
354
355async function showStatus($: EngineInterface) {
356 const a = await read($, attached)
357 const linked = isSame(a, await read($, link)) ? ' · linked' : ''
358 $.ui.status(a ? `${a.project.name} @ ${a.machineName} · ${summary(a)}${linked}` : undefined)
359}
360
361// Reads the project's instructions and skills with the pane listing each
362// step, then hands them to the model in one note at the end of the conversation.
363async function attach(
364 $: EngineInterface,
365 p: RpPick,
366 isLinked = false,
367): Promise<RpAttached | null> {
368 const start: RpProgress = {
369 machineName: p.machineName,
370 projectName: p.project.name,
371 steps: [
372 ...INSTRUCTION_FILES.map(id => ({ id, label: id, state: 'running' as const })),
373 ...SKILL_DIRS.map(id => ({ id, label: id, state: 'running' as const })),
374 { id: NOTE_STEP, label: 'Add to the conversation', state: 'waiting' },
375 ],
376 }
377 await update($, progress, () => start)
378 showProgress($, start)
379 try {
380 const [files, skillLists] = await Promise.all([
381 Promise.all(INSTRUCTION_FILES.map(path => loadInstruction($, p, path))),
382 Promise.all(SKILL_DIRS.map(dir => loadSkills($, p, dir))),
383 ])
384 const instructions = files.filter((f): f is ProjectFile => f !== null)
385 const skills: RpSkill[] = []
386 for (const s of skillLists.flat()) {
387 if (!skills.some(k => k.name === s.name)) skills.push(s)
388 }
389
390 await setStep($, NOTE_STEP, { state: 'running' })
391 const note = attachNote(p, instructions, skills, isLinked)
392 await appendNote($, note)
393 await setStep($, NOTE_STEP, { state: 'done' })
394
395 const a: RpAttached = { ...p, instructionFiles: instructions.map(f => f.path), skills, note }
396 await update($, attached, () => a)
397 await update($, needsNote, () => false)
398 await update($, progress, () => null)
399 await showStatus($)
400 await $.ui.close({ id: PANE })
401 $.ui.toast(
402 `Attached ${p.project.name} @ ${p.machineName}${isLinked ? ' (linked)' : ''}: ${summary(a)}`,
403 )
404 return a
405 } catch (err) {
406 const message = String((err as Error).message ?? err)
407 await update($, progress, cur => cur && { ...cur, error: message })
408 await setStep($, NOTE_STEP, { state: 'failed' })
409 await showStatus($)
410 return null
411 }
412}
413
414async function detach($: EngineInterface): Promise<string> {
415 const a = await read($, attached)
416 if (!a) return 'No ReadyRig project is attached.'
417 await update($, attached, () => null)
418 await update($, needsNote, () => false)
419 await showStatus($)
420 await appendNote($, detachNote(a))
421 const l = await read($, link)
422 const stays = isSame(a, l) ? ` This folder stays linked to it: /rp unlink stops attaching it.` : ''
423 return `Detached ${a.project.name} @ ${a.machineName}.${stays}`
424}
425
426function slashed(path: string): string {
427 return /[\\/]$/.test(path) ? path : `${path}/`
428}
429
430async function readLinks($: EngineInterface): Promise<Record<string, RpPick>> {
431 const value = await $.store.get(LINKS)
432 return value && typeof value === 'object' ? (value as Record<string, RpPick>) : {}
433}
434
435// The link of the session's project root, or of the nearest folder above it.
436async function findLink($: EngineInterface): Promise<RpLink | null> {
437 const root = await $.session.root()
438 const links = await readLinks($)
439 const folder = Object.keys(links)
440 .filter(f => root === f || slashed(root).startsWith(slashed(f)) || root.startsWith(`${f}\\`))
441 .sort((a, b) => b.length - a.length)[0]
442 const p = folder ? links[folder] : undefined
443 return folder && p ? { ...p, folder } : null
444}
445
446// Links the session's project root to `p`, in place of a link it had.
447async function linkHere($: EngineInterface, p: RpPick): Promise<string> {
448 const folder = await $.session.root()
449 const links = await readLinks($)
450 const pick: RpPick = { machineId: p.machineId, machineName: p.machineName, project: p.project }
451 await $.store.set(LINKS, { ...links, [folder]: pick })
452 await update($, link, () => ({ ...pick, folder }))
453 await showStatus($)
454 return (
455 `Linked ${folder} to ${p.project.name} @ ${p.machineName}: a session started ` +
456 `in this folder, or in one below it, attaches it.`
457 )
458}
459
460async function unlink($: EngineInterface): Promise<string> {
461 const l = await findLink($)
462 if (!l) return 'This folder is not linked to a ReadyRig project.'
463 const { [l.folder]: _, ...rest } = await readLinks($)
464 await $.store.set(LINKS, rest)
465 // A link of a folder above this one may apply now.
466 await update($, link, () => null)
467 const above = await findLink($)
468 await update($, link, () => above)
469 await showStatus($)
470 const a = await read($, attached)
471 const stays = isSame(a, l) ? ' It stays attached to this session: /rp detach detaches it.' : ''
472 return `Unlinked ${l.folder} from ${l.project.name} @ ${l.machineName}.${stays}`
473}
474
475// The machine of a link, with its projects. Until the ReadyRig MCP server
476// connects, the session has no such tool and the call rejects: try again. A
477// denied call or an error answer is final.
478async function linkedMachine($: EngineInterface, l: RpLink): Promise<RpMachine> {
479 let ran: any
480 for (let tries = 1; !ran; tries++) {
481 try {
482 ran = await $.tool.call({ tool: 'mcp__readyrig__list_computers' } as any)
483 } catch (err) {
484 if (tries >= CONNECT_TRIES) throw err
485 await $.clock.sleep(CONNECT_WAIT_MS)
486 }
487 }
488 const c = (answerOf(ran).computers ?? []).find((c: any) => c.id === l.machineId)
489 if (!c) return { ...unknownMachine(l), error: 'not one of your ReadyRig computers' }
490 return loadMachine($, c)
491}
492
493function unknownMachine(l: RpLink): RpMachine {
494 return { id: l.machineId, name: l.machineName, platform: '', online: false, projects: [] }
495}
496
497// A session started in a linked folder attaches the linked project. A reload
498// of the mod leaves an attached project as it is.
499async function attachLinked($: EngineInterface) {
500 const l = await findLink($)
501 await update($, link, () => l)
502 if (!l || (await read($, attached)) || (await read($, progress))) return showStatus($)
503 const failed = (why: string) => {
504 $.ui.status(undefined)
505 $.ui.toast(`Could not attach ${l.project.name} @ ${l.machineName}, linked to this folder: ${why}`)
506 }
507 $.ui.status(`attaching ${l.project.name} @ ${l.machineName} (linked)…`)
508 let m: RpMachine
509 try {
510 m = await linkedMachine($, l)
511 } catch (err) {
512 return failed(String((err as Error).message ?? err))
513 }
514 if (m.error) return failed(m.error)
515 const project = m.projects.find(p => p.id === l.project.id)
516 if (!project) return failed(`the machine has no project ${l.project.name} any more`)
517 const a = await attach($, { machineId: m.id, machineName: m.name, project }, true)
518 if (!a) failed((await read($, progress))?.error ?? 'unknown error')
519 await update($, progress, () => null)
520}
521
522export function shellQuote(text: string): string {
523 return `'${text.replace(/'/g, `'\\''`)}'`
524}
525
526// Why show_image refuses a path, or null. The PNG copy is made by a shell
527// command, so the path is held inside the project as read_file holds its own.
528export function imagePathError(path: string): string | null {
529 if (!path.trim()) return 'give the path of an image file'
530 if (/^[/~$\\]|^[A-Za-z]:/.test(path)) return 'use a path relative to the project'
531 if (path.split(/[\\/]/).includes('..')) return 'the path must stay inside the project'
532 if (!IMAGE_EXT.test(path)) return 'not an image file (png, jpg, gif, webp, heic, tiff or bmp)'
533 return null
534}
535
536// On macOS, sips writes a PNG of the picture to `out`, at most IMAGE_MAX_SIDE
537// a side and never enlarged, smaller until it fits IMAGE_MAX_BYTES, and prints
538// `ok <width> <height>`. Without sips it prints `no-sips` and writes nothing.
539export function convertScript(path: string, out: string): string {
540 const src = shellQuote(`./${path}`)
541 const dst = shellQuote(out)
542 return [
543 'set -e',
544 'command -v sips >/dev/null 2>&1 || { echo no-sips; exit 0; }',
545 `mkdir -p ${PREVIEW_DIR}`,
546 `big=$(sips -g pixelWidth -g pixelHeight ${src} | awk '/pixel(Width|Height)/ { if ($2 > m) m = $2 } END { print m + 0 }')`,
547 `m=${IMAGE_MAX_SIDE}`,
548 'if [ "$big" -gt 0 ] && [ "$big" -lt "$m" ]; then m=$big; fi',
549 'while :; do',
550 ` sips -s format png -Z "$m" ${src} --out ${dst} >/dev/null`,
551 ` if [ "$(stat -f %z ${dst})" -le ${IMAGE_MAX_BYTES} ] || [ "$m" -le ${IMAGE_MIN_SIDE} ]; then break; fi`,
552 ' m=$((m * 7 / 10))',
553 'done',
554 `sips -g pixelWidth -g pixelHeight ${dst} | awk '/pixelWidth/ { w = $2 } /pixelHeight/ { h = $2 } END { print "ok", w, h }'`,
555 ].join('\n')
556}
557
558// A PNG's size, from the IHDR chunk at the start of its base64.
559export function pngSize(base64: string): { width: number; height: number } | null {
560 const head = atob(base64.slice(0, 32))
561 if (head.slice(1, 4) !== 'PNG' || head.length < 24) return null
562 const at = (i: number) =>
563 ((head.charCodeAt(i) << 24) | (head.charCodeAt(i + 1) << 16) | (head.charCodeAt(i + 2) << 8) | head.charCodeAt(i + 3)) >>> 0
564 return { width: at(16), height: at(20) }
565}
566
567// The terminal cells a picture is drawn over, its shape kept.
568export function imageCells(width: number, height: number): { columns: number; rows: number } {
569 let columns = Math.max(4, Math.min(IMAGE_COLUMNS, Math.round(width / CELL_PX)))
570 let rows = Math.max(2, Math.round((columns * height) / width / 2))
571 if (rows > IMAGE_ROWS) {
572 columns = Math.max(4, Math.round((columns * IMAGE_ROWS) / rows))
573 rows = IMAGE_ROWS
574 }
575 return { columns, rows }
576}
577
578// A shell command on a ReadyRig computer; a non-zero exit rejects with its stderr.
579async function runCommand($: EngineInterface, machineId: string, project: string, command: string) {
580 const out = await callComputer($, machineId, 'exec_command', {
581 project,
582 command,
583 yield_time_ms: 10_000,
584 })
585 if (out.running) throw new Error('the command is taking too long')
586 if (out.exit_code) throw new Error(String(out.stderr || out.stdout || `exit ${out.exit_code}`).trim())
587 return String(out.stdout ?? '')
588}
589
590// read_file answers a picture as an MCP image block beside its JSON text.
591async function readPng($: EngineInterface, machineId: string, project: string, path: string) {
592 const ran: any = await $.tool.call({
593 tool: 'mcp__readyrig__call_computer_tool',
594 computer_id: machineId,
595 tool_name: 'read_file',
596 arguments: { project, path },
597 } as any)
598 const out = answerOf(ran)
599 if (out.status === 'error' || out.error) throw new Error(String(out.error || 'tool failed'))
600 const blocks: any[] = Array.isArray(ran.result) ? ran.result : (ran.result?.content ?? [])
601 const block = blocks.find(b => b?.type === 'image')
602 const data = block?.data ?? block?.source?.data
603 if (typeof data !== 'string' || !data) throw new Error('ReadyRig sent no picture')
604 if (!pngSize(data)) throw new Error('ReadyRig sent a picture that is not a PNG')
605 return data
606}
607
608// The picture as a PNG the terminal can draw: converted on macOS, read as it
609// is elsewhere when it is a PNG already. The copy is removed in every case.
610async function fetchImage($: EngineInterface, p: RpPick, path: string, id: string): Promise<RpImage> {
611 const project = p.project.id
612 const copy = `${PREVIEW_DIR}/${id.replace(/[^\w-]/g, '')}.png`
613 let png: string
614 try {
615 const said = (await runCommand($, p.machineId, project, convertScript(path, copy))).trim()
616 if (said === 'no-sips') {
617 if (!/\.png$/i.test(path)) throw new Error('only PNG files can be shown from a computer without macOS sips')
618 png = await readPng($, p.machineId, project, path)
619 } else {
620 png = await readPng($, p.machineId, project, copy)
621 }
622 } finally {
623 await runCommand($, p.machineId, project, `rm -f ${shellQuote(copy)}; rmdir ${PREVIEW_DIR} 2>/dev/null || true`).catch(() => {})
624 }
625 if (png.length * 0.75 > IMAGE_MAX_BYTES) throw new Error('the picture is larger than 2 MiB')
626 const size = pngSize(png)!
627 return { ...size, png, path, machineId: p.machineId, machineName: p.machineName, projectId: project }
628}
629
630async function openInPreview($: EngineInterface, img: RpImage): Promise<string | null> {
631 try {
632 await runCommand($, img.machineId, img.projectId, `open -a Preview ${shellQuote(`./${img.path}`)}`)
633 return null
634 } catch (err) {
635 return `Could not open ${img.path} in Preview on ${img.machineName}: ${String((err as Error).message ?? err)}`
636 }
637}
638
639const STEP_ICON: Record<RpStep['state'], string> = {
640 waiting: '·',
641 running: '…',
642 done: '✓',
643 none: '–',
644 failed: '✗',
645}
646
647export const register: Register = on => {
648 // Attaching a linked project runs while Claude Code starts; the first prompt
649 // waits for it, so the model has the note before it answers.
650 let linking: Promise<void> | null = null
651 // The show_image calls whose pictures are kept, oldest first.
652 const shown: string[] = []
653
654 on('session.start', async ($, e, next) => {
655 await $.command.register({
656 name: 'rp',
657 description: 'Attach a ReadyRig project (its AGENTS.md, CLAUDE.md and skills) to this session',
658 argumentHint: '[detach | link | unlink]',
659 })
660 await $.tool.register({
661 name: SHOW_IMAGE,
662 description:
663 'Show the person an image file from the ReadyRig project attached with /rp: it is drawn ' +
664 'in their terminal (Ghostty, kitty) with an "Open in Preview" button, and where the ' +
665 'terminal draws no pictures (tmux, herdr) the button alone. Use it when they ask to ' +
666 'see an image or a screenshot, or when showing one helps. You do not see the picture: ' +
667 'read it with read_file when you need to look at it yourself.',
668 inputSchema: {
669 type: 'object',
670 properties: {
671 path: { type: 'string', description: 'The image file, relative to the attached project' },
672 open_in_preview: {
673 type: 'boolean',
674 description: 'Also open it in Preview on that Mac, as when they ask to open it',
675 },
676 },
677 required: ['path'],
678 additionalProperties: false,
679 },
680 isDeferred: false,
681 })
682 linking = attachLinked($).catch(() => {})
683
684 return next(e)
685 })
686
687 on('tool.call', { tool: SHOW_IMAGE_TOOL }, async ($, e) => {
688 const input = e as unknown as { path?: unknown; open_in_preview?: unknown }
689 const path = typeof input.path === 'string' ? input.path.replace(/^\.\//, '') : ''
690 const a = await read($, attached)
691 if (!a) return { deny: 'No ReadyRig project is attached: the person attaches one with /rp.' }
692 const why = imagePathError(path)
693 if (why) return { deny: `Cannot show ${path || 'that'}: ${why}.` }
694 let img: RpImage
695 try {
696 img = await fetchImage($, a, path, e.tool_use_id)
697 } catch (err) {
698 return { deny: `Cannot show ${path}: ${String((err as Error).message ?? err)}` }
699 }
700 await update($, memberOf(images, { requestId: e.tool_use_id }), () => img)
701 shown.push(e.tool_use_id)
702 for (const old of shown.splice(0, Math.max(0, shown.length - IMAGES_KEPT))) {
703 await update($, memberOf(images, { requestId: old }), () => null)
704 }
705 const failed = input.open_in_preview === true ? await openInPreview($, img) : null
706 const opened = input.open_in_preview === true && !failed ? ' and opened it in Preview' : ''
707 return {
708 result:
709 `Showed ${path} (${img.width}×${img.height} PNG) from ${a.project.name} @ ${a.machineName} ` +
710 `to the person${opened}.${failed ? ` ${failed}` : ''}`,
711 }
712 }).catch(($, e) => ({ deny: `Cannot show the image: it took too long or failed.` }))
713
714 on('command.run', { command: 'rp' }, async ($, e) => {
715 const arg = e.args.trim()
716 if (arg === 'detach' || arg === 'clear') {
717 await $.ui.close({ id: PANE })
718 return { text: await detach($) }
719 }
720 if (arg === 'unlink') return { text: await unlink($) }
721 const current = await read($, attached)
722 if (arg === 'link' && current) return { text: await linkHere($, current) }
723
724 const isLink = arg === 'link'
725 await update($, query, () => '')
726 await update($, progress, () => null)
727 await update($, isLinking, () => isLink)
728 await $.ui.open({
729 id: PANE,
730 title: isLink ? 'Link a ReadyRig project to this folder' : 'ReadyRig projects',
731 focus: true,
732 closeOnEscape: true,
733 })
734 await load($)
735
736 return {
737 text: isLink
738 ? 'Pick a ReadyRig project to attach and link to this folder in the pane (Esc to cancel).'
739 : 'Pick a ReadyRig project to attach in the pane (Esc to cancel).',
740 }
741 })
742
743 // The note is appended once, at the end of the conversation, so the cached
744 // prompt before it stays valid. A compaction of the main conversation or a
745 // /clear drops it: the next prompt puts it back.
746 on('session.compact', async ($, e, next) => {
747 const out = await next(e)
748 if (!e.agentId && e.trigger !== 'precompute' && out.messages) {
749 await update($, needsNote, () => true)
750 }
751 return out
752 })
753
754 on('session.end', async ($, e, next) => {
755 if (e.reason === 'clear') await update($, needsNote, () => true)
756 return next(e)
757 })
758
759 on('prompt.submit', async ($, e, next) => {
760 const isCommand = e.text.trimStart().startsWith('/')
761 // Held under the hook's 10 s budget; a slower attach adds its note when done.
762 if (linking && !isCommand) {
763 await Promise.race([linking, $.clock.sleep(LINK_WAIT_MS)])
764 linking = null
765 }
766 const a = await read($, attached)
767 if (a && (await read($, needsNote)) && !isCommand) {
768 await appendNote($, a.note)
769 await update($, needsNote, () => false)
770 }
771 return next(e)
772 }).catch(($, e, next) => next(e))
773
774 // The picture over the row's cells where the terminal draws pictures, its
775 // dim path elsewhere, and a button that opens it in Preview on the Mac.
776 on('ui.render', { component: 'ToolResult', props: { tool: SHOW_IMAGE_TOOL } }, async ($, e, next) => {
777 if (e.props.isErrored) return next(e)
778 const img = await read($, memberOf(images, e))
779 if (!img) return next(e)
780 const elements = $.ui.resolve(e)
781 const { Box, Text, Button } = elements
782 const Image = 'Image' in elements ? elements.Image : null
783 const cells = imageCells(img.width, img.height)
784 return (
785 <Box flexDirection="column">
786 {Image && (
787 <Image
788 source={{ png: img.png }}
789 columns={cells.columns}
790 rows={cells.rows}
791 alt={`[${img.path}]`}
792 />
793 )}
794 <Box flexDirection="row" flexWrap="wrap">
795 <Text dimColor>
796 {img.path} · {img.width}×{img.height} · {img.machineName} ·{' '}
797 </Text>
798 <Button
799 key="preview"
800 plain
801 label="Open in Preview"
802 onPress={async () => {
803 const failed = await openInPreview($, img)
804 if (failed) $.ui.toast(failed)
805 }}
806 />
807 </Box>
808 </Box>
809 )
810 })
811
812 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
813 const elements = $.ui.resolve(e)
814 const { Box, Text, Button } = elements
815 // The mobile app draws no text field yet: it shows the whole list.
816 const Input = 'Input' in elements ? elements.Input : null
817 const list = await read($, machines)
818 const loading = await read($, isLoading)
819 const failed = await read($, error)
820 const current = await read($, attached)
821 const running = await read($, progress)
822 const search = await read($, query)
823 const linked = await read($, link)
824 const shown = filterMachines(list, search)
825
826 if (running) {
827 const labelWidth = Math.max(...running.steps.map(s => s.label.length)) + 2
828 return (
829 <Box flexDirection="column">
830 <Box marginBottom={1}>
831 <Text bold>
832 Attaching {running.projectName} <Text dimColor>@ {running.machineName}</Text>
833 </Text>
834 </Box>
835 {running.steps.map(s => (
836 <Box key={`s-${s.id}`} flexDirection="row" paddingLeft={2}>
837 <Box width={2} flexShrink={0}>
838 <Text color={s.state === 'failed' ? 'red' : s.state === 'done' ? 'green' : undefined}>
839 {STEP_ICON[s.state]}
840 </Text>
841 </Box>
842 <Box width={labelWidth} flexShrink={0}>
843 <Text dimColor={s.state === 'waiting'}>{s.label}</Text>
844 </Box>
845 <Box flexGrow={1} flexShrink={1}>
846 <Text dimColor wrap="wrap">
847 {s.detail ?? (s.state === 'running' ? 'reading…' : '')}
848 </Text>
849 </Box>
850 </Box>
851 ))}
852 {running.error && (
853 <Box marginTop={1}>
854 <Text color="red">Could not attach: {running.error} · Esc to close</Text>
855 </Box>
856 )}
857 </Box>
858 )
859 }
860
861 // From /rp link, the project picked is linked once it is attached.
862 const choose = async (m: RpMachine, project: RpProject) => {
863 const a = await attach($, { machineId: m.id, machineName: m.name, project })
864 if (a && (await read($, isLinking))) {
865 await update($, isLinking, () => false)
866 $.ui.toast(await linkHere($, a))
867 }
868 }
869
870 // Enter in the search box picks the first project that matches.
871 const chooseFirst = async (text: string) => {
872 const m = filterMachines(await read($, machines), text)[0]
873 const p = m?.projects[0]
874 if (m && p) await choose(m, p)
875 }
876
877 // One name column for every machine, so the paths line up.
878 const nameWidth = Math.max(0, ...list.flatMap(m => m.projects.map(p => p.name.length)))
879 // Too narrow for name and path side by side: put the path on its own line.
880 const isStacked = (e.props.bodyColumns ?? 80) - (2 + 2 + nameWidth + 2) < 20
881
882 return (
883 <Box flexDirection="column">
884 {Input && (
885 <Box marginBottom={1}>
886 <Input
887 key="search"
888 label="Search: "
889 placeholder="project, path or machine"
890 value={search}
891 submitLabel="attach first"
892 autoFocus
893 onInput={value => update($, query, () => value)}
894 onSubmit={value => chooseFirst(value)}
895 />
896 </Box>
897 )}
898 {loading && <Text dimColor>Loading ReadyRig machines…</Text>}
899 {failed && <Text color="red">Could not list machines: {failed}</Text>}
900 {!loading && !failed && list.length === 0 && (
901 <Text dimColor>No ReadyRig machines found.</Text>
902 )}
903 {!loading && list.length > 0 && shown.length === 0 && (
904 <Text dimColor>No projects match "{search}".</Text>
905 )}
906 {shown.map(m => (
907 <Box key={`m-${m.id}`} flexDirection="column" marginBottom={1}>
908 <Text bold>
909 {m.name} <Text dimColor>({m.platform}{m.online ? '' : ', offline'})</Text>
910 </Text>
911 {m.error && (
912 <Box paddingLeft={2}>
913 <Text dimColor>{m.error}</Text>
914 </Box>
915 )}
916 {!m.error && m.projects.length === 0 && (
917 <Box paddingLeft={2}>
918 <Text dimColor>no projects</Text>
919 </Box>
920 )}
921 {m.projects.map(p => (
922 <Box
923 key={`p-${m.id}-${p.id}`}
924 flexDirection={isStacked ? 'column' : 'row'}
925 paddingLeft={2}
926 >
927 <Box flexDirection="row" flexShrink={0}>
928 <Box width={2} flexShrink={0}>
929 <Text>{isSame(current, { machineId: m.id, machineName: m.name, project: p }) ? '●' : ' '}</Text>
930 </Box>
931 <Box width={isStacked ? undefined : nameWidth + 2} flexShrink={0}>
932 <Button
933 key={`b-${m.id}-${p.id}`}
934 plain
935 label={p.name}
936 onPress={() => choose(m, p)}
937 />
938 </Box>
939 </Box>
940 <Box flexGrow={1} flexShrink={1} paddingLeft={isStacked ? 4 : 0}>
941 <Text dimColor wrap="wrap">{p.path}</Text>
942 </Box>
943 </Box>
944 ))}
945 </Box>
946 ))}
947 {current && (
948 <Box flexDirection="row" flexWrap="wrap">
949 <Text dimColor>Attached: {current.project.name} @ {current.machineName} · </Text>
950 <Button
951 key="detach"
952 plain
953 label="detach"
954 onPress={async () => {
955 await detach($)
956 await $.ui.close({ id: PANE })
957 }}
958 />
959 {!isSame(current, linked) && (
960 <Box key="link-row" flexDirection="row">
961 <Text dimColor> · </Text>
962 <Button
963 key="link"
964 plain
965 label="link to this folder"
966 onPress={async () => $.ui.toast(await linkHere($, current))}
967 />
968 </Box>
969 )}
970 </Box>
971 )}
972 {linked && (
973 <Box flexDirection="row" flexWrap="wrap">
974 <Text dimColor>
975 Linked: {linked.folder} → {linked.project.name} @ {linked.machineName} ·{' '}
976 </Text>
977 <Button
978 key="unlink"
979 plain
980 label="unlink"
981 onPress={async () => $.ui.toast(await unlink($))}
982 />
983 </Box>
984 )}
985 </Box>
986 )
987 })
988}
989types/index.d.ts 78 lines1export type RpProject = { id: string; name: string; path: string }
2
3export type RpMachine = {
4 id: string
5 name: string
6 platform: string
7 online: boolean
8 projects: RpProject[]
9 error?: string
10}
11
12export type RpPick = {
13 machineId: string
14 machineName: string
15 project: RpProject
16}
17
18// A folder on this computer linked to a ReadyRig project: a session started
19// in it, or in a folder below it, attaches the project.
20export type RpLink = RpPick & { folder: string }
21
22// A skill from .agents/skills or .claude/skills; path is project-relative.
23export type RpSkill = { name: string; description: string; path: string }
24
25// The project attached to the session, with the note the model was handed.
26export type RpAttached = RpPick & {
27 instructionFiles: string[]
28 skills: RpSkill[]
29 note: string
30}
31
32// One step of attaching, as the pane lists it while it runs.
33export type RpStep = {
34 id: string
35 label: string
36 state: 'waiting' | 'running' | 'done' | 'none' | 'failed'
37 detail?: string
38}
39
40export type RpProgress = {
41 machineName: string
42 projectName: string
43 steps: RpStep[]
44 error?: string
45}
46
47// A picture show_image drew: a PNG of at most 2 MiB, base64, and where it is.
48export type RpImage = {
49 png: string
50 width: number
51 height: number
52 path: string
53 machineId: string
54 machineName: string
55 projectId: string
56}
57
58declare module 'claude-code' {
59 interface PluginState {
60 rp: {
61 machines: RpMachine[]
62 isLoading: boolean
63 error: string | null
64 attached: RpAttached | null
65 // The conversation lost the attached project's note (a compaction, /clear).
66 needsNote: boolean
67 progress: RpProgress | null
68 query: string
69 // The link of the session's folder, or of the nearest folder above it.
70 link: RpLink | null
71 // The pane was opened by /rp link: the project picked is linked too.
72 isLinking: boolean
73 // By show_image call (tool_use_id); null once the picture is let go.
74 image: StateFamily<RpImage | null>
75 }
76 }
77}
78