@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
@@ -0,0 +1,124 @@
1
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
2
+ import { getGithubAuthManager } from "./github-auth.js";
3
+ import { createGithubClient } from "../teamauto/github-client.js";
4
+ export async function handleTeamAutoActivityRequest(deps, res) {
5
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
6
+ if (!teamAuto) {
7
+ sendError(res, 503, "TeamAuto scheduler is not running");
8
+ return;
9
+ }
10
+ try {
11
+ const activity = await teamAuto.getActivity();
12
+ sendJson(res, 200, { activity });
13
+ }
14
+ catch (err) {
15
+ sendError(res, 500, err instanceof Error ? err.message : "failed to load activity");
16
+ }
17
+ }
18
+ export async function handleTeamAutoReposListRequest(deps, res) {
19
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
20
+ if (!teamAuto) {
21
+ sendError(res, 503, "TeamAuto scheduler is not running");
22
+ return;
23
+ }
24
+ try {
25
+ sendJson(res, 200, await teamAuto.getStatus());
26
+ }
27
+ catch (err) {
28
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read TeamAuto status");
29
+ }
30
+ }
31
+ // Selectable repos for the bind picker (the logged-in GitHub account's).
32
+ export async function handleTeamAutoRepoCandidatesRequest(deps, res) {
33
+ try {
34
+ const auth = getGithubAuthManager(deps.config, deps.logger);
35
+ const candidates = await createGithubClient(auth).listUserRepos();
36
+ sendJson(res, 200, { candidates });
37
+ }
38
+ catch (err) {
39
+ sendError(res, 400, err instanceof Error ? err.message : "failed to list repositories");
40
+ }
41
+ }
42
+ export async function handleTeamAutoRepoBindRequest(deps, req, res) {
43
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
44
+ if (!teamAuto) {
45
+ sendError(res, 503, "TeamAuto scheduler is not running");
46
+ return;
47
+ }
48
+ let body = {};
49
+ try {
50
+ body = await parseJsonBody(req);
51
+ }
52
+ catch { /* empty body */ }
53
+ const repo = typeof body.repo === "string" ? body.repo : "";
54
+ if (!repo) {
55
+ sendError(res, 400, "repo (owner/name) is required");
56
+ return;
57
+ }
58
+ try {
59
+ const created = await teamAuto.addRepo(repo, {
60
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
61
+ keywordInclude: Array.isArray(body.keywordInclude) ? body.keywordInclude.filter((k) => typeof k === "string") : undefined,
62
+ keywordExclude: Array.isArray(body.keywordExclude) ? body.keywordExclude.filter((k) => typeof k === "string") : undefined,
63
+ });
64
+ sendJson(res, 201, created);
65
+ }
66
+ catch (err) {
67
+ sendError(res, 400, err instanceof Error ? err.message : "failed to bind repo");
68
+ }
69
+ }
70
+ /**
71
+ * Per-repo actions under /api/v1/teamauto/repos/:id (DELETE unbind / PATCH
72
+ * update / POST :id/sweep). Returns false when the method does not match any
73
+ * action, leaving the request to fall through to the dispatcher's 404 exactly
74
+ * as the inline block did.
75
+ */
76
+ export async function handleTeamAutoRepoItemRequest(deps, req, res, pathname) {
77
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
78
+ if (!teamAuto) {
79
+ sendError(res, 503, "TeamAuto scheduler is not running");
80
+ return true;
81
+ }
82
+ const repoId = decodeURIComponent(pathname.slice("/api/v1/teamauto/repos/".length).replace(/\/sweep$/, ""));
83
+ const isSweep = pathname.endsWith("/sweep");
84
+ if (req.method === "DELETE" && !isSweep) {
85
+ try {
86
+ await teamAuto.removeRepo(repoId);
87
+ sendJson(res, 200, { ok: true });
88
+ }
89
+ catch (err) {
90
+ sendError(res, 400, err instanceof Error ? err.message : "failed to unbind");
91
+ }
92
+ return true;
93
+ }
94
+ if (req.method === "PATCH" && !isSweep) {
95
+ let body = {};
96
+ try {
97
+ body = await parseJsonBody(req);
98
+ }
99
+ catch { /* empty */ }
100
+ try {
101
+ const updated = await teamAuto.updateRepo(repoId, {
102
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
103
+ maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
104
+ fullReview: body.fullReview === "off" || body.fullReview === "weekly" || body.fullReview === "daily" ? body.fullReview : undefined,
105
+ takeOwnership: typeof body.takeOwnership === "boolean" ? body.takeOwnership : undefined,
106
+ });
107
+ sendJson(res, 200, updated);
108
+ }
109
+ catch (err) {
110
+ sendError(res, 400, err instanceof Error ? err.message : "failed to update");
111
+ }
112
+ return true;
113
+ }
114
+ if (req.method === "POST" && isSweep) {
115
+ try {
116
+ sendJson(res, 200, { summary: await teamAuto.runSweepNow(repoId, true) });
117
+ }
118
+ catch (err) {
119
+ sendError(res, 400, err instanceof Error ? err.message : "sweep failed");
120
+ }
121
+ return true;
122
+ }
123
+ return false;
124
+ }
@@ -0,0 +1,68 @@
1
+ // PR-A of issue #204 (http-server monolith split): static web UI asset
2
+ // serving extracted verbatim from controller/http-server.ts. Zero behavior
3
+ // change - the route shells in http-server call these functions unchanged.
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { sendError } from "../protocol.js";
8
+ // Tunnel/CDN caches rewrite the origin's Cache-Control: no-cache into a long
9
+ // browser freeze for cacheable extensions like .js (observed: Cloudflare
10
+ // Browser Cache TTL max-age=14400 on tunneled UI assets). A UI update then
11
+ // never reaches visitors through the tunnel. Serving content-versioned URLs
12
+ // (?v=<hash>) makes every UI deploy a URL no browser or edge has ever seen,
13
+ // so stale-cache behavior cannot recur.
14
+ const uiAssetVersionCache = new Map();
15
+ function uiAssetVersion(uiPath, file) {
16
+ const full = path.join(uiPath, file);
17
+ try {
18
+ const mtimeMs = fs.statSync(full).mtimeMs;
19
+ const cached = uiAssetVersionCache.get(full);
20
+ if (cached && cached.mtimeMs === mtimeMs)
21
+ return cached.version;
22
+ const version = createHash("sha1").update(fs.readFileSync(full)).digest("hex").slice(0, 10);
23
+ uiAssetVersionCache.set(full, { mtimeMs, version });
24
+ return version;
25
+ }
26
+ catch {
27
+ return String(Date.now()); // unreadable asset: bust for this request
28
+ }
29
+ }
30
+ const UI_HTML_ASSET_REFS = [
31
+ "/ui/style.css",
32
+ "/ui/app.js",
33
+ "/ui/assets/teamclaw-app-icon.png",
34
+ ];
35
+ export function serveVersionedHtml(res, htmlPath) {
36
+ try {
37
+ const uiPath = path.dirname(htmlPath);
38
+ let html = fs.readFileSync(htmlPath, "utf8");
39
+ for (const ref of UI_HTML_ASSET_REFS) {
40
+ html = html.split(`"${ref}"`).join(`"${ref}?v=${uiAssetVersion(uiPath, ref.slice("/ui/".length))}"`);
41
+ }
42
+ res.writeHead(200, {
43
+ "Content-Type": "text/html; charset=utf-8",
44
+ "Access-Control-Allow-Origin": "*",
45
+ "Cache-Control": "no-cache",
46
+ });
47
+ res.end(html);
48
+ }
49
+ catch {
50
+ sendError(res, 404, "File not found");
51
+ }
52
+ }
53
+ export function serveStaticFile(res, filePath, contentType) {
54
+ try {
55
+ const content = fs.readFileSync(filePath);
56
+ res.writeHead(200, {
57
+ "Content-Type": contentType,
58
+ "Access-Control-Allow-Origin": "*",
59
+ // UI assets change with every plugin deploy on a localhost controller;
60
+ // always revalidate so browsers never stick to a stale app.js.
61
+ "Cache-Control": "no-cache",
62
+ });
63
+ res.end(content);
64
+ }
65
+ catch {
66
+ sendError(res, 404, "File not found");
67
+ }
68
+ }
@@ -10,7 +10,9 @@ import { fileURLToPath } from "node:url";
10
10
  import JSON5 from "json5";
11
11
  import { generateId } from "../protocol.js";
12
12
  import { resolveDefaultOpenClawConfigPath, resolveDefaultOpenClawStateDir, resolveDefaultTeamClawRuntimeRootDir, resolveDefaultAgentDir, resolveTeamClawAgentDir, resolveTeamClawAgentWorkspaceRootDir, resolveTeamClawWorkspaceDir, TEAMCLAW_AGENT_ID, } from "../openclaw-workspace.js";
13
- import { ROLES } from "../roles.js";
13
+ // Phase 1.3: the role universe and the fallback role come from the active
14
+ // TeamProfile loader (software-rd baseline).
15
+ import { getActiveRoleIds, getActiveDefaultRole } from "../profile-loader.js";
14
16
  import { inferTaskRole } from "./role-inference.js";
15
17
  const DEFAULT_CONTAINER_WORKER_PORT = 9527;
16
18
  const DEFAULT_CONTAINER_GATEWAY_PORT = 18789;
@@ -28,6 +30,12 @@ export class WorkerProvisioningManager {
28
30
  reconcilePromise = null;
29
31
  reconcileQueued = false;
30
32
  stopped = false;
33
+ // Phase 2.1 (design 2.3, switch step 2): while a team profile switch drains
34
+ // and archives the old team, the periodic reconcile must not fight the
35
+ // drain by launching replacement workers for the outgoing profile's
36
+ // pending tasks. Suspended reconcile calls return immediately; it is
37
+ // lifted before the new profile's warmup so normal operation resumes.
38
+ reconcileSuspended = false;
31
39
  constructor(deps) {
32
40
  this.deps = deps;
33
41
  this.backend = createProvisionerBackend(deps.config, deps.logger);
@@ -148,8 +156,12 @@ export class WorkerProvisioningManager {
148
156
  this.deps.logger.info(`Provisioner: terminating managed worker ${workerId} (${reason})`);
149
157
  await this.terminateManagedWorker(workerId, reason, "terminated");
150
158
  }
159
+ /** Phase 2.1: suspend/resume the reconcile loop during a team profile switch. */
160
+ setReconcileSuspended(suspended) {
161
+ this.reconcileSuspended = suspended;
162
+ }
151
163
  async requestReconcile(reason) {
152
- if (!this.backend || this.stopped) {
164
+ if (!this.backend || this.stopped || this.reconcileSuspended) {
153
165
  return;
154
166
  }
155
167
  if (this.reconcilePromise) {
@@ -235,6 +247,20 @@ export class WorkerProvisioningManager {
235
247
  });
236
248
  this.deps.logger.warn(`Provisioner: startup readiness degraded: ${failureDetails}`);
237
249
  }
250
+ /**
251
+ * Phase 2.1 (design 2.3, switch step 5): warm the new profile's warmupRoles
252
+ * through the standard launch path after a profile switch. Dispatches the
253
+ * launches (prerequisites + ensureWarmWorkersForRoles); the workers then
254
+ * register asynchronously exactly like a cold start, so readiness tracking
255
+ * (startupReadiness polling / reconcile) covers the rest.
256
+ */
257
+ async warmRolesForTeamSwitch(roles, reason) {
258
+ if (!this.backend || this.stopped) {
259
+ return;
260
+ }
261
+ await this.ensureStartupProvisioningPrerequisites();
262
+ await this.ensureWarmWorkersForRoles(roles, reason);
263
+ }
238
264
  async stop() {
239
265
  if (!this.backend) {
240
266
  return;
@@ -302,7 +328,7 @@ export class WorkerProvisioningManager {
302
328
  if (configured.length > 0) {
303
329
  return [...new Set(configured)];
304
330
  }
305
- return ["developer"];
331
+ return [getActiveDefaultRole()];
306
332
  }
307
333
  async ensureStartupProvisioningPrerequisites() {
308
334
  await ensureWritableDirectory(resolveTeamClawAgentWorkspaceRootDir());
@@ -542,7 +568,7 @@ export class WorkerProvisioningManager {
542
568
  getProvisionableRoles(state) {
543
569
  const roleIds = new Set(this.deps.config.workerProvisioningRoles.length > 0
544
570
  ? this.deps.config.workerProvisioningRoles
545
- : ROLES.map((role) => role.id));
571
+ : getActiveRoleIds());
546
572
  if (!state) {
547
573
  return [...roleIds];
548
574
  }
@@ -0,0 +1,188 @@
1
+ import { parseJsonBody, sendError, sendJson } from "../protocol.js";
2
+ import { getActiveDefaultRole, getActiveProfileId, getActiveRoleIds, validateActiveRoleId, } from "../profile-loader.js";
3
+ import { resetTaskForFreshAttempt, serializeTask, } from "./task-execution.js";
4
+ import { autoAssignPendingTasks, scheduleProvisioningReconcile } from "./task-assignment.js";
5
+ // POST /api/v1/workers/register
6
+ export async function handleWorkerRegisterRequest(deps, req, res) {
7
+ const { logger, updateTeamState, wsServer } = deps;
8
+ const body = await parseJsonBody(req);
9
+ const workerId = typeof body.workerId === "string" ? body.workerId : "";
10
+ const rawRole = typeof body.role === "string" ? body.role.trim() : "";
11
+ const role = validateActiveRoleId(rawRole) ?? "";
12
+ const label = typeof body.label === "string" ? body.label : role;
13
+ const workerUrl = typeof body.url === "string" ? body.url : "";
14
+ const capabilities = Array.isArray(body.capabilities) ? body.capabilities : [];
15
+ const launchToken = typeof body.launchToken === "string" ? body.launchToken : undefined;
16
+ if (!workerId || !role || !workerUrl) {
17
+ // Issue #192: a role string that the ACTIVE profile does not know is
18
+ // the actionable failure (worker config carried an id from another
19
+ // profile, or the team switched profiles underneath the worker) - say
20
+ // so with the valid id list instead of the generic "required" 400.
21
+ if (workerId && !role && workerUrl && rawRole) {
22
+ sendError(res, 400, `role "${rawRole}" is not part of the active team profile "${getActiveProfileId()}" (valid roles: ${getActiveRoleIds().join(", ")}). ` +
23
+ "Update the worker's role config to one of these roles, or have the controller switch the team profile.");
24
+ return;
25
+ }
26
+ sendError(res, 400, "workerId, role, and url are required");
27
+ return;
28
+ }
29
+ const registrationValidation = deps.workerProvisioningManager?.validateRegistration(workerId, role, launchToken);
30
+ if (registrationValidation && !registrationValidation.ok) {
31
+ sendError(res, 403, registrationValidation.reason ?? "Worker registration rejected");
32
+ return;
33
+ }
34
+ const state = updateTeamState((s) => {
35
+ s.workers[workerId] = {
36
+ id: workerId,
37
+ role,
38
+ label,
39
+ status: "idle",
40
+ transport: "http",
41
+ url: workerUrl,
42
+ lastHeartbeat: Date.now(),
43
+ capabilities,
44
+ registeredAt: Date.now(),
45
+ };
46
+ });
47
+ deps.workerProvisioningManager?.onWorkerRegistered(workerId);
48
+ wsServer.broadcastUpdate({ type: "worker:online", data: state.workers[workerId] });
49
+ logger.info(`Controller: worker registered - ${label} (${workerId}) at ${workerUrl}`);
50
+ sendJson(res, 201, { status: "registered", worker: state.workers[workerId] });
51
+ void autoAssignPendingTasks(deps, workerId).catch((err) => {
52
+ logger.warn(`Controller: failed to auto-assign after worker registration (${workerId}): ${String(err)}`);
53
+ });
54
+ }
55
+ // DELETE /api/v1/workers/:id
56
+ export async function handleWorkerDeleteRequest(deps, res, pathname) {
57
+ const { logger, getTeamState, updateTeamState, wsServer } = deps;
58
+ const workerId = pathname.split("/").pop();
59
+ if (deps.workerProvisioningManager?.hasManagedWorker(workerId)) {
60
+ await deps.workerProvisioningManager.onWorkerRemoved(workerId, "worker delete requested");
61
+ }
62
+ const affectedTaskIds = [];
63
+ updateTeamState((s) => {
64
+ const worker = s.workers[workerId];
65
+ if (worker) {
66
+ worker.status = "offline";
67
+ worker.currentTaskId = undefined;
68
+ delete s.workers[workerId];
69
+ }
70
+ for (const task of Object.values(s.tasks)) {
71
+ if (task.assignedWorkerId === workerId &&
72
+ task.status !== "completed" &&
73
+ task.status !== "failed" &&
74
+ task.status !== "blocked") {
75
+ task.status = "pending";
76
+ task.assignedWorkerId = undefined;
77
+ resetTaskForFreshAttempt(task);
78
+ task.updatedAt = Date.now();
79
+ affectedTaskIds.push(task.id);
80
+ }
81
+ }
82
+ });
83
+ await autoAssignPendingTasks(deps);
84
+ for (const taskId of affectedTaskIds) {
85
+ const task = getTeamState()?.tasks[taskId];
86
+ if (task) {
87
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(task) });
88
+ }
89
+ }
90
+ wsServer.broadcastUpdate({ type: "worker:offline", data: { workerId } });
91
+ logger.info(`Controller: worker removed - ${workerId}`);
92
+ sendJson(res, 200, { status: "removed" });
93
+ }
94
+ // GET /api/v1/workers
95
+ export async function handleWorkerListRequest(deps, res) {
96
+ const { getTeamState } = deps;
97
+ const state = getTeamState();
98
+ const workers = state
99
+ ? Object.values(state.workers).map((worker) => ({
100
+ ...worker,
101
+ // Ghost rows from previous gateway processes (provisioned workers
102
+ // die with the process they ran in). The controller cleans these on
103
+ // startup; the flag lets the UI mark leftovers as removable.
104
+ staleRemovable: worker.id.startsWith("provisioned-") && worker.status === "offline",
105
+ }))
106
+ : [];
107
+ sendJson(res, 200, { workers });
108
+ }
109
+ // POST /api/v1/workers/:id/heartbeat
110
+ export async function handleWorkerHeartbeatRequest(deps, req, res, pathname) {
111
+ const { updateTeamState } = deps;
112
+ const workerId = pathname.split("/")[4];
113
+ const body = await parseJsonBody(req);
114
+ const status = typeof body.status === "string" ? body.status : "idle";
115
+ const currentTaskId = typeof body.currentTaskId === "string" ? body.currentTaskId : undefined;
116
+ updateTeamState((s) => {
117
+ if (s.workers[workerId]) {
118
+ s.workers[workerId].lastHeartbeat = Date.now();
119
+ s.workers[workerId].status = status;
120
+ s.workers[workerId].currentTaskId = currentTaskId;
121
+ }
122
+ });
123
+ deps.workerProvisioningManager?.onWorkerHeartbeat(workerId, status);
124
+ if (status === "idle") {
125
+ await autoAssignPendingTasks(deps, workerId);
126
+ }
127
+ else {
128
+ scheduleProvisioningReconcile(deps, `heartbeat:${workerId}:${status}`);
129
+ }
130
+ sendJson(res, 200, { status: "ok" });
131
+ }
132
+ export function getEffectiveStartupReadiness(deps, state) {
133
+ if (!deps.workerProvisioningManager?.isEnabled()) {
134
+ return null;
135
+ }
136
+ // Both branches are already-validated RoleId sources: config roles go
137
+ // through parseRoleList (validateRoleIdList) and the fallback is the
138
+ // active profile's defaultRole — no runtime validation needed here.
139
+ const requiredRoles = deps.config.workerProvisioningRoles.length > 0
140
+ ? [...new Set(deps.config.workerProvisioningRoles)]
141
+ : [getActiveDefaultRole()];
142
+ const readyWorkerIds = requiredRoles
143
+ .map((role) => Object.values(state?.workers ?? {}).find((worker) => worker.role === role && (worker.status === "idle" || worker.status === "busy"))?.id)
144
+ .filter((workerId) => Boolean(workerId));
145
+ if (readyWorkerIds.length === requiredRoles.length) {
146
+ const recorded = state?.provisioning?.startupReadiness;
147
+ return {
148
+ status: "ready",
149
+ startedAt: recorded?.startedAt ?? state?.createdAt ?? Date.now(),
150
+ checkedAt: Date.now(),
151
+ attempts: recorded?.attempts ?? 0,
152
+ requiredRoles,
153
+ readyWorkerIds,
154
+ message: recorded?.status === "ready"
155
+ ? recorded.message
156
+ : `Startup provisioning ready with ${readyWorkerIds.length} warm worker(s).`,
157
+ };
158
+ }
159
+ return state?.provisioning?.startupReadiness ?? {
160
+ status: "checking",
161
+ startedAt: state?.createdAt ?? Date.now(),
162
+ checkedAt: Date.now(),
163
+ attempts: 0,
164
+ requiredRoles,
165
+ readyWorkerIds,
166
+ message: `Startup provisioning warm-up is still initializing for ${requiredRoles.join(", ")}.`,
167
+ };
168
+ }
169
+ export function buildStartupReadinessMessage(readiness) {
170
+ const requiredRoles = readiness.requiredRoles.length > 0 ? readiness.requiredRoles.join(", ") : "configured startup roles";
171
+ if (readiness.status === "ready") {
172
+ return readiness.message ?? "Startup provisioning is ready.";
173
+ }
174
+ if (readiness.status === "checking") {
175
+ return readiness.message ?? `Startup provisioning is still warming workers for ${requiredRoles}.`;
176
+ }
177
+ return readiness.message ?? `Startup provisioning is degraded for ${requiredRoles}. Check provisioning logs and fix worker startup before retrying.`;
178
+ }
179
+ export function shouldBlockControllerUntilProvisioningReady(deps, state) {
180
+ const readiness = getEffectiveStartupReadiness(deps, state);
181
+ if (!readiness) {
182
+ return { blocked: false, readiness: null };
183
+ }
184
+ return {
185
+ blocked: readiness.status !== "ready",
186
+ readiness,
187
+ };
188
+ }
@@ -1,6 +1,7 @@
1
1
  import os from "node:os";
2
2
  import { generateId, createRegistrationRequest } from "./protocol.js";
3
- import { getRole } from "./roles.js";
3
+ // Phase 1.3: the worker role label/icon come from the active TeamProfile.
4
+ import { getActiveRole } from "./profile-loader.js";
4
5
  import { loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity } from "./state.js";
5
6
  import { MDnsBrowser } from "./discovery.js";
6
7
  function getLocalIp(targetHost) {
@@ -72,7 +73,7 @@ export class IdentityManager {
72
73
  this.logger.warn("Identity: no controller found via mDNS or manual URL");
73
74
  return null;
74
75
  }
75
- const roleDef = getRole(this.config.role);
76
+ const roleDef = getActiveRole(this.config.role);
76
77
  const workerId = requestedWorkerId ?? generateId();
77
78
  const controllerHost = new URL(controllerUrl).hostname;
78
79
  // Prefer explicit override (set by provisioner for Docker/K8s workers),
@@ -1,6 +1,7 @@
1
- import { ROLES } from "./roles.js";
1
+ // Phase 1.3: runtime role legitimacy is checked against the active
2
+ // TeamProfile (software-rd baseline); roles.ts keeps the registry-layer guard.
3
+ import { validateActiveRoleId } from "./profile-loader.js";
2
4
  const CONTRACT_VERSION = "1.0";
3
- const ROLE_IDS = new Set(ROLES.map((role) => role.id));
4
5
  const RESULT_DELIVERABLE_KINDS = new Set([
5
6
  "file",
6
7
  "directory",
@@ -39,11 +40,10 @@ export function normalizeOptionalContractText(raw) {
39
40
  return normalized || undefined;
40
41
  }
41
42
  export function normalizeContractRole(raw) {
42
- if (typeof raw !== "string") {
43
- return undefined;
44
- }
45
- const normalized = raw.trim();
46
- return normalized && ROLE_IDS.has(normalized) ? normalized : undefined;
43
+ // Phase 0.3 introduced single-source role validation; Phase 1.3 moved the
44
+ // runtime check to the active TeamProfile (validateActiveRoleId). This
45
+ // exported name keeps the contract-level API stable.
46
+ return validateActiveRoleId(raw);
47
47
  }
48
48
  export function summarizeContractText(text, maxChars = 180) {
49
49
  const normalized = text.replace(/\s+/g, " ").trim();
@@ -7,6 +7,9 @@ import fs from "node:fs/promises";
7
7
  import os from "node:os";
8
8
  import path from "node:path";
9
9
  import JSON5 from "json5";
10
+ // Dependency-free canonical role id list (Phase 1.2); see role-ids.ts for why
11
+ // this module cannot value-import roles.ts.
12
+ import { ROLE_IDS } from "./role-ids.js";
10
13
  export const TEAMCLAW_AGENT_ID = "teamclaw";
11
14
  export const TEAMCLAW_ISOLATION_MODE_INDEPENDENT = "independent";
12
15
  export const TEAMCLAW_ISOLATION_MODE_MAIN = "main";
@@ -219,19 +222,26 @@ export function resolveTeamClawAgentDir(env = process.env, homedir = os.homedir)
219
222
  }
220
223
  /**
221
224
  * OpenClaw 2026.10+ moved model-provider auth out of the legacy per-agent
222
- * `auth-profiles.json` file and into the host config (models.providers[*]
223
- * with apiKey/auth, optionally backed by the secrets store). Treat a host
224
- * config with provider auth as ready so the readiness gate does not false-
225
- * negative on current hosts.
225
+ * `auth-profiles.json` file and into the host config. Two host shapes exist:
226
+ * 2026.10 wrote `models.providers[*]` with apiKey/auth (optionally backed by
227
+ * the secrets store); 2026.11 onboard writes `auth.profiles[*]` entries
228
+ * (`provider` + `mode`, the secret itself in the secrets store) and models
229
+ * reference profiles via the `<model>@<profile>` suffix. Treat either shape
230
+ * as ready so the readiness gate does not false-negative on current hosts.
226
231
  */
227
232
  function hostConfiguredProviderAuthExists(env = process.env, homedir = os.homedir) {
228
233
  try {
229
234
  const configPath = resolveDefaultOpenClawConfigPath(env, homedir);
230
235
  const parsed = JSON.parse(readFileSync(configPath, "utf8"));
231
236
  const providers = parsed.models?.providers ?? parsed.providers ?? {};
232
- return Object.values(providers).some((value) => Boolean(value) &&
237
+ const inlineProviderAuth = Object.values(providers).some((value) => Boolean(value) &&
233
238
  typeof value === "object" &&
234
239
  ("apiKey" in value || "auth" in value));
240
+ if (inlineProviderAuth) {
241
+ return true;
242
+ }
243
+ const authProfiles = Object.values(parsed.auth?.profiles ?? {});
244
+ return authProfiles.some((value) => Boolean(value) && typeof value === "object");
235
245
  }
236
246
  catch {
237
247
  return false;
@@ -401,19 +411,31 @@ export async function updateTeamClawWorkspaceDir(workspaceDir, logger, env = pro
401
411
  logger?.warn?.(`TeamClaw: workspace updated to ${normalized} (restart the gateway to apply)`);
402
412
  return { configPath, agentEntryPath: normalized };
403
413
  }
404
- const TEAMCLAW_ROLE_CATALOG = [
405
- { id: "pm", label: "Project Manager" },
406
- { id: "architect", label: "Architect" },
407
- { id: "developer", label: "Developer" },
408
- { id: "qa", label: "QA Engineer" },
409
- { id: "release-engineer", label: "Release Engineer" },
410
- { id: "infra-engineer", label: "Infra Engineer" },
411
- { id: "devops", label: "DevOps Engineer" },
412
- { id: "security-engineer", label: "Security Engineer" },
413
- { id: "designer", label: "Designer" },
414
- { id: "marketing", label: "Marketing" },
415
- { id: "data-engineer", label: "Data Engineer" },
416
- ];
414
+ // Phase 1.2: the catalog's id set and order derive from the canonical
415
+ // role-ids.ts list (openclaw-workspace.ts sits below roles.ts in the module
416
+ // graph, so it cannot value-import the registry itself). The labels are the
417
+ // compact names the model-settings dialog has always shown; they
418
+ // intentionally differ from the full registry labels in roles.ts (e.g.
419
+ // "Project Manager" vs "Product Manager"), so they stay explicit here.
420
+ // tests/test-role-single-source.mjs pins the derived output to the exact
421
+ // pre-Phase-1.2 value.
422
+ const TEAMCLAW_ROLE_CATALOG_LABELS = {
423
+ pm: "Project Manager",
424
+ architect: "Architect",
425
+ developer: "Developer",
426
+ qa: "QA Engineer",
427
+ "release-engineer": "Release Engineer",
428
+ "infra-engineer": "Infra Engineer",
429
+ devops: "DevOps Engineer",
430
+ "security-engineer": "Security Engineer",
431
+ designer: "Designer",
432
+ marketing: "Marketing",
433
+ "data-engineer": "Data Engineer",
434
+ };
435
+ export const TEAMCLAW_ROLE_CATALOG = ROLE_IDS.map((id) => ({
436
+ id,
437
+ label: TEAMCLAW_ROLE_CATALOG_LABELS[id] ?? id,
438
+ }));
417
439
  /**
418
440
  * Model catalog for the UI settings dialog: provider/model ids from the host
419
441
  * config (names only - never secrets), plus the current teamclaw default and