@exla/rudder 4.0.0-alpha.7 → 4.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 (238) hide show
  1. package/README.md +33 -69
  2. package/assets/skills/burst/SKILL.md +64 -0
  3. package/dist/agent-efficiency/backend-observer.d.ts +13 -0
  4. package/dist/agent-efficiency/backend-observer.js +77 -0
  5. package/dist/agent-efficiency/backend-observer.js.map +1 -0
  6. package/dist/agent-efficiency/handoff.d.ts +9 -0
  7. package/dist/agent-efficiency/handoff.js +42 -0
  8. package/dist/agent-efficiency/handoff.js.map +1 -0
  9. package/dist/agent-efficiency/index.d.ts +11 -0
  10. package/dist/agent-efficiency/index.js +7 -0
  11. package/dist/agent-efficiency/index.js.map +1 -0
  12. package/dist/agent-efficiency/lessons.d.ts +55 -0
  13. package/dist/agent-efficiency/lessons.js +107 -0
  14. package/dist/agent-efficiency/lessons.js.map +1 -0
  15. package/dist/agent-efficiency/privacy.d.ts +6 -0
  16. package/dist/agent-efficiency/privacy.js +28 -0
  17. package/dist/agent-efficiency/privacy.js.map +1 -0
  18. package/dist/agent-efficiency/production.d.ts +16 -0
  19. package/dist/agent-efficiency/production.js +120 -0
  20. package/dist/agent-efficiency/production.js.map +1 -0
  21. package/dist/agent-efficiency/storage.d.ts +3 -0
  22. package/dist/agent-efficiency/storage.js +28 -0
  23. package/dist/agent-efficiency/storage.js.map +1 -0
  24. package/dist/agent-efficiency/telemetry.d.ts +59 -0
  25. package/dist/agent-efficiency/telemetry.js +143 -0
  26. package/dist/agent-efficiency/telemetry.js.map +1 -0
  27. package/dist/agent-efficiency/trace-lessons.d.ts +21 -0
  28. package/dist/agent-efficiency/trace-lessons.js +36 -0
  29. package/dist/agent-efficiency/trace-lessons.js.map +1 -0
  30. package/dist/agent-efficiency/waits.d.ts +52 -0
  31. package/dist/agent-efficiency/waits.js +131 -0
  32. package/dist/agent-efficiency/waits.js.map +1 -0
  33. package/dist/backends.js +14 -8
  34. package/dist/backends.js.map +1 -1
  35. package/dist/board/authority.d.ts +48 -0
  36. package/dist/board/authority.js +125 -0
  37. package/dist/board/authority.js.map +1 -0
  38. package/dist/board/board.js +6 -2
  39. package/dist/board/daemon.d.ts +3 -6
  40. package/dist/board/daemon.js +242 -222
  41. package/dist/board/daemon.js.map +1 -1
  42. package/dist/board/host-access.d.ts +8 -0
  43. package/dist/board/host-access.js +222 -0
  44. package/dist/board/host-access.js.map +1 -0
  45. package/dist/board/project-files.d.ts +12 -0
  46. package/dist/board/project-files.js +78 -0
  47. package/dist/board/project-files.js.map +1 -0
  48. package/dist/brain.d.ts +2 -1
  49. package/dist/brain.js +15 -21
  50. package/dist/brain.js.map +1 -1
  51. package/dist/claude-sdk-protocol.js +10 -7
  52. package/dist/claude-sdk-protocol.js.map +1 -1
  53. package/dist/cloud-build-profile.d.ts +22 -0
  54. package/dist/cloud-build-profile.js +160 -0
  55. package/dist/cloud-build-profile.js.map +1 -0
  56. package/dist/cloud.js +23 -470
  57. package/dist/cloud.js.map +1 -1
  58. package/dist/codex-binary.d.ts +1 -0
  59. package/dist/codex-binary.js +8 -1
  60. package/dist/codex-binary.js.map +1 -1
  61. package/dist/daemon.d.ts +2 -0
  62. package/dist/daemon.js +14 -2
  63. package/dist/daemon.js.map +1 -1
  64. package/dist/effort.d.ts +8 -0
  65. package/dist/effort.js +15 -2
  66. package/dist/effort.js.map +1 -1
  67. package/dist/engine-authority.js +16 -0
  68. package/dist/engine-authority.js.map +1 -1
  69. package/dist/engine.d.ts +1 -1
  70. package/dist/engine.js +11 -2
  71. package/dist/engine.js.map +1 -1
  72. package/dist/fabric-fetch.d.ts +25 -0
  73. package/dist/fabric-fetch.js +402 -0
  74. package/dist/fabric-fetch.js.map +1 -0
  75. package/dist/fabric-local.d.ts +5 -2
  76. package/dist/fabric-local.js +36 -1
  77. package/dist/fabric-local.js.map +1 -1
  78. package/dist/fabric-remote.d.ts +76 -1
  79. package/dist/fabric-remote.js +333 -61
  80. package/dist/fabric-remote.js.map +1 -1
  81. package/dist/git.js +23 -0
  82. package/dist/git.js.map +1 -1
  83. package/dist/graph.js +9 -1
  84. package/dist/graph.js.map +1 -1
  85. package/dist/jj.d.ts +3 -1
  86. package/dist/jj.js +34 -2
  87. package/dist/jj.js.map +1 -1
  88. package/dist/main.js +115 -311
  89. package/dist/main.js.map +1 -1
  90. package/dist/migration.d.ts +2 -0
  91. package/dist/migration.js +3 -0
  92. package/dist/migration.js.map +1 -1
  93. package/dist/models.js +11 -6
  94. package/dist/models.js.map +1 -1
  95. package/dist/native/darwin-arm64/native-manifest.json +19 -0
  96. package/dist/native/darwin-arm64/rudder-jj +0 -0
  97. package/dist/native/darwin-arm64/rudder-native +0 -0
  98. package/dist/native/linux-x64/native-manifest.json +19 -0
  99. package/dist/native/linux-x64/rudder-jj +0 -0
  100. package/dist/native/linux-x64/rudder-native +0 -0
  101. package/dist/native-agents.js +3 -7
  102. package/dist/native-agents.js.map +1 -1
  103. package/dist/native-binary.js +11 -1
  104. package/dist/native-binary.js.map +1 -1
  105. package/dist/operations/cli.d.ts +23 -0
  106. package/dist/operations/cli.js +110 -0
  107. package/dist/operations/cli.js.map +1 -0
  108. package/dist/operations/registry.d.ts +1076 -0
  109. package/dist/operations/registry.js +69 -0
  110. package/dist/operations/registry.js.map +1 -0
  111. package/dist/operations/registry.json +124 -0
  112. package/dist/operations/requests.d.ts +167 -0
  113. package/dist/operations/requests.js +223 -0
  114. package/dist/operations/requests.js.map +1 -0
  115. package/dist/planning-ownership/index.d.ts +134 -0
  116. package/dist/planning-ownership/index.js +291 -0
  117. package/dist/planning-ownership/index.js.map +1 -0
  118. package/dist/planning-ownership/ingress.d.ts +30 -0
  119. package/dist/planning-ownership/ingress.js +41 -0
  120. package/dist/planning-ownership/ingress.js.map +1 -0
  121. package/dist/planning-ownership/store.d.ts +19 -0
  122. package/dist/planning-ownership/store.js +30 -0
  123. package/dist/planning-ownership/store.js.map +1 -0
  124. package/dist/private-access/cli.d.ts +22 -0
  125. package/dist/private-access/cli.js +76 -0
  126. package/dist/private-access/cli.js.map +1 -0
  127. package/dist/private-access/engine.d.ts +20 -0
  128. package/dist/private-access/engine.js +47 -0
  129. package/dist/private-access/engine.js.map +1 -0
  130. package/dist/private-access/home.d.ts +21 -0
  131. package/dist/private-access/home.js +80 -0
  132. package/dist/private-access/home.js.map +1 -0
  133. package/dist/private-access/previews.d.ts +101 -0
  134. package/dist/private-access/previews.js +447 -0
  135. package/dist/private-access/previews.js.map +1 -0
  136. package/dist/project-files/cli.d.ts +7 -0
  137. package/dist/project-files/cli.js +22 -0
  138. package/dist/project-files/cli.js.map +1 -0
  139. package/dist/project-files/engine.d.ts +14 -0
  140. package/dist/project-files/engine.js +52 -0
  141. package/dist/project-files/engine.js.map +1 -0
  142. package/dist/project-files/home.d.ts +13 -0
  143. package/dist/project-files/home.js +46 -0
  144. package/dist/project-files/home.js.map +1 -0
  145. package/dist/project-files/http.d.ts +9 -0
  146. package/dist/project-files/http.js +54 -0
  147. package/dist/project-files/http.js.map +1 -0
  148. package/dist/project-files/open.d.ts +10 -0
  149. package/dist/project-files/open.js +37 -0
  150. package/dist/project-files/open.js.map +1 -0
  151. package/dist/project-files/references.d.ts +9 -0
  152. package/dist/project-files/references.js +29 -0
  153. package/dist/project-files/references.js.map +1 -0
  154. package/dist/project-files/service.d.ts +32 -0
  155. package/dist/project-files/service.js +236 -0
  156. package/dist/project-files/service.js.map +1 -0
  157. package/dist/project-files/types.d.ts +40 -0
  158. package/dist/project-files/types.js +2 -0
  159. package/dist/project-files/types.js.map +1 -0
  160. package/dist/run-manager.d.ts +8 -0
  161. package/dist/run-manager.js +193 -13
  162. package/dist/run-manager.js.map +1 -1
  163. package/dist/run-timeline.d.ts +31 -0
  164. package/dist/run-timeline.js +116 -0
  165. package/dist/run-timeline.js.map +1 -0
  166. package/dist/scheduler.js +72 -13
  167. package/dist/scheduler.js.map +1 -1
  168. package/dist/surfaces.js +3 -8
  169. package/dist/surfaces.js.map +1 -1
  170. package/dist/tailscale-preview.d.ts +6 -2
  171. package/dist/tailscale-preview.js +58 -13
  172. package/dist/tailscale-preview.js.map +1 -1
  173. package/dist/task-routing.d.ts +2 -0
  174. package/dist/task-routing.js +42 -25
  175. package/dist/task-routing.js.map +1 -1
  176. package/dist/terminal-screen.d.ts +6 -0
  177. package/dist/terminal-screen.js +23 -0
  178. package/dist/terminal-screen.js.map +1 -0
  179. package/dist/tool-cache.d.ts +23 -0
  180. package/dist/tool-cache.js +144 -0
  181. package/dist/tool-cache.js.map +1 -0
  182. package/dist/types.d.ts +0 -17
  183. package/dist/types.js.map +1 -1
  184. package/dist/util.d.ts +8 -0
  185. package/dist/util.js +38 -2
  186. package/dist/util.js.map +1 -1
  187. package/dist/v4-migration/capture.d.ts +53 -0
  188. package/dist/v4-migration/capture.js +197 -0
  189. package/dist/v4-migration/capture.js.map +1 -0
  190. package/dist/v4-migration/cli.d.ts +4 -0
  191. package/dist/v4-migration/cli.js +38 -0
  192. package/dist/v4-migration/cli.js.map +1 -0
  193. package/dist/v4-migration/recovery.d.ts +43 -0
  194. package/dist/v4-migration/recovery.js +180 -0
  195. package/dist/v4-migration/recovery.js.map +1 -0
  196. package/dist/version-check.d.ts +2 -0
  197. package/dist/version-check.js +23 -0
  198. package/dist/version-check.js.map +1 -1
  199. package/dist/warm-snapshot.d.ts +55 -0
  200. package/dist/warm-snapshot.js +382 -0
  201. package/dist/warm-snapshot.js.map +1 -0
  202. package/package.json +4 -3
  203. package/scripts/copy-native.mjs +35 -48
  204. package/scripts/native-artifacts.mjs +248 -0
  205. package/dist/improve/advisor.d.ts +0 -10
  206. package/dist/improve/advisor.js +0 -115
  207. package/dist/improve/advisor.js.map +0 -1
  208. package/dist/improve/collect.d.ts +0 -49
  209. package/dist/improve/collect.js +0 -274
  210. package/dist/improve/collect.js.map +0 -1
  211. package/dist/improve/gate.d.ts +0 -17
  212. package/dist/improve/gate.js +0 -60
  213. package/dist/improve/gate.js.map +0 -1
  214. package/dist/improve/index.d.ts +0 -9
  215. package/dist/improve/index.js +0 -376
  216. package/dist/improve/index.js.map +0 -1
  217. package/dist/improve/judge.d.ts +0 -32
  218. package/dist/improve/judge.js +0 -114
  219. package/dist/improve/judge.js.map +0 -1
  220. package/dist/improve/mine.d.ts +0 -31
  221. package/dist/improve/mine.js +0 -192
  222. package/dist/improve/mine.js.map +0 -1
  223. package/dist/improve/propose.d.ts +0 -51
  224. package/dist/improve/propose.js +0 -150
  225. package/dist/improve/propose.js.map +0 -1
  226. package/dist/improve/rank.d.ts +0 -16
  227. package/dist/improve/rank.js +0 -49
  228. package/dist/improve/rank.js.map +0 -1
  229. package/dist/improve/schedule.d.ts +0 -1
  230. package/dist/improve/schedule.js +0 -95
  231. package/dist/improve/schedule.js.map +0 -1
  232. package/dist/improve/ship.d.ts +0 -25
  233. package/dist/improve/ship.js +0 -82
  234. package/dist/improve/ship.js.map +0 -1
  235. package/dist/improve/state.d.ts +0 -157
  236. package/dist/improve/state.js +0 -264
  237. package/dist/improve/state.js.map +0 -1
  238. package/dist/native/darwin-x64/rudder-native +0 -0
@@ -1,66 +1,18 @@
1
- import { spawn } from "node:child_process";
2
- import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
1
+ import { randomUUID } from "node:crypto";
3
2
  import fs from "node:fs";
4
3
  import fsp from "node:fs/promises";
5
4
  import http from "node:http";
6
5
  import path from "node:path";
7
6
  import { fileURLToPath } from "node:url";
8
- // Per-daemon secret. The SPA shell embeds it (only loopback callers ever receive
9
- // the shell — see the Host check below) and the browser echoes it back as the
10
- // `x-rudder-token` header on every mutating request. A custom header forces a CORS
11
- // preflight cross-origin (which this server never approves) and the value is
12
- // unguessable, so a drive-by web page cannot forge a steer/inject/merge/cancel.
13
- const BOARD_TOKEN = randomBytes(24).toString("hex");
14
- // Cap request bodies so an unauthenticated POST can't buffer unbounded memory.
7
+ import { BoardAuthority } from "./authority.js";
8
+ import { openBoardBrowser, serveBoardHostAccess } from "./host-access.js";
9
+ import { BoardProjectFiles } from "./project-files.js";
15
10
  const MAX_BODY_BYTES = 1_000_000;
16
- /** This process's board token (exported for tests; it is regenerated each start). */
17
- export function getBoardToken() {
18
- return BOARD_TOKEN;
19
- }
20
- /** The board binds 127.0.0.1 only, so a legitimate Host header is always loopback.
21
- * Rejecting anything else defeats DNS-rebinding: an attacker page whose hostname
22
- * resolves to 127.0.0.1 still sends its own (non-loopback) Host. */
23
11
  export function isLoopbackHost(req) {
24
12
  const host = (req.headers.host ?? "").trim().toLowerCase();
25
13
  const name = host.replace(/:\d+$/, "");
26
14
  return name === "127.0.0.1" || name === "localhost" || name === "[::1]" || name === "::1";
27
15
  }
28
- function isLoopbackOrigin(origin) {
29
- try {
30
- const h = new URL(origin).hostname.toLowerCase();
31
- return h === "127.0.0.1" || h === "localhost" || h === "::1";
32
- }
33
- catch {
34
- return false;
35
- }
36
- }
37
- export function hasValidToken(req) {
38
- const header = req.headers["x-rudder-token"];
39
- const token = Array.isArray(header) ? header[0] : header;
40
- if (typeof token !== "string" || token.length !== BOARD_TOKEN.length) {
41
- return false;
42
- }
43
- try {
44
- return timingSafeEqual(Buffer.from(token), Buffer.from(BOARD_TOKEN));
45
- }
46
- catch {
47
- return false;
48
- }
49
- }
50
- /** Guard every state-mutating request. Returns true (after writing a 403) when the
51
- * request must be denied: a non-loopback Origin, or a missing/invalid token. */
52
- function denyMutation(req, res) {
53
- const origin = req.headers.origin;
54
- if (typeof origin === "string" && origin.length > 0 && !isLoopbackOrigin(origin)) {
55
- sendJson(res, 403, { error: "forbidden origin" });
56
- return true;
57
- }
58
- if (!hasValidToken(req)) {
59
- sendJson(res, 403, { error: "missing or invalid board token" });
60
- return true;
61
- }
62
- return false;
63
- }
64
16
  import { findProjectBySlug, loadProjects, loadRunRecord, outputPath, projectStateDir, runsDir } from "../state.js";
65
17
  import { mergeJjRunIntoCurrentWorkspace } from "../jj.js";
66
18
  import { hardParents, readGraph, softParents, updateGraph } from "../graph.js";
@@ -74,38 +26,37 @@ import { fetchQuota, machineResources, scanTokenUsage } from "../usage.js";
74
26
  const BOARD_JS_PATH = fileURLToPath(new URL("./board.js", import.meta.url));
75
27
  const BOARD_CSS_PATH = fileURLToPath(new URL("./board.css", import.meta.url));
76
28
  const logger = createLogger("board", { fileName: "daemon.log" });
77
- // One Set of SSE clients per slug, plus one fs.watch per watched runs dir.
78
- const sseClients = new Map();
79
- const watchers = new Map();
80
- // A second watch per slug on the tracked DECISIONS.md at the repo root: it lives
81
- // outside .rudder, so a sibling decision (or `rudder remember`) must trigger a
82
- // re-broadcast (memory.updated SSE) the same way a run/graph change does.
83
- const decisionsWatchers = new Map();
84
- const watchTimers = new Map();
85
29
  export async function startBoardDaemon(opts) {
86
30
  const controlMode = opts.controlMode ?? "projector";
31
+ let slug = "";
32
+ try {
33
+ const projects = await loadProjects();
34
+ slug = projects.find((entry) => sameRepoPath(entry.repoRoot, opts.repoRoot))?.slug ?? "";
35
+ }
36
+ catch { /* A new project can still open its index. */ }
37
+ const authority = new BoardAuthority(slug, controlMode);
38
+ const state = { authority, files: new BoardProjectFiles(), sseClients: new Map(), watchers: new Map(),
39
+ decisionsWatchers: new Map(), watchTimers: new Map(), lastNodes: new Map(), lastEdges: new Map(),
40
+ lastMemory: new Map(), lastActivity: new Map(), broadcasts: new Map() };
87
41
  // Subscribe the SSE broadcaster to the shared bus: node.*/schedule.*/merge.*
88
42
  // events re-broadcast a fresh snapshot to every connected client (simplest
89
43
  // correct projection; the SPA always rebuilds from the snapshot on connect).
90
44
  let unsubscribe;
91
45
  if (opts.bus) {
92
46
  unsubscribe = opts.bus.subscribe(() => {
93
- for (const slug of sseClients.keys()) {
94
- void rebroadcastForSlug(slug);
47
+ for (const slug of state.sseClients.keys()) {
48
+ void rebroadcastForSlug(slug, state);
95
49
  }
96
50
  });
97
51
  }
98
- const server = http.createServer((req, res) => {
99
- handleRequest(req, res, opts.bus, controlMode, opts.repoRoot).catch((error) => {
100
- const message = error instanceof Error ? error.message : String(error);
52
+ const server = http.createServer({ maxHeaderSize: 8192, headersTimeout: 5000, requestTimeout: 5000,
53
+ keepAliveTimeout: 5000, connectionsCheckingInterval: 500 }, (req, res) => {
54
+ handleRequest(req, res, opts.bus, controlMode, opts.repoRoot, state).catch(() => {
101
55
  logger.warn("board request failed", {
102
56
  method: req.method,
103
- url: req.url,
104
- repoRoot: opts.repoRoot,
105
- error: message,
106
57
  });
107
58
  if (!res.headersSent) {
108
- sendJson(res, 500, { error: message });
59
+ sendJson(res, 500, { error: "board request failed" });
109
60
  }
110
61
  else {
111
62
  try {
@@ -117,31 +68,55 @@ export async function startBoardDaemon(opts) {
117
68
  }
118
69
  });
119
70
  });
120
- await new Promise((resolve, reject) => {
121
- server.once("error", reject);
122
- server.listen(opts.port, "127.0.0.1", () => {
123
- server.removeListener("error", reject);
124
- resolve();
71
+ server.maxConnections = 128;
72
+ server.maxRequestsPerSocket = 100;
73
+ try {
74
+ await new Promise((resolve, reject) => {
75
+ server.once("error", reject);
76
+ server.listen(opts.port, "127.0.0.1", () => {
77
+ server.removeListener("error", reject);
78
+ resolve();
79
+ });
125
80
  });
126
- });
81
+ }
82
+ catch (error) {
83
+ authority.close();
84
+ unsubscribe?.();
85
+ throw error;
86
+ }
127
87
  const address = server.address();
128
88
  const port = typeof address === "object" && address ? address.port : opts.port;
129
- const url = `http://127.0.0.1:${port}`;
130
- const close = async () => {
89
+ const url = new URL(`http://127.0.0.1:${port}`).origin;
90
+ authority.bindOrigin(url);
91
+ let host;
92
+ try {
93
+ host = await serveBoardHostAccess(opts.repoRoot, authority);
94
+ }
95
+ catch (error) {
96
+ authority.close();
97
+ server.close();
131
98
  unsubscribe?.();
132
- for (const [, timer] of watchTimers) {
99
+ throw error;
100
+ }
101
+ let closing;
102
+ const close = () => closing ??= (async () => {
103
+ authority.close();
104
+ server.closeAllConnections();
105
+ await host.close();
106
+ unsubscribe?.();
107
+ for (const [, timer] of state.watchTimers) {
133
108
  clearTimeout(timer);
134
109
  }
135
- watchTimers.clear();
136
- for (const [, watcher] of watchers) {
110
+ state.watchTimers.clear();
111
+ for (const [, watcher] of state.watchers) {
137
112
  watcher.close();
138
113
  }
139
- watchers.clear();
140
- for (const [, watcher] of decisionsWatchers) {
114
+ state.watchers.clear();
115
+ for (const [, watcher] of state.decisionsWatchers) {
141
116
  watcher.close();
142
117
  }
143
- decisionsWatchers.clear();
144
- for (const [, clients] of sseClients) {
118
+ state.decisionsWatchers.clear();
119
+ for (const [, clients] of state.sseClients) {
145
120
  for (const client of clients) {
146
121
  try {
147
122
  client.res.end();
@@ -151,33 +126,55 @@ export async function startBoardDaemon(opts) {
151
126
  }
152
127
  }
153
128
  }
154
- sseClients.clear();
129
+ state.sseClients.clear();
155
130
  await new Promise((resolve) => server.close(() => resolve()));
156
- };
157
- // Determine this repo's slug for the open-browser convenience landing.
158
- let slug = "";
159
- try {
160
- const projects = await loadProjects();
161
- slug = projects.find((entry) => sameRepoPath(entry.repoRoot, opts.repoRoot))?.slug ?? "";
162
- }
163
- catch {
164
- slug = "";
165
- }
131
+ })();
166
132
  if (opts.open) {
167
- openBrowser(slug ? `${url}/rudder/${slug}` : `${url}/rudder`);
133
+ await openBoardBrowser(authority.bootstrapUrl()).catch(() => logger.warn("browser opener is unavailable"));
168
134
  }
169
- return { port, url, close };
135
+ return { port, url, instanceId: authority.instanceId, bootstrapUrl: (target) => authority.bootstrapUrl(target), close };
170
136
  }
171
- async function handleRequest(req, res, bus, controlMode, ownerRepoRoot) {
137
+ async function handleRequest(req, res, bus, controlMode, ownerRepoRoot, state) {
172
138
  const url = new URL(req.url || "/", "http://127.0.0.1");
173
139
  const pathname = decodeURIComponent(url.pathname);
174
140
  const method = (req.method || "GET").toUpperCase();
175
141
  // Anti-DNS-rebinding: the board is loopback-only, so reject any request whose Host
176
- // is not loopback before it can read state or serve the token-bearing shell.
177
- if (!isLoopbackHost(req)) {
142
+ // is not the bound loopback origin before serving even the neutral shell.
143
+ res.setHeader("Cache-Control", "no-store");
144
+ res.setHeader("Referrer-Policy", "no-referrer");
145
+ res.setHeader("X-Content-Type-Options", "nosniff");
146
+ res.setHeader("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'; object-src 'none'; form-action 'self'");
147
+ if (!isLoopbackHost(req) || !state.authority.matchesOrigin(req)) {
178
148
  sendJson(res, 403, { error: "forbidden host" });
179
149
  return;
180
150
  }
151
+ if (pathname === "/api/board/descriptor" && method === "GET") {
152
+ sendJson(res, 200, state.authority.descriptor());
153
+ return;
154
+ }
155
+ if (pathname === "/api/board/session" && method === "POST") {
156
+ const body = await readJsonBody(req, 4096);
157
+ const exchanged = Object.keys(body).sort().join(",") === "instance_id,ticket"
158
+ ? state.authority.exchange(req, body.ticket, body.instance_id) : null;
159
+ sendJson(res, exchanged ? 200 : 401, exchanged ?? { error: "Board access is unavailable" });
160
+ return;
161
+ }
162
+ let session = null;
163
+ if (pathname.startsWith("/api/")) {
164
+ session = state.authority.authenticate(req);
165
+ if (!session) {
166
+ sendJson(res, 401, { error: "Open this board from Rudder to connect" });
167
+ return;
168
+ }
169
+ }
170
+ if (pathname === "/api/board/session" && method === "GET") {
171
+ sendJson(res, 200, state.authority.info(session));
172
+ return;
173
+ }
174
+ if (pathname === "/api/board/session/renew" && method === "POST") {
175
+ sendJson(res, 200, state.authority.renew(session));
176
+ return;
177
+ }
181
178
  // Static SPA bundle.
182
179
  if (method === "GET" && pathname === "/board.js") {
183
180
  await sendStatic(res, BOARD_JS_PATH, "text/javascript; charset=utf-8");
@@ -191,7 +188,7 @@ async function handleRequest(req, res, bus, controlMode, ownerRepoRoot) {
191
188
  // resources. Read-only, machine-wide (not per project), loopback-only like
192
189
  // everything else here.
193
190
  if (method === "GET" && (pathname === "/usage" || pathname === "/rudder/usage")) {
194
- sendHtml(res, renderShell("", controlMode, false, "usage"));
191
+ sendHtml(res, renderShell());
195
192
  return;
196
193
  }
197
194
  if (method === "GET" && pathname === "/api/usage/tokens") {
@@ -233,35 +230,32 @@ async function handleRequest(req, res, bus, controlMode, ownerRepoRoot) {
233
230
  if (apiMatch) {
234
231
  const slug = apiMatch[1] ?? "";
235
232
  const rest = apiMatch[2] ?? "";
236
- await handleProjectApi(req, res, method, slug, rest, url, bus, controlMode, ownerRepoRoot);
233
+ await handleProjectApi(req, res, method, slug, rest, url, bus, controlMode, ownerRepoRoot, state, session);
237
234
  return;
238
235
  }
239
236
  // SPA shell for the index and per-project routes.
240
237
  if (method === "GET" && (pathname === "/" || pathname === "/rudder")) {
241
- sendHtml(res, renderShell("", controlMode, false));
238
+ sendHtml(res, renderShell());
242
239
  return;
243
240
  }
244
241
  const slugMatch = pathname.match(/^\/rudder\/([^/]+)\/?$/);
245
242
  if (method === "GET" && slugMatch) {
246
243
  const slug = slugMatch[1] ?? "";
247
- const project = await findProjectBySlug(slug);
248
- const canMutate = Boolean(project && sameRepoPath(project.repoRoot, ownerRepoRoot));
249
- sendHtml(res, renderShell(slug, controlMode, canMutate));
244
+ sendHtml(res, renderShell());
250
245
  return;
251
246
  }
252
247
  sendJson(res, 404, { error: "not found" });
253
248
  }
254
- async function handleProjectApi(req, res, method, slug, rest, url, bus, controlMode = "projector", ownerRepoRoot = "") {
249
+ async function handleProjectApi(req, res, method, slug, rest, url, bus, controlMode = "projector", ownerRepoRoot = "", state, session) {
250
+ if (!state.authority.valid(session)) {
251
+ sendJson(res, 401, { error: "Board session expired" });
252
+ return;
253
+ }
255
254
  const project = await findProjectBySlug(slug);
256
255
  if (!project) {
257
256
  sendJson(res, 404, { error: `unknown project: ${slug}` });
258
257
  return;
259
258
  }
260
- // Every mutating route is a POST. Require the secret token (+ loopback origin)
261
- // before any of them run, so a cross-site page cannot steer/inject/merge/cancel.
262
- if (method === "POST" && denyMutation(req, res)) {
263
- return;
264
- }
265
259
  // One daemon owns exactly one repository's scheduler or native-projector
266
260
  // channel. Other registered projects remain readable in the overview, but
267
261
  // mutations here would route work to the wrong owner.
@@ -278,8 +272,12 @@ async function handleProjectApi(req, res, method, slug, rest, url, bus, controlM
278
272
  sendJson(res, 200, snapshot);
279
273
  return;
280
274
  }
275
+ if (rest === "/files" || rest === "/file-scopes") {
276
+ await state.files.handle(req, res, url, project.repoRoot, state.authority, session);
277
+ return;
278
+ }
281
279
  if (rest === "/events" && method === "GET") {
282
- await handleSse(req, res, project);
280
+ await handleSse(req, res, project, state, session);
283
281
  return;
284
282
  }
285
283
  const steerReceiptMatch = rest.match(/^\/steer-receipts\/([A-Za-z0-9-]+)$/);
@@ -778,63 +776,66 @@ async function handleProjectsList(res) {
778
776
  // ---------------------------------------------------------------------------
779
777
  // SSE: emit a full snapshot on connect, then deltas driven by fs.watch.
780
778
  // ---------------------------------------------------------------------------
781
- async function handleSse(req, res, project) {
782
- res.writeHead(200, {
783
- "content-type": "text/event-stream",
784
- "cache-control": "no-cache, no-transform",
785
- connection: "keep-alive",
786
- });
779
+ async function handleSse(req, res, project, state, session) {
780
+ const release = state.authority.registerStream(session, () => res.destroy());
781
+ if (!release) {
782
+ sendJson(res, 429, { error: "Board stream capacity is busy" });
783
+ return;
784
+ }
785
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store", connection: "keep-alive" });
787
786
  res.write(": connected\n\n");
788
- const client = { res };
789
- let set = sseClients.get(project.slug);
790
- if (!set) {
791
- set = new Set();
792
- sseClients.set(project.slug, set);
793
- }
794
- set.add(client);
795
- ensureWatcher(project);
796
- // Full snapshot on connect.
797
- const snapshot = await buildSnapshot(project);
798
- writeSseFrame(res, "snapshot", snapshot);
787
+ const client = { res, session };
788
+ let clients = state.sseClients.get(project.slug);
789
+ if (!clients) {
790
+ clients = new Set();
791
+ state.sseClients.set(project.slug, clients);
792
+ }
793
+ clients.add(client);
794
+ let cleaned = false;
799
795
  const ping = setInterval(() => {
800
- try {
801
- res.write(": ping\n\n");
802
- }
803
- catch {
804
- // ignore
796
+ if (!state.authority.valid(session) || res.writableLength > 8 * 1024 * 1024) {
797
+ res.destroy();
798
+ return;
805
799
  }
806
- }, 15000);
807
- ping.unref?.();
800
+ res.write(": ping\n\n");
801
+ }, 15_000);
802
+ ping.unref();
808
803
  const cleanup = () => {
804
+ if (cleaned)
805
+ return;
806
+ cleaned = true;
807
+ release();
809
808
  clearInterval(ping);
810
- const clients = sseClients.get(project.slug);
811
- if (clients) {
812
- clients.delete(client);
813
- if (clients.size === 0) {
814
- sseClients.delete(project.slug);
815
- const watcher = watchers.get(project.slug);
816
- if (watcher) {
817
- watcher.close();
818
- watchers.delete(project.slug);
819
- }
820
- const decisionsWatcher = decisionsWatchers.get(project.slug);
821
- if (decisionsWatcher) {
822
- decisionsWatcher.close();
823
- decisionsWatchers.delete(project.slug);
824
- }
825
- const timer = watchTimers.get(project.slug);
826
- if (timer) {
827
- clearTimeout(timer);
828
- watchTimers.delete(project.slug);
829
- }
830
- }
809
+ const clients = state.sseClients.get(project.slug);
810
+ clients?.delete(client);
811
+ if (clients?.size === 0) {
812
+ state.sseClients.delete(project.slug);
813
+ state.watchers.get(project.slug)?.close();
814
+ state.watchers.delete(project.slug);
815
+ state.decisionsWatchers.get(project.slug)?.close();
816
+ state.decisionsWatchers.delete(project.slug);
817
+ clearTimeout(state.watchTimers.get(project.slug));
818
+ state.watchTimers.delete(project.slug);
819
+ state.lastNodes.delete(project.slug);
820
+ state.lastEdges.delete(project.slug);
821
+ state.lastMemory.delete(project.slug);
822
+ state.lastActivity.delete(project.slug);
831
823
  }
832
824
  };
833
- req.on("close", cleanup);
834
- res.on("close", cleanup);
825
+ req.once("aborted", cleanup);
826
+ res.once("close", cleanup);
827
+ ensureWatcher(project, state);
828
+ try {
829
+ writeSseFrame(state, client, "snapshot", await buildSnapshot(project));
830
+ }
831
+ catch {
832
+ res.destroy();
833
+ }
834
+ if (res.destroyed)
835
+ cleanup();
835
836
  }
836
- function ensureWatcher(project) {
837
- if (watchers.has(project.slug)) {
837
+ function ensureWatcher(project, state) {
838
+ if (state.watchers.has(project.slug)) {
838
839
  return;
839
840
  }
840
841
  // Watch the whole .rudder dir recursively: this covers both runs/<id>/*.json
@@ -850,27 +851,27 @@ function ensureWatcher(project) {
850
851
  }
851
852
  let watcher;
852
853
  try {
853
- watcher = fs.watch(dir, { recursive: true }, () => scheduleBroadcast(project));
854
+ watcher = fs.watch(dir, { recursive: true }, () => scheduleBroadcast(project, state));
854
855
  }
855
856
  catch {
856
857
  try {
857
858
  // Non-recursive fallback: watch the runs dir (most active) since some
858
859
  // platforms reject recursive watches.
859
- watcher = fs.watch(runsPath, () => scheduleBroadcast(project));
860
+ watcher = fs.watch(runsPath, () => scheduleBroadcast(project, state));
860
861
  }
861
862
  catch {
862
863
  return;
863
864
  }
864
865
  }
865
866
  watcher.on("error", () => undefined);
866
- watchers.set(project.slug, watcher);
867
- ensureDecisionsWatcher(project);
867
+ state.watchers.set(project.slug, watcher);
868
+ ensureDecisionsWatcher(project, state);
868
869
  }
869
870
  // Watch the repo-root DECISIONS.md (created on first render if absent) so an
870
871
  // agent or `rudder remember` appending a decision fires a re-broadcast and the
871
872
  // memory.updated SSE, exactly like a run/graph change inside .rudder.
872
- function ensureDecisionsWatcher(project) {
873
- if (decisionsWatchers.has(project.slug)) {
873
+ function ensureDecisionsWatcher(project, state) {
874
+ if (state.decisionsWatchers.has(project.slug)) {
874
875
  return;
875
876
  }
876
877
  const decisionsPath = path.join(project.repoRoot, "DECISIONS.md");
@@ -879,66 +880,77 @@ function ensureDecisionsWatcher(project) {
879
880
  // DECISIONS.md so the surface is covered even before it is first created.
880
881
  const watcher = fs.watch(project.repoRoot, (_event, filename) => {
881
882
  if (!filename || filename === "DECISIONS.md") {
882
- scheduleBroadcast(project);
883
+ scheduleBroadcast(project, state);
883
884
  }
884
885
  });
885
886
  watcher.on("error", () => undefined);
886
- decisionsWatchers.set(project.slug, watcher);
887
+ state.decisionsWatchers.set(project.slug, watcher);
887
888
  }
888
889
  catch {
889
890
  // Fall back to a direct file watch if the dir watch is rejected.
890
891
  try {
891
- const watcher = fs.watch(decisionsPath, () => scheduleBroadcast(project));
892
+ const watcher = fs.watch(decisionsPath, () => scheduleBroadcast(project, state));
892
893
  watcher.on("error", () => undefined);
893
- decisionsWatchers.set(project.slug, watcher);
894
+ state.decisionsWatchers.set(project.slug, watcher);
894
895
  }
895
896
  catch {
896
897
  // ignore: the .rudder watch + bus still cover most updates.
897
898
  }
898
899
  }
899
900
  }
900
- function scheduleBroadcast(project) {
901
- const existing = watchTimers.get(project.slug);
901
+ function scheduleBroadcast(project, state) {
902
+ const existing = state.watchTimers.get(project.slug);
902
903
  if (existing) {
903
904
  clearTimeout(existing);
904
905
  }
905
906
  const timer = setTimeout(() => {
906
- watchTimers.delete(project.slug);
907
- void broadcastSnapshot(project);
907
+ state.watchTimers.delete(project.slug);
908
+ void rebroadcastForSlug(project.slug, state);
908
909
  }, 50);
909
910
  timer.unref?.();
910
- watchTimers.set(project.slug, timer);
911
+ state.watchTimers.set(project.slug, timer);
911
912
  }
912
913
  // Phase 2 keeps deltas simple: recompute the snapshot and diff node ids so the
913
914
  // SPA receives node.added/node.updated/node.removed frames, mirroring the
914
915
  // cloud broadcast pattern (one payload, fan out to every client for the slug).
915
- const lastNodes = new Map();
916
- const lastEdges = new Map();
917
- const lastMemory = new Map();
918
- const lastActivity = new Map();
919
916
  function edgeKey(edge) {
920
917
  return `${edge.from}->${edge.to}:${edge.kind}`;
921
918
  }
922
919
  // Bus-driven re-broadcast: resolve the slug to a project and emit deltas. Used
923
920
  // when a scheduler/merge event fires so connected clients refresh without
924
921
  // waiting for the fs.watch debounce.
925
- async function rebroadcastForSlug(slug) {
926
- const clients = sseClients.get(slug);
927
- if (!clients || clients.size === 0) {
922
+ async function rebroadcastForSlug(slug, state) {
923
+ const active = state.broadcasts.get(slug);
924
+ if (active) {
925
+ active.again = true;
928
926
  return;
929
927
  }
930
- const project = await findProjectBySlug(slug);
931
- if (project) {
932
- await broadcastSnapshot(project);
928
+ const pending = { again: false };
929
+ state.broadcasts.set(slug, pending);
930
+ try {
931
+ do {
932
+ pending.again = false;
933
+ if (!state.sseClients.get(slug)?.size)
934
+ return;
935
+ const project = await findProjectBySlug(slug);
936
+ if (project && state.sseClients.get(slug)?.size)
937
+ await broadcastSnapshot(project, state);
938
+ } while (pending.again);
939
+ }
940
+ catch { /* A subsequent fs/bus event will retry projection. */ }
941
+ finally {
942
+ state.broadcasts.delete(slug);
933
943
  }
934
944
  }
935
- async function broadcastSnapshot(project) {
936
- const clients = sseClients.get(project.slug);
945
+ async function broadcastSnapshot(project, state) {
946
+ const clients = state.sseClients.get(project.slug);
937
947
  if (!clients || clients.size === 0) {
938
948
  return;
939
949
  }
940
950
  const snapshot = await buildSnapshot(project);
941
- const previous = lastNodes.get(project.slug) ?? new Map();
951
+ if (state.sseClients.get(project.slug) !== clients || clients.size === 0)
952
+ return;
953
+ const previous = state.lastNodes.get(project.slug) ?? new Map();
942
954
  const current = new Map();
943
955
  for (const node of snapshot.nodes) {
944
956
  current.set(node.id, node);
@@ -958,9 +970,9 @@ async function broadcastSnapshot(project) {
958
970
  frames.push({ event: "node.removed", data: { id } });
959
971
  }
960
972
  }
961
- lastNodes.set(project.slug, current);
973
+ state.lastNodes.set(project.slug, current);
962
974
  // Edge deltas from graph.json: edge.added / edge.removed for the Nest view.
963
- const previousEdges = lastEdges.get(project.slug) ?? new Map();
975
+ const previousEdges = state.lastEdges.get(project.slug) ?? new Map();
964
976
  const currentEdges = new Map();
965
977
  for (const edge of snapshot.edges) {
966
978
  currentEdges.set(edgeKey(edge), edge);
@@ -975,15 +987,15 @@ async function broadcastSnapshot(project) {
975
987
  frames.push({ event: "edge.removed", data: { from: edge.from, to: edge.to } });
976
988
  }
977
989
  }
978
- lastEdges.set(project.slug, currentEdges);
990
+ state.lastEdges.set(project.slug, currentEdges);
979
991
  const memoryKey = JSON.stringify(snapshot.memory);
980
- if (lastMemory.get(project.slug) !== memoryKey) {
981
- lastMemory.set(project.slug, memoryKey);
992
+ if (state.lastMemory.get(project.slug) !== memoryKey) {
993
+ state.lastMemory.set(project.slug, memoryKey);
982
994
  frames.push({ event: "memory.updated", data: { memory: snapshot.memory } });
983
995
  }
984
996
  const activityKey = JSON.stringify(snapshot.activity ?? []);
985
- if (lastActivity.get(project.slug) !== activityKey) {
986
- lastActivity.set(project.slug, activityKey);
997
+ if (state.lastActivity.get(project.slug) !== activityKey) {
998
+ state.lastActivity.set(project.slug, activityKey);
987
999
  frames.push({ event: "activity.updated", data: { activity: snapshot.activity ?? [] } });
988
1000
  }
989
1001
  if (frames.length === 0) {
@@ -991,14 +1003,24 @@ async function broadcastSnapshot(project) {
991
1003
  }
992
1004
  for (const client of clients) {
993
1005
  for (const frame of frames) {
994
- writeSseFrame(client.res, frame.event, frame.data);
1006
+ writeSseFrame(state, client, frame.event, frame.data);
995
1007
  }
996
1008
  }
997
1009
  }
998
- function writeSseFrame(res, event, data) {
1010
+ function writeSseFrame(state, client, event, data) {
1011
+ const { res } = client;
999
1012
  try {
1000
- res.write(`event: ${event}\n`);
1001
- res.write(`data: ${JSON.stringify(data)}\n\n`);
1013
+ if (!state.authority.valid(client.session)) {
1014
+ res.destroy();
1015
+ return;
1016
+ }
1017
+ const frame = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
1018
+ const bytes = Buffer.byteLength(frame);
1019
+ if (bytes > 4 * 1024 * 1024 || res.writableLength + bytes > 8 * 1024 * 1024) {
1020
+ res.destroy();
1021
+ return;
1022
+ }
1023
+ res.write(frame);
1002
1024
  }
1003
1025
  catch {
1004
1026
  // ignore broken pipe
@@ -1396,19 +1418,19 @@ async function loadActivity(repoRoot) {
1396
1418
  // ---------------------------------------------------------------------------
1397
1419
  // HTML shell. The SPA owns all CSS; this carries no inline styles.
1398
1420
  // ---------------------------------------------------------------------------
1399
- function renderShell(slug, controlMode, canMutate, view = "board") {
1400
- const slugJson = JSON.stringify(slug ?? "");
1421
+ function renderShell() {
1422
+ // No token, private project lookup or inline JSON. The browser derives its
1423
+ // route and loads all private metadata only after capability exchange.
1401
1424
  return `<!doctype html>
1402
1425
  <html lang="en">
1403
1426
  <head>
1404
1427
  <meta charset="utf-8" />
1405
1428
  <meta name="viewport" content="width=device-width, initial-scale=1" />
1406
- <title>${view === "usage" ? "rudder · usage" : "rudder"}</title>
1429
+ <title>rudder</title>
1407
1430
  <link rel="stylesheet" href="/board.css" />
1408
1431
  </head>
1409
1432
  <body>
1410
1433
  <div id="app"></div>
1411
- <script>window.__RUDDER_SLUG__ = ${slugJson}; window.__RUDDER_TOKEN__ = ${JSON.stringify(BOARD_TOKEN)}; window.__RUDDER_CONTROL_MODE__ = ${JSON.stringify(controlMode)}; window.__RUDDER_CAN_MUTATE__ = ${JSON.stringify(canMutate)}; window.__RUDDER_VIEW__ = ${JSON.stringify(view)}</script>
1412
1434
  <script type="module" src="/board.js"></script>
1413
1435
  </body>
1414
1436
  </html>
@@ -1454,18 +1476,24 @@ function inRepo(repoRoot, fn) {
1454
1476
  repoChdirLock = run.then(() => undefined, () => undefined);
1455
1477
  return run;
1456
1478
  }
1457
- async function readJsonBody(req) {
1479
+ async function readJsonBody(req, maxBytes = MAX_BODY_BYTES) {
1458
1480
  const chunks = [];
1459
1481
  let total = 0;
1460
- for await (const chunk of req) {
1461
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1462
- total += buf.length;
1463
- if (total > MAX_BODY_BYTES) {
1464
- // Oversized body: stop reading and treat as empty (DoS guard).
1465
- req.destroy();
1466
- return {};
1482
+ const deadline = setTimeout(() => req.destroy(), 5000);
1483
+ deadline.unref();
1484
+ try {
1485
+ for await (const chunk of req) {
1486
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1487
+ total += buf.length;
1488
+ if (total > maxBytes) {
1489
+ req.destroy();
1490
+ return {};
1491
+ }
1492
+ chunks.push(buf);
1467
1493
  }
1468
- chunks.push(buf);
1494
+ }
1495
+ finally {
1496
+ clearTimeout(deadline);
1469
1497
  }
1470
1498
  if (chunks.length === 0) {
1471
1499
  return {};
@@ -1499,12 +1527,4 @@ function sendHtml(res, body, status = 200) {
1499
1527
  res.writeHead(status, { "content-type": "text/html; charset=utf-8" });
1500
1528
  res.end(body);
1501
1529
  }
1502
- function openBrowser(url) {
1503
- const platform = process.platform;
1504
- const command = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open";
1505
- const args = platform === "win32" ? ["/c", "start", "", url] : [url];
1506
- const child = spawn(command, args, { detached: true, stdio: "ignore" });
1507
- child.on("error", () => undefined);
1508
- child.unref();
1509
- }
1510
1530
  //# sourceMappingURL=daemon.js.map