@teamclaws/teamclaw 2026.11.0 → 2026.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.mjs +272 -2
- package/dist/index.js +54 -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/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 +67 -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/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/types.js +15 -1
- package/dist/src/ui/app.js +846 -62
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +102 -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 +61 -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/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 +133 -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 +19 -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/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/scheduler.ts +2 -1
- package/src/types.ts +130 -1
- package/src/ui/app.js +846 -62
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +102 -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,31 +1,30 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { importControllerGitBundle } from "../git-collaboration.js";
|
|
8
|
-
import { startTeamProfileSwitch } from "./profile-switch.js";
|
|
9
|
-
import { serveStaticFile, serveVersionedHtml } from "./ui-assets.js";
|
|
1
|
+
import { webUiRootRoute, webUiIndexRoute, webUiGithubLoginPageRoute, webUiAssetsRoute, } from "./webui-routes.js";
|
|
2
|
+
import { githubAuthStatusRoute, githubAuthLoginRoute, githubAuthCallbackRoute, githubAuthLogoutRoute, githubAuthRefreshRoute, } from "./auth-routes.js";
|
|
3
|
+
import { workspaceStatusRoute, workspaceChangeDirRoute, modelsConfigGetRoute, modelsConfigPutRoute, workspaceTreeRoute, workspaceSubtreeRoute, workspaceFileRoute, workspaceProjectPathRoute, workspaceRawFileRoute, } from "./workspace-routes.js";
|
|
4
|
+
import { controllerManifestRoute, controllerRunsListRoute, projectDeleteRoute, controllerRunDeleteRoute, controllerIntakeRoute, } from "./controller-routes.js";
|
|
5
|
+
import { teamStatsRoute, teamStatusRoute, teamRolesRoute, teamProfilesListRoute, teamProfileGetRoute, teamProfileSwitchRoute, archivedTeamsRoute, } from "./status-routes.js";
|
|
6
|
+
import { reportsListRoute, reportsSessionRoute, healthRoute, } from "./report-routes.js";
|
|
10
7
|
import { handleTeamAutoActivityRequest, handleTeamAutoReposListRequest, handleTeamAutoRepoCandidatesRequest, handleTeamAutoRepoBindRequest, handleTeamAutoRepoItemRequest, } from "./teamauto-routes.js";
|
|
11
|
-
import { handleRepoStatusRequest, handleRepoBundleRequest, } from "./repo-routes.js";
|
|
8
|
+
import { handleRepoStatusRequest, handleRepoBundleRequest, repoImportRoute, } from "./repo-routes.js";
|
|
12
9
|
import { handlePreviewProxyRequest } from "./preview-proxy.js";
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
import {
|
|
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";
|
|
10
|
+
// Issue #226 W2: the tunnel-side tables (gate page + management API, with
|
|
11
|
+
// their inline handler bodies, the gate-page HTML rendering and the tunnel
|
|
12
|
+
// form reader) live in ./tunnel-routes.ts; both factories are re-exported
|
|
13
|
+
// below so http-server.ts's imports are unchanged.
|
|
14
|
+
export { createTunnelGateRoutes, createTunnelManagementRoutes } from "./tunnel-routes.js";
|
|
15
|
+
import { handleWorkerDeleteRequest, handleWorkerHeartbeatRequest, handleWorkerListRequest, handleWorkerRegisterRequest, } from "./worker-routes.js";
|
|
26
16
|
import { handleTaskAssignRequest, handleTaskCheckpointRequest, handleTaskCreateRequest, handleTaskDeleteRequest, handleTaskExecutionEventRequest, handleTaskExecutionGetRequest, handleTaskGetRequest, handleTaskHandoffRequest, handleTaskListRequest, handleTaskParallelHelpRequest, handleTaskPatchRequest, handleTaskResultContractRequest, handleTaskResultRequest, } from "./task-routes.js";
|
|
27
17
|
import { handleBroadcastMessageRequest, handleDirectMessageRequest, handleMessageListRequest, handleReviewRequestMessageRequest, } from "./message-routes.js";
|
|
28
18
|
import { handleClarificationAnswerRequest, handleClarificationCreateRequest, handleClarificationListRequest, } from "./clarification-routes.js";
|
|
19
|
+
// Issue #23 (backend wave): device-pairing security domain module. It owns
|
|
20
|
+
// the token/pairing primitives, the auth middleware (wired by
|
|
21
|
+
// http-server.ts), the WS upgrade guard and the handlers registered in the
|
|
22
|
+
// security section of the table below. It imports this file as TYPE ONLY
|
|
23
|
+
// (RouteContext), so the module graph stays acyclic.
|
|
24
|
+
import { handleSecurityDeviceDeleteRequest, handleSecurityEnableRequest, handleSecurityGetRequest, handleSecurityPairAutoRequest, handleSecurityPairRequest, handleSecurityPairStartRequest, handleSecurityResetRequest, } from "./security.js";
|
|
25
|
+
// Design 2.4 workflows backend: POST /api/v1/workflows/{id}/start handler
|
|
26
|
+
// (engine + route live in ./workflow-routes.ts).
|
|
27
|
+
import { workflowStartRoute } from "./workflow-routes.js";
|
|
29
28
|
function routeMethodMatches(routeMethod, method) {
|
|
30
29
|
if (routeMethod === "*") {
|
|
31
30
|
return true;
|
|
@@ -61,181 +60,27 @@ export async function dispatchRoutes(routes, ctx) {
|
|
|
61
60
|
return false;
|
|
62
61
|
}
|
|
63
62
|
// ===========================================================================
|
|
64
|
-
// Shared helpers
|
|
65
|
-
//
|
|
63
|
+
// Shared helpers. W2 of issue #226: the helpers whose consumers moved out
|
|
64
|
+
// (shell escaping, LAN-URL building, the GitHub callback HTML renderer,
|
|
65
|
+
// workspace error mapping, team stats, the tunnel form reader) moved with
|
|
66
|
+
// them; nothing inline remains in this module.
|
|
66
67
|
// ===========================================================================
|
|
67
68
|
/**
|
|
68
69
|
* Retry hint shared by the transition-matrix gate (http-server.ts, task
|
|
69
|
-
* submission / repo import) and the intake handler
|
|
70
|
-
*
|
|
71
|
-
*
|
|
70
|
+
* submission / repo import) and the intake handler. Declared in
|
|
71
|
+
* ./controller-routes.ts since W2 (it moved with the intake handler body);
|
|
72
|
+
* re-exported here so http-server.ts's gate import is unchanged.
|
|
72
73
|
*/
|
|
73
|
-
export
|
|
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
|
-
}
|
|
74
|
+
export { SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS } from "./controller-routes.js";
|
|
192
75
|
// ===========================================================================
|
|
193
76
|
// Route handlers. The PR-A/B/C domain handlers are forwarded to unchanged;
|
|
194
|
-
//
|
|
195
|
-
//
|
|
196
|
-
// the
|
|
77
|
+
// every handler body that was still inline here moved verbatim into its
|
|
78
|
+
// domain module with W2 of issue #226 (see the import block): route-table
|
|
79
|
+
// binds the exported handlers directly, exactly like the issue-#23 security
|
|
80
|
+
// handlers. Only the thin forwarder shells for the PR-A/B/C domain modules
|
|
81
|
+
// (whose handlers predate RouteContext) and the preview-proxy fire-and-
|
|
82
|
+
// forget shell remain below.
|
|
197
83
|
// ===========================================================================
|
|
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
84
|
// ---- TeamAuto (pre-PR-D lines 631-654; handlers in ./teamauto-routes.ts) ----
|
|
240
85
|
async function teamAutoActivityRoute(ctx) {
|
|
241
86
|
await handleTeamAutoActivityRequest(ctx.deps, ctx.res);
|
|
@@ -256,276 +101,6 @@ async function teamAutoRepoBindRoute(ctx) {
|
|
|
256
101
|
function teamAutoRepoItemRoute(ctx) {
|
|
257
102
|
return handleTeamAutoRepoItemRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
|
|
258
103
|
}
|
|
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
104
|
// ---- Worker Management (pre-PR-D lines 939-960; handlers in ./worker-routes.ts) ----
|
|
530
105
|
async function workerRegisterRoute(ctx) {
|
|
531
106
|
await handleWorkerRegisterRequest(ctx.deps, ctx.req, ctx.res);
|
|
@@ -546,21 +121,6 @@ async function taskCreateRoute(ctx) {
|
|
|
546
121
|
async function taskListRoute(ctx) {
|
|
547
122
|
await handleTaskListRequest(ctx.deps, ctx.res);
|
|
548
123
|
}
|
|
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
124
|
async function taskGetRoute(ctx) {
|
|
565
125
|
await handleTaskGetRequest(ctx.deps, ctx.res, ctx.pathname);
|
|
566
126
|
}
|
|
@@ -596,175 +156,6 @@ async function taskExecutionEventRoute(ctx) {
|
|
|
596
156
|
async function taskParallelHelpRoute(ctx) {
|
|
597
157
|
await handleTaskParallelHelpRequest(ctx.deps, ctx.req, ctx.res, ctx.pathname);
|
|
598
158
|
}
|
|
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
159
|
// ---- Message Routing (pre-PR-D lines 1292-1313; handlers in ./message-routes.ts) ----
|
|
769
160
|
async function messageDirectRoute(ctx) {
|
|
770
161
|
await handleDirectMessageRequest(ctx.deps, ctx.req, ctx.res);
|
|
@@ -791,274 +182,24 @@ async function clarificationAnswerRoute(ctx) {
|
|
|
791
182
|
// ---- Git Collaboration (pre-PR-D lines 1342-1412) ----
|
|
792
183
|
// PR-B of issue #204: the repo status/bundle handlers and the shared
|
|
793
184
|
// refreshControllerRepoState glue live in ./repo-routes.ts; the POST
|
|
794
|
-
// /repo/import handler body
|
|
185
|
+
// /repo/import handler body joined them with W2 of issue #226 (its
|
|
795
186
|
// recordTaskExecutionEvent dependency is task-lifecycle glue owned by the
|
|
796
|
-
// PR-C cut).
|
|
187
|
+
// PR-C cut - acyclic, see the repo-routes.ts header).
|
|
797
188
|
async function repoStatusRoute(ctx) {
|
|
798
189
|
await handleRepoStatusRequest(ctx.deps, ctx.res);
|
|
799
190
|
}
|
|
800
191
|
async function repoBundleRoute(ctx) {
|
|
801
192
|
await handleRepoBundleRequest(ctx.deps, ctx.res);
|
|
802
193
|
}
|
|
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
194
|
// ---- Previews / reports / health (pre-PR-D lines 1580-1633) ----
|
|
195
|
+
// W2 of issue #226: the reports list/session and health handler bodies live
|
|
196
|
+
// in ./report-routes.ts; only the fire-and-forget preview-proxy shell stays.
|
|
1012
197
|
// /api/v1/previews/:id/* — proxy to preview subprocess.
|
|
1013
198
|
// PR-B of issue #204: the proxy implementation lives in ./preview-proxy.ts.
|
|
1014
199
|
// Deliberately NOT awaited (fire-and-forget proxy), exactly as before.
|
|
1015
200
|
function previewsProxyRoute(ctx) {
|
|
1016
201
|
handlePreviewProxyRequest(ctx.deps, ctx.req, ctx.res, ctx.requestUrl, ctx.pathname);
|
|
1017
202
|
}
|
|
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
203
|
// ===========================================================================
|
|
1063
204
|
// The controller route table. ORDER IS LOAD-BEARING: it mirrors the pre-PR-D
|
|
1064
205
|
// if/startsWith chain of http-server.ts one-to-one (the "old lines" in the
|
|
@@ -1204,150 +345,31 @@ export const controllerRouteTable = [
|
|
|
1204
345
|
{ method: "GET", path: "/api/v1/reports/", prefix: true, handler: reportsSessionRoute },
|
|
1205
346
|
// GET /api/v1/health
|
|
1206
347
|
{ method: "GET", path: "/api/v1/health", handler: healthRoute },
|
|
348
|
+
// ==================== Device pairing security (issue #23) ====================
|
|
349
|
+
// The five POST endpoints are EXEMPT from the device-auth middleware and
|
|
350
|
+
// enforce their own stricter origin rules inside controller/security.ts:
|
|
351
|
+
// enable - loopback only (mints the FIRST device; remote = attacker)
|
|
352
|
+
// pair/start- authenticated device or loopback (mints a fresh code,
|
|
353
|
+
// invalidating the previous one)
|
|
354
|
+
// pair - one-shot 60s code exchange -> {token, deviceId}
|
|
355
|
+
// pair-auto - LAN peer + config.security.autoPair + protection on
|
|
356
|
+
// reset - authenticated device or loopback (anti-lockout hatch)
|
|
357
|
+
// GET /security and DELETE /security/devices/:id are NOT exempt: the
|
|
358
|
+
// middleware itself guarantees the caller holds a valid device token.
|
|
359
|
+
{ method: "POST", path: "/api/v1/security/enable", handler: handleSecurityEnableRequest },
|
|
360
|
+
{ method: "POST", path: "/api/v1/security/pair/start", handler: handleSecurityPairStartRequest },
|
|
361
|
+
{ method: "POST", path: "/api/v1/security/pair", handler: handleSecurityPairRequest },
|
|
362
|
+
{ method: "POST", path: "/api/v1/security/pair-auto", handler: handleSecurityPairAutoRequest },
|
|
363
|
+
{ method: "GET", path: "/api/v1/security", handler: handleSecurityGetRequest },
|
|
364
|
+
{ method: "DELETE", path: /^\/api\/v1\/security\/devices\/[^/]+$/, handler: handleSecurityDeviceDeleteRequest },
|
|
365
|
+
{ method: "POST", path: "/api/v1/security/reset", handler: handleSecurityResetRequest },
|
|
366
|
+
// ==================== Workflow templates (design 2.4) ====================
|
|
367
|
+
// Appended after the historical table + security suffix (no path overlap
|
|
368
|
+
// with any earlier route, so the append cannot reorder historical
|
|
369
|
+
// matching - same append-only precedent as the security entries above).
|
|
370
|
+
// POST /api/v1/workflows/{id}/start - kick off a declarative workflow run
|
|
371
|
+
// of the active profile (banking: credit-approval); body may carry
|
|
372
|
+
// { context } (initial business context). The handler enforces the
|
|
373
|
+
// transition-matrix 503 itself (see workflow-routes.ts).
|
|
374
|
+
{ method: "POST", path: /^\/api\/v1\/workflows\/[^/]+\/start$/, handler: workflowStartRoute },
|
|
1207
375
|
];
|
|
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
|
-
}
|