paseo-plugin-genui 0.0.0-stage → 0.1.0

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 (375) hide show
  1. package/LICENSE +202 -0
  2. package/OVERVIEW.md +21 -0
  3. package/README.md +77 -2
  4. package/assets/fonts/Excalifont-OFL.txt +109 -0
  5. package/assets/fonts/Excalifont-Regular-latin.woff2 +0 -0
  6. package/assets/icon.png +0 -0
  7. package/assets/icon.svg +1 -0
  8. package/assets/screenshot-chat.png +0 -0
  9. package/assets/screenshot-gallery.png +0 -0
  10. package/assets/screenshot-playground.png +0 -0
  11. package/client/components/content.tsx +468 -0
  12. package/client/components/data.tsx +967 -0
  13. package/client/components/dev.tsx +998 -0
  14. package/client/components/diagram.tsx +513 -0
  15. package/client/components/inputs.tsx +994 -0
  16. package/client/components/layout.tsx +239 -0
  17. package/client/components/media.tsx +428 -0
  18. package/client/components/project.tsx +641 -0
  19. package/client/components/widgets.tsx +836 -0
  20. package/client/gallery.tsx +449 -0
  21. package/client/live-ui.tsx +525 -0
  22. package/client/loaders.ts +342 -0
  23. package/client/markdown.tsx +172 -0
  24. package/client/node-renderer.tsx +149 -0
  25. package/client/render.tsx +186 -0
  26. package/client/runtime.ts +103 -0
  27. package/client/settings.tsx +57 -0
  28. package/client/web.ts +186 -0
  29. package/gallery/Acceptance-baseline.ui +1 -0
  30. package/gallery/Acceptance-checklist.ui +14 -0
  31. package/gallery/Acceptance-evidence.ui +9 -0
  32. package/gallery/Acceptance.ui +1 -0
  33. package/gallery/Badge.ui +3 -0
  34. package/gallery/Benchmark-context.ui +8 -0
  35. package/gallery/Benchmark-hyperfine.ui +1 -0
  36. package/gallery/Benchmark-runs-list.ui +9 -0
  37. package/gallery/Benchmark-runs.ui +1 -0
  38. package/gallery/Benchmark-vitest.ui +1 -0
  39. package/gallery/Benchmark.ui +9 -0
  40. package/gallery/Board-bb-tasks.ui +1 -0
  41. package/gallery/Board-gh-issues.ui +1 -0
  42. package/gallery/Board-gh-prs.ui +1 -0
  43. package/gallery/Board.ui +12 -0
  44. package/gallery/Button-destructive.ui +4 -0
  45. package/gallery/Button.ui +5 -0
  46. package/gallery/Calendar.ui +15 -0
  47. package/gallery/CalendarHeatmap-short.ui +11 -0
  48. package/gallery/CalendarHeatmap.ui +4 -0
  49. package/gallery/Callout.ui +4 -0
  50. package/gallery/Card.ui +4 -0
  51. package/gallery/Carousel.ui +8 -0
  52. package/gallery/Changes-paths.ui +1 -0
  53. package/gallery/Changes-uncommitted.ui +1 -0
  54. package/gallery/Changes.ui +1 -0
  55. package/gallery/Chart-area.ui +3 -0
  56. package/gallery/Chart-funnel.ui +3 -0
  57. package/gallery/Chart-heatmap.ui +11 -0
  58. package/gallery/Chart-pie.ui +3 -0
  59. package/gallery/Chart-radar.ui +3 -0
  60. package/gallery/Chart-scatter.ui +4 -0
  61. package/gallery/Chart-stacked.ui +5 -0
  62. package/gallery/Chart.ui +3 -0
  63. package/gallery/Checklist.ui +6 -0
  64. package/gallery/Choice.ui +8 -0
  65. package/gallery/Code.ui +3 -0
  66. package/gallery/Commits-limit.ui +1 -0
  67. package/gallery/Commits.ui +1 -0
  68. package/gallery/Compare-conditions.ui +4 -0
  69. package/gallery/Compare-three.ui +7 -0
  70. package/gallery/Compare.ui +4 -0
  71. package/gallery/Coverage-go.ui +1 -0
  72. package/gallery/Coverage-lcov.ui +1 -0
  73. package/gallery/Coverage-python.ui +1 -0
  74. package/gallery/Coverage.ui +1 -0
  75. package/gallery/DateInput.ui +5 -0
  76. package/gallery/Decision-percent.ui +10 -0
  77. package/gallery/Decision.ui +12 -0
  78. package/gallery/Dependencies-audit.ui +1 -0
  79. package/gallery/Dependencies-both.ui +1 -0
  80. package/gallery/Dependencies-list.ui +7 -0
  81. package/gallery/Dependencies-pip.ui +1 -0
  82. package/gallery/Dependencies-pnpm.ui +1 -0
  83. package/gallery/Dependencies.ui +1 -0
  84. package/gallery/Details.ui +4 -0
  85. package/gallery/Diagram-flow.ui +16 -0
  86. package/gallery/Diagram-sequence.ui +15 -0
  87. package/gallery/Diagram.ui +16 -0
  88. package/gallery/Diff.ui +3 -0
  89. package/gallery/Divider.ui +5 -0
  90. package/gallery/EditableTable.ui +9 -0
  91. package/gallery/Entity-list.ui +6 -0
  92. package/gallery/Entity.ui +8 -0
  93. package/gallery/Environments.ui +1 -0
  94. package/gallery/Estimate-points.ui +6 -0
  95. package/gallery/Estimate.ui +8 -0
  96. package/gallery/File.ui +4 -0
  97. package/gallery/Findings-biome.ui +1 -0
  98. package/gallery/Findings-eslint.ui +1 -0
  99. package/gallery/Findings-oxlint.ui +1 -0
  100. package/gallery/Findings-review.ui +1 -0
  101. package/gallery/Findings-ruff.ui +1 -0
  102. package/gallery/Findings-sarif.ui +1 -0
  103. package/gallery/Findings-ship.ui +11 -0
  104. package/gallery/Findings-tsc.ui +1 -0
  105. package/gallery/Findings.ui +7 -0
  106. package/gallery/Flashcards.ui +3 -0
  107. package/gallery/FollowUps.ui +4 -0
  108. package/gallery/Form.ui +8 -0
  109. package/gallery/Gallery-links.ui +8 -0
  110. package/gallery/Gallery-strip.ui +14 -0
  111. package/gallery/Gallery.ui +10 -0
  112. package/gallery/Gauge.ui +7 -0
  113. package/gallery/Grid.ui +8 -0
  114. package/gallery/Hotspots-photo.ui +8 -0
  115. package/gallery/Hotspots.ui +11 -0
  116. package/gallery/Icon.ui +5 -0
  117. package/gallery/Image.ui +4 -0
  118. package/gallery/ImageSearch-aspects.ui +6 -0
  119. package/gallery/ImageSearch.ui +4 -0
  120. package/gallery/Input.ui +5 -0
  121. package/gallery/Json-api.ui +1 -0
  122. package/gallery/Json.ui +8 -0
  123. package/gallery/KeyValue.ui +3 -0
  124. package/gallery/List-dots.ui +8 -0
  125. package/gallery/List.ui +8 -0
  126. package/gallery/ListEditor.ui +5 -0
  127. package/gallery/Logs-jsonl.ui +1 -0
  128. package/gallery/Logs-lines.ui +11 -0
  129. package/gallery/Logs-python.ui +1 -0
  130. package/gallery/Logs.ui +1 -0
  131. package/gallery/Map-city.ui +8 -0
  132. package/gallery/Map.ui +8 -0
  133. package/gallery/Metric.ui +3 -0
  134. package/gallery/OptionCards-multi.ui +10 -0
  135. package/gallery/OptionCards.ui +10 -0
  136. package/gallery/Pipeline-checks.ui +1 -0
  137. package/gallery/Pipeline-passed.ui +1 -0
  138. package/gallery/Pipeline-running.ui +1 -0
  139. package/gallery/Pipeline-stages.ui +13 -0
  140. package/gallery/Pipeline.ui +1 -0
  141. package/gallery/Plan.ui +9 -0
  142. package/gallery/Progress.ui +4 -0
  143. package/gallery/Provenance-deploy.ui +6 -0
  144. package/gallery/Provenance-no-receipt.ui +1 -0
  145. package/gallery/Provenance.ui +1 -0
  146. package/gallery/PullRequest.ui +1 -0
  147. package/gallery/Quiz.ui +6 -0
  148. package/gallery/Radio.ui +5 -0
  149. package/gallery/Rating.ui +5 -0
  150. package/gallery/Roadmap-sprint.ui +8 -0
  151. package/gallery/Roadmap-year.ui +9 -0
  152. package/gallery/Roadmap.ui +12 -0
  153. package/gallery/Row.ui +3 -0
  154. package/gallery/SegmentedBar-status.ui +8 -0
  155. package/gallery/SegmentedBar.ui +8 -0
  156. package/gallery/Select.ui +5 -0
  157. package/gallery/Slider.ui +7 -0
  158. package/gallery/Snippet.ui +3 -0
  159. package/gallery/Sources-chips.ui +4 -0
  160. package/gallery/Sources.ui +8 -0
  161. package/gallery/Sparkline.ui +6 -0
  162. package/gallery/Stack.ui +7 -0
  163. package/gallery/StackTrace-aggregate.ui +1 -0
  164. package/gallery/StackTrace-browser.ui +1 -0
  165. package/gallery/StackTrace-go.ui +1 -0
  166. package/gallery/StackTrace-java.ui +1 -0
  167. package/gallery/StackTrace-python.ui +1 -0
  168. package/gallery/StackTrace-rust.ui +1 -0
  169. package/gallery/StackTrace.ui +1 -0
  170. package/gallery/Status.ui +9 -0
  171. package/gallery/Stepper.ui +5 -0
  172. package/gallery/Steps.ui +8 -0
  173. package/gallery/Swatches-long-names.ui +4 -0
  174. package/gallery/Swatches-picker.ui +5 -0
  175. package/gallery/Swatches.ui +10 -0
  176. package/gallery/Table.ui +7 -0
  177. package/gallery/Tabs.ui +8 -0
  178. package/gallery/Tests-junit.ui +1 -0
  179. package/gallery/Tests-vitest-junit.ui +1 -0
  180. package/gallery/Tests-vitest.ui +1 -0
  181. package/gallery/Tests.ui +9 -0
  182. package/gallery/Text.ui +4 -0
  183. package/gallery/TextArea.ui +5 -0
  184. package/gallery/Threads-ids.ui +1 -0
  185. package/gallery/Threads.ui +1 -0
  186. package/gallery/Timeline.ui +8 -0
  187. package/gallery/Timer.ui +4 -0
  188. package/gallery/Toggle.ui +5 -0
  189. package/gallery/Transcript-text.ui +1 -0
  190. package/gallery/Transcript-untimed.ui +1 -0
  191. package/gallery/Transcript-whisper.ui +1 -0
  192. package/gallery/Transcript.ui +1 -0
  193. package/gallery/Tree.ui +3 -0
  194. package/gallery/Treemap-du.ui +1 -0
  195. package/gallery/Treemap-esbuild.ui +1 -0
  196. package/gallery/Treemap-tree.ui +7 -0
  197. package/gallery/Treemap.ui +18 -0
  198. package/gallery/Walkthrough.ui +9 -0
  199. package/gallery/Waterfall-har.ui +1 -0
  200. package/gallery/Waterfall-trace.ui +1 -0
  201. package/gallery/Waterfall.ui +11 -0
  202. package/gallery/data/acceptance/coil/viewport-lifecycle.json +25 -0
  203. package/gallery/data/acceptance/coil-gate.json +153 -0
  204. package/gallery/data/acceptance/orbit-baseline.json +163 -0
  205. package/gallery/data/acceptance/shots/gate-cell-opened.png +0 -0
  206. package/gallery/data/acceptance/shots/gate-light.png +0 -0
  207. package/gallery/data/acceptance/shots/gate-phone-dark.png +0 -0
  208. package/gallery/data/activity.json +1 -0
  209. package/gallery/data/bb-tasks-orb.json +420 -0
  210. package/gallery/data/biome.json +229 -0
  211. package/gallery/data/compare/status-after.png +0 -0
  212. package/gallery/data/compare/status-before.png +0 -0
  213. package/gallery/data/compare/status-dark-2x.png +0 -0
  214. package/gallery/data/compare/status-rerender.png +0 -0
  215. package/gallery/data/coverage-py.json +1 -0
  216. package/gallery/data/coverage-summary.json +1 -0
  217. package/gallery/data/coverage.out +23 -0
  218. package/gallery/data/deploys.json +1 -0
  219. package/gallery/data/device-runs.json +285 -0
  220. package/gallery/data/du-node-modules.txt +359 -0
  221. package/gallery/data/esbuild-meta.json +292 -0
  222. package/gallery/data/eslint.json +266 -0
  223. package/gallery/data/eslint.sarif +343 -0
  224. package/gallery/data/findings-review.json +76 -0
  225. package/gallery/data/gh-issues-nextjs.json +293 -0
  226. package/gallery/data/gh-pr-checks.json +272 -0
  227. package/gallery/data/gh-prs-nextjs.json +419 -0
  228. package/gallery/data/gh-run-failed.json +1 -0
  229. package/gallery/data/gh-run-passed.json +1 -0
  230. package/gallery/data/gh-run-running.json +1 -0
  231. package/gallery/data/github-release.json +57 -0
  232. package/gallery/data/hyperfine-startup.json +187 -0
  233. package/gallery/data/lcov.info +234 -0
  234. package/gallery/data/logs/media-sync.log +127 -0
  235. package/gallery/data/logs/thumbnailer.jsonl +17 -0
  236. package/gallery/data/logs/vitest-run.log +89 -0
  237. package/gallery/data/npm-audit.json +672 -0
  238. package/gallery/data/npm-outdated.json +179 -0
  239. package/gallery/data/oxlint.json +156 -0
  240. package/gallery/data/pip-outdated.json +68 -0
  241. package/gallery/data/pnpm-outdated.json +58 -0
  242. package/gallery/data/provenance/devicectl-install.json +35 -0
  243. package/gallery/data/provenance/install-timeout.log +4 -0
  244. package/gallery/data/provenance/iphone-install.json +72 -0
  245. package/gallery/data/provenance/iphone-no-receipt.json +57 -0
  246. package/gallery/data/provenance/live-home.jpg +0 -0
  247. package/gallery/data/provenance/live-probe.txt +10 -0
  248. package/gallery/data/provenance/xcodebuild-2811.log +19 -0
  249. package/gallery/data/provenance/xcodebuild-4712.log +19 -0
  250. package/gallery/data/pytest-junit.xml +64 -0
  251. package/gallery/data/python-org-trace.json +35 -0
  252. package/gallery/data/python-org.har +31 -0
  253. package/gallery/data/retry.ts +13 -0
  254. package/gallery/data/ruff.json +261 -0
  255. package/gallery/data/src/durations.py +63 -0
  256. package/gallery/data/src/json-logic.ts +156 -0
  257. package/gallery/data/src/mapMath.ts +135 -0
  258. package/gallery/data/src/semver/bump.go +73 -0
  259. package/gallery/data/traces/browser-error.json +5 -0
  260. package/gallery/data/traces/go/main.go +27 -0
  261. package/gallery/data/traces/go-panic.txt +16 -0
  262. package/gallery/data/traces/java-caused-by.txt +15 -0
  263. package/gallery/data/traces/node-aggregate.txt +30 -0
  264. package/gallery/data/traces/node-cause.txt +21 -0
  265. package/gallery/data/traces/py/deploy.json +5 -0
  266. package/gallery/data/traces/py/deploy.py +17 -0
  267. package/gallery/data/traces/py/settings.py +19 -0
  268. package/gallery/data/traces/python-chain.txt +30 -0
  269. package/gallery/data/traces/rust/main.rs +11 -0
  270. package/gallery/data/traces/rust-panic.txt +16 -0
  271. package/gallery/data/traces/shop/cart.mjs +19 -0
  272. package/gallery/data/traces/shop/pricing.mjs +12 -0
  273. package/gallery/data/traces/shop/status.mjs +9 -0
  274. package/gallery/data/traces/web/app.js +11 -0
  275. package/gallery/data/traces/web/index.html +1 -0
  276. package/gallery/data/traces/web/search.js +10 -0
  277. package/gallery/data/transcript/call-noisy.wav +0 -0
  278. package/gallery/data/transcript/call.json +362 -0
  279. package/gallery/data/transcript/call.wav +0 -0
  280. package/gallery/data/transcript/mlx-whisper-tiny.en-noisy.json +1 -0
  281. package/gallery/data/transcript/whisper-cpp-base.en-noisy.json +658 -0
  282. package/gallery/data/transcript/whisper-cpp-base.en.json +658 -0
  283. package/gallery/data/transcript/whisper-cpp-base.en.srt +16 -0
  284. package/gallery/data/transcript/whisper-cpp-tiny.en-noisy.json +619 -0
  285. package/gallery/data/tsc.txt +4 -0
  286. package/gallery/data/vitest-bench.json +119 -0
  287. package/gallery/data/vitest-junit.xml +133 -0
  288. package/gallery/data/vitest-report.json +612 -0
  289. package/gallery/images/bell.svg +10 -0
  290. package/gallery/images/bike.svg +47 -0
  291. package/gallery/images/footer-planet.webp +0 -0
  292. package/gallery/images/front-light.svg +13 -0
  293. package/gallery/images/golden-hour.webp +0 -0
  294. package/gallery/images/option-flowers.webp +0 -0
  295. package/gallery/images/option-hilltop.webp +0 -0
  296. package/gallery/images/option-meadow.webp +0 -0
  297. package/gallery/images/option-sky.webp +0 -0
  298. package/gallery/images/u-lock.svg +10 -0
  299. package/index.client.tsx +164 -0
  300. package/index.server.ts +216 -0
  301. package/package.json +50 -4
  302. package/paseo-plugin.json +14 -0
  303. package/server/data-source.ts +407 -0
  304. package/server/project.ts +981 -0
  305. package/server/web/address.ts +57 -0
  306. package/server/web/cache.ts +85 -0
  307. package/server/web/commons.ts +126 -0
  308. package/server/web/geocode.ts +40 -0
  309. package/server/web/image.ts +35 -0
  310. package/server/web/lookups.ts +248 -0
  311. package/server/web/net.ts +210 -0
  312. package/shared/core/acceptance.ts +744 -0
  313. package/shared/core/ast.ts +76 -0
  314. package/shared/core/benchmark.ts +743 -0
  315. package/shared/core/catalog.ts +733 -0
  316. package/shared/core/compare.ts +225 -0
  317. package/shared/core/coverage.ts +456 -0
  318. package/shared/core/data.ts +334 -0
  319. package/shared/core/decisions.ts +527 -0
  320. package/shared/core/dependencies.ts +604 -0
  321. package/shared/core/diagnostics.ts +24 -0
  322. package/shared/core/environments.ts +212 -0
  323. package/shared/core/evaluate.ts +737 -0
  324. package/shared/core/fields.ts +66 -0
  325. package/shared/core/findings.ts +1172 -0
  326. package/shared/core/form.ts +69 -0
  327. package/shared/core/index.ts +44 -0
  328. package/shared/core/junit.ts +252 -0
  329. package/shared/core/lexer.ts +275 -0
  330. package/shared/core/logs.ts +496 -0
  331. package/shared/core/markdown.ts +2374 -0
  332. package/shared/core/parser.ts +355 -0
  333. package/shared/core/perf-units.ts +228 -0
  334. package/shared/core/pipeline.ts +679 -0
  335. package/shared/core/project.ts +472 -0
  336. package/shared/core/provenance.ts +725 -0
  337. package/shared/core/stack-trace.ts +718 -0
  338. package/shared/core/streaming.ts +136 -0
  339. package/shared/core/test-results.ts +562 -0
  340. package/shared/core/thread-activity.ts +203 -0
  341. package/shared/core/tracking.ts +887 -0
  342. package/shared/core/transcript.ts +1364 -0
  343. package/shared/core/treemap.ts +446 -0
  344. package/shared/core/types.ts +70 -0
  345. package/shared/core/validate.ts +574 -0
  346. package/shared/core/waterfall.ts +536 -0
  347. package/shared/diagram/flowchart.ts +205 -0
  348. package/shared/diagram/layout.ts +440 -0
  349. package/shared/diagram/markdown.ts +135 -0
  350. package/shared/diagram/sequence.ts +122 -0
  351. package/shared/diagram/zoom.ts +114 -0
  352. package/shared/fallback.ts +120 -0
  353. package/shared/genui.test.ts +122 -0
  354. package/shared/instructions.ts +144 -0
  355. package/shared/logic/calendarMath.ts +130 -0
  356. package/shared/logic/chartMath.ts +289 -0
  357. package/shared/logic/choose-logic.ts +196 -0
  358. package/shared/logic/compare-logic.ts +270 -0
  359. package/shared/logic/content-model.ts +227 -0
  360. package/shared/logic/environments-logic.ts +53 -0
  361. package/shared/logic/explain-logic.ts +315 -0
  362. package/shared/logic/fieldLogic.ts +138 -0
  363. package/shared/logic/gallery-search.ts +71 -0
  364. package/shared/logic/icons.ts +322 -0
  365. package/shared/logic/json-logic.ts +153 -0
  366. package/shared/logic/mapMath.ts +133 -0
  367. package/shared/logic/project-logic.ts +39 -0
  368. package/shared/logic/references-model.ts +201 -0
  369. package/shared/logic/sketch.ts +165 -0
  370. package/shared/logic/supersession.ts +77 -0
  371. package/shared/logic/values.ts +133 -0
  372. package/shared/logic/widget-logic.ts +163 -0
  373. package/shared/rpc.ts +252 -0
  374. package/shared/segment.ts +81 -0
  375. package/shared/settings.ts +12 -0
@@ -0,0 +1,981 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import type { PaseoApi } from "@getpaseo/client";
4
+ import type {
5
+ EnvironmentDetail,
6
+ EnvironmentDetailResult,
7
+ EnvironmentInfo,
8
+ EnvironmentThread,
9
+ } from "../shared/core/environments";
10
+ import {
11
+ matchesPathFilter,
12
+ MAX_COMMITS,
13
+ parseChangesTarget,
14
+ parsePathFilter,
15
+ type ChangedFile,
16
+ type ChangeKind,
17
+ type ChangesResult,
18
+ type ChangesScope,
19
+ type ChangesTarget,
20
+ type CommitsResult,
21
+ type EnvironmentsResult,
22
+ type FilePatch,
23
+ type MissingThread,
24
+ type PatchesResult,
25
+ type ProjectFailure,
26
+ type ProjectRequest,
27
+ type ProjectResult,
28
+ type PullRequestInfo,
29
+ type PullRequestResult,
30
+ type ThreadDisplayStatus,
31
+ type ThreadInfo,
32
+ type ThreadsResult,
33
+ } from "../shared/core/project";
34
+ import { lastMessage } from "../shared/core/thread-activity";
35
+ import { resolveAgentCwd } from "./data-source";
36
+
37
+ const execFileAsync = promisify(execFile);
38
+
39
+ function failure(reason: ProjectFailure["reason"], message: string): ProjectFailure {
40
+ return { ok: false, reason, message };
41
+ }
42
+
43
+ async function runGit(
44
+ cwd: string,
45
+ args: readonly string[],
46
+ ): Promise<{ ok: true; stdout: string } | { ok: false; error: string }> {
47
+ try {
48
+ const { stdout } = await execFileAsync("git", [...args], {
49
+ cwd,
50
+ maxBuffer: 8 * 1024 * 1024,
51
+ timeout: 10_000,
52
+ });
53
+ return { ok: true, stdout };
54
+ } catch (cause) {
55
+ return { ok: false, error: cause instanceof Error ? cause.message : String(cause) };
56
+ }
57
+ }
58
+
59
+ async function detectGitBranches(cwd: string): Promise<
60
+ | {
61
+ ok: true;
62
+ branch: string | null;
63
+ head: string | null;
64
+ base: string;
65
+ checkout: "branch" | "detached" | "unborn";
66
+ }
67
+ | ProjectFailure
68
+ > {
69
+ const inside = await runGit(cwd, ["rev-parse", "--is-inside-work-tree"]);
70
+ if (!inside.ok || inside.stdout.trim() !== "true") {
71
+ return failure("not-git", "This agent's workspace isn't a git checkout");
72
+ }
73
+ const sym = await runGit(cwd, ["symbolic-ref", "--short", "-q", "HEAD"]);
74
+ const headRes = await runGit(cwd, ["rev-parse", "--verify", "-q", "HEAD"]);
75
+ const head = headRes.ok ? headRes.stdout.trim().slice(0, 7) : null;
76
+ const branch = sym.ok ? sym.stdout.trim() || null : null;
77
+ const checkout = head === null ? "unborn" : branch !== null ? "branch" : "detached";
78
+
79
+ const originHead = await runGit(cwd, ["symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD"]);
80
+ let base = originHead.ok ? originHead.stdout.trim().replace(/^origin\//, "") : "";
81
+ if (!base) {
82
+ const mainExists = await runGit(cwd, ["rev-parse", "--verify", "-q", "main"]);
83
+ base = mainExists.ok ? "main" : "master";
84
+ }
85
+ return { ok: true, branch, head, base, checkout };
86
+ }
87
+
88
+ function mapStatusChar(code: string): ChangeKind {
89
+ switch (code[0]) {
90
+ case "A":
91
+ return "added";
92
+ case "D":
93
+ return "deleted";
94
+ case "R":
95
+ return "renamed";
96
+ case "C":
97
+ return "copied";
98
+ default:
99
+ return "modified";
100
+ }
101
+ }
102
+
103
+ function isSyntheticGalleryAgent(agentId: string): boolean {
104
+ return agentId === "gallery" || agentId.startsWith("thr_");
105
+ }
106
+
107
+ function demoChanges(target: ChangesTarget, filter: readonly string[] | null): ChangesResult {
108
+ const allFiles: ChangedFile[] = [
109
+ {
110
+ path: "src/worker/retry.ts",
111
+ previousPath: null,
112
+ kind: "modified",
113
+ additions: 28,
114
+ deletions: 6,
115
+ untracked: false,
116
+ diff: "inline",
117
+ },
118
+ {
119
+ path: "src/worker/retry.test.ts",
120
+ previousPath: null,
121
+ kind: "added",
122
+ additions: 54,
123
+ deletions: 0,
124
+ untracked: false,
125
+ diff: "inline",
126
+ },
127
+ {
128
+ path: "src/config/limits.ts",
129
+ previousPath: null,
130
+ kind: "modified",
131
+ additions: 4,
132
+ deletions: 2,
133
+ untracked: false,
134
+ diff: "inline",
135
+ },
136
+ ];
137
+ const files = allFiles.filter((file) => matchesPathFilter(file.path, filter));
138
+ const patches: FilePatch[] = [
139
+ {
140
+ path: "src/worker/retry.ts",
141
+ patch: `@@ -14,6 +14,12 @@ export async function scheduleRetry(job: Job, status: number) {\n- const waitMs = Math.min(30_000, 1_000 * 2 ** job.attempt);\n+ const retryAfter = job.headers?.["retry-after"];\n+ const parsed = retryAfter ? Number(retryAfter) * 1_000 : NaN;\n+ const waitMs = Number.isFinite(parsed)\n+ ? Math.min(60_000, Math.max(1_000, parsed))\n+ : Math.min(30_000, 1_000 * 2 ** job.attempt);\n await queue.delay(job.id, waitMs);\n }`,
142
+ truncated: false,
143
+ },
144
+ {
145
+ path: "src/worker/retry.test.ts",
146
+ patch: `@@ -0,0 +1,12 @@\n+import { describe, expect, it } from "vitest";\n+import { scheduleRetry } from "./retry";\n+\n+describe("scheduleRetry", () => {\n+ it("respects Retry-After on 429 responses", async () => {\n+ const delay = await scheduleRetry({ id: "j_1", attempt: 1, headers: { "retry-after": "8" } }, 429);\n+ expect(delay).toBe(8_000);\n+ });\n+});`,
147
+ truncated: false,
148
+ },
149
+ {
150
+ path: "src/config/limits.ts",
151
+ patch: `@@ -4,2 +4,4 @@\n-export const MAX_RETRY_MS = 30_000;\n+export const MAX_RETRY_MS = 60_000;\n+export const MIN_RETRY_MS = 1_000;`,
152
+ truncated: false,
153
+ },
154
+ ];
155
+ const scope: ChangesScope =
156
+ target.kind === "commit"
157
+ ? { kind: "commit", sha: target.sha, subject: "Honour Retry-After on 429" }
158
+ : target.kind === "uncommitted"
159
+ ? { kind: "uncommitted", branch: "feat/retry-after", unborn: false }
160
+ : { kind: "branch", branch: "feat/retry-after", head: "a4f91c2", base: "main", onBase: false };
161
+ return {
162
+ ok: true,
163
+ scope,
164
+ files,
165
+ totalFiles: allFiles.length,
166
+ filter,
167
+ listTruncated: false,
168
+ patches: patches.filter((p) => files.some((f) => f.path === p.path)),
169
+ livePatches: true,
170
+ takenAt: Date.now(),
171
+ stored: false,
172
+ };
173
+ }
174
+
175
+ function demoCommits(): CommitsResult {
176
+ const now = Math.floor(Date.now() / 1000);
177
+ return {
178
+ ok: true,
179
+ branch: "feat/retry-after",
180
+ checkout: "branch",
181
+ head: "a4f91c2",
182
+ base: "main",
183
+ onBase: false,
184
+ ahead: 3,
185
+ behind: 0,
186
+ commits: [
187
+ {
188
+ sha: "a4f91c28b019e4321c98d71a0e92341b87c65120",
189
+ shortSha: "a4f91c2",
190
+ subject: "Cover Retry-After header parsing in worker tests",
191
+ author: "Ada Lovelace",
192
+ authoredAt: now - 900,
193
+ },
194
+ {
195
+ sha: "7b3d08e912a4f50c11e9823a4b5c6d7e8f901234",
196
+ shortSha: "7b3d08e",
197
+ subject: "Honour Retry-After header on 429 responses",
198
+ author: "Ada Lovelace",
199
+ authoredAt: now - 2400,
200
+ },
201
+ {
202
+ sha: "1c8e44a092b3d18f7e6a5c4b3a291807f6e5d4c3",
203
+ shortSha: "1c8e44a",
204
+ subject: "Raise max retry cap to 60s",
205
+ author: "Ada Lovelace",
206
+ authoredAt: now - 5400,
207
+ },
208
+ ],
209
+ commitsTruncated: false,
210
+ takenAt: Date.now(),
211
+ stored: false,
212
+ };
213
+ }
214
+
215
+ function demoPullRequest(): PullRequestResult {
216
+ return {
217
+ ok: true,
218
+ branch: "feat/retry-after",
219
+ pullRequest: {
220
+ number: 142,
221
+ title: "Honour Retry-After on 429 worker responses",
222
+ url: "https://github.com/acme/worker/pull/142",
223
+ state: "open",
224
+ baseRef: "main",
225
+ headRef: "feat/retry-after",
226
+ checks: {
227
+ state: "passing",
228
+ passed: 6,
229
+ failed: 0,
230
+ pending: 0,
231
+ total: 6,
232
+ },
233
+ review: {
234
+ state: "approved",
235
+ requests: 0,
236
+ },
237
+ mergeability: "mergeable",
238
+ attention: "ready_to_merge",
239
+ autoMerge: false,
240
+ inMergeQueue: false,
241
+ updatedAt: Date.now() - 600_000,
242
+ },
243
+ fetchedAt: Date.now(),
244
+ };
245
+ }
246
+
247
+ function demoThreads(ids: readonly string[] | null): ThreadsResult {
248
+ const sample: ThreadInfo[] = [
249
+ {
250
+ found: true,
251
+ id: "thr_worker_tests",
252
+ title: "Verify retry backoff edge cases",
253
+ status: "idle",
254
+ needsInput: false,
255
+ archived: false,
256
+ provider: { id: "claude", name: "Claude Code", logoUrl: null },
257
+ model: "claude-sonnet-4-6",
258
+ reasoning: "high",
259
+ updatedAt: Date.now() - 300_000,
260
+ lastMessage: {
261
+ text: "All 14 retry backoff tests pass, including malformed Retry-After headers.",
262
+ truncated: false,
263
+ },
264
+ pending: null,
265
+ runningWorkers: 0,
266
+ },
267
+ {
268
+ found: true,
269
+ id: "thr_worker_bench",
270
+ title: "Benchmark queue throughput under 429 storms",
271
+ status: "active",
272
+ needsInput: false,
273
+ archived: false,
274
+ provider: { id: "codex", name: "Codex", logoUrl: null },
275
+ model: "gpt-5.4",
276
+ reasoning: "medium",
277
+ updatedAt: Date.now() - 45_000,
278
+ lastMessage: {
279
+ text: "Running hyperfine across 1,000 synthetic 429 jobs...",
280
+ truncated: false,
281
+ },
282
+ pending: null,
283
+ runningWorkers: 1,
284
+ },
285
+ ];
286
+ return {
287
+ ok: true,
288
+ mode: ids === null ? "subthreads" : "ids",
289
+ threads: sample,
290
+ truncated: false,
291
+ fetchedAt: Date.now(),
292
+ };
293
+ }
294
+
295
+ function demoEnvironments(): EnvironmentsResult {
296
+ const now = Date.now();
297
+ const envs: EnvironmentInfo[] = [
298
+ {
299
+ id: "env_main",
300
+ name: "retry-after",
301
+ kind: "managed-worktree",
302
+ provider: "git-worktree",
303
+ path: "/workspace/worker-retry-after",
304
+ branch: "feat/retry-after",
305
+ defaultBranch: "main",
306
+ base: "main",
307
+ git: true,
308
+ life: "ready",
309
+ current: true,
310
+ threads: [
311
+ {
312
+ id: "thr_1",
313
+ title: "Honour Retry-After on 429",
314
+ status: "idle",
315
+ needsInput: false,
316
+ archived: false,
317
+ subthread: false,
318
+ activeAt: now - 120_000,
319
+ },
320
+ ],
321
+ threadCounts: { total: 1, live: 1, running: 0, needsInput: 0 },
322
+ activeAt: now - 120_000,
323
+ updatedAt: now - 120_000,
324
+ detail: {
325
+ ok: true,
326
+ id: "env_main",
327
+ checkout: {
328
+ ok: true,
329
+ branch: "feat/retry-after",
330
+ checkout: "branch",
331
+ head: "a4f91c2",
332
+ defaultBranch: "main",
333
+ base: "main",
334
+ onBase: false,
335
+ ahead: 3,
336
+ behind: 0,
337
+ uncommitted: { files: 3, additions: 86, deletions: 8, complete: true },
338
+ },
339
+ pull: {
340
+ ok: true,
341
+ pullRequest: {
342
+ number: 142,
343
+ title: "Honour Retry-After on 429 worker responses",
344
+ url: "https://github.com/acme/worker/pull/142",
345
+ state: "open",
346
+ baseRef: "main",
347
+ headRef: "feat/retry-after",
348
+ checks: { state: "passing", passed: 6, failed: 0, pending: 0, total: 6 },
349
+ review: { state: "approved", requests: 0 },
350
+ mergeability: "mergeable",
351
+ attention: "ready_to_merge",
352
+ autoMerge: false,
353
+ inMergeQueue: false,
354
+ updatedAt: now - 600_000,
355
+ },
356
+ },
357
+ fetchedAt: now,
358
+ },
359
+ },
360
+ {
361
+ id: "env_checkout",
362
+ name: "main",
363
+ kind: "checkout",
364
+ provider: "project-checkout",
365
+ path: "/workspace/worker",
366
+ branch: "main",
367
+ defaultBranch: "main",
368
+ base: "main",
369
+ git: true,
370
+ life: "ready",
371
+ current: false,
372
+ threads: [],
373
+ threadCounts: { total: 0, live: 0, running: 0, needsInput: 0 },
374
+ activeAt: null,
375
+ updatedAt: now - 3_600_000,
376
+ detail: {
377
+ ok: true,
378
+ id: "env_checkout",
379
+ checkout: {
380
+ ok: true,
381
+ branch: "main",
382
+ checkout: "branch",
383
+ head: "9f12bc4",
384
+ defaultBranch: "main",
385
+ base: "main",
386
+ onBase: true,
387
+ ahead: null,
388
+ behind: null,
389
+ uncommitted: { files: 0, additions: 0, deletions: 0, complete: true },
390
+ },
391
+ pull: null,
392
+ fetchedAt: now,
393
+ },
394
+ },
395
+ ];
396
+ return {
397
+ ok: true,
398
+ environments: envs,
399
+ threadsTruncated: false,
400
+ fetchedAt: now,
401
+ };
402
+ }
403
+
404
+ export async function readProjectChanges(
405
+ paseo: PaseoApi,
406
+ agentId: string,
407
+ rawTarget: string | null,
408
+ rawPaths: readonly string[] | null,
409
+ ): Promise<ChangesResult> {
410
+ const parsedTarget = parseChangesTarget(rawTarget);
411
+ if (!parsedTarget.ok) return failure("invalid", parsedTarget.error);
412
+ const parsedPaths = parsePathFilter(rawPaths);
413
+ if (!parsedPaths.ok) return failure("invalid", parsedPaths.error);
414
+ const target = parsedTarget.value;
415
+ const filter = parsedPaths.value;
416
+
417
+ if (isSyntheticGalleryAgent(agentId)) return demoChanges(target, filter);
418
+
419
+ const cwd = await resolveAgentCwd(paseo, agentId);
420
+ if (!cwd) return demoChanges(target, filter);
421
+
422
+ const gitInfo = await detectGitBranches(cwd);
423
+ if (!gitInfo.ok) return gitInfo;
424
+
425
+ let diffArgs: string[];
426
+ let numstatArgs: string[];
427
+ let scope: ChangesScope;
428
+
429
+ if (target.kind === "commit") {
430
+ const subj = await runGit(cwd, ["show", "-s", "--format=%s", target.sha]);
431
+ scope = {
432
+ kind: "commit",
433
+ sha: target.sha,
434
+ subject: subj.ok ? subj.stdout.trim() || null : null,
435
+ };
436
+ diffArgs = ["show", "--format=", "--unified=3", target.sha];
437
+ numstatArgs = ["show", "--format=", "--numstat", "--find-renames", target.sha];
438
+ } else if (target.kind === "uncommitted" || gitInfo.checkout === "unborn" || gitInfo.branch === gitInfo.base) {
439
+ scope =
440
+ target.kind === "uncommitted" || gitInfo.checkout === "unborn"
441
+ ? { kind: "uncommitted", branch: gitInfo.branch, unborn: gitInfo.checkout === "unborn" }
442
+ : { kind: "branch", branch: gitInfo.branch, head: gitInfo.head, base: gitInfo.base, onBase: true };
443
+ diffArgs = ["diff", "HEAD", "--unified=3"];
444
+ numstatArgs = ["diff", "HEAD", "--numstat", "--find-renames"];
445
+ } else {
446
+ scope = {
447
+ kind: "branch",
448
+ branch: gitInfo.branch,
449
+ head: gitInfo.head,
450
+ base: gitInfo.base,
451
+ onBase: false,
452
+ };
453
+ diffArgs = ["diff", `${gitInfo.base}...HEAD`, "--unified=3"];
454
+ numstatArgs = ["diff", `${gitInfo.base}...HEAD`, "--numstat", "--find-renames"];
455
+ }
456
+
457
+ const [numstatRes, nameStatusRes, patchRes] = await Promise.all([
458
+ runGit(cwd, numstatArgs),
459
+ runGit(cwd, [numstatArgs[0]!, ...numstatArgs.slice(1).map((a) => (a === "--numstat" ? "--name-status" : a))]),
460
+ runGit(cwd, diffArgs),
461
+ ]);
462
+
463
+ if (!numstatRes.ok) return failure("unavailable", numstatRes.error);
464
+
465
+ const kindByPath = new Map<string, { kind: ChangeKind; previousPath: string | null }>();
466
+ if (nameStatusRes.ok) {
467
+ for (const line of nameStatusRes.stdout.split("\n")) {
468
+ if (!line.trim()) continue;
469
+ const parts = line.split("\t");
470
+ const code = parts[0] ?? "M";
471
+ if ((code.startsWith("R") || code.startsWith("C")) && parts.length >= 3) {
472
+ kindByPath.set(parts[2]!, { kind: mapStatusChar(code), previousPath: parts[1]! });
473
+ } else if (parts[1]) {
474
+ kindByPath.set(parts[1], { kind: mapStatusChar(code), previousPath: null });
475
+ }
476
+ }
477
+ }
478
+
479
+ const allFiles: ChangedFile[] = [];
480
+ for (const line of numstatRes.stdout.split("\n")) {
481
+ if (!line.trim()) continue;
482
+ const [addStr, delStr, rawPath] = line.split("\t");
483
+ if (!rawPath) continue;
484
+ const binary = addStr === "-" || delStr === "-";
485
+ const additions = binary ? 0 : Number(addStr) || 0;
486
+ const deletions = binary ? 0 : Number(delStr) || 0;
487
+ const meta = kindByPath.get(rawPath) ?? { kind: "modified" as const, previousPath: null };
488
+ allFiles.push({
489
+ path: rawPath,
490
+ previousPath: meta.previousPath,
491
+ kind: meta.kind,
492
+ additions,
493
+ deletions,
494
+ untracked: false,
495
+ diff: binary ? "binary" : "inline",
496
+ });
497
+ }
498
+
499
+ const files = allFiles.filter(
500
+ (f) => matchesPathFilter(f.path, filter) || (f.previousPath !== null && matchesPathFilter(f.previousPath, filter)),
501
+ );
502
+ const patches = parseUnifiedPatches(patchRes.ok ? patchRes.stdout : "").filter((p) =>
503
+ files.some((f) => f.path === p.path),
504
+ );
505
+
506
+ return {
507
+ ok: true,
508
+ scope,
509
+ files,
510
+ totalFiles: allFiles.length,
511
+ filter,
512
+ listTruncated: false,
513
+ patches,
514
+ livePatches: true,
515
+ takenAt: Date.now(),
516
+ stored: false,
517
+ };
518
+ }
519
+
520
+ function parseUnifiedPatches(rawDiff: string): FilePatch[] {
521
+ const patches: FilePatch[] = [];
522
+ const chunks = rawDiff.split(/^diff --git /m);
523
+ for (const chunk of chunks) {
524
+ if (!chunk.trim()) continue;
525
+ const lines = chunk.split("\n");
526
+ const header = lines[0] ?? "";
527
+ const match = / b\/(.+)$/.exec(header);
528
+ const filePath = match?.[1]?.trim();
529
+ if (!filePath) continue;
530
+ const hunkStart = lines.findIndex((line) => line.startsWith("@@ "));
531
+ if (hunkStart === -1) continue;
532
+ patches.push({
533
+ path: filePath,
534
+ patch: lines.slice(hunkStart).join("\n").trimEnd(),
535
+ truncated: false,
536
+ });
537
+ }
538
+ return patches;
539
+ }
540
+
541
+ export async function readProjectPatches(
542
+ paseo: PaseoApi,
543
+ agentId: string,
544
+ rawTarget: string | null,
545
+ paths: readonly string[],
546
+ ): Promise<PatchesResult> {
547
+ const changes = await readProjectChanges(paseo, agentId, rawTarget, paths);
548
+ if (!changes.ok) return changes;
549
+ return { ok: true, patches: changes.patches };
550
+ }
551
+
552
+ export async function readProjectCommits(paseo: PaseoApi, agentId: string): Promise<CommitsResult> {
553
+ if (isSyntheticGalleryAgent(agentId)) return demoCommits();
554
+ const cwd = await resolveAgentCwd(paseo, agentId);
555
+ if (!cwd) return demoCommits();
556
+
557
+ const gitInfo = await detectGitBranches(cwd);
558
+ if (!gitInfo.ok) return gitInfo;
559
+
560
+ const onBase = gitInfo.branch === gitInfo.base;
561
+ const range = onBase ? `-n ${MAX_COMMITS}` : `${gitInfo.base}..HEAD`;
562
+ const logArgs = onBase
563
+ ? ["log", `-n`, String(MAX_COMMITS), "--format=%H%x09%h%x09%s%x09%an%x09%at"]
564
+ : ["log", range, "--format=%H%x09%h%x09%s%x09%an%x09%at"];
565
+ const logRes = await runGit(cwd, logArgs);
566
+ const commits = (logRes.ok ? logRes.stdout.split("\n") : [])
567
+ .filter((line) => line.trim() !== "")
568
+ .map((line) => {
569
+ const [sha = "", shortSha = "", subject = "", author = "", authoredAtStr = "0"] = line.split("\t");
570
+ return {
571
+ sha,
572
+ shortSha,
573
+ subject,
574
+ author,
575
+ authoredAt: Number(authoredAtStr) || 0,
576
+ };
577
+ });
578
+
579
+ let ahead: number | null = null;
580
+ let behind: number | null = null;
581
+ if (!onBase) {
582
+ const counts = await runGit(cwd, ["rev-list", "--left-right", "--count", `${gitInfo.base}...HEAD`]);
583
+ if (counts.ok) {
584
+ const [bStr, aStr] = counts.stdout.trim().split(/\s+/);
585
+ behind = Number(bStr) || 0;
586
+ ahead = Number(aStr) || 0;
587
+ }
588
+ }
589
+
590
+ return {
591
+ ok: true,
592
+ branch: gitInfo.branch,
593
+ checkout: gitInfo.checkout,
594
+ head: gitInfo.head,
595
+ base: gitInfo.base,
596
+ onBase,
597
+ ahead,
598
+ behind,
599
+ commits: commits.slice(0, MAX_COMMITS),
600
+ commitsTruncated: commits.length > MAX_COMMITS,
601
+ takenAt: Date.now(),
602
+ stored: false,
603
+ };
604
+ }
605
+
606
+ export async function readProjectPullRequest(paseo: PaseoApi, agentId: string): Promise<PullRequestResult> {
607
+ if (isSyntheticGalleryAgent(agentId)) return demoPullRequest();
608
+ const cwd = await resolveAgentCwd(paseo, agentId);
609
+ if (!cwd) return demoPullRequest();
610
+
611
+ const gitInfo = await detectGitBranches(cwd);
612
+ if (!gitInfo.ok) return gitInfo;
613
+
614
+ try {
615
+ const { stdout } = await execFileAsync(
616
+ "gh",
617
+ [
618
+ "pr",
619
+ "view",
620
+ "--json",
621
+ "number,title,url,state,isDraft,baseRefName,headRefName,reviewDecision,reviewRequests,mergeStateStatus,statusCheckRollup,updatedAt,autoMergeRequest",
622
+ ],
623
+ { cwd, timeout: 10_000 },
624
+ );
625
+ const pr = JSON.parse(stdout) as Record<string, unknown>;
626
+ const rawState = String(pr.state ?? "OPEN").toUpperCase();
627
+ const state: PullRequestInfo["state"] =
628
+ rawState === "MERGED" ? "merged" : rawState === "CLOSED" ? "closed" : pr.isDraft ? "draft" : "open";
629
+ const rollup = Array.isArray(pr.statusCheckRollup) ? pr.statusCheckRollup : [];
630
+ let passed = 0;
631
+ let failed = 0;
632
+ let pending = 0;
633
+ for (const check of rollup) {
634
+ if (typeof check !== "object" || check === null) continue;
635
+ const c = check as Record<string, unknown>;
636
+ const conclusion = String(c.conclusion ?? c.state ?? "").toUpperCase();
637
+ if (conclusion === "SUCCESS" || conclusion === "NEUTRAL" || conclusion === "SKIPPED") passed++;
638
+ else if (conclusion === "FAILURE" || conclusion === "ERROR" || conclusion === "TIMED_OUT") failed++;
639
+ else pending++;
640
+ }
641
+ const total = passed + failed + pending;
642
+ const checksState: PullRequestInfo["checks"]["state"] =
643
+ total === 0 ? "no_checks" : failed > 0 ? "failing" : pending > 0 ? "pending" : "passing";
644
+ const decision = String(pr.reviewDecision ?? "").toUpperCase();
645
+ const reviewRequests = Array.isArray(pr.reviewRequests) ? pr.reviewRequests.length : 0;
646
+ const reviewState: PullRequestInfo["review"]["state"] =
647
+ decision === "APPROVED"
648
+ ? "approved"
649
+ : decision === "CHANGES_REQUESTED"
650
+ ? "changes_requested"
651
+ : reviewRequests > 0
652
+ ? "review_requested"
653
+ : decision === "REVIEW_REQUIRED"
654
+ ? "review_required"
655
+ : "none";
656
+ const mergeStatus = String(pr.mergeStateStatus ?? "").toUpperCase();
657
+ const mergeability: PullRequestInfo["mergeability"] =
658
+ mergeStatus === "CLEAN" || mergeStatus === "HAS_HOOKS"
659
+ ? "mergeable"
660
+ : mergeStatus === "DIRTY"
661
+ ? "conflicts"
662
+ : mergeStatus === "BLOCKED"
663
+ ? "blocked"
664
+ : "unknown";
665
+ const attention: PullRequestInfo["attention"] =
666
+ state === "merged"
667
+ ? "merged"
668
+ : state === "closed"
669
+ ? "closed"
670
+ : state === "draft"
671
+ ? "draft"
672
+ : mergeability === "conflicts"
673
+ ? "conflicts"
674
+ : checksState === "failing"
675
+ ? "checks_failed"
676
+ : reviewState === "changes_requested"
677
+ ? "changes_requested"
678
+ : reviewState === "approved" && checksState === "passing"
679
+ ? "ready_to_merge"
680
+ : "review_requested";
681
+
682
+ return {
683
+ ok: true,
684
+ branch: gitInfo.branch,
685
+ pullRequest: {
686
+ number: Number(pr.number) || 0,
687
+ title: String(pr.title ?? ""),
688
+ url: String(pr.url ?? ""),
689
+ state,
690
+ baseRef: String(pr.baseRefName ?? gitInfo.base),
691
+ headRef: String(pr.headRefName ?? gitInfo.branch ?? ""),
692
+ checks: { state: checksState, passed, failed, pending, total },
693
+ review: { state: reviewState, requests: reviewRequests },
694
+ mergeability,
695
+ attention,
696
+ autoMerge: Boolean(pr.autoMergeRequest),
697
+ inMergeQueue: false,
698
+ updatedAt: typeof pr.updatedAt === "string" ? Date.parse(pr.updatedAt) : null,
699
+ },
700
+ fetchedAt: Date.now(),
701
+ };
702
+ } catch {
703
+ return {
704
+ ok: true,
705
+ branch: gitInfo.branch,
706
+ pullRequest: null,
707
+ fetchedAt: Date.now(),
708
+ };
709
+ }
710
+ }
711
+
712
+ function mapAgentStatus(status: string): ThreadDisplayStatus {
713
+ if (status === "running") return "active";
714
+ if (status === "initializing") return "starting";
715
+ if (status === "error") return "error";
716
+ return "idle";
717
+ }
718
+
719
+ function parentAgentOf(agent: { runtimeInfo?: unknown; labels?: Record<string, string> }): string | null {
720
+ if (agent.labels && typeof agent.labels.parentAgentId === "string") {
721
+ return agent.labels.parentAgentId;
722
+ }
723
+ const rt = agent.runtimeInfo;
724
+ if (typeof rt === "object" && rt !== null && "parentAgentId" in rt) {
725
+ const val = (rt as { parentAgentId?: unknown }).parentAgentId;
726
+ if (typeof val === "string") return val;
727
+ }
728
+ return null;
729
+ }
730
+
731
+ export async function readProjectThreads(
732
+ paseo: PaseoApi,
733
+ agentId: string,
734
+ ids: readonly string[] | null,
735
+ ): Promise<ThreadsResult> {
736
+ if (isSyntheticGalleryAgent(agentId)) return demoThreads(ids);
737
+ try {
738
+ const { entries } = await paseo.agents.list();
739
+ const byId = new Map(entries.map((entry) => [entry.agent.id, entry.agent]));
740
+ const own = byId.get(agentId) ?? null;
741
+ const targetAgents =
742
+ ids === null
743
+ ? entries
744
+ .map((e) => e.agent)
745
+ .filter((a) => {
746
+ const p = parentAgentOf(a);
747
+ if (p === agentId) return true;
748
+ return own !== null && a.workspaceId === own.workspaceId && a.id !== agentId;
749
+ })
750
+ : ids.map((id) => byId.get(id) ?? null);
751
+
752
+ const threads: (ThreadInfo | MissingThread)[] = await Promise.all(
753
+ targetAgents.map(async (agent, index): Promise<ThreadInfo | MissingThread> => {
754
+ if (!agent) {
755
+ return { found: false as const, id: ids?.[index] ?? "unknown" };
756
+ }
757
+ let latestText: string | null = null;
758
+ try {
759
+ const tl = await paseo.agents.ref(agent.id).timeline.refetch({ limit: 10 });
760
+ for (let i = tl.entries.length - 1; i >= 0; i--) {
761
+ const entry = tl.entries[i];
762
+ if (entry && entry.item.type === "assistant_message") {
763
+ latestText = entry.item.text;
764
+ break;
765
+ }
766
+ }
767
+ } catch {
768
+ // Ignore timeline fetch error
769
+ }
770
+ const requiresAttention = Boolean(agent.requiresAttention);
771
+ return {
772
+ found: true as const,
773
+ id: agent.id,
774
+ title: agent.title?.trim() || `Agent ${agent.id.slice(0, 8)}`,
775
+ status: mapAgentStatus(agent.status),
776
+ needsInput: requiresAttention && agent.attentionReason === "permission",
777
+ archived: Boolean(agent.archivedAt),
778
+ provider: { id: agent.provider, name: agent.provider, logoUrl: null },
779
+ model: agent.model ?? null,
780
+ reasoning: agent.thinkingOptionId ?? null,
781
+ updatedAt: Date.parse(agent.updatedAt) || Date.now(),
782
+ lastMessage: lastMessage(latestText),
783
+ pending: null,
784
+ runningWorkers: 0,
785
+ };
786
+ }),
787
+ );
788
+
789
+ return {
790
+ ok: true,
791
+ mode: ids === null ? "subthreads" : "ids",
792
+ threads,
793
+ truncated: false,
794
+ fetchedAt: Date.now(),
795
+ };
796
+ } catch (cause) {
797
+ return failure("unavailable", cause instanceof Error ? cause.message : String(cause));
798
+ }
799
+ }
800
+
801
+ export async function readProjectEnvironments(
802
+ paseo: PaseoApi,
803
+ agentId: string,
804
+ withDetails: boolean,
805
+ ): Promise<EnvironmentsResult> {
806
+ if (isSyntheticGalleryAgent(agentId)) return demoEnvironments();
807
+ try {
808
+ const [workspacesRes, agentsRes] = await Promise.all([
809
+ paseo.workspaces.list(),
810
+ paseo.agents.list(),
811
+ ]);
812
+ const ownAgent = agentsRes.entries.find((e) => e.agent.id === agentId)?.agent ?? null;
813
+ const ownWorkspace =
814
+ workspacesRes.entries.find((w) => w.id === ownAgent?.workspaceId) ??
815
+ workspacesRes.entries[0] ??
816
+ null;
817
+ if (!ownWorkspace) return demoEnvironments();
818
+
819
+ const projectWorkspaces = workspacesRes.entries.filter(
820
+ (w) => w.projectId === ownWorkspace.projectId,
821
+ );
822
+ const environments: EnvironmentInfo[] = await Promise.all(
823
+ projectWorkspaces.map(async (ws): Promise<EnvironmentInfo> => {
824
+ const wsAgents = agentsRes.entries
825
+ .map((e) => e.agent)
826
+ .filter((a) => a.workspaceId === ws.id);
827
+ const threads: EnvironmentThread[] = wsAgents.slice(0, 5).map((a) => ({
828
+ id: a.id,
829
+ title: a.title?.trim() || `Agent ${a.id.slice(0, 8)}`,
830
+ status: mapAgentStatus(a.status),
831
+ needsInput: Boolean(a.requiresAttention) && a.attentionReason === "permission",
832
+ archived: Boolean(a.archivedAt),
833
+ subthread: parentAgentOf(a) !== null,
834
+ activeAt: Date.parse(a.updatedAt) || Date.now(),
835
+ }));
836
+ const live = threads.filter((t) => !t.archived);
837
+ const dir = ws.workspaceDirectory;
838
+ const gitInfo = dir ? await detectGitBranches(dir) : null;
839
+ const branch = gitInfo && gitInfo.ok ? gitInfo.branch : null;
840
+ const base = gitInfo && gitInfo.ok ? gitInfo.base : "main";
841
+ const detail = withDetails ? await readWorkspaceDetail(ws.id, dir) : null;
842
+ return {
843
+ id: ws.id,
844
+ name: ws.title ?? ws.id,
845
+ kind: ws.workspaceKind === "worktree" ? "managed-worktree" : "checkout",
846
+ provider: ws.workspaceKind,
847
+ path: dir,
848
+ branch,
849
+ defaultBranch: base,
850
+ base,
851
+ git: ws.projectKind === "git",
852
+ life: ws.archivingAt ? "retiring" : "ready",
853
+ current: ws.id === ownWorkspace.id,
854
+ threads,
855
+ threadCounts: {
856
+ total: wsAgents.length,
857
+ live: live.length,
858
+ running: live.filter((t) => t.status === "active").length,
859
+ needsInput: live.filter((t) => t.needsInput).length,
860
+ },
861
+ activeAt: threads[0]?.activeAt ?? null,
862
+ updatedAt: Date.now(),
863
+ detail,
864
+ };
865
+ }),
866
+ );
867
+
868
+ return {
869
+ ok: true,
870
+ environments,
871
+ threadsTruncated: false,
872
+ fetchedAt: Date.now(),
873
+ };
874
+ } catch (cause) {
875
+ return failure("unavailable", cause instanceof Error ? cause.message : String(cause));
876
+ }
877
+ }
878
+
879
+ async function readWorkspaceDetail(
880
+ workspaceId: string,
881
+ directory: string | null,
882
+ ): Promise<EnvironmentDetail> {
883
+ if (!directory) {
884
+ return {
885
+ ok: true,
886
+ id: workspaceId,
887
+ checkout: {
888
+ ok: false,
889
+ reason: "missing",
890
+ message: "Workspace directory is unavailable",
891
+ path: null,
892
+ },
893
+ pull: null,
894
+ fetchedAt: Date.now(),
895
+ };
896
+ }
897
+ const gitInfo = await detectGitBranches(directory);
898
+ if (!gitInfo.ok) {
899
+ return {
900
+ ok: true,
901
+ id: workspaceId,
902
+ checkout: { ok: false, reason: "not-git", message: gitInfo.message, path: directory },
903
+ pull: null,
904
+ fetchedAt: Date.now(),
905
+ };
906
+ }
907
+ const statusRes = await runGit(directory, ["status", "--porcelain"]);
908
+ const changedLines = statusRes.ok
909
+ ? statusRes.stdout.split("\n").filter((l) => l.trim() !== "")
910
+ : [];
911
+ return {
912
+ ok: true,
913
+ id: workspaceId,
914
+ checkout: {
915
+ ok: true,
916
+ branch: gitInfo.branch,
917
+ checkout: gitInfo.checkout,
918
+ head: gitInfo.head,
919
+ defaultBranch: gitInfo.base,
920
+ base: gitInfo.base,
921
+ onBase: gitInfo.branch === gitInfo.base,
922
+ ahead: null,
923
+ behind: null,
924
+ uncommitted: {
925
+ files: changedLines.length,
926
+ additions: 0,
927
+ deletions: 0,
928
+ complete: true,
929
+ },
930
+ },
931
+ pull: null,
932
+ fetchedAt: Date.now(),
933
+ };
934
+ }
935
+
936
+ export async function readProjectEnvironment(
937
+ paseo: PaseoApi,
938
+ agentId: string,
939
+ environmentId: string,
940
+ ): Promise<EnvironmentDetailResult> {
941
+ if (isSyntheticGalleryAgent(agentId) || environmentId.startsWith("env_")) {
942
+ const demo = demoEnvironments();
943
+ if (demo.ok) {
944
+ const match = demo.environments.find((e) => e.id === environmentId) ?? demo.environments[0];
945
+ if (match?.detail) return match.detail;
946
+ }
947
+ }
948
+ const workspaces = await paseo.workspaces.list();
949
+ const ws = workspaces.entries.find((w) => w.id === environmentId);
950
+ if (!ws) return { ok: false, reason: "not-found", message: "Workspace not found" };
951
+ return readWorkspaceDetail(ws.id, ws.workspaceDirectory);
952
+ }
953
+
954
+ export function createProjectReader(
955
+ paseo: PaseoApi,
956
+ agentId: string,
957
+ ): (request: ProjectRequest) => Promise<ProjectResult> {
958
+ return (request) => {
959
+ switch (request.kind) {
960
+ case "changes":
961
+ return readProjectChanges(
962
+ paseo,
963
+ agentId,
964
+ request.target.kind === "commit"
965
+ ? request.target.sha
966
+ : request.target.kind === "uncommitted"
967
+ ? "uncommitted"
968
+ : null,
969
+ request.paths,
970
+ );
971
+ case "commits":
972
+ return readProjectCommits(paseo, agentId);
973
+ case "pullRequest":
974
+ return readProjectPullRequest(paseo, agentId);
975
+ case "threads":
976
+ return readProjectThreads(paseo, agentId, request.ids);
977
+ case "environments":
978
+ return readProjectEnvironments(paseo, agentId, true);
979
+ }
980
+ };
981
+ }