@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,190 @@
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 } from "node:child_process";
11
+ import { resolveDefaultOpenClawConfigPath, resolveDefaultTeamClawRuntimeRootDir, } from "../../openclaw-workspace.js";
12
+ import { pathExists, sanitizePathSegment } from "../../shared/utils.js";
13
+ import { copyControllerAuthProfiles } from "../provisioning-config.js";
14
+ import { resolveBakedTeamClawPluginRootDir, resolveCurrentTeamClawPluginRootDir, } from "./plugin-root.js";
15
+ const PROCESS_TERMINATION_TIMEOUT_MS = 10_000;
16
+ export class ProcessProvisioner {
17
+ type = "process";
18
+ logger;
19
+ processByWorkerId = new Map();
20
+ baseDirPromise;
21
+ constructor(logger) {
22
+ this.logger = logger;
23
+ const provisionedRoot = path.join(resolveDefaultTeamClawRuntimeRootDir(), "provisioned-workers");
24
+ this.baseDirPromise = fs.mkdir(provisionedRoot, { recursive: true })
25
+ .then(() => fs.mkdtemp(path.join(provisionedRoot, "session-")));
26
+ }
27
+ async launch(spec) {
28
+ const baseDir = await this.baseDirPromise;
29
+ const runtimeHomeDir = await fs.mkdtemp(path.join(baseDir, `${sanitizePathSegment(spec.role)}-`));
30
+ const stateDir = path.join(runtimeHomeDir, ".openclaw");
31
+ const configPath = path.join(stateDir, "openclaw.json");
32
+ await fs.mkdir(stateDir, { recursive: true });
33
+ await prepareProcessRuntimeExtensions(stateDir);
34
+ // Issue #237 W4: the bootstrap config carries provider API keys, so it
35
+ // must land owner-only - the default 0644 let any local user read the
36
+ // worker's credentials. { mode } applies at creation; on Windows (no
37
+ // POSIX perms) the option is a no-op and behavior is unchanged.
38
+ // Container backends have the same exposure via the
39
+ // TEAMCLAW_BOOTSTRAP_CONFIG_B64 env (docker inspect / pod env); see the
40
+ // migration note on buildContainerBootstrapScript().
41
+ // Review follow-up (#237): { mode } is creation-only, so an upgrade
42
+ // deployment rewriting a pre-existing 0644 file would keep the loose
43
+ // mode. Explicit chmod of the existing file first (ENOENT tolerated -
44
+ // first write then creates it 0600 via { mode }). Chosen over
45
+ // unlink-then-write to avoid the no-config window mid-rewrite.
46
+ await fs.chmod(configPath, 0o600).catch((err) => {
47
+ if (err.code !== "ENOENT")
48
+ throw err;
49
+ });
50
+ await fs.writeFile(configPath, spec.configJson, { encoding: "utf8", mode: 0o600 });
51
+ const gatewayEntrypoint = resolveGatewayEntrypoint();
52
+ const child = spawn(process.execPath, [
53
+ gatewayEntrypoint,
54
+ "gateway",
55
+ "--allow-unconfigured",
56
+ "--bind",
57
+ "loopback",
58
+ "--port",
59
+ String(spec.gatewayPort),
60
+ ], {
61
+ cwd: path.dirname(gatewayEntrypoint),
62
+ env: {
63
+ ...process.env,
64
+ ...spec.env,
65
+ HOME: runtimeHomeDir,
66
+ OPENCLAW_HOME: runtimeHomeDir,
67
+ OPENCLAW_STATE_DIR: stateDir,
68
+ OPENCLAW_CONFIG_PATH: configPath,
69
+ OPENCLAW_SKIP_CANVAS_HOST: "1",
70
+ TEAMCLAW_WORKER_ID: spec.workerId,
71
+ TEAMCLAW_LAUNCH_TOKEN: spec.launchToken,
72
+ ...(spec.workspaceDir ? { TEAMCLAW_WORKSPACE_DIR: spec.workspaceDir } : {}),
73
+ },
74
+ stdio: ["ignore", "pipe", "pipe"],
75
+ });
76
+ this.processByWorkerId.set(spec.workerId, child);
77
+ attachChildLogs(child, this.logger, `ProvisionedWorker[${spec.role}]`);
78
+ child.on("exit", (code, signal) => {
79
+ this.processByWorkerId.delete(spec.workerId);
80
+ this.logger.info(`Provisioner: process worker ${spec.workerId} exited (code=${String(code)}, signal=${String(signal)})`);
81
+ });
82
+ return {
83
+ instanceId: child.pid ? `pid:${child.pid}` : undefined,
84
+ instanceName: spec.workerId,
85
+ runtimeHomeDir,
86
+ };
87
+ }
88
+ async terminate(record) {
89
+ const child = this.processByWorkerId.get(record.workerId);
90
+ if (child) {
91
+ await stopChildProcess(child);
92
+ this.processByWorkerId.delete(record.workerId);
93
+ }
94
+ else if (record.instanceId?.startsWith("pid:")) {
95
+ const pid = Number(record.instanceId.slice("pid:".length));
96
+ if (Number.isFinite(pid) && pid > 0) {
97
+ try {
98
+ process.kill(pid, "SIGTERM");
99
+ }
100
+ catch {
101
+ // ignore
102
+ }
103
+ }
104
+ }
105
+ if (record.runtimeHomeDir) {
106
+ await fs.rm(record.runtimeHomeDir, { recursive: true, force: true }).catch(() => {
107
+ // ignore
108
+ });
109
+ }
110
+ }
111
+ async stop() {
112
+ for (const child of this.processByWorkerId.values()) {
113
+ await stopChildProcess(child).catch(() => {
114
+ // ignore
115
+ });
116
+ }
117
+ this.processByWorkerId.clear();
118
+ }
119
+ }
120
+ async function prepareProcessRuntimeExtensions(stateDir) {
121
+ const runtimeExtensionsDir = path.join(stateDir, "extensions");
122
+ const controllerExtensionsDir = path.join(path.dirname(resolveDefaultOpenClawConfigPath()), "extensions");
123
+ if (await pathExists(controllerExtensionsDir)) {
124
+ await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
125
+ }
126
+ else {
127
+ await fs.mkdir(runtimeExtensionsDir, { recursive: true });
128
+ // Baked-in images set TEAMCLAW_BAKED_IN=true and the legacy helper
129
+ // returned "" for that case, so the symlink target was empty and
130
+ // process workers fell back to resolving the plugin from their cwd
131
+ // ("/app/dist/openclaw.plugin.json" not found → exit loop, k3s e2e
132
+ // 2026-11-03). Probe the baked image layout instead: the controller
133
+ // entrypoint (process.argv[1], e.g. /app/dist/index.js) sits below
134
+ // the app root, where the runtime image ships
135
+ // /app/extensions/teamclaw with its openclaw.plugin.json.
136
+ const pluginRootDir = process.env.TEAMCLAW_BAKED_IN === "true"
137
+ ? await resolveBakedTeamClawPluginRootDir()
138
+ : resolveCurrentTeamClawPluginRootDir();
139
+ if (pluginRootDir) {
140
+ await fs.symlink(pluginRootDir, path.join(runtimeExtensionsDir, "teamclaw"), "dir");
141
+ }
142
+ }
143
+ await copyControllerAuthProfiles(stateDir);
144
+ }
145
+ function resolveGatewayEntrypoint() {
146
+ const scriptPath = process.argv[1];
147
+ if (!scriptPath) {
148
+ throw new Error("Unable to resolve OpenClaw gateway entrypoint");
149
+ }
150
+ return path.resolve(scriptPath);
151
+ }
152
+ function attachChildLogs(child, logger, prefix) {
153
+ if (child.stdout) {
154
+ const stdoutReader = readline.createInterface({ input: child.stdout });
155
+ stdoutReader.on("line", (line) => {
156
+ logger.info(`${prefix}: ${line}`);
157
+ });
158
+ }
159
+ if (child.stderr) {
160
+ const stderrReader = readline.createInterface({ input: child.stderr });
161
+ stderrReader.on("line", (line) => {
162
+ logger.warn(`${prefix}: ${line}`);
163
+ });
164
+ }
165
+ }
166
+ async function stopChildProcess(child) {
167
+ if (child.exitCode !== null || child.signalCode !== null) {
168
+ return;
169
+ }
170
+ await new Promise((resolve) => {
171
+ const timeout = setTimeout(() => {
172
+ if (child.exitCode === null && child.signalCode === null && child.pid) {
173
+ try {
174
+ process.kill(child.pid, "SIGKILL");
175
+ }
176
+ catch {
177
+ // ignore
178
+ }
179
+ }
180
+ resolve();
181
+ }, PROCESS_TERMINATION_TIMEOUT_MS);
182
+ const timer = timeout;
183
+ timer.unref?.();
184
+ child.once("exit", () => {
185
+ clearTimeout(timeout);
186
+ resolve();
187
+ });
188
+ child.kill("SIGTERM");
189
+ });
190
+ }
@@ -0,0 +1,239 @@
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 { resolveDefaultOpenClawConfigPath, resolveDefaultOpenClawStateDir, resolveDefaultAgentDir, resolveTeamClawAgentDir, resolveTeamClawAgentWorkspaceRootDir, TEAMCLAW_AGENT_ID, } from "../openclaw-workspace.js";
11
+ import { cloneJson, pathExists, sanitizePathSegment } from "../shared/utils.js";
12
+ export function buildProvisionedWorkerConfig(baseConfig, controllerConfig, spec) {
13
+ const config = cloneJson(baseConfig);
14
+ delete config.channels;
15
+ const agents = ensureRecord(config.agents);
16
+ const agentDefaults = ensureRecord(agents.defaults);
17
+ delete agentDefaults.repoRoot;
18
+ if (spec.workspaceDir) {
19
+ agentDefaults.workspace = spec.workspaceDir;
20
+ }
21
+ else {
22
+ delete agentDefaults.workspace;
23
+ }
24
+ // The host controller may run a newer openclaw that persists the keyed
25
+ // agents.entries schema (e.g. agents.entries.teamclaw.model written by the
26
+ // model-configuration feature). Provisioned workers can run an older
27
+ // openclaw that rejects unknown agents keys ("Unrecognized key: entries"),
28
+ // so fold the teamclaw entry's model back into the legacy
29
+ // agents.defaults.model and drop the entries map. New-schema workers also
30
+ // accept agents.defaults, keeping the folded config compatible both ways.
31
+ const agentsRecord = agents;
32
+ if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
33
+ const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
34
+ if (entryModel && !agentDefaults.model) {
35
+ agentDefaults.model = entryModel;
36
+ }
37
+ // Container backends may run older openclaw runtimes that reject the
38
+ // keyed agents schema ("Unrecognized key: entries") - fold down to
39
+ // legacy defaults there. Process workers share the controller's own
40
+ // runtime, which REQUIRES at least one entry ("agents.entries must
41
+ // contain at least one configured agent" crash-loop, exit 78, observed
42
+ // 2026-11-03 when entries was deleted unconditionally) - keep only the
43
+ // teamclaw worker entry for them.
44
+ const containerized = controllerConfig.workerProvisioningType === "docker" ||
45
+ controllerConfig.workerProvisioningType === "kubernetes";
46
+ if (containerized) {
47
+ delete agentsRecord.entries;
48
+ }
49
+ else {
50
+ agentsRecord.entries = {
51
+ [TEAMCLAW_AGENT_ID]: agentsRecord.entries[TEAMCLAW_AGENT_ID] ?? {},
52
+ };
53
+ // Pruning entries can dangle defaults.heartbeat.agentId /
54
+ // defaults.systemAgent.agentId ("main" no longer exists in the worker
55
+ // config) - remap any dangling agentId reference to the surviving
56
+ // teamclaw entry.
57
+ for (const sectionKey of Object.keys(agentDefaults)) {
58
+ const section = agentDefaults[sectionKey];
59
+ if (section &&
60
+ typeof section === "object" &&
61
+ typeof section.agentId === "string" &&
62
+ !agentsRecord.entries[section.agentId]) {
63
+ section.agentId = TEAMCLAW_AGENT_ID;
64
+ }
65
+ }
66
+ }
67
+ }
68
+ agents.defaults = agentDefaults;
69
+ config.agents = agents;
70
+ const gateway = ensureRecord(config.gateway);
71
+ gateway.mode = "local";
72
+ // Workers running inside Docker/K8s containers must bind on all
73
+ // interfaces so the controller (in a sibling container) can reach them.
74
+ gateway.bind =
75
+ controllerConfig.workerProvisioningType === "docker" ||
76
+ controllerConfig.workerProvisioningType === "kubernetes"
77
+ ? "lan"
78
+ : "loopback";
79
+ gateway.port = spec.gatewayPort;
80
+ delete gateway.remote;
81
+ config.gateway = gateway;
82
+ const plugins = ensureRecord(config.plugins);
83
+ plugins.enabled = true;
84
+ if (controllerConfig.workerProvisioningType === "docker" || controllerConfig.workerProvisioningType === "kubernetes") {
85
+ delete plugins.load;
86
+ }
87
+ const entries = ensureRecord(plugins.entries);
88
+ const teamclawEntry = ensureRecord(entries.teamclaw);
89
+ teamclawEntry.enabled = true;
90
+ const teamclawConfig = ensureRecord(teamclawEntry.config);
91
+ teamclawConfig.mode = "worker";
92
+ teamclawConfig.processModel = "multi";
93
+ teamclawConfig.role = spec.role;
94
+ teamclawConfig.port = spec.workerPort;
95
+ teamclawConfig.controllerUrl = spec.controllerUrl;
96
+ teamclawConfig.teamName = controllerConfig.teamName;
97
+ teamclawConfig.heartbeatIntervalMs = controllerConfig.heartbeatIntervalMs;
98
+ teamclawConfig.taskTimeoutMs = controllerConfig.taskTimeoutMs;
99
+ teamclawConfig.gitEnabled = controllerConfig.gitEnabled;
100
+ teamclawConfig.gitRemoteUrl = controllerConfig.gitRemoteUrl;
101
+ teamclawConfig.gitDefaultBranch = controllerConfig.gitDefaultBranch;
102
+ teamclawConfig.gitAuthorName = controllerConfig.gitAuthorName;
103
+ teamclawConfig.gitAuthorEmail = controllerConfig.gitAuthorEmail;
104
+ teamclawConfig.workerProvisioningType = "none";
105
+ teamclawConfig.workerProvisioningControllerUrl = "";
106
+ teamclawConfig.workerProvisioningRoles = [];
107
+ teamclawConfig.workerProvisioningMinPerRole = 0;
108
+ teamclawConfig.workerProvisioningMaxPerRole = 10;
109
+ teamclawConfig.workerProvisioningIdleTtlMs = controllerConfig.workerProvisioningIdleTtlMs;
110
+ teamclawConfig.workerProvisioningStartupTimeoutMs = controllerConfig.workerProvisioningStartupTimeoutMs;
111
+ teamclawConfig.workerProvisioningImage = "";
112
+ teamclawConfig.workerProvisioningPassEnv = [];
113
+ teamclawConfig.workerProvisioningExtraEnv = {};
114
+ teamclawConfig.workerProvisioningDockerNetwork = "";
115
+ teamclawConfig.workerProvisioningDockerMounts = [];
116
+ teamclawConfig.workerProvisioningWorkspaceRoot = "";
117
+ teamclawConfig.workerProvisioningDockerWorkspaceVolume = "";
118
+ teamclawConfig.workerProvisioningKubernetesNamespace = "default";
119
+ teamclawConfig.workerProvisioningKubernetesContext = "";
120
+ teamclawConfig.workerProvisioningKubernetesServiceAccount = "";
121
+ teamclawConfig.workerProvisioningKubernetesImagePullSecrets = [];
122
+ teamclawConfig.workerProvisioningKubernetesWorkspacePersistentVolumeClaim = "";
123
+ teamclawConfig.workerProvisioningKubernetesLabels = {};
124
+ teamclawConfig.workerProvisioningKubernetesAnnotations = {};
125
+ teamclawEntry.config = teamclawConfig;
126
+ entries.teamclaw = teamclawEntry;
127
+ plugins.entries = entries;
128
+ config.plugins = plugins;
129
+ return config;
130
+ }
131
+ export async function loadOpenClawConfig(configPath) {
132
+ const raw = await fs.readFile(configPath, "utf8");
133
+ return parseLooseJsonObject(raw, configPath);
134
+ }
135
+ export async function copyControllerAuthProfiles(stateDir) {
136
+ const candidateControllerStateDirs = [
137
+ path.dirname(resolveDefaultOpenClawConfigPath()),
138
+ resolveDefaultOpenClawStateDir(),
139
+ ];
140
+ const candidateAuthProfilePaths = [
141
+ path.join(resolveTeamClawAgentDir(), "auth-profiles.json"),
142
+ path.join(resolveDefaultAgentDir(), "auth-profiles.json"),
143
+ ...candidateControllerStateDirs.flatMap((controllerStateDir) => [
144
+ path.join(controllerStateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
145
+ path.join(controllerStateDir, "agents", "main", "agent", "auth-profiles.json"),
146
+ ]),
147
+ ].filter((value, index, values) => values.indexOf(value) === index);
148
+ let controllerAuthProfilesPath;
149
+ for (const candidatePath of candidateAuthProfilePaths) {
150
+ if (await pathExists(candidatePath)) {
151
+ controllerAuthProfilesPath = candidatePath;
152
+ break;
153
+ }
154
+ }
155
+ if (!controllerAuthProfilesPath) {
156
+ return;
157
+ }
158
+ const runtimeAuthProfilePaths = [
159
+ path.join(stateDir, "agents", TEAMCLAW_AGENT_ID, "agent", "auth-profiles.json"),
160
+ path.join(stateDir, "agents", "main", "agent", "auth-profiles.json"),
161
+ ];
162
+ for (const runtimeAuthProfilesPath of runtimeAuthProfilePaths) {
163
+ await fs.mkdir(path.dirname(runtimeAuthProfilesPath), { recursive: true });
164
+ await fs.copyFile(controllerAuthProfilesPath, runtimeAuthProfilesPath);
165
+ }
166
+ }
167
+ export function appendNoProxyEntries(env, controllerUrl) {
168
+ const requiredEntries = resolveRequiredNoProxyEntries(controllerUrl);
169
+ if (requiredEntries.length === 0) {
170
+ return env;
171
+ }
172
+ const upperBase = env.NO_PROXY ?? process.env.NO_PROXY ?? process.env.no_proxy ?? "";
173
+ const lowerBase = env.no_proxy ?? process.env.no_proxy ?? env.NO_PROXY ?? process.env.NO_PROXY ?? "";
174
+ env.NO_PROXY = mergeNoProxyEntries(upperBase, requiredEntries);
175
+ env.no_proxy = mergeNoProxyEntries(lowerBase, requiredEntries);
176
+ return env;
177
+ }
178
+ function resolveRequiredNoProxyEntries(controllerUrl) {
179
+ const required = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
180
+ try {
181
+ const host = new URL(controllerUrl).hostname.trim();
182
+ if (host) {
183
+ required.add(host);
184
+ }
185
+ }
186
+ catch {
187
+ // Ignore malformed controller URLs; worker registration will fail separately.
188
+ }
189
+ return Array.from(required);
190
+ }
191
+ function mergeNoProxyEntries(existing, requiredEntries) {
192
+ const tokens = new Map();
193
+ for (const entry of existing.split(",")) {
194
+ const trimmed = entry.trim();
195
+ if (!trimmed) {
196
+ continue;
197
+ }
198
+ tokens.set(trimmed.toLowerCase(), trimmed);
199
+ }
200
+ for (const entry of requiredEntries) {
201
+ const trimmed = entry.trim();
202
+ if (!trimmed) {
203
+ continue;
204
+ }
205
+ tokens.set(trimmed.toLowerCase(), trimmed);
206
+ }
207
+ return Array.from(tokens.values()).join(",");
208
+ }
209
+ function ensureRecord(value) {
210
+ return value && typeof value === "object" && !Array.isArray(value)
211
+ ? { ...value }
212
+ : {};
213
+ }
214
+ function parseLooseJsonObject(raw, configPath) {
215
+ try {
216
+ return JSON5.parse(raw);
217
+ }
218
+ catch (err) {
219
+ throw new Error(`Failed to parse OpenClaw config at ${configPath}: ${err instanceof Error ? err.message : String(err)}`);
220
+ }
221
+ }
222
+ export function buildProvisionedWorkspaceDir(provider, config, role, workerId) {
223
+ // Process-type workers run on the same host — share the controller's workspace
224
+ // so that file artifacts (previews, deliverables) are immediately visible to
225
+ // the controller without requiring git sync or file transfer.
226
+ if (provider === "process") {
227
+ return resolveTeamClawAgentWorkspaceRootDir();
228
+ }
229
+ if ((provider !== "docker" && provider !== "kubernetes") ||
230
+ !config.workerProvisioningWorkspaceRoot) {
231
+ return "";
232
+ }
233
+ return path.posix.join(config.workerProvisioningWorkspaceRoot, sanitizePathSegment(config.teamName), sanitizePathSegment(role), sanitizePathSegment(workerId));
234
+ }
235
+ export function getConfiguredWorkerWorkspaceDir(config) {
236
+ const agents = ensureRecord(config.agents);
237
+ const defaults = ensureRecord(agents.defaults);
238
+ return typeof defaults.workspace === "string" ? defaults.workspace : "";
239
+ }
@@ -0,0 +1,129 @@
1
+ import { sendJson, sendError, pinnedCorsAllowOrigin, readRequestBody } from "../protocol.js";
2
+ import { getActiveProfile, validateActiveRoleId } from "../profile-loader.js";
3
+ import { ensureControllerGitRepo, exportControllerGitBundle, importControllerGitBundle } from "../git-collaboration.js";
4
+ import { recordTaskExecutionEvent } from "./task-execution.js";
5
+ export async function refreshControllerRepoState(deps) {
6
+ // Phase 2.3: the ACTIVE PROFILE's git switch outranks the legacy config
7
+ // knob here - refreshing (or stamping) repo state for a profile that
8
+ // declared git off would re-introduce exactly the repo field the switch
9
+ // omitted for it (design 2.3: banking keeps no repo initialization). All
10
+ // callers already treat null as "no repo" (same as config gitEnabled off).
11
+ if (!deps.config.gitEnabled || !getActiveProfile().capabilities.git) {
12
+ return null;
13
+ }
14
+ try {
15
+ const repo = await ensureControllerGitRepo(deps.config, deps.logger);
16
+ if (repo) {
17
+ deps.updateTeamState((s) => {
18
+ s.repo = repo;
19
+ });
20
+ }
21
+ return repo;
22
+ }
23
+ catch (err) {
24
+ const message = err instanceof Error ? err.message : String(err);
25
+ deps.logger.warn(`Controller: failed to refresh git repo state: ${message}`);
26
+ deps.updateTeamState((s) => {
27
+ if (s.repo?.enabled) {
28
+ s.repo = {
29
+ ...s.repo,
30
+ error: message,
31
+ lastPreparedAt: Date.now(),
32
+ };
33
+ }
34
+ });
35
+ return deps.getTeamState()?.repo ?? null;
36
+ }
37
+ }
38
+ // GET /api/v1/repo
39
+ export async function handleRepoStatusRequest(deps, res) {
40
+ const repo = await refreshControllerRepoState(deps);
41
+ if (!repo?.enabled) {
42
+ sendJson(res, 200, { enabled: false });
43
+ return;
44
+ }
45
+ sendJson(res, 200, { repo });
46
+ }
47
+ // GET /api/v1/repo/bundle
48
+ export async function handleRepoBundleRequest(deps, res) {
49
+ try {
50
+ const exported = await exportControllerGitBundle(deps.config, deps.logger);
51
+ res.writeHead(200, {
52
+ "Content-Type": "application/octet-stream",
53
+ "Content-Length": exported.data.byteLength,
54
+ "Content-Disposition": `attachment; filename="${exported.filename}"`,
55
+ // Issue #23 security review follow-up: this response used to hardcode
56
+ // the L0 wildcard, which silently WIDENED a CORS origin the security
57
+ // gate had pinned while device protection is on. Honor the pinned
58
+ // header via the shared protocol helper; unpinned (protection off /
59
+ // non-browser) keeps the historical "*" byte for byte.
60
+ "Access-Control-Allow-Origin": pinnedCorsAllowOrigin(res),
61
+ "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
62
+ "Access-Control-Allow-Headers": "Content-Type",
63
+ });
64
+ res.end(exported.data);
65
+ }
66
+ catch (err) {
67
+ sendError(res, 503, err instanceof Error ? err.message : String(err));
68
+ }
69
+ }
70
+ // POST /api/v1/repo/import - issue #226 W2: moved verbatim from route-table.ts
71
+ // (which had moved it verbatim from http-server.ts with PR-D). Keeps the
72
+ // RouteContext shape; route-table's table entry binds it directly.
73
+ export async function repoImportRoute(ctx) {
74
+ const { req, res, requestUrl, deps } = ctx;
75
+ const { config, logger, updateTeamState } = deps;
76
+ const body = await readRequestBody(req);
77
+ if (!body.length) {
78
+ sendError(res, 400, "bundle body is required");
79
+ return;
80
+ }
81
+ const taskId = typeof requestUrl.searchParams.get("taskId") === "string" && requestUrl.searchParams.get("taskId")
82
+ ? requestUrl.searchParams.get("taskId")
83
+ : undefined;
84
+ const workerId = typeof requestUrl.searchParams.get("workerId") === "string" && requestUrl.searchParams.get("workerId")
85
+ ? requestUrl.searchParams.get("workerId")
86
+ : undefined;
87
+ const role = validateActiveRoleId(requestUrl.searchParams.get("role"));
88
+ try {
89
+ const imported = await importControllerGitBundle(config, logger, body, { taskId, workerId });
90
+ updateTeamState((s) => {
91
+ s.repo = imported.repo;
92
+ });
93
+ if (taskId) {
94
+ recordTaskExecutionEvent(taskId, {
95
+ type: imported.merged || imported.alreadyUpToDate ? "lifecycle" : "error",
96
+ phase: imported.merged
97
+ ? "repo_imported"
98
+ : imported.alreadyUpToDate
99
+ ? "repo_import_skipped"
100
+ : "repo_import_failed",
101
+ source: "controller",
102
+ message: imported.message,
103
+ workerId,
104
+ role,
105
+ }, deps);
106
+ }
107
+ sendJson(res, imported.merged || imported.alreadyUpToDate ? 200 : 409, {
108
+ repo: imported.repo,
109
+ merged: imported.merged,
110
+ fastForwarded: imported.fastForwarded,
111
+ alreadyUpToDate: imported.alreadyUpToDate,
112
+ message: imported.message,
113
+ });
114
+ }
115
+ catch (err) {
116
+ const message = err instanceof Error ? err.message : String(err);
117
+ if (taskId) {
118
+ recordTaskExecutionEvent(taskId, {
119
+ type: "error",
120
+ phase: "repo_import_failed",
121
+ source: "controller",
122
+ message,
123
+ workerId,
124
+ role,
125
+ }, deps);
126
+ }
127
+ sendError(res, 500, message);
128
+ }
129
+ }
@@ -0,0 +1,56 @@
1
+ // Issue #226 W2 (route-table carve-up): the delivery-report / health route
2
+ // handlers moved verbatim from route-table.ts (PR-D had moved them verbatim
3
+ // from http-server.ts before that) - bodies byte-identical, only the module
4
+ // home changed. route-table.ts keeps the table entries that bind these
5
+ // handlers. Like security.ts, this module imports route-table.js as TYPE
6
+ // ONLY (RouteContext), so the module graph stays acyclic.
7
+ import { sendJson, sendError } from "../protocol.js";
8
+ import { getTeamClawModelReadiness } from "../openclaw-workspace.js";
9
+ import { generateDeliveryReport, renderReportHtml } from "./delivery-report.js";
10
+ import { normalizeControllerIntakeSessionKey } from "./task-execution.js";
11
+ import { getEffectiveStartupReadiness } from "./worker-routes.js";
12
+ // GET /api/v1/reports — list all delivery reports
13
+ function reportsListRoute(ctx) {
14
+ const { res, deps } = ctx;
15
+ const state = deps.getTeamState();
16
+ const reports = Object.values(state?.reports ?? {}).sort((a, b) => b.generatedAt - a.generatedAt);
17
+ sendJson(res, 200, { reports });
18
+ }
19
+ // GET /api/v1/reports/:sessionKey — serve delivery report page
20
+ async function reportsSessionRoute(ctx) {
21
+ const { req, res, pathname, deps } = ctx;
22
+ const sessionKey = decodeURIComponent(pathname.slice("/api/v1/reports/".length));
23
+ const state = deps.getTeamState();
24
+ if (!state) {
25
+ sendError(res, 503, "Team state not loaded");
26
+ return;
27
+ }
28
+ const report = generateDeliveryReport(sessionKey, state, normalizeControllerIntakeSessionKey);
29
+ if (!report) {
30
+ sendError(res, 404, "No report found for this session");
31
+ return;
32
+ }
33
+ const accept = (req.headers["accept"] ?? "").toLowerCase();
34
+ if (accept.includes("application/json")) {
35
+ sendJson(res, 200, { report });
36
+ }
37
+ else {
38
+ const html = renderReportHtml(report);
39
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(html, "utf-8") });
40
+ res.end(html);
41
+ }
42
+ }
43
+ function healthRoute(ctx) {
44
+ const { res, deps, currentState } = ctx;
45
+ const readiness = getEffectiveStartupReadiness(deps, currentState);
46
+ const modelReadiness = getTeamClawModelReadiness();
47
+ const statusCode = readiness && readiness.status !== "ready" ? 503 : 200;
48
+ sendJson(res, statusCode, {
49
+ status: readiness?.status === "degraded" ? "degraded" : readiness?.status === "checking" ? "starting" : "ok",
50
+ mode: "controller",
51
+ timestamp: Date.now(),
52
+ provisioningReadiness: readiness,
53
+ modelReadiness,
54
+ });
55
+ }
56
+ export { reportsListRoute, reportsSessionRoute, healthRoute, };