@teamclaws/teamclaw 2026.8.1 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
@@ -0,0 +1,214 @@
1
+ // W1 of issue #226 (worker-provisioning god-file split): the local process
2
+ // backend, extracted VERBATIM from controller/worker-provisioning.ts
3
+ // (ProcessProvisioner + its child-process supervision, gateway entrypoint
4
+ // resolution, runtime-extension bootstrap and log attachment). The auth
5
+ // profile copy and plugin-root resolution live in provisioning-config.ts /
6
+ // plugin-root.ts. Never imports worker-provisioning.ts.
7
+ import fs from "node:fs/promises";
8
+ import path from "node:path";
9
+ import readline from "node:readline";
10
+ import { spawn, type ChildProcess } from "node:child_process";
11
+ import type { PluginLogger } from "../../../api.js";
12
+ import {
13
+ resolveDefaultOpenClawConfigPath,
14
+ resolveDefaultTeamClawRuntimeRootDir,
15
+ } from "../../openclaw-workspace.js";
16
+ import type { ProvisionedWorkerRecord } from "../../types.js";
17
+ import { pathExists, sanitizePathSegment } from "../../shared/utils.js";
18
+ import { copyControllerAuthProfiles } from "../provisioning-config.js";
19
+ import {
20
+ resolveBakedTeamClawPluginRootDir,
21
+ resolveCurrentTeamClawPluginRootDir,
22
+ } from "./plugin-root.js";
23
+ import type { LaunchResult, LaunchSpec, WorkerProvisionerBackend } from "./backend-contract.js";
24
+
25
+ const PROCESS_TERMINATION_TIMEOUT_MS = 10_000;
26
+
27
+ export class ProcessProvisioner implements WorkerProvisionerBackend {
28
+ readonly type = "process" as const;
29
+ private readonly logger: PluginLogger;
30
+ private readonly processByWorkerId = new Map<string, ChildProcess>();
31
+ private readonly baseDirPromise: Promise<string>;
32
+
33
+ constructor(logger: PluginLogger) {
34
+ this.logger = logger;
35
+ const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
36
+ this.baseDirPromise = fs.mkdir(provisionedRoot, { recursive: true })
37
+ .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
38
+ }
39
+
40
+ async launch(spec: LaunchSpec): Promise<LaunchResult> {
41
+ const baseDir = await this.baseDirPromise;
42
+ const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
43
+ const stateDir = path.join(runtimeHomeDir, ".openclaw");
44
+ const configPath = path.join(stateDir, "openclaw.json");
45
+ await fs.mkdir(stateDir, { recursive: true });
46
+ await prepareProcessRuntimeExtensions(stateDir);
47
+ // Issue #237 W4: the bootstrap config carries provider API keys, so it
48
+ // must land owner-only - the default 0644 let any local user read the
49
+ // worker's credentials. { mode } applies at creation; on Windows (no
50
+ // POSIX perms) the option is a no-op and behavior is unchanged.
51
+ // Container backends have the same exposure via the
52
+ // TEAMCLAW_BOOTSTRAP_CONFIG_B64 env (docker inspect / pod env); see the
53
+ // migration note on buildContainerBootstrapScript().
54
+ // Review follow-up (#237): { mode } is creation-only, so an upgrade
55
+ // deployment rewriting a pre-existing 0644 file would keep the loose
56
+ // mode. Explicit chmod of the existing file first (ENOENT tolerated -
57
+ // first write then creates it 0600 via { mode }). Chosen over
58
+ // unlink-then-write to avoid the no-config window mid-rewrite.
59
+ await fs.chmod(configPath, 0o600).catch((err: NodeJS.ErrnoException) => {
60
+ if (err.code !== "ENOENT") throw err;
61
+ });
62
+ await fs.writeFile(configPath, spec.configJson, { encoding: "utf8", mode: 0o600 });
63
+
64
+ const gatewayEntrypoint = resolveGatewayEntrypoint();
65
+ const child = spawn(process.execPath, [
66
+ gatewayEntrypoint,
67
+ "gateway",
68
+ "--allow-unconfigured",
69
+ "--bind",
70
+ "loopback",
71
+ "--port",
72
+ String(spec.gatewayPort),
73
+ ], {
74
+ cwd: path.dirname(gatewayEntrypoint),
75
+ env: {
76
+ ...process.env,
77
+ ...spec.env,
78
+ HOME: runtimeHomeDir,
79
+ OPENCLAW_HOME: runtimeHomeDir,
80
+ OPENCLAW_STATE_DIR: stateDir,
81
+ OPENCLAW_CONFIG_PATH: configPath,
82
+ OPENCLAW_SKIP_CANVAS_HOST: "1",
83
+ TEAMCLAW_WORKER_ID: spec.workerId,
84
+ TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
85
+ ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
86
+ },
87
+ stdio: ["ignore", "pipe", "pipe"],
88
+ });
89
+
90
+ this.processByWorkerId.set(spec.workerId, child);
91
+ attachChildLogs(child, this.logger, `ProvisionedWorker[${spec.role}]`);
92
+ child.on("exit", (code: number | null, signal: string | null) => {
93
+ this.processByWorkerId.delete(spec.workerId);
94
+ this.logger.info(
95
+ `Provisioner: process worker ${spec.workerId} exited (code=${String(code)}, signal=${String(signal)})`,
96
+ );
97
+ });
98
+
99
+ return {
100
+ instanceId: child.pid ? `pid:${child.pid}` : undefined,
101
+ instanceName: spec.workerId,
102
+ runtimeHomeDir,
103
+ };
104
+ }
105
+
106
+ async terminate(record: ProvisionedWorkerRecord): Promise<void> {
107
+ const child = this.processByWorkerId.get(record.workerId);
108
+ if (child) {
109
+ await stopChildProcess(child);
110
+ this.processByWorkerId.delete(record.workerId);
111
+ } else if (record.instanceId?.startsWith("pid:")) {
112
+ const pid = Number(record.instanceId.slice("pid:".length));
113
+ if (Number.isFinite(pid) && pid > 0) {
114
+ try {
115
+ process.kill(pid, "SIGTERM");
116
+ } catch {
117
+ // ignore
118
+ }
119
+ }
120
+ }
121
+
122
+ if (record.runtimeHomeDir) {
123
+ await fs.rm(record.runtimeHomeDir, { recursive: true, force: true }).catch(() => {
124
+ // ignore
125
+ });
126
+ }
127
+ }
128
+
129
+ async stop(): Promise<void> {
130
+ for (const child of this.processByWorkerId.values()) {
131
+ await stopChildProcess(child).catch(() => {
132
+ // ignore
133
+ });
134
+ }
135
+ this.processByWorkerId.clear();
136
+ }
137
+ }
138
+
139
+ async function prepareProcessRuntimeExtensions(stateDir: string): Promise<void> {
140
+ const runtimeExtensionsDir = path.join(stateDir, "extensions");
141
+ const controllerExtensionsDir = path.join(path.dirname(resolveDefaultOpenClawConfigPath()), "extensions");
142
+ if (await pathExists(controllerExtensionsDir)) {
143
+ await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
144
+ } else {
145
+ await fs.mkdir(runtimeExtensionsDir, { recursive: true });
146
+ // Baked-in images set TEAMCLAW_BAKED_IN=true and the legacy helper
147
+ // returned "" for that case, so the symlink target was empty and
148
+ // process workers fell back to resolving the plugin from their cwd
149
+ // ("/app/dist/openclaw.plugin.json" not found → exit loop, k3s e2e
150
+ // 2026-11-03). Probe the baked image layout instead: the controller
151
+ // entrypoint (process.argv[1], e.g. /app/dist/index.js) sits below
152
+ // the app root, where the runtime image ships
153
+ // /app/extensions/teamclaw with its openclaw.plugin.json.
154
+ const pluginRootDir = process.env.TEAMCLAW_BAKED_IN === "true"
155
+ ? await resolveBakedTeamClawPluginRootDir()
156
+ : resolveCurrentTeamClawPluginRootDir();
157
+ if (pluginRootDir) {
158
+ await fs.symlink(pluginRootDir, path.join(runtimeExtensionsDir, "teamclaw"), "dir");
159
+ }
160
+ }
161
+
162
+ await copyControllerAuthProfiles(stateDir);
163
+ }
164
+
165
+ function resolveGatewayEntrypoint(): string {
166
+ const scriptPath = process.argv[1];
167
+ if (!scriptPath) {
168
+ throw new Error("Unable to resolve OpenClaw gateway entrypoint");
169
+ }
170
+ return path.resolve(scriptPath);
171
+ }
172
+
173
+ function attachChildLogs(child: ChildProcess, logger: PluginLogger, prefix: string): void {
174
+ if (child.stdout) {
175
+ const stdoutReader = readline.createInterface({ input: child.stdout });
176
+ stdoutReader.on("line", (line: string) => {
177
+ logger.info(`${prefix}: ${line}`);
178
+ });
179
+ }
180
+ if (child.stderr) {
181
+ const stderrReader = readline.createInterface({ input: child.stderr });
182
+ stderrReader.on("line", (line: string) => {
183
+ logger.warn(`${prefix}: ${line}`);
184
+ });
185
+ }
186
+ }
187
+
188
+ async function stopChildProcess(child: ChildProcess): Promise<void> {
189
+ if (child.exitCode !== null || child.signalCode !== null) {
190
+ return;
191
+ }
192
+
193
+ await new Promise<void>((resolve) => {
194
+ const timeout = setTimeout(() => {
195
+ if (child.exitCode === null && child.signalCode === null && child.pid) {
196
+ try {
197
+ process.kill(child.pid, "SIGKILL");
198
+ } catch {
199
+ // ignore
200
+ }
201
+ }
202
+ resolve();
203
+ }, PROCESS_TERMINATION_TIMEOUT_MS);
204
+ const timer = timeout as unknown as { unref?: () => void };
205
+ timer.unref?.();
206
+
207
+ child.once("exit", () => {
208
+ clearTimeout(timeout);
209
+ resolve();
210
+ });
211
+
212
+ child.kill("SIGTERM");
213
+ });
214
+ }
@@ -0,0 +1,289 @@
1
+ // W1 of issue #226 (worker-provisioning god-file split): worker config
2
+ // synthesis, controller auth-profile copy and the no-proxy env builder,
3
+ // extracted VERBATIM from controller/worker-provisioning.ts (zero behavior
4
+ // change; only the functions consumed by the facade / process backend gained
5
+ // an `export`). This module never imports worker-provisioning.ts or the
6
+ // provisioning backends - dependency direction is one-way into it.
7
+ import fs from "node:fs/promises";
8
+ import path from "node:path";
9
+ import JSON5 from "json5";
10
+ import type { PluginConfig, RoleId, WorkerProvisioningType } from "../types.js";
11
+ import {
12
+ resolveDefaultOpenClawConfigPath,
13
+ resolveDefaultOpenClawStateDir,
14
+ resolveDefaultAgentDir,
15
+ resolveTeamClawAgentDir,
16
+ resolveTeamClawAgentWorkspaceRootDir,
17
+ TEAMCLAW_AGENT_ID,
18
+ } from "../openclaw-workspace.js";
19
+ import { cloneJson, pathExists, sanitizePathSegment } from "../shared/utils.js";
20
+
21
+ export function buildProvisionedWorkerConfig(
22
+ baseConfig: Record<string, unknown>,
23
+ controllerConfig: PluginConfig,
24
+ spec: {
25
+ role: RoleId;
26
+ controllerUrl: string;
27
+ workerPort: number;
28
+ gatewayPort: number;
29
+ workspaceDir?: string;
30
+ },
31
+ ): Record<string, unknown> {
32
+ const config = cloneJson(baseConfig);
33
+ delete config.channels;
34
+ const agents = ensureRecord(config.agents);
35
+ const agentDefaults = ensureRecord(agents.defaults);
36
+ delete agentDefaults.repoRoot;
37
+ if (spec.workspaceDir) {
38
+ agentDefaults.workspace = spec.workspaceDir;
39
+ } else {
40
+ delete agentDefaults.workspace;
41
+ }
42
+ // The host controller may run a newer openclaw that persists the keyed
43
+ // agents.entries schema (e.g. agents.entries.teamclaw.model written by the
44
+ // model-configuration feature). Provisioned workers can run an older
45
+ // openclaw that rejects unknown agents keys ("Unrecognized key: entries"),
46
+ // so fold the teamclaw entry's model back into the legacy
47
+ // agents.defaults.model and drop the entries map. New-schema workers also
48
+ // accept agents.defaults, keeping the folded config compatible both ways.
49
+ const agentsRecord = agents as {
50
+ entries?: Record<string, { model?: string }>;
51
+ };
52
+ if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
53
+ const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
54
+ if (entryModel && !agentDefaults.model) {
55
+ agentDefaults.model = entryModel;
56
+ }
57
+ // Container backends may run older openclaw runtimes that reject the
58
+ // keyed agents schema ("Unrecognized key: entries") - fold down to
59
+ // legacy defaults there. Process workers share the controller's own
60
+ // runtime, which REQUIRES at least one entry ("agents.entries must
61
+ // contain at least one configured agent" crash-loop, exit 78, observed
62
+ // 2026-11-03 when entries was deleted unconditionally) - keep only the
63
+ // teamclaw worker entry for them.
64
+ const containerized =
65
+ controllerConfig.workerProvisioningType === "docker" ||
66
+ controllerConfig.workerProvisioningType === "kubernetes";
67
+ if (containerized) {
68
+ delete agentsRecord.entries;
69
+ } else {
70
+ agentsRecord.entries = {
71
+ [TEAMCLAW_AGENT_ID]: agentsRecord.entries[TEAMCLAW_AGENT_ID] ?? {},
72
+ };
73
+ // Pruning entries can dangle defaults.heartbeat.agentId /
74
+ // defaults.systemAgent.agentId ("main" no longer exists in the worker
75
+ // config) - remap any dangling agentId reference to the surviving
76
+ // teamclaw entry.
77
+ for (const sectionKey of Object.keys(agentDefaults)) {
78
+ const section = (agentDefaults as Record<string, unknown>)[sectionKey];
79
+ if (
80
+ section &&
81
+ typeof section === "object" &&
82
+ typeof (section as { agentId?: unknown }).agentId === "string" &&
83
+ !agentsRecord.entries[(section as { agentId: string }).agentId]
84
+ ) {
85
+ (section as { agentId: string }).agentId = TEAMCLAW_AGENT_ID;
86
+ }
87
+ }
88
+ }
89
+ }
90
+ agents.defaults = agentDefaults;
91
+ config.agents = agents;
92
+
93
+ const gateway = ensureRecord(config.gateway);
94
+ gateway.mode = "local";
95
+ // Workers running inside Docker/K8s containers must bind on all
96
+ // interfaces so the controller (in a sibling container) can reach them.
97
+ gateway.bind =
98
+ controllerConfig.workerProvisioningType === "docker" ||
99
+ controllerConfig.workerProvisioningType === "kubernetes"
100
+ ? "lan"
101
+ : "loopback";
102
+ gateway.port = spec.gatewayPort;
103
+ delete gateway.remote;
104
+ config.gateway = gateway;
105
+
106
+ const plugins = ensureRecord(config.plugins);
107
+ plugins.enabled = true;
108
+ if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
109
+ delete plugins.load;
110
+ }
111
+ const entries = ensureRecord(plugins.entries);
112
+ const teamclawEntry = ensureRecord(entries.teamclaw);
113
+ teamclawEntry.enabled = true;
114
+ const teamclawConfig = ensureRecord(teamclawEntry.config);
115
+ teamclawConfig.mode = "worker";
116
+ teamclawConfig.processModel = "multi";
117
+ teamclawConfig.role = spec.role;
118
+ teamclawConfig.port = spec.workerPort;
119
+ teamclawConfig.controllerUrl = spec.controllerUrl;
120
+ teamclawConfig.teamName = controllerConfig.teamName;
121
+ teamclawConfig.heartbeatIntervalMs = controllerConfig.heartbeatIntervalMs;
122
+ teamclawConfig.taskTimeoutMs = controllerConfig.taskTimeoutMs;
123
+ teamclawConfig.gitEnabled = controllerConfig.gitEnabled;
124
+ teamclawConfig.gitRemoteUrl = controllerConfig.gitRemoteUrl;
125
+ teamclawConfig.gitDefaultBranch = controllerConfig.gitDefaultBranch;
126
+ teamclawConfig.gitAuthorName = controllerConfig.gitAuthorName;
127
+ teamclawConfig.gitAuthorEmail = controllerConfig.gitAuthorEmail;
128
+ teamclawConfig.workerProvisioningType = "none";
129
+ teamclawConfig.workerProvisioningControllerUrl = "";
130
+ teamclawConfig.workerProvisioningRoles = [];
131
+ teamclawConfig.workerProvisioningMinPerRole = 0;
132
+ teamclawConfig.workerProvisioningMaxPerRole = 10;
133
+ teamclawConfig.workerProvisioningIdleTtlMs = controllerConfig.workerProvisioningIdleTtlMs;
134
+ teamclawConfig.workerProvisioningStartupTimeoutMs = controllerConfig.workerProvisioningStartupTimeoutMs;
135
+ teamclawConfig.workerProvisioningImage = "";
136
+ teamclawConfig.workerProvisioningPassEnv = [];
137
+ teamclawConfig.workerProvisioningExtraEnv = {};
138
+ teamclawConfig.workerProvisioningDockerNetwork = "";
139
+ teamclawConfig.workerProvisioningDockerMounts = [];
140
+ teamclawConfig.workerProvisioningWorkspaceRoot = "";
141
+ teamclawConfig.workerProvisioningDockerWorkspaceVolume = "";
142
+ teamclawConfig.workerProvisioningKubernetesNamespace = "default";
143
+ teamclawConfig.workerProvisioningKubernetesContext = "";
144
+ teamclawConfig.workerProvisioningKubernetesServiceAccount = "";
145
+ teamclawConfig.workerProvisioningKubernetesImagePullSecrets = [];
146
+ teamclawConfig.workerProvisioningKubernetesWorkspacePersistentVolumeClaim = "";
147
+ teamclawConfig.workerProvisioningKubernetesLabels = {};
148
+ teamclawConfig.workerProvisioningKubernetesAnnotations = {};
149
+ teamclawEntry.config = teamclawConfig;
150
+ entries.teamclaw = teamclawEntry;
151
+ plugins.entries = entries;
152
+ config.plugins = plugins;
153
+
154
+ return config;
155
+ }
156
+
157
+ export async function loadOpenClawConfig(configPath: string): Promise<Record<string, unknown>> {
158
+ const raw = await fs.readFile(configPath, "utf8");
159
+ return parseLooseJsonObject(raw, configPath);
160
+ }
161
+
162
+ export async function copyControllerAuthProfiles(stateDir: string): Promise<void> {
163
+ const candidateControllerStateDirs = [
164
+ path.dirname(resolveDefaultOpenClawConfigPath()),
165
+ resolveDefaultOpenClawStateDir(),
166
+ ];
167
+ const candidateAuthProfilePaths = [
168
+ path.join(resolveTeamClawAgentDir(), "auth-profiles.json"),
169
+ path.join(resolveDefaultAgentDir(), "auth-profiles.json"),
170
+ ...candidateControllerStateDirs.flatMap((controllerStateDir) => [
171
+ path.join(controllerStateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
172
+ path.join(controllerStateDir, "agents", "main", "agent", "auth-profiles.json"),
173
+ ]),
174
+ ].filter((value, index, values) => values.indexOf(value) === index);
175
+ let controllerAuthProfilesPath: string | undefined;
176
+ for (const candidatePath of candidateAuthProfilePaths) {
177
+ if (await pathExists(candidatePath)) {
178
+ controllerAuthProfilesPath = candidatePath;
179
+ break;
180
+ }
181
+ }
182
+ if (!controllerAuthProfilesPath) {
183
+ return;
184
+ }
185
+ const runtimeAuthProfilePaths = [
186
+ path.join(stateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
187
+ path.join(stateDir, "agents", "main", "agent", "auth-profiles.json"),
188
+ ];
189
+ for (const runtimeAuthProfilesPath of runtimeAuthProfilePaths) {
190
+ await fs.mkdir(path.dirname(runtimeAuthProfilesPath), { recursive: true });
191
+ await fs.copyFile(controllerAuthProfilesPath, runtimeAuthProfilesPath);
192
+ }
193
+ }
194
+
195
+ export function appendNoProxyEntries(env: Record<string, string>, controllerUrl: string): Record<string, string> {
196
+ const requiredEntries = resolveRequiredNoProxyEntries(controllerUrl);
197
+ if (requiredEntries.length === 0) {
198
+ return env;
199
+ }
200
+
201
+ const upperBase = env.NO_PROXY ?? process.env.NO_PROXY ?? process.env.no_proxy ?? "";
202
+ const lowerBase = env.no_proxy ?? process.env.no_proxy ?? env.NO_PROXY ?? process.env.NO_PROXY ?? "";
203
+
204
+ env.NO_PROXY = mergeNoProxyEntries(upperBase, requiredEntries);
205
+ env.no_proxy = mergeNoProxyEntries(lowerBase, requiredEntries);
206
+ return env;
207
+ }
208
+
209
+ function resolveRequiredNoProxyEntries(controllerUrl: string): string[] {
210
+ const required = new Set<string>(["localhost", "127.0.0.1", "::1", "[::1]"]);
211
+ try {
212
+ const host = new URL(controllerUrl).hostname.trim();
213
+ if (host) {
214
+ required.add(host);
215
+ }
216
+ } catch {
217
+ // Ignore malformed controller URLs; worker registration will fail separately.
218
+ }
219
+ return Array.from(required);
220
+ }
221
+
222
+ function mergeNoProxyEntries(existing: string, requiredEntries: string[]): string {
223
+ const tokens = new Map<string, string>();
224
+ for (const entry of existing.split(",")) {
225
+ const trimmed = entry.trim();
226
+ if (!trimmed) {
227
+ continue;
228
+ }
229
+ tokens.set(trimmed.toLowerCase(), trimmed);
230
+ }
231
+ for (const entry of requiredEntries) {
232
+ const trimmed = entry.trim();
233
+ if (!trimmed) {
234
+ continue;
235
+ }
236
+ tokens.set(trimmed.toLowerCase(), trimmed);
237
+ }
238
+ return Array.from(tokens.values()).join(",");
239
+ }
240
+
241
+ function ensureRecord(value: unknown): Record<string, unknown> {
242
+ return value && typeof value === "object" && !Array.isArray(value)
243
+ ? { ...(value as Record<string, unknown>) }
244
+ : {};
245
+ }
246
+
247
+ function parseLooseJsonObject(raw: string, configPath: string): Record<string, unknown> {
248
+ try {
249
+ return JSON5.parse(raw) as Record<string, unknown>;
250
+ } catch (err) {
251
+ throw new Error(
252
+ `Failed to parse OpenClaw config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`,
253
+ );
254
+ }
255
+ }
256
+
257
+ export function buildProvisionedWorkspaceDir(
258
+ provider: WorkerProvisioningType,
259
+ config: PluginConfig,
260
+ role: RoleId,
261
+ workerId: string,
262
+ ): string {
263
+ // Process-type workers run on the same host — share the controller's workspace
264
+ // so that file artifacts (previews, deliverables) are immediately visible to
265
+ // the controller without requiring git sync or file transfer.
266
+ if (provider === "process") {
267
+ return resolveTeamClawAgentWorkspaceRootDir();
268
+ }
269
+
270
+ if (
271
+ (provider !== "docker" && provider !== "kubernetes") ||
272
+ !config.workerProvisioningWorkspaceRoot
273
+ ) {
274
+ return "";
275
+ }
276
+
277
+ return path.posix.join(
278
+ config.workerProvisioningWorkspaceRoot,
279
+ sanitizePathSegment(config.teamName),
280
+ sanitizePathSegment(role),
281
+ sanitizePathSegment(workerId),
282
+ );
283
+ }
284
+
285
+ export function getConfiguredWorkerWorkspaceDir(config: Record<string, unknown>): string {
286
+ const agents = ensureRecord(config.agents);
287
+ const defaults = ensureRecord(agents.defaults);
288
+ return typeof defaults.workspace === "string" ? defaults.workspace : "";
289
+ }
@@ -0,0 +1,163 @@
1
+ // PR-B of issue #204 (http-server monolith split): the git collaboration
2
+ // routes (GET /api/v1/repo status, GET /api/v1/repo/bundle export, POST
3
+ // /api/v1/repo/import) and the repo state refresh glue extracted verbatim
4
+ // from controller/http-server.ts. Zero behavior change. This module must
5
+ // NEVER import http-server (the reverse edge exists: http-server ->
6
+ // repo-routes). The import handler's stay in route-table.ts ended with W2
7
+ // of issue #226 (its recordTaskExecutionEvent dependency is task-lifecycle
8
+ // glue owned by the PR-C cut - task-execution.js does not import this
9
+ // module, so hosting it here is acyclic); it keeps its RouteContext shape
10
+ // and moved byte-identical.
11
+ import type { ServerResponse } from "node:http";
12
+ import type { PluginLogger } from "../../api.js";
13
+ import type { GitRepoState, PluginConfig, TeamState } from "../types.js";
14
+ import { sendJson, sendError, pinnedCorsAllowOrigin, readRequestBody } from "../protocol.js";
15
+ import { getActiveProfile, validateActiveRoleId } from "../profile-loader.js";
16
+ import { ensureControllerGitRepo, exportControllerGitBundle, importControllerGitBundle } from "../git-collaboration.js";
17
+ import { recordTaskExecutionEvent } from "./task-execution.js";
18
+ import type { RouteContext } from "./route-table.js";
19
+
20
+ /**
21
+ * Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
22
+ * the fields the repo route handlers and the refresh glue read. http-server
23
+ * keeps passing its full ControllerHttpDeps object; TypeScript structural
24
+ * typing accepts it, so no call site changes beyond the import path.
25
+ */
26
+ export type RepoRouteDeps = {
27
+ config: PluginConfig;
28
+ logger: PluginLogger;
29
+ getTeamState: () => TeamState | null;
30
+ updateTeamState: (updater: (state: TeamState) => void) => TeamState;
31
+ };
32
+
33
+ export async function refreshControllerRepoState(deps: RepoRouteDeps): Promise<GitRepoState | null> {
34
+ // Phase 2.3: the ACTIVE PROFILE's git switch outranks the legacy config
35
+ // knob here - refreshing (or stamping) repo state for a profile that
36
+ // declared git off would re-introduce exactly the repo field the switch
37
+ // omitted for it (design 2.3: banking keeps no repo initialization). All
38
+ // callers already treat null as "no repo" (same as config gitEnabled off).
39
+ if (!deps.config.gitEnabled || !getActiveProfile().capabilities.git) {
40
+ return null;
41
+ }
42
+
43
+ try {
44
+ const repo = await ensureControllerGitRepo(deps.config, deps.logger);
45
+ if (repo) {
46
+ deps.updateTeamState((s) => {
47
+ s.repo = repo;
48
+ });
49
+ }
50
+ return repo;
51
+ } catch (err) {
52
+ const message = err instanceof Error ? err.message : String(err);
53
+ deps.logger.warn(`Controller: failed to refresh git repo state: ${message}`);
54
+ deps.updateTeamState((s) => {
55
+ if (s.repo?.enabled) {
56
+ s.repo = {
57
+ ...s.repo,
58
+ error: message,
59
+ lastPreparedAt: Date.now(),
60
+ };
61
+ }
62
+ });
63
+ return deps.getTeamState()?.repo ?? null;
64
+ }
65
+ }
66
+
67
+ // GET /api/v1/repo
68
+ export async function handleRepoStatusRequest(deps: RepoRouteDeps, res: ServerResponse): Promise<void> {
69
+ const repo = await refreshControllerRepoState(deps);
70
+ if (!repo?.enabled) {
71
+ sendJson(res, 200, { enabled: false });
72
+ return;
73
+ }
74
+
75
+ sendJson(res, 200, { repo });
76
+ }
77
+
78
+ // GET /api/v1/repo/bundle
79
+ export async function handleRepoBundleRequest(deps: RepoRouteDeps, res: ServerResponse): Promise<void> {
80
+ try {
81
+ const exported = await exportControllerGitBundle(deps.config, deps.logger);
82
+ res.writeHead(200, {
83
+ "Content-Type": "application/octet-stream",
84
+ "Content-Length": exported.data.byteLength,
85
+ "Content-Disposition": `attachment; filename="${exported.filename}"`,
86
+ // Issue #23 security review follow-up: this response used to hardcode
87
+ // the L0 wildcard, which silently WIDENED a CORS origin the security
88
+ // gate had pinned while device protection is on. Honor the pinned
89
+ // header via the shared protocol helper; unpinned (protection off /
90
+ // non-browser) keeps the historical "*" byte for byte.
91
+ "Access-Control-Allow-Origin": pinnedCorsAllowOrigin(res),
92
+ "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
93
+ "Access-Control-Allow-Headers": "Content-Type",
94
+ });
95
+ res.end(exported.data);
96
+ } catch (err) {
97
+ sendError(res, 503, err instanceof Error ? err.message : String(err));
98
+ }
99
+ }
100
+
101
+ // POST /api/v1/repo/import - issue #226 W2: moved verbatim from route-table.ts
102
+ // (which had moved it verbatim from http-server.ts with PR-D). Keeps the
103
+ // RouteContext shape; route-table's table entry binds it directly.
104
+ export async function repoImportRoute(ctx: RouteContext): Promise<void> {
105
+ const { req, res, requestUrl, deps } = ctx;
106
+ const { config, logger, updateTeamState } = deps;
107
+ const body = await readRequestBody(req);
108
+ if (!body.length) {
109
+ sendError(res, 400, "bundle body is required");
110
+ return;
111
+ }
112
+
113
+ const taskId = typeof requestUrl.searchParams.get("taskId") === "string" && requestUrl.searchParams.get("taskId")
114
+ ? requestUrl.searchParams.get("taskId")!
115
+ : undefined;
116
+ const workerId = typeof requestUrl.searchParams.get("workerId") === "string" && requestUrl.searchParams.get("workerId")
117
+ ? requestUrl.searchParams.get("workerId")!
118
+ : undefined;
119
+ const role = validateActiveRoleId(requestUrl.searchParams.get("role"));
120
+
121
+ try {
122
+ const imported = await importControllerGitBundle(config, logger, body, { taskId, workerId });
123
+ updateTeamState((s) => {
124
+ s.repo = imported.repo;
125
+ });
126
+
127
+ if (taskId) {
128
+ recordTaskExecutionEvent(taskId, {
129
+ type: imported.merged || imported.alreadyUpToDate ? "lifecycle" : "error",
130
+ phase: imported.merged
131
+ ? "repo_imported"
132
+ : imported.alreadyUpToDate
133
+ ? "repo_import_skipped"
134
+ : "repo_import_failed",
135
+ source: "controller",
136
+ message: imported.message,
137
+ workerId,
138
+ role,
139
+ }, deps);
140
+ }
141
+
142
+ sendJson(res, imported.merged || imported.alreadyUpToDate ? 200 : 409, {
143
+ repo: imported.repo,
144
+ merged: imported.merged,
145
+ fastForwarded: imported.fastForwarded,
146
+ alreadyUpToDate: imported.alreadyUpToDate,
147
+ message: imported.message,
148
+ });
149
+ } catch (err) {
150
+ const message = err instanceof Error ? err.message : String(err);
151
+ if (taskId) {
152
+ recordTaskExecutionEvent(taskId, {
153
+ type: "error",
154
+ phase: "repo_import_failed",
155
+ source: "controller",
156
+ message,
157
+ workerId,
158
+ role,
159
+ }, deps);
160
+ }
161
+ sendError(res, 500, message);
162
+ }
163
+ }