@teamclaws/teamclaw 2026.8.1 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
@@ -1,26 +1,39 @@
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
- import { ROLES } from "../roles.js";
34
+ // Phase 1.3: the role universe and the fallback role come from the active
35
+ // TeamProfile loader (software-rd baseline).
36
+ import { getActiveRoleIds, getActiveDefaultRole } from "../profile-loader.js";
24
37
  import { inferTaskRole } from "./role-inference.js";
25
38
  import type {
26
39
  PluginConfig,
@@ -31,19 +44,37 @@ import type {
31
44
  TaskInfo,
32
45
  TeamProvisioningState,
33
46
  TeamState,
34
- WorkerProvisioningType,
35
47
  WorkerStatus,
36
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
+
37
69
 
38
70
  const DEFAULT_CONTAINER_WORKER_PORT = 9527;
39
71
  const DEFAULT_CONTAINER_GATEWAY_PORT = 18789;
40
- const DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR = "/app/extensions/teamclaw";
72
+
41
73
  const PROVISIONING_RECORD_RETENTION_MS = 6 * 60 * 60 * 1000;
42
74
  const PROVISIONING_FAILURE_COOLDOWN_MS = 30_000;
43
75
  const PROCESS_TERMINATION_TIMEOUT_MS = 10_000;
44
76
  const STARTUP_READINESS_POLL_INTERVAL_MS = 1_000;
45
77
  const STARTUP_READINESS_RETRY_INTERVAL_MS = 5_000;
46
- const DOCKER_API_VERSION = resolveDockerApiVersion();
47
78
 
48
79
  export type WorkerProvisioningManagerDeps = {
49
80
  config: PluginConfig;
@@ -54,32 +85,6 @@ export type WorkerProvisioningManagerDeps = {
54
85
  actualControllerPort?: number;
55
86
  };
56
87
 
57
- type LaunchSpec = {
58
- workerId: string;
59
- role: RoleId;
60
- launchToken: string;
61
- controllerUrl: string;
62
- workerPort: number;
63
- gatewayPort: number;
64
- publishedHostPort?: number;
65
- workspaceDir?: string;
66
- env: Record<string, string>;
67
- configJson: string;
68
- };
69
-
70
- type LaunchResult = {
71
- instanceId?: string;
72
- instanceName?: string;
73
- runtimeHomeDir?: string;
74
- };
75
-
76
- interface WorkerProvisionerBackend {
77
- readonly type: WorkerProvisioningType;
78
- launch(spec: LaunchSpec): Promise<LaunchResult>;
79
- terminate(record: ProvisionedWorkerRecord): Promise<void>;
80
- stop?(): Promise<void>;
81
- }
82
-
83
88
  export class WorkerProvisioningManager {
84
89
  private deps: WorkerProvisioningManagerDeps;
85
90
  private readonly backend: WorkerProvisionerBackend | null;
@@ -87,6 +92,12 @@ export class WorkerProvisioningManager {
87
92
  private reconcilePromise: Promise<void> | null = null;
88
93
  private reconcileQueued = false;
89
94
  private stopped = false;
95
+ // Phase 2.1 (design 2.3, switch step 2): while a team profile switch drains
96
+ // and archives the old team, the periodic reconcile must not fight the
97
+ // drain by launching replacement workers for the outgoing profile's
98
+ // pending tasks. Suspended reconcile calls return immediately; it is
99
+ // lifted before the new profile's warmup so normal operation resumes.
100
+ private reconcileSuspended = false;
90
101
 
91
102
  constructor(deps: WorkerProvisioningManagerDeps) {
92
103
  this.deps = deps;
@@ -153,7 +164,10 @@ export class WorkerProvisioningManager {
153
164
  reason: `Provisioned worker ${workerId} expected role ${record.role}, got ${role}`,
154
165
  };
155
166
  }
156
- if (!launchToken || launchToken !== record.launchToken) {
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)) {
157
171
  return {
158
172
  ok: false,
159
173
  managed: true,
@@ -225,8 +239,13 @@ export class WorkerProvisioningManager {
225
239
  await this.terminateManagedWorker(workerId, reason, "terminated");
226
240
  }
227
241
 
242
+ /** Phase 2.1: suspend/resume the reconcile loop during a team profile switch. */
243
+ setReconcileSuspended(suspended: boolean): void {
244
+ this.reconcileSuspended = suspended;
245
+ }
246
+
228
247
  async requestReconcile(reason: string): Promise<void> {
229
- if (!this.backend || this.stopped) {
248
+ if (!this.backend || this.stopped || this.reconcileSuspended) {
230
249
  return;
231
250
  }
232
251
 
@@ -324,6 +343,21 @@ export class WorkerProvisioningManager {
324
343
  this.deps.logger.warn(`Provisioner: startup readiness degraded: ${failureDetails}`);
325
344
  }
326
345
 
346
+ /**
347
+ * Phase 2.1 (design 2.3, switch step 5): warm the new profile's warmupRoles
348
+ * through the standard launch path after a profile switch. Dispatches the
349
+ * launches (prerequisites + ensureWarmWorkersForRoles); the workers then
350
+ * register asynchronously exactly like a cold start, so readiness tracking
351
+ * (startupReadiness polling / reconcile) covers the rest.
352
+ */
353
+ async warmRolesForTeamSwitch(roles: RoleId[], reason: string): Promise<void> {
354
+ if (!this.backend || this.stopped) {
355
+ return;
356
+ }
357
+ await this.ensureStartupProvisioningPrerequisites();
358
+ await this.ensureWarmWorkersForRoles(roles, reason);
359
+ }
360
+
327
361
  async stop(): Promise<void> {
328
362
  if (!this.backend) {
329
363
  return;
@@ -408,7 +442,7 @@ export class WorkerProvisioningManager {
408
442
  if (configured.length > 0) {
409
443
  return [...new Set(configured)];
410
444
  }
411
- return ["developer"];
445
+ return [getActiveDefaultRole()];
412
446
  }
413
447
 
414
448
  private async ensureStartupProvisioningPrerequisites(): Promise<void> {
@@ -558,7 +592,10 @@ export class WorkerProvisioningManager {
558
592
  }
559
593
 
560
594
  const workerId = `provisioned-${role}-${generateId()}`;
561
- const launchToken = `${generateId()}-${generateId()}`;
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();
562
599
  const controllerUrl = this.resolveControllerUrl();
563
600
  const requiresDedicatedHostPorts = requiresDedicatedHostPortsForProvisioner(
564
601
  this.backend.type,
@@ -695,7 +732,7 @@ export class WorkerProvisioningManager {
695
732
  const roleIds = new Set<RoleId>(
696
733
  this.deps.config.workerProvisioningRoles.length > 0
697
734
  ? this.deps.config.workerProvisioningRoles
698
- : ROLES.map((role) => role.id),
735
+ : getActiveRoleIds(),
699
736
  );
700
737
 
701
738
  if (!state) {
@@ -844,498 +881,6 @@ export class WorkerProvisioningManager {
844
881
  }
845
882
  }
846
883
 
847
- class ProcessProvisioner implements WorkerProvisionerBackend {
848
- readonly type = "process" as const;
849
- private readonly logger: PluginLogger;
850
- private readonly processByWorkerId = new Map<string, ChildProcess>();
851
- private readonly baseDirPromise: Promise<string>;
852
-
853
- constructor(logger: PluginLogger) {
854
- this.logger = logger;
855
- const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
856
- this.baseDirPromise = fs.mkdir(provisionedRoot, { recursive: true })
857
- .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
858
- }
859
-
860
- async launch(spec: LaunchSpec): Promise<LaunchResult> {
861
- const baseDir = await this.baseDirPromise;
862
- const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
863
- const stateDir = path.join(runtimeHomeDir, ".openclaw");
864
- const configPath = path.join(stateDir, "openclaw.json");
865
- await fs.mkdir(stateDir, { recursive: true });
866
- await prepareProcessRuntimeExtensions(stateDir);
867
- await fs.writeFile(configPath, spec.configJson, "utf8");
868
-
869
- const gatewayEntrypoint = resolveGatewayEntrypoint();
870
- const child = spawn(process.execPath, [
871
- gatewayEntrypoint,
872
- "gateway",
873
- "--allow-unconfigured",
874
- "--bind",
875
- "loopback",
876
- "--port",
877
- String(spec.gatewayPort),
878
- ], {
879
- cwd: path.dirname(gatewayEntrypoint),
880
- env: {
881
- ...process.env,
882
- ...spec.env,
883
- HOME: runtimeHomeDir,
884
- OPENCLAW_HOME: runtimeHomeDir,
885
- OPENCLAW_STATE_DIR: stateDir,
886
- OPENCLAW_CONFIG_PATH: configPath,
887
- OPENCLAW_SKIP_CANVAS_HOST: "1",
888
- TEAMCLAW_WORKER_ID: spec.workerId,
889
- TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
890
- ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
891
- },
892
- stdio: ["ignore", "pipe", "pipe"],
893
- });
894
-
895
- this.processByWorkerId.set(spec.workerId, child);
896
- attachChildLogs(child, this.logger, `ProvisionedWorker[${spec.role}]`);
897
- child.on("exit", (code: number | null, signal: string | null) => {
898
- this.processByWorkerId.delete(spec.workerId);
899
- this.logger.info(
900
- `Provisioner: process worker ${spec.workerId} exited (code=${String(code)}, signal=${String(signal)})`,
901
- );
902
- });
903
-
904
- return {
905
- instanceId: child.pid ? `pid:${child.pid}` : undefined,
906
- instanceName: spec.workerId,
907
- runtimeHomeDir,
908
- };
909
- }
910
-
911
- async terminate(record: ProvisionedWorkerRecord): Promise<void> {
912
- const child = this.processByWorkerId.get(record.workerId);
913
- if (child) {
914
- await stopChildProcess(child);
915
- this.processByWorkerId.delete(record.workerId);
916
- } else if (record.instanceId?.startsWith("pid:")) {
917
- const pid = Number(record.instanceId.slice("pid:".length));
918
- if (Number.isFinite(pid) && pid > 0) {
919
- try {
920
- process.kill(pid, "SIGTERM");
921
- } catch {
922
- // ignore
923
- }
924
- }
925
- }
926
-
927
- if (record.runtimeHomeDir) {
928
- await fs.rm(record.runtimeHomeDir, { recursive: true, force: true }).catch(() => {
929
- // ignore
930
- });
931
- }
932
- }
933
-
934
- async stop(): Promise<void> {
935
- for (const child of this.processByWorkerId.values()) {
936
- await stopChildProcess(child).catch(() => {
937
- // ignore
938
- });
939
- }
940
- this.processByWorkerId.clear();
941
- }
942
- }
943
-
944
- class DockerProvisioner implements WorkerProvisionerBackend {
945
- readonly type = "docker" as const;
946
- private readonly config: PluginConfig;
947
- private readonly logger: PluginLogger;
948
- private readonly client: DockerApiClient;
949
-
950
- constructor(config: PluginConfig, logger: PluginLogger) {
951
- this.config = config;
952
- this.logger = logger;
953
- this.client = new DockerApiClient();
954
- }
955
-
956
- async launch(spec: LaunchSpec): Promise<LaunchResult> {
957
- if (!this.config.workerProvisioningImage) {
958
- throw new Error("workerProvisioningImage is required for docker provisioning");
959
- }
960
-
961
- const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
962
- const env: Record<string, string> = {
963
- ...spec.env,
964
- HOME: "/home/node",
965
- OPENCLAW_HOME: "/home/node",
966
- OPENCLAW_STATE_DIR: "/home/node/.openclaw",
967
- OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
968
- OPENCLAW_SKIP_CANVAS_HOST: "1",
969
- TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
970
- TEAMCLAW_WORKER_ID: spec.workerId,
971
- TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
972
- ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
973
- };
974
-
975
- // When workers share a Docker network with the controller container, advertise
976
- // the container name and internal worker port so sibling containers can reach it
977
- // directly. When the controller runs on the host, fall back to publishing a host
978
- // port and advertising localhost for host-side callbacks.
979
- const usePortPublishing = spec.publishedHostPort !== undefined;
980
- if (this.config.workerProvisioningDockerNetwork) {
981
- env.TEAMCLAW_ADVERTISE_HOST = instanceName;
982
- env.TEAMCLAW_ADVERTISE_PORT = String(spec.workerPort);
983
- } else if (usePortPublishing) {
984
- env.TEAMCLAW_ADVERTISE_HOST = "localhost";
985
- env.TEAMCLAW_ADVERTISE_PORT = String(spec.publishedHostPort);
986
- }
987
-
988
- const hostConfig: Record<string, unknown> = {
989
- Binds: buildDockerBinds(this.config),
990
- NetworkMode: this.config.workerProvisioningDockerNetwork || undefined,
991
- };
992
-
993
- if (usePortPublishing) {
994
- hostConfig.PortBindings = {
995
- [`${spec.workerPort}/tcp`]: [{ HostPort: String(spec.publishedHostPort) }],
996
- };
997
- }
998
-
999
- const containerConfig: Record<string, unknown> = {
1000
- Image: this.config.workerProvisioningImage,
1001
- Cmd: ["sh", "-lc", buildContainerBootstrapScript()],
1002
- Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
1003
- User: "root",
1004
- Labels: {
1005
- "teamclaw.managed": "true",
1006
- "teamclaw.team": this.config.teamName,
1007
- "teamclaw.role": spec.role,
1008
- "teamclaw.worker_id": spec.workerId,
1009
- },
1010
- HostConfig: hostConfig,
1011
- };
1012
-
1013
- if (usePortPublishing) {
1014
- containerConfig.ExposedPorts = { [`${spec.workerPort}/tcp`]: {} };
1015
- }
1016
-
1017
- const response = await this.client.requestJson<{ Id?: string }>(
1018
- "POST",
1019
- `/containers/create?name=${encodeURIComponent(instanceName)}`,
1020
- containerConfig,
1021
- [201],
1022
- );
1023
-
1024
- const instanceId = typeof response.Id === "string" ? response.Id : undefined;
1025
- if (!instanceId) {
1026
- throw new Error("Docker create did not return a container ID");
1027
- }
1028
-
1029
- await this.client.requestVoid("POST", `/containers/${instanceId}/start`, undefined, [204]);
1030
- this.logger.info(`Provisioner: started docker worker container ${instanceName} (${instanceId})`);
1031
-
1032
- return {
1033
- instanceId,
1034
- instanceName,
1035
- };
1036
- }
1037
-
1038
- async terminate(record: ProvisionedWorkerRecord): Promise<void> {
1039
- const target = record.instanceId || record.instanceName;
1040
- if (!target) {
1041
- return;
1042
- }
1043
- await this.client.requestVoid("DELETE", `/containers/${target}?force=1`, undefined, [204, 404]);
1044
- }
1045
- }
1046
-
1047
- /**
1048
- * Lightweight Kubernetes API client using in-cluster service account or
1049
- * kubeconfig for out-of-cluster (via kubectl proxy or direct API).
1050
- * Avoids requiring kubectl binary in the container image.
1051
- */
1052
- class K8sApiClient {
1053
- private token: string | undefined;
1054
- private caCert: Buffer | undefined;
1055
- private apiServer: string;
1056
- private contextArgs: string;
1057
-
1058
- constructor(context: string, private readonly logger: PluginLogger) {
1059
- this.contextArgs = context;
1060
- // In-cluster detection: K8s injects these env vars and mounts SA token
1061
- const host = process.env.KUBERNETES_SERVICE_HOST;
1062
- const port = process.env.KUBERNETES_SERVICE_PORT;
1063
- if (host && port) {
1064
- this.apiServer = `https://${host}:${port}`;
1065
- try {
1066
- const fs = require("node:fs");
1067
- this.token = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8").trim();
1068
- this.caCert = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt");
1069
- } catch {
1070
- logger.warn("K8sApiClient: in-cluster but cannot read service account token — falling back to kubectl");
1071
- }
1072
- } else {
1073
- // Out-of-cluster: delegate to kubectl
1074
- this.apiServer = "";
1075
- }
1076
- }
1077
-
1078
- private get inCluster(): boolean {
1079
- return Boolean(this.apiServer && this.token);
1080
- }
1081
-
1082
- async createPod(namespace: string, manifest: unknown): Promise<void> {
1083
- if (this.inCluster) {
1084
- await this.apiRequest("POST", `/api/v1/namespaces/${namespace}/pods`, manifest, [200, 201]);
1085
- } else {
1086
- await runCommand("kubectl", [
1087
- ...buildKubectlContextArgs(this.contextArgs),
1088
- "apply", "-f", "-",
1089
- ], JSON.stringify(manifest));
1090
- }
1091
- }
1092
-
1093
- async deletePod(namespace: string, podName: string): Promise<void> {
1094
- if (this.inCluster) {
1095
- await this.apiRequest("DELETE", `/api/v1/namespaces/${namespace}/pods/${podName}?gracePeriodSeconds=0`, undefined, [200, 202, 404]);
1096
- } else {
1097
- await runCommand("kubectl", [
1098
- ...buildKubectlContextArgs(this.contextArgs),
1099
- "-n", namespace,
1100
- "delete", "pod", podName,
1101
- "--ignore-not-found=true", "--grace-period=0", "--force",
1102
- ]);
1103
- }
1104
- }
1105
-
1106
- private async apiRequest(method: string, apiPath: string, body: unknown, okStatuses: number[]): Promise<string> {
1107
- const payload = body !== undefined ? JSON.stringify(body) : undefined;
1108
- return new Promise<string>((resolve, reject) => {
1109
- const url = new URL(apiPath, this.apiServer);
1110
- const options: https.RequestOptions = {
1111
- method,
1112
- hostname: url.hostname,
1113
- port: url.port,
1114
- path: url.pathname + url.search,
1115
- headers: {
1116
- "Authorization": `Bearer ${this.token}`,
1117
- ...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}),
1118
- },
1119
- ...(this.caCert ? { ca: this.caCert } : { rejectUnauthorized: false }),
1120
- };
1121
-
1122
- const req = https.request(options, (res) => {
1123
- let data = "";
1124
- res.on("data", (chunk: string) => { data += chunk; });
1125
- res.on("end", () => {
1126
- if (okStatuses.includes(res.statusCode ?? 0)) {
1127
- resolve(data);
1128
- } else {
1129
- reject(new Error(`K8s API ${method} ${apiPath} returned ${res.statusCode}: ${data.slice(0, 500)}`));
1130
- }
1131
- });
1132
- });
1133
- req.on("error", reject);
1134
- if (payload) req.write(payload);
1135
- req.end();
1136
- });
1137
- }
1138
- }
1139
-
1140
- class KubernetesProvisioner implements WorkerProvisionerBackend {
1141
- readonly type = "kubernetes" as const;
1142
- private readonly config: PluginConfig;
1143
- private readonly logger: PluginLogger;
1144
- private readonly k8sApi: K8sApiClient;
1145
-
1146
- constructor(config: PluginConfig, logger: PluginLogger) {
1147
- this.config = config;
1148
- this.logger = logger;
1149
- this.k8sApi = new K8sApiClient(config.workerProvisioningKubernetesContext, logger);
1150
- }
1151
-
1152
- async launch(spec: LaunchSpec): Promise<LaunchResult> {
1153
- if (!this.config.workerProvisioningImage) {
1154
- throw new Error("workerProvisioningImage is required for kubernetes provisioning");
1155
- }
1156
-
1157
- const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
1158
- const ns = this.config.workerProvisioningKubernetesNamespace;
1159
- const env = {
1160
- ...spec.env,
1161
- HOME: "/home/node",
1162
- OPENCLAW_HOME: "/home/node",
1163
- OPENCLAW_STATE_DIR: "/home/node/.openclaw",
1164
- OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
1165
- OPENCLAW_SKIP_CANVAS_HOST: "1",
1166
- TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
1167
- TEAMCLAW_WORKER_ID: spec.workerId,
1168
- TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
1169
- ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
1170
- };
1171
- const workspaceRoot = this.config.workerProvisioningWorkspaceRoot;
1172
- const hasPersistentWorkspace = Boolean(
1173
- workspaceRoot && this.config.workerProvisioningKubernetesWorkspacePersistentVolumeClaim,
1174
- );
1175
- const imagePullSecrets = this.config.workerProvisioningKubernetesImagePullSecrets
1176
- .map((name) => name.trim())
1177
- .filter((name) => name.length > 0)
1178
- .map((name) => ({ name }));
1179
-
1180
- const manifest = {
1181
- apiVersion: "v1",
1182
- kind: "Pod",
1183
- metadata: {
1184
- name: instanceName,
1185
- namespace: ns,
1186
- labels: {
1187
- app: "teamclaw-worker",
1188
- "teamclaw.managed": "true",
1189
- "teamclaw.team": sanitizeName(this.config.teamName, 40),
1190
- "teamclaw.role": sanitizeName(spec.role, 40),
1191
- ...this.config.workerProvisioningKubernetesLabels,
1192
- },
1193
- annotations: {
1194
- ...this.config.workerProvisioningKubernetesAnnotations,
1195
- },
1196
- },
1197
- spec: {
1198
- restartPolicy: "Never",
1199
- hostname: buildManagedHostname(this.config.teamName, spec.role, spec.workerId),
1200
- serviceAccountName: this.config.workerProvisioningKubernetesServiceAccount || undefined,
1201
- imagePullSecrets: imagePullSecrets.length > 0 ? imagePullSecrets : undefined,
1202
- securityContext: hasPersistentWorkspace
1203
- ? {
1204
- runAsUser: 1000,
1205
- runAsGroup: 1000,
1206
- fsGroup: 1000,
1207
- }
1208
- : undefined,
1209
- volumes: hasPersistentWorkspace
1210
- ? [
1211
- {
1212
- name: "workspace",
1213
- persistentVolumeClaim: {
1214
- claimName: this.config.workerProvisioningKubernetesWorkspacePersistentVolumeClaim,
1215
- },
1216
- },
1217
- ]
1218
- : undefined,
1219
- containers: [
1220
- {
1221
- name: "worker",
1222
- image: this.config.workerProvisioningImage,
1223
- command: ["sh", "-lc"],
1224
- args: [buildContainerBootstrapScript()],
1225
- env: Object.entries(env).map(([name, value]) => ({ name, value })),
1226
- volumeMounts: hasPersistentWorkspace
1227
- ? [
1228
- {
1229
- name: "workspace",
1230
- mountPath: workspaceRoot,
1231
- },
1232
- ]
1233
- : undefined,
1234
- },
1235
- ],
1236
- },
1237
- };
1238
-
1239
- await this.k8sApi.createPod(ns, manifest);
1240
- this.logger.info(`Provisioner: applied kubernetes pod ${instanceName}`);
1241
-
1242
- return {
1243
- instanceId: instanceName,
1244
- instanceName,
1245
- };
1246
- }
1247
-
1248
- async terminate(record: ProvisionedWorkerRecord): Promise<void> {
1249
- const podName = record.instanceName || record.instanceId;
1250
- if (!podName) {
1251
- return;
1252
- }
1253
- const ns = this.config.workerProvisioningKubernetesNamespace;
1254
- await this.k8sApi.deletePod(ns, podName);
1255
- }
1256
- }
1257
-
1258
- class DockerApiClient {
1259
- private readonly endpoint: DockerEndpoint;
1260
-
1261
- constructor() {
1262
- this.endpoint = resolveDockerEndpoint();
1263
- }
1264
-
1265
- async requestJson<T>(method: string, requestPath: string, body?: unknown, okStatuses: number[] = [200]): Promise<T> {
1266
- const response = await this.request(method, requestPath, body, okStatuses);
1267
- if (!response.body) {
1268
- return {} as T;
1269
- }
1270
- return JSON.parse(response.body) as T;
1271
- }
1272
-
1273
- async requestVoid(method: string, requestPath: string, body?: unknown, okStatuses: number[] = [200]): Promise<void> {
1274
- await this.request(method, requestPath, body, okStatuses);
1275
- }
1276
-
1277
- private async request(
1278
- method: string,
1279
- requestPath: string,
1280
- body: unknown,
1281
- okStatuses: number[],
1282
- ): Promise<{ status: number; body: string }> {
1283
- const payload = body === undefined ? undefined : JSON.stringify(body);
1284
- // Prefer the daemon's negotiated default unless the operator pins a version explicitly.
1285
- const finalPath = DOCKER_API_VERSION ? `/${DOCKER_API_VERSION}${requestPath}` : requestPath;
1286
-
1287
- return await new Promise<{ status: number; body: string }>((resolve, reject) => {
1288
- const transport = this.endpoint.protocol === "https:" ? https : http;
1289
- const req = transport.request({
1290
- method,
1291
- socketPath: this.endpoint.socketPath,
1292
- hostname: this.endpoint.hostname,
1293
- port: this.endpoint.port,
1294
- path: finalPath,
1295
- headers: payload
1296
- ? {
1297
- "Content-Type": "application/json",
1298
- "Content-Length": Buffer.byteLength(payload),
1299
- }
1300
- : undefined,
1301
- }, (res: any) => {
1302
- const chunks: Buffer[] = [];
1303
- res.on("data", (chunk: Buffer) => chunks.push(chunk));
1304
- res.on("end", () => {
1305
- const text = Buffer.concat(chunks).toString("utf8");
1306
- const status = res.statusCode ?? 500;
1307
- if (!okStatuses.includes(status)) {
1308
- const message = extractDockerErrorMessage(text) || `Docker API ${method} ${requestPath} failed with ${status}`;
1309
- reject(new Error(message));
1310
- return;
1311
- }
1312
- resolve({ status, body: text });
1313
- });
1314
- });
1315
- req.on("error", reject);
1316
- if (payload) {
1317
- req.write(payload);
1318
- }
1319
- req.end();
1320
- });
1321
- }
1322
- }
1323
-
1324
- type DockerEndpoint = {
1325
- protocol: "http:" | "https:";
1326
- socketPath?: string;
1327
- hostname?: string;
1328
- port?: number;
1329
- };
1330
-
1331
- function resolveDockerApiVersion(): string | null {
1332
- const configured = process.env.DOCKER_API_VERSION?.trim();
1333
- if (!configured) {
1334
- return null;
1335
- }
1336
- return configured.startsWith("v") ? configured : `v${configured}`;
1337
- }
1338
-
1339
884
  function createProvisionerBackend(
1340
885
  config: PluginConfig,
1341
886
  logger: PluginLogger,
@@ -1353,142 +898,6 @@ function createProvisionerBackend(
1353
898
  }
1354
899
  }
1355
900
 
1356
- export function buildProvisionedWorkerConfig(
1357
- baseConfig: Record<string, unknown>,
1358
- controllerConfig: PluginConfig,
1359
- spec: {
1360
- role: RoleId;
1361
- controllerUrl: string;
1362
- workerPort: number;
1363
- gatewayPort: number;
1364
- workspaceDir?: string;
1365
- },
1366
- ): Record<string, unknown> {
1367
- const config = cloneJson(baseConfig);
1368
- delete config.channels;
1369
- const agents = ensureRecord(config.agents);
1370
- const agentDefaults = ensureRecord(agents.defaults);
1371
- delete agentDefaults.repoRoot;
1372
- if (spec.workspaceDir) {
1373
- agentDefaults.workspace = spec.workspaceDir;
1374
- } else {
1375
- delete agentDefaults.workspace;
1376
- }
1377
- // The host controller may run a newer openclaw that persists the keyed
1378
- // agents.entries schema (e.g. agents.entries.teamclaw.model written by the
1379
- // model-configuration feature). Provisioned workers can run an older
1380
- // openclaw that rejects unknown agents keys ("Unrecognized key: entries"),
1381
- // so fold the teamclaw entry's model back into the legacy
1382
- // agents.defaults.model and drop the entries map. New-schema workers also
1383
- // accept agents.defaults, keeping the folded config compatible both ways.
1384
- const agentsRecord = agents as {
1385
- entries?: Record<string, { model?: string }>;
1386
- };
1387
- if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
1388
- const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
1389
- if (entryModel && !agentDefaults.model) {
1390
- agentDefaults.model = entryModel;
1391
- }
1392
- // Container backends may run older openclaw runtimes that reject the
1393
- // keyed agents schema ("Unrecognized key: entries") - fold down to
1394
- // legacy defaults there. Process workers share the controller's own
1395
- // runtime, which REQUIRES at least one entry ("agents.entries must
1396
- // contain at least one configured agent" crash-loop, exit 78, observed
1397
- // 2026-11-03 when entries was deleted unconditionally) - keep only the
1398
- // teamclaw worker entry for them.
1399
- const containerized =
1400
- controllerConfig.workerProvisioningType === "docker" ||
1401
- controllerConfig.workerProvisioningType === "kubernetes";
1402
- if (containerized) {
1403
- delete agentsRecord.entries;
1404
- } else {
1405
- agentsRecord.entries = {
1406
- [TEAMCLAW_AGENT_ID]: agentsRecord.entries[TEAMCLAW_AGENT_ID] ?? {},
1407
- };
1408
- // Pruning entries can dangle defaults.heartbeat.agentId /
1409
- // defaults.systemAgent.agentId ("main" no longer exists in the worker
1410
- // config) - remap any dangling agentId reference to the surviving
1411
- // teamclaw entry.
1412
- for (const sectionKey of Object.keys(agentDefaults)) {
1413
- const section = (agentDefaults as Record<string, unknown>)[sectionKey];
1414
- if (
1415
- section &&
1416
- typeof section === "object" &&
1417
- typeof (section as { agentId?: unknown }).agentId === "string" &&
1418
- !agentsRecord.entries[(section as { agentId: string }).agentId]
1419
- ) {
1420
- (section as { agentId: string }).agentId = TEAMCLAW_AGENT_ID;
1421
- }
1422
- }
1423
- }
1424
- }
1425
- agents.defaults = agentDefaults;
1426
- config.agents = agents;
1427
-
1428
- const gateway = ensureRecord(config.gateway);
1429
- gateway.mode = "local";
1430
- // Workers running inside Docker/K8s containers must bind on all
1431
- // interfaces so the controller (in a sibling container) can reach them.
1432
- gateway.bind =
1433
- controllerConfig.workerProvisioningType === "docker" ||
1434
- controllerConfig.workerProvisioningType === "kubernetes"
1435
- ? "lan"
1436
- : "loopback";
1437
- gateway.port = spec.gatewayPort;
1438
- delete gateway.remote;
1439
- config.gateway = gateway;
1440
-
1441
- const plugins = ensureRecord(config.plugins);
1442
- plugins.enabled = true;
1443
- if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
1444
- delete plugins.load;
1445
- }
1446
- const entries = ensureRecord(plugins.entries);
1447
- const teamclawEntry = ensureRecord(entries.teamclaw);
1448
- teamclawEntry.enabled = true;
1449
- const teamclawConfig = ensureRecord(teamclawEntry.config);
1450
- teamclawConfig.mode = "worker";
1451
- teamclawConfig.processModel = "multi";
1452
- teamclawConfig.role = spec.role;
1453
- teamclawConfig.port = spec.workerPort;
1454
- teamclawConfig.controllerUrl = spec.controllerUrl;
1455
- teamclawConfig.teamName = controllerConfig.teamName;
1456
- teamclawConfig.heartbeatIntervalMs = controllerConfig.heartbeatIntervalMs;
1457
- teamclawConfig.taskTimeoutMs = controllerConfig.taskTimeoutMs;
1458
- teamclawConfig.gitEnabled = controllerConfig.gitEnabled;
1459
- teamclawConfig.gitRemoteUrl = controllerConfig.gitRemoteUrl;
1460
- teamclawConfig.gitDefaultBranch = controllerConfig.gitDefaultBranch;
1461
- teamclawConfig.gitAuthorName = controllerConfig.gitAuthorName;
1462
- teamclawConfig.gitAuthorEmail = controllerConfig.gitAuthorEmail;
1463
- teamclawConfig.workerProvisioningType = "none";
1464
- teamclawConfig.workerProvisioningControllerUrl = "";
1465
- teamclawConfig.workerProvisioningRoles = [];
1466
- teamclawConfig.workerProvisioningMinPerRole = 0;
1467
- teamclawConfig.workerProvisioningMaxPerRole = 10;
1468
- teamclawConfig.workerProvisioningIdleTtlMs = controllerConfig.workerProvisioningIdleTtlMs;
1469
- teamclawConfig.workerProvisioningStartupTimeoutMs = controllerConfig.workerProvisioningStartupTimeoutMs;
1470
- teamclawConfig.workerProvisioningImage = "";
1471
- teamclawConfig.workerProvisioningPassEnv = [];
1472
- teamclawConfig.workerProvisioningExtraEnv = {};
1473
- teamclawConfig.workerProvisioningDockerNetwork = "";
1474
- teamclawConfig.workerProvisioningDockerMounts = [];
1475
- teamclawConfig.workerProvisioningWorkspaceRoot = "";
1476
- teamclawConfig.workerProvisioningDockerWorkspaceVolume = "";
1477
- teamclawConfig.workerProvisioningKubernetesNamespace = "default";
1478
- teamclawConfig.workerProvisioningKubernetesContext = "";
1479
- teamclawConfig.workerProvisioningKubernetesServiceAccount = "";
1480
- teamclawConfig.workerProvisioningKubernetesImagePullSecrets = [];
1481
- teamclawConfig.workerProvisioningKubernetesWorkspacePersistentVolumeClaim = "";
1482
- teamclawConfig.workerProvisioningKubernetesLabels = {};
1483
- teamclawConfig.workerProvisioningKubernetesAnnotations = {};
1484
- teamclawEntry.config = teamclawConfig;
1485
- entries.teamclaw = teamclawEntry;
1486
- plugins.entries = entries;
1487
- config.plugins = plugins;
1488
-
1489
- return config;
1490
- }
1491
-
1492
901
  function ensureProvisioningState(state: TeamState): TeamProvisioningState {
1493
902
  if (!state.provisioning || typeof state.provisioning !== "object") {
1494
903
  state.provisioning = { workers: {} };
@@ -1506,176 +915,6 @@ async function ensureWritableDirectory(dir: string): Promise<void> {
1506
915
  await fs.rm(probePath, { force: true });
1507
916
  }
1508
917
 
1509
- function sleep(ms: number): Promise<void> {
1510
- return new Promise((resolve) => setTimeout(resolve, ms));
1511
- }
1512
-
1513
- async function loadOpenClawConfig(configPath: string): Promise<Record<string, unknown>> {
1514
- const raw = await fs.readFile(configPath, "utf8");
1515
- return parseLooseJsonObject(raw, configPath);
1516
- }
1517
-
1518
- async function prepareProcessRuntimeExtensions(stateDir: string): Promise<void> {
1519
- const runtimeExtensionsDir = path.join(stateDir, "extensions");
1520
- const controllerExtensionsDir = path.join(path.dirname(resolveDefaultOpenClawConfigPath()), "extensions");
1521
- if (await pathExists(controllerExtensionsDir)) {
1522
- await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
1523
- } else {
1524
- await fs.mkdir(runtimeExtensionsDir, { recursive: true });
1525
- // Baked-in images set TEAMCLAW_BAKED_IN=true and the legacy helper
1526
- // returned "" for that case, so the symlink target was empty and
1527
- // process workers fell back to resolving the plugin from their cwd
1528
- // ("/app/dist/openclaw.plugin.json" not found → exit loop, k3s e2e
1529
- // 2026-11-03). Probe the baked image layout instead: the controller
1530
- // entrypoint (process.argv[1], e.g. /app/dist/index.js) sits below
1531
- // the app root, where the runtime image ships
1532
- // /app/extensions/teamclaw with its openclaw.plugin.json.
1533
- const pluginRootDir = process.env.TEAMCLAW_BAKED_IN === "true"
1534
- ? await resolveBakedTeamClawPluginRootDir()
1535
- : resolveCurrentTeamClawPluginRootDir();
1536
- if (pluginRootDir) {
1537
- await fs.symlink(pluginRootDir, path.join(runtimeExtensionsDir, "teamclaw"), "dir");
1538
- }
1539
- }
1540
-
1541
- await copyControllerAuthProfiles(stateDir);
1542
- }
1543
-
1544
- async function copyControllerAuthProfiles(stateDir: string): Promise<void> {
1545
- const candidateControllerStateDirs = [
1546
- path.dirname(resolveDefaultOpenClawConfigPath()),
1547
- resolveDefaultOpenClawStateDir(),
1548
- ];
1549
- const candidateAuthProfilePaths = [
1550
- path.join(resolveTeamClawAgentDir(), "auth-profiles.json"),
1551
- path.join(resolveDefaultAgentDir(), "auth-profiles.json"),
1552
- ...candidateControllerStateDirs.flatMap((controllerStateDir) => [
1553
- path.join(controllerStateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
1554
- path.join(controllerStateDir, "agents", "main", "agent", "auth-profiles.json"),
1555
- ]),
1556
- ].filter((value, index, values) => values.indexOf(value) === index);
1557
- let controllerAuthProfilesPath: string | undefined;
1558
- for (const candidatePath of candidateAuthProfilePaths) {
1559
- if (await pathExists(candidatePath)) {
1560
- controllerAuthProfilesPath = candidatePath;
1561
- break;
1562
- }
1563
- }
1564
- if (!controllerAuthProfilesPath) {
1565
- return;
1566
- }
1567
- const runtimeAuthProfilePaths = [
1568
- path.join(stateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
1569
- path.join(stateDir, "agents", "main", "agent", "auth-profiles.json"),
1570
- ];
1571
- for (const runtimeAuthProfilesPath of runtimeAuthProfilePaths) {
1572
- await fs.mkdir(path.dirname(runtimeAuthProfilesPath), { recursive: true });
1573
- await fs.copyFile(controllerAuthProfilesPath, runtimeAuthProfilesPath);
1574
- }
1575
- }
1576
-
1577
- function cloneJson<T>(value: T): T {
1578
- return JSON.parse(JSON.stringify(value)) as T;
1579
- }
1580
-
1581
- function requiresDedicatedHostPortsForProvisioner(
1582
- provider: WorkerProvisioningType,
1583
- config: PluginConfig,
1584
- ): boolean {
1585
- if (provider === "process") {
1586
- return true;
1587
- }
1588
- return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
1589
- }
1590
-
1591
- function isDockerHostNetwork(networkMode: string): boolean {
1592
- return networkMode.trim().toLowerCase() === "host";
1593
- }
1594
-
1595
- function extractDockerBindTarget(bind: string): string | null {
1596
- for (const part of bind.split(":").reverse()) {
1597
- const trimmed = part.trim();
1598
- if (trimmed.startsWith("/")) {
1599
- return trimmed;
1600
- }
1601
- }
1602
- return null;
1603
- }
1604
-
1605
- function appendNoProxyEntries(env: Record<string, string>, controllerUrl: string): Record<string, string> {
1606
- const requiredEntries = resolveRequiredNoProxyEntries(controllerUrl);
1607
- if (requiredEntries.length === 0) {
1608
- return env;
1609
- }
1610
-
1611
- const upperBase = env.NO_PROXY ?? process.env.NO_PROXY ?? process.env.no_proxy ?? "";
1612
- const lowerBase = env.no_proxy ?? process.env.no_proxy ?? env.NO_PROXY ?? process.env.NO_PROXY ?? "";
1613
-
1614
- env.NO_PROXY = mergeNoProxyEntries(upperBase, requiredEntries);
1615
- env.no_proxy = mergeNoProxyEntries(lowerBase, requiredEntries);
1616
- return env;
1617
- }
1618
-
1619
- function resolveRequiredNoProxyEntries(controllerUrl: string): string[] {
1620
- const required = new Set<string>(["localhost", "127.0.0.1", "::1", "[::1]"]);
1621
- try {
1622
- const host = new URL(controllerUrl).hostname.trim();
1623
- if (host) {
1624
- required.add(host);
1625
- }
1626
- } catch {
1627
- // Ignore malformed controller URLs; worker registration will fail separately.
1628
- }
1629
- return Array.from(required);
1630
- }
1631
-
1632
- function mergeNoProxyEntries(existing: string, requiredEntries: string[]): string {
1633
- const tokens = new Map<string, string>();
1634
- for (const entry of existing.split(",")) {
1635
- const trimmed = entry.trim();
1636
- if (!trimmed) {
1637
- continue;
1638
- }
1639
- tokens.set(trimmed.toLowerCase(), trimmed);
1640
- }
1641
- for (const entry of requiredEntries) {
1642
- const trimmed = entry.trim();
1643
- if (!trimmed) {
1644
- continue;
1645
- }
1646
- tokens.set(trimmed.toLowerCase(), trimmed);
1647
- }
1648
- return Array.from(tokens.values()).join(",");
1649
- }
1650
-
1651
- async function pathExists(targetPath: string): Promise<boolean> {
1652
- try {
1653
- await fs.access(targetPath);
1654
- return true;
1655
- } catch (err) {
1656
- if ((err as NodeJS.ErrnoException).code === "ENOENT") {
1657
- return false;
1658
- }
1659
- throw err;
1660
- }
1661
- }
1662
-
1663
- function ensureRecord(value: unknown): Record<string, unknown> {
1664
- return value && typeof value === "object" && !Array.isArray(value)
1665
- ? { ...(value as Record<string, unknown>) }
1666
- : {};
1667
- }
1668
-
1669
- function parseLooseJsonObject(raw: string, configPath: string): Record<string, unknown> {
1670
- try {
1671
- return JSON5.parse(raw) as Record<string, unknown>;
1672
- } catch (err) {
1673
- throw new Error(
1674
- `Failed to parse OpenClaw config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`,
1675
- );
1676
- }
1677
- }
1678
-
1679
918
  async function reserveEphemeralPort(): Promise<number> {
1680
919
  return await new Promise<number>((resolve, reject) => {
1681
920
  const server = net.createServer();
@@ -1697,280 +936,3 @@ async function reserveEphemeralPort(): Promise<number> {
1697
936
  server.on("error", reject);
1698
937
  });
1699
938
  }
1700
-
1701
- function resolveGatewayEntrypoint(): string {
1702
- const scriptPath = process.argv[1];
1703
- if (!scriptPath) {
1704
- throw new Error("Unable to resolve OpenClaw gateway entrypoint");
1705
- }
1706
- return path.resolve(scriptPath);
1707
- }
1708
-
1709
- function resolveCurrentTeamClawPluginRootDir(): string {
1710
- return process.env.TEAMCLAW_BAKED_IN === "true" ? "" : path.resolve(fileURLToPath(new URL("../../", import.meta.url)));
1711
- }
1712
-
1713
- /**
1714
- * Locate the teamclaw plugin root inside a baked runtime image. The image
1715
- * ships the plugin at <app-root>/extensions/teamclaw; the controller
1716
- * entrypoint (process.argv[1]) lives under <app-root>, so walk up from it.
1717
- * Returns "" when no candidate carries an openclaw.plugin.json (the
1718
- * caller then skips the symlink instead of creating a dangling one).
1719
- */
1720
- async function resolveBakedTeamClawPluginRootDir(): Promise<string> {
1721
- const entrypoint = process.argv[1] ? path.resolve(process.argv[1]) : "";
1722
- const candidates = entrypoint
1723
- ? [
1724
- path.resolve(entrypoint, "../../extensions/teamclaw"),
1725
- path.resolve(entrypoint, "../extensions/teamclaw"),
1726
- ]
1727
- : [];
1728
- candidates.push("/app/extensions/teamclaw");
1729
- for (const candidate of candidates) {
1730
- try {
1731
- await fs.access(path.join(candidate, "openclaw.plugin.json"));
1732
- return candidate;
1733
- } catch {
1734
- // try the next candidate layout
1735
- }
1736
- }
1737
- return "";
1738
- }
1739
-
1740
- function attachChildLogs(child: ChildProcess, logger: PluginLogger, prefix: string): void {
1741
- if (child.stdout) {
1742
- const stdoutReader = readline.createInterface({ input: child.stdout });
1743
- stdoutReader.on("line", (line: string) => {
1744
- logger.info(`${prefix}: ${line}`);
1745
- });
1746
- }
1747
- if (child.stderr) {
1748
- const stderrReader = readline.createInterface({ input: child.stderr });
1749
- stderrReader.on("line", (line: string) => {
1750
- logger.warn(`${prefix}: ${line}`);
1751
- });
1752
- }
1753
- }
1754
-
1755
- async function stopChildProcess(child: ChildProcess): Promise<void> {
1756
- if (child.exitCode !== null || child.signalCode !== null) {
1757
- return;
1758
- }
1759
-
1760
- await new Promise<void>((resolve) => {
1761
- const timeout = setTimeout(() => {
1762
- if (child.exitCode === null && child.signalCode === null && child.pid) {
1763
- try {
1764
- process.kill(child.pid, "SIGKILL");
1765
- } catch {
1766
- // ignore
1767
- }
1768
- }
1769
- resolve();
1770
- }, PROCESS_TERMINATION_TIMEOUT_MS);
1771
- const timer = timeout as unknown as { unref?: () => void };
1772
- timer.unref?.();
1773
-
1774
- child.once("exit", () => {
1775
- clearTimeout(timeout);
1776
- resolve();
1777
- });
1778
-
1779
- child.kill("SIGTERM");
1780
- });
1781
- }
1782
-
1783
- function sanitizePathSegment(value: string): string {
1784
- const normalized = value.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "");
1785
- return normalized || "worker";
1786
- }
1787
-
1788
- function sanitizeName(value: string, maxLength = 63): string {
1789
- const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
1790
- return normalized || "teamclaw";
1791
- }
1792
-
1793
- function buildManagedInstanceName(teamName: string, role: RoleId, workerId: string): string {
1794
- return buildManagedName("teamclaw", teamName, role, workerId, {
1795
- teamBudget: 18,
1796
- roleBudget: 12,
1797
- workerBudget: 12,
1798
- hashLength: 8,
1799
- maxLength: 63,
1800
- });
1801
- }
1802
-
1803
- function buildManagedHostname(teamName: string, role: RoleId, workerId: string): string {
1804
- return buildManagedName("tc", teamName, role, workerId, {
1805
- teamBudget: 10,
1806
- roleBudget: 8,
1807
- workerBudget: 6,
1808
- hashLength: 6,
1809
- maxLength: 40,
1810
- });
1811
- }
1812
-
1813
- function buildManagedName(
1814
- prefix: string,
1815
- teamName: string,
1816
- role: RoleId,
1817
- workerId: string,
1818
- options: {
1819
- teamBudget: number;
1820
- roleBudget: number;
1821
- workerBudget: number;
1822
- hashLength: number;
1823
- maxLength: number;
1824
- },
1825
- ): string {
1826
- const teamPart = sanitizeLeadingSegment(teamName, options.teamBudget, "team");
1827
- const rolePart = sanitizeLeadingSegment(role, options.roleBudget, "worker");
1828
- const workerPart = sanitizeTrailingSegment(workerId, options.workerBudget, "worker");
1829
- const hash = shortStableHash(`${teamName}:${role}:${workerId}`).slice(0, options.hashLength);
1830
- return sanitizeName(`${prefix}-${teamPart}-${rolePart}-${workerPart}-${hash}`, options.maxLength);
1831
- }
1832
-
1833
- function shortStableHash(value: string): string {
1834
- return createHash("sha1").update(value).digest("hex");
1835
- }
1836
-
1837
- function sanitizeLeadingSegment(value: string, maxLength: number, fallback: string): string {
1838
- const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
1839
- return normalized || fallback;
1840
- }
1841
-
1842
- function sanitizeTrailingSegment(value: string, maxLength: number, fallback: string): string {
1843
- const normalized = sanitizePathSegment(value).slice(-maxLength).replace(/^-+|-+$/g, "");
1844
- return normalized || fallback;
1845
- }
1846
-
1847
- function buildContainerBootstrapScript(): string {
1848
- return [
1849
- "set -eu",
1850
- "mkdir -p \"$OPENCLAW_STATE_DIR\"",
1851
- "if [ -n \"${TEAMCLAW_WORKSPACE_DIR:-}\" ]; then mkdir -p \"$TEAMCLAW_WORKSPACE_DIR\"; fi",
1852
- "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);'",
1853
- "exec node dist/index.js gateway --allow-unconfigured",
1854
- ].join("\n");
1855
- }
1856
-
1857
- function buildDockerBinds(config: PluginConfig): string[] {
1858
- const binds = [...config.workerProvisioningDockerMounts];
1859
- if (!binds.some((bind) => extractDockerBindTarget(bind) === DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR)) {
1860
- const _pd = resolveCurrentTeamClawPluginRootDir();
1861
- if (_pd) binds.unshift(`${_pd}:${DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR}:ro`);
1862
- }
1863
- if (config.workerProvisioningDockerWorkspaceVolume && config.workerProvisioningWorkspaceRoot) {
1864
- binds.unshift(`${config.workerProvisioningDockerWorkspaceVolume}:${config.workerProvisioningWorkspaceRoot}`);
1865
- }
1866
- return [...new Set(binds)];
1867
- }
1868
-
1869
- function buildProvisionedWorkspaceDir(
1870
- provider: WorkerProvisioningType,
1871
- config: PluginConfig,
1872
- role: RoleId,
1873
- workerId: string,
1874
- ): string {
1875
- // Process-type workers run on the same host — share the controller's workspace
1876
- // so that file artifacts (previews, deliverables) are immediately visible to
1877
- // the controller without requiring git sync or file transfer.
1878
- if (provider === "process") {
1879
- return resolveTeamClawAgentWorkspaceRootDir();
1880
- }
1881
-
1882
- if (
1883
- (provider !== "docker" && provider !== "kubernetes") ||
1884
- !config.workerProvisioningWorkspaceRoot
1885
- ) {
1886
- return "";
1887
- }
1888
-
1889
- return path.posix.join(
1890
- config.workerProvisioningWorkspaceRoot,
1891
- sanitizePathSegment(config.teamName),
1892
- sanitizePathSegment(role),
1893
- sanitizePathSegment(workerId),
1894
- );
1895
- }
1896
-
1897
- function getConfiguredWorkerWorkspaceDir(config: Record<string, unknown>): string {
1898
- const agents = ensureRecord(config.agents);
1899
- const defaults = ensureRecord(agents.defaults);
1900
- return typeof defaults.workspace === "string" ? defaults.workspace : "";
1901
- }
1902
-
1903
- function resolveDockerEndpoint(): DockerEndpoint {
1904
- const dockerHost = process.env.DOCKER_HOST?.trim();
1905
- if (!dockerHost) {
1906
- return {
1907
- protocol: "http:",
1908
- socketPath: "/var/run/docker.sock",
1909
- };
1910
- }
1911
-
1912
- if (dockerHost.startsWith("unix://")) {
1913
- return {
1914
- protocol: "http:",
1915
- socketPath: dockerHost.slice("unix://".length),
1916
- };
1917
- }
1918
-
1919
- const normalized = dockerHost.startsWith("tcp://")
1920
- ? dockerHost.replace(/^tcp:\/\//, "http://")
1921
- : dockerHost;
1922
- const url = new URL(normalized);
1923
- return {
1924
- protocol: url.protocol === "https:" ? "https:" : "http:",
1925
- hostname: url.hostname,
1926
- port: url.port ? Number(url.port) : (url.protocol === "https:" ? 443 : 2375),
1927
- };
1928
- }
1929
-
1930
- function extractDockerErrorMessage(body: string): string | null {
1931
- if (!body.trim()) {
1932
- return null;
1933
- }
1934
- try {
1935
- const parsed = JSON.parse(body) as { message?: unknown };
1936
- return typeof parsed.message === "string" ? parsed.message : body;
1937
- } catch {
1938
- return body;
1939
- }
1940
- }
1941
-
1942
- async function runCommand(command: string, args: string[], stdin?: string): Promise<void> {
1943
- await new Promise<void>((resolve, reject) => {
1944
- const child = spawn(command, args, {
1945
- stdio: ["pipe", "pipe", "pipe"],
1946
- env: process.env,
1947
- });
1948
- let stderr = "";
1949
- let stdout = "";
1950
-
1951
- if (stdin) {
1952
- child.stdin?.end(stdin);
1953
- } else {
1954
- child.stdin?.end();
1955
- }
1956
-
1957
- child.stdout?.on("data", (chunk: Buffer) => {
1958
- stdout += chunk.toString("utf8");
1959
- });
1960
- child.stderr?.on("data", (chunk: Buffer) => {
1961
- stderr += chunk.toString("utf8");
1962
- });
1963
- child.on("error", reject);
1964
- child.on("exit", (code: number | null) => {
1965
- if (code === 0) {
1966
- resolve();
1967
- return;
1968
- }
1969
- reject(new Error(`${command} ${args.join(" ")} failed (${code}): ${(stderr || stdout).trim()}`));
1970
- });
1971
- });
1972
- }
1973
-
1974
- function buildKubectlContextArgs(context: string): string[] {
1975
- return context ? ["--context", context] : [];
1976
- }