@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
package/index.ts CHANGED
@@ -16,6 +16,17 @@ import { createControllerTools } from "./src/controller/controller-tools.js";
16
16
  import { publishWorkerRepo, syncWorkerRepo } from "./src/git-collaboration.js";
17
17
  import { resolveTeamClawProjectsDir } from "./src/openclaw-workspace.js";
18
18
  import { installRecommendedSkills } from "./src/worker/skill-installer.js";
19
+ // W6 of issue #226: local swallowing pathExists copy replaced by the shared
20
+ // one (identical semantics; alias keeps the call site byte-identical).
21
+ import { pathExistsTolerant as pathExists } from "./src/shared/utils.js";
22
+
23
+ // #253: the image build compiles this plugin into a flat rolldown bundle
24
+ // (dist/extensions/teamclaw/index.js) with NO nested dist/src tree, while the
25
+ // npm tarball layout ships dist/src/roles.js and no top-level index.js. The
26
+ // installer CLI (cli.mjs) reads the role registry through whichever layout it
27
+ // lands in, so the registry must be reachable from this entry as a named
28
+ // export for the bundled layout to resolve it.
29
+ export { ROLES, DEFAULT_ROLE } from "./src/roles.js";
19
30
 
20
31
  export default definePluginEntry({
21
32
  id: "teamclaw",
@@ -84,34 +95,42 @@ function registerController(api: OpenClawPluginApi, config: ReturnType<typeof pa
84
95
  });
85
96
  }
86
97
 
87
- function registerWorker(api: OpenClawPluginApi, config: ReturnType<typeof parsePluginConfig>) {
88
- const logger = api.logger;
89
- const messageQueue = new MessageQueue();
90
- let currentControllerUrl: string | null = null;
91
- let currentWorkerId: string | null = null;
92
-
93
- function getIdentity(): WorkerIdentity | null {
94
- if (!currentWorkerId || !currentControllerUrl) return null;
95
- return {
96
- workerId: currentWorkerId,
97
- role: config.role,
98
- controllerUrl: currentControllerUrl,
99
- registeredAt: Date.now(),
100
- };
101
- }
98
+ /**
99
+ * Issue #23 (client wave): headers for worker -> controller calls, same
100
+ * pattern as identity.ts / worker-service.ts / worker/tools.ts. A configured
101
+ * device token rides X-TeamClaw-Token; without one the headers are unchanged
102
+ * (L0). The token value is never logged.
103
+ */
104
+ function withDeviceToken(config: ReturnType<typeof parsePluginConfig>, headers: Record<string, string>): Record<string, string> {
105
+ const token = config.securityToken?.trim();
106
+ return token ? { ...headers, "X-TeamClaw-Token": token } : headers;
107
+ }
102
108
 
109
+ /**
110
+ * Execution-event + checkpoint reporters (issue #23 review follow-up: the
111
+ * execution stream and resume checkpoints MUST survive device protection, so
112
+ * both POSTs carry the paired device token). Extracted from registerWorker
113
+ * as an exported factory so the dist-level client tests can exercise the
114
+ * real header behavior against a stub controller.
115
+ */
116
+ export function createWorkerEventReporters(
117
+ config: ReturnType<typeof parsePluginConfig>,
118
+ logger: { warn(entry: string): void },
119
+ state: { getControllerUrl: () => string | null; getWorkerId: () => string | null },
120
+ ) {
103
121
  async function reportExecutionEvent(taskId: string, event: TaskExecutionEventInput): Promise<void> {
104
- if (!currentControllerUrl) {
122
+ const controllerUrl = state.getControllerUrl();
123
+ if (!controllerUrl) {
105
124
  return;
106
125
  }
107
126
 
108
127
  try {
109
- const res = await fetch(`${currentControllerUrl}/api/v1/tasks/${taskId}/execution`, {
128
+ const res = await fetch(`${controllerUrl}/api/v1/tasks/${taskId}/execution`, {
110
129
  method: "POST",
111
- headers: { "Content-Type": "application/json" },
130
+ headers: withDeviceToken(config, { "Content-Type": "application/json" }),
112
131
  body: JSON.stringify({
113
132
  ...event,
114
- workerId: currentWorkerId ?? undefined,
133
+ workerId: state.getWorkerId() ?? undefined,
115
134
  role: config.role,
116
135
  }),
117
136
  });
@@ -124,20 +143,47 @@ function registerWorker(api: OpenClawPluginApi, config: ReturnType<typeof parseP
124
143
  }
125
144
 
126
145
  async function reportCheckpoint(taskId: string, checkpoint: { lastAssistantMessage: string; progressNote?: string; sessionKey: string }): Promise<void> {
127
- if (!currentControllerUrl) {
146
+ const controllerUrl = state.getControllerUrl();
147
+ if (!controllerUrl) {
128
148
  return;
129
149
  }
130
150
  try {
131
- await fetch(`${currentControllerUrl}/api/v1/tasks/${taskId}/checkpoint`, {
151
+ await fetch(`${controllerUrl}/api/v1/tasks/${taskId}/checkpoint`, {
132
152
  method: "POST",
133
- headers: { "Content-Type": "application/json" },
134
- body: JSON.stringify({ ...checkpoint, workerId: currentWorkerId ?? undefined }),
153
+ headers: withDeviceToken(config, { "Content-Type": "application/json" }),
154
+ body: JSON.stringify({ ...checkpoint, workerId: state.getWorkerId() ?? undefined }),
135
155
  });
136
156
  } catch {
137
157
  // Checkpointing is best-effort; a lost heartbeat only costs resume freshness.
138
158
  }
139
159
  }
140
160
 
161
+ return { reportExecutionEvent, reportCheckpoint };
162
+ }
163
+
164
+ function registerWorker(api: OpenClawPluginApi, config: ReturnType<typeof parsePluginConfig>) {
165
+ const logger = api.logger;
166
+ const messageQueue = new MessageQueue();
167
+ let currentControllerUrl: string | null = null;
168
+ let currentWorkerId: string | null = null;
169
+
170
+ function getIdentity(): WorkerIdentity | null {
171
+ if (!currentWorkerId || !currentControllerUrl) return null;
172
+ return {
173
+ workerId: currentWorkerId,
174
+ role: config.role,
175
+ controllerUrl: currentControllerUrl,
176
+ registeredAt: Date.now(),
177
+ };
178
+ }
179
+
180
+ const { reportExecutionEvent, reportCheckpoint } = createWorkerEventReporters(config, logger, {
181
+ // Read through getters so the reporters always see the identity the
182
+ // worker service has established by the time an event fires.
183
+ getControllerUrl: () => currentControllerUrl,
184
+ getWorkerId: () => currentWorkerId,
185
+ });
186
+
141
187
  const getWorkerSessionKey = (assignment: TaskAssignmentPayload) =>
142
188
  assignment.executionSessionKey?.trim() || `teamclaw-task-${assignment.taskId}`;
143
189
 
@@ -171,15 +217,6 @@ function registerWorker(api: OpenClawPluginApi, config: ReturnType<typeof parseP
171
217
  return { sharedProjectDir, localProjectDir };
172
218
  }
173
219
 
174
- async function pathExists(targetPath: string): Promise<boolean> {
175
- try {
176
- await fs.access(targetPath);
177
- return true;
178
- } catch {
179
- return false;
180
- }
181
- }
182
-
183
220
  async function syncProjectDir(sourceDir: string, destinationDir: string): Promise<boolean> {
184
221
  if (!await pathExists(sourceDir)) {
185
222
  return false;
@@ -2,7 +2,7 @@
2
2
  "id": "teamclaw",
3
3
  "name": "TeamClaw",
4
4
  "description": "Virtual team collaboration - multiple OpenClaw instances form a virtual software company with role-based task routing.",
5
- "version": "2026.11.0",
5
+ "version": "2026.11.2",
6
6
  "activation": {
7
7
  "onStartup": true
8
8
  },
@@ -75,7 +75,7 @@
75
75
  "maxConcurrentTasks": {
76
76
  "label": "Max Concurrent Tasks",
77
77
  "hint": "number",
78
- "help": "Maximum number of tasks that can be in 'in_progress' status at the same time (1\u201350)"
78
+ "help": "Maximum number of tasks that can be in 'in_progress' status at the same time (1–50)"
79
79
  },
80
80
  "gitEnabled": {
81
81
  "label": "Git Collaboration",
@@ -106,6 +106,10 @@
106
106
  "hint": "optional - prefer the TEAMCLAW_GITHUB_CLIENT_SECRET env var",
107
107
  "help": "GitHub App OAuth client secret; the TEAMCLAW_GITHUB_CLIENT_SECRET environment variable takes precedence"
108
108
  },
109
+ "security": {
110
+ "label": "Device Pairing Security",
111
+ "help": "Controller device-pairing options; autoPair allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto), disable it to require a pairing code for every new device"
112
+ },
109
113
  "agentIsolationMode": {
110
114
  "label": "Agent Isolation Mode",
111
115
  "help": "Use a dedicated TeamClaw agent/workspace by default, or the legacy shared main-agent mode"
@@ -302,6 +306,23 @@
302
306
  "default": "",
303
307
  "description": "GitHub App OAuth client secret; the TEAMCLAW_GITHUB_CLIENT_SECRET environment variable takes precedence"
304
308
  },
309
+ "security": {
310
+ "type": "object",
311
+ "default": {},
312
+ "description": "Controller device-pairing security (issue #23); protection itself is enabled per-team via POST /api/v1/security/enable",
313
+ "properties": {
314
+ "autoPair": {
315
+ "type": "boolean",
316
+ "default": true,
317
+ "description": "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); disable to require a pairing code for every new device"
318
+ }
319
+ }
320
+ },
321
+ "securityToken": {
322
+ "type": "string",
323
+ "default": "",
324
+ "description": "Device pairing token for a protected controller (issue #23); written by `teamclaw pair`, sent as X-TeamClaw-Token on API calls. Leave empty for unpaired local mode"
325
+ },
305
326
  "agentIsolationMode": {
306
327
  "type": "string",
307
328
  "enum": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamclaws/teamclaw",
3
- "version": "2026.11.0",
3
+ "version": "2026.11.2",
4
4
  "description": "OpenClaw virtual software team orchestration plugin - controller, role-based workers, Web UI with internet tunnel sharing",
5
5
  "private": false,
6
6
  "keywords": [
package/src/config.ts CHANGED
@@ -105,6 +105,26 @@ function buildConfigSchema() {
105
105
  default: "",
106
106
  description: "GitHub App OAuth client secret; the TEAMCLAW_GITHUB_CLIENT_SECRET environment variable takes precedence",
107
107
  },
108
+ security: {
109
+ type: "object" as const,
110
+ default: {},
111
+ description: "Controller device-pairing security (issue #23); protection itself is enabled per-team via POST /api/v1/security/enable",
112
+ properties: {
113
+ autoPair: {
114
+ type: "boolean" as const,
115
+ default: true,
116
+ description: "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); disable to require a pairing code for every new device",
117
+ },
118
+ },
119
+ },
120
+ securityToken: {
121
+ type: "string" as const,
122
+ default: "",
123
+ // Deliberately NO uiHints entry: the token is a secret written by
124
+ // `teamclaw pair` / the desktop pairing flow and must never be
125
+ // echoed back through config surfaces or logs.
126
+ description: "Device pairing token for a protected controller (issue #23); written by `teamclaw pair`, sent as X-TeamClaw-Token on API calls. Leave empty for unpaired local mode",
127
+ },
108
128
  agentIsolationMode: {
109
129
  type: "string" as const,
110
130
  enum: ["independent", "main"],
@@ -309,6 +329,10 @@ function buildConfigSchema() {
309
329
  hint: "optional - prefer the TEAMCLAW_GITHUB_CLIENT_SECRET env var",
310
330
  help: "GitHub App OAuth client secret; the TEAMCLAW_GITHUB_CLIENT_SECRET environment variable takes precedence",
311
331
  },
332
+ security: {
333
+ label: "Device Pairing Security",
334
+ help: "Controller device-pairing options; autoPair allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto), disable it to require a pairing code for every new device",
335
+ },
312
336
  agentIsolationMode: {
313
337
  label: "Agent Isolation Mode",
314
338
  help: "Use a dedicated TeamClaw agent/workspace by default, or the legacy shared main-agent mode",
@@ -0,0 +1,157 @@
1
+ // Issue #226 W2 (route-table carve-up): the GitHub login/logout route
2
+ // handlers (plus their private HTML-rendering helpers) moved verbatim from
3
+ // route-table.ts (PR-D had moved them verbatim from http-server.ts before
4
+ // that) - bodies byte-identical, only the module home changed. route-table.ts
5
+ // keeps the table entries that bind these handlers. Like security.ts, this
6
+ // module imports route-table.js as TYPE ONLY (RouteContext), so the module
7
+ // graph stays acyclic.
8
+ import type { IncomingMessage, ServerResponse } from "node:http";
9
+ import type { PluginConfig } from "../types.js";
10
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
11
+ import { getGithubAuthManager } from "./github-auth.js";
12
+ import type { RouteContext } from "./route-table.js";
13
+
14
+ function resolveRequestOrigin(req: IncomingMessage, config: PluginConfig): string {
15
+ const host = req.headers.host;
16
+ if (typeof host === "string" && host.trim()) {
17
+ return `http://${host.trim()}`;
18
+ }
19
+ return `http://127.0.0.1:${config.port}`;
20
+ }
21
+
22
+ function escapeHtmlText(value: string): string {
23
+ return value
24
+ .replace(/&/g, "&amp;")
25
+ .replace(/</g, "&lt;")
26
+ .replace(/>/g, "&gt;")
27
+ .replace(/"/g, "&quot;")
28
+ .replace(/'/g, "&#39;");
29
+ }
30
+
31
+ function sendGithubCallbackHtml(res: ServerResponse, statusCode: number, title: string, message: string): void {
32
+ const html = [
33
+ "<!DOCTYPE html><html><head><meta charset=\"utf-8\">",
34
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
35
+ `<title>${escapeHtmlText(title)}</title>`,
36
+ "<style>body{font-family:-apple-system,system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:#0f1117;color:#e6e8ee}main{max-width:520px;padding:32px 40px;border:1px solid #2a2f3a;border-radius:14px;background:#161923;text-align:center}h1{font-size:20px;margin:0 0 10px}p{margin:6px 0;color:#a8b0c0;line-height:1.6}</style>",
37
+ "</head><body><main>",
38
+ `<h1>${escapeHtmlText(title)}</h1>`,
39
+ `<p>${escapeHtmlText(message)}</p>`,
40
+ "</main></body></html>",
41
+ ].join("");
42
+ res.writeHead(statusCode, {
43
+ "Content-Type": "text/html; charset=utf-8",
44
+ "Content-Length": Buffer.byteLength(html),
45
+ });
46
+ res.end(html);
47
+ }
48
+
49
+ async function githubAuthStatusRoute(ctx: RouteContext): Promise<void> {
50
+ const { req, res, deps } = ctx;
51
+ const { config, logger } = deps;
52
+ try {
53
+ const status = await getGithubAuthManager(config, logger).getStatus(resolveRequestOrigin(req, config));
54
+ sendJson(res, 200, status);
55
+ } catch (err) {
56
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read GitHub login status");
57
+ }
58
+ }
59
+
60
+ async function githubAuthLoginRoute(ctx: RouteContext): Promise<void> {
61
+ const { req, res, deps } = ctx;
62
+ const { config, logger } = deps;
63
+ let flow: string | undefined;
64
+ try {
65
+ const body = await parseJsonBody(req) as { flow?: unknown };
66
+ if (typeof body?.flow === "string") {
67
+ flow = body.flow.trim();
68
+ }
69
+ } catch {
70
+ // No body or invalid body: fall through to the default (device) flow.
71
+ }
72
+ const manager = getGithubAuthManager(config, logger);
73
+ try {
74
+ const loginPageUrl = resolveRequestOrigin(req, config).replace(/\/+$/, "") + "/ui/auth/github";
75
+ if (flow === "web") {
76
+ // Web flow needs a client secret for the code exchange; the device
77
+ // flow (default) is fully secretless.
78
+ const start = manager.beginLogin(resolveRequestOrigin(req, config));
79
+ sendJson(res, 200, { mode: "web", loginPageUrl, ...start });
80
+ } else {
81
+ const start = await manager.beginDeviceLogin();
82
+ // authorizeUrl intentionally points at our standalone login page so
83
+ // older UI clients that just open response.authorizeUrl land on the
84
+ // device-code page instead of a dead web-flow URL.
85
+ sendJson(res, 200, { mode: "device", loginPageUrl, authorizeUrl: loginPageUrl, ...start });
86
+ }
87
+ logger.info(`Controller: GitHub login flow started (${flow === "web" ? "web" : "device"})`);
88
+ } catch (err) {
89
+ sendError(res, 400, err instanceof Error ? err.message : "failed to start GitHub login");
90
+ }
91
+ }
92
+
93
+ async function githubAuthCallbackRoute(ctx: RouteContext): Promise<void> {
94
+ const { req, res, requestUrl, deps } = ctx;
95
+ const { config, logger } = deps;
96
+ const callbackError = requestUrl.searchParams.get("error");
97
+ if (callbackError) {
98
+ const description = requestUrl.searchParams.get("error_description") ?? "";
99
+ logger.warn(`Controller: GitHub login was denied (${callbackError})`);
100
+ sendGithubCallbackHtml(
101
+ res,
102
+ 400,
103
+ "GitHub login failed",
104
+ `Authorization was denied: ${callbackError}${description ? ` (${description})` : ""}`,
105
+ );
106
+ return;
107
+ }
108
+ const code = requestUrl.searchParams.get("code") ?? "";
109
+ const state = requestUrl.searchParams.get("state") ?? "";
110
+ try {
111
+ const account = await getGithubAuthManager(config, logger).completeLogin({
112
+ code: code || undefined,
113
+ state: state || undefined,
114
+ });
115
+ logger.info(`Controller: GitHub login completed for @${account.login}`);
116
+ sendGithubCallbackHtml(
117
+ res,
118
+ 200,
119
+ "GitHub login successful",
120
+ `Signed in as @${account.login}(GitHub 登录成功,可关闭本页返回 TeamClaw)。`,
121
+ );
122
+ } catch (err) {
123
+ const message = err instanceof Error ? err.message : String(err);
124
+ logger.warn(`Controller: GitHub login callback failed: ${message}`);
125
+ sendGithubCallbackHtml(res, 400, "GitHub login failed", `${message}`);
126
+ }
127
+ }
128
+
129
+ async function githubAuthLogoutRoute(ctx: RouteContext): Promise<void> {
130
+ const { res, deps } = ctx;
131
+ const { config, logger } = deps;
132
+ try {
133
+ await getGithubAuthManager(config, logger).logout();
134
+ sendJson(res, 200, { ok: true });
135
+ } catch (err) {
136
+ sendError(res, 500, err instanceof Error ? err.message : "failed to sign out of GitHub");
137
+ }
138
+ }
139
+
140
+ async function githubAuthRefreshRoute(ctx: RouteContext): Promise<void> {
141
+ const { res, deps } = ctx;
142
+ const { config, logger } = deps;
143
+ try {
144
+ const store = await getGithubAuthManager(config, logger).forceRefresh();
145
+ sendJson(res, 200, { ok: true, account: store.account, expiresAt: store.expiresAt });
146
+ } catch (err) {
147
+ sendError(res, 400, err instanceof Error ? err.message : "failed to refresh the GitHub token");
148
+ }
149
+ }
150
+
151
+ export {
152
+ githubAuthStatusRoute,
153
+ githubAuthLoginRoute,
154
+ githubAuthCallbackRoute,
155
+ githubAuthLogoutRoute,
156
+ githubAuthRefreshRoute,
157
+ };
@@ -16,7 +16,7 @@ import type {
16
16
  import { generateId, parseJsonBody, sendError, sendJson } from "../protocol.js";
17
17
  import { ensureTeamMessageContract } from "../interaction-contracts.js";
18
18
  import { validateActiveRoleId } from "../profile-loader.js";
19
- import { normalizeClarificationQuestionSchema } from "./orchestration-manifest.js";
19
+ import { normalizeClarificationQuestionSchema } from "../shared/clarification-schema.js";
20
20
  import {
21
21
  cancelTaskExecution,
22
22
  recordTaskExecutionEvent,
@@ -0,0 +1,152 @@
1
+ // Hot-reloadable worker-provisioning configuration routes (runtime scaling).
2
+ //
3
+ // GET /api/v1/team/config -> read-only snapshot of the hot-reloadable fields
4
+ // PATCH /api/v1/team/config -> whitelist-only update that
5
+ // 1. mutates deps.config IN MEMORY (the provisioner reads these fields on
6
+ // every computeRoleDemand pass, so the change applies on the next
7
+ // reconcile tick — no restart),
8
+ // 2. persists to the host openclaw.json plugins.entries.teamclaw.config
9
+ // (same read-modify-write pattern as updateTeamClawModelConfig), and
10
+ // 3. pokes the provisioner via requestReconcile + broadcasts a
11
+ // team:config_updated WS event so desktop/web UIs refresh.
12
+ //
13
+ // Deployment-shape behavior (issue context: all deployment forms):
14
+ // - process / managed-gateway / desktop-private / tunnel: memory + host-config
15
+ // persistence (resolveDefaultOpenClawConfigPath honors OPENCLAW_HOME /
16
+ // OPENCLAW_CONFIG_PATH, so sandboxed instances persist into their own home).
17
+ // - docker (controller on host): same as process — host config is writable.
18
+ // - docker/k8s (controller itself containerized): container FS is ephemeral,
19
+ // so persistence degrades to memory-only and the response carries
20
+ // persistenceMode: "memory-only" + a restart note (declared behavior, not
21
+ // a silent drop). k8s deployments should source config from ConfigMap and
22
+ // treat this API as runtime-only scaling.
23
+ // Scale-down semantics: lowering maxPerRole never kills active workers; idle
24
+ // workers drain via workerProvisioningIdleTtlMs and the cap stops refills.
25
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
26
+ import { updateTeamClawProvisioningConfig } from "../openclaw-workspace.js";
27
+ import type { RouteContext } from "./route-table.js";
28
+
29
+ /** Fields a PATCH may touch. Everything else in PluginConfig is rejected. */
30
+ const HOT_CONFIG_FIELDS = [
31
+ "workerProvisioningMaxPerRole",
32
+ "workerProvisioningMinPerRole",
33
+ "workerProvisioningIdleTtlMs",
34
+ ] as const;
35
+ type HotConfigField = (typeof HOT_CONFIG_FIELDS)[number];
36
+
37
+ const BOUNDS: Record<HotConfigField, { min: number; max: number }> = {
38
+ workerProvisioningMaxPerRole: { min: 1, max: 50 },
39
+ workerProvisioningMinPerRole: { min: 0, max: 50 },
40
+ // 1s floor keeps the idle reaper from churn-looping; 24h ceiling is generous.
41
+ workerProvisioningIdleTtlMs: { min: 1_000, max: 86_400_000 },
42
+ };
43
+
44
+ function teamConfigGetRoute(ctx: RouteContext): void {
45
+ const { res, deps } = ctx;
46
+ const c = deps.config;
47
+ sendJson(res, 200, {
48
+ workerProvisioningType: c.workerProvisioningType,
49
+ workerProvisioningDisabled: c.workerProvisioningDisabled,
50
+ workerProvisioningMinPerRole: c.workerProvisioningMinPerRole,
51
+ workerProvisioningMaxPerRole: c.workerProvisioningMaxPerRole,
52
+ workerProvisioningIdleTtlMs: c.workerProvisioningIdleTtlMs,
53
+ // k8s controllers run on ephemeral container FS: declare it up front.
54
+ persistenceMode: c.workerProvisioningType === "kubernetes" ? "memory-only" : "host-config",
55
+ });
56
+ }
57
+
58
+ async function teamConfigPatchRoute(ctx: RouteContext): Promise<void> {
59
+ const { req, res, deps } = ctx;
60
+ let body: Record<string, unknown> | null = null;
61
+ try {
62
+ body = (await parseJsonBody(req)) as Record<string, unknown>;
63
+ } catch {
64
+ sendError(res, 400, "invalid JSON body");
65
+ return;
66
+ }
67
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
68
+ sendError(res, 400, "JSON object body required");
69
+ return;
70
+ }
71
+
72
+ const unknown = Object.keys(body).filter((k) => !(HOT_CONFIG_FIELDS as readonly string[]).includes(k));
73
+ if (unknown.length > 0) {
74
+ sendError(res, 400, `unknown or non-hot-reloadable field(s): ${unknown.join(", ")}`);
75
+ return;
76
+ }
77
+
78
+ const update: Partial<Record<HotConfigField, number>> = {};
79
+ for (const field of HOT_CONFIG_FIELDS) {
80
+ if (body[field] === undefined) continue;
81
+ const raw = body[field];
82
+ if (typeof raw !== "number" || !Number.isFinite(raw)) {
83
+ sendError(res, 400, `${field} must be a finite number`);
84
+ return;
85
+ }
86
+ const { min, max } = BOUNDS[field];
87
+ update[field] = Math.max(min, Math.min(max, Math.floor(raw)));
88
+ }
89
+ if (Object.keys(update).length === 0) {
90
+ sendError(res, 400, `at least one of ${HOT_CONFIG_FIELDS.join(", ")} is required`);
91
+ return;
92
+ }
93
+
94
+ // 1) In-memory hot apply (deps.config is a live reference the provisioner
95
+ // reads on every demand computation — no restart needed).
96
+ const applied: Record<string, number> = {};
97
+ for (const [field, value] of Object.entries(update) as [HotConfigField, number][]) {
98
+ (deps.config as unknown as Record<string, number>)[field] = value;
99
+ applied[field] = value;
100
+ }
101
+ // Keep the min<=max invariant types.ts enforces at parse time.
102
+ const minR = update.workerProvisioningMinPerRole ?? deps.config.workerProvisioningMinPerRole;
103
+ if (deps.config.workerProvisioningMaxPerRole < minR) {
104
+ deps.config.workerProvisioningMaxPerRole = minR;
105
+ applied.workerProvisioningMaxPerRole = minR;
106
+ }
107
+
108
+ // 2) Persist (host config) unless the controller itself runs on an
109
+ // ephemeral container FS.
110
+ const memoryOnly = deps.config.workerProvisioningType === "kubernetes";
111
+ let persisted = false;
112
+ if (!memoryOnly) {
113
+ try {
114
+ await updateTeamClawProvisioningConfig(applied, {
115
+ warn: (message: string) => deps.logger.info(message),
116
+ });
117
+ persisted = true;
118
+ } catch (err) {
119
+ // Memory already applied — report partial success honestly.
120
+ deps.logger.warn(
121
+ `TeamClaw: hot config applied in memory but host-config persist failed: ${err instanceof Error ? err.message : String(err)}`,
122
+ );
123
+ }
124
+ }
125
+
126
+ // 3) Poke the provisioner so the new caps apply immediately instead of
127
+ // waiting for the next periodic reconcile tick, then tell UIs.
128
+ try {
129
+ await deps.workerProvisioningManager?.requestReconcile("team-config-hot-update");
130
+ } catch (err) {
131
+ deps.logger.warn(
132
+ `TeamClaw: config hot-update reconcile poke failed: ${err instanceof Error ? err.message : String(err)}`,
133
+ );
134
+ }
135
+ deps.wsServer.broadcastUpdate({ type: "team:config_updated", data: { ...applied, persisted } });
136
+ deps.logger.info(`TeamClaw: worker provisioning config hot-updated: ${JSON.stringify(applied)} (persisted=${persisted})`);
137
+
138
+ sendJson(res, 200, {
139
+ ok: true,
140
+ applied,
141
+ persisted,
142
+ persistenceMode: persisted ? "host-config" : "memory-only",
143
+ ...(persisted
144
+ ? {}
145
+ : {
146
+ restartNote:
147
+ "Applied in memory only; this deployment shape does not persist to a durable host config — after a gateway restart the config reverts to its persisted source.",
148
+ }),
149
+ });
150
+ }
151
+
152
+ export { teamConfigGetRoute, teamConfigPatchRoute };
@@ -15,6 +15,7 @@ import type {
15
15
  RoleId,
16
16
  TaskInfo,
17
17
  TaskPriority,
18
+ TaskWorkflowContext,
18
19
  TeamMessage,
19
20
  TeamState,
20
21
  WorkerTaskResultContract,
@@ -576,6 +577,12 @@ export async function createControllerManagedTask(
576
577
  controllerSessionKey?: string;
577
578
  projectName?: string;
578
579
  recommendedSkills?: string[];
580
+ /**
581
+ * Design 2.4 workflow-chain context: when present the task is a workflow
582
+ * step task (createdBy "workflow") and the completion hook routes the
583
+ * chain from it. Untouched for controller/other creators.
584
+ */
585
+ workflow?: TaskWorkflowContext;
579
586
  },
580
587
  deps: ControllerTaskDomainDeps,
581
588
  ): Promise<TaskInfo | undefined> {
@@ -605,6 +612,7 @@ export async function createControllerManagedTask(
605
612
  recommendedSkills: normalizedRecommendedSkills.length > 0 ? normalizedRecommendedSkills : undefined,
606
613
  controllerRunId: input.createdBy === "controller" ? input.controllerRunId : undefined,
607
614
  controllerSessionKey: normalizedSessionKey,
615
+ workflow: input.workflow,
608
616
  projectId,
609
617
  projectDir,
610
618
  createdAt: now,