@teamclaws/teamclaw 2026.8.1 → 2026.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/src/config.js +33 -2
  3. package/dist/src/controller/clarification-routes.js +315 -0
  4. package/dist/src/controller/controller-intake.js +895 -0
  5. package/dist/src/controller/controller-planning.js +813 -0
  6. package/dist/src/controller/controller-runs.js +175 -0
  7. package/dist/src/controller/controller-service.js +271 -40
  8. package/dist/src/controller/controller-tools.js +11 -6
  9. package/dist/src/controller/http-server.js +256 -6004
  10. package/dist/src/controller/kickoff-orchestrator.js +32 -6
  11. package/dist/src/controller/message-delivery.js +28 -0
  12. package/dist/src/controller/message-routes.js +114 -0
  13. package/dist/src/controller/orchestration-manifest.js +6 -28
  14. package/dist/src/controller/preview-proxy.js +98 -0
  15. package/dist/src/controller/profile-switch.js +289 -0
  16. package/dist/src/controller/project-registry.js +294 -0
  17. package/dist/src/controller/prompt-injector.js +19 -9
  18. package/dist/src/controller/repo-routes.js +63 -0
  19. package/dist/src/controller/role-inference.js +231 -20
  20. package/dist/src/controller/route-table.js +1353 -0
  21. package/dist/src/controller/task-assignment.js +508 -0
  22. package/dist/src/controller/task-cleanup.js +258 -0
  23. package/dist/src/controller/task-execution.js +240 -0
  24. package/dist/src/controller/task-results.js +461 -0
  25. package/dist/src/controller/task-router.js +74 -4
  26. package/dist/src/controller/task-routes.js +703 -0
  27. package/dist/src/controller/teamauto-routes.js +124 -0
  28. package/dist/src/controller/ui-assets.js +68 -0
  29. package/dist/src/controller/worker-provisioning.js +30 -4
  30. package/dist/src/controller/worker-routes.js +188 -0
  31. package/dist/src/identity.js +3 -2
  32. package/dist/src/interaction-contracts.js +7 -7
  33. package/dist/src/openclaw-workspace.js +40 -18
  34. package/dist/src/profile-loader.js +486 -0
  35. package/dist/src/profiles/banking.json +178 -0
  36. package/dist/src/profiles/crossborder-ecom.json +253 -0
  37. package/dist/src/profiles/insurance.json +157 -0
  38. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  39. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  40. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  41. package/dist/src/profiles/schema.json +201 -0
  42. package/dist/src/profiles/securities.json +137 -0
  43. package/dist/src/profiles/software-rd.json +264 -0
  44. package/dist/src/profiles/trading-co.json +200 -0
  45. package/dist/src/prompt-policy.js +26 -13
  46. package/dist/src/role-ids.js +29 -0
  47. package/dist/src/roles.js +54 -13
  48. package/dist/src/session-roles.js +14 -0
  49. package/dist/src/state.js +188 -10
  50. package/dist/src/task-executor.js +7 -17
  51. package/dist/src/teamauto/github-client.js +18 -0
  52. package/dist/src/teamauto/repo-sync.js +228 -6
  53. package/dist/src/teamauto/scanner.js +40 -12
  54. package/dist/src/teamauto/scheduler.js +231 -12
  55. package/dist/src/types.js +62 -15
  56. package/dist/src/ui/app.js +592 -24
  57. package/dist/src/ui/index.html +44 -11
  58. package/dist/src/ui/style.css +194 -0
  59. package/dist/src/worker/prompt-injector.js +44 -8
  60. package/dist/src/worker/skill-installer.js +3 -1
  61. package/dist/src/worker/worker-service.js +76 -3
  62. package/openclaw.plugin.json +28 -1
  63. package/package.json +3 -2
  64. package/src/config.ts +33 -2
  65. package/src/controller/clarification-routes.ts +404 -0
  66. package/src/controller/controller-intake.ts +1113 -0
  67. package/src/controller/controller-planning.ts +1029 -0
  68. package/src/controller/controller-runs.ts +239 -0
  69. package/src/controller/controller-service.ts +295 -41
  70. package/src/controller/controller-tools.ts +11 -7
  71. package/src/controller/http-server.ts +294 -6971
  72. package/src/controller/kickoff-orchestrator.ts +70 -7
  73. package/src/controller/message-delivery.ts +49 -0
  74. package/src/controller/message-routes.ts +137 -0
  75. package/src/controller/orchestration-manifest.ts +6 -29
  76. package/src/controller/preview-proxy.ts +127 -0
  77. package/src/controller/profile-switch.ts +366 -0
  78. package/src/controller/project-registry.ts +361 -0
  79. package/src/controller/prompt-injector.ts +23 -8
  80. package/src/controller/repo-routes.ts +91 -0
  81. package/src/controller/role-inference.ts +260 -22
  82. package/src/controller/route-table.ts +1616 -0
  83. package/src/controller/task-assignment.ts +618 -0
  84. package/src/controller/task-cleanup.ts +344 -0
  85. package/src/controller/task-execution.ts +356 -0
  86. package/src/controller/task-results.ts +544 -0
  87. package/src/controller/task-router.ts +98 -6
  88. package/src/controller/task-routes.ts +812 -0
  89. package/src/controller/teamauto-routes.ts +121 -0
  90. package/src/controller/ui-assets.ts +70 -0
  91. package/src/controller/websocket.ts +13 -1
  92. package/src/controller/worker-provisioning.ts +32 -4
  93. package/src/controller/worker-routes.ts +241 -0
  94. package/src/identity.ts +3 -2
  95. package/src/interaction-contracts.ts +7 -7
  96. package/src/openclaw-workspace.ts +44 -18
  97. package/src/profile-loader.ts +650 -0
  98. package/src/profiles/banking.json +178 -0
  99. package/src/profiles/crossborder-ecom.json +253 -0
  100. package/src/profiles/insurance.json +157 -0
  101. package/src/profiles/knowledge/hs-structure.md +97 -0
  102. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  103. package/src/profiles/knowledge/vat-principles.md +85 -0
  104. package/src/profiles/schema.json +201 -0
  105. package/src/profiles/securities.json +137 -0
  106. package/src/profiles/software-rd.json +264 -0
  107. package/src/profiles/trading-co.json +200 -0
  108. package/src/prompt-policy.ts +27 -13
  109. package/src/role-ids.ts +31 -0
  110. package/src/roles.ts +60 -14
  111. package/src/session-roles.ts +14 -0
  112. package/src/state.ts +236 -9
  113. package/src/task-executor.ts +7 -18
  114. package/src/teamauto/github-client.ts +21 -0
  115. package/src/teamauto/repo-sync.ts +246 -6
  116. package/src/teamauto/scanner.ts +47 -13
  117. package/src/teamauto/scheduler.ts +259 -16
  118. package/src/teamauto/store.ts +12 -0
  119. package/src/types.ts +133 -16
  120. package/src/ui/app.js +592 -24
  121. package/src/ui/index.html +44 -11
  122. package/src/ui/style.css +194 -0
  123. package/src/worker/prompt-injector.ts +48 -8
  124. package/src/worker/skill-installer.ts +3 -1
  125. package/src/worker/worker-service.ts +83 -3
@@ -14,7 +14,9 @@
14
14
  * 6. Controller synthesizes team input into final execution plan
15
15
  * 7. Unneeded workers are reclaimed by the idle TTL mechanism
16
16
  */
17
- import { getRole, ROLES } from "../roles.js";
17
+ // Phase 1.3: role data comes from the active TeamProfile loader.
18
+ import { getActiveDefaultRole, getActiveRole, getActiveRoleIds, validateActiveRoleId } from "../profile-loader.js";
19
+ import { inferTaskRoleWithConfidence } from "./role-inference.js";
18
20
  // ── Constants ────────────────────────────────────────────────────────────────
19
21
  /** Maximum time to wait for all workers to register after provisioning. */
20
22
  const WORKER_PROVISION_TIMEOUT_MS = 90_000;
@@ -22,13 +24,13 @@ const WORKER_PROVISION_TIMEOUT_MS = 90_000;
22
24
  const ASSESSMENT_TIMEOUT_MS = 120_000;
23
25
  /** Poll interval when waiting for workers to appear in state. */
24
26
  const WORKER_POLL_INTERVAL_MS = 2_000;
25
- const VALID_ROLE_IDS = new Set(ROLES.map((r) => r.id));
26
27
  // ── Public API ───────────────────────────────────────────────────────────────
27
28
  export async function runKickoffMeeting(request, deps) {
28
29
  const { logger } = deps;
29
30
  const { requirement, candidateRoles, complexity } = request;
30
31
  // Validate roles
31
- const validRoles = candidateRoles.filter((r) => VALID_ROLE_IDS.has(r));
32
+ // Resolved per call so the set always reflects the active profile.
33
+ const validRoles = candidateRoles.filter((r) => getActiveRoleIds().includes(r));
32
34
  if (validRoles.length === 0) {
33
35
  return buildEmptyResult(complexity, "No valid candidate roles provided.");
34
36
  }
@@ -126,7 +128,7 @@ function buildKickoffSummary(plan, _requirement) {
126
128
  if (needed.length > 0) {
127
129
  parts.push("### Roles Confirmed Needed");
128
130
  for (const a of needed) {
129
- const roleDef = getRole(a.role);
131
+ const roleDef = getActiveRole(a.role);
130
132
  const icon = roleDef?.icon ?? "•";
131
133
  parts.push(`\n**${icon} ${roleDef?.label ?? a.role}**`);
132
134
  parts.push(`- Scope: ${a.scope}`);
@@ -148,7 +150,7 @@ function buildKickoffSummary(plan, _requirement) {
148
150
  parts.push("");
149
151
  parts.push("### Roles Not Needed");
150
152
  for (const a of notNeeded) {
151
- const roleDef = getRole(a.role);
153
+ const roleDef = getActiveRole(a.role);
152
154
  parts.push(`- ${roleDef?.icon ?? "•"} ${roleDef?.label ?? a.role}: ${a.scope}`);
153
155
  }
154
156
  }
@@ -183,7 +185,7 @@ function buildKickoffSummary(plan, _requirement) {
183
185
  * The worker should respond with structured JSON matching KickoffAssessment.
184
186
  */
185
187
  export function buildKickoffAssessmentPrompt(role, requirement) {
186
- const roleDef = getRole(role);
188
+ const roleDef = getActiveRole(role);
187
189
  const roleLabel = roleDef?.label ?? role;
188
190
  return [
189
191
  `You are the ${roleLabel} in a virtual software team.`,
@@ -217,4 +219,28 @@ export function buildKickoffAssessmentPrompt(role, requirement) {
217
219
  function sleep(ms) {
218
220
  return new Promise((resolve) => setTimeout(resolve, ms));
219
221
  }
222
+ export async function resolveTaskRoleWithLlmFallback(task, deps = {}) {
223
+ const verdict = (deps.inferWithConfidence ?? inferTaskRoleWithConfidence)(task);
224
+ if (!verdict.needsLlmFallback) {
225
+ return verdict.role;
226
+ }
227
+ if (deps.llmRoleJudge) {
228
+ try {
229
+ const judged = await deps.llmRoleJudge({ task, verdict });
230
+ const validated = validateActiveRoleId(judged);
231
+ if (validated) {
232
+ deps.logger?.info(`RoleInference: LLM fallback judged role ${validated} (token fast path refused: ${verdict.reason})`);
233
+ return validated;
234
+ }
235
+ deps.logger?.warn(`RoleInference: LLM fallback returned ${JSON.stringify(judged)} which is not a role of the active profile; using defaultRole`);
236
+ }
237
+ catch (err) {
238
+ deps.logger?.warn(`RoleInference: LLM fallback failed (${err instanceof Error ? err.message : String(err)}); using defaultRole`);
239
+ }
240
+ }
241
+ else {
242
+ deps.logger?.info(`RoleInference: token fast path refused to decide (${verdict.reason}) and no LLM fallback is wired; using defaultRole`);
243
+ }
244
+ return getActiveDefaultRole();
245
+ }
220
246
  export { ASSESSMENT_TIMEOUT_MS };
@@ -0,0 +1,28 @@
1
+ export async function deliverMessageToWorker(worker, message, deps) {
2
+ const res = await fetch(`${worker.url}/api/v1/messages`, {
3
+ method: "POST",
4
+ headers: { "Content-Type": "application/json" },
5
+ body: JSON.stringify(message),
6
+ });
7
+ if (!res.ok) {
8
+ throw new Error(`worker ${worker.id} responded with ${res.status}`);
9
+ }
10
+ }
11
+ export async function routeDirectMessage(message, deps) {
12
+ const { getTeamState, logger, messageRouter } = deps;
13
+ const state = getTeamState();
14
+ if (!state) {
15
+ return false;
16
+ }
17
+ const routed = messageRouter.routeDirectMessage(message, state.workers);
18
+ if (!routed) {
19
+ return false;
20
+ }
21
+ try {
22
+ await deliverMessageToWorker(routed.worker, routed.message, deps);
23
+ }
24
+ catch (err) {
25
+ logger.warn(`Controller: failed to deliver message to ${routed.worker.id}: ${String(err)}`);
26
+ }
27
+ return true;
28
+ }
@@ -0,0 +1,114 @@
1
+ import { generateId, parseJsonBody, sendJson } from "../protocol.js";
2
+ import { ensureTeamMessageContract } from "../interaction-contracts.js";
3
+ import { validateActiveRoleId } from "../profile-loader.js";
4
+ import { deliverMessageToWorker, routeDirectMessage, } from "./message-delivery.js";
5
+ // POST /api/v1/messages/direct
6
+ export async function handleDirectMessageRequest(deps, req, res) {
7
+ const { updateTeamState, wsServer } = deps;
8
+ const body = await parseJsonBody(req);
9
+ const fromRole = validateActiveRoleId(body.fromRole);
10
+ const toRole = validateActiveRoleId(body.toRole);
11
+ const message = {
12
+ id: generateId(),
13
+ from: typeof body.from === "string" ? body.from : "",
14
+ fromRole,
15
+ toRole,
16
+ type: "direct",
17
+ content: typeof body.content === "string" ? body.content : "",
18
+ contract: ensureTeamMessageContract(body.contract, {
19
+ type: "direct",
20
+ content: typeof body.content === "string" ? body.content : "",
21
+ toRole,
22
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
23
+ }),
24
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
25
+ createdAt: Date.now(),
26
+ };
27
+ updateTeamState((s) => { s.messages.push(message); });
28
+ const routed = await routeDirectMessage(message, deps);
29
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
30
+ sendJson(res, 201, { status: routed ? "delivered" : "no-target", message });
31
+ }
32
+ // POST /api/v1/messages/broadcast
33
+ export async function handleBroadcastMessageRequest(deps, req, res) {
34
+ const { logger, getTeamState, updateTeamState, messageRouter, wsServer } = deps;
35
+ const body = await parseJsonBody(req);
36
+ const fromRole = validateActiveRoleId(body.fromRole);
37
+ const message = {
38
+ id: generateId(),
39
+ from: typeof body.from === "string" ? body.from : "",
40
+ fromRole,
41
+ type: "broadcast",
42
+ content: typeof body.content === "string" ? body.content : "",
43
+ contract: ensureTeamMessageContract(body.contract, {
44
+ type: "broadcast",
45
+ content: typeof body.content === "string" ? body.content : "",
46
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
47
+ }),
48
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
49
+ createdAt: Date.now(),
50
+ };
51
+ updateTeamState((s) => { s.messages.push(message); });
52
+ const state = getTeamState();
53
+ const routed = messageRouter.routeBroadcast(message, state.workers);
54
+ for (const { worker, message: routedMsg } of routed) {
55
+ try {
56
+ await deliverMessageToWorker(worker, routedMsg, deps);
57
+ }
58
+ catch (err) {
59
+ logger.warn(`Controller: failed to broadcast to ${worker.id}: ${String(err)}`);
60
+ }
61
+ }
62
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
63
+ sendJson(res, 201, { status: "broadcast", recipients: routed.length });
64
+ }
65
+ // POST /api/v1/messages/review-request
66
+ export async function handleReviewRequestMessageRequest(deps, req, res) {
67
+ const { logger, getTeamState, updateTeamState, messageRouter, wsServer } = deps;
68
+ const body = await parseJsonBody(req);
69
+ const fromRole = validateActiveRoleId(body.fromRole);
70
+ const toRole = validateActiveRoleId(body.toRole);
71
+ const message = {
72
+ id: generateId(),
73
+ from: typeof body.from === "string" ? body.from : "",
74
+ fromRole,
75
+ toRole,
76
+ type: "review-request",
77
+ content: typeof body.content === "string" ? body.content : "",
78
+ contract: ensureTeamMessageContract(body.contract, {
79
+ type: "review-request",
80
+ content: typeof body.content === "string" ? body.content : "",
81
+ toRole,
82
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
83
+ intent: "review-request",
84
+ needsResponse: true,
85
+ }),
86
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
87
+ createdAt: Date.now(),
88
+ };
89
+ updateTeamState((s) => { s.messages.push(message); });
90
+ const state = getTeamState();
91
+ const routed = messageRouter.routeReviewRequest(message, state.workers);
92
+ if (routed) {
93
+ try {
94
+ await deliverMessageToWorker(routed.worker, routed.message, deps);
95
+ }
96
+ catch (err) {
97
+ logger.warn(`Controller: failed to deliver review request: ${String(err)}`);
98
+ }
99
+ }
100
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
101
+ sendJson(res, 201, { status: routed ? "delivered" : "no-target", message });
102
+ }
103
+ // GET /api/v1/messages
104
+ export async function handleMessageListRequest(deps, res, requestUrl) {
105
+ const { getTeamState } = deps;
106
+ const state = getTeamState();
107
+ const messages = state?.messages ?? [];
108
+ const limit = parseInt(requestUrl.searchParams.get("limit") ?? "50", 10);
109
+ const offset = parseInt(requestUrl.searchParams.get("offset") ?? "0", 10);
110
+ sendJson(res, 200, {
111
+ messages: messages.slice(offset, offset + limit),
112
+ total: messages.length,
113
+ });
114
+ }
@@ -1,33 +1,11 @@
1
+ import { validateRoleIdList } from "../roles.js";
1
2
  import { deriveStableProjectKey } from "../openclaw-workspace.js";
2
- const TEAMCLAW_ROLE_IDS = new Set([
3
- "pm",
4
- "architect",
5
- "developer",
6
- "qa",
7
- "release-engineer",
8
- "infra-engineer",
9
- "devops",
10
- "security-engineer",
11
- "designer",
12
- "marketing",
13
- "data-engineer",
14
- ]);
15
3
  export function normalizeManifestRoleList(raw) {
16
- if (!Array.isArray(raw)) {
17
- return [];
18
- }
19
- const roleIds = [];
20
- for (const entry of raw) {
21
- if (typeof entry !== "string") {
22
- continue;
23
- }
24
- const normalized = entry.trim();
25
- if (!normalized || !TEAMCLAW_ROLE_IDS.has(normalized) || roleIds.includes(normalized)) {
26
- continue;
27
- }
28
- roleIds.push(normalized);
29
- }
30
- return roleIds;
4
+ // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts.
5
+ // The hand-written TEAMCLAW_ROLE_IDS copy this function used to keep was
6
+ // removed by Phase 1.2 (single-source-of-truth convergence); the role set
7
+ // now lives only in role-ids.ts / roles.ts.
8
+ return validateRoleIdList(raw);
31
9
  }
32
10
  export function normalizeManifestStringList(raw) {
33
11
  if (!Array.isArray(raw)) {
@@ -0,0 +1,98 @@
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 { sendJson } from "../protocol.js";
12
+ /**
13
+ * /api/v1/previews/:id/* - proxy to the preview subprocess. `pathname` starts
14
+ * with "/api/v1/previews/"; `requestUrl` is the parsed request URL (query
15
+ * string is forwarded to the subprocess).
16
+ */
17
+ export function handlePreviewProxyRequest(deps, req, res, requestUrl, pathname) {
18
+ const previewPrefix = "/api/v1/previews/";
19
+ const remaining = pathname.slice(previewPrefix.length);
20
+ const slashIdx = remaining.indexOf("/");
21
+ const previewId = slashIdx >= 0 ? remaining.slice(0, slashIdx) : remaining;
22
+ const subPath = slashIdx >= 0 ? remaining.slice(slashIdx) : "/";
23
+ const state = deps.getTeamState();
24
+ const preview = state?.previews?.[previewId];
25
+ if (!preview || preview.status !== "healthy") {
26
+ const status = preview?.status ?? "unknown";
27
+ const errMsg = preview?.lastError;
28
+ sendJson(res, 503, { error: "Preview not available", previewId, status, lastError: errMsg ?? undefined });
29
+ return;
30
+ }
31
+ const proxyPathPrefix = `/api/v1/previews/${encodeURIComponent(previewId)}`;
32
+ const proxyReq = http.request({
33
+ hostname: "127.0.0.1",
34
+ port: preview.targetPort,
35
+ path: subPath + (requestUrl.search || ""),
36
+ method: req.method,
37
+ headers: {
38
+ ...req.headers,
39
+ host: `127.0.0.1:${preview.targetPort}`,
40
+ "accept-encoding": "identity",
41
+ "x-forwarded-for": req.socket.remoteAddress ?? "",
42
+ "x-forwarded-host": req.headers.host ?? "",
43
+ "x-forwarded-proto": "http",
44
+ },
45
+ }, (proxyRes) => {
46
+ const contentType = (proxyRes.headers["content-type"] ?? "").toLowerCase();
47
+ if (proxyRes.statusCode !== 200 && proxyRes.statusCode !== 201 && proxyRes.statusCode !== 301 && proxyRes.statusCode !== 302 && proxyRes.statusCode !== 304) {
48
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
49
+ proxyRes.pipe(res);
50
+ return;
51
+ }
52
+ if (contentType.includes("text/html")) {
53
+ const chunks = [];
54
+ proxyRes.on("data", (chunk) => chunks.push(chunk));
55
+ proxyRes.on("end", () => {
56
+ let raw = Buffer.concat(chunks);
57
+ // Decompress if the upstream response is compressed (brotli/gzip/deflate).
58
+ const encoding = (proxyRes.headers["content-encoding"] ?? "").toLowerCase();
59
+ try {
60
+ if (encoding === "br") {
61
+ raw = zlib.brotliDecompressSync(raw);
62
+ }
63
+ else if (encoding === "gzip") {
64
+ raw = zlib.gunzipSync(raw);
65
+ }
66
+ else if (encoding === "deflate") {
67
+ raw = zlib.inflateSync(raw);
68
+ }
69
+ }
70
+ catch {
71
+ // If decompression fails, use raw bytes as-is.
72
+ }
73
+ const body = raw.toString("utf-8");
74
+ // Rewrite absolute-path references (href="/...", src="/...", action="/...")
75
+ // to include the proxy prefix so all navigation stays within the proxy.
76
+ const rewritten = body.replace(/\b(href|src|action)\s*=\s*"\/([^"]*)"/g, `$1="${proxyPathPrefix}/$2"`).replace(/\b(href|src|action)\s*=\s*'\/([^']*)'/g, `$1='${proxyPathPrefix}/$2'`);
77
+ const resHeaders = { ...proxyRes.headers };
78
+ // We've decoded and rewritten the body — remove upstream encoding headers.
79
+ delete resHeaders["content-encoding"];
80
+ delete resHeaders["transfer-encoding"];
81
+ resHeaders["content-length"] = String(Buffer.byteLength(rewritten, "utf-8"));
82
+ res.writeHead(proxyRes.statusCode ?? 200, resHeaders);
83
+ res.end(rewritten);
84
+ });
85
+ }
86
+ else {
87
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
88
+ proxyRes.pipe(res);
89
+ }
90
+ });
91
+ proxyReq.on("error", (err) => {
92
+ deps.logger.warn(`Controller: preview proxy error for ${previewId}: ${String(err)}`);
93
+ if (!res.headersSent) {
94
+ sendJson(res, 502, { error: "Preview proxy error", previewId, message: String(err) });
95
+ }
96
+ });
97
+ req.pipe(proxyReq);
98
+ }
@@ -0,0 +1,289 @@
1
+ import { saveTeamState, archiveTeamState, findTeamSwitchArchive } from "../state.js";
2
+ import { BUILTIN_PROFILES, getActiveProfile, hasProfile, setActiveProfileId, } from "../profile-loader.js";
3
+ import { ensureControllerGitRepo } from "../git-collaboration.js";
4
+ // ===========================================================================
5
+ // Team profile switch (Phase 2.1, vertical-team-profiles-design.md 2.3).
6
+ //
7
+ // Six-step semantics of POST /api/v1/team/profile:
8
+ // 0. validate profileId + reject concurrent switches (409) [endpoint]
9
+ // 1. transition = { draining, target, startedAt }; persisted + WS event
10
+ // 2. graceful drain of in-flight tasks (timeout -> force-collect),
11
+ // terminate workers [drainTeam...]
12
+ // 3. archive the WHOLE TeamState + roles snapshot [state.ts]
13
+ // 4. fresh capability-conditioned TeamState for the target
14
+ // 5. warm the target profile's warmupRoles [provisioner]
15
+ // 6. clear transition, persist, broadcast team.switch_completed
16
+ // ===========================================================================
17
+ const SWITCH_DRAIN_POLL_INTERVAL_MS = 500;
18
+ function sleepForSwitchDrain(ms) {
19
+ return new Promise((resolve) => setTimeout(resolve, ms));
20
+ }
21
+ function taskInFlightForDrain(task) {
22
+ return Boolean(task.assignedWorkerId) && (task.status === "assigned" || task.status === "in_progress");
23
+ }
24
+ /**
25
+ * Design 2.3 step 2: graceful drain. Waits until no task is assigned /
26
+ * in-progress any more (in-flight workers report results through their
27
+ * normal endpoints, which stay open during the transition), then returns.
28
+ * On timeout the remaining in-flight tasks are force-collected (failed with
29
+ * an explicit error so the archive records the forced end) and all workers
30
+ * are marked offline. Managed workers are terminated by the caller through
31
+ * the provisioning manager's onWorkerRemoved (the terminateManagedWorker
32
+ * single point); external workers observe 409 heartbeats and back off.
33
+ */
34
+ async function drainTeamForProfileSwitch(deps) {
35
+ const { config, logger, getTeamState, updateTeamState } = deps;
36
+ const deadline = Date.now() + config.teamSwitchDrainTimeoutMs;
37
+ while (Date.now() < deadline) {
38
+ const state = getTeamState();
39
+ if (!state || !Object.values(state.tasks).some(taskInFlightForDrain)) {
40
+ return { timedOut: false, forceCollected: [] };
41
+ }
42
+ await sleepForSwitchDrain(SWITCH_DRAIN_POLL_INTERVAL_MS);
43
+ }
44
+ const forceCollected = [];
45
+ updateTeamState((state) => {
46
+ for (const task of Object.values(state.tasks)) {
47
+ if (taskInFlightForDrain(task)) {
48
+ task.status = "failed";
49
+ task.error = `team profile switch drain timeout (${config.teamSwitchDrainTimeoutMs}ms) - in-flight task force-collected into the team archive`;
50
+ task.updatedAt = Date.now();
51
+ forceCollected.push(task.id);
52
+ }
53
+ }
54
+ for (const worker of Object.values(state.workers)) {
55
+ worker.status = "offline";
56
+ worker.currentTaskId = undefined;
57
+ }
58
+ });
59
+ logger.warn(`Controller: profile switch drain timed out after ${config.teamSwitchDrainTimeoutMs}ms - force-collected ${forceCollected.length} in-flight task(s)`);
60
+ return { timedOut: true, forceCollected };
61
+ }
62
+ /**
63
+ * Run switch steps 2-6 (step 1 - setting and persisting the transition -
64
+ * belongs to the POST endpoint / crash resume). Exported so the controller
65
+ * startup chain can resume an interrupted switch with the same semantics.
66
+ */
67
+ export async function executeTeamProfileSwitch(deps, targetProfileId, options = {}) {
68
+ const { config, logger, getTeamState, updateTeamState, wsServer, workerProvisioningManager } = deps;
69
+ const target = BUILTIN_PROFILES.get(targetProfileId);
70
+ if (!target) {
71
+ throw new Error(`TeamClaw team profile "${targetProfileId}" is not available in this installation`);
72
+ }
73
+ const setPhase = (phase) => {
74
+ updateTeamState((state) => {
75
+ if (state.transition?.targetProfileId === targetProfileId) {
76
+ state.transition.phase = phase;
77
+ }
78
+ });
79
+ };
80
+ if (!options.skipArchive) {
81
+ // Step 2: drain in-flight work, then stop every worker.
82
+ setPhase("draining");
83
+ workerProvisioningManager?.setReconcileSuspended(true);
84
+ const drain = await drainTeamForProfileSwitch(deps);
85
+ for (const workerId of Object.keys(getTeamState()?.provisioning?.workers ?? {})) {
86
+ if (workerProvisioningManager?.hasManagedWorker(workerId)) {
87
+ await workerProvisioningManager
88
+ .onWorkerRemoved(workerId, `team profile switch to "${targetProfileId}"`)
89
+ .catch((err) => logger.warn(`Controller: failed to terminate managed worker ${workerId} during profile switch: ${String(err)}`));
90
+ }
91
+ }
92
+ // Capability teardown for subsystems the target profile switches off
93
+ // (minimal Phase 2.3 preview; the full 404 short-circuit lands in 2.3).
94
+ // NOTE: teardown is one-directional at runtime. Switching a capability
95
+ // back ON does not (re)start its subsystem here - TeamAuto scheduling
96
+ // and preview restoration are wired at controller startup only, so an
97
+ // off -> on switch (e.g. minimal-bank -> software-rd) takes effect for
98
+ // those subsystems after the next gateway restart.
99
+ if (!target.capabilities.teamauto) {
100
+ const scheduler = deps.getTeamAutoScheduler?.() ?? null;
101
+ if (scheduler) {
102
+ try {
103
+ await scheduler.stop();
104
+ }
105
+ catch { /* scheduler already stopped */ }
106
+ }
107
+ }
108
+ if (!target.capabilities.runnablePreview && deps.previewManager) {
109
+ try {
110
+ await deps.previewManager.stopAll();
111
+ }
112
+ catch { /* previews already stopped */ }
113
+ }
114
+ // Step 3: archive the whole previous TeamState with a roles snapshot.
115
+ // The phase flip is persisted BEFORE the archive write so a crash between
116
+ // the two leaves an unambiguous "archive may exist" state for the resume
117
+ // path (file existence check).
118
+ setPhase("archiving");
119
+ const sourceState = getTeamState();
120
+ if (sourceState) {
121
+ await saveTeamState(sourceState);
122
+ const sourceProfile = getActiveProfile();
123
+ await archiveTeamState(sourceState, {
124
+ id: sourceProfile.id,
125
+ name: sourceProfile.name,
126
+ nameZh: sourceProfile.nameZh,
127
+ version: sourceProfile.version,
128
+ roles: sourceProfile.roles,
129
+ });
130
+ logger.info(`Controller: archived team "${sourceState.teamName}" (profile ${sourceProfile.id}, `
131
+ + `${Object.keys(sourceState.tasks).length} task(s))${drain.timedOut ? " after drain timeout" : ""}`);
132
+ }
133
+ }
134
+ // Step 4: fresh TeamState for the target profile, conditioned on its
135
+ // capability switches (design 2.3: banking omits repo/previews/reports).
136
+ // setActiveProfileId and the state mutation below are both synchronous, so
137
+ // no request can observe the new state against the old profile.
138
+ const repoState = target.capabilities.git
139
+ ? await ensureControllerGitRepo(config, logger).catch((err) => {
140
+ logger.warn(`Controller: failed to prepare git collaboration repo for profile "${target.id}": ${err instanceof Error ? err.message : String(err)}`);
141
+ return null;
142
+ })
143
+ : null;
144
+ setActiveProfileId(target.id);
145
+ const newCreatedAt = Date.now();
146
+ updateTeamState((state) => {
147
+ state.profileId = target.id;
148
+ state.teamName = target.name;
149
+ state.workers = {};
150
+ state.tasks = {};
151
+ state.controllerRuns = {};
152
+ state.projects = {};
153
+ state.messages = [];
154
+ state.clarifications = {};
155
+ state.provisioning = { workers: {} };
156
+ if (target.capabilities.git && repoState) {
157
+ state.repo = repoState;
158
+ }
159
+ else {
160
+ delete state.repo;
161
+ }
162
+ if (target.capabilities.runnablePreview) {
163
+ state.previews = {};
164
+ }
165
+ else {
166
+ delete state.previews;
167
+ }
168
+ if (target.capabilities.deliveryReview) {
169
+ state.reports = {};
170
+ }
171
+ else {
172
+ delete state.reports;
173
+ }
174
+ state.createdAt = newCreatedAt;
175
+ });
176
+ await saveTeamState(getTeamState());
177
+ // Step 5: warm the new profile's warmupRoles through the provisioning
178
+ // pipeline (launch dispatch; registration/readiness tracking continues in
179
+ // the background exactly like a cold start).
180
+ setPhase("warming");
181
+ await saveTeamState(getTeamState());
182
+ workerProvisioningManager?.setReconcileSuspended(false);
183
+ if (workerProvisioningManager?.isEnabled() && target.warmupRoles.length > 0) {
184
+ await workerProvisioningManager
185
+ .warmRolesForTeamSwitch(target.warmupRoles, `profile switch warmup (${target.id})`)
186
+ .catch((err) => logger.warn(`Controller: profile switch warmup failed: ${err instanceof Error ? err.message : String(err)}`));
187
+ }
188
+ // Step 6: settle - clear the transition, persist, announce.
189
+ updateTeamState((state) => {
190
+ delete state.transition;
191
+ });
192
+ await saveTeamState(getTeamState());
193
+ wsServer.broadcastUpdate({ type: "team.switch_completed", data: { profileId: target.id } });
194
+ logger.info(`Controller: team profile switch to "${target.id}" completed`);
195
+ }
196
+ /**
197
+ * Design 2.3 crash semantics: on controller startup, an unfinished persisted
198
+ * transition is resumed idempotently. If the archive file for this switch
199
+ * already exists AND the phase is at/after "archiving", jump straight to
200
+ * building the new team (skipArchive); otherwise re-run the drain from
201
+ * scratch (drain is idempotent - a completed drain simply finds no in-flight
202
+ * tasks). Returns true when a transition was resumed.
203
+ */
204
+ // No team.switch_failed broadcast on this path: startup resume runs before
205
+ // the HTTP/WS listeners exist, so there are no clients to receive it - a
206
+ // failed resume surfaces through the fatal startup path instead (#201 review
207
+ // note, recorded for external reviewers).
208
+ export async function resumeTeamProfileSwitch(deps) {
209
+ const state = deps.getTeamState();
210
+ const transition = state?.transition;
211
+ if (!state || !transition) {
212
+ return false;
213
+ }
214
+ if (!hasProfile(transition.targetProfileId)) {
215
+ // Same red line as restoring an unknown profileId (design 2.2): a team
216
+ // mid-switch to an unavailable profile must never silently land on a
217
+ // different profile.
218
+ throw new Error(`Controller: interrupted team profile switch references profile "${transition.targetProfileId}", which is not available in this installation. `);
219
+ }
220
+ deps.logger.info(`Controller: resuming interrupted team profile switch to "${transition.targetProfileId}" (phase: ${transition.phase}, started at ${new Date(transition.startedAt).toISOString()})`);
221
+ // A persisted state whose profileId already equals the target means step 4
222
+ // flipped the team identity onto the NEW team. Step 4 strictly follows the
223
+ // completed archive write in the same execution (the archive file lands
224
+ // atomically before step 4 runs), so that flip PROVES the archive exists.
225
+ // This covers both phase "warming" and the ghost-archive window between
226
+ // the step-4 flip reaching disk and the warming phase persisting - on disk
227
+ // that window reads as (phase "archiving", profileId = target), where
228
+ // looking up the SOURCE-named archive file with state.profileId would miss
229
+ // it and a re-drain would seal the already-emptied NEW team as a ghost
230
+ // archive entry. (Alternative considered: persisting a sourceProfileId on
231
+ // the transition - rejected; this flip predicate is the identical proof
232
+ // without transition-shape or migration churn, and it also degrades the
233
+ // manually-corrupted (draining, target) combination the same safe way.)
234
+ const step4Flipped = state.profileId === transition.targetProfileId;
235
+ const archiveExists = step4Flipped
236
+ || transition.phase === "warming"
237
+ || Boolean(await findTeamSwitchArchive(state.profileId, transition.startedAt));
238
+ const phaseAtOrAfterArchive = transition.phase === "archiving" || transition.phase === "warming";
239
+ await executeTeamProfileSwitch(deps, transition.targetProfileId, {
240
+ skipArchive: archiveExists && (phaseAtOrAfterArchive || step4Flipped),
241
+ });
242
+ return true;
243
+ }
244
+ /**
245
+ * Fire-and-forget switch execution launched by POST /api/v1/team/profile
246
+ * after step 1 (transition persisted + switch_started broadcast). Owns the
247
+ * failure path: worst-case archive-preservation detection, the
248
+ * team.switch_failed broadcast, and unwedging the transition.
249
+ */
250
+ export function startTeamProfileSwitch(deps, state, profileId, previousProfileId) {
251
+ const { logger, wsServer, updateTeamState, getTeamState } = deps;
252
+ void executeTeamProfileSwitch(deps, profileId).catch(async (err) => {
253
+ const detail = err instanceof Error ? err.message : String(err);
254
+ logger.error(`Controller: team profile switch to "${profileId}" failed: ${detail}`);
255
+ // Never leave the team wedged in a transition: clear it so whichever
256
+ // team the state now holds keeps serving and the switch can be
257
+ // re-issued. The archive (if step 3 ran) keeps the previous team. Also
258
+ // lift the provisioning reconcile suspension so the manager keeps
259
+ // operating for whichever team survived.
260
+ deps.workerProvisioningManager?.setReconcileSuspended(false);
261
+ // Honest worst case for the failure payload: once the step-3 archive
262
+ // write has landed (or step 4 already flipped the team identity - which
263
+ // strictly proves the archive landed), the state on disk may be
264
+ // partially switched and a restart is the reliable recovery. Detect
265
+ // with the same resume-path predicate: a source-named archive file at
266
+ // or after the transition's startedAt.
267
+ const transition = state.transition;
268
+ let archivePreserved = state.profileId === profileId;
269
+ if (!archivePreserved && transition) {
270
+ archivePreserved = Boolean(await findTeamSwitchArchive(previousProfileId, transition.startedAt).catch(() => null));
271
+ }
272
+ const reason = archivePreserved
273
+ ? `${detail} (archive preserved, team state may be partially switched, restart recommended)`
274
+ : detail;
275
+ // Broadcast BEFORE clearing the transition: the web switcher releases
276
+ // its loading/confirm state on this event instead of silently timing
277
+ // out on the reconcile fallback.
278
+ wsServer.broadcastUpdate({
279
+ type: "team.switch_failed",
280
+ data: { previousProfileId, targetProfileId: profileId, reason },
281
+ });
282
+ updateTeamState((s) => {
283
+ if (s.transition?.targetProfileId === profileId) {
284
+ delete s.transition;
285
+ }
286
+ });
287
+ void saveTeamState(getTeamState()).catch(() => undefined);
288
+ });
289
+ }