@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
@@ -0,0 +1,286 @@
1
+ import path from "node:path";
2
+ import { spawn } from "node:child_process";
3
+ const MANAGED_GATEWAY_PARENT_CHECK_INTERVAL_MS = 5_000;
4
+ const MANAGED_GATEWAY_PARENT_EXIT_GRACE_MS = 5_000;
5
+ export function spawnManagedGatewayProcess(options) {
6
+ const gatewayEntrypoint = path.resolve(options.gatewayEntrypoint);
7
+ const cwd = options.cwd ?? path.dirname(gatewayEntrypoint);
8
+ const child = spawn(process.execPath, buildManagedGatewayWrapperArgs(gatewayEntrypoint, options.gatewayPort), {
9
+ ...buildManagedProcessSpawnOptions({
10
+ cwd,
11
+ env: options.env,
12
+ stdio: options.stdio,
13
+ }),
14
+ });
15
+ attachSpawnErrorGuard(child, "managed-gateway");
16
+ return child;
17
+ }
18
+ export function spawnManagedCommandProcess(options) {
19
+ const cwd = options.cwd ?? process.cwd();
20
+ const child = spawn(process.execPath, buildManagedCommandWrapperArgs(options.command), {
21
+ ...buildManagedProcessSpawnOptions({
22
+ cwd,
23
+ env: options.env,
24
+ stdio: options.stdio,
25
+ }),
26
+ });
27
+ attachSpawnErrorGuard(child, "managed-command");
28
+ return child;
29
+ }
30
+ /**
31
+ * Prevent uncaught exception when spawn fails (e.g. ENOENT for missing cwd/binary).
32
+ * Without this guard, Node.js emits the error on process.nextTick which crashes the host.
33
+ */
34
+ function attachSpawnErrorGuard(child, label) {
35
+ child.on("error", (err) => {
36
+ console.error(`[teamclaw] spawn ${label} failed: ${err.message}`);
37
+ });
38
+ }
39
+ export async function stopManagedProcess(child, timeoutMs, onForceKill) {
40
+ if (child.exitCode !== null || child.signalCode !== null) {
41
+ return;
42
+ }
43
+ await new Promise((resolve) => {
44
+ let settled = false;
45
+ const finish = () => {
46
+ if (settled) {
47
+ return;
48
+ }
49
+ settled = true;
50
+ resolve();
51
+ };
52
+ const timeout = setTimeout(() => {
53
+ if (child.exitCode === null && child.signalCode === null) {
54
+ onForceKill?.();
55
+ signalManagedProcessPid(child.pid, "SIGKILL");
56
+ }
57
+ finish();
58
+ }, timeoutMs);
59
+ timeout.unref?.();
60
+ child.once("exit", () => {
61
+ clearTimeout(timeout);
62
+ finish();
63
+ });
64
+ signalManagedProcessPid(child.pid, "SIGTERM");
65
+ });
66
+ }
67
+ export async function stopManagedGatewayProcess(child, timeoutMs, onForceKill) {
68
+ await stopManagedProcess(child, timeoutMs, onForceKill);
69
+ }
70
+ export function signalManagedProcessPid(pid, signal) {
71
+ if (!pid || !Number.isFinite(pid) || pid <= 0) {
72
+ return;
73
+ }
74
+ if (process.platform !== "win32") {
75
+ try {
76
+ process.kill(-pid, signal);
77
+ return;
78
+ }
79
+ catch {
80
+ // Fall back to the direct PID when the wrapper process is already gone or the platform rejects group signaling.
81
+ }
82
+ }
83
+ try {
84
+ process.kill(pid, signal);
85
+ }
86
+ catch {
87
+ // Best-effort cleanup only.
88
+ }
89
+ }
90
+ export function signalManagedGatewayPid(pid, signal) {
91
+ signalManagedProcessPid(pid, signal);
92
+ }
93
+ function buildManagedProcessSpawnOptions(options) {
94
+ return {
95
+ cwd: options.cwd,
96
+ env: {
97
+ ...options.env,
98
+ TEAMCLAW_PARENT_PID: String(process.pid),
99
+ TEAMCLAW_PARENT_CHECK_INTERVAL_MS: String(MANAGED_GATEWAY_PARENT_CHECK_INTERVAL_MS),
100
+ TEAMCLAW_PARENT_EXIT_GRACE_MS: String(MANAGED_GATEWAY_PARENT_EXIT_GRACE_MS),
101
+ },
102
+ stdio: options.stdio ?? ["ignore", "pipe", "pipe"],
103
+ detached: process.platform !== "win32",
104
+ };
105
+ }
106
+ function buildManagedGatewayWrapperArgs(gatewayEntrypoint, gatewayPort) {
107
+ const wrapperScript = String.raw `
108
+ const { spawn } = require("node:child_process");
109
+
110
+ const gatewayEntrypoint = process.argv[1];
111
+ const gatewayPort = process.argv[2];
112
+ const parentPid = Number(process.env.TEAMCLAW_PARENT_PID || "0");
113
+ const parentCheckIntervalMs = Number(process.env.TEAMCLAW_PARENT_CHECK_INTERVAL_MS || "5000");
114
+ const parentExitGraceMs = Number(process.env.TEAMCLAW_PARENT_EXIT_GRACE_MS || "5000");
115
+ const shutdownSignals = process.platform === "win32"
116
+ ? ["SIGTERM", "SIGINT", "SIGBREAK"]
117
+ : ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"];
118
+
119
+ let shuttingDown = false;
120
+ let parentMonitor = null;
121
+
122
+ const child = spawn(process.execPath, [
123
+ gatewayEntrypoint,
124
+ "gateway",
125
+ "--allow-unconfigured",
126
+ "--bind",
127
+ "loopback",
128
+ "--port",
129
+ gatewayPort,
130
+ ], {
131
+ env: process.env,
132
+ stdio: "inherit",
133
+ });
134
+
135
+ function stopChild(signal) {
136
+ if (child.exitCode !== null || child.signalCode !== null) {
137
+ return;
138
+ }
139
+ try {
140
+ child.kill(signal);
141
+ } catch {
142
+ // ignore
143
+ }
144
+ }
145
+
146
+ function shutdown() {
147
+ if (shuttingDown) {
148
+ return;
149
+ }
150
+ shuttingDown = true;
151
+ if (parentMonitor) {
152
+ clearInterval(parentMonitor);
153
+ parentMonitor = null;
154
+ }
155
+ stopChild("SIGTERM");
156
+ const timeout = setTimeout(() => {
157
+ stopChild("SIGKILL");
158
+ }, parentExitGraceMs);
159
+ timeout.unref?.();
160
+ child.once("exit", () => {
161
+ clearTimeout(timeout);
162
+ process.exit(0);
163
+ });
164
+ }
165
+
166
+ if (parentPid > 1) {
167
+ parentMonitor = setInterval(() => {
168
+ try {
169
+ process.kill(parentPid, 0);
170
+ } catch {
171
+ shutdown();
172
+ }
173
+ }, parentCheckIntervalMs);
174
+ parentMonitor.unref?.();
175
+ }
176
+
177
+ for (const signal of shutdownSignals) {
178
+ process.once(signal, shutdown);
179
+ }
180
+
181
+ process.once("exit", () => {
182
+ stopChild("SIGTERM");
183
+ });
184
+
185
+ child.once("exit", (code, signal) => {
186
+ if (parentMonitor) {
187
+ clearInterval(parentMonitor);
188
+ parentMonitor = null;
189
+ }
190
+ if (shuttingDown) {
191
+ process.exit(code === null ? 0 : code);
192
+ return;
193
+ }
194
+ process.exit(code === null ? (signal ? 1 : 0) : code);
195
+ });
196
+ `;
197
+ return ["-e", wrapperScript, gatewayEntrypoint, String(gatewayPort)];
198
+ }
199
+ function buildManagedCommandWrapperArgs(command) {
200
+ const wrapperScript = String.raw `
201
+ const { spawn } = require("node:child_process");
202
+
203
+ const command = process.argv[1];
204
+ const parentPid = Number(process.env.TEAMCLAW_PARENT_PID || "0");
205
+ const parentCheckIntervalMs = Number(process.env.TEAMCLAW_PARENT_CHECK_INTERVAL_MS || "5000");
206
+ const parentExitGraceMs = Number(process.env.TEAMCLAW_PARENT_EXIT_GRACE_MS || "5000");
207
+ const shutdownSignals = process.platform === "win32"
208
+ ? ["SIGTERM", "SIGINT", "SIGBREAK"]
209
+ : ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"];
210
+ const shell = process.platform === "win32" ? "cmd.exe" : "sh";
211
+ const shellArgs = process.platform === "win32"
212
+ ? ["/d", "/s", "/c", command]
213
+ : ["-lc", command];
214
+
215
+ let shuttingDown = false;
216
+ let parentMonitor = null;
217
+
218
+ const child = spawn(shell, shellArgs, {
219
+ env: process.env,
220
+ stdio: "inherit",
221
+ });
222
+
223
+ function stopChild(signal) {
224
+ if (child.exitCode !== null || child.signalCode !== null) {
225
+ return;
226
+ }
227
+ try {
228
+ child.kill(signal);
229
+ } catch {
230
+ // ignore
231
+ }
232
+ }
233
+
234
+ function shutdown() {
235
+ if (shuttingDown) {
236
+ return;
237
+ }
238
+ shuttingDown = true;
239
+ if (parentMonitor) {
240
+ clearInterval(parentMonitor);
241
+ parentMonitor = null;
242
+ }
243
+ stopChild("SIGTERM");
244
+ const timeout = setTimeout(() => {
245
+ stopChild("SIGKILL");
246
+ }, parentExitGraceMs);
247
+ timeout.unref?.();
248
+ child.once("exit", () => {
249
+ clearTimeout(timeout);
250
+ process.exit(0);
251
+ });
252
+ }
253
+
254
+ if (parentPid > 1) {
255
+ parentMonitor = setInterval(() => {
256
+ try {
257
+ process.kill(parentPid, 0);
258
+ } catch {
259
+ shutdown();
260
+ }
261
+ }, parentCheckIntervalMs);
262
+ parentMonitor.unref?.();
263
+ }
264
+
265
+ for (const signal of shutdownSignals) {
266
+ process.once(signal, shutdown);
267
+ }
268
+
269
+ process.once("exit", () => {
270
+ stopChild("SIGTERM");
271
+ });
272
+
273
+ child.once("exit", (code, signal) => {
274
+ if (parentMonitor) {
275
+ clearInterval(parentMonitor);
276
+ parentMonitor = null;
277
+ }
278
+ if (shuttingDown) {
279
+ process.exit(code === null ? 0 : code);
280
+ return;
281
+ }
282
+ process.exit(code === null ? (signal ? 1 : 0) : code);
283
+ });
284
+ `;
285
+ return ["-e", wrapperScript, command];
286
+ }
@@ -0,0 +1,28 @@
1
+ export async function deliverMessageToWorker(worker, message, deps) {
2
+ const res = await fetch(`${worker.url}/api/v1/messages`, {
3
+ method: "POST",
4
+ headers: { "Content-Type": "application/json" },
5
+ body: JSON.stringify(message),
6
+ });
7
+ if (!res.ok) {
8
+ throw new Error(`worker ${worker.id} responded with ${res.status}`);
9
+ }
10
+ }
11
+ export async function routeDirectMessage(message, deps) {
12
+ const { getTeamState, logger, messageRouter } = deps;
13
+ const state = getTeamState();
14
+ if (!state) {
15
+ return false;
16
+ }
17
+ const routed = messageRouter.routeDirectMessage(message, state.workers);
18
+ if (!routed) {
19
+ return false;
20
+ }
21
+ try {
22
+ await deliverMessageToWorker(routed.worker, routed.message, deps);
23
+ }
24
+ catch (err) {
25
+ logger.warn(`Controller: failed to deliver message to ${routed.worker.id}: ${String(err)}`);
26
+ }
27
+ return true;
28
+ }
@@ -0,0 +1,38 @@
1
+ import { generateId } from "../protocol.js";
2
+ export class MessageRouter {
3
+ logger;
4
+ constructor(logger) {
5
+ this.logger = logger;
6
+ }
7
+ routeDirectMessage(message, workers) {
8
+ if (!message.toRole)
9
+ return null;
10
+ const targetWorker = Object.values(workers).find((w) => w.role === message.toRole && w.status !== "offline");
11
+ if (!targetWorker) {
12
+ this.logger.warn(`MessageRouter: no worker found for role ${message.toRole}`);
13
+ return null;
14
+ }
15
+ const routedMessage = {
16
+ ...message,
17
+ id: message.id || generateId(),
18
+ to: targetWorker.id,
19
+ createdAt: message.createdAt || Date.now(),
20
+ };
21
+ return { worker: targetWorker, message: routedMessage };
22
+ }
23
+ routeBroadcast(message, workers) {
24
+ const activeWorkers = Object.values(workers).filter((w) => w.status !== "offline" && w.id !== message.from);
25
+ return activeWorkers.map((worker) => ({
26
+ worker,
27
+ message: {
28
+ ...message,
29
+ id: generateId(),
30
+ to: worker.id,
31
+ createdAt: message.createdAt || Date.now(),
32
+ },
33
+ }));
34
+ }
35
+ routeReviewRequest(message, workers) {
36
+ return this.routeDirectMessage(message, workers);
37
+ }
38
+ }
@@ -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
+ }
@@ -0,0 +1,151 @@
1
+ import { validateRoleIdList } from "../roles.js";
2
+ import { deriveStableProjectKey } from "../openclaw-workspace.js";
3
+ export function normalizeManifestRoleList(raw) {
4
+ // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts.
5
+ // The hand-written TEAMCLAW_ROLE_IDS copy this function used to keep was
6
+ // removed by Phase 1.2 (single-source-of-truth convergence); the role set
7
+ // now lives only in role-ids.ts / roles.ts.
8
+ return validateRoleIdList(raw);
9
+ }
10
+ export function normalizeManifestStringList(raw) {
11
+ if (!Array.isArray(raw)) {
12
+ return [];
13
+ }
14
+ return raw
15
+ .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
16
+ .filter(Boolean);
17
+ }
18
+ export function normalizeOptionalManifestText(raw) {
19
+ if (typeof raw !== "string") {
20
+ return undefined;
21
+ }
22
+ const normalized = raw.trim();
23
+ return normalized || undefined;
24
+ }
25
+ export function normalizeClarificationOptions(raw) {
26
+ if (!Array.isArray(raw)) {
27
+ return [];
28
+ }
29
+ return raw
30
+ .filter((entry) => !!entry && typeof entry === "object")
31
+ .map((entry) => ({
32
+ value: typeof entry.value === "string" ? entry.value.trim() : "",
33
+ label: typeof entry.label === "string" ? entry.label.trim() : "",
34
+ hint: typeof entry.hint === "string" && entry.hint.trim() ? entry.hint.trim() : undefined,
35
+ }))
36
+ .filter((entry) => entry.value && entry.label);
37
+ }
38
+ export function normalizeClarificationQuestionSchema(raw) {
39
+ if (!raw || typeof raw !== "object") {
40
+ return undefined;
41
+ }
42
+ const input = raw;
43
+ const kind = typeof input.kind === "string" ? input.kind.trim() : "";
44
+ const title = typeof input.title === "string" ? input.title.trim() : "";
45
+ if (!title || !["single-select", "multi-select", "number", "text"].includes(kind)) {
46
+ return undefined;
47
+ }
48
+ const options = normalizeClarificationOptions(input.options);
49
+ const schema = {
50
+ kind: kind,
51
+ title,
52
+ description: normalizeOptionalManifestText(input.description),
53
+ required: input.required == null ? true : Boolean(input.required),
54
+ allowOther: Boolean(input.allowOther),
55
+ placeholder: normalizeOptionalManifestText(input.placeholder),
56
+ unit: normalizeOptionalManifestText(input.unit),
57
+ };
58
+ if (options.length > 0) {
59
+ schema.options = options;
60
+ }
61
+ if (typeof input.min === "number" && Number.isFinite(input.min)) {
62
+ schema.min = input.min;
63
+ }
64
+ if (typeof input.max === "number" && Number.isFinite(input.max)) {
65
+ schema.max = input.max;
66
+ }
67
+ if (typeof input.step === "number" && Number.isFinite(input.step)) {
68
+ schema.step = input.step;
69
+ }
70
+ if ((schema.kind === "single-select" || schema.kind === "multi-select") && (!schema.options || schema.options.length === 0)) {
71
+ return undefined;
72
+ }
73
+ return schema;
74
+ }
75
+ export function normalizeClarificationQuestionSchemas(raw) {
76
+ if (!Array.isArray(raw)) {
77
+ return [];
78
+ }
79
+ return raw
80
+ .map((entry) => normalizeClarificationQuestionSchema(entry))
81
+ .filter((entry) => Boolean(entry));
82
+ }
83
+ export function normalizeManifestCreatedTasks(raw) {
84
+ if (!Array.isArray(raw)) {
85
+ return [];
86
+ }
87
+ return raw
88
+ .filter((entry) => !!entry && typeof entry === "object")
89
+ .map((entry) => ({
90
+ title: typeof entry.title === "string" ? entry.title.trim() : "",
91
+ assignedRole: normalizeManifestRoleList([entry.assignedRole])[0],
92
+ expectedOutcome: typeof entry.expectedOutcome === "string" ? entry.expectedOutcome.trim() : "",
93
+ }))
94
+ .filter((entry) => entry.title && entry.expectedOutcome);
95
+ }
96
+ export function normalizeManifestDeferredTasks(raw) {
97
+ if (!Array.isArray(raw)) {
98
+ return [];
99
+ }
100
+ return raw
101
+ .filter((entry) => !!entry && typeof entry === "object")
102
+ .map((entry) => ({
103
+ title: typeof entry.title === "string" ? entry.title.trim() : "",
104
+ assignedRole: normalizeManifestRoleList([entry.assignedRole])[0],
105
+ blockedBy: typeof entry.blockedBy === "string" ? entry.blockedBy.trim() : "",
106
+ whenReady: typeof entry.whenReady === "string" ? entry.whenReady.trim() : "",
107
+ }))
108
+ .filter((entry) => entry.title && entry.blockedBy && entry.whenReady);
109
+ }
110
+ export function normalizeManifestCompletionOpportunities(raw) {
111
+ if (!Array.isArray(raw)) {
112
+ return [];
113
+ }
114
+ return raw
115
+ .filter((entry) => !!entry && typeof entry === "object")
116
+ .map((entry) => ({
117
+ title: typeof entry.title === "string" ? entry.title.trim() : "",
118
+ value: typeof entry.value === "string" ? entry.value.trim() : "",
119
+ summary: typeof entry.summary === "string" ? entry.summary.trim() : "",
120
+ }))
121
+ .filter((entry) => entry.title && entry.value && entry.summary);
122
+ }
123
+ export function normalizeControllerManifest(raw) {
124
+ if (!raw || typeof raw !== "object") {
125
+ return null;
126
+ }
127
+ const input = raw;
128
+ const requirementSummary = typeof input.requirementSummary === "string" ? input.requirementSummary.trim() : "";
129
+ if (!requirementSummary) {
130
+ return null;
131
+ }
132
+ const clarificationSchemas = normalizeClarificationQuestionSchemas(input.clarificationSchemas);
133
+ const clarificationQuestions = normalizeManifestStringList(input.clarificationQuestions);
134
+ return {
135
+ version: typeof input.version === "string" && input.version.trim() ? input.version.trim() : "1.0",
136
+ projectName: typeof input.projectName === "string" && input.projectName.trim()
137
+ ? (deriveStableProjectKey(input.projectName.trim()) || input.projectName.trim())
138
+ : undefined,
139
+ requirementSummary,
140
+ requiredRoles: normalizeManifestRoleList(input.requiredRoles),
141
+ clarificationsNeeded: Boolean(input.clarificationsNeeded),
142
+ clarificationQuestions: clarificationQuestions.length > 0 ? clarificationQuestions : clarificationSchemas.map((entry) => entry.title),
143
+ clarificationSchemas,
144
+ createdTasks: normalizeManifestCreatedTasks(input.createdTasks),
145
+ deferredTasks: normalizeManifestDeferredTasks(input.deferredTasks),
146
+ handoffPlan: normalizeOptionalManifestText(input.handoffPlan),
147
+ notes: normalizeOptionalManifestText(input.notes),
148
+ completionOpportunities: normalizeManifestCompletionOpportunities(input.completionOpportunities),
149
+ requirementFullyComplete: Boolean(input.requirementFullyComplete),
150
+ };
151
+ }