@teamclaws/teamclaw 2026.8.1 → 2026.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli.mjs +318 -17
- package/dist/index.js +54 -32
- package/dist/src/config.js +57 -2
- package/dist/src/controller/auth-routes.js +129 -0
- package/dist/src/controller/clarification-routes.js +315 -0
- package/dist/src/controller/controller-intake.js +895 -0
- package/dist/src/controller/controller-planning.js +814 -0
- package/dist/src/controller/controller-routes.js +195 -0
- package/dist/src/controller/controller-runs.js +175 -0
- package/dist/src/controller/controller-service.js +338 -50
- package/dist/src/controller/controller-tools.js +14 -7
- package/dist/src/controller/github-auth.js +2 -1
- package/dist/src/controller/http-server.js +290 -6003
- package/dist/src/controller/kickoff-orchestrator.js +33 -43
- package/dist/src/controller/message-delivery.js +31 -0
- package/dist/src/controller/message-routes.js +114 -0
- package/dist/src/controller/orchestration-manifest.js +11 -93
- package/dist/src/controller/preview-manager.js +51 -3
- package/dist/src/controller/preview-proxy.js +98 -0
- package/dist/src/controller/profile-switch.js +309 -0
- package/dist/src/controller/project-registry.js +294 -0
- package/dist/src/controller/prompt-injector.js +19 -9
- package/dist/src/controller/provisioning/backend-contract.js +9 -0
- package/dist/src/controller/provisioning/container-shared.js +64 -0
- package/dist/src/controller/provisioning/docker.js +214 -0
- package/dist/src/controller/provisioning/kubernetes.js +244 -0
- package/dist/src/controller/provisioning/plugin-root.js +41 -0
- package/dist/src/controller/provisioning/process-supervisor.js +190 -0
- package/dist/src/controller/provisioning-config.js +239 -0
- package/dist/src/controller/repo-routes.js +129 -0
- package/dist/src/controller/report-routes.js +56 -0
- package/dist/src/controller/role-inference.js +231 -20
- package/dist/src/controller/route-table.js +375 -0
- package/dist/src/controller/security.js +775 -0
- package/dist/src/controller/status-routes.js +287 -0
- package/dist/src/controller/task-assignment.js +511 -0
- package/dist/src/controller/task-cleanup.js +258 -0
- package/dist/src/controller/task-execution.js +271 -0
- package/dist/src/controller/task-results.js +471 -0
- package/dist/src/controller/task-router.js +74 -4
- 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 +41 -8
- package/dist/src/controller/tunnel-routes.js +225 -0
- package/dist/src/controller/ui-assets.js +68 -0
- package/dist/src/controller/websocket.js +6 -2
- package/dist/src/controller/webui-routes.js +49 -0
- package/dist/src/controller/worker-provisioning.js +69 -953
- package/dist/src/controller/worker-routes.js +188 -0
- package/dist/src/controller/workflow-routes.js +407 -0
- package/dist/src/controller/workspace-routes.js +200 -0
- package/dist/src/git-collaboration.js +4 -9
- package/dist/src/identity.js +15 -3
- package/dist/src/interaction-contracts.js +7 -7
- package/dist/src/openclaw-workspace.js +40 -18
- package/dist/src/profile-loader.js +604 -0
- package/dist/src/profiles/banking.json +202 -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 +281 -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 +42 -17
- package/dist/src/protocol.js +66 -3
- package/dist/src/role-ids.js +29 -0
- package/dist/src/roles.js +54 -13
- package/dist/src/session-roles.js +14 -0
- package/dist/src/shared/clarification-schema.js +65 -0
- package/dist/src/shared/github-auth.js +15 -0
- package/dist/src/shared/kickoff-prompt.js +37 -0
- package/dist/src/shared/utils.js +47 -0
- package/dist/src/state.js +275 -11
- package/dist/src/task-executor.js +7 -17
- package/dist/src/teamauto/github-client.js +18 -0
- package/dist/src/teamauto/repo-sync.js +228 -6
- package/dist/src/teamauto/scanner.js +40 -12
- package/dist/src/teamauto/scheduler.js +231 -12
- package/dist/src/types.js +77 -16
- package/dist/src/ui/app.js +1434 -82
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +144 -45
- package/dist/src/ui/style.css +194 -0
- package/dist/src/worker/http-handler.js +59 -0
- package/dist/src/worker/prompt-injector.js +44 -8
- package/dist/src/worker/skill-installer.js +6 -10
- package/dist/src/worker/tools.js +20 -10
- package/dist/src/worker/worker-service.js +93 -7
- package/index.ts +61 -32
- package/openclaw.plugin.json +50 -2
- package/package.json +3 -2
- package/src/config.ts +57 -2
- package/src/controller/auth-routes.ts +157 -0
- package/src/controller/clarification-routes.ts +404 -0
- package/src/controller/controller-intake.ts +1113 -0
- package/src/controller/controller-planning.ts +1037 -0
- package/src/controller/controller-routes.ts +237 -0
- package/src/controller/controller-runs.ts +239 -0
- package/src/controller/controller-service.ts +422 -50
- package/src/controller/controller-tools.ts +16 -9
- package/src/controller/github-auth.ts +28 -63
- package/src/controller/http-server.ts +336 -6964
- package/src/controller/kickoff-orchestrator.ts +69 -45
- package/src/controller/message-delivery.ts +52 -0
- package/src/controller/message-routes.ts +137 -0
- package/src/controller/orchestration-manifest.ts +14 -100
- package/src/controller/preview-manager.ts +53 -3
- package/src/controller/preview-proxy.ts +127 -0
- package/src/controller/profile-switch.ts +396 -0
- package/src/controller/project-registry.ts +361 -0
- package/src/controller/prompt-injector.ts +23 -8
- package/src/controller/provisioning/backend-contract.ts +51 -0
- package/src/controller/provisioning/container-shared.ts +84 -0
- package/src/controller/provisioning/docker.ts +260 -0
- package/src/controller/provisioning/kubernetes.ts +263 -0
- package/src/controller/provisioning/plugin-root.ts +42 -0
- package/src/controller/provisioning/process-supervisor.ts +214 -0
- package/src/controller/provisioning-config.ts +289 -0
- package/src/controller/repo-routes.ts +163 -0
- package/src/controller/report-routes.ts +64 -0
- package/src/controller/role-inference.ts +260 -22
- package/src/controller/route-table.ts +597 -0
- package/src/controller/security.ts +899 -0
- package/src/controller/status-routes.ts +354 -0
- package/src/controller/task-assignment.ts +622 -0
- package/src/controller/task-cleanup.ts +344 -0
- package/src/controller/task-execution.ts +399 -0
- package/src/controller/task-results.ts +556 -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/tunnel-manager.ts +45 -8
- package/src/controller/tunnel-routes.ts +231 -0
- package/src/controller/ui-assets.ts +70 -0
- package/src/controller/websocket.ts +32 -4
- package/src/controller/webui-routes.ts +55 -0
- package/src/controller/worker-provisioning.ts +83 -1121
- package/src/controller/worker-routes.ts +241 -0
- package/src/controller/workflow-routes.ts +498 -0
- package/src/controller/workspace-routes.ts +222 -0
- package/src/git-collaboration.ts +4 -9
- package/src/identity.ts +16 -3
- package/src/interaction-contracts.ts +7 -7
- package/src/openclaw-workspace.ts +44 -18
- package/src/profile-loader.ts +816 -0
- package/src/profiles/banking.json +202 -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 +281 -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 +44 -17
- package/src/protocol.ts +72 -2
- package/src/role-ids.ts +31 -0
- package/src/roles.ts +60 -14
- package/src/session-roles.ts +14 -0
- package/src/shared/clarification-schema.ts +81 -0
- package/src/shared/github-auth.ts +92 -0
- package/src/shared/kickoff-prompt.ts +47 -0
- package/src/shared/utils.ts +51 -0
- package/src/state.ts +326 -10
- package/src/task-executor.ts +7 -18
- package/src/teamauto/github-client.ts +23 -1
- package/src/teamauto/repo-sync.ts +248 -7
- package/src/teamauto/scanner.ts +47 -13
- package/src/teamauto/scheduler.ts +261 -17
- package/src/teamauto/store.ts +12 -0
- package/src/types.ts +263 -17
- package/src/ui/app.js +1434 -82
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +144 -45
- package/src/ui/style.css +194 -0
- package/src/worker/http-handler.ts +64 -1
- package/src/worker/prompt-injector.ts +48 -8
- package/src/worker/skill-installer.ts +6 -10
- package/src/worker/tools.ts +21 -10
- package/src/worker/worker-service.ts +101 -7
|
@@ -1,26 +1,48 @@
|
|
|
1
|
+
// W1 of issue #226 (worker-provisioning god-file split): this module is now
|
|
2
|
+
// the provisioner facade. WorkerProvisioningManager keeps the reconcile
|
|
3
|
+
// loop, role-demand computation, startup-readiness tracking and the
|
|
4
|
+
// launch/terminate orchestration; everything it delegates to moved VERBATIM
|
|
5
|
+
// (zero behavior change) into:
|
|
6
|
+
// - provisioning-config.ts worker config synthesis, controller
|
|
7
|
+
// auth-profile copy, no-proxy env
|
|
8
|
+
// - provisioning/backend-contract.ts backend interface + host-port policy
|
|
9
|
+
// - provisioning/plugin-root.ts TeamClaw plugin root resolution
|
|
10
|
+
// - provisioning/process-supervisor.ts local process backend
|
|
11
|
+
// - provisioning/docker.ts / kubernetes.ts container backends + API clients
|
|
12
|
+
// - provisioning/container-shared.ts managed names + bootstrap script
|
|
13
|
+
// - shared/utils.ts generic utils (pathExists/sleep/...)
|
|
14
|
+
// Dependency direction: this facade imports the modules above; none of them
|
|
15
|
+
// imports this file (no cycles). The external face is unchanged -
|
|
16
|
+
// WorkerProvisioningManager plus the buildProvisionedWorkerConfig re-export
|
|
17
|
+
// below keep their historical module path and signatures.
|
|
1
18
|
import fs from "node:fs/promises";
|
|
2
|
-
import http from "node:http";
|
|
3
|
-
import https from "node:https";
|
|
4
19
|
import net from "node:net";
|
|
5
20
|
import path from "node:path";
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
import {
|
|
12
|
-
|
|
13
|
-
|
|
21
|
+
import { generateId, generateLaunchToken, secretsEqual } from "../protocol.js";
|
|
22
|
+
// Issue #255 P0-1: the launch-token check at registration uses the shared
|
|
23
|
+
// constant-time secret equality (same helper the device gate and tunnel gate
|
|
24
|
+
// use). controller -> controller edge; security.ts never imports back here,
|
|
25
|
+
// so the module graph stays acyclic.
|
|
26
|
+
import { resolveDefaultOpenClawConfigPath, resolveDefaultTeamClawRuntimeRootDir, resolveTeamClawAgentDir, resolveTeamClawAgentWorkspaceRootDir, resolveTeamClawWorkspaceDir, } from "../openclaw-workspace.js";
|
|
27
|
+
// Phase 1.3: the role universe and the fallback role come from the active
|
|
28
|
+
// TeamProfile loader (software-rd baseline).
|
|
29
|
+
import { getActiveRoleIds, getActiveDefaultRole } from "../profile-loader.js";
|
|
14
30
|
import { inferTaskRole } from "./role-inference.js";
|
|
31
|
+
import { cloneJson, sleep } from "../shared/utils.js";
|
|
32
|
+
import { appendNoProxyEntries, buildProvisionedWorkspaceDir, buildProvisionedWorkerConfig, getConfiguredWorkerWorkspaceDir, loadOpenClawConfig, } from "./provisioning-config.js";
|
|
33
|
+
import { isDockerHostNetwork, requiresDedicatedHostPortsForProvisioner, } from "./provisioning/backend-contract.js";
|
|
34
|
+
import { ProcessProvisioner } from "./provisioning/process-supervisor.js";
|
|
35
|
+
import { DockerProvisioner } from "./provisioning/docker.js";
|
|
36
|
+
import { KubernetesProvisioner } from "./provisioning/kubernetes.js";
|
|
37
|
+
// Historical export face kept stable for tests / external tooling.
|
|
38
|
+
export { buildProvisionedWorkerConfig } from "./provisioning-config.js";
|
|
15
39
|
const DEFAULT_CONTAINER_WORKER_PORT = 9527;
|
|
16
40
|
const DEFAULT_CONTAINER_GATEWAY_PORT = 18789;
|
|
17
|
-
const DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR = "/app/extensions/teamclaw";
|
|
18
41
|
const PROVISIONING_RECORD_RETENTION_MS = 6 * 60 * 60 * 1000;
|
|
19
42
|
const PROVISIONING_FAILURE_COOLDOWN_MS = 30_000;
|
|
20
43
|
const PROCESS_TERMINATION_TIMEOUT_MS = 10_000;
|
|
21
44
|
const STARTUP_READINESS_POLL_INTERVAL_MS = 1_000;
|
|
22
45
|
const STARTUP_READINESS_RETRY_INTERVAL_MS = 5_000;
|
|
23
|
-
const DOCKER_API_VERSION = resolveDockerApiVersion();
|
|
24
46
|
export class WorkerProvisioningManager {
|
|
25
47
|
deps;
|
|
26
48
|
backend;
|
|
@@ -28,6 +50,12 @@ export class WorkerProvisioningManager {
|
|
|
28
50
|
reconcilePromise = null;
|
|
29
51
|
reconcileQueued = false;
|
|
30
52
|
stopped = false;
|
|
53
|
+
// Phase 2.1 (design 2.3, switch step 2): while a team profile switch drains
|
|
54
|
+
// and archives the old team, the periodic reconcile must not fight the
|
|
55
|
+
// drain by launching replacement workers for the outgoing profile's
|
|
56
|
+
// pending tasks. Suspended reconcile calls return immediately; it is
|
|
57
|
+
// lifted before the new profile's warmup so normal operation resumes.
|
|
58
|
+
reconcileSuspended = false;
|
|
31
59
|
constructor(deps) {
|
|
32
60
|
this.deps = deps;
|
|
33
61
|
this.backend = createProvisionerBackend(deps.config, deps.logger);
|
|
@@ -81,7 +109,10 @@ export class WorkerProvisioningManager {
|
|
|
81
109
|
reason: `Provisioned worker ${workerId} expected role ${record.role}, got ${role}`,
|
|
82
110
|
};
|
|
83
111
|
}
|
|
84
|
-
|
|
112
|
+
// Issue #255 P0-1: constant-time equality. Semantics unchanged (old
|
|
113
|
+
// PRNG-era tokens in upgraded TeamStates still match their own value);
|
|
114
|
+
// only the timing side channel of `!==` goes away.
|
|
115
|
+
if (!launchToken || !secretsEqual(launchToken, record.launchToken)) {
|
|
85
116
|
return {
|
|
86
117
|
ok: false,
|
|
87
118
|
managed: true,
|
|
@@ -148,8 +179,12 @@ export class WorkerProvisioningManager {
|
|
|
148
179
|
this.deps.logger.info(`Provisioner: terminating managed worker ${workerId} (${reason})`);
|
|
149
180
|
await this.terminateManagedWorker(workerId, reason, "terminated");
|
|
150
181
|
}
|
|
182
|
+
/** Phase 2.1: suspend/resume the reconcile loop during a team profile switch. */
|
|
183
|
+
setReconcileSuspended(suspended) {
|
|
184
|
+
this.reconcileSuspended = suspended;
|
|
185
|
+
}
|
|
151
186
|
async requestReconcile(reason) {
|
|
152
|
-
if (!this.backend || this.stopped) {
|
|
187
|
+
if (!this.backend || this.stopped || this.reconcileSuspended) {
|
|
153
188
|
return;
|
|
154
189
|
}
|
|
155
190
|
if (this.reconcilePromise) {
|
|
@@ -235,6 +270,20 @@ export class WorkerProvisioningManager {
|
|
|
235
270
|
});
|
|
236
271
|
this.deps.logger.warn(`Provisioner: startup readiness degraded: ${failureDetails}`);
|
|
237
272
|
}
|
|
273
|
+
/**
|
|
274
|
+
* Phase 2.1 (design 2.3, switch step 5): warm the new profile's warmupRoles
|
|
275
|
+
* through the standard launch path after a profile switch. Dispatches the
|
|
276
|
+
* launches (prerequisites + ensureWarmWorkersForRoles); the workers then
|
|
277
|
+
* register asynchronously exactly like a cold start, so readiness tracking
|
|
278
|
+
* (startupReadiness polling / reconcile) covers the rest.
|
|
279
|
+
*/
|
|
280
|
+
async warmRolesForTeamSwitch(roles, reason) {
|
|
281
|
+
if (!this.backend || this.stopped) {
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
await this.ensureStartupProvisioningPrerequisites();
|
|
285
|
+
await this.ensureWarmWorkersForRoles(roles, reason);
|
|
286
|
+
}
|
|
238
287
|
async stop() {
|
|
239
288
|
if (!this.backend) {
|
|
240
289
|
return;
|
|
@@ -302,7 +351,7 @@ export class WorkerProvisioningManager {
|
|
|
302
351
|
if (configured.length > 0) {
|
|
303
352
|
return [...new Set(configured)];
|
|
304
353
|
}
|
|
305
|
-
return [
|
|
354
|
+
return [getActiveDefaultRole()];
|
|
306
355
|
}
|
|
307
356
|
async ensureStartupProvisioningPrerequisites() {
|
|
308
357
|
await ensureWritableDirectory(resolveTeamClawAgentWorkspaceRootDir());
|
|
@@ -423,7 +472,10 @@ export class WorkerProvisioningManager {
|
|
|
423
472
|
return;
|
|
424
473
|
}
|
|
425
474
|
const workerId = `provisioned-${role}-${generateId()}`;
|
|
426
|
-
|
|
475
|
+
// Issue #255 P0-1: 256-bit CSPRNG token (see generateLaunchToken) -
|
|
476
|
+
// replaces the old two-generateId construction whose PRNG-derived
|
|
477
|
+
// fragments made tokens predictable from observed output.
|
|
478
|
+
const launchToken = generateLaunchToken();
|
|
427
479
|
const controllerUrl = this.resolveControllerUrl();
|
|
428
480
|
const requiresDedicatedHostPorts = requiresDedicatedHostPortsForProvisioner(this.backend.type, this.deps.config);
|
|
429
481
|
const workerPort = requiresDedicatedHostPorts
|
|
@@ -542,7 +594,7 @@ export class WorkerProvisioningManager {
|
|
|
542
594
|
getProvisionableRoles(state) {
|
|
543
595
|
const roleIds = new Set(this.deps.config.workerProvisioningRoles.length > 0
|
|
544
596
|
? this.deps.config.workerProvisioningRoles
|
|
545
|
-
:
|
|
597
|
+
: getActiveRoleIds());
|
|
546
598
|
if (!state) {
|
|
547
599
|
return [...roleIds];
|
|
548
600
|
}
|
|
@@ -661,443 +713,6 @@ export class WorkerProvisioningManager {
|
|
|
661
713
|
return changed;
|
|
662
714
|
}
|
|
663
715
|
}
|
|
664
|
-
class ProcessProvisioner {
|
|
665
|
-
type = "process";
|
|
666
|
-
logger;
|
|
667
|
-
processByWorkerId = new Map();
|
|
668
|
-
baseDirPromise;
|
|
669
|
-
constructor(logger) {
|
|
670
|
-
this.logger = logger;
|
|
671
|
-
const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
|
|
672
|
-
this.baseDirPromise = fs.mkdir(provisionedRoot, { recursive: true })
|
|
673
|
-
.then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
|
|
674
|
-
}
|
|
675
|
-
async launch(spec) {
|
|
676
|
-
const baseDir = await this.baseDirPromise;
|
|
677
|
-
const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
|
|
678
|
-
const stateDir = path.join(runtimeHomeDir, ".openclaw");
|
|
679
|
-
const configPath = path.join(stateDir, "openclaw.json");
|
|
680
|
-
await fs.mkdir(stateDir, { recursive: true });
|
|
681
|
-
await prepareProcessRuntimeExtensions(stateDir);
|
|
682
|
-
await fs.writeFile(configPath, spec.configJson, "utf8");
|
|
683
|
-
const gatewayEntrypoint = resolveGatewayEntrypoint();
|
|
684
|
-
const child = spawn(process.execPath, [
|
|
685
|
-
gatewayEntrypoint,
|
|
686
|
-
"gateway",
|
|
687
|
-
"--allow-unconfigured",
|
|
688
|
-
"--bind",
|
|
689
|
-
"loopback",
|
|
690
|
-
"--port",
|
|
691
|
-
String(spec.gatewayPort),
|
|
692
|
-
], {
|
|
693
|
-
cwd: path.dirname(gatewayEntrypoint),
|
|
694
|
-
env: {
|
|
695
|
-
...process.env,
|
|
696
|
-
...spec.env,
|
|
697
|
-
HOME: runtimeHomeDir,
|
|
698
|
-
OPENCLAW_HOME: runtimeHomeDir,
|
|
699
|
-
OPENCLAW_STATE_DIR: stateDir,
|
|
700
|
-
OPENCLAW_CONFIG_PATH: configPath,
|
|
701
|
-
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
702
|
-
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
703
|
-
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
704
|
-
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
705
|
-
},
|
|
706
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
707
|
-
});
|
|
708
|
-
this.processByWorkerId.set(spec.workerId, child);
|
|
709
|
-
attachChildLogs(child, this.logger, `ProvisionedWorker[${spec.role}]`);
|
|
710
|
-
child.on("exit", (code, signal) => {
|
|
711
|
-
this.processByWorkerId.delete(spec.workerId);
|
|
712
|
-
this.logger.info(`Provisioner: process worker ${spec.workerId} exited (code=${String(code)}, signal=${String(signal)})`);
|
|
713
|
-
});
|
|
714
|
-
return {
|
|
715
|
-
instanceId: child.pid ? `pid:${child.pid}` : undefined,
|
|
716
|
-
instanceName: spec.workerId,
|
|
717
|
-
runtimeHomeDir,
|
|
718
|
-
};
|
|
719
|
-
}
|
|
720
|
-
async terminate(record) {
|
|
721
|
-
const child = this.processByWorkerId.get(record.workerId);
|
|
722
|
-
if (child) {
|
|
723
|
-
await stopChildProcess(child);
|
|
724
|
-
this.processByWorkerId.delete(record.workerId);
|
|
725
|
-
}
|
|
726
|
-
else if (record.instanceId?.startsWith("pid:")) {
|
|
727
|
-
const pid = Number(record.instanceId.slice("pid:".length));
|
|
728
|
-
if (Number.isFinite(pid) && pid > 0) {
|
|
729
|
-
try {
|
|
730
|
-
process.kill(pid, "SIGTERM");
|
|
731
|
-
}
|
|
732
|
-
catch {
|
|
733
|
-
// ignore
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
if (record.runtimeHomeDir) {
|
|
738
|
-
await fs.rm(record.runtimeHomeDir, { recursive: true, force: true }).catch(() => {
|
|
739
|
-
// ignore
|
|
740
|
-
});
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
async stop() {
|
|
744
|
-
for (const child of this.processByWorkerId.values()) {
|
|
745
|
-
await stopChildProcess(child).catch(() => {
|
|
746
|
-
// ignore
|
|
747
|
-
});
|
|
748
|
-
}
|
|
749
|
-
this.processByWorkerId.clear();
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
class DockerProvisioner {
|
|
753
|
-
type = "docker";
|
|
754
|
-
config;
|
|
755
|
-
logger;
|
|
756
|
-
client;
|
|
757
|
-
constructor(config, logger) {
|
|
758
|
-
this.config = config;
|
|
759
|
-
this.logger = logger;
|
|
760
|
-
this.client = new DockerApiClient();
|
|
761
|
-
}
|
|
762
|
-
async launch(spec) {
|
|
763
|
-
if (!this.config.workerProvisioningImage) {
|
|
764
|
-
throw new Error("workerProvisioningImage is required for docker provisioning");
|
|
765
|
-
}
|
|
766
|
-
const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
|
|
767
|
-
const env = {
|
|
768
|
-
...spec.env,
|
|
769
|
-
HOME: "/home/node",
|
|
770
|
-
OPENCLAW_HOME: "/home/node",
|
|
771
|
-
OPENCLAW_STATE_DIR: "/home/node/.openclaw",
|
|
772
|
-
OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
|
|
773
|
-
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
774
|
-
TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
|
|
775
|
-
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
776
|
-
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
777
|
-
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
778
|
-
};
|
|
779
|
-
// When workers share a Docker network with the controller container, advertise
|
|
780
|
-
// the container name and internal worker port so sibling containers can reach it
|
|
781
|
-
// directly. When the controller runs on the host, fall back to publishing a host
|
|
782
|
-
// port and advertising localhost for host-side callbacks.
|
|
783
|
-
const usePortPublishing = spec.publishedHostPort !== undefined;
|
|
784
|
-
if (this.config.workerProvisioningDockerNetwork) {
|
|
785
|
-
env.TEAMCLAW_ADVERTISE_HOST = instanceName;
|
|
786
|
-
env.TEAMCLAW_ADVERTISE_PORT = String(spec.workerPort);
|
|
787
|
-
}
|
|
788
|
-
else if (usePortPublishing) {
|
|
789
|
-
env.TEAMCLAW_ADVERTISE_HOST = "localhost";
|
|
790
|
-
env.TEAMCLAW_ADVERTISE_PORT = String(spec.publishedHostPort);
|
|
791
|
-
}
|
|
792
|
-
const hostConfig = {
|
|
793
|
-
Binds: buildDockerBinds(this.config),
|
|
794
|
-
NetworkMode: this.config.workerProvisioningDockerNetwork || undefined,
|
|
795
|
-
};
|
|
796
|
-
if (usePortPublishing) {
|
|
797
|
-
hostConfig.PortBindings = {
|
|
798
|
-
[`${spec.workerPort}/tcp`]: [{ HostPort: String(spec.publishedHostPort) }],
|
|
799
|
-
};
|
|
800
|
-
}
|
|
801
|
-
const containerConfig = {
|
|
802
|
-
Image: this.config.workerProvisioningImage,
|
|
803
|
-
Cmd: ["sh", "-lc", buildContainerBootstrapScript()],
|
|
804
|
-
Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
|
|
805
|
-
User: "root",
|
|
806
|
-
Labels: {
|
|
807
|
-
"teamclaw.managed": "true",
|
|
808
|
-
"teamclaw.team": this.config.teamName,
|
|
809
|
-
"teamclaw.role": spec.role,
|
|
810
|
-
"teamclaw.worker_id": spec.workerId,
|
|
811
|
-
},
|
|
812
|
-
HostConfig: hostConfig,
|
|
813
|
-
};
|
|
814
|
-
if (usePortPublishing) {
|
|
815
|
-
containerConfig.ExposedPorts = { [`${spec.workerPort}/tcp`]: {} };
|
|
816
|
-
}
|
|
817
|
-
const response = await this.client.requestJson("POST", `/containers/create?name=${encodeURIComponent(instanceName)}`, containerConfig, [201]);
|
|
818
|
-
const instanceId = typeof response.Id === "string" ? response.Id : undefined;
|
|
819
|
-
if (!instanceId) {
|
|
820
|
-
throw new Error("Docker create did not return a container ID");
|
|
821
|
-
}
|
|
822
|
-
await this.client.requestVoid("POST", `/containers/${instanceId}/start`, undefined, [204]);
|
|
823
|
-
this.logger.info(`Provisioner: started docker worker container ${instanceName} (${instanceId})`);
|
|
824
|
-
return {
|
|
825
|
-
instanceId,
|
|
826
|
-
instanceName,
|
|
827
|
-
};
|
|
828
|
-
}
|
|
829
|
-
async terminate(record) {
|
|
830
|
-
const target = record.instanceId || record.instanceName;
|
|
831
|
-
if (!target) {
|
|
832
|
-
return;
|
|
833
|
-
}
|
|
834
|
-
await this.client.requestVoid("DELETE", `/containers/${target}?force=1`, undefined, [204, 404]);
|
|
835
|
-
}
|
|
836
|
-
}
|
|
837
|
-
/**
|
|
838
|
-
* Lightweight Kubernetes API client using in-cluster service account or
|
|
839
|
-
* kubeconfig for out-of-cluster (via kubectl proxy or direct API).
|
|
840
|
-
* Avoids requiring kubectl binary in the container image.
|
|
841
|
-
*/
|
|
842
|
-
class K8sApiClient {
|
|
843
|
-
logger;
|
|
844
|
-
token;
|
|
845
|
-
caCert;
|
|
846
|
-
apiServer;
|
|
847
|
-
contextArgs;
|
|
848
|
-
constructor(context, logger) {
|
|
849
|
-
this.logger = logger;
|
|
850
|
-
this.contextArgs = context;
|
|
851
|
-
// In-cluster detection: K8s injects these env vars and mounts SA token
|
|
852
|
-
const host = process.env.KUBERNETES_SERVICE_HOST;
|
|
853
|
-
const port = process.env.KUBERNETES_SERVICE_PORT;
|
|
854
|
-
if (host && port) {
|
|
855
|
-
this.apiServer = `https://${host}:${port}`;
|
|
856
|
-
try {
|
|
857
|
-
const fs = require("node:fs");
|
|
858
|
-
this.token = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8").trim();
|
|
859
|
-
this.caCert = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt");
|
|
860
|
-
}
|
|
861
|
-
catch {
|
|
862
|
-
logger.warn("K8sApiClient: in-cluster but cannot read service account token — falling back to kubectl");
|
|
863
|
-
}
|
|
864
|
-
}
|
|
865
|
-
else {
|
|
866
|
-
// Out-of-cluster: delegate to kubectl
|
|
867
|
-
this.apiServer = "";
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
get inCluster() {
|
|
871
|
-
return Boolean(this.apiServer && this.token);
|
|
872
|
-
}
|
|
873
|
-
async createPod(namespace, manifest) {
|
|
874
|
-
if (this.inCluster) {
|
|
875
|
-
await this.apiRequest("POST", `/api/v1/namespaces/${namespace}/pods`, manifest, [200, 201]);
|
|
876
|
-
}
|
|
877
|
-
else {
|
|
878
|
-
await runCommand("kubectl", [
|
|
879
|
-
...buildKubectlContextArgs(this.contextArgs),
|
|
880
|
-
"apply", "-f", "-",
|
|
881
|
-
], JSON.stringify(manifest));
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
async deletePod(namespace, podName) {
|
|
885
|
-
if (this.inCluster) {
|
|
886
|
-
await this.apiRequest("DELETE", `/api/v1/namespaces/${namespace}/pods/${podName}?gracePeriodSeconds=0`, undefined, [200, 202, 404]);
|
|
887
|
-
}
|
|
888
|
-
else {
|
|
889
|
-
await runCommand("kubectl", [
|
|
890
|
-
...buildKubectlContextArgs(this.contextArgs),
|
|
891
|
-
"-n", namespace,
|
|
892
|
-
"delete", "pod", podName,
|
|
893
|
-
"--ignore-not-found=true", "--grace-period=0", "--force",
|
|
894
|
-
]);
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
async apiRequest(method, apiPath, body, okStatuses) {
|
|
898
|
-
const payload = body !== undefined ? JSON.stringify(body) : undefined;
|
|
899
|
-
return new Promise((resolve, reject) => {
|
|
900
|
-
const url = new URL(apiPath, this.apiServer);
|
|
901
|
-
const options = {
|
|
902
|
-
method,
|
|
903
|
-
hostname: url.hostname,
|
|
904
|
-
port: url.port,
|
|
905
|
-
path: url.pathname + url.search,
|
|
906
|
-
headers: {
|
|
907
|
-
"Authorization": `Bearer ${this.token}`,
|
|
908
|
-
...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}),
|
|
909
|
-
},
|
|
910
|
-
...(this.caCert ? { ca: this.caCert } : { rejectUnauthorized: false }),
|
|
911
|
-
};
|
|
912
|
-
const req = https.request(options, (res) => {
|
|
913
|
-
let data = "";
|
|
914
|
-
res.on("data", (chunk) => { data += chunk; });
|
|
915
|
-
res.on("end", () => {
|
|
916
|
-
if (okStatuses.includes(res.statusCode ?? 0)) {
|
|
917
|
-
resolve(data);
|
|
918
|
-
}
|
|
919
|
-
else {
|
|
920
|
-
reject(new Error(`K8s API ${method} ${apiPath} returned ${res.statusCode}: ${data.slice(0, 500)}`));
|
|
921
|
-
}
|
|
922
|
-
});
|
|
923
|
-
});
|
|
924
|
-
req.on("error", reject);
|
|
925
|
-
if (payload)
|
|
926
|
-
req.write(payload);
|
|
927
|
-
req.end();
|
|
928
|
-
});
|
|
929
|
-
}
|
|
930
|
-
}
|
|
931
|
-
class KubernetesProvisioner {
|
|
932
|
-
type = "kubernetes";
|
|
933
|
-
config;
|
|
934
|
-
logger;
|
|
935
|
-
k8sApi;
|
|
936
|
-
constructor(config, logger) {
|
|
937
|
-
this.config = config;
|
|
938
|
-
this.logger = logger;
|
|
939
|
-
this.k8sApi = new K8sApiClient(config.workerProvisioningKubernetesContext, logger);
|
|
940
|
-
}
|
|
941
|
-
async launch(spec) {
|
|
942
|
-
if (!this.config.workerProvisioningImage) {
|
|
943
|
-
throw new Error("workerProvisioningImage is required for kubernetes provisioning");
|
|
944
|
-
}
|
|
945
|
-
const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
|
|
946
|
-
const ns = this.config.workerProvisioningKubernetesNamespace;
|
|
947
|
-
const env = {
|
|
948
|
-
...spec.env,
|
|
949
|
-
HOME: "/home/node",
|
|
950
|
-
OPENCLAW_HOME: "/home/node",
|
|
951
|
-
OPENCLAW_STATE_DIR: "/home/node/.openclaw",
|
|
952
|
-
OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
|
|
953
|
-
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
954
|
-
TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
|
|
955
|
-
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
956
|
-
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
957
|
-
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
958
|
-
};
|
|
959
|
-
const workspaceRoot = this.config.workerProvisioningWorkspaceRoot;
|
|
960
|
-
const hasPersistentWorkspace = Boolean(workspaceRoot && this.config.workerProvisioningKubernetesWorkspacePersistentVolumeClaim);
|
|
961
|
-
const imagePullSecrets = this.config.workerProvisioningKubernetesImagePullSecrets
|
|
962
|
-
.map((name) => name.trim())
|
|
963
|
-
.filter((name) => name.length > 0)
|
|
964
|
-
.map((name) => ({ name }));
|
|
965
|
-
const manifest = {
|
|
966
|
-
apiVersion: "v1",
|
|
967
|
-
kind: "Pod",
|
|
968
|
-
metadata: {
|
|
969
|
-
name: instanceName,
|
|
970
|
-
namespace: ns,
|
|
971
|
-
labels: {
|
|
972
|
-
app: "teamclaw-worker",
|
|
973
|
-
"teamclaw.managed": "true",
|
|
974
|
-
"teamclaw.team": sanitizeName(this.config.teamName, 40),
|
|
975
|
-
"teamclaw.role": sanitizeName(spec.role, 40),
|
|
976
|
-
...this.config.workerProvisioningKubernetesLabels,
|
|
977
|
-
},
|
|
978
|
-
annotations: {
|
|
979
|
-
...this.config.workerProvisioningKubernetesAnnotations,
|
|
980
|
-
},
|
|
981
|
-
},
|
|
982
|
-
spec: {
|
|
983
|
-
restartPolicy: "Never",
|
|
984
|
-
hostname: buildManagedHostname(this.config.teamName, spec.role, spec.workerId),
|
|
985
|
-
serviceAccountName: this.config.workerProvisioningKubernetesServiceAccount || undefined,
|
|
986
|
-
imagePullSecrets: imagePullSecrets.length > 0 ? imagePullSecrets : undefined,
|
|
987
|
-
securityContext: hasPersistentWorkspace
|
|
988
|
-
? {
|
|
989
|
-
runAsUser: 1000,
|
|
990
|
-
runAsGroup: 1000,
|
|
991
|
-
fsGroup: 1000,
|
|
992
|
-
}
|
|
993
|
-
: undefined,
|
|
994
|
-
volumes: hasPersistentWorkspace
|
|
995
|
-
? [
|
|
996
|
-
{
|
|
997
|
-
name: "workspace",
|
|
998
|
-
persistentVolumeClaim: {
|
|
999
|
-
claimName: this.config.workerProvisioningKubernetesWorkspacePersistentVolumeClaim,
|
|
1000
|
-
},
|
|
1001
|
-
},
|
|
1002
|
-
]
|
|
1003
|
-
: undefined,
|
|
1004
|
-
containers: [
|
|
1005
|
-
{
|
|
1006
|
-
name: "worker",
|
|
1007
|
-
image: this.config.workerProvisioningImage,
|
|
1008
|
-
command: ["sh", "-lc"],
|
|
1009
|
-
args: [buildContainerBootstrapScript()],
|
|
1010
|
-
env: Object.entries(env).map(([name, value]) => ({ name, value })),
|
|
1011
|
-
volumeMounts: hasPersistentWorkspace
|
|
1012
|
-
? [
|
|
1013
|
-
{
|
|
1014
|
-
name: "workspace",
|
|
1015
|
-
mountPath: workspaceRoot,
|
|
1016
|
-
},
|
|
1017
|
-
]
|
|
1018
|
-
: undefined,
|
|
1019
|
-
},
|
|
1020
|
-
],
|
|
1021
|
-
},
|
|
1022
|
-
};
|
|
1023
|
-
await this.k8sApi.createPod(ns, manifest);
|
|
1024
|
-
this.logger.info(`Provisioner: applied kubernetes pod ${instanceName}`);
|
|
1025
|
-
return {
|
|
1026
|
-
instanceId: instanceName,
|
|
1027
|
-
instanceName,
|
|
1028
|
-
};
|
|
1029
|
-
}
|
|
1030
|
-
async terminate(record) {
|
|
1031
|
-
const podName = record.instanceName || record.instanceId;
|
|
1032
|
-
if (!podName) {
|
|
1033
|
-
return;
|
|
1034
|
-
}
|
|
1035
|
-
const ns = this.config.workerProvisioningKubernetesNamespace;
|
|
1036
|
-
await this.k8sApi.deletePod(ns, podName);
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
class DockerApiClient {
|
|
1040
|
-
endpoint;
|
|
1041
|
-
constructor() {
|
|
1042
|
-
this.endpoint = resolveDockerEndpoint();
|
|
1043
|
-
}
|
|
1044
|
-
async requestJson(method, requestPath, body, okStatuses = [200]) {
|
|
1045
|
-
const response = await this.request(method, requestPath, body, okStatuses);
|
|
1046
|
-
if (!response.body) {
|
|
1047
|
-
return {};
|
|
1048
|
-
}
|
|
1049
|
-
return JSON.parse(response.body);
|
|
1050
|
-
}
|
|
1051
|
-
async requestVoid(method, requestPath, body, okStatuses = [200]) {
|
|
1052
|
-
await this.request(method, requestPath, body, okStatuses);
|
|
1053
|
-
}
|
|
1054
|
-
async request(method, requestPath, body, okStatuses) {
|
|
1055
|
-
const payload = body === undefined ? undefined : JSON.stringify(body);
|
|
1056
|
-
// Prefer the daemon's negotiated default unless the operator pins a version explicitly.
|
|
1057
|
-
const finalPath = DOCKER_API_VERSION ? `/${DOCKER_API_VERSION}${requestPath}` : requestPath;
|
|
1058
|
-
return await new Promise((resolve, reject) => {
|
|
1059
|
-
const transport = this.endpoint.protocol === "https:" ? https : http;
|
|
1060
|
-
const req = transport.request({
|
|
1061
|
-
method,
|
|
1062
|
-
socketPath: this.endpoint.socketPath,
|
|
1063
|
-
hostname: this.endpoint.hostname,
|
|
1064
|
-
port: this.endpoint.port,
|
|
1065
|
-
path: finalPath,
|
|
1066
|
-
headers: payload
|
|
1067
|
-
? {
|
|
1068
|
-
"Content-Type": "application/json",
|
|
1069
|
-
"Content-Length": Buffer.byteLength(payload),
|
|
1070
|
-
}
|
|
1071
|
-
: undefined,
|
|
1072
|
-
}, (res) => {
|
|
1073
|
-
const chunks = [];
|
|
1074
|
-
res.on("data", (chunk) => chunks.push(chunk));
|
|
1075
|
-
res.on("end", () => {
|
|
1076
|
-
const text = Buffer.concat(chunks).toString("utf8");
|
|
1077
|
-
const status = res.statusCode ?? 500;
|
|
1078
|
-
if (!okStatuses.includes(status)) {
|
|
1079
|
-
const message = extractDockerErrorMessage(text) || `Docker API ${method} ${requestPath} failed with ${status}`;
|
|
1080
|
-
reject(new Error(message));
|
|
1081
|
-
return;
|
|
1082
|
-
}
|
|
1083
|
-
resolve({ status, body: text });
|
|
1084
|
-
});
|
|
1085
|
-
});
|
|
1086
|
-
req.on("error", reject);
|
|
1087
|
-
if (payload) {
|
|
1088
|
-
req.write(payload);
|
|
1089
|
-
}
|
|
1090
|
-
req.end();
|
|
1091
|
-
});
|
|
1092
|
-
}
|
|
1093
|
-
}
|
|
1094
|
-
function resolveDockerApiVersion() {
|
|
1095
|
-
const configured = process.env.DOCKER_API_VERSION?.trim();
|
|
1096
|
-
if (!configured) {
|
|
1097
|
-
return null;
|
|
1098
|
-
}
|
|
1099
|
-
return configured.startsWith("v") ? configured : `v${configured}`;
|
|
1100
|
-
}
|
|
1101
716
|
function createProvisionerBackend(config, logger) {
|
|
1102
717
|
switch (config.workerProvisioningType) {
|
|
1103
718
|
case "process":
|
|
@@ -1111,125 +726,6 @@ function createProvisionerBackend(config, logger) {
|
|
|
1111
726
|
return null;
|
|
1112
727
|
}
|
|
1113
728
|
}
|
|
1114
|
-
export function buildProvisionedWorkerConfig(baseConfig, controllerConfig, spec) {
|
|
1115
|
-
const config = cloneJson(baseConfig);
|
|
1116
|
-
delete config.channels;
|
|
1117
|
-
const agents = ensureRecord(config.agents);
|
|
1118
|
-
const agentDefaults = ensureRecord(agents.defaults);
|
|
1119
|
-
delete agentDefaults.repoRoot;
|
|
1120
|
-
if (spec.workspaceDir) {
|
|
1121
|
-
agentDefaults.workspace = spec.workspaceDir;
|
|
1122
|
-
}
|
|
1123
|
-
else {
|
|
1124
|
-
delete agentDefaults.workspace;
|
|
1125
|
-
}
|
|
1126
|
-
// The host controller may run a newer openclaw that persists the keyed
|
|
1127
|
-
// agents.entries schema (e.g. agents.entries.teamclaw.model written by the
|
|
1128
|
-
// model-configuration feature). Provisioned workers can run an older
|
|
1129
|
-
// openclaw that rejects unknown agents keys ("Unrecognized key: entries"),
|
|
1130
|
-
// so fold the teamclaw entry's model back into the legacy
|
|
1131
|
-
// agents.defaults.model and drop the entries map. New-schema workers also
|
|
1132
|
-
// accept agents.defaults, keeping the folded config compatible both ways.
|
|
1133
|
-
const agentsRecord = agents;
|
|
1134
|
-
if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
|
|
1135
|
-
const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
|
|
1136
|
-
if (entryModel && !agentDefaults.model) {
|
|
1137
|
-
agentDefaults.model = entryModel;
|
|
1138
|
-
}
|
|
1139
|
-
// Container backends may run older openclaw runtimes that reject the
|
|
1140
|
-
// keyed agents schema ("Unrecognized key: entries") - fold down to
|
|
1141
|
-
// legacy defaults there. Process workers share the controller's own
|
|
1142
|
-
// runtime, which REQUIRES at least one entry ("agents.entries must
|
|
1143
|
-
// contain at least one configured agent" crash-loop, exit 78, observed
|
|
1144
|
-
// 2026-11-03 when entries was deleted unconditionally) - keep only the
|
|
1145
|
-
// teamclaw worker entry for them.
|
|
1146
|
-
const containerized = controllerConfig.workerProvisioningType === "docker" ||
|
|
1147
|
-
controllerConfig.workerProvisioningType === "kubernetes";
|
|
1148
|
-
if (containerized) {
|
|
1149
|
-
delete agentsRecord.entries;
|
|
1150
|
-
}
|
|
1151
|
-
else {
|
|
1152
|
-
agentsRecord.entries = {
|
|
1153
|
-
[TEAMCLAW_AGENT_ID]: agentsRecord.entries[TEAMCLAW_AGENT_ID] ?? {},
|
|
1154
|
-
};
|
|
1155
|
-
// Pruning entries can dangle defaults.heartbeat.agentId /
|
|
1156
|
-
// defaults.systemAgent.agentId ("main" no longer exists in the worker
|
|
1157
|
-
// config) - remap any dangling agentId reference to the surviving
|
|
1158
|
-
// teamclaw entry.
|
|
1159
|
-
for (const sectionKey of Object.keys(agentDefaults)) {
|
|
1160
|
-
const section = agentDefaults[sectionKey];
|
|
1161
|
-
if (section &&
|
|
1162
|
-
typeof section === "object" &&
|
|
1163
|
-
typeof section.agentId === "string" &&
|
|
1164
|
-
!agentsRecord.entries[section.agentId]) {
|
|
1165
|
-
section.agentId = TEAMCLAW_AGENT_ID;
|
|
1166
|
-
}
|
|
1167
|
-
}
|
|
1168
|
-
}
|
|
1169
|
-
}
|
|
1170
|
-
agents.defaults = agentDefaults;
|
|
1171
|
-
config.agents = agents;
|
|
1172
|
-
const gateway = ensureRecord(config.gateway);
|
|
1173
|
-
gateway.mode = "local";
|
|
1174
|
-
// Workers running inside Docker/K8s containers must bind on all
|
|
1175
|
-
// interfaces so the controller (in a sibling container) can reach them.
|
|
1176
|
-
gateway.bind =
|
|
1177
|
-
controllerConfig.workerProvisioningType === "docker" ||
|
|
1178
|
-
controllerConfig.workerProvisioningType === "kubernetes"
|
|
1179
|
-
? "lan"
|
|
1180
|
-
: "loopback";
|
|
1181
|
-
gateway.port = spec.gatewayPort;
|
|
1182
|
-
delete gateway.remote;
|
|
1183
|
-
config.gateway = gateway;
|
|
1184
|
-
const plugins = ensureRecord(config.plugins);
|
|
1185
|
-
plugins.enabled = true;
|
|
1186
|
-
if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
|
|
1187
|
-
delete plugins.load;
|
|
1188
|
-
}
|
|
1189
|
-
const entries = ensureRecord(plugins.entries);
|
|
1190
|
-
const teamclawEntry = ensureRecord(entries.teamclaw);
|
|
1191
|
-
teamclawEntry.enabled = true;
|
|
1192
|
-
const teamclawConfig = ensureRecord(teamclawEntry.config);
|
|
1193
|
-
teamclawConfig.mode = "worker";
|
|
1194
|
-
teamclawConfig.processModel = "multi";
|
|
1195
|
-
teamclawConfig.role = spec.role;
|
|
1196
|
-
teamclawConfig.port = spec.workerPort;
|
|
1197
|
-
teamclawConfig.controllerUrl = spec.controllerUrl;
|
|
1198
|
-
teamclawConfig.teamName = controllerConfig.teamName;
|
|
1199
|
-
teamclawConfig.heartbeatIntervalMs = controllerConfig.heartbeatIntervalMs;
|
|
1200
|
-
teamclawConfig.taskTimeoutMs = controllerConfig.taskTimeoutMs;
|
|
1201
|
-
teamclawConfig.gitEnabled = controllerConfig.gitEnabled;
|
|
1202
|
-
teamclawConfig.gitRemoteUrl = controllerConfig.gitRemoteUrl;
|
|
1203
|
-
teamclawConfig.gitDefaultBranch = controllerConfig.gitDefaultBranch;
|
|
1204
|
-
teamclawConfig.gitAuthorName = controllerConfig.gitAuthorName;
|
|
1205
|
-
teamclawConfig.gitAuthorEmail = controllerConfig.gitAuthorEmail;
|
|
1206
|
-
teamclawConfig.workerProvisioningType = "none";
|
|
1207
|
-
teamclawConfig.workerProvisioningControllerUrl = "";
|
|
1208
|
-
teamclawConfig.workerProvisioningRoles = [];
|
|
1209
|
-
teamclawConfig.workerProvisioningMinPerRole = 0;
|
|
1210
|
-
teamclawConfig.workerProvisioningMaxPerRole = 10;
|
|
1211
|
-
teamclawConfig.workerProvisioningIdleTtlMs = controllerConfig.workerProvisioningIdleTtlMs;
|
|
1212
|
-
teamclawConfig.workerProvisioningStartupTimeoutMs = controllerConfig.workerProvisioningStartupTimeoutMs;
|
|
1213
|
-
teamclawConfig.workerProvisioningImage = "";
|
|
1214
|
-
teamclawConfig.workerProvisioningPassEnv = [];
|
|
1215
|
-
teamclawConfig.workerProvisioningExtraEnv = {};
|
|
1216
|
-
teamclawConfig.workerProvisioningDockerNetwork = "";
|
|
1217
|
-
teamclawConfig.workerProvisioningDockerMounts = [];
|
|
1218
|
-
teamclawConfig.workerProvisioningWorkspaceRoot = "";
|
|
1219
|
-
teamclawConfig.workerProvisioningDockerWorkspaceVolume = "";
|
|
1220
|
-
teamclawConfig.workerProvisioningKubernetesNamespace = "default";
|
|
1221
|
-
teamclawConfig.workerProvisioningKubernetesContext = "";
|
|
1222
|
-
teamclawConfig.workerProvisioningKubernetesServiceAccount = "";
|
|
1223
|
-
teamclawConfig.workerProvisioningKubernetesImagePullSecrets = [];
|
|
1224
|
-
teamclawConfig.workerProvisioningKubernetesWorkspacePersistentVolumeClaim = "";
|
|
1225
|
-
teamclawConfig.workerProvisioningKubernetesLabels = {};
|
|
1226
|
-
teamclawConfig.workerProvisioningKubernetesAnnotations = {};
|
|
1227
|
-
teamclawEntry.config = teamclawConfig;
|
|
1228
|
-
entries.teamclaw = teamclawEntry;
|
|
1229
|
-
plugins.entries = entries;
|
|
1230
|
-
config.plugins = plugins;
|
|
1231
|
-
return config;
|
|
1232
|
-
}
|
|
1233
729
|
function ensureProvisioningState(state) {
|
|
1234
730
|
if (!state.provisioning || typeof state.provisioning !== "object") {
|
|
1235
731
|
state.provisioning = { workers: {} };
|
|
@@ -1245,158 +741,6 @@ async function ensureWritableDirectory(dir) {
|
|
|
1245
741
|
await fs.writeFile(probePath, "ok\n", "utf8");
|
|
1246
742
|
await fs.rm(probePath, { force: true });
|
|
1247
743
|
}
|
|
1248
|
-
function sleep(ms) {
|
|
1249
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1250
|
-
}
|
|
1251
|
-
async function loadOpenClawConfig(configPath) {
|
|
1252
|
-
const raw = await fs.readFile(configPath, "utf8");
|
|
1253
|
-
return parseLooseJsonObject(raw, configPath);
|
|
1254
|
-
}
|
|
1255
|
-
async function prepareProcessRuntimeExtensions(stateDir) {
|
|
1256
|
-
const runtimeExtensionsDir = path.join(stateDir, "extensions");
|
|
1257
|
-
const controllerExtensionsDir = path.join(path.dirname(resolveDefaultOpenClawConfigPath()), "extensions");
|
|
1258
|
-
if (await pathExists(controllerExtensionsDir)) {
|
|
1259
|
-
await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
|
|
1260
|
-
}
|
|
1261
|
-
else {
|
|
1262
|
-
await fs.mkdir(runtimeExtensionsDir, { recursive: true });
|
|
1263
|
-
// Baked-in images set TEAMCLAW_BAKED_IN=true and the legacy helper
|
|
1264
|
-
// returned "" for that case, so the symlink target was empty and
|
|
1265
|
-
// process workers fell back to resolving the plugin from their cwd
|
|
1266
|
-
// ("/app/dist/openclaw.plugin.json" not found → exit loop, k3s e2e
|
|
1267
|
-
// 2026-11-03). Probe the baked image layout instead: the controller
|
|
1268
|
-
// entrypoint (process.argv[1], e.g. /app/dist/index.js) sits below
|
|
1269
|
-
// the app root, where the runtime image ships
|
|
1270
|
-
// /app/extensions/teamclaw with its openclaw.plugin.json.
|
|
1271
|
-
const pluginRootDir = process.env.TEAMCLAW_BAKED_IN === "true"
|
|
1272
|
-
? await resolveBakedTeamClawPluginRootDir()
|
|
1273
|
-
: resolveCurrentTeamClawPluginRootDir();
|
|
1274
|
-
if (pluginRootDir) {
|
|
1275
|
-
await fs.symlink(pluginRootDir, path.join(runtimeExtensionsDir, "teamclaw"), "dir");
|
|
1276
|
-
}
|
|
1277
|
-
}
|
|
1278
|
-
await copyControllerAuthProfiles(stateDir);
|
|
1279
|
-
}
|
|
1280
|
-
async function copyControllerAuthProfiles(stateDir) {
|
|
1281
|
-
const candidateControllerStateDirs = [
|
|
1282
|
-
path.dirname(resolveDefaultOpenClawConfigPath()),
|
|
1283
|
-
resolveDefaultOpenClawStateDir(),
|
|
1284
|
-
];
|
|
1285
|
-
const candidateAuthProfilePaths = [
|
|
1286
|
-
path.join(resolveTeamClawAgentDir(), "auth-profiles.json"),
|
|
1287
|
-
path.join(resolveDefaultAgentDir(), "auth-profiles.json"),
|
|
1288
|
-
...candidateControllerStateDirs.flatMap((controllerStateDir) => [
|
|
1289
|
-
path.join(controllerStateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
|
|
1290
|
-
path.join(controllerStateDir, "agents", "main", "agent", "auth-profiles.json"),
|
|
1291
|
-
]),
|
|
1292
|
-
].filter((value, index, values) => values.indexOf(value) === index);
|
|
1293
|
-
let controllerAuthProfilesPath;
|
|
1294
|
-
for (const candidatePath of candidateAuthProfilePaths) {
|
|
1295
|
-
if (await pathExists(candidatePath)) {
|
|
1296
|
-
controllerAuthProfilesPath = candidatePath;
|
|
1297
|
-
break;
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
if (!controllerAuthProfilesPath) {
|
|
1301
|
-
return;
|
|
1302
|
-
}
|
|
1303
|
-
const runtimeAuthProfilePaths = [
|
|
1304
|
-
path.join(stateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
|
|
1305
|
-
path.join(stateDir, "agents", "main", "agent", "auth-profiles.json"),
|
|
1306
|
-
];
|
|
1307
|
-
for (const runtimeAuthProfilesPath of runtimeAuthProfilePaths) {
|
|
1308
|
-
await fs.mkdir(path.dirname(runtimeAuthProfilesPath), { recursive: true });
|
|
1309
|
-
await fs.copyFile(controllerAuthProfilesPath, runtimeAuthProfilesPath);
|
|
1310
|
-
}
|
|
1311
|
-
}
|
|
1312
|
-
function cloneJson(value) {
|
|
1313
|
-
return JSON.parse(JSON.stringify(value));
|
|
1314
|
-
}
|
|
1315
|
-
function requiresDedicatedHostPortsForProvisioner(provider, config) {
|
|
1316
|
-
if (provider === "process") {
|
|
1317
|
-
return true;
|
|
1318
|
-
}
|
|
1319
|
-
return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
|
|
1320
|
-
}
|
|
1321
|
-
function isDockerHostNetwork(networkMode) {
|
|
1322
|
-
return networkMode.trim().toLowerCase() === "host";
|
|
1323
|
-
}
|
|
1324
|
-
function extractDockerBindTarget(bind) {
|
|
1325
|
-
for (const part of bind.split(":").reverse()) {
|
|
1326
|
-
const trimmed = part.trim();
|
|
1327
|
-
if (trimmed.startsWith("/")) {
|
|
1328
|
-
return trimmed;
|
|
1329
|
-
}
|
|
1330
|
-
}
|
|
1331
|
-
return null;
|
|
1332
|
-
}
|
|
1333
|
-
function appendNoProxyEntries(env, controllerUrl) {
|
|
1334
|
-
const requiredEntries = resolveRequiredNoProxyEntries(controllerUrl);
|
|
1335
|
-
if (requiredEntries.length === 0) {
|
|
1336
|
-
return env;
|
|
1337
|
-
}
|
|
1338
|
-
const upperBase = env.NO_PROXY ?? process.env.NO_PROXY ?? process.env.no_proxy ?? "";
|
|
1339
|
-
const lowerBase = env.no_proxy ?? process.env.no_proxy ?? env.NO_PROXY ?? process.env.NO_PROXY ?? "";
|
|
1340
|
-
env.NO_PROXY = mergeNoProxyEntries(upperBase, requiredEntries);
|
|
1341
|
-
env.no_proxy = mergeNoProxyEntries(lowerBase, requiredEntries);
|
|
1342
|
-
return env;
|
|
1343
|
-
}
|
|
1344
|
-
function resolveRequiredNoProxyEntries(controllerUrl) {
|
|
1345
|
-
const required = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
1346
|
-
try {
|
|
1347
|
-
const host = new URL(controllerUrl).hostname.trim();
|
|
1348
|
-
if (host) {
|
|
1349
|
-
required.add(host);
|
|
1350
|
-
}
|
|
1351
|
-
}
|
|
1352
|
-
catch {
|
|
1353
|
-
// Ignore malformed controller URLs; worker registration will fail separately.
|
|
1354
|
-
}
|
|
1355
|
-
return Array.from(required);
|
|
1356
|
-
}
|
|
1357
|
-
function mergeNoProxyEntries(existing, requiredEntries) {
|
|
1358
|
-
const tokens = new Map();
|
|
1359
|
-
for (const entry of existing.split(",")) {
|
|
1360
|
-
const trimmed = entry.trim();
|
|
1361
|
-
if (!trimmed) {
|
|
1362
|
-
continue;
|
|
1363
|
-
}
|
|
1364
|
-
tokens.set(trimmed.toLowerCase(), trimmed);
|
|
1365
|
-
}
|
|
1366
|
-
for (const entry of requiredEntries) {
|
|
1367
|
-
const trimmed = entry.trim();
|
|
1368
|
-
if (!trimmed) {
|
|
1369
|
-
continue;
|
|
1370
|
-
}
|
|
1371
|
-
tokens.set(trimmed.toLowerCase(), trimmed);
|
|
1372
|
-
}
|
|
1373
|
-
return Array.from(tokens.values()).join(",");
|
|
1374
|
-
}
|
|
1375
|
-
async function pathExists(targetPath) {
|
|
1376
|
-
try {
|
|
1377
|
-
await fs.access(targetPath);
|
|
1378
|
-
return true;
|
|
1379
|
-
}
|
|
1380
|
-
catch (err) {
|
|
1381
|
-
if (err.code === "ENOENT") {
|
|
1382
|
-
return false;
|
|
1383
|
-
}
|
|
1384
|
-
throw err;
|
|
1385
|
-
}
|
|
1386
|
-
}
|
|
1387
|
-
function ensureRecord(value) {
|
|
1388
|
-
return value && typeof value === "object" && !Array.isArray(value)
|
|
1389
|
-
? { ...value }
|
|
1390
|
-
: {};
|
|
1391
|
-
}
|
|
1392
|
-
function parseLooseJsonObject(raw, configPath) {
|
|
1393
|
-
try {
|
|
1394
|
-
return JSON5.parse(raw);
|
|
1395
|
-
}
|
|
1396
|
-
catch (err) {
|
|
1397
|
-
throw new Error(`Failed to parse OpenClaw config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1398
|
-
}
|
|
1399
|
-
}
|
|
1400
744
|
async function reserveEphemeralPort() {
|
|
1401
745
|
return await new Promise((resolve, reject) => {
|
|
1402
746
|
const server = net.createServer();
|
|
@@ -1418,231 +762,3 @@ async function reserveEphemeralPort() {
|
|
|
1418
762
|
server.on("error", reject);
|
|
1419
763
|
});
|
|
1420
764
|
}
|
|
1421
|
-
function resolveGatewayEntrypoint() {
|
|
1422
|
-
const scriptPath = process.argv[1];
|
|
1423
|
-
if (!scriptPath) {
|
|
1424
|
-
throw new Error("Unable to resolve OpenClaw gateway entrypoint");
|
|
1425
|
-
}
|
|
1426
|
-
return path.resolve(scriptPath);
|
|
1427
|
-
}
|
|
1428
|
-
function resolveCurrentTeamClawPluginRootDir() {
|
|
1429
|
-
return process.env.TEAMCLAW_BAKED_IN === "true" ? "" : path.resolve(fileURLToPath(new URL("../../", import.meta.url)));
|
|
1430
|
-
}
|
|
1431
|
-
/**
|
|
1432
|
-
* Locate the teamclaw plugin root inside a baked runtime image. The image
|
|
1433
|
-
* ships the plugin at <app-root>/extensions/teamclaw; the controller
|
|
1434
|
-
* entrypoint (process.argv[1]) lives under <app-root>, so walk up from it.
|
|
1435
|
-
* Returns "" when no candidate carries an openclaw.plugin.json (the
|
|
1436
|
-
* caller then skips the symlink instead of creating a dangling one).
|
|
1437
|
-
*/
|
|
1438
|
-
async function resolveBakedTeamClawPluginRootDir() {
|
|
1439
|
-
const entrypoint = process.argv[1] ? path.resolve(process.argv[1]) : "";
|
|
1440
|
-
const candidates = entrypoint
|
|
1441
|
-
? [
|
|
1442
|
-
path.resolve(entrypoint, "../../extensions/teamclaw"),
|
|
1443
|
-
path.resolve(entrypoint, "../extensions/teamclaw"),
|
|
1444
|
-
]
|
|
1445
|
-
: [];
|
|
1446
|
-
candidates.push("/app/extensions/teamclaw");
|
|
1447
|
-
for (const candidate of candidates) {
|
|
1448
|
-
try {
|
|
1449
|
-
await fs.access(path.join(candidate, "openclaw.plugin.json"));
|
|
1450
|
-
return candidate;
|
|
1451
|
-
}
|
|
1452
|
-
catch {
|
|
1453
|
-
// try the next candidate layout
|
|
1454
|
-
}
|
|
1455
|
-
}
|
|
1456
|
-
return "";
|
|
1457
|
-
}
|
|
1458
|
-
function attachChildLogs(child, logger, prefix) {
|
|
1459
|
-
if (child.stdout) {
|
|
1460
|
-
const stdoutReader = readline.createInterface({ input: child.stdout });
|
|
1461
|
-
stdoutReader.on("line", (line) => {
|
|
1462
|
-
logger.info(`${prefix}: ${line}`);
|
|
1463
|
-
});
|
|
1464
|
-
}
|
|
1465
|
-
if (child.stderr) {
|
|
1466
|
-
const stderrReader = readline.createInterface({ input: child.stderr });
|
|
1467
|
-
stderrReader.on("line", (line) => {
|
|
1468
|
-
logger.warn(`${prefix}: ${line}`);
|
|
1469
|
-
});
|
|
1470
|
-
}
|
|
1471
|
-
}
|
|
1472
|
-
async function stopChildProcess(child) {
|
|
1473
|
-
if (child.exitCode !== null || child.signalCode !== null) {
|
|
1474
|
-
return;
|
|
1475
|
-
}
|
|
1476
|
-
await new Promise((resolve) => {
|
|
1477
|
-
const timeout = setTimeout(() => {
|
|
1478
|
-
if (child.exitCode === null && child.signalCode === null && child.pid) {
|
|
1479
|
-
try {
|
|
1480
|
-
process.kill(child.pid, "SIGKILL");
|
|
1481
|
-
}
|
|
1482
|
-
catch {
|
|
1483
|
-
// ignore
|
|
1484
|
-
}
|
|
1485
|
-
}
|
|
1486
|
-
resolve();
|
|
1487
|
-
}, PROCESS_TERMINATION_TIMEOUT_MS);
|
|
1488
|
-
const timer = timeout;
|
|
1489
|
-
timer.unref?.();
|
|
1490
|
-
child.once("exit", () => {
|
|
1491
|
-
clearTimeout(timeout);
|
|
1492
|
-
resolve();
|
|
1493
|
-
});
|
|
1494
|
-
child.kill("SIGTERM");
|
|
1495
|
-
});
|
|
1496
|
-
}
|
|
1497
|
-
function sanitizePathSegment(value) {
|
|
1498
|
-
const normalized = value.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
1499
|
-
return normalized || "worker";
|
|
1500
|
-
}
|
|
1501
|
-
function sanitizeName(value, maxLength = 63) {
|
|
1502
|
-
const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
|
|
1503
|
-
return normalized || "teamclaw";
|
|
1504
|
-
}
|
|
1505
|
-
function buildManagedInstanceName(teamName, role, workerId) {
|
|
1506
|
-
return buildManagedName("teamclaw", teamName, role, workerId, {
|
|
1507
|
-
teamBudget: 18,
|
|
1508
|
-
roleBudget: 12,
|
|
1509
|
-
workerBudget: 12,
|
|
1510
|
-
hashLength: 8,
|
|
1511
|
-
maxLength: 63,
|
|
1512
|
-
});
|
|
1513
|
-
}
|
|
1514
|
-
function buildManagedHostname(teamName, role, workerId) {
|
|
1515
|
-
return buildManagedName("tc", teamName, role, workerId, {
|
|
1516
|
-
teamBudget: 10,
|
|
1517
|
-
roleBudget: 8,
|
|
1518
|
-
workerBudget: 6,
|
|
1519
|
-
hashLength: 6,
|
|
1520
|
-
maxLength: 40,
|
|
1521
|
-
});
|
|
1522
|
-
}
|
|
1523
|
-
function buildManagedName(prefix, teamName, role, workerId, options) {
|
|
1524
|
-
const teamPart = sanitizeLeadingSegment(teamName, options.teamBudget, "team");
|
|
1525
|
-
const rolePart = sanitizeLeadingSegment(role, options.roleBudget, "worker");
|
|
1526
|
-
const workerPart = sanitizeTrailingSegment(workerId, options.workerBudget, "worker");
|
|
1527
|
-
const hash = shortStableHash(`${teamName}:${role}:${workerId}`).slice(0, options.hashLength);
|
|
1528
|
-
return sanitizeName(`${prefix}-${teamPart}-${rolePart}-${workerPart}-${hash}`, options.maxLength);
|
|
1529
|
-
}
|
|
1530
|
-
function shortStableHash(value) {
|
|
1531
|
-
return createHash("sha1").update(value).digest("hex");
|
|
1532
|
-
}
|
|
1533
|
-
function sanitizeLeadingSegment(value, maxLength, fallback) {
|
|
1534
|
-
const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
|
|
1535
|
-
return normalized || fallback;
|
|
1536
|
-
}
|
|
1537
|
-
function sanitizeTrailingSegment(value, maxLength, fallback) {
|
|
1538
|
-
const normalized = sanitizePathSegment(value).slice(-maxLength).replace(/^-+|-+$/g, "");
|
|
1539
|
-
return normalized || fallback;
|
|
1540
|
-
}
|
|
1541
|
-
function buildContainerBootstrapScript() {
|
|
1542
|
-
return [
|
|
1543
|
-
"set -eu",
|
|
1544
|
-
"mkdir -p \"$OPENCLAW_STATE_DIR\"",
|
|
1545
|
-
"if [ -n \"${TEAMCLAW_WORKSPACE_DIR:-}\" ]; then mkdir -p \"$TEAMCLAW_WORKSPACE_DIR\"; fi",
|
|
1546
|
-
"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);'",
|
|
1547
|
-
"exec node dist/index.js gateway --allow-unconfigured",
|
|
1548
|
-
].join("\n");
|
|
1549
|
-
}
|
|
1550
|
-
function buildDockerBinds(config) {
|
|
1551
|
-
const binds = [...config.workerProvisioningDockerMounts];
|
|
1552
|
-
if (!binds.some((bind) => extractDockerBindTarget(bind) === DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR)) {
|
|
1553
|
-
const _pd = resolveCurrentTeamClawPluginRootDir();
|
|
1554
|
-
if (_pd)
|
|
1555
|
-
binds.unshift(`${_pd}:${DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR}:ro`);
|
|
1556
|
-
}
|
|
1557
|
-
if (config.workerProvisioningDockerWorkspaceVolume && config.workerProvisioningWorkspaceRoot) {
|
|
1558
|
-
binds.unshift(`${config.workerProvisioningDockerWorkspaceVolume}:${config.workerProvisioningWorkspaceRoot}`);
|
|
1559
|
-
}
|
|
1560
|
-
return [...new Set(binds)];
|
|
1561
|
-
}
|
|
1562
|
-
function buildProvisionedWorkspaceDir(provider, config, role, workerId) {
|
|
1563
|
-
// Process-type workers run on the same host — share the controller's workspace
|
|
1564
|
-
// so that file artifacts (previews, deliverables) are immediately visible to
|
|
1565
|
-
// the controller without requiring git sync or file transfer.
|
|
1566
|
-
if (provider === "process") {
|
|
1567
|
-
return resolveTeamClawAgentWorkspaceRootDir();
|
|
1568
|
-
}
|
|
1569
|
-
if ((provider !== "docker" && provider !== "kubernetes") ||
|
|
1570
|
-
!config.workerProvisioningWorkspaceRoot) {
|
|
1571
|
-
return "";
|
|
1572
|
-
}
|
|
1573
|
-
return path.posix.join(config.workerProvisioningWorkspaceRoot, sanitizePathSegment(config.teamName), sanitizePathSegment(role), sanitizePathSegment(workerId));
|
|
1574
|
-
}
|
|
1575
|
-
function getConfiguredWorkerWorkspaceDir(config) {
|
|
1576
|
-
const agents = ensureRecord(config.agents);
|
|
1577
|
-
const defaults = ensureRecord(agents.defaults);
|
|
1578
|
-
return typeof defaults.workspace === "string" ? defaults.workspace : "";
|
|
1579
|
-
}
|
|
1580
|
-
function resolveDockerEndpoint() {
|
|
1581
|
-
const dockerHost = process.env.DOCKER_HOST?.trim();
|
|
1582
|
-
if (!dockerHost) {
|
|
1583
|
-
return {
|
|
1584
|
-
protocol: "http:",
|
|
1585
|
-
socketPath: "/var/run/docker.sock",
|
|
1586
|
-
};
|
|
1587
|
-
}
|
|
1588
|
-
if (dockerHost.startsWith("unix://")) {
|
|
1589
|
-
return {
|
|
1590
|
-
protocol: "http:",
|
|
1591
|
-
socketPath: dockerHost.slice("unix://".length),
|
|
1592
|
-
};
|
|
1593
|
-
}
|
|
1594
|
-
const normalized = dockerHost.startsWith("tcp://")
|
|
1595
|
-
? dockerHost.replace(/^tcp:\/\//, "http://")
|
|
1596
|
-
: dockerHost;
|
|
1597
|
-
const url = new URL(normalized);
|
|
1598
|
-
return {
|
|
1599
|
-
protocol: url.protocol === "https:" ? "https:" : "http:",
|
|
1600
|
-
hostname: url.hostname,
|
|
1601
|
-
port: url.port ? Number(url.port) : (url.protocol === "https:" ? 443 : 2375),
|
|
1602
|
-
};
|
|
1603
|
-
}
|
|
1604
|
-
function extractDockerErrorMessage(body) {
|
|
1605
|
-
if (!body.trim()) {
|
|
1606
|
-
return null;
|
|
1607
|
-
}
|
|
1608
|
-
try {
|
|
1609
|
-
const parsed = JSON.parse(body);
|
|
1610
|
-
return typeof parsed.message === "string" ? parsed.message : body;
|
|
1611
|
-
}
|
|
1612
|
-
catch {
|
|
1613
|
-
return body;
|
|
1614
|
-
}
|
|
1615
|
-
}
|
|
1616
|
-
async function runCommand(command, args, stdin) {
|
|
1617
|
-
await new Promise((resolve, reject) => {
|
|
1618
|
-
const child = spawn(command, args, {
|
|
1619
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
1620
|
-
env: process.env,
|
|
1621
|
-
});
|
|
1622
|
-
let stderr = "";
|
|
1623
|
-
let stdout = "";
|
|
1624
|
-
if (stdin) {
|
|
1625
|
-
child.stdin?.end(stdin);
|
|
1626
|
-
}
|
|
1627
|
-
else {
|
|
1628
|
-
child.stdin?.end();
|
|
1629
|
-
}
|
|
1630
|
-
child.stdout?.on("data", (chunk) => {
|
|
1631
|
-
stdout += chunk.toString("utf8");
|
|
1632
|
-
});
|
|
1633
|
-
child.stderr?.on("data", (chunk) => {
|
|
1634
|
-
stderr += chunk.toString("utf8");
|
|
1635
|
-
});
|
|
1636
|
-
child.on("error", reject);
|
|
1637
|
-
child.on("exit", (code) => {
|
|
1638
|
-
if (code === 0) {
|
|
1639
|
-
resolve();
|
|
1640
|
-
return;
|
|
1641
|
-
}
|
|
1642
|
-
reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${(stderr || stdout).trim()}`));
|
|
1643
|
-
});
|
|
1644
|
-
});
|
|
1645
|
-
}
|
|
1646
|
-
function buildKubectlContextArgs(context) {
|
|
1647
|
-
return context ? ["--context", context] : [];
|
|
1648
|
-
}
|