agent-relay-server 0.119.0 → 0.119.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 (95) hide show
  1. package/docs/openapi.json +1 -1
  2. package/package.json +6 -5
  3. package/public/assets/{MessageBubble-BdnzeQjY.js → MessageBubble-DbaaemH3.js} +2 -2
  4. package/public/assets/{MessageBubble-BdnzeQjY.js.map → MessageBubble-DbaaemH3.js.map} +1 -1
  5. package/public/assets/{PlanGraphPanel-sG8nqUHw.js → PlanGraphPanel-C_hnK9yH.js} +2 -2
  6. package/public/assets/{PlanGraphPanel-sG8nqUHw.js.map → PlanGraphPanel-C_hnK9yH.js.map} +1 -1
  7. package/public/assets/{activity-CZpvbkAW.js → activity-Cbw43afW.js} +2 -2
  8. package/public/assets/{activity-CZpvbkAW.js.map → activity-Cbw43afW.js.map} +1 -1
  9. package/public/assets/{agent-profiles-BfZgLPvN.js → agent-profiles-BZZpTAZn.js} +2 -2
  10. package/public/assets/{agent-profiles-BfZgLPvN.js.map → agent-profiles-BZZpTAZn.js.map} +1 -1
  11. package/public/assets/{agent-type-icon-CG2v7tF0.js → agent-type-icon-2YWBWhYC.js} +2 -2
  12. package/public/assets/{agent-type-icon-CG2v7tF0.js.map → agent-type-icon-2YWBWhYC.js.map} +1 -1
  13. package/public/assets/{agents-DSOCIAV6.js → agents-nvHlibqo.js} +2 -2
  14. package/public/assets/{agents-DSOCIAV6.js.map → agents-nvHlibqo.js.map} +1 -1
  15. package/public/assets/{analytics-C3vhiVvA.js → analytics-B9bbDReP.js} +2 -2
  16. package/public/assets/{analytics-C3vhiVvA.js.map → analytics-B9bbDReP.js.map} +1 -1
  17. package/public/assets/{automation-RkZtUqxK.js → automation-CjtLgS3h.js} +2 -2
  18. package/public/assets/{automation-RkZtUqxK.js.map → automation-CjtLgS3h.js.map} +1 -1
  19. package/public/assets/{branch-state-badge-BG7WdFNG.js → branch-state-badge-DRFIs9q0.js} +2 -2
  20. package/public/assets/{branch-state-badge-BG7WdFNG.js.map → branch-state-badge-DRFIs9q0.js.map} +1 -1
  21. package/public/assets/{channels-CF3EsyIK.js → channels-CL00bLDh.js} +2 -2
  22. package/public/assets/{channels-CF3EsyIK.js.map → channels-CL00bLDh.js.map} +1 -1
  23. package/public/assets/{chat-E5MI0WxW.js → chat-DKf_9fgB.js} +2 -2
  24. package/public/assets/{chat-E5MI0WxW.js.map → chat-DKf_9fgB.js.map} +1 -1
  25. package/public/assets/{connectors-CitVhhON.js → connectors-QYtScfNz.js} +2 -2
  26. package/public/assets/{connectors-CitVhhON.js.map → connectors-QYtScfNz.js.map} +1 -1
  27. package/public/assets/{display-_5kFrHJh.js → display-CP3jEw1H.js} +2 -2
  28. package/public/assets/{display-_5kFrHJh.js.map → display-CP3jEw1H.js.map} +1 -1
  29. package/public/assets/{formatted-body-BnlRQjBi.js → formatted-body-BnSiFCc3.js} +3 -3
  30. package/public/assets/{formatted-body-BnlRQjBi.js.map → formatted-body-BnSiFCc3.js.map} +1 -1
  31. package/public/assets/{formatted-body-impl-9iNv975q.js → formatted-body-impl-Cnchy-Iv.js} +2 -2
  32. package/public/assets/{formatted-body-impl-9iNv975q.js.map → formatted-body-impl-Cnchy-Iv.js.map} +1 -1
  33. package/public/assets/{index-CUugubHc.js → index-kelZvgcV.js} +6 -6
  34. package/public/assets/{index-CUugubHc.js.map → index-kelZvgcV.js.map} +1 -1
  35. package/public/assets/{insights-D0bcKaNd.js → insights-Ccz5zFIQ.js} +2 -2
  36. package/public/assets/{insights-D0bcKaNd.js.map → insights-Ccz5zFIQ.js.map} +1 -1
  37. package/public/assets/{integrations-CGVHvoEv.js → integrations-BICEazmP.js} +2 -2
  38. package/public/assets/{integrations-CGVHvoEv.js.map → integrations-BICEazmP.js.map} +1 -1
  39. package/public/assets/{maintenance-C0vzzP7r.js → maintenance-DpYnmrVo.js} +2 -2
  40. package/public/assets/{maintenance-C0vzzP7r.js.map → maintenance-DpYnmrVo.js.map} +1 -1
  41. package/public/assets/{managed-agents-DUkT3MHx.js → managed-agents-qQtr531p.js} +2 -2
  42. package/public/assets/{managed-agents-DUkT3MHx.js.map → managed-agents-qQtr531p.js.map} +1 -1
  43. package/public/assets/{markdown-preview-impl-CDHHjZr3.js → markdown-preview-impl-DhkWrgsW.js} +2 -2
  44. package/public/assets/{markdown-preview-impl-CDHHjZr3.js.map → markdown-preview-impl-DhkWrgsW.js.map} +1 -1
  45. package/public/assets/{memory-hrJcJKdD.js → memory-AsWF2gfa.js} +2 -2
  46. package/public/assets/{memory-hrJcJKdD.js.map → memory-AsWF2gfa.js.map} +1 -1
  47. package/public/assets/{messages-C3YD6xJ3.js → messages-D0vT-ovM.js} +2 -2
  48. package/public/assets/{messages-C3YD6xJ3.js.map → messages-D0vT-ovM.js.map} +1 -1
  49. package/public/assets/{orchestrators-CshVnsUu.js → orchestrators-Oo8U_GW2.js} +2 -2
  50. package/public/assets/{orchestrators-CshVnsUu.js.map → orchestrators-Oo8U_GW2.js.map} +1 -1
  51. package/public/assets/{overview-DEtzai33.js → overview-UTAK7pAB.js} +2 -2
  52. package/public/assets/{overview-DEtzai33.js.map → overview-UTAK7pAB.js.map} +1 -1
  53. package/public/assets/{pairs-DFpYOOlU.js → pairs-TZYezwEi.js} +2 -2
  54. package/public/assets/{pairs-DFpYOOlU.js.map → pairs-TZYezwEi.js.map} +1 -1
  55. package/public/assets/{projects-BAi5dytW.js → projects-ClgQ10Al.js} +2 -2
  56. package/public/assets/{projects-BAi5dytW.js.map → projects-ClgQ10Al.js.map} +1 -1
  57. package/public/assets/{prompt-settings-jpRG8tAv.js → prompt-settings-Tia685AV.js} +2 -2
  58. package/public/assets/{prompt-settings-jpRG8tAv.js.map → prompt-settings-Tia685AV.js.map} +1 -1
  59. package/public/assets/{registry-DFiSS4hB.js → registry-CAXZWvzr.js} +2 -2
  60. package/public/assets/{registry-DFiSS4hB.js.map → registry-CAXZWvzr.js.map} +1 -1
  61. package/public/assets/{security-D5tkecYh.js → security-BDAMCUzN.js} +2 -2
  62. package/public/assets/{security-D5tkecYh.js.map → security-BDAMCUzN.js.map} +1 -1
  63. package/public/assets/{select-DctZnR2Q.js → select-ytVYIxZP.js} +2 -2
  64. package/public/assets/{select-DctZnR2Q.js.map → select-ytVYIxZP.js.map} +1 -1
  65. package/public/assets/{settings-NlRG3Wvf.js → settings-CnalH4Zd.js} +2 -2
  66. package/public/assets/{settings-NlRG3Wvf.js.map → settings-CnalH4Zd.js.map} +1 -1
  67. package/public/assets/store-BDCUnpt5.js +9 -0
  68. package/public/assets/store-BDCUnpt5.js.map +1 -0
  69. package/public/assets/{tasks-Q9e41WzI.js → tasks-CHGO51En.js} +2 -2
  70. package/public/assets/{tasks-Q9e41WzI.js.map → tasks-CHGO51En.js.map} +1 -1
  71. package/public/assets/{teams-pyH9kHhS.js → teams-DDL-I-pP.js} +2 -2
  72. package/public/assets/{teams-pyH9kHhS.js.map → teams-DDL-I-pP.js.map} +1 -1
  73. package/public/assets/{terminal-viewer-impl-RPC_OOk0.js → terminal-viewer-impl-CnXpHy1R.js} +2 -2
  74. package/public/assets/{terminal-viewer-impl-RPC_OOk0.js.map → terminal-viewer-impl-CnXpHy1R.js.map} +1 -1
  75. package/public/assets/types-8ThujPP2.js +2 -0
  76. package/public/assets/types-8ThujPP2.js.map +1 -0
  77. package/public/assets/{user-avatar-Bd4txMth.js → user-avatar-Cw7jcQY-.js} +2 -2
  78. package/public/assets/{user-avatar-Bd4txMth.js.map → user-avatar-Cw7jcQY-.js.map} +1 -1
  79. package/public/assets/{work-queue-CWLzjgBV.js → work-queue-BwX92bVS.js} +2 -2
  80. package/public/assets/{work-queue-CWLzjgBV.js.map → work-queue-BwX92bVS.js.map} +1 -1
  81. package/public/assets/{workspaces-BV9-9JQr.js → workspaces-DSsvsOFa.js} +2 -2
  82. package/public/assets/{workspaces-BV9-9JQr.js.map → workspaces-DSsvsOFa.js.map} +1 -1
  83. package/public/index.html +6 -6
  84. package/runner/plugins/claude/.claude-plugin/plugin.json +1 -1
  85. package/runner/plugins/claude/claude-statusline-probe.cjs +134 -0
  86. package/runner/plugins/claude/monitors/relay-monitor.provisioned.mjs +3 -3
  87. package/src/cli/context-probe.ts +9 -7
  88. package/src/index.ts +10 -434
  89. package/src/routing-policy-store.ts +5 -5
  90. package/src/server.ts +433 -0
  91. package/src/spawn-targets.ts +12 -4
  92. package/public/assets/store-D2BjyanL.js +0 -9
  93. package/public/assets/store-D2BjyanL.js.map +0 -1
  94. package/public/assets/types-DSwhOFcJ.js +0 -2
  95. package/public/assets/types-DSwhOFcJ.js.map +0 -1
@@ -41,13 +41,15 @@ export async function handleContextProbeCommand(args: string[]): Promise<void> {
41
41
  }
42
42
 
43
43
  if (printStatusLine) {
44
- const command = [
45
- "agent-relay",
46
- "context-probe",
47
- ...(wrapRequested ? ["--wrap", ...(wrapCommand ? [shellQuote(wrapCommand)] : [])] : ["--standalone"]),
48
- ...(agentId ? ["--agent-id", shellQuote(agentId)] : []),
49
- ...(stateDir ? ["--state-dir", shellQuote(stateDir)] : []),
50
- ].join(" ");
44
+ const command = wrapRequested && !wrapCommand && !agentId && !stateDir
45
+ ? "agent-relay-claude-statusline"
46
+ : [
47
+ "agent-relay",
48
+ "context-probe",
49
+ ...(wrapRequested ? ["--wrap", ...(wrapCommand ? [shellQuote(wrapCommand)] : [])] : ["--standalone"]),
50
+ ...(agentId ? ["--agent-id", shellQuote(agentId)] : []),
51
+ ...(stateDir ? ["--state-dir", shellQuote(stateDir)] : []),
52
+ ].join(" ");
51
53
  console.log(command);
52
54
  return;
53
55
  }
package/src/index.ts CHANGED
@@ -1,443 +1,19 @@
1
1
  #!/usr/bin/env bun
2
- import type { ServerWebSocket } from "bun";
3
- import { initDb, getOrchestrator } from "./db";
4
- import { matchRoute } from "./routes";
5
- import { emitNewMessage, emitTaskChanged } from "./sse";
6
- import { busHandleClose, busHandleMessage, busHandleOpen, handleBusUpgrade } from "./bus";
7
- import { emitRelayEvent } from "./events";
8
- import { reconcileAutomationRuns, runDueAutomations, type AutomationDispatchResult, type AutomationReconcileResult } from "./automations";
9
- import { getLifecycleManager } from "./lifecycle-manager";
10
- import { getCompactionWatch } from "./compaction-watch";
11
- import { getConfig, setConfig } from "./config-store";
12
- import { startConnectorStatusPoller } from "./connectors";
13
- import { installNotificationSubscriptionRule } from "./notification-subscription-rules";
14
- import { installQuotaAdvisoryHandler } from "./quota-advisory";
15
- import { startPlanLiveBindings } from "./services/plan-live-bindings";
16
- import { startRelayScheduler } from "./services/scheduler";
17
- import { recordWorkspaceIssueActivity } from "./services/spawn-issue-activity";
18
- import { onWorkspaceCreate } from "./db";
19
- import { resolve, sep } from "path";
20
- import { gzipSync, brotliCompressSync, constants as zlibConstants } from "node:zlib";
21
- import {
22
- AUTOMATION_INTERVAL_MS,
23
- IDLE_TIMEOUT_SECONDS,
24
- LOG_REQUESTS,
25
- VERSION,
26
- relayToken,
27
- } from "./config";
28
- import { CONTRACT_VERSIONS } from "./contracts";
29
- import {
30
- applyCors,
31
- assertSafeNetworkConfig,
32
- corsPreflight,
33
- forbidden,
34
- getComponentAuth,
35
- getIntegrationAuth,
36
- isAuthorized,
37
- isScopedRequestAuthorized,
38
- isOriginAllowed,
39
- isRequestAuthorizedFor,
40
- unauthorized,
41
- } from "./security";
42
- import { handleCli } from "./cli";
43
- import { startMaintenanceScheduler } from "./maintenance";
44
- import { errMessage, RELAY_TOKEN_HEADER } from "agent-relay-sdk";
2
+ import { errMessage } from "agent-relay-sdk";
45
3
 
46
4
  async function main(): Promise<void> {
47
- const result = await handleCli(process.argv.slice(2));
48
- if (result === "handled") return;
49
- startServer();
50
- }
51
-
52
- // Restart-on-update gating (issue #341).
53
- //
54
- // A `restartOnUpdate` policy should cycle its managed agent only when the agent's
55
- // running runner code is now protocol-INCOMPATIBLE with the relay — i.e. on a
56
- // runner-protocol bump — NOT on every package version change. Gating on the package
57
- // version churned the always-on Telegram agent ~12×/day (one restart per patch
58
- // redeploy), dropping in-flight work (surfaced #340). The runner protocol
59
- // (CONTRACT_VERSIONS.runnerProtocol) only moves on a breaking runner change, so this
60
- // fires ~never during normal releases.
61
- //
62
- // `relay-version` is still tracked for observability/telemetry, but it no longer
63
- // triggers restarts.
64
- export function reconcileRelayVersion(): void {
65
- const storedVersion = getConfig<string>("system", "relay-version")?.value;
66
- if (storedVersion !== VERSION) setConfig("system", "relay-version", VERSION, "server-startup");
67
-
68
- const storedProtocol = getConfig<string>("system", "runner-protocol-version")?.value;
69
- const currentProtocol = String(CONTRACT_VERSIONS.runnerProtocol);
70
- if (storedProtocol === currentProtocol) return;
71
- // Skip the very first run (no stored protocol yet) — that's initial bootstrap, not an upgrade.
72
- if (storedProtocol) getLifecycleManager().onRelayUpdated(VERSION);
73
- setConfig("system", "runner-protocol-version", currentProtocol, "server-startup");
74
- }
75
-
76
- function startServer(): void {
77
- const PORT = Number(process.env.PORT) || 4850;
78
- const HOST = process.env.HOST || "127.0.0.1";
79
- const DB_PATH = process.env.DB_PATH || "agent-relay.db";
80
-
81
- assertSafeNetworkConfig(HOST);
82
- initDb(DB_PATH);
83
- onWorkspaceCreate(recordWorkspaceIssueActivity);
84
- installQuotaAdvisoryHandler();
85
- installNotificationSubscriptionRule();
86
- startPlanLiveBindings();
87
- getLifecycleManager().start();
88
- getCompactionWatch().start();
89
- reconcileRelayVersion();
90
- startConnectorStatusPoller();
91
- startMaintenanceScheduler();
92
- startRelayScheduler();
93
-
94
- setInterval(() => {
95
- emitAutomationReconciliations(reconcileAutomationRuns());
96
- emitAutomationDispatches(runDueAutomations());
97
- }, AUTOMATION_INTERVAL_MS);
98
-
99
- Bun.serve<RelaySocketData>({
100
- port: PORT,
101
- hostname: HOST,
102
- idleTimeout: IDLE_TIMEOUT_SECONDS,
103
- fetch: createFetchHandler({ publicDir: process.env.PUBLIC_DIR, logRequests: LOG_REQUESTS }),
104
- websocket: {
105
- open(ws) {
106
- if (ws.data?.kind === "terminal-proxy") return openTerminalProxy(ws as TerminalProxySocket);
107
- return busHandleOpen(ws as any);
108
- },
109
- message(ws, data) {
110
- if (ws.data?.kind === "terminal-proxy") return sendTerminalProxyFrame(ws as TerminalProxySocket, data);
111
- return busHandleMessage(ws as any, data);
112
- },
113
- close(ws) {
114
- if (ws.data?.kind === "terminal-proxy") return closeTerminalProxy(ws as TerminalProxySocket);
115
- return busHandleClose(ws as any);
116
- },
117
- },
118
- });
119
-
120
- console.log(`agent-relay ${VERSION} running on http://${HOST}:${PORT}`);
121
- }
122
-
123
- interface TerminalProxySocketData {
124
- kind: "terminal-proxy";
125
- upstreamUrl: string;
126
- upstreamToken?: string;
127
- upstream?: WebSocket;
128
- pending: Array<string | Buffer>;
129
- }
130
-
131
- type RelaySocketData = {
132
- kind: "bus";
133
- id: string;
134
- componentScopes?: string[];
135
- } | TerminalProxySocketData;
136
-
137
- type TerminalProxySocket = ServerWebSocket<TerminalProxySocketData>;
138
-
139
- function emitAutomationDispatches(results: AutomationDispatchResult[]): void {
140
- for (const result of results) {
141
- if (result.command) emitAutomationCommand(result.command);
142
- if (result.message) emitNewMessage(result.message);
143
- if (result.task) emitTaskChanged(result.task, "task.created");
144
- emitRelayEvent({
145
- type: "automation.run",
146
- source: "server",
147
- subject: result.run.id,
148
- data: { automation: result.automation, run: result.run, task: result.task },
149
- });
150
- }
151
- }
152
-
153
- function emitAutomationReconciliations(results: AutomationReconcileResult[]): void {
154
- for (const result of results) {
155
- if (result.command) emitAutomationCommand(result.command);
156
- if (result.message) emitNewMessage(result.message);
157
- if (result.task) emitTaskChanged(result.task, "task.updated");
158
- emitRelayEvent({
159
- type: "automation.run",
160
- source: "server",
161
- subject: result.run.id,
162
- data: { run: result.run, task: result.task },
163
- });
164
- }
165
- }
166
-
167
- function emitAutomationCommand(command: { id: string; source: string; status: string }): void {
168
- emitRelayEvent({
169
- type: command.status === "pending" ? "command.requested" : `command.${command.status}`,
170
- source: command.source,
171
- subject: command.id,
172
- data: { command },
173
- });
174
- }
175
-
176
- function openTerminalProxy(ws: TerminalProxySocket): void {
177
- const token = ws.data.upstreamToken;
178
- // Bun's client WebSocket accepts a `headers` option (non-standard; absent from DOM types).
179
- const upstream = token
180
- ? new WebSocket(ws.data.upstreamUrl, { headers: { [RELAY_TOKEN_HEADER]: token } } as unknown as string[])
181
- : new WebSocket(ws.data.upstreamUrl);
182
- ws.data.upstream = upstream;
183
-
184
- upstream.onopen = () => {
185
- const pending = ws.data.pending.splice(0);
186
- for (const frame of pending) upstream.send(frame);
187
- };
188
- upstream.onmessage = (event) => {
189
- if (typeof event.data === "string" || event.data instanceof Buffer) {
190
- ws.send(event.data);
191
- } else if (event.data instanceof ArrayBuffer) {
192
- ws.send(event.data);
193
- } else if (event.data instanceof Blob) {
194
- void event.data.arrayBuffer().then((buffer) => ws.send(buffer)).catch(() => {});
195
- }
196
- };
197
- upstream.onerror = () => {
198
- ws.send(JSON.stringify({ type: "error", error: "terminal stream upstream error" }));
199
- };
200
- upstream.onclose = () => {
201
- ws.close();
202
- };
203
- }
204
-
205
- function sendTerminalProxyFrame(ws: TerminalProxySocket, data: string | Buffer): void {
206
- const upstream = ws.data.upstream;
207
- if (!upstream || upstream.readyState === WebSocket.CONNECTING) {
208
- ws.data.pending.push(data);
5
+ const args = process.argv.slice(2);
6
+ if (args[0] === "context-probe") {
7
+ const { handleContextProbeCommand } = await import("./cli/context-probe");
8
+ await handleContextProbeCommand(args.slice(1));
209
9
  return;
210
10
  }
211
- if (upstream.readyState !== WebSocket.OPEN) return;
212
- upstream.send(data);
213
- }
214
11
 
215
- function closeTerminalProxy(ws: TerminalProxySocket): void {
216
- const upstream = ws.data.upstream;
217
- ws.data.pending = [];
218
- if (upstream && upstream.readyState === WebSocket.OPEN) upstream.close();
219
- }
220
-
221
- export function createFetchHandler(
222
- opts: { publicDir?: string; logRequests?: boolean } = {},
223
- ): {
224
- (req: Request): Promise<Response>;
225
- (req: Request, server: Bun.Server<RelaySocketData>): Promise<Response | undefined>;
226
- } {
227
- const publicDir = resolve(opts.publicDir ?? resolve(import.meta.dir, "../public"));
228
- const publicDirPrefix = publicDir + sep;
229
- const logRequests = opts.logRequests ?? false;
230
-
231
- return async function fetch(req: Request, server?: Bun.Server<RelaySocketData>): Promise<Response | undefined> {
232
- const url = new URL(req.url);
233
-
234
- if (url.pathname === "/bus") {
235
- if (!server) return new Response("WebSocket upgrade unavailable", { status: 400 });
236
- return handleBusUpgrade(req, server);
237
- }
238
-
239
- const terminalStreamMatch = url.pathname.match(/^\/api\/orchestrators\/([^/]+)\/terminal\/([^/]+)\/stream$/);
240
- if (req.method === "GET" && terminalStreamMatch) {
241
- if (!server) return new Response("WebSocket upgrade unavailable", { status: 400 });
242
- if (!isOriginAllowed(req)) return Response.json({ error: "origin not allowed" }, { status: 403 });
243
- if (!isAuthorized(req)) return unauthorized(req);
244
- const orchestratorId = decodeURIComponent(terminalStreamMatch[1]!);
245
- const session = decodeURIComponent(terminalStreamMatch[2]!);
246
- if (!isRequestAuthorizedFor(req, { scope: "terminal:attach", resource: { orchestratorId, terminalAttach: true } })) {
247
- return forbidden(req);
248
- }
249
- const orch = getOrchestrator(orchestratorId);
250
- if (!orch) return Response.json({ error: "orchestrator not found" }, { status: 404 });
251
- if (!orch.apiUrl) return Response.json({ error: "orchestrator does not expose an API" }, { status: 422 });
252
- if (orch.status !== "online") return Response.json({ error: "orchestrator is offline" }, { status: 422 });
253
- const upstream = new URL(`/api/terminal/${encodeURIComponent(session)}/stream`, orch.apiUrl);
254
- upstream.protocol = upstream.protocol === "https:" ? "wss:" : "ws:";
255
- // Pass the relay token as a header (not a query param) so it never lands in
256
- // access/proxy logs (#149). The orchestrator accepts both, but headers are safer.
257
- const token = relayToken();
258
- const upgraded = server.upgrade(req, {
259
- data: { kind: "terminal-proxy", upstreamUrl: upstream.toString(), upstreamToken: token, pending: [] },
260
- });
261
- if (!upgraded) return new Response("WebSocket upgrade failed", { status: 400 });
262
- return undefined;
263
- }
264
-
265
- if (req.method === "OPTIONS") {
266
- return corsPreflight(req);
267
- }
268
- if (!isOriginAllowed(req)) {
269
- return Response.json({ error: "origin not allowed" }, { status: 403 });
270
- }
271
-
272
- // API routes
273
- const matched = matchRoute(req.method, url.pathname);
274
- if (matched) {
275
- const publicPaths = ["/api/spec", "/api/docs", "/api/health"];
276
- // Pre-auth allowlist (#389): the auth endpoints must be reachable unauthenticated — they ARE
277
- // the way a session is obtained. Each handler self-authenticates (login verifies credentials,
278
- // refresh validates the refresh token, logout revokes the presented token). Everything else
279
- // still flows through the component-token gate below.
280
- const publicAuthPaths = ["/api/auth/providers", "/api/auth/login", "/api/auth/refresh", "/api/auth/logout"];
281
- if (!publicPaths.includes(url.pathname) && !publicAuthPaths.includes(url.pathname)) {
282
- const integrationAuth = getIntegrationAuth(req);
283
- const componentAuth = getComponentAuth(req);
284
- const handlerOwnsScopedAuth = url.pathname === "/api/tokens/me" ||
285
- url.pathname === "/api/settings" ||
286
- url.pathname.startsWith("/api/settings/");
287
- if (!isAuthorized(req)) {
288
- if (!integrationAuth) {
289
- return unauthorized(req);
290
- }
291
- if (!handlerOwnsScopedAuth && !isScopedRequestAuthorized(req)) return forbidden(req);
292
- }
293
- if (componentAuth && !handlerOwnsScopedAuth && !isScopedRequestAuthorized(req)) return forbidden(req);
294
- }
295
- const response = await matched.handler(req, matched.params);
296
- applyCors(req, response);
297
- if (logRequests && url.pathname.startsWith("/api/")) {
298
- console.log(`${req.method} ${url.pathname} → ${response.status}`);
299
- }
300
- return response;
301
- }
302
-
303
- // Dashboard — serve static files, rejecting path traversal and directory requests
304
- let requested = url.pathname === "/" ? "/index.html" : url.pathname;
305
- if (requested.endsWith("/")) requested += "index.html";
306
- const resolved = resolve(publicDir, `.${requested}`);
307
- if (!resolved.startsWith(publicDirPrefix)) {
308
- return Response.json({ error: "not found" }, { status: 404 });
309
- }
310
- const file = Bun.file(resolved);
311
- if (await file.exists()) {
312
- return await serveStaticFile(req, resolved, requested, file);
313
- }
314
-
315
- return Response.json({ error: "not found" }, { status: 404 });
316
- } as {
317
- (req: Request): Promise<Response>;
318
- (req: Request, server: Bun.Server<RelaySocketData>): Promise<Response | undefined>;
319
- };
320
- }
321
-
322
- // In-memory compressed-variant cache, keyed by absolute path. Invalidated when
323
- // the file's mtime/size changes, so a rebuilt bundle is recompressed on next
324
- // request. The dashboard ships as a minified, code-split bundle (#200/#201);
325
- // brotli/gzip on top cuts the wire size further, which is the dominant cost over
326
- // high-latency links. Hashed /assets/* chunks are also served immutable so
327
- // repeat visits skip them entirely (see staticHeaders).
328
- type CompressedVariant = { body: Uint8Array; encoding: "br" | "gzip" };
329
- const compressedCache = new Map<
330
- string,
331
- { mtimeMs: number; size: number; br?: Uint8Array; gzip?: Uint8Array }
332
- >();
333
-
334
- const COMPRESSIBLE = /\.(html|js|css|svg|json|webmanifest|map)$/;
335
-
336
- function isCompressible(pathname: string): boolean {
337
- return pathname === "/" || pathname.endsWith("/") || COMPRESSIBLE.test(pathname);
338
- }
339
-
340
- function negotiateEncoding(req: Request): "br" | "gzip" | null {
341
- const accept = req.headers.get("accept-encoding") ?? "";
342
- if (/\bbr\b/.test(accept)) return "br";
343
- if (/\bgzip\b/.test(accept)) return "gzip";
344
- return null;
345
- }
346
-
347
- async function getCompressedVariant(
348
- resolved: string,
349
- mtimeMs: number,
350
- size: number,
351
- encoding: "br" | "gzip",
352
- raw: () => Promise<Uint8Array>,
353
- ): Promise<CompressedVariant> {
354
- let entry = compressedCache.get(resolved);
355
- if (!entry || entry.mtimeMs !== mtimeMs || entry.size !== size) {
356
- entry = { mtimeMs, size };
357
- compressedCache.set(resolved, entry);
358
- }
359
- const cached = entry[encoding];
360
- if (cached) return { body: cached, encoding };
361
- const data = await raw();
362
- const body =
363
- encoding === "br"
364
- ? brotliCompressSync(data, {
365
- params: {
366
- // Quality 5 ~ near-gzip CPU, much better ratio; this runs once per
367
- // file version then serves from cache, so cost is amortized away.
368
- [zlibConstants.BROTLI_PARAM_QUALITY]: 5,
369
- [zlibConstants.BROTLI_PARAM_SIZE_HINT]: data.byteLength,
370
- },
371
- })
372
- : gzipSync(data, { level: 6 });
373
- entry[encoding] = body;
374
- return { body, encoding };
375
- }
376
-
377
- async function serveStaticFile(
378
- req: Request,
379
- resolved: string,
380
- requested: string,
381
- file: ReturnType<typeof Bun.file>,
382
- ): Promise<Response> {
383
- const stat = await file.stat();
384
- const headers = staticHeaders(requested);
385
- // Strong-ish validator from mtime + size; encoding-suffixed so a client never
386
- // gets a 304 for a variant it didn't store.
387
- const baseTag = `${stat.mtime.getTime().toString(36)}-${stat.size.toString(36)}`;
388
-
389
- const encoding = isCompressible(requested) ? negotiateEncoding(req) : null;
390
- const etag = `"${baseTag}${encoding ? `-${encoding}` : ""}"`;
391
- headers.set("ETag", etag);
392
- if (req.headers.get("if-none-match") === etag) {
393
- return new Response(null, { status: 304, headers });
394
- }
395
-
396
- if (encoding) {
397
- const { body } = await getCompressedVariant(
398
- resolved,
399
- stat.mtime.getTime(),
400
- stat.size,
401
- encoding,
402
- () => file.bytes(),
403
- );
404
- headers.set("Content-Encoding", encoding);
405
- headers.set("Vary", "Accept-Encoding");
406
- headers.set("Content-Length", String(body.byteLength));
407
- // Uint8Array is a valid BodyInit at runtime in Bun; the DOM lib types omit it.
408
- return new Response(body as unknown as BodyInit, { headers });
409
- }
410
-
411
- return new Response(file, { headers });
412
- }
413
-
414
- function staticHeaders(pathname: string): Headers {
415
- const headers = new Headers();
416
- const contentType = staticContentType(pathname);
417
- if (contentType) headers.set("Content-Type", contentType);
418
- // Hashed build assets are content-addressed (a content change = a new
419
- // filename), so they're safe to cache forever — the browser never needs to
420
- // revalidate them. The shell + PWA control files must always revalidate
421
- // instead (ETag makes that a cheap 304 when unchanged).
422
- if (pathname.startsWith("/assets/")) {
423
- headers.set("Cache-Control", "public, max-age=31536000, immutable");
424
- } else if (pathname === "/sw.js" || pathname === "/manifest.webmanifest") {
425
- headers.set("Cache-Control", "no-cache");
426
- } else if (pathname === "/" || pathname.endsWith("/") || pathname.endsWith(".html")) {
427
- headers.set("Cache-Control", "no-cache");
428
- }
429
- return headers;
430
- }
431
-
432
- function staticContentType(pathname: string): string | undefined {
433
- if (pathname.endsWith(".webmanifest")) return "application/manifest+json; charset=utf-8";
434
- if (pathname.endsWith(".js")) return "text/javascript; charset=utf-8";
435
- if (pathname.endsWith(".css")) return "text/css; charset=utf-8";
436
- if (pathname.endsWith(".map")) return "application/json; charset=utf-8";
437
- if (pathname.endsWith(".html")) return "text/html; charset=utf-8";
438
- if (pathname.endsWith(".svg")) return "image/svg+xml";
439
- if (pathname.endsWith(".png")) return "image/png";
440
- return undefined;
12
+ const { handleCli } = await import("./cli");
13
+ const result = await handleCli(args);
14
+ if (result === "handled") return;
15
+ const { startServer } = await import("./server");
16
+ startServer();
441
17
  }
442
18
 
443
19
  if (import.meta.main) {
@@ -48,15 +48,15 @@ export const DEFAULT_DISPATCH_POLICY: DispatchPolicy = {
48
48
  rules: [
49
49
  { label: "review → Codex (reviewer edge)", match: { type: "review" }, target: { provider: "codex", effort: "high" } },
50
50
  { label: "debug → Codex high", match: { type: "debug" }, target: { provider: "codex", effort: "high" } },
51
- { label: "ui → Sonnet", match: { type: "ui" }, target: { provider: "claude", model: "sonnet-4.6", effort: "medium" } },
51
+ { label: "ui → Sonnet", match: { type: "ui" }, target: { provider: "claude", model: "sonnet-5", effort: "medium" } },
52
52
  { label: "complex build → Opus 4.8 high", match: { type: "build", complexity: "complex" }, target: { provider: "claude", model: "opus-4.8", effort: "high" } },
53
53
  { label: "research → Opus 4.8 high", match: { type: "research" }, target: { provider: "claude", model: "opus-4.8", effort: "high" } },
54
54
  { label: "refactor → Opus 4.8 medium", match: { type: "refactor" }, target: { provider: "claude", model: "opus-4.8", effort: "medium" } },
55
- { label: "moderate build → Sonnet medium", match: { type: "build", complexity: "moderate" }, target: { provider: "claude", model: "sonnet-4.6", effort: "medium" } },
56
- { label: "ops → Sonnet low", match: { type: "ops" }, target: { provider: "claude", model: "sonnet-4.6", effort: "low" } },
57
- { label: "trivial → Sonnet low", match: { complexity: "trivial" }, target: { provider: "claude", model: "sonnet-4.6", effort: "low" } },
55
+ { label: "moderate build → Sonnet medium", match: { type: "build", complexity: "moderate" }, target: { provider: "claude", model: "sonnet-5", effort: "medium" } },
56
+ { label: "ops → Sonnet low", match: { type: "ops" }, target: { provider: "claude", model: "sonnet-5", effort: "low" } },
57
+ { label: "trivial → Sonnet low", match: { complexity: "trivial" }, target: { provider: "claude", model: "sonnet-5", effort: "low" } },
58
58
  ],
59
- fallback: { provider: "claude", model: "sonnet-4.6", effort: "medium" },
59
+ fallback: { provider: "claude", model: "sonnet-5", effort: "medium" },
60
60
  // Large footprint demands a 1M-window model; the dispatcher escalates same-family (e.g.
61
61
  // opus-4.8 → opus-4.8[1m]) when the matched model's window is below this.
62
62
  footprintMinContextTokens: { large: 1_000_000 },