@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,1674 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import https from "node:https";
|
|
4
|
+
import net from "node:net";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import readline from "node:readline";
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { spawn } from "node:child_process";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import JSON5 from "json5";
|
|
11
|
+
import { generateId } from "../protocol.js";
|
|
12
|
+
import { resolveDefaultOpenClawConfigPath, resolveDefaultOpenClawStateDir, resolveDefaultTeamClawRuntimeRootDir, resolveDefaultAgentDir, resolveTeamClawAgentDir, resolveTeamClawAgentWorkspaceRootDir, resolveTeamClawWorkspaceDir, TEAMCLAW_AGENT_ID, } from "../openclaw-workspace.js";
|
|
13
|
+
// Phase 1.3: the role universe and the fallback role come from the active
|
|
14
|
+
// TeamProfile loader (software-rd baseline).
|
|
15
|
+
import { getActiveRoleIds, getActiveDefaultRole } from "../profile-loader.js";
|
|
16
|
+
import { inferTaskRole } from "./role-inference.js";
|
|
17
|
+
const DEFAULT_CONTAINER_WORKER_PORT = 9527;
|
|
18
|
+
const DEFAULT_CONTAINER_GATEWAY_PORT = 18789;
|
|
19
|
+
const DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR = "/app/extensions/teamclaw";
|
|
20
|
+
const PROVISIONING_RECORD_RETENTION_MS = 6 * 60 * 60 * 1000;
|
|
21
|
+
const PROVISIONING_FAILURE_COOLDOWN_MS = 30_000;
|
|
22
|
+
const PROCESS_TERMINATION_TIMEOUT_MS = 10_000;
|
|
23
|
+
const STARTUP_READINESS_POLL_INTERVAL_MS = 1_000;
|
|
24
|
+
const STARTUP_READINESS_RETRY_INTERVAL_MS = 5_000;
|
|
25
|
+
const DOCKER_API_VERSION = resolveDockerApiVersion();
|
|
26
|
+
export class WorkerProvisioningManager {
|
|
27
|
+
deps;
|
|
28
|
+
backend;
|
|
29
|
+
baseConfigPromise = null;
|
|
30
|
+
reconcilePromise = null;
|
|
31
|
+
reconcileQueued = false;
|
|
32
|
+
stopped = false;
|
|
33
|
+
// Phase 2.1 (design 2.3, switch step 2): while a team profile switch drains
|
|
34
|
+
// and archives the old team, the periodic reconcile must not fight the
|
|
35
|
+
// drain by launching replacement workers for the outgoing profile's
|
|
36
|
+
// pending tasks. Suspended reconcile calls return immediately; it is
|
|
37
|
+
// lifted before the new profile's warmup so normal operation resumes.
|
|
38
|
+
reconcileSuspended = false;
|
|
39
|
+
constructor(deps) {
|
|
40
|
+
this.deps = deps;
|
|
41
|
+
this.backend = createProvisionerBackend(deps.config, deps.logger);
|
|
42
|
+
}
|
|
43
|
+
/** Update the actual controller port after the HTTP server binds. */
|
|
44
|
+
setActualPort(port) {
|
|
45
|
+
this.deps = { ...this.deps, actualControllerPort: port };
|
|
46
|
+
}
|
|
47
|
+
isEnabled() {
|
|
48
|
+
return this.backend !== null;
|
|
49
|
+
}
|
|
50
|
+
hasManagedWorker(workerId) {
|
|
51
|
+
return Boolean(this.deps.getTeamState()?.provisioning?.workers?.[workerId]);
|
|
52
|
+
}
|
|
53
|
+
/** Returns true when the worker was provisioned as a local process (shared filesystem). */
|
|
54
|
+
isSharedWorkspaceWorker(workerId) {
|
|
55
|
+
const record = this.deps.getTeamState()?.provisioning?.workers?.[workerId];
|
|
56
|
+
return Boolean(record && record.provider === "process");
|
|
57
|
+
}
|
|
58
|
+
syncState(state) {
|
|
59
|
+
if (!this.backend) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
return this.refreshProvisioningState(state, Date.now());
|
|
63
|
+
}
|
|
64
|
+
primeStartupReadiness() {
|
|
65
|
+
if (!this.backend || this.stopped) {
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const now = Date.now();
|
|
69
|
+
const previousAttempts = this.deps.getTeamState()?.provisioning?.startupReadiness?.attempts ?? 0;
|
|
70
|
+
this.updateStartupReadiness({
|
|
71
|
+
status: "checking",
|
|
72
|
+
startedAt: now,
|
|
73
|
+
checkedAt: now,
|
|
74
|
+
attempts: previousAttempts,
|
|
75
|
+
requiredRoles: this.determineStartupReadinessRoles(),
|
|
76
|
+
readyWorkerIds: [],
|
|
77
|
+
message: "Controller started; waiting for startup provisioning warm-up.",
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
validateRegistration(workerId, role, launchToken) {
|
|
81
|
+
const record = this.deps.getTeamState()?.provisioning?.workers?.[workerId];
|
|
82
|
+
if (!record) {
|
|
83
|
+
return { ok: true, managed: false };
|
|
84
|
+
}
|
|
85
|
+
if (record.role !== role) {
|
|
86
|
+
return {
|
|
87
|
+
ok: false,
|
|
88
|
+
managed: true,
|
|
89
|
+
reason: `Provisioned worker ${workerId} expected role ${record.role}, got ${role}`,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
if (!launchToken || launchToken !== record.launchToken) {
|
|
93
|
+
return {
|
|
94
|
+
ok: false,
|
|
95
|
+
managed: true,
|
|
96
|
+
reason: `Provisioned worker ${workerId} is missing a valid launch token`,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
if (record.status === "failed" || record.status === "terminated" || record.status === "terminating") {
|
|
100
|
+
return {
|
|
101
|
+
ok: false,
|
|
102
|
+
managed: true,
|
|
103
|
+
reason: `Provisioned worker ${workerId} is no longer allowed to register (${record.status})`,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
return { ok: true, managed: true };
|
|
107
|
+
}
|
|
108
|
+
onWorkerRegistered(workerId) {
|
|
109
|
+
if (!this.backend) {
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
this.deps.updateTeamState((state) => {
|
|
113
|
+
const record = ensureProvisioningState(state).workers[workerId];
|
|
114
|
+
if (!record) {
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
const now = Date.now();
|
|
118
|
+
record.status = "registered";
|
|
119
|
+
record.registeredAt = record.registeredAt ?? now;
|
|
120
|
+
record.updatedAt = now;
|
|
121
|
+
record.idleSince = now;
|
|
122
|
+
delete record.lastError;
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
onWorkerHeartbeat(workerId, status) {
|
|
126
|
+
if (!this.backend) {
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
this.deps.updateTeamState((state) => {
|
|
130
|
+
const record = ensureProvisioningState(state).workers[workerId];
|
|
131
|
+
if (!record) {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
const now = Date.now();
|
|
135
|
+
if (record.status === "launching") {
|
|
136
|
+
record.status = "registered";
|
|
137
|
+
record.registeredAt = record.registeredAt ?? now;
|
|
138
|
+
}
|
|
139
|
+
record.updatedAt = now;
|
|
140
|
+
if (status === "idle") {
|
|
141
|
+
record.idleSince = record.idleSince ?? now;
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
delete record.idleSince;
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
async onWorkerRemoved(workerId, reason) {
|
|
149
|
+
if (!this.backend) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const record = this.deps.getTeamState()?.provisioning?.workers?.[workerId];
|
|
153
|
+
if (!record || record.status === "terminated" || record.status === "failed") {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
this.deps.logger.info(`Provisioner: terminating managed worker ${workerId} (${reason})`);
|
|
157
|
+
await this.terminateManagedWorker(workerId, reason, "terminated");
|
|
158
|
+
}
|
|
159
|
+
/** Phase 2.1: suspend/resume the reconcile loop during a team profile switch. */
|
|
160
|
+
setReconcileSuspended(suspended) {
|
|
161
|
+
this.reconcileSuspended = suspended;
|
|
162
|
+
}
|
|
163
|
+
async requestReconcile(reason) {
|
|
164
|
+
if (!this.backend || this.stopped || this.reconcileSuspended) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (this.reconcilePromise) {
|
|
168
|
+
this.reconcileQueued = true;
|
|
169
|
+
return this.reconcilePromise;
|
|
170
|
+
}
|
|
171
|
+
this.reconcilePromise = this.runReconcileLoop(reason)
|
|
172
|
+
.catch((err) => {
|
|
173
|
+
this.deps.logger.warn(`Provisioner: reconcile failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
174
|
+
})
|
|
175
|
+
.finally(() => {
|
|
176
|
+
this.reconcilePromise = null;
|
|
177
|
+
});
|
|
178
|
+
return this.reconcilePromise;
|
|
179
|
+
}
|
|
180
|
+
async runStartupReadinessCheck() {
|
|
181
|
+
if (!this.backend || this.stopped) {
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
const requiredRoles = this.determineStartupReadinessRoles();
|
|
185
|
+
const previousAttempts = this.deps.getTeamState()?.provisioning?.startupReadiness?.attempts ?? 0;
|
|
186
|
+
const startedAt = Date.now();
|
|
187
|
+
this.updateStartupReadiness({
|
|
188
|
+
status: "checking",
|
|
189
|
+
startedAt,
|
|
190
|
+
checkedAt: startedAt,
|
|
191
|
+
attempts: previousAttempts + 1,
|
|
192
|
+
requiredRoles,
|
|
193
|
+
readyWorkerIds: [],
|
|
194
|
+
message: `Warming startup workers for ${requiredRoles.join(", ")}.`,
|
|
195
|
+
});
|
|
196
|
+
try {
|
|
197
|
+
await this.ensureStartupProvisioningPrerequisites();
|
|
198
|
+
await this.ensureWarmWorkersForRoles(requiredRoles, "startup readiness warmup");
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
202
|
+
this.updateStartupReadiness({
|
|
203
|
+
status: "degraded",
|
|
204
|
+
startedAt,
|
|
205
|
+
checkedAt: Date.now(),
|
|
206
|
+
attempts: previousAttempts + 1,
|
|
207
|
+
requiredRoles,
|
|
208
|
+
readyWorkerIds: [],
|
|
209
|
+
message,
|
|
210
|
+
});
|
|
211
|
+
this.deps.logger.warn(`Provisioner: startup readiness prerequisites failed: ${message}`);
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
const deadline = Date.now() + this.deps.config.workerProvisioningStartupTimeoutMs;
|
|
215
|
+
let lastRetryAt = 0;
|
|
216
|
+
while (!this.stopped && Date.now() < deadline) {
|
|
217
|
+
const readiness = this.collectRoleReadiness(requiredRoles);
|
|
218
|
+
if (readiness.missingRoles.length === 0) {
|
|
219
|
+
this.updateStartupReadiness({
|
|
220
|
+
status: "ready",
|
|
221
|
+
startedAt,
|
|
222
|
+
checkedAt: Date.now(),
|
|
223
|
+
attempts: previousAttempts + 1,
|
|
224
|
+
requiredRoles,
|
|
225
|
+
readyWorkerIds: readiness.readyWorkerIds,
|
|
226
|
+
message: `Startup provisioning ready with ${readiness.readyWorkerIds.length} warm worker(s).`,
|
|
227
|
+
});
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (Date.now() - lastRetryAt >= STARTUP_READINESS_RETRY_INTERVAL_MS) {
|
|
231
|
+
lastRetryAt = Date.now();
|
|
232
|
+
await this.ensureWarmWorkersForRoles(readiness.missingRoles, "startup readiness retry");
|
|
233
|
+
await this.requestReconcile("startup readiness poll");
|
|
234
|
+
}
|
|
235
|
+
await sleep(STARTUP_READINESS_POLL_INTERVAL_MS);
|
|
236
|
+
}
|
|
237
|
+
const finalReadiness = this.collectRoleReadiness(requiredRoles);
|
|
238
|
+
const failureDetails = this.describeStartupReadinessFailure(finalReadiness.missingRoles);
|
|
239
|
+
this.updateStartupReadiness({
|
|
240
|
+
status: "degraded",
|
|
241
|
+
startedAt,
|
|
242
|
+
checkedAt: Date.now(),
|
|
243
|
+
attempts: previousAttempts + 1,
|
|
244
|
+
requiredRoles,
|
|
245
|
+
readyWorkerIds: finalReadiness.readyWorkerIds,
|
|
246
|
+
message: failureDetails,
|
|
247
|
+
});
|
|
248
|
+
this.deps.logger.warn(`Provisioner: startup readiness degraded: ${failureDetails}`);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Phase 2.1 (design 2.3, switch step 5): warm the new profile's warmupRoles
|
|
252
|
+
* through the standard launch path after a profile switch. Dispatches the
|
|
253
|
+
* launches (prerequisites + ensureWarmWorkersForRoles); the workers then
|
|
254
|
+
* register asynchronously exactly like a cold start, so readiness tracking
|
|
255
|
+
* (startupReadiness polling / reconcile) covers the rest.
|
|
256
|
+
*/
|
|
257
|
+
async warmRolesForTeamSwitch(roles, reason) {
|
|
258
|
+
if (!this.backend || this.stopped) {
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
await this.ensureStartupProvisioningPrerequisites();
|
|
262
|
+
await this.ensureWarmWorkersForRoles(roles, reason);
|
|
263
|
+
}
|
|
264
|
+
async stop() {
|
|
265
|
+
if (!this.backend) {
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
this.stopped = true;
|
|
269
|
+
const state = this.deps.getTeamState();
|
|
270
|
+
const managedWorkerIds = state?.provisioning
|
|
271
|
+
? Object.entries(state.provisioning.workers)
|
|
272
|
+
.filter(([, record]) => record.provider === this.backend?.type && record.status !== "terminated")
|
|
273
|
+
.map(([workerId]) => workerId)
|
|
274
|
+
: [];
|
|
275
|
+
for (const workerId of managedWorkerIds) {
|
|
276
|
+
try {
|
|
277
|
+
await this.terminateManagedWorker(workerId, "controller shutdown", "terminated");
|
|
278
|
+
}
|
|
279
|
+
catch (err) {
|
|
280
|
+
this.deps.logger.warn(`Provisioner: failed to stop worker ${workerId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
await this.backend.stop?.();
|
|
284
|
+
}
|
|
285
|
+
async runReconcileLoop(initialReason) {
|
|
286
|
+
let reason = initialReason;
|
|
287
|
+
do {
|
|
288
|
+
this.reconcileQueued = false;
|
|
289
|
+
await this.reconcileOnce(reason);
|
|
290
|
+
reason = "queued reconcile";
|
|
291
|
+
} while (this.reconcileQueued && !this.stopped);
|
|
292
|
+
}
|
|
293
|
+
async reconcileOnce(reason) {
|
|
294
|
+
if (!this.backend) {
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const now = Date.now();
|
|
298
|
+
this.deps.updateTeamState((state) => {
|
|
299
|
+
this.refreshProvisioningState(state, now);
|
|
300
|
+
});
|
|
301
|
+
await this.expireStalledLaunches(now);
|
|
302
|
+
const state = this.deps.getTeamState();
|
|
303
|
+
if (!state) {
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
const roles = this.getProvisionableRoles(state);
|
|
307
|
+
for (const role of roles) {
|
|
308
|
+
const demand = this.computeRoleDemand(state, role);
|
|
309
|
+
if (demand > 0) {
|
|
310
|
+
if (this.deps.config.workerProvisioningRoles.length > 0 &&
|
|
311
|
+
!this.deps.config.workerProvisioningRoles.includes(role)) {
|
|
312
|
+
this.deps.logger.info(`Provisioner: allowing role ${role} because pending task demand exists outside configured workerProvisioningRoles`);
|
|
313
|
+
}
|
|
314
|
+
this.deps.logger.info(`Provisioner: role ${role} needs ${demand} additional worker(s) (${reason})`);
|
|
315
|
+
}
|
|
316
|
+
for (let i = 0; i < demand; i += 1) {
|
|
317
|
+
if (this.hasRecentProvisioningFailure(role)) {
|
|
318
|
+
this.deps.logger.warn(`Provisioner: recent ${role} launch failure detected; cooling down`);
|
|
319
|
+
break;
|
|
320
|
+
}
|
|
321
|
+
await this.launchWorker(role);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
await this.scaleDownIdleWorkers(now);
|
|
325
|
+
}
|
|
326
|
+
determineStartupReadinessRoles() {
|
|
327
|
+
const configured = this.deps.config.workerProvisioningRoles;
|
|
328
|
+
if (configured.length > 0) {
|
|
329
|
+
return [...new Set(configured)];
|
|
330
|
+
}
|
|
331
|
+
return [getActiveDefaultRole()];
|
|
332
|
+
}
|
|
333
|
+
async ensureStartupProvisioningPrerequisites() {
|
|
334
|
+
await ensureWritableDirectory(resolveTeamClawAgentWorkspaceRootDir());
|
|
335
|
+
await ensureWritableDirectory(resolveTeamClawWorkspaceDir());
|
|
336
|
+
await ensureWritableDirectory(resolveDefaultTeamClawRuntimeRootDir());
|
|
337
|
+
if (this.deps.config.workerProvisioningType === "process") {
|
|
338
|
+
await ensureWritableDirectory(resolveTeamClawAgentDir());
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
async ensureWarmWorkersForRoles(roles, reason) {
|
|
342
|
+
const state = this.deps.getTeamState();
|
|
343
|
+
for (const role of roles) {
|
|
344
|
+
if (this.hasActiveOrLaunchingWorkerForRole(state, role)) {
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
347
|
+
if (this.hasRecentProvisioningFailure(role)) {
|
|
348
|
+
this.deps.logger.warn(`Provisioner: startup warmup skipped ${role} due to recent failure`);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
this.deps.logger.info(`Provisioner: warming ${role} worker (${reason})`);
|
|
352
|
+
await this.launchWorker(role);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
async expireStalledLaunches(now) {
|
|
356
|
+
const state = this.deps.getTeamState();
|
|
357
|
+
if (!state?.provisioning) {
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
const timedOut = Object.values(state.provisioning.workers)
|
|
361
|
+
.filter((record) => record.status === "launching")
|
|
362
|
+
.filter((record) => now - record.requestedAt > this.deps.config.workerProvisioningStartupTimeoutMs);
|
|
363
|
+
for (const record of timedOut) {
|
|
364
|
+
await this.terminateManagedWorker(record.workerId, `startup timeout exceeded (${this.deps.config.workerProvisioningStartupTimeoutMs}ms)`, "failed");
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
async scaleDownIdleWorkers(now) {
|
|
368
|
+
const state = this.deps.getTeamState();
|
|
369
|
+
if (!state?.provisioning) {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const roles = this.getProvisionableRoles(state);
|
|
373
|
+
for (const role of roles) {
|
|
374
|
+
const activeWorkers = Object.values(state.workers).filter((worker) => worker.role === role && worker.status !== "offline");
|
|
375
|
+
const pendingDemand = this.countPendingTasksForRole(state, role);
|
|
376
|
+
if (pendingDemand > 0) {
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
let remainingActive = activeWorkers.length;
|
|
380
|
+
const managedIdleWorkers = activeWorkers
|
|
381
|
+
.filter((worker) => worker.status === "idle")
|
|
382
|
+
.map((worker) => ({
|
|
383
|
+
worker,
|
|
384
|
+
record: state.provisioning?.workers[worker.id],
|
|
385
|
+
}))
|
|
386
|
+
.filter((entry) => Boolean(entry.record))
|
|
387
|
+
.filter(({ record }) => record.status === "registered")
|
|
388
|
+
.sort((a, b) => (a.record.idleSince ?? Number.MAX_SAFE_INTEGER) - (b.record.idleSince ?? Number.MAX_SAFE_INTEGER));
|
|
389
|
+
for (const entry of managedIdleWorkers) {
|
|
390
|
+
if (remainingActive <= this.deps.config.workerProvisioningMinPerRole) {
|
|
391
|
+
break;
|
|
392
|
+
}
|
|
393
|
+
if (!entry.record.idleSince || now - entry.record.idleSince < this.deps.config.workerProvisioningIdleTtlMs) {
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
await this.terminateManagedWorker(entry.worker.id, "idle TTL exceeded", "terminated");
|
|
397
|
+
remainingActive -= 1;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
hasRecentProvisioningFailure(role) {
|
|
402
|
+
const now = Date.now();
|
|
403
|
+
const records = this.deps.getTeamState()?.provisioning?.workers ?? {};
|
|
404
|
+
return Object.values(records).some((record) => record.role === role &&
|
|
405
|
+
record.status === "failed" &&
|
|
406
|
+
now - record.updatedAt < PROVISIONING_FAILURE_COOLDOWN_MS);
|
|
407
|
+
}
|
|
408
|
+
hasActiveOrLaunchingWorkerForRole(state, role) {
|
|
409
|
+
if (!state) {
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
const activeWorker = Object.values(state.workers).some((worker) => worker.role === role && worker.status !== "offline");
|
|
413
|
+
if (activeWorker) {
|
|
414
|
+
return true;
|
|
415
|
+
}
|
|
416
|
+
return Object.values(state.provisioning?.workers ?? {}).some((record) => record.role === role && (record.status === "launching" || record.status === "registered"));
|
|
417
|
+
}
|
|
418
|
+
collectRoleReadiness(roles) {
|
|
419
|
+
const state = this.deps.getTeamState();
|
|
420
|
+
const readyWorkerIds = [];
|
|
421
|
+
const missingRoles = [];
|
|
422
|
+
for (const role of roles) {
|
|
423
|
+
const worker = Object.values(state?.workers ?? {}).find((candidate) => candidate.role === role && (candidate.status === "idle" || candidate.status === "busy"));
|
|
424
|
+
if (worker) {
|
|
425
|
+
readyWorkerIds.push(worker.id);
|
|
426
|
+
}
|
|
427
|
+
else {
|
|
428
|
+
missingRoles.push(role);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return { readyWorkerIds, missingRoles };
|
|
432
|
+
}
|
|
433
|
+
describeStartupReadinessFailure(missingRoles) {
|
|
434
|
+
const records = Object.values(this.deps.getTeamState()?.provisioning?.workers ?? {});
|
|
435
|
+
const relevant = records.filter((record) => missingRoles.includes(record.role));
|
|
436
|
+
const detail = relevant
|
|
437
|
+
.map((record) => `${record.role}:${record.status}${record.lastError ? ` (${record.lastError})` : ""}`)
|
|
438
|
+
.join(", ");
|
|
439
|
+
const suffix = detail ? ` Latest records: ${detail}` : "";
|
|
440
|
+
return `Startup worker readiness failed for roles: ${missingRoles.join(", ")}.${suffix}`;
|
|
441
|
+
}
|
|
442
|
+
updateStartupReadiness(readiness) {
|
|
443
|
+
this.deps.updateTeamState((state) => {
|
|
444
|
+
ensureProvisioningState(state).startupReadiness = readiness;
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
async launchWorker(role) {
|
|
448
|
+
if (!this.backend) {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
const workerId = `provisioned-${role}-${generateId()}`;
|
|
452
|
+
const launchToken = `${generateId()}-${generateId()}`;
|
|
453
|
+
const controllerUrl = this.resolveControllerUrl();
|
|
454
|
+
const requiresDedicatedHostPorts = requiresDedicatedHostPortsForProvisioner(this.backend.type, this.deps.config);
|
|
455
|
+
const workerPort = requiresDedicatedHostPorts
|
|
456
|
+
? await reserveEphemeralPort()
|
|
457
|
+
: DEFAULT_CONTAINER_WORKER_PORT;
|
|
458
|
+
const gatewayPort = requiresDedicatedHostPorts
|
|
459
|
+
? await reserveEphemeralPort()
|
|
460
|
+
: DEFAULT_CONTAINER_GATEWAY_PORT;
|
|
461
|
+
// Docker bridge networks need a host port to publish so the controller
|
|
462
|
+
// (running on the host) can reach the worker container.
|
|
463
|
+
const needsPublishedPort = this.backend.type === "docker" &&
|
|
464
|
+
!isDockerHostNetwork(this.deps.config.workerProvisioningDockerNetwork);
|
|
465
|
+
const publishedHostPort = needsPublishedPort ? await reserveEphemeralPort() : undefined;
|
|
466
|
+
const now = Date.now();
|
|
467
|
+
this.deps.updateTeamState((state) => {
|
|
468
|
+
ensureProvisioningState(state).workers[workerId] = {
|
|
469
|
+
workerId,
|
|
470
|
+
role,
|
|
471
|
+
provider: this.backend.type,
|
|
472
|
+
status: "launching",
|
|
473
|
+
launchToken,
|
|
474
|
+
requestedAt: now,
|
|
475
|
+
updatedAt: now,
|
|
476
|
+
};
|
|
477
|
+
});
|
|
478
|
+
try {
|
|
479
|
+
const baseConfig = await this.loadBaseOpenClawConfig();
|
|
480
|
+
const workerConfig = buildProvisionedWorkerConfig(baseConfig, this.deps.config, {
|
|
481
|
+
role,
|
|
482
|
+
controllerUrl,
|
|
483
|
+
workerPort,
|
|
484
|
+
gatewayPort,
|
|
485
|
+
workspaceDir: buildProvisionedWorkspaceDir(this.backend.type, this.deps.config, role, workerId),
|
|
486
|
+
});
|
|
487
|
+
const launchResult = await this.backend.launch({
|
|
488
|
+
workerId,
|
|
489
|
+
role,
|
|
490
|
+
launchToken,
|
|
491
|
+
controllerUrl,
|
|
492
|
+
workerPort,
|
|
493
|
+
gatewayPort,
|
|
494
|
+
publishedHostPort,
|
|
495
|
+
workspaceDir: getConfiguredWorkerWorkspaceDir(workerConfig),
|
|
496
|
+
env: this.buildForwardedEnv(controllerUrl),
|
|
497
|
+
configJson: `${JSON.stringify(workerConfig, null, 2)}\n`,
|
|
498
|
+
});
|
|
499
|
+
this.deps.updateTeamState((state) => {
|
|
500
|
+
const record = ensureProvisioningState(state).workers[workerId];
|
|
501
|
+
if (!record) {
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
record.instanceId = launchResult.instanceId ?? record.instanceId;
|
|
505
|
+
record.instanceName = launchResult.instanceName ?? record.instanceName;
|
|
506
|
+
record.runtimeHomeDir = launchResult.runtimeHomeDir ?? record.runtimeHomeDir;
|
|
507
|
+
record.updatedAt = Date.now();
|
|
508
|
+
});
|
|
509
|
+
this.deps.logger.info(`Provisioner: launched ${role} worker ${workerId} via ${this.backend.type}`);
|
|
510
|
+
}
|
|
511
|
+
catch (err) {
|
|
512
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
513
|
+
this.deps.updateTeamState((state) => {
|
|
514
|
+
const record = ensureProvisioningState(state).workers[workerId];
|
|
515
|
+
if (!record) {
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
record.status = "failed";
|
|
519
|
+
record.updatedAt = Date.now();
|
|
520
|
+
record.lastError = message;
|
|
521
|
+
});
|
|
522
|
+
this.deps.logger.warn(`Provisioner: failed to launch ${role} worker ${workerId}: ${message}`);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
async terminateManagedWorker(workerId, reason, terminalStatus) {
|
|
526
|
+
if (!this.backend) {
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
const state = this.deps.getTeamState();
|
|
530
|
+
const record = state?.provisioning?.workers?.[workerId];
|
|
531
|
+
if (!record) {
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
this.deps.updateTeamState((draft) => {
|
|
535
|
+
const current = ensureProvisioningState(draft).workers[workerId];
|
|
536
|
+
if (!current) {
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
current.status = "terminating";
|
|
540
|
+
current.updatedAt = Date.now();
|
|
541
|
+
if (draft.workers[workerId]) {
|
|
542
|
+
draft.workers[workerId].status = "offline";
|
|
543
|
+
draft.workers[workerId].currentTaskId = undefined;
|
|
544
|
+
}
|
|
545
|
+
});
|
|
546
|
+
try {
|
|
547
|
+
await this.backend.terminate(record);
|
|
548
|
+
}
|
|
549
|
+
catch (err) {
|
|
550
|
+
this.deps.logger.warn(`Provisioner: backend terminate failed for ${workerId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
551
|
+
}
|
|
552
|
+
this.deps.updateTeamState((draft) => {
|
|
553
|
+
const current = ensureProvisioningState(draft).workers[workerId];
|
|
554
|
+
if (!current) {
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
current.status = terminalStatus;
|
|
558
|
+
current.updatedAt = Date.now();
|
|
559
|
+
delete current.idleSince;
|
|
560
|
+
if (terminalStatus === "failed") {
|
|
561
|
+
current.lastError = reason;
|
|
562
|
+
}
|
|
563
|
+
else {
|
|
564
|
+
delete current.lastError;
|
|
565
|
+
}
|
|
566
|
+
});
|
|
567
|
+
}
|
|
568
|
+
getProvisionableRoles(state) {
|
|
569
|
+
const roleIds = new Set(this.deps.config.workerProvisioningRoles.length > 0
|
|
570
|
+
? this.deps.config.workerProvisioningRoles
|
|
571
|
+
: getActiveRoleIds());
|
|
572
|
+
if (!state) {
|
|
573
|
+
return [...roleIds];
|
|
574
|
+
}
|
|
575
|
+
for (const task of Object.values(state.tasks)) {
|
|
576
|
+
if (task.status !== "pending" && task.status !== "assigned") {
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
const taskRole = this.inferTaskRole(task);
|
|
580
|
+
if (taskRole) {
|
|
581
|
+
roleIds.add(taskRole);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
for (const worker of Object.values(state.workers)) {
|
|
585
|
+
roleIds.add(worker.role);
|
|
586
|
+
}
|
|
587
|
+
for (const record of Object.values(state.provisioning?.workers ?? {})) {
|
|
588
|
+
roleIds.add(record.role);
|
|
589
|
+
}
|
|
590
|
+
return [...roleIds];
|
|
591
|
+
}
|
|
592
|
+
countPendingTasksForRole(state, role) {
|
|
593
|
+
return Object.values(state.tasks).filter((task) => this.doesTaskNeedRole(task, state, role)).length;
|
|
594
|
+
}
|
|
595
|
+
doesTaskNeedRole(task, state, role) {
|
|
596
|
+
if (task.status !== "pending" && task.status !== "assigned") {
|
|
597
|
+
return false;
|
|
598
|
+
}
|
|
599
|
+
if (task.assignedWorkerId) {
|
|
600
|
+
const assignedWorker = state.workers[task.assignedWorkerId];
|
|
601
|
+
if (assignedWorker && assignedWorker.status !== "offline") {
|
|
602
|
+
return false;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
if (task.assignedRole) {
|
|
606
|
+
return task.assignedRole === role;
|
|
607
|
+
}
|
|
608
|
+
return this.inferTaskRole(task) === role;
|
|
609
|
+
}
|
|
610
|
+
inferTaskRole(task) {
|
|
611
|
+
return inferTaskRole(task);
|
|
612
|
+
}
|
|
613
|
+
computeRoleDemand(state, role) {
|
|
614
|
+
const pendingDemand = this.countPendingTasksForRole(state, role);
|
|
615
|
+
const activeWorkers = Object.values(state.workers).filter((worker) => worker.role === role && worker.status !== "offline");
|
|
616
|
+
const idleWorkers = activeWorkers.filter((worker) => worker.status === "idle").length;
|
|
617
|
+
const launchingWorkers = Object.values(state.provisioning?.workers ?? {}).filter((record) => record.role === role && record.status === "launching").length;
|
|
618
|
+
const warmShortfall = Math.max(0, this.deps.config.workerProvisioningMinPerRole - (activeWorkers.length + launchingWorkers));
|
|
619
|
+
const queueDrivenNeed = Math.max(0, pendingDemand - idleWorkers - launchingWorkers);
|
|
620
|
+
const cap = Math.max(0, this.deps.config.workerProvisioningMaxPerRole - activeWorkers.length - launchingWorkers);
|
|
621
|
+
return Math.min(cap, Math.max(warmShortfall, queueDrivenNeed));
|
|
622
|
+
}
|
|
623
|
+
resolveControllerUrl() {
|
|
624
|
+
if (this.backend?.type === "process") {
|
|
625
|
+
// Process workers run on the same host — always use loopback regardless
|
|
626
|
+
// of workerProvisioningControllerUrl (which may target Docker DNS).
|
|
627
|
+
const port = this.deps.actualControllerPort ?? this.deps.config.port;
|
|
628
|
+
return `http://127.0.0.1:${port}`;
|
|
629
|
+
}
|
|
630
|
+
if (this.deps.config.workerProvisioningControllerUrl) {
|
|
631
|
+
return this.deps.config.workerProvisioningControllerUrl;
|
|
632
|
+
}
|
|
633
|
+
throw new Error(`workerProvisioningControllerUrl is required when workerProvisioningType=${this.backend?.type}`);
|
|
634
|
+
}
|
|
635
|
+
buildForwardedEnv(controllerUrl) {
|
|
636
|
+
const env = {
|
|
637
|
+
...this.deps.config.workerProvisioningExtraEnv,
|
|
638
|
+
};
|
|
639
|
+
for (const name of this.deps.config.workerProvisioningPassEnv) {
|
|
640
|
+
const value = process.env[name];
|
|
641
|
+
if (typeof value === "string" && value.length > 0) {
|
|
642
|
+
env[name] = value;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
return appendNoProxyEntries(env, controllerUrl);
|
|
646
|
+
}
|
|
647
|
+
async loadBaseOpenClawConfig() {
|
|
648
|
+
if (!this.baseConfigPromise) {
|
|
649
|
+
this.baseConfigPromise = loadOpenClawConfig(resolveDefaultOpenClawConfigPath());
|
|
650
|
+
}
|
|
651
|
+
return cloneJson(await this.baseConfigPromise);
|
|
652
|
+
}
|
|
653
|
+
refreshProvisioningState(state, now) {
|
|
654
|
+
let changed = !state.provisioning || typeof state.provisioning !== "object";
|
|
655
|
+
const provisioning = ensureProvisioningState(state);
|
|
656
|
+
for (const [workerId, record] of Object.entries(provisioning.workers)) {
|
|
657
|
+
const worker = state.workers[workerId];
|
|
658
|
+
if (worker && worker.status !== "offline") {
|
|
659
|
+
if (record.status === "launching") {
|
|
660
|
+
record.status = "registered";
|
|
661
|
+
record.registeredAt = record.registeredAt ?? worker.registeredAt ?? now;
|
|
662
|
+
changed = true;
|
|
663
|
+
}
|
|
664
|
+
if (record.status === "registered") {
|
|
665
|
+
if (worker.status === "idle") {
|
|
666
|
+
if (!record.idleSince) {
|
|
667
|
+
record.idleSince = now;
|
|
668
|
+
changed = true;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
else if (record.idleSince) {
|
|
672
|
+
delete record.idleSince;
|
|
673
|
+
changed = true;
|
|
674
|
+
}
|
|
675
|
+
if (record.updatedAt < worker.lastHeartbeat) {
|
|
676
|
+
record.updatedAt = worker.lastHeartbeat;
|
|
677
|
+
changed = true;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if ((record.status === "failed" || record.status === "terminated") &&
|
|
682
|
+
now - record.updatedAt > PROVISIONING_RECORD_RETENTION_MS) {
|
|
683
|
+
delete provisioning.workers[workerId];
|
|
684
|
+
changed = true;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
return changed;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
class ProcessProvisioner {
|
|
691
|
+
type = "process";
|
|
692
|
+
logger;
|
|
693
|
+
processByWorkerId = new Map();
|
|
694
|
+
baseDirPromise;
|
|
695
|
+
constructor(logger) {
|
|
696
|
+
this.logger = logger;
|
|
697
|
+
const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
|
|
698
|
+
this.baseDirPromise = fs.mkdir(provisionedRoot, { recursive: true })
|
|
699
|
+
.then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
|
|
700
|
+
}
|
|
701
|
+
async launch(spec) {
|
|
702
|
+
const baseDir = await this.baseDirPromise;
|
|
703
|
+
const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
|
|
704
|
+
const stateDir = path.join(runtimeHomeDir, ".openclaw");
|
|
705
|
+
const configPath = path.join(stateDir, "openclaw.json");
|
|
706
|
+
await fs.mkdir(stateDir, { recursive: true });
|
|
707
|
+
await prepareProcessRuntimeExtensions(stateDir);
|
|
708
|
+
await fs.writeFile(configPath, spec.configJson, "utf8");
|
|
709
|
+
const gatewayEntrypoint = resolveGatewayEntrypoint();
|
|
710
|
+
const child = spawn(process.execPath, [
|
|
711
|
+
gatewayEntrypoint,
|
|
712
|
+
"gateway",
|
|
713
|
+
"--allow-unconfigured",
|
|
714
|
+
"--bind",
|
|
715
|
+
"loopback",
|
|
716
|
+
"--port",
|
|
717
|
+
String(spec.gatewayPort),
|
|
718
|
+
], {
|
|
719
|
+
cwd: path.dirname(gatewayEntrypoint),
|
|
720
|
+
env: {
|
|
721
|
+
...process.env,
|
|
722
|
+
...spec.env,
|
|
723
|
+
HOME: runtimeHomeDir,
|
|
724
|
+
OPENCLAW_HOME: runtimeHomeDir,
|
|
725
|
+
OPENCLAW_STATE_DIR: stateDir,
|
|
726
|
+
OPENCLAW_CONFIG_PATH: configPath,
|
|
727
|
+
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
728
|
+
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
729
|
+
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
730
|
+
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
731
|
+
},
|
|
732
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
733
|
+
});
|
|
734
|
+
this.processByWorkerId.set(spec.workerId, child);
|
|
735
|
+
attachChildLogs(child, this.logger, `ProvisionedWorker[${spec.role}]`);
|
|
736
|
+
child.on("exit", (code, signal) => {
|
|
737
|
+
this.processByWorkerId.delete(spec.workerId);
|
|
738
|
+
this.logger.info(`Provisioner: process worker ${spec.workerId} exited (code=${String(code)}, signal=${String(signal)})`);
|
|
739
|
+
});
|
|
740
|
+
return {
|
|
741
|
+
instanceId: child.pid ? `pid:${child.pid}` : undefined,
|
|
742
|
+
instanceName: spec.workerId,
|
|
743
|
+
runtimeHomeDir,
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
async terminate(record) {
|
|
747
|
+
const child = this.processByWorkerId.get(record.workerId);
|
|
748
|
+
if (child) {
|
|
749
|
+
await stopChildProcess(child);
|
|
750
|
+
this.processByWorkerId.delete(record.workerId);
|
|
751
|
+
}
|
|
752
|
+
else if (record.instanceId?.startsWith("pid:")) {
|
|
753
|
+
const pid = Number(record.instanceId.slice("pid:".length));
|
|
754
|
+
if (Number.isFinite(pid) && pid > 0) {
|
|
755
|
+
try {
|
|
756
|
+
process.kill(pid, "SIGTERM");
|
|
757
|
+
}
|
|
758
|
+
catch {
|
|
759
|
+
// ignore
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
if (record.runtimeHomeDir) {
|
|
764
|
+
await fs.rm(record.runtimeHomeDir, { recursive: true, force: true }).catch(() => {
|
|
765
|
+
// ignore
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
async stop() {
|
|
770
|
+
for (const child of this.processByWorkerId.values()) {
|
|
771
|
+
await stopChildProcess(child).catch(() => {
|
|
772
|
+
// ignore
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
this.processByWorkerId.clear();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
class DockerProvisioner {
|
|
779
|
+
type = "docker";
|
|
780
|
+
config;
|
|
781
|
+
logger;
|
|
782
|
+
client;
|
|
783
|
+
constructor(config, logger) {
|
|
784
|
+
this.config = config;
|
|
785
|
+
this.logger = logger;
|
|
786
|
+
this.client = new DockerApiClient();
|
|
787
|
+
}
|
|
788
|
+
async launch(spec) {
|
|
789
|
+
if (!this.config.workerProvisioningImage) {
|
|
790
|
+
throw new Error("workerProvisioningImage is required for docker provisioning");
|
|
791
|
+
}
|
|
792
|
+
const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
|
|
793
|
+
const env = {
|
|
794
|
+
...spec.env,
|
|
795
|
+
HOME: "/home/node",
|
|
796
|
+
OPENCLAW_HOME: "/home/node",
|
|
797
|
+
OPENCLAW_STATE_DIR: "/home/node/.openclaw",
|
|
798
|
+
OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
|
|
799
|
+
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
800
|
+
TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
|
|
801
|
+
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
802
|
+
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
803
|
+
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
804
|
+
};
|
|
805
|
+
// When workers share a Docker network with the controller container, advertise
|
|
806
|
+
// the container name and internal worker port so sibling containers can reach it
|
|
807
|
+
// directly. When the controller runs on the host, fall back to publishing a host
|
|
808
|
+
// port and advertising localhost for host-side callbacks.
|
|
809
|
+
const usePortPublishing = spec.publishedHostPort !== undefined;
|
|
810
|
+
if (this.config.workerProvisioningDockerNetwork) {
|
|
811
|
+
env.TEAMCLAW_ADVERTISE_HOST = instanceName;
|
|
812
|
+
env.TEAMCLAW_ADVERTISE_PORT = String(spec.workerPort);
|
|
813
|
+
}
|
|
814
|
+
else if (usePortPublishing) {
|
|
815
|
+
env.TEAMCLAW_ADVERTISE_HOST = "localhost";
|
|
816
|
+
env.TEAMCLAW_ADVERTISE_PORT = String(spec.publishedHostPort);
|
|
817
|
+
}
|
|
818
|
+
const hostConfig = {
|
|
819
|
+
Binds: buildDockerBinds(this.config),
|
|
820
|
+
NetworkMode: this.config.workerProvisioningDockerNetwork || undefined,
|
|
821
|
+
};
|
|
822
|
+
if (usePortPublishing) {
|
|
823
|
+
hostConfig.PortBindings = {
|
|
824
|
+
[`${spec.workerPort}/tcp`]: [{ HostPort: String(spec.publishedHostPort) }],
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
const containerConfig = {
|
|
828
|
+
Image: this.config.workerProvisioningImage,
|
|
829
|
+
Cmd: ["sh", "-lc", buildContainerBootstrapScript()],
|
|
830
|
+
Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
|
|
831
|
+
User: "root",
|
|
832
|
+
Labels: {
|
|
833
|
+
"teamclaw.managed": "true",
|
|
834
|
+
"teamclaw.team": this.config.teamName,
|
|
835
|
+
"teamclaw.role": spec.role,
|
|
836
|
+
"teamclaw.worker_id": spec.workerId,
|
|
837
|
+
},
|
|
838
|
+
HostConfig: hostConfig,
|
|
839
|
+
};
|
|
840
|
+
if (usePortPublishing) {
|
|
841
|
+
containerConfig.ExposedPorts = { [`${spec.workerPort}/tcp`]: {} };
|
|
842
|
+
}
|
|
843
|
+
const response = await this.client.requestJson("POST", `/containers/create?name=${encodeURIComponent(instanceName)}`, containerConfig, [201]);
|
|
844
|
+
const instanceId = typeof response.Id === "string" ? response.Id : undefined;
|
|
845
|
+
if (!instanceId) {
|
|
846
|
+
throw new Error("Docker create did not return a container ID");
|
|
847
|
+
}
|
|
848
|
+
await this.client.requestVoid("POST", `/containers/${instanceId}/start`, undefined, [204]);
|
|
849
|
+
this.logger.info(`Provisioner: started docker worker container ${instanceName} (${instanceId})`);
|
|
850
|
+
return {
|
|
851
|
+
instanceId,
|
|
852
|
+
instanceName,
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
async terminate(record) {
|
|
856
|
+
const target = record.instanceId || record.instanceName;
|
|
857
|
+
if (!target) {
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
await this.client.requestVoid("DELETE", `/containers/${target}?force=1`, undefined, [204, 404]);
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* Lightweight Kubernetes API client using in-cluster service account or
|
|
865
|
+
* kubeconfig for out-of-cluster (via kubectl proxy or direct API).
|
|
866
|
+
* Avoids requiring kubectl binary in the container image.
|
|
867
|
+
*/
|
|
868
|
+
class K8sApiClient {
|
|
869
|
+
logger;
|
|
870
|
+
token;
|
|
871
|
+
caCert;
|
|
872
|
+
apiServer;
|
|
873
|
+
contextArgs;
|
|
874
|
+
constructor(context, logger) {
|
|
875
|
+
this.logger = logger;
|
|
876
|
+
this.contextArgs = context;
|
|
877
|
+
// In-cluster detection: K8s injects these env vars and mounts SA token
|
|
878
|
+
const host = process.env.KUBERNETES_SERVICE_HOST;
|
|
879
|
+
const port = process.env.KUBERNETES_SERVICE_PORT;
|
|
880
|
+
if (host && port) {
|
|
881
|
+
this.apiServer = `https://${host}:${port}`;
|
|
882
|
+
try {
|
|
883
|
+
const fs = require("node:fs");
|
|
884
|
+
this.token = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8").trim();
|
|
885
|
+
this.caCert = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt");
|
|
886
|
+
}
|
|
887
|
+
catch {
|
|
888
|
+
logger.warn("K8sApiClient: in-cluster but cannot read service account token — falling back to kubectl");
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
else {
|
|
892
|
+
// Out-of-cluster: delegate to kubectl
|
|
893
|
+
this.apiServer = "";
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
get inCluster() {
|
|
897
|
+
return Boolean(this.apiServer && this.token);
|
|
898
|
+
}
|
|
899
|
+
async createPod(namespace, manifest) {
|
|
900
|
+
if (this.inCluster) {
|
|
901
|
+
await this.apiRequest("POST", `/api/v1/namespaces/${namespace}/pods`, manifest, [200, 201]);
|
|
902
|
+
}
|
|
903
|
+
else {
|
|
904
|
+
await runCommand("kubectl", [
|
|
905
|
+
...buildKubectlContextArgs(this.contextArgs),
|
|
906
|
+
"apply", "-f", "-",
|
|
907
|
+
], JSON.stringify(manifest));
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
async deletePod(namespace, podName) {
|
|
911
|
+
if (this.inCluster) {
|
|
912
|
+
await this.apiRequest("DELETE", `/api/v1/namespaces/${namespace}/pods/${podName}?gracePeriodSeconds=0`, undefined, [200, 202, 404]);
|
|
913
|
+
}
|
|
914
|
+
else {
|
|
915
|
+
await runCommand("kubectl", [
|
|
916
|
+
...buildKubectlContextArgs(this.contextArgs),
|
|
917
|
+
"-n", namespace,
|
|
918
|
+
"delete", "pod", podName,
|
|
919
|
+
"--ignore-not-found=true", "--grace-period=0", "--force",
|
|
920
|
+
]);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
async apiRequest(method, apiPath, body, okStatuses) {
|
|
924
|
+
const payload = body !== undefined ? JSON.stringify(body) : undefined;
|
|
925
|
+
return new Promise((resolve, reject) => {
|
|
926
|
+
const url = new URL(apiPath, this.apiServer);
|
|
927
|
+
const options = {
|
|
928
|
+
method,
|
|
929
|
+
hostname: url.hostname,
|
|
930
|
+
port: url.port,
|
|
931
|
+
path: url.pathname + url.search,
|
|
932
|
+
headers: {
|
|
933
|
+
"Authorization": `Bearer ${this.token}`,
|
|
934
|
+
...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}),
|
|
935
|
+
},
|
|
936
|
+
...(this.caCert ? { ca: this.caCert } : { rejectUnauthorized: false }),
|
|
937
|
+
};
|
|
938
|
+
const req = https.request(options, (res) => {
|
|
939
|
+
let data = "";
|
|
940
|
+
res.on("data", (chunk) => { data += chunk; });
|
|
941
|
+
res.on("end", () => {
|
|
942
|
+
if (okStatuses.includes(res.statusCode ?? 0)) {
|
|
943
|
+
resolve(data);
|
|
944
|
+
}
|
|
945
|
+
else {
|
|
946
|
+
reject(new Error(`K8s API ${method} ${apiPath} returned ${res.statusCode}: ${data.slice(0, 500)}`));
|
|
947
|
+
}
|
|
948
|
+
});
|
|
949
|
+
});
|
|
950
|
+
req.on("error", reject);
|
|
951
|
+
if (payload)
|
|
952
|
+
req.write(payload);
|
|
953
|
+
req.end();
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
class KubernetesProvisioner {
|
|
958
|
+
type = "kubernetes";
|
|
959
|
+
config;
|
|
960
|
+
logger;
|
|
961
|
+
k8sApi;
|
|
962
|
+
constructor(config, logger) {
|
|
963
|
+
this.config = config;
|
|
964
|
+
this.logger = logger;
|
|
965
|
+
this.k8sApi = new K8sApiClient(config.workerProvisioningKubernetesContext, logger);
|
|
966
|
+
}
|
|
967
|
+
async launch(spec) {
|
|
968
|
+
if (!this.config.workerProvisioningImage) {
|
|
969
|
+
throw new Error("workerProvisioningImage is required for kubernetes provisioning");
|
|
970
|
+
}
|
|
971
|
+
const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
|
|
972
|
+
const ns = this.config.workerProvisioningKubernetesNamespace;
|
|
973
|
+
const env = {
|
|
974
|
+
...spec.env,
|
|
975
|
+
HOME: "/home/node",
|
|
976
|
+
OPENCLAW_HOME: "/home/node",
|
|
977
|
+
OPENCLAW_STATE_DIR: "/home/node/.openclaw",
|
|
978
|
+
OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
|
|
979
|
+
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
980
|
+
TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
|
|
981
|
+
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
982
|
+
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
983
|
+
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
984
|
+
};
|
|
985
|
+
const workspaceRoot = this.config.workerProvisioningWorkspaceRoot;
|
|
986
|
+
const hasPersistentWorkspace = Boolean(workspaceRoot && this.config.workerProvisioningKubernetesWorkspacePersistentVolumeClaim);
|
|
987
|
+
const imagePullSecrets = this.config.workerProvisioningKubernetesImagePullSecrets
|
|
988
|
+
.map((name) => name.trim())
|
|
989
|
+
.filter((name) => name.length > 0)
|
|
990
|
+
.map((name) => ({ name }));
|
|
991
|
+
const manifest = {
|
|
992
|
+
apiVersion: "v1",
|
|
993
|
+
kind: "Pod",
|
|
994
|
+
metadata: {
|
|
995
|
+
name: instanceName,
|
|
996
|
+
namespace: ns,
|
|
997
|
+
labels: {
|
|
998
|
+
app: "teamclaw-worker",
|
|
999
|
+
"teamclaw.managed": "true",
|
|
1000
|
+
"teamclaw.team": sanitizeName(this.config.teamName, 40),
|
|
1001
|
+
"teamclaw.role": sanitizeName(spec.role, 40),
|
|
1002
|
+
...this.config.workerProvisioningKubernetesLabels,
|
|
1003
|
+
},
|
|
1004
|
+
annotations: {
|
|
1005
|
+
...this.config.workerProvisioningKubernetesAnnotations,
|
|
1006
|
+
},
|
|
1007
|
+
},
|
|
1008
|
+
spec: {
|
|
1009
|
+
restartPolicy: "Never",
|
|
1010
|
+
hostname: buildManagedHostname(this.config.teamName, spec.role, spec.workerId),
|
|
1011
|
+
serviceAccountName: this.config.workerProvisioningKubernetesServiceAccount || undefined,
|
|
1012
|
+
imagePullSecrets: imagePullSecrets.length > 0 ? imagePullSecrets : undefined,
|
|
1013
|
+
securityContext: hasPersistentWorkspace
|
|
1014
|
+
? {
|
|
1015
|
+
runAsUser: 1000,
|
|
1016
|
+
runAsGroup: 1000,
|
|
1017
|
+
fsGroup: 1000,
|
|
1018
|
+
}
|
|
1019
|
+
: undefined,
|
|
1020
|
+
volumes: hasPersistentWorkspace
|
|
1021
|
+
? [
|
|
1022
|
+
{
|
|
1023
|
+
name: "workspace",
|
|
1024
|
+
persistentVolumeClaim: {
|
|
1025
|
+
claimName: this.config.workerProvisioningKubernetesWorkspacePersistentVolumeClaim,
|
|
1026
|
+
},
|
|
1027
|
+
},
|
|
1028
|
+
]
|
|
1029
|
+
: undefined,
|
|
1030
|
+
containers: [
|
|
1031
|
+
{
|
|
1032
|
+
name: "worker",
|
|
1033
|
+
image: this.config.workerProvisioningImage,
|
|
1034
|
+
command: ["sh", "-lc"],
|
|
1035
|
+
args: [buildContainerBootstrapScript()],
|
|
1036
|
+
env: Object.entries(env).map(([name, value]) => ({ name, value })),
|
|
1037
|
+
volumeMounts: hasPersistentWorkspace
|
|
1038
|
+
? [
|
|
1039
|
+
{
|
|
1040
|
+
name: "workspace",
|
|
1041
|
+
mountPath: workspaceRoot,
|
|
1042
|
+
},
|
|
1043
|
+
]
|
|
1044
|
+
: undefined,
|
|
1045
|
+
},
|
|
1046
|
+
],
|
|
1047
|
+
},
|
|
1048
|
+
};
|
|
1049
|
+
await this.k8sApi.createPod(ns, manifest);
|
|
1050
|
+
this.logger.info(`Provisioner: applied kubernetes pod ${instanceName}`);
|
|
1051
|
+
return {
|
|
1052
|
+
instanceId: instanceName,
|
|
1053
|
+
instanceName,
|
|
1054
|
+
};
|
|
1055
|
+
}
|
|
1056
|
+
async terminate(record) {
|
|
1057
|
+
const podName = record.instanceName || record.instanceId;
|
|
1058
|
+
if (!podName) {
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
const ns = this.config.workerProvisioningKubernetesNamespace;
|
|
1062
|
+
await this.k8sApi.deletePod(ns, podName);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
class DockerApiClient {
|
|
1066
|
+
endpoint;
|
|
1067
|
+
constructor() {
|
|
1068
|
+
this.endpoint = resolveDockerEndpoint();
|
|
1069
|
+
}
|
|
1070
|
+
async requestJson(method, requestPath, body, okStatuses = [200]) {
|
|
1071
|
+
const response = await this.request(method, requestPath, body, okStatuses);
|
|
1072
|
+
if (!response.body) {
|
|
1073
|
+
return {};
|
|
1074
|
+
}
|
|
1075
|
+
return JSON.parse(response.body);
|
|
1076
|
+
}
|
|
1077
|
+
async requestVoid(method, requestPath, body, okStatuses = [200]) {
|
|
1078
|
+
await this.request(method, requestPath, body, okStatuses);
|
|
1079
|
+
}
|
|
1080
|
+
async request(method, requestPath, body, okStatuses) {
|
|
1081
|
+
const payload = body === undefined ? undefined : JSON.stringify(body);
|
|
1082
|
+
// Prefer the daemon's negotiated default unless the operator pins a version explicitly.
|
|
1083
|
+
const finalPath = DOCKER_API_VERSION ? `/${DOCKER_API_VERSION}${requestPath}` : requestPath;
|
|
1084
|
+
return await new Promise((resolve, reject) => {
|
|
1085
|
+
const transport = this.endpoint.protocol === "https:" ? https : http;
|
|
1086
|
+
const req = transport.request({
|
|
1087
|
+
method,
|
|
1088
|
+
socketPath: this.endpoint.socketPath,
|
|
1089
|
+
hostname: this.endpoint.hostname,
|
|
1090
|
+
port: this.endpoint.port,
|
|
1091
|
+
path: finalPath,
|
|
1092
|
+
headers: payload
|
|
1093
|
+
? {
|
|
1094
|
+
"Content-Type": "application/json",
|
|
1095
|
+
"Content-Length": Buffer.byteLength(payload),
|
|
1096
|
+
}
|
|
1097
|
+
: undefined,
|
|
1098
|
+
}, (res) => {
|
|
1099
|
+
const chunks = [];
|
|
1100
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
1101
|
+
res.on("end", () => {
|
|
1102
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
1103
|
+
const status = res.statusCode ?? 500;
|
|
1104
|
+
if (!okStatuses.includes(status)) {
|
|
1105
|
+
const message = extractDockerErrorMessage(text) || `Docker API ${method} ${requestPath} failed with ${status}`;
|
|
1106
|
+
reject(new Error(message));
|
|
1107
|
+
return;
|
|
1108
|
+
}
|
|
1109
|
+
resolve({ status, body: text });
|
|
1110
|
+
});
|
|
1111
|
+
});
|
|
1112
|
+
req.on("error", reject);
|
|
1113
|
+
if (payload) {
|
|
1114
|
+
req.write(payload);
|
|
1115
|
+
}
|
|
1116
|
+
req.end();
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
function resolveDockerApiVersion() {
|
|
1121
|
+
const configured = process.env.DOCKER_API_VERSION?.trim();
|
|
1122
|
+
if (!configured) {
|
|
1123
|
+
return null;
|
|
1124
|
+
}
|
|
1125
|
+
return configured.startsWith("v") ? configured : `v${configured}`;
|
|
1126
|
+
}
|
|
1127
|
+
function createProvisionerBackend(config, logger) {
|
|
1128
|
+
switch (config.workerProvisioningType) {
|
|
1129
|
+
case "process":
|
|
1130
|
+
return new ProcessProvisioner(logger);
|
|
1131
|
+
case "docker":
|
|
1132
|
+
return new DockerProvisioner(config, logger);
|
|
1133
|
+
case "kubernetes":
|
|
1134
|
+
return new KubernetesProvisioner(config, logger);
|
|
1135
|
+
case "none":
|
|
1136
|
+
default:
|
|
1137
|
+
return null;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
export function buildProvisionedWorkerConfig(baseConfig, controllerConfig, spec) {
|
|
1141
|
+
const config = cloneJson(baseConfig);
|
|
1142
|
+
delete config.channels;
|
|
1143
|
+
const agents = ensureRecord(config.agents);
|
|
1144
|
+
const agentDefaults = ensureRecord(agents.defaults);
|
|
1145
|
+
delete agentDefaults.repoRoot;
|
|
1146
|
+
if (spec.workspaceDir) {
|
|
1147
|
+
agentDefaults.workspace = spec.workspaceDir;
|
|
1148
|
+
}
|
|
1149
|
+
else {
|
|
1150
|
+
delete agentDefaults.workspace;
|
|
1151
|
+
}
|
|
1152
|
+
// The host controller may run a newer openclaw that persists the keyed
|
|
1153
|
+
// agents.entries schema (e.g. agents.entries.teamclaw.model written by the
|
|
1154
|
+
// model-configuration feature). Provisioned workers can run an older
|
|
1155
|
+
// openclaw that rejects unknown agents keys ("Unrecognized key: entries"),
|
|
1156
|
+
// so fold the teamclaw entry's model back into the legacy
|
|
1157
|
+
// agents.defaults.model and drop the entries map. New-schema workers also
|
|
1158
|
+
// accept agents.defaults, keeping the folded config compatible both ways.
|
|
1159
|
+
const agentsRecord = agents;
|
|
1160
|
+
if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
|
|
1161
|
+
const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
|
|
1162
|
+
if (entryModel && !agentDefaults.model) {
|
|
1163
|
+
agentDefaults.model = entryModel;
|
|
1164
|
+
}
|
|
1165
|
+
// Container backends may run older openclaw runtimes that reject the
|
|
1166
|
+
// keyed agents schema ("Unrecognized key: entries") - fold down to
|
|
1167
|
+
// legacy defaults there. Process workers share the controller's own
|
|
1168
|
+
// runtime, which REQUIRES at least one entry ("agents.entries must
|
|
1169
|
+
// contain at least one configured agent" crash-loop, exit 78, observed
|
|
1170
|
+
// 2026-11-03 when entries was deleted unconditionally) - keep only the
|
|
1171
|
+
// teamclaw worker entry for them.
|
|
1172
|
+
const containerized = controllerConfig.workerProvisioningType === "docker" ||
|
|
1173
|
+
controllerConfig.workerProvisioningType === "kubernetes";
|
|
1174
|
+
if (containerized) {
|
|
1175
|
+
delete agentsRecord.entries;
|
|
1176
|
+
}
|
|
1177
|
+
else {
|
|
1178
|
+
agentsRecord.entries = {
|
|
1179
|
+
[TEAMCLAW_AGENT_ID]: agentsRecord.entries[TEAMCLAW_AGENT_ID] ?? {},
|
|
1180
|
+
};
|
|
1181
|
+
// Pruning entries can dangle defaults.heartbeat.agentId /
|
|
1182
|
+
// defaults.systemAgent.agentId ("main" no longer exists in the worker
|
|
1183
|
+
// config) - remap any dangling agentId reference to the surviving
|
|
1184
|
+
// teamclaw entry.
|
|
1185
|
+
for (const sectionKey of Object.keys(agentDefaults)) {
|
|
1186
|
+
const section = agentDefaults[sectionKey];
|
|
1187
|
+
if (section &&
|
|
1188
|
+
typeof section === "object" &&
|
|
1189
|
+
typeof section.agentId === "string" &&
|
|
1190
|
+
!agentsRecord.entries[section.agentId]) {
|
|
1191
|
+
section.agentId = TEAMCLAW_AGENT_ID;
|
|
1192
|
+
}
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
agents.defaults = agentDefaults;
|
|
1197
|
+
config.agents = agents;
|
|
1198
|
+
const gateway = ensureRecord(config.gateway);
|
|
1199
|
+
gateway.mode = "local";
|
|
1200
|
+
// Workers running inside Docker/K8s containers must bind on all
|
|
1201
|
+
// interfaces so the controller (in a sibling container) can reach them.
|
|
1202
|
+
gateway.bind =
|
|
1203
|
+
controllerConfig.workerProvisioningType === "docker" ||
|
|
1204
|
+
controllerConfig.workerProvisioningType === "kubernetes"
|
|
1205
|
+
? "lan"
|
|
1206
|
+
: "loopback";
|
|
1207
|
+
gateway.port = spec.gatewayPort;
|
|
1208
|
+
delete gateway.remote;
|
|
1209
|
+
config.gateway = gateway;
|
|
1210
|
+
const plugins = ensureRecord(config.plugins);
|
|
1211
|
+
plugins.enabled = true;
|
|
1212
|
+
if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
|
|
1213
|
+
delete plugins.load;
|
|
1214
|
+
}
|
|
1215
|
+
const entries = ensureRecord(plugins.entries);
|
|
1216
|
+
const teamclawEntry = ensureRecord(entries.teamclaw);
|
|
1217
|
+
teamclawEntry.enabled = true;
|
|
1218
|
+
const teamclawConfig = ensureRecord(teamclawEntry.config);
|
|
1219
|
+
teamclawConfig.mode = "worker";
|
|
1220
|
+
teamclawConfig.processModel = "multi";
|
|
1221
|
+
teamclawConfig.role = spec.role;
|
|
1222
|
+
teamclawConfig.port = spec.workerPort;
|
|
1223
|
+
teamclawConfig.controllerUrl = spec.controllerUrl;
|
|
1224
|
+
teamclawConfig.teamName = controllerConfig.teamName;
|
|
1225
|
+
teamclawConfig.heartbeatIntervalMs = controllerConfig.heartbeatIntervalMs;
|
|
1226
|
+
teamclawConfig.taskTimeoutMs = controllerConfig.taskTimeoutMs;
|
|
1227
|
+
teamclawConfig.gitEnabled = controllerConfig.gitEnabled;
|
|
1228
|
+
teamclawConfig.gitRemoteUrl = controllerConfig.gitRemoteUrl;
|
|
1229
|
+
teamclawConfig.gitDefaultBranch = controllerConfig.gitDefaultBranch;
|
|
1230
|
+
teamclawConfig.gitAuthorName = controllerConfig.gitAuthorName;
|
|
1231
|
+
teamclawConfig.gitAuthorEmail = controllerConfig.gitAuthorEmail;
|
|
1232
|
+
teamclawConfig.workerProvisioningType = "none";
|
|
1233
|
+
teamclawConfig.workerProvisioningControllerUrl = "";
|
|
1234
|
+
teamclawConfig.workerProvisioningRoles = [];
|
|
1235
|
+
teamclawConfig.workerProvisioningMinPerRole = 0;
|
|
1236
|
+
teamclawConfig.workerProvisioningMaxPerRole = 10;
|
|
1237
|
+
teamclawConfig.workerProvisioningIdleTtlMs = controllerConfig.workerProvisioningIdleTtlMs;
|
|
1238
|
+
teamclawConfig.workerProvisioningStartupTimeoutMs = controllerConfig.workerProvisioningStartupTimeoutMs;
|
|
1239
|
+
teamclawConfig.workerProvisioningImage = "";
|
|
1240
|
+
teamclawConfig.workerProvisioningPassEnv = [];
|
|
1241
|
+
teamclawConfig.workerProvisioningExtraEnv = {};
|
|
1242
|
+
teamclawConfig.workerProvisioningDockerNetwork = "";
|
|
1243
|
+
teamclawConfig.workerProvisioningDockerMounts = [];
|
|
1244
|
+
teamclawConfig.workerProvisioningWorkspaceRoot = "";
|
|
1245
|
+
teamclawConfig.workerProvisioningDockerWorkspaceVolume = "";
|
|
1246
|
+
teamclawConfig.workerProvisioningKubernetesNamespace = "default";
|
|
1247
|
+
teamclawConfig.workerProvisioningKubernetesContext = "";
|
|
1248
|
+
teamclawConfig.workerProvisioningKubernetesServiceAccount = "";
|
|
1249
|
+
teamclawConfig.workerProvisioningKubernetesImagePullSecrets = [];
|
|
1250
|
+
teamclawConfig.workerProvisioningKubernetesWorkspacePersistentVolumeClaim = "";
|
|
1251
|
+
teamclawConfig.workerProvisioningKubernetesLabels = {};
|
|
1252
|
+
teamclawConfig.workerProvisioningKubernetesAnnotations = {};
|
|
1253
|
+
teamclawEntry.config = teamclawConfig;
|
|
1254
|
+
entries.teamclaw = teamclawEntry;
|
|
1255
|
+
plugins.entries = entries;
|
|
1256
|
+
config.plugins = plugins;
|
|
1257
|
+
return config;
|
|
1258
|
+
}
|
|
1259
|
+
function ensureProvisioningState(state) {
|
|
1260
|
+
if (!state.provisioning || typeof state.provisioning !== "object") {
|
|
1261
|
+
state.provisioning = { workers: {} };
|
|
1262
|
+
}
|
|
1263
|
+
if (!state.provisioning.workers || typeof state.provisioning.workers !== "object") {
|
|
1264
|
+
state.provisioning.workers = {};
|
|
1265
|
+
}
|
|
1266
|
+
return state.provisioning;
|
|
1267
|
+
}
|
|
1268
|
+
async function ensureWritableDirectory(dir) {
|
|
1269
|
+
await fs.mkdir(dir, { recursive: true });
|
|
1270
|
+
const probePath = path.join(dir, `.teamclaw-write-probe-${process.pid}-${Date.now()}`);
|
|
1271
|
+
await fs.writeFile(probePath, "ok\n", "utf8");
|
|
1272
|
+
await fs.rm(probePath, { force: true });
|
|
1273
|
+
}
|
|
1274
|
+
function sleep(ms) {
|
|
1275
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1276
|
+
}
|
|
1277
|
+
async function loadOpenClawConfig(configPath) {
|
|
1278
|
+
const raw = await fs.readFile(configPath, "utf8");
|
|
1279
|
+
return parseLooseJsonObject(raw, configPath);
|
|
1280
|
+
}
|
|
1281
|
+
async function prepareProcessRuntimeExtensions(stateDir) {
|
|
1282
|
+
const runtimeExtensionsDir = path.join(stateDir, "extensions");
|
|
1283
|
+
const controllerExtensionsDir = path.join(path.dirname(resolveDefaultOpenClawConfigPath()), "extensions");
|
|
1284
|
+
if (await pathExists(controllerExtensionsDir)) {
|
|
1285
|
+
await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
|
|
1286
|
+
}
|
|
1287
|
+
else {
|
|
1288
|
+
await fs.mkdir(runtimeExtensionsDir, { recursive: true });
|
|
1289
|
+
// Baked-in images set TEAMCLAW_BAKED_IN=true and the legacy helper
|
|
1290
|
+
// returned "" for that case, so the symlink target was empty and
|
|
1291
|
+
// process workers fell back to resolving the plugin from their cwd
|
|
1292
|
+
// ("/app/dist/openclaw.plugin.json" not found → exit loop, k3s e2e
|
|
1293
|
+
// 2026-11-03). Probe the baked image layout instead: the controller
|
|
1294
|
+
// entrypoint (process.argv[1], e.g. /app/dist/index.js) sits below
|
|
1295
|
+
// the app root, where the runtime image ships
|
|
1296
|
+
// /app/extensions/teamclaw with its openclaw.plugin.json.
|
|
1297
|
+
const pluginRootDir = process.env.TEAMCLAW_BAKED_IN === "true"
|
|
1298
|
+
? await resolveBakedTeamClawPluginRootDir()
|
|
1299
|
+
: resolveCurrentTeamClawPluginRootDir();
|
|
1300
|
+
if (pluginRootDir) {
|
|
1301
|
+
await fs.symlink(pluginRootDir, path.join(runtimeExtensionsDir, "teamclaw"), "dir");
|
|
1302
|
+
}
|
|
1303
|
+
}
|
|
1304
|
+
await copyControllerAuthProfiles(stateDir);
|
|
1305
|
+
}
|
|
1306
|
+
async function copyControllerAuthProfiles(stateDir) {
|
|
1307
|
+
const candidateControllerStateDirs = [
|
|
1308
|
+
path.dirname(resolveDefaultOpenClawConfigPath()),
|
|
1309
|
+
resolveDefaultOpenClawStateDir(),
|
|
1310
|
+
];
|
|
1311
|
+
const candidateAuthProfilePaths = [
|
|
1312
|
+
path.join(resolveTeamClawAgentDir(), "auth-profiles.json"),
|
|
1313
|
+
path.join(resolveDefaultAgentDir(), "auth-profiles.json"),
|
|
1314
|
+
...candidateControllerStateDirs.flatMap((controllerStateDir) => [
|
|
1315
|
+
path.join(controllerStateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
|
|
1316
|
+
path.join(controllerStateDir, "agents", "main", "agent", "auth-profiles.json"),
|
|
1317
|
+
]),
|
|
1318
|
+
].filter((value, index, values) => values.indexOf(value) === index);
|
|
1319
|
+
let controllerAuthProfilesPath;
|
|
1320
|
+
for (const candidatePath of candidateAuthProfilePaths) {
|
|
1321
|
+
if (await pathExists(candidatePath)) {
|
|
1322
|
+
controllerAuthProfilesPath = candidatePath;
|
|
1323
|
+
break;
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
if (!controllerAuthProfilesPath) {
|
|
1327
|
+
return;
|
|
1328
|
+
}
|
|
1329
|
+
const runtimeAuthProfilePaths = [
|
|
1330
|
+
path.join(stateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
|
|
1331
|
+
path.join(stateDir, "agents", "main", "agent", "auth-profiles.json"),
|
|
1332
|
+
];
|
|
1333
|
+
for (const runtimeAuthProfilesPath of runtimeAuthProfilePaths) {
|
|
1334
|
+
await fs.mkdir(path.dirname(runtimeAuthProfilesPath), { recursive: true });
|
|
1335
|
+
await fs.copyFile(controllerAuthProfilesPath, runtimeAuthProfilesPath);
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
function cloneJson(value) {
|
|
1339
|
+
return JSON.parse(JSON.stringify(value));
|
|
1340
|
+
}
|
|
1341
|
+
function requiresDedicatedHostPortsForProvisioner(provider, config) {
|
|
1342
|
+
if (provider === "process") {
|
|
1343
|
+
return true;
|
|
1344
|
+
}
|
|
1345
|
+
return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
|
|
1346
|
+
}
|
|
1347
|
+
function isDockerHostNetwork(networkMode) {
|
|
1348
|
+
return networkMode.trim().toLowerCase() === "host";
|
|
1349
|
+
}
|
|
1350
|
+
function extractDockerBindTarget(bind) {
|
|
1351
|
+
for (const part of bind.split(":").reverse()) {
|
|
1352
|
+
const trimmed = part.trim();
|
|
1353
|
+
if (trimmed.startsWith("/")) {
|
|
1354
|
+
return trimmed;
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
return null;
|
|
1358
|
+
}
|
|
1359
|
+
function appendNoProxyEntries(env, controllerUrl) {
|
|
1360
|
+
const requiredEntries = resolveRequiredNoProxyEntries(controllerUrl);
|
|
1361
|
+
if (requiredEntries.length === 0) {
|
|
1362
|
+
return env;
|
|
1363
|
+
}
|
|
1364
|
+
const upperBase = env.NO_PROXY ?? process.env.NO_PROXY ?? process.env.no_proxy ?? "";
|
|
1365
|
+
const lowerBase = env.no_proxy ?? process.env.no_proxy ?? env.NO_PROXY ?? process.env.NO_PROXY ?? "";
|
|
1366
|
+
env.NO_PROXY = mergeNoProxyEntries(upperBase, requiredEntries);
|
|
1367
|
+
env.no_proxy = mergeNoProxyEntries(lowerBase, requiredEntries);
|
|
1368
|
+
return env;
|
|
1369
|
+
}
|
|
1370
|
+
function resolveRequiredNoProxyEntries(controllerUrl) {
|
|
1371
|
+
const required = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
1372
|
+
try {
|
|
1373
|
+
const host = new URL(controllerUrl).hostname.trim();
|
|
1374
|
+
if (host) {
|
|
1375
|
+
required.add(host);
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
catch {
|
|
1379
|
+
// Ignore malformed controller URLs; worker registration will fail separately.
|
|
1380
|
+
}
|
|
1381
|
+
return Array.from(required);
|
|
1382
|
+
}
|
|
1383
|
+
function mergeNoProxyEntries(existing, requiredEntries) {
|
|
1384
|
+
const tokens = new Map();
|
|
1385
|
+
for (const entry of existing.split(",")) {
|
|
1386
|
+
const trimmed = entry.trim();
|
|
1387
|
+
if (!trimmed) {
|
|
1388
|
+
continue;
|
|
1389
|
+
}
|
|
1390
|
+
tokens.set(trimmed.toLowerCase(), trimmed);
|
|
1391
|
+
}
|
|
1392
|
+
for (const entry of requiredEntries) {
|
|
1393
|
+
const trimmed = entry.trim();
|
|
1394
|
+
if (!trimmed) {
|
|
1395
|
+
continue;
|
|
1396
|
+
}
|
|
1397
|
+
tokens.set(trimmed.toLowerCase(), trimmed);
|
|
1398
|
+
}
|
|
1399
|
+
return Array.from(tokens.values()).join(",");
|
|
1400
|
+
}
|
|
1401
|
+
async function pathExists(targetPath) {
|
|
1402
|
+
try {
|
|
1403
|
+
await fs.access(targetPath);
|
|
1404
|
+
return true;
|
|
1405
|
+
}
|
|
1406
|
+
catch (err) {
|
|
1407
|
+
if (err.code === "ENOENT") {
|
|
1408
|
+
return false;
|
|
1409
|
+
}
|
|
1410
|
+
throw err;
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
function ensureRecord(value) {
|
|
1414
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
1415
|
+
? { ...value }
|
|
1416
|
+
: {};
|
|
1417
|
+
}
|
|
1418
|
+
function parseLooseJsonObject(raw, configPath) {
|
|
1419
|
+
try {
|
|
1420
|
+
return JSON5.parse(raw);
|
|
1421
|
+
}
|
|
1422
|
+
catch (err) {
|
|
1423
|
+
throw new Error(`Failed to parse OpenClaw config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
async function reserveEphemeralPort() {
|
|
1427
|
+
return await new Promise((resolve, reject) => {
|
|
1428
|
+
const server = net.createServer();
|
|
1429
|
+
server.listen(0, "127.0.0.1", () => {
|
|
1430
|
+
const address = server.address();
|
|
1431
|
+
const port = address && typeof address === "object" ? address.port : 0;
|
|
1432
|
+
server.close((err) => {
|
|
1433
|
+
if (err) {
|
|
1434
|
+
reject(err);
|
|
1435
|
+
return;
|
|
1436
|
+
}
|
|
1437
|
+
if (!port) {
|
|
1438
|
+
reject(new Error("Failed to reserve ephemeral port"));
|
|
1439
|
+
return;
|
|
1440
|
+
}
|
|
1441
|
+
resolve(port);
|
|
1442
|
+
});
|
|
1443
|
+
});
|
|
1444
|
+
server.on("error", reject);
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
function resolveGatewayEntrypoint() {
|
|
1448
|
+
const scriptPath = process.argv[1];
|
|
1449
|
+
if (!scriptPath) {
|
|
1450
|
+
throw new Error("Unable to resolve OpenClaw gateway entrypoint");
|
|
1451
|
+
}
|
|
1452
|
+
return path.resolve(scriptPath);
|
|
1453
|
+
}
|
|
1454
|
+
function resolveCurrentTeamClawPluginRootDir() {
|
|
1455
|
+
return process.env.TEAMCLAW_BAKED_IN === "true" ? "" : path.resolve(fileURLToPath(new URL("../../", import.meta.url)));
|
|
1456
|
+
}
|
|
1457
|
+
/**
|
|
1458
|
+
* Locate the teamclaw plugin root inside a baked runtime image. The image
|
|
1459
|
+
* ships the plugin at <app-root>/extensions/teamclaw; the controller
|
|
1460
|
+
* entrypoint (process.argv[1]) lives under <app-root>, so walk up from it.
|
|
1461
|
+
* Returns "" when no candidate carries an openclaw.plugin.json (the
|
|
1462
|
+
* caller then skips the symlink instead of creating a dangling one).
|
|
1463
|
+
*/
|
|
1464
|
+
async function resolveBakedTeamClawPluginRootDir() {
|
|
1465
|
+
const entrypoint = process.argv[1] ? path.resolve(process.argv[1]) : "";
|
|
1466
|
+
const candidates = entrypoint
|
|
1467
|
+
? [
|
|
1468
|
+
path.resolve(entrypoint, "../../extensions/teamclaw"),
|
|
1469
|
+
path.resolve(entrypoint, "../extensions/teamclaw"),
|
|
1470
|
+
]
|
|
1471
|
+
: [];
|
|
1472
|
+
candidates.push("/app/extensions/teamclaw");
|
|
1473
|
+
for (const candidate of candidates) {
|
|
1474
|
+
try {
|
|
1475
|
+
await fs.access(path.join(candidate, "openclaw.plugin.json"));
|
|
1476
|
+
return candidate;
|
|
1477
|
+
}
|
|
1478
|
+
catch {
|
|
1479
|
+
// try the next candidate layout
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
return "";
|
|
1483
|
+
}
|
|
1484
|
+
function attachChildLogs(child, logger, prefix) {
|
|
1485
|
+
if (child.stdout) {
|
|
1486
|
+
const stdoutReader = readline.createInterface({ input: child.stdout });
|
|
1487
|
+
stdoutReader.on("line", (line) => {
|
|
1488
|
+
logger.info(`${prefix}: ${line}`);
|
|
1489
|
+
});
|
|
1490
|
+
}
|
|
1491
|
+
if (child.stderr) {
|
|
1492
|
+
const stderrReader = readline.createInterface({ input: child.stderr });
|
|
1493
|
+
stderrReader.on("line", (line) => {
|
|
1494
|
+
logger.warn(`${prefix}: ${line}`);
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
async function stopChildProcess(child) {
|
|
1499
|
+
if (child.exitCode !== null || child.signalCode !== null) {
|
|
1500
|
+
return;
|
|
1501
|
+
}
|
|
1502
|
+
await new Promise((resolve) => {
|
|
1503
|
+
const timeout = setTimeout(() => {
|
|
1504
|
+
if (child.exitCode === null && child.signalCode === null && child.pid) {
|
|
1505
|
+
try {
|
|
1506
|
+
process.kill(child.pid, "SIGKILL");
|
|
1507
|
+
}
|
|
1508
|
+
catch {
|
|
1509
|
+
// ignore
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
resolve();
|
|
1513
|
+
}, PROCESS_TERMINATION_TIMEOUT_MS);
|
|
1514
|
+
const timer = timeout;
|
|
1515
|
+
timer.unref?.();
|
|
1516
|
+
child.once("exit", () => {
|
|
1517
|
+
clearTimeout(timeout);
|
|
1518
|
+
resolve();
|
|
1519
|
+
});
|
|
1520
|
+
child.kill("SIGTERM");
|
|
1521
|
+
});
|
|
1522
|
+
}
|
|
1523
|
+
function sanitizePathSegment(value) {
|
|
1524
|
+
const normalized = value.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
1525
|
+
return normalized || "worker";
|
|
1526
|
+
}
|
|
1527
|
+
function sanitizeName(value, maxLength = 63) {
|
|
1528
|
+
const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
|
|
1529
|
+
return normalized || "teamclaw";
|
|
1530
|
+
}
|
|
1531
|
+
function buildManagedInstanceName(teamName, role, workerId) {
|
|
1532
|
+
return buildManagedName("teamclaw", teamName, role, workerId, {
|
|
1533
|
+
teamBudget: 18,
|
|
1534
|
+
roleBudget: 12,
|
|
1535
|
+
workerBudget: 12,
|
|
1536
|
+
hashLength: 8,
|
|
1537
|
+
maxLength: 63,
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
function buildManagedHostname(teamName, role, workerId) {
|
|
1541
|
+
return buildManagedName("tc", teamName, role, workerId, {
|
|
1542
|
+
teamBudget: 10,
|
|
1543
|
+
roleBudget: 8,
|
|
1544
|
+
workerBudget: 6,
|
|
1545
|
+
hashLength: 6,
|
|
1546
|
+
maxLength: 40,
|
|
1547
|
+
});
|
|
1548
|
+
}
|
|
1549
|
+
function buildManagedName(prefix, teamName, role, workerId, options) {
|
|
1550
|
+
const teamPart = sanitizeLeadingSegment(teamName, options.teamBudget, "team");
|
|
1551
|
+
const rolePart = sanitizeLeadingSegment(role, options.roleBudget, "worker");
|
|
1552
|
+
const workerPart = sanitizeTrailingSegment(workerId, options.workerBudget, "worker");
|
|
1553
|
+
const hash = shortStableHash(`${teamName}:${role}:${workerId}`).slice(0, options.hashLength);
|
|
1554
|
+
return sanitizeName(`${prefix}-${teamPart}-${rolePart}-${workerPart}-${hash}`, options.maxLength);
|
|
1555
|
+
}
|
|
1556
|
+
function shortStableHash(value) {
|
|
1557
|
+
return createHash("sha1").update(value).digest("hex");
|
|
1558
|
+
}
|
|
1559
|
+
function sanitizeLeadingSegment(value, maxLength, fallback) {
|
|
1560
|
+
const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
|
|
1561
|
+
return normalized || fallback;
|
|
1562
|
+
}
|
|
1563
|
+
function sanitizeTrailingSegment(value, maxLength, fallback) {
|
|
1564
|
+
const normalized = sanitizePathSegment(value).slice(-maxLength).replace(/^-+|-+$/g, "");
|
|
1565
|
+
return normalized || fallback;
|
|
1566
|
+
}
|
|
1567
|
+
function buildContainerBootstrapScript() {
|
|
1568
|
+
return [
|
|
1569
|
+
"set -eu",
|
|
1570
|
+
"mkdir -p \"$OPENCLAW_STATE_DIR\"",
|
|
1571
|
+
"if [ -n \"${TEAMCLAW_WORKSPACE_DIR:-}\" ]; then mkdir -p \"$TEAMCLAW_WORKSPACE_DIR\"; fi",
|
|
1572
|
+
"node -e 'const fs=require(\"fs\"); const configPath=process.env.OPENCLAW_CONFIG_PATH; const raw=Buffer.from(process.env.TEAMCLAW_BOOTSTRAP_CONFIG_B64||\"\", \"base64\").toString(\"utf8\"); fs.mkdirSync(require(\"path\").dirname(configPath), { recursive: true }); fs.writeFileSync(configPath, raw);'",
|
|
1573
|
+
"exec node dist/index.js gateway --allow-unconfigured",
|
|
1574
|
+
].join("\n");
|
|
1575
|
+
}
|
|
1576
|
+
function buildDockerBinds(config) {
|
|
1577
|
+
const binds = [...config.workerProvisioningDockerMounts];
|
|
1578
|
+
if (!binds.some((bind) => extractDockerBindTarget(bind) === DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR)) {
|
|
1579
|
+
const _pd = resolveCurrentTeamClawPluginRootDir();
|
|
1580
|
+
if (_pd)
|
|
1581
|
+
binds.unshift(`${_pd}:${DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR}:ro`);
|
|
1582
|
+
}
|
|
1583
|
+
if (config.workerProvisioningDockerWorkspaceVolume && config.workerProvisioningWorkspaceRoot) {
|
|
1584
|
+
binds.unshift(`${config.workerProvisioningDockerWorkspaceVolume}:${config.workerProvisioningWorkspaceRoot}`);
|
|
1585
|
+
}
|
|
1586
|
+
return [...new Set(binds)];
|
|
1587
|
+
}
|
|
1588
|
+
function buildProvisionedWorkspaceDir(provider, config, role, workerId) {
|
|
1589
|
+
// Process-type workers run on the same host — share the controller's workspace
|
|
1590
|
+
// so that file artifacts (previews, deliverables) are immediately visible to
|
|
1591
|
+
// the controller without requiring git sync or file transfer.
|
|
1592
|
+
if (provider === "process") {
|
|
1593
|
+
return resolveTeamClawAgentWorkspaceRootDir();
|
|
1594
|
+
}
|
|
1595
|
+
if ((provider !== "docker" && provider !== "kubernetes") ||
|
|
1596
|
+
!config.workerProvisioningWorkspaceRoot) {
|
|
1597
|
+
return "";
|
|
1598
|
+
}
|
|
1599
|
+
return path.posix.join(config.workerProvisioningWorkspaceRoot, sanitizePathSegment(config.teamName), sanitizePathSegment(role), sanitizePathSegment(workerId));
|
|
1600
|
+
}
|
|
1601
|
+
function getConfiguredWorkerWorkspaceDir(config) {
|
|
1602
|
+
const agents = ensureRecord(config.agents);
|
|
1603
|
+
const defaults = ensureRecord(agents.defaults);
|
|
1604
|
+
return typeof defaults.workspace === "string" ? defaults.workspace : "";
|
|
1605
|
+
}
|
|
1606
|
+
function resolveDockerEndpoint() {
|
|
1607
|
+
const dockerHost = process.env.DOCKER_HOST?.trim();
|
|
1608
|
+
if (!dockerHost) {
|
|
1609
|
+
return {
|
|
1610
|
+
protocol: "http:",
|
|
1611
|
+
socketPath: "/var/run/docker.sock",
|
|
1612
|
+
};
|
|
1613
|
+
}
|
|
1614
|
+
if (dockerHost.startsWith("unix://")) {
|
|
1615
|
+
return {
|
|
1616
|
+
protocol: "http:",
|
|
1617
|
+
socketPath: dockerHost.slice("unix://".length),
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
const normalized = dockerHost.startsWith("tcp://")
|
|
1621
|
+
? dockerHost.replace(/^tcp:\/\//, "http://")
|
|
1622
|
+
: dockerHost;
|
|
1623
|
+
const url = new URL(normalized);
|
|
1624
|
+
return {
|
|
1625
|
+
protocol: url.protocol === "https:" ? "https:" : "http:",
|
|
1626
|
+
hostname: url.hostname,
|
|
1627
|
+
port: url.port ? Number(url.port) : (url.protocol === "https:" ? 443 : 2375),
|
|
1628
|
+
};
|
|
1629
|
+
}
|
|
1630
|
+
function extractDockerErrorMessage(body) {
|
|
1631
|
+
if (!body.trim()) {
|
|
1632
|
+
return null;
|
|
1633
|
+
}
|
|
1634
|
+
try {
|
|
1635
|
+
const parsed = JSON.parse(body);
|
|
1636
|
+
return typeof parsed.message === "string" ? parsed.message : body;
|
|
1637
|
+
}
|
|
1638
|
+
catch {
|
|
1639
|
+
return body;
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
async function runCommand(command, args, stdin) {
|
|
1643
|
+
await new Promise((resolve, reject) => {
|
|
1644
|
+
const child = spawn(command, args, {
|
|
1645
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1646
|
+
env: process.env,
|
|
1647
|
+
});
|
|
1648
|
+
let stderr = "";
|
|
1649
|
+
let stdout = "";
|
|
1650
|
+
if (stdin) {
|
|
1651
|
+
child.stdin?.end(stdin);
|
|
1652
|
+
}
|
|
1653
|
+
else {
|
|
1654
|
+
child.stdin?.end();
|
|
1655
|
+
}
|
|
1656
|
+
child.stdout?.on("data", (chunk) => {
|
|
1657
|
+
stdout += chunk.toString("utf8");
|
|
1658
|
+
});
|
|
1659
|
+
child.stderr?.on("data", (chunk) => {
|
|
1660
|
+
stderr += chunk.toString("utf8");
|
|
1661
|
+
});
|
|
1662
|
+
child.on("error", reject);
|
|
1663
|
+
child.on("exit", (code) => {
|
|
1664
|
+
if (code === 0) {
|
|
1665
|
+
resolve();
|
|
1666
|
+
return;
|
|
1667
|
+
}
|
|
1668
|
+
reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${(stderr || stdout).trim()}`));
|
|
1669
|
+
});
|
|
1670
|
+
});
|
|
1671
|
+
}
|
|
1672
|
+
function buildKubectlContextArgs(context) {
|
|
1673
|
+
return context ? ["--context", context] : [];
|
|
1674
|
+
}
|