@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,121 @@
1
+ // PR-B of issue #204 (http-server monolith split): the TeamAuto route
2
+ // handlers extracted verbatim from controller/http-server.ts. Zero behavior
3
+ // change - the route shells in http-server keep the method+pathname matches
4
+ // and call these functions with the same deps object as before. This module
5
+ // must NEVER import http-server (the reverse edge exists:
6
+ // http-server -> teamauto-routes); the scheduler and the GitHub auth manager
7
+ // arrive through the deps slice and direct peer imports below.
8
+ import type { IncomingMessage, ServerResponse } from "node:http";
9
+ import type { PluginLogger } from "../../api.js";
10
+ import type { PluginConfig } from "../types.js";
11
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
12
+ import { getGithubAuthManager } from "./github-auth.js";
13
+ import { createGithubClient } from "../teamauto/github-client.js";
14
+ import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
15
+
16
+ /**
17
+ * Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
18
+ * the fields the TeamAuto route handlers read. http-server keeps passing its
19
+ * full ControllerHttpDeps object; TypeScript structural typing accepts it,
20
+ * so no call site changes beyond the import path.
21
+ */
22
+ export type TeamAutoRouteDeps = {
23
+ config: PluginConfig;
24
+ logger: PluginLogger;
25
+ /** Late-bound TeamAuto scheduler (autonomous repo collaboration). */
26
+ getTeamAutoScheduler?: () => TeamAutoScheduler | null;
27
+ };
28
+
29
+ export async function handleTeamAutoActivityRequest(deps: TeamAutoRouteDeps, res: ServerResponse): Promise<void> {
30
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
31
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
32
+ try {
33
+ const activity = await teamAuto.getActivity();
34
+ sendJson(res, 200, { activity });
35
+ } catch (err) {
36
+ sendError(res, 500, err instanceof Error ? err.message : "failed to load activity");
37
+ }
38
+ }
39
+
40
+ export async function handleTeamAutoReposListRequest(deps: TeamAutoRouteDeps, res: ServerResponse): Promise<void> {
41
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
42
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
43
+ try {
44
+ sendJson(res, 200, await teamAuto.getStatus());
45
+ } catch (err) {
46
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read TeamAuto status");
47
+ }
48
+ }
49
+
50
+ // Selectable repos for the bind picker (the logged-in GitHub account's).
51
+ export async function handleTeamAutoRepoCandidatesRequest(deps: TeamAutoRouteDeps, res: ServerResponse): Promise<void> {
52
+ try {
53
+ const auth = getGithubAuthManager(deps.config, deps.logger);
54
+ const candidates = await createGithubClient(auth).listUserRepos();
55
+ sendJson(res, 200, { candidates });
56
+ } catch (err) {
57
+ sendError(res, 400, err instanceof Error ? err.message : "failed to list repositories");
58
+ }
59
+ }
60
+
61
+ export async function handleTeamAutoRepoBindRequest(deps: TeamAutoRouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
62
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
63
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
64
+ let body: Record<string, unknown> = {};
65
+ try { body = await parseJsonBody(req); } catch { /* empty body */ }
66
+ const repo = typeof body.repo === "string" ? body.repo : "";
67
+ if (!repo) { sendError(res, 400, "repo (owner/name) is required"); return; }
68
+ try {
69
+ const created = await teamAuto.addRepo(repo, {
70
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
71
+ keywordInclude: Array.isArray(body.keywordInclude) ? body.keywordInclude.filter((k): k is string => typeof k === "string") : undefined,
72
+ keywordExclude: Array.isArray(body.keywordExclude) ? body.keywordExclude.filter((k): k is string => typeof k === "string") : undefined,
73
+ });
74
+ sendJson(res, 201, created);
75
+ } catch (err) {
76
+ sendError(res, 400, err instanceof Error ? err.message : "failed to bind repo");
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Per-repo actions under /api/v1/teamauto/repos/:id (DELETE unbind / PATCH
82
+ * update / POST :id/sweep). Returns false when the method does not match any
83
+ * action, leaving the request to fall through to the dispatcher's 404 exactly
84
+ * as the inline block did.
85
+ */
86
+ export async function handleTeamAutoRepoItemRequest(
87
+ deps: TeamAutoRouteDeps,
88
+ req: IncomingMessage,
89
+ res: ServerResponse,
90
+ pathname: string,
91
+ ): Promise<boolean> {
92
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
93
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return true; }
94
+ const repoId = decodeURIComponent(pathname.slice("/api/v1/teamauto/repos/".length).replace(/\/sweep$/, ""));
95
+ const isSweep = pathname.endsWith("/sweep");
96
+ if (req.method === "DELETE" && !isSweep) {
97
+ try { await teamAuto.removeRepo(repoId); sendJson(res, 200, { ok: true }); }
98
+ catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to unbind"); }
99
+ return true;
100
+ }
101
+ if (req.method === "PATCH" && !isSweep) {
102
+ let body: Record<string, unknown> = {};
103
+ try { body = await parseJsonBody(req); } catch { /* empty */ }
104
+ try {
105
+ const updated = await teamAuto.updateRepo(repoId, {
106
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
107
+ maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
108
+ fullReview: body.fullReview === "off" || body.fullReview === "weekly" || body.fullReview === "daily" ? body.fullReview : undefined,
109
+ takeOwnership: typeof body.takeOwnership === "boolean" ? body.takeOwnership : undefined,
110
+ });
111
+ sendJson(res, 200, updated);
112
+ } catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to update"); }
113
+ return true;
114
+ }
115
+ if (req.method === "POST" && isSweep) {
116
+ try { sendJson(res, 200, { summary: await teamAuto.runSweepNow(repoId, true) }); }
117
+ catch (err) { sendError(res, 400, err instanceof Error ? err.message : "sweep failed"); }
118
+ return true;
119
+ }
120
+ return false;
121
+ }
@@ -0,0 +1,70 @@
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 type { ServerResponse } from "node:http";
8
+ import { sendError } from "../protocol.js";
9
+
10
+ // Tunnel/CDN caches rewrite the origin's Cache-Control: no-cache into a long
11
+ // browser freeze for cacheable extensions like .js (observed: Cloudflare
12
+ // Browser Cache TTL max-age=14400 on tunneled UI assets). A UI update then
13
+ // never reaches visitors through the tunnel. Serving content-versioned URLs
14
+ // (?v=<hash>) makes every UI deploy a URL no browser or edge has ever seen,
15
+ // so stale-cache behavior cannot recur.
16
+ const uiAssetVersionCache = new Map<string, { mtimeMs: number; version: string }>();
17
+
18
+ function uiAssetVersion(uiPath: string, file: string): string {
19
+ const full = path.join(uiPath, file);
20
+ try {
21
+ const mtimeMs = fs.statSync(full).mtimeMs;
22
+ const cached = uiAssetVersionCache.get(full);
23
+ if (cached && cached.mtimeMs === mtimeMs) return cached.version;
24
+ const version = createHash("sha1").update(fs.readFileSync(full)).digest("hex").slice(0, 10);
25
+ uiAssetVersionCache.set(full, { mtimeMs, version });
26
+ return version;
27
+ } catch {
28
+ return String(Date.now()); // unreadable asset: bust for this request
29
+ }
30
+ }
31
+
32
+ const UI_HTML_ASSET_REFS = [
33
+ "/ui/style.css",
34
+ "/ui/app.js",
35
+ "/ui/assets/teamclaw-app-icon.png",
36
+ ];
37
+
38
+ export function serveVersionedHtml(res: ServerResponse, htmlPath: string): void {
39
+ try {
40
+ const uiPath = path.dirname(htmlPath);
41
+ let html = fs.readFileSync(htmlPath, "utf8");
42
+ for (const ref of UI_HTML_ASSET_REFS) {
43
+ html = html.split(`"${ref}"`).join(`"${ref}?v=${uiAssetVersion(uiPath, ref.slice("/ui/".length))}"`);
44
+ }
45
+ res.writeHead(200, {
46
+ "Content-Type": "text/html; charset=utf-8",
47
+ "Access-Control-Allow-Origin": "*",
48
+ "Cache-Control": "no-cache",
49
+ });
50
+ res.end(html);
51
+ } catch {
52
+ sendError(res, 404, "File not found");
53
+ }
54
+ }
55
+
56
+ export function serveStaticFile(res: ServerResponse, filePath: string, contentType: string): void {
57
+ try {
58
+ const content = fs.readFileSync(filePath);
59
+ res.writeHead(200, {
60
+ "Content-Type": contentType,
61
+ "Access-Control-Allow-Origin": "*",
62
+ // UI assets change with every plugin deploy on a localhost controller;
63
+ // always revalidate so browsers never stick to a stale app.js.
64
+ "Cache-Control": "no-cache",
65
+ });
66
+ res.end(content);
67
+ } catch {
68
+ sendError(res, 404, "File not found");
69
+ }
70
+ }
@@ -20,7 +20,19 @@ export type WsEvent =
20
20
  | { type: "project:deleted"; data: unknown }
21
21
  | { type: "requirement:complete"; data: unknown }
22
22
  | { type: "report:ready"; data: unknown }
23
- | { type: "teamauto:activity"; data: unknown };
23
+ | { type: "teamauto:activity"; data: unknown }
24
+ // Phase 2.2 (design sections 2.3/4): team profile switch lifecycle. Event
25
+ // names follow the design document verbatim (dot-separated) rather than the
26
+ // colon convention used by the domain events above - they are the external
27
+ // contract UI/desktop/workers will subscribe to.
28
+ | { type: "team.switch_started"; data: { profileId: string; previousProfileId: string } }
29
+ | { type: "team.switch_completed"; data: { profileId: string } }
30
+ // Phase 2 follow-up (#201 review): the switch failed mid-flight. Broadcast
31
+ // BEFORE the transition is cleared so UI waiters see the failure instead of
32
+ // silently timing out on reconcile. `reason` states the honest worst case:
33
+ // once the step-3 archive write has landed, the team may be partially
34
+ // switched and a restart is the reliable way back to a known-good team.
35
+ | { type: "team.switch_failed"; data: { previousProfileId: string; targetProfileId: string; reason: string } };
24
36
 
25
37
  export class TeamWebSocketServer {
26
38
  private wss: WebSocketServer | null = null;
@@ -20,7 +20,9 @@ import {
20
20
  resolveTeamClawWorkspaceDir,
21
21
  TEAMCLAW_AGENT_ID,
22
22
  } from "../openclaw-workspace.js";
23
- import { ROLES } from "../roles.js";
23
+ // Phase 1.3: the role universe and the fallback role come from the active
24
+ // TeamProfile loader (software-rd baseline).
25
+ import { getActiveRoleIds, getActiveDefaultRole } from "../profile-loader.js";
24
26
  import { inferTaskRole } from "./role-inference.js";
25
27
  import type {
26
28
  PluginConfig,
@@ -87,6 +89,12 @@ export class WorkerProvisioningManager {
87
89
  private reconcilePromise: Promise<void> | null = null;
88
90
  private reconcileQueued = false;
89
91
  private stopped = false;
92
+ // Phase 2.1 (design 2.3, switch step 2): while a team profile switch drains
93
+ // and archives the old team, the periodic reconcile must not fight the
94
+ // drain by launching replacement workers for the outgoing profile's
95
+ // pending tasks. Suspended reconcile calls return immediately; it is
96
+ // lifted before the new profile's warmup so normal operation resumes.
97
+ private reconcileSuspended = false;
90
98
 
91
99
  constructor(deps: WorkerProvisioningManagerDeps) {
92
100
  this.deps = deps;
@@ -225,8 +233,13 @@ export class WorkerProvisioningManager {
225
233
  await this.terminateManagedWorker(workerId, reason, "terminated");
226
234
  }
227
235
 
236
+ /** Phase 2.1: suspend/resume the reconcile loop during a team profile switch. */
237
+ setReconcileSuspended(suspended: boolean): void {
238
+ this.reconcileSuspended = suspended;
239
+ }
240
+
228
241
  async requestReconcile(reason: string): Promise<void> {
229
- if (!this.backend || this.stopped) {
242
+ if (!this.backend || this.stopped || this.reconcileSuspended) {
230
243
  return;
231
244
  }
232
245
 
@@ -324,6 +337,21 @@ export class WorkerProvisioningManager {
324
337
  this.deps.logger.warn(`Provisioner: startup readiness degraded: ${failureDetails}`);
325
338
  }
326
339
 
340
+ /**
341
+ * Phase 2.1 (design 2.3, switch step 5): warm the new profile's warmupRoles
342
+ * through the standard launch path after a profile switch. Dispatches the
343
+ * launches (prerequisites + ensureWarmWorkersForRoles); the workers then
344
+ * register asynchronously exactly like a cold start, so readiness tracking
345
+ * (startupReadiness polling / reconcile) covers the rest.
346
+ */
347
+ async warmRolesForTeamSwitch(roles: RoleId[], reason: string): Promise<void> {
348
+ if (!this.backend || this.stopped) {
349
+ return;
350
+ }
351
+ await this.ensureStartupProvisioningPrerequisites();
352
+ await this.ensureWarmWorkersForRoles(roles, reason);
353
+ }
354
+
327
355
  async stop(): Promise<void> {
328
356
  if (!this.backend) {
329
357
  return;
@@ -408,7 +436,7 @@ export class WorkerProvisioningManager {
408
436
  if (configured.length > 0) {
409
437
  return [...new Set(configured)];
410
438
  }
411
- return ["developer"];
439
+ return [getActiveDefaultRole()];
412
440
  }
413
441
 
414
442
  private async ensureStartupProvisioningPrerequisites(): Promise<void> {
@@ -695,7 +723,7 @@ export class WorkerProvisioningManager {
695
723
  const roleIds = new Set<RoleId>(
696
724
  this.deps.config.workerProvisioningRoles.length > 0
697
725
  ? this.deps.config.workerProvisioningRoles
698
- : ROLES.map((role) => role.id),
726
+ : getActiveRoleIds(),
699
727
  );
700
728
 
701
729
  if (!state) {
@@ -0,0 +1,241 @@
1
+ // PR-C of issue #204 (http-server monolith split): the worker lifecycle
2
+ // routes (register/heartbeat/delete/list) and the startup provisioning
3
+ // readiness gate extracted verbatim from controller/http-server.ts. Zero
4
+ // behavior change - the route shells in http-server keep the method+pathname
5
+ // matches and call these handlers with the same deps object as before. This
6
+ // module must NEVER import http-server (the reverse edge exists:
7
+ // http-server -> worker-routes).
8
+ import type { IncomingMessage, ServerResponse } from "node:http";
9
+ import type {
10
+ StartupProvisioningReadiness,
11
+ TeamState,
12
+ WorkerInfo,
13
+ } from "../types.js";
14
+ import { parseJsonBody, sendError, sendJson } from "../protocol.js";
15
+ import {
16
+ getActiveDefaultRole,
17
+ getActiveProfileId,
18
+ getActiveRoleIds,
19
+ validateActiveRoleId,
20
+ } from "../profile-loader.js";
21
+ import {
22
+ resetTaskForFreshAttempt,
23
+ serializeTask,
24
+ type ControllerTaskDomainDeps,
25
+ } from "./task-execution.js";
26
+ import { autoAssignPendingTasks, scheduleProvisioningReconcile } from "./task-assignment.js";
27
+
28
+ // POST /api/v1/workers/register
29
+ export async function handleWorkerRegisterRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
30
+ const { logger, updateTeamState, wsServer } = deps;
31
+ const body = await parseJsonBody(req);
32
+ const workerId = typeof body.workerId === "string" ? body.workerId : "";
33
+ const rawRole = typeof body.role === "string" ? body.role.trim() : "";
34
+ const role = validateActiveRoleId(rawRole) ?? "";
35
+ const label = typeof body.label === "string" ? body.label : role;
36
+ const workerUrl = typeof body.url === "string" ? body.url : "";
37
+ const capabilities = Array.isArray(body.capabilities) ? body.capabilities as string[] : [];
38
+ const launchToken = typeof body.launchToken === "string" ? body.launchToken : undefined;
39
+
40
+ if (!workerId || !role || !workerUrl) {
41
+ // Issue #192: a role string that the ACTIVE profile does not know is
42
+ // the actionable failure (worker config carried an id from another
43
+ // profile, or the team switched profiles underneath the worker) - say
44
+ // so with the valid id list instead of the generic "required" 400.
45
+ if (workerId && !role && workerUrl && rawRole) {
46
+ sendError(
47
+ res,
48
+ 400,
49
+ `role "${rawRole}" is not part of the active team profile "${getActiveProfileId()}" (valid roles: ${getActiveRoleIds().join(", ")}). ` +
50
+ "Update the worker's role config to one of these roles, or have the controller switch the team profile.",
51
+ );
52
+ return;
53
+ }
54
+ sendError(res, 400, "workerId, role, and url are required");
55
+ return;
56
+ }
57
+
58
+ const registrationValidation = deps.workerProvisioningManager?.validateRegistration(workerId, role, launchToken);
59
+ if (registrationValidation && !registrationValidation.ok) {
60
+ sendError(res, 403, registrationValidation.reason ?? "Worker registration rejected");
61
+ return;
62
+ }
63
+
64
+ const state = updateTeamState((s) => {
65
+ s.workers[workerId] = {
66
+ id: workerId,
67
+ role,
68
+ label,
69
+ status: "idle",
70
+ transport: "http",
71
+ url: workerUrl,
72
+ lastHeartbeat: Date.now(),
73
+ capabilities,
74
+ registeredAt: Date.now(),
75
+ };
76
+ });
77
+ deps.workerProvisioningManager?.onWorkerRegistered(workerId);
78
+
79
+ wsServer.broadcastUpdate({ type: "worker:online", data: state.workers[workerId] });
80
+ logger.info(`Controller: worker registered - ${label} (${workerId}) at ${workerUrl}`);
81
+ sendJson(res, 201, { status: "registered", worker: state.workers[workerId] });
82
+ void autoAssignPendingTasks(deps, workerId).catch((err) => {
83
+ logger.warn(`Controller: failed to auto-assign after worker registration (${workerId}): ${String(err)}`);
84
+ });
85
+ }
86
+
87
+ // DELETE /api/v1/workers/:id
88
+ export async function handleWorkerDeleteRequest(deps: ControllerTaskDomainDeps, res: ServerResponse, pathname: string): Promise<void> {
89
+ const { logger, getTeamState, updateTeamState, wsServer } = deps;
90
+ const workerId = pathname.split("/").pop()!;
91
+ if (deps.workerProvisioningManager?.hasManagedWorker(workerId)) {
92
+ await deps.workerProvisioningManager.onWorkerRemoved(workerId, "worker delete requested");
93
+ }
94
+
95
+ const affectedTaskIds: string[] = [];
96
+ updateTeamState((s) => {
97
+ const worker = s.workers[workerId];
98
+ if (worker) {
99
+ worker.status = "offline";
100
+ worker.currentTaskId = undefined;
101
+ delete s.workers[workerId];
102
+ }
103
+
104
+ for (const task of Object.values(s.tasks)) {
105
+ if (
106
+ task.assignedWorkerId === workerId &&
107
+ task.status !== "completed" &&
108
+ task.status !== "failed" &&
109
+ task.status !== "blocked"
110
+ ) {
111
+ task.status = "pending";
112
+ task.assignedWorkerId = undefined;
113
+ resetTaskForFreshAttempt(task);
114
+ task.updatedAt = Date.now();
115
+ affectedTaskIds.push(task.id);
116
+ }
117
+ }
118
+ });
119
+
120
+ await autoAssignPendingTasks(deps);
121
+ for (const taskId of affectedTaskIds) {
122
+ const task = getTeamState()?.tasks[taskId];
123
+ if (task) {
124
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(task) });
125
+ }
126
+ }
127
+ wsServer.broadcastUpdate({ type: "worker:offline", data: { workerId } });
128
+ logger.info(`Controller: worker removed - ${workerId}`);
129
+ sendJson(res, 200, { status: "removed" });
130
+ }
131
+
132
+ // GET /api/v1/workers
133
+ export async function handleWorkerListRequest(deps: ControllerTaskDomainDeps, res: ServerResponse): Promise<void> {
134
+ const { getTeamState } = deps;
135
+ const state = getTeamState();
136
+ const workers = state
137
+ ? Object.values(state.workers).map((worker) => ({
138
+ ...worker,
139
+ // Ghost rows from previous gateway processes (provisioned workers
140
+ // die with the process they ran in). The controller cleans these on
141
+ // startup; the flag lets the UI mark leftovers as removable.
142
+ staleRemovable: worker.id.startsWith("provisioned-") && worker.status === "offline",
143
+ }))
144
+ : [];
145
+ sendJson(res, 200, { workers });
146
+ }
147
+
148
+ // POST /api/v1/workers/:id/heartbeat
149
+ export async function handleWorkerHeartbeatRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
150
+ const { updateTeamState } = deps;
151
+ const workerId = pathname.split("/")[4]!;
152
+ const body = await parseJsonBody(req);
153
+ const status = typeof body.status === "string" ? body.status as WorkerInfo["status"] : "idle";
154
+ const currentTaskId = typeof body.currentTaskId === "string" ? body.currentTaskId : undefined;
155
+
156
+ updateTeamState((s) => {
157
+ if (s.workers[workerId]) {
158
+ s.workers[workerId].lastHeartbeat = Date.now();
159
+ s.workers[workerId].status = status;
160
+ s.workers[workerId].currentTaskId = currentTaskId;
161
+ }
162
+ });
163
+ deps.workerProvisioningManager?.onWorkerHeartbeat(workerId, status);
164
+
165
+ if (status === "idle") {
166
+ await autoAssignPendingTasks(deps, workerId);
167
+ } else {
168
+ scheduleProvisioningReconcile(deps, `heartbeat:${workerId}:${status}`);
169
+ }
170
+ sendJson(res, 200, { status: "ok" });
171
+ }
172
+
173
+ export function getEffectiveStartupReadiness(
174
+ deps: ControllerTaskDomainDeps,
175
+ state: TeamState | null,
176
+ ): StartupProvisioningReadiness | null {
177
+ if (!deps.workerProvisioningManager?.isEnabled()) {
178
+ return null;
179
+ }
180
+ // Both branches are already-validated RoleId sources: config roles go
181
+ // through parseRoleList (validateRoleIdList) and the fallback is the
182
+ // active profile's defaultRole — no runtime validation needed here.
183
+ const requiredRoles = deps.config.workerProvisioningRoles.length > 0
184
+ ? [...new Set(deps.config.workerProvisioningRoles)]
185
+ : [getActiveDefaultRole()];
186
+ const readyWorkerIds = requiredRoles
187
+ .map((role) => Object.values(state?.workers ?? {}).find((worker) =>
188
+ worker.role === role && (worker.status === "idle" || worker.status === "busy")
189
+ )?.id)
190
+ .filter((workerId): workerId is string => Boolean(workerId));
191
+
192
+ if (readyWorkerIds.length === requiredRoles.length) {
193
+ const recorded = state?.provisioning?.startupReadiness;
194
+ return {
195
+ status: "ready",
196
+ startedAt: recorded?.startedAt ?? state?.createdAt ?? Date.now(),
197
+ checkedAt: Date.now(),
198
+ attempts: recorded?.attempts ?? 0,
199
+ requiredRoles,
200
+ readyWorkerIds,
201
+ message: recorded?.status === "ready"
202
+ ? recorded.message
203
+ : `Startup provisioning ready with ${readyWorkerIds.length} warm worker(s).`,
204
+ };
205
+ }
206
+
207
+ return state?.provisioning?.startupReadiness ?? {
208
+ status: "checking",
209
+ startedAt: state?.createdAt ?? Date.now(),
210
+ checkedAt: Date.now(),
211
+ attempts: 0,
212
+ requiredRoles,
213
+ readyWorkerIds,
214
+ message: `Startup provisioning warm-up is still initializing for ${requiredRoles.join(", ")}.`,
215
+ };
216
+ }
217
+
218
+ export function buildStartupReadinessMessage(readiness: StartupProvisioningReadiness): string {
219
+ const requiredRoles = readiness.requiredRoles.length > 0 ? readiness.requiredRoles.join(", ") : "configured startup roles";
220
+ if (readiness.status === "ready") {
221
+ return readiness.message ?? "Startup provisioning is ready.";
222
+ }
223
+ if (readiness.status === "checking") {
224
+ return readiness.message ?? `Startup provisioning is still warming workers for ${requiredRoles}.`;
225
+ }
226
+ return readiness.message ?? `Startup provisioning is degraded for ${requiredRoles}. Check provisioning logs and fix worker startup before retrying.`;
227
+ }
228
+
229
+ export function shouldBlockControllerUntilProvisioningReady(
230
+ deps: ControllerTaskDomainDeps,
231
+ state: TeamState | null,
232
+ ): { blocked: boolean; readiness: StartupProvisioningReadiness | null } {
233
+ const readiness = getEffectiveStartupReadiness(deps, state);
234
+ if (!readiness) {
235
+ return { blocked: false, readiness: null };
236
+ }
237
+ return {
238
+ blocked: readiness.status !== "ready",
239
+ readiness,
240
+ };
241
+ }
package/src/identity.ts CHANGED
@@ -2,7 +2,8 @@ import os from "node:os";
2
2
  import type { PluginLogger } from "../api.js";
3
3
  import type { PluginConfig, WorkerIdentity } from "./types.js";
4
4
  import { generateId, createRegistrationRequest } from "./protocol.js";
5
- import { getRole } from "./roles.js";
5
+ // Phase 1.3: the worker role label/icon come from the active TeamProfile.
6
+ import { getActiveRole } from "./profile-loader.js";
6
7
  import { loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity } from "./state.js";
7
8
  import { MDnsBrowser } from "./discovery.js";
8
9
 
@@ -87,7 +88,7 @@ export class IdentityManager {
87
88
  return null;
88
89
  }
89
90
 
90
- const roleDef = getRole(this.config.role);
91
+ const roleDef = getActiveRole(this.config.role);
91
92
  const workerId = requestedWorkerId ?? generateId();
92
93
  const controllerHost = new URL(controllerUrl).hostname;
93
94
  // Prefer explicit override (set by provisioner for Docker/K8s workers),
@@ -1,4 +1,6 @@
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
  import type {
3
5
  RoleId,
4
6
  TaskHandoffContract,
@@ -14,7 +16,6 @@ import type {
14
16
  } from "./types.js";
15
17
 
16
18
  const CONTRACT_VERSION = "1.0";
17
- const ROLE_IDS = new Set<RoleId>(ROLES.map((role) => role.id));
18
19
  const RESULT_DELIVERABLE_KINDS = new Set<WorkerTaskResultDeliverable["kind"]>([
19
20
  "file",
20
21
  "directory",
@@ -56,11 +57,10 @@ export function normalizeOptionalContractText(raw: unknown): string | undefined
56
57
  }
57
58
 
58
59
  export function normalizeContractRole(raw: unknown): RoleId | undefined {
59
- if (typeof raw !== "string") {
60
- return undefined;
61
- }
62
- const normalized = raw.trim() as RoleId;
63
- return normalized && ROLE_IDS.has(normalized) ? normalized : undefined;
60
+ // Phase 0.3 introduced single-source role validation; Phase 1.3 moved the
61
+ // runtime check to the active TeamProfile (validateActiveRoleId). This
62
+ // exported name keeps the contract-level API stable.
63
+ return validateActiveRoleId(raw);
64
64
  }
65
65
 
66
66
  export function summarizeContractText(text: string, maxChars = 180): string {