pi-crew 0.9.68 → 0.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (253) hide show
  1. package/CHANGELOG.md +222 -0
  2. package/NOTICE.md +21 -0
  3. package/README.md +44 -2
  4. package/agents/analyst.md +1 -1
  5. package/agents/cold-verifier.md +3 -1
  6. package/agents/critic.md +1 -1
  7. package/agents/executor.md +1 -1
  8. package/agents/explorer.md +1 -1
  9. package/agents/planner.md +1 -1
  10. package/agents/reviewer.md +1 -1
  11. package/agents/security-reviewer.md +1 -1
  12. package/agents/test-engineer.md +1 -1
  13. package/agents/verifier.md +1 -1
  14. package/agents/writer.md +1 -1
  15. package/dist/index.mjs +68113 -60774
  16. package/docs/README.md +2 -0
  17. package/docs/actions-reference.md +31 -0
  18. package/docs/commands-reference.md +17 -6
  19. package/docs/resource-formats.md +13 -0
  20. package/package.json +4 -2
  21. package/schema.json +503 -91
  22. package/scripts/resource-sampler.mjs +36 -2
  23. package/skills/requirements-to-task-packet/SKILL.md +26 -0
  24. package/skills/widget-rendering/SKILL.md +7 -7
  25. package/src/agents/agent-config.ts +2 -1
  26. package/src/agents/discover-agents.ts +23 -14
  27. package/src/config/config-merge.ts +183 -0
  28. package/src/config/config-validation.ts +687 -0
  29. package/src/config/config.ts +22 -864
  30. package/src/config/defaults.ts +43 -2
  31. package/src/config/drift-detector.ts +1 -1
  32. package/src/config/env-vars.ts +691 -0
  33. package/src/config/role-tools.ts +11 -9
  34. package/src/config/sanitize-project-config.ts +172 -0
  35. package/src/config/types.ts +49 -1
  36. package/src/extension/async-notifier.ts +25 -2
  37. package/src/extension/crew-cleanup.ts +13 -0
  38. package/src/extension/crew-vibes/config.ts +2 -1
  39. package/src/extension/crew-vibes/footer.ts +19 -0
  40. package/src/extension/crew-vibes/index.ts +11 -1
  41. package/src/extension/plan-orchestrate.ts +132 -0
  42. package/src/extension/register.ts +8 -0
  43. package/src/extension/registration/command-registration.ts +1 -0
  44. package/src/extension/registration/commands/dashboard.ts +158 -0
  45. package/src/extension/registration/commands/index.ts +35 -0
  46. package/src/extension/registration/commands/manage.ts +303 -0
  47. package/src/extension/registration/commands/run.ts +228 -0
  48. package/src/extension/registration/commands/shared.ts +639 -0
  49. package/src/extension/registration/commands/status.ts +60 -0
  50. package/src/extension/registration/commands.ts +13 -1224
  51. package/src/extension/registration/foreground-run-controller.ts +10 -2
  52. package/src/extension/registration/lifecycle-handlers.ts +178 -17
  53. package/src/extension/registration/runtime-cleanup.ts +23 -5
  54. package/src/extension/registration/subagent-tools.ts +218 -9
  55. package/src/extension/registration/team-tool.ts +5 -1
  56. package/src/extension/registration/ui.ts +5 -4
  57. package/src/extension/rpc-hmac.ts +5 -3
  58. package/src/extension/team-tool/api/heartbeat.ts +47 -10
  59. package/src/extension/team-tool/api/plan-approval.ts +9 -0
  60. package/src/extension/team-tool/api/task-claims.ts +109 -40
  61. package/src/extension/team-tool/cancel.ts +84 -50
  62. package/src/extension/team-tool/dispatch/index.ts +1 -0
  63. package/src/extension/team-tool/dispatch/run.ts +4 -1
  64. package/src/extension/team-tool/doctor.ts +103 -1
  65. package/src/extension/team-tool/orchestrate.ts +66 -1
  66. package/src/extension/team-tool/plans.ts +192 -0
  67. package/src/extension/team-tool/respond.ts +197 -65
  68. package/src/extension/team-tool/run-deadline.ts +35 -3
  69. package/src/extension/team-tool/run-intent.ts +63 -0
  70. package/src/extension/team-tool/run.ts +74 -20
  71. package/src/extension/team-tool/status.ts +84 -26
  72. package/src/extension/team-tool.ts +11 -2
  73. package/src/hooks/registry.ts +1 -6
  74. package/src/i18n.ts +9 -0
  75. package/src/prompt/prompt-runtime.ts +521 -2
  76. package/src/prompt/worker-events-channel.ts +173 -0
  77. package/src/runtime/README.md +8 -8
  78. package/src/runtime/async-runner.ts +7 -3
  79. package/src/runtime/background-runner.ts +42 -14
  80. package/src/runtime/broker/broker-issuer.ts +9 -2
  81. package/src/runtime/broker/crew-broker-tokens.ts +43 -6
  82. package/src/runtime/broker/crew-broker.ts +838 -10
  83. package/src/runtime/broker/wait-status-cache.ts +157 -0
  84. package/src/runtime/budget-enforcement.ts +281 -0
  85. package/src/runtime/child-pi/child-pi-constants.ts +8 -0
  86. package/src/runtime/child-pi/child-pi-spawn.ts +60 -14
  87. package/src/runtime/child-pi/child-pi-streams.ts +21 -1
  88. package/src/runtime/child-pi/child-pi-timers.ts +324 -0
  89. package/src/runtime/child-pi/child-pi.ts +97 -201
  90. package/src/runtime/child-pi/mock-fixtures.ts +16 -2
  91. package/src/runtime/crew-agent-records.ts +259 -14
  92. package/src/runtime/delegate-spawn.ts +148 -0
  93. package/src/runtime/detached-run-results.ts +90 -0
  94. package/src/runtime/deterministic-ast.ts +2 -1
  95. package/src/runtime/dispatch-batch.ts +945 -0
  96. package/src/runtime/finalize-run.ts +557 -0
  97. package/src/runtime/goal-workflow/adaptive-plan.ts +116 -15
  98. package/src/runtime/goal-workflow/dynamic-workflow-runner.ts +8 -3
  99. package/src/runtime/goal-workflow/goal-state-store.ts +1 -1
  100. package/src/runtime/group-join.ts +11 -125
  101. package/src/runtime/live-session/live-session-runtime.ts +26 -1
  102. package/src/runtime/merge-gate.ts +32 -10
  103. package/src/runtime/merge-loop.ts +130 -0
  104. package/src/runtime/model/model-budget-summary.ts +53 -0
  105. package/src/runtime/model/model-fallback.ts +36 -2
  106. package/src/runtime/model/pi-args.ts +10 -0
  107. package/src/runtime/model/provider-extensions.ts +10 -0
  108. package/src/runtime/orphan-worker-registry.ts +1 -1
  109. package/src/runtime/output/output-validator.ts +45 -0
  110. package/src/runtime/parent-guard.ts +3 -1
  111. package/src/runtime/peer-dep.ts +2 -1
  112. package/src/runtime/per-write-validator.ts +0 -5
  113. package/src/runtime/pi-spawn.ts +61 -15
  114. package/src/runtime/plan-approval.ts +125 -0
  115. package/src/runtime/plan-replan.ts +151 -0
  116. package/src/runtime/process-status.ts +16 -1
  117. package/src/runtime/recovery/checkpoint.ts +0 -18
  118. package/src/runtime/recovery/crash-recovery.ts +111 -46
  119. package/src/runtime/run-tracker.ts +77 -10
  120. package/src/runtime/scheduler-context.ts +98 -0
  121. package/src/runtime/scheduling/coalesce-tasks.ts +5 -0
  122. package/src/runtime/scheduling/global-worker-cap.ts +2 -1
  123. package/src/runtime/scheduling/nested-slots.ts +70 -0
  124. package/src/runtime/scheduling/run-coalesced-task-group.ts +64 -13
  125. package/src/runtime/scheduling/task-graph-scheduler.ts +0 -10
  126. package/src/runtime/settings-store.ts +219 -0
  127. package/src/runtime/spawn-policy.ts +217 -0
  128. package/src/runtime/stale-reconciler.ts +87 -6
  129. package/src/runtime/subagent-manager.ts +25 -1
  130. package/src/runtime/task-output-context.ts +230 -9
  131. package/src/runtime/task-packet.ts +23 -1
  132. package/src/runtime/task-runner/child-executor.ts +106 -7
  133. package/src/runtime/task-runner/post-execution.ts +125 -1
  134. package/src/runtime/task-runner/pre-execution.ts +39 -1
  135. package/src/runtime/task-runner/prompt-builder.ts +51 -1
  136. package/src/runtime/task-runner/retrieval-orchestrator.ts +72 -18
  137. package/src/runtime/task-runner/spec-evidence.ts +403 -0
  138. package/src/runtime/task-runner/state-helpers.ts +26 -24
  139. package/src/runtime/task-runner.ts +11 -0
  140. package/src/runtime/team-runner.ts +132 -1673
  141. package/src/runtime/verification/spec-sandbox.ts +255 -0
  142. package/src/runtime/verification/verification-gates.ts +3 -2
  143. package/src/runtime/verification/verification-worktree.ts +2 -1
  144. package/src/runtime/workflow-phase-advance.ts +100 -0
  145. package/src/runtime/workspace-tree.ts +9 -0
  146. package/src/schema/config-schema.ts +66 -26
  147. package/src/schema/sensitive-config-paths.ts +64 -0
  148. package/src/schema/team-tool-schema.ts +13 -3
  149. package/src/state/README.md +4 -10
  150. package/src/state/atomic-write.ts +20 -3
  151. package/src/state/contracts.ts +38 -0
  152. package/src/state/coordination/mailbox.ts +12 -2
  153. package/src/state/event-log/cursor.ts +223 -0
  154. package/src/state/event-log/event-log-rotation.ts +12 -4
  155. package/src/state/event-log/event-log.ts +152 -369
  156. package/src/state/event-log/sequence-cache.ts +373 -0
  157. package/src/state/event-log/worker-atomic-writer.ts +2 -1
  158. package/src/state/stores/active-run-registry.ts +3 -2
  159. package/src/state/stores/manifest-io.ts +237 -0
  160. package/src/state/stores/ownership-map.ts +162 -0
  161. package/src/state/stores/plan-store.ts +241 -0
  162. package/src/state/stores/run-cache.ts +0 -90
  163. package/src/state/stores/spec-store.ts +189 -0
  164. package/src/state/stores/state-store.ts +139 -232
  165. package/src/state/types.ts +199 -0
  166. package/src/ui/dashboard-panes/plan-pane.ts +136 -0
  167. package/src/ui/dashboard-panes/progress-pane.ts +6 -0
  168. package/src/ui/dashboard-panes/transcript-pane.ts +31 -0
  169. package/src/ui/dock-footer.ts +49 -0
  170. package/src/ui/heartbeat-aggregator.ts +9 -1
  171. package/src/ui/inline-panel/agent-pane.ts +375 -0
  172. package/src/ui/inline-panel/agent-transcript.ts +338 -0
  173. package/src/ui/inline-panel/agent-view-overlay.ts +225 -0
  174. package/src/ui/inline-panel/crew-editor.ts +192 -0
  175. package/src/ui/inline-panel/index.ts +290 -0
  176. package/src/ui/inline-panel/panel-rows.ts +37 -0
  177. package/src/ui/inline-panel/panel-selection.ts +157 -0
  178. package/src/ui/inline-panel/panel-store.ts +111 -0
  179. package/src/ui/inline-panel/view-session-store.ts +36 -0
  180. package/src/ui/keybinding-map.ts +54 -13
  181. package/src/ui/pi-ui-compat.ts +9 -0
  182. package/src/ui/powerbar-publisher.ts +52 -1
  183. package/src/ui/run-dashboard.ts +31 -5
  184. package/src/ui/run-snapshot-cache.ts +57 -30
  185. package/src/ui/snapshot-types.ts +6 -1
  186. package/src/ui/widget/index.ts +176 -22
  187. package/src/ui/widget/task-list.ts +198 -0
  188. package/src/ui/widget/widget-formatters.ts +240 -4
  189. package/src/ui/widget/widget-renderer.ts +243 -38
  190. package/src/ui/widget/widget-types.ts +11 -0
  191. package/src/utils/child-process-shield.ts +106 -0
  192. package/src/utils/file-coalescer.ts +0 -4
  193. package/src/utils/fs-errno.ts +66 -0
  194. package/src/utils/fs-watch.ts +1 -1
  195. package/src/utils/internal-error.ts +3 -1
  196. package/src/utils/paths.ts +11 -3
  197. package/src/utils/redaction.ts +7 -0
  198. package/src/utils/safe-abort.ts +45 -0
  199. package/src/utils/task-name-generator.ts +1 -8
  200. package/src/workflows/discover-workflows.ts +20 -2
  201. package/src/workflows/validate-workflow.ts +7 -1
  202. package/src/workflows/workflow-config.ts +17 -0
  203. package/src/workflows/workflow-serializer.ts +3 -0
  204. package/src/worktree/worktree-manager.ts +22 -0
  205. package/workflows/default.workflow.md +36 -26
  206. package/workflows/strict-fast-fix.workflow.md +26 -0
  207. package/src/agents/agent-search.ts +0 -98
  208. package/src/benchmark/benchmark-runner.ts +0 -313
  209. package/src/benchmark/feedback-loop.ts +0 -73
  210. package/src/config/resilient-parser.ts +0 -117
  211. package/src/extension/crew-vibes/cat-frames.ts +0 -18
  212. package/src/extension/result-watcher.ts +0 -139
  213. package/src/observability/exporters/prometheus-exporter.ts +0 -54
  214. package/src/observability/metric-retention.ts +0 -64
  215. package/src/runtime/compaction/compaction-summary.ts +0 -278
  216. package/src/runtime/errors/crew-errors.ts +0 -162
  217. package/src/runtime/live-session/intercom-bridge.ts +0 -187
  218. package/src/runtime/loop-gates.ts +0 -128
  219. package/src/runtime/metric-parser.ts +0 -36
  220. package/src/runtime/output/stream-preview.ts +0 -184
  221. package/src/runtime/output/tool-progress.ts +0 -278
  222. package/src/runtime/phase-tracker.ts +0 -385
  223. package/src/runtime/pipeline-runner.ts +0 -523
  224. package/src/runtime/process/process-lifecycle.ts +0 -491
  225. package/src/runtime/recovery/retry-runner.ts +0 -330
  226. package/src/runtime/run-drift.ts +0 -219
  227. package/src/runtime/task-quality.ts +0 -199
  228. package/src/runtime/task-runner/run-projection.ts +0 -128
  229. package/src/runtime/verification/post-checks.ts +0 -142
  230. package/src/state/coordination/schedule.ts +0 -166
  231. package/src/state/event-log/jsonl-writer.ts +0 -115
  232. package/src/state/hook-instinct-bridge.ts +0 -94
  233. package/src/state/hook-integrations.ts +0 -51
  234. package/src/state/session-state-map.ts +0 -51
  235. package/src/state/stores/blob-store.ts +0 -308
  236. package/src/state/stores/instinct-store.ts +0 -275
  237. package/src/state/stores/observation-store.ts +0 -176
  238. package/src/state/tiered-eval.ts +0 -480
  239. package/src/state/types-eval.ts +0 -58
  240. package/src/tools/safe-bash-extension.ts +0 -54
  241. package/src/tools/safe-bash.ts +0 -505
  242. package/src/ui/agent-management-overlay.ts +0 -160
  243. package/src/ui/crew-footer.ts +0 -102
  244. package/src/ui/crew-select-list.ts +0 -114
  245. package/src/ui/dashboard-panes/capability-pane.ts +0 -77
  246. package/src/ui/transcript-entries.ts +0 -256
  247. package/src/utils/conflict-detect.ts +0 -721
  248. package/src/utils/fingerprint.ts +0 -180
  249. package/src/utils/gh-protocol.ts +0 -556
  250. package/src/utils/project-detector.ts +0 -160
  251. package/src/utils/sse-parser.ts +0 -131
  252. package/src/workflows/cost-estimator.ts +0 -34
  253. package/src/workflows/intermediate-store.ts +0 -166
@@ -1,556 +0,0 @@
1
- /**
2
- * gh-protocol.ts — GitHub URL protocol for issue:// and pr:// URLs.
3
- *
4
- * Forked from oh-my-pi packages/coding-agent/src/internal-urls/issue-pr-protocol.ts
5
- * with adaptations for pi-crew's needs (no SQLite cache, no session registry).
6
- *
7
- * URL shapes:
8
- * - `issue://` — list recent issues (repo derived from cwd)
9
- * - `issue://owner/repo` — list issues for repo
10
- * - `issue://123` — single issue (repo from cwd)
11
- * - `issue://owner/repo/123` — fully qualified
12
- * - `issue://owner/repo/123?comments=0` — suppress comments
13
- *
14
- * - `pr://` — list recent PRs (repo derived from cwd)
15
- * - `pr://owner/repo` — list PRs for repo
16
- * - `pr://456` — single PR (repo from cwd)
17
- * - `pr://owner/repo/456` — fully qualified
18
- * - `pr://owner/repo/456/diff` — list changed files
19
- * - `pr://owner/repo/456/diff/all` — full unified diff
20
- *
21
- * Requirements: GitHub CLI (`gh`) installed and authenticated.
22
- * Repo resolution: git remote get-url origin from cwd.
23
- */
24
- import { execFileSync } from "node:child_process";
25
- import { errorMessage } from "./guards.ts";
26
-
27
- /** Resolve the default repo from `git remote get-url origin` in cwd. */
28
- export function resolveDefaultRepo(cwd: string): string {
29
- try {
30
- // FIX (Round 14): Use execFileSync (args as array) instead of execSync
31
- // (single string) so the command is not interpreted by a shell.
32
- const remoteUrl = execFileSync("git", ["remote", "get-url", "origin"], {
33
- cwd,
34
- encoding: "utf-8",
35
- timeout: 10_000,
36
- stdio: ["pipe", "pipe", "pipe"],
37
- }).trim();
38
-
39
- // git@github.com:owner/repo.git or https://github.com/owner/repo.git
40
- const sshMatch = remoteUrl.match(/git@github\.com:([^/]+)\/([^/.]+)/);
41
- if (sshMatch) return `${sshMatch[1]}/${sshMatch[2]}`;
42
-
43
- const httpsMatch = remoteUrl.match(/github\.com\/([^/]+)\/([^/.]+)/);
44
- if (httpsMatch) return `${httpsMatch[1]}/${httpsMatch[2]}`;
45
-
46
- throw new Error(`Could not parse git remote URL: ${remoteUrl}`);
47
- } catch (err) {
48
- const msg = errorMessage(err);
49
- throw new Error(`Failed to resolve default repo from git: ${msg}`);
50
- }
51
- }
52
-
53
- interface ParsedListOptions {
54
- kind: "list";
55
- repo: string;
56
- state: "open" | "closed" | "all";
57
- limit: number;
58
- author?: string;
59
- label?: string;
60
- }
61
-
62
- interface ParsedSingle {
63
- kind: "single";
64
- repo?: string;
65
- number: number;
66
- comments: boolean;
67
- }
68
-
69
- interface ParsedPrDiff {
70
- kind: "pr-diff";
71
- repo?: string;
72
- number: number;
73
- mode: "list" | "all" | "slice";
74
- index?: number;
75
- }
76
-
77
- type Parsed = ParsedListOptions | ParsedSingle | ParsedPrDiff;
78
-
79
- const LIST_LIMIT_DEFAULT = 30;
80
- const LIST_LIMIT_MAX = 100;
81
-
82
- function parsePositiveInt(value: string): number | undefined {
83
- const n = Number.parseInt(value, 10);
84
- return Number.isInteger(n) && n > 0 ? n : undefined;
85
- }
86
-
87
- /** Parse search params for list options. */
88
- function parseListOptions(url: URL, scheme: "issue" | "pr", repo: string): ParsedListOptions {
89
- const allowedStates = scheme === "pr" ? ["open", "closed", "merged", "all"] : ["open", "closed", "all"];
90
- const stateRaw = url.searchParams.get("state");
91
- const state = (stateRaw && (allowedStates as string[]).includes(stateRaw) ? stateRaw : "open") as ParsedListOptions["state"];
92
-
93
- let limit = LIST_LIMIT_DEFAULT;
94
- const limitRaw = url.searchParams.get("limit");
95
- if (limitRaw !== null) {
96
- const parsed = parsePositiveInt(limitRaw);
97
- if (parsed !== undefined) limit = Math.min(parsed, LIST_LIMIT_MAX);
98
- }
99
-
100
- return {
101
- kind: "list",
102
- repo,
103
- state,
104
- limit,
105
- author: url.searchParams.get("author") ?? undefined,
106
- label: url.searchParams.get("label") ?? undefined,
107
- };
108
- }
109
-
110
- /**
111
- * Parse an issue:// or pr:// URL.
112
- *
113
- * Supported shapes:
114
- * - `scheme://` — list default repo
115
- * - `scheme://<number>` — single item, default repo
116
- * - `scheme://owner/repo` — list specific repo
117
- * - `scheme://owner/repo/<number>` — single item, specific repo
118
- * - `scheme://owner/repo/<number>/diff[/all|<N>]` — PR diff (pr:// only)
119
- */
120
- export function parseGitHubUrl(raw: string, scheme: "issue" | "pr"): Parsed {
121
- let url: URL;
122
- try {
123
- // Treat as a URL-like path; prepend scheme if missing
124
- const withScheme = raw.startsWith(`${scheme}://`) ? raw : `${scheme}://${raw}`;
125
- url = new URL(withScheme);
126
- } catch {
127
- throw new Error(
128
- `Invalid ${scheme}:// URL '${raw}'. Expected ${scheme}://, ${scheme}://<number>, ${scheme}://<owner>/<repo>, or ${scheme}://<owner>/<repo>/<number>.`,
129
- );
130
- }
131
-
132
- const host = url.hostname;
133
- const rawPathname = url.pathname;
134
- // Strip leading slash
135
- const stripped = rawPathname.startsWith("/") ? rawPathname.slice(1) : rawPathname;
136
- const pathParts: string[] = stripped !== "" ? stripped.split("/").filter(Boolean) : [];
137
-
138
- // Empty → list default repo
139
- if (!host && pathParts.length === 0) {
140
- return {
141
- kind: "list",
142
- repo: "",
143
- state: "open",
144
- limit: LIST_LIMIT_DEFAULT,
145
- };
146
- }
147
-
148
- // If host looks like a number, treat as single-item shorthand
149
- if (parsePositiveInt(host) !== undefined) {
150
- // pathParts.length === 0 → scheme://N (single item, default repo)
151
- // pathParts[0] === "diff" → scheme://N/diff[/sub] (PR diff, default repo)
152
- if (pathParts.length === 0) {
153
- const commentsParam = url.searchParams.get("comments");
154
- const comments = !(commentsParam === "0" || commentsParam?.toLowerCase() === "false");
155
- return {
156
- kind: "single",
157
- repo: undefined,
158
- number: parsePositiveInt(host)!,
159
- comments,
160
- };
161
- }
162
- if (pathParts[0] === "diff") {
163
- if (scheme !== "pr") throw new Error(`Invalid ${scheme}:// URL. Diff is only available for pr:// URLs.`);
164
- const number = parsePositiveInt(host)!;
165
- const diffParts = pathParts;
166
- if (diffParts.length === 1) {
167
- return {
168
- kind: "pr-diff",
169
- repo: undefined,
170
- number,
171
- mode: "list",
172
- };
173
- }
174
- if (diffParts[1] === "all") {
175
- return {
176
- kind: "pr-diff",
177
- repo: undefined,
178
- number,
179
- mode: "all",
180
- };
181
- }
182
- const idx = parsePositiveInt(diffParts[1]);
183
- if (idx === undefined) {
184
- throw new Error(`Invalid pr:// diff sub-path '${diffParts[1]}'. Use 'all' or a 1-indexed file number.`);
185
- }
186
- return {
187
- kind: "pr-diff",
188
- repo: undefined,
189
- number,
190
- mode: "slice",
191
- index: idx,
192
- };
193
- }
194
- // Numeric host with non-diff path — invalid number
195
- throw new Error(`Invalid ${scheme}:// number: ${host}`);
196
- }
197
-
198
- // Non-numeric host with 0 path parts
199
- if (pathParts.length === 0 && host) {
200
- // If host looks like a domain name (contains dots), it's a partial repo ref
201
- // (scheme://owner.missing-repo). Otherwise, treat as invalid number.
202
- if (!host.includes(".")) {
203
- throw new Error(`Invalid ${scheme}:// number: ${host}`);
204
- }
205
- throw new Error(`Invalid ${scheme}:// URL. Expected ${scheme}://<owner>/<repo> or ${scheme}://<owner>/<repo>/<number>.`);
206
- }
207
-
208
- // scheme://owner/repo → list
209
- if (pathParts.length === 1 && host) {
210
- const repo = `${host}/${pathParts[0]}`;
211
- return parseListOptions(url, scheme, repo);
212
- }
213
-
214
- // scheme://owner/repo/N[/diff[/sub]]]
215
- if (pathParts.length >= 2 && host) {
216
- const repo = `${host}/${pathParts[0]}`;
217
- const numberPart = pathParts[1];
218
-
219
- const num = parsePositiveInt(numberPart);
220
- if (num === undefined) {
221
- throw new Error(`Invalid ${scheme}:// number: ${numberPart ?? "(missing)"}`);
222
- }
223
-
224
- // PR diff path
225
- const diffParts = pathParts.slice(2);
226
- if (diffParts.length > 0) {
227
- if (scheme === "issue") {
228
- throw new Error(
229
- `Invalid issue:// URL. Issue views do not have a diff; use pr://<owner>/<repo>/<n>/diff for pull requests.`,
230
- );
231
- }
232
- if (diffParts[0] !== "diff" || diffParts.length > 2) {
233
- throw new Error(`Invalid pr:// URL. Expected pr://<n>/diff, pr://<n>/diff/all, or pr://<n>/diff/<i>.`);
234
- }
235
- if (diffParts.length === 1) {
236
- return { kind: "pr-diff", repo, number: num, mode: "list" };
237
- }
238
- const sub = diffParts[1] ?? "";
239
- if (sub === "all") {
240
- return { kind: "pr-diff", repo, number: num, mode: "all" };
241
- }
242
- const idx = parsePositiveInt(sub);
243
- if (idx === undefined) {
244
- throw new Error(`Invalid pr:// diff sub-path '${sub}'. Use 'all' or a 1-indexed file number.`);
245
- }
246
- return {
247
- kind: "pr-diff",
248
- repo,
249
- number: num,
250
- mode: "slice",
251
- index: idx,
252
- };
253
- }
254
-
255
- const commentsParam2 = url.searchParams.get("comments");
256
- const comments = !(commentsParam2 === "0" || commentsParam2?.toLowerCase() === "false");
257
- return { kind: "single", repo, number: num, comments };
258
- }
259
-
260
- // scheme://N (numeric in path) — single, default repo
261
- if (pathParts.length === 1 && parsePositiveInt(pathParts[0]) !== undefined) {
262
- const commentsParam3 = url.searchParams.get("comments");
263
- const comments = !(commentsParam3 === "0" || commentsParam3?.toLowerCase() === "false");
264
- return {
265
- kind: "single",
266
- repo: undefined,
267
- number: parsePositiveInt(pathParts[0])!,
268
- comments,
269
- };
270
- }
271
-
272
- // Fallback: unrecognized shape
273
- throw new Error(
274
- `Invalid ${scheme}:// URL. Expected ${scheme}://, ${scheme}://<number>, ${scheme}://<owner>/<repo>, or ${scheme}://<owner>/<repo>/<number>.`,
275
- );
276
- }
277
-
278
- interface GitHubListItem {
279
- number?: number;
280
- title?: string;
281
- state?: string;
282
- stateReason?: string | null;
283
- author?: { login?: string } | null;
284
- labels?: Array<{ name?: string }>;
285
- createdAt?: string;
286
- updatedAt?: string;
287
- url?: string;
288
- isDraft?: boolean;
289
- baseRefName?: string;
290
- headRefName?: string;
291
- }
292
-
293
- function formatListItem(scheme: "issue" | "pr", repo: string, item: GitHubListItem): string {
294
- const num = item.number ?? "?";
295
- const title = item.title ?? "(no title)";
296
- const state = item.state?.toLowerCase() ?? "?";
297
- const author = item.author?.login ?? "?";
298
- const updated = item.updatedAt ?? item.createdAt ?? "";
299
- const draftSuffix = scheme === "pr" && item.isDraft ? " [draft]" : "";
300
- const labels = (item.labels ?? [])
301
- .map((l) => l.name)
302
- .filter(Boolean)
303
- .join(", ");
304
- const labelSuffix = labels ? ` labels: ${labels}` : "";
305
- const itemUrl = num === "?" ? `${scheme}://${repo}` : `${scheme}://${repo}/${num}`;
306
- return `- [${state}${draftSuffix}] #${num} @${author} ${updated}\n ${title}${labelSuffix}\n ${itemUrl}`;
307
- }
308
-
309
- function runGh(cwd: string, args: string[]): string {
310
- try {
311
- return execFileSync("gh", args, {
312
- cwd,
313
- encoding: "utf-8",
314
- timeout: 30_000,
315
- stdio: ["pipe", "pipe", "pipe"],
316
- });
317
- } catch (err) {
318
- const msg = errorMessage(err);
319
- throw new Error(`gh command failed: ${msg}`);
320
- }
321
- }
322
-
323
- function ghJson<T>(cwd: string, args: string[]): T {
324
- const jsonOut = execFileSync("gh", args, {
325
- cwd,
326
- encoding: "utf-8",
327
- timeout: 30_000,
328
- stdio: ["pipe", "pipe", "pipe"],
329
- });
330
- try {
331
- return JSON.parse(jsonOut) as T;
332
- } catch {
333
- throw new Error(`gh JSON parse failed for: ${args.join(" ")}\nOutput: ${jsonOut.slice(0, 200)}`);
334
- }
335
- }
336
-
337
- interface GhResult<T> {
338
- content: string;
339
- notes: string[];
340
- data?: T;
341
- }
342
-
343
- /**
344
- * Execute a parsed GitHub URL and return the result.
345
- *
346
- * @param parsed Parsed URL result from `parseGitHubUrl`
347
- * @param scheme "issue" or "pr"
348
- * @param cwd Working directory for repo resolution
349
- */
350
- export function resolveGitHubUrl(parsed: Parsed, scheme: "issue" | "pr", cwd: string): GhResult<unknown> {
351
- // Resolve repo for list operations
352
- if (parsed.kind === "list") {
353
- const repo = parsed.repo || resolveDefaultRepo(cwd);
354
- const fields =
355
- scheme === "issue"
356
- ? ["number", "title", "state", "stateReason", "author", "labels", "createdAt", "updatedAt", "url"]
357
- : [
358
- "number",
359
- "title",
360
- "state",
361
- "isDraft",
362
- "author",
363
- "baseRefName",
364
- "headRefName",
365
- "labels",
366
- "createdAt",
367
- "updatedAt",
368
- "url",
369
- ];
370
-
371
- const args = [scheme, "list", "--repo", repo, "--state", parsed.state, "--limit", String(parsed.limit), "--json", fields.join(",")];
372
- if (parsed.author) args.push("--author", parsed.author);
373
- if (parsed.label) args.push("--label", parsed.label);
374
-
375
- let items: GitHubListItem[] = [];
376
- try {
377
- items = ghJson<GitHubListItem[]>(cwd, args);
378
- } catch (err) {
379
- const msg = errorMessage(err);
380
- throw new Error(`${scheme}:// listing failed: ${msg}`);
381
- }
382
-
383
- const header = `# ${scheme === "issue" ? "Issues" : "Pull Requests"} in ${repo} (${parsed.state}, up to ${parsed.limit})`;
384
- const body = items.length === 0 ? "_No matches._" : items.map((item) => formatListItem(scheme, repo, item)).join("\n\n");
385
- const footer = `\n\n---\nRead a specific item: \`${scheme}://${repo}/<N>\` (or \`${scheme}://<N>\` for the current repo).`;
386
- return {
387
- content: `${header}\n\n${body}${footer}`,
388
- notes: [`Live listing for ${repo} via gh`],
389
- data: items,
390
- };
391
- }
392
-
393
- // Resolve repo for single items
394
- let repo = parsed.repo;
395
- if (!repo) {
396
- try {
397
- repo = resolveDefaultRepo(cwd);
398
- } catch (err) {
399
- const msg = errorMessage(err);
400
- throw new Error(
401
- `${scheme}://${(parsed as ParsedSingle).number} could not resolve a default repo from cwd '${cwd}': ${msg}\nUse ${scheme}://<owner>/<repo>/${(parsed as ParsedSingle).number} instead.`,
402
- );
403
- }
404
- }
405
-
406
- // PR diff
407
- if (parsed.kind === "pr-diff") {
408
- if (parsed.mode === "all") {
409
- try {
410
- const diff = execFileSync("gh", ["pr", "diff", String(parsed.number), "--repo", repo], {
411
- cwd,
412
- encoding: "utf-8",
413
- timeout: 30_000,
414
- stdio: ["pipe", "pipe", "pipe"],
415
- });
416
- return {
417
- content: diff,
418
- notes: [`Full diff for ${scheme}://${repo}/${parsed.number}`],
419
- };
420
- } catch (err) {
421
- const msg = errorMessage(err);
422
- throw new Error(`pr://${parsed.number}/diff failed: ${msg}`);
423
- }
424
- }
425
-
426
- if (parsed.mode === "list") {
427
- try {
428
- const raw = execFileSync(
429
- "gh",
430
- [
431
- "pr",
432
- "view",
433
- String(parsed.number),
434
- "--repo",
435
- repo,
436
- "--json",
437
- "files",
438
- "--jq",
439
- '.files[] | "(.filename) +(.additions) -(.deletions) [(.status)]"',
440
- ],
441
- {
442
- cwd,
443
- encoding: "utf-8",
444
- timeout: 30_000,
445
- stdio: ["pipe", "pipe", "pipe"],
446
- },
447
- );
448
- const fileLines = raw.split("\n").filter(Boolean);
449
- const header = `# Pull Request Diff: ${repo}#${parsed.number} (${fileLines.length} file${fileLines.length === 1 ? "" : "s"})`;
450
- const body =
451
- fileLines.length === 0
452
- ? "_No file changes._"
453
- : fileLines.map((line, i) => `${i + 1}. ${line}\n pr://${repo}/${parsed.number}/diff/${i + 1}`).join("\n\n");
454
- const footer = `\n\n---\nRead all: \`pr://${repo}/${parsed.number}/diff/all\`. Each file is also available as \`pr://${repo}/${parsed.number}/diff/<i>\`.`;
455
- return {
456
- content: `${header}\n\n${body}${footer}`,
457
- notes: [`File listing for pr://${repo}/${parsed.number}`],
458
- };
459
- } catch (err) {
460
- const msg = errorMessage(err);
461
- throw new Error(`pr://${parsed.number}/diff failed: ${msg}`);
462
- }
463
- }
464
-
465
- if (parsed.mode === "slice" && parsed.index !== undefined) {
466
- try {
467
- const raw = execFileSync(
468
- "gh",
469
- [
470
- "pr",
471
- "view",
472
- String(parsed.number),
473
- "--repo",
474
- repo,
475
- "--json",
476
- "files",
477
- "--jq",
478
- '.files[] | "(.filename) +(.additions) -(.deletions) [(.status)]"',
479
- ],
480
- {
481
- cwd,
482
- encoding: "utf-8",
483
- timeout: 30_000,
484
- stdio: ["pipe", "pipe", "pipe"],
485
- },
486
- );
487
- const fileLines = raw.split("\n").filter(Boolean);
488
- const targetIdx = parsed.index - 1;
489
- if (targetIdx < 0 || targetIdx >= fileLines.length) {
490
- throw new Error(`File index ${parsed.index} out of range (1..${fileLines.length}).`);
491
- }
492
- const fullDiff = execFileSync("gh", ["pr", "diff", String(parsed.number), "--repo", repo], {
493
- cwd,
494
- encoding: "utf-8",
495
- timeout: 30_000,
496
- stdio: ["pipe", "pipe", "pipe"],
497
- });
498
- // Extract the diff for the target file by splitting on "diff --git" headers
499
- const diffBlocks = fullDiff.split(/(?=diff --git )/);
500
- const fileName = fileLines[targetIdx]!.split(" ")[0];
501
- const matched = diffBlocks.find((block) => block.includes(fileName!));
502
- return {
503
- content: matched || `File ${fileName} not found in diff.`,
504
- notes: [`Diff for file ${parsed.index}/${fileLines.length}: ${fileName} in pr://${repo}/${parsed.number}`],
505
- };
506
- } catch (err) {
507
- const msg = errorMessage(err);
508
- throw new Error(`pr://${parsed.number}/diff/${parsed.index} failed: ${msg}`);
509
- }
510
- }
511
- }
512
-
513
- // Single issue/PR
514
- const single = parsed as ParsedSingle;
515
- try {
516
- let content: string;
517
- if (scheme === "issue") {
518
- const args = ["issue", "view", String(single.number), "--repo", repo];
519
- if (!single.comments) args.push("--comments", "false");
520
- content = execFileSync("gh", args, {
521
- cwd,
522
- encoding: "utf-8",
523
- timeout: 30_000,
524
- stdio: ["pipe", "pipe", "pipe"],
525
- });
526
- } else {
527
- const args = ["pr", "view", String(single.number), "--repo", repo];
528
- if (!single.comments) args.push("--comments", "false");
529
- content = execFileSync("gh", args, {
530
- cwd,
531
- encoding: "utf-8",
532
- timeout: 30_000,
533
- stdio: ["pipe", "pipe", "pipe"],
534
- });
535
- // Append diff URL hint
536
- content += `\n\n---\nDiff: pr://${repo}/${single.number}/diff\nFiles: pr://${repo}/${single.number}/diff/list`;
537
- }
538
- return {
539
- content,
540
- notes: [`${scheme}://${repo}/${single.number} via gh`],
541
- };
542
- } catch (err) {
543
- const msg = errorMessage(err);
544
- throw new Error(`${scheme}://${repo}/${single.number} failed: ${msg}`);
545
- }
546
- }
547
-
548
- /**
549
- * Resolve a raw `issue://` or `pr://` URL string.
550
- * Convenience wrapper combining parse + resolve.
551
- */
552
- /** @internal */
553
- function resolveGitHubProtocol(raw: string, scheme: "issue" | "pr", cwd: string): GhResult<unknown> {
554
- const parsed = parseGitHubUrl(raw, scheme);
555
- return resolveGitHubUrl(parsed, scheme, cwd);
556
- }