@defrex/autobuild 1.10.0 → 1.11.1

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 (255) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +745 -69
  3. package/bin/ab-dispatch-generation.ts +3 -1
  4. package/docs/accounts.md +2 -1
  5. package/docs/answering-blocked-builds.md +20 -0
  6. package/docs/architecture.md +165 -29
  7. package/docs/build-store.md +10 -7
  8. package/docs/cli.md +33 -1
  9. package/docs/configuration-overview.md +4 -1
  10. package/docs/configuration.md +381 -29
  11. package/docs/dispatcher.md +64 -4
  12. package/docs/forges.md +7 -0
  13. package/docs/integration-tree.md +2 -2
  14. package/docs/operating.md +4 -2
  15. package/docs/operator-api.md +134 -6
  16. package/docs/operator-surfaces.md +85 -0
  17. package/docs/optimization-nodes.md +69 -11
  18. package/docs/plugin-authoring.md +37 -1
  19. package/docs/remote-store-protocol.md +94 -13
  20. package/docs/remote-ticket-protocol.md +40 -0
  21. package/docs/restacking.md +20 -4
  22. package/docs/setup.md +14 -2
  23. package/docs/ticket-dependencies.md +10 -3
  24. package/docs/ticket-sources.md +24 -2
  25. package/docs/tickets.md +7 -1
  26. package/docs/troubleshooting.md +8 -0
  27. package/docs/verification.md +4 -3
  28. package/docs/workspaces.md +3 -0
  29. package/package.json +9 -5
  30. package/packages/core/src/cli/accounts.ts +7 -2
  31. package/packages/core/src/cli/attention.ts +3 -1
  32. package/packages/core/src/cli/binary-direct.ts +2 -0
  33. package/packages/core/src/cli/binary-lifecycle.ts +2 -1
  34. package/packages/core/src/cli/build-control.ts +79 -1
  35. package/packages/core/src/cli/context.ts +4 -0
  36. package/packages/core/src/cli/dashboard/facts.ts +49 -53
  37. package/packages/core/src/cli/dashboard/header.ts +111 -0
  38. package/packages/core/src/cli/dashboard/model.ts +31 -39
  39. package/packages/core/src/cli/dashboard/objective-row.ts +46 -14
  40. package/packages/core/src/cli/dashboard/poll.ts +179 -76
  41. package/packages/core/src/cli/dashboard/render.ts +159 -230
  42. package/packages/core/src/cli/dashboard/row-text.ts +538 -0
  43. package/packages/core/src/cli/dashboard/timeline.ts +288 -0
  44. package/packages/core/src/cli/dashboard/vocabulary.ts +188 -0
  45. package/packages/core/src/cli/dispatch-args.ts +44 -1
  46. package/packages/core/src/cli/dispatch-frontend.ts +40 -40
  47. package/packages/core/src/cli/dispatch-launch-stop.ts +18 -0
  48. package/packages/core/src/cli/dispatch-launcher.ts +20 -7
  49. package/packages/core/src/cli/dispatch-web.ts +155 -0
  50. package/packages/core/src/cli/dispatch.ts +202 -38
  51. package/packages/core/src/cli/help.ts +87 -3
  52. package/packages/core/src/cli/init-validation.ts +3 -3
  53. package/packages/core/src/cli/main.ts +70 -6
  54. package/packages/core/src/cli/mcp.ts +35 -3
  55. package/packages/core/src/cli/objective.ts +1 -1
  56. package/packages/core/src/cli/operator-preference.ts +57 -0
  57. package/packages/core/src/cli/repo-lease.ts +2 -0
  58. package/packages/core/src/cli/repo-state.ts +56 -6
  59. package/packages/core/src/cli/repository-status.ts +105 -49
  60. package/packages/core/src/cli/status.ts +82 -1
  61. package/packages/core/src/cli/terminal-restore.ts +32 -7
  62. package/packages/core/src/cli/ticket.ts +98 -36
  63. package/packages/core/src/cli/wait.ts +14 -6
  64. package/packages/core/src/cli/watch.ts +20 -4
  65. package/packages/core/src/cli/web.ts +139 -0
  66. package/packages/core/src/config/live.ts +99 -14
  67. package/packages/core/src/config/load.ts +61 -20
  68. package/packages/core/src/config/local.ts +212 -0
  69. package/packages/core/src/config/pipeline-source.ts +2 -0
  70. package/packages/core/src/config/reference.ts +18 -0
  71. package/packages/core/src/config/schema.ts +45 -10
  72. package/packages/core/src/events/catalog.ts +4 -0
  73. package/packages/core/src/events/payloads.ts +97 -0
  74. package/packages/core/src/events/policy.ts +10 -0
  75. package/packages/core/src/events/repository.ts +46 -3
  76. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +381 -30
  77. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/017d8dd5bb6dd80b.json.gz +0 -0
  78. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/178e12f1759b7552.json.gz +0 -0
  79. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/4932c70a2af97faf.json.gz +0 -0
  80. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/536085773daf6b58.json.gz +0 -0
  81. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/6bd6275061aaffa5.json.gz +0 -0
  82. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/89625654b02e9ac1.json.gz +0 -0
  83. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/a98af134be2da8a9.json.gz +0 -0
  84. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/d5d5ccca80a893d8.json.gz +0 -0
  85. package/packages/core/src/kernel/__snapshots__/reducer-identity-corpora/f8155387eb5f375c.json.gz +0 -0
  86. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/3c27f918b194e3b3.json +465 -0
  87. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/46196d8f0076496a.json +97 -0
  88. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/79f0e0f4ccd43ba2.json +455 -0
  89. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/859c09edac738823.json +1086 -0
  90. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a283c1f3462b1cc1.json +81 -0
  91. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a6e570fb126991ff.json +36 -0
  92. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/a8acf22c968b6e3d.json +81 -0
  93. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/ba7b85895bf6698e.json +1153 -0
  94. package/packages/core/src/kernel/__snapshots__/reducer-identity-records/fc66408cde0b6b04.json +637 -0
  95. package/packages/core/src/kernel/build-roster.ts +230 -0
  96. package/packages/core/src/kernel/dispatch-capacity.ts +4 -2
  97. package/packages/core/src/kernel/dispatch-status.ts +139 -0
  98. package/packages/core/src/kernel/engine.ts +43 -5
  99. package/packages/core/src/kernel/execution-intervals.ts +61 -0
  100. package/packages/core/src/kernel/generators/optimization-log.ts +101 -0
  101. package/packages/core/src/kernel/generators/repository-journals.ts +13 -0
  102. package/packages/core/src/kernel/leaf-restack-base.ts +33 -7
  103. package/packages/core/src/kernel/leaf-restack-state.ts +82 -3
  104. package/packages/core/src/kernel/log-index.ts +19 -0
  105. package/packages/core/src/kernel/optimization-admission.ts +244 -3
  106. package/packages/core/src/kernel/optimization.ts +183 -4
  107. package/packages/core/src/kernel/phase-failures.ts +121 -0
  108. package/packages/core/src/kernel/published-branch-head.ts +60 -0
  109. package/packages/core/src/kernel/read-facts.ts +15 -13
  110. package/packages/core/src/kernel/reducer-registry.ts +27 -8
  111. package/packages/core/src/kernel/reducer-revisions.ts +27 -0
  112. package/packages/core/src/kernel/reducer.ts +63 -4
  113. package/packages/core/src/kernel/rollup.ts +61 -0
  114. package/packages/core/src/kernel/setup-streak.ts +38 -0
  115. package/packages/core/src/kernel/step-durations.ts +257 -0
  116. package/packages/core/src/kernel/target-observation.ts +6 -1
  117. package/packages/core/src/kernel/target-rewrite-recovery.ts +116 -0
  118. package/packages/core/src/kernel/verify-diff-base.ts +5 -0
  119. package/packages/core/src/kernel/verify-stages.ts +13 -3
  120. package/packages/core/src/ontology.ts +5 -0
  121. package/packages/core/src/operator/agent-context-serve.ts +631 -0
  122. package/packages/core/src/operator/annotations.ts +75 -5
  123. package/packages/core/src/operator/attention.ts +470 -0
  124. package/packages/core/src/operator/canonical-skills.ts +35 -0
  125. package/packages/core/src/operator/cli-equivalents.ts +270 -0
  126. package/packages/core/src/operator/context-prompts.ts +61 -0
  127. package/packages/core/src/operator/index.ts +49 -1
  128. package/packages/core/src/operator/landings.ts +28 -19
  129. package/packages/core/src/operator/optimization.ts +7 -0
  130. package/packages/core/src/operator/protocol.ts +3 -0
  131. package/packages/core/src/operator/query.ts +129 -74
  132. package/packages/core/src/operator/read-view.ts +5 -2
  133. package/packages/core/src/operator/registry.ts +406 -46
  134. package/packages/core/src/operator/requests.ts +20 -18
  135. package/packages/core/src/operator/sandbox-host.ts +107 -11
  136. package/packages/core/src/operator/sandbox-resolver.ts +253 -0
  137. package/packages/core/src/operator/sandbox.ts +778 -82
  138. package/packages/core/src/operator/ticket-asset-list.ts +77 -0
  139. package/packages/core/src/operator/ticket-assets.ts +167 -0
  140. package/packages/core/src/operator/tickets.ts +33 -2
  141. package/packages/core/src/plugin-sdk/index.ts +22 -0
  142. package/packages/core/src/plugins/manifest.ts +1 -1
  143. package/packages/core/src/ports/forge/fake.ts +92 -1
  144. package/packages/core/src/ports/forge/git-blob.ts +15 -0
  145. package/packages/core/src/ports/forge/github.ts +82 -0
  146. package/packages/core/src/ports/forge/local-git.ts +61 -1
  147. package/packages/core/src/ports/forge-failure.ts +24 -0
  148. package/packages/core/src/ports/runner/antigravity-test.fixture.ts +149 -0
  149. package/packages/core/src/ports/runner/claude-test.fixture.ts +71 -0
  150. package/packages/core/src/ports/runner/codex-test.fixture.ts +63 -0
  151. package/packages/core/src/ports/tickets/contract.ts +71 -0
  152. package/packages/core/src/ports/tickets/fake.ts +11 -0
  153. package/packages/core/src/ports/tickets/file.ts +18 -0
  154. package/packages/core/src/ports/tickets/github-fake.ts +136 -4
  155. package/packages/core/src/ports/tickets/github.ts +387 -30
  156. package/packages/core/src/ports/tickets/hosted-index.ts +10 -0
  157. package/packages/core/src/ports/tickets/linear.ts +130 -0
  158. package/packages/core/src/ports/tickets/priority.ts +9 -0
  159. package/packages/core/src/ports/tickets/remote-protocol.ts +34 -0
  160. package/packages/core/src/ports/tickets/remote.ts +70 -6
  161. package/packages/core/src/ports/tickets/search.ts +139 -0
  162. package/packages/core/src/ports/types.ts +104 -2
  163. package/packages/core/src/ports/workspace/builtin-capabilities.ts +9 -0
  164. package/packages/core/src/ports/workspace/create.ts +15 -1
  165. package/packages/core/src/ports/workspace/fake.ts +340 -12
  166. package/packages/core/src/ports/workspace/git-worktree.ts +833 -42
  167. package/packages/core/src/ports/workspace/operator-sandbox.ts +129 -12
  168. package/packages/core/src/ports/workspace/process-group.ts +48 -0
  169. package/packages/core/src/ports/workspace/vercel-sandbox.ts +1260 -123
  170. package/packages/core/src/processes/agent-context-assemble.ts +576 -0
  171. package/packages/core/src/processes/agent-context.ts +469 -0
  172. package/packages/core/src/processes/build-runner.ts +387 -236
  173. package/packages/core/src/processes/dispatcher.ts +211 -55
  174. package/packages/core/src/processes/execution-no-progress.ts +4 -0
  175. package/packages/core/src/processes/optimization-activity.ts +120 -0
  176. package/packages/core/src/processes/phase-failure-budget.ts +1 -0
  177. package/packages/core/src/processes/repo-view.ts +78 -2
  178. package/packages/core/src/processes/sandbox-state.ts +53 -6
  179. package/packages/core/src/processes/tick-publication.ts +2 -0
  180. package/packages/core/src/processes/workspace-preparation.ts +76 -0
  181. package/packages/core/src/scenarios/harness.ts +0 -5
  182. package/packages/core/src/store/account-redaction.ts +1 -0
  183. package/packages/core/src/store/adapter.ts +52 -1
  184. package/packages/core/src/store/agent-context.ts +432 -0
  185. package/packages/core/src/store/build-feed.ts +291 -0
  186. package/packages/core/src/store/build-scope.ts +19 -1
  187. package/packages/core/src/store/contract.ts +911 -14
  188. package/packages/core/src/store/digest.ts +19 -6
  189. package/packages/core/src/store/histogram.ts +113 -0
  190. package/packages/core/src/store/local/schema.ts +62 -0
  191. package/packages/core/src/store/local/store.ts +628 -22
  192. package/packages/core/src/store/local/ticket-asset-heads.ts +23 -0
  193. package/packages/core/src/store/memory.ts +461 -69
  194. package/packages/core/src/store/open-builds.ts +19 -0
  195. package/packages/core/src/store/phase-session.ts +32 -4
  196. package/packages/core/src/store/reduced-reads.ts +14 -4
  197. package/packages/core/src/store/reducer-value-shapes.json +7027 -5751
  198. package/packages/core/src/store/reducer-values.ts +6 -1
  199. package/packages/core/src/store/remote/client.ts +208 -2
  200. package/packages/core/src/store/remote/compatibility.ts +1 -1
  201. package/packages/core/src/store/remote/index.ts +33 -0
  202. package/packages/core/src/store/remote/protocol.ts +69 -0
  203. package/packages/core/src/store/remote/released-clients.json +22 -0
  204. package/packages/core/src/store/remote/released-reducer-values/1.11.0.json +35680 -0
  205. package/packages/core/src/store/remote/released-reducer-values/1.11.1.json +35718 -0
  206. package/packages/core/src/store/remote/released-reducer-values/index.ts +20 -16
  207. package/packages/core/src/store/retention.ts +23 -1
  208. package/packages/core/src/store/rollups.ts +337 -0
  209. package/packages/core/src/store/session-handle.ts +20 -2
  210. package/packages/core/src/store/snapshots.ts +10 -0
  211. package/packages/core/src/store/types.ts +108 -9
  212. package/packages/core/src/testing/dispatch-journals.ts +117 -0
  213. package/packages/core/src/testing/dispatch-read-budget.ts +1092 -2
  214. package/packages/core/src/testing/git-config-isolation.ts +7 -5
  215. package/packages/core/src/testing/index.ts +27 -0
  216. package/packages/core/src/testing/memory-operator-sandbox.ts +346 -0
  217. package/packages/core/src/testing/reduced-read-budget.ts +1873 -98
  218. package/packages/core/src/web/analytics-source.ts +303 -0
  219. package/packages/core/src/web/assets/Atkinson-OFL.txt +93 -0
  220. package/packages/core/src/web/assets/AtkinsonHyperlegibleNext.latin.woff2 +0 -0
  221. package/packages/core/src/web/assets/JetBrains-OFL.txt +93 -0
  222. package/packages/core/src/web/assets/JetBrainsMono.latin.woff2 +0 -0
  223. package/packages/core/src/web/assets/app.css +1 -0
  224. package/packages/core/src/web/assets/app.js +9 -0
  225. package/packages/core/src/web/assets/manifest.json +31 -0
  226. package/packages/core/src/web/assets/theme.js +1 -0
  227. package/packages/core/src/web/bounded.ts +31 -0
  228. package/packages/core/src/web/http.ts +315 -0
  229. package/packages/core/src/web/hub.ts +160 -0
  230. package/packages/core/src/web/options.ts +38 -0
  231. package/packages/core/src/web/overview-source.ts +322 -0
  232. package/packages/core/src/web/page.ts +56 -0
  233. package/packages/core/src/web/protocol.ts +151 -0
  234. package/packages/core/src/web/read-only.ts +23 -0
  235. package/packages/core/src/web/repository-source.ts +39 -0
  236. package/packages/core/src/web/server.ts +97 -0
  237. package/skills/code-review/SKILL.md +10 -2
  238. package/skills/guide/SKILL.md +376 -54
  239. package/skills/guide/references/accounts.md +2 -1
  240. package/skills/guide/references/integration-tree.md +2 -2
  241. package/skills/guide/references/operator-api.md +134 -6
  242. package/skills/guide/references/optimization-nodes.md +69 -11
  243. package/skills/guide/references/plugin-authoring.md +37 -1
  244. package/skills/guide/references/remote-store-protocol.md +94 -13
  245. package/skills/guide/references/remote-ticket-protocol.md +40 -0
  246. package/skills/guide/references/restacking.md +20 -4
  247. package/skills/guide/references/setup.md +14 -2
  248. package/skills/guide/references/ticket-dependencies.md +10 -3
  249. package/skills/implement/SKILL.md +23 -4
  250. package/skills/operate/SKILL.md +134 -32
  251. package/skills/plan/SKILL.md +10 -4
  252. package/skills/plan-review/SKILL.md +9 -2
  253. package/skills/spec/SKILL.md +34 -8
  254. package/skills/tickets/SKILL.md +51 -5
  255. package/templates/hosted-service/package.json +2 -2
@@ -0,0 +1,31 @@
1
+ {
2
+ "files": [
3
+ {
4
+ "path": "AtkinsonHyperlegibleNext.latin.woff2",
5
+ "type": "font/woff2"
6
+ },
7
+ {
8
+ "path": "JetBrainsMono.latin.woff2",
9
+ "type": "font/woff2"
10
+ },
11
+ {
12
+ "path": "app.css",
13
+ "type": "text/css; charset=utf-8"
14
+ },
15
+ {
16
+ "path": "app.js",
17
+ "type": "text/javascript; charset=utf-8"
18
+ },
19
+ {
20
+ "path": "theme.js",
21
+ "type": "text/javascript; charset=utf-8"
22
+ }
23
+ ],
24
+ "script": "app.js",
25
+ "stylesheet": "app.css",
26
+ "themeScript": "theme.js",
27
+ "fonts": [
28
+ "AtkinsonHyperlegibleNext.latin.woff2",
29
+ "JetBrainsMono.latin.woff2"
30
+ ]
31
+ }
@@ -0,0 +1 @@
1
+ (()=>{try{let t=localStorage.getItem("ab-theme");if(t==="light"||t==="dark")document.documentElement.dataset.theme=t}catch{}})();
@@ -0,0 +1,31 @@
1
+ /** Store reads a web source runs at once over a list of builds. */
2
+ export const BUILD_READ_CONCURRENCY = 8
3
+
4
+ /**
5
+ * `read` over every item, at most `BUILD_READ_CONCURRENCY` at a time, with
6
+ * results in item order. A failure starts no further reads, and the call
7
+ * rejects with the first failure only once every read already started has
8
+ * settled. A caller holding a lock therefore releases it after the last of
9
+ * its reads, so none can write a cache after a later request has moved on.
10
+ */
11
+ export async function mapBounded<T, R>(
12
+ items: readonly T[],
13
+ read: (item: T) => Promise<R>,
14
+ ): Promise<R[]> {
15
+ const results: R[] = new Array(items.length)
16
+ let next = 0
17
+ let failure: { error: unknown } | undefined
18
+ const worker = async () => {
19
+ while (failure === undefined && next < items.length) {
20
+ const at = next++
21
+ try {
22
+ results[at] = await read(items[at]!)
23
+ } catch (error) {
24
+ failure ??= { error }
25
+ }
26
+ }
27
+ }
28
+ await Promise.all(Array.from({ length: Math.min(BUILD_READ_CONCURRENCY, items.length) }, worker))
29
+ if (failure !== undefined) throw failure.error
30
+ return results
31
+ }
@@ -0,0 +1,315 @@
1
+ import { BuildFeedValidationError } from '../store/build-feed'
2
+ import {
3
+ AnalyticsQueryError,
4
+ parseAnalyticsQuery,
5
+ type WebAnalyticsSource,
6
+ } from './analytics-source'
7
+ import type { WebModelHub } from './hub'
8
+ import { renderPage } from './page'
9
+ import { PAGE_FRAME_WAIT_MS, WEB_EVENTS, type WebAssetManifest } from './protocol'
10
+
11
+ /** The comment line that keeps an idle event stream open through proxies. */
12
+ export const HEARTBEAT_MS = 15_000
13
+
14
+ export interface HeartbeatTimer {
15
+ set(callback: () => void, ms: number): unknown
16
+ clear(handle: unknown): void
17
+ }
18
+
19
+ const realHeartbeat: HeartbeatTimer = {
20
+ set: (callback, ms) => setInterval(callback, ms),
21
+ clear: (handle) => clearInterval(handle as ReturnType<typeof setInterval>),
22
+ }
23
+
24
+ const realTimeout: HeartbeatTimer = {
25
+ set: (callback, ms) => setTimeout(callback, ms),
26
+ clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
27
+ }
28
+
29
+ export interface WebHandlerOptions {
30
+ hub: WebModelHub
31
+ repositoryLabel: string
32
+ manifest: WebAssetManifest
33
+ /** Body of a manifest file; only called for names the manifest lists. */
34
+ readAsset(path: string): BodyInit
35
+ /** Host names a request may address, or `any` when `--host` widened the bind. */
36
+ allowedHosts: ReadonlySet<string> | 'any'
37
+ nonce?: () => string
38
+ heartbeat?: HeartbeatTimer
39
+ /** How long a page request waits for the hub's first frame, and the timer
40
+ * that bounds it. Defaults to `PAGE_FRAME_WAIT_MS` on real timers. */
41
+ pageWait?: { ms: number; timer: HeartbeatTimer }
42
+ /** The analytics and timeline reads; absent, or answering undefined while
43
+ * a dispatcher's store is not open yet, makes those routes answer 503. */
44
+ analytics?: () => WebAnalyticsPort | undefined
45
+ }
46
+
47
+ /** What the JSON routes call: `WebAnalyticsSource`, or a test double. */
48
+ export type WebAnalyticsPort = Pick<WebAnalyticsSource, 'analytics' | 'timeline'>
49
+
50
+ /** The slice of Bun's server the handler uses. */
51
+ export interface WebServerHandle {
52
+ timeout(request: Request, seconds: number): void
53
+ }
54
+
55
+ export type WebHandler = (
56
+ request: Request,
57
+ server?: WebServerHandle,
58
+ ) => Response | Promise<Response>
59
+
60
+ export function mintNonce(): string {
61
+ return Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString('base64')
62
+ }
63
+
64
+ /** The Host header's name: port stripped, IPv6 unbracketed, lowercased. */
65
+ export function requestHostName(host: string | null): string | undefined {
66
+ if (host === null || host === '') return undefined
67
+ const value = host.trim().toLowerCase()
68
+ if (value.startsWith('[')) {
69
+ const end = value.indexOf(']')
70
+ return end > 0 ? value.slice(1, end) : undefined
71
+ }
72
+ const colon = value.indexOf(':')
73
+ if (colon === -1) return value
74
+ // A bare IPv6 address without brackets carries no port.
75
+ return value.indexOf(':', colon + 1) === -1 ? value.slice(0, colon) : value
76
+ }
77
+
78
+ /** The hosts a loopback server answers to. */
79
+ export function loopbackHosts(bindHost: string): ReadonlySet<string> {
80
+ return new Set([requestHostName(bindHost) ?? bindHost, 'localhost', '127.0.0.1'])
81
+ }
82
+
83
+ const common = { 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer' }
84
+
85
+ export function pageCsp(nonce: string): string {
86
+ return [
87
+ "default-src 'self'",
88
+ `style-src 'self' 'nonce-${nonce}'`,
89
+ "base-uri 'none'",
90
+ "form-action 'none'",
91
+ "frame-ancestors 'none'",
92
+ ].join('; ')
93
+ }
94
+
95
+ function pageHeaders(nonce: string): HeadersInit {
96
+ return {
97
+ ...common,
98
+ 'Content-Type': 'text/html; charset=utf-8',
99
+ 'Cache-Control': 'no-store',
100
+ 'Content-Security-Policy': pageCsp(nonce),
101
+ }
102
+ }
103
+
104
+ function assetHeaders(type: string): HeadersInit {
105
+ return { ...common, 'Content-Type': type, 'Cache-Control': 'no-cache' }
106
+ }
107
+
108
+ function eventHeaders(): HeadersInit {
109
+ return {
110
+ ...common,
111
+ 'Content-Type': 'text/event-stream',
112
+ 'Cache-Control': 'no-cache',
113
+ 'X-Accel-Buffering': 'no',
114
+ }
115
+ }
116
+
117
+ function json(status: number, body: unknown, head = false): Response {
118
+ return new Response(head ? null : JSON.stringify(body), {
119
+ status,
120
+ headers: { ...common, 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
121
+ })
122
+ }
123
+
124
+ const API_PREFIX = '/api/'
125
+ const TIMELINE_ROUTE = /^\/api\/builds\/([^/]+)\/timeline$/u
126
+
127
+ /**
128
+ * The read-only JSON routes. `HEAD` builds headers only and reads nothing.
129
+ * Validation failures answer 400, an unknown build or route 404, a server
130
+ * without a store 503, and any store failure, including a typed remote
131
+ * incompatibility, 502 with its message: nothing falls back to another read.
132
+ */
133
+ async function api(
134
+ url: URL,
135
+ head: boolean,
136
+ source: (() => WebAnalyticsPort | undefined) | undefined,
137
+ ): Promise<Response> {
138
+ const path = url.pathname
139
+ const timeline = TIMELINE_ROUTE.exec(path)
140
+ let slug: string | undefined
141
+ if (timeline !== null) {
142
+ try {
143
+ slug = decodeURIComponent(timeline[1]!)
144
+ } catch {
145
+ return json(404, { error: 'not found' }, head)
146
+ }
147
+ if (slug === '') return json(404, { error: 'not found' }, head)
148
+ } else if (path !== '/api/analytics') return json(404, { error: 'not found' }, head)
149
+ const reads = source?.()
150
+ if (reads === undefined)
151
+ return json(503, { error: 'Analytics are unavailable until the store is open.' }, head)
152
+ try {
153
+ if (slug === undefined) {
154
+ const query = parseAnalyticsQuery(url.searchParams)
155
+ if (head) return json(200, null, true)
156
+ return json(200, await reads.analytics(query))
157
+ }
158
+ if (head) return json(200, null, true)
159
+ const row = await reads.timeline(slug)
160
+ return row === null ? json(404, { error: `no build ${slug}` }) : json(200, { row })
161
+ } catch (error) {
162
+ const message = error instanceof Error ? error.message : String(error)
163
+ if (error instanceof AnalyticsQueryError || error instanceof BuildFeedValidationError)
164
+ return json(400, { error: message }, head)
165
+ return json(502, { error: `Store read failed: ${message}` })
166
+ }
167
+ }
168
+
169
+ function text(status: number, body: string, extra: HeadersInit = {}): Response {
170
+ return new Response(body, {
171
+ status,
172
+ headers: { ...common, 'Content-Type': 'text/plain; charset=utf-8', ...extra },
173
+ })
174
+ }
175
+
176
+ /**
177
+ * The read-only request handler: the page, the committed assets, one event
178
+ * stream and the analytics JSON routes. Only `GET` and `HEAD` are accepted, and `HEAD` builds
179
+ * headers only, so it never reads an asset or joins the refresh loop.
180
+ */
181
+ export function createWebHandler(opts: WebHandlerOptions): WebHandler {
182
+ const nonce = opts.nonce ?? mintNonce
183
+ const heartbeat = opts.heartbeat ?? realHeartbeat
184
+ const pageWait = opts.pageWait ?? { ms: PAGE_FRAME_WAIT_MS, timer: realTimeout }
185
+ const assets = new Map(opts.manifest.files.map((file) => [file.path, file.type]))
186
+
187
+ return (request, server) => {
188
+ if (opts.allowedHosts !== 'any') {
189
+ const host = requestHostName(request.headers.get('host'))
190
+ if (host === undefined || !opts.allowedHosts.has(host))
191
+ return text(403, `ab web refuses Host ${host ?? '(none)'}; open the printed URL`)
192
+ }
193
+ if (request.method !== 'GET' && request.method !== 'HEAD')
194
+ return text(405, 'ab web is read-only', { Allow: 'GET, HEAD' })
195
+ const head = request.method === 'HEAD'
196
+ const url = new URL(request.url)
197
+ const path = url.pathname
198
+
199
+ if (path.startsWith(API_PREFIX)) return api(url, head, opts.analytics)
200
+
201
+ if (path.startsWith('/assets/')) {
202
+ let name: string
203
+ try {
204
+ name = decodeURIComponent(path.slice('/assets/'.length))
205
+ } catch {
206
+ return text(404, 'not found')
207
+ }
208
+ const type = assets.get(name)
209
+ if (type === undefined) return text(404, 'not found')
210
+ return new Response(head ? null : opts.readAsset(name), { headers: assetHeaders(type) })
211
+ }
212
+
213
+ if (path === '/events') {
214
+ if (head) return new Response(null, { headers: eventHeaders() })
215
+ return eventStream(request, server, opts.hub, heartbeat)
216
+ }
217
+
218
+ const minted = nonce()
219
+ if (head) return new Response(null, { headers: pageHeaders(minted) })
220
+ const page = (frame: string | undefined) =>
221
+ new Response(
222
+ renderPage({
223
+ nonce: minted,
224
+ repositoryLabel: opts.repositoryLabel,
225
+ manifest: opts.manifest,
226
+ ...(frame !== undefined ? { frame } : {}),
227
+ }),
228
+ { headers: pageHeaders(minted) },
229
+ )
230
+ const held = opts.hub.current
231
+ if (held !== undefined) return page(held)
232
+ return firstFrame(opts.hub, pageWait, request.signal).then(page)
233
+ }
234
+ }
235
+
236
+ /**
237
+ * The hub's first frame, for a page request that arrives before it has one.
238
+ * Subscribing joins or starts the hub's one shared read, the same read the
239
+ * page's event stream starts a moment later. The hub delivers a frame for
240
+ * every finished read, data or its failure notice, so the wait ends at that
241
+ * frame; the bound covers only a hung read, and an aborted request stops
242
+ * waiting. Every path unsubscribes.
243
+ */
244
+ function firstFrame(
245
+ hub: WebModelHub,
246
+ wait: { ms: number; timer: HeartbeatTimer },
247
+ signal: AbortSignal,
248
+ ): Promise<string | undefined> {
249
+ if (signal.aborted) return Promise.resolve(undefined)
250
+ return new Promise((resolve) => {
251
+ let settled = false
252
+ let unsubscribe: (() => void) | undefined
253
+ let timer: unknown
254
+ const finish = (frame: string | undefined) => {
255
+ if (settled) return
256
+ settled = true
257
+ unsubscribe?.()
258
+ if (timer !== undefined) wait.timer.clear(timer)
259
+ signal.removeEventListener('abort', abort)
260
+ resolve(frame)
261
+ }
262
+ const abort = () => finish(undefined)
263
+ signal.addEventListener('abort', abort)
264
+ unsubscribe = hub.subscribe((json) => finish(json))
265
+ if (settled) unsubscribe()
266
+ else timer = wait.timer.set(() => finish(undefined), wait.ms)
267
+ })
268
+ }
269
+
270
+ function eventStream(
271
+ request: Request,
272
+ server: WebServerHandle | undefined,
273
+ hub: WebModelHub,
274
+ heartbeat: HeartbeatTimer,
275
+ ): Response {
276
+ // Bun closes a connection idle for 10 s by default; a stream must outlive that.
277
+ server?.timeout(request, 0)
278
+ const encoder = new TextEncoder()
279
+ let cleanup: (() => void) | undefined
280
+ const body = new ReadableStream<Uint8Array>({
281
+ start(controller) {
282
+ if (request.signal.aborted) {
283
+ controller.close()
284
+ return
285
+ }
286
+ let done = false
287
+ let unsubscribe: (() => void) | undefined
288
+ let timer: unknown
289
+ const finish = () => {
290
+ if (done) return
291
+ done = true
292
+ unsubscribe?.()
293
+ if (timer !== undefined) heartbeat.clear(timer)
294
+ request.signal.removeEventListener('abort', finish)
295
+ }
296
+ cleanup = finish
297
+ const send = (chunk: string) => {
298
+ if (done) return
299
+ try {
300
+ controller.enqueue(encoder.encode(chunk))
301
+ } catch {
302
+ finish()
303
+ }
304
+ }
305
+ request.signal.addEventListener('abort', finish)
306
+ unsubscribe = hub.subscribe((json) => send(`event: ${WEB_EVENTS.model}\ndata: ${json}\n\n`))
307
+ if (done) unsubscribe()
308
+ else timer = heartbeat.set(() => send(': keep-alive\n\n'), HEARTBEAT_MS)
309
+ },
310
+ cancel() {
311
+ cleanup?.()
312
+ },
313
+ })
314
+ return new Response(body, { headers: eventHeaders() })
315
+ }
@@ -0,0 +1,160 @@
1
+ import { DashboardRefresh, type RefreshScheduler } from '../cli/dashboard/refresh'
2
+ import { type WebFrame, type WebFrameSource, WebReadFencedError } from './protocol'
3
+
4
+ export type WebFrameListener = (json: string) => void
5
+
6
+ export interface WebModelHubOptions {
7
+ /** Pull mode: the hub reads frames itself while anyone is connected. Absent
8
+ * is push mode: the hub reads nothing and serves what `publish` hands it. */
9
+ source?: WebFrameSource
10
+ /** The store reads over a network; the refresh cadence adapts as the viewer's does. */
11
+ networkReads?: boolean
12
+ scheduler?: RefreshScheduler
13
+ /** Called once per failure streak; a later success resets it. */
14
+ onError?: (error: unknown) => void
15
+ }
16
+
17
+ /**
18
+ * One refresh loop shared by every connected browser. The loop exists only
19
+ * while at least one subscriber is connected, so an idle server reads
20
+ * nothing; each tick reads one frame, serializes it once, and fans the string
21
+ * out only when it changed, so ten tabs cost the same reads as one.
22
+ *
23
+ * At most one source read is in flight across the hub's lifetime: a loop
24
+ * started by a reconnecting tab joins a read its predecessor left running
25
+ * instead of starting a second one, and a read whose subscribers all left
26
+ * stops at its next store stage.
27
+ *
28
+ * Without a source the hub is in push mode: it owns no loop and reads
29
+ * nothing, and its owner publishes frames from reads it already makes
30
+ * (`ab dispatch --web`).
31
+ */
32
+ export class WebModelHub {
33
+ private readonly listeners = new Set<WebFrameListener>()
34
+ private refresh: DashboardRefresh | undefined
35
+ /** The hub-wide in-flight read, shared across refresh loop generations. */
36
+ private reading: ReturnType<WebFrameSource['read']> | undefined
37
+ private json: string | undefined
38
+ private failing = false
39
+ private closed = false
40
+
41
+ constructor(private readonly opts: WebModelHubOptions) {}
42
+
43
+ get subscribers(): number {
44
+ return this.listeners.size
45
+ }
46
+
47
+ /** The last frame pushed, serialized; absent before the first read. */
48
+ get current(): string | undefined {
49
+ return this.json
50
+ }
51
+
52
+ subscribe(listener: WebFrameListener): () => void {
53
+ if (this.closed) return () => {}
54
+ // A distinct identity per subscription, so one function may subscribe twice.
55
+ const entry: WebFrameListener = (json) => listener(json)
56
+ this.listeners.add(entry)
57
+ if (this.json !== undefined) this.deliver(entry, this.json)
58
+ if (this.listeners.has(entry) && this.refresh === undefined && this.opts.source !== undefined) {
59
+ // An absent scheduler takes DashboardRefresh's real-timer default.
60
+ this.refresh = new DashboardRefresh(
61
+ () => this.tick(),
62
+ this.opts.scheduler,
63
+ this.opts.networkReads,
64
+ )
65
+ void this.refresh.request()
66
+ }
67
+ let active = true
68
+ return () => {
69
+ if (!active) return
70
+ active = false
71
+ this.remove(entry)
72
+ }
73
+ }
74
+
75
+ /** Push mode: serve `frame`, fanning it out only when it changed. */
76
+ publish(frame: WebFrame): void {
77
+ if (this.closed) return
78
+ this.push(JSON.stringify(frame))
79
+ }
80
+
81
+ /** Push mode: replace the frame with the failure's notice. */
82
+ fail(error: unknown): void {
83
+ this.publish(noticeFrame(error))
84
+ }
85
+
86
+ /** Await the in-flight tick and source read, if any. */
87
+ async join(): Promise<void> {
88
+ await this.refresh?.join()
89
+ await this.reading?.catch(() => {})
90
+ }
91
+
92
+ close(): void {
93
+ this.closed = true
94
+ this.listeners.clear()
95
+ this.stop()
96
+ }
97
+
98
+ private remove(entry: WebFrameListener): void {
99
+ this.listeners.delete(entry)
100
+ if (this.listeners.size === 0) this.stop()
101
+ }
102
+
103
+ private stop(): void {
104
+ // DashboardRefresh.stop is terminal; the next subscriber starts a new loop.
105
+ this.refresh?.stop()
106
+ this.refresh = undefined
107
+ }
108
+
109
+ private async tick(): Promise<void> {
110
+ const refresh = this.refresh
111
+ let frame: WebFrame
112
+ try {
113
+ const result = await this.read()
114
+ if (result === undefined) return
115
+ refresh?.activity(result.live)
116
+ frame = result.frame
117
+ this.failing = false
118
+ } catch (error) {
119
+ // Abandoned for lack of subscribers: nobody is waiting for a notice.
120
+ if (error instanceof WebReadFencedError) return
121
+ frame = noticeFrame(error)
122
+ if (!this.failing) this.opts.onError?.(error)
123
+ this.failing = true
124
+ }
125
+ if (this.refresh !== refresh || refresh === undefined) return
126
+ this.push(JSON.stringify(frame))
127
+ }
128
+
129
+ private push(json: string): void {
130
+ if (json === this.json) return
131
+ this.json = json
132
+ for (const listener of [...this.listeners]) this.deliver(listener, json)
133
+ }
134
+
135
+ /** Start the source read, or join the one already running. */
136
+ private read(): ReturnType<WebFrameSource['read']> {
137
+ if (this.reading === undefined) {
138
+ const reading = this.opts.source!.read(() => !this.closed && this.listeners.size > 0)
139
+ this.reading = reading
140
+ const clear = () => {
141
+ if (this.reading === reading) this.reading = undefined
142
+ }
143
+ reading.then(clear, clear)
144
+ }
145
+ return this.reading
146
+ }
147
+
148
+ private deliver(listener: WebFrameListener, json: string): void {
149
+ try {
150
+ listener(json)
151
+ } catch {
152
+ // A broken subscriber leaves; the others still receive the frame.
153
+ this.remove(listener)
154
+ }
155
+ }
156
+ }
157
+
158
+ function noticeFrame(error: unknown): WebFrame {
159
+ return { notice: `Viewer unavailable: ${error instanceof Error ? error.message : String(error)}` }
160
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Web server options shared by `ab web` and `ab dispatch --web`. No store,
3
+ * React or server imports, so the dispatcher launcher can use it without
4
+ * widening its filesystem/process-only import graph.
5
+ */
6
+
7
+ export const DEFAULT_WEB_HOST = '127.0.0.1'
8
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1'])
9
+
10
+ /** True when `host` keeps the server on this machine. */
11
+ export function isLoopbackHost(host: string): boolean {
12
+ return LOOPBACK.has(host.toLowerCase())
13
+ }
14
+
15
+ /** Parse `--port`: an integer from 0 to 65535; 0 lets the OS choose. */
16
+ export function parseWebPort(value: string | undefined, usage: string): number {
17
+ if (value === undefined) return 0
18
+ const port = Number(value)
19
+ if (!/^\d+$/u.test(value) || !Number.isInteger(port) || port < 0 || port > 65_535)
20
+ throw new Error(`--port requires an integer from 0 to 65535, got "${value}" — ${usage}`)
21
+ return port
22
+ }
23
+
24
+ /** Ask the OS for a free port on `hostname`, then release it. A dispatcher
25
+ * launcher pins it into every generation's argv, so the URL it announces
26
+ * survives runtime upgrades. One local bind; no store. */
27
+ export async function reserveWebPort(hostname: string): Promise<number> {
28
+ const server = Bun.serve({
29
+ hostname,
30
+ port: 0,
31
+ reusePort: false,
32
+ fetch: () => new Response(null, { status: 503 }),
33
+ })
34
+ const port = server.port
35
+ await server.stop(true)
36
+ if (port === undefined) throw new Error(`could not reserve a web port on ${hostname}`)
37
+ return port
38
+ }