@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.
Files changed (120) hide show
  1. package/cli.mjs +272 -2
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +24 -0
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +1 -1
  6. package/dist/src/controller/controller-planning.js +1 -0
  7. package/dist/src/controller/controller-routes.js +195 -0
  8. package/dist/src/controller/controller-service.js +67 -10
  9. package/dist/src/controller/controller-tools.js +3 -1
  10. package/dist/src/controller/github-auth.js +2 -1
  11. package/dist/src/controller/http-server.js +51 -16
  12. package/dist/src/controller/kickoff-orchestrator.js +3 -39
  13. package/dist/src/controller/message-delivery.js +4 -1
  14. package/dist/src/controller/orchestration-manifest.js +5 -65
  15. package/dist/src/controller/preview-manager.js +51 -3
  16. package/dist/src/controller/profile-switch.js +42 -22
  17. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  18. package/dist/src/controller/provisioning/container-shared.js +64 -0
  19. package/dist/src/controller/provisioning/docker.js +214 -0
  20. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  21. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  22. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  23. package/dist/src/controller/provisioning-config.js +239 -0
  24. package/dist/src/controller/repo-routes.js +70 -4
  25. package/dist/src/controller/report-routes.js +56 -0
  26. package/dist/src/controller/route-table.js +67 -1045
  27. package/dist/src/controller/security.js +775 -0
  28. package/dist/src/controller/status-routes.js +287 -0
  29. package/dist/src/controller/task-assignment.js +5 -2
  30. package/dist/src/controller/task-execution.js +31 -0
  31. package/dist/src/controller/task-results.js +10 -0
  32. package/dist/src/controller/tunnel-manager.js +41 -8
  33. package/dist/src/controller/tunnel-routes.js +225 -0
  34. package/dist/src/controller/websocket.js +6 -2
  35. package/dist/src/controller/webui-routes.js +49 -0
  36. package/dist/src/controller/worker-provisioning.js +39 -949
  37. package/dist/src/controller/workflow-routes.js +407 -0
  38. package/dist/src/controller/workspace-routes.js +200 -0
  39. package/dist/src/git-collaboration.js +4 -9
  40. package/dist/src/identity.js +12 -1
  41. package/dist/src/profile-loader.js +119 -1
  42. package/dist/src/profiles/banking.json +26 -2
  43. package/dist/src/profiles/schema.json +82 -2
  44. package/dist/src/prompt-policy.js +18 -6
  45. package/dist/src/protocol.js +66 -3
  46. package/dist/src/shared/clarification-schema.js +65 -0
  47. package/dist/src/shared/github-auth.js +15 -0
  48. package/dist/src/shared/kickoff-prompt.js +37 -0
  49. package/dist/src/shared/utils.js +47 -0
  50. package/dist/src/state.js +89 -3
  51. package/dist/src/types.js +15 -1
  52. package/dist/src/ui/app.js +846 -62
  53. package/dist/src/ui/github-login.html +1 -0
  54. package/dist/src/ui/index.html +102 -36
  55. package/dist/src/worker/http-handler.js +59 -0
  56. package/dist/src/worker/skill-installer.js +3 -9
  57. package/dist/src/worker/tools.js +20 -10
  58. package/dist/src/worker/worker-service.js +17 -4
  59. package/index.ts +61 -32
  60. package/openclaw.plugin.json +23 -2
  61. package/package.json +1 -1
  62. package/src/config.ts +24 -0
  63. package/src/controller/auth-routes.ts +157 -0
  64. package/src/controller/clarification-routes.ts +1 -1
  65. package/src/controller/controller-planning.ts +8 -0
  66. package/src/controller/controller-routes.ts +237 -0
  67. package/src/controller/controller-service.ts +128 -10
  68. package/src/controller/controller-tools.ts +5 -2
  69. package/src/controller/github-auth.ts +28 -63
  70. package/src/controller/http-server.ts +66 -17
  71. package/src/controller/kickoff-orchestrator.ts +3 -42
  72. package/src/controller/message-delivery.ts +4 -1
  73. package/src/controller/orchestration-manifest.ts +8 -71
  74. package/src/controller/preview-manager.ts +53 -3
  75. package/src/controller/profile-switch.ts +53 -23
  76. package/src/controller/provisioning/backend-contract.ts +51 -0
  77. package/src/controller/provisioning/container-shared.ts +84 -0
  78. package/src/controller/provisioning/docker.ts +260 -0
  79. package/src/controller/provisioning/kubernetes.ts +263 -0
  80. package/src/controller/provisioning/plugin-root.ts +42 -0
  81. package/src/controller/provisioning/process-supervisor.ts +214 -0
  82. package/src/controller/provisioning-config.ts +289 -0
  83. package/src/controller/repo-routes.ts +84 -12
  84. package/src/controller/report-routes.ts +64 -0
  85. package/src/controller/route-table.ts +133 -1152
  86. package/src/controller/security.ts +899 -0
  87. package/src/controller/status-routes.ts +354 -0
  88. package/src/controller/task-assignment.ts +5 -1
  89. package/src/controller/task-execution.ts +43 -0
  90. package/src/controller/task-results.ts +12 -0
  91. package/src/controller/tunnel-manager.ts +45 -8
  92. package/src/controller/tunnel-routes.ts +231 -0
  93. package/src/controller/websocket.ts +19 -3
  94. package/src/controller/webui-routes.ts +55 -0
  95. package/src/controller/worker-provisioning.ts +51 -1117
  96. package/src/controller/workflow-routes.ts +498 -0
  97. package/src/controller/workspace-routes.ts +222 -0
  98. package/src/git-collaboration.ts +4 -9
  99. package/src/identity.ts +13 -1
  100. package/src/profile-loader.ts +167 -1
  101. package/src/profiles/banking.json +26 -2
  102. package/src/profiles/schema.json +82 -2
  103. package/src/prompt-policy.ts +19 -6
  104. package/src/protocol.ts +72 -2
  105. package/src/shared/clarification-schema.ts +81 -0
  106. package/src/shared/github-auth.ts +92 -0
  107. package/src/shared/kickoff-prompt.ts +47 -0
  108. package/src/shared/utils.ts +51 -0
  109. package/src/state.ts +92 -3
  110. package/src/teamauto/github-client.ts +2 -1
  111. package/src/teamauto/repo-sync.ts +2 -1
  112. package/src/teamauto/scheduler.ts +2 -1
  113. package/src/types.ts +130 -1
  114. package/src/ui/app.js +846 -62
  115. package/src/ui/github-login.html +1 -0
  116. package/src/ui/index.html +102 -36
  117. package/src/worker/http-handler.ts +64 -1
  118. package/src/worker/skill-installer.ts +3 -9
  119. package/src/worker/tools.ts +21 -10
  120. package/src/worker/worker-service.ts +18 -4
@@ -7,6 +7,46 @@ const PREVIEW_LAUNCH_TIMEOUT_MS = 120_000;
7
7
  const PREVIEW_HEALTH_INTERVAL_MS = 1_500;
8
8
  const PREVIEW_STOP_TIMEOUT_MS = 5_000;
9
9
  const GENERIC_SERVE_COMMAND = "npx -y serve -l {PORT}";
10
+ // Issue #237 W1: preview commands are LLM-authored (result contracts) and
11
+ // run through a shell - they must NOT inherit the controller's environment,
12
+ // or a prompt-injected previewCommand could exfiltrate every controller
13
+ // credential (GH_TOKEN, provider API keys, tunnel tokens). Policy: minimal
14
+ // allowlist of toolchain basics, matched case-insensitively so Windows
15
+ // (Path/SystemRoot/...) survives, plus the explicit preview vars set at the
16
+ // spawn site. Repos that genuinely need more can pass names through
17
+ // TEAMCLAW_PREVIEW_EXTRA_ENV (comma-separated list of env var names whose
18
+ // controller values are forwarded verbatim); anything else is absent.
19
+ const PREVIEW_ENV_ALLOWLIST = new Set([
20
+ "PATH", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TZ", "TERM", "SHELL",
21
+ // Windows toolchain basics (no-ops elsewhere, harmless to match).
22
+ // PROCESSOR_ARCHITECTURE/PROCESSOR_IDENTIFIER are read by node-gyp-style
23
+ // native builds (review follow-up to #237 W1) - plain toolchain
24
+ // descriptors, no credential material.
25
+ "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "PATHEXT", "WINDIR", "USERPROFILE",
26
+ "APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMDATA", "NUMBER_OF_PROCESSORS", "OS",
27
+ "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER",
28
+ ]);
29
+ const PREVIEW_EXTRA_ENV_VAR = "TEAMCLAW_PREVIEW_EXTRA_ENV";
30
+ /** Builds the restricted environment for preview subprocesses (#237 W1):
31
+ * allowlisted controller vars + extraEnv (venv PATH/VIRTUAL_ENV) + whatever
32
+ * the operator declared via TEAMCLAW_PREVIEW_EXTRA_ENV. Never returns the
33
+ * full process.env. Exported for the #237 regression test. */
34
+ export function buildPreviewEnv(extraEnv) {
35
+ const allow = new Set(PREVIEW_ENV_ALLOWLIST);
36
+ for (const name of (process.env[PREVIEW_EXTRA_ENV_VAR] ?? "").split(",")) {
37
+ const normalized = name.trim().toUpperCase();
38
+ if (normalized) {
39
+ allow.add(normalized);
40
+ }
41
+ }
42
+ const env = {};
43
+ for (const [key, value] of Object.entries(process.env)) {
44
+ if (value !== undefined && allow.has(key.toUpperCase())) {
45
+ env[key] = value;
46
+ }
47
+ }
48
+ return { ...env, ...extraEnv };
49
+ }
10
50
  /**
11
51
  * Detect the tech stack from files in `cwd` and return a suitable preview command.
12
52
  * Only overrides `existingCommand` when it is the generic static file server
@@ -394,7 +434,10 @@ export class PreviewManager {
394
434
  const pipInstall = spawnManagedCommandProcess({
395
435
  command: `${pipBin} install -q -r requirements.txt`,
396
436
  cwd,
397
- env: { ...process.env, ...extraEnv },
437
+ // #237 W1: requirements.txt is worker-influenced and pip executes
438
+ // setup.py at install time, so this subprocess gets the same
439
+ // restricted env as the preview command itself.
440
+ env: buildPreviewEnv(extraEnv),
398
441
  });
399
442
  await new Promise((resolve) => {
400
443
  pipInstall.on("exit", () => resolve());
@@ -408,10 +451,15 @@ export class PreviewManager {
408
451
  }
409
452
  const child = spawnManagedCommandProcess({
410
453
  command: resolvedCommand,
454
+ // cwd is already forced inside the workspace (resolveWorkspaceDirectory
455
+ // confinement above), so the shell cannot escape the deliverable dir.
411
456
  cwd,
457
+ // #237 W1: restricted allowlist env - never the controller's full
458
+ // process.env (credential exfiltration via prompt-injected
459
+ // previewCommand). HOST/PORT/TEAMCLAW_PREVIEW_* are the explicit
460
+ // preview contract vars.
412
461
  env: {
413
- ...process.env,
414
- ...extraEnv,
462
+ ...buildPreviewEnv(extraEnv),
415
463
  HOST: "0.0.0.0",
416
464
  PORT: String(record.targetPort),
417
465
  TEAMCLAW_PREVIEW_BASE_PATH: record.liveUrl.replace(/\/$/u, ""),
@@ -1,4 +1,4 @@
1
- import { saveTeamState, archiveTeamState, findTeamSwitchArchive } from "../state.js";
1
+ import { archiveTeamState, findTeamSwitchArchive } from "../state.js";
2
2
  import { BUILTIN_PROFILES, getActiveProfile, hasProfile, setActiveProfileId, } from "../profile-loader.js";
3
3
  import { ensureControllerGitRepo } from "../git-collaboration.js";
4
4
  // ===========================================================================
@@ -65,21 +65,27 @@ async function drainTeamForProfileSwitch(deps) {
65
65
  * startup chain can resume an interrupted switch with the same semantics.
66
66
  */
67
67
  export async function executeTeamProfileSwitch(deps, targetProfileId, options = {}) {
68
- const { config, logger, getTeamState, updateTeamState, wsServer, workerProvisioningManager } = deps;
68
+ const { config, logger, getTeamState, updateTeamState, workerProvisioningManager } = deps;
69
69
  const target = BUILTIN_PROFILES.get(targetProfileId);
70
70
  if (!target) {
71
71
  throw new Error(`TeamClaw team profile "${targetProfileId}" is not available in this installation`);
72
72
  }
73
- const setPhase = (phase) => {
74
- updateTeamState((state) => {
73
+ // W4 (#226): phase flips persist through the single write entry. The
74
+ // awaited-durability variant is used everywhere so callers that need the
75
+ // crash-window barrier (step 3's archiving flip, step 5's warming flip)
76
+ // can await it; callers that historically fire-and-forget the save simply
77
+ // drop the handle (an un-awaited rejection behaves exactly like the old
78
+ // floating void save).
79
+ const setPhase = (phase, options = {}) => {
80
+ return updateTeamState((state) => {
75
81
  if (state.transition?.targetProfileId === targetProfileId) {
76
82
  state.transition.phase = phase;
77
83
  }
78
- });
84
+ }, { ...options, persist: "awaited" });
79
85
  };
80
86
  if (!options.skipArchive) {
81
87
  // Step 2: drain in-flight work, then stop every worker.
82
- setPhase("draining");
88
+ void setPhase("draining").persisted.catch(() => undefined);
83
89
  workerProvisioningManager?.setReconcileSuspended(true);
84
90
  const drain = await drainTeamForProfileSwitch(deps);
85
91
  for (const workerId of Object.keys(getTeamState()?.provisioning?.workers ?? {})) {
@@ -114,11 +120,19 @@ export async function executeTeamProfileSwitch(deps, targetProfileId, options =
114
120
  // Step 3: archive the whole previous TeamState with a roles snapshot.
115
121
  // The phase flip is persisted BEFORE the archive write so a crash between
116
122
  // the two leaves an unambiguous "archive may exist" state for the resume
117
- // path (file existence check).
118
- setPhase("archiving");
123
+ // path (file existence check). W4 (#226): the awaited durability barrier
124
+ // is the single entry's persisted handle (one save enqueued at the same
125
+ // point the old fire-and-forget + awaited second save pair wrote).
126
+ const archiving = setPhase("archiving");
127
+ // #251 note (no behavior change): `sourceState` below is whatever
128
+ // getTeamState() returns AFTER the awaited "archiving" persist barrier
129
+ // - it is NOT a phase-accurate snapshot frozen at the moment the drain
130
+ // finished. In-flight mutations racing the switch can be captured in
131
+ // the archive; the resume path tolerates this because the transition
132
+ // marker, not the snapshot contents, drives recovery.
119
133
  const sourceState = getTeamState();
120
134
  if (sourceState) {
121
- await saveTeamState(sourceState);
135
+ await archiving.persisted;
122
136
  const sourceProfile = getActiveProfile();
123
137
  await archiveTeamState(sourceState, {
124
138
  id: sourceProfile.id,
@@ -143,7 +157,7 @@ export async function executeTeamProfileSwitch(deps, targetProfileId, options =
143
157
  : null;
144
158
  setActiveProfileId(target.id);
145
159
  const newCreatedAt = Date.now();
146
- updateTeamState((state) => {
160
+ const step4 = updateTeamState((state) => {
147
161
  state.profileId = target.id;
148
162
  state.teamName = target.name;
149
163
  state.workers = {};
@@ -172,25 +186,28 @@ export async function executeTeamProfileSwitch(deps, targetProfileId, options =
172
186
  delete state.reports;
173
187
  }
174
188
  state.createdAt = newCreatedAt;
175
- });
176
- await saveTeamState(getTeamState());
189
+ }, { persist: "awaited" });
190
+ await step4.persisted;
177
191
  // Step 5: warm the new profile's warmupRoles through the provisioning
178
192
  // pipeline (launch dispatch; registration/readiness tracking continues in
179
193
  // the background exactly like a cold start).
180
- setPhase("warming");
181
- await saveTeamState(getTeamState());
194
+ await setPhase("warming").persisted;
182
195
  workerProvisioningManager?.setReconcileSuspended(false);
183
196
  if (workerProvisioningManager?.isEnabled() && target.warmupRoles.length > 0) {
184
197
  await workerProvisioningManager
185
198
  .warmRolesForTeamSwitch(target.warmupRoles, `profile switch warmup (${target.id})`)
186
199
  .catch((err) => logger.warn(`Controller: profile switch warmup failed: ${err instanceof Error ? err.message : String(err)}`));
187
200
  }
188
- // Step 6: settle - clear the transition, persist, announce.
189
- updateTeamState((state) => {
201
+ // Step 6: settle - clear the transition, persist, announce. W4 (#226):
202
+ // the switch_completed broadcast rides the single entry's awaited
203
+ // persistence, preserving the event order (persisted, then announced).
204
+ const settled = updateTeamState((state) => {
190
205
  delete state.transition;
206
+ }, {
207
+ persist: "awaited",
208
+ broadcast: [{ type: "team.switch_completed", data: { profileId: target.id } }],
191
209
  });
192
- await saveTeamState(getTeamState());
193
- wsServer.broadcastUpdate({ type: "team.switch_completed", data: { profileId: target.id } });
210
+ await settled.persisted;
194
211
  logger.info(`Controller: team profile switch to "${target.id}" completed`);
195
212
  }
196
213
  /**
@@ -248,7 +265,7 @@ export async function resumeTeamProfileSwitch(deps) {
248
265
  * team.switch_failed broadcast, and unwedging the transition.
249
266
  */
250
267
  export function startTeamProfileSwitch(deps, state, profileId, previousProfileId) {
251
- const { logger, wsServer, updateTeamState, getTeamState } = deps;
268
+ const { logger, wsServer, updateTeamState } = deps;
252
269
  void executeTeamProfileSwitch(deps, profileId).catch(async (err) => {
253
270
  const detail = err instanceof Error ? err.message : String(err);
254
271
  logger.error(`Controller: team profile switch to "${profileId}" failed: ${detail}`);
@@ -279,11 +296,14 @@ export function startTeamProfileSwitch(deps, state, profileId, previousProfileId
279
296
  type: "team.switch_failed",
280
297
  data: { previousProfileId, targetProfileId: profileId, reason },
281
298
  });
282
- updateTeamState((s) => {
299
+ // W4 (#226): best-effort persist of the unwedging through the single
300
+ // entry - one enqueued save with the failure path's swallow (the old
301
+ // shape fired an un-caught floating save plus this caught one).
302
+ const cleared = updateTeamState((s) => {
283
303
  if (s.transition?.targetProfileId === profileId) {
284
304
  delete s.transition;
285
305
  }
286
- });
287
- void saveTeamState(getTeamState()).catch(() => undefined);
306
+ }, { persist: "awaited" });
307
+ void cleared.persisted.catch(() => undefined);
288
308
  });
289
309
  }
@@ -0,0 +1,9 @@
1
+ export function requiresDedicatedHostPortsForProvisioner(provider, config) {
2
+ if (provider === "process") {
3
+ return true;
4
+ }
5
+ return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
6
+ }
7
+ export function isDockerHostNetwork(networkMode) {
8
+ return networkMode.trim().toLowerCase() === "host";
9
+ }
@@ -0,0 +1,64 @@
1
+ // W1 of issue #226 (worker-provisioning god-file split): managed-name
2
+ // construction and the container bootstrap script shared by the docker and
3
+ // kubernetes backends, extracted VERBATIM from controller/worker-provisioning.ts.
4
+ // The generic string sanitizers now live in shared/utils.ts.
5
+ import { createHash } from "node:crypto";
6
+ import { sanitizePathSegment, sanitizeName } from "../../shared/utils.js";
7
+ export function buildManagedInstanceName(teamName, role, workerId) {
8
+ return buildManagedName("teamclaw", teamName, role, workerId, {
9
+ teamBudget: 18,
10
+ roleBudget: 12,
11
+ workerBudget: 12,
12
+ hashLength: 8,
13
+ maxLength: 63,
14
+ });
15
+ }
16
+ export function buildManagedHostname(teamName, role, workerId) {
17
+ return buildManagedName("tc", teamName, role, workerId, {
18
+ teamBudget: 10,
19
+ roleBudget: 8,
20
+ workerBudget: 6,
21
+ hashLength: 6,
22
+ maxLength: 40,
23
+ });
24
+ }
25
+ function buildManagedName(prefix, teamName, role, workerId, options) {
26
+ const teamPart = sanitizeLeadingSegment(teamName, options.teamBudget, "team");
27
+ const rolePart = sanitizeLeadingSegment(role, options.roleBudget, "worker");
28
+ const workerPart = sanitizeTrailingSegment(workerId, options.workerBudget, "worker");
29
+ const hash = shortStableHash(`${teamName}:${role}:${workerId}`).slice(0, options.hashLength);
30
+ return sanitizeName(`${prefix}-${teamPart}-${rolePart}-${workerPart}-${hash}`, options.maxLength);
31
+ }
32
+ function shortStableHash(value) {
33
+ return createHash("sha1").update(value).digest("hex");
34
+ }
35
+ function sanitizeLeadingSegment(value, maxLength, fallback) {
36
+ const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
37
+ return normalized || fallback;
38
+ }
39
+ function sanitizeTrailingSegment(value, maxLength, fallback) {
40
+ const normalized = sanitizePathSegment(value).slice(-maxLength).replace(/^-+|-+$/g, "");
41
+ return normalized || fallback;
42
+ }
43
+ export function buildContainerBootstrapScript() {
44
+ return [
45
+ "set -eu",
46
+ "mkdir -p \"$OPENCLAW_STATE_DIR\"",
47
+ "if [ -n \"${TEAMCLAW_WORKSPACE_DIR:-}\" ]; then mkdir -p \"$TEAMCLAW_WORKSPACE_DIR\"; fi",
48
+ // Issue #237 W4: the bootstrap config carries provider API keys - write
49
+ // it owner-only inside the container too (the old permissionless call
50
+ // defaulted to 0644). The remaining exposure is the env injection
51
+ // itself (TEAMCLAW_BOOTSTRAP_CONFIG_B64 is visible to `docker inspect`
52
+ // and pod-env readers); migrating the docker/kubernetes backends to
53
+ // mounted Secrets needs a coordinated chart/image change (cf. #230's
54
+ // image-skew caveat) and is tracked by #237 W4.
55
+ // Review follow-up (#237): { mode } is creation-only, so rewriting a
56
+ // pre-existing 0644 config (baked into an older image or surviving on
57
+ // a mounted volume) would keep the loose mode - chmodSync the existing
58
+ // file first, tolerating ENOENT for first writes (then { mode: 0o600 }
59
+ // creates it owner-only). Chosen over unlink-then-write to avoid the
60
+ // no-config window mid-rewrite.
61
+ "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 }); try { fs.chmodSync(configPath, 0o600); } catch (err) { if (err.code !== \"ENOENT\") throw err; } fs.writeFileSync(configPath, raw, { mode: 0o600 });'",
62
+ "exec node dist/index.js gateway --allow-unconfigured",
63
+ ].join("\n");
64
+ }
@@ -0,0 +1,214 @@
1
+ // W1 of issue #226 (worker-provisioning god-file split): the docker backend,
2
+ // extracted VERBATIM from controller/worker-provisioning.ts (DockerProvisioner
3
+ // + the unauthenticated local-socket DockerApiClient + endpoint / bind / API
4
+ // version helpers). Never imports worker-provisioning.ts.
5
+ import http from "node:http";
6
+ import https from "node:https";
7
+ import { buildContainerBootstrapScript, buildManagedInstanceName } from "./container-shared.js";
8
+ import { resolveCurrentTeamClawPluginRootDir } from "./plugin-root.js";
9
+ const DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR = "/app/extensions/teamclaw";
10
+ const DOCKER_API_VERSION = resolveDockerApiVersion();
11
+ export class DockerProvisioner {
12
+ type = "docker";
13
+ config;
14
+ logger;
15
+ client;
16
+ constructor(config, logger) {
17
+ this.config = config;
18
+ this.logger = logger;
19
+ this.client = new DockerApiClient();
20
+ }
21
+ async launch(spec) {
22
+ if (!this.config.workerProvisioningImage) {
23
+ throw new Error("workerProvisioningImage is required for docker provisioning");
24
+ }
25
+ const instanceName = buildManagedInstanceName(this.config.teamName, spec.role, spec.workerId);
26
+ const env = {
27
+ ...spec.env,
28
+ HOME: "/home/node",
29
+ OPENCLAW_HOME: "/home/node",
30
+ OPENCLAW_STATE_DIR: "/home/node/.openclaw",
31
+ OPENCLAW_CONFIG_PATH: "/home/node/.openclaw/openclaw.json",
32
+ OPENCLAW_SKIP_CANVAS_HOST: "1",
33
+ TEAMCLAW_BOOTSTRAP_CONFIG_B64: Buffer.from(spec.configJson, "utf8").toString("base64"),
34
+ TEAMCLAW_WORKER_ID: spec.workerId,
35
+ TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
36
+ ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
37
+ };
38
+ // When workers share a Docker network with the controller container, advertise
39
+ // the container name and internal worker port so sibling containers can reach it
40
+ // directly. When the controller runs on the host, fall back to publishing a host
41
+ // port and advertising localhost for host-side callbacks.
42
+ const usePortPublishing = spec.publishedHostPort !== undefined;
43
+ if (this.config.workerProvisioningDockerNetwork) {
44
+ env.TEAMCLAW_ADVERTISE_HOST = instanceName;
45
+ env.TEAMCLAW_ADVERTISE_PORT = String(spec.workerPort);
46
+ }
47
+ else if (usePortPublishing) {
48
+ env.TEAMCLAW_ADVERTISE_HOST = "localhost";
49
+ env.TEAMCLAW_ADVERTISE_PORT = String(spec.publishedHostPort);
50
+ }
51
+ const hostConfig = {
52
+ Binds: buildDockerBinds(this.config),
53
+ NetworkMode: this.config.workerProvisioningDockerNetwork || undefined,
54
+ };
55
+ if (usePortPublishing) {
56
+ hostConfig.PortBindings = {
57
+ [`${spec.workerPort}/tcp`]: [{ HostPort: String(spec.publishedHostPort) }],
58
+ };
59
+ }
60
+ const containerConfig = {
61
+ Image: this.config.workerProvisioningImage,
62
+ Cmd: ["sh", "-lc", buildContainerBootstrapScript()],
63
+ Env: Object.entries(env).map(([key, value]) => `${key}=${value}`),
64
+ User: "root",
65
+ Labels: {
66
+ "teamclaw.managed": "true",
67
+ "teamclaw.team": this.config.teamName,
68
+ "teamclaw.role": spec.role,
69
+ "teamclaw.worker_id": spec.workerId,
70
+ },
71
+ HostConfig: hostConfig,
72
+ };
73
+ if (usePortPublishing) {
74
+ containerConfig.ExposedPorts = { [`${spec.workerPort}/tcp`]: {} };
75
+ }
76
+ const response = await this.client.requestJson("POST", `/containers/create?name=${encodeURIComponent(instanceName)}`, containerConfig, [201]);
77
+ const instanceId = typeof response.Id === "string" ? response.Id : undefined;
78
+ if (!instanceId) {
79
+ throw new Error("Docker create did not return a container ID");
80
+ }
81
+ await this.client.requestVoid("POST", `/containers/${instanceId}/start`, undefined, [204]);
82
+ this.logger.info(`Provisioner: started docker worker container ${instanceName} (${instanceId})`);
83
+ return {
84
+ instanceId,
85
+ instanceName,
86
+ };
87
+ }
88
+ async terminate(record) {
89
+ const target = record.instanceId || record.instanceName;
90
+ if (!target) {
91
+ return;
92
+ }
93
+ await this.client.requestVoid("DELETE", `/containers/${target}?force=1`, undefined, [204, 404]);
94
+ }
95
+ }
96
+ class DockerApiClient {
97
+ endpoint;
98
+ constructor() {
99
+ this.endpoint = resolveDockerEndpoint();
100
+ }
101
+ async requestJson(method, requestPath, body, okStatuses = [200]) {
102
+ const response = await this.request(method, requestPath, body, okStatuses);
103
+ if (!response.body) {
104
+ return {};
105
+ }
106
+ return JSON.parse(response.body);
107
+ }
108
+ async requestVoid(method, requestPath, body, okStatuses = [200]) {
109
+ await this.request(method, requestPath, body, okStatuses);
110
+ }
111
+ async request(method, requestPath, body, okStatuses) {
112
+ const payload = body === undefined ? undefined : JSON.stringify(body);
113
+ // Prefer the daemon's negotiated default unless the operator pins a version explicitly.
114
+ const finalPath = DOCKER_API_VERSION ? `/${DOCKER_API_VERSION}${requestPath}` : requestPath;
115
+ return await new Promise((resolve, reject) => {
116
+ const transport = this.endpoint.protocol === "https:" ? https : http;
117
+ const req = transport.request({
118
+ method,
119
+ socketPath: this.endpoint.socketPath,
120
+ hostname: this.endpoint.hostname,
121
+ port: this.endpoint.port,
122
+ path: finalPath,
123
+ headers: payload
124
+ ? {
125
+ "Content-Type": "application/json",
126
+ "Content-Length": Buffer.byteLength(payload),
127
+ }
128
+ : undefined,
129
+ }, (res) => {
130
+ const chunks = [];
131
+ res.on("data", (chunk) => chunks.push(chunk));
132
+ res.on("end", () => {
133
+ const text = Buffer.concat(chunks).toString("utf8");
134
+ const status = res.statusCode ?? 500;
135
+ if (!okStatuses.includes(status)) {
136
+ const message = extractDockerErrorMessage(text) || `Docker API ${method} ${requestPath} failed with ${status}`;
137
+ reject(new Error(message));
138
+ return;
139
+ }
140
+ resolve({ status, body: text });
141
+ });
142
+ });
143
+ req.on("error", reject);
144
+ if (payload) {
145
+ req.write(payload);
146
+ }
147
+ req.end();
148
+ });
149
+ }
150
+ }
151
+ function resolveDockerApiVersion() {
152
+ const configured = process.env.DOCKER_API_VERSION?.trim();
153
+ if (!configured) {
154
+ return null;
155
+ }
156
+ return configured.startsWith("v") ? configured : `v${configured}`;
157
+ }
158
+ function extractDockerBindTarget(bind) {
159
+ for (const part of bind.split(":").reverse()) {
160
+ const trimmed = part.trim();
161
+ if (trimmed.startsWith("/")) {
162
+ return trimmed;
163
+ }
164
+ }
165
+ return null;
166
+ }
167
+ function buildDockerBinds(config) {
168
+ const binds = [...config.workerProvisioningDockerMounts];
169
+ if (!binds.some((bind) => extractDockerBindTarget(bind) === DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR)) {
170
+ const _pd = resolveCurrentTeamClawPluginRootDir();
171
+ if (_pd)
172
+ binds.unshift(`${_pd}:${DEFAULT_DOCKER_BUNDLED_TEAMCLAW_PLUGIN_DIR}:ro`);
173
+ }
174
+ if (config.workerProvisioningDockerWorkspaceVolume && config.workerProvisioningWorkspaceRoot) {
175
+ binds.unshift(`${config.workerProvisioningDockerWorkspaceVolume}:${config.workerProvisioningWorkspaceRoot}`);
176
+ }
177
+ return [...new Set(binds)];
178
+ }
179
+ function resolveDockerEndpoint() {
180
+ const dockerHost = process.env.DOCKER_HOST?.trim();
181
+ if (!dockerHost) {
182
+ return {
183
+ protocol: "http:",
184
+ socketPath: "/var/run/docker.sock",
185
+ };
186
+ }
187
+ if (dockerHost.startsWith("unix://")) {
188
+ return {
189
+ protocol: "http:",
190
+ socketPath: dockerHost.slice("unix://".length),
191
+ };
192
+ }
193
+ const normalized = dockerHost.startsWith("tcp://")
194
+ ? dockerHost.replace(/^tcp:\/\//, "http://")
195
+ : dockerHost;
196
+ const url = new URL(normalized);
197
+ return {
198
+ protocol: url.protocol === "https:" ? "https:" : "http:",
199
+ hostname: url.hostname,
200
+ port: url.port ? Number(url.port) : (url.protocol === "https:" ? 443 : 2375),
201
+ };
202
+ }
203
+ function extractDockerErrorMessage(body) {
204
+ if (!body.trim()) {
205
+ return null;
206
+ }
207
+ try {
208
+ const parsed = JSON.parse(body);
209
+ return typeof parsed.message === "string" ? parsed.message : body;
210
+ }
211
+ catch {
212
+ return body;
213
+ }
214
+ }