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