hooks/register.tsx 274 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Todo, TodoWhen } from '../types'
5
6const PLUGIN = 'user-todos'
7const TOOL_ADD = 'mcp__user-todos__add'
8const TOOL_DONE = 'mcp__user-todos__done'
9const TOOL_MOVE = 'mcp__user-todos__move'
10const TOOL_LIST = 'mcp__user-todos__list'
11// 「あとで」は全セッション共通なので $.store に置き、帯の描画用に $.state へ写す
12const LATER_STORE_KEY = 'later'
13// 他のセッションが「あとで」を書き換えても帯に反映されるよう、定期的に読み直す
14const SYNC_MS = 30_000
15
16const now = atom({ plugin: 'user-todos', key: 'now' } as const, [] as Todo[])
17const later = atom({ plugin: 'user-todos', key: 'later' } as const, [] as Todo[])
18// ターミナルの配色(Catppuccin Mocha)に揃えたパステルの黄色
19const NOW_COLOR = '#f9e2af'
20const isLaterOpen = atom({ plugin: 'user-todos', key: 'isLaterOpen' } as const, false)
21// 「あとで」のうち別リポジトリで登録した分は、帯を開いても畳んでおく
22const isOthersOpen = atom({ plugin: 'user-todos', key: 'isOthersOpen' } as const, false)
23// このセッションのリポジトリ名(起動時に一度だけ調べる)
24const repo = atom({ plugin: 'user-todos', key: 'repo' } as const, '')
25
26const WHEN_SCHEMA = {
27 type: 'string',
28 enum: ['now', 'later'],
29 description: 'now: 今の作業を進めるのにユーザーの行動が要る / later: 今すぐではないが、あとでユーザーがやること',
30}
31
32const isTodo = (value: unknown): value is Todo =>
33 typeof value === 'object' &&
34 value !== null &&
35 typeof (value as Todo).id === 'string' &&
36 typeof (value as Todo).text === 'string'
37
38const loadLater = async ($: EngineInterface): Promise<Todo[]> => {
39 const stored = await $.store.get(LATER_STORE_KEY)
40 return Array.isArray(stored) ? stored.filter(isTodo) : []
41}
42
43// 他のセッションの書き込みを消さないよう、書き換えのたびに $.store から読み直してから書く
44const changeLater = async ($: EngineInterface, fn: (list: Todo[]) => Todo[]): Promise<Todo[]> => {
45 const next = fn(await loadLater($))
46 await $.store.set(LATER_STORE_KEY, next)
47 await update($, later, () => next)
48 return next
49}
50
51const syncLater = async ($: EngineInterface) => {
52 const stored = await loadLater($)
53 await update($, later, () => stored)
54}
55
56const repoName = async ($: EngineInterface): Promise<string> => {
57 const cwd = await $.session.cwd()
58 try {
59 const { exitCode, stdout } = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { timeoutMs: 5000 })
60 const root = exitCode === 0 ? stdout.trim() : ''
61 return (root || cwd).split('/').pop() ?? cwd
62 } catch {
63 return cwd.split('/').pop() ?? cwd
64 }
65}
66
67const formatList = (nowList: Todo[], laterList: Todo[]) => {
68 const lines = (list: Todo[]) => (list.length === 0 ? [' (なし)'] : list.map(todo => ` - ${todo.id}: ${todo.text}`))
69 return ['今やる:', ...lines(nowList), 'あとで:', ...lines(laterList)].join('\n')
70}
71
72const findIn = async ($: EngineInterface, id: string): Promise<TodoWhen | undefined> => {
73 if ((await read($, now)).some(todo => todo.id === id)) return 'now'
74 if ((await loadLater($)).some(todo => todo.id === id)) return 'later'
75 return undefined
76}
77
78const remove = async ($: EngineInterface, id: string) => {
79 await update($, now, list => list.filter(todo => todo.id !== id))
80 await changeLater($, list => list.filter(todo => todo.id !== id))
81}
82
83// 同じミリ秒に複数登録されても id が重ならないよう、連番を足す
84let sequence = 0
85const newId = async ($: EngineInterface) => {
86 sequence += 1
87 return `${(await $.clock.now()).toString(36)}${sequence.toString(36)}`
88}
89
90export const register: Register = on => {
91 on('session.start', async ($, e, next) => {
92 const name = await repoName($)
93 await update($, repo, () => name)
94 await syncLater($)
95 $.clock.every(SYNC_MS, () => void syncLater($))
96
97 await $.tool.register({
98 name: 'add',
99 description:
100 'ユーザーにやってもらうことを、プロンプト上の帯に登録して常に見えるようにする。' +
101 '確認・動作確認・判断・外部の連絡待ちなど、ユーザーが何かしないと作業が進まないときは、返答で頼むのと同時に必ず when=now で登録する。' +
102 '今すぐではないがあとでユーザーがやること(後回しにした作業、期日のある対応など)は when=later で登録する(全セッション・全リポジトリ共通で残る)。' +
103 'text は「誰が・何をしたら再開できるか」がわかる1文にする。機密情報(APIキー、顧客名、社内URL)は書かない。',
104 inputSchema: {
105 type: 'object',
106 properties: {
107 text: { type: 'string', description: 'ユーザーにやってもらうこと(1文)' },
108 when: WHEN_SCHEMA,
109 },
110 required: ['text', 'when'],
111 },
112 isDeferred: false,
113 })
114 await $.tool.register({
115 name: 'done',
116 description:
117 '帯に登録した項目を完了にして消す。ユーザーがやったと言った、または結果から済んだとわかったときに呼ぶ。' +
118 'ユーザーが返事をしただけで、頼んだことが済んでいなければ消さない。',
119 inputSchema: {
120 type: 'object',
121 properties: { id: { type: 'string', description: 'add / list が返した項目の id' } },
122 required: ['id'],
123 },
124 isDeferred: false,
125 })
126 await $.tool.register({
127 name: 'move',
128 description: '項目を「今やる」と「あとで」の間で移す。ユーザーが後回しにすると言ったときや、あとでの項目に今取りかかるときに呼ぶ。',
129 inputSchema: {
130 type: 'object',
131 properties: {
132 id: { type: 'string', description: 'add / list が返した項目の id' },
133 to: WHEN_SCHEMA,
134 },
135 required: ['id', 'to'],
136 },
137 isDeferred: false,
138 })
139 await $.tool.register({
140 name: 'list',
141 description: '帯に登録されている「今やる」と「あとで」の項目を id 付きで返す。',
142 inputSchema: { type: 'object', properties: {} },
143 isDeferred: false,
144 })
145
146 return next(e)
147 })
148
149 // ツールの引数は e.input ではなく e の直下に載る(tool / tool_use_id / agentId は予約キー)
150 on('tool.call', { tool: TOOL_ADD }, async ($, e) => {
151 const { text, when } = e as unknown as { text: string; when: TodoWhen }
152 const todo: Todo = {
153 id: await newId($),
154 text: text.trim(),
155 repo: await repoName($),
156 createdAt: new Date(await $.clock.now()).toISOString(),
157 }
158 if (when === 'later') {
159 await changeLater($, list => [...list, todo])
160 } else {
161 await update($, now, list => [...list, todo])
162 }
163 return { result: `${when === 'later' ? 'あとで' : '今やる'}に登録しました(id: ${todo.id})。` }
164 })
165
166 on('tool.call', { tool: TOOL_DONE }, async ($, e) => {
167 const { id } = e as unknown as { id: string }
168 if ((await findIn($, id)) === undefined) {
169 return { result: `id ${id} の項目はありません。\n${formatList(await read($, now), await loadLater($))}` }
170 }
171 await remove($, id)
172 return { result: `${id} を完了にしました。` }
173 })
174
175 on('tool.call', { tool: TOOL_MOVE }, async ($, e) => {
176 const { id, to } = e as unknown as { id: string; to: TodoWhen }
177 const from = await findIn($, id)
178 if (from === undefined) {
179 return { result: `id ${id} の項目はありません。\n${formatList(await read($, now), await loadLater($))}` }
180 }
181 if (from === to) {
182 return { result: `${id} はすでに${to === 'later' ? 'あとで' : '今やる'}にあります。` }
183 }
184 const todo = (from === 'now' ? await read($, now) : await loadLater($)).find(one => one.id === id)
185 if (todo === undefined) {
186 return { result: `id ${id} の項目はありません。` }
187 }
188 await remove($, id)
189 if (to === 'later') {
190 await changeLater($, list => [...list, todo])
191 } else {
192 await update($, now, list => [...list, todo])
193 }
194 return { result: `${id} を${to === 'later' ? 'あとで' : '今やる'}に移しました。` }
195 })
196
197 on('tool.call', { tool: TOOL_LIST }, async $ => {
198 await syncLater($)
199 return { result: formatList(await read($, now), await read($, later)) }
200 })
201
202 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
203 const nowList = await read($, now)
204 const laterList = await read($, later)
205 if (e.props.hasSurvey || (nowList.length === 0 && laterList.length === 0)) {
206 return next(e)
207 }
208
209 const { Box, Button, Text } = $.ui.resolve(e)
210 const isOpen = await read($, isLaterOpen)
211 const isOthersShown = await read($, isOthersOpen)
212 const currentRepo = await read($, repo)
213 const mine = laterList.filter(todo => todo.repo === currentRepo)
214 const others = laterList.filter(todo => todo.repo !== currentRepo)
215 const row = (todo: Todo, actions: 'now' | 'later' | 'other') => (
216 <Box key={`row-${todo.id}`} flexDirection="row">
217 <Button key={`done-${todo.id}`} label="✓" onPress={() => remove($, todo.id)} />
218 <Text> </Text>
219 {actions !== 'now' && (
220 <Button
221 key={`up-${todo.id}`}
222 label="今やる"
223 onPress={async () => {
224 await remove($, todo.id)
225 await update($, now, list => [...list, todo])
226 }}
227 />
228 )}
229 <Text wrap="truncate-end">
230 {actions !== 'now' ? ' ' : ''}
231 {actions === 'other' && <Text dimColor>{todo.repo} </Text>}
232 {todo.text}
233 </Text>
234 </Box>
235 )
236
237 return (
238 <Box flexDirection="column">
239 {nowList.length > 0 && (
240 <Text bold color={NOW_COLOR}>
241 ▶ Your turn ({nowList.length})
242 </Text>
243 )}
244 {nowList.map(todo => row(todo, 'now'))}
245 {laterList.length > 0 && (
246 <Box flexDirection="row">
247 <Button
248 key="toggle-later"
249 plain
250 onPress={() => update($, isLaterOpen, open => !open)}
251 >
252 <Text dimColor>
253 {isOpen ? '▼' : '▶'} Later ({laterList.length})
254 </Text>
255 </Button>
256 </Box>
257 )}
258 {isOpen && mine.map(todo => row(todo, 'later'))}
259 {isOpen && others.length > 0 && (
260 <Box flexDirection="row">
261 <Button key="toggle-others" plain onPress={() => update($, isOthersOpen, open => !open)}>
262 <Text dimColor>
263 {' '}
264 {isOthersShown ? '▼' : '▶'} 他のリポジトリ ({others.length})
265 </Text>
266 </Button>
267 </Box>
268 )}
269 {isOpen && isOthersShown && others.map(todo => row(todo, 'other'))}
270 </Box>
271 )
272 })
273}
274