@teamclaws/teamclaw 2026.8.0 → 2026.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.mjs +46 -15
- package/dist/api.js +1 -0
- package/dist/index.js +325 -0
- package/dist/src/config.js +412 -0
- package/dist/src/controller/clarification-routes.js +315 -0
- package/dist/src/controller/controller-capacity.js +14 -0
- package/dist/src/controller/controller-intake.js +895 -0
- package/dist/src/controller/controller-planning.js +813 -0
- package/dist/src/controller/controller-runs.js +175 -0
- package/dist/src/controller/controller-service.js +624 -0
- package/dist/src/controller/controller-tools.js +587 -0
- package/dist/src/controller/delivery-report.js +458 -0
- package/dist/src/controller/github-auth.js +564 -0
- package/dist/src/controller/http-server.js +284 -0
- package/dist/src/controller/kickoff-orchestrator.js +246 -0
- package/dist/src/controller/managed-gateway-process.js +286 -0
- package/dist/src/controller/message-delivery.js +28 -0
- package/dist/src/controller/message-router.js +38 -0
- package/dist/src/controller/message-routes.js +114 -0
- package/dist/src/controller/orchestration-manifest.js +151 -0
- package/dist/src/controller/preview-manager.js +586 -0
- package/dist/src/controller/preview-proxy.js +98 -0
- package/dist/src/controller/profile-switch.js +289 -0
- package/dist/src/controller/project-registry.js +294 -0
- package/dist/src/controller/prompt-injector.js +197 -0
- package/dist/src/controller/repo-routes.js +63 -0
- package/dist/src/controller/role-inference.js +246 -0
- package/dist/src/controller/route-table.js +1353 -0
- package/dist/src/controller/task-assignment.js +508 -0
- package/dist/src/controller/task-cleanup.js +258 -0
- package/dist/src/controller/task-execution.js +240 -0
- package/dist/src/controller/task-results.js +461 -0
- package/dist/src/controller/task-router.js +137 -0
- package/dist/src/controller/task-routes.js +703 -0
- package/dist/src/controller/teamauto-routes.js +124 -0
- package/dist/src/controller/tunnel-manager.js +548 -0
- package/dist/src/controller/ui-assets.js +68 -0
- package/dist/src/controller/websocket.js +42 -0
- package/dist/src/controller/worker-provisioning.js +1674 -0
- package/dist/src/controller/worker-routes.js +188 -0
- package/dist/src/discovery.js +86 -0
- package/dist/src/git-collaboration.js +694 -0
- package/dist/src/identity.js +132 -0
- package/dist/src/install-defaults.js +1 -0
- package/dist/src/interaction-contracts.js +531 -0
- package/dist/src/networking.js +91 -0
- package/dist/src/openclaw-workspace.js +925 -0
- package/dist/src/profile-loader.js +486 -0
- package/dist/src/profiles/banking.json +178 -0
- package/dist/src/profiles/crossborder-ecom.json +253 -0
- package/dist/src/profiles/insurance.json +157 -0
- package/dist/src/profiles/knowledge/hs-structure.md +97 -0
- package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
- package/dist/src/profiles/knowledge/vat-principles.md +85 -0
- package/dist/src/profiles/schema.json +201 -0
- package/dist/src/profiles/securities.json +137 -0
- package/dist/src/profiles/software-rd.json +264 -0
- package/dist/src/profiles/trading-co.json +200 -0
- package/dist/src/prompt-policy.js +386 -0
- package/dist/src/protocol.js +58 -0
- package/dist/src/role-ids.js +29 -0
- package/dist/src/roles.js +390 -0
- package/dist/src/session-roles.js +14 -0
- package/dist/src/state.js +361 -0
- package/dist/src/task-executor.js +1023 -0
- package/dist/src/teamauto/github-client.js +210 -0
- package/dist/src/teamauto/norms.js +85 -0
- package/dist/src/teamauto/repo-sync.js +423 -0
- package/dist/src/teamauto/scanner.js +207 -0
- package/dist/src/teamauto/schedule.js +123 -0
- package/dist/src/teamauto/scheduler.js +907 -0
- package/dist/src/teamauto/store.js +133 -0
- package/dist/src/types.js +290 -0
- package/dist/src/ui/app.js +4860 -0
- package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
- package/dist/src/ui/github-login.html +296 -0
- package/dist/src/ui/index.html +447 -0
- package/dist/src/ui/style.css +2805 -0
- package/dist/src/worker/http-handler.js +146 -0
- package/dist/src/worker/message-queue.js +24 -0
- package/dist/src/worker/prompt-injector.js +78 -0
- package/dist/src/worker/skill-installer.js +255 -0
- package/dist/src/worker/tools.js +541 -0
- package/dist/src/worker/worker-service.js +307 -0
- package/dist/src/workspace-browser.js +269 -0
- package/openclaw.plugin.json +28 -1
- package/package.json +3 -2
- package/src/config.ts +33 -2
- package/src/controller/clarification-routes.ts +404 -0
- package/src/controller/controller-intake.ts +1113 -0
- package/src/controller/controller-planning.ts +1029 -0
- package/src/controller/controller-runs.ts +239 -0
- package/src/controller/controller-service.ts +295 -41
- package/src/controller/controller-tools.ts +11 -7
- package/src/controller/http-server.ts +294 -6971
- package/src/controller/kickoff-orchestrator.ts +70 -7
- package/src/controller/message-delivery.ts +49 -0
- package/src/controller/message-routes.ts +137 -0
- package/src/controller/orchestration-manifest.ts +6 -29
- package/src/controller/preview-proxy.ts +127 -0
- package/src/controller/profile-switch.ts +366 -0
- package/src/controller/project-registry.ts +361 -0
- package/src/controller/prompt-injector.ts +23 -8
- package/src/controller/repo-routes.ts +91 -0
- package/src/controller/role-inference.ts +260 -22
- package/src/controller/route-table.ts +1616 -0
- package/src/controller/task-assignment.ts +618 -0
- package/src/controller/task-cleanup.ts +344 -0
- package/src/controller/task-execution.ts +356 -0
- package/src/controller/task-results.ts +544 -0
- package/src/controller/task-router.ts +98 -6
- package/src/controller/task-routes.ts +812 -0
- package/src/controller/teamauto-routes.ts +121 -0
- package/src/controller/ui-assets.ts +70 -0
- package/src/controller/websocket.ts +13 -1
- package/src/controller/worker-provisioning.ts +32 -4
- package/src/controller/worker-routes.ts +241 -0
- package/src/identity.ts +3 -2
- package/src/interaction-contracts.ts +7 -7
- package/src/openclaw-workspace.ts +44 -18
- package/src/profile-loader.ts +650 -0
- package/src/profiles/banking.json +178 -0
- package/src/profiles/crossborder-ecom.json +253 -0
- package/src/profiles/insurance.json +157 -0
- package/src/profiles/knowledge/hs-structure.md +97 -0
- package/src/profiles/knowledge/incoterms-2020.md +188 -0
- package/src/profiles/knowledge/vat-principles.md +85 -0
- package/src/profiles/schema.json +201 -0
- package/src/profiles/securities.json +137 -0
- package/src/profiles/software-rd.json +264 -0
- package/src/profiles/trading-co.json +200 -0
- package/src/prompt-policy.ts +27 -13
- package/src/role-ids.ts +31 -0
- package/src/roles.ts +60 -14
- package/src/session-roles.ts +14 -0
- package/src/state.ts +236 -9
- package/src/task-executor.ts +7 -18
- package/src/teamauto/github-client.ts +21 -0
- package/src/teamauto/repo-sync.ts +246 -6
- package/src/teamauto/scanner.ts +47 -13
- package/src/teamauto/scheduler.ts +259 -16
- package/src/teamauto/store.ts +12 -0
- package/src/types.ts +133 -16
- package/src/ui/app.js +592 -24
- package/src/ui/index.html +44 -11
- package/src/ui/style.css +194 -0
- package/src/worker/prompt-injector.ts +48 -8
- package/src/worker/skill-installer.ts +3 -1
- package/src/worker/worker-service.ts +83 -3
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import { exec } from "node:child_process";
|
|
3
|
+
import { loadTeamState, saveTeamState } from "../state.js";
|
|
4
|
+
import { MDnsAdvertiser } from "../discovery.js";
|
|
5
|
+
import { WORKER_TIMEOUT_MS } from "../protocol.js";
|
|
6
|
+
import { createControllerHttpServer } from "./http-server.js";
|
|
7
|
+
// PR-C of issue #204: the assignment pipeline incl. the gated auto-assign
|
|
8
|
+
// loop lives in ./task-assignment.js, not http-server.ts.
|
|
9
|
+
import { autoAssignPendingTasks } from "./task-assignment.js";
|
|
10
|
+
// PR-A of issue #204: the profile switch state machine (incl. crash resume)
|
|
11
|
+
// lives in ./profile-switch.ts, not http-server.ts.
|
|
12
|
+
import { resumeTeamProfileSwitch } from "./profile-switch.js";
|
|
13
|
+
import { TaskRouter } from "./task-router.js";
|
|
14
|
+
import { MessageRouter } from "./message-router.js";
|
|
15
|
+
import { TeamWebSocketServer } from "./websocket.js";
|
|
16
|
+
import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey } from "../openclaw-workspace.js";
|
|
17
|
+
import { ensureControllerGitRepo } from "../git-collaboration.js";
|
|
18
|
+
import { WorkerProvisioningManager } from "./worker-provisioning.js";
|
|
19
|
+
import { PreviewManager } from "./preview-manager.js";
|
|
20
|
+
import { runKickoffMeeting, buildKickoffAssessmentPrompt, ASSESSMENT_TIMEOUT_MS } from "./kickoff-orchestrator.js";
|
|
21
|
+
import { resolvePreferredLanAddress } from "../networking.js";
|
|
22
|
+
import { createTeamAutoScheduler } from "../teamauto/scheduler.js";
|
|
23
|
+
import { getGithubAuthManager } from "./github-auth.js";
|
|
24
|
+
// Phase 1.6 (design 2.3): TeamState.profileId is the single runtime truth for
|
|
25
|
+
// the active TeamProfile; config teamProfile only seeds first initialization.
|
|
26
|
+
import { getActiveProfile, getActiveRoleIds, hasProfile, setActiveProfileId, validateActiveRoleId, SOFTWARE_RD_PROFILE_ID } from "../profile-loader.js";
|
|
27
|
+
function getPreferredLanUiUrl(port) {
|
|
28
|
+
const preferredLanAddress = resolvePreferredLanAddress();
|
|
29
|
+
if (!preferredLanAddress) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
return `http://${preferredLanAddress}:${port}/ui`;
|
|
33
|
+
}
|
|
34
|
+
export function createControllerService(deps) {
|
|
35
|
+
const { config, logger } = deps;
|
|
36
|
+
let teamState = null;
|
|
37
|
+
let mdnsAdvertiser;
|
|
38
|
+
let taskRouter;
|
|
39
|
+
let messageRouter;
|
|
40
|
+
let wsServer;
|
|
41
|
+
let timeoutTimer = null;
|
|
42
|
+
let workerProvisioningManager = null;
|
|
43
|
+
let teamAutoSchedulerRef = null;
|
|
44
|
+
let previewManager;
|
|
45
|
+
return {
|
|
46
|
+
id: "teamclaw-controller",
|
|
47
|
+
async start(_ctx) {
|
|
48
|
+
const serviceStartedAt = Date.now();
|
|
49
|
+
await ensureOpenClawWorkspaceMemoryDir(logger);
|
|
50
|
+
// Load or create team state. The active profile is resolved FIRST (from
|
|
51
|
+
// the restored TeamState.profileId, or the config bootstrap value on
|
|
52
|
+
// first initialization) so that capability-dependent startup wiring
|
|
53
|
+
// below knows which profile it is initializing (Phase 2.3 preview).
|
|
54
|
+
teamState = await loadTeamState(config.teamName);
|
|
55
|
+
let seededProfileId;
|
|
56
|
+
if (!teamState) {
|
|
57
|
+
// Phase 1.6: first initialization seeds the active profile from the
|
|
58
|
+
// config bootstrap value. An unknown id is the one sanctioned
|
|
59
|
+
// fallback (design 2.2): warn and run the software-rd baseline.
|
|
60
|
+
const requestedProfileId = config.teamProfile;
|
|
61
|
+
seededProfileId = requestedProfileId;
|
|
62
|
+
if (!hasProfile(requestedProfileId)) {
|
|
63
|
+
seededProfileId = SOFTWARE_RD_PROFILE_ID;
|
|
64
|
+
logger.warn(`Controller: configured teamProfile "${requestedProfileId}" is not a built-in profile; falling back to "${SOFTWARE_RD_PROFILE_ID}"`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
// Restored state: TeamState.profileId is the runtime truth (config
|
|
69
|
+
// changes do not re-seed it). A dangling reference means the profile
|
|
70
|
+
// package this team ran on is not available in this installation.
|
|
71
|
+
// Design 2.2 red line: FATAL, never silently run another profile -
|
|
72
|
+
// that is exactly how a banking team would degrade into the software
|
|
73
|
+
// baseline unnoticed. (The config-miss fallback above stays a warn:
|
|
74
|
+
// it only seeds first initialization, where no team exists yet.)
|
|
75
|
+
if (!hasProfile(teamState.profileId)) {
|
|
76
|
+
throw new Error(`Controller: team state references team profile "${teamState.profileId}", which is not available in this installation. `
|
|
77
|
+
+ "Check the teamProfile config value and the persisted state profileId, or reinstall a TeamClaw version that ships this profile.");
|
|
78
|
+
}
|
|
79
|
+
seededProfileId = teamState.profileId;
|
|
80
|
+
}
|
|
81
|
+
setActiveProfileId(seededProfileId);
|
|
82
|
+
const activeCapabilities = getActiveProfile().capabilities;
|
|
83
|
+
// Phase 2.3 preview (minimal capability wiring, design 2.1): the git
|
|
84
|
+
// collaboration repo is only prepared for profiles with git enabled -
|
|
85
|
+
// a document-delivery team has no repo concept. On the software-rd
|
|
86
|
+
// baseline (git: true) behavior is unchanged.
|
|
87
|
+
const repoState = activeCapabilities.git
|
|
88
|
+
? await ensureControllerGitRepo(config, logger).catch((err) => {
|
|
89
|
+
logger.warn(`Controller: failed to prepare git collaboration repo: ${err instanceof Error ? err.message : String(err)}`);
|
|
90
|
+
return null;
|
|
91
|
+
})
|
|
92
|
+
: null;
|
|
93
|
+
let repoStateChanged = false;
|
|
94
|
+
if (!teamState) {
|
|
95
|
+
teamState = {
|
|
96
|
+
profileId: seededProfileId,
|
|
97
|
+
teamName: config.teamName,
|
|
98
|
+
workers: {},
|
|
99
|
+
tasks: {},
|
|
100
|
+
controllerRuns: {},
|
|
101
|
+
projects: {},
|
|
102
|
+
messages: [],
|
|
103
|
+
clarifications: {},
|
|
104
|
+
repo: repoState ?? undefined,
|
|
105
|
+
createdAt: Date.now(),
|
|
106
|
+
updatedAt: Date.now(),
|
|
107
|
+
};
|
|
108
|
+
await saveTeamState(teamState);
|
|
109
|
+
logger.info(`Controller: created new team "${config.teamName}" (profile: ${seededProfileId})`);
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
const previousRepoState = JSON.stringify(teamState.repo ?? null);
|
|
113
|
+
teamState.repo = repoState ?? (activeCapabilities.git ? teamState.repo : undefined);
|
|
114
|
+
repoStateChanged = JSON.stringify(teamState.repo ?? null) !== previousRepoState;
|
|
115
|
+
logger.info(`Controller: restored team "${config.teamName}" with ${Object.keys(teamState.workers).length} workers`);
|
|
116
|
+
}
|
|
117
|
+
deps.onTeamStateAvailable?.(() => teamState);
|
|
118
|
+
const updateState = (updater) => {
|
|
119
|
+
updater(teamState);
|
|
120
|
+
void saveTeamState(teamState);
|
|
121
|
+
return teamState;
|
|
122
|
+
};
|
|
123
|
+
// Provisioned workers die with the previous gateway process. Their
|
|
124
|
+
// persisted entries flip to offline once heartbeats stop but were
|
|
125
|
+
// never removed, so every gateway restart accumulated ghost rows in
|
|
126
|
+
// the workers list. Clear them on startup: provisioned-* entries that
|
|
127
|
+
// are offline (or whose heartbeat predates this process) cannot be
|
|
128
|
+
// alive because no worker for them exists yet.
|
|
129
|
+
const ghostWorkerIds = Object.values(teamState.workers)
|
|
130
|
+
.filter((worker) => worker.id.startsWith("provisioned-")
|
|
131
|
+
&& (worker.status === "offline" || !worker.lastHeartbeat || worker.lastHeartbeat < serviceStartedAt))
|
|
132
|
+
.map((worker) => worker.id);
|
|
133
|
+
if (ghostWorkerIds.length > 0) {
|
|
134
|
+
updateState((state) => {
|
|
135
|
+
for (const workerId of ghostWorkerIds) {
|
|
136
|
+
delete state.workers[workerId];
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
logger.info(`Controller: removed ${ghostWorkerIds.length} stale provisioned worker record(s) from a previous gateway process`);
|
|
140
|
+
}
|
|
141
|
+
workerProvisioningManager = new WorkerProvisioningManager({
|
|
142
|
+
config,
|
|
143
|
+
logger,
|
|
144
|
+
getTeamState: () => teamState,
|
|
145
|
+
updateTeamState: updateState,
|
|
146
|
+
});
|
|
147
|
+
if (workerProvisioningManager.isEnabled()) {
|
|
148
|
+
workerProvisioningManager.primeStartupReadiness();
|
|
149
|
+
}
|
|
150
|
+
previewManager = new PreviewManager({
|
|
151
|
+
logger,
|
|
152
|
+
getTeamState: () => teamState,
|
|
153
|
+
updateTeamState: updateState,
|
|
154
|
+
});
|
|
155
|
+
// Run ALL syncState calls (avoid || short-circuit skipping some).
|
|
156
|
+
const syncC = workerProvisioningManager.syncState(teamState);
|
|
157
|
+
if (repoStateChanged || syncC) {
|
|
158
|
+
await saveTeamState(teamState);
|
|
159
|
+
}
|
|
160
|
+
// Clean up orphaned tasks — tasks assigned to workers that no longer
|
|
161
|
+
// exist OR that are offline (stale entries surviving from a previous run).
|
|
162
|
+
// Resume support: instead of silently restarting, keep the checkpoint and
|
|
163
|
+
// count resume attempts; past MAX the task fails fast instead of looping.
|
|
164
|
+
const MAX_RESUME_ATTEMPTS = 3;
|
|
165
|
+
{
|
|
166
|
+
let orphanCleaned = false;
|
|
167
|
+
for (const task of Object.values(teamState.tasks)) {
|
|
168
|
+
if (task.assignedWorkerId &&
|
|
169
|
+
(task.status === "assigned" || task.status === "in_progress")) {
|
|
170
|
+
const worker = teamState.workers[task.assignedWorkerId];
|
|
171
|
+
if (!worker || worker.status === "offline") {
|
|
172
|
+
const attempt = (task.resumeAttempt ?? 0) + 1;
|
|
173
|
+
if (attempt > MAX_RESUME_ATTEMPTS) {
|
|
174
|
+
logger.warn(`Controller: task ${task.id} exceeded ${MAX_RESUME_ATTEMPTS} resume attempts - failing`);
|
|
175
|
+
task.status = "failed";
|
|
176
|
+
task.error = `resumed ${MAX_RESUME_ATTEMPTS} times without completing (last checkpoint: ${task.checkpoint?.lastAssistantMessage?.slice(0, 200) ?? "none"})`;
|
|
177
|
+
task.updatedAt = Date.now();
|
|
178
|
+
orphanCleaned = true;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
logger.info(`Controller: resetting orphaned task ${task.id} for resume attempt ${attempt} (worker ${task.assignedWorkerId} ${worker ? "offline" : "missing"})`);
|
|
182
|
+
task.status = "pending";
|
|
183
|
+
task.assignedWorkerId = undefined;
|
|
184
|
+
task.resumeAttempt = attempt;
|
|
185
|
+
if (task.checkpoint) {
|
|
186
|
+
task.checkpoint.attempt = attempt;
|
|
187
|
+
}
|
|
188
|
+
task.updatedAt = Date.now();
|
|
189
|
+
orphanCleaned = true;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (orphanCleaned) {
|
|
194
|
+
await saveTeamState(teamState);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
mdnsAdvertiser = new MDnsAdvertiser(logger);
|
|
198
|
+
// Phase 2.5 wiring (design 2.3 "LLM 兜底", P2.5 follow-up): the
|
|
199
|
+
// controller LLM session is the production role judge for tasks the
|
|
200
|
+
// bilingual token fast path refuses to decide (tie / all-zero). The
|
|
201
|
+
// judge runs on a dedicated one-shot subagent session - NOT the intake
|
|
202
|
+
// conversation - so verdicts never pollute intake semantics. Missing
|
|
203
|
+
// runtime subagent => no judge, and the TaskRouter keeps its exact
|
|
204
|
+
// pre-wiring behavior.
|
|
205
|
+
const llmRoleJudge = createControllerLlmRoleJudge(deps);
|
|
206
|
+
if (llmRoleJudge) {
|
|
207
|
+
logger.info("Controller: LLM role judge wired into task dispatch (unconfident role inference escalates to the controller LLM)");
|
|
208
|
+
}
|
|
209
|
+
taskRouter = new TaskRouter(logger, llmRoleJudge ? { llmRoleJudge } : undefined);
|
|
210
|
+
messageRouter = new MessageRouter(logger);
|
|
211
|
+
wsServer = new TeamWebSocketServer(logger);
|
|
212
|
+
// When running inside a container (Docker or K8s), bind to 0.0.0.0
|
|
213
|
+
// so that port mapping, service networking, and health probes work.
|
|
214
|
+
// When running locally (host machine), bind to 127.0.0.1 for safety.
|
|
215
|
+
const isContainer = fs.existsSync("/.dockerenv") ||
|
|
216
|
+
fs.existsSync("/run/.containerenv") ||
|
|
217
|
+
process.env.KUBERNETES_SERVICE_HOST !== undefined;
|
|
218
|
+
const listenPort = config.port;
|
|
219
|
+
const listenHost = isContainer ? "0.0.0.0" : "127.0.0.1";
|
|
220
|
+
let serviceKickoffHandler;
|
|
221
|
+
const httpDeps = {
|
|
222
|
+
config,
|
|
223
|
+
logger,
|
|
224
|
+
runtime: deps.runtime,
|
|
225
|
+
getTeamState: () => teamState,
|
|
226
|
+
updateTeamState: updateState,
|
|
227
|
+
taskRouter,
|
|
228
|
+
messageRouter,
|
|
229
|
+
wsServer,
|
|
230
|
+
workerProvisioningManager,
|
|
231
|
+
previewManager,
|
|
232
|
+
getKickoffHandler: () => serviceKickoffHandler,
|
|
233
|
+
getTeamAutoScheduler: () => teamAutoSchedulerRef,
|
|
234
|
+
};
|
|
235
|
+
const server = createControllerHttpServer(httpDeps);
|
|
236
|
+
const PORT_RETRY_STEP = 10;
|
|
237
|
+
const PORT_MAX_RETRIES = 10;
|
|
238
|
+
let actualPort = 0;
|
|
239
|
+
await new Promise((resolve, reject) => {
|
|
240
|
+
let attempt = 0;
|
|
241
|
+
const tryListen = (port) => {
|
|
242
|
+
server.once("error", (err) => {
|
|
243
|
+
if (err.code === "EADDRINUSE" && attempt < PORT_MAX_RETRIES) {
|
|
244
|
+
attempt++;
|
|
245
|
+
const nextPort = config.port + attempt * PORT_RETRY_STEP;
|
|
246
|
+
logger.warn(`Controller: port ${port} in use, retrying on ${nextPort}`);
|
|
247
|
+
tryListen(nextPort);
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
reject(err);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
server.listen(port, listenHost, () => {
|
|
254
|
+
const addr = server.address();
|
|
255
|
+
actualPort = typeof addr === "object" && addr ? addr.port : 0;
|
|
256
|
+
if (actualPort !== config.port) {
|
|
257
|
+
logger.info(`Controller: configured port ${config.port} unavailable, bound to ${actualPort} instead`);
|
|
258
|
+
}
|
|
259
|
+
logger.info(`Controller: HTTP server listening on port ${actualPort}`);
|
|
260
|
+
const uiUrl = `http://127.0.0.1:${actualPort}/ui`;
|
|
261
|
+
logger.info(`Controller: Web UI available at ${uiUrl}`);
|
|
262
|
+
const lanUiUrl = getPreferredLanUiUrl(actualPort);
|
|
263
|
+
if (lanUiUrl) {
|
|
264
|
+
logger.info(`Controller: Web UI available on LAN at ${lanUiUrl}`);
|
|
265
|
+
}
|
|
266
|
+
deps.onActualPort?.(actualPort);
|
|
267
|
+
openBrowser(uiUrl, logger);
|
|
268
|
+
resolve();
|
|
269
|
+
});
|
|
270
|
+
};
|
|
271
|
+
tryListen(listenPort);
|
|
272
|
+
});
|
|
273
|
+
// Propagate the actual port to worker provisioning (created earlier, before port was known)
|
|
274
|
+
if (workerProvisioningManager.isEnabled()) {
|
|
275
|
+
workerProvisioningManager.setActualPort(actualPort);
|
|
276
|
+
}
|
|
277
|
+
// Phase 2.1 (design 2.3 crash semantics): resume an interrupted team
|
|
278
|
+
// profile switch before TeamAuto/preview restoration/provisioning kick
|
|
279
|
+
// in, so no subsystem fights the resume. Runs after the port is known
|
|
280
|
+
// (switch warmup launches need the actual controller URL). Requests
|
|
281
|
+
// arriving mid-resume hit the transition concurrency matrix (409/503),
|
|
282
|
+
// which is exactly what it exists for. An unavailable target profile is
|
|
283
|
+
// fatal here - same red line as restoring an unknown profileId.
|
|
284
|
+
await resumeTeamProfileSwitch(httpDeps);
|
|
285
|
+
// TeamAuto: autonomous repo collaboration (bind repos via /api/v1/teamauto/*).
|
|
286
|
+
// Phase 2.3 preview (minimal capability wiring): a profile with
|
|
287
|
+
// teamauto disabled never starts the scheduler at all.
|
|
288
|
+
if (getActiveProfile().capabilities.teamauto) {
|
|
289
|
+
try {
|
|
290
|
+
const auth = getGithubAuthManager(config, logger);
|
|
291
|
+
teamAutoSchedulerRef = createTeamAutoScheduler({
|
|
292
|
+
logger,
|
|
293
|
+
auth,
|
|
294
|
+
getTeamState: () => teamState,
|
|
295
|
+
updateTeamState: updateState,
|
|
296
|
+
onTasksCreated: async () => {
|
|
297
|
+
// Same deps object as every HTTP call site (issue #191 gate
|
|
298
|
+
// review): the autoAssign re-entrancy gate is keyed per deps
|
|
299
|
+
// object, so an ad-hoc object here would open a SECOND gate -
|
|
300
|
+
// a TeamAuto round and an HTTP round could then run concurrently
|
|
301
|
+
// with separate attemptedPairs sets (double dispatch attempts,
|
|
302
|
+
// same-task double LLM-judge window). The ad-hoc object also
|
|
303
|
+
// silently dropped workerProvisioningManager/getTeamAutoScheduler
|
|
304
|
+
// for these rounds (no reconcile nudge; teamauto write tasks
|
|
305
|
+
// dispatched from this path fell back to the shared checkout
|
|
306
|
+
// instead of a task-scoped worktree). It was a leftover from
|
|
307
|
+
// before the shared httpDeps existed, not a deliberate split.
|
|
308
|
+
await autoAssignPendingTasks(httpDeps);
|
|
309
|
+
},
|
|
310
|
+
onActivity: (entry) => {
|
|
311
|
+
wsServer.broadcastUpdate({
|
|
312
|
+
type: "teamauto:activity",
|
|
313
|
+
data: { at: entry.at, repoId: entry.repoId, kind: entry.kind, text: entry.text },
|
|
314
|
+
});
|
|
315
|
+
},
|
|
316
|
+
});
|
|
317
|
+
await teamAutoSchedulerRef.start();
|
|
318
|
+
deps.onTeamAutoSchedulerAvailable?.(() => teamAutoSchedulerRef);
|
|
319
|
+
}
|
|
320
|
+
catch (err) {
|
|
321
|
+
logger.warn(`Controller: TeamAuto scheduler failed to start: ${err instanceof Error ? err.message : String(err)}`);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
logger.info("Controller: TeamAuto scheduler skipped (capability disabled by the active team profile)");
|
|
326
|
+
}
|
|
327
|
+
// Start mDNS advertising with the actual port
|
|
328
|
+
await mdnsAdvertiser.start(actualPort, config.teamName);
|
|
329
|
+
if (workerProvisioningManager.isEnabled()) {
|
|
330
|
+
void workerProvisioningManager.runStartupReadinessCheck();
|
|
331
|
+
}
|
|
332
|
+
// ── Kickoff handler ───────────────────────────────────────────────
|
|
333
|
+
const kickoffHandler = async (candidateRoles, complexity, requirement) => {
|
|
334
|
+
const result = await runKickoffMeeting({ requirement, candidateRoles, complexity }, {
|
|
335
|
+
logger,
|
|
336
|
+
getTeamState: () => teamState,
|
|
337
|
+
ensureRoleProvisioned: async (role) => {
|
|
338
|
+
if (workerProvisioningManager?.isEnabled()) {
|
|
339
|
+
await workerProvisioningManager.requestReconcile(`kickoff-provision-${role}`);
|
|
340
|
+
}
|
|
341
|
+
},
|
|
342
|
+
requestWorkerAssessment: async (worker, req) => {
|
|
343
|
+
return await requestKickoffAssessment(worker, req);
|
|
344
|
+
},
|
|
345
|
+
});
|
|
346
|
+
return { assessments: result.plan.assessments, summary: result.summary };
|
|
347
|
+
};
|
|
348
|
+
serviceKickoffHandler = kickoffHandler;
|
|
349
|
+
deps.onKickoffHandlerAvailable?.(kickoffHandler);
|
|
350
|
+
// Phase 2.3 preview (minimal capability wiring): only profiles with
|
|
351
|
+
// runnablePreview enabled restore dynamic previews on startup.
|
|
352
|
+
if (getActiveProfile().capabilities.runnablePreview) {
|
|
353
|
+
logger.info(`Controller: starting preview restoration...`);
|
|
354
|
+
void previewManager.restorePreviewsOnStartup().then(() => {
|
|
355
|
+
logger.info(`Controller: preview restoration completed`);
|
|
356
|
+
}).catch((err) => {
|
|
357
|
+
logger.warn(`Controller: failed to restore previews on startup: ${String(err)}`);
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
// Start timeout monitoring
|
|
361
|
+
timeoutTimer = setInterval(() => {
|
|
362
|
+
if (!teamState)
|
|
363
|
+
return;
|
|
364
|
+
let changed = false;
|
|
365
|
+
const now = Date.now();
|
|
366
|
+
for (const [workerId, worker] of Object.entries(teamState.workers)) {
|
|
367
|
+
if (worker.status === "offline") {
|
|
368
|
+
// Stale offline entries are dead session workers (provisioned
|
|
369
|
+
// per-task workers exit when their task ends; their registry
|
|
370
|
+
// entries used to linger forever and pile up - observed live:
|
|
371
|
+
// the intake agent read a wall of offline developers and
|
|
372
|
+
// misreported the repos they had served as "repo offline").
|
|
373
|
+
// Same reap semantics as the startup sweep, applied at runtime.
|
|
374
|
+
if (now - worker.lastHeartbeat > WORKER_TIMEOUT_MS) {
|
|
375
|
+
delete teamState.workers[workerId];
|
|
376
|
+
changed = true;
|
|
377
|
+
logger.info(`Controller: reaped stale offline worker ${workerId}`);
|
|
378
|
+
}
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
if (now - worker.lastHeartbeat > WORKER_TIMEOUT_MS) {
|
|
382
|
+
logger.info(`Controller: worker ${workerId} timed out`);
|
|
383
|
+
const activeTaskId = worker.currentTaskId;
|
|
384
|
+
worker.status = "offline";
|
|
385
|
+
worker.currentTaskId = undefined;
|
|
386
|
+
changed = true;
|
|
387
|
+
wsServer.broadcastUpdate({ type: "worker:offline", data: { workerId } });
|
|
388
|
+
if (activeTaskId) {
|
|
389
|
+
const task = teamState.tasks[activeTaskId];
|
|
390
|
+
if (task &&
|
|
391
|
+
task.assignedWorkerId === workerId &&
|
|
392
|
+
task.status !== "completed" &&
|
|
393
|
+
task.status !== "failed" &&
|
|
394
|
+
task.status !== "blocked") {
|
|
395
|
+
task.status = "pending";
|
|
396
|
+
task.assignedWorkerId = undefined;
|
|
397
|
+
task.updatedAt = now;
|
|
398
|
+
wsServer.broadcastUpdate({ type: "task:updated", data: { ...task } });
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
if (workerProvisioningManager?.hasManagedWorker(workerId)) {
|
|
402
|
+
void workerProvisioningManager.onWorkerRemoved(workerId, "heartbeat timeout");
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
if (changed) {
|
|
407
|
+
saveTeamState(teamState);
|
|
408
|
+
}
|
|
409
|
+
// Runtime orphan-task reconciliation (user-found: one live worker but
|
|
410
|
+
// two active tasks - the second task was pinned to a worker whose
|
|
411
|
+
// registry entry was already gone). The startup sweep handles this
|
|
412
|
+
// once at boot; tasks whose worker disappears AFTER claiming sat in
|
|
413
|
+
// in_progress forever. Mirror the startup semantics: reset to pending
|
|
414
|
+
// (bounded resume attempts), re-dispatch happens via the reconcile
|
|
415
|
+
// call below. Skip workers the sweep above just released - their
|
|
416
|
+
// tasks were already handled with a broadcast.
|
|
417
|
+
{
|
|
418
|
+
let orphaned = false;
|
|
419
|
+
for (const task of Object.values(teamState.tasks)) {
|
|
420
|
+
if (task.assignedWorkerId &&
|
|
421
|
+
(task.status === "assigned" || task.status === "in_progress") &&
|
|
422
|
+
!teamState.workers[task.assignedWorkerId]) {
|
|
423
|
+
const attempt = (task.resumeAttempt ?? 0) + 1;
|
|
424
|
+
const MAX_RESUME_ATTEMPTS = 3;
|
|
425
|
+
if (attempt > MAX_RESUME_ATTEMPTS) {
|
|
426
|
+
logger.warn(`Controller: task ${task.id} exceeded ${MAX_RESUME_ATTEMPTS} resume attempts (worker gone) - failing`);
|
|
427
|
+
task.status = "failed";
|
|
428
|
+
task.error = `worker disappeared without completing (resumed ${MAX_RESUME_ATTEMPTS} times)`;
|
|
429
|
+
}
|
|
430
|
+
else {
|
|
431
|
+
logger.info(`Controller: resetting orphaned task ${task.id} for resume attempt ${attempt} (worker ${task.assignedWorkerId} missing)`);
|
|
432
|
+
task.status = "pending";
|
|
433
|
+
task.resumeAttempt = attempt;
|
|
434
|
+
if (task.checkpoint) {
|
|
435
|
+
task.checkpoint.attempt = attempt;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
task.assignedWorkerId = undefined;
|
|
439
|
+
task.updatedAt = now;
|
|
440
|
+
wsServer.broadcastUpdate({ type: "task:updated", data: { ...task } });
|
|
441
|
+
orphaned = true;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (orphaned) {
|
|
445
|
+
saveTeamState(teamState);
|
|
446
|
+
changed = true;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
if (workerProvisioningManager?.isEnabled()) {
|
|
450
|
+
void workerProvisioningManager.requestReconcile("periodic controller sync");
|
|
451
|
+
}
|
|
452
|
+
}, 15000);
|
|
453
|
+
if (timeoutTimer) {
|
|
454
|
+
const timer = timeoutTimer;
|
|
455
|
+
timer.unref?.();
|
|
456
|
+
}
|
|
457
|
+
},
|
|
458
|
+
async stop() {
|
|
459
|
+
deps.onTeamStateAvailable?.(() => null);
|
|
460
|
+
if (timeoutTimer) {
|
|
461
|
+
clearInterval(timeoutTimer);
|
|
462
|
+
timeoutTimer = null;
|
|
463
|
+
}
|
|
464
|
+
try {
|
|
465
|
+
await teamAutoSchedulerRef?.stop();
|
|
466
|
+
}
|
|
467
|
+
catch { /* scheduler already stopped */ }
|
|
468
|
+
teamAutoSchedulerRef = null;
|
|
469
|
+
if (workerProvisioningManager) {
|
|
470
|
+
await workerProvisioningManager.stop();
|
|
471
|
+
}
|
|
472
|
+
await previewManager.stopAll();
|
|
473
|
+
wsServer.close();
|
|
474
|
+
mdnsAdvertiser.stop();
|
|
475
|
+
logger.info("Controller: stopped");
|
|
476
|
+
},
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
function openBrowser(url, logger) {
|
|
480
|
+
const cmd = process.platform === "darwin"
|
|
481
|
+
? `open "${url}"`
|
|
482
|
+
: process.platform === "win32"
|
|
483
|
+
? `start "" "${url}"`
|
|
484
|
+
: `xdg-open "${url}"`;
|
|
485
|
+
exec(cmd, (err) => {
|
|
486
|
+
if (err) {
|
|
487
|
+
logger.warn(`Controller: failed to open browser: ${err.message}`);
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* Request a kickoff assessment from a worker.
|
|
493
|
+
*
|
|
494
|
+
* Request kickoff assessment from a worker over HTTP.
|
|
495
|
+
*/
|
|
496
|
+
async function requestKickoffAssessment(worker, requirement) {
|
|
497
|
+
const role = worker.role;
|
|
498
|
+
const prompt = buildKickoffAssessmentPrompt(role, requirement);
|
|
499
|
+
// External worker — POST to kickoff assess endpoint
|
|
500
|
+
if (!worker.url) {
|
|
501
|
+
throw new Error(`Worker ${worker.id} has no URL for kickoff assessment`);
|
|
502
|
+
}
|
|
503
|
+
const controller = new AbortController();
|
|
504
|
+
const timeout = setTimeout(() => controller.abort(), ASSESSMENT_TIMEOUT_MS);
|
|
505
|
+
try {
|
|
506
|
+
const res = await fetch(`${worker.url}/api/v1/kickoff/assess`, {
|
|
507
|
+
method: "POST",
|
|
508
|
+
headers: { "Content-Type": "application/json" },
|
|
509
|
+
body: JSON.stringify({ requirement, role }),
|
|
510
|
+
signal: controller.signal,
|
|
511
|
+
});
|
|
512
|
+
if (!res.ok) {
|
|
513
|
+
throw new Error(`Worker ${worker.id} returned ${res.status} for kickoff assessment`);
|
|
514
|
+
}
|
|
515
|
+
const data = await res.json();
|
|
516
|
+
return data.assessment;
|
|
517
|
+
}
|
|
518
|
+
finally {
|
|
519
|
+
clearTimeout(timeout);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
// ── Phase 2.5 wiring: controller LLM as the role judge ───────────────────────
|
|
523
|
+
//
|
|
524
|
+
// resolveTaskRoleWithLlmFallback (kickoff-orchestrator) defined the seam in
|
|
525
|
+
// P2.5 with fake-driven tests but no production caller. This factory builds
|
|
526
|
+
// the production llmRoleJudge: a ONE-SHOT subagent session on the controller
|
|
527
|
+
// runtime (never the long-lived intake conversation, so verdicts cannot
|
|
528
|
+
// pollute intake semantics) that answers with a single role id of the ACTIVE
|
|
529
|
+
// profile. The resolver validates the answer (validateActiveRoleId) and
|
|
530
|
+
// degrades to the profile defaultRole when the judge is unavailable, times
|
|
531
|
+
// out, errors, or names a role outside the active profile - the TaskRouter
|
|
532
|
+
// then treats the outcome as a routing hint, so dispatch never blocks on a
|
|
533
|
+
// strand.
|
|
534
|
+
/** Budget for a one-id LLM verdict; past it the resolver degrades to defaultRole. */
|
|
535
|
+
const ROLE_JUDGE_TIMEOUT_MS = 30_000;
|
|
536
|
+
const ROLE_JUDGE_SESSION_PREFIX = "teamclaw-role-judge:";
|
|
537
|
+
const ROLE_JUDGE_SYSTEM_PROMPT = [
|
|
538
|
+
"You are the role router of a TeamClaw controller.",
|
|
539
|
+
"Given one task, pick the single team role that should own it.",
|
|
540
|
+
"Reply with EXACTLY one role id from the provided list - no prose, no markdown, no explanation.",
|
|
541
|
+
].join(" ");
|
|
542
|
+
function createControllerLlmRoleJudge(deps) {
|
|
543
|
+
const subagent = deps.runtime?.subagent;
|
|
544
|
+
if (!subagent
|
|
545
|
+
|| typeof subagent.run !== "function"
|
|
546
|
+
|| typeof subagent.waitForRun !== "function"
|
|
547
|
+
|| typeof subagent.getSessionMessages !== "function") {
|
|
548
|
+
// Runtime without an LLM subagent (e.g. minimal test doubles): leave the
|
|
549
|
+
// seam unwired; the TaskRouter keeps its pre-wiring behavior.
|
|
550
|
+
return undefined;
|
|
551
|
+
}
|
|
552
|
+
const logger = deps.logger;
|
|
553
|
+
return async ({ task, verdict }) => {
|
|
554
|
+
const roleIds = getActiveRoleIds();
|
|
555
|
+
const message = [
|
|
556
|
+
`Task title: ${task.title}`,
|
|
557
|
+
`Task description: ${task.description?.trim() || "(none)"}`,
|
|
558
|
+
"",
|
|
559
|
+
`Token-based role scoring refused to decide (${verdict.reason}).`,
|
|
560
|
+
`Pick the single role that should own this task. Answer with EXACTLY one role id from: ${roleIds.join(", ")}`,
|
|
561
|
+
].join("\n");
|
|
562
|
+
// Fresh one-shot session per verdict: the judge must stay stateless and
|
|
563
|
+
// separate from any intake/worker conversation.
|
|
564
|
+
const sessionKey = buildTeamClawAgentSessionKey(`${ROLE_JUDGE_SESSION_PREFIX}${task.id}-${Date.now()}`);
|
|
565
|
+
const run = await subagent.run({
|
|
566
|
+
sessionKey,
|
|
567
|
+
message,
|
|
568
|
+
extraSystemPrompt: ROLE_JUDGE_SYSTEM_PROMPT,
|
|
569
|
+
idempotencyKey: `role-judge-${task.id}-${Date.now()}`,
|
|
570
|
+
});
|
|
571
|
+
const waited = await subagent.waitForRun({
|
|
572
|
+
runId: run.runId,
|
|
573
|
+
timeoutMs: ROLE_JUDGE_TIMEOUT_MS,
|
|
574
|
+
});
|
|
575
|
+
if (waited.status !== "ok") {
|
|
576
|
+
logger.warn(`Controller: LLM role judge did not complete for task ${task.id} (${waited.status}${"error" in waited && waited.error ? `: ${waited.error}` : ""}); using the profile defaultRole`);
|
|
577
|
+
return null;
|
|
578
|
+
}
|
|
579
|
+
const session = await subagent.getSessionMessages({ sessionKey, limit: 5 });
|
|
580
|
+
const reply = extractLastAssistantText(session.messages);
|
|
581
|
+
const direct = validateActiveRoleId(reply.trim());
|
|
582
|
+
if (direct) {
|
|
583
|
+
return direct;
|
|
584
|
+
}
|
|
585
|
+
// Tolerate light prose wrapping ("The role is: qa."): first ACTIVE role
|
|
586
|
+
// id that appears as a whole word in the reply.
|
|
587
|
+
for (const roleId of roleIds) {
|
|
588
|
+
const pattern = new RegExp(`(^|[^a-z0-9-])${roleId.replace(/[-]/g, "\\-")}([^a-z0-9-]|$)`);
|
|
589
|
+
if (pattern.test(reply)) {
|
|
590
|
+
return roleId;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
logger.warn(`Controller: LLM role judge reply for task ${task.id} named no active role (${reply.slice(0, 120) || "empty reply"}); using the profile defaultRole`);
|
|
594
|
+
return null;
|
|
595
|
+
};
|
|
596
|
+
}
|
|
597
|
+
/** Last assistant message text (string or text blocks), mirroring the http-server intake helper semantics. */
|
|
598
|
+
function extractLastAssistantText(messages) {
|
|
599
|
+
const assistantMessages = messages.filter((message) => {
|
|
600
|
+
if (!message || typeof message !== "object") {
|
|
601
|
+
return false;
|
|
602
|
+
}
|
|
603
|
+
return message.role === "assistant";
|
|
604
|
+
});
|
|
605
|
+
const lastAssistant = assistantMessages[assistantMessages.length - 1];
|
|
606
|
+
if (!lastAssistant) {
|
|
607
|
+
return "";
|
|
608
|
+
}
|
|
609
|
+
if (typeof lastAssistant.content === "string") {
|
|
610
|
+
return lastAssistant.content;
|
|
611
|
+
}
|
|
612
|
+
if (Array.isArray(lastAssistant.content)) {
|
|
613
|
+
const textBlocks = lastAssistant.content
|
|
614
|
+
.filter((block) => {
|
|
615
|
+
return !!block && typeof block === "object" && block.type === "text";
|
|
616
|
+
})
|
|
617
|
+
.map((block) => (typeof block.text === "string" ? block.text : ""))
|
|
618
|
+
.filter(Boolean);
|
|
619
|
+
if (textBlocks.length > 0) {
|
|
620
|
+
return textBlocks.join("\n");
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
return "";
|
|
624
|
+
}
|