@teamclaws/teamclaw 2026.11.0 → 2026.11.2
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.
- package/cli.mjs +368 -13
- package/dist/index.js +61 -32
- package/dist/src/config.js +24 -0
- package/dist/src/controller/auth-routes.js +129 -0
- package/dist/src/controller/clarification-routes.js +1 -1
- package/dist/src/controller/config-routes.js +138 -0
- package/dist/src/controller/controller-planning.js +1 -0
- package/dist/src/controller/controller-routes.js +195 -0
- package/dist/src/controller/controller-service.js +67 -10
- package/dist/src/controller/controller-tools.js +3 -1
- package/dist/src/controller/github-auth.js +2 -1
- package/dist/src/controller/http-server.js +51 -16
- package/dist/src/controller/kickoff-orchestrator.js +3 -39
- package/dist/src/controller/message-delivery.js +4 -1
- package/dist/src/controller/orchestration-manifest.js +5 -65
- package/dist/src/controller/preview-manager.js +51 -3
- package/dist/src/controller/profile-switch.js +42 -22
- package/dist/src/controller/provisioning/backend-contract.js +9 -0
- package/dist/src/controller/provisioning/container-shared.js +64 -0
- package/dist/src/controller/provisioning/docker.js +214 -0
- package/dist/src/controller/provisioning/kubernetes.js +244 -0
- package/dist/src/controller/provisioning/plugin-root.js +41 -0
- package/dist/src/controller/provisioning/process-supervisor.js +190 -0
- package/dist/src/controller/provisioning-config.js +239 -0
- package/dist/src/controller/repo-routes.js +70 -4
- package/dist/src/controller/report-routes.js +56 -0
- package/dist/src/controller/route-table.js +73 -1045
- package/dist/src/controller/security.js +775 -0
- package/dist/src/controller/status-routes.js +287 -0
- package/dist/src/controller/task-assignment.js +5 -2
- package/dist/src/controller/task-execution.js +31 -0
- package/dist/src/controller/task-results.js +10 -0
- package/dist/src/controller/tunnel-manager.js +41 -8
- package/dist/src/controller/tunnel-routes.js +225 -0
- package/dist/src/controller/websocket.js +6 -2
- package/dist/src/controller/webui-routes.js +49 -0
- package/dist/src/controller/worker-provisioning.js +39 -949
- package/dist/src/controller/workflow-routes.js +407 -0
- package/dist/src/controller/workspace-routes.js +200 -0
- package/dist/src/git-collaboration.js +4 -9
- package/dist/src/identity.js +12 -1
- package/dist/src/openclaw-workspace.js +36 -0
- package/dist/src/profile-loader.js +119 -1
- package/dist/src/profiles/banking.json +26 -2
- package/dist/src/profiles/schema.json +82 -2
- package/dist/src/prompt-policy.js +18 -6
- package/dist/src/protocol.js +66 -3
- package/dist/src/shared/clarification-schema.js +65 -0
- package/dist/src/shared/github-auth.js +15 -0
- package/dist/src/shared/kickoff-prompt.js +37 -0
- package/dist/src/shared/utils.js +47 -0
- package/dist/src/state.js +89 -3
- package/dist/src/teamauto/scanner.js +21 -2
- package/dist/src/teamauto/scheduler.js +9 -2
- package/dist/src/types.js +15 -1
- package/dist/src/ui/app.js +990 -73
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +125 -36
- package/dist/src/worker/http-handler.js +59 -0
- package/dist/src/worker/skill-installer.js +3 -9
- package/dist/src/worker/tools.js +20 -10
- package/dist/src/worker/worker-service.js +17 -4
- package/index.ts +69 -32
- package/openclaw.plugin.json +23 -2
- package/package.json +1 -1
- package/src/config.ts +24 -0
- package/src/controller/auth-routes.ts +157 -0
- package/src/controller/clarification-routes.ts +1 -1
- package/src/controller/config-routes.ts +152 -0
- package/src/controller/controller-planning.ts +8 -0
- package/src/controller/controller-routes.ts +237 -0
- package/src/controller/controller-service.ts +128 -10
- package/src/controller/controller-tools.ts +5 -2
- package/src/controller/github-auth.ts +28 -63
- package/src/controller/http-server.ts +66 -17
- package/src/controller/kickoff-orchestrator.ts +3 -42
- package/src/controller/message-delivery.ts +4 -1
- package/src/controller/orchestration-manifest.ts +8 -71
- package/src/controller/preview-manager.ts +53 -3
- package/src/controller/profile-switch.ts +53 -23
- package/src/controller/provisioning/backend-contract.ts +51 -0
- package/src/controller/provisioning/container-shared.ts +84 -0
- package/src/controller/provisioning/docker.ts +260 -0
- package/src/controller/provisioning/kubernetes.ts +263 -0
- package/src/controller/provisioning/plugin-root.ts +42 -0
- package/src/controller/provisioning/process-supervisor.ts +214 -0
- package/src/controller/provisioning-config.ts +289 -0
- package/src/controller/repo-routes.ts +84 -12
- package/src/controller/report-routes.ts +64 -0
- package/src/controller/route-table.ts +139 -1152
- package/src/controller/security.ts +899 -0
- package/src/controller/status-routes.ts +354 -0
- package/src/controller/task-assignment.ts +5 -1
- package/src/controller/task-execution.ts +43 -0
- package/src/controller/task-results.ts +12 -0
- package/src/controller/tunnel-manager.ts +45 -8
- package/src/controller/tunnel-routes.ts +231 -0
- package/src/controller/websocket.ts +20 -3
- package/src/controller/webui-routes.ts +55 -0
- package/src/controller/worker-provisioning.ts +51 -1117
- package/src/controller/workflow-routes.ts +498 -0
- package/src/controller/workspace-routes.ts +222 -0
- package/src/git-collaboration.ts +4 -9
- package/src/identity.ts +13 -1
- package/src/openclaw-workspace.ts +47 -0
- package/src/profile-loader.ts +167 -1
- package/src/profiles/banking.json +26 -2
- package/src/profiles/schema.json +82 -2
- package/src/prompt-policy.ts +19 -6
- package/src/protocol.ts +72 -2
- package/src/shared/clarification-schema.ts +81 -0
- package/src/shared/github-auth.ts +92 -0
- package/src/shared/kickoff-prompt.ts +47 -0
- package/src/shared/utils.ts +51 -0
- package/src/state.ts +92 -3
- package/src/teamauto/github-client.ts +2 -1
- package/src/teamauto/repo-sync.ts +2 -1
- package/src/teamauto/scanner.ts +22 -3
- package/src/teamauto/scheduler.ts +11 -3
- package/src/teamauto/store.ts +5 -0
- package/src/types.ts +130 -1
- package/src/ui/app.js +990 -73
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +125 -36
- package/src/worker/http-handler.ts +64 -1
- package/src/worker/skill-installer.ts +3 -9
- package/src/worker/tools.ts +21 -10
- package/src/worker/worker-service.ts +18 -4
|
@@ -1,36 +1,63 @@
|
|
|
1
|
-
import fs from "node:fs";
|
|
2
|
-
import path from "node:path";
|
|
3
1
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
4
|
-
import type {
|
|
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";
|
|
2
|
+
import type { TeamState } from "../types.js";
|
|
22
3
|
// PR-D of issue #204: this module owns the declarative route table + the
|
|
23
4
|
// dispatcher that replaced http-server.ts's serial if/startsWith chain. It
|
|
24
|
-
// imports the domain route modules (PR-A/B/C cuts) and
|
|
25
|
-
//
|
|
26
|
-
//
|
|
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
|
|
5
|
+
// imports the domain route modules (PR-A/B/C cuts) and must never be
|
|
6
|
+
// imported by the domain modules at runtime and never imports http-server.ts
|
|
7
|
+
// at RUNTIME (only the ControllerHttpDeps type, which is erased at compile
|
|
30
8
|
// time) so the module graph stays acyclic.
|
|
9
|
+
// Issue #226 W2: the handler bodies that PR-D had still kept inline here
|
|
10
|
+
// (web UI / GitHub auth / workspace+model config / controller runs+intake /
|
|
11
|
+
// team status+profiles+switch / reports+health / repo import) moved verbatim
|
|
12
|
+
// into the domain modules below; route-table is now the pure table +
|
|
13
|
+
// dispatcher (+ the tunnel-side tables, whose handlers never read state).
|
|
31
14
|
import type { ControllerHttpDeps } from "./http-server.js";
|
|
32
|
-
import {
|
|
33
|
-
|
|
15
|
+
import {
|
|
16
|
+
webUiRootRoute,
|
|
17
|
+
webUiIndexRoute,
|
|
18
|
+
webUiGithubLoginPageRoute,
|
|
19
|
+
webUiAssetsRoute,
|
|
20
|
+
} from "./webui-routes.js";
|
|
21
|
+
import {
|
|
22
|
+
githubAuthStatusRoute,
|
|
23
|
+
githubAuthLoginRoute,
|
|
24
|
+
githubAuthCallbackRoute,
|
|
25
|
+
githubAuthLogoutRoute,
|
|
26
|
+
githubAuthRefreshRoute,
|
|
27
|
+
} from "./auth-routes.js";
|
|
28
|
+
import {
|
|
29
|
+
workspaceStatusRoute,
|
|
30
|
+
workspaceChangeDirRoute,
|
|
31
|
+
modelsConfigGetRoute,
|
|
32
|
+
modelsConfigPutRoute,
|
|
33
|
+
workspaceTreeRoute,
|
|
34
|
+
workspaceSubtreeRoute,
|
|
35
|
+
workspaceFileRoute,
|
|
36
|
+
workspaceProjectPathRoute,
|
|
37
|
+
workspaceRawFileRoute,
|
|
38
|
+
} from "./workspace-routes.js";
|
|
39
|
+
import {
|
|
40
|
+
controllerManifestRoute,
|
|
41
|
+
controllerRunsListRoute,
|
|
42
|
+
projectDeleteRoute,
|
|
43
|
+
controllerRunDeleteRoute,
|
|
44
|
+
controllerIntakeRoute,
|
|
45
|
+
} from "./controller-routes.js";
|
|
46
|
+
import {
|
|
47
|
+
teamStatsRoute,
|
|
48
|
+
teamStatusRoute,
|
|
49
|
+
teamRolesRoute,
|
|
50
|
+
teamProfilesListRoute,
|
|
51
|
+
teamProfileGetRoute,
|
|
52
|
+
teamProfileSwitchRoute,
|
|
53
|
+
archivedTeamsRoute,
|
|
54
|
+
} from "./status-routes.js";
|
|
55
|
+
import { teamConfigGetRoute, teamConfigPatchRoute } from "./config-routes.js";
|
|
56
|
+
import {
|
|
57
|
+
reportsListRoute,
|
|
58
|
+
reportsSessionRoute,
|
|
59
|
+
healthRoute,
|
|
60
|
+
} from "./report-routes.js";
|
|
34
61
|
import {
|
|
35
62
|
handleTeamAutoActivityRequest,
|
|
36
63
|
handleTeamAutoReposListRequest,
|
|
@@ -41,50 +68,15 @@ import {
|
|
|
41
68
|
import {
|
|
42
69
|
handleRepoStatusRequest,
|
|
43
70
|
handleRepoBundleRequest,
|
|
71
|
+
repoImportRoute,
|
|
44
72
|
} from "./repo-routes.js";
|
|
45
73
|
import { handlePreviewProxyRequest } from "./preview-proxy.js";
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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";
|
|
74
|
+
// Issue #226 W2: the tunnel-side tables (gate page + management API, with
|
|
75
|
+
// their inline handler bodies, the gate-page HTML rendering and the tunnel
|
|
76
|
+
// form reader) live in ./tunnel-routes.ts; both factories are re-exported
|
|
77
|
+
// below so http-server.ts's imports are unchanged.
|
|
78
|
+
export { createTunnelGateRoutes, createTunnelManagementRoutes } from "./tunnel-routes.js";
|
|
84
79
|
import {
|
|
85
|
-
buildStartupReadinessMessage,
|
|
86
|
-
getEffectiveStartupReadiness,
|
|
87
|
-
shouldBlockControllerUntilProvisioningReady,
|
|
88
80
|
handleWorkerDeleteRequest,
|
|
89
81
|
handleWorkerHeartbeatRequest,
|
|
90
82
|
handleWorkerListRequest,
|
|
@@ -116,6 +108,24 @@ import {
|
|
|
116
108
|
handleClarificationCreateRequest,
|
|
117
109
|
handleClarificationListRequest,
|
|
118
110
|
} from "./clarification-routes.js";
|
|
111
|
+
// Issue #23 (backend wave): device-pairing security domain module. It owns
|
|
112
|
+
// the token/pairing primitives, the auth middleware (wired by
|
|
113
|
+
// http-server.ts), the WS upgrade guard and the handlers registered in the
|
|
114
|
+
// security section of the table below. It imports this file as TYPE ONLY
|
|
115
|
+
// (RouteContext), so the module graph stays acyclic.
|
|
116
|
+
import {
|
|
117
|
+
handleSecurityDeviceDeleteRequest,
|
|
118
|
+
handleSecurityEnableRequest,
|
|
119
|
+
handleSecurityGetRequest,
|
|
120
|
+
handleSecurityPairAutoRequest,
|
|
121
|
+
handleSecurityPairRequest,
|
|
122
|
+
handleSecurityPairStartRequest,
|
|
123
|
+
handleSecurityResetRequest,
|
|
124
|
+
} from "./security.js";
|
|
125
|
+
import type { SecurityPeer } from "./security.js";
|
|
126
|
+
// Design 2.4 workflows backend: POST /api/v1/workflows/{id}/start handler
|
|
127
|
+
// (engine + route live in ./workflow-routes.ts).
|
|
128
|
+
import { workflowStartRoute } from "./workflow-routes.js";
|
|
119
129
|
|
|
120
130
|
// ===========================================================================
|
|
121
131
|
// PR-D of issue #204: declarative route table + dispatcher.
|
|
@@ -158,6 +168,14 @@ export type RouteContext = {
|
|
|
158
168
|
* handlers never read state.
|
|
159
169
|
*/
|
|
160
170
|
currentState: TeamState | null;
|
|
171
|
+
/**
|
|
172
|
+
* Issue #23: per-request peer classification (loopback/LAN/tunnel)
|
|
173
|
+
* computed by the composition root alongside the device-auth gate; the
|
|
174
|
+
* pairing handlers read it to enforce their origin rules (enable:
|
|
175
|
+
* loopback only; pair-auto: LAN only). Absent for the tunnel-side
|
|
176
|
+
* tables.
|
|
177
|
+
*/
|
|
178
|
+
peer?: SecurityPeer;
|
|
161
179
|
};
|
|
162
180
|
|
|
163
181
|
export type RouteHandler = (ctx: RouteContext) => Promise<boolean | void> | boolean | void;
|
|
@@ -210,210 +228,30 @@ export async function dispatchRoutes(routes: readonly RouteDef[], ctx: RouteCont
|
|
|
210
228
|
}
|
|
211
229
|
|
|
212
230
|
// ===========================================================================
|
|
213
|
-
// Shared helpers
|
|
214
|
-
//
|
|
231
|
+
// Shared helpers. W2 of issue #226: the helpers whose consumers moved out
|
|
232
|
+
// (shell escaping, LAN-URL building, the GitHub callback HTML renderer,
|
|
233
|
+
// workspace error mapping, team stats, the tunnel form reader) moved with
|
|
234
|
+
// them; nothing inline remains in this module.
|
|
215
235
|
// ===========================================================================
|
|
216
236
|
|
|
217
237
|
/**
|
|
218
238
|
* Retry hint shared by the transition-matrix gate (http-server.ts, task
|
|
219
|
-
* submission / repo import) and the intake handler
|
|
220
|
-
*
|
|
221
|
-
*
|
|
239
|
+
* submission / repo import) and the intake handler. Declared in
|
|
240
|
+
* ./controller-routes.ts since W2 (it moved with the intake handler body);
|
|
241
|
+
* re-exported here so http-server.ts's gate import is unchanged.
|
|
222
242
|
*/
|
|
223
|
-
export
|
|
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, "&")
|
|
302
|
-
.replace(/</g, "<")
|
|
303
|
-
.replace(/>/g, ">")
|
|
304
|
-
.replace(/"/g, """)
|
|
305
|
-
.replace(/'/g, "'");
|
|
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
|
-
}
|
|
243
|
+
export { SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS } from "./controller-routes.js";
|
|
368
244
|
|
|
369
245
|
// ===========================================================================
|
|
370
246
|
// Route handlers. The PR-A/B/C domain handlers are forwarded to unchanged;
|
|
371
|
-
//
|
|
372
|
-
//
|
|
373
|
-
// the
|
|
247
|
+
// every handler body that was still inline here moved verbatim into its
|
|
248
|
+
// domain module with W2 of issue #226 (see the import block): route-table
|
|
249
|
+
// binds the exported handlers directly, exactly like the issue-#23 security
|
|
250
|
+
// handlers. Only the thin forwarder shells for the PR-A/B/C domain modules
|
|
251
|
+
// (whose handlers predate RouteContext) and the preview-proxy fire-and-
|
|
252
|
+
// forget shell remain below.
|
|
374
253
|
// ===========================================================================
|
|
375
254
|
|
|
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
255
|
// ---- TeamAuto (pre-PR-D lines 631-654; handlers in ./teamauto-routes.ts) ----
|
|
418
256
|
|
|
419
257
|
async function teamAutoActivityRoute(ctx: RouteContext): Promise<void> {
|
|
@@ -440,288 +278,6 @@ function teamAutoRepoItemRoute(ctx: RouteContext): Promise<boolean> {
|
|
|
440
278
|
return handleTeamAutoRepoItemRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
|
|
441
279
|
}
|
|
442
280
|
|
|
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
281
|
// ---- Worker Management (pre-PR-D lines 939-960; handlers in ./worker-routes.ts) ----
|
|
726
282
|
|
|
727
283
|
async function workerRegisterRoute(ctx: RouteContext): Promise<void> {
|
|
@@ -750,21 +306,6 @@ async function taskListRoute(ctx: RouteContext): Promise<void> {
|
|
|
750
306
|
await handleTaskListRequest(ctx.deps, ctx.res);
|
|
751
307
|
}
|
|
752
308
|
|
|
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
309
|
async function taskGetRoute(ctx: RouteContext): Promise<void> {
|
|
769
310
|
await handleTaskGetRequest(ctx.deps, ctx.res, ctx.pathname);
|
|
770
311
|
}
|
|
@@ -811,189 +352,6 @@ async function taskParallelHelpRoute(ctx: RouteContext): Promise<void> {
|
|
|
811
352
|
await handleTaskParallelHelpRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
|
|
812
353
|
}
|
|
813
354
|
|
|
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
355
|
// ---- Message Routing (pre-PR-D lines 1292-1313; handlers in ./message-routes.ts) ----
|
|
998
356
|
|
|
999
357
|
async function messageDirectRoute(ctx: RouteContext): Promise<void> {
|
|
@@ -1029,9 +387,9 @@ async function clarificationAnswerRoute(ctx: RouteContext): Promise<void> {
|
|
|
1029
387
|
// ---- Git Collaboration (pre-PR-D lines 1342-1412) ----
|
|
1030
388
|
// PR-B of issue #204: the repo status/bundle handlers and the shared
|
|
1031
389
|
// refreshControllerRepoState glue live in ./repo-routes.ts; the POST
|
|
1032
|
-
// /repo/import handler body
|
|
390
|
+
// /repo/import handler body joined them with W2 of issue #226 (its
|
|
1033
391
|
// recordTaskExecutionEvent dependency is task-lifecycle glue owned by the
|
|
1034
|
-
// PR-C cut).
|
|
392
|
+
// PR-C cut - acyclic, see the repo-routes.ts header).
|
|
1035
393
|
|
|
1036
394
|
async function repoStatusRoute(ctx: RouteContext): Promise<void> {
|
|
1037
395
|
await handleRepoStatusRequest(ctx.deps, ctx.res);
|
|
@@ -1041,233 +399,9 @@ async function repoBundleRoute(ctx: RouteContext): Promise<void> {
|
|
|
1041
399
|
await handleRepoBundleRequest(ctx.deps, ctx.res);
|
|
1042
400
|
}
|
|
1043
401
|
|
|
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
402
|
// ---- Previews / reports / health (pre-PR-D lines 1580-1633) ----
|
|
403
|
+
// W2 of issue #226: the reports list/session and health handler bodies live
|
|
404
|
+
// in ./report-routes.ts; only the fire-and-forget preview-proxy shell stays.
|
|
1271
405
|
|
|
1272
406
|
// /api/v1/previews/:id/* — proxy to preview subprocess.
|
|
1273
407
|
// PR-B of issue #204: the proxy implementation lives in ./preview-proxy.ts.
|
|
@@ -1276,52 +410,6 @@ function previewsProxyRoute(ctx: RouteContext): void {
|
|
|
1276
410
|
handlePreviewProxyRequest(ctx.deps, ctx.req, ctx.res, ctx.requestUrl, ctx.pathname);
|
|
1277
411
|
}
|
|
1278
412
|
|
|
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
413
|
// ===========================================================================
|
|
1326
414
|
// The controller route table. ORDER IS LOAD-BEARING: it mirrors the pre-PR-D
|
|
1327
415
|
// if/startsWith chain of http-server.ts one-to-one (the "old lines" in the
|
|
@@ -1478,139 +566,38 @@ export const controllerRouteTable: readonly RouteDef[] = [
|
|
|
1478
566
|
{ method: "GET", path: "/api/v1/reports/", prefix: true, handler: reportsSessionRoute },
|
|
1479
567
|
// GET /api/v1/health
|
|
1480
568
|
{ method: "GET", path: "/api/v1/health", handler: healthRoute },
|
|
1481
|
-
];
|
|
1482
569
|
|
|
1483
|
-
//
|
|
1484
|
-
//
|
|
1485
|
-
//
|
|
1486
|
-
//
|
|
1487
|
-
// -
|
|
1488
|
-
//
|
|
1489
|
-
//
|
|
1490
|
-
// -
|
|
1491
|
-
//
|
|
1492
|
-
//
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
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
|
-
}
|
|
570
|
+
// ==================== Device pairing security (issue #23) ====================
|
|
571
|
+
// The five POST endpoints are EXEMPT from the device-auth middleware and
|
|
572
|
+
// enforce their own stricter origin rules inside controller/security.ts:
|
|
573
|
+
// enable - loopback only (mints the FIRST device; remote = attacker)
|
|
574
|
+
// pair/start- authenticated device or loopback (mints a fresh code,
|
|
575
|
+
// invalidating the previous one)
|
|
576
|
+
// pair - one-shot 60s code exchange -> {token, deviceId}
|
|
577
|
+
// pair-auto - LAN peer + config.security.autoPair + protection on
|
|
578
|
+
// reset - authenticated device or loopback (anti-lockout hatch)
|
|
579
|
+
// GET /security and DELETE /security/devices/:id are NOT exempt: the
|
|
580
|
+
// middleware itself guarantees the caller holds a valid device token.
|
|
581
|
+
{ method: "POST", path: "/api/v1/security/enable", handler: handleSecurityEnableRequest },
|
|
582
|
+
{ method: "POST", path: "/api/v1/security/pair/start", handler: handleSecurityPairStartRequest },
|
|
583
|
+
{ method: "POST", path: "/api/v1/security/pair", handler: handleSecurityPairRequest },
|
|
584
|
+
{ method: "POST", path: "/api/v1/security/pair-auto", handler: handleSecurityPairAutoRequest },
|
|
585
|
+
{ method: "GET", path: "/api/v1/security", handler: handleSecurityGetRequest },
|
|
586
|
+
{ method: "DELETE", path: /^\/api\/v1\/security\/devices\/[^/]+$/, handler: handleSecurityDeviceDeleteRequest },
|
|
587
|
+
{ method: "POST", path: "/api/v1/security/reset", handler: handleSecurityResetRequest },
|
|
588
|
+
|
|
589
|
+
// ==================== Workflow templates (design 2.4) ====================
|
|
590
|
+
// Appended after the historical table + security suffix (no path overlap
|
|
591
|
+
// with any earlier route, so the append cannot reorder historical
|
|
592
|
+
// matching - same append-only precedent as the security entries above).
|
|
593
|
+
// POST /api/v1/workflows/{id}/start - kick off a declarative workflow run
|
|
594
|
+
// of the active profile (banking: credit-approval); body may carry
|
|
595
|
+
// { context } (initial business context). The handler enforces the
|
|
596
|
+
// transition-matrix 503 itself (see workflow-routes.ts).
|
|
597
|
+
{ method: "POST", path: /^\/api\/v1\/workflows\/[^/]+\/start$/, handler: workflowStartRoute },
|
|
598
|
+
// Hot worker-provisioning config (#hot-config): GET snapshot + PATCH
|
|
599
|
+
// hot-apply. Appended at the table tail on the same append-only precedent
|
|
600
|
+
// (no path overlap with any earlier route).
|
|
601
|
+
{ method: "GET", path: "/api/v1/team/config", handler: teamConfigGetRoute },
|
|
602
|
+
{ method: "PATCH", path: "/api/v1/team/config", handler: teamConfigPatchRoute },
|
|
603
|
+
];
|