@teamclaws/teamclaw 2026.11.0 → 2026.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/cli.mjs +368 -13
  2. package/dist/index.js +61 -32
  3. package/dist/src/config.js +24 -0
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +1 -1
  6. package/dist/src/controller/config-routes.js +138 -0
  7. package/dist/src/controller/controller-planning.js +1 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-service.js +67 -10
  10. package/dist/src/controller/controller-tools.js +3 -1
  11. package/dist/src/controller/github-auth.js +2 -1
  12. package/dist/src/controller/http-server.js +51 -16
  13. package/dist/src/controller/kickoff-orchestrator.js +3 -39
  14. package/dist/src/controller/message-delivery.js +4 -1
  15. package/dist/src/controller/orchestration-manifest.js +5 -65
  16. package/dist/src/controller/preview-manager.js +51 -3
  17. package/dist/src/controller/profile-switch.js +42 -22
  18. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  19. package/dist/src/controller/provisioning/container-shared.js +64 -0
  20. package/dist/src/controller/provisioning/docker.js +214 -0
  21. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  22. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  23. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  24. package/dist/src/controller/provisioning-config.js +239 -0
  25. package/dist/src/controller/repo-routes.js +70 -4
  26. package/dist/src/controller/report-routes.js +56 -0
  27. package/dist/src/controller/route-table.js +73 -1045
  28. package/dist/src/controller/security.js +775 -0
  29. package/dist/src/controller/status-routes.js +287 -0
  30. package/dist/src/controller/task-assignment.js +5 -2
  31. package/dist/src/controller/task-execution.js +31 -0
  32. package/dist/src/controller/task-results.js +10 -0
  33. package/dist/src/controller/tunnel-manager.js +41 -8
  34. package/dist/src/controller/tunnel-routes.js +225 -0
  35. package/dist/src/controller/websocket.js +6 -2
  36. package/dist/src/controller/webui-routes.js +49 -0
  37. package/dist/src/controller/worker-provisioning.js +39 -949
  38. package/dist/src/controller/workflow-routes.js +407 -0
  39. package/dist/src/controller/workspace-routes.js +200 -0
  40. package/dist/src/git-collaboration.js +4 -9
  41. package/dist/src/identity.js +12 -1
  42. package/dist/src/openclaw-workspace.js +36 -0
  43. package/dist/src/profile-loader.js +119 -1
  44. package/dist/src/profiles/banking.json +26 -2
  45. package/dist/src/profiles/schema.json +82 -2
  46. package/dist/src/prompt-policy.js +18 -6
  47. package/dist/src/protocol.js +66 -3
  48. package/dist/src/shared/clarification-schema.js +65 -0
  49. package/dist/src/shared/github-auth.js +15 -0
  50. package/dist/src/shared/kickoff-prompt.js +37 -0
  51. package/dist/src/shared/utils.js +47 -0
  52. package/dist/src/state.js +89 -3
  53. package/dist/src/teamauto/scanner.js +21 -2
  54. package/dist/src/teamauto/scheduler.js +9 -2
  55. package/dist/src/types.js +15 -1
  56. package/dist/src/ui/app.js +990 -73
  57. package/dist/src/ui/github-login.html +1 -0
  58. package/dist/src/ui/index.html +125 -36
  59. package/dist/src/worker/http-handler.js +59 -0
  60. package/dist/src/worker/skill-installer.js +3 -9
  61. package/dist/src/worker/tools.js +20 -10
  62. package/dist/src/worker/worker-service.js +17 -4
  63. package/index.ts +69 -32
  64. package/openclaw.plugin.json +23 -2
  65. package/package.json +1 -1
  66. package/src/config.ts +24 -0
  67. package/src/controller/auth-routes.ts +157 -0
  68. package/src/controller/clarification-routes.ts +1 -1
  69. package/src/controller/config-routes.ts +152 -0
  70. package/src/controller/controller-planning.ts +8 -0
  71. package/src/controller/controller-routes.ts +237 -0
  72. package/src/controller/controller-service.ts +128 -10
  73. package/src/controller/controller-tools.ts +5 -2
  74. package/src/controller/github-auth.ts +28 -63
  75. package/src/controller/http-server.ts +66 -17
  76. package/src/controller/kickoff-orchestrator.ts +3 -42
  77. package/src/controller/message-delivery.ts +4 -1
  78. package/src/controller/orchestration-manifest.ts +8 -71
  79. package/src/controller/preview-manager.ts +53 -3
  80. package/src/controller/profile-switch.ts +53 -23
  81. package/src/controller/provisioning/backend-contract.ts +51 -0
  82. package/src/controller/provisioning/container-shared.ts +84 -0
  83. package/src/controller/provisioning/docker.ts +260 -0
  84. package/src/controller/provisioning/kubernetes.ts +263 -0
  85. package/src/controller/provisioning/plugin-root.ts +42 -0
  86. package/src/controller/provisioning/process-supervisor.ts +214 -0
  87. package/src/controller/provisioning-config.ts +289 -0
  88. package/src/controller/repo-routes.ts +84 -12
  89. package/src/controller/report-routes.ts +64 -0
  90. package/src/controller/route-table.ts +139 -1152
  91. package/src/controller/security.ts +899 -0
  92. package/src/controller/status-routes.ts +354 -0
  93. package/src/controller/task-assignment.ts +5 -1
  94. package/src/controller/task-execution.ts +43 -0
  95. package/src/controller/task-results.ts +12 -0
  96. package/src/controller/tunnel-manager.ts +45 -8
  97. package/src/controller/tunnel-routes.ts +231 -0
  98. package/src/controller/websocket.ts +20 -3
  99. package/src/controller/webui-routes.ts +55 -0
  100. package/src/controller/worker-provisioning.ts +51 -1117
  101. package/src/controller/workflow-routes.ts +498 -0
  102. package/src/controller/workspace-routes.ts +222 -0
  103. package/src/git-collaboration.ts +4 -9
  104. package/src/identity.ts +13 -1
  105. package/src/openclaw-workspace.ts +47 -0
  106. package/src/profile-loader.ts +167 -1
  107. package/src/profiles/banking.json +26 -2
  108. package/src/profiles/schema.json +82 -2
  109. package/src/prompt-policy.ts +19 -6
  110. package/src/protocol.ts +72 -2
  111. package/src/shared/clarification-schema.ts +81 -0
  112. package/src/shared/github-auth.ts +92 -0
  113. package/src/shared/kickoff-prompt.ts +47 -0
  114. package/src/shared/utils.ts +51 -0
  115. package/src/state.ts +92 -3
  116. package/src/teamauto/github-client.ts +2 -1
  117. package/src/teamauto/repo-sync.ts +2 -1
  118. package/src/teamauto/scanner.ts +22 -3
  119. package/src/teamauto/scheduler.ts +11 -3
  120. package/src/teamauto/store.ts +5 -0
  121. package/src/types.ts +130 -1
  122. package/src/ui/app.js +990 -73
  123. package/src/ui/github-login.html +1 -0
  124. package/src/ui/index.html +125 -36
  125. package/src/worker/http-handler.ts +64 -1
  126. package/src/worker/skill-installer.ts +3 -9
  127. package/src/worker/tools.ts +21 -10
  128. package/src/worker/worker-service.ts +18 -4
@@ -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
+ }
@@ -1,18 +1,21 @@
1
1
  // PR-B of issue #204 (http-server monolith split): the git collaboration
2
- // read-side routes (GET /api/v1/repo status, GET /api/v1/repo/bundle export)
3
- // and the repo state refresh glue extracted verbatim from
4
- // controller/http-server.ts. Zero behavior change - the route shells in
5
- // http-server keep the method+pathname matches and call these functions with
6
- // the same deps object as before. This module must NEVER import http-server
7
- // (the reverse edge exists: http-server -> repo-routes); POST /repo/import
8
- // stays in http-server for now because its recordTaskExecutionEvent
9
- // dependency is task-lifecycle glue owned by the PR-C cut.
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.
10
11
  import type { ServerResponse } from "node:http";
11
12
  import type { PluginLogger } from "../../api.js";
12
13
  import type { GitRepoState, PluginConfig, TeamState } from "../types.js";
13
- import { sendJson, sendError } from "../protocol.js";
14
- import { getActiveProfile } from "../profile-loader.js";
15
- import { ensureControllerGitRepo, exportControllerGitBundle } from "../git-collaboration.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";
16
19
 
17
20
  /**
18
21
  * Structural slice of ControllerHttpDeps (http-server.ts) covering exactly
@@ -80,7 +83,12 @@ export async function handleRepoBundleRequest(deps: RepoRouteDeps, res: ServerRe
80
83
  "Content-Type": "application/octet-stream",
81
84
  "Content-Length": exported.data.byteLength,
82
85
  "Content-Disposition": `attachment; filename="${exported.filename}"`,
83
- "Access-Control-Allow-Origin": "*",
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),
84
92
  "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
85
93
  "Access-Control-Allow-Headers": "Content-Type",
86
94
  });
@@ -89,3 +97,67 @@ export async function handleRepoBundleRequest(deps: RepoRouteDeps, res: ServerRe
89
97
  sendError(res, 503, err instanceof Error ? err.message : String(err));
90
98
  }
91
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
+ }
@@ -0,0 +1,64 @@
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
+ import type { RouteContext } from "./route-table.js";
13
+
14
+ // GET /api/v1/reports — list all delivery reports
15
+ function reportsListRoute(ctx: RouteContext): void {
16
+ const { res, deps } = ctx;
17
+ const state = deps.getTeamState();
18
+ const reports = Object.values(state?.reports ?? {}).sort((a, b) => b.generatedAt - a.generatedAt);
19
+ sendJson(res, 200, { reports });
20
+ }
21
+
22
+ // GET /api/v1/reports/:sessionKey — serve delivery report page
23
+ async function reportsSessionRoute(ctx: RouteContext): Promise<void> {
24
+ const { req, res, pathname, deps } = ctx;
25
+ const sessionKey = decodeURIComponent(pathname.slice("/api/v1/reports/".length));
26
+ const state = deps.getTeamState();
27
+ if (!state) {
28
+ sendError(res, 503, "Team state not loaded");
29
+ return;
30
+ }
31
+ const report = generateDeliveryReport(sessionKey, state, normalizeControllerIntakeSessionKey);
32
+ if (!report) {
33
+ sendError(res, 404, "No report found for this session");
34
+ return;
35
+ }
36
+ const accept = (req.headers["accept"] ?? "").toLowerCase();
37
+ if (accept.includes("application/json")) {
38
+ sendJson(res, 200, { report });
39
+ } else {
40
+ const html = renderReportHtml(report);
41
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Length": Buffer.byteLength(html, "utf-8") });
42
+ res.end(html);
43
+ }
44
+ }
45
+
46
+ function healthRoute(ctx: RouteContext): void {
47
+ const { res, deps, currentState } = ctx;
48
+ const readiness = getEffectiveStartupReadiness(deps, currentState);
49
+ const modelReadiness = getTeamClawModelReadiness();
50
+ const statusCode = readiness && readiness.status !== "ready" ? 503 : 200;
51
+ sendJson(res, statusCode, {
52
+ status: readiness?.status === "degraded" ? "degraded" : readiness?.status === "checking" ? "starting" : "ok",
53
+ mode: "controller",
54
+ timestamp: Date.now(),
55
+ provisioningReadiness: readiness,
56
+ modelReadiness,
57
+ });
58
+ }
59
+
60
+ export {
61
+ reportsListRoute,
62
+ reportsSessionRoute,
63
+ healthRoute,
64
+ };