@teamclaws/teamclaw 2026.8.0 → 2026.11.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 (149) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/api.js +1 -0
  3. package/dist/index.js +325 -0
  4. package/dist/src/config.js +412 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-capacity.js +14 -0
  7. package/dist/src/controller/controller-intake.js +895 -0
  8. package/dist/src/controller/controller-planning.js +813 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +624 -0
  11. package/dist/src/controller/controller-tools.js +587 -0
  12. package/dist/src/controller/delivery-report.js +458 -0
  13. package/dist/src/controller/github-auth.js +564 -0
  14. package/dist/src/controller/http-server.js +284 -0
  15. package/dist/src/controller/kickoff-orchestrator.js +246 -0
  16. package/dist/src/controller/managed-gateway-process.js +286 -0
  17. package/dist/src/controller/message-delivery.js +28 -0
  18. package/dist/src/controller/message-router.js +38 -0
  19. package/dist/src/controller/message-routes.js +114 -0
  20. package/dist/src/controller/orchestration-manifest.js +151 -0
  21. package/dist/src/controller/preview-manager.js +586 -0
  22. package/dist/src/controller/preview-proxy.js +98 -0
  23. package/dist/src/controller/profile-switch.js +289 -0
  24. package/dist/src/controller/project-registry.js +294 -0
  25. package/dist/src/controller/prompt-injector.js +197 -0
  26. package/dist/src/controller/repo-routes.js +63 -0
  27. package/dist/src/controller/role-inference.js +246 -0
  28. package/dist/src/controller/route-table.js +1353 -0
  29. package/dist/src/controller/task-assignment.js +508 -0
  30. package/dist/src/controller/task-cleanup.js +258 -0
  31. package/dist/src/controller/task-execution.js +240 -0
  32. package/dist/src/controller/task-results.js +461 -0
  33. package/dist/src/controller/task-router.js +137 -0
  34. package/dist/src/controller/task-routes.js +703 -0
  35. package/dist/src/controller/teamauto-routes.js +124 -0
  36. package/dist/src/controller/tunnel-manager.js +548 -0
  37. package/dist/src/controller/ui-assets.js +68 -0
  38. package/dist/src/controller/websocket.js +42 -0
  39. package/dist/src/controller/worker-provisioning.js +1674 -0
  40. package/dist/src/controller/worker-routes.js +188 -0
  41. package/dist/src/discovery.js +86 -0
  42. package/dist/src/git-collaboration.js +694 -0
  43. package/dist/src/identity.js +132 -0
  44. package/dist/src/install-defaults.js +1 -0
  45. package/dist/src/interaction-contracts.js +531 -0
  46. package/dist/src/networking.js +91 -0
  47. package/dist/src/openclaw-workspace.js +925 -0
  48. package/dist/src/profile-loader.js +486 -0
  49. package/dist/src/profiles/banking.json +178 -0
  50. package/dist/src/profiles/crossborder-ecom.json +253 -0
  51. package/dist/src/profiles/insurance.json +157 -0
  52. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  53. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  54. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  55. package/dist/src/profiles/schema.json +201 -0
  56. package/dist/src/profiles/securities.json +137 -0
  57. package/dist/src/profiles/software-rd.json +264 -0
  58. package/dist/src/profiles/trading-co.json +200 -0
  59. package/dist/src/prompt-policy.js +386 -0
  60. package/dist/src/protocol.js +58 -0
  61. package/dist/src/role-ids.js +29 -0
  62. package/dist/src/roles.js +390 -0
  63. package/dist/src/session-roles.js +14 -0
  64. package/dist/src/state.js +361 -0
  65. package/dist/src/task-executor.js +1023 -0
  66. package/dist/src/teamauto/github-client.js +210 -0
  67. package/dist/src/teamauto/norms.js +85 -0
  68. package/dist/src/teamauto/repo-sync.js +423 -0
  69. package/dist/src/teamauto/scanner.js +207 -0
  70. package/dist/src/teamauto/schedule.js +123 -0
  71. package/dist/src/teamauto/scheduler.js +907 -0
  72. package/dist/src/teamauto/store.js +133 -0
  73. package/dist/src/types.js +290 -0
  74. package/dist/src/ui/app.js +4860 -0
  75. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  76. package/dist/src/ui/github-login.html +296 -0
  77. package/dist/src/ui/index.html +447 -0
  78. package/dist/src/ui/style.css +2805 -0
  79. package/dist/src/worker/http-handler.js +146 -0
  80. package/dist/src/worker/message-queue.js +24 -0
  81. package/dist/src/worker/prompt-injector.js +78 -0
  82. package/dist/src/worker/skill-installer.js +255 -0
  83. package/dist/src/worker/tools.js +541 -0
  84. package/dist/src/worker/worker-service.js +307 -0
  85. package/dist/src/workspace-browser.js +269 -0
  86. package/openclaw.plugin.json +28 -1
  87. package/package.json +3 -2
  88. package/src/config.ts +33 -2
  89. package/src/controller/clarification-routes.ts +404 -0
  90. package/src/controller/controller-intake.ts +1113 -0
  91. package/src/controller/controller-planning.ts +1029 -0
  92. package/src/controller/controller-runs.ts +239 -0
  93. package/src/controller/controller-service.ts +295 -41
  94. package/src/controller/controller-tools.ts +11 -7
  95. package/src/controller/http-server.ts +294 -6971
  96. package/src/controller/kickoff-orchestrator.ts +70 -7
  97. package/src/controller/message-delivery.ts +49 -0
  98. package/src/controller/message-routes.ts +137 -0
  99. package/src/controller/orchestration-manifest.ts +6 -29
  100. package/src/controller/preview-proxy.ts +127 -0
  101. package/src/controller/profile-switch.ts +366 -0
  102. package/src/controller/project-registry.ts +361 -0
  103. package/src/controller/prompt-injector.ts +23 -8
  104. package/src/controller/repo-routes.ts +91 -0
  105. package/src/controller/role-inference.ts +260 -22
  106. package/src/controller/route-table.ts +1616 -0
  107. package/src/controller/task-assignment.ts +618 -0
  108. package/src/controller/task-cleanup.ts +344 -0
  109. package/src/controller/task-execution.ts +356 -0
  110. package/src/controller/task-results.ts +544 -0
  111. package/src/controller/task-router.ts +98 -6
  112. package/src/controller/task-routes.ts +812 -0
  113. package/src/controller/teamauto-routes.ts +121 -0
  114. package/src/controller/ui-assets.ts +70 -0
  115. package/src/controller/websocket.ts +13 -1
  116. package/src/controller/worker-provisioning.ts +32 -4
  117. package/src/controller/worker-routes.ts +241 -0
  118. package/src/identity.ts +3 -2
  119. package/src/interaction-contracts.ts +7 -7
  120. package/src/openclaw-workspace.ts +44 -18
  121. package/src/profile-loader.ts +650 -0
  122. package/src/profiles/banking.json +178 -0
  123. package/src/profiles/crossborder-ecom.json +253 -0
  124. package/src/profiles/insurance.json +157 -0
  125. package/src/profiles/knowledge/hs-structure.md +97 -0
  126. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  127. package/src/profiles/knowledge/vat-principles.md +85 -0
  128. package/src/profiles/schema.json +201 -0
  129. package/src/profiles/securities.json +137 -0
  130. package/src/profiles/software-rd.json +264 -0
  131. package/src/profiles/trading-co.json +200 -0
  132. package/src/prompt-policy.ts +27 -13
  133. package/src/role-ids.ts +31 -0
  134. package/src/roles.ts +60 -14
  135. package/src/session-roles.ts +14 -0
  136. package/src/state.ts +236 -9
  137. package/src/task-executor.ts +7 -18
  138. package/src/teamauto/github-client.ts +21 -0
  139. package/src/teamauto/repo-sync.ts +246 -6
  140. package/src/teamauto/scanner.ts +47 -13
  141. package/src/teamauto/scheduler.ts +259 -16
  142. package/src/teamauto/store.ts +12 -0
  143. package/src/types.ts +133 -16
  144. package/src/ui/app.js +592 -24
  145. package/src/ui/index.html +44 -11
  146. package/src/ui/style.css +194 -0
  147. package/src/worker/prompt-injector.ts +48 -8
  148. package/src/worker/skill-installer.ts +3 -1
  149. package/src/worker/worker-service.ts +83 -3
@@ -0,0 +1,1616 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import type { IncomingMessage, ServerResponse } from "node:http";
4
+ import type { PluginConfig, TeamState } from "../types.js";
5
+ import {
6
+ parseJsonBody,
7
+ readRequestBody,
8
+ sendJson,
9
+ sendError,
10
+ } from "../protocol.js";
11
+ import { saveTeamState, listArchivedTeams } from "../state.js";
12
+ import { listWorkspaceTree, listWorkspaceSubtree, readWorkspaceFile, readWorkspaceRawFile } from "../workspace-browser.js";
13
+ import {
14
+ BUILTIN_PROFILES,
15
+ getActiveProfile,
16
+ getActiveRoles,
17
+ getActiveDefaultRole,
18
+ hasProfile,
19
+ validateActiveRoleId,
20
+ } from "../profile-loader.js";
21
+ import { importControllerGitBundle } from "../git-collaboration.js";
22
+ // PR-D of issue #204: this module owns the declarative route table + the
23
+ // dispatcher that replaced http-server.ts's serial if/startsWith chain. It
24
+ // imports the domain route modules (PR-A/B/C cuts) and keeps the handful of
25
+ // handlers that were still inline in http-server.ts verbatim (the handler
26
+ // bodies moved here unchanged; only the surrounding shell changed from an
27
+ // `if (method && pathname)` block into a table entry). It must never be
28
+ // imported by the domain modules and never imports http-server.ts at
29
+ // RUNTIME (only the ControllerHttpDeps type, which is erased at compile
30
+ // time) so the module graph stays acyclic.
31
+ import type { ControllerHttpDeps } from "./http-server.js";
32
+ import { startTeamProfileSwitch } from "./profile-switch.js";
33
+ import { serveStaticFile, serveVersionedHtml } from "./ui-assets.js";
34
+ import {
35
+ handleTeamAutoActivityRequest,
36
+ handleTeamAutoReposListRequest,
37
+ handleTeamAutoRepoCandidatesRequest,
38
+ handleTeamAutoRepoBindRequest,
39
+ handleTeamAutoRepoItemRequest,
40
+ } from "./teamauto-routes.js";
41
+ import {
42
+ handleRepoStatusRequest,
43
+ handleRepoBundleRequest,
44
+ } from "./repo-routes.js";
45
+ import { handlePreviewProxyRequest } from "./preview-proxy.js";
46
+ import { getGithubAuthManager } from "./github-auth.js";
47
+ import { gatePageHtml, computeGateCookie, GATE_COOKIE_NAME, selfHostedTokenFromEnv, type TunnelManager } from "./tunnel-manager.js";
48
+ import { generateDeliveryReport, renderReportHtml } from "./delivery-report.js";
49
+ import {
50
+ teamClawWorkspaceIsDefault,
51
+ updateTeamClawWorkspaceDir,
52
+ getTeamClawModelReadiness,
53
+ getTeamClawModelCatalog,
54
+ updateTeamClawModelConfig,
55
+ resolveTeamClawWorkspaceDir,
56
+ } from "../openclaw-workspace.js";
57
+ import { resolvePreferredLanAddress } from "../networking.js";
58
+ import { normalizeControllerManifest } from "./orchestration-manifest.js";
59
+ import {
60
+ normalizeControllerIntakeSessionKey,
61
+ recordTaskExecutionEvent,
62
+ serializeTask,
63
+ } from "./task-execution.js";
64
+ import {
65
+ findLatestControllerRunIdForSession,
66
+ syncProjectRegistryEntry,
67
+ } from "./project-registry.js";
68
+ import {
69
+ appendControllerRunEvent,
70
+ serializeControllerRun,
71
+ updateControllerRun,
72
+ } from "./controller-runs.js";
73
+ import {
74
+ deleteControllerRunCascade,
75
+ deleteProjectCascade,
76
+ resolveSafeProjectDirectory,
77
+ } from "./task-cleanup.js";
78
+ import {
79
+ ControllerIntakeSwitchInProgressError,
80
+ reconcileControllerClarifications,
81
+ runControllerIntake,
82
+ } from "./controller-intake.js";
83
+ import { buildControllerManifestEventMessage } from "./controller-planning.js";
84
+ import {
85
+ buildStartupReadinessMessage,
86
+ getEffectiveStartupReadiness,
87
+ shouldBlockControllerUntilProvisioningReady,
88
+ handleWorkerDeleteRequest,
89
+ handleWorkerHeartbeatRequest,
90
+ handleWorkerListRequest,
91
+ handleWorkerRegisterRequest,
92
+ } from "./worker-routes.js";
93
+ import {
94
+ handleTaskAssignRequest,
95
+ handleTaskCheckpointRequest,
96
+ handleTaskCreateRequest,
97
+ handleTaskDeleteRequest,
98
+ handleTaskExecutionEventRequest,
99
+ handleTaskExecutionGetRequest,
100
+ handleTaskGetRequest,
101
+ handleTaskHandoffRequest,
102
+ handleTaskListRequest,
103
+ handleTaskParallelHelpRequest,
104
+ handleTaskPatchRequest,
105
+ handleTaskResultContractRequest,
106
+ handleTaskResultRequest,
107
+ } from "./task-routes.js";
108
+ import {
109
+ handleBroadcastMessageRequest,
110
+ handleDirectMessageRequest,
111
+ handleMessageListRequest,
112
+ handleReviewRequestMessageRequest,
113
+ } from "./message-routes.js";
114
+ import {
115
+ handleClarificationAnswerRequest,
116
+ handleClarificationCreateRequest,
117
+ handleClarificationListRequest,
118
+ } from "./clarification-routes.js";
119
+
120
+ // ===========================================================================
121
+ // PR-D of issue #204: declarative route table + dispatcher.
122
+ //
123
+ // Every request that survives the dispatch-layer gates in http-server.ts
124
+ // (CORS preflight -> tunnel gate -> transition matrix -> capability 404
125
+ // gates) is matched against `controllerRouteTable` BELOW IN ARRAY ORDER -
126
+ // the order is a compatibility contract and mirrors the historical
127
+ // if/startsWith chain of http-server.ts one-to-one (order-sensitive pairs:
128
+ // the exact /ui/auth/github routes precede the /ui/ prefix; the exact
129
+ // teamauto repos routes precede the per-repo prefix whose handler may
130
+ // decline with `false` and fall through; the preview proxy prefix sits
131
+ // after every /api/v1 exact route and before reports/health). The parity
132
+ // is pinned by tests/test-route-table.mjs against the pre-PR-D source.
133
+ //
134
+ // RouteDef semantics:
135
+ // - `method`: exact HTTP method, array whitelist, or "*" (any method -
136
+ // used by the teamauto per-repo prefix whose handler self-dispatches).
137
+ // - `path` + `prefix`: a string path is exact pathname equality, unless
138
+ // `prefix: true` marks it as a startsWith prefix (kept as plain strings
139
+ // so the prefix literals stay greppable); a RegExp path is
140
+ // `.test(pathname)` (anchored, for :id routes).
141
+ // - `handler`: receives the RouteContext; returning `false` means "not
142
+ // handled - continue matching" (fall-through), anything else (void,
143
+ // true, a thrown error) ends dispatch. No match at all => the caller
144
+ // answers the final 404.
145
+ // ===========================================================================
146
+
147
+ export type RouteContext = {
148
+ req: IncomingMessage;
149
+ res: ServerResponse;
150
+ /** The parsed request URL (query params via searchParams). */
151
+ requestUrl: URL;
152
+ /** The URL pathname of the request. */
153
+ pathname: string;
154
+ deps: ControllerHttpDeps;
155
+ /**
156
+ * Team state captured once at handleRequest entry (the transition matrix
157
+ * gate reads the same snapshot); null for the tunnel-side tables, whose
158
+ * handlers never read state.
159
+ */
160
+ currentState: TeamState | null;
161
+ };
162
+
163
+ export type RouteHandler = (ctx: RouteContext) => Promise<boolean | void> | boolean | void;
164
+
165
+ export type RouteDef = {
166
+ /** HTTP method, method whitelist, or "*" for any method. */
167
+ method: string | string[];
168
+ /** Exact pathname (string), startsWith prefix (string + prefix: true), or predicate (RegExp). */
169
+ path: string | RegExp;
170
+ /** Treat a string `path` as a startsWith prefix instead of exact equality. */
171
+ prefix?: boolean;
172
+ handler: RouteHandler;
173
+ };
174
+
175
+ function routeMethodMatches(routeMethod: string | string[], method: string): boolean {
176
+ if (routeMethod === "*") {
177
+ return true;
178
+ }
179
+ return Array.isArray(routeMethod) ? routeMethod.includes(method) : routeMethod === method;
180
+ }
181
+
182
+ function routePathMatches(route: RouteDef, pathname: string): boolean {
183
+ if (typeof route.path === "string") {
184
+ return route.prefix === true ? pathname.startsWith(route.path) : pathname === route.path;
185
+ }
186
+ return route.path.test(pathname);
187
+ }
188
+
189
+ /**
190
+ * Matches `ctx` against `routes` in array order. Returns true when a route
191
+ * handled the request (handler did not return false); false when the table
192
+ * was exhausted, in which case the caller answers the final 404.
193
+ */
194
+ export async function dispatchRoutes(routes: readonly RouteDef[], ctx: RouteContext): Promise<boolean> {
195
+ const method = ctx.req.method ?? "";
196
+ for (const route of routes) {
197
+ if (!routeMethodMatches(route.method, method)) {
198
+ continue;
199
+ }
200
+ if (!routePathMatches(route, ctx.pathname)) {
201
+ continue;
202
+ }
203
+ const handled = await route.handler(ctx);
204
+ if (handled !== false) {
205
+ return true;
206
+ }
207
+ // handler declined (teamauto per-repo pattern): keep matching.
208
+ }
209
+ return false;
210
+ }
211
+
212
+ // ===========================================================================
213
+ // Shared helpers (moved verbatim from http-server.ts; PR-D only changed
214
+ // their module home, not their behavior).
215
+ // ===========================================================================
216
+
217
+ /**
218
+ * Retry hint shared by the transition-matrix gate (http-server.ts, task
219
+ * submission / repo import) and the intake handler below. Lives here since
220
+ * PR-D because the intake handler body (which carries it in 503 bodies)
221
+ * moved into this file; http-server.ts imports it back for the gates.
222
+ */
223
+ export const SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS = 5;
224
+
225
+ const EXTERNAL_WORKER_INSTALL_SPEC = "@teamclaws/teamclaw";
226
+
227
+ async function readFormBody(request: IncomingMessage): Promise<Record<string, unknown>> {
228
+ const chunks: Buffer[] = [];
229
+ for await (const chunk of request) chunks.push(chunk as Buffer);
230
+ const raw = Buffer.concat(chunks).toString("utf8");
231
+ const out: Record<string, unknown> = {};
232
+ for (const [k, v] of new URLSearchParams(raw)) out[k] = v;
233
+ return out;
234
+ }
235
+
236
+ function resolveRequestPort(req: IncomingMessage, fallbackPort: number): number {
237
+ const hostHeader = req.headers.host?.trim();
238
+ if (!hostHeader) {
239
+ return fallbackPort;
240
+ }
241
+ try {
242
+ const parsed = new URL(`http://${hostHeader}`);
243
+ return parsed.port ? Number(parsed.port) : fallbackPort;
244
+ } catch {
245
+ return fallbackPort;
246
+ }
247
+ }
248
+
249
+ function resolveRecommendedLanControllerUrl(req: IncomingMessage, fallbackPort: number): string {
250
+ const port = resolveRequestPort(req, fallbackPort);
251
+ const preferredLan = resolvePreferredLanAddress();
252
+ return preferredLan ? `http://${preferredLan}:${port}` : "";
253
+ }
254
+
255
+ function shellEscapeSingleQuotes(value: string): string {
256
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
257
+ }
258
+
259
+ function buildExternalWorkerInstallInfo(req: IncomingMessage, config: PluginConfig): Record<string, unknown> {
260
+ const recommendedControllerUrl = resolveRecommendedLanControllerUrl(req, config.port);
261
+ return {
262
+ teamName: config.teamName,
263
+ recommendedControllerUrl,
264
+ defaultRole: getActiveDefaultRole(),
265
+ roles: getActiveRoles().map((role) => ({ id: role.id, label: role.label, icon: role.icon })),
266
+ autoDiscoveryCommandPrefix:
267
+ `npx -y ${EXTERNAL_WORKER_INSTALL_SPEC} install --yes --install-mode worker --team-name ${shellEscapeSingleQuotes(config.teamName)} --worker-role `,
268
+ manualCommandPrefix:
269
+ `npx -y ${EXTERNAL_WORKER_INSTALL_SPEC} install --yes --install-mode worker --team-name ${shellEscapeSingleQuotes(config.teamName)} --worker-role `,
270
+ manualControllerUrlFlag: recommendedControllerUrl
271
+ ? ` --controller-url ${shellEscapeSingleQuotes(recommendedControllerUrl)}`
272
+ : "",
273
+ manualControllerWarning: recommendedControllerUrl
274
+ ? "Manual worker installs must use the controller LAN IP, not localhost/127.0.0.1."
275
+ : "No private LAN IPv4 address was detected on this controller host yet, so manual worker install commands are unavailable until a LAN address exists.",
276
+ autoDiscoveryWarning: "mDNS auto-discovery only works when the worker and controller are reachable on the same LAN.",
277
+ };
278
+ }
279
+
280
+ function workspaceRequestErrorStatus(err: unknown): number {
281
+ if (err && typeof err === "object" && "code" in err && (err as { code?: unknown }).code === "ENOENT") {
282
+ return 404;
283
+ }
284
+ return 400;
285
+ }
286
+
287
+ function workspaceRequestErrorMessage(err: unknown): string {
288
+ return err instanceof Error ? err.message : "Workspace request failed";
289
+ }
290
+
291
+ function resolveRequestOrigin(req: IncomingMessage, config: PluginConfig): string {
292
+ const host = req.headers.host;
293
+ if (typeof host === "string" && host.trim()) {
294
+ return `http://${host.trim()}`;
295
+ }
296
+ return `http://127.0.0.1:${config.port}`;
297
+ }
298
+
299
+ function escapeHtmlText(value: string): string {
300
+ return value
301
+ .replace(/&/g, "&amp;")
302
+ .replace(/</g, "&lt;")
303
+ .replace(/>/g, "&gt;")
304
+ .replace(/"/g, "&quot;")
305
+ .replace(/'/g, "&#39;");
306
+ }
307
+
308
+ function sendGithubCallbackHtml(res: ServerResponse, statusCode: number, title: string, message: string): void {
309
+ const html = [
310
+ "<!DOCTYPE html><html><head><meta charset=\"utf-8\">",
311
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
312
+ `<title>${escapeHtmlText(title)}</title>`,
313
+ "<style>body{font-family:-apple-system,system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:#0f1117;color:#e6e8ee}main{max-width:520px;padding:32px 40px;border:1px solid #2a2f3a;border-radius:14px;background:#161923;text-align:center}h1{font-size:20px;margin:0 0 10px}p{margin:6px 0;color:#a8b0c0;line-height:1.6}</style>",
314
+ "</head><body><main>",
315
+ `<h1>${escapeHtmlText(title)}</h1>`,
316
+ `<p>${escapeHtmlText(message)}</p>`,
317
+ "</main></body></html>",
318
+ ].join("");
319
+ res.writeHead(statusCode, {
320
+ "Content-Type": "text/html; charset=utf-8",
321
+ "Content-Length": Buffer.byteLength(html),
322
+ });
323
+ res.end(html);
324
+ }
325
+
326
+ type TeamStatsResponse = {
327
+ totalWorkers: number;
328
+ workersByStatus: { idle: number; busy: number; offline: number };
329
+ totalTasks: number;
330
+ tasksByStatus: Record<string, number>;
331
+ averageTaskDuration: number | null;
332
+ uptime: number;
333
+ };
334
+
335
+ // PR-D note: computeTeamStats used to be declared INSIDE handleRequest
336
+ // (between task-route shells); it is hoisted to module scope here, body
337
+ // unchanged, single call site unchanged.
338
+ function computeTeamStats(state: TeamState): TeamStatsResponse {
339
+ const workers = Object.values(state.workers);
340
+ const tasks = Object.values(state.tasks);
341
+
342
+ const workersByStatus = { idle: 0, busy: 0, offline: 0 };
343
+ for (const worker of workers) {
344
+ workersByStatus[worker.status] += 1;
345
+ }
346
+
347
+ const tasksByStatus: Record<string, number> = {};
348
+ for (const task of tasks) {
349
+ tasksByStatus[task.status] = (tasksByStatus[task.status] ?? 0) + 1;
350
+ }
351
+
352
+ const completedTasks = tasks.filter(
353
+ (task) => task.status === "completed" && task.startedAt && task.completedAt,
354
+ );
355
+ const averageTaskDuration = completedTasks.length > 0
356
+ ? completedTasks.reduce((sum, task) => sum + (task.completedAt! - task.startedAt!), 0) / completedTasks.length
357
+ : null;
358
+
359
+ return {
360
+ totalWorkers: workers.length,
361
+ workersByStatus,
362
+ totalTasks: tasks.length,
363
+ tasksByStatus,
364
+ averageTaskDuration,
365
+ uptime: process.uptime() * 1000,
366
+ };
367
+ }
368
+
369
+ // ===========================================================================
370
+ // Route handlers. The PR-A/B/C domain handlers are forwarded to unchanged;
371
+ // the bodies that were inline in http-server.ts moved here verbatim (the
372
+ // only edit is reading req/res/requestUrl/pathname/deps/currentState from
373
+ // the RouteContext instead of the old function arguments).
374
+ // ===========================================================================
375
+
376
+ // ---- Web UI (http-server.ts pre-PR-D lines 588-625) ----
377
+
378
+ function webUiRootRoute(ctx: RouteContext): void {
379
+ const { res } = ctx;
380
+ res.statusCode = 302;
381
+ res.setHeader("Location", "/ui");
382
+ res.end();
383
+ }
384
+
385
+ function webUiIndexRoute(ctx: RouteContext): void {
386
+ const { res } = ctx;
387
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
388
+ serveVersionedHtml(res, path.join(uiPath, "index.html"));
389
+ }
390
+
391
+ // Standalone GitHub device-login page (big user code + prefilled link + polling).
392
+ function webUiGithubLoginPageRoute(ctx: RouteContext): void {
393
+ const { res } = ctx;
394
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
395
+ serveStaticFile(res, path.join(uiPath, "github-login.html"), "text/html; charset=utf-8");
396
+ }
397
+
398
+ function webUiAssetsRoute(ctx: RouteContext): void {
399
+ const { res, pathname } = ctx;
400
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
401
+ const file = pathname.slice(4); // remove "/ui/"
402
+ if (file.endsWith(".css")) {
403
+ serveStaticFile(res, path.join(uiPath, file), "text/css; charset=utf-8");
404
+ } else if (file.endsWith(".js")) {
405
+ serveStaticFile(res, path.join(uiPath, file), "application/javascript; charset=utf-8");
406
+ } else if (file.endsWith(".png")) {
407
+ serveStaticFile(res, path.join(uiPath, file), "image/png");
408
+ } else if (file.endsWith(".svg")) {
409
+ serveStaticFile(res, path.join(uiPath, file), "image/svg+xml; charset=utf-8");
410
+ } else if (file.endsWith(".ico")) {
411
+ serveStaticFile(res, path.join(uiPath, file), "image/x-icon");
412
+ } else {
413
+ serveStaticFile(res, path.join(uiPath, file), "application/octet-stream");
414
+ }
415
+ }
416
+
417
+ // ---- TeamAuto (pre-PR-D lines 631-654; handlers in ./teamauto-routes.ts) ----
418
+
419
+ async function teamAutoActivityRoute(ctx: RouteContext): Promise<void> {
420
+ await handleTeamAutoActivityRequest(ctx.deps, ctx.res);
421
+ }
422
+
423
+ async function teamAutoReposListRoute(ctx: RouteContext): Promise<void> {
424
+ await handleTeamAutoReposListRequest(ctx.deps, ctx.res);
425
+ }
426
+
427
+ // Selectable repos for the bind picker (the logged-in GitHub account's).
428
+ async function teamAutoRepoCandidatesRoute(ctx: RouteContext): Promise<void> {
429
+ await handleTeamAutoRepoCandidatesRequest(ctx.deps, ctx.res);
430
+ }
431
+
432
+ async function teamAutoRepoBindRoute(ctx: RouteContext): Promise<void> {
433
+ await handleTeamAutoRepoBindRequest(ctx.deps, ctx.req, ctx.res);
434
+ }
435
+
436
+ // Any-method prefix route: the handler self-dispatches by method and
437
+ // DECLINES (returns false) for methods it does not own, falling through to
438
+ // the rest of the table - preserved by returning its boolean upstream.
439
+ function teamAutoRepoItemRoute(ctx: RouteContext): Promise<boolean> {
440
+ return handleTeamAutoRepoItemRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
441
+ }
442
+
443
+ // ---- GitHub Auth (pre-PR-D lines 658-753) ----
444
+
445
+ async function githubAuthStatusRoute(ctx: RouteContext): Promise<void> {
446
+ const { req, res, deps } = ctx;
447
+ const { config, logger } = deps;
448
+ try {
449
+ const status = await getGithubAuthManager(config, logger).getStatus(resolveRequestOrigin(req, config));
450
+ sendJson(res, 200, status);
451
+ } catch (err) {
452
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read GitHub login status");
453
+ }
454
+ }
455
+
456
+ async function githubAuthLoginRoute(ctx: RouteContext): Promise<void> {
457
+ const { req, res, deps } = ctx;
458
+ const { config, logger } = deps;
459
+ let flow: string | undefined;
460
+ try {
461
+ const body = await parseJsonBody(req) as { flow?: unknown };
462
+ if (typeof body?.flow === "string") {
463
+ flow = body.flow.trim();
464
+ }
465
+ } catch {
466
+ // No body or invalid body: fall through to the default (device) flow.
467
+ }
468
+ const manager = getGithubAuthManager(config, logger);
469
+ try {
470
+ const loginPageUrl = resolveRequestOrigin(req, config).replace(/\/+$/, "") + "/ui/auth/github";
471
+ if (flow === "web") {
472
+ // Web flow needs a client secret for the code exchange; the device
473
+ // flow (default) is fully secretless.
474
+ const start = manager.beginLogin(resolveRequestOrigin(req, config));
475
+ sendJson(res, 200, { mode: "web", loginPageUrl, ...start });
476
+ } else {
477
+ const start = await manager.beginDeviceLogin();
478
+ // authorizeUrl intentionally points at our standalone login page so
479
+ // older UI clients that just open response.authorizeUrl land on the
480
+ // device-code page instead of a dead web-flow URL.
481
+ sendJson(res, 200, { mode: "device", loginPageUrl, authorizeUrl: loginPageUrl, ...start });
482
+ }
483
+ logger.info(`Controller: GitHub login flow started (${flow === "web" ? "web" : "device"})`);
484
+ } catch (err) {
485
+ sendError(res, 400, err instanceof Error ? err.message : "failed to start GitHub login");
486
+ }
487
+ }
488
+
489
+ async function githubAuthCallbackRoute(ctx: RouteContext): Promise<void> {
490
+ const { req, res, requestUrl, deps } = ctx;
491
+ const { config, logger } = deps;
492
+ const callbackError = requestUrl.searchParams.get("error");
493
+ if (callbackError) {
494
+ const description = requestUrl.searchParams.get("error_description") ?? "";
495
+ logger.warn(`Controller: GitHub login was denied (${callbackError})`);
496
+ sendGithubCallbackHtml(
497
+ res,
498
+ 400,
499
+ "GitHub login failed",
500
+ `Authorization was denied: ${callbackError}${description ? ` (${description})` : ""}`,
501
+ );
502
+ return;
503
+ }
504
+ const code = requestUrl.searchParams.get("code") ?? "";
505
+ const state = requestUrl.searchParams.get("state") ?? "";
506
+ try {
507
+ const account = await getGithubAuthManager(config, logger).completeLogin({
508
+ code: code || undefined,
509
+ state: state || undefined,
510
+ });
511
+ logger.info(`Controller: GitHub login completed for @${account.login}`);
512
+ sendGithubCallbackHtml(
513
+ res,
514
+ 200,
515
+ "GitHub login successful",
516
+ `Signed in as @${account.login}(GitHub 登录成功,可关闭本页返回 TeamClaw)。`,
517
+ );
518
+ } catch (err) {
519
+ const message = err instanceof Error ? err.message : String(err);
520
+ logger.warn(`Controller: GitHub login callback failed: ${message}`);
521
+ sendGithubCallbackHtml(res, 400, "GitHub login failed", `${message}`);
522
+ }
523
+ }
524
+
525
+ async function githubAuthLogoutRoute(ctx: RouteContext): Promise<void> {
526
+ const { res, deps } = ctx;
527
+ const { config, logger } = deps;
528
+ try {
529
+ await getGithubAuthManager(config, logger).logout();
530
+ sendJson(res, 200, { ok: true });
531
+ } catch (err) {
532
+ sendError(res, 500, err instanceof Error ? err.message : "failed to sign out of GitHub");
533
+ }
534
+ }
535
+
536
+ async function githubAuthRefreshRoute(ctx: RouteContext): Promise<void> {
537
+ const { res, deps } = ctx;
538
+ const { config, logger } = deps;
539
+ try {
540
+ const store = await getGithubAuthManager(config, logger).forceRefresh();
541
+ sendJson(res, 200, { ok: true, account: store.account, expiresAt: store.expiresAt });
542
+ } catch (err) {
543
+ sendError(res, 400, err instanceof Error ? err.message : "failed to refresh the GitHub token");
544
+ }
545
+ }
546
+
547
+ // ---- Workspace Browser + model config (pre-PR-D lines 757-931) ----
548
+
549
+ function workspaceStatusRoute(ctx: RouteContext): void {
550
+ const { res } = ctx;
551
+ sendJson(res, 200, {
552
+ workspaceDir: resolveTeamClawWorkspaceDir(),
553
+ isDefault: teamClawWorkspaceIsDefault(),
554
+ });
555
+ }
556
+
557
+ async function workspaceChangeDirRoute(ctx: RouteContext): Promise<void> {
558
+ const { req, res, deps } = ctx;
559
+ let body: unknown;
560
+ try {
561
+ body = await parseJsonBody(req);
562
+ } catch {
563
+ sendError(res, 400, "invalid JSON body");
564
+ return;
565
+ }
566
+ const workspaceDir = typeof (body as { workspaceDir?: unknown })?.workspaceDir === "string"
567
+ ? (body as { workspaceDir: string }).workspaceDir
568
+ : "";
569
+ if (!workspaceDir.trim()) {
570
+ sendError(res, 400, "workspaceDir is required");
571
+ return;
572
+ }
573
+ try {
574
+ const result = await updateTeamClawWorkspaceDir(workspaceDir, {
575
+ warn: (message: string) => deps.logger.info(message),
576
+ });
577
+ sendJson(res, 200, {
578
+ ok: true,
579
+ workspaceDir: result.agentEntryPath,
580
+ configPath: result.configPath,
581
+ restartRequired: true,
582
+ });
583
+ } catch (err) {
584
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update workspace directory");
585
+ }
586
+ }
587
+
588
+ // GET /api/v1/models/config - model catalog + current selection for the UI settings dialog
589
+ async function modelsConfigGetRoute(ctx: RouteContext): Promise<void> {
590
+ const { res } = ctx;
591
+ try {
592
+ sendJson(res, 200, await getTeamClawModelCatalog());
593
+ } catch (err) {
594
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read model configuration");
595
+ }
596
+ }
597
+
598
+ // PUT /api/v1/models/config - persist default and per-role model selection
599
+ async function modelsConfigPutRoute(ctx: RouteContext): Promise<void> {
600
+ const { req, res, deps } = ctx;
601
+ let body: { defaultModel?: unknown; roleModelOverrides?: unknown } | null = null;
602
+ try {
603
+ body = await parseJsonBody(req) as { defaultModel?: unknown; roleModelOverrides?: unknown };
604
+ } catch {
605
+ sendError(res, 400, "invalid JSON body");
606
+ return;
607
+ }
608
+ const update: { defaultModel?: string; roleModelOverrides?: Record<string, string> } = {};
609
+ if (typeof body?.defaultModel === "string") {
610
+ update.defaultModel = body.defaultModel.trim();
611
+ }
612
+ if (body?.roleModelOverrides && typeof body.roleModelOverrides === "object" && !Array.isArray(body.roleModelOverrides)) {
613
+ const overrides: Record<string, string> = {};
614
+ for (const [role, value] of Object.entries(body.roleModelOverrides as Record<string, unknown>)) {
615
+ if (typeof value === "string" && value.trim()) {
616
+ overrides[role] = value.trim();
617
+ }
618
+ }
619
+ update.roleModelOverrides = overrides;
620
+ }
621
+ if (update.defaultModel === undefined && update.roleModelOverrides === undefined) {
622
+ sendError(res, 400, "defaultModel or roleModelOverrides is required");
623
+ return;
624
+ }
625
+ try {
626
+ await updateTeamClawModelConfig(update, {
627
+ warn: (message: string) => deps.logger.info(message),
628
+ });
629
+ sendJson(res, 200, {
630
+ ok: true,
631
+ restartNote: "Config changes hot-reload; restart the gateway (openclaw gateway restart) if a change does not take effect.",
632
+ catalog: await getTeamClawModelCatalog(),
633
+ });
634
+ } catch (err) {
635
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update model configuration");
636
+ }
637
+ }
638
+
639
+ async function workspaceTreeRoute(ctx: RouteContext): Promise<void> {
640
+ const { res, requestUrl } = ctx;
641
+ try {
642
+ // depth=N limits tree expansion (default 1 for lazy loading)
643
+ const depthParam = requestUrl.searchParams.get("depth");
644
+ const maxDepth = depthParam !== null ? Math.max(0, Math.min(parseInt(depthParam, 10) || 1, 8)) : 1;
645
+ sendJson(res, 200, await listWorkspaceTree(maxDepth));
646
+ } catch (err) {
647
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
648
+ }
649
+ }
650
+
651
+ async function workspaceSubtreeRoute(ctx: RouteContext): Promise<void> {
652
+ const { res, requestUrl } = ctx;
653
+ const dirPath = requestUrl.searchParams.get("path") ?? "";
654
+ if (!dirPath) {
655
+ sendError(res, 400, "path is required");
656
+ return;
657
+ }
658
+ try {
659
+ sendJson(res, 200, { entries: await listWorkspaceSubtree(dirPath) });
660
+ } catch (err) {
661
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
662
+ }
663
+ }
664
+
665
+ async function workspaceFileRoute(ctx: RouteContext): Promise<void> {
666
+ const { res, requestUrl } = ctx;
667
+ const relativePath = requestUrl.searchParams.get("path") ?? "";
668
+ if (!relativePath) {
669
+ sendError(res, 400, "path is required");
670
+ return;
671
+ }
672
+
673
+ try {
674
+ sendJson(res, 200, { file: await readWorkspaceFile(relativePath) });
675
+ } catch (err) {
676
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
677
+ }
678
+ }
679
+
680
+ async function workspaceProjectPathRoute(ctx: RouteContext): Promise<void> {
681
+ const { res, requestUrl } = ctx;
682
+ const projectDir = requestUrl.searchParams.get("projectDir") ?? "";
683
+ if (!projectDir) {
684
+ sendError(res, 400, "projectDir is required");
685
+ return;
686
+ }
687
+ const absolutePath = resolveSafeProjectDirectory(projectDir);
688
+ if (!absolutePath) {
689
+ sendError(res, 400, "Invalid projectDir");
690
+ return;
691
+ }
692
+ if (!fs.existsSync(absolutePath)) {
693
+ sendError(res, 404, "Project directory not found");
694
+ return;
695
+ }
696
+ sendJson(res, 200, {
697
+ projectDir,
698
+ absolutePath,
699
+ });
700
+ }
701
+
702
+ async function workspaceRawFileRoute(ctx: RouteContext): Promise<void> {
703
+ const { res, pathname } = ctx;
704
+ const rawPathname = pathname.slice("/api/v1/workspace/raw/".length);
705
+ if (!rawPathname) {
706
+ sendError(res, 400, "path is required");
707
+ return;
708
+ }
709
+
710
+ try {
711
+ const relativePath = decodeURIComponent(rawPathname);
712
+ const file = await readWorkspaceRawFile(relativePath);
713
+ res.writeHead(200, {
714
+ "Content-Type": file.contentType,
715
+ "Cache-Control": "no-store",
716
+ "Access-Control-Allow-Origin": "*",
717
+ "X-Content-Type-Options": "nosniff",
718
+ });
719
+ res.end(file.content);
720
+ } catch (err) {
721
+ sendError(res, workspaceRequestErrorStatus(err), workspaceRequestErrorMessage(err));
722
+ }
723
+ }
724
+
725
+ // ---- Worker Management (pre-PR-D lines 939-960; handlers in ./worker-routes.ts) ----
726
+
727
+ async function workerRegisterRoute(ctx: RouteContext): Promise<void> {
728
+ await handleWorkerRegisterRequest(ctx.deps, ctx.req, ctx.res);
729
+ }
730
+
731
+ async function workerDeleteRoute(ctx: RouteContext): Promise<void> {
732
+ await handleWorkerDeleteRequest(ctx.deps, ctx.res, ctx.pathname);
733
+ }
734
+
735
+ async function workerListRoute(ctx: RouteContext): Promise<void> {
736
+ await handleWorkerListRequest(ctx.deps, ctx.res);
737
+ }
738
+
739
+ async function workerHeartbeatRoute(ctx: RouteContext): Promise<void> {
740
+ await handleWorkerHeartbeatRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
741
+ }
742
+
743
+ // ---- Task Management (pre-PR-D lines 968-1100; handlers in ./task-routes.ts) ----
744
+
745
+ async function taskCreateRoute(ctx: RouteContext): Promise<void> {
746
+ await handleTaskCreateRequest(ctx.deps, ctx.req, ctx.res);
747
+ }
748
+
749
+ async function taskListRoute(ctx: RouteContext): Promise<void> {
750
+ await handleTaskListRequest(ctx.deps, ctx.res);
751
+ }
752
+
753
+ async function teamStatsRoute(ctx: RouteContext): Promise<void> {
754
+ const { res, deps } = ctx;
755
+ const state = deps.getTeamState();
756
+ if (!state) {
757
+ sendError(res, 503, "Team state not available");
758
+ return;
759
+ }
760
+ try {
761
+ const stats = computeTeamStats(state);
762
+ sendJson(res, 200, stats);
763
+ } catch (err) {
764
+ sendError(res, 500, `Failed to compute stats: ${err instanceof Error ? err.message : String(err)}`);
765
+ }
766
+ }
767
+
768
+ async function taskGetRoute(ctx: RouteContext): Promise<void> {
769
+ await handleTaskGetRequest(ctx.deps, ctx.res, ctx.pathname);
770
+ }
771
+
772
+ async function taskDeleteRoute(ctx: RouteContext): Promise<void> {
773
+ await handleTaskDeleteRequest(ctx.deps, ctx.res, ctx.pathname);
774
+ }
775
+
776
+ async function taskExecutionGetRoute(ctx: RouteContext): Promise<void> {
777
+ await handleTaskExecutionGetRequest(ctx.deps, ctx.res, ctx.pathname);
778
+ }
779
+
780
+ async function taskPatchRoute(ctx: RouteContext): Promise<void> {
781
+ await handleTaskPatchRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
782
+ }
783
+
784
+ async function taskAssignRoute(ctx: RouteContext): Promise<void> {
785
+ await handleTaskAssignRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
786
+ }
787
+
788
+ async function taskHandoffRoute(ctx: RouteContext): Promise<void> {
789
+ await handleTaskHandoffRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
790
+ }
791
+
792
+ // POST /api/v1/tasks/:id/checkpoint - worker persists an execution progress
793
+ // snapshot so an interrupted task can resume instead of restarting.
794
+ async function taskCheckpointRoute(ctx: RouteContext): Promise<void> {
795
+ await handleTaskCheckpointRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
796
+ }
797
+
798
+ async function taskResultContractRoute(ctx: RouteContext): Promise<void> {
799
+ await handleTaskResultContractRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
800
+ }
801
+
802
+ async function taskResultRoute(ctx: RouteContext): Promise<void> {
803
+ await handleTaskResultRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
804
+ }
805
+
806
+ async function taskExecutionEventRoute(ctx: RouteContext): Promise<void> {
807
+ await handleTaskExecutionEventRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
808
+ }
809
+
810
+ async function taskParallelHelpRoute(ctx: RouteContext): Promise<void> {
811
+ await handleTaskParallelHelpRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
812
+ }
813
+
814
+ // ---- Controller runs / intake (pre-PR-D lines 1109-1289) ----
815
+
816
+ async function controllerManifestRoute(ctx: RouteContext): Promise<void> {
817
+ const { req, res, deps } = ctx;
818
+ const { logger, getTeamState, updateTeamState, wsServer } = deps;
819
+ const body = await parseJsonBody(req);
820
+ const sessionKey = normalizeControllerIntakeSessionKey(body.sessionKey);
821
+ const manifest = normalizeControllerManifest(body.manifest);
822
+ if (!manifest) {
823
+ sendError(res, 400, "manifest is required and must include requirementSummary");
824
+ return;
825
+ }
826
+
827
+ const runId = findLatestControllerRunIdForSession(sessionKey, deps.getTeamState(), {
828
+ preferActive: true,
829
+ });
830
+ if (!runId) {
831
+ sendError(res, 404, "Controller run not found for session");
832
+ return;
833
+ }
834
+
835
+ const updatedRun = updateControllerRun(runId, deps, (run) => {
836
+ run.manifest = manifest;
837
+ const state = deps.getTeamState();
838
+ if (state) {
839
+ const project = syncProjectRegistryEntry(state, {
840
+ projectId: manifest.projectName ?? run.projectId,
841
+ projectDir: run.projectDir ?? manifest.projectName,
842
+ aliases: [manifest.projectName, run.projectId],
843
+ summary: manifest.requirementSummary,
844
+ updatedAt: Date.now(),
845
+ });
846
+ run.projectId = project.projectId;
847
+ run.projectDir = project.projectDir;
848
+ }
849
+
850
+ if (run.projectDir) {
851
+ const state = deps.getTeamState();
852
+ if (state) {
853
+ for (const taskId of run.createdTaskIds) {
854
+ const task = state.tasks[taskId];
855
+ if (task) {
856
+ if (!task.projectDir) {
857
+ task.projectDir = run.projectDir;
858
+ }
859
+ if (!task.projectId) {
860
+ task.projectId = run.projectId;
861
+ }
862
+ }
863
+ }
864
+ }
865
+ }
866
+
867
+ appendControllerRunEvent(run, {
868
+ type: "output",
869
+ phase: "manifest_recorded",
870
+ source: "controller",
871
+ status: "running",
872
+ sessionKey,
873
+ message: buildControllerManifestEventMessage(manifest),
874
+ });
875
+ });
876
+
877
+ if (!updatedRun) {
878
+ sendError(res, 404, "Controller run not found");
879
+ return;
880
+ }
881
+
882
+ if (manifest.requirementFullyComplete) {
883
+ logger.info(`Controller: requirement fully complete for session ${sessionKey} (run ${runId})`);
884
+ wsServer.broadcastUpdate({
885
+ type: "requirement:complete",
886
+ data: {
887
+ runId,
888
+ sessionKey,
889
+ requirementSummary: manifest.requirementSummary,
890
+ },
891
+ });
892
+ }
893
+
894
+ sendJson(res, 201, {
895
+ controllerRun: serializeControllerRun(updatedRun),
896
+ manifest,
897
+ });
898
+ }
899
+
900
+ async function controllerRunsListRoute(ctx: RouteContext): Promise<void> {
901
+ const { res, deps } = ctx;
902
+ const state = reconcileControllerClarifications(deps);
903
+ const controllerRuns = state
904
+ ? Object.values(state.controllerRuns)
905
+ .sort((left, right) => right.updatedAt - left.updatedAt)
906
+ .map((run) => serializeControllerRun(run))
907
+ : [];
908
+ sendJson(res, 200, { controllerRuns });
909
+ }
910
+
911
+ async function projectDeleteRoute(ctx: RouteContext): Promise<void> {
912
+ const { res, pathname, deps } = ctx;
913
+ const projectDir = decodeURIComponent(pathname.split("/").pop()!);
914
+ const result = await deleteProjectCascade(projectDir, deps);
915
+ if (!result.deleted) {
916
+ sendError(res, 404, "Project not found or project cleanup could not be confirmed");
917
+ return;
918
+ }
919
+ const safeProjectPath = resolveSafeProjectDirectory(projectDir);
920
+ const stillExists = safeProjectPath ? fs.existsSync(safeProjectPath) : true;
921
+ if (stillExists) {
922
+ sendError(res, 409, "Project cleanup could not be confirmed");
923
+ return;
924
+ }
925
+ sendJson(res, 200, {
926
+ status: "deleted",
927
+ confirmed: true,
928
+ projectDir,
929
+ cleanup: result.summary,
930
+ });
931
+ }
932
+
933
+ async function controllerRunDeleteRoute(ctx: RouteContext): Promise<void> {
934
+ const { res, pathname, deps } = ctx;
935
+ const { getTeamState } = deps;
936
+ const runId = pathname.split("/").pop()!;
937
+ const result = await deleteControllerRunCascade(runId, deps);
938
+ if (!result.deleted) {
939
+ sendError(res, 404, "Controller run not found");
940
+ return;
941
+ }
942
+ const stillExists = !!getTeamState()?.controllerRuns[runId];
943
+ if (stillExists) {
944
+ sendError(res, 409, "Planning run cleanup could not be confirmed");
945
+ return;
946
+ }
947
+ sendJson(res, 200, {
948
+ status: "deleted",
949
+ confirmed: true,
950
+ runId,
951
+ cleanup: result.summary,
952
+ });
953
+ }
954
+
955
+ async function controllerIntakeRoute(ctx: RouteContext): Promise<void> {
956
+ const { req, res, deps, currentState } = ctx;
957
+ const { logger } = deps;
958
+ const readinessGate = shouldBlockControllerUntilProvisioningReady(deps, currentState);
959
+ if (readinessGate.blocked && readinessGate.readiness) {
960
+ sendError(res, 503, buildStartupReadinessMessage(readinessGate.readiness));
961
+ return;
962
+ }
963
+ const body = await parseJsonBody(req);
964
+ const message = typeof body.message === "string" ? body.message.trim() : "";
965
+ if (!message) {
966
+ sendError(res, 400, "message is required");
967
+ return;
968
+ }
969
+
970
+ const sessionKey = normalizeControllerIntakeSessionKey(body.sessionKey);
971
+
972
+ try {
973
+ const result = await runControllerIntake(message, sessionKey, deps);
974
+ sendJson(res, 200, result);
975
+ } catch (err) {
976
+ if (err instanceof ControllerIntakeSwitchInProgressError) {
977
+ // Same response shape as the URL-level transition gate (503 +
978
+ // Retry-After); reachable here when a switch starts between the gate
979
+ // and the intake entry (the gate reads the state once per request).
980
+ res.setHeader("Retry-After", String(SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS));
981
+ sendJson(res, 503, {
982
+ error: err.message,
983
+ retryAfterSeconds: SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS,
984
+ transition: {
985
+ phase: err.transition.phase,
986
+ targetProfileId: err.transition.targetProfileId,
987
+ },
988
+ });
989
+ return;
990
+ }
991
+ const errorMessage = err instanceof Error ? err.message : String(err);
992
+ logger.warn(`Controller: intake failed for ${sessionKey}: ${errorMessage}`);
993
+ sendError(res, errorMessage.includes("timed out") ? 504 : 500, errorMessage);
994
+ }
995
+ }
996
+
997
+ // ---- Message Routing (pre-PR-D lines 1292-1313; handlers in ./message-routes.ts) ----
998
+
999
+ async function messageDirectRoute(ctx: RouteContext): Promise<void> {
1000
+ await handleDirectMessageRequest(ctx.deps, ctx.req, ctx.res);
1001
+ }
1002
+
1003
+ async function messageBroadcastRoute(ctx: RouteContext): Promise<void> {
1004
+ await handleBroadcastMessageRequest(ctx.deps, ctx.req, ctx.res);
1005
+ }
1006
+
1007
+ async function messageReviewRequestRoute(ctx: RouteContext): Promise<void> {
1008
+ await handleReviewRequestMessageRequest(ctx.deps, ctx.req, ctx.res);
1009
+ }
1010
+
1011
+ async function messageListRoute(ctx: RouteContext): Promise<void> {
1012
+ await handleMessageListRequest(ctx.deps, ctx.res, ctx.requestUrl);
1013
+ }
1014
+
1015
+ // ---- Clarification Requests (pre-PR-D lines 1318-1333; handlers in ./clarification-routes.ts) ----
1016
+
1017
+ async function clarificationCreateRoute(ctx: RouteContext): Promise<void> {
1018
+ await handleClarificationCreateRequest(ctx.deps, ctx.req, ctx.res);
1019
+ }
1020
+
1021
+ async function clarificationListRoute(ctx: RouteContext): Promise<void> {
1022
+ await handleClarificationListRequest(ctx.deps, ctx.res);
1023
+ }
1024
+
1025
+ async function clarificationAnswerRoute(ctx: RouteContext): Promise<void> {
1026
+ await handleClarificationAnswerRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
1027
+ }
1028
+
1029
+ // ---- Git Collaboration (pre-PR-D lines 1342-1412) ----
1030
+ // PR-B of issue #204: the repo status/bundle handlers and the shared
1031
+ // refreshControllerRepoState glue live in ./repo-routes.ts; the POST
1032
+ // /repo/import handler body moved here with PR-D (its
1033
+ // recordTaskExecutionEvent dependency is task-lifecycle glue owned by the
1034
+ // PR-C cut).
1035
+
1036
+ async function repoStatusRoute(ctx: RouteContext): Promise<void> {
1037
+ await handleRepoStatusRequest(ctx.deps, ctx.res);
1038
+ }
1039
+
1040
+ async function repoBundleRoute(ctx: RouteContext): Promise<void> {
1041
+ await handleRepoBundleRequest(ctx.deps, ctx.res);
1042
+ }
1043
+
1044
+ async function repoImportRoute(ctx: RouteContext): Promise<void> {
1045
+ const { req, res, requestUrl, deps } = ctx;
1046
+ const { config, logger, updateTeamState } = deps;
1047
+ const body = await readRequestBody(req);
1048
+ if (!body.length) {
1049
+ sendError(res, 400, "bundle body is required");
1050
+ return;
1051
+ }
1052
+
1053
+ const taskId = typeof requestUrl.searchParams.get("taskId") === "string" && requestUrl.searchParams.get("taskId")
1054
+ ? requestUrl.searchParams.get("taskId")!
1055
+ : undefined;
1056
+ const workerId = typeof requestUrl.searchParams.get("workerId") === "string" && requestUrl.searchParams.get("workerId")
1057
+ ? requestUrl.searchParams.get("workerId")!
1058
+ : undefined;
1059
+ const role = validateActiveRoleId(requestUrl.searchParams.get("role"));
1060
+
1061
+ try {
1062
+ const imported = await importControllerGitBundle(config, logger, body, { taskId, workerId });
1063
+ updateTeamState((s) => {
1064
+ s.repo = imported.repo;
1065
+ });
1066
+
1067
+ if (taskId) {
1068
+ recordTaskExecutionEvent(taskId, {
1069
+ type: imported.merged || imported.alreadyUpToDate ? "lifecycle" : "error",
1070
+ phase: imported.merged
1071
+ ? "repo_imported"
1072
+ : imported.alreadyUpToDate
1073
+ ? "repo_import_skipped"
1074
+ : "repo_import_failed",
1075
+ source: "controller",
1076
+ message: imported.message,
1077
+ workerId,
1078
+ role,
1079
+ }, deps);
1080
+ }
1081
+
1082
+ sendJson(res, imported.merged || imported.alreadyUpToDate ? 200 : 409, {
1083
+ repo: imported.repo,
1084
+ merged: imported.merged,
1085
+ fastForwarded: imported.fastForwarded,
1086
+ alreadyUpToDate: imported.alreadyUpToDate,
1087
+ message: imported.message,
1088
+ });
1089
+ } catch (err) {
1090
+ const message = err instanceof Error ? err.message : String(err);
1091
+ if (taskId) {
1092
+ recordTaskExecutionEvent(taskId, {
1093
+ type: "error",
1094
+ phase: "repo_import_failed",
1095
+ source: "controller",
1096
+ message,
1097
+ workerId,
1098
+ role,
1099
+ }, deps);
1100
+ }
1101
+ sendError(res, 500, message);
1102
+ }
1103
+ }
1104
+
1105
+ // ---- Team Info / profiles (pre-PR-D lines 1417-1576) ----
1106
+
1107
+ async function teamStatusRoute(ctx: RouteContext): Promise<void> {
1108
+ const { req, res, deps } = ctx;
1109
+ const { config } = deps;
1110
+ const state = reconcileControllerClarifications(deps);
1111
+ const startupReadiness = getEffectiveStartupReadiness(deps, state);
1112
+ const modelReadiness = getTeamClawModelReadiness();
1113
+ const externalWorkerInstall = buildExternalWorkerInstallInfo(req, config);
1114
+ if (!state) {
1115
+ sendJson(res, 200, {
1116
+ teamName: config.teamName,
1117
+ workers: [],
1118
+ tasks: [],
1119
+ controllerRuns: [],
1120
+ messages: [],
1121
+ clarifications: [],
1122
+ previews: [],
1123
+ repo: null,
1124
+ pendingClarificationCount: 0,
1125
+ modelReadiness,
1126
+ externalWorkerInstall,
1127
+ provisioning: startupReadiness ? { startupReadiness } : undefined,
1128
+ });
1129
+ return;
1130
+ }
1131
+
1132
+ const clarifications = Object.values(state.clarifications).sort((left, right) => right.createdAt - left.createdAt);
1133
+ sendJson(res, 200, {
1134
+ teamName: state.teamName,
1135
+ workers: Object.values(state.workers),
1136
+ tasks: Object.values(state.tasks).map((task) => serializeTask(task)),
1137
+ controllerRuns: Object.values(state.controllerRuns)
1138
+ .sort((left, right) => right.updatedAt - left.updatedAt)
1139
+ .map((run) => serializeControllerRun(run)),
1140
+ messages: state.messages,
1141
+ clarifications,
1142
+ previews: Object.values(state.previews ?? {}),
1143
+ repo: state.repo ?? null,
1144
+ modelReadiness,
1145
+ externalWorkerInstall,
1146
+ provisioning: {
1147
+ ...(state.provisioning ?? { workers: {} }),
1148
+ startupReadiness,
1149
+ },
1150
+ taskCount: Object.keys(state.tasks).length,
1151
+ workerCount: Object.keys(state.workers).length,
1152
+ pendingClarificationCount: clarifications.filter((item) => item.status === "pending").length,
1153
+ });
1154
+ }
1155
+
1156
+ function teamRolesRoute(ctx: RouteContext): void {
1157
+ const { res } = ctx;
1158
+ sendJson(res, 200, { roles: getActiveRoles(), defaultRole: getActiveDefaultRole() });
1159
+ }
1160
+
1161
+ // GET /api/v1/profiles — list the available team profile packages
1162
+ // (Phase 2.1, design section 4: the switcher UI reads this list).
1163
+ function teamProfilesListRoute(ctx: RouteContext): void {
1164
+ const { res } = ctx;
1165
+ const profiles = [...BUILTIN_PROFILES.values()]
1166
+ .sort((a, b) => a.id.localeCompare(b.id))
1167
+ .map((profile) => ({
1168
+ id: profile.id,
1169
+ name: profile.name,
1170
+ nameZh: profile.nameZh,
1171
+ icon: profile.icon,
1172
+ industry: profile.industry,
1173
+ description: profile.description,
1174
+ roleCount: profile.roles.length,
1175
+ version: profile.version,
1176
+ // Capability switches ride along so the switcher confirm step can
1177
+ // warn that off -> on flips need a gateway restart to take effect
1178
+ // (subsystems are wired at controller startup only; runtime teardown
1179
+ // is one-directional). Additive field - existing consumers ignore it.
1180
+ capabilities: profile.capabilities,
1181
+ ...(profile.reviewedBy ? { reviewedBy: profile.reviewedBy } : {}),
1182
+ }));
1183
+ sendJson(res, 200, { profiles });
1184
+ }
1185
+
1186
+ // GET /api/v1/team/profile — active profile detail incl. capabilities
1187
+ // (design section 4: UI hides capability-gated entries based on this).
1188
+ function teamProfileGetRoute(ctx: RouteContext): void {
1189
+ const { res, deps } = ctx;
1190
+ const { config } = deps;
1191
+ const state = deps.getTeamState();
1192
+ const profile = getActiveProfile();
1193
+ sendJson(res, 200, {
1194
+ profileId: state?.profileId ?? profile.id,
1195
+ profile,
1196
+ teamName: state?.teamName ?? config.teamName,
1197
+ transition: state?.transition ?? null,
1198
+ });
1199
+ }
1200
+
1201
+ // POST /api/v1/team/profile { profileId } — six-step switch semantics
1202
+ // (Phase 2.1, design section 2.3). Returns 202; progress arrives via the
1203
+ // team.switch_started / team.switch_completed WS events.
1204
+ async function teamProfileSwitchRoute(ctx: RouteContext): Promise<void> {
1205
+ const { req, res, deps } = ctx;
1206
+ const { config, logger, getTeamState, updateTeamState, wsServer } = deps;
1207
+ const body = await parseJsonBody(req);
1208
+ const profileId = typeof body.profileId === "string" ? body.profileId.trim() : "";
1209
+ if (!profileId || !hasProfile(profileId)) {
1210
+ sendError(
1211
+ res,
1212
+ 404,
1213
+ `unknown team profile "${profileId || "<empty>"}" (available: ${[...BUILTIN_PROFILES.keys()].sort().join(", ")})`,
1214
+ );
1215
+ return;
1216
+ }
1217
+ const state = getTeamState();
1218
+ if (!state) {
1219
+ sendError(res, 503, "Team state not loaded");
1220
+ return;
1221
+ }
1222
+ if (state.transition) {
1223
+ sendJson(res, 409, {
1224
+ error: `a team profile switch to "${state.transition.targetProfileId}" is already in progress (phase: ${state.transition.phase})`,
1225
+ transition: state.transition,
1226
+ });
1227
+ return;
1228
+ }
1229
+
1230
+ // Step 1: persist the transition (the crash-resume truth) and announce.
1231
+ // The check-and-set above plus this mutation run without an await in
1232
+ // between, so a concurrent second POST observes the transition (409).
1233
+ const previousProfileId = state.profileId;
1234
+ updateTeamState((s) => {
1235
+ s.transition = { phase: "draining", targetProfileId: profileId, startedAt: Date.now() };
1236
+ });
1237
+ try {
1238
+ await saveTeamState(state);
1239
+ } catch (err) {
1240
+ // Durability failed: roll the in-memory transition back so the team is
1241
+ // never wedged behind a transition the crash-resume path cannot see.
1242
+ // Nothing has been broadcast yet, so no external observer was told a
1243
+ // switch had started.
1244
+ updateTeamState((s) => {
1245
+ delete s.transition;
1246
+ });
1247
+ sendError(res, 500, `failed to persist the team profile switch transition: ${err instanceof Error ? err.message : String(err)}`);
1248
+ return;
1249
+ }
1250
+ wsServer.broadcastUpdate({ type: "team.switch_started", data: { profileId, previousProfileId } });
1251
+ logger.info(`Controller: team profile switch started - "${previousProfileId}" -> "${profileId}"`);
1252
+
1253
+ // Steps 2-6 plus the failure broadcast path live in ./profile-switch.ts
1254
+ // (startTeamProfileSwitch: fire-and-forget executeTeamProfileSwitch with
1255
+ // the archive-preservation-aware team.switch_failed unwedging).
1256
+ startTeamProfileSwitch(deps, state, profileId, previousProfileId);
1257
+
1258
+ sendJson(res, 202, { status: "switching", profileId, transition: state.transition });
1259
+ }
1260
+
1261
+ // GET /api/v1/archived-teams — archived team metadata list
1262
+ // (Phase 2.1, design section 4: profileId/teamName/time/taskCount; detail
1263
+ // queries and the archive UI stay v1.1).
1264
+ async function archivedTeamsRoute(ctx: RouteContext): Promise<void> {
1265
+ const { res } = ctx;
1266
+ const archives = await listArchivedTeams();
1267
+ sendJson(res, 200, { archives });
1268
+ }
1269
+
1270
+ // ---- Previews / reports / health (pre-PR-D lines 1580-1633) ----
1271
+
1272
+ // /api/v1/previews/:id/* — proxy to preview subprocess.
1273
+ // PR-B of issue #204: the proxy implementation lives in ./preview-proxy.ts.
1274
+ // Deliberately NOT awaited (fire-and-forget proxy), exactly as before.
1275
+ function previewsProxyRoute(ctx: RouteContext): void {
1276
+ handlePreviewProxyRequest(ctx.deps, ctx.req, ctx.res, ctx.requestUrl, ctx.pathname);
1277
+ }
1278
+
1279
+ // GET /api/v1/reports — list all delivery reports
1280
+ function reportsListRoute(ctx: RouteContext): void {
1281
+ const { res, deps } = ctx;
1282
+ const state = deps.getTeamState();
1283
+ const reports = Object.values(state?.reports ?? {}).sort((a, b) => b.generatedAt - a.generatedAt);
1284
+ sendJson(res, 200, { reports });
1285
+ }
1286
+
1287
+ // GET /api/v1/reports/:sessionKey — serve delivery report page
1288
+ async function reportsSessionRoute(ctx: RouteContext): Promise<void> {
1289
+ const { req, res, pathname, deps } = ctx;
1290
+ const sessionKey = decodeURIComponent(pathname.slice("/api/v1/reports/".length));
1291
+ const state = deps.getTeamState();
1292
+ if (!state) {
1293
+ sendError(res, 503, "Team state not loaded");
1294
+ return;
1295
+ }
1296
+ const report = generateDeliveryReport(sessionKey, state, normalizeControllerIntakeSessionKey);
1297
+ if (!report) {
1298
+ sendError(res, 404, "No report found for this session");
1299
+ return;
1300
+ }
1301
+ const accept = (req.headers["accept"] ?? "").toLowerCase();
1302
+ if (accept.includes("application/json")) {
1303
+ sendJson(res, 200, { report });
1304
+ } else {
1305
+ const html = renderReportHtml(report);
1306
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(html, "utf-8") });
1307
+ res.end(html);
1308
+ }
1309
+ }
1310
+
1311
+ function healthRoute(ctx: RouteContext): void {
1312
+ const { res, deps, currentState } = ctx;
1313
+ const readiness = getEffectiveStartupReadiness(deps, currentState);
1314
+ const modelReadiness = getTeamClawModelReadiness();
1315
+ const statusCode = readiness && readiness.status !== "ready" ? 503 : 200;
1316
+ sendJson(res, statusCode, {
1317
+ status: readiness?.status === "degraded" ? "degraded" : readiness?.status === "checking" ? "starting" : "ok",
1318
+ mode: "controller",
1319
+ timestamp: Date.now(),
1320
+ provisioningReadiness: readiness,
1321
+ modelReadiness,
1322
+ });
1323
+ }
1324
+
1325
+ // ===========================================================================
1326
+ // The controller route table. ORDER IS LOAD-BEARING: it mirrors the pre-PR-D
1327
+ // if/startsWith chain of http-server.ts one-to-one (the "old lines" in the
1328
+ // section comments refer to http-server.ts at e223767, the merge base of
1329
+ // this branch). tests/test-route-table.mjs asserts this order against both
1330
+ // a hardcoded expectation and that git snapshot.
1331
+ // ===========================================================================
1332
+
1333
+ export const controllerRouteTable: readonly RouteDef[] = [
1334
+ // ==================== Web UI (old lines 588-625) ====================
1335
+ { method: "GET", path: "/", handler: webUiRootRoute },
1336
+ { method: "GET", path: "/ui", handler: webUiIndexRoute },
1337
+ { method: "GET", path: "/ui/", handler: webUiIndexRoute },
1338
+ // Standalone GitHub device-login page (big user code + prefilled link + polling).
1339
+ { method: "GET", path: "/ui/auth/github", handler: webUiGithubLoginPageRoute },
1340
+ { method: "GET", path: "/ui/auth/github/", handler: webUiGithubLoginPageRoute },
1341
+ { method: "GET", path: "/ui/", prefix: true, handler: webUiAssetsRoute },
1342
+
1343
+ // ==================== TeamAuto (old lines 631-654) ====================
1344
+ { method: "GET", path: "/api/v1/teamauto/activity", handler: teamAutoActivityRoute },
1345
+ { method: "GET", path: "/api/v1/teamauto/repos", handler: teamAutoReposListRoute },
1346
+ // Selectable repos for the bind picker (the logged-in GitHub account's).
1347
+ { method: "GET", path: "/api/v1/teamauto/repo-candidates", handler: teamAutoRepoCandidatesRoute },
1348
+ { method: "POST", path: "/api/v1/teamauto/repos", handler: teamAutoRepoBindRoute },
1349
+ // Per-repo prefix, any method: exact entries above win first; the handler
1350
+ // declines (false) for unknown methods and dispatch falls through.
1351
+ { method: "*", path: "/api/v1/teamauto/repos/", prefix: true, handler: teamAutoRepoItemRoute },
1352
+
1353
+ // ==================== GitHub Auth (old lines 658-753) ====================
1354
+ { method: "GET", path: "/api/v1/auth/github/status", handler: githubAuthStatusRoute },
1355
+ { method: "POST", path: "/api/v1/auth/github/login", handler: githubAuthLoginRoute },
1356
+ { method: "GET", path: "/api/v1/auth/github/callback", handler: githubAuthCallbackRoute },
1357
+ { method: "POST", path: "/api/v1/auth/github/logout", handler: githubAuthLogoutRoute },
1358
+ { method: "POST", path: "/api/v1/auth/github/refresh", handler: githubAuthRefreshRoute },
1359
+
1360
+ // ==================== Workspace Browser (old lines 757-931) ====================
1361
+ { method: "GET", path: "/api/v1/workspace/status", handler: workspaceStatusRoute },
1362
+ { method: "POST", path: "/api/v1/workspace/change-dir", handler: workspaceChangeDirRoute },
1363
+ // GET /api/v1/models/config - model catalog + current selection for the UI settings dialog
1364
+ { method: "GET", path: "/api/v1/models/config", handler: modelsConfigGetRoute },
1365
+ // PUT /api/v1/models/config - persist default and per-role model selection
1366
+ { method: "PUT", path: "/api/v1/models/config", handler: modelsConfigPutRoute },
1367
+ { method: "GET", path: "/api/v1/workspace/tree", handler: workspaceTreeRoute },
1368
+ { method: "GET", path: "/api/v1/workspace/subtree", handler: workspaceSubtreeRoute },
1369
+ { method: "GET", path: "/api/v1/workspace/file", handler: workspaceFileRoute },
1370
+ { method: "GET", path: "/api/v1/workspace/project-path", handler: workspaceProjectPathRoute },
1371
+ { method: "GET", path: "/api/v1/workspace/raw/", prefix: true, handler: workspaceRawFileRoute },
1372
+
1373
+ // ==================== Worker Management (old lines 939-960) ====================
1374
+ // POST /api/v1/workers/register
1375
+ { method: "POST", path: "/api/v1/workers/register", handler: workerRegisterRoute },
1376
+ // DELETE /api/v1/workers/:id
1377
+ { method: "DELETE", path: /^\/api\/v1\/workers\/[^/]+$/, handler: workerDeleteRoute },
1378
+ // GET /api/v1/workers
1379
+ { method: "GET", path: "/api/v1/workers", handler: workerListRoute },
1380
+ // POST /api/v1/workers/:id/heartbeat
1381
+ { method: "POST", path: /^\/api\/v1\/workers\/[^/]+\/heartbeat$/, handler: workerHeartbeatRoute },
1382
+
1383
+ // ==================== Task Management (old lines 968-1100) ====================
1384
+ // POST /api/v1/tasks
1385
+ { method: "POST", path: "/api/v1/tasks", handler: taskCreateRoute },
1386
+ // GET /api/v1/tasks
1387
+ { method: "GET", path: "/api/v1/tasks", handler: taskListRoute },
1388
+ // GET /api/v1/stats
1389
+ { method: "GET", path: "/api/v1/stats", handler: teamStatsRoute },
1390
+ // GET /api/v1/tasks/:id
1391
+ { method: "GET", path: /^\/api\/v1\/tasks\/[^/]+$/, handler: taskGetRoute },
1392
+ // DELETE /api/v1/tasks/:id
1393
+ { method: "DELETE", path: /^\/api\/v1\/tasks\/[^/]+$/, handler: taskDeleteRoute },
1394
+ // GET /api/v1/tasks/:id/execution
1395
+ { method: "GET", path: /^\/api\/v1\/tasks\/[^/]+\/execution$/, handler: taskExecutionGetRoute },
1396
+ // PATCH /api/v1/tasks/:id
1397
+ { method: "PATCH", path: /^\/api\/v1\/tasks\/[^/]+$/, handler: taskPatchRoute },
1398
+ // POST /api/v1/tasks/:id/assign
1399
+ { method: "POST", path: /^\/api\/v1\/tasks\/[^/]+\/assign$/, handler: taskAssignRoute },
1400
+ // POST /api/v1/tasks/:id/handoff
1401
+ { method: "POST", path: /^\/api\/v1\/tasks\/[^/]+\/handoff$/, handler: taskHandoffRoute },
1402
+ // POST /api/v1/tasks/:id/checkpoint - worker persists an execution progress
1403
+ // snapshot so an interrupted task can resume instead of restarting.
1404
+ { method: "POST", path: /^\/api\/v1\/tasks\/[^/]+\/checkpoint$/, handler: taskCheckpointRoute },
1405
+ // POST /api/v1/tasks/:id/result-contract
1406
+ { method: "POST", path: /^\/api\/v1\/tasks\/[^/]+\/result-contract$/, handler: taskResultContractRoute },
1407
+ // POST /api/v1/tasks/:id/result
1408
+ { method: "POST", path: /^\/api\/v1\/tasks\/[^/]+\/result$/, handler: taskResultRoute },
1409
+ // POST /api/v1/tasks/:id/execution
1410
+ { method: "POST", path: /^\/api\/v1\/tasks\/[^/]+\/execution$/, handler: taskExecutionEventRoute },
1411
+ // POST /api/v1/tasks/:id/parallel-help
1412
+ { method: "POST", path: /^\/api\/v1\/tasks\/[^/]+\/parallel-help$/, handler: taskParallelHelpRoute },
1413
+
1414
+ // ==================== Message Routing (old lines 1109-1313) ====================
1415
+ // POST /api/v1/controller/manifest
1416
+ { method: "POST", path: "/api/v1/controller/manifest", handler: controllerManifestRoute },
1417
+ // GET /api/v1/controller/runs
1418
+ { method: "GET", path: "/api/v1/controller/runs", handler: controllerRunsListRoute },
1419
+ // DELETE /api/v1/projects/:projectDir
1420
+ { method: "DELETE", path: /^\/api\/v1\/projects\/[^/]+$/, handler: projectDeleteRoute },
1421
+ // DELETE /api/v1/controller/runs/:id
1422
+ { method: "DELETE", path: /^\/api\/v1\/controller\/runs\/[^/]+$/, handler: controllerRunDeleteRoute },
1423
+ // POST /api/v1/controller/intake
1424
+ { method: "POST", path: "/api/v1/controller/intake", handler: controllerIntakeRoute },
1425
+ // POST /api/v1/messages/direct
1426
+ { method: "POST", path: "/api/v1/messages/direct", handler: messageDirectRoute },
1427
+ // POST /api/v1/messages/broadcast
1428
+ { method: "POST", path: "/api/v1/messages/broadcast", handler: messageBroadcastRoute },
1429
+ // POST /api/v1/messages/review-request
1430
+ { method: "POST", path: "/api/v1/messages/review-request", handler: messageReviewRequestRoute },
1431
+ // GET /api/v1/messages
1432
+ { method: "GET", path: "/api/v1/messages", handler: messageListRoute },
1433
+
1434
+ // ==================== Clarification Requests (old lines 1318-1333) ====================
1435
+ // POST /api/v1/clarifications
1436
+ { method: "POST", path: "/api/v1/clarifications", handler: clarificationCreateRoute },
1437
+ // GET /api/v1/clarifications
1438
+ { method: "GET", path: "/api/v1/clarifications", handler: clarificationListRoute },
1439
+ // POST /api/v1/clarifications/:id/answer
1440
+ { method: "POST", path: /^\/api\/v1\/clarifications\/[^/]+\/answer$/, handler: clarificationAnswerRoute },
1441
+
1442
+ // ==================== Git Collaboration (old lines 1342-1412) ====================
1443
+ // GET /api/v1/repo
1444
+ { method: "GET", path: "/api/v1/repo", handler: repoStatusRoute },
1445
+ // GET /api/v1/repo/bundle
1446
+ { method: "GET", path: "/api/v1/repo/bundle", handler: repoBundleRoute },
1447
+ // POST /api/v1/repo/import
1448
+ { method: "POST", path: "/api/v1/repo/import", handler: repoImportRoute },
1449
+
1450
+ // ==================== Team Info (old lines 1417-1576) ====================
1451
+ // GET /api/v1/team/status
1452
+ { method: "GET", path: "/api/v1/team/status", handler: teamStatusRoute },
1453
+ // GET /api/v1/roles
1454
+ { method: "GET", path: "/api/v1/roles", handler: teamRolesRoute },
1455
+ // GET /api/v1/profiles — list the available team profile packages
1456
+ // (Phase 2.1, design section 4: the switcher UI reads this list).
1457
+ { method: "GET", path: "/api/v1/profiles", handler: teamProfilesListRoute },
1458
+ // GET /api/v1/team/profile — active profile detail incl. capabilities
1459
+ // (design section 4: UI hides capability-gated entries based on this).
1460
+ { method: "GET", path: "/api/v1/team/profile", handler: teamProfileGetRoute },
1461
+ // POST /api/v1/team/profile { profileId } — six-step switch semantics
1462
+ // (Phase 2.1, design section 2.3). Returns 202; progress arrives via the
1463
+ // team.switch_started / team.switch_completed WS events.
1464
+ { method: "POST", path: "/api/v1/team/profile", handler: teamProfileSwitchRoute },
1465
+ // GET /api/v1/archived-teams — archived team metadata list
1466
+ // (Phase 2.1, design section 4: profileId/teamName/time/taskCount; detail
1467
+ // queries and the archive UI stay v1.1).
1468
+ { method: "GET", path: "/api/v1/archived-teams", handler: archivedTeamsRoute },
1469
+
1470
+ // ==================== Previews / reports / health (old lines 1580-1633) ====================
1471
+ // /api/v1/previews/:id/* — proxy to preview subprocess (5-method
1472
+ // whitelist, prefix route; sits after every exact /api/v1 route so it can
1473
+ // never shadow them).
1474
+ { method: ["GET", "HEAD", "POST", "PUT", "DELETE"], path: "/api/v1/previews/", prefix: true, handler: previewsProxyRoute },
1475
+ // GET /api/v1/reports — list all delivery reports
1476
+ { method: "GET", path: "/api/v1/reports", handler: reportsListRoute },
1477
+ // GET /api/v1/reports/:sessionKey — serve delivery report page
1478
+ { method: "GET", path: "/api/v1/reports/", prefix: true, handler: reportsSessionRoute },
1479
+ // GET /api/v1/health
1480
+ { method: "GET", path: "/api/v1/health", handler: healthRoute },
1481
+ ];
1482
+
1483
+ // ===========================================================================
1484
+ // Tunnel-side route tables (pre-PR-D http-server.ts lines 348-432, the
1485
+ // outer server callback's tunnel branch). These run BEFORE handleRequest
1486
+ // and are split exactly along the old viaTunnel if/else:
1487
+ // - viaTunnel: the gate page routes answer; every other tunnel request
1488
+ // must pass the gate cookie (403 gate page), then continues to the
1489
+ // controller route table;
1490
+ // - direct (non-tunnel): the tunnel management API answers, everything
1491
+ // else continues to the controller route table.
1492
+ // ===========================================================================
1493
+
1494
+ /** GET /__tunnel_gate + GET / + POST /__tunnel_gate/verify (via tunnel only). */
1495
+ export function createTunnelGateRoutes(tunnelManager: TunnelManager): readonly RouteDef[] {
1496
+ return [
1497
+ {
1498
+ method: "GET",
1499
+ path: "/__tunnel_gate",
1500
+ handler: ({ res, req }) => {
1501
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1502
+ res.end(gatePageHtml(String(req.headers.host), false));
1503
+ },
1504
+ },
1505
+ {
1506
+ // Valid gate cookie on "/" goes straight to the dashboard; the gate
1507
+ // page only greets visitors who have not authenticated yet.
1508
+ method: "GET",
1509
+ path: "/",
1510
+ handler: ({ res, req, pathname }) => {
1511
+ if (pathname === "/" && tunnelManager.gateAllows(req)) {
1512
+ res.writeHead(302, { Location: "/ui/" });
1513
+ res.end();
1514
+ return;
1515
+ }
1516
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1517
+ res.end(gatePageHtml(String(req.headers.host), false));
1518
+ },
1519
+ },
1520
+ {
1521
+ method: "POST",
1522
+ path: "/__tunnel_gate/verify",
1523
+ handler: async ({ res, req }) => {
1524
+ const form = await readFormBody(req);
1525
+ const submitted = String((form as { token?: unknown }).token ?? "").trim().toUpperCase();
1526
+ const st = tunnelManager.status();
1527
+ if (st.active && st.gateToken && submitted === st.gateToken) {
1528
+ const cookie = `${GATE_COOKIE_NAME}=${computeGateCookie(st.gateToken, st.tunnelId ?? "")}; Path=/; Max-Age=43200; HttpOnly; SameSite=Lax`;
1529
+ res.writeHead(302, { "Set-Cookie": cookie, Location: "/" });
1530
+ res.end();
1531
+ return;
1532
+ }
1533
+ res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
1534
+ res.end(gatePageHtml(String(req.headers.host), true));
1535
+ },
1536
+ },
1537
+ ];
1538
+ }
1539
+
1540
+ /** /api/v1/tunnel/* management API (direct requests only, never via tunnel). */
1541
+ export function createTunnelManagementRoutes(tunnelManager: TunnelManager, deps: ControllerHttpDeps): readonly RouteDef[] {
1542
+ const { config, logger } = deps;
1543
+ return [
1544
+ {
1545
+ method: "GET",
1546
+ path: "/api/v1/tunnel/status",
1547
+ handler: ({ res }) => {
1548
+ sendJson(res, 200, tunnelManager.status());
1549
+ },
1550
+ },
1551
+ {
1552
+ method: "POST",
1553
+ path: "/api/v1/tunnel/start",
1554
+ handler: async ({ res }) => {
1555
+ const authStatus = await getGithubAuthManager(config, logger).getStatus();
1556
+ const account = authStatus.account;
1557
+ if (!account?.login) { sendError(res, 401, "GitHub login required to share a tunnel"); return; }
1558
+ // Async launch: poll /tunnel/status for phase progress and the
1559
+ // resulting hostname/gateToken once startOp.phase === "done".
1560
+ const launched = tunnelManager.start(account.login);
1561
+ sendJson(res, 202, { launched, status: tunnelManager.status() });
1562
+ },
1563
+ },
1564
+ {
1565
+ // Self-hosted: user-owned Cloudflare tunnel via connector token (no
1566
+ // GitHub login, no platform tunnel server). Token from the request
1567
+ // body, or the TEAMCLAW_TUNNEL_TOKEN env injection when body is empty.
1568
+ method: "POST",
1569
+ path: "/api/v1/tunnel/start-self-hosted",
1570
+ handler: async ({ req, res }) => {
1571
+ let token = "";
1572
+ try {
1573
+ const body = await readFormBody(req) as { token?: unknown };
1574
+ token = String(body.token ?? "");
1575
+ } catch { /* fall through to env */ }
1576
+ if (!token.trim()) {
1577
+ const envToken = selfHostedTokenFromEnv();
1578
+ if (!envToken) { sendError(res, 400, "connector token required (or set TEAMCLAW_TUNNEL_TOKEN)"); return; }
1579
+ token = envToken;
1580
+ }
1581
+ const r = tunnelManager.startSelfHosted(token);
1582
+ if (!r.launched) { sendError(res, 400, r.error ?? "failed to start self-hosted tunnel"); return; }
1583
+ sendJson(res, 202, { launched: true, status: tunnelManager.status() });
1584
+ },
1585
+ },
1586
+ {
1587
+ method: "POST",
1588
+ path: "/api/v1/tunnel/start-quick",
1589
+ handler: ({ res }) => {
1590
+ const r = tunnelManager.startQuick();
1591
+ if (!r.launched) { sendError(res, 400, r.error ?? "failed to start quick tunnel"); return; }
1592
+ sendJson(res, 202, { launched: true, status: tunnelManager.status() });
1593
+ },
1594
+ },
1595
+ {
1596
+ method: "POST",
1597
+ path: "/api/v1/tunnel/stop",
1598
+ handler: async ({ res }) => {
1599
+ await tunnelManager.stop();
1600
+ sendJson(res, 200, tunnelManager.status());
1601
+ },
1602
+ },
1603
+ {
1604
+ method: "POST",
1605
+ path: "/api/v1/tunnel/install-cloudflared",
1606
+ handler: async ({ res }) => {
1607
+ try {
1608
+ const result = await tunnelManager.installCloudflared();
1609
+ sendJson(res, result.ok ? 200 : 500, { ...result, status: tunnelManager.status() });
1610
+ } catch (err) {
1611
+ sendError(res, 500, err instanceof Error ? err.message : "install failed");
1612
+ }
1613
+ },
1614
+ },
1615
+ ];
1616
+ }