@teamclaws/teamclaw 2026.8.0 → 2026.8.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 (54) hide show
  1. package/dist/api.js +1 -0
  2. package/dist/index.js +325 -0
  3. package/dist/src/config.js +381 -0
  4. package/dist/src/controller/controller-capacity.js +14 -0
  5. package/dist/src/controller/controller-service.js +393 -0
  6. package/dist/src/controller/controller-tools.js +582 -0
  7. package/dist/src/controller/delivery-report.js +458 -0
  8. package/dist/src/controller/github-auth.js +564 -0
  9. package/dist/src/controller/http-server.js +6032 -0
  10. package/dist/src/controller/kickoff-orchestrator.js +220 -0
  11. package/dist/src/controller/managed-gateway-process.js +286 -0
  12. package/dist/src/controller/message-router.js +38 -0
  13. package/dist/src/controller/orchestration-manifest.js +173 -0
  14. package/dist/src/controller/preview-manager.js +586 -0
  15. package/dist/src/controller/prompt-injector.js +187 -0
  16. package/dist/src/controller/role-inference.js +35 -0
  17. package/dist/src/controller/task-router.js +67 -0
  18. package/dist/src/controller/tunnel-manager.js +548 -0
  19. package/dist/src/controller/websocket.js +42 -0
  20. package/dist/src/controller/worker-provisioning.js +1648 -0
  21. package/dist/src/discovery.js +86 -0
  22. package/dist/src/git-collaboration.js +694 -0
  23. package/dist/src/identity.js +131 -0
  24. package/dist/src/install-defaults.js +1 -0
  25. package/dist/src/interaction-contracts.js +531 -0
  26. package/dist/src/networking.js +91 -0
  27. package/dist/src/openclaw-workspace.js +903 -0
  28. package/dist/src/prompt-policy.js +373 -0
  29. package/dist/src/protocol.js +58 -0
  30. package/dist/src/roles.js +349 -0
  31. package/dist/src/state.js +183 -0
  32. package/dist/src/task-executor.js +1033 -0
  33. package/dist/src/teamauto/github-client.js +192 -0
  34. package/dist/src/teamauto/norms.js +85 -0
  35. package/dist/src/teamauto/repo-sync.js +201 -0
  36. package/dist/src/teamauto/scanner.js +179 -0
  37. package/dist/src/teamauto/schedule.js +123 -0
  38. package/dist/src/teamauto/scheduler.js +688 -0
  39. package/dist/src/teamauto/store.js +133 -0
  40. package/dist/src/types.js +243 -0
  41. package/dist/src/ui/app.js +4292 -0
  42. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  43. package/dist/src/ui/github-login.html +296 -0
  44. package/dist/src/ui/index.html +414 -0
  45. package/dist/src/ui/style.css +2611 -0
  46. package/dist/src/worker/http-handler.js +146 -0
  47. package/dist/src/worker/message-queue.js +24 -0
  48. package/dist/src/worker/prompt-injector.js +42 -0
  49. package/dist/src/worker/skill-installer.js +253 -0
  50. package/dist/src/worker/tools.js +541 -0
  51. package/dist/src/worker/worker-service.js +234 -0
  52. package/dist/src/workspace-browser.js +269 -0
  53. package/openclaw.plugin.json +1 -1
  54. package/package.json +1 -1
@@ -0,0 +1,586 @@
1
+ import net from "node:net";
2
+ import path from "node:path";
3
+ import fs from "node:fs/promises";
4
+ import { resolveTeamClawAgentWorkspaceRootDir } from "../openclaw-workspace.js";
5
+ import { spawnManagedCommandProcess, stopManagedProcess } from "./managed-gateway-process.js";
6
+ const PREVIEW_LAUNCH_TIMEOUT_MS = 120_000;
7
+ const PREVIEW_HEALTH_INTERVAL_MS = 1_500;
8
+ const PREVIEW_STOP_TIMEOUT_MS = 5_000;
9
+ const GENERIC_SERVE_COMMAND = "npx -y serve -l {PORT}";
10
+ /**
11
+ * Detect the tech stack from files in `cwd` and return a suitable preview command.
12
+ * Only overrides `existingCommand` when it is the generic static file server
13
+ * and the deliverable explicitly specifies a runnable framework.
14
+ *
15
+ * IMPORTANT: The worker (LLM) is responsible for providing the real preview
16
+ * command in its result contract. This function only provides a lightweight
17
+ * fallback for static file directories.
18
+ */
19
+ async function resolveSmartPreviewCommand(cwd, existingCommand) {
20
+ if (existingCommand !== GENERIC_SERVE_COMMAND) {
21
+ return existingCommand;
22
+ }
23
+ try {
24
+ const entries = await fs.readdir(cwd, { withFileTypes: true });
25
+ const filenames = entries.filter((e) => e.isFile()).map((e) => e.name);
26
+ // Node.js — detect package.json with dev/start script
27
+ if (filenames.includes("package.json")) {
28
+ const pkgRaw = await fs.readFile(path.join(cwd, "package.json"), "utf-8").catch(() => "");
29
+ if (pkgRaw) {
30
+ try {
31
+ const pkg = JSON.parse(pkgRaw);
32
+ if (pkg.scripts?.dev) {
33
+ return "npm run dev -- --port {PORT}";
34
+ }
35
+ if (pkg.scripts?.start) {
36
+ return "npm start -- --port {PORT}";
37
+ }
38
+ }
39
+ catch {
40
+ // ignore parse errors
41
+ }
42
+ }
43
+ }
44
+ // Python — detect requirements.txt or pyproject.toml and pick the right runner
45
+ if (filenames.includes("requirements.txt") || filenames.includes("pyproject.toml")) {
46
+ // Prefer venv python if available (workers typically create a venv)
47
+ const dirnames = entries.filter((e) => e.isDirectory()).map((e) => e.name);
48
+ const venvDir = dirnames.find((d) => d === "venv" || d === ".venv" || d === "env");
49
+ const pythonBin = venvDir ? `${venvDir}/bin/python` : "python";
50
+ // Check for a main.py that imports FastAPI/Flask
51
+ const mainPy = filenames.includes("main.py")
52
+ ? await fs.readFile(path.join(cwd, "main.py"), "utf-8").catch(() => "")
53
+ : filenames.includes("app.py")
54
+ ? await fs.readFile(path.join(cwd, "app.py"), "utf-8").catch(() => "")
55
+ : "";
56
+ if (mainPy) {
57
+ const entryFile = filenames.includes("main.py") ? "main" : "app";
58
+ if (/from\s+fastapi\b|import\s+fastapi/i.test(mainPy)) {
59
+ const appMatch = mainPy.match(/(\w+)\s*=\s*FastAPI\s*\(/);
60
+ const appVar = appMatch?.[1] ?? "app";
61
+ return `${pythonBin} -m uvicorn ${entryFile}:${appVar} --host 0.0.0.0 --port {PORT}`;
62
+ }
63
+ if (/from\s+flask\b|import\s+flask/i.test(mainPy)) {
64
+ return `${pythonBin} -m flask --app ${entryFile} run --host 0.0.0.0 --port {PORT}`;
65
+ }
66
+ }
67
+ // Generic Python with manage.py (Django)
68
+ if (filenames.includes("manage.py")) {
69
+ return `${pythonBin} manage.py runserver 0.0.0.0:{PORT}`;
70
+ }
71
+ }
72
+ // Java — detect pom.xml (Maven / Spring Boot)
73
+ if (filenames.includes("pom.xml")) {
74
+ const pomRaw = await fs.readFile(path.join(cwd, "pom.xml"), "utf-8").catch(() => "");
75
+ if (pomRaw.includes("spring-boot")) {
76
+ return "mvn spring-boot:run -Dspring-boot.run.arguments=--server.port={PORT}";
77
+ }
78
+ // Gradle wrapper
79
+ }
80
+ if (filenames.includes("build.gradle") || filenames.includes("build.gradle.kts")) {
81
+ return "./gradlew bootRun --args='--server.port={PORT}'";
82
+ }
83
+ // Go — detect go.mod
84
+ if (filenames.includes("go.mod")) {
85
+ if (filenames.includes("main.go")) {
86
+ return "go run . --port {PORT}";
87
+ }
88
+ }
89
+ // Rust — detect Cargo.toml
90
+ if (filenames.includes("Cargo.toml")) {
91
+ return "cargo run -- --port {PORT}";
92
+ }
93
+ }
94
+ catch {
95
+ // cwd may not exist yet or be unreadable
96
+ }
97
+ return existingCommand;
98
+ }
99
+ function normalizeOptionalText(value) {
100
+ if (typeof value !== "string") {
101
+ return undefined;
102
+ }
103
+ const normalized = value.trim();
104
+ return normalized || undefined;
105
+ }
106
+ function normalizePreviewReadyPath(value) {
107
+ const normalized = normalizeOptionalText(value);
108
+ if (!normalized) {
109
+ return "/";
110
+ }
111
+ return normalized.startsWith("/") ? normalized : `/${normalized}`;
112
+ }
113
+ function normalizePreviewCwd(deliverable) {
114
+ const explicit = normalizeOptionalText(deliverable.previewCwd);
115
+ if (explicit) {
116
+ return explicit;
117
+ }
118
+ const value = normalizeOptionalText(deliverable.value);
119
+ if (!value) {
120
+ return undefined;
121
+ }
122
+ if (deliverable.kind === "directory") {
123
+ return value;
124
+ }
125
+ const directory = path.posix.dirname(value);
126
+ return directory === "." ? "." : directory;
127
+ }
128
+ function buildPreviewId(taskId, deliverableIndex) {
129
+ return `preview-${taskId}-${deliverableIndex}`;
130
+ }
131
+ function buildPreviewLiveUrl(previewId) {
132
+ return `/api/v1/previews/${encodeURIComponent(previewId)}/`;
133
+ }
134
+ function isWorkspacePathInsideRoot(rootDir, targetPath) {
135
+ const relative = path.relative(rootDir, targetPath);
136
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
137
+ }
138
+ function resolveWorkspaceDirectory(rootDir, relativePath) {
139
+ const resolved = path.resolve(rootDir, relativePath);
140
+ return isWorkspacePathInsideRoot(rootDir, resolved) ? resolved : null;
141
+ }
142
+ export class PreviewManager {
143
+ deps;
144
+ processes = new Map();
145
+ stoppingPreviewIds = new Set();
146
+ healthMonitorTimer = null;
147
+ static HEALTH_MONITOR_INTERVAL_MS = 30_000; // check every 30s
148
+ constructor(deps) {
149
+ this.deps = deps;
150
+ }
151
+ /** Start periodic health monitoring for all healthy previews. */
152
+ startHealthMonitor() {
153
+ if (this.healthMonitorTimer)
154
+ return;
155
+ this.healthMonitorTimer = setInterval(() => {
156
+ void this.runHealthChecks();
157
+ }, PreviewManager.HEALTH_MONITOR_INTERVAL_MS);
158
+ this.healthMonitorTimer.unref?.();
159
+ }
160
+ stopHealthMonitor() {
161
+ if (this.healthMonitorTimer) {
162
+ clearInterval(this.healthMonitorTimer);
163
+ this.healthMonitorTimer = null;
164
+ }
165
+ }
166
+ /** Re-check all "healthy" previews; mark failed if process gone or not responding. */
167
+ async runHealthChecks() {
168
+ const state = this.deps.getTeamState();
169
+ if (!state)
170
+ return;
171
+ const healthyPreviews = Object.values(state.previews ?? {}).filter((p) => p.status === "healthy");
172
+ for (const preview of healthyPreviews) {
173
+ // Check if process is still alive
174
+ const proc = this.processes.get(preview.id);
175
+ if (!proc) {
176
+ this.markPreviewFailed(preview.id, "Preview process is no longer running.");
177
+ continue;
178
+ }
179
+ // Check if still responding to HTTP
180
+ const healthy = await this.checkPreviewHealth(preview);
181
+ if (!healthy) {
182
+ this.deps.logger.warn(`Controller: preview ${preview.id} failed periodic health check`);
183
+ this.markPreviewFailed(preview.id, "Preview stopped responding to health checks.");
184
+ }
185
+ else {
186
+ this.deps.updateTeamState((s) => {
187
+ const p = s.previews?.[preview.id];
188
+ if (p)
189
+ p.lastHealthCheckAt = Date.now();
190
+ });
191
+ }
192
+ }
193
+ }
194
+ async syncTaskPreviews(taskId) {
195
+ const state = this.deps.getTeamState();
196
+ const task = state?.tasks[taskId];
197
+ if (!task || task.status !== "completed" || !task.resultContract) {
198
+ await this.stopTaskPreviews(taskId, !task ? "task removed" : `task moved to ${task.status}`);
199
+ return;
200
+ }
201
+ const specs = await this.collectPreviewSpecs(taskId, task.resultContract);
202
+ const desiredIds = new Set(specs.map((spec) => spec.previewId));
203
+ const existingIds = Object.values(state?.previews ?? {})
204
+ .filter((preview) => preview.taskId === taskId)
205
+ .map((preview) => preview.id);
206
+ for (const previewId of existingIds) {
207
+ if (!desiredIds.has(previewId)) {
208
+ await this.removePreview(previewId, "preview no longer declared on the task result");
209
+ }
210
+ }
211
+ for (const spec of specs) {
212
+ await this.ensurePreview(spec);
213
+ }
214
+ if (specs.length > 0)
215
+ this.startHealthMonitor();
216
+ }
217
+ async stopTaskPreviews(taskId, reason) {
218
+ const previewIds = Object.values(this.deps.getTeamState()?.previews ?? {})
219
+ .filter((preview) => preview.taskId === taskId)
220
+ .map((preview) => preview.id);
221
+ for (const previewId of previewIds) {
222
+ await this.removePreview(previewId, reason);
223
+ }
224
+ }
225
+ static isPreviewableDeliverable(d) {
226
+ return d.artifactType === "web-app" || d.artifactType === "static-site" || d.artifactType === "rest-api";
227
+ }
228
+ async restorePreviewsOnStartup() {
229
+ const state = this.deps.getTeamState();
230
+ if (!state) {
231
+ this.deps.logger.warn("PreviewManager: restorePreviewsOnStartup called but no team state");
232
+ return;
233
+ }
234
+ const completedTasks = Object.values(state.tasks).filter((t) => t.status === "completed" && t.resultContract);
235
+ const tasksWithPreviews = completedTasks.filter((t) => t.resultContract.deliverables.some((d) => PreviewManager.isPreviewableDeliverable(d)));
236
+ this.deps.logger.info(`PreviewManager: restorePreviewsOnStartup: ${tasksWithPreviews.length} tasks with previews out of ${completedTasks.length} completed`);
237
+ for (const preview of Object.values(state.previews ?? {})) {
238
+ const task = state.tasks[preview.taskId];
239
+ const deliverable = task?.resultContract?.deliverables?.[preview.deliverableIndex];
240
+ if (!task || task.status !== "completed" || !deliverable || !PreviewManager.isPreviewableDeliverable(deliverable)) {
241
+ await this.removePreview(preview.id, "preview can no longer be restored from task state");
242
+ }
243
+ }
244
+ for (const task of Object.values(state.tasks)) {
245
+ if (task.status !== "completed" || !task.resultContract) {
246
+ continue;
247
+ }
248
+ if (!task.resultContract.deliverables.some((d) => PreviewManager.isPreviewableDeliverable(d))) {
249
+ continue;
250
+ }
251
+ try {
252
+ await this.syncTaskPreviews(task.id);
253
+ }
254
+ catch (err) {
255
+ this.deps.logger.warn(`Controller: failed to restore preview(s) for ${task.id}: ${String(err)}`);
256
+ }
257
+ }
258
+ this.startHealthMonitor();
259
+ }
260
+ async stopAll(reason = "controller shutdown") {
261
+ this.stopHealthMonitor();
262
+ const previewIds = Array.from(new Set([
263
+ ...this.processes.keys(),
264
+ ...Object.keys(this.deps.getTeamState()?.previews ?? {}),
265
+ ]));
266
+ for (const previewId of previewIds) {
267
+ await this.stopPreviewProcess(previewId, reason, { removeRecord: false, clearLiveUrl: false });
268
+ }
269
+ }
270
+ async collectPreviewSpecs(taskId, contract) {
271
+ const workspaceRoot = resolveTeamClawAgentWorkspaceRootDir();
272
+ const specs = [];
273
+ for (const [deliverableIndex, deliverable] of contract.deliverables.entries()) {
274
+ if (deliverable.artifactType !== "web-app" && deliverable.artifactType !== "static-site" && deliverable.artifactType !== "rest-api") {
275
+ continue;
276
+ }
277
+ const rawCommand = normalizeOptionalText(deliverable.previewCommand) ?? GENERIC_SERVE_COMMAND;
278
+ const previewCwd = normalizePreviewCwd(deliverable);
279
+ if (!previewCwd) {
280
+ this.deps.logger.warn(`Controller: skipping preview for task ${taskId} deliverable[${deliverableIndex}] — cannot resolve previewCwd from value "${deliverable.value}"`);
281
+ continue;
282
+ }
283
+ // Resolve the actual working directory for file-system detection
284
+ const resolvedCwd = resolveWorkspaceDirectory(workspaceRoot, previewCwd);
285
+ const previewCommand = resolvedCwd
286
+ ? await resolveSmartPreviewCommand(resolvedCwd, rawCommand)
287
+ : rawCommand;
288
+ specs.push({
289
+ previewId: buildPreviewId(taskId, deliverableIndex),
290
+ taskId,
291
+ deliverableIndex,
292
+ deliverableValue: deliverable.value,
293
+ previewCommand,
294
+ previewCwd,
295
+ previewReadyPath: normalizePreviewReadyPath(deliverable.previewReadyPath),
296
+ liveUrl: buildPreviewLiveUrl(buildPreviewId(taskId, deliverableIndex)),
297
+ });
298
+ }
299
+ return specs;
300
+ }
301
+ async ensurePreview(spec) {
302
+ const current = this.deps.getTeamState()?.previews?.[spec.previewId];
303
+ this.setTaskDeliverableLiveUrl(spec.taskId, spec.deliverableIndex, spec.liveUrl);
304
+ const isSameConfiguration = current
305
+ && current.previewCommand === spec.previewCommand
306
+ && current.previewCwd === spec.previewCwd
307
+ && current.previewReadyPath === spec.previewReadyPath
308
+ && current.deliverableValue === spec.deliverableValue;
309
+ if (isSameConfiguration
310
+ && this.processes.has(spec.previewId)
311
+ && (current?.status === "healthy" || current?.status === "launching")) {
312
+ return;
313
+ }
314
+ if (current || this.processes.has(spec.previewId)) {
315
+ await this.stopPreviewProcess(spec.previewId, "preview configuration refreshed", {
316
+ removeRecord: false,
317
+ clearLiveUrl: false,
318
+ });
319
+ }
320
+ const targetPort = await this.reserveEphemeralPort();
321
+ const now = Date.now();
322
+ const record = {
323
+ id: spec.previewId,
324
+ taskId: spec.taskId,
325
+ deliverableIndex: spec.deliverableIndex,
326
+ deliverableValue: spec.deliverableValue,
327
+ previewCommand: spec.previewCommand,
328
+ previewCwd: spec.previewCwd,
329
+ previewReadyPath: spec.previewReadyPath,
330
+ liveUrl: spec.liveUrl,
331
+ targetPort,
332
+ status: "launching",
333
+ createdAt: current?.createdAt ?? now,
334
+ updatedAt: now,
335
+ };
336
+ this.deps.updateTeamState((state) => {
337
+ if (!state.previews) {
338
+ state.previews = {};
339
+ }
340
+ state.previews[spec.previewId] = record;
341
+ const task = state.tasks[spec.taskId];
342
+ const deliverable = task?.resultContract?.deliverables?.[spec.deliverableIndex];
343
+ if (deliverable) {
344
+ deliverable.liveUrl = spec.liveUrl;
345
+ }
346
+ });
347
+ await this.launchPreview(record);
348
+ }
349
+ async launchPreview(record) {
350
+ const workspaceRoot = resolveTeamClawAgentWorkspaceRootDir();
351
+ const cwd = resolveWorkspaceDirectory(workspaceRoot, record.previewCwd);
352
+ if (!cwd) {
353
+ this.markPreviewFailed(record.id, `Dynamic preview path must stay inside the workspace: ${record.previewCwd}`);
354
+ return;
355
+ }
356
+ try {
357
+ await fs.access(cwd, fs.constants.R_OK);
358
+ }
359
+ catch {
360
+ this.markPreviewFailed(record.id, `Dynamic preview cwd does not exist or is not readable: ${cwd}`);
361
+ return;
362
+ }
363
+ // Sanitize preview command: strip redundant `cd <path> &&` prefix since cwd is already set
364
+ let sanitizedCommand = record.previewCommand;
365
+ sanitizedCommand = sanitizedCommand.replace(/^\s*cd\s+\S+\s*&&\s*/u, "");
366
+ // Strip `source .../activate &&` and `venv setup &&` — we handle venv via PATH below
367
+ sanitizedCommand = sanitizedCommand.replace(/\bsource\s+\S*activate\s*&&\s*/gu, "");
368
+ sanitizedCommand = sanitizedCommand.replace(/\bpython3?\s+-m\s+venv\s+\S+\s*&&\s*/gu, "");
369
+ sanitizedCommand = sanitizedCommand.replace(/\bpip\s+install\s+[^&]+&&\s*/gu, "");
370
+ const resolvedCommand = sanitizedCommand
371
+ .replace(/\{PORT\}/gu, String(record.targetPort));
372
+ // Auto-detect Python venv and prepend to PATH
373
+ const extraEnv = {};
374
+ const venvNames = ["venv", ".venv", "env"];
375
+ for (const vn of venvNames) {
376
+ const venvBin = path.join(cwd, vn, "bin");
377
+ try {
378
+ await fs.access(path.join(venvBin, "python"), fs.constants.X_OK);
379
+ extraEnv.PATH = `${venvBin}:${process.env.PATH ?? ""}`;
380
+ extraEnv.VIRTUAL_ENV = path.join(cwd, vn);
381
+ this.deps.logger.info(`Controller: using Python venv at ${venvBin} for preview ${record.id}`);
382
+ break;
383
+ }
384
+ catch {
385
+ // no venv here
386
+ }
387
+ }
388
+ // Pre-install Python dependencies if requirements.txt exists and venv is available
389
+ if (extraEnv.VIRTUAL_ENV) {
390
+ const reqPath = path.join(cwd, "requirements.txt");
391
+ try {
392
+ await fs.access(reqPath, fs.constants.R_OK);
393
+ const pipBin = path.join(extraEnv.VIRTUAL_ENV, "bin", "pip");
394
+ const pipInstall = spawnManagedCommandProcess({
395
+ command: `${pipBin} install -q -r requirements.txt`,
396
+ cwd,
397
+ env: { ...process.env, ...extraEnv },
398
+ });
399
+ await new Promise((resolve) => {
400
+ pipInstall.on("exit", () => resolve());
401
+ pipInstall.on("error", () => resolve());
402
+ setTimeout(() => resolve(), 60_000);
403
+ });
404
+ }
405
+ catch {
406
+ // no requirements.txt or pip failed — proceed anyway
407
+ }
408
+ }
409
+ const child = spawnManagedCommandProcess({
410
+ command: resolvedCommand,
411
+ cwd,
412
+ env: {
413
+ ...process.env,
414
+ ...extraEnv,
415
+ HOST: "0.0.0.0",
416
+ PORT: String(record.targetPort),
417
+ TEAMCLAW_PREVIEW_BASE_PATH: record.liveUrl.replace(/\/$/u, ""),
418
+ TEAMCLAW_PREVIEW_URL: record.liveUrl,
419
+ },
420
+ });
421
+ this.processes.set(record.id, child);
422
+ this.deps.updateTeamState((state) => {
423
+ const preview = state.previews?.[record.id];
424
+ if (!preview) {
425
+ return;
426
+ }
427
+ preview.pid = child.pid ?? undefined;
428
+ preview.status = "launching";
429
+ preview.updatedAt = Date.now();
430
+ delete preview.lastError;
431
+ });
432
+ let settled = false;
433
+ const finish = async (status, errorMessage) => {
434
+ if (settled) {
435
+ return;
436
+ }
437
+ settled = true;
438
+ clearInterval(healthTimer);
439
+ clearTimeout(launchTimeout);
440
+ if (status === "healthy") {
441
+ this.markPreviewHealthy(record.id);
442
+ }
443
+ else {
444
+ this.markPreviewFailed(record.id, errorMessage ?? "Preview launch failed");
445
+ }
446
+ };
447
+ const healthTimer = setInterval(() => {
448
+ void this.checkPreviewHealth(record)
449
+ .then((healthy) => {
450
+ if (healthy) {
451
+ void finish("healthy");
452
+ }
453
+ })
454
+ .catch(() => {
455
+ // keep polling until timeout or exit
456
+ });
457
+ }, PREVIEW_HEALTH_INTERVAL_MS);
458
+ healthTimer.unref?.();
459
+ const launchTimeout = setTimeout(() => {
460
+ void finish("failed", `Dynamic preview did not become ready within ${Math.round(PREVIEW_LAUNCH_TIMEOUT_MS / 1000)} seconds.`).finally(() => {
461
+ void this.stopPreviewProcess(record.id, "dynamic preview launch timed out", {
462
+ removeRecord: false,
463
+ clearLiveUrl: false,
464
+ nextStatus: "failed",
465
+ lastError: `Dynamic preview did not become ready within ${Math.round(PREVIEW_LAUNCH_TIMEOUT_MS / 1000)} seconds.`,
466
+ });
467
+ });
468
+ }, PREVIEW_LAUNCH_TIMEOUT_MS);
469
+ launchTimeout.unref?.();
470
+ child.once("exit", (code, signal) => {
471
+ clearInterval(healthTimer);
472
+ clearTimeout(launchTimeout);
473
+ this.processes.delete(record.id);
474
+ if (this.stoppingPreviewIds.has(record.id)) {
475
+ this.stoppingPreviewIds.delete(record.id);
476
+ return;
477
+ }
478
+ if (!settled) {
479
+ void finish("failed", `Dynamic preview exited before readiness (code=${code ?? "null"}, signal=${signal ?? "null"}).`);
480
+ return;
481
+ }
482
+ this.markPreviewFailed(record.id, `Dynamic preview process exited (code=${code ?? "null"}, signal=${signal ?? "null"}).`);
483
+ });
484
+ }
485
+ async removePreview(previewId, reason) {
486
+ await this.stopPreviewProcess(previewId, reason, {
487
+ removeRecord: true,
488
+ clearLiveUrl: true,
489
+ });
490
+ }
491
+ async stopPreviewProcess(previewId, reason, options) {
492
+ const child = this.processes.get(previewId);
493
+ if (child) {
494
+ this.stoppingPreviewIds.add(previewId);
495
+ this.processes.delete(previewId);
496
+ await stopManagedProcess(child, PREVIEW_STOP_TIMEOUT_MS).catch((err) => {
497
+ this.deps.logger.warn(`Controller: failed to stop preview ${previewId}: ${String(err)}`);
498
+ });
499
+ this.stoppingPreviewIds.delete(previewId);
500
+ }
501
+ this.deps.updateTeamState((state) => {
502
+ const preview = state.previews?.[previewId];
503
+ if (!preview) {
504
+ return;
505
+ }
506
+ const task = state.tasks[preview.taskId];
507
+ const deliverable = task?.resultContract?.deliverables?.[preview.deliverableIndex];
508
+ if (deliverable && options.clearLiveUrl && deliverable.liveUrl === preview.liveUrl) {
509
+ delete deliverable.liveUrl;
510
+ }
511
+ if (options.removeRecord) {
512
+ delete state.previews?.[previewId];
513
+ return;
514
+ }
515
+ preview.status = options.nextStatus ?? "stopped";
516
+ preview.updatedAt = Date.now();
517
+ preview.lastError = options.lastError ?? reason;
518
+ delete preview.pid;
519
+ });
520
+ }
521
+ setTaskDeliverableLiveUrl(taskId, deliverableIndex, liveUrl) {
522
+ this.deps.updateTeamState((state) => {
523
+ const task = state.tasks[taskId];
524
+ const deliverable = task?.resultContract?.deliverables?.[deliverableIndex];
525
+ if (!deliverable || deliverable.liveUrl === liveUrl) {
526
+ return;
527
+ }
528
+ deliverable.liveUrl = liveUrl;
529
+ task.updatedAt = Date.now();
530
+ });
531
+ }
532
+ markPreviewHealthy(previewId) {
533
+ this.deps.updateTeamState((state) => {
534
+ const preview = state.previews?.[previewId];
535
+ if (!preview) {
536
+ return;
537
+ }
538
+ preview.status = "healthy";
539
+ preview.updatedAt = Date.now();
540
+ preview.lastHealthCheckAt = Date.now();
541
+ delete preview.lastError;
542
+ });
543
+ }
544
+ markPreviewFailed(previewId, errorMessage) {
545
+ this.deps.updateTeamState((state) => {
546
+ const preview = state.previews?.[previewId];
547
+ if (!preview) {
548
+ return;
549
+ }
550
+ preview.status = "failed";
551
+ preview.updatedAt = Date.now();
552
+ preview.lastError = errorMessage;
553
+ delete preview.pid;
554
+ });
555
+ }
556
+ async checkPreviewHealth(record) {
557
+ try {
558
+ const response = await fetch(`http://127.0.0.1:${record.targetPort}${record.previewReadyPath}`, {
559
+ method: "GET",
560
+ redirect: "manual",
561
+ signal: AbortSignal.timeout(5_000),
562
+ });
563
+ return response.status < 500;
564
+ }
565
+ catch {
566
+ return false;
567
+ }
568
+ }
569
+ async reserveEphemeralPort() {
570
+ return await new Promise((resolve, reject) => {
571
+ const server = net.createServer();
572
+ server.listen(0, "127.0.0.1", () => {
573
+ const address = server.address();
574
+ const port = typeof address === "object" && address ? address.port : 0;
575
+ server.close((err) => {
576
+ if (err) {
577
+ reject(err);
578
+ return;
579
+ }
580
+ resolve(port);
581
+ });
582
+ });
583
+ server.on("error", reject);
584
+ });
585
+ }
586
+ }