@teamclaws/teamclaw 2026.8.1 → 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 +318 -17
- package/dist/index.js +54 -32
- package/dist/src/config.js +57 -2
- package/dist/src/controller/auth-routes.js +129 -0
- package/dist/src/controller/clarification-routes.js +315 -0
- package/dist/src/controller/controller-intake.js +895 -0
- package/dist/src/controller/controller-planning.js +814 -0
- package/dist/src/controller/controller-routes.js +195 -0
- package/dist/src/controller/controller-runs.js +175 -0
- package/dist/src/controller/controller-service.js +338 -50
- package/dist/src/controller/controller-tools.js +14 -7
- package/dist/src/controller/github-auth.js +2 -1
- package/dist/src/controller/http-server.js +290 -6003
- package/dist/src/controller/kickoff-orchestrator.js +33 -43
- package/dist/src/controller/message-delivery.js +31 -0
- package/dist/src/controller/message-routes.js +114 -0
- package/dist/src/controller/orchestration-manifest.js +11 -93
- package/dist/src/controller/preview-manager.js +51 -3
- package/dist/src/controller/preview-proxy.js +98 -0
- package/dist/src/controller/profile-switch.js +309 -0
- package/dist/src/controller/project-registry.js +294 -0
- package/dist/src/controller/prompt-injector.js +19 -9
- 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 +129 -0
- package/dist/src/controller/report-routes.js +56 -0
- package/dist/src/controller/role-inference.js +231 -20
- package/dist/src/controller/route-table.js +375 -0
- package/dist/src/controller/security.js +775 -0
- package/dist/src/controller/status-routes.js +287 -0
- package/dist/src/controller/task-assignment.js +511 -0
- package/dist/src/controller/task-cleanup.js +258 -0
- package/dist/src/controller/task-execution.js +271 -0
- package/dist/src/controller/task-results.js +471 -0
- package/dist/src/controller/task-router.js +74 -4
- 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 +41 -8
- package/dist/src/controller/tunnel-routes.js +225 -0
- package/dist/src/controller/ui-assets.js +68 -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 +69 -953
- package/dist/src/controller/worker-routes.js +188 -0
- 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 +15 -3
- package/dist/src/interaction-contracts.js +7 -7
- package/dist/src/openclaw-workspace.js +40 -18
- package/dist/src/profile-loader.js +604 -0
- package/dist/src/profiles/banking.json +202 -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 +281 -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 +42 -17
- package/dist/src/protocol.js +66 -3
- package/dist/src/role-ids.js +29 -0
- package/dist/src/roles.js +54 -13
- package/dist/src/session-roles.js +14 -0
- 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 +275 -11
- package/dist/src/task-executor.js +7 -17
- package/dist/src/teamauto/github-client.js +18 -0
- package/dist/src/teamauto/repo-sync.js +228 -6
- package/dist/src/teamauto/scanner.js +40 -12
- package/dist/src/teamauto/scheduler.js +231 -12
- package/dist/src/types.js +77 -16
- package/dist/src/ui/app.js +1434 -82
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +144 -45
- package/dist/src/ui/style.css +194 -0
- package/dist/src/worker/http-handler.js +59 -0
- package/dist/src/worker/prompt-injector.js +44 -8
- package/dist/src/worker/skill-installer.js +6 -10
- package/dist/src/worker/tools.js +20 -10
- package/dist/src/worker/worker-service.js +93 -7
- package/index.ts +61 -32
- package/openclaw.plugin.json +50 -2
- package/package.json +3 -2
- package/src/config.ts +57 -2
- package/src/controller/auth-routes.ts +157 -0
- package/src/controller/clarification-routes.ts +404 -0
- package/src/controller/controller-intake.ts +1113 -0
- package/src/controller/controller-planning.ts +1037 -0
- package/src/controller/controller-routes.ts +237 -0
- package/src/controller/controller-runs.ts +239 -0
- package/src/controller/controller-service.ts +422 -50
- package/src/controller/controller-tools.ts +16 -9
- package/src/controller/github-auth.ts +28 -63
- package/src/controller/http-server.ts +336 -6964
- package/src/controller/kickoff-orchestrator.ts +69 -45
- package/src/controller/message-delivery.ts +52 -0
- package/src/controller/message-routes.ts +137 -0
- package/src/controller/orchestration-manifest.ts +14 -100
- package/src/controller/preview-manager.ts +53 -3
- package/src/controller/preview-proxy.ts +127 -0
- package/src/controller/profile-switch.ts +396 -0
- package/src/controller/project-registry.ts +361 -0
- package/src/controller/prompt-injector.ts +23 -8
- 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 +163 -0
- package/src/controller/report-routes.ts +64 -0
- package/src/controller/role-inference.ts +260 -22
- package/src/controller/route-table.ts +597 -0
- package/src/controller/security.ts +899 -0
- package/src/controller/status-routes.ts +354 -0
- package/src/controller/task-assignment.ts +622 -0
- package/src/controller/task-cleanup.ts +344 -0
- package/src/controller/task-execution.ts +399 -0
- package/src/controller/task-results.ts +556 -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/tunnel-manager.ts +45 -8
- package/src/controller/tunnel-routes.ts +231 -0
- package/src/controller/ui-assets.ts +70 -0
- package/src/controller/websocket.ts +32 -4
- package/src/controller/webui-routes.ts +55 -0
- package/src/controller/worker-provisioning.ts +83 -1121
- package/src/controller/worker-routes.ts +241 -0
- 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 +16 -3
- package/src/interaction-contracts.ts +7 -7
- package/src/openclaw-workspace.ts +44 -18
- package/src/profile-loader.ts +816 -0
- package/src/profiles/banking.json +202 -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 +281 -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 +44 -17
- package/src/protocol.ts +72 -2
- package/src/role-ids.ts +31 -0
- package/src/roles.ts +60 -14
- package/src/session-roles.ts +14 -0
- 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 +326 -10
- package/src/task-executor.ts +7 -18
- package/src/teamauto/github-client.ts +23 -1
- package/src/teamauto/repo-sync.ts +248 -7
- package/src/teamauto/scanner.ts +47 -13
- package/src/teamauto/scheduler.ts +261 -17
- package/src/teamauto/store.ts +12 -0
- package/src/types.ts +263 -17
- package/src/ui/app.js +1434 -82
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +144 -45
- package/src/ui/style.css +194 -0
- package/src/worker/http-handler.ts +64 -1
- package/src/worker/prompt-injector.ts +48 -8
- package/src/worker/skill-installer.ts +6 -10
- package/src/worker/tools.ts +21 -10
- package/src/worker/worker-service.ts +101 -7
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// PR-B of issue #204 (http-server monolith split): the preview subprocess
|
|
2
|
+
// proxy for /api/v1/previews/:id/* extracted verbatim from
|
|
3
|
+
// controller/http-server.ts. Zero behavior change - the route shell in
|
|
4
|
+
// http-server keeps the method whitelist + prefix match and calls this
|
|
5
|
+
// handler with the same request/response objects as before. This module must
|
|
6
|
+
// NEVER import http-server (the reverse edge exists:
|
|
7
|
+
// http-server -> preview-proxy); preview state arrives through the deps
|
|
8
|
+
// slice below.
|
|
9
|
+
import http from "node:http";
|
|
10
|
+
import zlib from "node:zlib";
|
|
11
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
12
|
+
import type { PluginLogger } from "../../api.js";
|
|
13
|
+
import type { TeamState } from "../types.js";
|
|
14
|
+
import { sendJson } from "../protocol.js";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
|
|
18
|
+
* the fields the preview proxy reads. http-server keeps passing its full
|
|
19
|
+
* ControllerHttpDeps object; TypeScript structural typing accepts it, so no
|
|
20
|
+
* call site changes beyond the import path.
|
|
21
|
+
*/
|
|
22
|
+
export type PreviewProxyDeps = {
|
|
23
|
+
logger: PluginLogger;
|
|
24
|
+
getTeamState: () => TeamState | null;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* /api/v1/previews/:id/* - proxy to the preview subprocess. `pathname` starts
|
|
29
|
+
* with "/api/v1/previews/"; `requestUrl` is the parsed request URL (query
|
|
30
|
+
* string is forwarded to the subprocess).
|
|
31
|
+
*/
|
|
32
|
+
export function handlePreviewProxyRequest(
|
|
33
|
+
deps: PreviewProxyDeps,
|
|
34
|
+
req: IncomingMessage,
|
|
35
|
+
res: ServerResponse,
|
|
36
|
+
requestUrl: URL,
|
|
37
|
+
pathname: string,
|
|
38
|
+
): void {
|
|
39
|
+
const previewPrefix = "/api/v1/previews/";
|
|
40
|
+
const remaining = pathname.slice(previewPrefix.length);
|
|
41
|
+
const slashIdx = remaining.indexOf("/");
|
|
42
|
+
const previewId = slashIdx >= 0 ? remaining.slice(0, slashIdx) : remaining;
|
|
43
|
+
const subPath = slashIdx >= 0 ? remaining.slice(slashIdx) : "/";
|
|
44
|
+
|
|
45
|
+
const state = deps.getTeamState();
|
|
46
|
+
const preview = state?.previews?.[previewId];
|
|
47
|
+
if (!preview || preview.status !== "healthy") {
|
|
48
|
+
const status = preview?.status ?? "unknown";
|
|
49
|
+
const errMsg = preview?.lastError;
|
|
50
|
+
sendJson(res, 503, { error: "Preview not available", previewId, status, lastError: errMsg ?? undefined });
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const proxyPathPrefix = `/api/v1/previews/${encodeURIComponent(previewId)}`;
|
|
55
|
+
const proxyReq = http.request(
|
|
56
|
+
{
|
|
57
|
+
hostname: "127.0.0.1",
|
|
58
|
+
port: preview.targetPort,
|
|
59
|
+
path: subPath + (requestUrl.search || ""),
|
|
60
|
+
method: req.method,
|
|
61
|
+
headers: {
|
|
62
|
+
...req.headers,
|
|
63
|
+
host: `127.0.0.1:${preview.targetPort}`,
|
|
64
|
+
"accept-encoding": "identity",
|
|
65
|
+
"x-forwarded-for": req.socket.remoteAddress ?? "",
|
|
66
|
+
"x-forwarded-host": req.headers.host ?? "",
|
|
67
|
+
"x-forwarded-proto": "http",
|
|
68
|
+
},
|
|
69
|
+
},
|
|
70
|
+
(proxyRes: http.IncomingMessage) => {
|
|
71
|
+
const contentType = (proxyRes.headers["content-type"] ?? "").toLowerCase();
|
|
72
|
+
if (proxyRes.statusCode !== 200 && proxyRes.statusCode !== 201 && proxyRes.statusCode !== 301 && proxyRes.statusCode !== 302 && proxyRes.statusCode !== 304) {
|
|
73
|
+
res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
|
|
74
|
+
proxyRes.pipe(res);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (contentType.includes("text/html")) {
|
|
79
|
+
const chunks: Buffer[] = [];
|
|
80
|
+
proxyRes.on("data", (chunk: Buffer) => chunks.push(chunk));
|
|
81
|
+
proxyRes.on("end", () => {
|
|
82
|
+
let raw = Buffer.concat(chunks);
|
|
83
|
+
// Decompress if the upstream response is compressed (brotli/gzip/deflate).
|
|
84
|
+
const encoding = (proxyRes.headers["content-encoding"] ?? "").toLowerCase();
|
|
85
|
+
try {
|
|
86
|
+
if (encoding === "br") {
|
|
87
|
+
raw = zlib.brotliDecompressSync(raw);
|
|
88
|
+
} else if (encoding === "gzip") {
|
|
89
|
+
raw = zlib.gunzipSync(raw);
|
|
90
|
+
} else if (encoding === "deflate") {
|
|
91
|
+
raw = zlib.inflateSync(raw);
|
|
92
|
+
}
|
|
93
|
+
} catch {
|
|
94
|
+
// If decompression fails, use raw bytes as-is.
|
|
95
|
+
}
|
|
96
|
+
const body = raw.toString("utf-8");
|
|
97
|
+
// Rewrite absolute-path references (href="/...", src="/...", action="/...")
|
|
98
|
+
// to include the proxy prefix so all navigation stays within the proxy.
|
|
99
|
+
const rewritten = body.replace(
|
|
100
|
+
/\b(href|src|action)\s*=\s*"\/([^"]*)"/g,
|
|
101
|
+
`$1="${proxyPathPrefix}/$2"`,
|
|
102
|
+
).replace(
|
|
103
|
+
/\b(href|src|action)\s*=\s*'\/([^']*)'/g,
|
|
104
|
+
`$1='${proxyPathPrefix}/$2'`,
|
|
105
|
+
);
|
|
106
|
+
const resHeaders = { ...proxyRes.headers };
|
|
107
|
+
// We've decoded and rewritten the body — remove upstream encoding headers.
|
|
108
|
+
delete resHeaders["content-encoding"];
|
|
109
|
+
delete resHeaders["transfer-encoding"];
|
|
110
|
+
resHeaders["content-length"] = String(Buffer.byteLength(rewritten, "utf-8"));
|
|
111
|
+
res.writeHead(proxyRes.statusCode ?? 200, resHeaders);
|
|
112
|
+
res.end(rewritten);
|
|
113
|
+
});
|
|
114
|
+
} else {
|
|
115
|
+
res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
|
|
116
|
+
proxyRes.pipe(res);
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
);
|
|
120
|
+
proxyReq.on("error", (err: Error) => {
|
|
121
|
+
deps.logger.warn(`Controller: preview proxy error for ${previewId}: ${String(err)}`);
|
|
122
|
+
if (!res.headersSent) {
|
|
123
|
+
sendJson(res, 502, { error: "Preview proxy error", previewId, message: String(err) });
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
req.pipe(proxyReq);
|
|
127
|
+
}
|
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
// PR-A of issue #204 (http-server monolith split): the team profile switch
|
|
2
|
+
// state machine extracted verbatim from controller/http-server.ts. Zero
|
|
3
|
+
// behavior change - the POST /api/v1/team/profile route shell and the
|
|
4
|
+
// controller startup chain (controller-service.ts) call these functions with
|
|
5
|
+
// the same deps object as before. This module must NEVER import http-server
|
|
6
|
+
// (the reverse edge exists: http-server -> profile-switch); ws broadcasts,
|
|
7
|
+
// state persistence and provisioning all arrive through the deps slice below.
|
|
8
|
+
// Issue #226 W4: persistence rides the single write entry (deps.
|
|
9
|
+
// updateTeamState) - including the awaited durability barriers this state
|
|
10
|
+
// machine needs - instead of independent saveTeamState calls; the update
|
|
11
|
+
// contract types are type-only imports from controller-service.js (the
|
|
12
|
+
// runtime edge points the other way, so the module graph stays acyclic).
|
|
13
|
+
import type { PluginLogger } from "../../api.js";
|
|
14
|
+
import type {
|
|
15
|
+
PluginConfig,
|
|
16
|
+
TaskInfo,
|
|
17
|
+
TeamState,
|
|
18
|
+
} from "../types.js";
|
|
19
|
+
import type {
|
|
20
|
+
TeamStateUpdateHandle,
|
|
21
|
+
TeamStateUpdateOptions,
|
|
22
|
+
UpdateTeamStateFn,
|
|
23
|
+
} from "./controller-service.js";
|
|
24
|
+
import { archiveTeamState, findTeamSwitchArchive } from "../state.js";
|
|
25
|
+
import {
|
|
26
|
+
BUILTIN_PROFILES,
|
|
27
|
+
getActiveProfile,
|
|
28
|
+
hasProfile,
|
|
29
|
+
setActiveProfileId,
|
|
30
|
+
} from "../profile-loader.js";
|
|
31
|
+
import { ensureControllerGitRepo } from "../git-collaboration.js";
|
|
32
|
+
import type { TeamWebSocketServer } from "./websocket.js";
|
|
33
|
+
import type { WorkerProvisioningManager } from "./worker-provisioning.js";
|
|
34
|
+
import type { PreviewManager } from "./preview-manager.js";
|
|
35
|
+
import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
|
|
39
|
+
* the fields the switch machine reads. http-server and controller-service
|
|
40
|
+
* keep passing their full ControllerHttpDeps object; TypeScript structural
|
|
41
|
+
* typing accepts it, so no call site changes beyond the import path.
|
|
42
|
+
*/
|
|
43
|
+
export type TeamProfileSwitchDeps = {
|
|
44
|
+
config: PluginConfig;
|
|
45
|
+
logger: PluginLogger;
|
|
46
|
+
getTeamState: () => TeamState | null;
|
|
47
|
+
updateTeamState: UpdateTeamStateFn;
|
|
48
|
+
wsServer: TeamWebSocketServer;
|
|
49
|
+
workerProvisioningManager?: WorkerProvisioningManager | null;
|
|
50
|
+
previewManager?: PreviewManager;
|
|
51
|
+
/** Late-bound TeamAuto scheduler (autonomous repo collaboration). */
|
|
52
|
+
getTeamAutoScheduler?: () => TeamAutoScheduler | null;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// ===========================================================================
|
|
56
|
+
// Team profile switch (Phase 2.1, vertical-team-profiles-design.md 2.3).
|
|
57
|
+
//
|
|
58
|
+
// Six-step semantics of POST /api/v1/team/profile:
|
|
59
|
+
// 0. validate profileId + reject concurrent switches (409) [endpoint]
|
|
60
|
+
// 1. transition = { draining, target, startedAt }; persisted + WS event
|
|
61
|
+
// 2. graceful drain of in-flight tasks (timeout -> force-collect),
|
|
62
|
+
// terminate workers [drainTeam...]
|
|
63
|
+
// 3. archive the WHOLE TeamState + roles snapshot [state.ts]
|
|
64
|
+
// 4. fresh capability-conditioned TeamState for the target
|
|
65
|
+
// 5. warm the target profile's warmupRoles [provisioner]
|
|
66
|
+
// 6. clear transition, persist, broadcast team.switch_completed
|
|
67
|
+
// ===========================================================================
|
|
68
|
+
|
|
69
|
+
const SWITCH_DRAIN_POLL_INTERVAL_MS = 500;
|
|
70
|
+
|
|
71
|
+
function sleepForSwitchDrain(ms: number): Promise<void> {
|
|
72
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function taskInFlightForDrain(task: TaskInfo): boolean {
|
|
76
|
+
return Boolean(task.assignedWorkerId) && (task.status === "assigned" || task.status === "in_progress");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Design 2.3 step 2: graceful drain. Waits until no task is assigned /
|
|
81
|
+
* in-progress any more (in-flight workers report results through their
|
|
82
|
+
* normal endpoints, which stay open during the transition), then returns.
|
|
83
|
+
* On timeout the remaining in-flight tasks are force-collected (failed with
|
|
84
|
+
* an explicit error so the archive records the forced end) and all workers
|
|
85
|
+
* are marked offline. Managed workers are terminated by the caller through
|
|
86
|
+
* the provisioning manager's onWorkerRemoved (the terminateManagedWorker
|
|
87
|
+
* single point); external workers observe 409 heartbeats and back off.
|
|
88
|
+
*/
|
|
89
|
+
async function drainTeamForProfileSwitch(
|
|
90
|
+
deps: TeamProfileSwitchDeps,
|
|
91
|
+
): Promise<{ timedOut: boolean; forceCollected: string[] }> {
|
|
92
|
+
const { config, logger, getTeamState, updateTeamState } = deps;
|
|
93
|
+
const deadline = Date.now() + config.teamSwitchDrainTimeoutMs;
|
|
94
|
+
while (Date.now() < deadline) {
|
|
95
|
+
const state = getTeamState();
|
|
96
|
+
if (!state || !Object.values(state.tasks).some(taskInFlightForDrain)) {
|
|
97
|
+
return { timedOut: false, forceCollected: [] };
|
|
98
|
+
}
|
|
99
|
+
await sleepForSwitchDrain(SWITCH_DRAIN_POLL_INTERVAL_MS);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const forceCollected: string[] = [];
|
|
103
|
+
updateTeamState((state) => {
|
|
104
|
+
for (const task of Object.values(state.tasks)) {
|
|
105
|
+
if (taskInFlightForDrain(task)) {
|
|
106
|
+
task.status = "failed";
|
|
107
|
+
task.error = `team profile switch drain timeout (${config.teamSwitchDrainTimeoutMs}ms) - in-flight task force-collected into the team archive`;
|
|
108
|
+
task.updatedAt = Date.now();
|
|
109
|
+
forceCollected.push(task.id);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
for (const worker of Object.values(state.workers)) {
|
|
113
|
+
worker.status = "offline";
|
|
114
|
+
worker.currentTaskId = undefined;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
logger.warn(
|
|
118
|
+
`Controller: profile switch drain timed out after ${config.teamSwitchDrainTimeoutMs}ms - force-collected ${forceCollected.length} in-flight task(s)`,
|
|
119
|
+
);
|
|
120
|
+
return { timedOut: true, forceCollected };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export type TeamProfileSwitchOptions = {
|
|
124
|
+
/**
|
|
125
|
+
* Crash resume (design 2.3): the archive file for this switch already
|
|
126
|
+
* exists, so skip the drain+archive steps (2-3) and rebuild the new team
|
|
127
|
+
* directly (steps 4-6).
|
|
128
|
+
*/
|
|
129
|
+
skipArchive?: boolean;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Run switch steps 2-6 (step 1 - setting and persisting the transition -
|
|
134
|
+
* belongs to the POST endpoint / crash resume). Exported so the controller
|
|
135
|
+
* startup chain can resume an interrupted switch with the same semantics.
|
|
136
|
+
*/
|
|
137
|
+
export async function executeTeamProfileSwitch(
|
|
138
|
+
deps: TeamProfileSwitchDeps,
|
|
139
|
+
targetProfileId: string,
|
|
140
|
+
options: TeamProfileSwitchOptions = {},
|
|
141
|
+
): Promise<void> {
|
|
142
|
+
const { config, logger, getTeamState, updateTeamState, workerProvisioningManager } = deps;
|
|
143
|
+
const target = BUILTIN_PROFILES.get(targetProfileId);
|
|
144
|
+
if (!target) {
|
|
145
|
+
throw new Error(`TeamClaw team profile "${targetProfileId}" is not available in this installation`);
|
|
146
|
+
}
|
|
147
|
+
// W4 (#226): phase flips persist through the single write entry. The
|
|
148
|
+
// awaited-durability variant is used everywhere so callers that need the
|
|
149
|
+
// crash-window barrier (step 3's archiving flip, step 5's warming flip)
|
|
150
|
+
// can await it; callers that historically fire-and-forget the save simply
|
|
151
|
+
// drop the handle (an un-awaited rejection behaves exactly like the old
|
|
152
|
+
// floating void save).
|
|
153
|
+
const setPhase = (phase: "draining" | "archiving" | "warming", options: TeamStateUpdateOptions = {}): TeamStateUpdateHandle => {
|
|
154
|
+
return updateTeamState((state) => {
|
|
155
|
+
if (state.transition?.targetProfileId === targetProfileId) {
|
|
156
|
+
state.transition.phase = phase;
|
|
157
|
+
}
|
|
158
|
+
}, { ...options, persist: "awaited" });
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
if (!options.skipArchive) {
|
|
162
|
+
// Step 2: drain in-flight work, then stop every worker.
|
|
163
|
+
void setPhase("draining").persisted.catch(() => undefined);
|
|
164
|
+
workerProvisioningManager?.setReconcileSuspended(true);
|
|
165
|
+
const drain = await drainTeamForProfileSwitch(deps);
|
|
166
|
+
for (const workerId of Object.keys(getTeamState()?.provisioning?.workers ?? {})) {
|
|
167
|
+
if (workerProvisioningManager?.hasManagedWorker(workerId)) {
|
|
168
|
+
await workerProvisioningManager
|
|
169
|
+
.onWorkerRemoved(workerId, `team profile switch to "${targetProfileId}"`)
|
|
170
|
+
.catch((err) => logger.warn(`Controller: failed to terminate managed worker ${workerId} during profile switch: ${String(err)}`));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// Capability teardown for subsystems the target profile switches off
|
|
174
|
+
// (minimal Phase 2.3 preview; the full 404 short-circuit lands in 2.3).
|
|
175
|
+
// NOTE: teardown is one-directional at runtime. Switching a capability
|
|
176
|
+
// back ON does not (re)start its subsystem here - TeamAuto scheduling
|
|
177
|
+
// and preview restoration are wired at controller startup only, so an
|
|
178
|
+
// off -> on switch (e.g. minimal-bank -> software-rd) takes effect for
|
|
179
|
+
// those subsystems after the next gateway restart.
|
|
180
|
+
if (!target.capabilities.teamauto) {
|
|
181
|
+
const scheduler = deps.getTeamAutoScheduler?.() ?? null;
|
|
182
|
+
if (scheduler) {
|
|
183
|
+
try {
|
|
184
|
+
await scheduler.stop();
|
|
185
|
+
} catch { /* scheduler already stopped */ }
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
if (!target.capabilities.runnablePreview && deps.previewManager) {
|
|
189
|
+
try {
|
|
190
|
+
await deps.previewManager.stopAll();
|
|
191
|
+
} catch { /* previews already stopped */ }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Step 3: archive the whole previous TeamState with a roles snapshot.
|
|
195
|
+
// The phase flip is persisted BEFORE the archive write so a crash between
|
|
196
|
+
// the two leaves an unambiguous "archive may exist" state for the resume
|
|
197
|
+
// path (file existence check). W4 (#226): the awaited durability barrier
|
|
198
|
+
// is the single entry's persisted handle (one save enqueued at the same
|
|
199
|
+
// point the old fire-and-forget + awaited second save pair wrote).
|
|
200
|
+
const archiving = setPhase("archiving");
|
|
201
|
+
// #251 note (no behavior change): `sourceState` below is whatever
|
|
202
|
+
// getTeamState() returns AFTER the awaited "archiving" persist barrier
|
|
203
|
+
// - it is NOT a phase-accurate snapshot frozen at the moment the drain
|
|
204
|
+
// finished. In-flight mutations racing the switch can be captured in
|
|
205
|
+
// the archive; the resume path tolerates this because the transition
|
|
206
|
+
// marker, not the snapshot contents, drives recovery.
|
|
207
|
+
const sourceState = getTeamState();
|
|
208
|
+
if (sourceState) {
|
|
209
|
+
await archiving.persisted;
|
|
210
|
+
const sourceProfile = getActiveProfile();
|
|
211
|
+
await archiveTeamState(sourceState, {
|
|
212
|
+
id: sourceProfile.id,
|
|
213
|
+
name: sourceProfile.name,
|
|
214
|
+
nameZh: sourceProfile.nameZh,
|
|
215
|
+
version: sourceProfile.version,
|
|
216
|
+
roles: sourceProfile.roles,
|
|
217
|
+
});
|
|
218
|
+
logger.info(
|
|
219
|
+
`Controller: archived team "${sourceState.teamName}" (profile ${sourceProfile.id}, `
|
|
220
|
+
+ `${Object.keys(sourceState.tasks).length} task(s))${drain.timedOut ? " after drain timeout" : ""}`,
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Step 4: fresh TeamState for the target profile, conditioned on its
|
|
226
|
+
// capability switches (design 2.3: banking omits repo/previews/reports).
|
|
227
|
+
// setActiveProfileId and the state mutation below are both synchronous, so
|
|
228
|
+
// no request can observe the new state against the old profile.
|
|
229
|
+
const repoState = target.capabilities.git
|
|
230
|
+
? await ensureControllerGitRepo(config, logger).catch((err) => {
|
|
231
|
+
logger.warn(`Controller: failed to prepare git collaboration repo for profile "${target.id}": ${err instanceof Error ? err.message : String(err)}`);
|
|
232
|
+
return null;
|
|
233
|
+
})
|
|
234
|
+
: null;
|
|
235
|
+
setActiveProfileId(target.id);
|
|
236
|
+
const newCreatedAt = Date.now();
|
|
237
|
+
const step4 = updateTeamState((state) => {
|
|
238
|
+
state.profileId = target.id;
|
|
239
|
+
state.teamName = target.name;
|
|
240
|
+
state.workers = {};
|
|
241
|
+
state.tasks = {};
|
|
242
|
+
state.controllerRuns = {};
|
|
243
|
+
state.projects = {};
|
|
244
|
+
state.messages = [];
|
|
245
|
+
state.clarifications = {};
|
|
246
|
+
state.provisioning = { workers: {} };
|
|
247
|
+
if (target.capabilities.git && repoState) {
|
|
248
|
+
state.repo = repoState;
|
|
249
|
+
} else {
|
|
250
|
+
delete state.repo;
|
|
251
|
+
}
|
|
252
|
+
if (target.capabilities.runnablePreview) {
|
|
253
|
+
state.previews = {};
|
|
254
|
+
} else {
|
|
255
|
+
delete state.previews;
|
|
256
|
+
}
|
|
257
|
+
if (target.capabilities.deliveryReview) {
|
|
258
|
+
state.reports = {};
|
|
259
|
+
} else {
|
|
260
|
+
delete state.reports;
|
|
261
|
+
}
|
|
262
|
+
state.createdAt = newCreatedAt;
|
|
263
|
+
}, { persist: "awaited" });
|
|
264
|
+
await step4.persisted;
|
|
265
|
+
|
|
266
|
+
// Step 5: warm the new profile's warmupRoles through the provisioning
|
|
267
|
+
// pipeline (launch dispatch; registration/readiness tracking continues in
|
|
268
|
+
// the background exactly like a cold start).
|
|
269
|
+
await setPhase("warming").persisted;
|
|
270
|
+
workerProvisioningManager?.setReconcileSuspended(false);
|
|
271
|
+
if (workerProvisioningManager?.isEnabled() && target.warmupRoles.length > 0) {
|
|
272
|
+
await workerProvisioningManager
|
|
273
|
+
.warmRolesForTeamSwitch(target.warmupRoles, `profile switch warmup (${target.id})`)
|
|
274
|
+
.catch((err) => logger.warn(`Controller: profile switch warmup failed: ${err instanceof Error ? err.message : String(err)}`));
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Step 6: settle - clear the transition, persist, announce. W4 (#226):
|
|
278
|
+
// the switch_completed broadcast rides the single entry's awaited
|
|
279
|
+
// persistence, preserving the event order (persisted, then announced).
|
|
280
|
+
const settled = updateTeamState((state) => {
|
|
281
|
+
delete state.transition;
|
|
282
|
+
}, {
|
|
283
|
+
persist: "awaited",
|
|
284
|
+
broadcast: [{ type: "team.switch_completed", data: { profileId: target.id } }],
|
|
285
|
+
});
|
|
286
|
+
await settled.persisted;
|
|
287
|
+
logger.info(`Controller: team profile switch to "${target.id}" completed`);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Design 2.3 crash semantics: on controller startup, an unfinished persisted
|
|
292
|
+
* transition is resumed idempotently. If the archive file for this switch
|
|
293
|
+
* already exists AND the phase is at/after "archiving", jump straight to
|
|
294
|
+
* building the new team (skipArchive); otherwise re-run the drain from
|
|
295
|
+
* scratch (drain is idempotent - a completed drain simply finds no in-flight
|
|
296
|
+
* tasks). Returns true when a transition was resumed.
|
|
297
|
+
*/
|
|
298
|
+
// No team.switch_failed broadcast on this path: startup resume runs before
|
|
299
|
+
// the HTTP/WS listeners exist, so there are no clients to receive it - a
|
|
300
|
+
// failed resume surfaces through the fatal startup path instead (#201 review
|
|
301
|
+
// note, recorded for external reviewers).
|
|
302
|
+
export async function resumeTeamProfileSwitch(deps: TeamProfileSwitchDeps): Promise<boolean> {
|
|
303
|
+
const state = deps.getTeamState();
|
|
304
|
+
const transition = state?.transition;
|
|
305
|
+
if (!state || !transition) {
|
|
306
|
+
return false;
|
|
307
|
+
}
|
|
308
|
+
if (!hasProfile(transition.targetProfileId)) {
|
|
309
|
+
// Same red line as restoring an unknown profileId (design 2.2): a team
|
|
310
|
+
// mid-switch to an unavailable profile must never silently land on a
|
|
311
|
+
// different profile.
|
|
312
|
+
throw new Error(
|
|
313
|
+
`Controller: interrupted team profile switch references profile "${transition.targetProfileId}", which is not available in this installation. `,
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
deps.logger.info(
|
|
317
|
+
`Controller: resuming interrupted team profile switch to "${transition.targetProfileId}" (phase: ${transition.phase}, started at ${new Date(transition.startedAt).toISOString()})`,
|
|
318
|
+
);
|
|
319
|
+
// A persisted state whose profileId already equals the target means step 4
|
|
320
|
+
// flipped the team identity onto the NEW team. Step 4 strictly follows the
|
|
321
|
+
// completed archive write in the same execution (the archive file lands
|
|
322
|
+
// atomically before step 4 runs), so that flip PROVES the archive exists.
|
|
323
|
+
// This covers both phase "warming" and the ghost-archive window between
|
|
324
|
+
// the step-4 flip reaching disk and the warming phase persisting - on disk
|
|
325
|
+
// that window reads as (phase "archiving", profileId = target), where
|
|
326
|
+
// looking up the SOURCE-named archive file with state.profileId would miss
|
|
327
|
+
// it and a re-drain would seal the already-emptied NEW team as a ghost
|
|
328
|
+
// archive entry. (Alternative considered: persisting a sourceProfileId on
|
|
329
|
+
// the transition - rejected; this flip predicate is the identical proof
|
|
330
|
+
// without transition-shape or migration churn, and it also degrades the
|
|
331
|
+
// manually-corrupted (draining, target) combination the same safe way.)
|
|
332
|
+
const step4Flipped = state.profileId === transition.targetProfileId;
|
|
333
|
+
const archiveExists = step4Flipped
|
|
334
|
+
|| transition.phase === "warming"
|
|
335
|
+
|| Boolean(await findTeamSwitchArchive(state.profileId, transition.startedAt));
|
|
336
|
+
const phaseAtOrAfterArchive = transition.phase === "archiving" || transition.phase === "warming";
|
|
337
|
+
await executeTeamProfileSwitch(deps, transition.targetProfileId, {
|
|
338
|
+
skipArchive: archiveExists && (phaseAtOrAfterArchive || step4Flipped),
|
|
339
|
+
});
|
|
340
|
+
return true;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Fire-and-forget switch execution launched by POST /api/v1/team/profile
|
|
345
|
+
* after step 1 (transition persisted + switch_started broadcast). Owns the
|
|
346
|
+
* failure path: worst-case archive-preservation detection, the
|
|
347
|
+
* team.switch_failed broadcast, and unwedging the transition.
|
|
348
|
+
*/
|
|
349
|
+
export function startTeamProfileSwitch(
|
|
350
|
+
deps: TeamProfileSwitchDeps,
|
|
351
|
+
state: TeamState,
|
|
352
|
+
profileId: string,
|
|
353
|
+
previousProfileId: string,
|
|
354
|
+
): void {
|
|
355
|
+
const { logger, wsServer, updateTeamState } = deps;
|
|
356
|
+
void executeTeamProfileSwitch(deps, profileId).catch(async (err) => {
|
|
357
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
358
|
+
logger.error(`Controller: team profile switch to "${profileId}" failed: ${detail}`);
|
|
359
|
+
// Never leave the team wedged in a transition: clear it so whichever
|
|
360
|
+
// team the state now holds keeps serving and the switch can be
|
|
361
|
+
// re-issued. The archive (if step 3 ran) keeps the previous team. Also
|
|
362
|
+
// lift the provisioning reconcile suspension so the manager keeps
|
|
363
|
+
// operating for whichever team survived.
|
|
364
|
+
deps.workerProvisioningManager?.setReconcileSuspended(false);
|
|
365
|
+
// Honest worst case for the failure payload: once the step-3 archive
|
|
366
|
+
// write has landed (or step 4 already flipped the team identity - which
|
|
367
|
+
// strictly proves the archive landed), the state on disk may be
|
|
368
|
+
// partially switched and a restart is the reliable recovery. Detect
|
|
369
|
+
// with the same resume-path predicate: a source-named archive file at
|
|
370
|
+
// or after the transition's startedAt.
|
|
371
|
+
const transition = state.transition;
|
|
372
|
+
let archivePreserved = state.profileId === profileId;
|
|
373
|
+
if (!archivePreserved && transition) {
|
|
374
|
+
archivePreserved = Boolean(await findTeamSwitchArchive(previousProfileId, transition.startedAt).catch(() => null));
|
|
375
|
+
}
|
|
376
|
+
const reason = archivePreserved
|
|
377
|
+
? `${detail} (archive preserved, team state may be partially switched, restart recommended)`
|
|
378
|
+
: detail;
|
|
379
|
+
// Broadcast BEFORE clearing the transition: the web switcher releases
|
|
380
|
+
// its loading/confirm state on this event instead of silently timing
|
|
381
|
+
// out on the reconcile fallback.
|
|
382
|
+
wsServer.broadcastUpdate({
|
|
383
|
+
type: "team.switch_failed",
|
|
384
|
+
data: { previousProfileId, targetProfileId: profileId, reason },
|
|
385
|
+
});
|
|
386
|
+
// W4 (#226): best-effort persist of the unwedging through the single
|
|
387
|
+
// entry - one enqueued save with the failure path's swallow (the old
|
|
388
|
+
// shape fired an un-caught floating save plus this caught one).
|
|
389
|
+
const cleared = updateTeamState((s) => {
|
|
390
|
+
if (s.transition?.targetProfileId === profileId) {
|
|
391
|
+
delete s.transition;
|
|
392
|
+
}
|
|
393
|
+
}, { persist: "awaited" });
|
|
394
|
+
void cleared.persisted.catch(() => undefined);
|
|
395
|
+
});
|
|
396
|
+
}
|