@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
package/src/config.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import type { PluginConfig } from "./types.js";
2
2
  import { parsePluginConfig } from "./types.js";
3
- import { ROLE_IDS } from "./roles.js";
3
+ // Phase 1.3: the enum is driven by the active TeamProfile (software-rd
4
+ // baseline) instead of importing the roles.ts registry directly. The
5
+ // manifest generator evaluates this file without imports and injects
6
+ // equivalent getActiveRoleIds/SOFTWARE_RD_PROFILE_ID bindings.
7
+ import { getActiveRoleIds, SOFTWARE_RD_PROFILE_ID } from "./profile-loader.js";
4
8
  import { TEAMCLAW_PUBLISHED_RUNTIME_IMAGE } from "./install-defaults.js";
5
9
 
6
10
  function buildConfigSchema() {
@@ -19,6 +23,11 @@ function buildConfigSchema() {
19
23
  default: 9527,
20
24
  description: "HTTP server port for this instance",
21
25
  },
26
+ listenHost: {
27
+ type: "string" as const,
28
+ default: "",
29
+ description: "HTTP listen host override (empty = 127.0.0.1 on hosts, 0.0.0.0 in containers); set 0.0.0.0 for external workers reachable by a remote controller",
30
+ },
22
31
  role: {
23
32
  type: "string" as const,
24
33
  default: "developer",
@@ -34,6 +43,11 @@ function buildConfigSchema() {
34
43
  default: "TeamClaw",
35
44
  description: "Team name for mDNS identification",
36
45
  },
46
+ teamProfile: {
47
+ type: "string" as const,
48
+ default: SOFTWARE_RD_PROFILE_ID,
49
+ description: "Team profile package id (software-rd baseline); seeds first initialization only - the persisted team state profile is the runtime truth",
50
+ },
37
51
  heartbeatIntervalMs: {
38
52
  type: "number" as const,
39
53
  default: 10000,
@@ -44,6 +58,11 @@ function buildConfigSchema() {
44
58
  default: 600000,
45
59
  description: "Inactivity threshold in milliseconds before TeamClaw probes a stalled role task instead of failing it",
46
60
  },
61
+ teamSwitchDrainTimeoutMs: {
62
+ type: "number" as const,
63
+ default: 30000,
64
+ description: "How long a team profile switch waits for in-flight tasks to finish before force-collecting them (design 2.3 graceful drain)",
65
+ },
47
66
  maxConcurrentTasks: {
48
67
  type: "integer" as const,
49
68
  default: 5,
@@ -86,6 +105,26 @@ function buildConfigSchema() {
86
105
  default: "",
87
106
  description: "GitHub App OAuth client secret; the TEAMCLAW_GITHUB_CLIENT_SECRET environment variable takes precedence",
88
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
+ },
89
128
  agentIsolationMode: {
90
129
  type: "string" as const,
91
130
  enum: ["independent", "main"],
@@ -120,7 +159,7 @@ function buildConfigSchema() {
120
159
  description: "Preferred on-demand roles; task-required roles can still launch automatically. Empty means no preferred startup role list, so startup readiness falls back to a warm developer worker",
121
160
  items: {
122
161
  type: "string" as const,
123
- enum: ROLE_IDS,
162
+ enum: getActiveRoleIds(),
124
163
  },
125
164
  },
126
165
  workerProvisioningMinPerRole: {
@@ -236,14 +275,26 @@ function buildConfigSchema() {
236
275
  uiHints: {
237
276
  mode: { label: "Mode", help: "controller manages the team, worker executes tasks" },
238
277
  port: { label: "Port", help: "HTTP server port for this instance" },
278
+ listenHost: {
279
+ label: "Listen Host",
280
+ help: "HTTP bind address override; empty defaults to 127.0.0.1 on hosts and 0.0.0.0 in containers. Use 0.0.0.0 when a remote controller must reach this worker",
281
+ },
239
282
  role: { label: "Role", help: "Worker role (worker mode only)" },
240
283
  controllerUrl: { label: "Controller URL", help: "Manual fallback if mDNS discovery fails" },
241
284
  teamName: { label: "Team Name", help: "Team identifier for mDNS" },
285
+ teamProfile: {
286
+ label: "Team Profile",
287
+ help: "Team profile package id; applies to the first team initialization only (Phase 2 adds profile switching)",
288
+ },
242
289
  heartbeatIntervalMs: { label: "Heartbeat Interval", help: "In milliseconds, minimum 1000" },
243
290
  taskTimeoutMs: {
244
291
  label: "Task Stall Threshold",
245
292
  help: "In milliseconds, how long TeamClaw waits without visible progress before probing the task instead of failing it",
246
293
  },
294
+ teamSwitchDrainTimeoutMs: {
295
+ label: "Profile Switch Drain Timeout",
296
+ help: "In milliseconds, how long a team profile switch waits for in-flight tasks to finish before force-collecting them",
297
+ },
247
298
  maxConcurrentTasks: {
248
299
  label: "Max Concurrent Tasks",
249
300
  hint: "number",
@@ -278,6 +329,10 @@ function buildConfigSchema() {
278
329
  hint: "optional - prefer the TEAMCLAW_GITHUB_CLIENT_SECRET env var",
279
330
  help: "GitHub App OAuth client secret; the TEAMCLAW_GITHUB_CLIENT_SECRET environment variable takes precedence",
280
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
+ },
281
336
  agentIsolationMode: {
282
337
  label: "Agent Isolation Mode",
283
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, "&")
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
+ };
@@ -0,0 +1,404 @@
1
+ // PR-C of issue #204 (http-server monolith split): the clarification request
2
+ // domain - requestTaskClarification (task blocking + worker release), the
3
+ // structured answer builders, and the create/list/answer route handlers -
4
+ // lifted verbatim from controller/http-server.ts. Zero behavior change - the
5
+ // route shells in http-server keep the method+pathname matches and call these
6
+ // handlers with the same deps object as before. This module must NEVER import
7
+ // http-server (the reverse edge exists: http-server -> clarification-routes).
8
+ import type { IncomingMessage, ServerResponse } from "node:http";
9
+ import type {
10
+ ClarificationRequest,
11
+ RoleId,
12
+ TaskInfo,
13
+ TeamMessage,
14
+ WorkerInfo,
15
+ } from "../types.js";
16
+ import { generateId, parseJsonBody, sendError, sendJson } from "../protocol.js";
17
+ import { ensureTeamMessageContract } from "../interaction-contracts.js";
18
+ import { validateActiveRoleId } from "../profile-loader.js";
19
+ import { normalizeClarificationQuestionSchema } from "../shared/clarification-schema.js";
20
+ import {
21
+ cancelTaskExecution,
22
+ recordTaskExecutionEvent,
23
+ resetTaskForFreshAttempt,
24
+ serializeTask,
25
+ type ControllerTaskDomainDeps,
26
+ } from "./task-execution.js";
27
+ import { assignTaskToWorker } from "./task-assignment.js";
28
+ import { routeDirectMessage } from "./message-delivery.js";
29
+ import {
30
+ reconcileControllerClarifications,
31
+ runControllerIntake,
32
+ } from "./controller-intake.js";
33
+
34
+ // POST /api/v1/clarifications
35
+ export async function handleClarificationCreateRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
36
+ const body = await parseJsonBody(req);
37
+ const taskId = typeof body.taskId === "string" ? body.taskId : "";
38
+ const requestedBy = typeof body.requestedBy === "string" ? body.requestedBy : "";
39
+ const requestedByWorkerId = typeof body.requestedByWorkerId === "string" ? body.requestedByWorkerId : undefined;
40
+ const requestedByRole = validateActiveRoleId(body.requestedByRole);
41
+ const question = typeof body.question === "string" ? body.question.trim() : "";
42
+ const blockingReason = typeof body.blockingReason === "string" ? body.blockingReason.trim() : "";
43
+ const context = typeof body.context === "string" && body.context.trim() ? body.context.trim() : undefined;
44
+ const questionSchema = normalizeClarificationQuestionSchema(body.questionSchema);
45
+
46
+ if (!taskId || !question || !blockingReason) {
47
+ sendError(res, 400, "taskId, question, and blockingReason are required");
48
+ return;
49
+ }
50
+
51
+ const requested = await requestTaskClarification({
52
+ taskId,
53
+ requestedBy,
54
+ requestedByWorkerId,
55
+ requestedByRole,
56
+ question,
57
+ questionSchema,
58
+ blockingReason,
59
+ context,
60
+ }, deps);
61
+ if (requested.status === "missing-task") {
62
+ sendError(res, 404, "Task not found");
63
+ return;
64
+ }
65
+ if (requested.status === "conflict") {
66
+ sendError(res, 409, "Cannot request clarification for a completed task");
67
+ return;
68
+ }
69
+ if (requested.status === "already-pending") {
70
+ sendJson(res, 200, {
71
+ clarification: requested.clarification,
72
+ task: serializeTask(requested.task),
73
+ status: "already-pending",
74
+ });
75
+ return;
76
+ }
77
+ sendJson(res, 201, {
78
+ clarification: requested.clarification,
79
+ task: serializeTask(requested.task),
80
+ });
81
+ }
82
+
83
+ // GET /api/v1/clarifications
84
+ export async function handleClarificationListRequest(deps: ControllerTaskDomainDeps, res: ServerResponse): Promise<void> {
85
+ const state = reconcileControllerClarifications(deps);
86
+ const clarifications = state
87
+ ? Object.values(state.clarifications).sort((left, right) => right.createdAt - left.createdAt)
88
+ : [];
89
+ sendJson(res, 200, {
90
+ clarifications,
91
+ pendingCount: clarifications.filter((item) => item.status === "pending").length,
92
+ });
93
+ }
94
+
95
+ // POST /api/v1/clarifications/:id/answer
96
+ export async function handleClarificationAnswerRequest(deps: ControllerTaskDomainDeps, req: IncomingMessage, res: ServerResponse, pathname: string): Promise<void> {
97
+ const { getTeamState, taskRouter, updateTeamState, wsServer } = deps;
98
+ const clarificationId = pathname.split("/")[4]!;
99
+ const body = await parseJsonBody(req);
100
+ const answerValue = typeof body.answerValue === "string" ? body.answerValue.trim() : undefined;
101
+ const answerValues = Array.isArray(body.answerValues)
102
+ ? body.answerValues.map((entry) => String(entry || "").trim()).filter(Boolean)
103
+ : undefined;
104
+ const answerNumber = typeof body.answerNumber === "number" && Number.isFinite(body.answerNumber)
105
+ ? body.answerNumber
106
+ : undefined;
107
+ const answerComment = typeof body.answerComment === "string" && body.answerComment.trim()
108
+ ? body.answerComment.trim()
109
+ : undefined;
110
+ const answeredBy = typeof body.answeredBy === "string" && body.answeredBy.trim()
111
+ ? body.answeredBy.trim()
112
+ : "human";
113
+
114
+ const currentState = getTeamState();
115
+ const currentClarification = currentState?.clarifications[clarificationId];
116
+ if (!currentClarification) {
117
+ sendError(res, 404, "Clarification request not found");
118
+ return;
119
+ }
120
+
121
+ const answer = buildStructuredClarificationAnswer(currentClarification, {
122
+ answer: typeof body.answer === "string" ? body.answer.trim() : "",
123
+ answerValue,
124
+ answerValues,
125
+ answerNumber,
126
+ answerComment,
127
+ });
128
+
129
+ if (!answer) {
130
+ sendError(res, 400, "answer is required");
131
+ return;
132
+ }
133
+
134
+ if (currentClarification.status === "answered") {
135
+ sendError(res, 409, "Clarification request already answered");
136
+ return;
137
+ }
138
+
139
+ const now = Date.now();
140
+ const state = updateTeamState((s) => {
141
+ const clarification = s.clarifications[clarificationId];
142
+ if (!clarification) {
143
+ return;
144
+ }
145
+
146
+ clarification.status = "answered";
147
+ clarification.answer = answer;
148
+ clarification.answerValue = answerValue;
149
+ clarification.answerValues = answerValues;
150
+ clarification.answerNumber = answerNumber;
151
+ clarification.answerComment = answerComment;
152
+ clarification.answeredBy = answeredBy;
153
+ clarification.answeredAt = now;
154
+ clarification.updatedAt = now;
155
+
156
+ const task = s.tasks[clarification.taskId];
157
+ if (!task) {
158
+ return;
159
+ }
160
+
161
+ task.status = "pending";
162
+ task.progress = `Clarification answered by ${answeredBy}: ${answer}`;
163
+ task.clarificationRequestId = undefined;
164
+ resetTaskForFreshAttempt(task);
165
+ task.updatedAt = now;
166
+ });
167
+
168
+ const clarification = state.clarifications[clarificationId];
169
+ const task = clarification?.taskId ? state.tasks[clarification.taskId] : undefined;
170
+
171
+ let responseMessage: TeamMessage | undefined;
172
+ if (clarification?.requestedByRole && task) {
173
+ responseMessage = {
174
+ id: generateId(),
175
+ from: answeredBy,
176
+ toRole: clarification.requestedByRole,
177
+ type: "direct",
178
+ content: `Clarification answer for task ${task.id}: ${answer}`,
179
+ contract: ensureTeamMessageContract(null, {
180
+ type: "direct",
181
+ content: `Clarification answer for task ${task.id}: ${answer}`,
182
+ toRole: clarification.requestedByRole,
183
+ taskId: task.id,
184
+ summary: `Clarification answered for task ${task.id}`,
185
+ details: answer,
186
+ requestedAction: "Resume the task using this clarification.",
187
+ needsResponse: false,
188
+ intent: "update",
189
+ }),
190
+ taskId: task.id,
191
+ createdAt: now,
192
+ };
193
+
194
+ updateTeamState((s) => {
195
+ s.messages.push(responseMessage!);
196
+ });
197
+ await routeDirectMessage(responseMessage, deps);
198
+ wsServer.broadcastUpdate({ type: "message:new", data: responseMessage });
199
+ }
200
+
201
+ let resumedTask = task;
202
+ let resumedWorker: WorkerInfo | null = null;
203
+ let continuedControllerRun: {
204
+ sessionKey: string;
205
+ controllerRunId?: string;
206
+ runId?: string;
207
+ reply?: string;
208
+ queued?: boolean;
209
+ } | null = null;
210
+ if (task) {
211
+ const latestState = getTeamState()!;
212
+ if (clarification?.requestedByWorkerId && latestState.workers[clarification.requestedByWorkerId]?.status === "idle") {
213
+ resumedWorker = latestState.workers[clarification.requestedByWorkerId]!;
214
+ } else {
215
+ resumedWorker = taskRouter.routeTask(task, latestState.workers);
216
+ }
217
+
218
+ if (resumedWorker) {
219
+ resumedTask = await assignTaskToWorker(task.id, resumedWorker, deps, {
220
+ assignedRole: task.assignedRole,
221
+ });
222
+ }
223
+ } else if (clarification?.controllerRunId) {
224
+ const targetSessionKey = clarification.controllerSessionKey
225
+ || state.controllerRuns[clarification.controllerRunId]?.sessionKey;
226
+ if (targetSessionKey) {
227
+ continuedControllerRun = {
228
+ sessionKey: targetSessionKey,
229
+ controllerRunId: clarification.controllerRunId,
230
+ queued: true,
231
+ };
232
+ void runControllerIntake(
233
+ buildControllerClarificationAnswerMessage(clarification, answer, answeredBy),
234
+ targetSessionKey,
235
+ deps,
236
+ ).catch((err) => {
237
+ deps.logger.warn(
238
+ `Controller: failed to continue intake after clarification ${clarification.id}: ${String(err)}`,
239
+ );
240
+ });
241
+ }
242
+ }
243
+
244
+ wsServer.broadcastUpdate({ type: "clarification:answered", data: clarification });
245
+ if (resumedTask) {
246
+ recordTaskExecutionEvent(resumedTask.id, {
247
+ type: "lifecycle",
248
+ phase: "clarification_answered",
249
+ source: "controller",
250
+ message: `Clarification answered by ${answeredBy}: ${answer}`,
251
+ role: clarification?.requestedByRole,
252
+ workerId: clarification?.requestedByWorkerId,
253
+ }, deps);
254
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(resumedTask) });
255
+ }
256
+
257
+ sendJson(res, 200, {
258
+ clarification,
259
+ task: serializeTask(resumedTask),
260
+ resumedWorker,
261
+ controllerRun: continuedControllerRun,
262
+ message: responseMessage,
263
+ });
264
+ }
265
+
266
+ export function buildControllerClarificationAnswerMessage(
267
+ clarification: ClarificationRequest,
268
+ answer: string,
269
+ answeredBy: string,
270
+ ): string {
271
+ return [
272
+ "The human has answered a pending controller clarification.",
273
+ `Question: ${clarification.question}`,
274
+ `Answer: ${answer}`,
275
+ `Answered by: ${answeredBy}`,
276
+ "Use this answer to continue the same requirement and update the plan/tasks accordingly.",
277
+ ].join("\n");
278
+ }
279
+
280
+ export function buildStructuredClarificationAnswer(
281
+ clarification: ClarificationRequest,
282
+ payload: {
283
+ answer?: string;
284
+ answerValue?: string;
285
+ answerValues?: string[];
286
+ answerNumber?: number;
287
+ answerComment?: string;
288
+ },
289
+ ): string {
290
+ if (typeof payload.answer === "string" && payload.answer.trim()) {
291
+ return payload.answer.trim();
292
+ }
293
+ const schema = clarification.questionSchema;
294
+ const optionLabel = (value: string): string => {
295
+ const match = schema?.options?.find((entry) => entry.value === value);
296
+ return match?.label || value;
297
+ };
298
+ const parts: string[] = [];
299
+ if (schema?.kind === "single-select" && payload.answerValue) {
300
+ parts.push(optionLabel(payload.answerValue));
301
+ } else if (schema?.kind === "multi-select" && Array.isArray(payload.answerValues) && payload.answerValues.length > 0) {
302
+ parts.push(payload.answerValues.map((entry) => optionLabel(entry)).join(", "));
303
+ } else if (schema?.kind === "number" && typeof payload.answerNumber === "number" && Number.isFinite(payload.answerNumber)) {
304
+ parts.push(`${payload.answerNumber}${schema.unit ? ` ${schema.unit}` : ""}`);
305
+ } else if (payload.answerValue) {
306
+ parts.push(payload.answerValue);
307
+ }
308
+ if (payload.answerComment && payload.answerComment.trim()) {
309
+ parts.push(parts.length > 0 ? `Additional context: ${payload.answerComment.trim()}` : payload.answerComment.trim());
310
+ }
311
+ return parts.join("\n").trim();
312
+ }
313
+
314
+ export async function requestTaskClarification(params: {
315
+ taskId: string;
316
+ requestedBy: string;
317
+ requestedByWorkerId?: string;
318
+ requestedByRole?: RoleId;
319
+ question: string;
320
+ blockingReason: string;
321
+ context?: string;
322
+ questionSchema?: ClarificationRequest["questionSchema"];
323
+ }, deps: ControllerTaskDomainDeps): Promise<{
324
+ status: "created" | "already-pending" | "conflict" | "missing-task";
325
+ clarification?: ClarificationRequest;
326
+ task?: TaskInfo;
327
+ }> {
328
+ const { getTeamState, updateTeamState, wsServer } = deps;
329
+ const currentState = getTeamState();
330
+ const currentTask = currentState?.tasks[params.taskId];
331
+ if (!currentTask) {
332
+ return { status: "missing-task" };
333
+ }
334
+
335
+ if (currentTask.clarificationRequestId) {
336
+ const existing = currentState?.clarifications[currentTask.clarificationRequestId];
337
+ if (existing?.status === "pending") {
338
+ return { status: "already-pending", clarification: existing, task: currentTask };
339
+ }
340
+ }
341
+
342
+ if (currentTask.status === "completed" || currentTask.status === "failed") {
343
+ return { status: "conflict", task: currentTask };
344
+ }
345
+
346
+ const previousWorkerId = currentTask.assignedWorkerId;
347
+ const clarificationId = generateId();
348
+ const now = Date.now();
349
+ const clarification: ClarificationRequest = {
350
+ id: clarificationId,
351
+ taskId: params.taskId,
352
+ requestedBy: params.requestedBy,
353
+ requestedByWorkerId: params.requestedByWorkerId,
354
+ requestedByRole: params.requestedByRole,
355
+ question: params.question,
356
+ questionSchema: params.questionSchema,
357
+ blockingReason: params.blockingReason,
358
+ context: params.context,
359
+ status: "pending",
360
+ createdAt: now,
361
+ updatedAt: now,
362
+ };
363
+
364
+ const state = updateTeamState((s) => {
365
+ s.clarifications[clarificationId] = clarification;
366
+ const task = s.tasks[params.taskId];
367
+ if (!task) {
368
+ return;
369
+ }
370
+
371
+ const assignedWorkerId = task.assignedWorkerId;
372
+ task.status = "blocked";
373
+ task.progress = `Awaiting clarification: ${params.question}`;
374
+ task.clarificationRequestId = clarificationId;
375
+ task.assignedWorkerId = undefined;
376
+ task.updatedAt = now;
377
+
378
+ if (assignedWorkerId && s.workers[assignedWorkerId]) {
379
+ const assignedWorker = s.workers[assignedWorkerId];
380
+ if (assignedWorker.status !== "offline") {
381
+ assignedWorker.status = "idle";
382
+ }
383
+ assignedWorker.currentTaskId = undefined;
384
+ }
385
+ });
386
+
387
+ await cancelTaskExecution(params.taskId, previousWorkerId, "clarification request", deps);
388
+
389
+ const updatedTask = state.tasks[params.taskId];
390
+ wsServer.broadcastUpdate({ type: "clarification:requested", data: clarification });
391
+ if (updatedTask) {
392
+ recordTaskExecutionEvent(params.taskId, {
393
+ type: "lifecycle",
394
+ phase: "clarification_requested",
395
+ source: "controller",
396
+ message: `Clarification requested: ${params.question}`,
397
+ role: clarification.requestedByRole,
398
+ workerId: clarification.requestedByWorkerId,
399
+ }, deps);
400
+ wsServer.broadcastUpdate({ type: "task:updated", data: serializeTask(updatedTask) });
401
+ }
402
+
403
+ return { status: "created", clarification, task: updatedTask };
404
+ }