@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
@@ -1,6 +1,4 @@
1
1
  import type {
2
- ClarificationQuestionOption,
3
- ClarificationQuestionSchema,
4
2
  ControllerManifestCompletionOpportunity,
5
3
  ControllerManifestCreatedTask,
6
4
  ControllerManifestDeferredTask,
@@ -9,6 +7,14 @@ import type {
9
7
  } from "../types.js";
10
8
  import { validateRoleIdList } from "../roles.js";
11
9
  import { deriveStableProjectKey } from "../openclaw-workspace.js";
10
+ // Issue #226 W3: the clarification-schema normalization family moved to the
11
+ // shared layer (worker/tools.ts consumes it; the worker must not import the
12
+ // controller tree). This module keeps the manifest-specific normalizers and
13
+ // imports the shared contract — controller -> shared direction only.
14
+ import {
15
+ normalizeClarificationQuestionSchemas,
16
+ normalizeOptionalManifestText,
17
+ } from "../shared/clarification-schema.js";
12
18
 
13
19
  export function normalizeManifestRoleList(raw: unknown): RoleId[] {
14
20
  // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts.
@@ -27,75 +33,6 @@ export function normalizeManifestStringList(raw: unknown): string[] {
27
33
  .filter(Boolean);
28
34
  }
29
35
 
30
- export function normalizeOptionalManifestText(raw: unknown): string | undefined {
31
- if (typeof raw !== "string") {
32
- return undefined;
33
- }
34
- const normalized = raw.trim();
35
- return normalized || undefined;
36
- }
37
-
38
- export function normalizeClarificationOptions(raw: unknown): ClarificationQuestionOption[] {
39
- if (!Array.isArray(raw)) {
40
- return [];
41
- }
42
- return raw
43
- .filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === "object")
44
- .map((entry) => ({
45
- value: typeof entry.value === "string" ? entry.value.trim() : "",
46
- label: typeof entry.label === "string" ? entry.label.trim() : "",
47
- hint: typeof entry.hint === "string" && entry.hint.trim() ? entry.hint.trim() : undefined,
48
- }))
49
- .filter((entry) => entry.value && entry.label);
50
- }
51
-
52
- export function normalizeClarificationQuestionSchema(raw: unknown): ClarificationQuestionSchema | undefined {
53
- if (!raw || typeof raw !== "object") {
54
- return undefined;
55
- }
56
- const input = raw as Record<string, unknown>;
57
- const kind = typeof input.kind === "string" ? input.kind.trim() : "";
58
- const title = typeof input.title === "string" ? input.title.trim() : "";
59
- if (!title || !["single-select", "multi-select", "number", "text"].includes(kind)) {
60
- return undefined;
61
- }
62
- const options = normalizeClarificationOptions(input.options);
63
- const schema: ClarificationQuestionSchema = {
64
- kind: kind as ClarificationQuestionSchema["kind"],
65
- title,
66
- description: normalizeOptionalManifestText(input.description),
67
- required: input.required == null ? true : Boolean(input.required),
68
- allowOther: Boolean(input.allowOther),
69
- placeholder: normalizeOptionalManifestText(input.placeholder),
70
- unit: normalizeOptionalManifestText(input.unit),
71
- };
72
- if (options.length > 0) {
73
- schema.options = options;
74
- }
75
- if (typeof input.min === "number" && Number.isFinite(input.min)) {
76
- schema.min = input.min;
77
- }
78
- if (typeof input.max === "number" && Number.isFinite(input.max)) {
79
- schema.max = input.max;
80
- }
81
- if (typeof input.step === "number" && Number.isFinite(input.step)) {
82
- schema.step = input.step;
83
- }
84
- if ((schema.kind === "single-select" || schema.kind === "multi-select") && (!schema.options || schema.options.length === 0)) {
85
- return undefined;
86
- }
87
- return schema;
88
- }
89
-
90
- export function normalizeClarificationQuestionSchemas(raw: unknown): ClarificationQuestionSchema[] {
91
- if (!Array.isArray(raw)) {
92
- return [];
93
- }
94
- return raw
95
- .map((entry) => normalizeClarificationQuestionSchema(entry))
96
- .filter((entry): entry is ClarificationQuestionSchema => Boolean(entry));
97
- }
98
-
99
36
  export function normalizeManifestCreatedTasks(raw: unknown): ControllerManifestCreatedTask[] {
100
37
  if (!Array.isArray(raw)) {
101
38
  return [];
@@ -13,6 +13,48 @@ const PREVIEW_STOP_TIMEOUT_MS = 5_000;
13
13
 
14
14
  const GENERIC_SERVE_COMMAND = "npx -y serve -l {PORT}";
15
15
 
16
+ // Issue #237 W1: preview commands are LLM-authored (result contracts) and
17
+ // run through a shell - they must NOT inherit the controller's environment,
18
+ // or a prompt-injected previewCommand could exfiltrate every controller
19
+ // credential (GH_TOKEN, provider API keys, tunnel tokens). Policy: minimal
20
+ // allowlist of toolchain basics, matched case-insensitively so Windows
21
+ // (Path/SystemRoot/...) survives, plus the explicit preview vars set at the
22
+ // spawn site. Repos that genuinely need more can pass names through
23
+ // TEAMCLAW_PREVIEW_EXTRA_ENV (comma-separated list of env var names whose
24
+ // controller values are forwarded verbatim); anything else is absent.
25
+ const PREVIEW_ENV_ALLOWLIST = new Set([
26
+ "PATH", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "TMPDIR", "TZ", "TERM", "SHELL",
27
+ // Windows toolchain basics (no-ops elsewhere, harmless to match).
28
+ // PROCESSOR_ARCHITECTURE/PROCESSOR_IDENTIFIER are read by node-gyp-style
29
+ // native builds (review follow-up to #237 W1) - plain toolchain
30
+ // descriptors, no credential material.
31
+ "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "PATHEXT", "WINDIR", "USERPROFILE",
32
+ "APPDATA", "LOCALAPPDATA", "PROGRAMFILES", "PROGRAMDATA", "NUMBER_OF_PROCESSORS", "OS",
33
+ "PROCESSOR_ARCHITECTURE", "PROCESSOR_IDENTIFIER",
34
+ ]);
35
+ const PREVIEW_EXTRA_ENV_VAR = "TEAMCLAW_PREVIEW_EXTRA_ENV";
36
+
37
+ /** Builds the restricted environment for preview subprocesses (#237 W1):
38
+ * allowlisted controller vars + extraEnv (venv PATH/VIRTUAL_ENV) + whatever
39
+ * the operator declared via TEAMCLAW_PREVIEW_EXTRA_ENV. Never returns the
40
+ * full process.env. Exported for the #237 regression test. */
41
+ export function buildPreviewEnv(extraEnv: Record<string, string>): NodeJS.ProcessEnv {
42
+ const allow = new Set(PREVIEW_ENV_ALLOWLIST);
43
+ for (const name of (process.env[PREVIEW_EXTRA_ENV_VAR] ?? "").split(",")) {
44
+ const normalized = name.trim().toUpperCase();
45
+ if (normalized) {
46
+ allow.add(normalized);
47
+ }
48
+ }
49
+ const env: Record<string, string> = {};
50
+ for (const [key, value] of Object.entries(process.env)) {
51
+ if (value !== undefined && allow.has(key.toUpperCase())) {
52
+ env[key] = value;
53
+ }
54
+ }
55
+ return { ...env, ...extraEnv };
56
+ }
57
+
16
58
  /**
17
59
  * Detect the tech stack from files in `cwd` and return a suitable preview command.
18
60
  * Only overrides `existingCommand` when it is the generic static file server
@@ -456,7 +498,10 @@ export class PreviewManager {
456
498
  const pipInstall = spawnManagedCommandProcess({
457
499
  command: `${pipBin} install -q -r requirements.txt`,
458
500
  cwd,
459
- env: { ...process.env, ...extraEnv },
501
+ // #237 W1: requirements.txt is worker-influenced and pip executes
502
+ // setup.py at install time, so this subprocess gets the same
503
+ // restricted env as the preview command itself.
504
+ env: buildPreviewEnv(extraEnv),
460
505
  });
461
506
  await new Promise<void>((resolve) => {
462
507
  pipInstall.on("exit", () => resolve());
@@ -470,10 +515,15 @@ export class PreviewManager {
470
515
 
471
516
  const child = spawnManagedCommandProcess({
472
517
  command: resolvedCommand,
518
+ // cwd is already forced inside the workspace (resolveWorkspaceDirectory
519
+ // confinement above), so the shell cannot escape the deliverable dir.
473
520
  cwd,
521
+ // #237 W1: restricted allowlist env - never the controller's full
522
+ // process.env (credential exfiltration via prompt-injected
523
+ // previewCommand). HOST/PORT/TEAMCLAW_PREVIEW_* are the explicit
524
+ // preview contract vars.
474
525
  env: {
475
- ...process.env,
476
- ...extraEnv,
526
+ ...buildPreviewEnv(extraEnv),
477
527
  HOST: "0.0.0.0",
478
528
  PORT: String(record.targetPort),
479
529
  TEAMCLAW_PREVIEW_BASE_PATH: record.liveUrl.replace(/\/$/u, ""),
@@ -5,13 +5,23 @@
5
5
  // the same deps object as before. This module must NEVER import http-server
6
6
  // (the reverse edge exists: http-server -> profile-switch); ws broadcasts,
7
7
  // state persistence and provisioning all arrive through the deps slice below.
8
+ // Issue #226 W4: persistence rides the single write entry (deps.
9
+ // updateTeamState) - including the awaited durability barriers this state
10
+ // machine needs - instead of independent saveTeamState calls; the update
11
+ // contract types are type-only imports from controller-service.js (the
12
+ // runtime edge points the other way, so the module graph stays acyclic).
8
13
  import type { PluginLogger } from "../../api.js";
9
14
  import type {
10
15
  PluginConfig,
11
16
  TaskInfo,
12
17
  TeamState,
13
18
  } from "../types.js";
14
- import { saveTeamState, archiveTeamState, findTeamSwitchArchive } from "../state.js";
19
+ import type {
20
+ TeamStateUpdateHandle,
21
+ TeamStateUpdateOptions,
22
+ UpdateTeamStateFn,
23
+ } from "./controller-service.js";
24
+ import { archiveTeamState, findTeamSwitchArchive } from "../state.js";
15
25
  import {
16
26
  BUILTIN_PROFILES,
17
27
  getActiveProfile,
@@ -34,7 +44,7 @@ export type TeamProfileSwitchDeps = {
34
44
  config: PluginConfig;
35
45
  logger: PluginLogger;
36
46
  getTeamState: () => TeamState | null;
37
- updateTeamState: (updater: (state: TeamState) => void) => TeamState;
47
+ updateTeamState: UpdateTeamStateFn;
38
48
  wsServer: TeamWebSocketServer;
39
49
  workerProvisioningManager?: WorkerProvisioningManager | null;
40
50
  previewManager?: PreviewManager;
@@ -129,22 +139,28 @@ export async function executeTeamProfileSwitch(
129
139
  targetProfileId: string,
130
140
  options: TeamProfileSwitchOptions = {},
131
141
  ): Promise<void> {
132
- const { config, logger, getTeamState, updateTeamState, wsServer, workerProvisioningManager } = deps;
142
+ const { config, logger, getTeamState, updateTeamState, workerProvisioningManager } = deps;
133
143
  const target = BUILTIN_PROFILES.get(targetProfileId);
134
144
  if (!target) {
135
145
  throw new Error(`TeamClaw team profile "${targetProfileId}" is not available in this installation`);
136
146
  }
137
- const setPhase = (phase: "draining" | "archiving" | "warming"): void => {
138
- updateTeamState((state) => {
147
+ // W4 (#226): phase flips persist through the single write entry. The
148
+ // awaited-durability variant is used everywhere so callers that need the
149
+ // crash-window barrier (step 3's archiving flip, step 5's warming flip)
150
+ // can await it; callers that historically fire-and-forget the save simply
151
+ // drop the handle (an un-awaited rejection behaves exactly like the old
152
+ // floating void save).
153
+ const setPhase = (phase: "draining" | "archiving" | "warming", options: TeamStateUpdateOptions = {}): TeamStateUpdateHandle => {
154
+ return updateTeamState((state) => {
139
155
  if (state.transition?.targetProfileId === targetProfileId) {
140
156
  state.transition.phase = phase;
141
157
  }
142
- });
158
+ }, { ...options, persist: "awaited" });
143
159
  };
144
160
 
145
161
  if (!options.skipArchive) {
146
162
  // Step 2: drain in-flight work, then stop every worker.
147
- setPhase("draining");
163
+ void setPhase("draining").persisted.catch(() => undefined);
148
164
  workerProvisioningManager?.setReconcileSuspended(true);
149
165
  const drain = await drainTeamForProfileSwitch(deps);
150
166
  for (const workerId of Object.keys(getTeamState()?.provisioning?.workers ?? {})) {
@@ -178,11 +194,19 @@ export async function executeTeamProfileSwitch(
178
194
  // Step 3: archive the whole previous TeamState with a roles snapshot.
179
195
  // The phase flip is persisted BEFORE the archive write so a crash between
180
196
  // the two leaves an unambiguous "archive may exist" state for the resume
181
- // path (file existence check).
182
- setPhase("archiving");
197
+ // path (file existence check). W4 (#226): the awaited durability barrier
198
+ // is the single entry's persisted handle (one save enqueued at the same
199
+ // point the old fire-and-forget + awaited second save pair wrote).
200
+ const archiving = setPhase("archiving");
201
+ // #251 note (no behavior change): `sourceState` below is whatever
202
+ // getTeamState() returns AFTER the awaited "archiving" persist barrier
203
+ // - it is NOT a phase-accurate snapshot frozen at the moment the drain
204
+ // finished. In-flight mutations racing the switch can be captured in
205
+ // the archive; the resume path tolerates this because the transition
206
+ // marker, not the snapshot contents, drives recovery.
183
207
  const sourceState = getTeamState();
184
208
  if (sourceState) {
185
- await saveTeamState(sourceState);
209
+ await archiving.persisted;
186
210
  const sourceProfile = getActiveProfile();
187
211
  await archiveTeamState(sourceState, {
188
212
  id: sourceProfile.id,
@@ -210,7 +234,7 @@ export async function executeTeamProfileSwitch(
210
234
  : null;
211
235
  setActiveProfileId(target.id);
212
236
  const newCreatedAt = Date.now();
213
- updateTeamState((state) => {
237
+ const step4 = updateTeamState((state) => {
214
238
  state.profileId = target.id;
215
239
  state.teamName = target.name;
216
240
  state.workers = {};
@@ -236,14 +260,13 @@ export async function executeTeamProfileSwitch(
236
260
  delete state.reports;
237
261
  }
238
262
  state.createdAt = newCreatedAt;
239
- });
240
- await saveTeamState(getTeamState()!);
263
+ }, { persist: "awaited" });
264
+ await step4.persisted;
241
265
 
242
266
  // Step 5: warm the new profile's warmupRoles through the provisioning
243
267
  // pipeline (launch dispatch; registration/readiness tracking continues in
244
268
  // the background exactly like a cold start).
245
- setPhase("warming");
246
- await saveTeamState(getTeamState()!);
269
+ await setPhase("warming").persisted;
247
270
  workerProvisioningManager?.setReconcileSuspended(false);
248
271
  if (workerProvisioningManager?.isEnabled() && target.warmupRoles.length > 0) {
249
272
  await workerProvisioningManager
@@ -251,12 +274,16 @@ export async function executeTeamProfileSwitch(
251
274
  .catch((err) => logger.warn(`Controller: profile switch warmup failed: ${err instanceof Error ? err.message : String(err)}`));
252
275
  }
253
276
 
254
- // Step 6: settle - clear the transition, persist, announce.
255
- updateTeamState((state) => {
277
+ // Step 6: settle - clear the transition, persist, announce. W4 (#226):
278
+ // the switch_completed broadcast rides the single entry's awaited
279
+ // persistence, preserving the event order (persisted, then announced).
280
+ const settled = updateTeamState((state) => {
256
281
  delete state.transition;
282
+ }, {
283
+ persist: "awaited",
284
+ broadcast: [{ type: "team.switch_completed", data: { profileId: target.id } }],
257
285
  });
258
- await saveTeamState(getTeamState()!);
259
- wsServer.broadcastUpdate({ type: "team.switch_completed", data: { profileId: target.id } });
286
+ await settled.persisted;
260
287
  logger.info(`Controller: team profile switch to "${target.id}" completed`);
261
288
  }
262
289
 
@@ -325,7 +352,7 @@ export function startTeamProfileSwitch(
325
352
  profileId: string,
326
353
  previousProfileId: string,
327
354
  ): void {
328
- const { logger, wsServer, updateTeamState, getTeamState } = deps;
355
+ const { logger, wsServer, updateTeamState } = deps;
329
356
  void executeTeamProfileSwitch(deps, profileId).catch(async (err) => {
330
357
  const detail = err instanceof Error ? err.message : String(err);
331
358
  logger.error(`Controller: team profile switch to "${profileId}" failed: ${detail}`);
@@ -356,11 +383,14 @@ export function startTeamProfileSwitch(
356
383
  type: "team.switch_failed",
357
384
  data: { previousProfileId, targetProfileId: profileId, reason },
358
385
  });
359
- updateTeamState((s) => {
386
+ // W4 (#226): best-effort persist of the unwedging through the single
387
+ // entry - one enqueued save with the failure path's swallow (the old
388
+ // shape fired an un-caught floating save plus this caught one).
389
+ const cleared = updateTeamState((s) => {
360
390
  if (s.transition?.targetProfileId === profileId) {
361
391
  delete s.transition;
362
392
  }
363
- });
364
- void saveTeamState(getTeamState()!).catch(() => undefined);
393
+ }, { persist: "awaited" });
394
+ void cleared.persisted.catch(() => undefined);
365
395
  });
366
396
  }
@@ -0,0 +1,51 @@
1
+ // W1 of issue #226 (worker-provisioning god-file split): the provisioner
2
+ // backend contract and the host-port policy shared by the facade and the
3
+ // backend modules, extracted VERBATIM from controller/worker-provisioning.ts.
4
+ // Pure types + pure functions: this module must never import a backend
5
+ // implementation or worker-provisioning.ts (dependency direction is one-way).
6
+ import type {
7
+ PluginConfig,
8
+ ProvisionedWorkerRecord,
9
+ RoleId,
10
+ WorkerProvisioningType,
11
+ } from "../../types.js";
12
+
13
+ export type LaunchSpec = {
14
+ workerId: string;
15
+ role: RoleId;
16
+ launchToken: string;
17
+ controllerUrl: string;
18
+ workerPort: number;
19
+ gatewayPort: number;
20
+ publishedHostPort?: number;
21
+ workspaceDir?: string;
22
+ env: Record<string, string>;
23
+ configJson: string;
24
+ };
25
+
26
+ export type LaunchResult = {
27
+ instanceId?: string;
28
+ instanceName?: string;
29
+ runtimeHomeDir?: string;
30
+ };
31
+
32
+ export interface WorkerProvisionerBackend {
33
+ readonly type: WorkerProvisioningType;
34
+ launch(spec: LaunchSpec): Promise<LaunchResult>;
35
+ terminate(record: ProvisionedWorkerRecord): Promise<void>;
36
+ stop?(): Promise<void>;
37
+ }
38
+
39
+ export function requiresDedicatedHostPortsForProvisioner(
40
+ provider: WorkerProvisioningType,
41
+ config: PluginConfig,
42
+ ): boolean {
43
+ if (provider === "process") {
44
+ return true;
45
+ }
46
+ return provider === "docker" && isDockerHostNetwork(config.workerProvisioningDockerNetwork);
47
+ }
48
+
49
+ export function isDockerHostNetwork(networkMode: string): boolean {
50
+ return networkMode.trim().toLowerCase() === "host";
51
+ }
@@ -0,0 +1,84 @@
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 type { RoleId } from "../../types.js";
7
+ import { sanitizePathSegment, sanitizeName } from "../../shared/utils.js";
8
+
9
+ export function buildManagedInstanceName(teamName: string, role: RoleId, workerId: string): string {
10
+ return buildManagedName("teamclaw", teamName, role, workerId, {
11
+ teamBudget: 18,
12
+ roleBudget: 12,
13
+ workerBudget: 12,
14
+ hashLength: 8,
15
+ maxLength: 63,
16
+ });
17
+ }
18
+
19
+ export function buildManagedHostname(teamName: string, role: RoleId, workerId: string): string {
20
+ return buildManagedName("tc", teamName, role, workerId, {
21
+ teamBudget: 10,
22
+ roleBudget: 8,
23
+ workerBudget: 6,
24
+ hashLength: 6,
25
+ maxLength: 40,
26
+ });
27
+ }
28
+
29
+ function buildManagedName(
30
+ prefix: string,
31
+ teamName: string,
32
+ role: RoleId,
33
+ workerId: string,
34
+ options: {
35
+ teamBudget: number;
36
+ roleBudget: number;
37
+ workerBudget: number;
38
+ hashLength: number;
39
+ maxLength: number;
40
+ },
41
+ ): string {
42
+ const teamPart = sanitizeLeadingSegment(teamName, options.teamBudget, "team");
43
+ const rolePart = sanitizeLeadingSegment(role, options.roleBudget, "worker");
44
+ const workerPart = sanitizeTrailingSegment(workerId, options.workerBudget, "worker");
45
+ const hash = shortStableHash(`${teamName}:${role}:${workerId}`).slice(0, options.hashLength);
46
+ return sanitizeName(`${prefix}-${teamPart}-${rolePart}-${workerPart}-${hash}`, options.maxLength);
47
+ }
48
+
49
+ function shortStableHash(value: string): string {
50
+ return createHash("sha1").update(value).digest("hex");
51
+ }
52
+
53
+ function sanitizeLeadingSegment(value: string, maxLength: number, fallback: string): string {
54
+ const normalized = sanitizePathSegment(value).slice(0, maxLength).replace(/^-+|-+$/g, "");
55
+ return normalized || fallback;
56
+ }
57
+
58
+ function sanitizeTrailingSegment(value: string, maxLength: number, fallback: string): string {
59
+ const normalized = sanitizePathSegment(value).slice(-maxLength).replace(/^-+|-+$/g, "");
60
+ return normalized || fallback;
61
+ }
62
+
63
+ export function buildContainerBootstrapScript(): string {
64
+ return [
65
+ "set -eu",
66
+ "mkdir -p \"$OPENCLAW_STATE_DIR\"",
67
+ "if [ -n \"${TEAMCLAW_WORKSPACE_DIR:-}\" ]; then mkdir -p \"$TEAMCLAW_WORKSPACE_DIR\"; fi",
68
+ // Issue #237 W4: the bootstrap config carries provider API keys - write
69
+ // it owner-only inside the container too (the old permissionless call
70
+ // defaulted to 0644). The remaining exposure is the env injection
71
+ // itself (TEAMCLAW_BOOTSTRAP_CONFIG_B64 is visible to `docker inspect`
72
+ // and pod-env readers); migrating the docker/kubernetes backends to
73
+ // mounted Secrets needs a coordinated chart/image change (cf. #230's
74
+ // image-skew caveat) and is tracked by #237 W4.
75
+ // Review follow-up (#237): { mode } is creation-only, so rewriting a
76
+ // pre-existing 0644 config (baked into an older image or surviving on
77
+ // a mounted volume) would keep the loose mode - chmodSync the existing
78
+ // file first, tolerating ENOENT for first writes (then { mode: 0o600 }
79
+ // creates it owner-only). Chosen over unlink-then-write to avoid the
80
+ // no-config window mid-rewrite.
81
+ "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 });'",
82
+ "exec node dist/index.js gateway --allow-unconfigured",
83
+ ].join("\n");
84
+ }