@teamclaws/teamclaw 2026.11.0 → 2026.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/cli.mjs +368 -13
  2. package/dist/index.js +61 -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/config-routes.js +138 -0
  7. package/dist/src/controller/controller-planning.js +1 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-service.js +67 -10
  10. package/dist/src/controller/controller-tools.js +3 -1
  11. package/dist/src/controller/github-auth.js +2 -1
  12. package/dist/src/controller/http-server.js +51 -16
  13. package/dist/src/controller/kickoff-orchestrator.js +3 -39
  14. package/dist/src/controller/message-delivery.js +4 -1
  15. package/dist/src/controller/orchestration-manifest.js +5 -65
  16. package/dist/src/controller/preview-manager.js +51 -3
  17. package/dist/src/controller/profile-switch.js +42 -22
  18. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  19. package/dist/src/controller/provisioning/container-shared.js +64 -0
  20. package/dist/src/controller/provisioning/docker.js +214 -0
  21. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  22. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  23. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  24. package/dist/src/controller/provisioning-config.js +239 -0
  25. package/dist/src/controller/repo-routes.js +70 -4
  26. package/dist/src/controller/report-routes.js +56 -0
  27. package/dist/src/controller/route-table.js +73 -1045
  28. package/dist/src/controller/security.js +775 -0
  29. package/dist/src/controller/status-routes.js +287 -0
  30. package/dist/src/controller/task-assignment.js +5 -2
  31. package/dist/src/controller/task-execution.js +31 -0
  32. package/dist/src/controller/task-results.js +10 -0
  33. package/dist/src/controller/tunnel-manager.js +41 -8
  34. package/dist/src/controller/tunnel-routes.js +225 -0
  35. package/dist/src/controller/websocket.js +6 -2
  36. package/dist/src/controller/webui-routes.js +49 -0
  37. package/dist/src/controller/worker-provisioning.js +39 -949
  38. package/dist/src/controller/workflow-routes.js +407 -0
  39. package/dist/src/controller/workspace-routes.js +200 -0
  40. package/dist/src/git-collaboration.js +4 -9
  41. package/dist/src/identity.js +12 -1
  42. package/dist/src/openclaw-workspace.js +36 -0
  43. package/dist/src/profile-loader.js +119 -1
  44. package/dist/src/profiles/banking.json +26 -2
  45. package/dist/src/profiles/schema.json +82 -2
  46. package/dist/src/prompt-policy.js +18 -6
  47. package/dist/src/protocol.js +66 -3
  48. package/dist/src/shared/clarification-schema.js +65 -0
  49. package/dist/src/shared/github-auth.js +15 -0
  50. package/dist/src/shared/kickoff-prompt.js +37 -0
  51. package/dist/src/shared/utils.js +47 -0
  52. package/dist/src/state.js +89 -3
  53. package/dist/src/teamauto/scanner.js +21 -2
  54. package/dist/src/teamauto/scheduler.js +9 -2
  55. package/dist/src/types.js +15 -1
  56. package/dist/src/ui/app.js +990 -73
  57. package/dist/src/ui/github-login.html +1 -0
  58. package/dist/src/ui/index.html +125 -36
  59. package/dist/src/worker/http-handler.js +59 -0
  60. package/dist/src/worker/skill-installer.js +3 -9
  61. package/dist/src/worker/tools.js +20 -10
  62. package/dist/src/worker/worker-service.js +17 -4
  63. package/index.ts +69 -32
  64. package/openclaw.plugin.json +23 -2
  65. package/package.json +1 -1
  66. package/src/config.ts +24 -0
  67. package/src/controller/auth-routes.ts +157 -0
  68. package/src/controller/clarification-routes.ts +1 -1
  69. package/src/controller/config-routes.ts +152 -0
  70. package/src/controller/controller-planning.ts +8 -0
  71. package/src/controller/controller-routes.ts +237 -0
  72. package/src/controller/controller-service.ts +128 -10
  73. package/src/controller/controller-tools.ts +5 -2
  74. package/src/controller/github-auth.ts +28 -63
  75. package/src/controller/http-server.ts +66 -17
  76. package/src/controller/kickoff-orchestrator.ts +3 -42
  77. package/src/controller/message-delivery.ts +4 -1
  78. package/src/controller/orchestration-manifest.ts +8 -71
  79. package/src/controller/preview-manager.ts +53 -3
  80. package/src/controller/profile-switch.ts +53 -23
  81. package/src/controller/provisioning/backend-contract.ts +51 -0
  82. package/src/controller/provisioning/container-shared.ts +84 -0
  83. package/src/controller/provisioning/docker.ts +260 -0
  84. package/src/controller/provisioning/kubernetes.ts +263 -0
  85. package/src/controller/provisioning/plugin-root.ts +42 -0
  86. package/src/controller/provisioning/process-supervisor.ts +214 -0
  87. package/src/controller/provisioning-config.ts +289 -0
  88. package/src/controller/repo-routes.ts +84 -12
  89. package/src/controller/report-routes.ts +64 -0
  90. package/src/controller/route-table.ts +139 -1152
  91. package/src/controller/security.ts +899 -0
  92. package/src/controller/status-routes.ts +354 -0
  93. package/src/controller/task-assignment.ts +5 -1
  94. package/src/controller/task-execution.ts +43 -0
  95. package/src/controller/task-results.ts +12 -0
  96. package/src/controller/tunnel-manager.ts +45 -8
  97. package/src/controller/tunnel-routes.ts +231 -0
  98. package/src/controller/websocket.ts +20 -3
  99. package/src/controller/webui-routes.ts +55 -0
  100. package/src/controller/worker-provisioning.ts +51 -1117
  101. package/src/controller/workflow-routes.ts +498 -0
  102. package/src/controller/workspace-routes.ts +222 -0
  103. package/src/git-collaboration.ts +4 -9
  104. package/src/identity.ts +13 -1
  105. package/src/openclaw-workspace.ts +47 -0
  106. package/src/profile-loader.ts +167 -1
  107. package/src/profiles/banking.json +26 -2
  108. package/src/profiles/schema.json +82 -2
  109. package/src/prompt-policy.ts +19 -6
  110. package/src/protocol.ts +72 -2
  111. package/src/shared/clarification-schema.ts +81 -0
  112. package/src/shared/github-auth.ts +92 -0
  113. package/src/shared/kickoff-prompt.ts +47 -0
  114. package/src/shared/utils.ts +51 -0
  115. package/src/state.ts +92 -3
  116. package/src/teamauto/github-client.ts +2 -1
  117. package/src/teamauto/repo-sync.ts +2 -1
  118. package/src/teamauto/scanner.ts +22 -3
  119. package/src/teamauto/scheduler.ts +11 -3
  120. package/src/teamauto/store.ts +5 -0
  121. package/src/types.ts +130 -1
  122. package/src/ui/app.js +990 -73
  123. package/src/ui/github-login.html +1 -0
  124. package/src/ui/index.html +125 -36
  125. package/src/worker/http-handler.ts +64 -1
  126. package/src/worker/skill-installer.ts +3 -9
  127. package/src/worker/tools.ts +21 -10
  128. package/src/worker/worker-service.ts +18 -4
@@ -6,17 +6,25 @@
6
6
  // ./route-table.ts, PR-D) and every handler body lives in a domain module.
7
7
  // Request pipeline, in order:
8
8
  //
9
- // 1. CORS preflight (OPTIONS short-circuit)
10
- // 2. Tunnel gate (viaTunnel classification: gate page routes / gate
9
+ // 1. CORS preflight (OPTIONS short-circuit; wildcard while device
10
+ // protection is off - the historical behavior - and narrowed to the
11
+ // UI's own origin once it is on)
12
+ // 2. Device-auth gate (issue #23, ./security.ts createSecurityMiddleware):
13
+ // zero-op while no devices are paired (L0); once devices exist every
14
+ // non-exempt /api request must present a valid device token and the
15
+ // response CORS policy is pinned before dispatch. Runs BEFORE the
16
+ // tunnel gate and the handleRequest gates so transition/capability/
17
+ // tunnel-management responses never leak to unpaired callers.
18
+ // 3. Tunnel gate (viaTunnel classification: gate page routes / gate
11
19
  // cookie 403 / tunnel management API - tables in ./route-table.ts)
12
- // 3. handleRequest gates (verbatim, NOT part of the route table):
20
+ // 4. handleRequest gates (verbatim, NOT part of the route table):
13
21
  // a. profile-switch transition matrix (409 worker re-register,
14
22
  // 503+Retry-After task submission / repo import)
15
23
  // b. capability 404 gates (steady-state existence gate, after (a) on
16
24
  // purpose: transition semantics win over the 404)
17
- // 4. declarative route table match (./route-table.ts, array order =
25
+ // 5. declarative route table match (./route-table.ts, array order =
18
26
  // the historical if/startsWith chain, one-to-one)
19
- // 5. fall-through 404
27
+ // 6. fall-through 404
20
28
  //
21
29
  // Domain module index (the 18 modules this root composes; none of them may
22
30
  // import this file):
@@ -47,6 +55,12 @@ import { createTunnelManager, gatePageHtml } from "./tunnel-manager.js";
47
55
  // (route-table imports this file as TYPE ONLY), so the module graph stays
48
56
  // acyclic.
49
57
  import { controllerRouteTable, createTunnelGateRoutes, createTunnelManagementRoutes, dispatchRoutes, SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS, } from "./route-table.js";
58
+ // Issue #23 (backend wave): the device-pairing security module owns the
59
+ // auth middleware, the CORS narrowing policy, the WS upgrade guard and the
60
+ // pairing handlers (registered via route-table.ts). This file only wires
61
+ // them into the pipeline below - all pathname/method policy lives in
62
+ // security.ts.
63
+ import { classifySecurityPeer, corsPreflightDecision, createSecurityMiddleware, createWebSocketUpgradeGuard, isProtectionOn, } from "./security.js";
50
64
  // ===========================================================================
51
65
  // Team profile switch dispatch-layer constants (Phase 2.1,
52
66
  // vertical-team-profiles-design.md 2.3). The six-step switch machine itself
@@ -123,14 +137,17 @@ export function createControllerHttpServer(deps) {
123
137
  // Tunnel-side route tables are built once (lazily, next to the lazy
124
138
  // tunnel manager singleton they close over) and reused for every request.
125
139
  let tunnelRoutesSingleton = null;
140
+ // Issue #23: the device gate. Zero-friction ladder - while no device is
141
+ // paired (protection off) this is a no-op passthrough (L0, the exact
142
+ // pre-issue behavior); once devices exist it enforces per-device tokens
143
+ // on every non-exempt /api route (exemptions and 401 shape in security.ts).
144
+ const securityGate = createSecurityMiddleware(deps);
126
145
  const server = http.createServer(async (req, res) => {
127
- // CORS preflight
146
+ // CORS preflight (issue #23: wildcard while protection is off - the
147
+ // historical bytes - and narrowed to the UI's own origin once on).
128
148
  if (req.method === "OPTIONS") {
129
- res.writeHead(200, {
130
- "Access-Control-Allow-Origin": "*",
131
- "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
132
- "Access-Control-Allow-Headers": "Content-Type",
133
- });
149
+ const decision = corsPreflightDecision(req, isProtectionOn(deps.getTeamState()));
150
+ res.writeHead(decision.status, decision.headers);
134
151
  res.end();
135
152
  return;
136
153
  }
@@ -154,6 +171,17 @@ export function createControllerHttpServer(deps) {
154
171
  req, res, requestUrl: url, pathname, deps, currentState: null,
155
172
  };
156
173
  const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
174
+ // ==================== Device auth gate (issue #23) ====================
175
+ // Runs BEFORE the tunnel gate tables, the transition matrix and the
176
+ // capability gates so none of those surfaces answer - or leak response
177
+ // shape information - to unpaired callers while protection is on.
178
+ // Requests arriving through the sharing tunnel are classified from the
179
+ // Host header (cloudflared dials in from loopback, so the socket peer
180
+ // address would lie); see classifySecurityPeer in ./security.ts.
181
+ const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
182
+ if (!securityGate(req, res, pathname, peer)) {
183
+ return;
184
+ }
157
185
  if (viaTunnel) {
158
186
  if (await dispatchRoutes(tunnelRoutesSingleton.gate, tunnelCtx)) {
159
187
  return;
@@ -170,15 +198,22 @@ export function createControllerHttpServer(deps) {
170
198
  }
171
199
  }
172
200
  try {
173
- await handleRequest(req, res, pathname, deps);
201
+ await handleRequest(req, res, pathname, deps, peer);
174
202
  }
175
203
  catch (err) {
176
204
  logger.error(`Controller HTTP error: ${err instanceof Error ? err.message : String(err)}`);
177
205
  sendError(res, 500, "Internal server error");
178
206
  }
179
207
  });
180
- // Attach WebSocket
181
- wsServer.attach(server);
208
+ // Attach WebSocket (issue #23: while device protection is on, upgrades
209
+ // must carry a valid device token - ?token= query for browsers, cookie /
210
+ // Bearer for native clients; see createWebSocketUpgradeGuard).
211
+ wsServer.attach(server, {
212
+ verifyUpgrade: createWebSocketUpgradeGuard({
213
+ ...deps,
214
+ isTunnelHost: (host) => tunnelManagerSingleton?.isTunnelRequest(host) ?? false,
215
+ }),
216
+ });
182
217
  // Plugin shutdown: kill the local connector and tear down the remote
183
218
  // tunnel so gateway exits never leak orphan cloudflared processes.
184
219
  server.on("close", () => {
@@ -206,7 +241,7 @@ export function createControllerHttpServer(deps) {
206
241
  }, 2000);
207
242
  return server;
208
243
  }
209
- async function handleRequest(req, res, pathname, deps) {
244
+ async function handleRequest(req, res, pathname, deps, peer) {
210
245
  const requestUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
211
246
  const currentState = deps.getTeamState();
212
247
  // ==================== Profile switch concurrency matrix ====================
@@ -276,7 +311,7 @@ async function handleRequest(req, res, pathname, deps) {
276
311
  // false) to continue matching; an exhausted table falls through to the
277
312
  // final 404 below - both semantics are preserved from the old chain.
278
313
  const handled = await dispatchRoutes(controllerRouteTable, {
279
- req, res, requestUrl, pathname, deps, currentState,
314
+ req, res, requestUrl, pathname, deps, currentState, peer,
280
315
  });
281
316
  if (!handled) {
282
317
  sendError(res, 404, "Not found");
@@ -16,6 +16,9 @@
16
16
  */
17
17
  // Phase 1.3: role data comes from the active TeamProfile loader.
18
18
  import { getActiveDefaultRole, getActiveRole, getActiveRoleIds, validateActiveRoleId } from "../profile-loader.js";
19
+ // W6 of issue #226: the local sleep copy (byte-identical to the shared one)
20
+ // was removed in favor of shared/utils.js.
21
+ import { sleep } from "../shared/utils.js";
19
22
  import { inferTaskRoleWithConfidence } from "./role-inference.js";
20
23
  // ── Constants ────────────────────────────────────────────────────────────────
21
24
  /** Maximum time to wait for all workers to register after provisioning. */
@@ -180,45 +183,6 @@ function buildKickoffSummary(plan, _requirement) {
180
183
  parts.push("Use these team assessments to create the final execution plan. Only create tasks for roles that confirmed they are needed. Respect the dependency ordering suggested by the team.");
181
184
  return parts.join("\n");
182
185
  }
183
- /**
184
- * Build the kickoff assessment prompt sent to a worker.
185
- * The worker should respond with structured JSON matching KickoffAssessment.
186
- */
187
- export function buildKickoffAssessmentPrompt(role, requirement) {
188
- const roleDef = getActiveRole(role);
189
- const roleLabel = roleDef?.label ?? role;
190
- return [
191
- `You are the ${roleLabel} in a virtual software team.`,
192
- `Your team is conducting a kickoff meeting for a new requirement.`,
193
- ``,
194
- `## Requirement`,
195
- requirement,
196
- ``,
197
- `## Your Task`,
198
- `Evaluate this requirement from your professional perspective as ${roleLabel}.`,
199
- `Respond with a JSON object (and nothing else) with these fields:`,
200
- ``,
201
- `{`,
202
- ` "needed": boolean, // Is your role needed for this project?`,
203
- ` "scope": string, // What would you contribute? (1-2 sentences)`,
204
- ` "suggestedTasks": string[], // Specific tasks you'd handle (2-5 items)`,
205
- ` "dependencies": string[], // What you need from other roles before or during your work`,
206
- ` "risks": string[], // Concerns or risks from your perspective`,
207
- ` "questions": string[] // Clarifications you'd want before starting`,
208
- `}`,
209
- ``,
210
- `Guidelines:`,
211
- `- Be honest about whether your role is truly needed. Don't inflate your importance.`,
212
- `- For "needed", consider: does the project actually require ${roleLabel}-level expertise?`,
213
- `- A simple single-file script does NOT need an architect. A TODO app does NOT need a security engineer.`,
214
- `- Keep suggestedTasks concrete and actionable, not vague.`,
215
- `- Only list dependencies on roles that are actually relevant.`,
216
- `- Return ONLY the JSON object, no markdown fencing, no explanation.`,
217
- ].join("\n");
218
- }
219
- function sleep(ms) {
220
- return new Promise((resolve) => setTimeout(resolve, ms));
221
- }
222
186
  export async function resolveTaskRoleWithLlmFallback(task, deps = {}) {
223
187
  const verdict = (deps.inferWithConfidence ?? inferTaskRoleWithConfidence)(task);
224
188
  if (!verdict.needsLlmFallback) {
@@ -1,7 +1,10 @@
1
+ import { withWorkerDispatchToken } from "./task-execution.js";
1
2
  export async function deliverMessageToWorker(worker, message, deps) {
3
+ // Issue #222: carry the worker's dispatch token so a token-paired worker
4
+ // accepts the injection; L0 sends the historical header set unchanged.
2
5
  const res = await fetch(`${worker.url}/api/v1/messages`, {
3
6
  method: "POST",
4
- headers: { "Content-Type": "application/json" },
7
+ headers: withWorkerDispatchToken({ "Content-Type": "application/json" }, worker.id, deps.config, deps.getTeamState()),
5
8
  body: JSON.stringify(message),
6
9
  });
7
10
  if (!res.ok) {
@@ -1,5 +1,10 @@
1
1
  import { validateRoleIdList } from "../roles.js";
2
2
  import { deriveStableProjectKey } from "../openclaw-workspace.js";
3
+ // Issue #226 W3: the clarification-schema normalization family moved to the
4
+ // shared layer (worker/tools.ts consumes it; the worker must not import the
5
+ // controller tree). This module keeps the manifest-specific normalizers and
6
+ // imports the shared contract — controller -> shared direction only.
7
+ import { normalizeClarificationQuestionSchemas, normalizeOptionalManifestText, } from "../shared/clarification-schema.js";
3
8
  export function normalizeManifestRoleList(raw) {
4
9
  // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts.
5
10
  // The hand-written TEAMCLAW_ROLE_IDS copy this function used to keep was
@@ -15,71 +20,6 @@ export function normalizeManifestStringList(raw) {
15
20
  .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
16
21
  .filter(Boolean);
17
22
  }
18
- export function normalizeOptionalManifestText(raw) {
19
- if (typeof raw !== "string") {
20
- return undefined;
21
- }
22
- const normalized = raw.trim();
23
- return normalized || undefined;
24
- }
25
- export function normalizeClarificationOptions(raw) {
26
- if (!Array.isArray(raw)) {
27
- return [];
28
- }
29
- return raw
30
- .filter((entry) => !!entry && typeof entry === "object")
31
- .map((entry) => ({
32
- value: typeof entry.value === "string" ? entry.value.trim() : "",
33
- label: typeof entry.label === "string" ? entry.label.trim() : "",
34
- hint: typeof entry.hint === "string" && entry.hint.trim() ? entry.hint.trim() : undefined,
35
- }))
36
- .filter((entry) => entry.value && entry.label);
37
- }
38
- export function normalizeClarificationQuestionSchema(raw) {
39
- if (!raw || typeof raw !== "object") {
40
- return undefined;
41
- }
42
- const input = raw;
43
- const kind = typeof input.kind === "string" ? input.kind.trim() : "";
44
- const title = typeof input.title === "string" ? input.title.trim() : "";
45
- if (!title || !["single-select", "multi-select", "number", "text"].includes(kind)) {
46
- return undefined;
47
- }
48
- const options = normalizeClarificationOptions(input.options);
49
- const schema = {
50
- kind: kind,
51
- title,
52
- description: normalizeOptionalManifestText(input.description),
53
- required: input.required == null ? true : Boolean(input.required),
54
- allowOther: Boolean(input.allowOther),
55
- placeholder: normalizeOptionalManifestText(input.placeholder),
56
- unit: normalizeOptionalManifestText(input.unit),
57
- };
58
- if (options.length > 0) {
59
- schema.options = options;
60
- }
61
- if (typeof input.min === "number" && Number.isFinite(input.min)) {
62
- schema.min = input.min;
63
- }
64
- if (typeof input.max === "number" && Number.isFinite(input.max)) {
65
- schema.max = input.max;
66
- }
67
- if (typeof input.step === "number" && Number.isFinite(input.step)) {
68
- schema.step = input.step;
69
- }
70
- if ((schema.kind === "single-select" || schema.kind === "multi-select") && (!schema.options || schema.options.length === 0)) {
71
- return undefined;
72
- }
73
- return schema;
74
- }
75
- export function normalizeClarificationQuestionSchemas(raw) {
76
- if (!Array.isArray(raw)) {
77
- return [];
78
- }
79
- return raw
80
- .map((entry) => normalizeClarificationQuestionSchema(entry))
81
- .filter((entry) => Boolean(entry));
82
- }
83
23
  export function normalizeManifestCreatedTasks(raw) {
84
24
  if (!Array.isArray(raw)) {
85
25
  return [];
@@ -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
+ }