No description.

CLI to manage and install AI agent skills to various platforms.
pnpx @kurokeita/add-skill --help
List available skills in the repository:
pnpx @kurokeita/add-skill list skill
List locally installed skills:
pnpx @kurokeita/add-skill list skill --local
# Pick a scope non-interactively (default: global)
pnpx @kurokeita/add-skill list --local --scope project
pnpx @kurokeita/add-skill list --local --scope both
Starts an interactive session to select and install skills. Supports live search/filtering as you type.
pnpx @kurokeita/add-skill add
# Install at project scope (writes under the current directory's
# `.<platform>/...` paths instead of `~/...`). Project scope is
# refused at $HOME or outside a git work tree.
pnpx @kurokeita/add-skill add --scope project
Interactively select installed skills to remove. Supports live search/filtering as you type.
pnpx @kurokeita/add-skill remove skill
# Pick a scope non-interactively
pnpx @kurokeita/add-skill remove skill --scope project
pnpx @kurokeita/add-skill remove skill --scope both
Install a skill directly from a GitHub URL.
pnpx @kurokeita/add-skill add skill https://github.com/owner/repo/tree/main/skills/skill-name
add copies every skill into a single canonical directory:
~/.agents/skills<project-root>/.agents/skillsAfter copying, add can optionally wire each platform you select: it installs a session-start hook (under .agents/hooks/) and registers it in that platform's config. On each new session the hook symlinks the canonical .agents/skills entries back into the platform's own skills directory, so every tool sees the same set of skills from one source of truth.
A skill can also ship Claude Code hooks in a hooks/ dir. hooks/hooks.json holds the hooks object of .claude/settings.json, and ${HOOKS_DIR} in its commands resolves to .claude/hooks. When add installs a skill that has this manifest, it offers to copy the other files in hooks/ to .claude/hooks/ and merge the entries into .claude/settings.json (global or project, matching the install scope). git-commit uses this to install its commit-gate.py hook.
list and remove operate on the canonical .agents/skills dir. Removing a skill also prunes any platform symlink left pointing at it.
The tables below show where each platform loads skills from. These are the symlink destinations the session-start hook creates.
| Platform | Skills Path |
|---|---|
| Antigravity | ~/.gemini/antigravity/global_skills |
| Claude Code | ~/.claude/skills |
| Codex | ~/.codex/skills |
| Gemini CLI | ~/.gemini/skills |
| GitHub Copilot | ~/.copilot/skills |
| Windsurf | ~/.codeium/windsurf/skills |
When you pick --scope project, the canonical .agents/ dir and the symlink destinations live under the current working directory instead of ~. The mapping below uses <project-root> to mean process.cwd() (no git-toplevel relocation: a monorepo subdirectory installs into that subdirectory, not the repo root).
| Platform | Skills Path |
|---|---|
| Antigravity | <project-root>/.gemini/antigravity/skills |
| Claude Code | <project-root>/.claude/skills |
| Codex | <project-root>/.codex/skills |
| Gemini CLI | <project-root>/.gemini/skills |
| GitHub Copilot | <project-root>/.copilot/skills |
| Windsurf | <project-root>/.codeium/windsurf/skills |
Project scope is refused when cwd equals your home directory or cwd is not inside a git work tree. When refused interactively, you can fall back to global scope without losing your already-selected skills and platforms.
git clone https://github.com/kurokeita/ai-agent.git
cd ai-agent
pnpm install
pnpm dev
pnpm lint
pnpm format
pnpm build
This project is licensed under the GNU General Public License v3.0.
hooks/register.tsx 414 lines1import type { EngineInterface, Register } from "claude-code"
2import { atom, read, update } from "claude-code"
3
4import type { CheckState, Pr, Step } from "../types"
5import {
6 parseSummary,
7 platformOf,
8 prNumbersIn,
9 repoNameOf,
10 SUMMARY_SYSTEM,
11 transcriptOf,
12} from "./discover"
13import { fetchAzure, fetchGitHub, git, type Run } from "./fetch"
14
15const PANE = "work-pane"
16const branches = atom({ plugin: "work-pane", key: "branches" } as const, [])
17const work = atom({ plugin: "work-pane", key: "work" } as const, null)
18const isFetching = atom(
19 { plugin: "work-pane", key: "isFetching" } as const,
20 false,
21)
22const summary = atom({ plugin: "work-pane", key: "summary" } as const, null)
23const isSummarizing = atom(
24 { plugin: "work-pane", key: "isSummarizing" } as const,
25 false,
26)
27const collapsed = atom({ plugin: "work-pane", key: "collapsed" } as const, [])
28
29let isFetchRunning = false
30let isAutoOpened = false
31// Which conversation this process shows, and whether a prompt was sent in it here.
32let watchedId = ""
33let hasPromptedHere = false
34let isClearPending = false
35let sessionStartedAt = Date.now()
36
37const runner =
38 ($: EngineInterface): Run =>
39 (argv) =>
40 $.process
41 .run(argv, { timeoutMs: 60_000 })
42 .catch((error) => ({ exitCode: 1, stdout: "", stderr: String(error) }))
43
44const isPaneOpen = async ($: EngineInterface) =>
45 (await $.ui.panes()).some((pane) => pane.id === PANE)
46
47// The branches this session sat on at the end of a turn, newest first.
48async function noteBranch($: EngineInterface): Promise<string> {
49 const branch = await git(runner($), ["branch", "--show-current"])
50 if (branch)
51 await update($, branches, (list) =>
52 [branch, ...list.filter((b) => b !== branch)].slice(0, 10),
53 )
54 return branch
55}
56
57// The current branch, plus the branches this session committed to. A branch the
58// session only started on or passed through has no commits since it began.
59async function trackedBranches(
60 $: EngineInterface,
61 current: string,
62): Promise<string[]> {
63 const since = `--since=${new Date(sessionStartedAt).toISOString()}`
64 const tracked = current ? [current] : []
65 for (const branch of await read($, branches)) {
66 if (branch === current) continue
67 if (await git(runner($), ["log", "-1", "--format=%H", since, branch]))
68 tracked.push(branch)
69 }
70 return tracked
71}
72
73async function refreshWork($: EngineInterface) {
74 if (isFetchRunning) return
75 isFetchRunning = true
76 await update($, isFetching, () => true)
77 try {
78 const remote = await git(runner($), ["remote", "get-url", "origin"])
79 const platform = platformOf(remote)
80 if (!platform) {
81 await update($, work, () => ({
82 prs: [],
83 items: [],
84 fetchedAt: Date.now(),
85 isUnsupported: true,
86 }))
87 return
88 }
89 const current = await noteBranch($)
90 const prNumbers = prNumbersIn(
91 await $.session.messages(),
92 platform,
93 repoNameOf(remote),
94 )
95 const fetch = platform === "github" ? fetchGitHub : fetchAzure
96 const result = await fetch(
97 runner($),
98 await trackedBranches($, current),
99 prNumbers,
100 )
101 await update($, work, () => result)
102 } finally {
103 isFetchRunning = false
104 await update($, isFetching, () => false)
105 }
106}
107
108async function summarize($: EngineInterface) {
109 if (await read($, isSummarizing)) return
110 await update($, isSummarizing, () => true)
111 try {
112 const prompt = transcriptOf(await $.session.messages())
113 // The API refuses an empty user message with a 400.
114 if (!prompt.trim()) {
115 await update($, summary, () => ({
116 error: "Nothing to summarize yet. Send a prompt first.",
117 at: Date.now(),
118 }))
119 return
120 }
121 const reply = await $.model.complete({
122 model: "haiku",
123 system: SUMMARY_SYSTEM,
124 prompt,
125 maxTokens: 1500,
126 })
127 const parsed = reply.isAnswered ? parseSummary(reply.text) : null
128 const error = reply.isAnswered
129 ? "The summary came back unreadable."
130 : reply.reason === "api-error"
131 ? `Summary failed: api-error ${reply.status ?? ""} ${reply.error}`
132 : `Summary failed: ${reply.reason}`
133 await update($, summary, () =>
134 parsed ? { ...parsed, at: Date.now() } : { error, at: Date.now() },
135 )
136 } finally {
137 await update($, isSummarizing, () => false)
138 }
139}
140
141// Summarizes once when the pane shows and no summary exists yet, or the last try failed.
142async function summarizeIfMissing($: EngineInterface) {
143 const current = await read($, summary)
144 if (!current || "error" in current) await summarize($)
145}
146
147// A conversation is resumed when it has turns no prompt of this process made:
148// --resume and --continue load them before session.start, while the picker and
149// an in-session /resume load them later, under a new session id.
150// A resumed conversation opens the pane once, whether or not it has a PR or item.
151async function checkResumed($: EngineInterface) {
152 const id = await $.session.id()
153 if (id !== watchedId) {
154 watchedId = id
155 // A /clear starts its conversation here, though the transcript's /clear row counts as a turn.
156 hasPromptedHere = isClearPending
157 isClearPending = false
158 isAutoOpened = false
159 // Another conversation now: its branches start over from here.
160 sessionStartedAt = Date.now()
161 await update($, branches, () => [])
162 }
163 if (isAutoOpened || hasPromptedHere || (await $.session.turns()) === 0) return
164 isAutoOpened = true
165 void refreshWork($)
166 // No focus: the prompt keeps the keyboard. Ctrl+X Tab or a click focuses it to scroll.
167 await $.ui.open({ id: PANE, title: "Work", columns: 64 })
168 await summarizeIfMissing($)
169}
170
171function ago(at: number): string {
172 const s = Math.max(0, Math.round((Date.now() - at) / 1000))
173 if (s < 60) return `${s}s ago`
174 if (s < 3600) return `${Math.round(s / 60)}m ago`
175 return `${Math.round(s / 3600)}h ago`
176}
177
178const STATE_COLOR: Record<string, string> = {
179 open: "success",
180 draft: "subtle",
181 merged: "merged",
182 closed: "error",
183 done: "success",
184 resolved: "success",
185 removed: "subtle",
186 "to do": "subtle",
187 new: "subtle",
188 active: "suggestion",
189 committed: "suggestion",
190 "in progress": "suggestion",
191}
192const CHECKS: Record<CheckState, { text: string; color: string }> = {
193 passing: { text: "✓ checks", color: "success" },
194 failing: { text: "✗ checks", color: "error" },
195 pending: { text: "● checks", color: "warning" },
196 none: { text: "no checks", color: "subtle" },
197}
198const STEP: Record<Step["status"], { mark: string; color: string }> = {
199 done: { mark: "✓", color: "success" },
200 current: { mark: "●", color: "warning" },
201 todo: { mark: "○", color: "subtle" },
202}
203
204export const register: Register = (on) => {
205 on("session.start", async ($, e, next) => {
206 await $.command.register({
207 name: "work",
208 description: "Show this session's PRs, work items and summary in a pane",
209 })
210 void checkResumed($)
211 $.clock.every(5_000, () => checkResumed($))
212 $.clock.every(60_000, async () => {
213 if (await isPaneOpen($)) await refreshWork($)
214 })
215
216 return next(e)
217 })
218
219 on("turn.complete", async ($, e, next) => {
220 const result = await next(e)
221 if (e.agentId) return result
222 // A main-conversation turn is when the session pushes branches and opens PRs,
223 // and moves its goal and steps on.
224 void (async () => {
225 await noteBranch($)
226 if (await isPaneOpen($)) await Promise.all([refreshWork($), summarize($)])
227 })()
228
229 return result
230 })
231
232 on("session.end", async (_$, e, next) => {
233 if (e.reason === "clear") isClearPending = true
234
235 return next(e)
236 })
237
238 on("prompt.submit", async (_$, e, next) => {
239 hasPromptedHere = true
240
241 return next(e)
242 })
243
244 on("command.run", { command: "work" }, async ($) => {
245 // Opened by hand: auto-open has nothing left to do, so turns refresh the pane.
246 isAutoOpened = true
247 void refreshWork($)
248 await $.ui.open({
249 id: PANE,
250 title: "Work",
251 columns: 64,
252 focus: true,
253 closeOnEscape: true,
254 })
255 void summarizeIfMissing($)
256
257 return {
258 text: "Work pane opened. Up/Down or PgUp/PgDn scroll, Esc closes.",
259 }
260 })
261
262 on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
263 const { Box, Text, Link, Button } = $.ui.resolve(e)
264 const current = await read($, work)
265 const fetching = await read($, isFetching)
266 const sum = await read($, summary)
267 const summarizing = await read($, isSummarizing)
268 const shut = await read($, collapsed)
269
270 const toggle = (pr: Pr) =>
271 update($, collapsed, (list) =>
272 list.includes(pr.number)
273 ? list.filter((n) => n !== pr.number)
274 : [...list, pr.number],
275 )
276 const prs = current?.prs ?? []
277 const items = current?.items ?? []
278 const hasWork = !current?.isUnsupported
279
280 return (
281 <Box flexDirection="column" rowGap={1}>
282 <Box flexDirection="column">
283 <Text>
284 <Text bold color="planMode">
285 Summary
286 </Text>
287 <Text dimColor>
288 {summarizing ? " updating…" : sum ? ` ${ago(sum.at)}` : ""}
289 </Text>
290 </Text>
291 {!sum && (
292 <Text dimColor>Press Refresh to summarize this session.</Text>
293 )}
294 {sum && "error" in sum && <Text color="error">{sum.error}</Text>}
295 {sum && "goal" in sum && <Text>{sum.goal}</Text>}
296 </Box>
297
298 {sum && "steps" in sum && sum.steps.length > 0 && (
299 <Box flexDirection="column">
300 <Text bold color="planMode">
301 Steps
302 </Text>
303 {sum.steps.map((step) => (
304 <Text
305 wrap="truncate-end"
306 color={
307 step.status === "todo" ? undefined : STEP[step.status].color
308 }
309 dimColor={step.status === "todo"}
310 bold={step.status === "current"}
311 >
312 {STEP[step.status].mark} {step.text}
313 </Text>
314 ))}
315 </Box>
316 )}
317
318 {hasWork && (
319 <Box flexDirection="column">
320 <Text>
321 <Text bold color="planMode">
322 Pull requests
323 </Text>
324 <Text dimColor>
325 {" "}
326 {prs.length}
327 {fetching ? " · updating…" : ""}
328 </Text>
329 </Text>
330 {current?.error && <Text color="error">{current.error}</Text>}
331 {prs.length === 0 && !current?.error && (
332 <Text dimColor>None found for this session yet.</Text>
333 )}
334 {prs.map((pr) => (
335 <Box flexDirection="column">
336 <Box flexDirection="row" columnGap={1}>
337 <Button
338 key={`toggle-${pr.number}`}
339 plain
340 label={shut.includes(pr.number) ? "▸" : "▾"}
341 onPress={() => void toggle(pr)}
342 />
343 <Text wrap="truncate-end">
344 <Link href={pr.url}>#{pr.number}</Link>
345 <Text color={STATE_COLOR[pr.state] ?? "text"}>
346 {" "}
347 {pr.state}
348 </Text>
349 <Text dimColor> [{pr.branch}]</Text> {pr.title}
350 </Text>
351 </Box>
352 {!shut.includes(pr.number) && (
353 <Text>
354 {" "}
355 {pr.review && (
356 <Text
357 color={pr.review === "approved" ? "success" : "warning"}
358 >
359 {pr.review}{" "}
360 </Text>
361 )}
362 <Text color={CHECKS[pr.checks].color}>
363 {CHECKS[pr.checks].text}
364 </Text>
365 <Text dimColor> {pr.comments} comments</Text>
366 </Text>
367 )}
368 </Box>
369 ))}
370 </Box>
371 )}
372
373 {hasWork && (
374 <Box flexDirection="column">
375 <Text>
376 <Text bold color="planMode">
377 Work items
378 </Text>
379 <Text dimColor> {items.length}</Text>
380 </Text>
381 {items.length === 0 && <Text dimColor>None linked yet.</Text>}
382 {items.map((item) => (
383 <Text wrap="truncate-end">
384 <Link href={item.url}>#{item.id}</Link>
385 <Text color={STATE_COLOR[item.state] ?? "text"}>
386 {" "}
387 {item.state}
388 </Text>{" "}
389 {item.title}
390 </Text>
391 ))}
392 </Box>
393 )}
394
395 <Box flexDirection="row" columnGap={1}>
396 <Button
397 key="refresh"
398 label="Refresh"
399 hotkey="r"
400 onPress={() => void Promise.all([refreshWork($), summarize($)])}
401 />
402 {hasWork && (
403 <Text dimColor>
404 {current
405 ? `PRs updated ${ago(current.fetchedAt)}`
406 : "PRs not fetched yet"}
407 </Text>
408 )}
409 </Box>
410 </Box>
411 )
412 })
413}
414hooks/discover.ts 143 lines1import type { SessionMessage } from "claude-code"
2
3import type { CheckState, Step } from "../types"
4
5export type Platform = "github" | "azure"
6
7export function platformOf(remote: string): Platform | null {
8 if (/github\.com[:/]/.test(remote)) return "github"
9 if (/dev\.azure\.com[:/]|\.visualstudio\.com\//.test(remote)) return "azure"
10 return null
11}
12
13export function repoNameOf(remote: string): string {
14 return (
15 remote
16 .trim()
17 .replace(/\.git$/, "")
18 .split(/[/:]/)
19 .pop() ?? ""
20 ).toLowerCase()
21}
22
23function decoded(name: string): string {
24 try {
25 return decodeURIComponent(name).toLowerCase()
26 } catch {
27 return name.toLowerCase()
28 }
29}
30
31// PR links anywhere in the conversation: a command's output (gh pr create and
32// gh pr edit print the URL), the model's own text, or a link the person pasted.
33// Only links into this repository count, since the fetch runs against it.
34export function prNumbersIn(
35 messages: readonly SessionMessage[],
36 platform: Platform,
37 repo: string,
38): number[] {
39 const pattern =
40 platform === "github"
41 ? /github\.com\/[\w.-]+\/([\w.-]+)\/pull\/(\d{1,9})/g
42 : /_git\/([^/\s?#"']+)\/pullrequest\/(\d{1,9})/gi
43 const found = new Set<number>()
44 for (const message of messages) {
45 const texts = [message.text]
46 for (const use of message.toolUses)
47 texts.push(JSON.stringify(use.input), use.text ?? "")
48 for (const result of message.toolResults ?? []) texts.push(result.text)
49 for (const text of texts) {
50 for (const match of text.matchAll(pattern)) {
51 if (decoded(match[1] ?? "") === repo) found.add(Number(match[2]))
52 }
53 }
54 }
55 return [...found]
56}
57
58// Items a branch without a PR points at: a 3-9 digit segment of its name (plus
59// gh issue develop's "<n>-slug"), then AB#N or #N in its own commits. 9 digits
60// at most, as both APIs take 32-bit ids and one bad literal fails the query.
61export function itemRefs(
62 platform: Platform,
63 branch: string,
64 commitLog: string,
65): number[] {
66 const refs: string[] = []
67 const lead =
68 platform === "github" ? /^(\d{1,9})-/.exec(branch)?.[1] : undefined
69 if (lead) refs.push(lead)
70 refs.push(
71 ...branch.split(/[^A-Za-z0-9]+/).filter((part) => /^\d{3,9}$/.test(part)),
72 )
73 const pattern = platform === "github" ? /#(\d{1,9})/g : /AB#(\d{1,9})/g
74 for (const match of commitLog.matchAll(pattern)) refs.push(match[1] ?? "")
75 return [...new Set(refs.filter(Boolean).map(Number))].slice(0, 10)
76}
77
78export function githubChecks(rollup: string | null | undefined): CheckState {
79 if (rollup === "SUCCESS") return "passing"
80 if (rollup === "FAILURE" || rollup === "ERROR") return "failing"
81 if (rollup === "PENDING" || rollup === "EXPECTED") return "pending"
82 return "none"
83}
84
85export function azureChecks(statuses: readonly string[]): CheckState {
86 if (statuses.some((s) => s === "rejected" || s === "broken")) return "failing"
87 if (statuses.some((s) => s === "running" || s === "queued")) return "pending"
88 if (statuses.some((s) => s === "approved")) return "passing"
89 return "none"
90}
91
92export function azureReview(votes: readonly number[]): string {
93 if (votes.includes(-10)) return "rejected"
94 if (votes.includes(-5)) return "waiting for author"
95 if (votes.some((vote) => vote >= 5)) return "approved"
96 return ""
97}
98
99export const SUMMARY_SYSTEM = `You summarize a coding session for a side panel.
100Reply with JSON only, no prose and no code fence:
101{"goal": "<2-4 sentences: what the session is trying to achieve and where it stands now>",
102 "steps": [{"text": "<one short line>", "status": "done" | "current" | "todo"}]}
103Steps run in order, at most 12, and at most one is "current".`
104
105// The newest part of the conversation that fits the model's budget.
106export function transcriptOf(messages: readonly SessionMessage[]): string {
107 const lines = messages.map((m) => {
108 const tools = m.toolUses.map(
109 (use) => `[${use.tool}] ${JSON.stringify(use.input).slice(0, 200)}`,
110 )
111 return `${m.role}: ${[m.text.slice(0, 2000), ...tools].filter(Boolean).join("\n")}`
112 })
113 return lines.join("\n\n").slice(-60_000)
114}
115
116export function parseSummary(
117 text: string,
118): { goal: string; steps: Step[] } | null {
119 const start = text.indexOf("{")
120 const end = text.lastIndexOf("}")
121 if (start < 0 || end < start) return null
122 try {
123 const value = JSON.parse(text.slice(start, end + 1)) as {
124 goal?: unknown
125 steps?: unknown
126 }
127 if (typeof value.goal !== "string" || !Array.isArray(value.steps))
128 return null
129 const steps: Step[] = []
130 for (const step of value.steps as { text?: unknown; status?: unknown }[]) {
131 if (typeof step?.text !== "string") continue
132 const status =
133 step.status === "done" || step.status === "current"
134 ? step.status
135 : "todo"
136 steps.push({ text: step.text, status })
137 }
138 return { goal: value.goal, steps }
139 } catch {
140 return null
141 }
142}
143hooks/fetch.ts 328 lines1import type { Item, Pr, Work } from "../types"
2import {
3 azureChecks,
4 azureReview,
5 githubChecks,
6 itemRefs,
7 type Platform,
8} from "./discover"
9
10// Runs a command; register.tsx supplies it, since only that file may use $.
11export type Run = (
12 argv: string[],
13) => Promise<{ exitCode: number; stdout: string; stderr: string }>
14
15export async function git(run: Run, args: string[]): Promise<string> {
16 const { exitCode, stdout } = await run(["git", ...args])
17 return exitCode === 0 ? stdout.trim() : ""
18}
19
20function firstLine(text: string): string {
21 return text.trim().split("\n")[0] ?? ""
22}
23
24async function refsByBranch(
25 run: Run,
26 platform: Platform,
27 branches: readonly string[],
28) {
29 const base = await git(run, [
30 "symbolic-ref",
31 "--short",
32 "refs/remotes/origin/HEAD",
33 ])
34 const refs = new Map<string, number[]>()
35 for (const branch of branches) {
36 const log = base
37 ? await git(run, ["log", "--format=%B", `${base}..${branch}`])
38 : ""
39 refs.set(branch, itemRefs(platform, branch, log))
40 }
41 return refs
42}
43
44const PR_FIELDS = `number title url state isDraft reviewDecision headRefName
45 comments { totalCount } reviewThreads { totalCount }
46 commits(last: 1) { nodes { commit { statusCheckRollup { state } } } }
47 closingIssuesReferences(first: 10) { nodes { number title url state } }`
48
49type GhIssue = { number: number; title: string; url: string; state: string }
50type GhPr = {
51 number: number
52 title: string
53 url: string
54 state: string
55 isDraft: boolean
56 reviewDecision: string | null
57 headRefName: string
58 comments: { totalCount: number }
59 reviewThreads: { totalCount: number }
60 commits: {
61 nodes: { commit: { statusCheckRollup: { state: string } | null } }[]
62 }
63 closingIssuesReferences: { nodes: GhIssue[] }
64}
65
66const ghItem = (issue: GhIssue): Item => ({
67 id: issue.number,
68 url: issue.url,
69 title: issue.title,
70 state: issue.state.toLowerCase(),
71})
72
73// One GraphQL call: each branch's newest PR, each PR the conversation linked,
74// and every item ref, as aliases. Branch names go in as variables, never into
75// the query text. gh exits 1 when an alias does not resolve yet still prints
76// the rest, so success is judged by data.repository.
77export async function fetchGitHub(
78 run: Run,
79 branches: readonly string[],
80 prNumbers: readonly number[],
81): Promise<Work> {
82 const refs = await refsByBranch(run, "github", branches)
83 const vars: string[] = []
84 const fields: string[] = []
85 const args: string[] = []
86 branches.forEach((branch, i) => {
87 vars.push(`, $b${i}: String!`)
88 args.push("-f", `b${i}=${branch}`)
89 fields.push(`b${i}: pullRequests(headRefName: $b${i}, first: 1, states: [OPEN, MERGED, CLOSED],
90 orderBy: {field: CREATED_AT, direction: DESC}) { nodes { ...P } }`)
91 })
92 for (const n of prNumbers)
93 fields.push(`p${n}: pullRequest(number: ${n}) { ...P }`)
94 for (const n of new Set([...refs.values()].flat())) {
95 fields.push(
96 `i${n}: issueOrPullRequest(number: ${n}) { ... on Issue { number title url state } }`,
97 )
98 }
99 if (fields.length === 0) return { prs: [], items: [], fetchedAt: Date.now() }
100 const query = `query($owner: String!, $name: String!${vars.join("")}) {
101 repository(owner: $owner, name: $name) { ${fields.join("\n")} }
102 } fragment P on PullRequest { ${PR_FIELDS} }`
103 const out = await run([
104 "gh",
105 "api",
106 "graphql",
107 "-F",
108 "owner={owner}",
109 "-F",
110 "name={repo}",
111 ...args,
112 "-f",
113 `query=${query}`,
114 ])
115 let repo: Record<string, unknown> | undefined
116 try {
117 repo = (
118 JSON.parse(out.stdout) as {
119 data?: { repository?: Record<string, unknown> }
120 }
121 ).data?.repository
122 } catch {
123 repo = undefined
124 }
125 if (!repo)
126 return {
127 prs: [],
128 items: [],
129 fetchedAt: Date.now(),
130 error: `gh: ${firstLine(out.stderr) || "no data"}`,
131 }
132
133 const prs = new Map<number, Pr>()
134 const items = new Map<number, Item>()
135 const addPr = (pr: GhPr) => {
136 prs.set(pr.number, {
137 number: pr.number,
138 url: pr.url,
139 title: pr.title,
140 branch: pr.headRefName,
141 state:
142 pr.isDraft && pr.state === "OPEN" ? "draft" : pr.state.toLowerCase(),
143 review: (pr.reviewDecision ?? "").toLowerCase().replace(/_/g, " "),
144 checks: githubChecks(
145 pr.commits.nodes[0]?.commit.statusCheckRollup?.state,
146 ),
147 comments: pr.comments.totalCount + pr.reviewThreads.totalCount,
148 })
149 for (const issue of pr.closingIssuesReferences.nodes)
150 items.set(issue.number, ghItem(issue))
151 }
152 branches.forEach((branch, i) => {
153 const pr = (repo[`b${i}`] as { nodes: GhPr[] } | null)?.nodes[0]
154 if (pr) {
155 addPr(pr)
156 return
157 }
158 for (const n of refs.get(branch) ?? []) {
159 const issue = repo[`i${n}`] as GhIssue | null
160 if (issue?.number) items.set(issue.number, ghItem(issue))
161 }
162 })
163 for (const n of prNumbers) {
164 const pr = repo[`p${n}`] as GhPr | null
165 if (pr) addPr(pr)
166 }
167 return {
168 prs: [...prs.values()],
169 items: [...items.values()],
170 fetchedAt: Date.now(),
171 }
172}
173
174async function az(run: Run, args: string[]): Promise<unknown> {
175 const out = await run(["az", ...args, "--only-show-errors", "-o", "json"])
176 if (out.exitCode !== 0) return null
177 try {
178 return JSON.parse(out.stdout)
179 } catch {
180 return null
181 }
182}
183
184type AzPr = {
185 pullRequestId: number
186 title: string
187 status: string
188 isDraft: boolean
189 url: string
190 sourceRefName: string
191 reviewers?: { vote: number }[]
192 repository: { id: string; project: { id: string } }
193}
194type AzWorkItem = { id: number; url: string; fields: Record<string, string> }
195
196const AZ_STATE: Record<string, string> = {
197 active: "open",
198 completed: "merged",
199 abandoned: "closed",
200}
201
202const azItem = (w: AzWorkItem): Item => ({
203 id: w.id,
204 url: w.url.replace("/_apis/wit/workItems/", "/_workitems/edit/"),
205 title: w.fields["System.Title"] ?? "",
206 state: (w.fields["System.State"] ?? "").toLowerCase(),
207})
208
209// One az call per lookup, run in parallel: each branch's newest PR, each linked
210// PR, then each PR's work items, blocking policies (its checks) and threads.
211export async function fetchAzure(
212 run: Run,
213 branches: readonly string[],
214 prNumbers: readonly number[],
215): Promise<Work> {
216 const refs = await refsByBranch(run, "azure", branches)
217 const byBranch = await Promise.all(
218 branches.map((b) =>
219 az(run, [
220 "repos",
221 "pr",
222 "list",
223 "--source-branch",
224 b,
225 "--status",
226 "all",
227 "--top",
228 "1",
229 ]),
230 ),
231 )
232 const byNumber = await Promise.all(
233 prNumbers.map((n) => az(run, ["repos", "pr", "show", "--id", String(n)])),
234 )
235 if (
236 [...byBranch, ...byNumber].length > 0 &&
237 [...byBranch, ...byNumber].every((r) => r === null)
238 ) {
239 return {
240 prs: [],
241 items: [],
242 fetchedAt: Date.now(),
243 error: "az: every lookup failed (logged in?)",
244 }
245 }
246
247 const raw = new Map<number, AzPr>()
248 const refsWithoutPr: number[] = []
249 byBranch.forEach((list, i) => {
250 const pr = (list as AzPr[] | null)?.[0]
251 if (pr) raw.set(pr.pullRequestId, pr)
252 else refsWithoutPr.push(...(refs.get(branches[i] ?? "") ?? []))
253 })
254 for (const pr of byNumber as (AzPr | null)[])
255 if (pr) raw.set(pr.pullRequestId, pr)
256
257 const items = new Map<number, Item>()
258 const prs = await Promise.all(
259 [...raw.values()].map(async (pr): Promise<Pr> => {
260 const id = String(pr.pullRequestId)
261 const [workItems, policies, threads] = await Promise.all([
262 az(run, ["repos", "pr", "work-item", "list", "--id", id]),
263 az(run, ["repos", "pr", "policy", "list", "--id", id]),
264 az(run, [
265 "devops",
266 "invoke",
267 "--area",
268 "git",
269 "--resource",
270 "pullRequestThreads",
271 "--api-version",
272 "7.1",
273 "--route-parameters",
274 `project=${pr.repository.project.id}`,
275 `repositoryId=${pr.repository.id}`,
276 `pullRequestId=${id}`,
277 ]),
278 ])
279 for (const w of (workItems as AzWorkItem[] | null) ?? [])
280 items.set(w.id, azItem(w))
281 const blocking = (
282 (policies as
283 | { status: string; configuration: { isBlocking: boolean } }[]
284 | null) ?? []
285 )
286 .filter((p) => p.configuration.isBlocking)
287 .map((p) => p.status)
288 const comments = (
289 (
290 threads as {
291 value?: {
292 isDeleted: boolean
293 comments: { commentType: string }[]
294 }[]
295 } | null
296 )?.value ?? []
297 ).filter(
298 (t) => !t.isDeleted && t.comments[0]?.commentType === "text",
299 ).length
300 return {
301 number: pr.pullRequestId,
302 url: pr.url
303 .replace("/_apis/git/repositories/", "/_git/")
304 .replace("/pullRequests/", "/pullrequest/"),
305 title: pr.title,
306 branch: pr.sourceRefName.replace(/^refs\/heads\//, ""),
307 state:
308 pr.isDraft && pr.status === "active"
309 ? "draft"
310 : (AZ_STATE[pr.status] ?? pr.status),
311 review: azureReview((pr.reviewers ?? []).map((r) => r.vote)),
312 checks: azureChecks(blocking),
313 comments,
314 }
315 }),
316 )
317
318 const missing = [...new Set(refsWithoutPr)].filter((n) => !items.has(n))
319 if (missing.length > 0) {
320 const wiql = `SELECT [System.Id], [System.Title], [System.State] FROM WorkItems WHERE [System.Id] IN (${missing.join(", ")})`
321 for (const w of ((await az(run, ["boards", "query", "--wiql", wiql])) as
322 | AzWorkItem[]
323 | null) ?? [])
324 items.set(w.id, azItem(w))
325 }
326 return { prs, items: [...items.values()], fetchedAt: Date.now() }
327}
328types/index.d.ts 37 lines1export type CheckState = "passing" | "failing" | "pending" | "none"
2export type Pr = {
3 number: number
4 url: string
5 title: string
6 branch: string
7 state: string
8 review: string
9 checks: CheckState
10 comments: number
11}
12export type Item = { id: number; url: string; title: string; state: string }
13export type Work = {
14 prs: Pr[]
15 items: Item[]
16 fetchedAt: number
17 error?: string
18 isUnsupported?: boolean
19}
20export type Step = { text: string; status: "done" | "current" | "todo" }
21export type Summary =
22 | { goal: string; steps: Step[]; at: number }
23 | { error: string; at: number }
24
25declare module "claude-code" {
26 interface PluginState {
27 "work-pane": {
28 branches: string[]
29 work: Work | null
30 isFetching: boolean
31 summary: Summary | null
32 isSummarizing: boolean
33 collapsed: number[]
34 }
35 }
36}
37