SLOPSHOPPER

playpen

The sessions you are working in right now as small cards above the prompt: a status lamp, a short label, what just happened, and one press to answer or jump…

bandguardcommandpromptmodelprocess
v0.9.5MITupdated 2026-10-23KytioisaCat/playpen
A shopper browsing a rack in a slop shop
README

playpen

Who needs attention? Your other Claude Code sessions as small cards above the prompt: a lamp for the state, a short label, what just happened, and one press to answer or jump there.

A pixel-art figure points at a Claude Code window with three session cards above the prompt: one green, one yellow, one red

A mod for Claude Code, built on the plugin hooks the desktop app's Code tab and the terminal share. The name is the playpen: the sessions play on their own, and you look up when one of them calls. MIT, one file, nothing leaves your machine except the few words on each card.

Why

Run four or five sessions at once and the question is always the same: which one is waiting for me? The sidebar says which sessions exist, not which one just asked something. playpen keeps the sessions you are actually working in in view, right where you type, and turns red when one of them needs you. You answer from where you are, or jump there.

What you see

The playpen band above the prompt in the Claude desktop app: six cards in two rows, one red with an open question

| | | | :- | :- | | Lamp | yellow while Claude works, including while agents or shells it started run in the background · green when the turn is done · red when the session needs you (a permission dialog or a question) · grey while the session rests (its process stopped) | | Label | what the session is about, in a few words, with the project (its folder) as a small tag on the right | | Gist | the state of its latest reply, in a few words; red while a question is open | | ✦ | hand the session off to a fresh one with a brief of its work (press twice: the first press arms it) | | ► | answer from here: the open question with its options, or the suggested next prompt with a send button. A permission dialog is the exception: see below | | × | hide the card until you write in that session again, in every session's band |

A small model writes the label and gist in the language of the reply. Each session writes its own card's words, so every band shows the same card the same way, and the label is made once and kept, since you find a card by it: it is made again only when you rename the session.

  • A card exists because you wrote in that session. It appears at your first prompt there and stays for 8 hours of your active time after you last wrote in it, until you press × or archive the session. Active time runs only between your prompts: a pause over half an hour, a night or a weekend does not count, so in the morning the board still shows where you left off, while a session you have not touched through a working day falls off. When the app stops an idle session's process, or you restart the app, the card rests: grey, with its last summary, and wakes up when you open that session again. A red card stays until you have dealt with it.
  • Click the label to jump to that session.
  • A /btw side question opens a session of its own in the app; it gets no card, since it belongs to the session it was asked in.
  • Permission dialogs are answered in their own session. A red card for a permission shows what it asks to run (Bash: git push origin main) and an open session button. Claude Code draws that dialog itself and lets no plugin answer it, since the answer authorises an action; playpen tells you where to go, and you approve or deny there. Questions (AskUserQuestion) are plain answers and can be given from any card.
  • Places belong to projects. The first card from a folder takes the next free place; a later session in the same folder sits with it. Nothing moves when activity changes, and nothing moves under the pointer.
  • Three per row, two rows at most by default: six sessions in two lines above the prompt. With three or fewer it is one line.
  • /board collapses or expands the band.

Install

From any Claude Code session:

/plugin marketplace add KytioisaCat/playpen
/plugin install playpen@kytioisacat
/reload-plugins

The install dialog asks for a few settings; the defaults are fine.

| Setting | Default | What it does | | :- | :- | :- | | Hours on the board | 8 | A card stays this many hours of your active time after you last wrote in its session; pauses over half an hour do not count. A red card stays until handled. | | Maximum cards | 6 | How many cards the band shows at most, three per row. | | Short labels | on | Let a small model write the label and gist. Off, the card shows the title and the latest reply cut short. | | Label model | claude-haiku-5-5 | Model alias or id for the labels. | | Red after, in auto mode | 45 s | How long a call may wait for a permission in auto mode before the card turns red. See Permissions in auto mode. |

To try it without installing, clone the repository and start a session with claude --plugin-dir /path/to/playpen.

Hand-off

When a session's context has grown long, press ✦ twice on its card. The session writes a brief of its work — the goal, what was done, the decisions and why, the state of the files, the open problems, the next steps — and saves it to <project>/.claude/playpen/handoff-<stamp>-<title>.md. The app's new-session page opens with a short opener filled in; the app creates the session when you send that prompt, so one Enter is yours. The new session's own playpen then gives the brief to the model as hidden context of that first prompt, moves the session to the project folder if the app opened it elsewhere (you approve the folder once), and keeps the old session's place in the sidebar: its pin and its custom group. The old card retires; the old session stays as it was.

The model is the one thing it cannot carry. The app starts every new session on the model last picked in its menu, whichever session asked for the hand-off, and nothing a session does from inside changes that choice or what the app shows. So when the two differ, playpen answers the first reply with the previous session's model and tells you, in a toast and a transcript line, to pick that model in the menu if you want to go on with it; otherwise the next messages use the app's choice. When the models are the same, nothing is said. This stays until the app lets a session be started on a model.

Permissions in auto mode

In auto mode the app's classifier decides each permission itself, usually in a second or two, sometimes in ten or more, and only now and then leaves it to you as a dialog. A plugin is told that a call needs a permission and when the call is done, but not whether a dialog is up in between: the app keeps that to itself. So in auto mode playpen turns a card red when a call is waiting for a permission and the session has not moved for a set time, 45 seconds by default (Red after, in auto mode): no call has started or ended. Calls the classifier lets through one by one keep the session moving, so a queue stays yellow. That keeps the classifier's thinking from flashing cards red, at two prices: a real dialog shows red up to that long after it appeared, and a single approved command that runs longer than the wait (a long build, a big copy) looks the same as a dialog and may show red until it ends. In the other modes a permission is always a dialog, and the card turns red within a few seconds.

Requirements and limits

  • Claude Code 2.1.286 or later. The mod API is early access and may change between releases; a release that breaks the band gets a fix here.
  • The desktop app gives the cards their titles and links and makes the jump work. In a plain terminal a card shows "Untitled session" and the jump copies a link.
  • macOS for the jump (open claude://…); elsewhere the link is copied to the clipboard.
  • The hand-off cannot choose the new session's model (above).
  • A permission dialog cannot be answered from another session: playpen shows what it asks and takes you there.
  • In auto mode a real permission dialog shows red only after the set wait (45 s by default), since the app does not tell plugins when its classifier hands a call to you.

How it works

The mod runs in every session. Each session writes one JSON file about itself to ~/.claude/playpen/sessions/: its title and link from the desktop app, its state from the mod's hooks (a tool call the engine put to a dialog, an AskUserQuestion with its options, the end of a turn), and the prompt suggestion. The hidden cards and the places on the board are one shared file, ~/.claude/playpen/board.json, so every band shows the same board. Every session's band reads that folder every few seconds; a file whose heartbeat is older than 45 seconds counts as ended, so a crashed session disappears on its own.

Answering from another session appends the text to that session's inbox, ~/.claude/playpen/inbox/<id>.json. The receiving mod reads its inbox every second, ends the turn that is waiting on the dialog, and submits the text as your own prompt. The hand-off goes the same way, with a marker the new session reads at start.

Development

The plugin loads in place from a clone registered as a local marketplace (claude plugin marketplace add /path/to/playpen), so an edit to hooks/register.tsx takes effect at /reload-plugins or the next session. claude plugin validate . reads the marketplace file; to see what the hooks module hooks and calls, validate a copy without .claude-plugin/marketplace.json.

The engine writes its type declarations into .claude-plugin/types/ the first time it loads the mod from this folder, and tsconfig.json extends them, so an editor or npx tsc -p . type-checks the module against the exact build you run.

Ideas, not planned

Things that would fit the board and may come if someone wants them:

  • A toast, and maybe a sound, when a card turns red or green, as an option off by default.
  • Digit hotkeys to jump to a card's session from the keyboard.
  • Tests under claude plugin test, and a listing in the Claude Directory.

Privacy

Everything stays on your machine except the label and gist, which come from one small model call per changed card on your own Claude plan. The call sees the session title and the start of the latest reply. Treat that like any other text you send to Claude.

License

MIT

Source 1 files
hooks/register.tsx 1746 lines
1import type { Register, EngineInterface, PluginOptions } from 'claude-code'
2
3// playpen: a band above the prompt with one small card per session you
4// are working in right now.
5//
6// The mod runs in every session, and each session writes one JSON file about
7// itself to ~/.claude/playpen/sessions/<id>.json: its title and link from
8// the desktop app, its exact state from the hooks below, the open question
9// with its options, the prompt suggestion, and the engine session id that
10// $.session.send addresses. Every session's band reads that folder.
11//
12// A card exists because you wrote in that session. It appears at your first
13// prompt there, stays while the session lives and you have written in it
14// within the window (red ones stay until handled), and goes when you press ×,
15// when the session ends, or when its heartbeat stops.
16//
17// A place on the board belongs to a project, not a session: the first card of
18// a folder takes the next free place, and a later session in the same folder
19// sits with it. So a hand-off, which starts a fresh session in the same folder
20// with a brief the old one wrote, lands where the old card was.
21
22type State = 'working' | 'done' | 'waiting' | 'ended'
23
24type Question = { text: string; options: string[] }
25
26type Own = {
27  id: string // the app's session id (local_...), the card's identity
28  engineId: string // what $.session.id() answers; the send address
29  title: string
30  link: string
31  cwd: string
32  state: State
33  snippet: string
34  question: Question | null
35  permission: string | null // what a permission dialog asks to do, when one is up
36  suggestion: string | null
37  lastPromptAt: number
38  activeAt?: number // the board's active clock when you last wrote here
39  // the card's label and gist, written by the session itself so every band
40  // shows the same words; miniKey is what they were made from
41  label?: string
42  labelTitle?: string // the session title the label was made for
43  gist?: string
44  miniKey?: string
45  updatedAt: number
46  isRetired?: boolean // handed off to a new session; off the board for good
47}
48
49type Card = Own & { label: string; gist: string }
50
51const POLL_MS = 3_000
52const INBOX_MS = 1_000
53const HEARTBEAT_MS = 10_000
54const STALE_MS = 45_000
55// An ask still open after this is a dialog. In auto mode an ask goes to the
56// app's classifier first, a model call that takes seconds (13 s seen), and a
57// dialog only follows when it cannot decide; a real dialog waits for you, so
58// a long bound there costs nothing but a late red.
59const ASK_MS = 2_500
60let askAutoMs = 45_000 // the person's setting: how long auto mode's classifier gets before red
61let sessionMode: string | null = null // the app's permission mode for this session
62// sized for a desktop card a third of the band wide; a narrower card cuts them
63const LABEL_MAX = 28
64const GIST_MAX = 36
65const LABEL_ASK = 24
66const GIST_ASK = 32
67const SNIPPET_MAX = 400 // of the latest reply, kept for the expanded card
68const PER_ROW = 3
69const MIN_CARD = 24
70const MAX_CARD = 40
71// a message from another playpen: consumed by the receiving mod, and
72// either submitted as the person's own prompt there or, for HANDOFF, acted on
73const RELAY = '[playpen] '
74const HANDOFF = 'handoff'
75
76const HANDOFF_ASK =
77  'Summarize our work and conversation so far so it can be handed to a new session with a fresh context: ' +
78  'the goal, what has been done, the decisions made and why, the current state of the code or files, ' +
79  'open problems, and the next steps. Write it as a brief for someone who has not seen this conversation. ' +
80  'Reply with the brief only.'
81
82let home = ''
83let ownDir = ''
84let me: Own | null = null
85let hasPrompted = false
86let heldTurnId: string | null = null
87let isHandingOff = false
88let handoffTurnId: string | null = null // the turn that writes the brief
89// the previous session's model, for a session the hand-off link opened. The
90// app starts the session on the model last picked, and nothing from in here
91// changes that choice or what the app shows. So the first turn alone, the
92// reply to the brief, is answered by the previous model, and the person is
93// told to pick it in the model menu to go on with it. Until the app lets a
94// session be started on a model, nothing more is tried.
95let wantedModel: string | null = null
96let isBriefGiven = false
97// background work the session's last turn left running (build agents, shells,
98// monitors): the turn ended, the work did not, so the card stays yellow
99let backgroundCount = 0
100let isMachineTurn = false // the latest prompt came from a routine or a task, not you
101// ✦ takes two presses: the first arms it for a few seconds, the second fires
102let armedId: string | null = null
103const ARM_MS = 4_000
104// ► opens the card's answer on its second row: the question's options, or
105// the prompt suggestion with a send button; it closes on its own
106let openId: string | null = null
107const OPEN_MS = 12_000
108let deck: Card[] = []
109let lastDeckJson = ''
110let isCollapsed = false
111let isPolling = false
112let isSummarizing = false
113let hidden: Record<string, number> = {}
114let slots: string[] = [] // folders, in the order their first card appeared
115let order: string[] = [] // session ids, in the order they first appeared
116
117// Tool calls in flight and which of them have a dialog up. Several tools can
118// run at once, so one call ending must not clear another call's wait.
119const inFlight = new Map<string, { tool: string; input: string }>()
120const waitingIds = new Set<string>()
121let isPromptUp = false
122
123// --- options -----------------------------------------------------------------
124
125let maxCards = 6
126let windowMs = 8 * 60 * 60 * 1000 // of active time
127let shouldSummarize = true
128let summaryModel = 'claude-haiku-5-5'
129
130function readOptions(options: PluginOptions) {
131  const num = (v: unknown, fallback: number) => (typeof v === 'number' && v > 0 ? v : fallback)
132  windowMs = num(options.window_hours, 8) * 60 * 60 * 1000
133  maxCards = Math.min(12, num(options.max_cards, 6))
134  shouldSummarize = options.summarize !== false
135  summaryModel = typeof options.model === 'string' && options.model ? options.model : 'claude-haiku-5-5'
136  askAutoMs = Math.min(300, Math.max(3, num(options.auto_red_seconds, 45))) * 1000
137}
138
139// --- small helpers -------------------------------------------------------------
140
141const trim = (s: string, n: number) => {
142  const flat = s.replace(/\s+/g, ' ').trim()
143  return flat.length > n ? flat.slice(0, Math.max(1, n - 1)) + '…' : flat
144}
145
146const lampColor = (state: State) =>
147  state === 'working' ? 'yellow' : state === 'waiting' ? 'red' : state === 'done' ? 'green' : 'gray'
148
149const stateWord = (state: State) =>
150  state === 'working' ? 'working' : state === 'waiting' ? 'needs you' : state === 'done' ? 'done' : 'ended'
151
152const mcpText = (r: { content: { type: string; text?: string }[] }) =>
153  r.content.map(b => (b.type === 'text' ? (b.text ?? '') : '')).join('')
154
155// The AskUserQuestion input, cut down to the first question and its labels.
156function toQuestion(input: unknown): Question | null {
157  const q = (input as { questions?: { question?: string; options?: { label?: string }[] }[] })?.questions?.[0]
158  if (!q?.question) return null
159  const options = (q.options ?? [])
160    .map(o => o.label ?? '')
161    .filter(Boolean)
162    .slice(0, 4)
163  return { text: q.question, options }
164}
165
166async function init($: EngineInterface) {
167  if (home) return
168  home = (await $.env.get('HOME')) ?? '/tmp'
169  ownDir = `${home}/.claude/playpen/sessions`
170  // only a missing board: one read while another band writes it is there
171  if (!(await $.fs.exists(boardPath()))) {
172    // the first band on the shared board brings what its own store kept
173    await writeBoard($, {
174      hidden: ((await $.store.get('hidden')) as Record<string, number> | undefined) ?? {},
175      slots: ((await $.store.get('slots')) as string[] | undefined) ?? [],
176      order: ((await $.store.get('order')) as string[] | undefined) ?? [],
177    })
178  }
179  await syncBoard($)
180}
181
182// --- the board every session shares ----------------------------------------------
183
184// Hidden cards and the places on the board belong to the person, not to one
185// session: every band reads the same file each poll, and a write merges into
186// what is there, so a card closed in one session is closed in all of them.
187// activeMs is the board's clock of your working time: it moves only by the
188// gaps between your prompts, in any session, each counted up to PAUSE_MS, so a
189// night, a weekend or a lunch adds nothing. A card falls off when that clock
190// has run windowMs past the moment you last wrote in its session.
191type Board = { hidden: Record<string, number>; slots: string[]; order: string[]; activeMs: number; lastActiveAt: number }
192const PAUSE_MS = 30 * 60 * 1000
193
194const boardPath = () => `${home}/.claude/playpen/board.json`
195
196async function readBoard($: EngineInterface): Promise<Board | null> {
197  try {
198    if (!(await $.fs.exists(boardPath()))) return null
199    const b = JSON.parse(await $.fs.read(boardPath())) as Partial<Board>
200    return { hidden: b.hidden ?? {}, slots: b.slots ?? [], order: b.order ?? [], activeMs: b.activeMs ?? 0, lastActiveAt: b.lastActiveAt ?? 0 }
201  } catch {
202    return null // half-written: this round keeps what it had
203  }
204}
205
206// The sessions the app still lists (not archived, not deleted), asked now and
207// then: a card whose process stopped rests on the board while its session is
208// in this list, and goes when it is archived. Unknown, every card rests.
209let appIds: Set<string> | null = null
210let appIdsAt = 0
211const APP_IDS_MS = 30_000
212
213async function syncAppIds($: EngineInterface) {
214  const now = await $.clock.now()
215  if (now - appIdsAt < APP_IDS_MS) return
216  appIdsAt = now
217  try {
218    const rows = await listApp($, 100)
219    if (rows.length > 0) appIds = new Set(rows.map(r => r.sessionId ?? ''))
220  } catch {
221    // keep what was known
222  }
223}
224
225const union = (a: string[], b: string[]) => [...a, ...b.filter(x => !a.includes(x))]
226
227async function syncBoard($: EngineInterface) {
228  const b = await readBoard($)
229  if (b) {
230    hidden = b.hidden
231    slots = b.slots
232    order = b.order
233    activeMs = b.activeMs
234    lastActiveAt = b.lastActiveAt
235  }
236}
237
238let activeMs = 0
239let lastActiveAt = 0
240
241// The board as it stands, to build a write on. A board another band is
242// writing right now reads as half a file: read again a moment later, and
243// failing that, build on what this band last read, never on an empty board,
244// which written back would reopen every closed card and reshuffle the places.
245async function baseBoard($: EngineInterface): Promise<Board> {
246  const b = (await readBoard($)) ?? (await $.clock.sleep(50).then(() => readBoard($)))
247  return b ?? { hidden, slots, order, activeMs, lastActiveAt }
248}
249
250// Your prompt moves the active clock by the gap since the last one, up to a pause.
251async function tickActive($: EngineInterface): Promise<number> {
252  const now = await $.clock.now()
253  const b = await baseBoard($)
254  const gap = b.lastActiveAt > 0 ? Math.min(Math.max(0, now - b.lastActiveAt), PAUSE_MS) : 0
255  await writeBoard($, { activeMs: b.activeMs + gap, lastActiveAt: now })
256  return activeMs
257}
258
259async function writeBoard($: EngineInterface, patch: Partial<Board>) {
260  const b = await baseBoard($)
261  const next: Board = {
262    hidden: { ...b.hidden, ...(patch.hidden ?? {}) },
263    slots: union(b.slots, patch.slots ?? []).slice(-128),
264    order: union(b.order, patch.order ?? []).slice(-512),
265    activeMs: Math.max(b.activeMs, patch.activeMs ?? 0),
266    lastActiveAt: Math.max(b.lastActiveAt, patch.lastActiveAt ?? 0),
267  }
268  hidden = next.hidden
269  slots = next.slots
270  order = next.order
271  activeMs = next.activeMs
272  lastActiveAt = next.lastActiveAt
273  try {
274    await $.fs.write(boardPath(), JSON.stringify(next))
275  } catch {
276    // unwritable: this band still keeps it in memory
277  }
278}
279
280// --- this session's own file --------------------------------------------------
281
282// The app knows this session's id, title and link; the engine's own id is the
283// transcript's name and differs after a resume.
284type AppSession = {
285  sessionId?: string
286  title?: string
287  link?: string
288  cwd?: string
289  model?: string
290  isArchived?: boolean
291  pinned?: boolean
292  permissionMode?: string
293  group?: { id: string; name: string } | null
294}
295
296async function selfApp($: EngineInterface): Promise<AppSession | null> {
297  try {
298    const r = await $.mcp.call('ccd_session_mgmt', 'get_session', { session_id: 'self' })
299    if (r.isError) return null
300    return JSON.parse(mcpText(r)) as AppSession
301  } catch {
302    return null
303  }
304}
305
306async function writeMe($: EngineInterface, patch: Partial<Own> = {}) {
307  if (!me || !hasPrompted) return
308  me = { ...me, ...patch, updatedAt: await $.clock.now() }
309  try {
310    await $.fs.write(`${ownDir}/${me.id}.json`, JSON.stringify(me))
311  } catch {
312    // unwritable folder: the band still knows this session from memory
313  }
314}
315
316// What a permission dialog asks to do, in a line: the tool and the part of
317// its input a person decides on.
318function describeCall(tool: string, input: string): string {
319  let args: Record<string, unknown> = {}
320  try {
321    args = JSON.parse(input) as Record<string, unknown>
322  } catch {
323    // the tool's name alone
324  }
325  const pick = ['command', 'file_path', 'path', 'url', 'pattern', 'query'].map(k => args[k]).find(v => typeof v === 'string')
326  const name = tool.startsWith('mcp__') ? tool.split('__').slice(1).join(' ') : tool
327  return trim(pick ? `${name}: ${pick as string}` : name, 160)
328}
329
330function pendingPermission(): string | null {
331  for (const id of waitingIds) {
332    const call = inFlight.get(id)
333    if (call && call.tool !== 'AskUserQuestion') return describeCall(call.tool, call.input)
334  }
335  return isPromptUp ? 'a permission dialog' : null
336}
337
338// Calls that asked for a permission and have not ended, and when the session
339// last moved: a call started or ended. The app does not tell a plugin when a
340// dialog is up, so a session counts as waiting on you when a call is asking
341// and nothing has moved for the set time; a queue of calls the classifier
342// lets through one by one keeps moving, and stays yellow.
343const asking = new Set<string>()
344const timedIds = new Set<string>() // the asks this wait turned red
345let movedAt = 0
346let isCheckSet = false
347
348const askWaitMs = () => (sessionMode === 'auto' ? askAutoMs : ASK_MS)
349
350async function moved($: EngineInterface) {
351  movedAt = await $.clock.now()
352  if (timedIds.size > 0) {
353    for (const id of timedIds) waitingIds.delete(id)
354    timedIds.clear()
355    await settle($)
356  }
357  scheduleCheck($, askWaitMs())
358}
359
360function scheduleCheck($: EngineInterface, ms: number) {
361  if (isCheckSet || asking.size === 0) return
362  isCheckSet = true
363  $.clock.after(ms, () => {
364    isCheckSet = false
365    void checkStill($)
366  })
367}
368
369async function checkStill($: EngineInterface) {
370  const live = [...asking].filter(id => inFlight.has(id))
371  if (live.length === 0) return
372  const still = (await $.clock.now()) - movedAt
373  if (still < askWaitMs()) {
374    scheduleCheck($, askWaitMs() - still)
375    return
376  }
377  for (const id of live) {
378    if (!waitingIds.has(id)) {
379      waitingIds.add(id)
380      timedIds.add(id)
381    }
382  }
383  await settle($)
384}
385
386const settle = ($: EngineInterface) =>
387  writeMe($, {
388    state: waitingIds.size > 0 || isPromptUp ? 'waiting' : 'working',
389    permission: pendingPermission(),
390  })
391
392async function lastReply($: EngineInterface) {
393  const last = [...(await $.session.messages())].reverse().find(m => m.role === 'assistant' && m.text.trim())
394  return last ? last.text.trim() : ''
395}
396
397const mySnippet = async ($: EngineInterface) => trim(await lastReply($), SNIPPET_MAX)
398
399// The app may not have answered at start, and the card then carries a
400// made-up id whose link the app does not know. Until the app names this
401// session, the band cannot tell its own card among the others, and the
402// app's list of sessions, which leaves out the one asking, would drop it.
403let isSelfKnown = false
404let isLearning = false
405const SELF_WAIT_MS = 1_500
406
407// Takes the app's own id once it answers: a card this session had under it
408// is taken back, and a file written under the made-up one retires.
409async function learnSelf($: EngineInterface, given?: AppSession | null) {
410  if (!me || isLearning) return
411  isLearning = true
412  try {
413    const self = given !== undefined ? given : await Promise.race([selfApp($), $.clock.sleep(SELF_WAIT_MS).then(() => null)])
414    if (self?.permissionMode) sessionMode = self.permissionMode
415    if (!me || !self?.sessionId) return
416    isSelfKnown = true
417    if (self.sessionId !== me.id) {
418      const stale = me
419      me = {
420        ...me,
421        id: self.sessionId,
422        link: self.link ?? `claude://claude.ai/epitaxy/${self.sessionId}`,
423        title: self.title ?? me.title,
424      }
425      if (hasPrompted) {
426        // you wrote here before the app answered: the card keeps the words
427        // it had under its real id
428        const was = await readOwn($, me.id)
429        if (was && !was.isRetired) me = { ...me, label: was.label, labelTitle: was.labelTitle, gist: was.gist }
430        try {
431          await $.fs.write(`${ownDir}/${stale.id}.json`, JSON.stringify({ ...stale, isRetired: true }))
432        } catch {
433          // its heartbeat stops, so it ends on its own
434        }
435        await writeMe($)
436      } else {
437        await resumeCard($)
438      }
439    } else if (self.link && self.link !== me.link) {
440      me = { ...me, link: self.link }
441    }
442    void refresh($)
443  } finally {
444    isLearning = false
445  }
446}
447
448// Asks the app each second for a while after start, so the card has its
449// real id before you look down at the band, not at the next heartbeat.
450function learnSelfSoon($: EngineInterface, tries = 15) {
451  $.clock.after(1_000, () => {
452    void (async () => {
453      if (isSelfKnown || !me) return
454      await learnSelf($)
455      if (!isSelfKnown && tries > 1) learnSelfSoon($, tries - 1)
456    })()
457  })
458}
459
460// The heartbeat: proves the session is alive, and picks up a title the app
461// gave the session after its first prompt.
462async function heartbeat($: EngineInterface) {
463  if (!me) return
464  if (!hasPrompted && isSelfKnown) return
465  const self = await selfApp($)
466  await learnSelf($, self)
467  if (!hasPrompted) return
468  await writeMe($, self?.title ? { title: self.title } : {})
469}
470
471// Whether a card has fallen off: active time past the window. A file from
472// before the active clock existed counts by the wall clock, a day and a half.
473const isStale = (o: Own, now: number) =>
474  o.activeAt !== undefined ? activeMs - o.activeAt > windowMs : now - o.lastPromptAt > 36 * 60 * 60 * 1000
475
476// A session whose card is still on the board takes it back when it starts:
477// the app stops idle sessions' processes and starts them again when opened,
478// and that is the same session you were working in, not a look at an old one.
479async function resumeCard($: EngineInterface) {
480  if (!me || hasPrompted) return
481  const was = await readOwn($, me.id)
482  if (!was) return // none, or unreadable: the card comes back at your next prompt
483  const now = await $.clock.now()
484  const hiddenAt = hidden[me.id]
485  if (was.isRetired || (was.state !== 'waiting' && isStale(was, now))) return
486  if (hiddenAt !== undefined && was.lastPromptAt <= hiddenAt) return
487  hasPrompted = true
488  // the same card as before the restart: its words, so the label stays the
489  // one you know it by, and its place on the active clock
490  await writeMe($, {
491    lastPromptAt: was.lastPromptAt,
492    activeAt: was.activeAt,
493    label: was.label,
494    labelTitle: was.labelTitle,
495    gist: was.gist,
496    miniKey: was.miniKey,
497    state: 'done',
498  })
499  void refresh($)
500}
501
502async function readOwn($: EngineInterface, id: string): Promise<Own | null> {
503  try {
504    const path = `${ownDir}/${id}.json`
505    if (!(await $.fs.exists(path))) return null
506    return JSON.parse(await $.fs.read(path)) as Own
507  } catch {
508    return null
509  }
510}
511
512// --- every session's file -----------------------------------------------------
513
514// Each file as last read whole. A file its session is writing right now reads
515// as half a file; the card keeps its last copy rather than leaving the band
516// for a round and moving every card after it.
517const lastGood = new Map<string, Own>()
518
519async function readAll($: EngineInterface): Promise<Own[]> {
520  const all = new Map<string, Own>()
521  let entries: { name: string; kind: string }[] = []
522  try {
523    entries = await $.fs.list(ownDir)
524  } catch {
525    return me && hasPrompted ? [me] : []
526  }
527  const now = await $.clock.now()
528  for (const entry of entries) {
529    if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
530    let read: Own | undefined
531    try {
532      read = JSON.parse(await $.fs.read(`${ownDir}/${entry.name}`)) as Own
533      lastGood.set(entry.name, read)
534    } catch {
535      read = lastGood.get(entry.name)
536    }
537    if (!read) continue
538    const o = { ...read }
539    // a process that died mid-turn never wrote 'ended'; the heartbeat tells
540    if (o.state !== 'ended' && now - o.updatedAt > STALE_MS) o.state = 'ended'
541    all.set(o.id, o)
542  }
543  if (me && hasPrompted) all.set(me.id, me)
544  return [...all.values()]
545}
546
547// --- short labels from a small model ----------------------------------------
548
549// the label and gist are made for this title, reply and open question; a
550// change in any of them is a new pair to summarize
551const miniKey = (card: Pick<Own, 'title' | 'snippet' | 'question' | 'permission'>) =>
552  `${card.title}\u0000${card.snippet}\u0000${card.question?.text ?? ''}\u0000${card.permission ?? ''}`
553
554// A session writes its own card's label and gist into its own file, once per
555// change, and every band reads them from there. The label is made once and
556// kept, since you find a card by it; it is made again only when the session's
557// title changes (you renamed it). The gist follows every turn.
558async function summarizeMe($: EngineInterface) {
559  if (!shouldSummarize || isSummarizing || !me || !hasPrompted || (me.state === 'working' && backgroundCount === 0)) return
560  const key = miniKey(me)
561  if (me.miniKey === key) return
562  isSummarizing = true
563  try {
564    const folder = me.cwd.split('/').pop() ?? ''
565    const r = await $.model.complete({
566      model: summaryModel,
567      effort: 'low',
568      maxTokens: 80,
569      timeoutMs: 10_000,
570      system:
571        'You write labels for small cards that show what is going on in several coding sessions at once. ' +
572        'Reply with exactly one JSON line: {"label": "...", "gist": "..."}. ' +
573        `"label" (max ${LABEL_ASK} characters): the topic of the session, so the reader knows which chat it is. Prefer the concrete subject (feature, bug, component, document) over generic words. ` +
574        `"gist" (max ${GIST_ASK} characters): the current status from the latest reply. Lead with what matters: done, needs a decision or input, error, blocked, in progress, or a question asked. Telegram style, no trailing period. ` +
575        'Write in the language of the latest reply; if there is none, the language of the title. Keep proper nouns and technical terms as they are. No other text.',
576      prompt:
577        `Project folder: ${folder}\nSession title: ${me.title}\n` +
578        `Latest reply from Claude: ${me.snippet || '(nothing yet)'}` +
579        (me.question ? `\nOpen question to the person right now (the gist should say what is asked): ${me.question.text}` : '') +
580        (me.permission ? `\nA permission dialog is waiting for the person right now (the gist should say what it asks to do): ${me.permission}` : ''),
581    })
582    if (r.isAnswered && me) {
583      const match = r.text.match(/\{[\s\S]*\}/)
584      const parsed = match ? (JSON.parse(match[0]) as { label?: string; gist?: string }) : {}
585      const isLocked = !!me.label && me.labelTitle === me.title
586      await writeMe($, {
587        miniKey: key,
588        labelTitle: me.title,
589        label: isLocked ? me.label : trim(parsed.label || me.title, LABEL_MAX),
590        gist: trim(parsed.gist || me.snippet, GIST_MAX),
591      })
592      void refresh($)
593    }
594  } catch {
595    // a model that refuses or answers oddly: the card keeps its plain text
596  } finally {
597    isSummarizing = false
598  }
599}
600
601// A /btw side question opens a session of its own, titled "btw: ...", under
602// the one it was asked in. It belongs to that session, so it gets no card.
603const isAside = (o: Pick<Own, 'title'>) => /^btw\b/i.test(o.title.trim())
604
605// --- the deck -------------------------------------------------------------------
606
607async function buildDeck($: EngineInterface): Promise<Card[]> {
608  const now = await $.clock.now()
609  await syncBoard($)
610  await syncAppIds($)
611  const cards: Card[] = []
612  for (const o of await readAll($)) {
613    if (o.isRetired || isAside(o)) continue
614    // a stopped process is not a closed session: its card rests until the
615    // session is archived, you press ×, or newer sessions take its place.
616    // The app's list leaves out the session asking, so a band that does not
617    // yet know its own id cannot tell its own resting card from an archived
618    // one, and keeps them all
619    if (o.state === 'ended' && appIds && isSelfKnown && !appIds.has(o.id) && o.id !== me?.id) continue
620    const hiddenAt = hidden[o.id]
621    if (hiddenAt !== undefined && o.lastPromptAt <= hiddenAt) continue
622    // a red card stays until handled; the others fall off after the window of active time
623    if (o.state !== 'waiting' && isStale(o, now)) continue
624    cards.push({
625      ...o,
626      label: o.label || trim(o.title, LABEL_MAX),
627      gist: o.gist || trim(o.snippet, GIST_MAX),
628    })
629  }
630
631  // a full board makes room from its resting cards, the longest unwritten first
632  const resting = cards.filter(c => c.state === 'ended').sort((a, b) => a.lastPromptAt - b.lastPromptAt || (a.id < b.id ? -1 : 1))
633  const drop = new Set(resting.slice(0, Math.max(0, cards.length - maxCards)).map(c => c.id))
634  // a folder keeps its place; within it, sessions keep the order they came in.
635  // One that has no place yet goes after those that do, by when you wrote in
636  // it, so every band sorts the same cards the same way.
637  const rank = (list: string[], key: string) => {
638    const i = list.indexOf(key)
639    return i < 0 ? Number.MAX_SAFE_INTEGER : i
640  }
641  const shown = cards
642    .filter(c => !drop.has(c.id))
643    .sort(
644      (a, b) =>
645        rank(slots, a.cwd) - rank(slots, b.cwd) ||
646        rank(order, a.id) - rank(order, b.id) ||
647        a.lastPromptAt - b.lastPromptAt ||
648        (a.id < b.id ? -1 : 1),
649    )
650    .slice(0, maxCards)
651  // only cards on the board get a place, so the list never pushes them out
652  const newSlots = shown.map(c => c.cwd).filter((cwd, i, all) => !slots.includes(cwd) && all.indexOf(cwd) === i)
653  const fresh = shown.map(c => c.id).filter(id => !order.includes(id))
654  if (newSlots.length > 0 || fresh.length > 0) await writeBoard($, { slots: newSlots, order: fresh })
655  return shown
656}
657
658async function refresh($: EngineInterface) {
659  if (isPolling) return
660  isPolling = true
661  try {
662    deck = await buildDeck($)
663    const json = JSON.stringify(deck)
664    if (json !== lastDeckJson) {
665      lastDeckJson = json
666      $.ui.invalidate('ui.render')
667    }
668    void summarizeMe($)
669  } finally {
670    isPolling = false
671  }
672}
673
674// --- actions on another session --------------------------------------------
675
676async function jump($: EngineInterface, card: Card) {
677  try {
678    const r = await $.process.run(['open', card.link])
679    if (r.exitCode !== 0) throw new Error(r.stderr)
680  } catch {
681    await $.ui.copy({ text: card.link })
682    $.ui.toast('Could not open the session; its link is on the clipboard')
683  }
684}
685
686// × hides the card until you write in that session again
687async function hide($: EngineInterface, card: Card) {
688  await writeBoard($, { hidden: { [card.id]: card.lastPromptAt } })
689  await refresh($)
690}
691
692// Leaves text in the inbox of a session that runs this mod. Its own poll
693// picks it up within a second and acts on it: a hand-off, or an answer it
694// submits as the person's own prompt. A file, not $.session.send, because a
695// send from a mod has no model request behind it for auto mode's permission
696// classifier to judge, and it is refused.
697const inboxPath = (id: string) => `${home}/.claude/playpen/inbox/${id}.json`
698
699async function readInbox($: EngineInterface, id: string): Promise<string[]> {
700  try {
701    if (!(await $.fs.exists(inboxPath(id)))) return []
702    const parsed = JSON.parse(await $.fs.read(inboxPath(id))) as unknown
703    return Array.isArray(parsed) ? parsed.filter((t): t is string => typeof t === 'string') : []
704  } catch {
705    return []
706  }
707}
708
709async function relay($: EngineInterface, card: Card, text: string) {
710  try {
711    const waiting = await readInbox($, card.id)
712    await $.fs.write(inboxPath(card.id), JSON.stringify([...waiting, text]))
713    $.ui.toast(`Sent to ${card.label}: ${trim(text, 40)}`)
714  } catch (error) {
715    $.ui.toast(`Not delivered: ${trim(String(error), 60)}`)
716  }
717}
718
719// This session's side: whatever another playpen left for it.
720let isReadingInbox = false
721async function pollInbox($: EngineInterface) {
722  if (!me || isReadingInbox) return
723  isReadingInbox = true
724  try {
725    const texts = await readInbox($, me.id)
726    if (texts.length === 0) return
727    await $.fs.write(inboxPath(me.id), '[]')
728    for (const text of texts) {
729      if (text === HANDOFF) {
730        void startHandoff($)
731      } else {
732        await applyAnswer($, text)
733        $.ui.toast(`Playpen: ${trim(text, 40)}`)
734      }
735    }
736  } finally {
737    isReadingInbox = false
738  }
739}
740
741// What a relay does on arrival, also run directly for this session's own card:
742// end a turn that is waiting on a dialog, then submit the text as the person's
743// own prompt, so it answers the question instead of queueing behind it.
744async function applyAnswer($: EngineInterface, text: string) {
745  if (heldTurnId && (me?.question || me?.state === 'waiting')) {
746    try {
747      await $.turn.abort({ turnId: heldTurnId })
748    } catch {
749      // the turn had already ended; the prompt below runs when idle
750    }
751  }
752  void $.prompt.submit({ text, asUser: true })
753}
754
755// Sends an answer to a card's session: through the relay for another
756// session, directly for this one.
757async function answer($: EngineInterface, card: Card, isMe: boolean, text: string) {
758  openId = null
759  $.ui.invalidate('ui.render')
760  if (isMe) {
761    await applyAnswer($, text)
762    $.ui.toast(`Playpen: ${trim(text, 40)}`)
763  } else {
764    await relay($, card, text)
765  }
766}
767
768// ►: opens the answer row when the card has something to answer with.
769function pressAnswer($: EngineInterface, card: Card) {
770  if (card.state === 'ended') {
771    $.ui.toast('That session is resting; open it, and its card wakes up')
772    return
773  }
774  if (card.state === 'waiting' && card.permission) {
775    $.ui.toast(`Asks to run ${card.permission}. A permission is answered in its own session; open it to approve or deny.`)
776    return
777  }
778  const hasOptions = card.question !== null && card.question.options.length > 0
779  if (!hasOptions && !card.suggestion) {
780    $.ui.toast(card.question ? 'That question has no options; open the session' : 'Nothing to answer there yet')
781    return
782  }
783  openId = openId === card.id ? null : card.id
784  $.ui.invalidate('ui.render')
785  if (openId === card.id) {
786    $.clock.after(OPEN_MS, () => {
787      if (openId === card.id) {
788        openId = null
789        $.ui.invalidate('ui.render')
790      }
791    })
792  }
793}
794
795// When the engine's own suggestion service says nothing within a moment of
796// the turn ending, and the reply ends on a question or an offer, write the
797// reply the person would most likely send to accept it, so ► has something.
798async function suggestFallback($: EngineInterface, reply: string) {
799  if (!shouldSummarize || !me || !hasPrompted) return
800  const tail = reply.slice(-400)
801  if (!/\?/.test(tail)) return
802  const turnEndedAt = me.updatedAt
803  $.clock.after(2_500, () => {
804    void (async () => {
805      if (!me || me.suggestion || me.state !== 'done' || me.lastPromptAt > turnEndedAt) return
806      try {
807        const r = await $.model.complete({
808          model: summaryModel,
809          effort: 'low',
810          maxTokens: 60,
811          timeoutMs: 10_000,
812          system:
813            'An assistant just ended its reply with a question or an offer. Write the one short message the person ' +
814            'would most likely send back to accept it and let the work continue. Same language as the reply. ' +
815            'One line, no quotes, no explanation.',
816          prompt: tail,
817        })
818        if (r.isAnswered && r.text.trim() && me.state === 'done' && !me.suggestion) {
819          await writeMe($, { suggestion: trim(r.text, 200) })
820        }
821      } catch {
822        // no suggestion then; ► says so
823      }
824    })()
825  })
826}
827
828// --- hand-off: this session writes a brief, a fresh one starts from it -------
829
830// Step one, in the session being handed off: ask for the brief. The turn
831// that answers it finishes the job in finishHandoff.
832async function startHandoff($: EngineInterface) {
833  if (isHandingOff) return
834  isHandingOff = true
835  handoffTurnId = null
836  $.ui.log('hand-off: asking for the brief')
837  $.ui.toast('Hand-off: writing the brief…')
838  if (heldTurnId) {
839    try {
840      // ending the running turn raises its turn.complete; the brief's own
841      // turn is the next one to start, and only that one finishes the hand-off
842      await $.turn.abort({ turnId: heldTurnId })
843    } catch {
844      // the turn had already ended; the prompt below runs when idle
845    }
846  }
847  void $.prompt.submit({ text: HANDOFF_ASK, asUser: true })
848}
849
850// A hand-off started through the app's link leaves this marker; the new
851// session in that folder picks it up at start and takes the previous
852// session's model. The opener itself arrives through the link, sent by the
853// person's Enter: the app creates the session only then, so the mod cannot
854// send it first, and must not send it again.
855const pendingPath = () => `${home}/.claude/playpen/handoff/pending.json`
856// A session with no folder runs in a scratch workspace the app makes, and
857// the app may make a fresh one for the session the link opens; two scratch
858// workspaces count as the same place.
859const isScratch = (p: string) => p.includes('/scratch-workspaces/')
860const sameWorkspace = (a: string, b: string) => a === b || (isScratch(a) && isScratch(b))
861const PENDING_MS = 10 * 60 * 1000
862
863type Pending = {
864  cwd?: string
865  model?: string
866  briefPath?: string
867  title?: string
868  at?: number
869  pinned?: boolean
870  group?: { id: string; name: string } | null
871}
872
873// The marker is consumed once, by whichever of the start hooks reads it first.
874let pendingRead: Promise<Pending | null> | null = null
875
876function readPending($: EngineInterface): Promise<Pending | null> {
877  pendingRead ??= (async () => {
878    try {
879      await init($)
880      if (!(await $.fs.exists(pendingPath()))) return null
881      const pending = JSON.parse(await $.fs.read(pendingPath())) as Pending
882      const now = await $.clock.now()
883      if (!pending.at || now - pending.at > PENDING_MS) return null
884      await $.fs.write(pendingPath(), '{}')
885      return pending
886    } catch {
887      return null
888    }
889  })()
890  return pendingRead
891}
892
893// The brief, for the first turn's context: the new session reads it here,
894// whatever folder the app put it in, so no file read is asked of the model.
895let briefRead: Promise<string | null> | null = null
896
897function briefContext($: EngineInterface): Promise<string | null> {
898  briefRead ??= (async () => {
899    const pending = await readPending($)
900    if (!pending?.briefPath) return null
901    try {
902      const text = await $.fs.read(pending.briefPath)
903      return `The playpen mod handed this session off from the session "${pending.title ?? ''}". Its brief, also saved at ${pending.briefPath}:\n\n${text}`
904    } catch (error) {
905      $.ui.log(`hand-off: the brief at ${pending.briefPath} could not be read: ${trim(String(error), 160)}`)
906      return null
907    }
908  })()
909  return briefRead
910}
911
912async function takePendingHandoff($: EngineInterface, cwd: string) {
913  try {
914    const pending = await readPending($)
915    if (!pending) return
916    // the previous session's model, where the app started this one on another;
917    // first, before anything that waits, so the first request already goes there
918    const appModel = await $.session.model()
919    if (pending.model && pending.model !== appModel) {
920      wantedModel = pending.model
921      $.ui.log(
922        `hand-off: the previous session ran on ${pending.model}; the app started this one on the model last picked, ${appModel}. ` +
923        `This first reply is answered by ${pending.model}. To go on with ${pending.model}, pick it in the model menu; otherwise the next messages use ${appModel}.`,
924      )
925      $.ui.toast(
926        `MODEL: pick ${pending.model} in the model menu to go on as before. The previous session ran on it; this one started on ${appModel}. Only this first reply is answered by ${pending.model}.`,
927        { timeoutMs: 15_000 },
928      )
929    }
930    // the project folder, where the app opened the session elsewhere: the
931    // app's own move, which the person approves
932    if (pending.cwd && !isScratch(pending.cwd) && pending.cwd !== cwd) {
933      try {
934        const r = await $.mcp.call('ccd_directory', 'change_directory', { path: pending.cwd })
935        $.ui.log(`hand-off: folder ${r.isError ? 'not moved' : 'moved'} to ${pending.cwd} (${trim(mcpText(r), 160)})`)
936      } catch (error) {
937        $.ui.log(`hand-off: folder not moved to ${pending.cwd}: ${trim(String(error), 160)}`)
938      }
939    }
940    // the previous session's place in the sidebar: its group, then its pin
941    // (a move into a group takes a pin off). On "self", the app asks no one.
942    const placed: string[] = []
943    try {
944      if (pending.group?.id) {
945        const r = await $.mcp.call('ccd_sidebar', 'move_sessions', { session_ids: ['self'], group_id: pending.group.id })
946        if (!r.isError) placed.push(`filed under ${pending.group.name}`)
947        else $.ui.log(`hand-off: not filed under ${pending.group.name} (${trim(mcpText(r), 120)})`)
948      }
949      if (pending.pinned) {
950        const r = await $.mcp.call('ccd_sidebar', 'set_pinned', { session_id: 'self', pinned: true })
951        if (!r.isError) placed.push('pinned')
952        else $.ui.log(`hand-off: not pinned (${trim(mcpText(r), 120)})`)
953      }
954    } catch (error) {
955      $.ui.log(`hand-off: sidebar place not taken: ${trim(String(error), 120)}`)
956    }
957    if (placed.length) $.ui.log(`hand-off: this session is ${placed.join(' and ')}, as the previous one was`)
958    $.ui.log('hand-off: this session continues the one that wrote the brief')
959  } catch {
960    // an unreadable marker: the model stays the app's choice
961  }
962}
963
964// The app starts a session from the link in the folder and on the model of
965// its own last choices, whatever the link names. The new session's own
966// playpen sets the model and folder from the marker; from here, the
967// first session the app lists after the link opened is named once in the
968// log, with where it opened. (Setting its model from here through the app
969// asks the person each time; the marker needs no one.)
970const WATCH_MS = 5 * 60 * 1000
971
972async function listApp($: EngineInterface, limit = 20): Promise<AppSession[]> {
973  const r = await $.mcp.call('ccd_session_mgmt', 'list_sessions', { limit })
974  if (r.isError) return []
975  const rows = JSON.parse(mcpText(r))
976  return Array.isArray(rows) ? (rows as AppSession[]) : []
977}
978
979function watchNewSession($: EngineInterface, cwd: string, known: Set<string>, since: number) {
980  let isBusy = false
981  const timer = $.clock.every(POLL_MS, () => void tick())
982  async function tick() {
983    if (isBusy) return
984    isBusy = true
985    try {
986      if ((await $.clock.now()) - since > WATCH_MS) {
987        timer.cancel()
988        $.ui.log(`hand-off: no new session seen within ${WATCH_MS / 60_000} minutes`)
989        return
990      }
991      const fresh = (await listApp($)).find(s => s.sessionId && !s.isArchived && !known.has(s.sessionId))
992      if (!fresh?.sessionId) return
993      timer.cancel()
994      const where = fresh.cwd && !sameWorkspace(fresh.cwd, cwd) ? ` in ${fresh.cwd}, not this folder` : ' in this folder'
995      $.ui.log(`hand-off: the new session ${fresh.sessionId} opened${where}`)
996      // its own pin goes, now that the new session (which pins itself) exists
997      if ((await selfApp($))?.pinned) {
998        const r = await $.mcp.call('ccd_sidebar', 'set_pinned', { session_id: 'self', pinned: false })
999        $.ui.log(r.isError ? `hand-off: could not unpin this session (${trim(mcpText(r), 120)})` : 'hand-off: this session is unpinned; the new one takes the pin')
1000      }
1001    } catch (error) {
1002      timer.cancel()
1003      $.ui.log(`hand-off: could not watch for the new session: ${trim(String(error), 160)}`)
1004    } finally {
1005      isBusy = false
1006    }
1007  }
1008}
1009
1010// Step two: save the brief as a file, start a fresh session in the same
1011// folder that reads it first, and retire this card. The new session's card
1012// takes this folder's place on the board. Each step leaves a line in the
1013// transcript, so a failure can be read afterwards.
1014//
1015// Two ways to start the session. The app's `start_session` tool inherits
1016// model, effort and permission mode, but it is behind a feature flag and not
1017// offered to every session. The app's own deep link,
1018// `claude://code/new?folder=…&q=…`, opens the new-session flow with the
1019// folder chosen and the prompt filled in, and works everywhere the app does.
1020async function finishHandoff($: EngineInterface) {
1021  if (!me) return
1022  const brief = await lastReply($)
1023  if (!brief) {
1024    isHandingOff = false
1025    $.ui.log('hand-off: the turn ended without a brief; nothing started')
1026    $.ui.toast('Hand-off: no brief was written')
1027    return
1028  }
1029  const title = me.title.replace(/ \(continued\)$/, '')
1030  const stamp = new Date(await $.clock.now()).toISOString().replace(/[:.]/g, '-').slice(0, 19)
1031  const slug = title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'session'
1032  // inside the project, under its .claude folder: a file there is read
1033  // without a permission prompt, one outside the working directory is not
1034  const briefPath = `${me.cwd}/.claude/playpen/handoff-${stamp}-${slug}.md`
1035  try {
1036    await $.fs.write(
1037      briefPath,
1038      `# Hand-off brief: ${title}\n\nFrom a Claude Code session in \`${me.cwd}\`, written by that session on ${stamp.slice(0, 10)} so a fresh session can continue its work.\n\n${brief}\n`,
1039    )
1040  } catch (error) {
1041    $.ui.log(`hand-off: could not save the brief: ${trim(String(error), 200)}`)
1042  }
1043  $.ui.log(`hand-off: brief of ${brief.length} characters saved to ${briefPath}`)
1044  // short, because it rides in the link that opens the new session
1045  const opener =
1046    `Continue the work handed off from the session "${title}". ` +
1047    'Its brief is in your context; it is the whole history. Pick up from its next steps.' +
1048    (isScratch(me.cwd) ? '' : ` The work is in ${me.cwd}: if this session is not in that folder, move there first with change_directory.`)
1049
1050  let started = ''
1051  try {
1052    const r = await $.mcp.call('ccd_session', 'start_session', {
1053      initiation: 'user_asked',
1054      context: 'fresh',
1055      title: trim(title, 50) + ' (continued)',
1056      prompt: opener,
1057      background:
1058        `Started by the playpen mod as a hand-off from the session "${title}" in ${me.cwd}, ` +
1059        'whose context was getting long. The brief that session wrote about its own work is at ' +
1060        `${briefPath}; treat it as the whole history.`,
1061      use_worktree: false,
1062    })
1063    const text = mcpText(r)
1064    if (r.isError) throw new Error(text)
1065    const newId = text.match(/local_[0-9a-f-]+/)?.[0]
1066    $.ui.log(`hand-off: start_session answered: ${trim(text, 200)}`)
1067    if (newId) {
1068      // off the parent's thread in the sidebar: it is a continuation, not a side task
1069      try {
1070        await $.mcp.call('ccd_session_mgmt', 'detach_session', { session_id: newId })
1071      } catch {
1072        // stays nested; the board does not care
1073      }
1074      void jumpTo($, newId)
1075    }
1076    started = 'through start_session'
1077  } catch (error) {
1078    $.ui.log(`hand-off: start_session is not available here (${trim(String(error), 120)}); opening the app's new-session link`)
1079    // The link opens the app's new-session page on this folder with the
1080    // opener filled in. The app creates the session only when that prompt is
1081    // sent, so one Enter is the person's; nothing else is. The new session's
1082    // own playpen finds this marker at start and sets this session's
1083    // model there, where the app started it on another.
1084    // the model as the app names it, which its picker and set_session_model take
1085    const self = await selfApp($)
1086    let model = self?.model ?? ''
1087    if (!model) {
1088      try {
1089        model = await $.session.model()
1090      } catch {
1091        // the new session keeps the app's default
1092      }
1093    }
1094    const known = new Set((await listApp($).catch(() => [])).map(s => s.sessionId ?? ''))
1095    known.add(me.id)
1096    const at = await $.clock.now()
1097    try {
1098      await $.fs.write(pendingPath(), JSON.stringify({ cwd: me.cwd, model, briefPath, title, at, pinned: self?.pinned, group: self?.group } satisfies Pending))
1099    } catch {
1100      // the model is then the app's choice
1101    }
1102    // a scratch folder named in the link is taken as "no folder" and a fresh
1103    // one is made, after a trust dialog about the old; so it is left out
1104    const folder = isScratch(me.cwd) ? '' : `folder=${encodeURIComponent(me.cwd)}&`
1105    const url = `claude://code/new?${folder}q=${encodeURIComponent(opener)}`
1106    try {
1107      const r = await $.process.run(['open', url])
1108      if (r.exitCode !== 0) throw new Error(r.stderr || `open exited ${r.exitCode}`)
1109      started = 'through the new-session link'
1110      watchNewSession($, me.cwd, known, at)
1111    } catch (error2) {
1112      $.ui.log(`hand-off: could not open the new-session link: ${trim(String(error2), 200)}`)
1113    }
1114  }
1115
1116  if (started) {
1117    await writeMe($, { isRetired: true })
1118    $.ui.log(`hand-off: new session started ${started}; this card retires`)
1119    $.ui.toast('Handed off: new session opening with the brief; this card retires')
1120  } else {
1121    try {
1122      await $.ui.copy({ text: `Read the hand-off brief at ${briefPath} first, then continue from its next steps.` })
1123    } catch {
1124      // the path is in this transcript, just above
1125    }
1126    $.ui.toast('Hand-off: could not start a session; the brief is saved and its path copied')
1127  }
1128  isHandingOff = false
1129  handoffTurnId = null
1130}
1131
1132// The first press on ✦ arms the card's hand-off and shows it plainly; the
1133// second, within ARM_MS, runs it. A press elsewhere, or time, disarms.
1134function pressHandoff($: EngineInterface, card: Card, isMe: boolean) {
1135  if (armedId !== card.id) {
1136    armedId = card.id
1137    $.ui.invalidate('ui.render')
1138    $.clock.after(ARM_MS, () => {
1139      if (armedId === card.id) {
1140        armedId = null
1141        $.ui.invalidate('ui.render')
1142      }
1143    })
1144    return
1145  }
1146  armedId = null
1147  $.ui.invalidate('ui.render')
1148  void (isMe ? startHandoff($) : relay($, card, HANDOFF))
1149}
1150
1151async function jumpTo($: EngineInterface, appId: string | undefined) {
1152  if (!appId) return
1153  try {
1154    await $.process.run(['open', `claude://claude.ai/epitaxy/${appId}`])
1155  } catch {
1156    // the new session is in the sidebar either way
1157  }
1158}
1159
1160// --- the band -----------------------------------------------------------------
1161
1162export const register: Register = (on, options) => {
1163  readOptions(options)
1164
1165  on('session.start', async ($, e, next) => {
1166    await init($)
1167    const self = await selfApp($)
1168    sessionMode = self?.permissionMode ?? null
1169    const engineId = await $.session.id()
1170    const id = self?.sessionId ?? `local_${engineId}`
1171    const now = await $.clock.now()
1172    // Nothing is written until you prompt here: opening an old session to
1173    // look something up wakes its process, and that alone is not working in it.
1174    hasPrompted = false
1175    me = {
1176      id,
1177      engineId,
1178      title: self?.title ?? 'Untitled session',
1179      link: self?.link ?? `claude://claude.ai/epitaxy/${id}`,
1180      cwd: e.cwd,
1181      state: 'done',
1182      snippet: await mySnippet($),
1183      question: null,
1184      permission: null,
1185      suggestion: null,
1186      lastPromptAt: now,
1187      updatedAt: now,
1188    }
1189
1190    await $.command.register({ name: 'board', description: 'Show or hide the playpen band', immediate: true })
1191
1192    isSelfKnown = !!self?.sessionId
1193    await resumeCard($)
1194    if (!isSelfKnown) learnSelfSoon($)
1195
1196    // a session the hand-off link opened: send its opener without an Enter
1197    void takePendingHandoff($, e.cwd)
1198
1199    $.clock.every(POLL_MS, () => void refresh($))
1200    $.clock.every(INBOX_MS, () => void pollInbox($))