SLOPSHOPPER

pinboard

Pin tables, artifact links and answers from the conversation into a side pane you can reopen any time (/pin, /pins, /unpin).

paneguardcommandtoasttooltimer
v0.3.0MITupdated 2026-10-12Young-in/pinboard
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · pinboard
│ ┃ pins ✕ › fix the failing auth test and add an audit log call │ ┃ Pins 0 f: 다음 필터 │ ┃ 전체 0 이 세션 0 이 프로젝트 0 표 0 아티 ⏺ Read(src/auth.ts) │ ┃ ──────────────────────────────────────────── ⎿ Read 6 lines │ ┃ ──────────── ⏺ Update(src/auth.ts) │ ┃ ⎿ Added 2 lines, removed 1 line │ ┃ 아직 핀이 없어요 ⏺ Bash(bun test) │ ┃ /pin 마지막 답변의 표·링크 ⎿ 3 pass, 1 fail │ ┃ 저장 │ ┃ "이 표 핀해줘" 모델에게 말로 저장 ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ a s d g h 아래 후보에서 바로 저장 │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ ↩ u: 되돌리기 I updated src/auth.ts to rejec › /pin │ ┃ ⎿ pinboard: 📌 저장: ¶ I updated src/auth.ts to reject expired claims │ ┃ ──────────────────────────────────────────── │ ┃ ──────────── │ ┃ ctrl+x tab 으로 패널 조작 · /pin help 도움말 │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · pins
Pins 0 f: 다음 필터 전체 0 이 세션 0 이 프로젝트 0 표 0 아티팩트 0 링크 0 ──────────────────────────────────────────────────────── 아직 핀이 없어요 /pin 마지막 답변의 표·링크 저장 "이 표 핀해줘" 모델에게 말로 저장 a s d g h 아래 후보에서 바로 저장 ↩ u: 되돌리기 I updated src/auth.ts to reject expired… ──────────────────────────────────────────────────────── ctrl+x tab 으로 패널 조작 · /pin help 도움말
README

pinboard

Claude Code mod: 대화 중에 나온 표, 아티팩트 링크, 답변을 핀으로 저장해 두고 옆 패널(Pins)에서 언제든 다시 보는 플러그인입니다. Pin tables, artifact links and answers from a Claude Code conversation into a side pane you can reopen any time.

긴 대화에서 "아까 그 표"를 찾으려고 위로 한참 스크롤하는 일을 없애려고 만들었습니다. 핀은 세션이 끝나도 남습니다.

설치

GitHub 저장소를 마켓플레이스로 등록해 설치합니다. Claude Code 프롬프트에서:

/plugin install pinboard --marketplace Young-in/pinboard

Add marketplace?에 y, 범위는 user를 고르면 됩니다. 개발 중이거나 로컬 폴더에서 바로 쓰려면:

claude --plugin-dir /path/to/pinboard

터미널 플래그를 줄 수 없는 환경(데스크톱 앱 등)에서는 ~/.claude/settings.json의 env에 CLAUDE_CODE_PLUGIN_DIRS=/path/to/pinboard를 넣습니다.

사용법

저장하기

입력동작
/pin마우스로 선택한 텍스트가 있으면 그것을 저장. 없으면 마지막 답변의 표와 아티팩트 링크를 저장. 둘 다 없으면 답변 전체 저장
/pin 제목위와 같되 제목을 지정
/pin all [제목]마지막 답변 전체
/pin tables / /pin links마지막 답변의 표만 / 링크만 (일반 https 링크 포함)
패널의 "이번 세션의 후보"답변이 올 때마다 표와 claude.ai/artifact 링크를 감지해 띄움. 한 번 누르면 저장
모델에게 말로"이 표 저장해줘", "핀해줘" 하면 모델이 pin 도구를 호출

보기·쓰기

패널은 이렇게 생겼습니다. 색은 사용자의 Claude Code 테마를 따릅니다.

Pins 4                                      f: 다음 필터
전체 4  이 세션 2  이 프로젝트 4  표 2  아티팩트 1  링크 1
────────────────────────────────────────────────────────
이 세션
▍ 1: 모델별 벤치마크 점수                         ▤ 5분
  2: 에이전트 결과                       @표 찾기 ▤ 2분

다른 세션 · 10-08 18:10 · youngin
  3: Benchmark Scorecard                          ◈ 4일
  4: Claude Code 플러그인 문서                     ⇗ 4일

╭──────────────────────────────────────────────────────╮
│ ▤ 모델별 벤치마크 점수                                │
│ 표 · youngin · 2026-10-08 17:42                      │
│                                                      │
│  (표가 마크다운으로 다시 그려짐)                       │
│                                                      │
│ c: 복사  p: 프롬프트에 넣기  x: 삭제                  │
╰──────────────────────────────────────────────────────╯

─ 이번 세션의 후보 · 누르면 저장 ────────────────────────
+ a: 실험 결과                                    ▤ 방금
────────────────────────────────────────────────────────
Esc 프롬프트로 · /pin help 도움말
  • /pins: 패널 열기/닫기. fullscreen 터미널(110열 이상)에서는 대화 오른쪽에 도킹되고, 그 외에는 프롬프트 위 인라인 블록으로 열립니다.
  • ctrl+x tab으로 패널에 포커스를 주면 단축키가 동작합니다. 버튼마다 단축키가 c: 복사처럼 붙어 있습니다. 1~9 핀 선택, a/s/d/g/h 후보 저장, c 복사, p 프롬프트에 넣기, x 삭제(한 번 더 눌러 확인), u 되돌리기, f 다음 필터, Esc 프롬프트로. 필터 탭은 마우스로 눌러도 됩니다.
  • 선택한 핀은 종류별 색 테두리 카드 안에 마크다운으로 다시 그려집니다. 링크 핀은 클릭할 수 있는 하이퍼링크입니다.
  • 제목은 한글 폭(2칸)을 계산해 패널 폭에 맞게 말줄임됩니다.
  • /pin show 3: 3번 핀의 내용을 대화에 출력합니다. 모델도 읽으므로 "이걸로 다시 해줘"가 됩니다.

세션과 에이전트

  • 핀은 모든 세션이 함께 씁니다. 다른 세션에서 저장하거나 지운 핀은 3초 안에 이 세션 패널에도 반영되고, 동시에 저장해도 서로 덮어쓰지 않습니다.
  • 전체 보기에서는 핀을 저장한 세션별로 묶어 보여 줍니다. 이 세션이 맨 위이고, 다른 세션은 처음 핀한 시각과 프로젝트로 구분됩니다.
  • 이 세션 탭은 지금 세션에서 저장한 핀만 보여 줍니다. 고른 탭은 다음 세션에서도 유지됩니다.
  • 서브에이전트나 팀원 에이전트의 답변에 나온 표·링크도 후보로 잡힙니다. 이 후보는 작업 목록에서 그 에이전트 화면을 열었을 때만 보입니다.
  • 에이전트 화면을 보는 동안 패널에는 그 에이전트의 핀과 후보만 나옵니다. 이때 /pin은 그 에이전트의 마지막 답변을 저장합니다.
  • 메인 화면에서는 에이전트가 저장한 핀에 @이름 표시가 붙습니다.

지우기·관리

입력동작
/pin rm 3, /unpin 3, /pin rm last패널 번호 또는 가장 최근 핀 삭제
/pin undo마지막 삭제 되돌리기 (/pin clear도 되돌릴 수 있음)
/pin clear전체 삭제 (확인 후)
/pin export~/.claude/pins/pins-<날짜>.md로 내보내기
`/pin auto on\off`세션 시작·새 후보 감지 시 패널 자동 열기 (기본 on). 패널을 직접 닫으면 그 세션에서는 다시 자동으로 열지 않음
/pin help도움말

모델용 도구는 pin, unpin, list 세 개입니다. "핀 목록 보여줘", "둘째 핀 지워줘" 같은 요청을 모델이 처리합니다.

동작 방식

Claude Code 함수 훅 플러그인입니다. hooks/register.tsx 하나가 다음 이벤트를 받습니다.

  • session.start: 커맨드와 도구를 등록하고, 저장소($.store)의 핀을 세션 상태로 불러옵니다. 3초마다 저장소를 다시 읽는 타이머도 겁니다.
  • command.run: /pin, /unpin, /pins.
  • tool.call: mcp__pinboard__pin|unpin|list. 에이전트가 부른 pin은 그 에이전트를 기록합니다.
  • session.append (door response): 메인 대화와 각 에이전트 답변의 텍스트 블록에서 표와 아티팩트 링크를 뽑아 후보로 둡니다.
  • ui.render (Pane): 패널을 그립니다. 상태는 $.state atom에 두어 바뀔 때마다 패널이 다시 그려집니다. 화면에 어떤 대화(메인 또는 에이전트)가 떠 있는지는 그릴 때만 알 수 있어서, 마지막으로 그린 화면을 /pin이 참고합니다.
  • ui.close: 사용자가 패널을 닫으면 그 세션에서는 자동으로 다시 열지 않습니다.

핀은 $.store의 pins 키에 JSON으로 보관됩니다. 저장소가 기준이고, 바꿀 때마다 저장 직전에 다시 읽어 합칩니다. 최대 200개, 본문은 20 KB에서 잘립니다. 같은 내용(공백 차이 무시)은 두 번 저장되지 않습니다. 핀마다 저장한 세션 ID, 작업 폴더, 에이전트 ID와 이름을 기록합니다.

표 추출은 hooks/extract.ts의 순수 함수입니다. 헤더 줄 다음에 |---| 구분 줄이 오는 마크다운 표를 찾고, 바로 위의 짧은 줄이나 헤딩, 콜론으로 끝나는 줄을 제목으로 씁니다.

제약

  • 오른쪽 도킹과 마우스 선택 읽기는 fullscreen 터미널 레이아웃에서만 됩니다. 일반 화면에서는 패널이 프롬프트 위에 인라인으로 열리고, /pin은 마지막 답변 추출로 동작합니다.
  • 패널의 버튼과 단축키는 패널이 키보드를 잡고 있을 때(ctrl+x tab 또는 클릭) 눌립니다.
  • 에이전트 화면에서 /pin이 그 에이전트 답변을 고르려면 패널이 열려 있어야 합니다. 닫혀 있으면 메인 대화 기준으로 동작합니다.
  • 핀 목록은 설치본마다 따로입니다. 마켓플레이스로 설치한 것과 --plugin-dir로 띄운 것은 저장 파일이 달라서 서로의 핀이 보이지 않습니다.
  • 저장소에는 버전 비교 쓰기가 없어서, 두 세션이 같은 순간(수 밀리초 안)에 저장하면 한쪽이 빠질 수 있습니다. 보통 사용에서는 일어나기 어렵습니다.
  • 플러그인 API는 early access입니다. Claude Code 2.1.294에서 작성·검증했고, 이후 빌드에서 바뀔 수 있습니다.

개발

claude plugin validate .   # 매니페스트와 훅 모듈을 엔진 기준으로 검사
claude plugin test .       # hooks/*.test.ts(x) 를 엔진 위에서 실행

Claude Code가 이 폴더를 로드하면 .claude-plugin/types/에 API 타입 선언과 tsconfig.json을 생성합니다(둘 다 .gitignore 대상). 그 뒤 tsc -p .로 타입 검사가 됩니다(TypeScript 5.5 이상, Node 20 이상).

엔진은 $(엔진 인터페이스)를 훅 모듈과 같은 파일에 선언된 함수로만 따라가고 import 경계를 넘기지 못합니다. 그래서 $를 쓰는 코드는 register.tsx 한 파일에 섹션으로 나뉘어 있고, 순수 함수만 extract.ts로 분리돼 있습니다.

.claude-plugin/plugin.json      매니페스트
.claude-plugin/marketplace.json 이 저장소를 마켓플레이스로 쓰기 위한 파일
hooks/hooks.json                훅 모듈 지정
hooks/register.tsx              상태·저장소, 커맨드, 패널, 훅 등록
hooks/extract.ts                표·링크 추출, 제목 생성 (순수 함수)
hooks/format.ts                 터미널 폭(한글 2칸) 계산, 말줄임, 시간 표기 (순수 함수)
hooks/*.test.ts(x)              테스트
types/index.d.ts                세션 상태 계약 (PluginState)

변경 내역은 CHANGELOG.md에 있습니다. 이전 버전으로 돌아가려면 태그를 씁니다(예: git checkout v0.1.0).

라이선스

MIT

Source 4 files
hooks/register.tsx 1026 lines
1// pinboard: pin tables, artifact links and answers from the conversation into a side pane.
2//
3// One module on purpose: the engine follows `$` only into functions declared in the file that
4// registers the hooks, never across an import, so everything that touches `$` lives here, in
5// sections. The markdown extraction is pure and lives in extract.ts.
6//
7// Entry points: /pin, /pins, /unpin; the model's pin/unpin/list tools; every reply scanned for
8// tables and artifact links (candidates); the Pane the person opens.
9import { atom, read, update } from 'claude-code'
10import type { EngineInterface, Register, RenderInputOf, RenderSurface } from 'claude-code'
11
12import type { PinboardCandidate, PinboardFilter, PinboardKind, PinboardPin } from '../types'
13import {
14  bodyKey,
15  classify,
16  cleanTitle,
17  extractAll,
18  extractLinks,
19  extractTables,
20  firstLineTitle,
21  isKind,
22  projectName,
23} from './extract'
24import { fitWidth, KIND_LABEL, localStamp, shortAge, textWidth } from './format'
25
26// ────────────────────────────────────────────────────────────────────────────
27// State, store and shared operations
28// ────────────────────────────────────────────────────────────────────────────
29
30type Dollar = EngineInterface
31/** Which agent an item came from: a subagent's or teammate's id and the name it is shown by. */
32type AgentTag = { agentId?: string; agentLabel?: string }
33type PinInput = { kind: PinboardKind; title: string; body: string; sourceUuid?: string } & AgentTag
34
35const PANE = 'pins'
36const PANE_TITLE = 'Pins'
37const STORE_PINS = 'pins'
38const STORE_BACKUP = 'pins.backup'
39const STORE_AUTO_OPEN = 'autoOpen'
40const MAX_PINS = 200
41const MAX_BODY = 20_000
42const MAX_CANDIDATES = 8
43/** How often a session re-reads the shared store to show what other sessions pinned or removed. */
44const REFRESH_MS = 3_000
45
46const STORE_FILTER = 'filter'
47
48const FILTERS: PinboardFilter[] = ['all', 'session', 'project', 'table', 'artifact', 'link']
49const FILTER_LABEL: Record<PinboardFilter, string> = {
50  all: '전체',
51  session: '이 세션',
52  table: '표',
53  artifact: '아티팩트',
54  link: '링크',
55  project: '이 프로젝트',
56}
57const GLYPH: Record<PinboardKind, string> = { table: '▤', artifact: '◈', link: '⇗', text: '¶' }
58
59const pins = atom({ plugin: 'pinboard', key: 'pins' } as const, [])
60const selectedId = atom({ plugin: 'pinboard', key: 'selectedId' } as const, null)
61const filter = atom({ plugin: 'pinboard', key: 'filter' } as const, 'all')
62const candidates = atom({ plugin: 'pinboard', key: 'candidates' } as const, [])
63const lastRemoved = atom({ plugin: 'pinboard', key: 'lastRemoved' } as const, null)
64const confirmDeleteId = atom({ plugin: 'pinboard', key: 'confirmDeleteId' } as const, null)
65const autoOpenSuppressed = atom({ plugin: 'pinboard', key: 'autoOpenSuppressed' } as const, false)
66
67function newId(seed: number): string {
68  return `${seed.toString(36)}-${Math.random().toString(36).slice(2, 8)}`
69}
70
71/**
72 * The agent whose transcript the person last had in view beside the pane, as the pane's last drawing saw it;
73 * undefined for the main conversation. Commands read it, since only a drawing is told which view is on screen.
74 * A module variable on purpose: a hint about the screen, fine to lose on a reload.
75 */
76let viewedAgentId: string | undefined
77
78/** Where the pane is looked at from: the session's folder and id, and the agent in view if any. */
79type Scope = { cwd: string; sessionId: string; agentId?: string }
80
81async function currentScope($: Dollar, agentId = viewedAgentId): Promise<Scope> {
82  const [cwd, sessionId] = await Promise.all([$.session.cwd(), $.session.id()])
83  return agentId ? { cwd, sessionId, agentId } : { cwd, sessionId }
84}
85
86function isFilter(value: unknown): value is PinboardFilter {
87  return typeof value === 'string' && (FILTERS as string[]).includes(value)
88}
89
90/** The pins of the view: one agent's while its transcript is in view, else every pin. */
91function inView(list: PinboardPin[], scope: Scope): PinboardPin[] {
92  return scope.agentId ? list.filter(p => p.agentId === scope.agentId) : list
93}
94
95function visible(list: PinboardPin[], f: PinboardFilter, scope: Scope): PinboardPin[] {
96  const base = inView(list, scope)
97  if (f === 'all') return base
98  if (f === 'session') return base.filter(p => p.sessionId === scope.sessionId)
99  if (f === 'project') return base.filter(p => p.cwd === scope.cwd)
100  return base.filter(p => p.kind === f)
101}
102
103/** The name an agent is shown by: its SendMessage name, its task description, or its type. */
104async function agentLabelOf($: Dollar, agentId: string): Promise<string> {
105  try {
106    const agent = (await $.agent.list()).find(a => a.id === agentId)
107    const label = agent?.name || agent?.description || agent?.type
108    if (label) return label
109  } catch {
110    // the roster is a nicety; fall back to the id
111  }
112  return `에이전트 ${agentId.slice(0, 6)}`
113}
114
115async function agentTag($: Dollar, agentId: string | undefined): Promise<AgentTag> {
116  return agentId ? { agentId, agentLabel: await agentLabelOf($, agentId) } : {}
117}
118
119type PinGroup = { sessionId: string; isCurrent: boolean; label: string; pins: PinboardPin[] }
120
121/** Pins grouped by the session that saved them: this session first, then the others, most recent first. */
122function groupBySession(list: PinboardPin[], scope: Scope): PinGroup[] {
123  const bySession = new Map<string, PinboardPin[]>()
124  for (const p of [...list].sort((a, b) => b.createdAt - a.createdAt)) {
125    const group = bySession.get(p.sessionId)
126    if (group) group.push(p)
127    else bySession.set(p.sessionId, [p])
128  }
129  const groups = [...bySession].map(([sessionId, group]) => {
130    const isCurrent = sessionId === scope.sessionId
131    const oldest = group[group.length - 1]!
132    const label = isCurrent
133      ? '이 세션'
134      : `다른 세션 · ${localStamp(oldest.createdAt).slice(5)} · ${projectName(oldest.cwd)}`
135    return { sessionId, isCurrent, label, pins: group }
136  })
137  return groups.sort((a, b) => Number(b.isCurrent) - Number(a.isCurrent) || b.pins[0]!.createdAt - a.pins[0]!.createdAt)
138}
139
140/** The pins a filter shows, in the order the pane numbers them. */
141function displayOrder(list: PinboardPin[], f: PinboardFilter, scope: Scope): PinboardPin[] {
142  return groupBySession(visible(list, f, scope), scope).flatMap(g => g.pins)
143}
144
145function describe(p: PinboardPin): string {
146  return `${GLYPH[p.kind]} ${p.title}`
147}
148
149// Every session of one installed copy shares one list in `$.store`. The store is the truth: each change
150// reads it right before writing, and `refreshPins` mirrors it into session state, where the pane reads it.
151
152/** The pins as the store holds them now. */
153async function loadPins($: Dollar): Promise<PinboardPin[]> {
154  const stored = await $.store.get(STORE_PINS)
155  return Array.isArray(stored) ? (stored as PinboardPin[]) : []
156}
157
158function signature(list: readonly PinboardPin[]): string {
159  return list.map(p => p.id).join(',')
160}
161
162/** Mirrors the store into session state when another session changed it, so the pane redraws. */
163async function refreshPins($: Dollar): Promise<PinboardPin[]> {
164  const fresh = await loadPins($)
165  const mirrored = await read($, pins)
166  if (signature(fresh) !== signature(mirrored)) await update($, pins, () => fresh)
167  return fresh
168}
169
170/**
171 * Changes the shared list: reads the store fresh, applies `change`, writes the result back and mirrors it.
172 * Reading right before writing keeps what other sessions saved meanwhile. `change` returning its input
173 * unchanged writes nothing.
174 */
175async function mutatePins($: Dollar, change: (list: PinboardPin[]) => PinboardPin[]): Promise<PinboardPin[]> {
176  const list = await loadPins($)
177  const next = change(list)
178  if (next !== list) await $.store.set(STORE_PINS, next.slice(0, MAX_PINS))
179  await update($, pins, () => next.slice(0, MAX_PINS))
180  return next
181}
182
183/** Adds the items not already pinned (same body, whitespace aside), newest first; returns what was added. */
184async function addPins($: Dollar, items: PinInput[]): Promise<PinboardPin[]> {
185  const [now, sessionId, cwd] = await Promise.all([$.clock.now(), $.session.id(), $.session.cwd()])
186  const added: PinboardPin[] = []
187  await mutatePins($, current => {
188    const known = new Set(current.map(p => bodyKey(p.body)))
189    for (const it of items) {
190      const body = it.body.length > MAX_BODY ? `${it.body.slice(0, MAX_BODY)}\n\n…(잘림)` : it.body
191      const key = bodyKey(body)
192      if (!key || known.has(key)) continue
193      known.add(key)
194      const pin: PinboardPin = {
195        id: newId(now + added.length),
196        createdAt: now,
197        sessionId,
198        cwd,
199        kind: it.kind,
200        title: it.title || firstLineTitle(body),
201        body,
202      }
203      if (it.sourceUuid) pin.sourceUuid = it.sourceUuid
204      if (it.agentId) pin.agentId = it.agentId
205      if (it.agentLabel) pin.agentLabel = it.agentLabel
206      added.push(pin)
207    }
208    return added.length > 0 ? [...added, ...current] : current
209  })
210  if (added.length === 0) return []
211  const addedKeys = new Set(added.map(p => bodyKey(p.body)))
212  await update($, selectedId, () => added[0]?.id ?? null)
213  await update($, confirmDeleteId, () => null)
214  await update($, candidates, list => list.filter(c => !addedKeys.has(bodyKey(c.body))))
215  return added
216}
217
218/** Removes one pin and keeps it as `lastRemoved` for undo. */
219async function removePin($: Dollar, id: string): Promise<PinboardPin | undefined> {
220  let target: PinboardPin | undefined
221  await mutatePins($, current => {
222    target = current.find(p => p.id === id)
223    return target ? current.filter(p => p.id !== id) : current
224  })
225  if (!target) return undefined
226  const removed = target
227  await update($, lastRemoved, () => removed)
228  await update($, confirmDeleteId, () => null)
229  await update($, selectedId, cur => (cur === id ? null : cur))
230  return removed
231}
232
233/** Restores the last removed pin, or the backup `/pin clear` left. */
234async function undo($: Dollar): Promise<string> {
235  const removed = await read($, lastRemoved)
236  if (removed) {
237    await mutatePins($, current =>
238      current.some(p => p.id === removed.id)
239        ? current
240        : [removed, ...current].sort((a, b) => b.createdAt - a.createdAt),
241    )
242    await update($, lastRemoved, () => null)
243    await update($, selectedId, () => removed.id)
244    return `↩ 되돌림: ${describe(removed)}`
245  }
246  const backup = await $.store.get(STORE_BACKUP)
247  if (Array.isArray(backup) && backup.length > 0) {
248    let restored = 0
249    await mutatePins($, current => {
250      const ids = new Set(current.map(p => p.id))
251      const back = (backup as PinboardPin[]).filter(p => !ids.has(p.id))
252      restored = back.length
253      return [...current, ...back].sort((a, b) => b.createdAt - a.createdAt)
254    })
255    await $.store.delete(STORE_BACKUP)
256    return `↩ 되돌림: 핀 ${restored}개 복구`
257  }
258  return '되돌릴 핀이 없습니다.'
259}
260
261async function isPaneOpen($: Dollar): Promise<boolean> {
262  return (await $.ui.panes()).some(p => p.id === PANE)
263}
264
265/**
266 * Opens the pane. `asked` means the person did something (a command, a press): it seats at any width and
267 * lifts the suppression their close set. Unasked opens respect `/pin auto off` and a close this session.
268 */
269async function openPane($: Dollar, options: { asked: boolean; focus?: boolean }): Promise<boolean> {
270  if (options.asked) {
271    await update($, autoOpenSuppressed, () => false)
272  } else {
273    const auto = (await $.store.get(STORE_AUTO_OPEN)) !== false
274    if (!auto || (await read($, autoOpenSuppressed))) return false
275  }
276  const opened = await $.ui.open(
277    options.focus ? { id: PANE, title: PANE_TITLE, focus: true } : { id: PANE, title: PANE_TITLE },
278  )
279  return opened.isPlaced
280}
281
282/** A pin by its number in the pane (filtered, newest first), `last`, its id, or a title substring. */
283async function resolvePin($: Dollar, token: string): Promise<PinboardPin | undefined> {
284  const list = await refreshPins($)
285  const t = token.trim()
286  if (!t || t === 'last') return list[0]
287  const n = Number(t)
288  if (Number.isInteger(n) && n >= 1) {
289    const shown = displayOrder(list, await read($, filter), await currentScope($))
290    if (n <= shown.length) return shown[n - 1]
291  }
292  const lower = t.toLowerCase()
293  return list.find(p => p.id === t) ?? list.find(p => p.title.toLowerCase().includes(lower))
294}
295
296/** The newest assistant message with text in the main conversation, or in one agent's; undefined before any. */
297async function lastAnswer($: Dollar, agentId?: string): Promise<string | undefined> {
298  const messages = agentId ? await $.session.messages({ agentId }) : await $.session.messages()
299  if (!Array.isArray(messages)) return undefined
300  for (let i = messages.length - 1; i >= 0; i--) {
301    const m = messages[i]
302    if (m && m.role === 'assistant' && m.text.trim()) return m.text
303  }
304  return undefined
305}
306
307// ────────────────────────────────────────────────────────────────────────────
308// Slash commands: /pin, /unpin, /pins
309// ────────────────────────────────────────────────────────────────────────────
310
311const HELP = [
312  '/pin                마우스 선택이 있으면 그것을, 없으면 마지막 답변의 표·아티팩트 링크를 저장 (없으면 답변 전체)',
313  '/pin [제목]         위와 같되 제목을 지정',
314  '/pin all [제목]     마지막 답변 전체 저장',
315  '/pin tables|links   마지막 답변의 표만 | 링크만 저장',
316  '/pin rm <n|last>    n번(패널 번호) 또는 최근 핀 삭제  (/unpin <n> 도 같음)',
317  '/pin undo           마지막 삭제(또는 clear) 되돌리기',
318  '/pin show <n>       n번 핀 내용을 대화에 출력 (모델도 읽음)',
319  '/pin clear          모두 삭제 (확인 후)',
320  '/pin export         ~/.claude/pins/pins-<날짜>.md 로 내보내기',
321  '/pin auto on|off    세션 시작·새 후보 감지 시 패널 자동 열기',
322  '/pins               패널 열기/닫기',
323  '세션: 전체 보기는 세션별로 묶임 · "이 세션" 탭은 지금 세션 핀만',
324  '에이전트: 그 에이전트 화면을 보는 동안(패널 열림) 패널과 /pin 은 그 에이전트 기준',
325  '패널 단축키(ctrl+x tab 으로 포커스): 1~9 선택 · a/s/d/g/h 후보 저장 · c 복사 · p 프롬프트에 넣기 · x 삭제 · u 되돌리기 · f 필터',
326].join('\n')
327
328function report(added: Awaited<ReturnType<typeof addPins>>, tag: AgentTag = {}): string {
329  const from = tag.agentLabel ? ` (에이전트 ${tag.agentLabel})` : ''
330  if (added.length === 0) return '이미 저장된 내용입니다.'
331  if (added.length === 1) return `📌 저장${from}: ${describe(added[0]!)}`
332  return `📌 ${added.length}개 저장${from}:\n${added.map(p => `  ${describe(p)}`).join('\n')}`
333}
334
335/**
336 * Pins from the last answer of the transcript in view: the main conversation's, or the agent's whose
337 * transcript the pane last showed beside it.
338 */
339async function pinFromAnswer($: Dollar, mode: 'auto' | 'all' | 'links' | 'tables', title: string): Promise<string> {
340  const tag = await agentTag($, viewedAgentId)
341  const text = await lastAnswer($, tag.agentId)
342  if (!text) return tag.agentId ? '이 에이전트에서 저장할 답변이 없습니다.' : '저장할 답변이 없습니다.'
343  let items: PinInput[]
344  if (mode === 'all') items = [{ kind: classify(text), title: title || firstLineTitle(text), body: text.trim() }]
345  else if (mode === 'links') items = extractLinks(text, false)
346  else if (mode === 'tables') items = extractTables(text)
347  else items = extractAll(text)
348  if (items.length === 0) {
349    if (mode === 'links') return '마지막 답변에 링크가 없습니다.'
350    if (mode === 'tables') return '마지막 답변에 표가 없습니다.'
351    items = [{ kind: 'text', title: title || firstLineTitle(text), body: text.trim() }]
352  } else if (title && mode !== 'all') {
353    const n = items.length
354    items = items.map((it, i) => ({ ...it, title: n > 1 ? `${title} (${i + 1}/${n})` : title }))
355  }
356  const added = await addPins(
357    $,
358    items.map(it => ({ ...it, ...tag })),
359  )
360  await openPane($, { asked: true })
361  return report(added, tag)
362}
363
364/** `/pin [title]`: the mouse selection when there is one, else the last answer's tables and artifact links. */
365async function pinDefault($: Dollar, title: string): Promise<string> {
366  let selected: { text: string; requestId?: string } | undefined
367  try {
368    selected = await $.ui.selection()
369  } catch {
370    selected = undefined
371  }
372  const text = selected?.text.trim() ?? ''
373  if (text) {
374    const tag = await agentTag($, viewedAgentId)
375    const item: PinInput = { kind: classify(text), title: title || firstLineTitle(text), body: text, ...tag }
376    if (selected?.requestId) item.sourceUuid = selected.requestId
377    const added = await addPins($, [item])
378    await openPane($, { asked: true })
379    return report(added, tag)
380  }
381  return pinFromAnswer($, 'auto', title)
382}
383
384async function runRemove($: Dollar, token: string): Promise<string> {
385  const target = await resolvePin($, token)
386  if (!target) return `핀을 찾지 못했습니다: ${token.trim() || '(없음)'}`
387  await removePin($, target.id)
388  return `🗑 삭제: ${describe(target)}  (/pin undo 로 복구)`
389}
390
391async function runShow($: Dollar, token: string): Promise<string> {
392  const target = await resolvePin($, token)
393  if (!target) return `핀을 찾지 못했습니다: ${token.trim() || '(없음)'}`
394  await update($, selectedId, () => target.id)
395  await openPane($, { asked: true })
396  return `${describe(target)}\n\n${target.body}`
397}
398
399async function runClear($: Dollar, rest: string): Promise<string> {
400  const list = await refreshPins($)
401  if (list.length === 0) return '저장된 핀이 없습니다.'
402  let ok = rest.trim() === '--yes'
403  if (!ok) {
404    try {
405      ok = (await $.ui.ask(`핀 ${list.length}개를 모두 삭제할까요?`, ['삭제', '취소'])) === '삭제'
406    } catch {
407      return '취소됨 (대화형이 아니면 /pin clear --yes)'
408    }
409  }
410  if (!ok) return '취소됨'
411  let cleared: PinboardPin[] = []
412  await mutatePins($, current => {
413    cleared = current
414    return []
415  })
416  await $.store.set(STORE_BACKUP, cleared)
417  await update($, selectedId, () => null)
418  await update($, lastRemoved, () => null)
419  return `🗑 핀 ${cleared.length}개 삭제 (/pin undo 로 복구)`
420}
421
422async function runExport($: Dollar): Promise<string> {
423  const list = await refreshPins($)
424  if (list.length === 0) return '내보낼 핀이 없습니다.'
425  const home = (await $.env.get('HOME')) ?? '.'
426  const date = localStamp(await $.clock.now()).slice(0, 10)
427  const path = `${home}/.claude/pins/pins-${date}.md`
428  const sections = list.map(p => {
429    const meta = `${KIND_LABEL[p.kind]} · ${projectName(p.cwd)} · ${localStamp(p.createdAt)}`
430    return `## ${GLYPH[p.kind]} ${p.title}\n\n_${meta}_\n\n${p.body}\n`
431  })
432  try {
433    await $.fs.write(path, [`# Pins (${list.length}) · ${date}`, '', ...sections].join('\n'))
434  } catch (err) {
435    return `내보내기 실패: ${String(err)}`
436  }
437  return `📄 내보냄: ${path}`
438}
439
440async function runAuto($: Dollar, rest: string): Promise<string> {
441  const v = rest.trim().toLowerCase()
442  if (v !== 'on' && v !== 'off') {
443    const cur = await $.store.get(STORE_AUTO_OPEN)
444    return `자동 열기: ${cur === false ? 'off' : 'on'}  (/pin auto on|off)`
445  }
446  await $.store.set(STORE_AUTO_OPEN, v === 'on')
447  return `자동 열기: ${v}`
448}
449
450/** `/pin ...`: the first word picks a subcommand; anything else is a title for the default save. */
451async function runPin($: Dollar, rawArgs: string): Promise<string> {
452  const args = rawArgs.trim()
453  const [head = '', ...tail] = args.split(/\s+/)
454  const rest = tail.join(' ').trim()
455  switch (head.toLowerCase()) {
456    case 'help':
457    case '?':
458      return HELP
459    case 'rm':
460    case 'remove':
461    case 'del':
462    case 'delete':
463      return runRemove($, rest)
464    case 'undo':
465      return undo($)
466    case 'show':
467    case 'cat':
468      return runShow($, rest)
469    case 'clear':
470      return runClear($, rest)
471    case 'export':
472      return runExport($)
473    case 'auto':
474      return runAuto($, rest)
475    case 'all':
476      return pinFromAnswer($, 'all', rest)
477    case 'links':
478    case 'link':
479      return pinFromAnswer($, 'links', rest)
480    case 'tables':
481    case 'table':
482      return pinFromAnswer($, 'tables', rest)
483    default:
484      return pinDefault($, args)
485  }
486}
487
488/** `/pins`: closes the pane when open, else opens it with the keyboard. */
489async function togglePane($: Dollar): Promise<string> {
490  if (await isPaneOpen($)) {
491    await $.ui.close({ id: PANE })
492    return 'Pins 패널 닫음'
493  }
494  const placed = await openPane($, { asked: true, focus: true })
495  return placed
496    ? 'Pins 패널 열림 (ctrl+x tab: 패널 포커스 · Esc: 프롬프트로 · /pin help: 도움말)'
497    : 'Pins 패널은 열렸지만 아직 표시되지 않음 (터미널을 넓히면 보입니다)'
498}
499
500// ────────────────────────────────────────────────────────────────────────────
501// The Pins pane
502// ────────────────────────────────────────────────────────────────────────────
503
504const MAX_ROWS = 30
505const CANDIDATE_HOTKEYS = ['a', 's', 'd', 'g', 'h']
506// Theme keys, so the colors follow the person's light or dark theme.
507const ACCENT = 'claude'
508const KIND_COLOR: Record<PinboardKind, string> = {
509  table: 'suggestion',
510  artifact: 'merged',
511  link: 'ide',
512  text: 'subtle',
513}
514
515async function renderPane($: Dollar, e: RenderInputOf<'Pane', RenderSurface>) {
516  const { Box, Text, Button, Markdown, Link } = $.ui.resolve(e)
517  // Only a drawing is told which transcript is on screen; remember it for /pin and /unpin.
518  const viewAgent = e.props.view.agentId
519  viewedAgentId = viewAgent
520  const [list, f, sel, allCands, removed, confirm, now, scope, viewLabel] = await Promise.all([
521    read($, pins),
522    read($, filter),
523    read($, selectedId),
524    read($, candidates),
525    read($, lastRemoved),
526    read($, confirmDeleteId),
527    $.clock.now(),
528    currentScope($, viewAgent),
529    viewAgent ? agentLabelOf($, viewAgent) : Promise.resolve(undefined),
530  ])
531  const base = inView(list, scope)
532  const groups = groupBySession(visible(list, f, scope), scope)
533  const shown = groups.flatMap(g => g.pins)
534  const selected = shown.find(p => p.id === sel) ?? null
535  // The main view offers the main conversation's candidates; an agent's view offers that agent's.
536  const cands = allCands.filter(c => c.agentId === viewAgent)
537  const width = Math.max(20, e.props.bodyColumns)
538
539  const select = (id: string) => {
540    void update($, confirmDeleteId, () => null)
541    void update($, selectedId, cur => (cur === id ? null : id))
542  }
543  const setFilter = (next: PinboardFilter) => {
544    void update($, selectedId, () => null)
545    void update($, filter, () => next)
546    void $.store.set(STORE_FILTER, next)
547  }
548  const cycleFilter = () => setFilter(FILTERS[(FILTERS.indexOf(f) + 1) % FILTERS.length] ?? 'all')
549  const counts: Record<PinboardFilter, number> = {
550    all: base.length,
551    session: base.filter(p => p.sessionId === scope.sessionId).length,
552    project: base.filter(p => p.cwd === scope.cwd).length,
553    table: base.filter(p => p.kind === 'table').length,
554    artifact: base.filter(p => p.kind === 'artifact').length,
555    link: base.filter(p => p.kind === 'link').length,
556  }
557  const rule = '─'.repeat(width)
558
559  const pinRow = (p: PinboardPin, i: number) => {
560    const isSelected = p.id === sel
561    const hotkey = i < 9 ? String(i + 1) : undefined
562    const age = shortAge(now, p.createdAt)
563    // In the main view a pin an agent saved names the agent beside its age.
564    const badge = !viewAgent && p.agentLabel ? fitWidth(`@${p.agentLabel}`, 14) : ''
565    // marker 2 + "1: " 3 + gap 2 + glyph and age on the right (+ the badge)
566    const room = width - 2 - 3 - 2 - (2 + textWidth(age)) - (badge ? textWidth(badge) + 1 : 0)
567    const title = fitWidth(hotkey ? p.title : `${i + 1}. ${p.title}`, room)
568    return (
569      <Box key={`row:${p.id}`} justifyContent="space-between">
570        <Box>
571          <Text color={ACCENT}>{isSelected ? '▍ ' : '  '}</Text>
572          <Button
573            key={`sel:${p.id}`}
574            {...(hotkey ? { hotkey } : {})}
575            plain
576            dimColor={!isSelected}
577            hover={{ dimColor: false }}
578            label={title}
579            onPress={() => select(p.id)}
580          />
581        </Box>
582        <Text>
583          {badge ? <Text dimColor>{badge} </Text> : null}
584          <Text color={KIND_COLOR[p.kind]}>{GLYPH[p.kind]}</Text> <Text dimColor>{age}</Text>
585        </Text>
586      </Box>
587    )
588  }
589
590  // Rows in display order, with a header per session when more than one session's pins are shown.
591  const rows: ReturnType<typeof pinRow>[] = []
592  let index = 0
593  for (const g of groups) {
594    if (index >= MAX_ROWS) break
595    if (groups.length > 1) {
596      rows.push(
597        <Box key={`group:${g.sessionId}`} marginTop={index === 0 ? 0 : 1}>
598          {g.isCurrent ? (
599            <Text color={ACCENT} bold>
600              {fitWidth(g.label, width)}
601            </Text>
602          ) : (
603            <Text dimColor>{fitWidth(g.label, width)}</Text>
604          )}
605        </Box>,
606      )
607    }
608    for (const p of g.pins) {
609      if (index >= MAX_ROWS) break
610      rows.push(pinRow(p, index))
611      index++
612    }
613  }
614
615  return (
616    <Box flexDirection="column">
617      <Box justifyContent="space-between">
618        <Text bold>
619          Pins <Text dimColor>{base.length}</Text>
620        </Text>
621        <Button key="filter" hotkey="f" plain dimColor label="다음 필터" onPress={cycleFilter} />
622      </Box>
623      {viewLabel ? (
624        <Text wrap="truncate-end">
625          <Text color={ACCENT} bold>
626            ↳ {viewLabel}
627          </Text>
628          <Text dimColor> 에이전트의 핀과 후보만 보여요</Text>
629        </Text>
630      ) : null}
631      <Box flexWrap="wrap" columnGap={2}>
632        {FILTERS.map(name =>
633          name === f ? (
634            <Text color="claude" bold underline>
635              {FILTER_LABEL[name]} {counts[name]}
636            </Text>
637          ) : (
638            <Button
639              key={`tab:${name}`}
640              plain
641              dimColor
642              label={`${FILTER_LABEL[name]} ${counts[name]}`}
643              onPress={() => setFilter(name)}
644            />
645          ),
646        )}
647      </Box>
648      <Text dimColor>{rule}</Text>
649
650      {base.length === 0 && (
651        <Box flexDirection="column" paddingX={2} marginY={1}>
652          <Text bold>{viewAgent ? '이 에이전트의 핀이 아직 없어요' : '아직 핀이 없어요'}</Text>
653          {EMPTY_HINTS.map(([how, what]) => (
654            <Text>
655              <Text color={ACCENT}>{padCells(how, 16)}</Text>
656              <Text dimColor>{what}</Text>
657            </Text>
658          ))}
659        </Box>
660      )}
661      {base.length > 0 && shown.length === 0 && (
662        <Box paddingX={2} marginY={1}>
663          <Text dimColor>이 필터에 맞는 핀이 없어요 · f 로 다음 필터</Text>
664        </Box>
665      )}
666
667      {rows}
668      {shown.length > MAX_ROWS && (
669        <Text dimColor>
670          {'  '}… {shown.length - MAX_ROWS}개 더 · f 로 필터
671        </Text>
672      )}
673
674      {selected && (
675        <Box
676          flexDirection="column"
677          marginTop={1}
678          paddingX={1}
679          borderStyle="round"
680          borderColor={KIND_COLOR[selected.kind]}
681        >
682          <Text bold>
683            <Text color={KIND_COLOR[selected.kind]}>{GLYPH[selected.kind]}</Text> {fitWidth(selected.title, width - 6)}
684          </Text>
685          <Text dimColor wrap="truncate-end">
686            {KIND_LABEL[selected.kind]} · {projectName(selected.cwd)} · {localStamp(selected.createdAt)}
687            {selected.agentLabel ? ` · 에이전트 ${selected.agentLabel}` : ''}
688          </Text>
689          <Box marginY={1} flexDirection="column">
690            {selected.kind === 'link' || selected.kind === 'artifact' ? (
691              <Link href={selected.body} label={fitWidth(selected.body, width - 4)} />
692            ) : (
693              <Markdown text={selected.body} />
694            )}
695          </Box>
696          {confirm === selected.id ? (
697            <Box columnGap={2} flexWrap="wrap">
698              <Text color="error" bold>
699                정말 삭제할까요?
700              </Text>
701              <Button
702                key="delete-yes"
703                hotkey="x"
704                plain
705                label="삭제"
706                onPress={() => {
707                  void removePin($, selected.id)
708                }}
709              />
710              <Button
711                key="delete-no"
712                hotkey="o"
713                plain
714                label="취소"
715                onPress={() => void update($, confirmDeleteId, () => null)}
716              />
717            </Box>
718          ) : (
719            <Box columnGap={2} flexWrap="wrap">
720              <Button
721                key="copy"
722                hotkey="c"
723                plain
724                label="복사"
725                onPress={press => {
726                  void $.ui
727                    .copy({ text: selected.body, surface: press.surface })
728                    .then(r => $.ui.toast(r.isCopied ? '복사됨' : `복사 실패: ${r.reason}`))
729                }}
730              />
731              <Button
732                key="prompt"
733                hotkey="p"
734                plain
735                label="프롬프트에 넣기"
736                onPress={() => {
737                  void $.prompt.fill({ text: `${selected.body}\n`, mode: 'insert' })
738                }}
739              />
740              <Button
741                key="delete"
742                hotkey="x"
743                plain
744                dimColor
745                label="삭제"
746                onPress={() => void update($, confirmDeleteId, () => selected.id)}
747              />
748            </Box>
749          )}
750        </Box>
751      )}
752
753      {removed && (
754        <Box marginTop={1}>
755          <Text color="warning">↩ </Text>
756          <Button
757            key="undo"
758            hotkey="u"
759            plain
760            label="되돌리기"
761            onPress={() => {
762              void undo($)
763            }}
764          />
765          <Text dimColor> {fitWidth(removed.title, width - 16)}</Text>
766        </Box>
767      )}
768
769      {cands.length > 0 && (
770        <Box flexDirection="column" marginTop={1}>
771          <Text dimColor>
772            {labelledRule(viewAgent ? '이 에이전트의 후보 · 누르면 저장' : '이번 세션의 후보 · 누르면 저장', width)}
773          </Text>
774          {cands.map((c, i) => {
775            const hotkey = CANDIDATE_HOTKEYS[i]
776            const age = shortAge(now, c.seenAt)
777            const room = width - 2 - 3 - 2 - (2 + textWidth(age))
778            return (
779              <Box key={`cand:${c.id}`} justifyContent="space-between">
780                <Box>
781                  <Text color={ACCENT}>+ </Text>
782                  <Button
783                    key={`save:${c.id}`}
784                    {...(hotkey ? { hotkey } : {})}
785                    plain
786                    dimColor
787                    hover={{ dimColor: false }}
788                    label={fitWidth(c.title, room)}
789                    onPress={() => {
790                      const tag: AgentTag = c.agentId ? { agentId: c.agentId, agentLabel: c.agentLabel ?? '' } : {}
791                      void addPins($, [
792                        { kind: c.kind, title: c.title, body: c.body, sourceUuid: c.sourceUuid, ...tag },
793                      ])
794                    }}
795                  />
796                </Box>
797                <Text>
798                  <Text color={KIND_COLOR[c.kind]}>{GLYPH[c.kind]}</Text> <Text dimColor>{age}</Text>
799                </Text>
800              </Box>
801            )
802          })}
803        </Box>
804      )}
805
806      <Box flexDirection="column" marginTop={1}>
807        <Text dimColor>{rule}</Text>
808        <Text dimColor wrap="truncate-end">
809          {e.props.isFocused ? 'Esc 프롬프트로 · /pin help 도움말' : 'ctrl+x tab 으로 패널 조작 · /pin help 도움말'}
810        </Text>
811      </Box>
812    </Box>
813  )
814}
815
816const EMPTY_HINTS: [string, string][] = [
817  ['/pin', '마지막 답변의 표·링크 저장'],
818  ['"이 표 핀해줘"', '모델에게 말로 저장'],
819  ['a s d g h', '아래 후보에서 바로 저장'],
820]
821
822/** `text` followed by spaces up to `cells` cells (at least one). */
823function padCells(text: string, cells: number): string {
824  return text + ' '.repeat(Math.max(1, cells - textWidth(text)))
825}
826
827/** A rule with a label at its start: `─ label ─────`, `width` cells long. */
828function labelledRule(label: string, width: number): string {
829  const head = `─ ${label} `
830  return head + '─'.repeat(Math.max(0, width - textWidth(head)))
831}
832
833// ────────────────────────────────────────────────────────────────────────────
834// Hooks
835// ────────────────────────────────────────────────────────────────────────────
836
837/** Keeps at most `cap` candidates for each agent (and for the main conversation), newest first. */
838function capPerAgent(list: PinboardCandidate[], cap: number): PinboardCandidate[] {
839  const seen = new Map<string, number>()
840  return list.filter(c => {
841    const key = c.agentId ?? ''
842    const n = (seen.get(key) ?? 0) + 1
843    seen.set(key, n)
844    return n <= cap
845  })
846}
847
848/** A plugin tool answers with a string (or an array of content blocks); an object is refused. */
849function toolText(text: string) {
850  return { result: text }
851}
852
853export const register: Register = on => {
854  on('session.start', async ($, e, next) => {
855    try {
856      await Promise.all([
857        $.command.register({
858          name: 'pin',
859          description: '마지막 답변의 표·아티팩트 링크(또는 마우스 선택)를 Pins 패널에 저장',
860          argumentHint:
861            '[제목] | all | tables | links | rm <n> | undo | show <n> | clear | export | auto on|off | help',
862        }),
863        $.command.register({ name: 'pins', description: 'Pins 패널 열기/닫기' }),
864        $.command.register({ name: 'unpin', description: '핀 삭제 (/pin rm 과 같음)', argumentHint: '<n|last|제목>' }),
865        $.tool.register({
866          name: 'pin',
867          description:
868            "Save an item from this conversation into the user's Pins side pane so they can reopen it any time. " +
869            "Use when the user asks to pin, save, keep or bookmark a table, link, artifact or answer (e.g. '이 표 저장해줘', '핀해줘'). " +
870            'Pass the exact markdown of the item: a whole markdown table, a URL, or the text itself.',
871          inputSchema: {
872            type: 'object',
873            properties: {
874              markdown: {
875                type: 'string',
876                description: 'The item to save, verbatim markdown (a full table, a URL, or text).',
877              },
878              title: {
879                type: 'string',
880                description: 'Short title (<= 60 chars). Derived from the content when omitted.',
881              },
882              kind: {
883                type: 'string',
884                enum: ['table', 'artifact', 'link', 'text'],
885                description: 'Derived from the content when omitted.',
886              },
887            },
888            required: ['markdown'],
889          },
890        }),
891        $.tool.register({
892          name: 'unpin',
893          description:
894            "Remove a pin from the user's Pins pane. Identify it by id, by its 1-based index as `list` shows, or by a title substring. Call `list` first when unsure.",
895          inputSchema: {
896            type: 'object',
897            properties: {
898              id: { type: 'string' },
899              index: { type: 'integer', minimum: 1 },
900              title: { type: 'string', description: 'A substring of the pin title.' },
901            },
902          },
903        }),
904        $.tool.register({
905          name: 'list',
906          description: "List the user's saved pins: index, kind, title, project and id.",
907        }),
908      ])
909    } catch (err) {
910      $.ui.log(`pinboard: registration failed: ${String(err)}`, { to: 'debug' })
911    }
912
913    // The store is the truth; session state mirrors it so the pane redraws on every change. The timer
914    // picks up what other sessions pin or remove while this one runs.
915    const list = await refreshPins($)
916    const savedFilter = await $.store.get(STORE_FILTER)
917    if (isFilter(savedFilter)) await update($, filter, () => savedFilter)
918    $.clock.every(REFRESH_MS, () => {
919      void refreshPins($).catch(() => undefined)
920    })
921    if (e.isInteractive && list.length > 0) await openPane($, { asked: false })
922
923    return next(e)
924  })
925
926  on('command.run', { command: 'pin' }, async ($, e) => ({ text: await runPin($, e.args) }))
927  on('command.run', { command: 'unpin' }, async ($, e) => ({ text: await runRemove($, e.args) }))
928  on('command.run', { command: 'pins' }, async $ => ({ text: await togglePane($) }))
929
930  on('tool.call', { tool: 'mcp__pinboard__pin' }, async ($, e) => {
931    const input = e as unknown as Record<string, unknown>
932    const markdown = typeof input.markdown === 'string' ? input.markdown.trim() : ''
933    if (!markdown) return toolText('error: markdown is empty')
934    const title = typeof input.title === 'string' ? cleanTitle(input.title) : ''
935    const kind = isKind(input.kind) ? input.kind : classify(markdown)
936    // A subagent or teammate calling the tool runs in its own loop: the pin remembers which.
937    const tag = await agentTag($, typeof input.agentId === 'string' ? input.agentId : undefined)
938    const added = await addPins($, [{ kind, title, body: markdown, ...tag }])
939    await openPane($, { asked: true })
940    const first = added[0]
941    return toolText(first ? `pinned: ${describe(first)} (id ${first.id})` : 'already pinned (identical content exists)')
942  }).catch(() => ({ deny: 'pinboard: pin failed' }))
943
944  on('tool.call', { tool: 'mcp__pinboard__unpin' }, async ($, e) => {
945    const input = e as unknown as Record<string, unknown>
946    const token =
947      typeof input.id === 'string'
948        ? input.id
949        : typeof input.index === 'number'
950          ? String(input.index)
951          : typeof input.title === 'string'
952            ? input.title
953            : ''
954    if (!token) return toolText('error: give id, index or title')
955    const target = await resolvePin($, token)
956    if (!target) return toolText(`error: no pin matches "${token}"`)
957    await removePin($, target.id)
958    return toolText(`unpinned: ${describe(target)} (the user can restore it with /pin undo)`)
959  }).catch(() => ({ deny: 'pinboard: unpin failed' }))
960
961  on('tool.call', { tool: 'mcp__pinboard__list' }, async $ => {
962    const list = await refreshPins($)
963    if (list.length === 0) return toolText('no pins')
964    return toolText(
965      list
966        .map((p, i) => {
967          const agent = p.agentLabel ? ` · agent ${p.agentLabel}` : ''
968          return `${i + 1}. [${p.kind}] ${p.title} · ${projectName(p.cwd)}${agent} · id ${p.id}`
969        })
970        .join('\n'),
971    )
972  }).catch(() => ({ deny: 'pinboard: list failed' }))
973
974  // Every block of a reply, the main conversation's and each agent's: its tables and artifact links become
975  // one-press candidates, tagged with the agent. The pane offers each view its own.
976  on('session.append', { door: 'response' }, async ($, e, next) => {
977    const stored = await next(e)
978    try {
979      if (e.message.role === 'assistant') {
980        const texts: string[] = []
981        for (const block of e.message.content) {
982          if (block.type === 'text' && typeof block.text === 'string') texts.push(block.text)
983        }
984        const found = texts.flatMap(t => extractAll(t))
985        if (found.length > 0) {
986          const now = await $.clock.now()
987          const pinned = new Set((await refreshPins($)).map(p => bodyKey(p.body)))
988          const fresh = found.filter(f => !pinned.has(bodyKey(f.body)))
989          if (fresh.length > 0) {
990            const tag = await agentTag($, e.agentId)
991            await update($, candidates, list => {
992              const have = new Set(list.map(c => bodyKey(c.body)))
993              const incoming: PinboardCandidate[] = fresh
994                .filter(f => !have.has(bodyKey(f.body)))
995                .map((f, i) => ({
996                  id: newId(now + i),
997                  kind: f.kind,
998                  title: f.title,
999                  body: f.body,
1000                  sourceUuid: e.uuid,
1001                  seenAt: now,
1002                  ...tag,
1003                }))
1004              return capPerAgent([...incoming, ...list], MAX_CANDIDATES)
1005            })
1006            // Only the main conversation opens the pane unasked: agents can be many and busy.
1007            // Awaited: work a hook leaves running is dropped when its dispatch ends.
1008            if (e.agentId === undefined && !(await isPaneOpen($))) await openPane($, { asked: false })
1009          }
1010        }
1011      }
1012    } catch {
1013      // candidates are best effort; the row is already stored
1014    }
1015    return stored
1016  })
1017
1018  // The person closed the pane: no unasked reopen until they ask for it again.
1019  on('ui.close', { id: PANE }, async ($, e, next) => {
1020    if (e.origin.kind === 'person') await update($, autoOpenSuppressed, () => true)
1021    return next(e)
1022  })
1023
1024  on('ui.render', { component: 'Pane', requestId: PANE }, ($, e) => renderPane($, e))
1025}
1026
hooks/extract.ts 119 lines
1// Pure helpers: find markdown tables and links in a reply, name them, classify text.
2import type { PinboardKind } from '../types'
3
4export type Extracted = { kind: PinboardKind; title: string; body: string }
5
6export const MAX_TITLE = 60
7
8const SEPARATOR = /^\s*\|?\s*:?-{2,}:?\s*(?:\|\s*:?-{2,}:?\s*)*\|?\s*$/
9const URL = /https?:\/\/[^\s<>()[\]'"`]+/g
10const MD_LINK = /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g
11const ARTIFACT = /claude\.ai\/(?:code\/)?artifact\//
12
13export function cleanTitle(line: string): string {
14  return line
15    .replace(/^[#>\-*\d.)\s]+/, '')
16    .replace(/[*_`]/g, '')
17    .replace(/[::]\s*$/, '')
18    .trim()
19    .slice(0, MAX_TITLE)
20}
21
22function isTableLine(line: string): boolean {
23  const t = line.trim()
24  return t.length > 0 && t.includes('|')
25}
26
27export function headerCells(line: string): string[] {
28  return line
29    .trim()
30    .replace(/^\|/, '')
31    .replace(/\|$/, '')
32    .split('|')
33    .map(c => c.trim())
34    .filter(Boolean)
35}
36
37export function extractTables(text: string): Extracted[] {
38  const lines = text.split('\n')
39  const out: Extracted[] = []
40  let i = 0
41  while (i < lines.length - 1) {
42    const header = lines[i] ?? ''
43    const sep = lines[i + 1] ?? ''
44    if (isTableLine(header) && SEPARATOR.test(sep)) {
45      let end = i + 2
46      while (end < lines.length && isTableLine(lines[end] ?? '')) end++
47      const body = lines.slice(i, end).join('\n').trim()
48      let title = ''
49      for (let j = i - 1; j >= 0; j--) {
50        const above = (lines[j] ?? '').trim()
51        if (!above) continue
52        if (isTableLine(above) || SEPARATOR.test(above)) break
53        // A heading, a short label or a line ending in a colon names the table; a long sentence does not.
54        if (above.length <= 48 || /^#/.test(above) || /[::]$/.test(above)) title = cleanTitle(above)
55        break
56      }
57      if (!title) title = headerCells(header).join(' | ').slice(0, MAX_TITLE)
58      out.push({ kind: 'table', title: title || '표', body })
59      i = end
60    } else {
61      i++
62    }
63  }
64  return out
65}
66
67export function extractLinks(text: string, onlyArtifacts: boolean): Extracted[] {
68  const labels = new Map<string, string>()
69  for (const m of text.matchAll(MD_LINK)) labels.set(m[2] ?? '', m[1] ?? '')
70  const out: Extracted[] = []
71  const seen = new Set<string>()
72  for (const m of text.matchAll(URL)) {
73    const url = (m[0] ?? '').replace(/[.,;:!?*]+$/, '')
74    if (!url || seen.has(url)) continue
75    seen.add(url)
76    const isArtifact = ARTIFACT.test(url)
77    if (onlyArtifacts && !isArtifact) continue
78    const label = cleanTitle(labels.get(url) ?? '')
79    const fallback = isArtifact
80      ? `artifact ${url.split('/').filter(Boolean).pop() ?? ''}`
81      : url.replace(/^https?:\/\//, '')
82    out.push({ kind: isArtifact ? 'artifact' : 'link', title: (label || fallback).slice(0, MAX_TITLE), body: url })
83  }
84  return out
85}
86
87/** Tables and artifact links: what /pin and the candidate list pick up by default. */
88export function extractAll(text: string): Extracted[] {
89  return [...extractTables(text), ...extractLinks(text, true)]
90}
91
92export function firstLineTitle(text: string, fallback = '메모'): string {
93  for (const line of text.split('\n')) {
94    const t = cleanTitle(line)
95    if (t) return t
96  }
97  return fallback
98}
99
100export function classify(text: string): PinboardKind {
101  const t = text.trim()
102  if (/^https?:\/\/\S+$/.test(t)) return ARTIFACT.test(t) ? 'artifact' : 'link'
103  if (extractTables(t).length > 0) return 'table'
104  return 'text'
105}
106
107export function isKind(value: unknown): value is PinboardKind {
108  return value === 'table' || value === 'artifact' || value === 'link' || value === 'text'
109}
110
111export function projectName(cwd: string): string {
112  return cwd.split('/').filter(Boolean).pop() ?? cwd
113}
114
115/** Whitespace-insensitive identity of a body, for de-duplication. */
116export function bodyKey(body: string): string {
117  return body.replace(/\s+/g, ' ').trim()
118}
119
hooks/format.ts 84 lines
1// Pure display helpers for the pane: terminal cell widths, truncation, short times.
2import type { PinboardKind } from '../types'
3
4/** Cells a code point takes in a terminal: 2 for wide East Asian characters and emoji, 0 for combining marks. */
5export function cellWidth(codePoint: number): number {
6  if (codePoint < 32 || (codePoint >= 0x7f && codePoint < 0xa0)) return 0
7  if (
8    (codePoint >= 0x0300 && codePoint <= 0x036f) ||
9    (codePoint >= 0x200b && codePoint <= 0x200f) ||
10    (codePoint >= 0xfe00 && codePoint <= 0xfe0f)
11  )
12    return 0
13  if (
14    (codePoint >= 0x1100 && codePoint <= 0x115f) ||
15    (codePoint >= 0x2e80 && codePoint <= 0x303e) ||
16    (codePoint >= 0x3041 && codePoint <= 0x33ff) ||
17    (codePoint >= 0x3400 && codePoint <= 0x4dbf) ||
18    (codePoint >= 0x4e00 && codePoint <= 0x9fff) ||
19    (codePoint >= 0xa960 && codePoint <= 0xa97f) ||
20    (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||
21    (codePoint >= 0xf900 && codePoint <= 0xfaff) ||
22    (codePoint >= 0xfe30 && codePoint <= 0xfe4f) ||
23    (codePoint >= 0xff00 && codePoint <= 0xff60) ||
24    (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
25    (codePoint >= 0x1f300 && codePoint <= 0x1faff) ||
26    (codePoint >= 0x20000 && codePoint <= 0x3fffd)
27  )
28    return 2
29  return 1
30}
31
32/** Cells a string takes in a terminal. */
33export function textWidth(text: string): number {
34  let w = 0
35  for (const ch of text) w += cellWidth(ch.codePointAt(0) ?? 0)
36  return w
37}
38
39/** Cuts `text` to at most `cells` cells, ending in `…` when it was cut. */
40export function fitWidth(text: string, cells: number): string {
41  if (cells <= 0) return ''
42  if (textWidth(text) <= cells) return text
43  let out = ''
44  let w = 0
45  for (const ch of text) {
46    const cw = cellWidth(ch.codePointAt(0) ?? 0)
47    if (w + cw > cells - 1) break
48    out += ch
49    w += cw
50  }
51  return `${out.trimEnd()}…`
52}
53
54/** A compact age for a list column: 방금, 5분, 3시간, 2일, or the date as MM-DD. */
55export function shortAge(now: number, then: number): string {
56  const s = Math.max(0, Math.round((now - then) / 1000))
57  if (s < 60) return '방금'
58  const m = Math.floor(s / 60)
59  if (m < 60) return `${m}분`
60  const h = Math.floor(m / 60)
61  if (h < 24) return `${h}시간`
62  const d = Math.floor(h / 24)
63  if (d < 7) return `${d}일`
64  const date = new Date(then)
65  return `${pad2(date.getMonth() + 1)}-${pad2(date.getDate())}`
66}
67
68/** Local date and time as YYYY-MM-DD HH:MM. */
69export function localStamp(then: number): string {
70  const d = new Date(then)
71  return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`
72}
73
74function pad2(n: number): string {
75  return n < 10 ? `0${n}` : String(n)
76}
77
78export const KIND_LABEL: Record<PinboardKind, string> = {
79  table: '표',
80  artifact: '아티팩트',
81  link: '링크',
82  text: '메모',
83}
84
types/index.d.ts 48 lines
1export type PinboardKind = 'table' | 'artifact' | 'link' | 'text'
2
3/** One saved item. Kept in `$.store` across sessions. */
4export type PinboardPin = {
5  id: string
6  createdAt: number
7  sessionId: string
8  cwd: string
9  kind: PinboardKind
10  title: string
11  body: string
12  sourceUuid?: string
13  /** The subagent or teammate it came from; absent for the main conversation. */
14  agentId?: string
15  /** That agent's name as shown when it was pinned, kept since the agent is gone in later sessions. */
16  agentLabel?: string
17}
18
19/** A table or artifact link seen in a reply this session, one press away from being a pin. */
20export type PinboardCandidate = {
21  id: string
22  kind: PinboardKind
23  title: string
24  body: string
25  sourceUuid: string
26  seenAt: number
27  /** The subagent or teammate whose reply it was in; absent for the main conversation. */
28  agentId?: string
29  agentLabel?: string
30}
31
32export type PinboardFilter = 'all' | 'session' | 'project' | 'table' | 'artifact' | 'link'
33
34declare module 'claude-code' {
35  interface PluginState {
36    pinboard: {
37      pins: PinboardPin[]
38      selectedId: string | null
39      filter: PinboardFilter
40      candidates: PinboardCandidate[]
41      lastRemoved: PinboardPin | null
42      confirmDeleteId: string | null
43      /** True once the person closed the pane this session: no unasked reopen until they open it again. */
44      autoOpenSuppressed: boolean
45    }
46  }
47}
48