@teamclaws/teamclaw 2026.8.0 → 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 (149) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/api.js +1 -0
  3. package/dist/index.js +325 -0
  4. package/dist/src/config.js +412 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-capacity.js +14 -0
  7. package/dist/src/controller/controller-intake.js +895 -0
  8. package/dist/src/controller/controller-planning.js +813 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +624 -0
  11. package/dist/src/controller/controller-tools.js +587 -0
  12. package/dist/src/controller/delivery-report.js +458 -0
  13. package/dist/src/controller/github-auth.js +564 -0
  14. package/dist/src/controller/http-server.js +284 -0
  15. package/dist/src/controller/kickoff-orchestrator.js +246 -0
  16. package/dist/src/controller/managed-gateway-process.js +286 -0
  17. package/dist/src/controller/message-delivery.js +28 -0
  18. package/dist/src/controller/message-router.js +38 -0
  19. package/dist/src/controller/message-routes.js +114 -0
  20. package/dist/src/controller/orchestration-manifest.js +151 -0
  21. package/dist/src/controller/preview-manager.js +586 -0
  22. package/dist/src/controller/preview-proxy.js +98 -0
  23. package/dist/src/controller/profile-switch.js +289 -0
  24. package/dist/src/controller/project-registry.js +294 -0
  25. package/dist/src/controller/prompt-injector.js +197 -0
  26. package/dist/src/controller/repo-routes.js +63 -0
  27. package/dist/src/controller/role-inference.js +246 -0
  28. package/dist/src/controller/route-table.js +1353 -0
  29. package/dist/src/controller/task-assignment.js +508 -0
  30. package/dist/src/controller/task-cleanup.js +258 -0
  31. package/dist/src/controller/task-execution.js +240 -0
  32. package/dist/src/controller/task-results.js +461 -0
  33. package/dist/src/controller/task-router.js +137 -0
  34. package/dist/src/controller/task-routes.js +703 -0
  35. package/dist/src/controller/teamauto-routes.js +124 -0
  36. package/dist/src/controller/tunnel-manager.js +548 -0
  37. package/dist/src/controller/ui-assets.js +68 -0
  38. package/dist/src/controller/websocket.js +42 -0
  39. package/dist/src/controller/worker-provisioning.js +1674 -0
  40. package/dist/src/controller/worker-routes.js +188 -0
  41. package/dist/src/discovery.js +86 -0
  42. package/dist/src/git-collaboration.js +694 -0
  43. package/dist/src/identity.js +132 -0
  44. package/dist/src/install-defaults.js +1 -0
  45. package/dist/src/interaction-contracts.js +531 -0
  46. package/dist/src/networking.js +91 -0
  47. package/dist/src/openclaw-workspace.js +925 -0
  48. package/dist/src/profile-loader.js +486 -0
  49. package/dist/src/profiles/banking.json +178 -0
  50. package/dist/src/profiles/crossborder-ecom.json +253 -0
  51. package/dist/src/profiles/insurance.json +157 -0
  52. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  53. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  54. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  55. package/dist/src/profiles/schema.json +201 -0
  56. package/dist/src/profiles/securities.json +137 -0
  57. package/dist/src/profiles/software-rd.json +264 -0
  58. package/dist/src/profiles/trading-co.json +200 -0
  59. package/dist/src/prompt-policy.js +386 -0
  60. package/dist/src/protocol.js +58 -0
  61. package/dist/src/role-ids.js +29 -0
  62. package/dist/src/roles.js +390 -0
  63. package/dist/src/session-roles.js +14 -0
  64. package/dist/src/state.js +361 -0
  65. package/dist/src/task-executor.js +1023 -0
  66. package/dist/src/teamauto/github-client.js +210 -0
  67. package/dist/src/teamauto/norms.js +85 -0
  68. package/dist/src/teamauto/repo-sync.js +423 -0
  69. package/dist/src/teamauto/scanner.js +207 -0
  70. package/dist/src/teamauto/schedule.js +123 -0
  71. package/dist/src/teamauto/scheduler.js +907 -0
  72. package/dist/src/teamauto/store.js +133 -0
  73. package/dist/src/types.js +290 -0
  74. package/dist/src/ui/app.js +4860 -0
  75. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  76. package/dist/src/ui/github-login.html +296 -0
  77. package/dist/src/ui/index.html +447 -0
  78. package/dist/src/ui/style.css +2805 -0
  79. package/dist/src/worker/http-handler.js +146 -0
  80. package/dist/src/worker/message-queue.js +24 -0
  81. package/dist/src/worker/prompt-injector.js +78 -0
  82. package/dist/src/worker/skill-installer.js +255 -0
  83. package/dist/src/worker/tools.js +541 -0
  84. package/dist/src/worker/worker-service.js +307 -0
  85. package/dist/src/workspace-browser.js +269 -0
  86. package/openclaw.plugin.json +28 -1
  87. package/package.json +3 -2
  88. package/src/config.ts +33 -2
  89. package/src/controller/clarification-routes.ts +404 -0
  90. package/src/controller/controller-intake.ts +1113 -0
  91. package/src/controller/controller-planning.ts +1029 -0
  92. package/src/controller/controller-runs.ts +239 -0
  93. package/src/controller/controller-service.ts +295 -41
  94. package/src/controller/controller-tools.ts +11 -7
  95. package/src/controller/http-server.ts +294 -6971
  96. package/src/controller/kickoff-orchestrator.ts +70 -7
  97. package/src/controller/message-delivery.ts +49 -0
  98. package/src/controller/message-routes.ts +137 -0
  99. package/src/controller/orchestration-manifest.ts +6 -29
  100. package/src/controller/preview-proxy.ts +127 -0
  101. package/src/controller/profile-switch.ts +366 -0
  102. package/src/controller/project-registry.ts +361 -0
  103. package/src/controller/prompt-injector.ts +23 -8
  104. package/src/controller/repo-routes.ts +91 -0
  105. package/src/controller/role-inference.ts +260 -22
  106. package/src/controller/route-table.ts +1616 -0
  107. package/src/controller/task-assignment.ts +618 -0
  108. package/src/controller/task-cleanup.ts +344 -0
  109. package/src/controller/task-execution.ts +356 -0
  110. package/src/controller/task-results.ts +544 -0
  111. package/src/controller/task-router.ts +98 -6
  112. package/src/controller/task-routes.ts +812 -0
  113. package/src/controller/teamauto-routes.ts +121 -0
  114. package/src/controller/ui-assets.ts +70 -0
  115. package/src/controller/websocket.ts +13 -1
  116. package/src/controller/worker-provisioning.ts +32 -4
  117. package/src/controller/worker-routes.ts +241 -0
  118. package/src/identity.ts +3 -2
  119. package/src/interaction-contracts.ts +7 -7
  120. package/src/openclaw-workspace.ts +44 -18
  121. package/src/profile-loader.ts +650 -0
  122. package/src/profiles/banking.json +178 -0
  123. package/src/profiles/crossborder-ecom.json +253 -0
  124. package/src/profiles/insurance.json +157 -0
  125. package/src/profiles/knowledge/hs-structure.md +97 -0
  126. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  127. package/src/profiles/knowledge/vat-principles.md +85 -0
  128. package/src/profiles/schema.json +201 -0
  129. package/src/profiles/securities.json +137 -0
  130. package/src/profiles/software-rd.json +264 -0
  131. package/src/profiles/trading-co.json +200 -0
  132. package/src/prompt-policy.ts +27 -13
  133. package/src/role-ids.ts +31 -0
  134. package/src/roles.ts +60 -14
  135. package/src/session-roles.ts +14 -0
  136. package/src/state.ts +236 -9
  137. package/src/task-executor.ts +7 -18
  138. package/src/teamauto/github-client.ts +21 -0
  139. package/src/teamauto/repo-sync.ts +246 -6
  140. package/src/teamauto/scanner.ts +47 -13
  141. package/src/teamauto/scheduler.ts +259 -16
  142. package/src/teamauto/store.ts +12 -0
  143. package/src/types.ts +133 -16
  144. package/src/ui/app.js +592 -24
  145. package/src/ui/index.html +44 -11
  146. package/src/ui/style.css +194 -0
  147. package/src/worker/prompt-injector.ts +48 -8
  148. package/src/worker/skill-installer.ts +3 -1
  149. package/src/worker/worker-service.ts +83 -3
@@ -16,8 +16,11 @@
16
16
  */
17
17
 
18
18
  import type { PluginLogger } from "../../api.js";
19
- import type { KickoffAssessment, KickoffPlan, RoleId, TeamState, WorkerInfo } from "../types.js";
20
- import { getRole, ROLES } from "../roles.js";
19
+ import type { KickoffAssessment, KickoffPlan, RoleId, TaskInfo, TeamState, WorkerInfo } from "../types.js";
20
+ // Phase 1.3: role data comes from the active TeamProfile loader.
21
+ import { getActiveDefaultRole, getActiveRole, getActiveRoleIds, validateActiveRoleId } from "../profile-loader.js";
22
+ import { inferTaskRoleWithConfidence } from "./role-inference.js";
23
+ import type { RoleInferenceVerdict } from "./role-inference.js";
21
24
 
22
25
  // ── Constants ────────────────────────────────────────────────────────────────
23
26
 
@@ -30,7 +33,7 @@ const ASSESSMENT_TIMEOUT_MS = 120_000;
30
33
  /** Poll interval when waiting for workers to appear in state. */
31
34
  const WORKER_POLL_INTERVAL_MS = 2_000;
32
35
 
33
- const VALID_ROLE_IDS = new Set<string>(ROLES.map((r) => r.id));
36
+
34
37
 
35
38
  // ── Types ────────────────────────────────────────────────────────────────────
36
39
 
@@ -65,7 +68,8 @@ export async function runKickoffMeeting(
65
68
  const { requirement, candidateRoles, complexity } = request;
66
69
 
67
70
  // Validate roles
68
- const validRoles = candidateRoles.filter((r) => VALID_ROLE_IDS.has(r));
71
+ // Resolved per call so the set always reflects the active profile.
72
+ const validRoles = candidateRoles.filter((r) => getActiveRoleIds().includes(r));
69
73
  if (validRoles.length === 0) {
70
74
  return buildEmptyResult(complexity, "No valid candidate roles provided.");
71
75
  }
@@ -184,7 +188,7 @@ function buildKickoffSummary(plan: KickoffPlan, _requirement: string): string {
184
188
  if (needed.length > 0) {
185
189
  parts.push("### Roles Confirmed Needed");
186
190
  for (const a of needed) {
187
- const roleDef = getRole(a.role);
191
+ const roleDef = getActiveRole(a.role);
188
192
  const icon = roleDef?.icon ?? "•";
189
193
  parts.push(`\n**${icon} ${roleDef?.label ?? a.role}**`);
190
194
  parts.push(`- Scope: ${a.scope}`);
@@ -207,7 +211,7 @@ function buildKickoffSummary(plan: KickoffPlan, _requirement: string): string {
207
211
  parts.push("");
208
212
  parts.push("### Roles Not Needed");
209
213
  for (const a of notNeeded) {
210
- const roleDef = getRole(a.role);
214
+ const roleDef = getActiveRole(a.role);
211
215
  parts.push(`- ${roleDef?.icon ?? "•"} ${roleDef?.label ?? a.role}: ${a.scope}`);
212
216
  }
213
217
  }
@@ -252,7 +256,7 @@ function buildKickoffSummary(plan: KickoffPlan, _requirement: string): string {
252
256
  * The worker should respond with structured JSON matching KickoffAssessment.
253
257
  */
254
258
  export function buildKickoffAssessmentPrompt(role: RoleId, requirement: string): string {
255
- const roleDef = getRole(role);
259
+ const roleDef = getActiveRole(role);
256
260
  const roleLabel = roleDef?.label ?? role;
257
261
 
258
262
  return [
@@ -289,4 +293,63 @@ function sleep(ms: number): Promise<void> {
289
293
  return new Promise((resolve) => setTimeout(resolve, ms));
290
294
  }
291
295
 
296
+ // ── Phase 2.5: LLM fallback for unconfident role inference (design 2.3) ─────
297
+ //
298
+ // The tiered token scoring in role-inference.ts is the FAST PATH only. When
299
+ // it refuses to decide (all-zero, or the top two roles tie), the role
300
+ // decision escalates to the controller LLM pass - the same LLM-driven intake
301
+ // flow that drives this orchestrator (manifest requiredRoles, kickoff
302
+ // candidateRoles, worker assessments). role-inference stays a pure module,
303
+ // so the escalation lives here behind an injected callback: production
304
+ // callers wire the callback to their controller-LLM session; tests inject a
305
+ // fake. Without a callback the resolver degrades to the profile defaultRole
306
+ // (the Phase 0.1 configurable fallback).
307
+
308
+ export type TaskRoleResolutionDeps = {
309
+ /** Pure token fast path. Injectable so tests can pin the escalation wiring. */
310
+ inferWithConfidence?: typeof inferTaskRoleWithConfidence;
311
+ /**
312
+ * LLM fallback: ask the controller LLM pass to judge the role for the
313
+ * task. Returns a role id (validated against the active profile; invalid
314
+ * or null results fall back to the profile defaultRole).
315
+ * "id" is part of the payload (P2.5 wiring) so production judges can key
316
+ * one-shot sessions and logs by task id.
317
+ */
318
+ llmRoleJudge?: (input: { task: Pick<TaskInfo, "id" | "assignedRole" | "title" | "description">; verdict: RoleInferenceVerdict }) => Promise<RoleId | string | null>;
319
+ logger?: Pick<PluginLogger, "info" | "warn">;
320
+ };
321
+
322
+ export async function resolveTaskRoleWithLlmFallback(
323
+ task: Pick<TaskInfo, "id" | "assignedRole" | "title" | "description">,
324
+ deps: TaskRoleResolutionDeps = {},
325
+ ): Promise<RoleId> {
326
+ const verdict = (deps.inferWithConfidence ?? inferTaskRoleWithConfidence)(task);
327
+ if (!verdict.needsLlmFallback) {
328
+ return verdict.role!;
329
+ }
330
+
331
+ if (deps.llmRoleJudge) {
332
+ try {
333
+ const judged = await deps.llmRoleJudge({ task, verdict });
334
+ const validated = validateActiveRoleId(judged);
335
+ if (validated) {
336
+ deps.logger?.info(
337
+ `RoleInference: LLM fallback judged role ${validated} (token fast path refused: ${verdict.reason})`,
338
+ );
339
+ return validated;
340
+ }
341
+ deps.logger?.warn(
342
+ `RoleInference: LLM fallback returned ${JSON.stringify(judged)} which is not a role of the active profile; using defaultRole`,
343
+ );
344
+ } catch (err) {
345
+ deps.logger?.warn(`RoleInference: LLM fallback failed (${err instanceof Error ? err.message : String(err)}); using defaultRole`);
346
+ }
347
+ } else {
348
+ deps.logger?.info(
349
+ `RoleInference: token fast path refused to decide (${verdict.reason}) and no LLM fallback is wired; using defaultRole`,
350
+ );
351
+ }
352
+ return getActiveDefaultRole();
353
+ }
354
+
292
355
  export { ASSESSMENT_TIMEOUT_MS };
@@ -0,0 +1,49 @@
1
+ // PR-C of issue #204 (http-server monolith split): the worker message
2
+ // delivery helpers extracted verbatim from controller/http-server.ts. Zero
3
+ // behavior change. This module must NEVER import http-server (the reverse
4
+ // edge exists: http-server -> message-delivery); the router and state getter
5
+ // arrive through the deps slice below. Kept separate from the higher-level
6
+ // message ROUTES because the controller-planning intake glue also delivers
7
+ // messages and must stay below the route layer.
8
+ import type { TeamMessage, WorkerInfo } from "../types.js";
9
+ import type { ControllerTaskDomainDeps } from "./task-execution.js";
10
+
11
+ export async function deliverMessageToWorker(
12
+ worker: WorkerInfo,
13
+ message: TeamMessage,
14
+ deps: ControllerTaskDomainDeps,
15
+ ): Promise<void> {
16
+ const res = await fetch(`${worker.url}/api/v1/messages`, {
17
+ method: "POST",
18
+ headers: { "Content-Type": "application/json" },
19
+ body: JSON.stringify(message),
20
+ });
21
+
22
+ if (!res.ok) {
23
+ throw new Error(`worker ${worker.id} responded with ${res.status}`);
24
+ }
25
+ }
26
+
27
+ export async function routeDirectMessage(
28
+ message: TeamMessage,
29
+ deps: ControllerTaskDomainDeps,
30
+ ): Promise<boolean> {
31
+ const { getTeamState, logger, messageRouter } = deps;
32
+ const state = getTeamState();
33
+ if (!state) {
34
+ return false;
35
+ }
36
+
37
+ const routed = messageRouter.routeDirectMessage(message, state.workers);
38
+ if (!routed) {
39
+ return false;
40
+ }
41
+
42
+ try {
43
+ await deliverMessageToWorker(routed.worker, routed.message, deps);
44
+ } catch (err) {
45
+ logger.warn(`Controller: failed to deliver message to ${routed.worker.id}: ${String(err)}`);
46
+ }
47
+
48
+ return true;
49
+ }
@@ -0,0 +1,137 @@
1
+ // PR-C of issue #204 (http-server monolith split): the team message routes
2
+ // (direct/broadcast/review-request send + list) lifted verbatim from the
3
+ // inline dispatch blocks in controller/http-server.ts. Zero behavior change -
4
+ // the route shells in http-server keep the method+pathname matches and call
5
+ // these handlers with the same deps object as before. This module must NEVER
6
+ // import http-server (the reverse edge exists: http-server -> message-routes).
7
+ import type { IncomingMessage, ServerResponse } from "node:http";
8
+ import type { TeamMessage } from "../types.js";
9
+ import { generateId, parseJsonBody, sendJson } from "../protocol.js";
10
+ import { ensureTeamMessageContract } from "../interaction-contracts.js";
11
+ import { validateActiveRoleId } from "../profile-loader.js";
12
+ import {
13
+ deliverMessageToWorker,
14
+ routeDirectMessage,
15
+ } from "./message-delivery.js";
16
+ import type { ControllerTaskDomainDeps } from "./task-execution.js";
17
+
18
+ // POST /api/v1/messages/direct
19
+ export async function handleDirectMessageRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
20
+ const { updateTeamState, wsServer } = deps;
21
+ const body = await parseJsonBody(req);
22
+ const fromRole = validateActiveRoleId(body.fromRole);
23
+ const toRole = validateActiveRoleId(body.toRole);
24
+ const message: TeamMessage = {
25
+ id: generateId(),
26
+ from: typeof body.from === "string" ? body.from : "",
27
+ fromRole,
28
+ toRole,
29
+ type: "direct",
30
+ content: typeof body.content === "string" ? body.content : "",
31
+ contract: ensureTeamMessageContract(body.contract, {
32
+ type: "direct",
33
+ content: typeof body.content === "string" ? body.content : "",
34
+ toRole,
35
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
36
+ }),
37
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
38
+ createdAt: Date.now(),
39
+ };
40
+
41
+ updateTeamState((s) => { s.messages.push(message); });
42
+
43
+ const routed = await routeDirectMessage(message, deps);
44
+
45
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
46
+ sendJson(res, 201, { status: routed ? "delivered" : "no-target", message });
47
+ }
48
+
49
+ // POST /api/v1/messages/broadcast
50
+ export async function handleBroadcastMessageRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
51
+ const { logger, getTeamState, updateTeamState, messageRouter, wsServer } = deps;
52
+ const body = await parseJsonBody(req);
53
+ const fromRole = validateActiveRoleId(body.fromRole);
54
+ const message: TeamMessage = {
55
+ id: generateId(),
56
+ from: typeof body.from === "string" ? body.from : "",
57
+ fromRole,
58
+ type: "broadcast",
59
+ content: typeof body.content === "string" ? body.content : "",
60
+ contract: ensureTeamMessageContract(body.contract, {
61
+ type: "broadcast",
62
+ content: typeof body.content === "string" ? body.content : "",
63
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
64
+ }),
65
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
66
+ createdAt: Date.now(),
67
+ };
68
+
69
+ updateTeamState((s) => { s.messages.push(message); });
70
+
71
+ const state = getTeamState()!;
72
+ const routed = messageRouter.routeBroadcast(message, state.workers);
73
+ for (const { worker, message: routedMsg } of routed) {
74
+ try {
75
+ await deliverMessageToWorker(worker, routedMsg, deps);
76
+ } catch (err) {
77
+ logger.warn(`Controller: failed to broadcast to ${worker.id}: ${String(err)}`);
78
+ }
79
+ }
80
+
81
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
82
+ sendJson(res, 201, { status: "broadcast", recipients: routed.length });
83
+ }
84
+
85
+ // POST /api/v1/messages/review-request
86
+ export async function handleReviewRequestMessageRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
87
+ const { logger, getTeamState, updateTeamState, messageRouter, wsServer } = deps;
88
+ const body = await parseJsonBody(req);
89
+ const fromRole = validateActiveRoleId(body.fromRole);
90
+ const toRole = validateActiveRoleId(body.toRole);
91
+ const message: TeamMessage = {
92
+ id: generateId(),
93
+ from: typeof body.from === "string" ? body.from : "",
94
+ fromRole,
95
+ toRole,
96
+ type: "review-request",
97
+ content: typeof body.content === "string" ? body.content : "",
98
+ contract: ensureTeamMessageContract(body.contract, {
99
+ type: "review-request",
100
+ content: typeof body.content === "string" ? body.content : "",
101
+ toRole,
102
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
103
+ intent: "review-request",
104
+ needsResponse: true,
105
+ }),
106
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
107
+ createdAt: Date.now(),
108
+ };
109
+
110
+ updateTeamState((s) => { s.messages.push(message); });
111
+
112
+ const state = getTeamState()!;
113
+ const routed = messageRouter.routeReviewRequest(message, state.workers);
114
+ if (routed) {
115
+ try {
116
+ await deliverMessageToWorker(routed.worker, routed.message, deps);
117
+ } catch (err) {
118
+ logger.warn(`Controller: failed to deliver review request: ${String(err)}`);
119
+ }
120
+ }
121
+
122
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
123
+ sendJson(res, 201, { status: routed ? "delivered" : "no-target", message });
124
+ }
125
+
126
+ // GET /api/v1/messages
127
+ export async function handleMessageListRequest(deps: ControllerTaskDomainDeps, res: ServerResponse, requestUrl: URL): Promise<void> {
128
+ const { getTeamState } = deps;
129
+ const state = getTeamState();
130
+ const messages = state?.messages ?? [];
131
+ const limit = parseInt(requestUrl.searchParams.get("limit") ?? "50", 10);
132
+ const offset = parseInt(requestUrl.searchParams.get("offset") ?? "0", 10);
133
+ sendJson(res, 200, {
134
+ messages: messages.slice(offset, offset + limit),
135
+ total: messages.length,
136
+ });
137
+ }
@@ -7,38 +7,15 @@ import type {
7
7
  ControllerOrchestrationManifest,
8
8
  RoleId,
9
9
  } from "../types.js";
10
+ import { validateRoleIdList } from "../roles.js";
10
11
  import { deriveStableProjectKey } from "../openclaw-workspace.js";
11
12
 
12
- const TEAMCLAW_ROLE_IDS = new Set<RoleId>([
13
- "pm",
14
- "architect",
15
- "developer",
16
- "qa",
17
- "release-engineer",
18
- "infra-engineer",
19
- "devops",
20
- "security-engineer",
21
- "designer",
22
- "marketing",
23
- "data-engineer",
24
- ]);
25
-
26
13
  export function normalizeManifestRoleList(raw: unknown): RoleId[] {
27
- if (!Array.isArray(raw)) {
28
- return [];
29
- }
30
- const roleIds: RoleId[] = [];
31
- for (const entry of raw) {
32
- if (typeof entry !== "string") {
33
- continue;
34
- }
35
- const normalized = entry.trim() as RoleId;
36
- if (!normalized || !TEAMCLAW_ROLE_IDS.has(normalized) || roleIds.includes(normalized)) {
37
- continue;
38
- }
39
- roleIds.push(normalized);
40
- }
41
- return roleIds;
14
+ // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts.
15
+ // The hand-written TEAMCLAW_ROLE_IDS copy this function used to keep was
16
+ // removed by Phase 1.2 (single-source-of-truth convergence); the role set
17
+ // now lives only in role-ids.ts / roles.ts.
18
+ return validateRoleIdList(raw);
42
19
  }
43
20
 
44
21
  export function normalizeManifestStringList(raw: unknown): string[] {
@@ -0,0 +1,127 @@
1
+ // PR-B of issue #204 (http-server monolith split): the preview subprocess
2
+ // proxy for /api/v1/previews/:id/* extracted verbatim from
3
+ // controller/http-server.ts. Zero behavior change - the route shell in
4
+ // http-server keeps the method whitelist + prefix match and calls this
5
+ // handler with the same request/response objects as before. This module must
6
+ // NEVER import http-server (the reverse edge exists:
7
+ // http-server -> preview-proxy); preview state arrives through the deps
8
+ // slice below.
9
+ import http from "node:http";
10
+ import zlib from "node:zlib";
11
+ import type { IncomingMessage, ServerResponse } from "node:http";
12
+ import type { PluginLogger } from "../../api.js";
13
+ import type { TeamState } from "../types.js";
14
+ import { sendJson } from "../protocol.js";
15
+
16
+ /**
17
+ * Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
18
+ * the fields the preview proxy reads. http-server keeps passing its full
19
+ * ControllerHttpDeps object; TypeScript structural typing accepts it, so no
20
+ * call site changes beyond the import path.
21
+ */
22
+ export type PreviewProxyDeps = {
23
+ logger: PluginLogger;
24
+ getTeamState: () => TeamState | null;
25
+ };
26
+
27
+ /**
28
+ * /api/v1/previews/:id/* - proxy to the preview subprocess. `pathname` starts
29
+ * with "/api/v1/previews/"; `requestUrl` is the parsed request URL (query
30
+ * string is forwarded to the subprocess).
31
+ */
32
+ export function handlePreviewProxyRequest(
33
+ deps: PreviewProxyDeps,
34
+ req: IncomingMessage,
35
+ res: ServerResponse,
36
+ requestUrl: URL,
37
+ pathname: string,
38
+ ): void {
39
+ const previewPrefix = "/api/v1/previews/";
40
+ const remaining = pathname.slice(previewPrefix.length);
41
+ const slashIdx = remaining.indexOf("/");
42
+ const previewId = slashIdx >= 0 ? remaining.slice(0, slashIdx) : remaining;
43
+ const subPath = slashIdx >= 0 ? remaining.slice(slashIdx) : "/";
44
+
45
+ const state = deps.getTeamState();
46
+ const preview = state?.previews?.[previewId];
47
+ if (!preview || preview.status !== "healthy") {
48
+ const status = preview?.status ?? "unknown";
49
+ const errMsg = preview?.lastError;
50
+ sendJson(res, 503, { error: "Preview not available", previewId, status, lastError: errMsg ?? undefined });
51
+ return;
52
+ }
53
+
54
+ const proxyPathPrefix = `/api/v1/previews/${encodeURIComponent(previewId)}`;
55
+ const proxyReq = http.request(
56
+ {
57
+ hostname: "127.0.0.1",
58
+ port: preview.targetPort,
59
+ path: subPath + (requestUrl.search || ""),
60
+ method: req.method,
61
+ headers: {
62
+ ...req.headers,
63
+ host: `127.0.0.1:${preview.targetPort}`,
64
+ "accept-encoding": "identity",
65
+ "x-forwarded-for": req.socket.remoteAddress ?? "",
66
+ "x-forwarded-host": req.headers.host ?? "",
67
+ "x-forwarded-proto": "http",
68
+ },
69
+ },
70
+ (proxyRes: http.IncomingMessage) => {
71
+ const contentType = (proxyRes.headers["content-type"] ?? "").toLowerCase();
72
+ if (proxyRes.statusCode !== 200 && proxyRes.statusCode !== 201 && proxyRes.statusCode !== 301 && proxyRes.statusCode !== 302 && proxyRes.statusCode !== 304) {
73
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
74
+ proxyRes.pipe(res);
75
+ return;
76
+ }
77
+
78
+ if (contentType.includes("text/html")) {
79
+ const chunks: Buffer[] = [];
80
+ proxyRes.on("data", (chunk: Buffer) => chunks.push(chunk));
81
+ proxyRes.on("end", () => {
82
+ let raw = Buffer.concat(chunks);
83
+ // Decompress if the upstream response is compressed (brotli/gzip/deflate).
84
+ const encoding = (proxyRes.headers["content-encoding"] ?? "").toLowerCase();
85
+ try {
86
+ if (encoding === "br") {
87
+ raw = zlib.brotliDecompressSync(raw);
88
+ } else if (encoding === "gzip") {
89
+ raw = zlib.gunzipSync(raw);
90
+ } else if (encoding === "deflate") {
91
+ raw = zlib.inflateSync(raw);
92
+ }
93
+ } catch {
94
+ // If decompression fails, use raw bytes as-is.
95
+ }
96
+ const body = raw.toString("utf-8");
97
+ // Rewrite absolute-path references (href="/...", src="/...", action="/...")
98
+ // to include the proxy prefix so all navigation stays within the proxy.
99
+ const rewritten = body.replace(
100
+ /\b(href|src|action)\s*=\s*"\/([^"]*)"/g,
101
+ `$1="${proxyPathPrefix}/$2"`,
102
+ ).replace(
103
+ /\b(href|src|action)\s*=\s*'\/([^']*)'/g,
104
+ `$1='${proxyPathPrefix}/$2'`,
105
+ );
106
+ const resHeaders = { ...proxyRes.headers };
107
+ // We've decoded and rewritten the body — remove upstream encoding headers.
108
+ delete resHeaders["content-encoding"];
109
+ delete resHeaders["transfer-encoding"];
110
+ resHeaders["content-length"] = String(Buffer.byteLength(rewritten, "utf-8"));
111
+ res.writeHead(proxyRes.statusCode ?? 200, resHeaders);
112
+ res.end(rewritten);
113
+ });
114
+ } else {
115
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
116
+ proxyRes.pipe(res);
117
+ }
118
+ },
119
+ );
120
+ proxyReq.on("error", (err: Error) => {
121
+ deps.logger.warn(`Controller: preview proxy error for ${previewId}: ${String(err)}`);
122
+ if (!res.headersSent) {
123
+ sendJson(res, 502, { error: "Preview proxy error", previewId, message: String(err) });
124
+ }
125
+ });
126
+ req.pipe(proxyReq);
127
+ }