@teamclaws/teamclaw 2026.4.3-2 → 2026.5.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.
- package/README.md +8 -2
- package/cli.mjs +116 -19
- package/index.ts +17 -0
- package/openclaw.plugin.json +57 -3
- package/package.json +8 -3
- package/src/config.ts +32 -1
- package/src/controller/controller-service.ts +66 -2
- package/src/controller/controller-tools.ts +34 -22
- package/src/controller/github-auth.ts +699 -0
- package/src/controller/http-server.ts +1454 -34
- package/src/controller/orchestration-manifest.ts +1 -0
- package/src/controller/prompt-injector.ts +7 -1
- package/src/controller/websocket.ts +5 -0
- package/src/controller/worker-provisioning.ts +2 -2
- package/src/discovery.ts +6 -4
- package/src/git-collaboration.ts +33 -0
- package/src/interaction-contracts.ts +2 -2
- package/src/openclaw-workspace.ts +477 -32
- package/src/prompt-policy.ts +11 -1
- package/src/roles.ts +52 -0
- package/src/state.ts +66 -34
- package/src/task-executor.ts +110 -3
- package/src/teamauto/github-client.ts +254 -0
- package/src/teamauto/norms.ts +103 -0
- package/src/teamauto/repo-sync.ts +218 -0
- package/src/teamauto/scanner.ts +221 -0
- package/src/teamauto/scheduler.ts +585 -0
- package/src/teamauto/store.ts +242 -0
- package/src/types.ts +90 -4
- package/src/ui/app.js +801 -11
- package/src/ui/github-login.html +296 -0
- package/src/ui/index.html +99 -2
- package/src/ui/style.css +344 -58
- package/src/worker/prompt-injector.ts +8 -0
- package/src/worker/tools.ts +48 -45
- package/src/worker/worker-service.ts +37 -1
- package/tsconfig.build.json +13 -0
- package/tsconfig.json +1 -5
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import http from "node:http";
|
|
4
4
|
import zlib from "node:zlib";
|
|
5
|
+
import { execFileSync } from "node:child_process";
|
|
5
6
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
6
7
|
import type { OpenClawPluginApi, PluginLogger } from "../../api.js";
|
|
7
8
|
import type {
|
|
@@ -38,13 +39,22 @@ import {
|
|
|
38
39
|
} from "../protocol.js";
|
|
39
40
|
import { listWorkspaceTree, listWorkspaceSubtree, readWorkspaceFile, readWorkspaceRawFile } from "../workspace-browser.js";
|
|
40
41
|
import { ROLES, normalizeRecommendedSkills, resolveRecommendedSkillsForRole } from "../roles.js";
|
|
41
|
-
import {
|
|
42
|
+
import {
|
|
43
|
+
buildRepoSyncInfo,
|
|
44
|
+
ensureControllerGitRepo,
|
|
45
|
+
exportControllerGitBundle,
|
|
46
|
+
importControllerGitBundle,
|
|
47
|
+
removeTrackedWorkspaceSubtree,
|
|
48
|
+
} from "../git-collaboration.js";
|
|
42
49
|
import { TaskRouter } from "./task-router.js";
|
|
43
50
|
import { MessageRouter } from "./message-router.js";
|
|
44
51
|
import { TeamWebSocketServer } from "./websocket.js";
|
|
45
52
|
import type { WorkerProvisioningManager } from "./worker-provisioning.js";
|
|
46
53
|
import type { PreviewManager } from "./preview-manager.js";
|
|
47
54
|
import { createControllerPromptInjector } from "./prompt-injector.js";
|
|
55
|
+
import { getGithubAuthManager } from "./github-auth.js";
|
|
56
|
+
import { createGithubClient } from "../teamauto/github-client.js";
|
|
57
|
+
import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
|
|
48
58
|
import { buildControllerNoWorkersMessage, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
|
|
49
59
|
import { generateDeliveryReport, isSessionComplete, renderReportHtml, type DeliveryReport } from "./delivery-report.js";
|
|
50
60
|
import {
|
|
@@ -65,6 +75,10 @@ import {
|
|
|
65
75
|
resolveTeamClawProjectsDir,
|
|
66
76
|
deriveStableProjectKey,
|
|
67
77
|
deriveProjectSlug,
|
|
78
|
+
teamClawWorkspaceIsDefault,
|
|
79
|
+
updateTeamClawWorkspaceDir,
|
|
80
|
+
getTeamClawModelCatalog,
|
|
81
|
+
updateTeamClawModelConfig,
|
|
68
82
|
} from "../openclaw-workspace.js";
|
|
69
83
|
import { resolvePreferredLanAddress } from "../networking.js";
|
|
70
84
|
import { normalizeClarificationQuestionSchema, normalizeControllerManifest } from "./orchestration-manifest.js";
|
|
@@ -83,6 +97,8 @@ export type ControllerHttpDeps = {
|
|
|
83
97
|
previewManager?: PreviewManager;
|
|
84
98
|
/** Late-bound kickoff handler for automatic team kickoff on complex projects. */
|
|
85
99
|
getKickoffHandler?: () => KickoffHandler | undefined;
|
|
100
|
+
/** Late-bound TeamAuto scheduler (autonomous repo collaboration). */
|
|
101
|
+
getTeamAutoScheduler?: () => TeamAutoScheduler | null;
|
|
86
102
|
};
|
|
87
103
|
|
|
88
104
|
const MAX_TASK_EXECUTION_EVENTS = 250;
|
|
@@ -92,6 +108,10 @@ const MAX_TASK_CONTEXT_SUMMARY_CHARS = 500;
|
|
|
92
108
|
const CONTROLLER_INTAKE_SESSION_PREFIX = "teamclaw-controller-web:";
|
|
93
109
|
const CONTROLLER_INTAKE_AGENT_SESSION_RE = /^agent:[^:]+:(teamclaw-controller-web:[a-zA-Z0-9:_-]{1,120})$/;
|
|
94
110
|
const CONTROLLER_RUN_WAIT_SLICE_MS = 30_000;
|
|
111
|
+
const CONTROLLER_SESSION_PROGRESS_MESSAGE_LIMIT = 200;
|
|
112
|
+
const MAX_SESSION_PROGRESS_MESSAGE_CHARS = 4000;
|
|
113
|
+
const TOOL_CALL_BLOCK_TYPES = new Set(["tool_use", "toolcall", "tool_call"]);
|
|
114
|
+
const TOOL_RESULT_BLOCK_TYPES = new Set(["tool_result", "tool_result_error"]);
|
|
95
115
|
const EXISTING_PROJECT_REUSE_HINT_RE = /\b(existing|optimi(?:s|z)e|optimi(?:s|z)ation|improvement|enhanc(?:e|ement)|follow[- ]?up|extend|update|bugfix|bug fix)\b/iu;
|
|
96
116
|
const GENERIC_PROJECT_FOLLOW_UP_RE = /\b(continue|continuing|next step|what else|what's next|follow[- ]?up|more|remaining)\b|继续|接下来|下一步|还有哪些|还可以做什么/u;
|
|
97
117
|
const PROJECT_MATCH_STOPWORDS = new Set([
|
|
@@ -404,6 +424,328 @@ function trimControllerRuns(state: TeamState): void {
|
|
|
404
424
|
}
|
|
405
425
|
}
|
|
406
426
|
|
|
427
|
+
type TaskCleanupSummary = {
|
|
428
|
+
deletedTaskIds: string[];
|
|
429
|
+
deletedClarificationIds: string[];
|
|
430
|
+
deletedMessageIds: string[];
|
|
431
|
+
stoppedPreviewIds: string[];
|
|
432
|
+
deletedReportIds: string[];
|
|
433
|
+
deletedProjectDirs: string[];
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
function buildEmptyTaskCleanupSummary(): TaskCleanupSummary {
|
|
437
|
+
return {
|
|
438
|
+
deletedTaskIds: [],
|
|
439
|
+
deletedClarificationIds: [],
|
|
440
|
+
deletedMessageIds: [],
|
|
441
|
+
stoppedPreviewIds: [],
|
|
442
|
+
deletedReportIds: [],
|
|
443
|
+
deletedProjectDirs: [],
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function resolveSafeProjectDirectory(projectDir: string | undefined): string | null {
|
|
448
|
+
const normalized = String(projectDir ?? "").trim().replace(/^\/+|\/+$/gu, "");
|
|
449
|
+
if (!normalized || normalized === "." || normalized === "..") {
|
|
450
|
+
return null;
|
|
451
|
+
}
|
|
452
|
+
if (normalized.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
|
|
453
|
+
return null;
|
|
454
|
+
}
|
|
455
|
+
const projectsRoot = path.resolve(resolveTeamClawProjectsDir());
|
|
456
|
+
const projectPath = path.resolve(projectsRoot, normalized);
|
|
457
|
+
const relative = path.relative(projectsRoot, projectPath);
|
|
458
|
+
if (!relative || relative === "" || relative === "." || relative.startsWith("..") || path.isAbsolute(relative)) {
|
|
459
|
+
return null;
|
|
460
|
+
}
|
|
461
|
+
return projectPath;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
async function deleteProjectDirectoryIfUnused(
|
|
465
|
+
projectDir: string | undefined,
|
|
466
|
+
deps: ControllerHttpDeps,
|
|
467
|
+
summary: TaskCleanupSummary,
|
|
468
|
+
): Promise<void> {
|
|
469
|
+
if (!projectDir) {
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
const state = deps.getTeamState();
|
|
473
|
+
const stillReferencedByTask = Object.values(state?.tasks ?? {}).some((task) => task.projectDir === projectDir);
|
|
474
|
+
const stillReferencedByRun = Object.values(state?.controllerRuns ?? {}).some((run) => run.projectDir === projectDir);
|
|
475
|
+
if (stillReferencedByTask || stillReferencedByRun) {
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
const safeProjectPath = resolveSafeProjectDirectory(projectDir);
|
|
480
|
+
if (!safeProjectPath) {
|
|
481
|
+
deps.logger.warn(`Controller: skipped unsafe project directory cleanup for ${String(projectDir)}`);
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
if (!fs.existsSync(safeProjectPath)) {
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
await removeTrackedWorkspaceSubtree(deps.config, deps.logger, safeProjectPath);
|
|
488
|
+
await fs.promises.rm(safeProjectPath, { recursive: true, force: true });
|
|
489
|
+
if (fs.existsSync(safeProjectPath)) {
|
|
490
|
+
throw new Error(`Project directory cleanup could not be confirmed for ${projectDir}`);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
deps.updateTeamState((stateDraft) => {
|
|
494
|
+
const projectRecord = findProjectRecordByDir(stateDraft, projectDir);
|
|
495
|
+
if (projectRecord) {
|
|
496
|
+
delete stateDraft.projects[projectRecord.id];
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
summary.deletedProjectDirs.push(projectDir);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
function isTaskTerminalForCleanup(task: TaskInfo | undefined): boolean {
|
|
503
|
+
if (!task) {
|
|
504
|
+
return true;
|
|
505
|
+
}
|
|
506
|
+
return task.status === "completed" || task.status === "failed";
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function canAutoDeleteStaleControllerRun(
|
|
510
|
+
run: ControllerRunInfo,
|
|
511
|
+
state: TeamState | null,
|
|
512
|
+
now: number,
|
|
513
|
+
staleAfterMs: number,
|
|
514
|
+
): boolean {
|
|
515
|
+
if (run.status !== "pending" && run.status !== "running") {
|
|
516
|
+
return false;
|
|
517
|
+
}
|
|
518
|
+
const lastActivityAt = run.execution?.lastUpdatedAt ?? run.updatedAt ?? run.createdAt ?? 0;
|
|
519
|
+
if (!lastActivityAt || now - lastActivityAt < staleAfterMs) {
|
|
520
|
+
return false;
|
|
521
|
+
}
|
|
522
|
+
const ownedTasks = Object.values(state?.tasks ?? {}).filter((task) => task.controllerRunId === run.id);
|
|
523
|
+
if (ownedTasks.some((task) => !isTaskTerminalForCleanup(task))) {
|
|
524
|
+
return false;
|
|
525
|
+
}
|
|
526
|
+
const hasPendingClarification = Object.values(state?.clarifications ?? {}).some((clarification) =>
|
|
527
|
+
clarification.controllerRunId === run.id && clarification.status === "pending",
|
|
528
|
+
);
|
|
529
|
+
return !hasPendingClarification;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async function pruneStaleControllerRuns(
|
|
533
|
+
deps: ControllerHttpDeps,
|
|
534
|
+
options?: { excludeRunId?: string },
|
|
535
|
+
): Promise<void> {
|
|
536
|
+
const state = deps.getTeamState();
|
|
537
|
+
const now = Date.now();
|
|
538
|
+
const staleAfterMs = deps.config.taskTimeoutMs * 2;
|
|
539
|
+
const staleRunIds = Object.values(state?.controllerRuns ?? {})
|
|
540
|
+
.filter((run) => run.id !== options?.excludeRunId)
|
|
541
|
+
.filter((run) => canAutoDeleteStaleControllerRun(run, state, now, staleAfterMs))
|
|
542
|
+
.sort((left, right) => left.updatedAt - right.updatedAt)
|
|
543
|
+
.map((run) => run.id);
|
|
544
|
+
for (const staleRunId of staleRunIds) {
|
|
545
|
+
await deleteControllerRunCascade(staleRunId, deps, { preserveSessionArtifacts: true });
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
async function deleteProjectCascade(
|
|
550
|
+
projectDir: string,
|
|
551
|
+
deps: ControllerHttpDeps,
|
|
552
|
+
): Promise<{ deleted: boolean; summary: TaskCleanupSummary & { projectDir?: string } }> {
|
|
553
|
+
const safeProjectPath = resolveSafeProjectDirectory(projectDir);
|
|
554
|
+
if (!safeProjectPath) {
|
|
555
|
+
return { deleted: false, summary: { ...buildEmptyTaskCleanupSummary(), projectDir: undefined } };
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const summary: TaskCleanupSummary & { projectDir?: string } = {
|
|
559
|
+
...buildEmptyTaskCleanupSummary(),
|
|
560
|
+
projectDir,
|
|
561
|
+
};
|
|
562
|
+
const state = deps.getTeamState();
|
|
563
|
+
const runIds = Object.values(state?.controllerRuns ?? {})
|
|
564
|
+
.filter((run) => run.projectDir === projectDir)
|
|
565
|
+
.map((run) => run.id);
|
|
566
|
+
const taskIds = Object.values(state?.tasks ?? {})
|
|
567
|
+
.filter((task) => task.projectDir === projectDir)
|
|
568
|
+
.map((task) => task.id);
|
|
569
|
+
|
|
570
|
+
for (const runId of runIds) {
|
|
571
|
+
const result = await deleteControllerRunCascade(runId, deps);
|
|
572
|
+
if (!result.deleted) {
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
summary.deletedTaskIds.push(...result.summary.deletedTaskIds);
|
|
576
|
+
summary.deletedClarificationIds.push(...result.summary.deletedClarificationIds);
|
|
577
|
+
summary.deletedMessageIds.push(...result.summary.deletedMessageIds);
|
|
578
|
+
summary.stoppedPreviewIds.push(...result.summary.stoppedPreviewIds);
|
|
579
|
+
summary.deletedReportIds.push(...result.summary.deletedReportIds);
|
|
580
|
+
summary.deletedProjectDirs.push(...result.summary.deletedProjectDirs);
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
for (const taskId of taskIds) {
|
|
584
|
+
await deleteTaskCascade(taskId, deps, summary);
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
await deleteProjectDirectoryIfUnused(projectDir, deps, summary);
|
|
588
|
+
if (!summary.deletedProjectDirs.includes(projectDir) && !fs.existsSync(safeProjectPath)) {
|
|
589
|
+
summary.deletedProjectDirs.push(projectDir);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
if (summary.deletedProjectDirs.includes(projectDir)) {
|
|
593
|
+
deps.wsServer.broadcastUpdate({ type: "project:deleted", data: { projectDir } });
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
return { deleted: summary.deletedProjectDirs.includes(projectDir), summary };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
async function deleteTaskCascade(
|
|
600
|
+
taskId: string,
|
|
601
|
+
deps: ControllerHttpDeps,
|
|
602
|
+
summary: TaskCleanupSummary,
|
|
603
|
+
): Promise<boolean> {
|
|
604
|
+
const existingTask = deps.getTeamState()?.tasks[taskId];
|
|
605
|
+
if (!existingTask) {
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
await cancelTaskExecution(taskId, existingTask.assignedWorkerId, "cleanup deletion", deps);
|
|
610
|
+
await deps.previewManager?.stopTaskPreviews(taskId, "task deleted during cleanup");
|
|
611
|
+
|
|
612
|
+
const previewIds = Object.values(deps.getTeamState()?.previews ?? {})
|
|
613
|
+
.filter((preview) => preview.taskId === taskId)
|
|
614
|
+
.map((preview) => preview.id);
|
|
615
|
+
|
|
616
|
+
const deletedClarificationIds: string[] = [];
|
|
617
|
+
const deletedMessageIds: string[] = [];
|
|
618
|
+
const deletedReportIds: string[] = [];
|
|
619
|
+
const normalizedSessionKey = existingTask.controllerSessionKey
|
|
620
|
+
? normalizeControllerIntakeSessionKey(existingTask.controllerSessionKey)
|
|
621
|
+
: undefined;
|
|
622
|
+
|
|
623
|
+
deps.updateTeamState((state) => {
|
|
624
|
+
delete state.tasks[taskId];
|
|
625
|
+
|
|
626
|
+
for (const clarification of Object.values(state.clarifications)) {
|
|
627
|
+
if (clarification.taskId === taskId) {
|
|
628
|
+
deletedClarificationIds.push(clarification.id);
|
|
629
|
+
delete state.clarifications[clarification.id];
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if (state.messages.length > 0) {
|
|
634
|
+
const keptMessages: TeamMessage[] = [];
|
|
635
|
+
for (const message of state.messages) {
|
|
636
|
+
if (message.taskId === taskId) {
|
|
637
|
+
deletedMessageIds.push(message.id);
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
keptMessages.push(message);
|
|
641
|
+
}
|
|
642
|
+
state.messages = keptMessages;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
if (normalizedSessionKey && state.reports) {
|
|
646
|
+
for (const report of Object.values(state.reports)) {
|
|
647
|
+
if (normalizeControllerIntakeSessionKey(report.sessionKey) === normalizedSessionKey) {
|
|
648
|
+
deletedReportIds.push(report.id);
|
|
649
|
+
delete state.reports[report.id];
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
for (const run of Object.values(state.controllerRuns)) {
|
|
655
|
+
if (run.sourceTaskId === taskId) {
|
|
656
|
+
delete run.sourceTaskId;
|
|
657
|
+
}
|
|
658
|
+
if (run.createdTaskIds.includes(taskId)) {
|
|
659
|
+
run.createdTaskIds = run.createdTaskIds.filter((id) => id !== taskId);
|
|
660
|
+
run.updatedAt = Date.now();
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
summary.deletedTaskIds.push(taskId);
|
|
666
|
+
summary.deletedClarificationIds.push(...deletedClarificationIds);
|
|
667
|
+
summary.deletedMessageIds.push(...deletedMessageIds);
|
|
668
|
+
summary.stoppedPreviewIds.push(...previewIds);
|
|
669
|
+
summary.deletedReportIds.push(...deletedReportIds);
|
|
670
|
+
await deleteProjectDirectoryIfUnused(existingTask.projectDir, deps, summary);
|
|
671
|
+
|
|
672
|
+
deps.wsServer.broadcastUpdate({ type: "task:deleted", data: { taskId } });
|
|
673
|
+
for (const clarificationId of deletedClarificationIds) {
|
|
674
|
+
deps.wsServer.broadcastUpdate({ type: "clarification:deleted", data: { clarificationId, taskId } });
|
|
675
|
+
}
|
|
676
|
+
for (const messageId of deletedMessageIds) {
|
|
677
|
+
deps.wsServer.broadcastUpdate({ type: "message:deleted", data: { messageId, taskId } });
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
return true;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
async function deleteControllerRunCascade(
|
|
684
|
+
runId: string,
|
|
685
|
+
deps: ControllerHttpDeps,
|
|
686
|
+
options?: {
|
|
687
|
+
preserveSessionArtifacts?: boolean;
|
|
688
|
+
},
|
|
689
|
+
): Promise<{
|
|
690
|
+
deleted: boolean;
|
|
691
|
+
summary: TaskCleanupSummary & { deletedRunId?: string };
|
|
692
|
+
}> {
|
|
693
|
+
const run = deps.getTeamState()?.controllerRuns[runId];
|
|
694
|
+
if (!run) {
|
|
695
|
+
return { deleted: false, summary: { ...buildEmptyTaskCleanupSummary() } };
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const summary: TaskCleanupSummary & { deletedRunId?: string } = {
|
|
699
|
+
...buildEmptyTaskCleanupSummary(),
|
|
700
|
+
deletedRunId: undefined,
|
|
701
|
+
};
|
|
702
|
+
|
|
703
|
+
const linkedTaskIds = new Set<string>(run.createdTaskIds);
|
|
704
|
+
for (const task of Object.values(deps.getTeamState()?.tasks ?? {})) {
|
|
705
|
+
if (task.controllerRunId === run.id) {
|
|
706
|
+
linkedTaskIds.add(task.id);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
for (const taskId of linkedTaskIds) {
|
|
711
|
+
await deleteTaskCascade(taskId, deps, summary);
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
const deletedClarificationIds: string[] = [];
|
|
715
|
+
const deletedReportIds: string[] = [];
|
|
716
|
+
deps.updateTeamState((state) => {
|
|
717
|
+
delete state.controllerRuns[runId];
|
|
718
|
+
summary.deletedRunId = runId;
|
|
719
|
+
|
|
720
|
+
for (const clarification of Object.values(state.clarifications)) {
|
|
721
|
+
if (clarification.controllerRunId === runId) {
|
|
722
|
+
deletedClarificationIds.push(clarification.id);
|
|
723
|
+
delete state.clarifications[clarification.id];
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
if (state.reports) {
|
|
728
|
+
const normalizedSessionKey = normalizeControllerIntakeSessionKey(run.sessionKey);
|
|
729
|
+
for (const report of Object.values(state.reports)) {
|
|
730
|
+
if (!options?.preserveSessionArtifacts && normalizeControllerIntakeSessionKey(report.sessionKey) === normalizedSessionKey) {
|
|
731
|
+
deletedReportIds.push(report.id);
|
|
732
|
+
delete state.reports[report.id];
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
});
|
|
737
|
+
|
|
738
|
+
summary.deletedClarificationIds.push(...deletedClarificationIds);
|
|
739
|
+
summary.deletedReportIds.push(...deletedReportIds);
|
|
740
|
+
|
|
741
|
+
deps.wsServer.broadcastUpdate({ type: "controller:run_deleted", data: { runId } });
|
|
742
|
+
for (const clarificationId of deletedClarificationIds) {
|
|
743
|
+
deps.wsServer.broadcastUpdate({ type: "clarification:deleted", data: { clarificationId, controllerRunId: runId } });
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
return { deleted: true, summary };
|
|
747
|
+
}
|
|
748
|
+
|
|
407
749
|
function serializeControllerRun(run?: ControllerRunInfo, includeExecutionEvents = true): Record<string, unknown> | undefined {
|
|
408
750
|
if (!run) {
|
|
409
751
|
return undefined;
|
|
@@ -434,9 +776,14 @@ function buildControllerRunTitle(
|
|
|
434
776
|
sourceTaskTitle?: string,
|
|
435
777
|
): string {
|
|
436
778
|
if (source === "task_follow_up") {
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
779
|
+
const normalizedSourceTitle = String(sourceTaskTitle || "").replace(/\s+/g, " ").trim();
|
|
780
|
+
if (normalizedSourceTitle) {
|
|
781
|
+
const compactSourceTitle = normalizedSourceTitle.length <= 72
|
|
782
|
+
? normalizedSourceTitle
|
|
783
|
+
: `${normalizedSourceTitle.slice(0, 72).trimEnd()}…`;
|
|
784
|
+
return `Controller follow-up after ${compactSourceTitle}`;
|
|
785
|
+
}
|
|
786
|
+
return "Controller workflow follow-up";
|
|
440
787
|
}
|
|
441
788
|
|
|
442
789
|
const normalized = message.replace(/\s+/g, " ").trim();
|
|
@@ -872,6 +1219,205 @@ function extractLastAssistantText(messages: unknown[]): string {
|
|
|
872
1219
|
return JSON.stringify(lastAssistant);
|
|
873
1220
|
}
|
|
874
1221
|
|
|
1222
|
+
type SessionProgressEntry = {
|
|
1223
|
+
fingerprint: string;
|
|
1224
|
+
message: string;
|
|
1225
|
+
phase: string;
|
|
1226
|
+
stream: string;
|
|
1227
|
+
isRateLimit: boolean;
|
|
1228
|
+
};
|
|
1229
|
+
|
|
1230
|
+
function normalizeSessionRole(value: unknown): string {
|
|
1231
|
+
if (typeof value !== "string") {
|
|
1232
|
+
return "";
|
|
1233
|
+
}
|
|
1234
|
+
const normalized = value.trim().toLowerCase().replace(/[-\s]+/g, "_");
|
|
1235
|
+
if (normalized === "toolresult") {
|
|
1236
|
+
return "tool_result";
|
|
1237
|
+
}
|
|
1238
|
+
return normalized;
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
function normalizeBlockType(value: unknown): string {
|
|
1242
|
+
if (typeof value !== "string") {
|
|
1243
|
+
return "";
|
|
1244
|
+
}
|
|
1245
|
+
return value.trim().toLowerCase();
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
function truncateProgressMessage(value: string): string {
|
|
1249
|
+
const trimmed = value.trim();
|
|
1250
|
+
if (!trimmed) {
|
|
1251
|
+
return "";
|
|
1252
|
+
}
|
|
1253
|
+
if (trimmed.length <= MAX_SESSION_PROGRESS_MESSAGE_CHARS) {
|
|
1254
|
+
return trimmed;
|
|
1255
|
+
}
|
|
1256
|
+
return `${trimmed.slice(0, MAX_SESSION_PROGRESS_MESSAGE_CHARS)}\n… (truncated)`;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
function normalizeProgressComparableText(value: string): string {
|
|
1260
|
+
return value.trim().replace(/\r\n/g, "\n");
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
function safeJsonStringify(value: unknown): string {
|
|
1264
|
+
try {
|
|
1265
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
1266
|
+
} catch (_err) {
|
|
1267
|
+
return String(value);
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
function renderSessionMessage(message: Record<string, unknown>, role: string): { message: string; stream: string } {
|
|
1272
|
+
const content = message.content;
|
|
1273
|
+
if (typeof content === "string") {
|
|
1274
|
+
return {
|
|
1275
|
+
message: truncateProgressMessage(content),
|
|
1276
|
+
stream: role,
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
if (Array.isArray(content)) {
|
|
1281
|
+
const textParts: string[] = [];
|
|
1282
|
+
const toolCalls: string[] = [];
|
|
1283
|
+
let toolResultCount = 0;
|
|
1284
|
+
let toolResultErrors = 0;
|
|
1285
|
+
|
|
1286
|
+
for (const entry of content) {
|
|
1287
|
+
if (!entry || typeof entry !== "object") {
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
const block = entry as Record<string, unknown>;
|
|
1292
|
+
const type = normalizeBlockType(block.type);
|
|
1293
|
+
if (type === "text") {
|
|
1294
|
+
const text = typeof block.text === "string" ? block.text.trim() : "";
|
|
1295
|
+
if (text) {
|
|
1296
|
+
textParts.push(text);
|
|
1297
|
+
}
|
|
1298
|
+
continue;
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
if (TOOL_CALL_BLOCK_TYPES.has(type)) {
|
|
1302
|
+
const name = typeof block.name === "string" ? block.name.trim() : "";
|
|
1303
|
+
if (name) {
|
|
1304
|
+
toolCalls.push(name);
|
|
1305
|
+
}
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
if (TOOL_RESULT_BLOCK_TYPES.has(type)) {
|
|
1310
|
+
toolResultCount += 1;
|
|
1311
|
+
if (block.is_error === true) {
|
|
1312
|
+
toolResultErrors += 1;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
const parts: string[] = [];
|
|
1318
|
+
if (textParts.length > 0) {
|
|
1319
|
+
parts.push(textParts.join("\n"));
|
|
1320
|
+
}
|
|
1321
|
+
if (toolCalls.length > 0) {
|
|
1322
|
+
parts.push(`[tool call] ${toolCalls.join(", ")}`);
|
|
1323
|
+
}
|
|
1324
|
+
if (toolResultCount > 0) {
|
|
1325
|
+
parts.push(`[tool result] ${toolResultCount}${toolResultErrors > 0 ? ` (${toolResultErrors} error)` : ""}`);
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
if (parts.length > 0) {
|
|
1329
|
+
return {
|
|
1330
|
+
message: truncateProgressMessage(parts.join("\n")),
|
|
1331
|
+
stream: textParts.length > 0 ? role : "tool",
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
const fallbackToolName = typeof message.toolName === "string"
|
|
1337
|
+
? message.toolName.trim()
|
|
1338
|
+
: (typeof message.tool_name === "string" ? message.tool_name.trim() : "");
|
|
1339
|
+
if (fallbackToolName) {
|
|
1340
|
+
return {
|
|
1341
|
+
message: `[tool call] ${fallbackToolName}`,
|
|
1342
|
+
stream: "tool",
|
|
1343
|
+
};
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
return {
|
|
1347
|
+
message: truncateProgressMessage(safeJsonStringify(message)),
|
|
1348
|
+
stream: role || "session",
|
|
1349
|
+
};
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
function buildSessionProgressEntries(messages: unknown[], controllerMessage: string): SessionProgressEntry[] {
|
|
1353
|
+
const entries: SessionProgressEntry[] = [];
|
|
1354
|
+
const normalizedControllerMessage = normalizeProgressComparableText(controllerMessage);
|
|
1355
|
+
|
|
1356
|
+
for (const rawMessage of messages) {
|
|
1357
|
+
if (!rawMessage || typeof rawMessage !== "object") {
|
|
1358
|
+
continue;
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
const message = rawMessage as Record<string, unknown>;
|
|
1362
|
+
const role = normalizeSessionRole(message.role);
|
|
1363
|
+
if (!role) {
|
|
1364
|
+
continue;
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
const rendered = renderSessionMessage(message, role);
|
|
1368
|
+
if (!rendered.message) {
|
|
1369
|
+
continue;
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
const comparableMessage = normalizeProgressComparableText(rendered.message);
|
|
1373
|
+
if (role === "user" && normalizedControllerMessage && comparableMessage.includes(normalizedControllerMessage)) {
|
|
1374
|
+
continue;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
entries.push({
|
|
1378
|
+
fingerprint: `${rendered.stream}:${comparableMessage}`,
|
|
1379
|
+
message: rendered.message,
|
|
1380
|
+
phase: rendered.stream,
|
|
1381
|
+
stream: rendered.stream,
|
|
1382
|
+
isRateLimit: isRateLimitMessage(rendered.message),
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
return entries;
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
function getNewSessionProgressEntries(
|
|
1390
|
+
entries: SessionProgressEntry[],
|
|
1391
|
+
previousFingerprints: string[],
|
|
1392
|
+
): SessionProgressEntry[] {
|
|
1393
|
+
if (entries.length === 0) {
|
|
1394
|
+
return [];
|
|
1395
|
+
}
|
|
1396
|
+
if (previousFingerprints.length === 0) {
|
|
1397
|
+
return entries;
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
const currentFingerprints = entries.map((entry) => entry.fingerprint);
|
|
1401
|
+
const maxOverlap = Math.min(previousFingerprints.length, currentFingerprints.length);
|
|
1402
|
+
let overlap = 0;
|
|
1403
|
+
|
|
1404
|
+
for (let size = maxOverlap; size > 0; size -= 1) {
|
|
1405
|
+
let matches = true;
|
|
1406
|
+
for (let index = 0; index < size; index += 1) {
|
|
1407
|
+
if (previousFingerprints[previousFingerprints.length - size + index] !== currentFingerprints[index]) {
|
|
1408
|
+
matches = false;
|
|
1409
|
+
break;
|
|
1410
|
+
}
|
|
1411
|
+
}
|
|
1412
|
+
if (matches) {
|
|
1413
|
+
overlap = size;
|
|
1414
|
+
break;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
return entries.slice(overlap);
|
|
1419
|
+
}
|
|
1420
|
+
|
|
875
1421
|
function formatDuration(timeoutMs: number): string {
|
|
876
1422
|
const totalSeconds = Math.ceil(timeoutMs / 1000);
|
|
877
1423
|
if (totalSeconds % 3600 === 0) {
|
|
@@ -992,6 +1538,7 @@ function reconcileControllerManifestTaskBindings(
|
|
|
992
1538
|
sessionKey: string,
|
|
993
1539
|
createdTaskIds: string[],
|
|
994
1540
|
manifest: ControllerOrchestrationManifest | undefined,
|
|
1541
|
+
controllerRunId: string,
|
|
995
1542
|
deps: ControllerHttpDeps,
|
|
996
1543
|
): { taskIds: string[]; linkedTaskIds: string[] } {
|
|
997
1544
|
if (!manifest || manifest.createdTasks.length === 0) {
|
|
@@ -1028,6 +1575,7 @@ function reconcileControllerManifestTaskBindings(
|
|
|
1028
1575
|
if (matchedTask.controllerSessionKey !== normalizedSessionKey) {
|
|
1029
1576
|
matchedTask.controllerSessionKey = normalizedSessionKey;
|
|
1030
1577
|
}
|
|
1578
|
+
matchedTask.controllerRunId = controllerRunId;
|
|
1031
1579
|
if (!usedTaskIds.has(matchedTask.id)) {
|
|
1032
1580
|
usedTaskIds.add(matchedTask.id);
|
|
1033
1581
|
linkedTaskIds.push(matchedTask.id);
|
|
@@ -1043,6 +1591,7 @@ function reconcileControllerManifestTaskBindings(
|
|
|
1043
1591
|
|
|
1044
1592
|
function tagControllerCreatedTasks(
|
|
1045
1593
|
taskIdsBeforeRun: Set<string>,
|
|
1594
|
+
controllerRunId: string,
|
|
1046
1595
|
sessionKey: string,
|
|
1047
1596
|
deps: ControllerHttpDeps,
|
|
1048
1597
|
): string[] {
|
|
@@ -1056,6 +1605,7 @@ function tagControllerCreatedTasks(
|
|
|
1056
1605
|
if (task.createdBy !== "controller") {
|
|
1057
1606
|
continue;
|
|
1058
1607
|
}
|
|
1608
|
+
task.controllerRunId = controllerRunId;
|
|
1059
1609
|
if (!task.controllerSessionKey) {
|
|
1060
1610
|
task.controllerSessionKey = normalizedSessionKey;
|
|
1061
1611
|
}
|
|
@@ -1306,7 +1856,25 @@ function buildBackfilledControllerManifest(
|
|
|
1306
1856
|
|
|
1307
1857
|
function looksLikeSoftwareRequirement(request: string): boolean {
|
|
1308
1858
|
const normalized = request.toLowerCase();
|
|
1309
|
-
return /(api|backend|frontend|fastapi|react|vue|node|python|typescript|javascript|sql|database|service|app|web|mobile|docker|kubernetes|deploy
|
|
1859
|
+
return /(api|backend|frontend|fastapi|react|vue|node|python|typescript|javascript|sql|database|service|app|web|mobile|docker|kubernetes|deploy|stderr|stdout|logging|logger|log file|config|yaml|json|cli|command|build|test|compile|bug|fix|output|file|repo|repository|code|测试|系统|平台|接口|服务|数据库|应用|前端|后端|日志|输出|文件|配置|命令|编译|构建|修复|代码|仓库)/.test(normalized);
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
function looksLikeManualExecutionClarification(question: string): boolean {
|
|
1863
|
+
const normalized = question.toLowerCase();
|
|
1864
|
+
return /(请先|请运行|请执行|请重试|请重新编译|请复现|run\b|rerun\b|retry\b|rebuild\b|recompile\b|git pull\b|go build\b|npm test\b|pnpm test\b|yarn test\b|pytest\b|cargo test\b|是否仍然|does it still|still crash|still fail)/i.test(normalized);
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
function extractExecutableFollowUpFromClarification(question: string): string | null {
|
|
1868
|
+
const trimmed = String(question || "").trim();
|
|
1869
|
+
if (!trimmed || !looksLikeManualExecutionClarification(trimmed)) {
|
|
1870
|
+
return null;
|
|
1871
|
+
}
|
|
1872
|
+
const normalized = trimmed.replace(/\s+/g, " ").trim();
|
|
1873
|
+
return [
|
|
1874
|
+
"Continue the same requirement by executing the obvious validation or rebuild step yourself instead of asking the human to run it manually.",
|
|
1875
|
+
`Requested follow-up verification: ${normalized}`,
|
|
1876
|
+
"Run the needed build/test/repro steps inside the project workspace, inspect the real outcome, and then either fix the issue or report the verified blocker with concrete evidence.",
|
|
1877
|
+
].join("\n\n");
|
|
1310
1878
|
}
|
|
1311
1879
|
|
|
1312
1880
|
function isArchitectureFirstRequirement(request: string): boolean {
|
|
@@ -1316,6 +1884,10 @@ function isArchitectureFirstRequirement(request: string): boolean {
|
|
|
1316
1884
|
|
|
1317
1885
|
function chooseFallbackAssignedRole(manifest: ControllerOrchestrationManifest, request: string): RoleId {
|
|
1318
1886
|
const requiredRoles = manifest.requiredRoles;
|
|
1887
|
+
const implementationLikeRequest = looksLikeSoftwareRequirement(request) && !isArchitectureFirstRequirement(request);
|
|
1888
|
+
if (requiredRoles.length === 1 && requiredRoles[0] === "architect" && implementationLikeRequest) {
|
|
1889
|
+
return "developer";
|
|
1890
|
+
}
|
|
1319
1891
|
if (requiredRoles.length === 0) {
|
|
1320
1892
|
return isArchitectureFirstRequirement(request) ? "architect" : "developer";
|
|
1321
1893
|
}
|
|
@@ -1355,6 +1927,116 @@ function buildFallbackControllerTaskTitle(request: string, assignedRole?: RoleId
|
|
|
1355
1927
|
: `Perform the requested ${assignedRole || "software"} work`;
|
|
1356
1928
|
}
|
|
1357
1929
|
|
|
1930
|
+
function looksLikeSupplementalHumanContextUpdate(request: string): boolean {
|
|
1931
|
+
const normalized = request.toLowerCase();
|
|
1932
|
+
const hasEndpointOrCredentialHint = /(apikey|api key|token|credential|endpoint|base url|provider|model list|models接口|连接信息|兼容接口|供应商|可用模型)/i.test(request);
|
|
1933
|
+
const urlCount = (request.match(/https?:\/\//gi) || []).length;
|
|
1934
|
+
const looksLikeFreshImplementationAsk = /(implement|build|create|write|develop|fix|refactor|design|架构|设计|实现|开发|修复|重构|创建)/i.test(normalized);
|
|
1935
|
+
return !looksLikeFreshImplementationAsk && (hasEndpointOrCredentialHint || urlCount >= 2);
|
|
1936
|
+
}
|
|
1937
|
+
|
|
1938
|
+
function getActiveTasksForSupplementalHumanContext(
|
|
1939
|
+
controllerRunId: string,
|
|
1940
|
+
sessionKey: string,
|
|
1941
|
+
manifest: ControllerOrchestrationManifest,
|
|
1942
|
+
state: TeamState | null,
|
|
1943
|
+
): TaskInfo[] {
|
|
1944
|
+
const normalizedSessionKey = normalizeControllerIntakeSessionKey(sessionKey);
|
|
1945
|
+
const runProjectDir = state?.controllerRuns?.[controllerRunId]?.projectDir;
|
|
1946
|
+
const requiredRoles = new Set(manifest.requiredRoles);
|
|
1947
|
+
return Object.values(state?.tasks ?? {})
|
|
1948
|
+
.filter((task) => task.status === "assigned" || task.status === "in_progress" || task.status === "review")
|
|
1949
|
+
.filter((task) => normalizeControllerIntakeSessionKey(task.controllerSessionKey) === normalizedSessionKey)
|
|
1950
|
+
.filter((task) => !runProjectDir || task.projectDir === runProjectDir)
|
|
1951
|
+
.filter((task) => requiredRoles.size === 0 || (task.assignedRole ? requiredRoles.has(task.assignedRole) : false))
|
|
1952
|
+
.sort((left, right) => {
|
|
1953
|
+
const leftScore = left.status === "in_progress" ? 2 : left.status === "assigned" ? 1 : 0;
|
|
1954
|
+
const rightScore = right.status === "in_progress" ? 2 : right.status === "assigned" ? 1 : 0;
|
|
1955
|
+
if (leftScore !== rightScore) {
|
|
1956
|
+
return rightScore - leftScore;
|
|
1957
|
+
}
|
|
1958
|
+
return right.updatedAt - left.updatedAt;
|
|
1959
|
+
});
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1962
|
+
async function forwardSupplementalHumanContextToActiveTasks(
|
|
1963
|
+
controllerRunId: string,
|
|
1964
|
+
sessionKey: string,
|
|
1965
|
+
request: string,
|
|
1966
|
+
manifest: ControllerOrchestrationManifest,
|
|
1967
|
+
deps: ControllerHttpDeps,
|
|
1968
|
+
): Promise<string[]> {
|
|
1969
|
+
if (!looksLikeSupplementalHumanContextUpdate(request)) {
|
|
1970
|
+
return [];
|
|
1971
|
+
}
|
|
1972
|
+
const state = deps.getTeamState();
|
|
1973
|
+
const targetTasks = getActiveTasksForSupplementalHumanContext(controllerRunId, sessionKey, manifest, state);
|
|
1974
|
+
if (targetTasks.length === 0) {
|
|
1975
|
+
return [];
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
const createdAt = Date.now();
|
|
1979
|
+
const messages: TeamMessage[] = targetTasks.map((task) => ({
|
|
1980
|
+
id: generateId(),
|
|
1981
|
+
from: "human-intake",
|
|
1982
|
+
to: task.assignedWorkerId,
|
|
1983
|
+
toRole: task.assignedRole,
|
|
1984
|
+
type: "direct",
|
|
1985
|
+
content: request,
|
|
1986
|
+
contract: ensureTeamMessageContract(null, {
|
|
1987
|
+
type: "direct",
|
|
1988
|
+
content: request,
|
|
1989
|
+
toRole: task.assignedRole,
|
|
1990
|
+
taskId: task.id,
|
|
1991
|
+
intent: "update",
|
|
1992
|
+
needsResponse: false,
|
|
1993
|
+
}),
|
|
1994
|
+
taskId: task.id,
|
|
1995
|
+
createdAt,
|
|
1996
|
+
}));
|
|
1997
|
+
|
|
1998
|
+
deps.updateTeamState((teamState) => {
|
|
1999
|
+
teamState.messages.push(...messages);
|
|
2000
|
+
});
|
|
2001
|
+
|
|
2002
|
+
for (const message of messages) {
|
|
2003
|
+
recordTaskExecutionEvent(message.taskId!, {
|
|
2004
|
+
type: "progress",
|
|
2005
|
+
phase: "human_context_forwarded",
|
|
2006
|
+
source: "controller",
|
|
2007
|
+
status: "running",
|
|
2008
|
+
message: "Human provided supplemental context for this task. Review task messages for the new details.",
|
|
2009
|
+
}, deps);
|
|
2010
|
+
deps.wsServer.broadcastUpdate({ type: "message:new", data: message });
|
|
2011
|
+
if (message.to) {
|
|
2012
|
+
const worker = deps.getTeamState()?.workers?.[message.to];
|
|
2013
|
+
if (worker && worker.status !== "offline") {
|
|
2014
|
+
try {
|
|
2015
|
+
await deliverMessageToWorker(worker, message, deps);
|
|
2016
|
+
} catch (err) {
|
|
2017
|
+
deps.logger.warn(`Controller: failed to forward supplemental context to ${worker.id}: ${String(err)}`);
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
|
|
2023
|
+
manifest.notes = manifest.notes
|
|
2024
|
+
? `${manifest.notes} TeamClaw forwarded this human intake as supplemental context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}.`
|
|
2025
|
+
: `TeamClaw forwarded this human intake as supplemental context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}.`;
|
|
2026
|
+
updateControllerRun(controllerRunId, deps, (run) => {
|
|
2027
|
+
run.manifest = manifest;
|
|
2028
|
+
appendControllerRunEvent(run, {
|
|
2029
|
+
type: "warning",
|
|
2030
|
+
phase: "context_forwarded",
|
|
2031
|
+
source: "controller",
|
|
2032
|
+
status: "running",
|
|
2033
|
+
sessionKey,
|
|
2034
|
+
message: `Forwarded supplemental human context to active task(s): ${targetTasks.map((task) => task.id).join(", ")}`,
|
|
2035
|
+
});
|
|
2036
|
+
});
|
|
2037
|
+
return targetTasks.map((task) => task.id);
|
|
2038
|
+
}
|
|
2039
|
+
|
|
1358
2040
|
async function createControllerManagedTask(
|
|
1359
2041
|
input: {
|
|
1360
2042
|
title: string;
|
|
@@ -1362,6 +2044,7 @@ async function createControllerManagedTask(
|
|
|
1362
2044
|
priority?: TaskPriority;
|
|
1363
2045
|
assignedRole?: RoleId;
|
|
1364
2046
|
createdBy: string;
|
|
2047
|
+
controllerRunId?: string;
|
|
1365
2048
|
controllerSessionKey?: string;
|
|
1366
2049
|
projectName?: string;
|
|
1367
2050
|
recommendedSkills?: string[];
|
|
@@ -1392,6 +2075,7 @@ async function createControllerManagedTask(
|
|
|
1392
2075
|
assignedRole: input.assignedRole,
|
|
1393
2076
|
createdBy: input.createdBy,
|
|
1394
2077
|
recommendedSkills: normalizedRecommendedSkills.length > 0 ? normalizedRecommendedSkills : undefined,
|
|
2078
|
+
controllerRunId: input.createdBy === "controller" ? input.controllerRunId : undefined,
|
|
1395
2079
|
controllerSessionKey: normalizedSessionKey,
|
|
1396
2080
|
projectId,
|
|
1397
2081
|
projectDir,
|
|
@@ -1465,7 +2149,20 @@ async function maybeBackfillExecutionReadyTask(
|
|
|
1465
2149
|
if (options?.source === "task_follow_up") {
|
|
1466
2150
|
return [];
|
|
1467
2151
|
}
|
|
1468
|
-
|
|
2152
|
+
const likelyTechnicalRequest = looksLikeSoftwareRequirement(request)
|
|
2153
|
+
|| manifest.requiredRoles.length > 0
|
|
2154
|
+
|| /code|repo|repository|日志|输出|文件|配置|命令|修复|实现|修改/.test(request.toLowerCase());
|
|
2155
|
+
if (!likelyTechnicalRequest) {
|
|
2156
|
+
return [];
|
|
2157
|
+
}
|
|
2158
|
+
const forwardedTaskIds = await forwardSupplementalHumanContextToActiveTasks(
|
|
2159
|
+
controllerRunId,
|
|
2160
|
+
sessionKey,
|
|
2161
|
+
request,
|
|
2162
|
+
manifest,
|
|
2163
|
+
deps,
|
|
2164
|
+
);
|
|
2165
|
+
if (forwardedTaskIds.length > 0) {
|
|
1469
2166
|
return [];
|
|
1470
2167
|
}
|
|
1471
2168
|
|
|
@@ -1475,6 +2172,7 @@ async function maybeBackfillExecutionReadyTask(
|
|
|
1475
2172
|
description: request,
|
|
1476
2173
|
assignedRole,
|
|
1477
2174
|
createdBy: "controller",
|
|
2175
|
+
controllerRunId,
|
|
1478
2176
|
controllerSessionKey: sessionKey,
|
|
1479
2177
|
recommendedSkills: resolveRecommendedSkillsForRole(assignedRole, []),
|
|
1480
2178
|
}, deps);
|
|
@@ -1751,6 +2449,59 @@ function buildManifestClarificationEntries(
|
|
|
1751
2449
|
];
|
|
1752
2450
|
}
|
|
1753
2451
|
|
|
2452
|
+
async function maybeConvertControllerClarificationToExecutionTask(
|
|
2453
|
+
controllerRunId: string,
|
|
2454
|
+
sessionKey: string,
|
|
2455
|
+
manifest: ControllerOrchestrationManifest,
|
|
2456
|
+
deps: ControllerHttpDeps,
|
|
2457
|
+
): Promise<string[]> {
|
|
2458
|
+
const candidateQuestion = (manifest.clarificationQuestions || []).find((entry) => looksLikeManualExecutionClarification(entry));
|
|
2459
|
+
const followUpDescription = candidateQuestion ? extractExecutableFollowUpFromClarification(candidateQuestion) : null;
|
|
2460
|
+
if (!candidateQuestion || !followUpDescription) {
|
|
2461
|
+
return [];
|
|
2462
|
+
}
|
|
2463
|
+
|
|
2464
|
+
const assignedRole = chooseFallbackAssignedRole(manifest, followUpDescription);
|
|
2465
|
+
const task = await createControllerManagedTask({
|
|
2466
|
+
title: buildFallbackControllerTaskTitle(candidateQuestion, assignedRole),
|
|
2467
|
+
description: followUpDescription,
|
|
2468
|
+
assignedRole,
|
|
2469
|
+
createdBy: "controller",
|
|
2470
|
+
controllerRunId,
|
|
2471
|
+
controllerSessionKey: sessionKey,
|
|
2472
|
+
recommendedSkills: resolveRecommendedSkillsForRole(assignedRole, []),
|
|
2473
|
+
}, deps);
|
|
2474
|
+
if (!task) {
|
|
2475
|
+
return [];
|
|
2476
|
+
}
|
|
2477
|
+
|
|
2478
|
+
manifest.createdTasks = [{
|
|
2479
|
+
title: task.title,
|
|
2480
|
+
assignedRole: task.assignedRole,
|
|
2481
|
+
expectedOutcome: summarizeManifestExpectedOutcome(task),
|
|
2482
|
+
}];
|
|
2483
|
+
manifest.clarificationsNeeded = false;
|
|
2484
|
+
manifest.clarificationQuestions = manifest.clarificationQuestions.filter((entry) => entry !== candidateQuestion);
|
|
2485
|
+
if (Array.isArray(manifest.clarificationSchemas)) {
|
|
2486
|
+
manifest.clarificationSchemas = manifest.clarificationSchemas.filter((schema) => schema.title !== candidateQuestion);
|
|
2487
|
+
}
|
|
2488
|
+
manifest.notes = manifest.notes
|
|
2489
|
+
? `${manifest.notes} TeamClaw converted a manual-action clarification into execution task ${task.id} so the team can perform the validation itself.`
|
|
2490
|
+
: `TeamClaw converted a manual-action clarification into execution task ${task.id} so the team can perform the validation itself.`;
|
|
2491
|
+
updateControllerRun(controllerRunId, deps, (run) => {
|
|
2492
|
+
run.manifest = manifest;
|
|
2493
|
+
appendControllerRunEvent(run, {
|
|
2494
|
+
type: "warning",
|
|
2495
|
+
phase: "clarification_converted_to_task",
|
|
2496
|
+
source: "controller",
|
|
2497
|
+
status: "running",
|
|
2498
|
+
sessionKey,
|
|
2499
|
+
message: `Controller converted a manual-action clarification into execution task ${task.id}.`,
|
|
2500
|
+
});
|
|
2501
|
+
});
|
|
2502
|
+
return [task.id];
|
|
2503
|
+
}
|
|
2504
|
+
|
|
1754
2505
|
function syncControllerRunClarifications(
|
|
1755
2506
|
controllerRunId: string,
|
|
1756
2507
|
sessionKey: string,
|
|
@@ -2066,6 +2817,15 @@ async function runControllerIntakeUnlocked(
|
|
|
2066
2817
|
nextProbeAt: Date.now() + deps.config.taskTimeoutMs,
|
|
2067
2818
|
probeCount: 0,
|
|
2068
2819
|
};
|
|
2820
|
+
const progressSnapshot: {
|
|
2821
|
+
fingerprints: string[];
|
|
2822
|
+
latestMessages: unknown[];
|
|
2823
|
+
lastActivityAt: number;
|
|
2824
|
+
} = {
|
|
2825
|
+
fingerprints: [],
|
|
2826
|
+
latestMessages: [],
|
|
2827
|
+
lastActivityAt: Date.now(),
|
|
2828
|
+
};
|
|
2069
2829
|
|
|
2070
2830
|
const markRateLimitWaiting = async (): Promise<void> => {
|
|
2071
2831
|
if (rateLimitState.active) {
|
|
@@ -2093,11 +2853,48 @@ async function runControllerIntakeUnlocked(
|
|
|
2093
2853
|
};
|
|
2094
2854
|
|
|
2095
2855
|
const noteObservedControllerActivity = (): void => {
|
|
2856
|
+
progressSnapshot.lastActivityAt = Date.now();
|
|
2096
2857
|
inactivityState.active = false;
|
|
2097
2858
|
inactivityState.visibleAt = undefined;
|
|
2098
2859
|
inactivityState.nextProbeAt = Date.now() + deps.config.taskTimeoutMs;
|
|
2099
2860
|
};
|
|
2100
2861
|
|
|
2862
|
+
const syncControllerSessionProgress = async (): Promise<void> => {
|
|
2863
|
+
const sessionMessages = await deps.runtime.subagent.getSessionMessages({
|
|
2864
|
+
sessionKey,
|
|
2865
|
+
limit: CONTROLLER_SESSION_PROGRESS_MESSAGE_LIMIT,
|
|
2866
|
+
});
|
|
2867
|
+
progressSnapshot.latestMessages = Array.isArray(sessionMessages.messages) ? sessionMessages.messages : [];
|
|
2868
|
+
const entries = buildSessionProgressEntries(progressSnapshot.latestMessages, message);
|
|
2869
|
+
const newEntries = getNewSessionProgressEntries(entries, progressSnapshot.fingerprints);
|
|
2870
|
+
progressSnapshot.fingerprints = entries.map((entry) => entry.fingerprint);
|
|
2871
|
+
if (newEntries.length > 0) {
|
|
2872
|
+
noteObservedControllerActivity();
|
|
2873
|
+
}
|
|
2874
|
+
for (const entry of newEntries) {
|
|
2875
|
+
if (entry.isRateLimit) {
|
|
2876
|
+
await markRateLimitWaiting();
|
|
2877
|
+
continue;
|
|
2878
|
+
}
|
|
2879
|
+
if (rateLimitState.active && isStillWaitingResponse(entry.message)) {
|
|
2880
|
+
continue;
|
|
2881
|
+
}
|
|
2882
|
+
if (rateLimitState.active) {
|
|
2883
|
+
clearRateLimitWaiting();
|
|
2884
|
+
}
|
|
2885
|
+
recordControllerRunEvent(controllerRun.id, {
|
|
2886
|
+
type: "progress",
|
|
2887
|
+
phase: entry.phase,
|
|
2888
|
+
source: "subagent",
|
|
2889
|
+
stream: entry.stream,
|
|
2890
|
+
status: "running",
|
|
2891
|
+
sessionKey,
|
|
2892
|
+
runId: runResult.runId,
|
|
2893
|
+
message: entry.message,
|
|
2894
|
+
}, deps);
|
|
2895
|
+
}
|
|
2896
|
+
};
|
|
2897
|
+
|
|
2101
2898
|
const extractSessionAssistantReply = async (): Promise<string> => {
|
|
2102
2899
|
const sessionMessages = await deps.runtime.subagent.getSessionMessages({
|
|
2103
2900
|
sessionKey,
|
|
@@ -2242,6 +3039,12 @@ async function runControllerIntakeUnlocked(
|
|
|
2242
3039
|
timeoutMs: CONTROLLER_RUN_WAIT_SLICE_MS,
|
|
2243
3040
|
});
|
|
2244
3041
|
|
|
3042
|
+
try {
|
|
3043
|
+
await syncControllerSessionProgress();
|
|
3044
|
+
} catch (err) {
|
|
3045
|
+
deps.logger.debug?.(`Controller: failed to sync planning session progress for ${controllerRun.id}: ${String(err)}`);
|
|
3046
|
+
}
|
|
3047
|
+
|
|
2245
3048
|
if (waitResult.status === "ok") {
|
|
2246
3049
|
clearRateLimitWaiting();
|
|
2247
3050
|
noteObservedControllerActivity();
|
|
@@ -2257,7 +3060,7 @@ async function runControllerIntakeUnlocked(
|
|
|
2257
3060
|
}
|
|
2258
3061
|
if (waitResult.status !== "ok") {
|
|
2259
3062
|
const errorMessage = waitResult.error || "Controller intake failed";
|
|
2260
|
-
const createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, sessionKey, deps);
|
|
3063
|
+
const createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, controllerRun.id, sessionKey, deps);
|
|
2261
3064
|
updateControllerRun(controllerRun.id, deps, (run) => {
|
|
2262
3065
|
run.createdTaskIds = createdTaskIds;
|
|
2263
3066
|
run.error = errorMessage;
|
|
@@ -2274,7 +3077,13 @@ async function runControllerIntakeUnlocked(
|
|
|
2274
3077
|
throw new Error(errorMessage);
|
|
2275
3078
|
}
|
|
2276
3079
|
|
|
2277
|
-
let createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, sessionKey, deps);
|
|
3080
|
+
let createdTaskIds = tagControllerCreatedTasks(taskIdsBeforeRun, controllerRun.id, sessionKey, deps);
|
|
3081
|
+
|
|
3082
|
+
try {
|
|
3083
|
+
await syncControllerSessionProgress();
|
|
3084
|
+
} catch (err) {
|
|
3085
|
+
deps.logger.debug?.(`Controller: failed final planning session sync for ${controllerRun.id}: ${String(err)}`);
|
|
3086
|
+
}
|
|
2278
3087
|
|
|
2279
3088
|
const rawReply = completionOverride || await extractSessionAssistantReply()
|
|
2280
3089
|
|| "Controller completed the intake run but did not return any text.";
|
|
@@ -2289,16 +3098,25 @@ async function runControllerIntakeUnlocked(
|
|
|
2289
3098
|
const fallbackTaskIds = await maybeBackfillExecutionReadyTask(
|
|
2290
3099
|
controllerRun.id,
|
|
2291
3100
|
sessionKey,
|
|
2292
|
-
message,
|
|
3101
|
+
message,
|
|
3102
|
+
recordedManifest,
|
|
3103
|
+
deps,
|
|
3104
|
+
{ source: options?.source },
|
|
3105
|
+
);
|
|
3106
|
+
if (fallbackTaskIds.length > 0) {
|
|
3107
|
+
createdTaskIds = Array.from(new Set([...createdTaskIds, ...fallbackTaskIds]));
|
|
3108
|
+
}
|
|
3109
|
+
const convertedClarificationTaskIds = await maybeConvertControllerClarificationToExecutionTask(
|
|
3110
|
+
controllerRun.id,
|
|
3111
|
+
sessionKey,
|
|
2293
3112
|
recordedManifest,
|
|
2294
3113
|
deps,
|
|
2295
|
-
{ source: options?.source },
|
|
2296
3114
|
);
|
|
2297
|
-
if (
|
|
2298
|
-
createdTaskIds = Array.from(new Set([...createdTaskIds, ...
|
|
3115
|
+
if (convertedClarificationTaskIds.length > 0) {
|
|
3116
|
+
createdTaskIds = Array.from(new Set([...createdTaskIds, ...convertedClarificationTaskIds]));
|
|
2299
3117
|
}
|
|
2300
3118
|
syncControllerRunClarifications(controllerRun.id, sessionKey, recordedManifest, deps);
|
|
2301
|
-
const reconciledTasks = reconcileControllerManifestTaskBindings(sessionKey, createdTaskIds, recordedManifest, deps);
|
|
3119
|
+
const reconciledTasks = reconcileControllerManifestTaskBindings(sessionKey, createdTaskIds, recordedManifest, controllerRun.id, deps);
|
|
2302
3120
|
|
|
2303
3121
|
// ── Automatic Team Kickoff ────────────────────────────────────────────
|
|
2304
3122
|
// For complex projects (3+ roles), automatically run a kickoff meeting
|
|
@@ -2334,6 +3152,9 @@ async function runControllerIntakeUnlocked(
|
|
|
2334
3152
|
);
|
|
2335
3153
|
// Store kickoff assessments on the manifest for UI/API visibility
|
|
2336
3154
|
recordedManifest.kickoffPlan = {
|
|
3155
|
+
complexity: recordedManifest.requiredRoles.length >= 5 ? "complex" : "medium",
|
|
3156
|
+
candidateRoles: recordedManifest.requiredRoles as RoleId[],
|
|
3157
|
+
completed: true,
|
|
2337
3158
|
assessments: kickoffResult.assessments,
|
|
2338
3159
|
summary: kickoffResult.summary,
|
|
2339
3160
|
triggeredAt: Date.now(),
|
|
@@ -2417,6 +3238,8 @@ async function runControllerIntakeUnlocked(
|
|
|
2417
3238
|
});
|
|
2418
3239
|
});
|
|
2419
3240
|
|
|
3241
|
+
await pruneStaleControllerRuns(deps, { excludeRunId: controllerRun.id });
|
|
3242
|
+
|
|
2420
3243
|
return {
|
|
2421
3244
|
sessionKey,
|
|
2422
3245
|
runId: runResult.runId,
|
|
@@ -2533,6 +3356,20 @@ function buildTaskContextSnapshot(task: TaskInfo, state: TeamState | null): Task
|
|
|
2533
3356
|
question: clarification.question,
|
|
2534
3357
|
blockingReason: clarification.blockingReason,
|
|
2535
3358
|
})),
|
|
3359
|
+
answeredClarifications: Object.values(state.clarifications)
|
|
3360
|
+
.filter((clarification) => clarification.status === "answered" && clarification.answer)
|
|
3361
|
+
.filter((clarification) =>
|
|
3362
|
+
clarification.taskId === task.id
|
|
3363
|
+
|| normalizeControllerIntakeSessionKey(clarification.controllerSessionKey) === normalizedSessionKey,
|
|
3364
|
+
)
|
|
3365
|
+
.sort((a, b) => (b.answeredAt ?? b.updatedAt ?? 0) - (a.answeredAt ?? a.updatedAt ?? 0))
|
|
3366
|
+
.slice(0, 5)
|
|
3367
|
+
.map((clarification) => ({
|
|
3368
|
+
question: clarification.question,
|
|
3369
|
+
answer: clarification.answer || "",
|
|
3370
|
+
answeredBy: clarification.answeredBy,
|
|
3371
|
+
blockingReason: clarification.blockingReason,
|
|
3372
|
+
})),
|
|
2536
3373
|
handoffPlan: latestRun?.manifest?.handoffPlan,
|
|
2537
3374
|
notes: latestRun?.manifest?.notes,
|
|
2538
3375
|
kickoffSummary: latestRun?.manifest?.kickoffPlan?.summary,
|
|
@@ -2629,6 +3466,22 @@ function scheduleProvisioningReconcile(deps: ControllerHttpDeps, reason: string)
|
|
|
2629
3466
|
void deps.workerProvisioningManager?.requestReconcile(reason);
|
|
2630
3467
|
}
|
|
2631
3468
|
|
|
3469
|
+
/** Collaboration contract helpers: at most ONE active write task per repo checkout. */
|
|
3470
|
+
function taskWriteRoot(task: TaskInfo): string | null {
|
|
3471
|
+
if (task.writeMode === "read-only" || !task.projectDir) { return null; }
|
|
3472
|
+
return task.projectDir.split("__task-")[0] ?? task.projectDir;
|
|
3473
|
+
}
|
|
3474
|
+
|
|
3475
|
+
function activeWriteRoots(state: TeamState): Set<string> {
|
|
3476
|
+
const roots = new Set<string>();
|
|
3477
|
+
for (const t of Object.values(state.tasks)) {
|
|
3478
|
+
if (t.status !== "assigned" && t.status !== "in_progress") { continue; }
|
|
3479
|
+
const root = taskWriteRoot(t);
|
|
3480
|
+
if (root) { roots.add(root); }
|
|
3481
|
+
}
|
|
3482
|
+
return roots;
|
|
3483
|
+
}
|
|
3484
|
+
|
|
2632
3485
|
function broadcastTaskExecutionEvent(
|
|
2633
3486
|
taskId: string,
|
|
2634
3487
|
task: TaskInfo,
|
|
@@ -2735,6 +3588,9 @@ function serveStaticFile(res: ServerResponse, filePath: string, contentType: str
|
|
|
2735
3588
|
res.writeHead(200, {
|
|
2736
3589
|
"Content-Type": contentType,
|
|
2737
3590
|
"Access-Control-Allow-Origin": "*",
|
|
3591
|
+
// UI assets change with every plugin deploy on a localhost controller;
|
|
3592
|
+
// always revalidate so browsers never stick to a stale app.js.
|
|
3593
|
+
"Cache-Control": "no-cache",
|
|
2738
3594
|
});
|
|
2739
3595
|
res.end(content);
|
|
2740
3596
|
} catch {
|
|
@@ -2776,7 +3632,7 @@ function getEffectiveStartupReadiness(
|
|
|
2776
3632
|
startedAt: recorded?.startedAt ?? state?.createdAt ?? Date.now(),
|
|
2777
3633
|
checkedAt: Date.now(),
|
|
2778
3634
|
attempts: recorded?.attempts ?? 0,
|
|
2779
|
-
requiredRoles,
|
|
3635
|
+
requiredRoles: requiredRoles as RoleId[],
|
|
2780
3636
|
readyWorkerIds,
|
|
2781
3637
|
message: recorded?.status === "ready"
|
|
2782
3638
|
? recorded.message
|
|
@@ -2789,7 +3645,7 @@ function getEffectiveStartupReadiness(
|
|
|
2789
3645
|
startedAt: state?.createdAt ?? Date.now(),
|
|
2790
3646
|
checkedAt: Date.now(),
|
|
2791
3647
|
attempts: 0,
|
|
2792
|
-
requiredRoles,
|
|
3648
|
+
requiredRoles: requiredRoles as RoleId[],
|
|
2793
3649
|
readyWorkerIds,
|
|
2794
3650
|
message: `Startup provisioning warm-up is still initializing for ${requiredRoles.join(", ")}.`,
|
|
2795
3651
|
};
|
|
@@ -3038,6 +3894,18 @@ function projectHasMeaningfulFileChanges(
|
|
|
3038
3894
|
if (!fs.existsSync(projectRoot)) {
|
|
3039
3895
|
return false;
|
|
3040
3896
|
}
|
|
3897
|
+
// Collaboration contract: write tasks deliver in a dedicated worktree.
|
|
3898
|
+
// An mtime scan is the wrong test there (committed files keep old mtimes
|
|
3899
|
+
// and the gate may run before the flush) - ask git instead: does HEAD carry
|
|
3900
|
+
// commits beyond the remote refs?
|
|
3901
|
+
if (task.projectDir.includes("__task-")) {
|
|
3902
|
+
try {
|
|
3903
|
+
const out = execFileSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], { cwd: projectRoot }).toString();
|
|
3904
|
+
return Number(out.trim()) > 0;
|
|
3905
|
+
} catch {
|
|
3906
|
+
return false;
|
|
3907
|
+
}
|
|
3908
|
+
}
|
|
3041
3909
|
const threshold = Math.max(task.startedAt ?? 0, task.createdAt ?? 0) - 1000;
|
|
3042
3910
|
const stack = [projectRoot];
|
|
3043
3911
|
while (stack.length > 0) {
|
|
@@ -3572,7 +4440,7 @@ async function dispatchTaskToWorker(
|
|
|
3572
4440
|
worker: WorkerInfo,
|
|
3573
4441
|
deps: ControllerHttpDeps,
|
|
3574
4442
|
): Promise<void> {
|
|
3575
|
-
const { getTeamState } = deps;
|
|
4443
|
+
const { getTeamState, logger, updateTeamState } = deps;
|
|
3576
4444
|
const state = getTeamState();
|
|
3577
4445
|
const task = state?.tasks[taskId];
|
|
3578
4446
|
if (!task) {
|
|
@@ -3585,22 +4453,49 @@ async function dispatchTaskToWorker(
|
|
|
3585
4453
|
try { fs.mkdirSync(projectPath, { recursive: true }); } catch { /* best-effort */ }
|
|
3586
4454
|
}
|
|
3587
4455
|
|
|
4456
|
+
// Collaboration contract: WRITE tasks execute in a task-scoped git worktree
|
|
4457
|
+
// (branch teamclaw/task-<id>) so parallel roles never share a dirty checkout;
|
|
4458
|
+
// delivery happens via push + PR in the write-back reconciler.
|
|
4459
|
+
let assignmentProjectDir = task.projectDir;
|
|
4460
|
+
if (task.writeMode === "write" && task.projectDir?.startsWith("teamauto/") && !task.projectDir.includes("__task-")) {
|
|
4461
|
+
const scheduler = deps.getTeamAutoScheduler?.();
|
|
4462
|
+
if (scheduler) {
|
|
4463
|
+
const repoId = task.projectDir.slice("teamauto/".length).replace(/__/g, "/");
|
|
4464
|
+
try {
|
|
4465
|
+
assignmentProjectDir = await scheduler.ensureWriteWorktree(repoId, taskId);
|
|
4466
|
+
updateTeamState((s) => {
|
|
4467
|
+
const t = s.tasks[taskId];
|
|
4468
|
+
if (t) { t.projectDir = assignmentProjectDir; }
|
|
4469
|
+
});
|
|
4470
|
+
logger.info(`Controller: write task ${taskId} -> worktree projects/${assignmentProjectDir}`);
|
|
4471
|
+
} catch (err) {
|
|
4472
|
+
logger.warn(`Controller: worktree setup failed for ${taskId}, falling back to shared checkout: ${String(err)}`);
|
|
4473
|
+
}
|
|
4474
|
+
}
|
|
4475
|
+
}
|
|
4476
|
+
|
|
3588
4477
|
const sharedWorkspace = deps.workerProvisioningManager?.isSharedWorkspaceWorker(worker.id)
|
|
3589
4478
|
|| false;
|
|
3590
4479
|
const repoState = await refreshControllerRepoState(deps);
|
|
3591
4480
|
const repoInfo = buildRepoSyncInfo(repoState, sharedWorkspace);
|
|
3592
4481
|
const description = buildTaskAssignmentDescription(task, state ?? null, repoInfo);
|
|
3593
4482
|
const recommendedSkills = resolveRecommendedSkillsForRole(task.assignedRole, task.recommendedSkills ?? []);
|
|
3594
|
-
|
|
4483
|
+
// Resume support: reuse the interrupted execution's session so the worker
|
|
4484
|
+
// continues the same persisted OpenClaw conversation instead of starting over.
|
|
4485
|
+
const executionIdentity = (task.checkpoint?.sessionKey)
|
|
4486
|
+
? { executionSessionKey: task.checkpoint.sessionKey, executionIdempotencyKey: buildTaskExecutionIdentity(task.id, worker.id).executionIdempotencyKey }
|
|
4487
|
+
: buildTaskExecutionIdentity(task.id, worker.id);
|
|
3595
4488
|
const assignment: TaskAssignmentPayload = {
|
|
3596
4489
|
taskId: task.id,
|
|
3597
4490
|
title: task.title,
|
|
3598
4491
|
description,
|
|
3599
4492
|
priority: task.priority,
|
|
3600
4493
|
recommendedSkills,
|
|
3601
|
-
projectDir:
|
|
4494
|
+
projectDir: assignmentProjectDir,
|
|
3602
4495
|
executionSessionKey: executionIdentity.executionSessionKey,
|
|
3603
4496
|
executionIdempotencyKey: executionIdentity.executionIdempotencyKey,
|
|
4497
|
+
checkpoint: task.checkpoint,
|
|
4498
|
+
resumeAttempt: task.resumeAttempt,
|
|
3604
4499
|
repo: repoInfo,
|
|
3605
4500
|
teamContext: buildTaskContextSnapshot(task, state ?? null),
|
|
3606
4501
|
};
|
|
@@ -3687,13 +4582,14 @@ async function assignTaskToWorker(
|
|
|
3687
4582
|
return deps.getTeamState()?.tasks[taskId];
|
|
3688
4583
|
}
|
|
3689
4584
|
|
|
3690
|
-
async function autoAssignPendingTasks(
|
|
4585
|
+
export async function autoAssignPendingTasks(
|
|
3691
4586
|
deps: ControllerHttpDeps,
|
|
3692
4587
|
preferredWorkerId?: string,
|
|
3693
4588
|
): Promise<TaskInfo[]> {
|
|
3694
|
-
const { getTeamState, taskRouter, wsServer, logger } = deps;
|
|
4589
|
+
const { getTeamState, taskRouter, wsServer, logger, config } = deps;
|
|
3695
4590
|
const attemptedPairs = new Set<string>();
|
|
3696
4591
|
const assignedTasks: TaskInfo[] = [];
|
|
4592
|
+
const maxConcurrent = config.maxConcurrentTasks;
|
|
3697
4593
|
|
|
3698
4594
|
while (true) {
|
|
3699
4595
|
const state = getTeamState();
|
|
@@ -3701,9 +4597,27 @@ async function autoAssignPendingTasks(
|
|
|
3701
4597
|
break;
|
|
3702
4598
|
}
|
|
3703
4599
|
|
|
4600
|
+
// Throttle: count currently in-progress tasks and respect maxConcurrentTasks
|
|
4601
|
+
const inProgressCount = Object.values(state.tasks).filter(
|
|
4602
|
+
(t) => t.status === "in_progress",
|
|
4603
|
+
).length;
|
|
4604
|
+
if (inProgressCount >= maxConcurrent) {
|
|
4605
|
+
logger.debug?.(
|
|
4606
|
+
`Controller: skipping auto-assign — ${inProgressCount} tasks in_progress (max ${maxConcurrent})`,
|
|
4607
|
+
);
|
|
4608
|
+
break;
|
|
4609
|
+
}
|
|
4610
|
+
|
|
4611
|
+
// Collaboration contract: serialize write tasks per repo checkout - a
|
|
4612
|
+
// second writer on the same root waits until the active one settles.
|
|
4613
|
+
const busyWriteRoots = activeWriteRoots(state);
|
|
3704
4614
|
const candidateAssignments = taskRouter
|
|
3705
4615
|
.autoAssignPendingTasks(state.tasks, state.workers)
|
|
3706
|
-
.filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`))
|
|
4616
|
+
.filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`))
|
|
4617
|
+
.filter(({ task }) => {
|
|
4618
|
+
const root = taskWriteRoot(task);
|
|
4619
|
+
return !(root && busyWriteRoots.has(root));
|
|
4620
|
+
});
|
|
3707
4621
|
|
|
3708
4622
|
const nextAssignment = (
|
|
3709
4623
|
(preferredWorkerId
|
|
@@ -3787,6 +4701,41 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
|
|
|
3787
4701
|
return server;
|
|
3788
4702
|
}
|
|
3789
4703
|
|
|
4704
|
+
function resolveRequestOrigin(req: IncomingMessage, config: PluginConfig): string {
|
|
4705
|
+
const host = req.headers.host;
|
|
4706
|
+
if (typeof host === "string" && host.trim()) {
|
|
4707
|
+
return `http://${host.trim()}`;
|
|
4708
|
+
}
|
|
4709
|
+
return `http://127.0.0.1:${config.port}`;
|
|
4710
|
+
}
|
|
4711
|
+
|
|
4712
|
+
function escapeHtmlText(value: string): string {
|
|
4713
|
+
return value
|
|
4714
|
+
.replace(/&/g, "&")
|
|
4715
|
+
.replace(/</g, "<")
|
|
4716
|
+
.replace(/>/g, ">")
|
|
4717
|
+
.replace(/"/g, """)
|
|
4718
|
+
.replace(/'/g, "'");
|
|
4719
|
+
}
|
|
4720
|
+
|
|
4721
|
+
function sendGithubCallbackHtml(res: ServerResponse, statusCode: number, title: string, message: string): void {
|
|
4722
|
+
const html = [
|
|
4723
|
+
"<!DOCTYPE html><html><head><meta charset=\"utf-8\">",
|
|
4724
|
+
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
|
|
4725
|
+
`<title>${escapeHtmlText(title)}</title>`,
|
|
4726
|
+
"<style>body{font-family:-apple-system,system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:#0f1117;color:#e6e8ee}main{max-width:520px;padding:32px 40px;border:1px solid #2a2f3a;border-radius:14px;background:#161923;text-align:center}h1{font-size:20px;margin:0 0 10px}p{margin:6px 0;color:#a8b0c0;line-height:1.6}</style>",
|
|
4727
|
+
"</head><body><main>",
|
|
4728
|
+
`<h1>${escapeHtmlText(title)}</h1>`,
|
|
4729
|
+
`<p>${escapeHtmlText(message)}</p>`,
|
|
4730
|
+
"</main></body></html>",
|
|
4731
|
+
].join("");
|
|
4732
|
+
res.writeHead(statusCode, {
|
|
4733
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
4734
|
+
"Content-Length": Buffer.byteLength(html),
|
|
4735
|
+
});
|
|
4736
|
+
res.end(html);
|
|
4737
|
+
}
|
|
4738
|
+
|
|
3790
4739
|
async function handleRequest(
|
|
3791
4740
|
req: IncomingMessage,
|
|
3792
4741
|
res: ServerResponse,
|
|
@@ -3811,6 +4760,13 @@ async function handleRequest(
|
|
|
3811
4760
|
return;
|
|
3812
4761
|
}
|
|
3813
4762
|
|
|
4763
|
+
// Standalone GitHub device-login page (big user code + prefilled link + polling).
|
|
4764
|
+
if (req.method === "GET" && (pathname === "/ui/auth/github" || pathname === "/ui/auth/github/")) {
|
|
4765
|
+
const uiPath = path.join(import.meta.dirname, "..", "ui");
|
|
4766
|
+
serveStaticFile(res, path.join(uiPath, "github-login.html"), "text/html; charset=utf-8");
|
|
4767
|
+
return;
|
|
4768
|
+
}
|
|
4769
|
+
|
|
3814
4770
|
if (req.method === "GET" && pathname.startsWith("/ui/")) {
|
|
3815
4771
|
const uiPath = path.join(import.meta.dirname, "..", "ui");
|
|
3816
4772
|
const file = pathname.slice(4); // remove "/ui/"
|
|
@@ -3830,8 +4786,283 @@ async function handleRequest(
|
|
|
3830
4786
|
return;
|
|
3831
4787
|
}
|
|
3832
4788
|
|
|
4789
|
+
// ==================== TeamAuto ====================
|
|
4790
|
+
|
|
4791
|
+
const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
|
|
4792
|
+
|
|
4793
|
+
if (req.method === "GET" && pathname === "/api/v1/teamauto/activity") {
|
|
4794
|
+
if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
|
|
4795
|
+
try {
|
|
4796
|
+
const activity = await teamAuto.getActivity();
|
|
4797
|
+
sendJson(res, 200, { activity });
|
|
4798
|
+
} catch (err) {
|
|
4799
|
+
sendError(res, 500, err instanceof Error ? err.message : "failed to load activity");
|
|
4800
|
+
}
|
|
4801
|
+
return;
|
|
4802
|
+
}
|
|
4803
|
+
|
|
4804
|
+
if (req.method === "GET" && pathname === "/api/v1/teamauto/repos") {
|
|
4805
|
+
if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
|
|
4806
|
+
try {
|
|
4807
|
+
sendJson(res, 200, await teamAuto.getStatus());
|
|
4808
|
+
} catch (err) {
|
|
4809
|
+
sendError(res, 500, err instanceof Error ? err.message : "failed to read TeamAuto status");
|
|
4810
|
+
}
|
|
4811
|
+
return;
|
|
4812
|
+
}
|
|
4813
|
+
|
|
4814
|
+
// Selectable repos for the bind picker (the logged-in GitHub account's).
|
|
4815
|
+
if (req.method === "GET" && pathname === "/api/v1/teamauto/repo-candidates") {
|
|
4816
|
+
try {
|
|
4817
|
+
const auth = getGithubAuthManager(config, logger);
|
|
4818
|
+
const candidates = await createGithubClient(auth).listUserRepos();
|
|
4819
|
+
sendJson(res, 200, { candidates });
|
|
4820
|
+
} catch (err) {
|
|
4821
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to list repositories");
|
|
4822
|
+
}
|
|
4823
|
+
return;
|
|
4824
|
+
}
|
|
4825
|
+
|
|
4826
|
+
if (req.method === "POST" && pathname === "/api/v1/teamauto/repos") {
|
|
4827
|
+
if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
|
|
4828
|
+
let body: Record<string, unknown> = {};
|
|
4829
|
+
try { body = await parseJsonBody(req); } catch { /* empty body */ }
|
|
4830
|
+
const repo = typeof body.repo === "string" ? body.repo : "";
|
|
4831
|
+
if (!repo) { sendError(res, 400, "repo (owner/name) is required"); return; }
|
|
4832
|
+
try {
|
|
4833
|
+
const created = await teamAuto.addRepo(repo, {
|
|
4834
|
+
schedule: typeof body.schedule === "string" ? body.schedule : undefined,
|
|
4835
|
+
keywordInclude: Array.isArray(body.keywordInclude) ? body.keywordInclude.filter((k): k is string => typeof k === "string") : undefined,
|
|
4836
|
+
keywordExclude: Array.isArray(body.keywordExclude) ? body.keywordExclude.filter((k): k is string => typeof k === "string") : undefined,
|
|
4837
|
+
});
|
|
4838
|
+
sendJson(res, 201, created);
|
|
4839
|
+
} catch (err) {
|
|
4840
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to bind repo");
|
|
4841
|
+
}
|
|
4842
|
+
return;
|
|
4843
|
+
}
|
|
4844
|
+
|
|
4845
|
+
if (pathname.startsWith("/api/v1/teamauto/repos/")) {
|
|
4846
|
+
if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
|
|
4847
|
+
const repoId = decodeURIComponent(pathname.slice("/api/v1/teamauto/repos/".length).replace(/\/sweep$/, ""));
|
|
4848
|
+
const isSweep = pathname.endsWith("/sweep");
|
|
4849
|
+
if (req.method === "DELETE" && !isSweep) {
|
|
4850
|
+
try { await teamAuto.removeRepo(repoId); sendJson(res, 200, { ok: true }); }
|
|
4851
|
+
catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to unbind"); }
|
|
4852
|
+
return;
|
|
4853
|
+
}
|
|
4854
|
+
if (req.method === "PATCH" && !isSweep) {
|
|
4855
|
+
let body: Record<string, unknown> = {};
|
|
4856
|
+
try { body = await parseJsonBody(req); } catch { /* empty */ }
|
|
4857
|
+
try {
|
|
4858
|
+
const updated = await teamAuto.updateRepo(repoId, {
|
|
4859
|
+
schedule: typeof body.schedule === "string" ? body.schedule : undefined,
|
|
4860
|
+
maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
|
|
4861
|
+
fullReview: body.fullReview === "off" || body.fullReview === "weekly" || body.fullReview === "daily" ? body.fullReview : undefined,
|
|
4862
|
+
takeOwnership: typeof body.takeOwnership === "boolean" ? body.takeOwnership : undefined,
|
|
4863
|
+
});
|
|
4864
|
+
sendJson(res, 200, updated);
|
|
4865
|
+
} catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to update"); }
|
|
4866
|
+
return;
|
|
4867
|
+
}
|
|
4868
|
+
if (req.method === "POST" && isSweep) {
|
|
4869
|
+
try { sendJson(res, 200, { summary: await teamAuto.runSweepNow(repoId, true) }); }
|
|
4870
|
+
catch (err) { sendError(res, 400, err instanceof Error ? err.message : "sweep failed"); }
|
|
4871
|
+
return;
|
|
4872
|
+
}
|
|
4873
|
+
}
|
|
4874
|
+
|
|
4875
|
+
// ==================== GitHub Auth ====================
|
|
4876
|
+
|
|
4877
|
+
if (req.method === "GET" && pathname === "/api/v1/auth/github/status") {
|
|
4878
|
+
try {
|
|
4879
|
+
const status = await getGithubAuthManager(config, logger).getStatus(resolveRequestOrigin(req, config));
|
|
4880
|
+
sendJson(res, 200, status);
|
|
4881
|
+
} catch (err) {
|
|
4882
|
+
sendError(res, 500, err instanceof Error ? err.message : "failed to read GitHub login status");
|
|
4883
|
+
}
|
|
4884
|
+
return;
|
|
4885
|
+
}
|
|
4886
|
+
|
|
4887
|
+
if (req.method === "POST" && pathname === "/api/v1/auth/github/login") {
|
|
4888
|
+
let flow: string | undefined;
|
|
4889
|
+
try {
|
|
4890
|
+
const body = await parseJsonBody(req) as { flow?: unknown };
|
|
4891
|
+
if (typeof body?.flow === "string") {
|
|
4892
|
+
flow = body.flow.trim();
|
|
4893
|
+
}
|
|
4894
|
+
} catch {
|
|
4895
|
+
// No body or invalid body: fall through to the default (device) flow.
|
|
4896
|
+
}
|
|
4897
|
+
const manager = getGithubAuthManager(config, logger);
|
|
4898
|
+
try {
|
|
4899
|
+
const loginPageUrl = resolveRequestOrigin(req, config).replace(/\/+$/, "") + "/ui/auth/github";
|
|
4900
|
+
if (flow === "web") {
|
|
4901
|
+
// Web flow needs a client secret for the code exchange; the device
|
|
4902
|
+
// flow (default) is fully secretless.
|
|
4903
|
+
const start = manager.beginLogin(resolveRequestOrigin(req, config));
|
|
4904
|
+
sendJson(res, 200, { mode: "web", loginPageUrl, ...start });
|
|
4905
|
+
} else {
|
|
4906
|
+
const start = await manager.beginDeviceLogin();
|
|
4907
|
+
// authorizeUrl intentionally points at our standalone login page so
|
|
4908
|
+
// older UI clients that just open response.authorizeUrl land on the
|
|
4909
|
+
// device-code page instead of a dead web-flow URL.
|
|
4910
|
+
sendJson(res, 200, { mode: "device", loginPageUrl, authorizeUrl: loginPageUrl, ...start });
|
|
4911
|
+
}
|
|
4912
|
+
logger.info(`Controller: GitHub login flow started (${flow === "web" ? "web" : "device"})`);
|
|
4913
|
+
} catch (err) {
|
|
4914
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to start GitHub login");
|
|
4915
|
+
}
|
|
4916
|
+
return;
|
|
4917
|
+
}
|
|
4918
|
+
|
|
4919
|
+
if (req.method === "GET" && pathname === "/api/v1/auth/github/callback") {
|
|
4920
|
+
const callbackError = requestUrl.searchParams.get("error");
|
|
4921
|
+
if (callbackError) {
|
|
4922
|
+
const description = requestUrl.searchParams.get("error_description") ?? "";
|
|
4923
|
+
logger.warn(`Controller: GitHub login was denied (${callbackError})`);
|
|
4924
|
+
sendGithubCallbackHtml(
|
|
4925
|
+
res,
|
|
4926
|
+
400,
|
|
4927
|
+
"GitHub login failed",
|
|
4928
|
+
`Authorization was denied: ${callbackError}${description ? ` (${description})` : ""}`,
|
|
4929
|
+
);
|
|
4930
|
+
return;
|
|
4931
|
+
}
|
|
4932
|
+
const code = requestUrl.searchParams.get("code") ?? "";
|
|
4933
|
+
const state = requestUrl.searchParams.get("state") ?? "";
|
|
4934
|
+
try {
|
|
4935
|
+
const account = await getGithubAuthManager(config, logger).completeLogin({
|
|
4936
|
+
code: code || undefined,
|
|
4937
|
+
state: state || undefined,
|
|
4938
|
+
});
|
|
4939
|
+
logger.info(`Controller: GitHub login completed for @${account.login}`);
|
|
4940
|
+
sendGithubCallbackHtml(
|
|
4941
|
+
res,
|
|
4942
|
+
200,
|
|
4943
|
+
"GitHub login successful",
|
|
4944
|
+
`Signed in as @${account.login}(GitHub 登录成功,可关闭本页返回 TeamClaw)。`,
|
|
4945
|
+
);
|
|
4946
|
+
} catch (err) {
|
|
4947
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
4948
|
+
logger.warn(`Controller: GitHub login callback failed: ${message}`);
|
|
4949
|
+
sendGithubCallbackHtml(res, 400, "GitHub login failed", `${message}`);
|
|
4950
|
+
}
|
|
4951
|
+
return;
|
|
4952
|
+
}
|
|
4953
|
+
|
|
4954
|
+
if (req.method === "POST" && pathname === "/api/v1/auth/github/logout") {
|
|
4955
|
+
try {
|
|
4956
|
+
await getGithubAuthManager(config, logger).logout();
|
|
4957
|
+
sendJson(res, 200, { ok: true });
|
|
4958
|
+
} catch (err) {
|
|
4959
|
+
sendError(res, 500, err instanceof Error ? err.message : "failed to sign out of GitHub");
|
|
4960
|
+
}
|
|
4961
|
+
return;
|
|
4962
|
+
}
|
|
4963
|
+
|
|
4964
|
+
if (req.method === "POST" && pathname === "/api/v1/auth/github/refresh") {
|
|
4965
|
+
try {
|
|
4966
|
+
const store = await getGithubAuthManager(config, logger).forceRefresh();
|
|
4967
|
+
sendJson(res, 200, { ok: true, account: store.account, expiresAt: store.expiresAt });
|
|
4968
|
+
} catch (err) {
|
|
4969
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to refresh the GitHub token");
|
|
4970
|
+
}
|
|
4971
|
+
return;
|
|
4972
|
+
}
|
|
4973
|
+
|
|
3833
4974
|
// ==================== Workspace Browser ====================
|
|
3834
4975
|
|
|
4976
|
+
if (req.method === "GET" && pathname === "/api/v1/workspace/status") {
|
|
4977
|
+
sendJson(res, 200, {
|
|
4978
|
+
workspaceDir: resolveTeamClawWorkspaceDir(),
|
|
4979
|
+
isDefault: teamClawWorkspaceIsDefault(),
|
|
4980
|
+
});
|
|
4981
|
+
return;
|
|
4982
|
+
}
|
|
4983
|
+
|
|
4984
|
+
if (req.method === "POST" && pathname === "/api/v1/workspace/change-dir") {
|
|
4985
|
+
let body: unknown;
|
|
4986
|
+
try {
|
|
4987
|
+
body = await parseJsonBody(req);
|
|
4988
|
+
} catch {
|
|
4989
|
+
sendError(res, 400, "invalid JSON body");
|
|
4990
|
+
return;
|
|
4991
|
+
}
|
|
4992
|
+
const workspaceDir = typeof (body as { workspaceDir?: unknown })?.workspaceDir === "string"
|
|
4993
|
+
? (body as { workspaceDir: string }).workspaceDir
|
|
4994
|
+
: "";
|
|
4995
|
+
if (!workspaceDir.trim()) {
|
|
4996
|
+
sendError(res, 400, "workspaceDir is required");
|
|
4997
|
+
return;
|
|
4998
|
+
}
|
|
4999
|
+
try {
|
|
5000
|
+
const result = await updateTeamClawWorkspaceDir(workspaceDir, {
|
|
5001
|
+
warn: (message: string) => deps.logger.info(message),
|
|
5002
|
+
});
|
|
5003
|
+
sendJson(res, 200, {
|
|
5004
|
+
ok: true,
|
|
5005
|
+
workspaceDir: result.agentEntryPath,
|
|
5006
|
+
configPath: result.configPath,
|
|
5007
|
+
restartRequired: true,
|
|
5008
|
+
});
|
|
5009
|
+
} catch (err) {
|
|
5010
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to update workspace directory");
|
|
5011
|
+
}
|
|
5012
|
+
return;
|
|
5013
|
+
}
|
|
5014
|
+
|
|
5015
|
+
// GET /api/v1/models/config - model catalog + current selection for the UI settings dialog
|
|
5016
|
+
if (req.method === "GET" && pathname === "/api/v1/models/config") {
|
|
5017
|
+
try {
|
|
5018
|
+
sendJson(res, 200, await getTeamClawModelCatalog());
|
|
5019
|
+
} catch (err) {
|
|
5020
|
+
sendError(res, 500, err instanceof Error ? err.message : "failed to read model configuration");
|
|
5021
|
+
}
|
|
5022
|
+
return;
|
|
5023
|
+
}
|
|
5024
|
+
|
|
5025
|
+
// PUT /api/v1/models/config - persist default and per-role model selection
|
|
5026
|
+
if (req.method === "PUT" && pathname === "/api/v1/models/config") {
|
|
5027
|
+
let body: { defaultModel?: unknown; roleModelOverrides?: unknown } | null = null;
|
|
5028
|
+
try {
|
|
5029
|
+
body = await parseJsonBody(req) as { defaultModel?: unknown; roleModelOverrides?: unknown };
|
|
5030
|
+
} catch {
|
|
5031
|
+
sendError(res, 400, "invalid JSON body");
|
|
5032
|
+
return;
|
|
5033
|
+
}
|
|
5034
|
+
const update: { defaultModel?: string; roleModelOverrides?: Record<string, string> } = {};
|
|
5035
|
+
if (typeof body?.defaultModel === "string") {
|
|
5036
|
+
update.defaultModel = body.defaultModel.trim();
|
|
5037
|
+
}
|
|
5038
|
+
if (body?.roleModelOverrides && typeof body.roleModelOverrides === "object" && !Array.isArray(body.roleModelOverrides)) {
|
|
5039
|
+
const overrides: Record<string, string> = {};
|
|
5040
|
+
for (const [role, value] of Object.entries(body.roleModelOverrides as Record<string, unknown>)) {
|
|
5041
|
+
if (typeof value === "string" && value.trim()) {
|
|
5042
|
+
overrides[role] = value.trim();
|
|
5043
|
+
}
|
|
5044
|
+
}
|
|
5045
|
+
update.roleModelOverrides = overrides;
|
|
5046
|
+
}
|
|
5047
|
+
if (update.defaultModel === undefined && update.roleModelOverrides === undefined) {
|
|
5048
|
+
sendError(res, 400, "defaultModel or roleModelOverrides is required");
|
|
5049
|
+
return;
|
|
5050
|
+
}
|
|
5051
|
+
try {
|
|
5052
|
+
await updateTeamClawModelConfig(update, {
|
|
5053
|
+
warn: (message: string) => deps.logger.info(message),
|
|
5054
|
+
});
|
|
5055
|
+
sendJson(res, 200, {
|
|
5056
|
+
ok: true,
|
|
5057
|
+
restartNote: "Config changes hot-reload; restart the gateway (openclaw gateway restart) if a change does not take effect.",
|
|
5058
|
+
catalog: await getTeamClawModelCatalog(),
|
|
5059
|
+
});
|
|
5060
|
+
} catch (err) {
|
|
5061
|
+
sendError(res, 400, err instanceof Error ? err.message : "failed to update model configuration");
|
|
5062
|
+
}
|
|
5063
|
+
return;
|
|
5064
|
+
}
|
|
5065
|
+
|
|
3835
5066
|
if (req.method === "GET" && pathname === "/api/v1/workspace/tree") {
|
|
3836
5067
|
try {
|
|
3837
5068
|
// depth=N limits tree expansion (default 1 for lazy loading)
|
|
@@ -3873,6 +5104,28 @@ async function handleRequest(
|
|
|
3873
5104
|
return;
|
|
3874
5105
|
}
|
|
3875
5106
|
|
|
5107
|
+
if (req.method === "GET" && pathname === "/api/v1/workspace/project-path") {
|
|
5108
|
+
const projectDir = requestUrl.searchParams.get("projectDir") ?? "";
|
|
5109
|
+
if (!projectDir) {
|
|
5110
|
+
sendError(res, 400, "projectDir is required");
|
|
5111
|
+
return;
|
|
5112
|
+
}
|
|
5113
|
+
const absolutePath = resolveSafeProjectDirectory(projectDir);
|
|
5114
|
+
if (!absolutePath) {
|
|
5115
|
+
sendError(res, 400, "Invalid projectDir");
|
|
5116
|
+
return;
|
|
5117
|
+
}
|
|
5118
|
+
if (!fs.existsSync(absolutePath)) {
|
|
5119
|
+
sendError(res, 404, "Project directory not found");
|
|
5120
|
+
return;
|
|
5121
|
+
}
|
|
5122
|
+
sendJson(res, 200, {
|
|
5123
|
+
projectDir,
|
|
5124
|
+
absolutePath,
|
|
5125
|
+
});
|
|
5126
|
+
return;
|
|
5127
|
+
}
|
|
5128
|
+
|
|
3876
5129
|
if (req.method === "GET" && pathname.startsWith("/api/v1/workspace/raw/")) {
|
|
3877
5130
|
const rawPathname = pathname.slice("/api/v1/workspace/raw/".length);
|
|
3878
5131
|
if (!rawPathname) {
|
|
@@ -3991,7 +5244,15 @@ async function handleRequest(
|
|
|
3991
5244
|
// GET /api/v1/workers
|
|
3992
5245
|
if (req.method === "GET" && pathname === "/api/v1/workers") {
|
|
3993
5246
|
const state = getTeamState();
|
|
3994
|
-
const workers = state
|
|
5247
|
+
const workers = state
|
|
5248
|
+
? Object.values(state.workers).map((worker) => ({
|
|
5249
|
+
...worker,
|
|
5250
|
+
// Ghost rows from previous gateway processes (provisioned workers
|
|
5251
|
+
// die with the process they ran in). The controller cleans these on
|
|
5252
|
+
// startup; the flag lets the UI mark leftovers as removable.
|
|
5253
|
+
staleRemovable: worker.id.startsWith("provisioned-") && worker.status === "offline",
|
|
5254
|
+
}))
|
|
5255
|
+
: [];
|
|
3995
5256
|
sendJson(res, 200, { workers });
|
|
3996
5257
|
return;
|
|
3997
5258
|
}
|
|
@@ -4067,18 +5328,19 @@ async function handleRequest(
|
|
|
4067
5328
|
const projectId = inheritedProject?.projectId ?? (explicitProjectName || undefined);
|
|
4068
5329
|
const projectDir = inheritedProject?.projectDir ?? projectId ?? deriveProjectSlug(title);
|
|
4069
5330
|
|
|
4070
|
-
|
|
4071
|
-
|
|
4072
|
-
|
|
4073
|
-
|
|
5331
|
+
const task: TaskInfo = {
|
|
5332
|
+
id: taskId,
|
|
5333
|
+
title,
|
|
5334
|
+
description,
|
|
4074
5335
|
status: "pending",
|
|
4075
5336
|
priority,
|
|
4076
|
-
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
|
|
4080
|
-
|
|
4081
|
-
|
|
5337
|
+
assignedRole,
|
|
5338
|
+
createdBy,
|
|
5339
|
+
recommendedSkills: recommendedSkills.length > 0 ? recommendedSkills : undefined,
|
|
5340
|
+
controllerRunId: undefined,
|
|
5341
|
+
controllerSessionKey,
|
|
5342
|
+
projectId,
|
|
5343
|
+
projectDir,
|
|
4082
5344
|
createdAt: now,
|
|
4083
5345
|
updatedAt: now,
|
|
4084
5346
|
};
|
|
@@ -4134,6 +5396,46 @@ async function handleRequest(
|
|
|
4134
5396
|
return;
|
|
4135
5397
|
}
|
|
4136
5398
|
|
|
5399
|
+
type TeamStatsResponse = {
|
|
5400
|
+
totalWorkers: number;
|
|
5401
|
+
workersByStatus: { idle: number; busy: number; offline: number };
|
|
5402
|
+
totalTasks: number;
|
|
5403
|
+
tasksByStatus: Record<string, number>;
|
|
5404
|
+
averageTaskDuration: number | null;
|
|
5405
|
+
uptime: number;
|
|
5406
|
+
};
|
|
5407
|
+
|
|
5408
|
+
function computeTeamStats(state: TeamState): TeamStatsResponse {
|
|
5409
|
+
const workers = Object.values(state.workers);
|
|
5410
|
+
const tasks = Object.values(state.tasks);
|
|
5411
|
+
|
|
5412
|
+
const workersByStatus = { idle: 0, busy: 0, offline: 0 };
|
|
5413
|
+
for (const worker of workers) {
|
|
5414
|
+
workersByStatus[worker.status] += 1;
|
|
5415
|
+
}
|
|
5416
|
+
|
|
5417
|
+
const tasksByStatus: Record<string, number> = {};
|
|
5418
|
+
for (const task of tasks) {
|
|
5419
|
+
tasksByStatus[task.status] = (tasksByStatus[task.status] ?? 0) + 1;
|
|
5420
|
+
}
|
|
5421
|
+
|
|
5422
|
+
const completedTasks = tasks.filter(
|
|
5423
|
+
(task) => task.status === "completed" && task.startedAt && task.completedAt,
|
|
5424
|
+
);
|
|
5425
|
+
const averageTaskDuration = completedTasks.length > 0
|
|
5426
|
+
? completedTasks.reduce((sum, task) => sum + (task.completedAt! - task.startedAt!), 0) / completedTasks.length
|
|
5427
|
+
: null;
|
|
5428
|
+
|
|
5429
|
+
return {
|
|
5430
|
+
totalWorkers: workers.length,
|
|
5431
|
+
workersByStatus,
|
|
5432
|
+
totalTasks: tasks.length,
|
|
5433
|
+
tasksByStatus,
|
|
5434
|
+
averageTaskDuration,
|
|
5435
|
+
uptime: process.uptime() * 1000,
|
|
5436
|
+
};
|
|
5437
|
+
}
|
|
5438
|
+
|
|
4137
5439
|
// GET /api/v1/tasks
|
|
4138
5440
|
if (req.method === "GET" && pathname === "/api/v1/tasks") {
|
|
4139
5441
|
const state = getTeamState();
|
|
@@ -4142,6 +5444,22 @@ async function handleRequest(
|
|
|
4142
5444
|
return;
|
|
4143
5445
|
}
|
|
4144
5446
|
|
|
5447
|
+
// GET /api/v1/stats
|
|
5448
|
+
if (req.method === "GET" && pathname === "/api/v1/stats") {
|
|
5449
|
+
const state = getTeamState();
|
|
5450
|
+
if (!state) {
|
|
5451
|
+
sendError(res, 503, "Team state not available");
|
|
5452
|
+
return;
|
|
5453
|
+
}
|
|
5454
|
+
try {
|
|
5455
|
+
const stats = computeTeamStats(state);
|
|
5456
|
+
sendJson(res, 200, stats);
|
|
5457
|
+
} catch (err) {
|
|
5458
|
+
sendError(res, 500, `Failed to compute stats: ${err instanceof Error ? err.message : String(err)}`);
|
|
5459
|
+
}
|
|
5460
|
+
return;
|
|
5461
|
+
}
|
|
5462
|
+
|
|
4145
5463
|
// GET /api/v1/tasks/:id
|
|
4146
5464
|
if (req.method === "GET" && pathname.match(/^\/api\/v1\/tasks\/[^/]+$/)) {
|
|
4147
5465
|
const taskId = pathname.split("/").pop()!;
|
|
@@ -4155,6 +5473,29 @@ async function handleRequest(
|
|
|
4155
5473
|
return;
|
|
4156
5474
|
}
|
|
4157
5475
|
|
|
5476
|
+
// DELETE /api/v1/tasks/:id
|
|
5477
|
+
if (req.method === "DELETE" && pathname.match(/^\/api\/v1\/tasks\/[^/]+$/)) {
|
|
5478
|
+
const taskId = pathname.split("/").pop()!;
|
|
5479
|
+
const summary = buildEmptyTaskCleanupSummary();
|
|
5480
|
+
const deleted = await deleteTaskCascade(taskId, deps, summary);
|
|
5481
|
+
if (!deleted) {
|
|
5482
|
+
sendError(res, 404, "Task not found");
|
|
5483
|
+
return;
|
|
5484
|
+
}
|
|
5485
|
+
const stillExists = !!getTeamState()?.tasks[taskId];
|
|
5486
|
+
if (stillExists) {
|
|
5487
|
+
sendError(res, 409, "Task cleanup could not be confirmed");
|
|
5488
|
+
return;
|
|
5489
|
+
}
|
|
5490
|
+
sendJson(res, 200, {
|
|
5491
|
+
status: "deleted",
|
|
5492
|
+
confirmed: true,
|
|
5493
|
+
taskId,
|
|
5494
|
+
cleanup: summary,
|
|
5495
|
+
});
|
|
5496
|
+
return;
|
|
5497
|
+
}
|
|
5498
|
+
|
|
4158
5499
|
// GET /api/v1/tasks/:id/execution
|
|
4159
5500
|
if (req.method === "GET" && pathname.match(/^\/api\/v1\/tasks\/[^/]+\/execution$/)) {
|
|
4160
5501
|
const taskId = pathname.split("/")[4]!;
|
|
@@ -4376,6 +5717,40 @@ async function handleRequest(
|
|
|
4376
5717
|
return;
|
|
4377
5718
|
}
|
|
4378
5719
|
|
|
5720
|
+
// POST /api/v1/tasks/:id/checkpoint - worker persists an execution progress
|
|
5721
|
+
// snapshot so an interrupted task can resume instead of restarting.
|
|
5722
|
+
if (req.method === "POST" && pathname.match(/^\/api\/v1\/tasks\/[^/]+\/checkpoint$/)) {
|
|
5723
|
+
const taskId = pathname.split("/")[4];
|
|
5724
|
+
let body: Record<string, unknown> = {};
|
|
5725
|
+
try { body = await parseJsonBody(req); } catch { sendError(res, 400, "invalid JSON body"); return; }
|
|
5726
|
+
const lastAssistantMessage = typeof body.lastAssistantMessage === "string" ? body.lastAssistantMessage.slice(0, 8000) : "";
|
|
5727
|
+
const progressNote = typeof body.progressNote === "string" ? body.progressNote.slice(0, 1000) : "";
|
|
5728
|
+
const sessionKey = typeof body.sessionKey === "string" ? body.sessionKey : "";
|
|
5729
|
+
if (!lastAssistantMessage && !progressNote) {
|
|
5730
|
+
sendError(res, 400, "lastAssistantMessage or progressNote is required");
|
|
5731
|
+
return;
|
|
5732
|
+
}
|
|
5733
|
+
const updated = updateTeamState((s) => {
|
|
5734
|
+
const task = s.tasks[taskId];
|
|
5735
|
+
if (!task) { return; }
|
|
5736
|
+
const prev = task.checkpoint;
|
|
5737
|
+
const notes = [...(prev?.progressNotes ?? [])];
|
|
5738
|
+
if (progressNote && !notes.includes(progressNote)) { notes.push(progressNote); }
|
|
5739
|
+
task.checkpoint = {
|
|
5740
|
+
updatedAt: Date.now(),
|
|
5741
|
+
attempt: prev?.attempt ?? 0,
|
|
5742
|
+
sessionKey: sessionKey || prev?.sessionKey || "",
|
|
5743
|
+
lastAssistantMessage: lastAssistantMessage || prev?.lastAssistantMessage || "",
|
|
5744
|
+
progressNotes: notes.slice(-10),
|
|
5745
|
+
};
|
|
5746
|
+
task.updatedAt = Date.now();
|
|
5747
|
+
});
|
|
5748
|
+
const task = updated?.tasks[taskId];
|
|
5749
|
+
if (!task) { sendError(res, 404, "task not found"); return; }
|
|
5750
|
+
sendJson(res, 200, { ok: true, updatedAt: task.checkpoint?.updatedAt });
|
|
5751
|
+
return;
|
|
5752
|
+
}
|
|
5753
|
+
|
|
4379
5754
|
// POST /api/v1/tasks/:id/result-contract
|
|
4380
5755
|
if (req.method === "POST" && pathname.match(/^\/api\/v1\/tasks\/[^/]+\/result-contract$/)) {
|
|
4381
5756
|
const taskId = pathname.split("/")[4]!;
|
|
@@ -4468,7 +5843,7 @@ async function handleRequest(
|
|
|
4468
5843
|
}, deps);
|
|
4469
5844
|
}
|
|
4470
5845
|
|
|
4471
|
-
const effectiveContract = buildEffectiveTaskResultContract(currentTask, result, error, submittedContract);
|
|
5846
|
+
const effectiveContract = buildEffectiveTaskResultContract(currentTask, result, error, submittedContract ?? undefined);
|
|
4472
5847
|
|
|
4473
5848
|
if (!error && effectiveContract.outcome === "blocked") {
|
|
4474
5849
|
updateTeamState((teamState) => {
|
|
@@ -4527,7 +5902,7 @@ async function handleRequest(
|
|
|
4527
5902
|
&& gatedTask
|
|
4528
5903
|
&& taskRequiresMeaningfulProjectChangeGate(gatedTask)
|
|
4529
5904
|
&& !projectHasMeaningfulFileChanges(gatedTask, effectiveContract)
|
|
4530
|
-
&& !allowsNoChangeCompletion(gatedTask, submittedContract, result)
|
|
5905
|
+
&& !allowsNoChangeCompletion(gatedTask, submittedContract ?? undefined, result)
|
|
4531
5906
|
) {
|
|
4532
5907
|
error = "Task reported completion but no meaningful project file changes were detected in the assigned project directory.";
|
|
4533
5908
|
recordTaskExecutionEvent(taskId, {
|
|
@@ -4770,6 +6145,51 @@ async function handleRequest(
|
|
|
4770
6145
|
return;
|
|
4771
6146
|
}
|
|
4772
6147
|
|
|
6148
|
+
// DELETE /api/v1/projects/:projectDir
|
|
6149
|
+
if (req.method === "DELETE" && pathname.match(/^\/api\/v1\/projects\/[^/]+$/)) {
|
|
6150
|
+
const projectDir = decodeURIComponent(pathname.split("/").pop()!);
|
|
6151
|
+
const result = await deleteProjectCascade(projectDir, deps);
|
|
6152
|
+
if (!result.deleted) {
|
|
6153
|
+
sendError(res, 404, "Project not found or project cleanup could not be confirmed");
|
|
6154
|
+
return;
|
|
6155
|
+
}
|
|
6156
|
+
const safeProjectPath = resolveSafeProjectDirectory(projectDir);
|
|
6157
|
+
const stillExists = safeProjectPath ? fs.existsSync(safeProjectPath) : true;
|
|
6158
|
+
if (stillExists) {
|
|
6159
|
+
sendError(res, 409, "Project cleanup could not be confirmed");
|
|
6160
|
+
return;
|
|
6161
|
+
}
|
|
6162
|
+
sendJson(res, 200, {
|
|
6163
|
+
status: "deleted",
|
|
6164
|
+
confirmed: true,
|
|
6165
|
+
projectDir,
|
|
6166
|
+
cleanup: result.summary,
|
|
6167
|
+
});
|
|
6168
|
+
return;
|
|
6169
|
+
}
|
|
6170
|
+
|
|
6171
|
+
// DELETE /api/v1/controller/runs/:id
|
|
6172
|
+
if (req.method === "DELETE" && pathname.match(/^\/api\/v1\/controller\/runs\/[^/]+$/)) {
|
|
6173
|
+
const runId = pathname.split("/").pop()!;
|
|
6174
|
+
const result = await deleteControllerRunCascade(runId, deps);
|
|
6175
|
+
if (!result.deleted) {
|
|
6176
|
+
sendError(res, 404, "Controller run not found");
|
|
6177
|
+
return;
|
|
6178
|
+
}
|
|
6179
|
+
const stillExists = !!getTeamState()?.controllerRuns[runId];
|
|
6180
|
+
if (stillExists) {
|
|
6181
|
+
sendError(res, 409, "Planning run cleanup could not be confirmed");
|
|
6182
|
+
return;
|
|
6183
|
+
}
|
|
6184
|
+
sendJson(res, 200, {
|
|
6185
|
+
status: "deleted",
|
|
6186
|
+
confirmed: true,
|
|
6187
|
+
runId,
|
|
6188
|
+
cleanup: result.summary,
|
|
6189
|
+
});
|
|
6190
|
+
return;
|
|
6191
|
+
}
|
|
6192
|
+
|
|
4773
6193
|
// POST /api/v1/controller/intake
|
|
4774
6194
|
if (req.method === "POST" && pathname === "/api/v1/controller/intake") {
|
|
4775
6195
|
const readinessGate = shouldBlockControllerUntilProvisioningReady(deps, currentState);
|