SLOPSHOPPER

sleight

Unofficial: lets Claude drive macOS apps in the background through the computer-use engine bundled with the ChatGPT desktop app, without taking over your…

paneguardcommandtoaststatusprompt
★ 5v1.4.2MITupdated 2026-10-22Land-o-Clusters/sleight/plugins/sleight
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sleight
│ ┃ sleight ✕ › fix the failing auth test and add an audit log call │ ┃ No picture yet. It appears after Claude uses │ ┃ an app, or press Refresh. ⏺ Read(src/auth.ts) │ ┃ ⎿ Read 6 lines │ ┃ [ Refresh ][ Stop ] ⏺ Update(src/auth.ts) │ ┃ Replay JSON file ⎿ Added 2 lines, removed 1 line │ ┃ [ Replay file ][ Record session ] ⏺ Bash(bun test) │ ┃ Actions ⎿ 3 pass, 1 fail │ ┃ None yet. │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /sleight │ ⎿ sleight: sleight pane opened. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · sleight
No picture yet. It appears after Claude uses an app, or press Refresh. [ Refresh ][ Stop ] Replay JSON file [ Replay file ][ Record session ] Actions None yet.
README

<h1 align="center"><img src="docs/assets/sleight-icon-256.png" width="64" height="64" align="center" alt="sleight icon: two hands passing a mouse pointer, trailing warm and cool pixels"> sleight</h1>

<a href="https://github.com/Land-o-Clusters/sleight/releases/latest"><img alt="latest release" src="https://img.shields.io/github/v/release/Land-o-Clusters/sleight?label=release&color=E8622C"></a> <img alt="license MIT" src="https://img.shields.io/badge/license-MIT-E8622C"> <img alt="platform macOS Apple Silicon" src="https://img.shields.io/badge/platform-macOS%20Apple%20Silicon-3E4A56"> <img alt="status unofficial" src="https://img.shields.io/badge/status-unofficial-3E4A56">

sleight is an MIT-licensed plugin for Claude Code, Codex, Grok CLI and Cursor (install not yet run). Grok Bot uses its local shell. Ask it to work out a sum in Calculator or edit a document, and it operates that app in the background.

You need an Apple Silicon Mac. The ChatGPT desktop app is required in /Applications because sleight runs its computer-use engine. You don't need a ChatGPT account or sign-in. sleight uses your coding agent's account or API access, without a separate Codex sign-in.

<a id="install-validation"></a>

[!IMPORTANT] sleight is unofficial. OpenAI and Anthropic don't endorse or support it. A ChatGPT update can break it. The new install flow and setup in a fresh macOS user haven't run live. Install time and typical task cost are unmeasured. See requirements for tested macOS versions. sleight contains no OpenAI code.

LCU, Cua, Peekaboo and FowlBrowser are competing computer-use tools. An arm means one agent setup.

<!-- hub:claim --> sleight's own 9-task native Mac benchmark: 251.2 s total expected time. Claude computer use: 453.9 s.<br> Expected time is mean time per attempt divided by the pass rate, estimating time to a correct result when failed attempts are retried.<br> Benchmark hub · Interactive page <!-- /hub:claim -->

Install

Install sleight from https://github.com/Land-o-Clusters/sleight and check it with its doctor.

Paste that into your coding agent. It follows INSTALL.md, stopping for your admin password, macOS permissions, Chrome's debugging switch and app approvals.

Where it runs

HostInstall route and validationLimits
Claude Code 2.1.288 or laterPlugin. Native and app claims on 2.1.289.No known host-specific gaps.
Codex CLIPlugin. Calculator and TextEdit passed on 0.160.0 after first-call retries, fixed since but not rerun live.Turbo needs trusted hooks and awaits a live check.
Grok CLIDirect MCP. Handshake on 1.0.13. Model and app tasks untested.Turbo off. Results capped at 20,000 bytes.
Grok Bot (preview)Local shell via sleight-mcp js. One live read passed.Turbo off. Approvals wait in the menu bar glove (limits).
Other MCP clientsStdio config, tested with our own client.Turbo unavailable.
CursorPlugin, with marketplace install unverified.Turbo unavailable.

The action pane, status line and /sleight are Claude Code only (host details).

To install by hand, follow INSTALL.md. If Computer Use is already on in ChatGPT or Codex, installing the plugin is enough. Otherwise run ./bin/sleight-mcp setup from the installed plugin folder (Computer Use). It uses ChatGPT's Node runtime. npm isn't needed.

sleight drives native apps, including Electron apps such as VS Code, Slack and Spotify, through the engine. Safari and Firefox use the engine's accessibility path. The engine refuses terminals and OpenAI's own apps (how it works).

Turbo

Turbo drives Chrome and Helium directly. It is on by default after you enable Chrome's one-time debugging switch. The browser asks you to allow each connection (setup).

In the turbo race, Chrome had the lowest expected time on 10 of 13 tasks, 258.9 s total against FowlBrowser's 447.8 s (2026-10-18 to 2026-10-19). Helium had the lowest expected time on 11 of 13, 241.8 s total against 338.3 s (2026-10-18).

From the installed plugin folder, you run ./bin/sleight-mcp turbo on (Chrome first, then Helium), ./bin/sleight-mcp turbo on --browser helium to choose Helium, or ./bin/sleight-mcp turbo off to opt out until you turn it on again (settings).

New in 1.4.0

  • Text drags move between windows, repair spacing and keep empty final lines. Opened-file handles keep their document window. sleight refuses formatted cross-window moves.
  • sleight rejects malformed native arguments before the engine sends input and reports the correct signature. It handles shutdown while the engine loads.
  • Turbo fills multi-selects and accepts modifier clicks on safe targets. Shorter replies explain field values, batch boundaries and viewport markers.
  • Requested sign-ups count as confirmed when your message names the username or email and password (limits).
  • Opt-in local stats report action times and reads saved.
  • Grok CLI adds direct MCP (10 tools in its 1.0.13 handshake). Cursor adds a plugin, with install not yet run. Grok Bot adds the local shell route as a preview: one live Calculator read passed, and its approvals wait in the menu bar glove.
  • Protected consent buttons require physical input (accessibility limits). Chrome and Helium turbo is on by default after Chrome's debugging consent.
  • The ghost hand is off by default: textedit-drag took 31 to 37 s with it, 23 to 26 s without (3 runs a side, details).

Release validation for 1.4.1 (2026-10-22, Haiku 5.5 at high effort, engine 26.1016.51333): the full check passed (12,770 tests), and 1.4.1 ran against 1.4.0 on sleight's own tasks. In Chrome both passed all 13 tasks 3 times, at 218.9 s total expected time against 213.0 s. On 8 native held-out tasks, run on the same harness, 1.4.1's mean total was 501.7 s (7 runs) against 1.4.0's 515.8 s (3 runs). One Opus 5.5 round passed all 13 Chrome tasks in 237.3 s. The 1.4.1 benchmark harness makes native tasks slower than 1.4.0's harness, measured but not yet explained (known problems).

<!-- hub:headline --> <img src="docs/results/img/headline-native-light.svg" width="900" alt="Native claim, 2026-10-17 to 2026-10-18: sleight's total expected time over 9 tasks is 251.2 s against Claude computer use at 453.9 s, and LCU, Codex, Cua and Peekaboo have no total because each never passed at least one task.">

<sub>Native claim, 2026-10-17 to 2026-10-18: sleight's total expected time over 9 tasks is 251.2 s against Claude computer use at 453.9 s, and LCU, Codex, Cua and Peekaboo have no total because each never passed at least one task.</sub> <!-- /hub:headline -->

How fast

<!-- hub:benchmarks -->

  • Native claim: "fastest", sleight's total expected time 251.2 s over 9 tasks (197 runs, 2026-10-17 to 2026-10-18). Engine 26.1007.71326, 2026-10-17 to 2026-10-18.
  • App claim: "fastest", sleight's total expected time 56.8 s over 3 tasks (60 runs, 2026-10-18, 02:39 to 03:16 UTC). Engine 26.1007.71326, 2026-10-18.
  • Chrome and Helium: turbo against FowlBrowser: in Chrome, the lowest expected time on 10 of 13 and a total of 258.9 s against FowlBrowser's 447.8 s (sleight-turbo-rel130). In Helium, the lowest expected time on 11 of 13 and a total of 241.8 s against FowlBrowser's 338.3 s (sleight-turbo-b5). 14 gate studies. Engine 26.1007.71326, 2026-10-18 and engine 26.1013.40934, 2026-10-19.
  • Safari and Firefox: the engine path against Codex, LCU, Cua and Peekaboo: in Safari sleight is fastest on 11 of 12 tasks, the only arm with a total (592.1 s) (sleight-b10, 2026-10-18). In Firefox sleight is fastest on 11 of 12 tasks, with a total of 557.1 s (sleight-b10, 2026-10-18). Engine 26.1007.71326, 2026-10-18 and engine 26.1013.40934, 2026-10-19.
  • Experiments: 17 studies with run data. The catalog has 95 benchmark write-ups and includes studies without structured run data.
  • Validation: build A against build B: 1 scored bank: 1 validation, 0 re-measure. 6 more have no score file. 21 A/B groups in all. Build B has a higher expected time or a lower pass rate than build A on 37 of 72 task comparisons. Newest scored bank: validation-140-final (2026-10-20).
  • Release passes and the earlier head-to-heads: 7 release passes (2026-10-05 to 2026-10-09), 115 results files in all.

<img src="docs/results/img/overview-light.svg" width="900" alt="Total expected seconds of sleight against the next-best arm with a total, in the newest complete set of each benchmark. Native apps, 251.2 s against Claude computer use at 453.9 s. VS Code, Slack, Spotify, 56.8 s against LCU at 101.3 s. Chrome, turbo, 258.9 s against FowlBrowser at 447.8 s. Helium, turbo, 241.8 s against FowlBrowser at 338.3 s. Safari, engine path, 592.1 s, and no other arm has a total. Firefox, engine path, 557.1 s against Cua at 2541.4 s.">

<sub>Total expected seconds of sleight against the next-best arm with a total, in the newest complete set of each benchmark. Native apps, 251.2 s against Claude computer use at 453.9 s. VS Code, Slack, Spotify, 56.8 s against LCU at 101.3 s. Chrome, turbo, 258.9 s against FowlBrowser at 447.8 s. Helium, turbo, 241.8 s against FowlBrowser at 338.3 s. Safari, engine path, 592.1 s, and no other arm has a total. Firefox, engine path, 557.1 s against Cua at 2541.4 s.</sub> <!-- /hub:benchmarks -->

How it works

The engine is the computer-use software bundled with ChatGPT. sleight's launcher starts it on ChatGPT's own Node runtime. The relay connects it to your agent and shows approval cards. In Claude Code, a UI extension (the mod) draws the action pane and ends the engine's turn after each of yours (how it works).

Safety

These are the intended checks. Known problems lists guards with only unit coverage and what has run live.

  • Each app gets one approval card with Allow, Always allow and Decline.
  • Always allow, payment and consent buttons accept only a person's click or key press.
  • VoiceOver, Switch Control, Voice Control and screen-sharing users need a physical keyboard or pointer for these cards in 1.4.0 (limits and planned alternative).
  • A payment goes ahead without another prompt only when your own message names what to pay, the amount and what to pay with. When a page tries to pay, sleight always asks (settings).
  • sleight treats page text as untrusted input when checking actions and approvals. The js tool runs JavaScript as you, so Claude Code asks before each call unless you allow mcp__plugin_sleight_computer__js.
  • sleight never switches Spaces or takes focus, except for Chrome's own consent prompt. A few fallbacks (foreground drag, hover, some menu bar icons) move the pointer briefly, each after you've stopped typing for 2 s.

More

Credits

  • @argofowl showed that the ChatGPT app's computer-use server works outside Codex.
  • LCU, started by 0xpolarzero, takes the same idea across several harnesses, and its notes mapped out the runtime's lifecycle.
  • Turbo includes playwright-core 1.64.0, unmodified, with its notices in THIRD-PARTY-NOTICES.md.

License

MIT. The ChatGPT app and its computer-use runtime belong to OpenAI, under OpenAI's terms, and sleight doesn't include or redistribute either. ChatGPT, Codex, Claude, Cursor, Chrome, Safari, Firefox, Helium, Microsoft Word, Excel, VS Code, Slack, Spotify and other app names are trademarks of their owners, who don't endorse or sponsor sleight, and appear here to describe compatibility and benchmark results.

Source 5 files
hooks/register.tsx 552 lines
1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { Frame, LogEntry, ViewStatus } from '../types'
5import { FRAME_MARKER, snapshotCode } from './snapshot'
6import { fileArgument, outcomeOf, resultEntries } from './replay'
7import type { ReplayScript } from './replay'
8import { preapprovedWriteDenied, loggingSwitchWriteDenied } from './preapproved-write-guard.mjs'
9
10// The server's own name in plugin.json; the session lists it as
11// plugin:sleight:computer, and its tools as mcp__plugin_sleight_computer__*.
12const SERVER = 'computer'
13const JS_TOOL = 'mcp__plugin_sleight_computer__js'
14const TURN_END_TOOL = 'mcp__plugin_sleight_computer__turn_ended'
15const REPLAY_TOOL = 'mcp__plugin_sleight_computer__replay'
16const BROWSER_TOOLS = ['browser_open', 'browser_read', 'browser_act', 'browser_fill']
17const PANE = 'sleight'
18const LOG_LIMIT = 200
19
20const log = atom({ plugin: 'sleight', key: 'log' } as const, [] as LogEntry[])
21const frame = atom({ plugin: 'sleight', key: 'frame' } as const, null as Frame | null)
22const view = atom({ plugin: 'sleight', key: 'view' } as const, { kind: 'idle' } as ViewStatus)
23const stopped = atom({ plugin: 'sleight', key: 'stopped' } as const, false)
24const replayFile = atom({ plugin: 'sleight', key: 'replayFile' } as const, '')
25const replaying = atom({ plugin: 'sleight', key: 'replaying' } as const, false)
26let replayActive = false
27let replayCancelled = false
28let replaySequence = 0
29const receipt = atom({ plugin: 'sleight', key: 'receipt' } as const, null as { path?: string; review?: string; unavailable?: boolean } | null)
30
31// Not drawn from, so plain module variables (a reload resets them, harmlessly).
32let usedThisTurn = false
33let turnRunning = false
34let actions = 0
35let lastApp: string | undefined
36// The exact snapshot code in flight, for the tool.check below.
37let snapshotInFlight: string | undefined
38// Apps the pane snapshotted since Claude last used sleight. The engine diffs
39// UI state against the latest read of an app, whoever made it, so Claude's
40// next diff would be against the pane's read; the next prompt says so.
41const snapshottedApps = new Set<string>()
42// The pane's last drawn size, for sizing the next snapshot.
43let paneColumns = 48
44let paneRows = 20
45// The surface that last drew the pane; a snapshot carries only what it draws.
46let paneSurface = 'terminal'
47
48// Host-issued turn capability stays in this mod's private runtime. It never
49// enters atoms, pane history, prompt context or model-facing tool results.
50type TurboEnvelope = { version: 1; session: string; nonce: string }
51let turboEnvelope: TurboEnvelope | undefined
52let turboSequence = 0
53let turboPending = Promise.resolve()
54
55async function beginTurboTurn($: any, text: string) {
56  if (turboSequence >= Number.MAX_SAFE_INTEGER) return
57  const turn = `turbo-${++turboSequence}`
58  const running = turboPending.then(async () => {
59    let contactingHost = false
60    try {
61      const state = await $.process.run([`${$.plugin.root}/bin/sleight-mcp`, 'turbo-state'])
62      if (state.exitCode !== 0 || state.isStdoutTruncated === true || typeof state.stdout !== 'string' ||
63          state.stdout.length > 4096) return
64      const enabled = JSON.parse(state.stdout)?.enabled
65      if (enabled !== true) {
66        if (enabled === false) turboEnvelope = undefined
67        return
68      }
69      contactingHost = true
70      if (!turboEnvelope) {
71        const response = await call($, 'turn_ended', { sleight_turbo: { event: 'bootstrap' } })
72        if (response.isError || response.content?.length !== 1 || response.content[0]?.type !== 'text' ||
73            typeof response.content[0].text !== 'string' || response.content[0].text.length > 4096) return
74        const data = JSON.parse(response.content[0].text)
75        const envelope = data?.sleightTurbo
76        if (!data || Object.keys(data).length !== 1 || !envelope || Object.keys(envelope).length !== 3 || envelope.version !== 1 ||
77            typeof envelope.session !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(envelope.session) ||
78            typeof envelope.nonce !== 'string' || !/^[a-f0-9]{64}$/.test(envelope.nonce)) return
79        turboEnvelope = { version: 1, session: envelope.session, nonce: envelope.nonce }
80      }
81      const response = await call($, 'turn_ended', { sleight_turbo: { ...turboEnvelope, event: 'begin', turn, text } })
82      // A declined or unavailable begin grants no authority. The bootstrap is
83      // one-use, so keep its validated envelope for a fresh genuine user turn.
84      if (!response.isError) usedThisTurn = true
85    } catch { if (contactingHost) turboEnvelope = undefined }
86  })
87  // Serialize genuine submissions so simultaneous user turns cannot create
88  // competing bootstrap envelopes. Failure never changes ordinary prompting.
89  turboPending = running
90  await running
91}
92
93const now = () => new Date().toTimeString().slice(0, 8)
94
95function appFrom(code: string, text: string | undefined): string | undefined {
96  return code.match(/getApp\(\s*["'`]([^"'`]+)["'`]/)?.[1] ?? text?.match(/App: ([^.\n]+)\./)?.[1]
97}
98
99function setStatus($: { ui: { status: (text: string | undefined) => void } }) {
100  $.ui.status(lastApp ? `sleight · ${lastApp} · ${actions} action${actions === 1 ? '' : 's'}` : undefined)
101}
102
103// Runs one call on the engine as this mod.
104async function call($: any, tool: string, args: Record<string, unknown>) {
105  const conn = await $.mcp.connect(SERVER)
106  if (!conn.isConnected) throw new Error(conn.message)
107  return $.mcp.call(conn.server, tool, args)
108}
109
110async function recordCurrent($: any, file?: string) {
111  if (turnRunning || replayActive) return { text: 'Wait for the current run to finish before recording.' }
112  try {
113    const path = file !== undefined ? fileArgument(file) : `sleight-${await $.session.id()}.json`
114    if (await $.fs.exists(path)) throw new Error(`${path} already exists. Choose another file.`)
115    const session = await $.session.id()
116    // The live API's messages may have been compacted. The CLI reads the saved transcript.
117    // Write to a sidecar so a script over the host's 4 MiB stdout cap still records.
118    const staging = `${path}.recording`
119    let recorded
120    try {
121      const run = await $.process.run([`${$.plugin.root}/bin/sleight-mcp`, 'record', session, staging])
122      if (run.exitCode !== 0) throw new Error(run.stderr || `Recorder exited ${run.exitCode}.`)
123      recorded = JSON.parse(await $.fs.read(staging))
124    } finally {
125      try { await $.process.run(['/bin/rm', '-f', staging]) } catch {}
126    }
127    if (!recorded.steps?.length) throw new Error('No successful sleight actions in this session yet.')
128    await $.fs.write(path, JSON.stringify(recorded, null, 2) + '\n')
129    await update($, replayFile, () => path)
130    return { text: `Recorded ${recorded.steps.length} steps to ${path}.${recorded.skipped?.length ? ` Skipped tools: ${[...new Set(recorded.skipped)].join(', ')}.` : ''}` }
131  } catch (err) {
132    return { text: `Recording failed: ${(err as Error).message}` }
133  }
134}
135
136async function replayCurrent($: any, file: string) {
137  if (turnRunning || replayActive) return { text: 'Wait for the current run to finish before replaying.' }
138  replayActive = true
139  replayCancelled = false
140  const id = `replay-${++replaySequence}`
141  let engineStarted = false
142  let handoff: string | undefined
143  try {
144    if (await read($, stopped) || replayCancelled) return { text: 'sleight is stopped. Send a new message before replaying.' }
145    const path = fileArgument(file)
146    const script: ReplayScript = JSON.parse(await $.fs.read(path))
147    if (replayCancelled) return { text: 'Replay stopped before starting.' }
148    if (script?.sleightReplay !== 1 || !Array.isArray(script.steps)) throw new Error('Not a sleight replay script.')
149    await update($, replayFile, () => path)
150    await update($, replaying, () => true)
151    snapshottedApps.clear()
152    await update($, log, list => [...list, { id, title: `Replaying ${path}`, status: 'running', at: now() } as LogEntry].slice(-LOG_LIMIT))
153    const conn = await $.mcp.connect(SERVER)
154    if (!conn.isConnected) throw new Error(conn.message)
155    if (await read($, stopped) || replayCancelled) {
156      await update($, log, list => list.map(entry => entry.id === id ? { ...entry, title: 'Replay stopped before starting.', status: 'refused' } : entry))
157      return { text: 'Replay stopped before starting.' }
158    }
159    engineStarted = true
160    const outcome = outcomeOf(await $.mcp.call(conn.server, 'replay', { script }))
161    // The replay's reads move the engine's diff baseline, as a pane snapshot does.
162    // Literal getApp("Name") is enough; otherwise the App: line in the outcome window.
163    const windowText = typeof outcome.window === 'string' ? outcome.window : undefined
164    for (const step of script.steps) {
165      const app = appFrom(step.args?.code ?? '', windowText)
166      if (app) snapshottedApps.add(app)
167    }
168    const entries = resultEntries(script, outcome, id, now())
169    await update($, log, list => [...list.filter(entry => entry.id !== id), ...entries].slice(-LOG_LIMIT))
170    if (await read($, stopped) || replayCancelled) {
171      const step = outcome.step ?? outcome.steps ?? outcome.waits.at(-1)?.step
172      const text = `Replay stopped by the user at step ${step ?? 'unknown'}. This step may have sent input. Check the window before repeating it.`
173      await update($, log, list => [...list, { id: `${id}-stop`, title: text, status: 'refused', at: now() } as LogEntry].slice(-LOG_LIMIT))
174      return { text }
175    }
176    if (!outcome.ok) {
177      // No pane read or turn_ended here: either can discard a pending flow exception.
178      handoff = 'sleight replay stopped. Inspect the stop details and finish the task with the existing app handles. ' +
179        'The stopped batch may have sent input; check the window before repeating any action. ' +
180        'Respect refusals and ask the user for any required approval. Replay result:\n' + JSON.stringify(outcome)
181      return { text: `Replay stopped at step ${outcome.step}: ${outcome.error}. Sending the stop details to Claude.` }
182    }
183    const app = [...script.steps].reverse().map(step => appFrom(step.args.code ?? '', windowText)).find(Boolean)
184    if (app) lastApp = app
185    actions += outcome.steps ?? 0
186    setStatus($)
187    await endEngineTurn($, 'Stop')
188    return { text: `Replay finished: ${outcome.steps} steps.` }
189  } catch (err) {
190    const message = (err as Error).message
191    await update($, log, list => [...list.filter(entry => entry.id !== id), { id, title: `Replay failed: ${message}`, status: 'error', at: now() } as LogEntry].slice(-LOG_LIMIT))
192    if (engineStarted) await endEngineTurn($, 'Interrupt')
193    return { text: `Replay failed: ${message}` }
194  } finally {
195    if (replayCancelled) await update($, stopped, () => true)
196    await update($, replaying, () => false)
197    replayActive = false
198    if (handoff) {
199      const prompt = handoff
200      $.clock.after(0, async () => {
201        if (await read($, stopped) || replayCancelled) return
202        if (replayActive || id !== `replay-${replaySequence}`) {
203          $.ui.toast('sleight: a newer replay started before the stop reached Claude. Send the stop details from the log when it finishes.')
204          return
205        }
206        await $.prompt.submit({ text: prompt }).catch((err: Error) => $.ui.toast(`sleight: couldn't hand the stop to Claude (${err.message}). Send the stop details from the log.`))
207      })
208    }
209  }
210}
211
212// Tells the engine the turn is over so it releases what it holds, as Codex
213// does at the end of each turn. The relay fills in the session and turn ids.
214async function endEngineTurn($: any, event: 'Stop' | 'Interrupt', checked = false) {
215  try {
216    const ended = await call($, 'turn_ended', { hook_event_name: event, ...(checked ? { sleight_stop: true } : {}) })
217    let latest = (ended as { _meta?: { 'sleight/receipt'?: { path?: string; review?: string; unavailable?: boolean } } })._meta?.['sleight/receipt']
218    // The installed host's $.mcp.call keeps content but drops _meta. The relay supplies JSON
219    // in one fixed marker so paths with spaces and multi-line reviews don't need a prose parser.
220    if (!latest) for (const block of ended.content ?? []) {
221      const text = block?.type === 'text' && typeof block.text === 'string' ? block.text : ''
222      if (!text.startsWith('sleight-receipt: ') || text.length > 262144) continue
223      try {
224        const value = JSON.parse(text.slice('sleight-receipt: '.length))
225        if (!value || typeof value !== 'object' || Array.isArray(value)) continue
226        latest = {
227          ...(typeof value.path === 'string' && value.path.startsWith('/') && value.path.length <= 4096 ? { path: value.path } : {}),
228          ...(typeof value.review === 'string' && value.review.length <= 32100 ? { review: value.review } : {}),
229          ...(value.unavailable === true ? { unavailable: true } : {}),
230        }
231      } catch {}
232    }
233    if (latest) await update($, receipt, () => latest)
234    $.ui.log(`sleight: turn_ended ${ended.isError ? `failed: ${JSON.stringify(ended.content)}` : 'sent'}`, { to: 'debug' })
235    // The relay names an app sleight drove that holds a keyboard event tap, once per session.
236    for (const block of ended.content ?? []) {
237      const text = typeof block?.text === 'string' ? block.text : ''
238      if (text.startsWith('sleight-warning: ')) $.ui.toast(text.slice('sleight-warning: '.length))
239    }
240    if (checked) {
241      return (ended.content ?? []).map((block: { text?: string }) => block.text ?? '')
242        .find((text: string) => text.startsWith('sleight stop:')) ?? 'sleight stop unconfirmed: the engine returned no checked receipt.'
243    }
244  } catch (err) {
245    $.ui.log(`sleight: could not end the turn: ${(err as Error).message}`, { to: 'debug' })
246    if (checked) return `sleight stop unconfirmed: ${(err as Error).message}`
247  }
248}
249
250async function snapshot($: any, app: string) {
251  await update($, view, () => ({ kind: 'snapshotting', app }) as ViewStatus)
252  try {
253    // Leave rows for the status, controls, file input, "Actions" and three log lines.
254    const code = snapshotCode(app, Math.max(8, paneColumns - 2), Math.max(4, paneRows - 9), paneSurface === 'terminal')
255    snapshotInFlight = code
256    const result = await call($, 'js', { code, title: 'sleight pane snapshot' }).finally(() => { snapshotInFlight = undefined })
257    const text = result.content.map((block: { text?: string }) => block.text ?? '').join('\n')
258    const line = text.split('\n').find((l: string) => l.startsWith(FRAME_MARKER))
259    if (result.isError || !line) {
260      throw new Error(result.isError ? text.slice(0, 200) : 'no frame in the result')
261    }
262    const shot = JSON.parse(line.slice(FRAME_MARKER.length))
263    snapshottedApps.add(app)
264    await update($, frame, () => ({ ...shot, at: now() }) as Frame)
265    await update($, view, () => ({ kind: 'idle' }) as ViewStatus)
266  } catch (err) {
267    await update($, view, () => ({ kind: 'error', message: (err as Error).message }) as ViewStatus)
268  }
269}
270
271// A pane list that rejects counts as closed: the turn's end runs after this check, and an engine
272// turn that never ends keeps the session busy.
273async function isPaneOpen($: any): Promise<boolean> {
274  try {
275    const panes = await $.ui.panes()
276    return panes.some((pane: { id: string }) => pane.id === PANE)
277  } catch {
278    return false
279  }
280}
281
282// In Auto mode the classifier refused the pane's own snapshot, since no request of the person's
283// asked for it (2026-10-08). This mod allows exactly two calls: its snapshot, by the code it just
284// built, and turn_ended. next.origin is set by the host, so only this plugin's own calls pass;
285// Claude's calls (origin engine) go to the normal check.
286function ownCallVerdict(e: { tool: string; input: unknown }, origin: { plugin: string } | undefined) {
287  if (origin?.plugin !== 'sleight') return undefined
288  if (e.tool === TURN_END_TOOL) return { decision: 'allow', reason: 'sleight ends the engine turn' } as const
289  const code = (e.input as { code?: unknown } | undefined)?.code
290  if (e.tool === JS_TOOL && snapshotInFlight !== undefined && code === snapshotInFlight) {
291    return { decision: 'allow', reason: 'sleight pane snapshot' } as const
292  }
293  return undefined
294}
295
296export const register: Register = on => {
297  on('classic.PreToolUse', async ($, e, next) => {
298    if (!['Write', 'Edit', 'MultiEdit', 'NotebookEdit', 'Bash'].includes(e.tool)) return next(e)
299    if (loggingSwitchWriteDenied(e)) return { deny: "Only the user turns on sleight's action log and outcome lines. Ask them to make this change." }
300    const denied = await preapprovedWriteDenied(e, {
301      stat: (path: string) => $.fs.stat(path, { resolve: true }),
302      home: await $.env.get('HOME'),
303    })
304    return denied ? { deny: "Only the user edits sleight's approval files. Ask them to make this change." } : next(e)
305  })
306  on('tool.check', async ($, e, next) => ownCallVerdict(e, next.origin) ?? next(e))
307    // Failing open to the normal check only ever tightens. A call from inside this mod's own
308    // frame lands here as a re-entry, decided from e and next alone. The host's published
309    // HookFailure kind union is 'throw' | 'timeout' only, so the kind reads through a widening.
310    .catch(($, e, next) => ((next.error?.kind as string | undefined) === 're-entry' ? ownCallVerdict(e, next.origin) : undefined) ?? next(e))
311  on('session.start', async ($, e, next) => {
312    turboEnvelope = undefined
313    await $.command.register({
314      name: 'sleight',
315      description: 'Open the sleight pane; replay a JSON file, record this session, or stop computer use',
316      argumentHint: '[replay <file> | record [file] | stop | prompt]',
317      immediate: true,
318    })
319    return next(e)
320  })
321
322  // A new prompt lifts a stop, and tells Claude about pane snapshots that
323  // moved the engine's diff baseline. The host skips this hook for our own
324  // automatic handoff, so that handoff cannot lift Stop.
325  on('prompt.submit', async ($, e, next) => {
326    if (await read($, stopped)) {
327      // A failed collection keeps the relay alive. Lift its closing flag only at this user boundary.
328      await call($, 'turn_ended', { sleight_resume: true }).catch(() => undefined)
329    }
330    await update($, stopped, () => false)
331    if ((e.origin?.kind === 'composer' || e.origin?.kind === 'bridge') &&
332        (e as { agentId?: string }).agentId === undefined) await beginTurboTurn($, e.text)
333    if (snapshottedApps.size === 0) return next(e)
334    const apps = [...snapshottedApps].join(', ')
335    snapshottedApps.clear()
336    const note =
337      `sleight: its pane or a replay read the UI state of ${apps} after your last sleight call. ` +
338      'The engine diffs against the latest read, so pass { disableDiffing: true } to your next ' +
339      'getAXState() for that app before relying on a diff.'
340    return next({ ...e, context: [...(e.context ?? []), note] })
341  })
342
343  on('turn.start', async ($, e, next) => {
344    turnRunning = true
345    return next(e)
346  })
347
348  on('tool.call', { tool: JS_TOOL }, async ($, e, next) => {
349    if (next.origin?.plugin === 'sleight') return next(e)
350    if (replayActive) return { deny: 'A replay is running. Wait for it to stop before sending another tool call.' }
351    if (await read($, stopped)) {
352      return { deny: 'The user stopped sleight with /sleight stop. Do not use it again until they ask.' }
353    }
354    usedThisTurn = true
355    snapshottedApps.clear()
356    const code = String(e.code ?? '')
357    const entry: LogEntry = {
358      id: e.tool_use_id,
359      title: String(e.title ?? '') || (code.split('\n')[0] ?? '').slice(0, 80),
360      status: 'running',
361      at: now(),
362    }
363    await update($, log, list => [...list, entry].slice(-LOG_LIMIT))
364    const ran = await next(e)
365    const app = appFrom(code, ran.text)
366    if (app) lastApp = app
367    actions++
368    const status: LogEntry['status'] = ran.deny !== undefined ? 'refused' : ran.isError ? 'error' : 'done'
369    await update($, log, list => list.map(one => (one.id === entry.id ? { ...one, status, app: app ?? one.app } : one)))
370    setStatus($)
371    return ran
372  })
373
374  // The host's tool-name union comes from its last saved capture, which here
375  // predates the replay tool, so the filter's name reads through a widening.
376  on('tool.call', { tool: REPLAY_TOOL as never }, async ($, e, next) => {
377    if (next.origin?.plugin === 'sleight') return next(e)
378    if (await read($, stopped)) return { deny: 'The user stopped sleight with /sleight stop. Do not use it again until they ask.' }
379    if (replayActive) return { deny: 'A replay is running. Wait for it to stop before sending another tool call.' }
380    usedThisTurn = true
381    return next(e)
382  })
383
384  // Compact browser verbs are session work too. The fixed completion hook must
385  // fence turbo even when the turn never called native JS. Log only the verb,
386  // keeping field values and page content out of the pane's action history.
387  for (const name of BROWSER_TOOLS) on('tool.call', { tool: `mcp__plugin_sleight_computer__${name}` as never }, async ($, e, next) => {
388    if (next.origin?.plugin === 'sleight') return next(e)
389    if (await read($, stopped)) return { deny: 'The user stopped sleight with /sleight stop. Do not use it again until they ask.' }
390    if (replayActive) return { deny: 'A replay is running. Wait for it to stop before sending another tool call.' }
391    usedThisTurn = true
392    const entry: LogEntry = { id: e.tool_use_id, title: name, status: 'running', at: now() }
393    await update($, log, list => [...list, entry].slice(-LOG_LIMIT))
394    const ran = await next(e)
395    actions++
396    const status: LogEntry['status'] = ran.deny !== undefined ? 'refused' : ran.isError ? 'error' : 'done'
397    await update($, log, list => list.map(one => one.id === entry.id ? { ...one, status } : one))
398    setStatus($)
399    return ran
400  })
401
402  // turn_ended stays listed so this mod can call it; Claude may not.
403  on('tool.call', { tool: TURN_END_TOOL }, async ($, e, next) =>
404    next.origin?.plugin === 'sleight' ? next(e) : { deny: 'turn_ended is internal to sleight; its hooks call it when a turn ends.' },
405  )
406
407  on('turn.complete', async ($, e, next) => {
408    const result = await next(e)
409    if (e.agentId !== undefined) return result
410    turnRunning = false
411    if (!usedThisTurn) return result
412    usedThisTurn = false
413    // Refresh the pane while the engine turn is still open, then end it.
414    if (lastApp && !e.isAborted && (await isPaneOpen($))) await snapshot($, lastApp)
415    await endEngineTurn($, e.isAborted ? 'Interrupt' : 'Stop')
416    return result
417  })
418
419  on('command.run', { command: 'sleight' }, async ($, e) => {
420    const args = e.args.trim()
421    if (args === 'record' || args.startsWith('record ')) return recordCurrent($, args.slice(6).trim() || undefined)
422    if (e.args.trim() === 'stop') {
423      if (replayActive) replayCancelled = true
424      await update($, stopped, () => true)
425      usedThisTurn = false
426      const receipt = await endEngineTurn($, 'Interrupt', true)
427      $.ui.status('sleight · stopped')
428      // The interrupted call usually ends Claude's turn at once (desktop app, 2026-10-11), so Esc
429      // is only for a turn that goes on without sleight.
430      return { text: `${receipt} If Claude keeps working, press Esc to end its turn.` }
431    }
432    await $.ui.open({ id: PANE, title: 'sleight' })
433    if (args === 'replay' || args.startsWith('replay ')) return replayCurrent($, args.slice(6))
434    // `/sleight do this` opens the pane and sends "do this" to Claude, as if
435    // typed on its own line. The engine refuses a submit from inside this hook
436    // (the prompt would wait on the command submitting it), so it goes out
437    // just after; it waits for any running turn to finish.
438    const prompt = e.args.trim()
439    if (!prompt) return { text: 'sleight pane opened.' }
440    $.clock.after(0, async () => {
441      // A new session may not have connected sleight yet. Sent first, the prompt ran with no
442      // sleight tools and Claude used the shell instead (2026-10-08).
443      await $.mcp.connect(SERVER).catch(() => undefined)
444      $.prompt.submit({ text: prompt, asUser: true }).catch(err => {
445        $.ui.toast(`sleight: couldn't send your prompt (${(err as Error).message}). Send it on its own line.`)
446      })
447    })
448    return { text: 'sleight pane opened. Sending your prompt to Claude.' }
449  })
450
451  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
452    const els = $.ui.resolve(e)
453    const { Box, Text, Button } = els
454    paneSurface = e.surface
455    paneColumns = Math.max(8, Math.min(120, e.props.bodyColumns ?? 48))
456    // The rows the surface gave the pane: about a third of the terminal inline,
457    // its full height docked. A picture sized to more pushes the buttons and
458    // log out of view.
459    paneRows = Math.max(10, Math.min(40, e.props.scroll?.bodyRows ?? Math.floor((e.viewport?.rows ?? 30) / 2)))
460
461    const [entries, shot, status, isStopped, file, isReplaying, latest] = await Promise.all([read($, log), read($, frame), read($, view), read($, stopped), read($, replayFile), read($, replaying), read($, receipt)])
462
463    const picture = (() => {
464      if (!shot) return <Text dimColor>No picture yet. It appears after Claude uses an app, or press Refresh.</Text>
465      if (e.surface === 'terminal' && 'Raster' in els && shot.cells) {
466        const { Raster } = els as any
467        return <Raster key="frame" columns={shot.columns} rows={shot.rows} cells={shot.cells} />
468      }
469      if ('Svg' in els && shot.image) {
470        const { Svg } = els as any
471        // Not `h`: JSX compiles to calls of the global h, and a local h broke the drawing.
472        const width = 320
473        const height = Math.round((shot.height / shot.width) * width)
474        const source =
475          `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">` +
476          `<image href="data:${shot.image.mime};base64,${shot.image.base64}" width="${width}" height="${height}"/></svg>`
477        return <Svg source={source} alt={`Screenshot of ${shot.app}`} width={width} height={height} />
478      }
479      return <Text dimColor>{`${shot.app}: picture not shown on this surface. Press Refresh.`}</Text>
480    })()
481
482    const statusLine =
483      isReplaying ? 'Replay running. Stop ends it after the current call.'
484      : status.kind === 'snapshotting' ? `Refreshing ${status.app}…`
485      : status.kind === 'error' ? `Couldn't refresh: ${status.message}`
486      : shot ? `${shot.app} at ${shot.at}`
487      : ''
488    // Size the log to the rows the pane shows, not the whole terminal: picture,
489    // status line, buttons and the "Actions" heading take the rest.
490    const bodyRows = e.props.scroll?.bodyRows ?? e.viewport?.rows ?? 30
491    const room = Math.max(3, bodyRows - (shot?.rows ?? 1) - 6)
492    const mark = { running: '…', done: '✓', error: '✗', refused: '⊘' } as const
493
494    return (
495      <Box flexDirection="column">
496        {picture}
497        <Text dimColor>{isStopped ? 'Stopped until your next message.' : statusLine}</Text>
498        <Box flexDirection="row">
499          <Button
500            key="refresh"
501            label={turnRunning ? 'Refresh (after this turn)' : 'Refresh'}
502            hotkey="r"
503            onPress={() => {
504              if (turnRunning || replayActive || !lastApp) return
505              const app = lastApp
506              void snapshot($, app).then(() => endEngineTurn($, 'Stop'))
507            }}
508          />
509          <Button
510            key="stop"
511            label="Stop"
512            hotkey="s"
513            onPress={() => {
514              if (replayActive) replayCancelled = true
515              void update($, stopped, () => true)
516              usedThisTurn = false
517              void endEngineTurn($, 'Interrupt', true).then(receipt => $.ui.toast(receipt ?? 'sleight stop unconfirmed'))
518              $.ui.status('sleight · stopped')
519            }}
520          />
521        </Box>
522        {'Input' in els && (() => {
523          const { Input } = els as any
524          return <Input key="replay-file" value={file} placeholder="Replay JSON file" onInput={(value: string) => update($, replayFile, () => value)} onSubmit={(value: string) => update($, replayFile, () => value)} />
525        })()}
526        <Box flexDirection="row">
527          <Button key="replay" label="Replay file" onPress={async () => {
528            const result = await replayCurrent($, await read($, replayFile))
529            $.ui.toast(result.text)
530          }} />
531          <Button key="record" label="Record session" onPress={async () => {
532            const result = await recordCurrent($, await read($, replayFile))
533            $.ui.toast(result.text)
534          }} />
535        </Box>
536        {/* Text, not a Link: Claude Code 2.1.288 refuses a file:// href and then draws nothing (CI, 2026-10-11). */}
537        {latest?.path?.startsWith('/') && <Text>Latest receipt: {latest.path}</Text>}
538        {latest?.unavailable && <Text>Receipt unavailable; the private file could not be written.</Text>}
539        {latest?.review && <Text>{latest.review}</Text>}
540        <Text bold>Actions</Text>
541        {entries.length === 0 && <Text dimColor>None yet.</Text>}
542        {/* Newest first, so the latest action stays visible however short the pane is. */}
543        {entries.slice(-room).reverse().map(entry => (
544          <Text dimColor={entry.status === 'done'} wrap="truncate-end">
545            {`${mark[entry.status]} ${entry.at} ${entry.app ? `${entry.app}: ` : ''}${entry.title}`}
546          </Text>
547        ))}
548      </Box>
549    )
550  })
551}
552
hooks/snapshot.ts 117 lines
1// The JavaScript the mod runs in the computer-use engine's session (through
2// the `js` tool) to draw its pane. It must stay self-contained: it runs in the
3// engine, not here. snapshotCode() fills in the app and the frame size.
4//
5// It writes one line, `SLEIGHT_FRAME <json>`: the app's screenshot as
6// terminal cells (upper half blocks, two pixels per cell) for a terminal pane,
7// or else as an image small enough to embed in an SVG. Only one, to keep the
8// result small. The engine's sandbox can't load `sharp`, so it decodes with
9// the bundled pure-JS jpeg-js and pngjs.
10
11const SNAPSHOT_JS = `await (async () => {
12  // Claude Code replaces an MCP result over its token limit (25,000 by default)
13  // with a notice, and base64 counts heavily: a 51,135-character image never
14  // reached the desktop pane (2026-10-08). So the image stays near 16,000.
15  const APP = __APP__, COLS = __COLS__, ROWS = __ROWS__, TERMINAL = __TERMINAL__, MAX_IMAGE_B64 = 16000;
16  const app = await cua.getApp(APP);
17  const shot = Buffer.from(await app.getScreenshot({ emit: false }));
18  const isJpeg = shot[0] === 0xff && shot[1] === 0xd8;
19  // A desktop image that fits needs dimensions, not decoded pixels. Read PNG's IHDR or JPEG's
20  // frame header; unsupported or truncated headers fall through to the existing decoder.
21  const dimensions = () => {
22    if (!isJpeg) {
23      if (shot.length >= 33 && shot.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) &&
24          shot.readUInt32BE(8) === 13 && shot.toString('ascii', 12, 16) === 'IHDR') {
25        return { width: shot.readUInt32BE(16), height: shot.readUInt32BE(20) };
26      }
27      return;
28    }
29    let at = 2;
30    while (at < shot.length) {
31      if (shot[at++] !== 0xff) return;
32      while (shot[at] === 0xff) at++;
33      const marker = shot[at++];
34      if (marker === 0xda || marker === 0xd9 || at + 2 > shot.length) return;
35      if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
36      const length = shot.readUInt16BE(at);
37      if (length < 2 || at + length > shot.length) return;
38      if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker) && length >= 8) {
39        return { width: shot.readUInt16BE(at + 5), height: shot.readUInt16BE(at + 3) };
40      }
41      at += length;
42    }
43  };
44  if (!TERMINAL && Math.ceil(shot.length / 3) * 4 <= MAX_IMAGE_B64) {
45    const size = dimensions();
46    if (size?.width > 0 && size?.height > 0) {
47      const scale = Math.max(size.width / COLS, size.height / (ROWS * 2));
48      const columns = Math.max(1, Math.min(COLS, Math.round(size.width / scale)));
49      const rows = Math.ceil(Math.max(2, Math.min(ROWS * 2, Math.round(size.height / scale))) / 2);
50      nodeRepl.write('SLEIGHT_FRAME ' + JSON.stringify({ app: APP, ...size,
51        columns, rows, image: { mime: isJpeg ? 'image/jpeg' : 'image/png', base64: shot.toString('base64') } }));
52      return;
53    }
54  }
55  const decoded = isJpeg
56    ? (await import('jpeg-js')).default.decode(shot, { useTArray: true })
57    : (await import('pngjs')).PNG.sync.read(shot);
58  const { width, height, data } = decoded;
59
60  // Fit the screenshot into COLS x ROWS*2 pixels, keeping its aspect ratio,
61  // averaging each source block.
62  const scale = Math.max(width / COLS, height / (ROWS * 2));
63  const outW = Math.max(1, Math.min(COLS, Math.round(width / scale)));
64  const outH = Math.max(2, Math.min(ROWS * 2, Math.round(height / scale)));
65  const px = (x, y) => {
66    const x0 = Math.floor(x * width / outW), x1 = Math.max(x0 + 1, Math.floor((x + 1) * width / outW));
67    const y0 = Math.floor(y * height / outH), y1 = Math.max(y0 + 1, Math.floor((y + 1) * height / outH));
68    let r = 0, g = 0, b = 0, n = 0;
69    for (let yy = y0; yy < y1; yy++) for (let xx = x0; xx < x1; xx++) {
70      const i = (yy * width + xx) * 4;
71      r += data[i]; g += data[i + 1]; b += data[i + 2]; n++;
72    }
73    return (Math.round(r / n) << 16) | (Math.round(g / n) << 8) | Math.round(b / n);
74  };
75  const rows = Math.ceil(outH / 2);
76  const cells = Buffer.alloc(TERMINAL ? outW * rows * 12 : 0);
77  if (TERMINAL) for (let r = 0; r < rows; r++) for (let c = 0; c < outW; c++) {
78    const o = (r * outW + c) * 12;
79    cells.writeUInt32LE(0x2580, o);
80    cells.writeUInt32LE(px(c, r * 2), o + 4);
81    cells.writeUInt32LE(r * 2 + 1 < outH ? px(c, r * 2 + 1) : 0x01000000, o + 8);
82  }
83
84  let image = { mime: isJpeg ? 'image/jpeg' : 'image/png', base64: shot.toString('base64') };
85  if (TERMINAL) image = undefined;
86  else if (image.base64.length > MAX_IMAGE_B64) {
87    // Too big to embed: re-encode as a JPEG, from 1.5 times the 320 px the desktop
88    // pane draws, smaller and rougher until it fits.
89    const { encode } = (await import('jpeg-js')).default;
90    for (const [maxW, quality] of [[480, 70], [400, 60], [320, 55], [240, 50], [160, 45], [96, 40], [48, 35]]) {
91      const w = Math.min(width, maxW), h = Math.max(1, Math.round(height * w / width));
92      const small = Buffer.alloc(w * h * 4);
93      for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
94        const si = (Math.floor(y * height / h) * width + Math.floor(x * width / w)) * 4, di = (y * w + x) * 4;
95        small[di] = data[si]; small[di + 1] = data[si + 1]; small[di + 2] = data[si + 2]; small[di + 3] = 255;
96      }
97      image = { mime: 'image/jpeg', base64: Buffer.from(encode({ data: small, width: w, height: h }, quality).data).toString('base64') };
98      if (image.base64.length <= MAX_IMAGE_B64) break;
99    }
100  }
101
102  nodeRepl.write('SLEIGHT_FRAME ' + JSON.stringify({
103    app: APP, width, height, columns: outW, rows, cells: TERMINAL ? cells.toString('base64') : undefined, image,
104  }));
105})()
106`
107
108export const FRAME_MARKER = 'SLEIGHT_FRAME '
109
110export function snapshotCode(app: string, columns: number, rows: number, terminal: boolean): string {
111  return SNAPSHOT_JS
112    .replace('__APP__', JSON.stringify(app))
113    .replace('__TERMINAL__', String(terminal))
114    .replace('__COLS__', String(columns))
115    .replace('__ROWS__', String(rows))
116}
117
hooks/replay.ts 44 lines
1import type { LogEntry } from '../types'
2
3export type ReplayScript = { sleightReplay: 1; steps: { tool: string; args: { code?: string; title?: string }; positions?: string[] }[] }
4export type ReplayOutcome = {
5  ok: boolean
6  steps?: number
7  step?: number
8  error?: string
9  waits: { step: number; waitedMs: number }[]
10  remaining?: ReplayScript['steps']
11  window?: string | null
12  windowError?: string
13}
14
15// A filename is the whole argument, optionally quoted. No shell is involved.
16export function fileArgument(text: string) {
17  const path = text.trim()
18  if (!path) throw new Error('Choose a JSON file.')
19  if (path[0] === '"' || path[0] === "'") {
20    if (path.at(-1) !== path[0] || path.length < 3) throw new Error('Close the filename quote.')
21    return path.slice(1, -1)
22  }
23  return path
24}
25
26export function outcomeOf(result: { content?: { text?: string }[]; isError?: boolean }): ReplayOutcome {
27  const text = (result.content ?? []).map(block => block.text ?? '').join('\n')
28  if (result.isError) throw new Error(text)
29  const outcome = JSON.parse(text)
30  if (typeof outcome.ok !== 'boolean' || !Array.isArray(outcome.waits)) throw new Error('No replay outcome in the tool result.')
31  return outcome
32}
33
34export function resultEntries(script: ReplayScript, outcome: ReplayOutcome, id: string, at: string): LogEntry[] {
35  return outcome.waits.map(wait => {
36    const step = script.steps[wait.step - 1]
37    const failed = !outcome.ok && wait.step === outcome.step
38    return {
39      id: `${id}-${wait.step}`, at, status: failed ? 'error' : 'done',
40      title: `Replay step ${wait.step}/${script.steps.length} ${step?.args.title ?? step?.tool ?? ''}: ${failed ? 'failed' : 'ok'} (waited ${wait.waitedMs} ms)${failed ? `: ${outcome.error}` : ''}`,
41    }
42  })
43}
44
hooks/preapproved-write-guard.mjs 255 lines
1const directorySuffix = '/library/application support/sleight';
2// grant-seal.key seals the Electron Always records in electron-grants.json; writing it would forge consent. hand.json is the
3// user's ghost hand opt-out. permissions.json holds the apps and sites the user told sleight never to act in. turbo-owner.json
4// names the copy that issued turbo.json's receipt, which decides whether a startup may move it.
5const suffixes = ['preapproved.json', 'turbo.json', 'turbo-apps.json', 'turbo-owner.json', 'electron-grants.json', 'grant-seal.key', 'hand.json', 'permissions.json'].map(filename => `${directorySuffix}/${filename}`);
6const mutations = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit']);
7const folded = path => path.normalize('NFC').toLowerCase();
8const protectedLiteral = path => {
9  const value = folded(normalize(path));
10  return suffixes.some(suffix => value.endsWith(suffix)) || value.endsWith(directorySuffix);
11};
12const normalize = path => {
13  const parts = [];
14  for (const part of path.split('/')) {
15    if (part === '..' && parts.length && parts.at(-1) !== '..') parts.pop();
16    else if (part && part !== '.') parts.push(part);
17  }
18  return (path.startsWith('/') ? '/' : '') + parts.join('/');
19};
20
21// True when the path is sleight's folder or a folder above it, so deleting, moving or changing it reaches the protected files.
22// Without the home folder, only ~ spellings can be judged.
23const above = (path, home) => {
24  const root = home ?? '/~', value = folded(normalize(path.replace(/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)/, () => root)));
25  const folder = folded(normalize(`${root}/Library/Application Support/sleight`));
26  return value.startsWith('/') && (value === folder || folder.startsWith(value === '/' ? '/' : value + '/'));
27};
28
29// Resolve before normalizing: a symlink followed by .. walks from its target.
30async function protectedPath(path, { stat, home }, ancestor = false) {
31  if (typeof path !== 'string' || !path || path.length > 4096) return false;
32  if (protectedLiteral(path) || ancestor && above(path, home)) return true;
33  if (home) path = path.replace(/^(?:~|\$HOME|\$\{HOME\})(?=\/|$)/, () => home);
34  let resolved = (await stat(path.startsWith('/') ? '/' : '.').catch(() => undefined))?.realPath;
35  if (!resolved) return false;
36  for (const part of path.split('/').filter(Boolean)) {
37    const next = `${resolved.replace(/\/$/, '')}/${part}`;
38    const info = await stat(next).catch(() => undefined);
39    resolved = info?.realPath ?? normalize(next);
40  }
41  return protectedLiteral(resolved) || ancestor && above(resolved, home);
42}
43
44// Only literal shell names and operators, never eval or shell expansion. Keep
45// operators inside quotes as text, and join quoted/escaped pieces of a word.
46function shellWords(command) {
47  const words = [];
48  let word = '', quote = '', active = false;
49  const flush = () => { if (active) words.push({ text: word }); word = ''; active = false; };
50  for (let i = 0; i < command.length; i++) {
51    const c = command[i];
52    if (c === '\\' && quote !== "'") {
53      const escaped = command[++i] ?? '';
54      if (escaped !== '\n') { active = true; word += escaped; }
55    }
56    else if (quote) { if (c === quote) quote = ''; else word += c; }
57    else if (c === "'" || c === '"') { quote = c; active = true; }
58    else if (c === '\n') { flush(); words.push({ text: ';', operator: true }); }
59    else if (/\s/.test(c)) flush();
60    else if (';&|<>()'.includes(c)) {
61      flush();
62      const pair = c + (command[i + 1] ?? '');
63      const operator = ['>>', '>|', '>&', '<<', '&&', '||', '|&'].includes(pair) ? (i++, pair) : c;
64      words.push({ text: operator, operator: true });
65    }
66    else { word += c; active = true; }
67  }
68  flush();
69  return words;
70}
71
72// Commands a find -exec runs that change or remove what it finds.
73const FIND_WRITERS = new Set(['rm', 'mv', 'cp', 'ln', 'chmod', 'chown', 'chgrp', 'chflags', 'truncate', 'tee', 'unlink', 'sed', 'perl', 'sh', 'bash', 'zsh',
74  'python', 'python3', 'node', 'ruby', 'xargs', 'dd', 'install', 'rsync', 'ditto', 'touch', 'shred', 'srm']);
75// A path with glob or brace characters names whatever its folder holds that matches; the folder decides.
76const globFolder = path => /[*?[{]/.test(path) ? path.slice(0, path.search(/[*?[{]/)).replace(/\/[^/]*$/, '') : undefined;
77const PROTECTED_NAME = /(?:preapproved|turbo|turbo-apps|turbo-owner|electron-grants|hand|permissions)\.json|grant-seal\.key/i;
78const launcher = name => name === 'sleight-mcp' || name === 'launch.mjs';
79const commandArgument = value => value.replace(/^['"]+|[;&|)'"]+$/g, '');
80// True when the words run the launcher's command with arguments `allowed` refuses (by default anything but status), as
81// separate words or inside a -c string, where the arguments run to the next shell operator.
82const statusOnly = rest => rest[0] === 'status';
83function launcherToggle(words, command, allowed = statusOnly) {
84  const names = words.map(word => word.split('/').at(-1)), first = names.findIndex(launcher);
85  if (first >= 0) {
86    const at = names.indexOf(command, first + 1);
87    if (at >= 0 && !allowed(names.slice(at + 1).map(commandArgument))) return true;
88  }
89  return words.some(word => {
90    if (!/\s/.test(word)) return false;
91    const hit = /(?<![\w.-])(?:\S*\/)?(?:sleight-mcp|launch\.mjs)(?=[\s'"]|$)/.exec(word);
92    return !!hit && [...word.slice(hit.index).matchAll(new RegExp(`(?<![\\w-])${command}(?![\\w-])([^;&|)\\n]*)`, 'g'))]
93      .some(match => !allowed(match[1].trim().split(/\s+/).filter(Boolean).map(commandArgument)));
94  });
95}
96// `permissions` alone or `permissions list` only reads; block, unblock, revoke and sites write permissions.json or a grant.
97const listingOnly = rest => rest.length === 0 || rest.length === 1 && rest[0] === 'list';
98
99function shellWritePaths(command, initialDirectory, depth = 0) {
100  if (depth > 8) return [];
101  const paths = [], segments = [{ words: [] }];
102  let directory = initialDirectory;
103  for (const word of shellWords(command)) {
104    const previous = segments.at(-1);
105    if (word.operator && [';', '&', '|', '|&', '&&', '||', '(', ')'].includes(word.text)) {
106      segments.push({ words: [], piped: word.text === '|' ? previous.words : undefined });
107    } else previous.words.push(word);
108  }
109  // ancestor: the command also reaches what is under the path (rm -r, mv, find -delete, chmod -R), so a parent folder counts.
110  const add = (path, literalOnly = false, ancestor = false) => {
111    if (typeof path !== 'string') return;
112    paths.push({ path: directory && !/^(?:\/|~|\$HOME|\$\{HOME\})/.test(path) ? `${directory}/${path}` : path, literalOnly, ancestor });
113  };
114  for (const { words: segment, piped } of segments) {
115    const texts = [];
116    for (let i = 0; i < segment.length; i++) {
117      if (segment[i].operator) {
118        const operator = segment[i].text;
119        const target = segment[++i];
120        if (['>', '>>', '>|', '>&'].includes(operator) && target && !target.operator) add(target.text);
121      } else texts.push(segment[i].text);
122    }
123    const allWords = [...texts];
124    let xargs = false;
125    while (texts.length) {
126      if (/^[A-Za-z_][A-Za-z_0-9]*=/.test(texts[0])) { texts.shift(); continue; }
127      const prefix = texts[0].split('/').at(-1);
128      if (!['env', 'command', 'sudo', 'time', 'nohup', 'xargs'].includes(prefix)) break;
129      xargs ||= prefix === 'xargs'; texts.shift();
130      while (texts[0]?.startsWith('-')) {
131        const flag = texts.shift();
132        if (['-u', '--unset', '-I', '-n', '-P'].includes(flag)) texts.shift();
133      }
134    }
135    const executable = texts.shift()?.split('/').at(-1);
136    const operands = texts.filter(text => text && !text.startsWith('-'));
137    // `sleight-mcp turbo on|off` writes turbo.json for the user, so a model's shell may not run it. Position-free on purpose:
138    // env, nohup, timeout, interpreter flags and sh -c strings all reach it. Only `turbo status` passes. When in doubt, deny.
139    // `hand on|off|capture` writes hand.json the same way, and only `hand status` passes.
140    if (launcherToggle(allWords, 'turbo')) add('~/Library/Application Support/sleight/turbo.json', true);
141    if (launcherToggle(allWords, 'hand')) add('~/Library/Application Support/sleight/hand.json', true);
142    // `permissions block|unblock|revoke|sites` change what sleight may do, and only the listing passes.
143    if (launcherToggle(allWords, 'permissions', listingOnly)) add('~/Library/Application Support/sleight/permissions.json', true);
144    if (xargs && piped) operands.push(...piped.filter(word => !word.operator).map(word => word.text));
145    if (executable === 'cd') {
146      const next = operands[0];
147      if (next) directory = /^(?:\/|~|\$HOME|\$\{HOME\})/.test(next) || !directory ? next : `${directory}/${next}`;
148    } else if (['bash', 'sh', 'zsh'].includes(executable) && texts.includes('-c')) {
149      paths.push(...shellWritePaths(texts[texts.indexOf('-c') + 1] ?? '', directory, depth + 1));
150    } else if (['cp', 'install', 'rsync', 'ln'].includes(executable)) {
151      const target = texts.findIndex(text => text === '-t' || text === '--target-directory');
152      add(target >= 0 ? texts[target + 1] : operands.at(-1));
153      const attached = texts.find(text => text.startsWith('--target-directory='));
154      if (attached) add(attached.slice('--target-directory='.length));
155    } else if (executable === 'rm') operands.forEach(path => add(path, false, true));
156    else if (executable === 'mv') operands.forEach((path, at) => add(path, false, at < operands.length - 1));
157    else if (['chmod', 'chown', 'chgrp', 'chflags'].includes(executable)) operands.forEach(path => add(path, false, texts.some(arg => /^-[^-]*R/.test(arg))));
158    else if (executable === 'find' && texts.some((arg, at) => arg === '-delete' ||
159      ['-exec', '-execdir', '-ok', '-okdir'].includes(arg) && FIND_WRITERS.has(texts[at + 1]?.split('/').at(-1)))) {
160      // find's search roots come before its first expression; a protected name anywhere in the expression denies too.
161      const start = texts.findIndex(arg => !['-H', '-L', '-P'].includes(arg)), end = texts.findIndex((arg, at) => at >= start && /^[-(!]/.test(arg));
162      const roots = texts.slice(start, end < 0 ? texts.length : end);
163      for (const root of roots.length ? roots : ['.']) add(root, false, true);
164      if (texts.some(arg => PROTECTED_NAME.test(arg))) add('~/Library/Application Support/sleight', true);
165    } else if (executable === 'tar' && /^-?[a-zA-Z]*x|^--extract$|^--get$/.test(texts[0] ?? '') || executable === 'tar' && texts.some(arg => /^-[a-zA-Z]*x/.test(arg))) {
166      // An archive unpacked into a folder can write any file under it.
167      const at = texts.findIndex(arg => arg === '-C' || arg === '--directory');
168      if (at >= 0) add(texts[at + 1], false, true);
169      texts.filter(arg => arg.startsWith('--directory=')).forEach(arg => add(arg.slice('--directory='.length), false, true));
170    } else if (executable === 'unzip' && texts.includes('-d')) add(texts[texts.indexOf('-d') + 1], false, true);
171    else if (executable === 'ditto') add(operands.at(-1), false, true);
172    else if (['curl', 'wget'].includes(executable)) {
173      texts.forEach((arg, at) => { if (['-o', '--output', '-O', '--output-document'].includes(arg)) add(texts[at + 1]); });
174      texts.filter(arg => /^--output(?:-document)?=/.test(arg)).forEach(arg => add(arg.slice(arg.indexOf('=') + 1)));
175    } else if (executable === 'git' && ['checkout', 'restore', 'apply'].includes(texts[0])) operands.slice(1).forEach(path => add(path));
176    else if (executable === 'patch') operands.forEach(path => add(path));
177    else if (['tee', 'truncate'].includes(executable) ||
178      (['sed', 'perl'].includes(executable) && texts.some(arg => /^-[^-]*i/.test(arg))) ||
179      (executable === 'defaults' && ['write', 'delete', 'import'].includes(texts[0]))) operands.forEach(path => add(path));
180    else if (executable === 'plutil' && texts.some(arg => ['-replace', '-insert', '-remove', '-convert'].includes(arg))) {
181      add(texts.includes('-o') ? texts[texts.indexOf('-o') + 1] : operands.at(-1));
182    } else if (executable === 'dd') texts.filter(arg => arg.startsWith('of=')).forEach(arg => add(arg.slice(3)));
183    else if (/^python(?:\d+(?:\.\d+)?)?$/.test(executable ?? '') || ['node', 'ruby', 'perl'].includes(executable)) {
184      const flag = texts.findIndex(arg => /^python/.test(executable) ? /^-c/.test(arg) : executable === 'perl' ? /^-\w*[eE]$/.test(arg) : /^-e|^--eval(?:=|$)/.test(arg));
185      if (flag < 0) continue;
186      const option = texts[flag], source = ['-c', '-e', '--eval'].includes(option) || executable === 'perl' ? texts[flag + 1] ?? '' : option.replace(/^(?:-[ce]|--eval=)/, '');
187      // Code that loads sleight's own writers can change permissions.json or the always list without naming either file.
188      if (/\b(?:permissions-command|preapproved)\.mjs\b/i.test(source)) { add('~/Library/Application Support/sleight', true); continue; }
189      const writes = /\bopen\s*\([^)]*,\s*(?:mode\s*=\s*)?['"][wax][+bt]*['"]|\b(?:writeFile(?:Sync)?|appendFile(?:Sync)?|unlink(?:Sync)?|rename(?:Sync)?|copyFile(?:Sync)?|rm(?:Sync)?|remove|truncate|File\.write)\s*\(|\b(?:unlink|rename|chmod|chown|rmtree|move|symlink)\b/;
190      if (!writes.test(source)) continue;
191      // Inline code is scanned as text only, never passed to the filesystem resolver.
192      for (const match of source.matchAll(/(?:~|\$\{?HOME\}?|\/|\.{1,2}\/)[^'"`;\n()<>|]*?(?:(?:preapproved|turbo|turbo-apps|turbo-owner|electron-grants|hand|permissions)\.json|grant-seal\.key|\/sleight(?=['"`;,)\s]|$))|\b(?:(?:preapproved|turbo|turbo-apps|turbo-owner|electron-grants|hand|permissions)\.json|grant-seal\.key)\b/gi)) add(match[0], true);
193    }
194  }
195  return paths;
196}
197
198export async function preapprovedWriteDenied(input, options) {
199  const { tool } = input;
200  let paths;
201  if (mutations.has(tool)) {
202    paths = [input.file_path, input.notebook_path, ...(Array.isArray(input.edits) ? input.edits.map(edit => edit?.file_path) : [])];
203  } else if (tool === 'Bash' && typeof input.command === 'string') {
204    paths = shellWritePaths(input.command);
205  } else return false;
206  for (const candidate of paths) {
207    const { path, literalOnly, ancestor } = tool === 'Bash' ? candidate : { path: candidate };
208    if (typeof path !== 'string') continue;
209    if (tool === 'Bash') {
210      if (protectedLiteral(path) || ancestor && above(path, options?.home)) return true;
211      const folder = globFolder(path);
212      if (folder && (protectedLiteral(folder) || ancestor && above(folder, options?.home))) return true;
213      if (literalOnly || /\s/.test(path) || path.length >= 512) continue;
214    }
215    if (await protectedPath(path, options, ancestor)) return true;
216  }
217  return false;
218}
219
220// SLEIGHT_ACTION_LOG and SLEIGHT_OUTCOMES are the user's switches. Claude's file and shell tools may not set them where
221// sleight's MCP server reads its environment: Claude Code settings, MCP configs, the plugin's own manifest and launcher,
222// shell startup files, launchd. This catches mistakes and the plain ways around it, not a determined agent: a script
223// Claude writes and then runs, a symlinked config path, or another MCP server's shell tool all get past it
224// (docs/known-problems.md).
225// The switches' stems, so an edit of part of a name counts; matched after JSON and shell escapes and quotes are folded out.
226const SWITCHES = /OUTCOMES|ACTION_LOG/;
227const unescaped = (text, concatenate = true) => {
228  const decoded = text.replace(/\\u([0-9a-fA-F]{4})|\\x([0-9a-fA-F]{2})/g, (_, u, x) => String.fromCharCode(parseInt(u ?? x, 16)));
229  return (concatenate ? decoded.replace(concatenate === 'js' ? /['"]\s*\+\s*['"]/g : /['"]\s*(?:\+\s*)?['"]/g, '') : decoded).replace(/['"\\]/g, '');
230};
231const switched = text => typeof text === 'string' && SWITCHES.test(unescaped(text));
232// Paths are matched lowercased (folded).
233const CONFIG = /(?:^|\/)(?:\.claude\/[^/]*\.json|\.claude\.json|\.?mcp\.json|managed-settings\.json|settings(?:\.local)?\.json|\.claude-plugin\/plugin\.json|bin\/sleight-mcp|launchagents\/[^/]+\.plist|\.config\/fish\/(?:[^/]+\/)*[^/]+\.fish|\.(?:zshrc|zshenv|zprofile|zlogin|bashrc|bash_profile|profile|envrc)|\.zshrc\.d\/[^/]+)$/;
234const CONFIG_TEXT = /(?:settings(?:\.local)?|\.claude|mcp|managed-settings|plugin)\.json|\.plist\b|\.fish\b|\.(?:zshrc|zshenv|zprofile|zlogin|bashrc|bash_profile|profile|envrc)\b/;
235// Commands that can write a file they name in their own text. awk only with an output redirect, a pipe or system().
236const SETTERS = /\b(?:claude\s+(?:mcp|config)|launchctl\s+setenv|python\d*(?:\.\d+)?|node|ruby|perl|jq|plutil|defaults|osascript)\b|\bg?awk\b[^\n]*(?:>|\||\bsystem\s*\()/;
237export function loggingSwitchWriteDenied(input) {
238  const { tool } = input ?? {};
239  if (mutations.has(tool)) {
240    const edits = Array.isArray(input.edits) ? input.edits : [];
241    const texts = [input.content, input.new_string, input.new_source, ...edits.map(edit => edit?.new_string)];
242    const paths = [input.file_path, input.notebook_path, ...edits.map(edit => edit?.file_path)];
243    return texts.some(switched) && paths.some(path => typeof path === 'string' && CONFIG.test(folded(normalize(path))));
244  }
245  if (tool !== 'Bash' || !switched(input.command)) return false;
246  const { command } = input, candidates = [command, unescaped(command), unescaped(command, false), unescaped(command, 'js')];
247  // Keep the raw spelling and argument spaces too: folding adjacent literals can join separate shell arguments.
248  if (candidates.some(text => /\blaunchctl\s+setenv\b|\bclaude\s+(?:mcp|config)\b/.test(text))) return true;
249  // A write to a config file, or an interpreter or editor tool run with one named: reads such as grep pass.
250  return shellWritePaths(command).some(({ path }) => CONFIG.test(folded(normalize(path)))) ||
251    // Each test on its own spelling: a fold that reaches the path can join the interpreter's name onto the argument before it
252    // (Python's and Ruby's adjacent literals), and the raw spelling keeps the name but not the path.
253    candidates.some(text => CONFIG_TEXT.test(text)) && candidates.some(text => SETTERS.test(text));
254}
255
types/index.d.ts 46 lines
1// What the sleight mod keeps in $.state for its pane.
2
3/** One action Claude took through sleight, newest last. */
4export type LogEntry = {
5  id: string
6  /** The short description Claude gave the call, or the start of its code. */
7  title: string
8  app?: string
9  status: 'running' | 'done' | 'error' | 'refused'
10  /** Local time, HH:MM:SS. */
11  at: string
12}
13
14/** The pane's latest picture of the app, from lib's snapshot script. */
15export type Frame = {
16  app: string
17  /** Terminal cells for a Raster: columns * rows little-endian u32 triplets, base64. Terminal panes only. */
18  columns: number
19  rows: number
20  cells?: string
21  /** The screenshot, small enough to embed in an SVG. Other surfaces only. */
22  image?: { mime: string; base64: string }
23  width: number
24  height: number
25  at: string
26}
27
28export type ViewStatus =
29  | { kind: 'idle' }
30  | { kind: 'snapshotting'; app: string }
31  | { kind: 'error'; message: string }
32
33declare module 'claude-code' {
34  interface PluginState {
35    sleight: {
36      log: LogEntry[]
37      frame: Frame | null
38      view: ViewStatus
39      stopped: boolean
40      replayFile: string
41      replaying: boolean
42      receipt: { path?: string; review?: string; unavailable?: boolean } | null
43    }
44  }
45}
46