@teamclaws/teamclaw 2026.11.0 → 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 +272 -2
- package/dist/index.js +54 -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/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 +67 -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/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/types.js +15 -1
- package/dist/src/ui/app.js +846 -62
- package/dist/src/ui/github-login.html +1 -0
- package/dist/src/ui/index.html +102 -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 +61 -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/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 +133 -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 +19 -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/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/scheduler.ts +2 -1
- package/src/types.ts +130 -1
- package/src/ui/app.js +846 -62
- package/src/ui/github-login.html +1 -0
- package/src/ui/index.html +102 -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,24 +1,35 @@
|
|
|
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 readline from "node:readline";
|
|
7
|
-
import { createHash } from "node:crypto";
|
|
8
|
-
import { spawn, type ChildProcess } from "node:child_process";
|
|
9
|
-
import { fileURLToPath } from "node:url";
|
|
10
|
-
import JSON5 from "json5";
|
|
11
21
|
import type { PluginLogger } from "../../api.js";
|
|
12
|
-
import { generateId } from "../protocol.js";
|
|
22
|
+
import { generateId, generateLaunchToken, secretsEqual } from "../protocol.js";
|
|
23
|
+
// Issue #255 P0-1: the launch-token check at registration uses the shared
|
|
24
|
+
// constant-time secret equality (same helper the device gate and tunnel gate
|
|
25
|
+
// use). controller -> controller edge; security.ts never imports back here,
|
|
26
|
+
// so the module graph stays acyclic.
|
|
13
27
|
import {
|
|
14
28
|
resolveDefaultOpenClawConfigPath,
|
|
15
|
-
resolveDefaultOpenClawStateDir,
|
|
16
29
|
resolveDefaultTeamClawRuntimeRootDir,
|
|
17
|
-
resolveDefaultAgentDir,
|
|
18
30
|
resolveTeamClawAgentDir,
|
|
19
31
|
resolveTeamClawAgentWorkspaceRootDir,
|
|
20
32
|
resolveTeamClawWorkspaceDir,
|
|
21
|
-
TEAMCLAW_AGENT_ID,
|
|
22
33
|
} from "../openclaw-workspace.js";
|
|
23
34
|
// Phase 1.3: the role universe and the fallback role come from the active
|
|
24
35
|
// TeamProfile loader (software-rd baseline).
|
|
@@ -33,19 +44,37 @@ import type {
|
|
|
33
44
|
TaskInfo,
|
|
34
45
|
TeamProvisioningState,
|
|
35
46
|
TeamState,
|
|
36
|
-
WorkerProvisioningType,
|
|
37
47
|
WorkerStatus,
|
|
38
48
|
} from "../types.js";
|
|
49
|
+
import { cloneJson, sleep } from "../shared/utils.js";
|
|
50
|
+
import {
|
|
51
|
+
appendNoProxyEntries,
|
|
52
|
+
buildProvisionedWorkspaceDir,
|
|
53
|
+
buildProvisionedWorkerConfig,
|
|
54
|
+
getConfiguredWorkerWorkspaceDir,
|
|
55
|
+
loadOpenClawConfig,
|
|
56
|
+
} from "./provisioning-config.js";
|
|
57
|
+
import type { WorkerProvisionerBackend } from "./provisioning/backend-contract.js";
|
|
58
|
+
import {
|
|
59
|
+
isDockerHostNetwork,
|
|
60
|
+
requiresDedicatedHostPortsForProvisioner,
|
|
61
|
+
} from "./provisioning/backend-contract.js";
|
|
62
|
+
import { ProcessProvisioner } from "./provisioning/process-supervisor.js";
|
|
63
|
+
import { DockerProvisioner } from "./provisioning/docker.js";
|
|
64
|
+
import { KubernetesProvisioner } from "./provisioning/kubernetes.js";
|
|
65
|
+
|
|
66
|
+
// Historical export face kept stable for tests / external tooling.
|
|
67
|
+
export { buildProvisionedWorkerConfig } from "./provisioning-config.js";
|
|
68
|
+
|
|
39
69
|
|
|
40
70
|
const DEFAULT_CONTAINER_WORKER_PORT = 9527;
|
|
41
71
|
const DEFAULT_CONTAINER_GATEWAY_PORT = 18789;
|
|
42
|
-
|
|
72
|
+
|
|
43
73
|
const PROVISIONING_RECORD_RETENTION_MS = 6 * 60 * 60 * 1000;
|
|
44
74
|
const PROVISIONING_FAILURE_COOLDOWN_MS = 30_000;
|
|
45
75
|
const PROCESS_TERMINATION_TIMEOUT_MS = 10_000;
|
|
46
76
|
const STARTUP_READINESS_POLL_INTERVAL_MS = 1_000;
|
|
47
77
|
const STARTUP_READINESS_RETRY_INTERVAL_MS = 5_000;
|
|
48
|
-
const DOCKER_API_VERSION = resolveDockerApiVersion();
|
|
49
78
|
|
|
50
79
|
export type WorkerProvisioningManagerDeps = {
|
|
51
80
|
config: PluginConfig;
|
|
@@ -56,32 +85,6 @@ export type WorkerProvisioningManagerDeps = {
|
|
|
56
85
|
actualControllerPort?: number;
|
|
57
86
|
};
|
|
58
87
|
|
|
59
|
-
type LaunchSpec = {
|
|
60
|
-
workerId: string;
|
|
61
|
-
role: RoleId;
|
|
62
|
-
launchToken: string;
|
|
63
|
-
controllerUrl: string;
|
|
64
|
-
workerPort: number;
|
|
65
|
-
gatewayPort: number;
|
|
66
|
-
publishedHostPort?: number;
|
|
67
|
-
workspaceDir?: string;
|
|
68
|
-
env: Record<string, string>;
|
|
69
|
-
configJson: string;
|
|
70
|
-
};
|
|
71
|
-
|
|
72
|
-
type LaunchResult = {
|
|
73
|
-
instanceId?: string;
|
|
74
|
-
instanceName?: string;
|
|
75
|
-
runtimeHomeDir?: string;
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
interface WorkerProvisionerBackend {
|
|
79
|
-
readonly type: WorkerProvisioningType;
|
|
80
|
-
launch(spec: LaunchSpec): Promise<LaunchResult>;
|
|
81
|
-
terminate(record: ProvisionedWorkerRecord): Promise<void>;
|
|
82
|
-
stop?(): Promise<void>;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
88
|
export class WorkerProvisioningManager {
|
|
86
89
|
private deps: WorkerProvisioningManagerDeps;
|
|
87
90
|
private readonly backend: WorkerProvisionerBackend | null;
|
|
@@ -161,7 +164,10 @@ export class WorkerProvisioningManager {
|
|
|
161
164
|
reason: `Provisioned worker ${workerId} expected role ${record.role}, got ${role}`,
|
|
162
165
|
};
|
|
163
166
|
}
|
|
164
|
-
|
|
167
|
+
// Issue #255 P0-1: constant-time equality. Semantics unchanged (old
|
|
168
|
+
// PRNG-era tokens in upgraded TeamStates still match their own value);
|
|
169
|
+
// only the timing side channel of `!==` goes away.
|
|
170
|
+
if (!launchToken || !secretsEqual(launchToken, record.launchToken)) {
|
|
165
171
|
return {
|
|
166
172
|
ok: false,
|
|
167
173
|
managed: true,
|
|
@@ -586,7 +592,10 @@ export class WorkerProvisioningManager {
|
|
|
586
592
|
}
|
|
587
593
|
|
|
588
594
|
const workerId = `provisioned-${role}-${generateId()}`;
|
|
589
|
-
|
|
595
|
+
// Issue #255 P0-1: 256-bit CSPRNG token (see generateLaunchToken) -
|
|
596
|
+
// replaces the old two-generateId construction whose PRNG-derived
|
|
597
|
+
// fragments made tokens predictable from observed output.
|
|
598
|
+
const launchToken = generateLaunchToken();
|
|
590
599
|
const controllerUrl = this.resolveControllerUrl();
|
|
591
600
|
const requiresDedicatedHostPorts = requiresDedicatedHostPortsForProvisioner(
|
|
592
601
|
this.backend.type,
|
|
@@ -872,498 +881,6 @@ export class WorkerProvisioningManager {
|
|
|
872
881
|
}
|
|
873
882
|
}
|
|
874
883
|
|
|
875
|
-
class ProcessProvisioner implements WorkerProvisionerBackend {
|
|
876
|
-
readonly type = "process" as const;
|
|
877
|
-
private readonly logger: PluginLogger;
|
|
878
|
-
private readonly processByWorkerId = new Map<string, ChildProcess>();
|
|
879
|
-
private readonly baseDirPromise: Promise<string>;
|
|
880
|
-
|
|
881
|
-
constructor(logger: PluginLogger) {
|
|
882
|
-
this.logger = logger;
|
|
883
|
-
const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
|
|
884
|
-
this.baseDirPromise = fs.mkdir(provisionedRoot, { recursive: true })
|
|
885
|
-
.then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
|
|
886
|
-
}
|
|
887
|
-
|
|
888
|
-
async launch(spec: LaunchSpec): Promise<LaunchResult> {
|
|
889
|
-
const baseDir = await this.baseDirPromise;
|
|
890
|
-
const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
|
|
891
|
-
const stateDir = path.join(runtimeHomeDir, ".openclaw");
|
|
892
|
-
const configPath = path.join(stateDir, "openclaw.json");
|
|
893
|
-
await fs.mkdir(stateDir, { recursive: true });
|
|
894
|
-
await prepareProcessRuntimeExtensions(stateDir);
|
|
895
|
-
await fs.writeFile(configPath, spec.configJson, "utf8");
|
|
896
|
-
|
|
897
|
-
const gatewayEntrypoint = resolveGatewayEntrypoint();
|
|
898
|
-
const child = spawn(process.execPath, [
|
|
899
|
-
gatewayEntrypoint,
|
|
900
|
-
"gateway",
|
|
901
|
-
"--allow-unconfigured",
|
|
902
|
-
"--bind",
|
|
903
|
-
"loopback",
|
|
904
|
-
"--port",
|
|
905
|
-
String(spec.gatewayPort),
|
|
906
|
-
], {
|
|
907
|
-
cwd: path.dirname(gatewayEntrypoint),
|
|
908
|
-
env: {
|
|
909
|
-
...process.env,
|
|
910
|
-
...spec.env,
|
|
911
|
-
HOME: runtimeHomeDir,
|
|
912
|
-
OPENCLAW_HOME: runtimeHomeDir,
|
|
913
|
-
OPENCLAW_STATE_DIR: stateDir,
|
|
914
|
-
OPENCLAW_CONFIG_PATH: configPath,
|
|
915
|
-
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
916
|
-
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
917
|
-
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
918
|
-
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
919
|
-
},
|
|
920
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
921
|
-
});
|
|
922
|
-
|
|
923
|
-
this.processByWorkerId.set(spec.workerId, child);
|
|
924
|
-
attachChildLogs(child, this.logger, `ProvisionedWorker[${spec.role}]`);
|
|
925
|
-
child.on("exit", (code: number | null, signal: string | null) => {
|
|
926
|
-
this.processByWorkerId.delete(spec.workerId);
|
|
927
|
-
this.logger.info(
|
|
928
|
-
`Provisioner: process worker ${spec.workerId} exited (code=${String(code)}, signal=${String(signal)})`,
|
|
929
|
-
);
|
|
930
|
-
});
|
|
931
|
-
|
|
932
|
-
return {
|
|
933
|
-
instanceId: child.pid ? `pid:${child.pid}` : undefined,
|
|
934
|
-
instanceName: spec.workerId,
|
|
935
|
-
runtimeHomeDir,
|
|
936
|
-
};
|
|
937
|
-
}
|
|
938
|
-
|
|
939
|
-
async terminate(record: ProvisionedWorkerRecord): Promise<void> {
|
|
940
|
-
const child = this.processByWorkerId.get(record.workerId);
|
|
941
|
-
if (child) {
|
|
942
|
-
await stopChildProcess(child);
|
|
943
|
-
this.processByWorkerId.delete(record.workerId);
|
|
944
|
-
} else if (record.instanceId?.startsWith("pid:")) {
|
|
945
|
-
const pid = Number(record.instanceId.slice("pid:".length));
|
|
946
|
-
if (Number.isFinite(pid) && pid > 0) {
|
|
947
|
-
try {
|
|
948
|
-
process.kill(pid, "SIGTERM");
|
|
949
|
-
} catch {
|
|
950
|
-
// ignore
|
|
951
|
-
}
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
|
|
955
|
-
if (record.runtimeHomeDir) {
|
|
956
|
-
await fs.rm(record.runtimeHomeDir, { recursive: true, force: true }).catch(() => {
|
|
957
|
-
// ignore
|
|
958
|
-
});
|
|
959
|
-
}
|
|
960
|
-
}
|
|
961
|
-
|
|
962
|
-
async stop(): Promise<void> {
|
|
963
|
-
for (const child of this.processByWorkerId.values()) {
|
|
964
|
-
await stopChildProcess(child).catch(() => {
|
|
965
|
-
// ignore
|
|
966
|
-
});
|
|
967
|
-
}
|
|
968
|
-
this.processByWorkerId.clear();
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
|
|
972
|
-
class DockerProvisioner implements WorkerProvisionerBackend {
|
|
973
|
-
readonly type = "docker" as const;
|
|
974
|
-
private readonly config: PluginConfig;
|
|
975
|
-
private readonly logger: PluginLogger;
|
|
976
|
-
private readonly client: DockerApiClient;
|
|
977
|
-
|
|
978
|
-
constructor(config: PluginConfig, logger: PluginLogger) {
|
|
979
|
-
this.config = config;
|
|
980
|
-
this.logger = logger;
|
|
981
|
-
this.client = new DockerApiClient();
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
async launch(spec: LaunchSpec): Promise<LaunchResult> {
|
|
985
|
-
if (!this.config.workerProvisioningImage) {
|
|
986
|
-
throw new Error("workerProvisioningImage is required for docker provisioning");
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
|
|
990
|
-
const env: Record<string, string> = {
|
|
991
|
-
...spec.env,
|
|
992
|
-
HOME: "/home/node",
|
|
993
|
-
OPENCLAW_HOME: "/home/node",
|
|
994
|
-
OPENCLAW_STATE_DIR: "/home/node/.openclaw",
|
|
995
|
-
OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
|
|
996
|
-
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
997
|
-
TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
|
|
998
|
-
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
999
|
-
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
1000
|
-
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
1001
|
-
};
|
|
1002
|
-
|
|
1003
|
-
// When workers share a Docker network with the controller container, advertise
|
|
1004
|
-
// the container name and internal worker port so sibling containers can reach it
|
|
1005
|
-
// directly. When the controller runs on the host, fall back to publishing a host
|
|
1006
|
-
// port and advertising localhost for host-side callbacks.
|
|
1007
|
-
const usePortPublishing = spec.publishedHostPort !== undefined;
|
|
1008
|
-
if (this.config.workerProvisioningDockerNetwork) {
|
|
1009
|
-
env.TEAMCLAW_ADVERTISE_HOST = instanceName;
|
|
1010
|
-
env.TEAMCLAW_ADVERTISE_PORT = String(spec.workerPort);
|
|
1011
|
-
} else if (usePortPublishing) {
|
|
1012
|
-
env.TEAMCLAW_ADVERTISE_HOST = "localhost";
|
|
1013
|
-
env.TEAMCLAW_ADVERTISE_PORT = String(spec.publishedHostPort);
|
|
1014
|
-
}
|
|
1015
|
-
|
|
1016
|
-
const hostConfig: Record<string, unknown> = {
|
|
1017
|
-
Binds: buildDockerBinds(this.config),
|
|
1018
|
-
NetworkMode: this.config.workerProvisioningDockerNetwork || undefined,
|
|
1019
|
-
};
|
|
1020
|
-
|
|
1021
|
-
if (usePortPublishing) {
|
|
1022
|
-
hostConfig.PortBindings = {
|
|
1023
|
-
[`${spec.workerPort}/tcp`]: [{ HostPort: String(spec.publishedHostPort) }],
|
|
1024
|
-
};
|
|
1025
|
-
}
|
|
1026
|
-
|
|
1027
|
-
const containerConfig: Record<string, unknown> = {
|
|
1028
|
-
Image: this.config.workerProvisioningImage,
|
|
1029
|
-
Cmd: ["sh", "-lc", buildContainerBootstrapScript()],
|
|
1030
|
-
Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
|
|
1031
|
-
User: "root",
|
|
1032
|
-
Labels: {
|
|
1033
|
-
"teamclaw.managed": "true",
|
|
1034
|
-
"teamclaw.team": this.config.teamName,
|
|
1035
|
-
"teamclaw.role": spec.role,
|
|
1036
|
-
"teamclaw.worker_id": spec.workerId,
|
|
1037
|
-
},
|
|
1038
|
-
HostConfig: hostConfig,
|
|
1039
|
-
};
|
|
1040
|
-
|
|
1041
|
-
if (usePortPublishing) {
|
|
1042
|
-
containerConfig.ExposedPorts = { [`${spec.workerPort}/tcp`]: {} };
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
|
-
const response = await this.client.requestJson<{ Id?: string }>(
|
|
1046
|
-
"POST",
|
|
1047
|
-
`/containers/create?name=${encodeURIComponent(instanceName)}`,
|
|
1048
|
-
containerConfig,
|
|
1049
|
-
[201],
|
|
1050
|
-
);
|
|
1051
|
-
|
|
1052
|
-
const instanceId = typeof response.Id === "string" ? response.Id : undefined;
|
|
1053
|
-
if (!instanceId) {
|
|
1054
|
-
throw new Error("Docker create did not return a container ID");
|
|
1055
|
-
}
|
|
1056
|
-
|
|
1057
|
-
await this.client.requestVoid("POST", `/containers/${instanceId}/start`, undefined, [204]);
|
|
1058
|
-
this.logger.info(`Provisioner: started docker worker container ${instanceName} (${instanceId})`);
|
|
1059
|
-
|
|
1060
|
-
return {
|
|
1061
|
-
instanceId,
|
|
1062
|
-
instanceName,
|
|
1063
|
-
};
|
|
1064
|
-
}
|
|
1065
|
-
|
|
1066
|
-
async terminate(record: ProvisionedWorkerRecord): Promise<void> {
|
|
1067
|
-
const target = record.instanceId || record.instanceName;
|
|
1068
|
-
if (!target) {
|
|
1069
|
-
return;
|
|
1070
|
-
}
|
|
1071
|
-
await this.client.requestVoid("DELETE", `/containers/${target}?force=1`, undefined, [204, 404]);
|
|
1072
|
-
}
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
/**
|
|
1076
|
-
* Lightweight Kubernetes API client using in-cluster service account or
|
|
1077
|
-
* kubeconfig for out-of-cluster (via kubectl proxy or direct API).
|
|
1078
|
-
* Avoids requiring kubectl binary in the container image.
|
|
1079
|
-
*/
|
|
1080
|
-
class K8sApiClient {
|
|
1081
|
-
private token: string | undefined;
|
|
1082
|
-
private caCert: Buffer | undefined;
|
|
1083
|
-
private apiServer: string;
|
|
1084
|
-
private contextArgs: string;
|
|
1085
|
-
|
|
1086
|
-
constructor(context: string, private readonly logger: PluginLogger) {
|
|
1087
|
-
this.contextArgs = context;
|
|
1088
|
-
// In-cluster detection: K8s injects these env vars and mounts SA token
|
|
1089
|
-
const host = process.env.KUBERNETES_SERVICE_HOST;
|
|
1090
|
-
const port = process.env.KUBERNETES_SERVICE_PORT;
|
|
1091
|
-
if (host && port) {
|
|
1092
|
-
this.apiServer = `https://${host}:${port}`;
|
|
1093
|
-
try {
|
|
1094
|
-
const fs = require("node:fs");
|
|
1095
|
-
this.token = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8").trim();
|
|
1096
|
-
this.caCert = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt");
|
|
1097
|
-
} catch {
|
|
1098
|
-
logger.warn("K8sApiClient: in-cluster but cannot read service account token — falling back to kubectl");
|
|
1099
|
-
}
|
|
1100
|
-
} else {
|
|
1101
|
-
// Out-of-cluster: delegate to kubectl
|
|
1102
|
-
this.apiServer = "";
|
|
1103
|
-
}
|
|
1104
|
-
}
|
|
1105
|
-
|
|
1106
|
-
private get inCluster(): boolean {
|
|
1107
|
-
return Boolean(this.apiServer && this.token);
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
async createPod(namespace: string, manifest: unknown): Promise<void> {
|
|
1111
|
-
if (this.inCluster) {
|
|
1112
|
-
await this.apiRequest("POST", `/api/v1/namespaces/${namespace}/pods`, manifest, [200, 201]);
|
|
1113
|
-
} else {
|
|
1114
|
-
await runCommand("kubectl", [
|
|
1115
|
-
...buildKubectlContextArgs(this.contextArgs),
|
|
1116
|
-
"apply", "-f", "-",
|
|
1117
|
-
], JSON.stringify(manifest));
|
|
1118
|
-
}
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
async deletePod(namespace: string, podName: string): Promise<void> {
|
|
1122
|
-
if (this.inCluster) {
|
|
1123
|
-
await this.apiRequest("DELETE", `/api/v1/namespaces/${namespace}/pods/${podName}?gracePeriodSeconds=0`, undefined, [200, 202, 404]);
|
|
1124
|
-
} else {
|
|
1125
|
-
await runCommand("kubectl", [
|
|
1126
|
-
...buildKubectlContextArgs(this.contextArgs),
|
|
1127
|
-
"-n", namespace,
|
|
1128
|
-
"delete", "pod", podName,
|
|
1129
|
-
"--ignore-not-found=true", "--grace-period=0", "--force",
|
|
1130
|
-
]);
|
|
1131
|
-
}
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
private async apiRequest(method: string, apiPath: string, body: unknown, okStatuses: number[]): Promise<string> {
|
|
1135
|
-
const payload = body !== undefined ? JSON.stringify(body) : undefined;
|
|
1136
|
-
return new Promise<string>((resolve, reject) => {
|
|
1137
|
-
const url = new URL(apiPath, this.apiServer);
|
|
1138
|
-
const options: https.RequestOptions = {
|
|
1139
|
-
method,
|
|
1140
|
-
hostname: url.hostname,
|
|
1141
|
-
port: url.port,
|
|
1142
|
-
path: url.pathname + url.search,
|
|
1143
|
-
headers: {
|
|
1144
|
-
"Authorization": `Bearer ${this.token}`,
|
|
1145
|
-
...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}),
|
|
1146
|
-
},
|
|
1147
|
-
...(this.caCert ? { ca: this.caCert } : { rejectUnauthorized: false }),
|
|
1148
|
-
};
|
|
1149
|
-
|
|
1150
|
-
const req = https.request(options, (res) => {
|
|
1151
|
-
let data = "";
|
|
1152
|
-
res.on("data", (chunk: string) => { data += chunk; });
|
|
1153
|
-
res.on("end", () => {
|
|
1154
|
-
if (okStatuses.includes(res.statusCode ?? 0)) {
|
|
1155
|
-
resolve(data);
|
|
1156
|
-
} else {
|
|
1157
|
-
reject(new Error(`K8s API ${method} ${apiPath} returned ${res.statusCode}: ${data.slice(0, 500)}`));
|
|
1158
|
-
}
|
|
1159
|
-
});
|
|
1160
|
-
});
|
|
1161
|
-
req.on("error", reject);
|
|
1162
|
-
if (payload) req.write(payload);
|
|
1163
|
-
req.end();
|
|
1164
|
-
});
|
|
1165
|
-
}
|
|
1166
|
-
}
|
|
1167
|
-
|
|
1168
|
-
class KubernetesProvisioner implements WorkerProvisionerBackend {
|
|
1169
|
-
readonly type = "kubernetes" as const;
|
|
1170
|
-
private readonly config: PluginConfig;
|
|
1171
|
-
private readonly logger: PluginLogger;
|
|
1172
|
-
private readonly k8sApi: K8sApiClient;
|
|
1173
|
-
|
|
1174
|
-
constructor(config: PluginConfig, logger: PluginLogger) {
|
|
1175
|
-
this.config = config;
|
|
1176
|
-
this.logger = logger;
|
|
1177
|
-
this.k8sApi = new K8sApiClient(config.workerProvisioningKubernetesContext, logger);
|
|
1178
|
-
}
|
|
1179
|
-
|
|
1180
|
-
async launch(spec: LaunchSpec): Promise<LaunchResult> {
|
|
1181
|
-
if (!this.config.workerProvisioningImage) {
|
|
1182
|
-
throw new Error("workerProvisioningImage is required for kubernetes provisioning");
|
|
1183
|
-
}
|
|
1184
|
-
|
|
1185
|
-
const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
|
|
1186
|
-
const ns = this.config.workerProvisioningKubernetesNamespace;
|
|
1187
|
-
const env = {
|
|
1188
|
-
...spec.env,
|
|
1189
|
-
HOME: "/home/node",
|
|
1190
|
-
OPENCLAW_HOME: "/home/node",
|
|
1191
|
-
OPENCLAW_STATE_DIR: "/home/node/.openclaw",
|
|
1192
|
-
OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
|
|
1193
|
-
OPENCLAW_SKIP_CANVAS_HOST: "1",
|
|
1194
|
-
TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
|
|
1195
|
-
TEAMCLAW_WORKER_ID: spec.workerId,
|
|
1196
|
-
TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
|
|
1197
|
-
...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
|
|
1198
|
-
};
|
|
1199
|
-
const workspaceRoot = this.config.workerProvisioningWorkspaceRoot;
|
|
1200
|
-
const hasPersistentWorkspace = Boolean(
|
|
1201
|
-
workspaceRoot && this.config.workerProvisioningKubernetesWorkspacePersistentVolumeClaim,
|
|
1202
|
-
);
|
|
1203
|
-
const imagePullSecrets = this.config.workerProvisioningKubernetesImagePullSecrets
|
|
1204
|
-
.map((name) => name.trim())
|
|
1205
|
-
.filter((name) => name.length > 0)
|
|
1206
|
-
.map((name) => ({ name }));
|
|
1207
|
-
|
|
1208
|
-
const manifest = {
|
|
1209
|
-
apiVersion: "v1",
|
|
1210
|
-
kind: "Pod",
|
|
1211
|
-
metadata: {
|
|
1212
|
-
name: instanceName,
|
|
1213
|
-
namespace: ns,
|
|
1214
|
-
labels: {
|
|
1215
|
-
app: "teamclaw-worker",
|
|
1216
|
-
"teamclaw.managed": "true",
|
|
1217
|
-
"teamclaw.team": sanitizeName(this.config.teamName, 40),
|
|
1218
|
-
"teamclaw.role": sanitizeName(spec.role, 40),
|
|
1219
|
-
...this.config.workerProvisioningKubernetesLabels,
|
|
1220
|
-
},
|
|
1221
|
-
annotations: {
|
|
1222
|
-
...this.config.workerProvisioningKubernetesAnnotations,
|
|
1223
|
-
},
|
|
1224
|
-
},
|
|
1225
|
-
spec: {
|
|
1226
|
-
restartPolicy: "Never",
|
|
1227
|
-
hostname: buildManagedHostname(this.config.teamName, spec.role, spec.workerId),
|
|
1228
|
-
serviceAccountName: this.config.workerProvisioningKubernetesServiceAccount || undefined,
|
|
1229
|
-
imagePullSecrets: imagePullSecrets.length > 0 ? imagePullSecrets : undefined,
|
|
1230
|
-
securityContext: hasPersistentWorkspace
|
|
1231
|
-
? {
|
|
1232
|
-
runAsUser: 1000,
|
|
1233
|
-
runAsGroup: 1000,
|
|
1234
|
-
fsGroup: 1000,
|
|
1235
|
-
}
|
|
1236
|
-
: undefined,
|
|
1237
|
-
volumes: hasPersistentWorkspace
|
|
1238
|
-
? [
|
|
1239
|
-
{
|
|
1240
|
-
name: "workspace",
|
|
1241
|
-
persistentVolumeClaim: {
|
|
1242
|
-
claimName: this.config.workerProvisioningKubernetesWorkspacePersistentVolumeClaim,
|
|
1243
|
-
},
|
|
1244
|
-
},
|
|
1245
|
-
]
|
|
1246
|
-
: undefined,
|
|
1247
|
-
containers: [
|
|
1248
|
-
{
|
|
1249
|
-
name: "worker",
|
|
1250
|
-
image: this.config.workerProvisioningImage,
|
|
1251
|
-
command: ["sh", "-lc"],
|
|
1252
|
-
args: [buildContainerBootstrapScript()],
|
|
1253
|
-
env: Object.entries(env).map(([name, value]) => ({ name, value })),
|
|
1254
|
-
volumeMounts: hasPersistentWorkspace
|
|
1255
|
-
? [
|
|
1256
|
-
{
|
|
1257
|
-
name: "workspace",
|
|
1258
|
-
mountPath: workspaceRoot,
|
|
1259
|
-
},
|
|
1260
|
-
]
|
|
1261
|
-
: undefined,
|
|
1262
|
-
},
|
|
1263
|
-
],
|
|
1264
|
-
},
|
|
1265
|
-
};
|
|
1266
|
-
|
|
1267
|
-
await this.k8sApi.createPod(ns, manifest);
|
|
1268
|
-
this.logger.info(`Provisioner: applied kubernetes pod ${instanceName}`);
|
|
1269
|
-
|
|
1270
|
-
return {
|
|
1271
|
-
instanceId: instanceName,
|
|
1272
|
-
instanceName,
|
|
1273
|
-
};
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
async terminate(record: ProvisionedWorkerRecord): Promise<void> {
|
|
1277
|
-
const podName = record.instanceName || record.instanceId;
|
|
1278
|
-
if (!podName) {
|
|
1279
|
-
return;
|
|
1280
|
-
}
|
|
1281
|
-
const ns = this.config.workerProvisioningKubernetesNamespace;
|
|
1282
|
-
await this.k8sApi.deletePod(ns, podName);
|
|
1283
|
-
}
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
class DockerApiClient {
|
|
1287
|
-
private readonly endpoint: DockerEndpoint;
|
|
1288
|
-
|
|
1289
|
-
constructor() {
|
|
1290
|
-
this.endpoint = resolveDockerEndpoint();
|
|
1291
|
-
}
|
|
1292
|
-
|
|
1293
|
-
async requestJson<T>(method: string, requestPath: string, body?: unknown, okStatuses: number[] = [200]): Promise<T> {
|
|
1294
|
-
const response = await this.request(method, requestPath, body, okStatuses);
|
|
1295
|
-
if (!response.body) {
|
|
1296
|
-
return {} as T;
|
|
1297
|
-
}
|
|
1298
|
-
return JSON.parse(response.body) as T;
|
|
1299
|
-
}
|
|
1300
|
-
|
|
1301
|
-
async requestVoid(method: string, requestPath: string, body?: unknown, okStatuses: number[] = [200]): Promise<void> {
|
|
1302
|
-
await this.request(method, requestPath, body, okStatuses);
|
|
1303
|
-
}
|
|
1304
|
-
|
|
1305
|
-
private async request(
|
|
1306
|
-
method: string,
|
|
1307
|
-
requestPath: string,
|
|
1308
|
-
body: unknown,
|
|
1309
|
-
okStatuses: number[],
|
|
1310
|
-
): Promise<{ status: number; body: string }> {
|
|
1311
|
-
const payload = body === undefined ? undefined : JSON.stringify(body);
|
|
1312
|
-
// Prefer the daemon's negotiated default unless the operator pins a version explicitly.
|
|
1313
|
-
const finalPath = DOCKER_API_VERSION ? `/${DOCKER_API_VERSION}${requestPath}` : requestPath;
|
|
1314
|
-
|
|
1315
|
-
return await new Promise<{ status: number; body: string }>((resolve, reject) => {
|
|
1316
|
-
const transport = this.endpoint.protocol === "https:" ? https : http;
|
|
1317
|
-
const req = transport.request({
|
|
1318
|
-
method,
|
|
1319
|
-
socketPath: this.endpoint.socketPath,
|
|
1320
|
-
hostname: this.endpoint.hostname,
|
|
1321
|
-
port: this.endpoint.port,
|
|
1322
|
-
path: finalPath,
|
|
1323
|
-
headers: payload
|
|
1324
|
-
? {
|
|
1325
|
-
"Content-Type": "application/json",
|
|
1326
|
-
"Content-Length": Buffer.byteLength(payload),
|
|
1327
|
-
}
|
|
1328
|
-
: undefined,
|
|
1329
|
-
}, (res: any) => {
|
|
1330
|
-
const chunks: Buffer[] = [];
|
|
1331
|
-
res.on("data", (chunk: Buffer) => chunks.push(chunk));
|
|
1332
|
-
res.on("end", () => {
|
|
1333
|
-
const text = Buffer.concat(chunks).toString("utf8");
|
|
1334
|
-
const status = res.statusCode ?? 500;
|
|
1335
|
-
if (!okStatuses.includes(status)) {
|
|
1336
|
-
const message = extractDockerErrorMessage(text) || `Docker API ${method} ${requestPath} failed with ${status}`;
|
|
1337
|
-
reject(new Error(message));
|
|
1338
|
-
return;
|
|
1339
|
-
}
|
|
1340
|
-
resolve({ status, body: text });
|
|
1341
|
-
});
|
|
1342
|
-
});
|
|
1343
|
-
req.on("error", reject);
|
|
1344
|
-
if (payload) {
|
|
1345
|
-
req.write(payload);
|
|
1346
|
-
}
|
|
1347
|
-
req.end();
|
|
1348
|
-
});
|
|
1349
|
-
}
|
|
1350
|
-
}
|
|
1351
|
-
|
|
1352
|
-
type DockerEndpoint = {
|
|
1353
|
-
protocol: "http:" | "https:";
|
|
1354
|
-
socketPath?: string;
|
|
1355
|
-
hostname?: string;
|
|
1356
|
-
port?: number;
|
|
1357
|
-
};
|
|
1358
|
-
|
|
1359
|
-
function resolveDockerApiVersion(): string | null {
|
|
1360
|
-
const configured = process.env.DOCKER_API_VERSION?.trim();
|
|
1361
|
-
if (!configured) {
|
|
1362
|
-
return null;
|
|
1363
|
-
}
|
|
1364
|
-
return configured.startsWith("v") ? configured : `v${configured}`;
|
|
1365
|
-
}
|
|
1366
|
-
|
|
1367
884
|
function createProvisionerBackend(
|
|
1368
885
|
config: PluginConfig,
|
|
1369
886
|
logger: PluginLogger,
|
|
@@ -1381,142 +898,6 @@ function createProvisionerBackend(
|
|
|
1381
898
|
}
|
|
1382
899
|
}
|
|
1383
900
|
|
|
1384
|
-
export function buildProvisionedWorkerConfig(
|
|
1385
|
-
baseConfig: Record<string, unknown>,
|
|
1386
|
-
controllerConfig: PluginConfig,
|
|
1387
|
-
spec: {
|
|
1388
|
-
role: RoleId;
|
|
1389
|
-
controllerUrl: string;
|
|
1390
|
-
workerPort: number;
|
|
1391
|
-
gatewayPort: number;
|
|
1392
|
-
workspaceDir?: string;
|
|
1393
|
-
},
|
|
1394
|
-
): Record<string, unknown> {
|
|
1395
|
-
const config = cloneJson(baseConfig);
|
|
1396
|
-
delete config.channels;
|
|
1397
|
-
const agents = ensureRecord(config.agents);
|
|
1398
|
-
const agentDefaults = ensureRecord(agents.defaults);
|
|
1399
|
-
delete agentDefaults.repoRoot;
|
|
1400
|
-
if (spec.workspaceDir) {
|
|
1401
|
-
agentDefaults.workspace = spec.workspaceDir;
|
|
1402
|
-
} else {
|
|
1403
|
-
delete agentDefaults.workspace;
|
|
1404
|
-
}
|
|
1405
|
-
// The host controller may run a newer openclaw that persists the keyed
|
|
1406
|
-
// agents.entries schema (e.g. agents.entries.teamclaw.model written by the
|
|
1407
|
-
// model-configuration feature). Provisioned workers can run an older
|
|
1408
|
-
// openclaw that rejects unknown agents keys ("Unrecognized key: entries"),
|
|
1409
|
-
// so fold the teamclaw entry's model back into the legacy
|
|
1410
|
-
// agents.defaults.model and drop the entries map. New-schema workers also
|
|
1411
|
-
// accept agents.defaults, keeping the folded config compatible both ways.
|
|
1412
|
-
const agentsRecord = agents as {
|
|
1413
|
-
entries?: Record<string, { model?: string }>;
|
|
1414
|
-
};
|
|
1415
|
-
if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
|
|
1416
|
-
const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
|
|
1417
|
-
if (entryModel && !agentDefaults.model) {
|
|
1418
|
-
agentDefaults.model = entryModel;
|
|
1419
|
-
}
|
|
1420
|
-
// Container backends may run older openclaw runtimes that reject the
|
|
1421
|
-
// keyed agents schema ("Unrecognized key: entries") - fold down to
|
|
1422
|
-
// legacy defaults there. Process workers share the controller's own
|
|
1423
|
-
// runtime, which REQUIRES at least one entry ("agents.entries must
|
|
1424
|
-
// contain at least one configured agent" crash-loop, exit 78, observed
|
|
1425
|
-
// 2026-11-03 when entries was deleted unconditionally) - keep only the
|
|
1426
|
-
// teamclaw worker entry for them.
|
|
1427
|
-
const containerized =
|
|
1428
|
-
controllerConfig.workerProvisioningType === "docker" ||
|
|
1429
|
-
controllerConfig.workerProvisioningType === "kubernetes";
|
|
1430
|
-
if (containerized) {
|
|
1431
|
-
delete agentsRecord.entries;
|
|
1432
|
-
} else {
|
|
1433
|
-
agentsRecord.entries = {
|
|
1434
|
-
[TEAMCLAW_AGENT_ID]: agentsRecord.entries[TEAMCLAW_AGENT_ID] ?? {},
|
|
1435
|
-
};
|
|
1436
|
-
// Pruning entries can dangle defaults.heartbeat.agentId /
|
|
1437
|
-
// defaults.systemAgent.agentId ("main" no longer exists in the worker
|
|
1438
|
-
// config) - remap any dangling agentId reference to the surviving
|
|
1439
|
-
// teamclaw entry.
|
|
1440
|
-
for (const sectionKey of Object.keys(agentDefaults)) {
|
|
1441
|
-
const section = (agentDefaults as Record<string, unknown>)[sectionKey];
|
|
1442
|
-
if (
|
|
1443
|
-
section &&
|
|
1444
|
-
typeof section === "object" &&
|
|
1445
|
-
typeof (section as { agentId?: unknown }).agentId === "string" &&
|
|
1446
|
-
!agentsRecord.entries[(section as { agentId: string }).agentId]
|
|
1447
|
-
) {
|
|
1448
|
-
(section as { agentId: string }).agentId = TEAMCLAW_AGENT_ID;
|
|
1449
|
-
}
|
|
1450
|
-
}
|
|
1451
|
-
}
|
|
1452
|
-
}
|
|
1453
|
-
agents.defaults = agentDefaults;
|
|
1454
|
-
config.agents = agents;
|
|
1455
|
-
|
|
1456
|
-
const gateway = ensureRecord(config.gateway);
|
|
1457
|
-
gateway.mode = "local";
|
|
1458
|
-
// Workers running inside Docker/K8s containers must bind on all
|
|
1459
|
-
// interfaces so the controller (in a sibling container) can reach them.
|
|
1460
|
-
gateway.bind =
|
|
1461
|
-
controllerConfig.workerProvisioningType === "docker" ||
|
|
1462
|
-
controllerConfig.workerProvisioningType === "kubernetes"
|
|
1463
|
-
? "lan"
|
|
1464
|
-
: "loopback";
|
|
1465
|
-
gateway.port = spec.gatewayPort;
|
|
1466
|
-
delete gateway.remote;
|
|
1467
|
-
config.gateway = gateway;
|
|
1468
|
-
|
|
1469
|
-
const plugins = ensureRecord(config.plugins);
|
|
1470
|
-
plugins.enabled = true;
|
|
1471
|
-
if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
|
|
1472
|
-
delete plugins.load;
|
|
1473
|
-
}
|
|
1474
|
-
const entries = ensureRecord(plugins.entries);
|
|
1475
|
-
const teamclawEntry = ensureRecord(entries.teamclaw);
|
|
1476
|
-
teamclawEntry.enabled = true;
|
|
1477
|
-
const teamclawConfig = ensureRecord(teamclawEntry.config);
|
|
1478
|
-
teamclawConfig.mode = "worker";
|
|
1479
|
-
teamclawConfig.processModel = "multi";
|
|
1480
|
-
teamclawConfig.role = spec.role;
|
|
1481
|
-
teamclawConfig.port = spec.workerPort;
|
|
1482
|
-
teamclawConfig.controllerUrl = spec.controllerUrl;
|
|
1483
|
-
teamclawConfig.teamName = controllerConfig.teamName;
|
|
1484
|
-
teamclawConfig.heartbeatIntervalMs = controllerConfig.heartbeatIntervalMs;
|
|
1485
|
-
teamclawConfig.taskTimeoutMs = controllerConfig.taskTimeoutMs;
|
|
1486
|
-
teamclawConfig.gitEnabled = controllerConfig.gitEnabled;
|
|
1487
|
-
teamclawConfig.gitRemoteUrl = controllerConfig.gitRemoteUrl;
|
|
1488
|
-
teamclawConfig.gitDefaultBranch = controllerConfig.gitDefaultBranch;
|
|
1489
|
-
teamclawConfig.gitAuthorName = controllerConfig.gitAuthorName;
|
|
1490
|
-
teamclawConfig.gitAuthorEmail = controllerConfig.gitAuthorEmail;
|
|
1491
|
-
teamclawConfig.workerProvisioningType = "none";
|
|
1492
|
-
teamclawConfig.workerProvisioningControllerUrl = "";
|
|
1493
|
-
teamclawConfig.workerProvisioningRoles = [];
|
|
1494
|
-
teamclawConfig.workerProvisioningMinPerRole = 0;
|
|
1495
|
-
teamclawConfig.workerProvisioningMaxPerRole = 10;
|
|
1496
|
-
teamclawConfig.workerProvisioningIdleTtlMs = controllerConfig.workerProvisioningIdleTtlMs;
|
|
1497
|
-
teamclawConfig.workerProvisioningStartupTimeoutMs = controllerConfig.workerProvisioningStartupTimeoutMs;
|
|
1498
|
-
teamclawConfig.workerProvisioningImage = "";
|
|
1499
|
-
teamclawConfig.workerProvisioningPassEnv = [];
|
|
1500
|
-
teamclawConfig.workerProvisioningExtraEnv = {};
|
|
1501
|
-
teamclawConfig.workerProvisioningDockerNetwork = "";
|
|
1502
|
-
teamclawConfig.workerProvisioningDockerMounts = [];
|
|
1503
|
-
teamclawConfig.workerProvisioningWorkspaceRoot = "";
|
|
1504
|
-
teamclawConfig.workerProvisioningDockerWorkspaceVolume = "";
|
|
1505
|
-
teamclawConfig.workerProvisioningKubernetesNamespace = "default";
|
|
1506
|
-
teamclawConfig.workerProvisioningKubernetesContext = "";
|
|
1507
|
-
teamclawConfig.workerProvisioningKubernetesServiceAccount = "";
|
|
1508
|
-
teamclawConfig.workerProvisioningKubernetesImagePullSecrets = [];
|
|
1509
|
-
teamclawConfig.workerProvisioningKubernetesWorkspacePersistentVolumeClaim = "";
|
|
1510
|
-
teamclawConfig.workerProvisioningKubernetesLabels = {};
|
|
1511
|
-
teamclawConfig.workerProvisioningKubernetesAnnotations = {};
|
|
1512
|
-
teamclawEntry.config = teamclawConfig;
|
|
1513
|
-
entries.teamclaw = teamclawEntry;
|
|
1514
|
-
plugins.entries = entries;
|
|
1515
|
-
config.plugins = plugins;
|
|
1516
|
-
|
|
1517
|
-
return config;
|
|
1518
|
-
}
|
|
1519
|
-
|
|
1520
901
|
function ensureProvisioningState(state: TeamState): TeamProvisioningState {
|
|
1521
902
|
if (!state.provisioning || typeof state.provisioning !== "object") {
|
|
1522
903
|
state.provisioning = { workers: {} };
|
|
@@ -1534,176 +915,6 @@ async function ensureWritableDirectory(dir: string): Promise<void> {
|
|
|
1534
915
|
await fs.rm(probePath, { force: true });
|
|
1535
916
|
}
|
|
1536
917
|
|
|
1537
|
-
function sleep(ms: number): Promise<void> {
|
|
1538
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1539
|
-
}
|
|
1540
|
-
|
|
1541
|
-
async function loadOpenClawConfig(configPath: string): Promise<Record<string, unknown>> {
|
|
1542
|
-
const raw = await fs.readFile(configPath, "utf8");
|
|
1543
|
-
return parseLooseJsonObject(raw, configPath);
|
|
1544
|
-
}
|
|
1545
|
-
|
|
1546
|
-
async function prepareProcessRuntimeExtensions(stateDir: string): Promise<void> {
|
|
1547
|
-
const runtimeExtensionsDir = path.join(stateDir, "extensions");
|
|
1548
|
-
const controllerExtensionsDir = path.join(path.dirname(resolveDefaultOpenClawConfigPath()), "extensions");
|
|
1549
|
-
if (await pathExists(controllerExtensionsDir)) {
|
|
1550
|
-
await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
|
|
1551
|
-
} else {
|
|
1552
|
-
await fs.mkdir(runtimeExtensionsDir, { recursive: true });
|
|
1553
|
-
// Baked-in images set TEAMCLAW_BAKED_IN=true and the legacy helper
|
|
1554
|
-
// returned "" for that case, so the symlink target was empty and
|
|
1555
|
-
// process workers fell back to resolving the plugin from their cwd
|
|
1556
|
-
// ("/app/dist/openclaw.plugin.json" not found → exit loop, k3s e2e
|
|
1557
|
-
// 2026-11-03). Probe the baked image layout instead: the controller
|
|
1558
|
-
// entrypoint (process.argv[1], e.g. /app/dist/index.js) sits below
|
|
1559
|
-
// the app root, where the runtime image ships
|
|
1560
|
-
// /app/extensions/teamclaw with its openclaw.plugin.json.
|
|
1561
|
-
const pluginRootDir = process.env.TEAMCLAW_BAKED_IN === "true"
|
|
1562
|
-
? await resolveBakedTeamClawPluginRootDir()
|
|
1563
|
-
: resolveCurrentTeamClawPluginRootDir();
|
|
1564
|
-
if (pluginRootDir) {
|
|
1565
|
-
await fs.symlink(pluginRootDir, path.join(runtimeExtensionsDir, "teamclaw"), "dir");
|
|
1566
|
-
}
|
|
1567
|
-
}
|
|
1568
|
-
|
|
1569
|
-
await copyControllerAuthProfiles(stateDir);
|
|
1570
|
-
}
|
|
1571
|
-
|
|
1572
|
-
async function copyControllerAuthProfiles(stateDir: string): Promise<void> {
|
|
1573
|
-
const candidateControllerStateDirs = [
|
|
1574
|
-
path.dirname(resolveDefaultOpenClawConfigPath()),
|
|
1575
|
-
resolveDefaultOpenClawStateDir(),
|
|
1576
|
-
];
|
|
1577
|
-
const candidateAuthProfilePaths = [
|
|
1578
|
-
path.join(resolveTeamClawAgentDir(), "auth-profiles.json"),
|
|
1579
|
-
path.join(resolveDefaultAgentDir(), "auth-profiles.json"),
|
|
1580
|
-
...candidateControllerStateDirs.flatMap((controllerStateDir) => [
|
|
1581
|
-
path.join(controllerStateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
|
|
1582
|
-
path.join(controllerStateDir, "agents", "main", "agent", "auth-profiles.json"),
|
|
1583
|
-
]),
|
|
1584
|
-
].filter((value, index, values) => values.indexOf(value) === index);
|
|
1585
|
-
let controllerAuthProfilesPath: string | undefined;
|
|
1586
|
-
for (const candidatePath of candidateAuthProfilePaths) {
|
|
1587
|
-
if (await pathExists(candidatePath)) {
|
|
1588
|
-
controllerAuthProfilesPath = candidatePath;
|
|
1589
|
-
break;
|
|
1590
|
-
}
|
|
1591
|
-
}
|
|
1592
|
-
if (!controllerAuthProfilesPath) {
|
|
1593
|
-
return;
|
|
1594
|
-
}
|
|
1595
|
-
const runtimeAuthProfilePaths = [
|
|
1596
|
-
path.join(stateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
|
|
1597
|
-
path.join(stateDir, "agents", "main", "agent", "auth-profiles.json"),
|
|
1598
|
-
];
|
|
1599
|
-
for (const runtimeAuthProfilesPath of runtimeAuthProfilePaths) {
|
|
1600
|
-
await fs.mkdir(path.dirname(runtimeAuthProfilesPath), { recursive: true });
|
|
1601
|
-
await fs.copyFile(controllerAuthProfilesPath, runtimeAuthProfilesPath);
|
|
1602
|
-
}
|
|
1603
|
-
}
|
|
1604
|
-
|
|
1605
|
-
function cloneJson<T>(value: T): T {
|
|
1606
|
-
return JSON.parse(JSON.stringify(value)) as T;
|
|
1607
|
-
}
|
|
1608
|
-
|
|
1609
|
-
function requiresDedicatedHostPortsForProvisioner(
|
|
1610
|
-
provider: WorkerProvisioningType,
|
|
1611
|
-
config: PluginConfig,
|
|
1612
|
-
): boolean {
|
|
1613
|
-
if (provider === "process") {
|
|
1614
|
-
return true;
|
|
1615
|
-
}
|
|
1616
|
-
return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
|
|
1617
|
-
}
|
|
1618
|
-
|
|
1619
|
-
function isDockerHostNetwork(networkMode: string): boolean {
|
|
1620
|
-
return networkMode.trim().toLowerCase() === "host";
|
|
1621
|
-
}
|
|
1622
|
-
|
|
1623
|
-
function extractDockerBindTarget(bind: string): string | null {
|
|
1624
|
-
for (const part of bind.split(":").reverse()) {
|
|
1625
|
-
const trimmed = part.trim();
|
|
1626
|
-
if (trimmed.startsWith("/")) {
|
|
1627
|
-
return trimmed;
|
|
1628
|
-
}
|
|
1629
|
-
}
|
|
1630
|
-
return null;
|
|
1631
|
-
}
|
|
1632
|
-
|
|
1633
|
-
function appendNoProxyEntries(env: Record<string, string>, controllerUrl: string): Record<string, string> {
|
|
1634
|
-
const requiredEntries = resolveRequiredNoProxyEntries(controllerUrl);
|
|
1635
|
-
if (requiredEntries.length === 0) {
|
|
1636
|
-
return env;
|
|
1637
|
-
}
|
|
1638
|
-
|
|
1639
|
-
const upperBase = env.NO_PROXY ?? process.env.NO_PROXY ?? process.env.no_proxy ?? "";
|
|
1640
|
-
const lowerBase = env.no_proxy ?? process.env.no_proxy ?? env.NO_PROXY ?? process.env.NO_PROXY ?? "";
|
|
1641
|
-
|
|
1642
|
-
env.NO_PROXY = mergeNoProxyEntries(upperBase, requiredEntries);
|
|
1643
|
-
env.no_proxy = mergeNoProxyEntries(lowerBase, requiredEntries);
|
|
1644
|
-
return env;
|
|
1645
|
-
}
|
|
1646
|
-
|
|
1647
|
-
function resolveRequiredNoProxyEntries(controllerUrl: string): string[] {
|
|
1648
|
-
const required = new Set<string>(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
|
1649
|
-
try {
|
|
1650
|
-
const host = new URL(controllerUrl).hostname.trim();
|
|
1651
|
-
if (host) {
|
|
1652
|
-
required.add(host);
|
|
1653
|
-
}
|
|
1654
|
-
} catch {
|
|
1655
|
-
// Ignore malformed controller URLs; worker registration will fail separately.
|
|
1656
|
-
}
|
|
1657
|
-
return Array.from(required);
|
|
1658
|
-
}
|
|
1659
|
-
|
|
1660
|
-
function mergeNoProxyEntries(existing: string, requiredEntries: string[]): string {
|
|
1661
|
-
const tokens = new Map<string, string>();
|
|
1662
|
-
for (const entry of existing.split(",")) {
|
|
1663
|
-
const trimmed = entry.trim();
|
|
1664
|
-
if (!trimmed) {
|
|
1665
|
-
continue;
|
|
1666
|
-
}
|
|
1667
|
-
tokens.set(trimmed.toLowerCase(), trimmed);
|
|
1668
|
-
}
|
|
1669
|
-
for (const entry of requiredEntries) {
|
|
1670
|
-
const trimmed = entry.trim();
|
|
1671
|
-
if (!trimmed) {
|
|
1672
|
-
continue;
|
|
1673
|
-
}
|
|
1674
|
-
tokens.set(trimmed.toLowerCase(), trimmed);
|
|
1675
|
-
}
|
|
1676
|
-
return Array.from(tokens.values()).join(",");
|
|
1677
|
-
}
|
|
1678
|
-
|
|
1679
|
-
async function pathExists(targetPath: string): Promise<boolean> {
|
|
1680
|
-
try {
|
|
1681
|
-
await fs.access(targetPath);
|
|
1682
|
-
return true;
|
|
1683
|
-
} catch (err) {
|
|
1684
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
1685
|
-
return false;
|
|
1686
|
-
}
|
|
1687
|
-
throw err;
|
|
1688
|
-
}
|
|
1689
|
-
}
|
|
1690
|
-
|
|
1691
|
-
function ensureRecord(value: unknown): Record<string, unknown> {
|
|
1692
|
-
return value && typeof value === "object" && !Array.isArray(value)
|
|
1693
|
-
? { ...(value as Record<string, unknown>) }
|
|
1694
|
-
: {};
|
|
1695
|
-
}
|
|
1696
|
-
|
|
1697
|
-
function parseLooseJsonObject(raw: string, configPath: string): Record<string, unknown> {
|
|
1698
|
-
try {
|
|
1699
|
-
return JSON5.parse(raw) as Record<string, unknown>;
|
|
1700
|
-
} catch (err) {
|
|
1701
|
-
throw new Error(
|
|
1702
|
-
`Failed to parse OpenClaw config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`,
|
|
1703
|
-
);
|
|
1704
|
-
}
|
|
1705
|
-
}
|
|
1706
|
-
|
|
1707
918
|
async function reserveEphemeralPort(): Promise<number> {
|
|
1708
919
|
return await new Promise<number>((resolve, reject) => {
|
|
1709
920
|
const server = net.createServer();
|
|
@@ -1725,280 +936,3 @@ async function reserveEphemeralPort(): Promise<number> {
|
|
|
1725
936
|
server.on("error", reject);
|
|
1726
937
|
});
|
|
1727
938
|
}
|
|
1728
|
-
|
|
1729
|
-
function resolveGatewayEntrypoint(): string {
|
|
1730
|
-
const scriptPath = process.argv[1];
|
|
1731
|
-
if (!scriptPath) {
|
|
1732
|
-
throw new Error("Unable to resolve OpenClaw gateway entrypoint");
|
|
1733
|
-
}
|
|
1734
|
-
return path.resolve(scriptPath);
|
|
1735
|
-
}
|
|
1736
|
-
|
|
1737
|
-
function resolveCurrentTeamClawPluginRootDir(): string {
|
|
1738
|
-
return process.env.TEAMCLAW_BAKED_IN === "true" ? "" : path.resolve(fileURLToPath(new URL("../../", import.meta.url)));
|
|
1739
|
-
}
|
|
1740
|
-
|
|
1741
|
-
/**
|
|
1742
|
-
* Locate the teamclaw plugin root inside a baked runtime image. The image
|
|
1743
|
-
* ships the plugin at <app-root>/extensions/teamclaw; the controller
|
|
1744
|
-
* entrypoint (process.argv[1]) lives under <app-root>, so walk up from it.
|
|
1745
|
-
* Returns "" when no candidate carries an openclaw.plugin.json (the
|
|
1746
|
-
* caller then skips the symlink instead of creating a dangling one).
|
|
1747
|
-
*/
|
|
1748
|
-
async function resolveBakedTeamClawPluginRootDir(): Promise<string> {
|
|
1749
|
-
const entrypoint = process.argv[1] ? path.resolve(process.argv[1]) : "";
|
|
1750
|
-
const candidates = entrypoint
|
|
1751
|
-
? [
|
|
1752
|
-
path.resolve(entrypoint, "../../extensions/teamclaw"),
|
|
1753
|
-
path.resolve(entrypoint, "../extensions/teamclaw"),
|
|
1754
|
-
]
|
|
1755
|
-
: [];
|
|
1756
|
-
candidates.push("/app/extensions/teamclaw");
|
|
1757
|
-
for (const candidate of candidates) {
|
|
1758
|
-
try {
|
|
1759
|
-
await fs.access(path.join(candidate, "openclaw.plugin.json"));
|
|
1760
|
-
return candidate;
|
|
1761
|
-
} catch {
|
|
1762
|
-
// try the next candidate layout
|
|
1763
|
-
}
|
|
1764
|
-
}
|
|
1765
|
-
return "";
|
|
1766
|
-
}
|
|
1767
|
-
|
|
1768
|
-
function attachChildLogs(child: ChildProcess, logger: PluginLogger, prefix: string): void {
|
|
1769
|
-
if (child.stdout) {
|
|
1770
|
-
const stdoutReader = readline.createInterface({ input: child.stdout });
|
|
1771
|
-
stdoutReader.on("line", (line: string) => {
|
|
1772
|
-
logger.info(`${prefix}: ${line}`);
|
|
1773
|
-
});
|
|
1774
|
-
}
|
|
1775
|
-
if (child.stderr) {
|
|
1776
|
-
const stderrReader = readline.createInterface({ input: child.stderr });
|
|
1777
|
-
stderrReader.on("line", (line: string) => {
|
|
1778
|
-
logger.warn(`${prefix}: ${line}`);
|
|
1779
|
-
});
|
|
1780
|
-
}
|
|
1781
|
-
}
|
|
1782
|
-
|
|
1783
|
-
async function stopChildProcess(child: ChildProcess): Promise<void> {
|
|
1784
|
-
if (child.exitCode !== null || child.signalCode !== null) {
|
|
1785
|
-
return;
|
|
1786
|
-
}
|
|
1787
|
-
|
|
1788
|
-
await new Promise<void>((resolve) => {
|
|
1789
|
-
const timeout = setTimeout(() => {
|
|
1790
|
-
if (child.exitCode === null && child.signalCode === null && child.pid) {
|
|
1791
|
-
try {
|
|
1792
|
-
process.kill(child.pid, "SIGKILL");
|
|
1793
|
-
} catch {
|
|
1794
|
-
// ignore
|
|
1795
|
-
}
|
|
1796
|
-
}
|
|
1797
|
-
resolve();
|
|
1798
|
-
}, PROCESS_TERMINATION_TIMEOUT_MS);
|
|
1799
|
-
const timer = timeout as unknown as { unref?: () => void };
|
|
1800
|
-
timer.unref?.();
|
|
1801
|
-
|
|
1802
|
-
child.once("exit", () => {
|
|
1803
|
-
clearTimeout(timeout);
|
|
1804
|
-
resolve();
|
|
1805
|
-
});
|
|
1806
|
-
|
|
1807
|
-
child.kill("SIGTERM");
|
|
1808
|
-
});
|
|
1809
|
-
}
|
|
1810
|
-
|
|
1811
|
-
function sanitizePathSegment(value: string): string {
|
|
1812
|
-
const normalized = value.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
|
|
1813
|
-
return normalized || "worker";
|
|
1814
|
-
}
|
|
1815
|
-
|
|
1816
|
-
function sanitizeName(value: string, maxLength = 63): string {
|
|
1817
|
-
const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
|
|
1818
|
-
return normalized || "teamclaw";
|
|
1819
|
-
}
|
|
1820
|
-
|
|
1821
|
-
function buildManagedInstanceName(teamName: string, role: RoleId, workerId: string): string {
|
|
1822
|
-
return buildManagedName("teamclaw", teamName, role, workerId, {
|
|
1823
|
-
teamBudget: 18,
|
|
1824
|
-
roleBudget: 12,
|
|
1825
|
-
workerBudget: 12,
|
|
1826
|
-
hashLength: 8,
|
|
1827
|
-
maxLength: 63,
|
|
1828
|
-
});
|
|
1829
|
-
}
|
|
1830
|
-
|
|
1831
|
-
function buildManagedHostname(teamName: string, role: RoleId, workerId: string): string {
|
|
1832
|
-
return buildManagedName("tc", teamName, role, workerId, {
|
|
1833
|
-
teamBudget: 10,
|
|
1834
|
-
roleBudget: 8,
|
|
1835
|
-
workerBudget: 6,
|
|
1836
|
-
hashLength: 6,
|
|
1837
|
-
maxLength: 40,
|
|
1838
|
-
});
|
|
1839
|
-
}
|
|
1840
|
-
|
|
1841
|
-
function buildManagedName(
|
|
1842
|
-
prefix: string,
|
|
1843
|
-
teamName: string,
|
|
1844
|
-
role: RoleId,
|
|
1845
|
-
workerId: string,
|
|
1846
|
-
options: {
|
|
1847
|
-
teamBudget: number;
|
|
1848
|
-
roleBudget: number;
|
|
1849
|
-
workerBudget: number;
|
|
1850
|
-
hashLength: number;
|
|
1851
|
-
maxLength: number;
|
|
1852
|
-
},
|
|
1853
|
-
): string {
|
|
1854
|
-
const teamPart = sanitizeLeadingSegment(teamName, options.teamBudget, "team");
|
|
1855
|
-
const rolePart = sanitizeLeadingSegment(role, options.roleBudget, "worker");
|
|
1856
|
-
const workerPart = sanitizeTrailingSegment(workerId, options.workerBudget, "worker");
|
|
1857
|
-
const hash = shortStableHash(`${teamName}:${role}:${workerId}`).slice(0, options.hashLength);
|
|
1858
|
-
return sanitizeName(`${prefix}-${teamPart}-${rolePart}-${workerPart}-${hash}`, options.maxLength);
|
|
1859
|
-
}
|
|
1860
|
-
|
|
1861
|
-
function shortStableHash(value: string): string {
|
|
1862
|
-
return createHash("sha1").update(value).digest("hex");
|
|
1863
|
-
}
|
|
1864
|
-
|
|
1865
|
-
function sanitizeLeadingSegment(value: string, maxLength: number, fallback: string): string {
|
|
1866
|
-
const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
|
|
1867
|
-
return normalized || fallback;
|
|
1868
|
-
}
|
|
1869
|
-
|
|
1870
|
-
function sanitizeTrailingSegment(value: string, maxLength: number, fallback: string): string {
|
|
1871
|
-
const normalized = sanitizePathSegment(value).slice(-maxLength).replace(/^-+|-+$/g, "");
|
|
1872
|
-
return normalized || fallback;
|
|
1873
|
-
}
|
|
1874
|
-
|
|
1875
|
-
function buildContainerBootstrapScript(): string {
|
|
1876
|
-
return [
|
|
1877
|
-
"set -eu",
|
|
1878
|
-
"mkdir -p \"$OPENCLAW_STATE_DIR\"",
|
|
1879
|
-
"if [ -n \"${TEAMCLAW_WORKSPACE_DIR:-}\" ]; then mkdir -p \"$TEAMCLAW_WORKSPACE_DIR\"; fi",
|
|
1880
|
-
"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);'",
|
|
1881
|
-
"exec node dist/index.js gateway --allow-unconfigured",
|
|
1882
|
-
].join("\n");
|
|
1883
|
-
}
|
|
1884
|
-
|
|
1885
|
-
function buildDockerBinds(config: PluginConfig): string[] {
|
|
1886
|
-
const binds = [...config.workerProvisioningDockerMounts];
|
|
1887
|
-
if (!binds.some((bind) => extractDockerBindTarget(bind) === DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR)) {
|
|
1888
|
-
const _pd = resolveCurrentTeamClawPluginRootDir();
|
|
1889
|
-
if (_pd) binds.unshift(`${_pd}:${DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR}:ro`);
|
|
1890
|
-
}
|
|
1891
|
-
if (config.workerProvisioningDockerWorkspaceVolume && config.workerProvisioningWorkspaceRoot) {
|
|
1892
|
-
binds.unshift(`${config.workerProvisioningDockerWorkspaceVolume}:${config.workerProvisioningWorkspaceRoot}`);
|
|
1893
|
-
}
|
|
1894
|
-
return [...new Set(binds)];
|
|
1895
|
-
}
|
|
1896
|
-
|
|
1897
|
-
function buildProvisionedWorkspaceDir(
|
|
1898
|
-
provider: WorkerProvisioningType,
|
|
1899
|
-
config: PluginConfig,
|
|
1900
|
-
role: RoleId,
|
|
1901
|
-
workerId: string,
|
|
1902
|
-
): string {
|
|
1903
|
-
// Process-type workers run on the same host — share the controller's workspace
|
|
1904
|
-
// so that file artifacts (previews, deliverables) are immediately visible to
|
|
1905
|
-
// the controller without requiring git sync or file transfer.
|
|
1906
|
-
if (provider === "process") {
|
|
1907
|
-
return resolveTeamClawAgentWorkspaceRootDir();
|
|
1908
|
-
}
|
|
1909
|
-
|
|
1910
|
-
if (
|
|
1911
|
-
(provider !== "docker" && provider !== "kubernetes") ||
|
|
1912
|
-
!config.workerProvisioningWorkspaceRoot
|
|
1913
|
-
) {
|
|
1914
|
-
return "";
|
|
1915
|
-
}
|
|
1916
|
-
|
|
1917
|
-
return path.posix.join(
|
|
1918
|
-
config.workerProvisioningWorkspaceRoot,
|
|
1919
|
-
sanitizePathSegment(config.teamName),
|
|
1920
|
-
sanitizePathSegment(role),
|
|
1921
|
-
sanitizePathSegment(workerId),
|
|
1922
|
-
);
|
|
1923
|
-
}
|
|
1924
|
-
|
|
1925
|
-
function getConfiguredWorkerWorkspaceDir(config: Record<string, unknown>): string {
|
|
1926
|
-
const agents = ensureRecord(config.agents);
|
|
1927
|
-
const defaults = ensureRecord(agents.defaults);
|
|
1928
|
-
return typeof defaults.workspace === "string" ? defaults.workspace : "";
|
|
1929
|
-
}
|
|
1930
|
-
|
|
1931
|
-
function resolveDockerEndpoint(): DockerEndpoint {
|
|
1932
|
-
const dockerHost = process.env.DOCKER_HOST?.trim();
|
|
1933
|
-
if (!dockerHost) {
|
|
1934
|
-
return {
|
|
1935
|
-
protocol: "http:",
|
|
1936
|
-
socketPath: "/var/run/docker.sock",
|
|
1937
|
-
};
|
|
1938
|
-
}
|
|
1939
|
-
|
|
1940
|
-
if (dockerHost.startsWith("unix://")) {
|
|
1941
|
-
return {
|
|
1942
|
-
protocol: "http:",
|
|
1943
|
-
socketPath: dockerHost.slice("unix://".length),
|
|
1944
|
-
};
|
|
1945
|
-
}
|
|
1946
|
-
|
|
1947
|
-
const normalized = dockerHost.startsWith("tcp://")
|
|
1948
|
-
? dockerHost.replace(/^tcp:\/\//, "http://")
|
|
1949
|
-
: dockerHost;
|
|
1950
|
-
const url = new URL(normalized);
|
|
1951
|
-
return {
|
|
1952
|
-
protocol: url.protocol === "https:" ? "https:" : "http:",
|
|
1953
|
-
hostname: url.hostname,
|
|
1954
|
-
port: url.port ? Number(url.port) : (url.protocol === "https:" ? 443 : 2375),
|
|
1955
|
-
};
|
|
1956
|
-
}
|
|
1957
|
-
|
|
1958
|
-
function extractDockerErrorMessage(body: string): string | null {
|
|
1959
|
-
if (!body.trim()) {
|
|
1960
|
-
return null;
|
|
1961
|
-
}
|
|
1962
|
-
try {
|
|
1963
|
-
const parsed = JSON.parse(body) as { message?: unknown };
|
|
1964
|
-
return typeof parsed.message === "string" ? parsed.message : body;
|
|
1965
|
-
} catch {
|
|
1966
|
-
return body;
|
|
1967
|
-
}
|
|
1968
|
-
}
|
|
1969
|
-
|
|
1970
|
-
async function runCommand(command: string, args: string[], stdin?: string): Promise<void> {
|
|
1971
|
-
await new Promise<void>((resolve, reject) => {
|
|
1972
|
-
const child = spawn(command, args, {
|
|
1973
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
1974
|
-
env: process.env,
|
|
1975
|
-
});
|
|
1976
|
-
let stderr = "";
|
|
1977
|
-
let stdout = "";
|
|
1978
|
-
|
|
1979
|
-
if (stdin) {
|
|
1980
|
-
child.stdin?.end(stdin);
|
|
1981
|
-
} else {
|
|
1982
|
-
child.stdin?.end();
|
|
1983
|
-
}
|
|
1984
|
-
|
|
1985
|
-
child.stdout?.on("data", (chunk: Buffer) => {
|
|
1986
|
-
stdout += chunk.toString("utf8");
|
|
1987
|
-
});
|
|
1988
|
-
child.stderr?.on("data", (chunk: Buffer) => {
|
|
1989
|
-
stderr += chunk.toString("utf8");
|
|
1990
|
-
});
|
|
1991
|
-
child.on("error", reject);
|
|
1992
|
-
child.on("exit", (code: number | null) => {
|
|
1993
|
-
if (code === 0) {
|
|
1994
|
-
resolve();
|
|
1995
|
-
return;
|
|
1996
|
-
}
|
|
1997
|
-
reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${(stderr || stdout).trim()}`));
|
|
1998
|
-
});
|
|
1999
|
-
});
|
|
2000
|
-
}
|
|
2001
|
-
|
|
2002
|
-
function buildKubectlContextArgs(context: string): string[] {
|
|
2003
|
-
return context ? ["--context", context] : [];
|
|
2004
|
-
}
|