@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
package/src/config.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import type { PluginConfig } from "./types.js";
2
2
  import { parsePluginConfig } from "./types.js";
3
- import { ROLE_IDS } from "./roles.js";
3
+ // Phase 1.3: the enum is driven by the active TeamProfile (software-rd
4
+ // baseline) instead of importing the roles.ts registry directly. The
5
+ // manifest generator evaluates this file without imports and injects
6
+ // equivalent getActiveRoleIds/SOFTWARE_RD_PROFILE_ID bindings.
7
+ import { getActiveRoleIds, SOFTWARE_RD_PROFILE_ID } from "./profile-loader.js";
4
8
  import { TEAMCLAW_PUBLISHED_RUNTIME_IMAGE } from "./install-defaults.js";
5
9
 
6
10
  function buildConfigSchema() {
@@ -19,6 +23,11 @@ function buildConfigSchema() {
19
23
  default: 9527,
20
24
  description: "HTTP server port for this instance",
21
25
  },
26
+ listenHost: {
27
+ type: "string" as const,
28
+ default: "",
29
+ description: "HTTP listen host override (empty = 127.0.0.1 on hosts, 0.0.0.0 in containers); set 0.0.0.0 for external workers reachable by a remote controller",
30
+ },
22
31
  role: {
23
32
  type: "string" as const,
24
33
  default: "developer",
@@ -34,6 +43,11 @@ function buildConfigSchema() {
34
43
  default: "TeamClaw",
35
44
  description: "Team name for mDNS identification",
36
45
  },
46
+ teamProfile: {
47
+ type: "string" as const,
48
+ default: SOFTWARE_RD_PROFILE_ID,
49
+ description: "Team profile package id (software-rd baseline); seeds first initialization only - the persisted team state profile is the runtime truth",
50
+ },
37
51
  heartbeatIntervalMs: {
38
52
  type: "number" as const,
39
53
  default: 10000,
@@ -44,6 +58,11 @@ function buildConfigSchema() {
44
58
  default: 600000,
45
59
  description: "Inactivity threshold in milliseconds before TeamClaw probes a stalled role task instead of failing it",
46
60
  },
61
+ teamSwitchDrainTimeoutMs: {
62
+ type: "number" as const,
63
+ default: 30000,
64
+ description: "How long a team profile switch waits for in-flight tasks to finish before force-collecting them (design 2.3 graceful drain)",
65
+ },
47
66
  maxConcurrentTasks: {
48
67
  type: "integer" as const,
49
68
  default: 5,
@@ -120,7 +139,7 @@ function buildConfigSchema() {
120
139
  description: "Preferred on-demand roles; task-required roles can still launch automatically. Empty means no preferred startup role list, so startup readiness falls back to a warm developer worker",
121
140
  items: {
122
141
  type: "string" as const,
123
- enum: ROLE_IDS,
142
+ enum: getActiveRoleIds(),
124
143
  },
125
144
  },
126
145
  workerProvisioningMinPerRole: {
@@ -236,14 +255,26 @@ function buildConfigSchema() {
236
255
  uiHints: {
237
256
  mode: { label: "Mode", help: "controller manages the team, worker executes tasks" },
238
257
  port: { label: "Port", help: "HTTP server port for this instance" },
258
+ listenHost: {
259
+ label: "Listen Host",
260
+ help: "HTTP bind address override; empty defaults to 127.0.0.1 on hosts and 0.0.0.0 in containers. Use 0.0.0.0 when a remote controller must reach this worker",
261
+ },
239
262
  role: { label: "Role", help: "Worker role (worker mode only)" },
240
263
  controllerUrl: { label: "Controller URL", help: "Manual fallback if mDNS discovery fails" },
241
264
  teamName: { label: "Team Name", help: "Team identifier for mDNS" },
265
+ teamProfile: {
266
+ label: "Team Profile",
267
+ help: "Team profile package id; applies to the first team initialization only (Phase 2 adds profile switching)",
268
+ },
242
269
  heartbeatIntervalMs: { label: "Heartbeat Interval", help: "In milliseconds, minimum 1000" },
243
270
  taskTimeoutMs: {
244
271
  label: "Task Stall Threshold",
245
272
  help: "In milliseconds, how long TeamClaw waits without visible progress before probing the task instead of failing it",
246
273
  },
274
+ teamSwitchDrainTimeoutMs: {
275
+ label: "Profile Switch Drain Timeout",
276
+ help: "In milliseconds, how long a team profile switch waits for in-flight tasks to finish before force-collecting them",
277
+ },
247
278
  maxConcurrentTasks: {
248
279
  label: "Max Concurrent Tasks",
249
280
  hint: "number",
@@ -0,0 +1,404 @@
1
+ // PR-C of issue #204 (http-server monolith split): the clarification request
2
+ // domain - requestTaskClarification (task blocking + worker release), the
3
+ // structured answer builders, and the create/list/answer route handlers -
4
+ // lifted verbatim from controller/http-server.ts. Zero behavior change - the
5
+ // route shells in http-server keep the method+pathname matches and call these
6
+ // handlers with the same deps object as before. This module must NEVER import
7
+ // http-server (the reverse edge exists: http-server -> clarification-routes).
8
+ import type { IncomingMessage, ServerResponse } from "node:http";
9
+ import type {
10
+ ClarificationRequest,
11
+ RoleId,
12
+ TaskInfo,
13
+ TeamMessage,
14
+ WorkerInfo,
15
+ } from "../types.js";
16
+ import { generateId, parseJsonBody, sendError, sendJson } from "../protocol.js";
17
+ import { ensureTeamMessageContract } from "../interaction-contracts.js";
18
+ import { validateActiveRoleId } from "../profile-loader.js";
19
+ import { normalizeClarificationQuestionSchema } from "./orchestration-manifest.js";
20
+ import {
21
+ cancelTaskExecution,
22
+ recordTaskExecutionEvent,
23
+ resetTaskForFreshAttempt,
24
+ serializeTask,
25
+ type ControllerTaskDomainDeps,
26
+ } from "./task-execution.js";
27
+ import { assignTaskToWorker } from "./task-assignment.js";
28
+ import { routeDirectMessage } from "./message-delivery.js";
29
+ import {
30
+ reconcileControllerClarifications,
31
+ runControllerIntake,
32
+ } from "./controller-intake.js";
33
+
34
+ // POST /api/v1/clarifications
35
+ export async function handleClarificationCreateRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
36
+ const body = await parseJsonBody(req);
37
+ const taskId = typeof body.taskId === "string" ? body.taskId : "";
38
+ const requestedBy = typeof body.requestedBy === "string" ? body.requestedBy : "";
39
+ const requestedByWorkerId = typeof body.requestedByWorkerId === "string" ? body.requestedByWorkerId : undefined;
40
+ const requestedByRole = validateActiveRoleId(body.requestedByRole);
41
+ const question = typeof body.question === "string" ? body.question.trim() : "";
42
+ const blockingReason = typeof body.blockingReason === "string" ? body.blockingReason.trim() : "";
43
+ const context = typeof body.context === "string" && body.context.trim() ? body.context.trim() : undefined;
44
+ const questionSchema = normalizeClarificationQuestionSchema(body.questionSchema);
45
+
46
+ if (!taskId || !question || !blockingReason) {
47
+ sendError(res, 400, "taskId, question, and blockingReason are required");
48
+ return;
49
+ }
50
+
51
+ const requested = await requestTaskClarification({
52
+ taskId,
53
+ requestedBy,
54
+ requestedByWorkerId,
55
+ requestedByRole,
56
+ question,
57
+ questionSchema,
58
+ blockingReason,
59
+ context,
60
+ }, deps);
61
+ if (requested.status === "missing-task") {
62
+ sendError(res, 404, "Task not found");
63
+ return;
64
+ }
65
+ if (requested.status === "conflict") {
66
+ sendError(res, 409, "Cannot request clarification for a completed task");
67
+ return;
68
+ }
69
+ if (requested.status === "already-pending") {
70
+ sendJson(res, 200, {
71
+ clarification: requested.clarification,
72
+ task: serializeTask(requested.task),
73
+ status: "already-pending",
74
+ });
75
+ return;
76
+ }
77
+ sendJson(res, 201, {
78
+ clarification: requested.clarification,
79
+ task: serializeTask(requested.task),
80
+ });
81
+ }
82
+
83
+ // GET /api/v1/clarifications
84
+ export async function handleClarificationListRequest(deps: ControllerTaskDomainDeps, res: ServerResponse): Promise<void> {
85
+ const state = reconcileControllerClarifications(deps);
86
+ const clarifications = state
87
+ ? Object.values(state.clarifications).sort((left, right) => right.createdAt - left.createdAt)
88
+ : [];
89
+ sendJson(res, 200, {
90
+ clarifications,
91
+ pendingCount: clarifications.filter((item) => item.status === "pending").length,
92
+ });
93
+ }
94
+
95
+ // POST /api/v1/clarifications/:id/answer
96
+ export async function handleClarificationAnswerRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
97
+ const { getTeamState, taskRouter, updateTeamState, wsServer } = deps;
98
+ const clarificationId = pathname.split("/")[4]!;
99
+ const body = await parseJsonBody(req);
100
+ const answerValue = typeof body.answerValue === "string" ? body.answerValue.trim() : undefined;
101
+ const answerValues = Array.isArray(body.answerValues)
102
+ ? body.answerValues.map((entry) => String(entry || "").trim()).filter(Boolean)
103
+ : undefined;
104
+ const answerNumber = typeof body.answerNumber === "number" && Number.isFinite(body.answerNumber)
105
+ ? body.answerNumber
106
+ : undefined;
107
+ const answerComment = typeof body.answerComment === "string" && body.answerComment.trim()
108
+ ? body.answerComment.trim()
109
+ : undefined;
110
+ const answeredBy = typeof body.answeredBy === "string" && body.answeredBy.trim()
111
+ ? body.answeredBy.trim()
112
+ : "human";
113
+
114
+ const currentState = getTeamState();
115
+ const currentClarification = currentState?.clarifications[clarificationId];
116
+ if (!currentClarification) {
117
+ sendError(res, 404, "Clarification request not found");
118
+ return;
119
+ }
120
+
121
+ const answer = buildStructuredClarificationAnswer(currentClarification, {
122
+ answer: typeof body.answer === "string" ? body.answer.trim() : "",
123
+ answerValue,
124
+ answerValues,
125
+ answerNumber,
126
+ answerComment,
127
+ });
128
+
129
+ if (!answer) {
130
+ sendError(res, 400, "answer is required");
131
+ return;
132
+ }
133
+
134
+ if (currentClarification.status === "answered") {
135
+ sendError(res, 409, "Clarification request already answered");
136
+ return;
137
+ }
138
+
139
+ const now = Date.now();
140
+ const state = updateTeamState((s) => {
141
+ const clarification = s.clarifications[clarificationId];
142
+ if (!clarification) {
143
+ return;
144
+ }
145
+
146
+ clarification.status = "answered";
147
+ clarification.answer = answer;
148
+ clarification.answerValue = answerValue;
149
+ clarification.answerValues = answerValues;
150
+ clarification.answerNumber = answerNumber;
151
+ clarification.answerComment = answerComment;
152
+ clarification.answeredBy = answeredBy;
153
+ clarification.answeredAt = now;
154
+ clarification.updatedAt = now;
155
+
156
+ const task = s.tasks[clarification.taskId];
157
+ if (!task) {
158
+ return;
159
+ }
160
+
161
+ task.status = "pending";
162
+ task.progress = `Clarification answered by ${answeredBy}: ${answer}`;
163
+ task.clarificationRequestId = undefined;
164
+ resetTaskForFreshAttempt(task);
165
+ task.updatedAt = now;
166
+ });
167
+
168
+ const clarification = state.clarifications[clarificationId];
169
+ const task = clarification?.taskId ? state.tasks[clarification.taskId] : undefined;
170
+
171
+ let responseMessage: TeamMessage | undefined;
172
+ if (clarification?.requestedByRole && task) {
173
+ responseMessage = {
174
+ id: generateId(),
175
+ from: answeredBy,
176
+ toRole: clarification.requestedByRole,
177
+ type: "direct",
178
+ content: `Clarification answer for task ${task.id}: ${answer}`,
179
+ contract: ensureTeamMessageContract(null, {
180
+ type: "direct",
181
+ content: `Clarification answer for task ${task.id}: ${answer}`,
182
+ toRole: clarification.requestedByRole,
183
+ taskId: task.id,
184
+ summary: `Clarification answered for task ${task.id}`,
185
+ details: answer,
186
+ requestedAction: "Resume the task using this clarification.",
187
+ needsResponse: false,
188
+ intent: "update",
189
+ }),
190
+ taskId: task.id,
191
+ createdAt: now,
192
+ };
193
+
194
+ updateTeamState((s) => {
195
+ s.messages.push(responseMessage!);
196
+ });
197
+ await routeDirectMessage(responseMessage, deps);
198
+ wsServer.broadcastUpdate({ type: "message:new", data: responseMessage });
199
+ }
200
+
201
+ let resumedTask = task;
202
+ let resumedWorker: WorkerInfo | null = null;
203
+ let continuedControllerRun: {
204
+ sessionKey: string;
205
+ controllerRunId?: string;
206
+ runId?: string;
207
+ reply?: string;
208
+ queued?: boolean;
209
+ } | null = null;
210
+ if (task) {
211
+ const latestState = getTeamState()!;
212
+ if (clarification?.requestedByWorkerId && latestState.workers[clarification.requestedByWorkerId]?.status === "idle") {
213
+ resumedWorker = latestState.workers[clarification.requestedByWorkerId]!;
214
+ } else {
215
+ resumedWorker = taskRouter.routeTask(task, latestState.workers);
216
+ }
217
+
218
+ if (resumedWorker) {
219
+ resumedTask = await assignTaskToWorker(task.id, resumedWorker, deps, {
220
+ assignedRole: task.assignedRole,
221
+ });
222
+ }
223
+ } else if (clarification?.controllerRunId) {
224
+ const targetSessionKey = clarification.controllerSessionKey
225
+ || state.controllerRuns[clarification.controllerRunId]?.sessionKey;
226
+ if (targetSessionKey) {
227
+ continuedControllerRun = {
228
+ sessionKey: targetSessionKey,
229
+ controllerRunId: clarification.controllerRunId,
230
+ queued: true,
231
+ };
232
+ void runControllerIntake(
233
+ buildControllerClarificationAnswerMessage(clarification, answer, answeredBy),
234
+ targetSessionKey,
235
+ deps,
236
+ ).catch((err) => {
237
+ deps.logger.warn(
238
+ `Controller: failed to continue intake after clarification ${clarification.id}: ${String(err)}`,
239
+ );
240
+ });
241
+ }
242
+ }
243
+
244
+ wsServer.broadcastUpdate({ type: "clarification:answered", data: clarification });
245
+ if (resumedTask) {
246
+ recordTaskExecutionEvent(resumedTask.id, {
247
+ type: "lifecycle",
248
+ phase: "clarification_answered",
249
+ source: "controller",
250
+ message: `Clarification answered by ${answeredBy}: ${answer}`,
251
+ role: clarification?.requestedByRole,
252
+ workerId: clarification?.requestedByWorkerId,
253
+ }, deps);
254
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(resumedTask) });
255
+ }
256
+
257
+ sendJson(res, 200, {
258
+ clarification,
259
+ task: serializeTask(resumedTask),
260
+ resumedWorker,
261
+ controllerRun: continuedControllerRun,
262
+ message: responseMessage,
263
+ });
264
+ }
265
+
266
+ export function buildControllerClarificationAnswerMessage(
267
+ clarification: ClarificationRequest,
268
+ answer: string,
269
+ answeredBy: string,
270
+ ): string {
271
+ return [
272
+ "The human has answered a pending controller clarification.",
273
+ `Question: ${clarification.question}`,
274
+ `Answer: ${answer}`,
275
+ `Answered by: ${answeredBy}`,
276
+ "Use this answer to continue the same requirement and update the plan/tasks accordingly.",
277
+ ].join("\n");
278
+ }
279
+
280
+ export function buildStructuredClarificationAnswer(
281
+ clarification: ClarificationRequest,
282
+ payload: {
283
+ answer?: string;
284
+ answerValue?: string;
285
+ answerValues?: string[];
286
+ answerNumber?: number;
287
+ answerComment?: string;
288
+ },
289
+ ): string {
290
+ if (typeof payload.answer === "string" && payload.answer.trim()) {
291
+ return payload.answer.trim();
292
+ }
293
+ const schema = clarification.questionSchema;
294
+ const optionLabel = (value: string): string => {
295
+ const match = schema?.options?.find((entry) => entry.value === value);
296
+ return match?.label || value;
297
+ };
298
+ const parts: string[] = [];
299
+ if (schema?.kind === "single-select" && payload.answerValue) {
300
+ parts.push(optionLabel(payload.answerValue));
301
+ } else if (schema?.kind === "multi-select" && Array.isArray(payload.answerValues) && payload.answerValues.length > 0) {
302
+ parts.push(payload.answerValues.map((entry) => optionLabel(entry)).join(", "));
303
+ } else if (schema?.kind === "number" && typeof payload.answerNumber === "number" && Number.isFinite(payload.answerNumber)) {
304
+ parts.push(`${payload.answerNumber}${schema.unit ? ` ${schema.unit}` : ""}`);
305
+ } else if (payload.answerValue) {
306
+ parts.push(payload.answerValue);
307
+ }
308
+ if (payload.answerComment && payload.answerComment.trim()) {
309
+ parts.push(parts.length > 0 ? `Additional context: ${payload.answerComment.trim()}` : payload.answerComment.trim());
310
+ }
311
+ return parts.join("\n").trim();
312
+ }
313
+
314
+ export async function requestTaskClarification(params: {
315
+ taskId: string;
316
+ requestedBy: string;
317
+ requestedByWorkerId?: string;
318
+ requestedByRole?: RoleId;
319
+ question: string;
320
+ blockingReason: string;
321
+ context?: string;
322
+ questionSchema?: ClarificationRequest["questionSchema"];
323
+ }, deps: ControllerTaskDomainDeps): Promise<{
324
+ status: "created" | "already-pending" | "conflict" | "missing-task";
325
+ clarification?: ClarificationRequest;
326
+ task?: TaskInfo;
327
+ }> {
328
+ const { getTeamState, updateTeamState, wsServer } = deps;
329
+ const currentState = getTeamState();
330
+ const currentTask = currentState?.tasks[params.taskId];
331
+ if (!currentTask) {
332
+ return { status: "missing-task" };
333
+ }
334
+
335
+ if (currentTask.clarificationRequestId) {
336
+ const existing = currentState?.clarifications[currentTask.clarificationRequestId];
337
+ if (existing?.status === "pending") {
338
+ return { status: "already-pending", clarification: existing, task: currentTask };
339
+ }
340
+ }
341
+
342
+ if (currentTask.status === "completed" || currentTask.status === "failed") {
343
+ return { status: "conflict", task: currentTask };
344
+ }
345
+
346
+ const previousWorkerId = currentTask.assignedWorkerId;
347
+ const clarificationId = generateId();
348
+ const now = Date.now();
349
+ const clarification: ClarificationRequest = {
350
+ id: clarificationId,
351
+ taskId: params.taskId,
352
+ requestedBy: params.requestedBy,
353
+ requestedByWorkerId: params.requestedByWorkerId,
354
+ requestedByRole: params.requestedByRole,
355
+ question: params.question,
356
+ questionSchema: params.questionSchema,
357
+ blockingReason: params.blockingReason,
358
+ context: params.context,
359
+ status: "pending",
360
+ createdAt: now,
361
+ updatedAt: now,
362
+ };
363
+
364
+ const state = updateTeamState((s) => {
365
+ s.clarifications[clarificationId] = clarification;
366
+ const task = s.tasks[params.taskId];
367
+ if (!task) {
368
+ return;
369
+ }
370
+
371
+ const assignedWorkerId = task.assignedWorkerId;
372
+ task.status = "blocked";
373
+ task.progress = `Awaiting clarification: ${params.question}`;
374
+ task.clarificationRequestId = clarificationId;
375
+ task.assignedWorkerId = undefined;
376
+ task.updatedAt = now;
377
+
378
+ if (assignedWorkerId && s.workers[assignedWorkerId]) {
379
+ const assignedWorker = s.workers[assignedWorkerId];
380
+ if (assignedWorker.status !== "offline") {
381
+ assignedWorker.status = "idle";
382
+ }
383
+ assignedWorker.currentTaskId = undefined;
384
+ }
385
+ });
386
+
387
+ await cancelTaskExecution(params.taskId, previousWorkerId, "clarification request", deps);
388
+
389
+ const updatedTask = state.tasks[params.taskId];
390
+ wsServer.broadcastUpdate({ type: "clarification:requested", data: clarification });
391
+ if (updatedTask) {
392
+ recordTaskExecutionEvent(params.taskId, {
393
+ type: "lifecycle",
394
+ phase: "clarification_requested",
395
+ source: "controller",
396
+ message: `Clarification requested: ${params.question}`,
397
+ role: clarification.requestedByRole,
398
+ workerId: clarification.requestedByWorkerId,
399
+ }, deps);
400
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
401
+ }
402
+
403
+ return { status: "created", clarification, task: updatedTask };
404
+ }