@teamclaws/teamclaw 2026.8.1 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
@@ -14,7 +14,12 @@
14
14
  * 6. Controller synthesizes team input into final execution plan
15
15
  * 7. Unneeded workers are reclaimed by the idle TTL mechanism
16
16
  */
17
- import { getRole, ROLES } from "../roles.js";
17
+ // Phase 1.3: role data comes from the active TeamProfile loader.
18
+ import { getActiveDefaultRole, getActiveRole, getActiveRoleIds, validateActiveRoleId } from "../profile-loader.js";
19
+ // W6 of issue #226: the local sleep copy (byte-identical to the shared one)
20
+ // was removed in favor of shared/utils.js.
21
+ import { sleep } from "../shared/utils.js";
22
+ import { inferTaskRoleWithConfidence } from "./role-inference.js";
18
23
  // ── Constants ────────────────────────────────────────────────────────────────
19
24
  /** Maximum time to wait for all workers to register after provisioning. */
20
25
  const WORKER_PROVISION_TIMEOUT_MS = 90_000;
@@ -22,13 +27,13 @@ const WORKER_PROVISION_TIMEOUT_MS = 90_000;
22
27
  const ASSESSMENT_TIMEOUT_MS = 120_000;
23
28
  /** Poll interval when waiting for workers to appear in state. */
24
29
  const WORKER_POLL_INTERVAL_MS = 2_000;
25
- const VALID_ROLE_IDS = new Set(ROLES.map((r) => r.id));
26
30
  // ── Public API ───────────────────────────────────────────────────────────────
27
31
  export async function runKickoffMeeting(request, deps) {
28
32
  const { logger } = deps;
29
33
  const { requirement, candidateRoles, complexity } = request;
30
34
  // Validate roles
31
- const validRoles = candidateRoles.filter((r) => VALID_ROLE_IDS.has(r));
35
+ // Resolved per call so the set always reflects the active profile.
36
+ const validRoles = candidateRoles.filter((r) => getActiveRoleIds().includes(r));
32
37
  if (validRoles.length === 0) {
33
38
  return buildEmptyResult(complexity, "No valid candidate roles provided.");
34
39
  }
@@ -126,7 +131,7 @@ function buildKickoffSummary(plan, _requirement) {
126
131
  if (needed.length > 0) {
127
132
  parts.push("### Roles Confirmed Needed");
128
133
  for (const a of needed) {
129
- const roleDef = getRole(a.role);
134
+ const roleDef = getActiveRole(a.role);
130
135
  const icon = roleDef?.icon ?? "•";
131
136
  parts.push(`\n**${icon} ${roleDef?.label ?? a.role}**`);
132
137
  parts.push(`- Scope: ${a.scope}`);
@@ -148,7 +153,7 @@ function buildKickoffSummary(plan, _requirement) {
148
153
  parts.push("");
149
154
  parts.push("### Roles Not Needed");
150
155
  for (const a of notNeeded) {
151
- const roleDef = getRole(a.role);
156
+ const roleDef = getActiveRole(a.role);
152
157
  parts.push(`- ${roleDef?.icon ?? "•"} ${roleDef?.label ?? a.role}: ${a.scope}`);
153
158
  }
154
159
  }
@@ -178,43 +183,28 @@ function buildKickoffSummary(plan, _requirement) {
178
183
  parts.push("Use these team assessments to create the final execution plan. Only create tasks for roles that confirmed they are needed. Respect the dependency ordering suggested by the team.");
179
184
  return parts.join("\n");
180
185
  }
181
- /**
182
- * Build the kickoff assessment prompt sent to a worker.
183
- * The worker should respond with structured JSON matching KickoffAssessment.
184
- */
185
- export function buildKickoffAssessmentPrompt(role, requirement) {
186
- const roleDef = getRole(role);
187
- const roleLabel = roleDef?.label ?? role;
188
- return [
189
- `You are the ${roleLabel} in a virtual software team.`,
190
- `Your team is conducting a kickoff meeting for a new requirement.`,
191
- ``,
192
- `## Requirement`,
193
- requirement,
194
- ``,
195
- `## Your Task`,
196
- `Evaluate this requirement from your professional perspective as ${roleLabel}.`,
197
- `Respond with a JSON object (and nothing else) with these fields:`,
198
- ``,
199
- `{`,
200
- ` "needed": boolean, // Is your role needed for this project?`,
201
- ` "scope": string, // What would you contribute? (1-2 sentences)`,
202
- ` "suggestedTasks": string[], // Specific tasks you'd handle (2-5 items)`,
203
- ` "dependencies": string[], // What you need from other roles before or during your work`,
204
- ` "risks": string[], // Concerns or risks from your perspective`,
205
- ` "questions": string[] // Clarifications you'd want before starting`,
206
- `}`,
207
- ``,
208
- `Guidelines:`,
209
- `- Be honest about whether your role is truly needed. Don't inflate your importance.`,
210
- `- For "needed", consider: does the project actually require ${roleLabel}-level expertise?`,
211
- `- A simple single-file script does NOT need an architect. A TODO app does NOT need a security engineer.`,
212
- `- Keep suggestedTasks concrete and actionable, not vague.`,
213
- `- Only list dependencies on roles that are actually relevant.`,
214
- `- Return ONLY the JSON object, no markdown fencing, no explanation.`,
215
- ].join("\n");
216
- }
217
- function sleep(ms) {
218
- return new Promise((resolve) => setTimeout(resolve, ms));
186
+ export async function resolveTaskRoleWithLlmFallback(task, deps = {}) {
187
+ const verdict = (deps.inferWithConfidence ?? inferTaskRoleWithConfidence)(task);
188
+ if (!verdict.needsLlmFallback) {
189
+ return verdict.role;
190
+ }
191
+ if (deps.llmRoleJudge) {
192
+ try {
193
+ const judged = await deps.llmRoleJudge({ task, verdict });
194
+ const validated = validateActiveRoleId(judged);
195
+ if (validated) {
196
+ deps.logger?.info(`RoleInference: LLM fallback judged role ${validated} (token fast path refused: ${verdict.reason})`);
197
+ return validated;
198
+ }
199
+ deps.logger?.warn(`RoleInference: LLM fallback returned ${JSON.stringify(judged)} which is not a role of the active profile; using defaultRole`);
200
+ }
201
+ catch (err) {
202
+ deps.logger?.warn(`RoleInference: LLM fallback failed (${err instanceof Error ? err.message : String(err)}); using defaultRole`);
203
+ }
204
+ }
205
+ else {
206
+ deps.logger?.info(`RoleInference: token fast path refused to decide (${verdict.reason}) and no LLM fallback is wired; using defaultRole`);
207
+ }
208
+ return getActiveDefaultRole();
219
209
  }
220
210
  export { ASSESSMENT_TIMEOUT_MS };
@@ -0,0 +1,31 @@
1
+ import { withWorkerDispatchToken } from "./task-execution.js";
2
+ export async function deliverMessageToWorker(worker, message, deps) {
3
+ // Issue #222: carry the worker's dispatch token so a token-paired worker
4
+ // accepts the injection; L0 sends the historical header set unchanged.
5
+ const res = await fetch(`${worker.url}/api/v1/messages`, {
6
+ method: "POST",
7
+ headers: withWorkerDispatchToken({ "Content-Type": "application/json" }, worker.id, deps.config, deps.getTeamState()),
8
+ body: JSON.stringify(message),
9
+ });
10
+ if (!res.ok) {
11
+ throw new Error(`worker ${worker.id} responded with ${res.status}`);
12
+ }
13
+ }
14
+ export async function routeDirectMessage(message, deps) {
15
+ const { getTeamState, logger, messageRouter } = deps;
16
+ const state = getTeamState();
17
+ if (!state) {
18
+ return false;
19
+ }
20
+ const routed = messageRouter.routeDirectMessage(message, state.workers);
21
+ if (!routed) {
22
+ return false;
23
+ }
24
+ try {
25
+ await deliverMessageToWorker(routed.worker, routed.message, deps);
26
+ }
27
+ catch (err) {
28
+ logger.warn(`Controller: failed to deliver message to ${routed.worker.id}: ${String(err)}`);
29
+ }
30
+ return true;
31
+ }
@@ -0,0 +1,114 @@
1
+ import { generateId, parseJsonBody, sendJson } from "../protocol.js";
2
+ import { ensureTeamMessageContract } from "../interaction-contracts.js";
3
+ import { validateActiveRoleId } from "../profile-loader.js";
4
+ import { deliverMessageToWorker, routeDirectMessage, } from "./message-delivery.js";
5
+ // POST /api/v1/messages/direct
6
+ export async function handleDirectMessageRequest(deps, req, res) {
7
+ const { updateTeamState, wsServer } = deps;
8
+ const body = await parseJsonBody(req);
9
+ const fromRole = validateActiveRoleId(body.fromRole);
10
+ const toRole = validateActiveRoleId(body.toRole);
11
+ const message = {
12
+ id: generateId(),
13
+ from: typeof body.from === "string" ? body.from : "",
14
+ fromRole,
15
+ toRole,
16
+ type: "direct",
17
+ content: typeof body.content === "string" ? body.content : "",
18
+ contract: ensureTeamMessageContract(body.contract, {
19
+ type: "direct",
20
+ content: typeof body.content === "string" ? body.content : "",
21
+ toRole,
22
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
23
+ }),
24
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
25
+ createdAt: Date.now(),
26
+ };
27
+ updateTeamState((s) => { s.messages.push(message); });
28
+ const routed = await routeDirectMessage(message, deps);
29
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
30
+ sendJson(res, 201, { status: routed ? "delivered" : "no-target", message });
31
+ }
32
+ // POST /api/v1/messages/broadcast
33
+ export async function handleBroadcastMessageRequest(deps, req, res) {
34
+ const { logger, getTeamState, updateTeamState, messageRouter, wsServer } = deps;
35
+ const body = await parseJsonBody(req);
36
+ const fromRole = validateActiveRoleId(body.fromRole);
37
+ const message = {
38
+ id: generateId(),
39
+ from: typeof body.from === "string" ? body.from : "",
40
+ fromRole,
41
+ type: "broadcast",
42
+ content: typeof body.content === "string" ? body.content : "",
43
+ contract: ensureTeamMessageContract(body.contract, {
44
+ type: "broadcast",
45
+ content: typeof body.content === "string" ? body.content : "",
46
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
47
+ }),
48
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
49
+ createdAt: Date.now(),
50
+ };
51
+ updateTeamState((s) => { s.messages.push(message); });
52
+ const state = getTeamState();
53
+ const routed = messageRouter.routeBroadcast(message, state.workers);
54
+ for (const { worker, message: routedMsg } of routed) {
55
+ try {
56
+ await deliverMessageToWorker(worker, routedMsg, deps);
57
+ }
58
+ catch (err) {
59
+ logger.warn(`Controller: failed to broadcast to ${worker.id}: ${String(err)}`);
60
+ }
61
+ }
62
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
63
+ sendJson(res, 201, { status: "broadcast", recipients: routed.length });
64
+ }
65
+ // POST /api/v1/messages/review-request
66
+ export async function handleReviewRequestMessageRequest(deps, req, res) {
67
+ const { logger, getTeamState, updateTeamState, messageRouter, wsServer } = deps;
68
+ const body = await parseJsonBody(req);
69
+ const fromRole = validateActiveRoleId(body.fromRole);
70
+ const toRole = validateActiveRoleId(body.toRole);
71
+ const message = {
72
+ id: generateId(),
73
+ from: typeof body.from === "string" ? body.from : "",
74
+ fromRole,
75
+ toRole,
76
+ type: "review-request",
77
+ content: typeof body.content === "string" ? body.content : "",
78
+ contract: ensureTeamMessageContract(body.contract, {
79
+ type: "review-request",
80
+ content: typeof body.content === "string" ? body.content : "",
81
+ toRole,
82
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
83
+ intent: "review-request",
84
+ needsResponse: true,
85
+ }),
86
+ taskId: typeof body.taskId === "string" ? body.taskId : undefined,
87
+ createdAt: Date.now(),
88
+ };
89
+ updateTeamState((s) => { s.messages.push(message); });
90
+ const state = getTeamState();
91
+ const routed = messageRouter.routeReviewRequest(message, state.workers);
92
+ if (routed) {
93
+ try {
94
+ await deliverMessageToWorker(routed.worker, routed.message, deps);
95
+ }
96
+ catch (err) {
97
+ logger.warn(`Controller: failed to deliver review request: ${String(err)}`);
98
+ }
99
+ }
100
+ wsServer.broadcastUpdate({ type: "message:new", data: message });
101
+ sendJson(res, 201, { status: routed ? "delivered" : "no-target", message });
102
+ }
103
+ // GET /api/v1/messages
104
+ export async function handleMessageListRequest(deps, res, requestUrl) {
105
+ const { getTeamState } = deps;
106
+ const state = getTeamState();
107
+ const messages = state?.messages ?? [];
108
+ const limit = parseInt(requestUrl.searchParams.get("limit") ?? "50", 10);
109
+ const offset = parseInt(requestUrl.searchParams.get("offset") ?? "0", 10);
110
+ sendJson(res, 200, {
111
+ messages: messages.slice(offset, offset + limit),
112
+ total: messages.length,
113
+ });
114
+ }
@@ -1,33 +1,16 @@
1
+ import { validateRoleIdList } from "../roles.js";
1
2
  import { deriveStableProjectKey } from "../openclaw-workspace.js";
2
- const TEAMCLAW_ROLE_IDS = new Set([
3
- "pm",
4
- "architect",
5
- "developer",
6
- "qa",
7
- "release-engineer",
8
- "infra-engineer",
9
- "devops",
10
- "security-engineer",
11
- "designer",
12
- "marketing",
13
- "data-engineer",
14
- ]);
3
+ // Issue #226 W3: the clarification-schema normalization family moved to the
4
+ // shared layer (worker/tools.ts consumes it; the worker must not import the
5
+ // controller tree). This module keeps the manifest-specific normalizers and
6
+ // imports the shared contract — controller -> shared direction only.
7
+ import { normalizeClarificationQuestionSchemas, normalizeOptionalManifestText, } from "../shared/clarification-schema.js";
15
8
  export function normalizeManifestRoleList(raw) {
16
- if (!Array.isArray(raw)) {
17
- return [];
18
- }
19
- const roleIds = [];
20
- for (const entry of raw) {
21
- if (typeof entry !== "string") {
22
- continue;
23
- }
24
- const normalized = entry.trim();
25
- if (!normalized || !TEAMCLAW_ROLE_IDS.has(normalized) || roleIds.includes(normalized)) {
26
- continue;
27
- }
28
- roleIds.push(normalized);
29
- }
30
- return roleIds;
9
+ // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts.
10
+ // The hand-written TEAMCLAW_ROLE_IDS copy this function used to keep was
11
+ // removed by Phase 1.2 (single-source-of-truth convergence); the role set
12
+ // now lives only in role-ids.ts / roles.ts.
13
+ return validateRoleIdList(raw);
31
14
  }
32
15
  export function normalizeManifestStringList(raw) {
33
16
  if (!Array.isArray(raw)) {
@@ -37,71 +20,6 @@ export function normalizeManifestStringList(raw) {
37
20
  .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
38
21
  .filter(Boolean);
39
22
  }
40
- export function normalizeOptionalManifestText(raw) {
41
- if (typeof raw !== "string") {
42
- return undefined;
43
- }
44
- const normalized = raw.trim();
45
- return normalized || undefined;
46
- }
47
- export function normalizeClarificationOptions(raw) {
48
- if (!Array.isArray(raw)) {
49
- return [];
50
- }
51
- return raw
52
- .filter((entry) => !!entry && typeof entry === "object")
53
- .map((entry) => ({
54
- value: typeof entry.value === "string" ? entry.value.trim() : "",
55
- label: typeof entry.label === "string" ? entry.label.trim() : "",
56
- hint: typeof entry.hint === "string" && entry.hint.trim() ? entry.hint.trim() : undefined,
57
- }))
58
- .filter((entry) => entry.value && entry.label);
59
- }
60
- export function normalizeClarificationQuestionSchema(raw) {
61
- if (!raw || typeof raw !== "object") {
62
- return undefined;
63
- }
64
- const input = raw;
65
- const kind = typeof input.kind === "string" ? input.kind.trim() : "";
66
- const title = typeof input.title === "string" ? input.title.trim() : "";
67
- if (!title || !["single-select", "multi-select", "number", "text"].includes(kind)) {
68
- return undefined;
69
- }
70
- const options = normalizeClarificationOptions(input.options);
71
- const schema = {
72
- kind: kind,
73
- title,
74
- description: normalizeOptionalManifestText(input.description),
75
- required: input.required == null ? true : Boolean(input.required),
76
- allowOther: Boolean(input.allowOther),
77
- placeholder: normalizeOptionalManifestText(input.placeholder),
78
- unit: normalizeOptionalManifestText(input.unit),
79
- };
80
- if (options.length > 0) {
81
- schema.options = options;
82
- }
83
- if (typeof input.min === "number" && Number.isFinite(input.min)) {
84
- schema.min = input.min;
85
- }
86
- if (typeof input.max === "number" && Number.isFinite(input.max)) {
87
- schema.max = input.max;
88
- }
89
- if (typeof input.step === "number" && Number.isFinite(input.step)) {
90
- schema.step = input.step;
91
- }
92
- if ((schema.kind === "single-select" || schema.kind === "multi-select") && (!schema.options || schema.options.length === 0)) {
93
- return undefined;
94
- }
95
- return schema;
96
- }
97
- export function normalizeClarificationQuestionSchemas(raw) {
98
- if (!Array.isArray(raw)) {
99
- return [];
100
- }
101
- return raw
102
- .map((entry) => normalizeClarificationQuestionSchema(entry))
103
- .filter((entry) => Boolean(entry));
104
- }
105
23
  export function normalizeManifestCreatedTasks(raw) {
106
24
  if (!Array.isArray(raw)) {
107
25
  return [];
@@ -7,6 +7,46 @@ const PREVIEW_LAUNCH_TIMEOUT_MS = 120_000;
7
7
  const PREVIEW_HEALTH_INTERVAL_MS = 1_500;
8
8
  const PREVIEW_STOP_TIMEOUT_MS = 5_000;
9
9
  const GENERIC_SERVE_COMMAND = "npx -y serve -l {PORT}";
10
+ // Issue #237 W1: preview commands are LLM-authored (result contracts) and
11
+ // run through a shell - they must NOT inherit the controller's environment,
12
+ // or a prompt-injected previewCommand could exfiltrate every controller
13
+ // credential (GH_TOKEN, provider API keys, tunnel tokens). Policy: minimal
14
+ // allowlist of toolchain basics, matched case-insensitively so Windows
15
+ // (Path/SystemRoot/...) survives, plus the explicit preview vars set at the
16
+ // spawn site. Repos that genuinely need more can pass names through
17
+ // TEAMCLAW_PREVIEW_EXTRA_ENV (comma-separated list of env var names whose
18
+ // controller values are forwarded verbatim); anything else is absent.
19
+ const PREVIEW_ENV_ALLOWLIST = new Set([
20
+ "PATH", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TZ", "TERM", "SHELL",
21
+ // Windows toolchain basics (no-ops elsewhere, harmless to match).
22
+ // PROCESSOR_ARCHITECTURE/PROCESSOR_IDENTIFIER are read by node-gyp-style
23
+ // native builds (review follow-up to #237 W1) - plain toolchain
24
+ // descriptors, no credential material.
25
+ "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "PATHEXT", "WINDIR", "USERPROFILE",
26
+ "APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMDATA", "NUMBER_OF_PROCESSORS", "OS",
27
+ "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER",
28
+ ]);
29
+ const PREVIEW_EXTRA_ENV_VAR = "TEAMCLAW_PREVIEW_EXTRA_ENV";
30
+ /** Builds the restricted environment for preview subprocesses (#237 W1):
31
+ * allowlisted controller vars + extraEnv (venv PATH/VIRTUAL_ENV) + whatever
32
+ * the operator declared via TEAMCLAW_PREVIEW_EXTRA_ENV. Never returns the
33
+ * full process.env. Exported for the #237 regression test. */
34
+ export function buildPreviewEnv(extraEnv) {
35
+ const allow = new Set(PREVIEW_ENV_ALLOWLIST);
36
+ for (const name of (process.env[PREVIEW_EXTRA_ENV_VAR] ?? "").split(",")) {
37
+ const normalized = name.trim().toUpperCase();
38
+ if (normalized) {
39
+ allow.add(normalized);
40
+ }
41
+ }
42
+ const env = {};
43
+ for (const [key, value] of Object.entries(process.env)) {
44
+ if (value !== undefined && allow.has(key.toUpperCase())) {
45
+ env[key] = value;
46
+ }
47
+ }
48
+ return { ...env, ...extraEnv };
49
+ }
10
50
  /**
11
51
  * Detect the tech stack from files in `cwd` and return a suitable preview command.
12
52
  * Only overrides `existingCommand` when it is the generic static file server
@@ -394,7 +434,10 @@ export class PreviewManager {
394
434
  const pipInstall = spawnManagedCommandProcess({
395
435
  command: `${pipBin} install -q -r requirements.txt`,
396
436
  cwd,
397
- env: { ...process.env, ...extraEnv },
437
+ // #237 W1: requirements.txt is worker-influenced and pip executes
438
+ // setup.py at install time, so this subprocess gets the same
439
+ // restricted env as the preview command itself.
440
+ env: buildPreviewEnv(extraEnv),
398
441
  });
399
442
  await new Promise((resolve) => {
400
443
  pipInstall.on("exit", () => resolve());
@@ -408,10 +451,15 @@ export class PreviewManager {
408
451
  }
409
452
  const child = spawnManagedCommandProcess({
410
453
  command: resolvedCommand,
454
+ // cwd is already forced inside the workspace (resolveWorkspaceDirectory
455
+ // confinement above), so the shell cannot escape the deliverable dir.
411
456
  cwd,
457
+ // #237 W1: restricted allowlist env - never the controller's full
458
+ // process.env (credential exfiltration via prompt-injected
459
+ // previewCommand). HOST/PORT/TEAMCLAW_PREVIEW_* are the explicit
460
+ // preview contract vars.
412
461
  env: {
413
- ...process.env,
414
- ...extraEnv,
462
+ ...buildPreviewEnv(extraEnv),
415
463
  HOST: "0.0.0.0",
416
464
  PORT: String(record.targetPort),
417
465
  TEAMCLAW_PREVIEW_BASE_PATH: record.liveUrl.replace(/\/$/u, ""),
@@ -0,0 +1,98 @@
1
+ // PR-B of issue #204 (http-server monolith split): the preview subprocess
2
+ // proxy for /api/v1/previews/:id/* extracted verbatim from
3
+ // controller/http-server.ts. Zero behavior change - the route shell in
4
+ // http-server keeps the method whitelist + prefix match and calls this
5
+ // handler with the same request/response objects as before. This module must
6
+ // NEVER import http-server (the reverse edge exists:
7
+ // http-server -> preview-proxy); preview state arrives through the deps
8
+ // slice below.
9
+ import http from "node:http";
10
+ import zlib from "node:zlib";
11
+ import { sendJson } from "../protocol.js";
12
+ /**
13
+ * /api/v1/previews/:id/* - proxy to the preview subprocess. `pathname` starts
14
+ * with "/api/v1/previews/"; `requestUrl` is the parsed request URL (query
15
+ * string is forwarded to the subprocess).
16
+ */
17
+ export function handlePreviewProxyRequest(deps, req, res, requestUrl, pathname) {
18
+ const previewPrefix = "/api/v1/previews/";
19
+ const remaining = pathname.slice(previewPrefix.length);
20
+ const slashIdx = remaining.indexOf("/");
21
+ const previewId = slashIdx >= 0 ? remaining.slice(0, slashIdx) : remaining;
22
+ const subPath = slashIdx >= 0 ? remaining.slice(slashIdx) : "/";
23
+ const state = deps.getTeamState();
24
+ const preview = state?.previews?.[previewId];
25
+ if (!preview || preview.status !== "healthy") {
26
+ const status = preview?.status ?? "unknown";
27
+ const errMsg = preview?.lastError;
28
+ sendJson(res, 503, { error: "Preview not available", previewId, status, lastError: errMsg ?? undefined });
29
+ return;
30
+ }
31
+ const proxyPathPrefix = `/api/v1/previews/${encodeURIComponent(previewId)}`;
32
+ const proxyReq = http.request({
33
+ hostname: "127.0.0.1",
34
+ port: preview.targetPort,
35
+ path: subPath + (requestUrl.search || ""),
36
+ method: req.method,
37
+ headers: {
38
+ ...req.headers,
39
+ host: `127.0.0.1:${preview.targetPort}`,
40
+ "accept-encoding": "identity",
41
+ "x-forwarded-for": req.socket.remoteAddress ?? "",
42
+ "x-forwarded-host": req.headers.host ?? "",
43
+ "x-forwarded-proto": "http",
44
+ },
45
+ }, (proxyRes) => {
46
+ const contentType = (proxyRes.headers["content-type"] ?? "").toLowerCase();
47
+ if (proxyRes.statusCode !== 200 && proxyRes.statusCode !== 201 && proxyRes.statusCode !== 301 && proxyRes.statusCode !== 302 && proxyRes.statusCode !== 304) {
48
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
49
+ proxyRes.pipe(res);
50
+ return;
51
+ }
52
+ if (contentType.includes("text/html")) {
53
+ const chunks = [];
54
+ proxyRes.on("data", (chunk) => chunks.push(chunk));
55
+ proxyRes.on("end", () => {
56
+ let raw = Buffer.concat(chunks);
57
+ // Decompress if the upstream response is compressed (brotli/gzip/deflate).
58
+ const encoding = (proxyRes.headers["content-encoding"] ?? "").toLowerCase();
59
+ try {
60
+ if (encoding === "br") {
61
+ raw = zlib.brotliDecompressSync(raw);
62
+ }
63
+ else if (encoding === "gzip") {
64
+ raw = zlib.gunzipSync(raw);
65
+ }
66
+ else if (encoding === "deflate") {
67
+ raw = zlib.inflateSync(raw);
68
+ }
69
+ }
70
+ catch {
71
+ // If decompression fails, use raw bytes as-is.
72
+ }
73
+ const body = raw.toString("utf-8");
74
+ // Rewrite absolute-path references (href="/...", src="/...", action="/...")
75
+ // to include the proxy prefix so all navigation stays within the proxy.
76
+ const rewritten = body.replace(/\b(href|src|action)\s*=\s*"\/([^"]*)"/g, `$1="${proxyPathPrefix}/$2"`).replace(/\b(href|src|action)\s*=\s*'\/([^']*)'/g, `$1='${proxyPathPrefix}/$2'`);
77
+ const resHeaders = { ...proxyRes.headers };
78
+ // We've decoded and rewritten the body — remove upstream encoding headers.
79
+ delete resHeaders["content-encoding"];
80
+ delete resHeaders["transfer-encoding"];
81
+ resHeaders["content-length"] = String(Buffer.byteLength(rewritten, "utf-8"));
82
+ res.writeHead(proxyRes.statusCode ?? 200, resHeaders);
83
+ res.end(rewritten);
84
+ });
85
+ }
86
+ else {
87
+ res.writeHead(proxyRes.statusCode ?? 502, proxyRes.headers);
88
+ proxyRes.pipe(res);
89
+ }
90
+ });
91
+ proxyReq.on("error", (err) => {
92
+ deps.logger.warn(`Controller: preview proxy error for ${previewId}: ${String(err)}`);
93
+ if (!res.headersSent) {
94
+ sendJson(res, 502, { error: "Preview proxy error", previewId, message: String(err) });
95
+ }
96
+ });
97
+ req.pipe(proxyReq);
98
+ }