@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,132 @@
1
+ import os from "node:os";
2
+ import { generateId, createRegistrationRequest } from "./protocol.js";
3
+ // Phase 1.3: the worker role label/icon come from the active TeamProfile.
4
+ import { getActiveRole } from "./profile-loader.js";
5
+ import { loadWorkerIdentity, saveWorkerIdentity, clearWorkerIdentity } from "./state.js";
6
+ import { MDnsBrowser } from "./discovery.js";
7
+ function getLocalIp(targetHost) {
8
+ if (!targetHost || targetHost === "localhost" || targetHost === "127.0.0.1") {
9
+ return "localhost";
10
+ }
11
+ const interfaces = os.networkInterfaces();
12
+ for (const name of Object.keys(interfaces)) {
13
+ const addrs = interfaces[name];
14
+ if (!addrs)
15
+ continue;
16
+ for (const addr of addrs) {
17
+ if (addr.family === "IPv4" && !addr.internal) {
18
+ return addr.address;
19
+ }
20
+ }
21
+ }
22
+ return "localhost";
23
+ }
24
+ export class IdentityManager {
25
+ config;
26
+ logger;
27
+ identity = null;
28
+ browser;
29
+ constructor(config, logger) {
30
+ this.config = config;
31
+ this.logger = logger;
32
+ this.browser = new MDnsBrowser(logger);
33
+ }
34
+ hasIdentity() {
35
+ return this.identity !== null;
36
+ }
37
+ getIdentity() {
38
+ return this.identity;
39
+ }
40
+ async discoverControllerUrl() {
41
+ if (this.config.controllerUrl) {
42
+ return this.config.controllerUrl;
43
+ }
44
+ const results = await this.browser.browse(this.config.teamName, 5000);
45
+ if (results.length > 0) {
46
+ const controller = results[0];
47
+ return `http://${controller.host}:${controller.port}`;
48
+ }
49
+ return null;
50
+ }
51
+ async register() {
52
+ const requestedWorkerId = process.env.TEAMCLAW_WORKER_ID?.trim() || undefined;
53
+ const launchToken = process.env.TEAMCLAW_LAUNCH_TOKEN?.trim() || undefined;
54
+ const existing = await loadWorkerIdentity();
55
+ if (existing) {
56
+ if (requestedWorkerId && existing.workerId !== requestedWorkerId) {
57
+ await clearWorkerIdentity();
58
+ }
59
+ else {
60
+ this.identity = existing;
61
+ this.logger.info(`Identity: restored existing identity (workerId=${existing.workerId})`);
62
+ return existing;
63
+ }
64
+ }
65
+ const restored = await loadWorkerIdentity();
66
+ if (restored) {
67
+ this.identity = restored;
68
+ this.logger.info(`Identity: restored existing identity (workerId=${restored.workerId})`);
69
+ return restored;
70
+ }
71
+ const controllerUrl = await this.discoverControllerUrl();
72
+ if (!controllerUrl) {
73
+ this.logger.warn("Identity: no controller found via mDNS or manual URL");
74
+ return null;
75
+ }
76
+ const roleDef = getActiveRole(this.config.role);
77
+ const workerId = requestedWorkerId ?? generateId();
78
+ const controllerHost = new URL(controllerUrl).hostname;
79
+ // Prefer explicit override (set by provisioner for Docker/K8s workers),
80
+ // then detected IP (works for bridge-network containers and real hosts),
81
+ // then os.hostname() as last resort.
82
+ const advertisedHost = process.env.TEAMCLAW_ADVERTISE_HOST?.trim() ||
83
+ getLocalIp(controllerHost) ||
84
+ os.hostname();
85
+ const advertisedPort = process.env.TEAMCLAW_ADVERTISE_PORT?.trim()
86
+ ? Number(process.env.TEAMCLAW_ADVERTISE_PORT.trim())
87
+ : this.config.port;
88
+ const workerUrl = `http://${advertisedHost}:${advertisedPort}`;
89
+ const registration = createRegistrationRequest(workerId, this.config.role, roleDef?.label ?? this.config.role, workerUrl, roleDef?.capabilities ?? [], launchToken);
90
+ try {
91
+ const res = await fetch(`${controllerUrl}/api/v1/workers/register`, {
92
+ method: "POST",
93
+ headers: { "Content-Type": "application/json" },
94
+ body: JSON.stringify(registration),
95
+ });
96
+ if (!res.ok) {
97
+ const text = await res.text();
98
+ this.logger.error(`Identity: registration failed (${res.status}): ${text}`);
99
+ return null;
100
+ }
101
+ const identity = {
102
+ workerId,
103
+ role: this.config.role,
104
+ controllerUrl,
105
+ registeredAt: Date.now(),
106
+ };
107
+ this.identity = identity;
108
+ await saveWorkerIdentity(identity);
109
+ this.logger.info(`Identity: registered as ${this.config.role} (workerId=${workerId}) at ${controllerUrl}`);
110
+ return identity;
111
+ }
112
+ catch (err) {
113
+ this.logger.error(`Identity: registration error: ${err instanceof Error ? err.message : String(err)}`);
114
+ return null;
115
+ }
116
+ }
117
+ async clear() {
118
+ if (this.identity) {
119
+ try {
120
+ await fetch(`${this.identity.controllerUrl}/api/v1/workers/${this.identity.workerId}`, {
121
+ method: "DELETE",
122
+ });
123
+ }
124
+ catch {
125
+ // ignore
126
+ }
127
+ }
128
+ this.identity = null;
129
+ await clearWorkerIdentity();
130
+ this.logger.info("Identity: cleared");
131
+ }
132
+ }
@@ -0,0 +1 @@
1
+ export const TEAMCLAW_PUBLISHED_RUNTIME_IMAGE = "ghcr.io/topcheer/teamclaw-openclaw:latest";
@@ -0,0 +1,531 @@
1
+ // Phase 1.3: runtime role legitimacy is checked against the active
2
+ // TeamProfile (software-rd baseline); roles.ts keeps the registry-layer guard.
3
+ import { validateActiveRoleId } from "./profile-loader.js";
4
+ const CONTRACT_VERSION = "1.0";
5
+ const RESULT_DELIVERABLE_KINDS = new Set([
6
+ "file",
7
+ "directory",
8
+ "command",
9
+ "artifact",
10
+ "note",
11
+ ]);
12
+ const RESULT_FOLLOW_UP_TYPES = new Set([
13
+ "review",
14
+ "handoff",
15
+ "clarification",
16
+ "downstream-task",
17
+ ]);
18
+ const MESSAGE_INTENTS = new Set([
19
+ "question",
20
+ "announcement",
21
+ "handoff",
22
+ "review-request",
23
+ "review-response",
24
+ "update",
25
+ "coordination",
26
+ ]);
27
+ export function normalizeContractStringList(raw) {
28
+ if (!Array.isArray(raw)) {
29
+ return [];
30
+ }
31
+ return raw
32
+ .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
33
+ .filter(Boolean);
34
+ }
35
+ export function normalizeOptionalContractText(raw) {
36
+ if (typeof raw !== "string") {
37
+ return undefined;
38
+ }
39
+ const normalized = raw.trim();
40
+ return normalized || undefined;
41
+ }
42
+ export function normalizeContractRole(raw) {
43
+ // Phase 0.3 introduced single-source role validation; Phase 1.3 moved the
44
+ // runtime check to the active TeamProfile (validateActiveRoleId). This
45
+ // exported name keeps the contract-level API stable.
46
+ return validateActiveRoleId(raw);
47
+ }
48
+ export function summarizeContractText(text, maxChars = 180) {
49
+ const normalized = text.replace(/\s+/g, " ").trim();
50
+ if (!normalized) {
51
+ return "";
52
+ }
53
+ if (normalized.length <= maxChars) {
54
+ return normalized;
55
+ }
56
+ return `${normalized.slice(0, maxChars).trimEnd()}…`;
57
+ }
58
+ export function ensureTeamMessageContract(raw, fallback) {
59
+ return normalizeTeamMessageContract(raw) ?? buildBackfilledTeamMessageContract(fallback);
60
+ }
61
+ export function normalizeTeamMessageContract(raw) {
62
+ if (!raw || typeof raw !== "object") {
63
+ return null;
64
+ }
65
+ const input = raw;
66
+ const summary = typeof input.summary === "string" ? input.summary.trim() : "";
67
+ if (!summary) {
68
+ return null;
69
+ }
70
+ const intent = normalizeMessageIntent(input.intent) ?? "update";
71
+ return {
72
+ version: typeof input.version === "string" && input.version.trim() ? input.version.trim() : CONTRACT_VERSION,
73
+ intent,
74
+ summary,
75
+ details: normalizeOptionalContractText(input.details),
76
+ requestedAction: normalizeOptionalContractText(input.requestedAction),
77
+ requestedRole: normalizeContractRole(input.requestedRole),
78
+ needsResponse: Boolean(input.needsResponse),
79
+ references: normalizeContractStringList(input.references),
80
+ };
81
+ }
82
+ export function normalizeWorkerProgressContract(raw) {
83
+ if (!raw || typeof raw !== "object") {
84
+ return null;
85
+ }
86
+ const input = raw;
87
+ const summary = typeof input.summary === "string" ? input.summary.trim() : "";
88
+ if (!summary) {
89
+ return null;
90
+ }
91
+ const status = normalizeProgressStatus(input.status) ?? "in_progress";
92
+ return {
93
+ version: typeof input.version === "string" && input.version.trim() ? input.version.trim() : CONTRACT_VERSION,
94
+ summary,
95
+ status,
96
+ currentStep: normalizeOptionalContractText(input.currentStep),
97
+ nextStep: normalizeOptionalContractText(input.nextStep),
98
+ blockers: normalizeContractStringList(input.blockers),
99
+ };
100
+ }
101
+ export function backfillWorkerProgressContract(progress, status) {
102
+ const normalized = progress.trim();
103
+ if (!normalized) {
104
+ return undefined;
105
+ }
106
+ return {
107
+ version: CONTRACT_VERSION,
108
+ summary: summarizeContractText(normalized),
109
+ status: normalizeProgressStatus(status) ?? "in_progress",
110
+ currentStep: normalized,
111
+ blockers: extractQuestionOrBulletLines(normalized, 3, /blocked|waiting|stuck|need/i),
112
+ };
113
+ }
114
+ export function renderWorkerProgressText(contract, fallbackProgress) {
115
+ if (!contract) {
116
+ return fallbackProgress?.trim() ?? "";
117
+ }
118
+ const lines = [contract.summary];
119
+ if (contract.currentStep) {
120
+ lines.push(`Current step: ${contract.currentStep}`);
121
+ }
122
+ if (contract.nextStep) {
123
+ lines.push(`Next step: ${contract.nextStep}`);
124
+ }
125
+ if (contract.blockers.length > 0) {
126
+ lines.push(`Blockers: ${contract.blockers.join("; ")}`);
127
+ }
128
+ return lines.filter(Boolean).join("\n");
129
+ }
130
+ export function normalizeTaskHandoffContract(raw, fallback) {
131
+ if (raw && typeof raw === "object") {
132
+ const input = raw;
133
+ const summary = typeof input.summary === "string" ? input.summary.trim() : "";
134
+ const reason = typeof input.reason === "string" ? input.reason.trim() : "";
135
+ if (summary && reason) {
136
+ return {
137
+ version: typeof input.version === "string" && input.version.trim() ? input.version.trim() : CONTRACT_VERSION,
138
+ summary,
139
+ reason,
140
+ targetRole: normalizeContractRole(input.targetRole) ?? fallback.targetRole,
141
+ expectedNextStep: normalizeOptionalContractText(input.expectedNextStep),
142
+ artifacts: normalizeContractStringList(input.artifacts),
143
+ };
144
+ }
145
+ }
146
+ return {
147
+ version: CONTRACT_VERSION,
148
+ summary: fallback.summary?.trim() || buildDefaultHandoffSummary(fallback.targetRole, fallback.reason),
149
+ reason: fallback.reason.trim(),
150
+ targetRole: fallback.targetRole,
151
+ expectedNextStep: fallback.expectedNextStep?.trim() || undefined,
152
+ artifacts: (fallback.artifacts ?? []).map((entry) => entry.trim()).filter(Boolean),
153
+ };
154
+ }
155
+ export function normalizeWorkerTaskResultContract(raw) {
156
+ if (!raw || typeof raw !== "object") {
157
+ return null;
158
+ }
159
+ const input = raw;
160
+ const summary = typeof input.summary === "string" ? input.summary.trim() : "";
161
+ if (!summary) {
162
+ return null;
163
+ }
164
+ return {
165
+ version: typeof input.version === "string" && input.version.trim() ? input.version.trim() : CONTRACT_VERSION,
166
+ outcome: normalizeResultOutcome(input.outcome),
167
+ summary,
168
+ deliverables: normalizeResultDeliverables(input.deliverables),
169
+ keyPoints: normalizeContractStringList(input.keyPoints),
170
+ blockers: normalizeContractStringList(input.blockers),
171
+ followUps: normalizeResultFollowUps(input.followUps),
172
+ questions: normalizeContractStringList(input.questions),
173
+ notes: normalizeOptionalContractText(input.notes),
174
+ discoveredPatterns: normalizeContractStringList(input.discoveredPatterns),
175
+ };
176
+ }
177
+ export function backfillWorkerTaskResultContract(task, result, error) {
178
+ const normalizedResult = result.trim();
179
+ const normalizedError = error?.trim();
180
+ const summarySource = normalizedError
181
+ || firstMeaningfulLine(normalizedResult)
182
+ || task?.lastHandoff?.summary
183
+ || task?.description
184
+ || task?.title
185
+ || "Worker result summary unavailable.";
186
+ const outcome = normalizedError
187
+ ? "failed"
188
+ : task?.lastHandoff
189
+ ? "blocked"
190
+ : "completed";
191
+ const keyPoints = extractQuestionOrBulletLines(normalizedResult, 5);
192
+ const questions = extractQuestionOrBulletLines(normalizedResult, 5, /\?$/);
193
+ const blockers = normalizedError
194
+ ? [normalizedError]
195
+ : task?.lastHandoff
196
+ ? [task.lastHandoff.reason]
197
+ : [];
198
+ const followUps = task?.lastHandoff
199
+ ? [{
200
+ type: "handoff",
201
+ targetRole: task.lastHandoff.targetRole,
202
+ reason: task.lastHandoff.reason,
203
+ }]
204
+ : [];
205
+ return {
206
+ version: CONTRACT_VERSION,
207
+ outcome,
208
+ summary: summarizeContractText(summarySource),
209
+ deliverables: inferResultDeliverables(normalizedResult, normalizedError),
210
+ keyPoints,
211
+ blockers,
212
+ followUps,
213
+ questions,
214
+ notes: "Backfilled by TeamClaw because the worker did not submit a structured result contract.",
215
+ };
216
+ }
217
+ function buildBackfilledTeamMessageContract(fallback) {
218
+ const summary = fallback.summary?.trim() || summarizeContractText(fallback.content);
219
+ const intent = fallback.intent ?? inferMessageIntent(fallback.type, fallback.content);
220
+ const requestedAction = fallback.requestedAction?.trim() || buildDefaultRequestedAction(intent, fallback.toRole);
221
+ const references = [...(fallback.references ?? []), ...(fallback.taskId ? [fallback.taskId] : [])]
222
+ .map((entry) => entry.trim())
223
+ .filter(Boolean);
224
+ return {
225
+ version: CONTRACT_VERSION,
226
+ intent,
227
+ summary: summary || "TeamClaw message",
228
+ details: fallback.details?.trim() || deriveMessageDetails(summary, fallback.content),
229
+ requestedAction: requestedAction || undefined,
230
+ requestedRole: fallback.toRole,
231
+ needsResponse: typeof fallback.needsResponse === "boolean" ? fallback.needsResponse : intent === "question" || intent === "review-request" || intent === "handoff",
232
+ references: Array.from(new Set(references)),
233
+ };
234
+ }
235
+ function normalizeResultDeliverables(raw) {
236
+ if (!Array.isArray(raw)) {
237
+ return [];
238
+ }
239
+ return raw
240
+ .filter((entry) => !!entry && typeof entry === "object")
241
+ .map((entry) => {
242
+ const kind = typeof entry.kind === "string" && RESULT_DELIVERABLE_KINDS.has(entry.kind)
243
+ ? entry.kind
244
+ : "note";
245
+ const value = typeof entry.value === "string" ? entry.value.trim() : "";
246
+ const summary = normalizeOptionalContractText(entry.summary);
247
+ const artifactType = typeof entry.artifactType === "string" ? entry.artifactType : undefined;
248
+ const previewCommand = normalizeOptionalContractText(entry.previewCommand);
249
+ const previewCwd = normalizeOptionalContractText(entry.previewCwd);
250
+ const previewReadyPath = normalizeOptionalContractText(entry.previewReadyPath);
251
+ const liveUrl = normalizeOptionalContractText(entry.liveUrl);
252
+ return value ? { kind, value, summary, artifactType, previewCommand, previewCwd, previewReadyPath, liveUrl } : null;
253
+ })
254
+ .filter((entry) => !!entry);
255
+ }
256
+ function normalizeResultFollowUps(raw) {
257
+ if (!Array.isArray(raw)) {
258
+ return [];
259
+ }
260
+ return raw
261
+ .filter((entry) => !!entry && typeof entry === "object")
262
+ .map((entry) => {
263
+ const type = typeof entry.type === "string" && RESULT_FOLLOW_UP_TYPES.has(entry.type)
264
+ ? entry.type
265
+ : null;
266
+ const reason = typeof entry.reason === "string" ? entry.reason.trim() : "";
267
+ if (!type || !reason) {
268
+ return null;
269
+ }
270
+ return {
271
+ type,
272
+ targetRole: normalizeContractRole(entry.targetRole),
273
+ reason,
274
+ };
275
+ })
276
+ .filter((entry) => !!entry);
277
+ }
278
+ function normalizeResultOutcome(raw) {
279
+ if (raw === "blocked" || raw === "failed") {
280
+ return raw;
281
+ }
282
+ return "completed";
283
+ }
284
+ function normalizeProgressStatus(raw) {
285
+ if (raw === "in_progress" || raw === "review") {
286
+ return raw;
287
+ }
288
+ return null;
289
+ }
290
+ function normalizeMessageIntent(raw) {
291
+ if (typeof raw !== "string") {
292
+ return null;
293
+ }
294
+ const normalized = raw.trim();
295
+ return MESSAGE_INTENTS.has(normalized) ? normalized : null;
296
+ }
297
+ function inferMessageIntent(type, content) {
298
+ if (type === "review-request") {
299
+ return "review-request";
300
+ }
301
+ if (content.includes("?")) {
302
+ return "question";
303
+ }
304
+ return type === "broadcast" ? "announcement" : "update";
305
+ }
306
+ function buildDefaultRequestedAction(intent, toRole) {
307
+ switch (intent) {
308
+ case "question":
309
+ return "Answer the question so the sender can continue safely.";
310
+ case "review-request":
311
+ return toRole
312
+ ? `Review the referenced work as ${toRole} and reply with findings.`
313
+ : "Review the referenced work and reply with findings.";
314
+ case "handoff":
315
+ return "Take over the next step described in the handoff summary.";
316
+ case "announcement":
317
+ return "Read the update and align your work if needed.";
318
+ default:
319
+ return "";
320
+ }
321
+ }
322
+ function buildDefaultHandoffSummary(targetRole, reason) {
323
+ if (targetRole) {
324
+ return `Hand off the current task to ${targetRole}: ${summarizeContractText(reason)}`;
325
+ }
326
+ return `Hand off the current task: ${summarizeContractText(reason)}`;
327
+ }
328
+ function deriveMessageDetails(summary, content) {
329
+ const normalized = content.trim();
330
+ if (!normalized || normalized === summary) {
331
+ return undefined;
332
+ }
333
+ return normalized;
334
+ }
335
+ function firstMeaningfulLine(text) {
336
+ for (const line of text.split(/\n+/)) {
337
+ const normalized = line.replace(/^[-*]\s*/, "").trim();
338
+ if (normalized) {
339
+ return normalized;
340
+ }
341
+ }
342
+ return "";
343
+ }
344
+ function extractQuestionOrBulletLines(text, maxItems, matcher) {
345
+ const lines = text
346
+ .split(/\n+/)
347
+ .map((line) => line.replace(/^[-*]\s*/, "").trim())
348
+ .filter(Boolean)
349
+ .filter((line) => !matcher || matcher.test(line));
350
+ return Array.from(new Set(lines.map((line) => summarizeContractText(line, 220)))).slice(0, maxItems);
351
+ }
352
+ const WEB_HTML_FILENAMES = new Set(["index.html", "app.html", "main.html", "home.html"]);
353
+ /**
354
+ * Default preview command used when the worker does not provide one.
355
+ * This is a minimal static file server — the worker (LLM) is responsible
356
+ * for providing the real, framework-appropriate command via previewCommand
357
+ * in its result contract.
358
+ */
359
+ function inferPreviewCommand(_cwd, _resultText, _filePaths) {
360
+ return "npx -y serve -l {PORT}";
361
+ }
362
+ function isWebHtmlPath(filePath) {
363
+ const segments = filePath.replace(/\\/gu, "/").split("/");
364
+ const filename = segments[segments.length - 1] ?? "";
365
+ if (!filename.toLowerCase().endsWith(".html") && !filename.toLowerCase().endsWith(".htm")) {
366
+ return false;
367
+ }
368
+ if (filename.startsWith(".") || filename.includes(".config.") || filename.includes(".test.") || filename.includes(".spec.")) {
369
+ return false;
370
+ }
371
+ return true;
372
+ }
373
+ function inferResultDeliverables(result, error) {
374
+ if (error) {
375
+ return [{
376
+ kind: "note",
377
+ value: error,
378
+ summary: "Execution error surfaced by the worker.",
379
+ }];
380
+ }
381
+ const deliverables = [];
382
+ let webAppInferred = false;
383
+ const pathMatches = Array.from(result.matchAll(/(?:^|[\s:(`])([A-Za-z0-9_./-]+\.[A-Za-z0-9_-]+)/g))
384
+ .map((match) => match[1])
385
+ .filter(Boolean);
386
+ const uniquePaths = Array.from(new Set(pathMatches)).slice(0, 5);
387
+ for (const filePath of uniquePaths) {
388
+ if (!webAppInferred && isWebHtmlPath(filePath)) {
389
+ const segments = filePath.replace(/\\/gu, "/").split("/");
390
+ const filename = segments[segments.length - 1] ?? "";
391
+ const dirname = segments.length > 1 ? segments.slice(0, -1).join("/") : ".";
392
+ const isTopLevelHtml = WEB_HTML_FILENAMES.has(filename);
393
+ if (isTopLevelHtml || filename.toLowerCase().endsWith(".html")) {
394
+ webAppInferred = true;
395
+ deliverables.push({
396
+ kind: "directory",
397
+ value: dirname,
398
+ summary: `Web application at ${dirname}`,
399
+ artifactType: "web-app",
400
+ previewCommand: inferPreviewCommand(dirname, result, uniquePaths),
401
+ previewCwd: dirname,
402
+ previewReadyPath: "/",
403
+ });
404
+ continue;
405
+ }
406
+ }
407
+ deliverables.push({
408
+ kind: "file",
409
+ value: filePath,
410
+ });
411
+ }
412
+ if (deliverables.length > 0) {
413
+ return deliverables;
414
+ }
415
+ if (!result.trim()) {
416
+ return [];
417
+ }
418
+ return [{
419
+ kind: "note",
420
+ value: summarizeContractText(result, 300),
421
+ summary: "Backfilled from the worker's final reply.",
422
+ }];
423
+ }
424
+ /**
425
+ * Enrich existing deliverables with preview fields (artifactType, previewCommand, etc.)
426
+ * by inferring from the raw result text.
427
+ *
428
+ * This function only enriches when the worker did NOT already provide these fields.
429
+ * When the worker (LLM) submits a proper result contract with previewCommand and
430
+ * artifactType, we trust it completely — it knows its own code better than we do.
431
+ *
432
+ * Returns the contract with enriched deliverables if any enrichment happened, or null
433
+ * if no enrichment was needed.
434
+ */
435
+ export function enrichDeliverablesWithPreviewInference(contract, resultText) {
436
+ const { deliverables } = contract;
437
+ const existingWebApp = deliverables.find((d) => d.artifactType === "web-app");
438
+ if (existingWebApp) {
439
+ // Worker already provided a web-app with a real previewCommand — trust it.
440
+ if (existingWebApp.previewCommand?.trim()) {
441
+ return null;
442
+ }
443
+ // Worker declared web-app but no command — try to provide a fallback command.
444
+ const cwd = existingWebApp.previewCwd?.trim();
445
+ if (cwd && cwd !== "." && cwd !== "./") {
446
+ // Has a real cwd but no command — provide generic static serve fallback
447
+ existingWebApp.previewCommand = inferPreviewCommand(cwd, resultText, deliverables.map((d) => d.value ?? ""));
448
+ return { ...contract, deliverables };
449
+ }
450
+ }
451
+ // Strategy 1: Extract file paths from result text to detect HTML files
452
+ const allSources = [resultText, ...deliverables.map((d) => d.summary ?? "")];
453
+ const pathMatches = Array.from(allSources.join("\n").matchAll(/(?:^|[\s:(,`])([A-Za-z0-9_./-]+\.[A-Za-z0-9_-]+)/g))
454
+ .map((match) => match[1])
455
+ .filter(Boolean);
456
+ for (const filePath of Array.from(new Set(pathMatches)).slice(0, 5)) {
457
+ if (isWebHtmlPath(filePath)) {
458
+ const segments = filePath.replace(/\\/gu, "/").split("/");
459
+ const filename = segments[segments.length - 1] ?? "";
460
+ const dirname = segments.length > 1 ? segments.slice(0, -1).join("/") : ".";
461
+ if (!filename.toLowerCase().endsWith(".html") && !filename.toLowerCase().endsWith(".htm")) {
462
+ continue;
463
+ }
464
+ const allDeliverablePaths = deliverables.map((d) => d.value ?? "");
465
+ const matchingIndex = deliverables.findIndex((d) => d.kind === "directory"
466
+ && filePath.replace(/\\/gu, "/").startsWith(d.value?.replace(/\\/gu, "/").replace(/\/$/u, "")));
467
+ if (matchingIndex >= 0) {
468
+ deliverables[matchingIndex] = {
469
+ ...deliverables[matchingIndex],
470
+ artifactType: "web-app",
471
+ previewCommand: inferPreviewCommand(dirname, resultText, allDeliverablePaths),
472
+ previewCwd: dirname,
473
+ previewReadyPath: "/",
474
+ summary: deliverables[matchingIndex].summary || `Web application at ${dirname}`,
475
+ };
476
+ }
477
+ else {
478
+ deliverables.push({
479
+ kind: "directory",
480
+ value: dirname,
481
+ summary: `Web application at ${dirname}`,
482
+ artifactType: "web-app",
483
+ previewCommand: inferPreviewCommand(dirname, resultText, allDeliverablePaths),
484
+ previewCwd: dirname,
485
+ previewReadyPath: "/",
486
+ });
487
+ }
488
+ return { ...contract, deliverables };
489
+ }
490
+ }
491
+ // Strategy 2: If result text mentions HTML/web/blog/site keywords and there's a
492
+ // directory deliverable without artifactType, infer web-app from the directory itself.
493
+ const webKeywords = /\b(html|web\s*app|web\s*site|blog|index\.html|app\.html|homepage)\b/i;
494
+ const hasWebKeywords = webKeywords.test(resultText) || deliverables.some((d) => webKeywords.test(d.summary ?? ""));
495
+ if (hasWebKeywords) {
496
+ const dirDeliverable = deliverables.find((d) => d.kind === "directory" && !d.artifactType && d.value);
497
+ if (dirDeliverable) {
498
+ const cwd = dirDeliverable.value.replace(/\/$/u, "");
499
+ const allDeliverablePaths = deliverables.map((d) => d.value ?? "");
500
+ deliverables[deliverables.indexOf(dirDeliverable)] = {
501
+ ...dirDeliverable,
502
+ artifactType: "web-app",
503
+ previewCommand: inferPreviewCommand(cwd, resultText, allDeliverablePaths),
504
+ previewCwd: cwd,
505
+ previewReadyPath: "/",
506
+ summary: dirDeliverable.summary || `Web application at ${cwd}`,
507
+ };
508
+ return { ...contract, deliverables };
509
+ }
510
+ }
511
+ // Strategy 3: Extract directory paths that contain HTML files from result text
512
+ // (e.g. "blog/index.html" → directory "blog"). This handles cases where deliverables
513
+ // are all "note" type but result text references HTML files in directories.
514
+ const dirHtmlPattern = /([A-Za-z0-9_.-]+\/)[A-Za-z0-9_.-]+\.html\b/g;
515
+ const dirMatches = Array.from(resultText.matchAll(dirHtmlPattern)).map((m) => m[1].replace(/\/$/u, ""));
516
+ const uniqueDirs = Array.from(new Set(dirMatches));
517
+ if (uniqueDirs.length > 0 && hasWebKeywords) {
518
+ const dirname = uniqueDirs[0];
519
+ deliverables.push({
520
+ kind: "directory",
521
+ value: dirname,
522
+ summary: `Web application at ${dirname}`,
523
+ artifactType: "web-app",
524
+ previewCommand: inferPreviewCommand(dirname, resultText, [dirname]),
525
+ previewCwd: dirname,
526
+ previewReadyPath: "/",
527
+ });
528
+ return { ...contract, deliverables };
529
+ }
530
+ return null;
531
+ }