@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
@@ -0,0 +1,399 @@
1
+ // PR-C of issue #204 (http-server monolith split): the task execution event
2
+ // ring and task serialization extracted verbatim from controller/http-server.ts.
3
+ // Zero behavior change - http-server and the sibling PR-C modules import these
4
+ // with the same deps object as before. This module must NEVER import
5
+ // http-server (the reverse edge exists: http-server -> task-execution); the
6
+ // websocket broadcast and the team-state mutator arrive through the deps
7
+ // slice below, and everything else is pure over TaskInfo.
8
+ import type { OpenClawPluginApi, PluginLogger } from "../../api.js";
9
+ import type {
10
+ KickoffAssessment,
11
+ PluginConfig,
12
+ RoleId,
13
+ TaskExecution,
14
+ TaskExecutionEvent,
15
+ TaskExecutionEventInput,
16
+ TaskExecutionSummary,
17
+ TaskInfo,
18
+ TaskStatus,
19
+ TeamState,
20
+ } from "../types.js";
21
+ import { generateId } from "../protocol.js";
22
+ import { buildTeamClawAgentSessionKey } from "../openclaw-workspace.js";
23
+ import type { TaskRouter } from "./task-router.js";
24
+ import type { MessageRouter } from "./message-router.js";
25
+ import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
26
+ import type { TeamWebSocketServer } from "./websocket.js";
27
+ import type { WorkerProvisioningManager } from "./worker-provisioning.js";
28
+ import type { PreviewManager } from "./preview-manager.js";
29
+
30
+ /**
31
+ * Structural mirror of ControllerHttpDeps (http-server.ts). The task/team
32
+ * lifecycle domain extracted by PR-C is one tightly coupled family whose
33
+ * helpers hand the SAME deps object to each other (intake -> planning ->
34
+ * assignment -> execution events), so the PR-C modules share this single
35
+ * slice instead of per-module subsets that would each have to union their
36
+ * transitive callees. http-server keeps passing its full ControllerHttpDeps
37
+ * object; TypeScript structural typing accepts it, so no call site changes
38
+ * beyond the import path. This module must never import http-server; the
39
+ * kickoff callback is declared structurally so controller-service.ts stays
40
+ * the only definition site of KickoffHandler (no new module edge).
41
+ */
42
+ type ControllerKickoffHandler = (
43
+ candidateRoles: RoleId[],
44
+ complexity: "simple" | "medium" | "complex",
45
+ requirement: string,
46
+ ) => Promise<{ assessments: KickoffAssessment[]; summary: string }>;
47
+
48
+ export type ControllerTaskDomainDeps = {
49
+ config: PluginConfig;
50
+ logger: PluginLogger;
51
+ runtime: OpenClawPluginApi["runtime"];
52
+ getTeamState: () => TeamState | null;
53
+ updateTeamState: (updater: (state: TeamState) => void) => TeamState;
54
+ taskRouter: TaskRouter;
55
+ messageRouter: MessageRouter;
56
+ wsServer: TeamWebSocketServer;
57
+ workerProvisioningManager?: WorkerProvisioningManager | null;
58
+ previewManager?: PreviewManager;
59
+ getKickoffHandler?: () => ControllerKickoffHandler | undefined;
60
+ /** Late-bound TeamAuto scheduler (autonomous repo collaboration). */
61
+ getTeamAutoScheduler?: () => TeamAutoScheduler | null;
62
+ };
63
+
64
+ export const MAX_TASK_EXECUTION_EVENTS = 250;
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Controller -> worker dispatch auth (issue #222, coordinated scope).
68
+ //
69
+ // Workers paired with a token (issue #222 worker wave) reject inbound /api
70
+ // calls without X-TeamClaw-Token; these helpers attach the token the target
71
+ // worker expects. Resolution order (minimal invasion, no new pairing
72
+ // surface - see the worker/http-handler.ts counterpart for the full model):
73
+ // 1. the worker's provisioning record launchToken (the provisioner
74
+ // already generates it per worker, delivers it via the
75
+ // TEAMCLAW_LAUNCH_TOKEN env, and persists it here) - provisioned
76
+ // fleets are covered with zero new plumbing;
77
+ // 2. the controller's own securityToken config (manual/external workers:
78
+ // the operator syncs the same value on both ends - the documented
79
+ // stance for self-managed workers);
80
+ // 3. neither => no header (L0: byte-identical historical requests).
81
+ // ---------------------------------------------------------------------------
82
+
83
+ export function resolveWorkerDispatchToken(
84
+ workerId: string,
85
+ config: Pick<PluginConfig, "securityToken">,
86
+ state: TeamState | null,
87
+ ): string | undefined {
88
+ const record = state?.provisioning?.workers?.[workerId];
89
+ if (record?.launchToken) {
90
+ return record.launchToken;
91
+ }
92
+ const shared = config.securityToken?.trim();
93
+ return shared ? shared : undefined;
94
+ }
95
+
96
+ /** Fetch headers for a controller -> worker call, carrying the worker's dispatch token when one is known. */
97
+ export function withWorkerDispatchToken(
98
+ headers: Record<string, string>,
99
+ workerId: string,
100
+ config: Pick<PluginConfig, "securityToken">,
101
+ state: TeamState | null,
102
+ ): Record<string, string> {
103
+ const token = resolveWorkerDispatchToken(workerId, config, state);
104
+ return token ? { ...headers, "X-TeamClaw-Token": token } : headers;
105
+ }
106
+
107
+ const CONTROLLER_INTAKE_SESSION_PREFIX = "teamclaw-controller-web:";
108
+ const CONTROLLER_INTAKE_AGENT_SESSION_RE = /^agent:[^:]+:(teamclaw-controller-web:[a-zA-Z0-9:_-]{1,120})$/;
109
+
110
+ export function mapTaskStatusToExecutionStatus(taskStatus: TaskStatus, current?: TaskExecution["status"]): TaskExecution["status"] {
111
+ switch (taskStatus) {
112
+ case "completed":
113
+ return "completed";
114
+ case "failed":
115
+ return "failed";
116
+ case "in_progress":
117
+ case "review":
118
+ return "running";
119
+ case "pending":
120
+ case "assigned":
121
+ return current ?? "pending";
122
+ case "blocked":
123
+ return current ?? "running";
124
+ default:
125
+ return current ?? "pending";
126
+ }
127
+ }
128
+
129
+ export function ensureTaskExecution(task: TaskInfo): TaskExecution {
130
+ if (!task.execution) {
131
+ task.execution = {
132
+ status: mapTaskStatusToExecutionStatus(task.status),
133
+ startedAt: task.startedAt,
134
+ endedAt: task.completedAt,
135
+ lastUpdatedAt: task.updatedAt,
136
+ events: [],
137
+ };
138
+ }
139
+
140
+ if (!Array.isArray(task.execution.events)) {
141
+ task.execution.events = [];
142
+ }
143
+
144
+ task.execution.status = task.execution.status ?? mapTaskStatusToExecutionStatus(task.status);
145
+ task.execution.startedAt = task.execution.startedAt ?? task.startedAt;
146
+ task.execution.endedAt = task.execution.endedAt ?? task.completedAt;
147
+ task.execution.lastUpdatedAt = task.execution.lastUpdatedAt ?? task.updatedAt;
148
+
149
+ return task.execution;
150
+ }
151
+
152
+ export function resetTaskForFreshAttempt(task: TaskInfo): void {
153
+ delete task.startedAt;
154
+ delete task.completedAt;
155
+ delete task.result;
156
+ delete task.error;
157
+ delete task.resultContract;
158
+ if (task.execution) {
159
+ task.execution.status = "pending";
160
+ delete task.execution.runId;
161
+ delete task.execution.sessionKey;
162
+ delete task.execution.startedAt;
163
+ delete task.execution.endedAt;
164
+ task.execution.lastUpdatedAt = Date.now();
165
+ }
166
+ }
167
+
168
+ export function buildTaskExecutionIdentity(taskId: string, workerId: string): {
169
+ executionSessionKey: string;
170
+ executionIdempotencyKey: string;
171
+ } {
172
+ const attemptId = generateId();
173
+ return {
174
+ executionSessionKey: buildTeamClawAgentSessionKey(`teamclaw-task-${taskId}-${attemptId}`),
175
+ executionIdempotencyKey: `teamclaw-${taskId}-${workerId}-${attemptId}`,
176
+ };
177
+ }
178
+
179
+ export function appendTaskExecutionEvent(task: TaskInfo, input: TaskExecutionEventInput): TaskExecutionEvent {
180
+ const now = input.createdAt ?? Date.now();
181
+ const execution = ensureTaskExecution(task);
182
+
183
+ if (input.runId) {
184
+ execution.runId = input.runId;
185
+ }
186
+ if (input.sessionKey) {
187
+ execution.sessionKey = input.sessionKey;
188
+ }
189
+ if (input.status) {
190
+ execution.status = input.status;
191
+ } else {
192
+ execution.status = mapTaskStatusToExecutionStatus(task.status, execution.status);
193
+ }
194
+
195
+ if ((input.status === "running" || input.phase === "run_started") && !execution.startedAt) {
196
+ execution.startedAt = now;
197
+ }
198
+ if ((input.status === "running" || input.phase === "run_started") && !task.startedAt) {
199
+ task.startedAt = now;
200
+ }
201
+ if ((input.status === "running" || input.phase === "run_started") && (task.status === "pending" || task.status === "assigned")) {
202
+ task.status = "in_progress";
203
+ }
204
+
205
+ if (execution.status === "completed" || execution.status === "failed") {
206
+ execution.endedAt = execution.endedAt ?? now;
207
+ }
208
+
209
+ execution.lastUpdatedAt = now;
210
+ task.updatedAt = now;
211
+
212
+ const event: TaskExecutionEvent = {
213
+ id: generateId(),
214
+ type: input.type,
215
+ createdAt: now,
216
+ message: input.message,
217
+ phase: input.phase,
218
+ source: input.source,
219
+ stream: input.stream,
220
+ role: input.role ?? task.assignedRole,
221
+ workerId: input.workerId ?? task.assignedWorkerId,
222
+ };
223
+
224
+ execution.events.push(event);
225
+ if (execution.events.length > MAX_TASK_EXECUTION_EVENTS) {
226
+ execution.events = execution.events.slice(-MAX_TASK_EXECUTION_EVENTS);
227
+ }
228
+
229
+ return event;
230
+ }
231
+
232
+ export function buildTaskExecutionSummary(execution?: TaskExecution): TaskExecutionSummary | undefined {
233
+ if (!execution) {
234
+ return undefined;
235
+ }
236
+
237
+ return {
238
+ status: execution.status,
239
+ runId: execution.runId,
240
+ startedAt: execution.startedAt,
241
+ endedAt: execution.endedAt,
242
+ lastUpdatedAt: execution.lastUpdatedAt,
243
+ eventCount: execution.events.length,
244
+ lastEvent: execution.events[execution.events.length - 1],
245
+ };
246
+ }
247
+
248
+ export function serializeTask(task?: TaskInfo, includeExecutionEvents = false): Record<string, unknown> | undefined {
249
+ if (!task) {
250
+ return undefined;
251
+ }
252
+
253
+ const payload: Record<string, unknown> = { ...task };
254
+ if (!task.execution) {
255
+ return payload;
256
+ }
257
+
258
+ payload.execution = includeExecutionEvents
259
+ ? {
260
+ status: task.execution.status,
261
+ runId: task.execution.runId,
262
+ startedAt: task.execution.startedAt,
263
+ endedAt: task.execution.endedAt,
264
+ lastUpdatedAt: task.execution.lastUpdatedAt,
265
+ events: task.execution.events.map((event) => ({ ...event })),
266
+ }
267
+ : buildTaskExecutionSummary(task.execution);
268
+
269
+ return payload;
270
+ }
271
+
272
+ export function normalizeControllerIntakeSessionKey(input: unknown): string {
273
+ const fallback = `${CONTROLLER_INTAKE_SESSION_PREFIX}default`;
274
+ if (typeof input !== "string") {
275
+ return fallback;
276
+ }
277
+
278
+ const trimmed = input.trim();
279
+ if (!trimmed) {
280
+ return fallback;
281
+ }
282
+
283
+ const runtimeMatch = trimmed.match(CONTROLLER_INTAKE_AGENT_SESSION_RE);
284
+ if (trimmed.startsWith("agent:") && !runtimeMatch) {
285
+ return fallback;
286
+ }
287
+
288
+ const logicalKey = runtimeMatch?.[1] ?? trimmed;
289
+ if (!/^[a-zA-Z0-9:_-]{1,120}$/.test(logicalKey)) {
290
+ return fallback;
291
+ }
292
+
293
+ const normalizedLogicalKey = logicalKey.startsWith(CONTROLLER_INTAKE_SESSION_PREFIX)
294
+ ? logicalKey
295
+ : `${CONTROLLER_INTAKE_SESSION_PREFIX}${logicalKey}`;
296
+ return buildTeamClawAgentSessionKey(normalizedLogicalKey);
297
+ }
298
+
299
+ export function broadcastTaskExecutionEvent(
300
+ taskId: string,
301
+ task: TaskInfo,
302
+ event: TaskExecutionEvent,
303
+ deps: ControllerTaskDomainDeps,
304
+ ): void {
305
+ deps.wsServer.broadcastUpdate({
306
+ type: "task:execution",
307
+ data: {
308
+ taskId,
309
+ event,
310
+ execution: buildTaskExecutionSummary(task.execution),
311
+ },
312
+ });
313
+ }
314
+
315
+ export function recordTaskExecutionEvent(
316
+ taskId: string,
317
+ input: TaskExecutionEventInput,
318
+ deps: ControllerTaskDomainDeps,
319
+ ): { task?: TaskInfo; event?: TaskExecutionEvent; statusChanged: boolean } {
320
+ const { updateTeamState, wsServer } = deps;
321
+ let statusChanged = false;
322
+ let event: TaskExecutionEvent | undefined;
323
+
324
+ const state = updateTeamState((s) => {
325
+ const task = s.tasks[taskId];
326
+ if (!task) {
327
+ return;
328
+ }
329
+
330
+ const previousStatus = task.status;
331
+ event = appendTaskExecutionEvent(task, input);
332
+ statusChanged = previousStatus !== task.status;
333
+ });
334
+
335
+ const updatedTask = state.tasks[taskId];
336
+ if (updatedTask && event) {
337
+ broadcastTaskExecutionEvent(taskId, updatedTask, event, deps);
338
+ if (statusChanged) {
339
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
340
+ }
341
+ }
342
+
343
+ return { task: updatedTask, event, statusChanged };
344
+ }
345
+
346
+ export function canAcceptWorkerUpdate(task: TaskInfo | undefined, workerId: string): boolean {
347
+ if (!task || task.assignedWorkerId !== workerId || task.completedAt) {
348
+ return false;
349
+ }
350
+
351
+ return task.status === "assigned" ||
352
+ task.status === "in_progress" ||
353
+ task.status === "review" ||
354
+ task.status === "completed" ||
355
+ task.status === "failed";
356
+ }
357
+
358
+ export async function cancelTaskExecution(
359
+ taskId: string,
360
+ workerId: string | undefined,
361
+ reason: string,
362
+ deps: ControllerTaskDomainDeps,
363
+ ): Promise<void> {
364
+ if (!workerId) {
365
+ return;
366
+ }
367
+
368
+ const worker = deps.getTeamState()?.workers[workerId];
369
+ if (!worker) {
370
+ return;
371
+ }
372
+
373
+ let cancelled = false;
374
+ try {
375
+ // Issue #222: carry the worker's dispatch token so a token-paired worker accepts the cancel.
376
+ const res = await fetch(`${worker.url}/api/v1/tasks/${taskId}/cancel`, {
377
+ method: "POST",
378
+ headers: withWorkerDispatchToken({}, workerId, deps.config, deps.getTeamState()),
379
+ });
380
+ cancelled = res.ok;
381
+ if (!res.ok) {
382
+ deps.logger.warn(`Controller: worker cancel failed for ${taskId} on ${workerId} (${res.status})`);
383
+ }
384
+ } catch (err) {
385
+ deps.logger.warn(`Controller: failed to cancel task ${taskId} on ${workerId}: ${String(err)}`);
386
+ }
387
+
388
+ if (!cancelled) {
389
+ return;
390
+ }
391
+
392
+ recordTaskExecutionEvent(taskId, {
393
+ type: "lifecycle",
394
+ phase: "execution_cancelled",
395
+ source: "controller",
396
+ message: `Cancelled active execution before ${reason}.`,
397
+ workerId,
398
+ }, deps);
399
+ }