@teamclaws/teamclaw 2026.11.0 → 2026.11.2
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 +368 -13
- package/dist/index.js +61 -32
- package/dist/src/config.js +24 -0
- package/dist/src/controller/auth-routes.js +129 -0
- package/dist/src/controller/clarification-routes.js +1 -1
- package/dist/src/controller/config-routes.js +138 -0
- package/dist/src/controller/controller-planning.js +1 -0
- package/dist/src/controller/controller-routes.js +195 -0
- package/dist/src/controller/controller-service.js +67 -10
- package/dist/src/controller/controller-tools.js +3 -1
- package/dist/src/controller/github-auth.js +2 -1
- package/dist/src/controller/http-server.js +51 -16
- package/dist/src/controller/kickoff-orchestrator.js +3 -39
- package/dist/src/controller/message-delivery.js +4 -1
- package/dist/src/controller/orchestration-manifest.js +5 -65
- package/dist/src/controller/preview-manager.js +51 -3
- package/dist/src/controller/profile-switch.js +42 -22
- 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 +70 -4
- package/dist/src/controller/report-routes.js +56 -0
- package/dist/src/controller/route-table.js +73 -1045
- package/dist/src/controller/security.js +775 -0
- package/dist/src/controller/status-routes.js +287 -0
- package/dist/src/controller/task-assignment.js +5 -2
- package/dist/src/controller/task-execution.js +31 -0
- package/dist/src/controller/task-results.js +10 -0
- package/dist/src/controller/tunnel-manager.js +41 -8
- package/dist/src/controller/tunnel-routes.js +225 -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 +39 -949
- 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 +12 -1
- package/dist/src/openclaw-workspace.js +36 -0
- package/dist/src/profile-loader.js +119 -1
- package/dist/src/profiles/banking.json +26 -2
- package/dist/src/profiles/schema.json +82 -2
- package/dist/src/prompt-policy.js +18 -6
- package/dist/src/protocol.js +66 -3
- 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 +89 -3
- package/dist/src/teamauto/scanner.js +21 -2
- package/dist/src/teamauto/scheduler.js +9 -2
- package/dist/src/types.js +15 -1
- package/dist/src/ui/app.js +990 -73
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +125 -36
- package/dist/src/worker/http-handler.js +59 -0
- package/dist/src/worker/skill-installer.js +3 -9
- package/dist/src/worker/tools.js +20 -10
- package/dist/src/worker/worker-service.js +17 -4
- package/index.ts +69 -32
- package/openclaw.plugin.json +23 -2
- package/package.json +1 -1
- package/src/config.ts +24 -0
- package/src/controller/auth-routes.ts +157 -0
- package/src/controller/clarification-routes.ts +1 -1
- package/src/controller/config-routes.ts +152 -0
- package/src/controller/controller-planning.ts +8 -0
- package/src/controller/controller-routes.ts +237 -0
- package/src/controller/controller-service.ts +128 -10
- package/src/controller/controller-tools.ts +5 -2
- package/src/controller/github-auth.ts +28 -63
- package/src/controller/http-server.ts +66 -17
- package/src/controller/kickoff-orchestrator.ts +3 -42
- package/src/controller/message-delivery.ts +4 -1
- package/src/controller/orchestration-manifest.ts +8 -71
- package/src/controller/preview-manager.ts +53 -3
- package/src/controller/profile-switch.ts +53 -23
- 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 +84 -12
- package/src/controller/report-routes.ts +64 -0
- package/src/controller/route-table.ts +139 -1152
- package/src/controller/security.ts +899 -0
- package/src/controller/status-routes.ts +354 -0
- package/src/controller/task-assignment.ts +5 -1
- package/src/controller/task-execution.ts +43 -0
- package/src/controller/task-results.ts +12 -0
- package/src/controller/tunnel-manager.ts +45 -8
- package/src/controller/tunnel-routes.ts +231 -0
- package/src/controller/websocket.ts +20 -3
- package/src/controller/webui-routes.ts +55 -0
- package/src/controller/worker-provisioning.ts +51 -1117
- 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 +13 -1
- package/src/openclaw-workspace.ts +47 -0
- package/src/profile-loader.ts +167 -1
- package/src/profiles/banking.json +26 -2
- package/src/profiles/schema.json +82 -2
- package/src/prompt-policy.ts +19 -6
- package/src/protocol.ts +72 -2
- 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 +92 -3
- package/src/teamauto/github-client.ts +2 -1
- package/src/teamauto/repo-sync.ts +2 -1
- package/src/teamauto/scanner.ts +22 -3
- package/src/teamauto/scheduler.ts +11 -3
- package/src/teamauto/store.ts +5 -0
- package/src/types.ts +130 -1
- package/src/ui/app.js +990 -73
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +125 -36
- package/src/worker/http-handler.ts +64 -1
- package/src/worker/skill-installer.ts +3 -9
- package/src/worker/tools.ts +21 -10
- package/src/worker/worker-service.ts +18 -4
|
@@ -1,28 +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
|
-
import { resolveDefaultOpenClawConfigPath, resolveDefaultOpenClawStateDir, resolveDefaultTeamClawRuntimeRootDir, resolveDefaultAgentDir, resolveTeamClawAgentDir, resolveTeamClawAgentWorkspaceRootDir, resolveTeamClawWorkspaceDir, TEAMCLAW_AGENT_ID, } from "../openclaw-workspace.js";
|
|
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";
|
|
13
27
|
// Phase 1.3: the role universe and the fallback role come from the active
|
|
14
28
|
// TeamProfile loader (software-rd baseline).
|
|
15
29
|
import { getActiveRoleIds, getActiveDefaultRole } from "../profile-loader.js";
|
|
16
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";
|
|
17
39
|
const DEFAULT_CONTAINER_WORKER_PORT = 9527;
|
|
18
40
|
const DEFAULT_CONTAINER_GATEWAY_PORT = 18789;
|
|
19
|
-
const DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR = "/app/extensions/teamclaw";
|
|
20
41
|
const PROVISIONING_RECORD_RETENTION_MS = 6 * 60 * 60 * 1000;
|
|
21
42
|
const PROVISIONING_FAILURE_COOLDOWN_MS = 30_000;
|
|
22
43
|
const PROCESS_TERMINATION_TIMEOUT_MS = 10_000;
|
|
23
44
|
const STARTUP_READINESS_POLL_INTERVAL_MS = 1_000;
|
|
24
45
|
const STARTUP_READINESS_RETRY_INTERVAL_MS = 5_000;
|
|
25
|
-
const DOCKER_API_VERSION = resolveDockerApiVersion();
|
|
26
46
|
export class WorkerProvisioningManager {
|
|
27
47
|
deps;
|
|
28
48
|
backend;
|
|
@@ -89,7 +109,10 @@ export class WorkerProvisioningManager {
|
|
|
89
109
|
reason: `Provisioned worker ${workerId} expected role ${record.role}, got ${role}`,
|
|
90
110
|
};
|
|
91
111
|
}
|
|
92
|
-
|
|
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)) {
|
|
93
116
|
return {
|
|
94
117
|
ok: false,
|
|
95
118
|
managed: true,
|
|
@@ -449,7 +472,10 @@ export class WorkerProvisioningManager {
|
|
|
449
472
|
return;
|
|
450
473
|
}
|
|
451
474
|
const workerId = `provisioned-${role}-${generateId()}`;
|
|
452
|
-
|
|
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();
|
|
453
479
|
const controllerUrl = this.resolveControllerUrl();
|
|
454
480
|
const requiresDedicatedHostPorts = requiresDedicatedHostPortsForProvisioner(this.backend.type, this.deps.config);
|
|
455
481
|
const workerPort = requiresDedicatedHostPorts
|
|
@@ -687,443 +713,6 @@ export class WorkerProvisioningManager {
|
|
|
687
713
|
return changed;
|
|
688
714
|
}
|
|
689
715
|
}
|
|
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
716
|
function createProvisionerBackend(config, logger) {
|
|
1128
717
|
switch (config.workerProvisioningType) {
|
|
1129
718
|
case "process":
|
|
@@ -1137,125 +726,6 @@ function createProvisionerBackend(config, logger) {
|
|
|
1137
726
|
return null;
|
|
1138
727
|
}
|
|
1139
728
|
}
|
|
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
729
|
function ensureProvisioningState(state) {
|
|
1260
730
|
if (!state.provisioning || typeof state.provisioning !== "object") {
|
|
1261
731
|
state.provisioning = { workers: {} };
|
|
@@ -1271,158 +741,6 @@ async function ensureWritableDirectory(dir) {
|
|
|
1271
741
|
await fs.writeFile(probePath, "ok\n", "utf8");
|
|
1272
742
|
await fs.rm(probePath, { force: true });
|
|
1273
743
|
}
|
|
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
744
|
async function reserveEphemeralPort() {
|
|
1427
745
|
return await new Promise((resolve, reject) => {
|
|
1428
746
|
const server = net.createServer();
|
|
@@ -1444,231 +762,3 @@ async function reserveEphemeralPort() {
|
|
|
1444
762
|
server.on("error", reject);
|
|
1445
763
|
});
|
|
1446
764
|
}
|
|
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
|
-
}
|