@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,129 @@
1
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
2
+ import { getGithubAuthManager } from "./github-auth.js";
3
+ function resolveRequestOrigin(req, config) {
4
+ const host = req.headers.host;
5
+ if (typeof host === "string" && host.trim()) {
6
+ return `http://${host.trim()}`;
7
+ }
8
+ return `http://127.0.0.1:${config.port}`;
9
+ }
10
+ function escapeHtmlText(value) {
11
+ return value
12
+ .replace(/&/g, "&")
13
+ .replace(/</g, "&lt;")
14
+ .replace(/>/g, "&gt;")
15
+ .replace(/"/g, "&quot;")
16
+ .replace(/'/g, "&#39;");
17
+ }
18
+ function sendGithubCallbackHtml(res, statusCode, title, message) {
19
+ const html = [
20
+ "<!DOCTYPE html><html><head><meta charset=\"utf-8\">",
21
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
22
+ `<title>${escapeHtmlText(title)}</title>`,
23
+ "<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>",
24
+ "</head><body><main>",
25
+ `<h1>${escapeHtmlText(title)}</h1>`,
26
+ `<p>${escapeHtmlText(message)}</p>`,
27
+ "</main></body></html>",
28
+ ].join("");
29
+ res.writeHead(statusCode, {
30
+ "Content-Type": "text/html; charset=utf-8",
31
+ "Content-Length": Buffer.byteLength(html),
32
+ });
33
+ res.end(html);
34
+ }
35
+ async function githubAuthStatusRoute(ctx) {
36
+ const { req, res, deps } = ctx;
37
+ const { config, logger } = deps;
38
+ try {
39
+ const status = await getGithubAuthManager(config, logger).getStatus(resolveRequestOrigin(req, config));
40
+ sendJson(res, 200, status);
41
+ }
42
+ catch (err) {
43
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read GitHub login status");
44
+ }
45
+ }
46
+ async function githubAuthLoginRoute(ctx) {
47
+ const { req, res, deps } = ctx;
48
+ const { config, logger } = deps;
49
+ let flow;
50
+ try {
51
+ const body = await parseJsonBody(req);
52
+ if (typeof body?.flow === "string") {
53
+ flow = body.flow.trim();
54
+ }
55
+ }
56
+ catch {
57
+ // No body or invalid body: fall through to the default (device) flow.
58
+ }
59
+ const manager = getGithubAuthManager(config, logger);
60
+ try {
61
+ const loginPageUrl = resolveRequestOrigin(req, config).replace(/\/+$/, "") + "/ui/auth/github";
62
+ if (flow === "web") {
63
+ // Web flow needs a client secret for the code exchange; the device
64
+ // flow (default) is fully secretless.
65
+ const start = manager.beginLogin(resolveRequestOrigin(req, config));
66
+ sendJson(res, 200, { mode: "web", loginPageUrl, ...start });
67
+ }
68
+ else {
69
+ const start = await manager.beginDeviceLogin();
70
+ // authorizeUrl intentionally points at our standalone login page so
71
+ // older UI clients that just open response.authorizeUrl land on the
72
+ // device-code page instead of a dead web-flow URL.
73
+ sendJson(res, 200, { mode: "device", loginPageUrl, authorizeUrl: loginPageUrl, ...start });
74
+ }
75
+ logger.info(`Controller: GitHub login flow started (${flow === "web" ? "web" : "device"})`);
76
+ }
77
+ catch (err) {
78
+ sendError(res, 400, err instanceof Error ? err.message : "failed to start GitHub login");
79
+ }
80
+ }
81
+ async function githubAuthCallbackRoute(ctx) {
82
+ const { req, res, requestUrl, deps } = ctx;
83
+ const { config, logger } = deps;
84
+ const callbackError = requestUrl.searchParams.get("error");
85
+ if (callbackError) {
86
+ const description = requestUrl.searchParams.get("error_description") ?? "";
87
+ logger.warn(`Controller: GitHub login was denied (${callbackError})`);
88
+ sendGithubCallbackHtml(res, 400, "GitHub login failed", `Authorization was denied: ${callbackError}${description ? ` (${description})` : ""}`);
89
+ return;
90
+ }
91
+ const code = requestUrl.searchParams.get("code") ?? "";
92
+ const state = requestUrl.searchParams.get("state") ?? "";
93
+ try {
94
+ const account = await getGithubAuthManager(config, logger).completeLogin({
95
+ code: code || undefined,
96
+ state: state || undefined,
97
+ });
98
+ logger.info(`Controller: GitHub login completed for @${account.login}`);
99
+ sendGithubCallbackHtml(res, 200, "GitHub login successful", `Signed in as @${account.login}(GitHub 登录成功,可关闭本页返回 TeamClaw)。`);
100
+ }
101
+ catch (err) {
102
+ const message = err instanceof Error ? err.message : String(err);
103
+ logger.warn(`Controller: GitHub login callback failed: ${message}`);
104
+ sendGithubCallbackHtml(res, 400, "GitHub login failed", `${message}`);
105
+ }
106
+ }
107
+ async function githubAuthLogoutRoute(ctx) {
108
+ const { res, deps } = ctx;
109
+ const { config, logger } = deps;
110
+ try {
111
+ await getGithubAuthManager(config, logger).logout();
112
+ sendJson(res, 200, { ok: true });
113
+ }
114
+ catch (err) {
115
+ sendError(res, 500, err instanceof Error ? err.message : "failed to sign out of GitHub");
116
+ }
117
+ }
118
+ async function githubAuthRefreshRoute(ctx) {
119
+ const { res, deps } = ctx;
120
+ const { config, logger } = deps;
121
+ try {
122
+ const store = await getGithubAuthManager(config, logger).forceRefresh();
123
+ sendJson(res, 200, { ok: true, account: store.account, expiresAt: store.expiresAt });
124
+ }
125
+ catch (err) {
126
+ sendError(res, 400, err instanceof Error ? err.message : "failed to refresh the GitHub token");
127
+ }
128
+ }
129
+ export { githubAuthStatusRoute, githubAuthLoginRoute, githubAuthCallbackRoute, githubAuthLogoutRoute, githubAuthRefreshRoute, };
@@ -1,7 +1,7 @@
1
1
  import { generateId, parseJsonBody, sendError, sendJson } from "../protocol.js";
2
2
  import { ensureTeamMessageContract } from "../interaction-contracts.js";
3
3
  import { validateActiveRoleId } from "../profile-loader.js";
4
- import { normalizeClarificationQuestionSchema } from "./orchestration-manifest.js";
4
+ import { normalizeClarificationQuestionSchema } from "../shared/clarification-schema.js";
5
5
  import { cancelTaskExecution, recordTaskExecutionEvent, resetTaskForFreshAttempt, serializeTask, } from "./task-execution.js";
6
6
  import { assignTaskToWorker } from "./task-assignment.js";
7
7
  import { routeDirectMessage } from "./message-delivery.js";
@@ -0,0 +1,138 @@
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
+ /** Fields a PATCH may touch. Everything else in PluginConfig is rejected. */
28
+ const HOT_CONFIG_FIELDS = [
29
+ "workerProvisioningMaxPerRole",
30
+ "workerProvisioningMinPerRole",
31
+ "workerProvisioningIdleTtlMs",
32
+ ];
33
+ const BOUNDS = {
34
+ workerProvisioningMaxPerRole: { min: 1, max: 50 },
35
+ workerProvisioningMinPerRole: { min: 0, max: 50 },
36
+ // 1s floor keeps the idle reaper from churn-looping; 24h ceiling is generous.
37
+ workerProvisioningIdleTtlMs: { min: 1_000, max: 86_400_000 },
38
+ };
39
+ function teamConfigGetRoute(ctx) {
40
+ const { res, deps } = ctx;
41
+ const c = deps.config;
42
+ sendJson(res, 200, {
43
+ workerProvisioningType: c.workerProvisioningType,
44
+ workerProvisioningDisabled: c.workerProvisioningDisabled,
45
+ workerProvisioningMinPerRole: c.workerProvisioningMinPerRole,
46
+ workerProvisioningMaxPerRole: c.workerProvisioningMaxPerRole,
47
+ workerProvisioningIdleTtlMs: c.workerProvisioningIdleTtlMs,
48
+ // k8s controllers run on ephemeral container FS: declare it up front.
49
+ persistenceMode: c.workerProvisioningType === "kubernetes" ? "memory-only" : "host-config",
50
+ });
51
+ }
52
+ async function teamConfigPatchRoute(ctx) {
53
+ const { req, res, deps } = ctx;
54
+ let body = null;
55
+ try {
56
+ body = (await parseJsonBody(req));
57
+ }
58
+ catch {
59
+ sendError(res, 400, "invalid JSON body");
60
+ return;
61
+ }
62
+ if (!body || typeof body !== "object" || Array.isArray(body)) {
63
+ sendError(res, 400, "JSON object body required");
64
+ return;
65
+ }
66
+ const unknown = Object.keys(body).filter((k) => !HOT_CONFIG_FIELDS.includes(k));
67
+ if (unknown.length > 0) {
68
+ sendError(res, 400, `unknown or non-hot-reloadable field(s): ${unknown.join(", ")}`);
69
+ return;
70
+ }
71
+ const update = {};
72
+ for (const field of HOT_CONFIG_FIELDS) {
73
+ if (body[field] === undefined)
74
+ continue;
75
+ const raw = body[field];
76
+ if (typeof raw !== "number" || !Number.isFinite(raw)) {
77
+ sendError(res, 400, `${field} must be a finite number`);
78
+ return;
79
+ }
80
+ const { min, max } = BOUNDS[field];
81
+ update[field] = Math.max(min, Math.min(max, Math.floor(raw)));
82
+ }
83
+ if (Object.keys(update).length === 0) {
84
+ sendError(res, 400, `at least one of ${HOT_CONFIG_FIELDS.join(", ")} is required`);
85
+ return;
86
+ }
87
+ // 1) In-memory hot apply (deps.config is a live reference the provisioner
88
+ // reads on every demand computation — no restart needed).
89
+ const applied = {};
90
+ for (const [field, value] of Object.entries(update)) {
91
+ deps.config[field] = value;
92
+ applied[field] = value;
93
+ }
94
+ // Keep the min<=max invariant types.ts enforces at parse time.
95
+ const minR = update.workerProvisioningMinPerRole ?? deps.config.workerProvisioningMinPerRole;
96
+ if (deps.config.workerProvisioningMaxPerRole < minR) {
97
+ deps.config.workerProvisioningMaxPerRole = minR;
98
+ applied.workerProvisioningMaxPerRole = minR;
99
+ }
100
+ // 2) Persist (host config) unless the controller itself runs on an
101
+ // ephemeral container FS.
102
+ const memoryOnly = deps.config.workerProvisioningType === "kubernetes";
103
+ let persisted = false;
104
+ if (!memoryOnly) {
105
+ try {
106
+ await updateTeamClawProvisioningConfig(applied, {
107
+ warn: (message) => deps.logger.info(message),
108
+ });
109
+ persisted = true;
110
+ }
111
+ catch (err) {
112
+ // Memory already applied — report partial success honestly.
113
+ deps.logger.warn(`TeamClaw: hot config applied in memory but host-config persist failed: ${err instanceof Error ? err.message : String(err)}`);
114
+ }
115
+ }
116
+ // 3) Poke the provisioner so the new caps apply immediately instead of
117
+ // waiting for the next periodic reconcile tick, then tell UIs.
118
+ try {
119
+ await deps.workerProvisioningManager?.requestReconcile("team-config-hot-update");
120
+ }
121
+ catch (err) {
122
+ deps.logger.warn(`TeamClaw: config hot-update reconcile poke failed: ${err instanceof Error ? err.message : String(err)}`);
123
+ }
124
+ deps.wsServer.broadcastUpdate({ type: "team:config_updated", data: { ...applied, persisted } });
125
+ deps.logger.info(`TeamClaw: worker provisioning config hot-updated: ${JSON.stringify(applied)} (persisted=${persisted})`);
126
+ sendJson(res, 200, {
127
+ ok: true,
128
+ applied,
129
+ persisted,
130
+ persistenceMode: persisted ? "host-config" : "memory-only",
131
+ ...(persisted
132
+ ? {}
133
+ : {
134
+ restartNote: "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.",
135
+ }),
136
+ });
137
+ }
138
+ export { teamConfigGetRoute, teamConfigPatchRoute };
@@ -465,6 +465,7 @@ export async function createControllerManagedTask(input, deps) {
465
465
  recommendedSkills: normalizedRecommendedSkills.length > 0 ? normalizedRecommendedSkills : undefined,
466
466
  controllerRunId: input.createdBy === "controller" ? input.controllerRunId : undefined,
467
467
  controllerSessionKey: normalizedSessionKey,
468
+ workflow: input.workflow,
468
469
  projectId,
469
470
  projectDir,
470
471
  createdAt: now,
@@ -0,0 +1,195 @@
1
+ // Issue #226 W2 (route-table carve-up): the controller runs / projects /
2
+ // intake route handlers moved verbatim from route-table.ts (PR-D had moved
3
+ // them verbatim from http-server.ts before that) - bodies byte-identical,
4
+ // only the module home changed. route-table.ts keeps the table entries that
5
+ // bind these handlers and re-exports the retry-hint constant for
6
+ // http-server.ts's dispatch gates. Like security.ts, this module imports
7
+ // route-table.js as TYPE ONLY (RouteContext), so the module graph stays
8
+ // acyclic.
9
+ import fs from "node:fs";
10
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
11
+ import { normalizeControllerManifest } from "./orchestration-manifest.js";
12
+ import { normalizeControllerIntakeSessionKey, } from "./task-execution.js";
13
+ import { findLatestControllerRunIdForSession, syncProjectRegistryEntry, } from "./project-registry.js";
14
+ import { appendControllerRunEvent, serializeControllerRun, updateControllerRun, } from "./controller-runs.js";
15
+ import { deleteControllerRunCascade, deleteProjectCascade, resolveSafeProjectDirectory, } from "./task-cleanup.js";
16
+ import { ControllerIntakeSwitchInProgressError, reconcileControllerClarifications, runControllerIntake, } from "./controller-intake.js";
17
+ import { buildControllerManifestEventMessage } from "./controller-planning.js";
18
+ import { buildStartupReadinessMessage, shouldBlockControllerUntilProvisioningReady, } from "./worker-routes.js";
19
+ /**
20
+ * Retry hint shared by the transition-matrix gate (http-server.ts, task
21
+ * submission / repo import) and the intake handler in this module. Lived in
22
+ * route-table.ts since PR-D (the intake handler body carried it in 503
23
+ * bodies); W2 moved it here with its consumer - route-table re-exports it so
24
+ * http-server.ts's gate import is unchanged.
25
+ */
26
+ export const SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS = 5;
27
+ async function controllerManifestRoute(ctx) {
28
+ const { req, res, deps } = ctx;
29
+ const { logger, getTeamState, updateTeamState, wsServer } = deps;
30
+ const body = await parseJsonBody(req);
31
+ const sessionKey = normalizeControllerIntakeSessionKey(body.sessionKey);
32
+ const manifest = normalizeControllerManifest(body.manifest);
33
+ if (!manifest) {
34
+ sendError(res, 400, "manifest is required and must include requirementSummary");
35
+ return;
36
+ }
37
+ const runId = findLatestControllerRunIdForSession(sessionKey, deps.getTeamState(), {
38
+ preferActive: true,
39
+ });
40
+ if (!runId) {
41
+ sendError(res, 404, "Controller run not found for session");
42
+ return;
43
+ }
44
+ const updatedRun = updateControllerRun(runId, deps, (run) => {
45
+ run.manifest = manifest;
46
+ const state = deps.getTeamState();
47
+ if (state) {
48
+ const project = syncProjectRegistryEntry(state, {
49
+ projectId: manifest.projectName ?? run.projectId,
50
+ projectDir: run.projectDir ?? manifest.projectName,
51
+ aliases: [manifest.projectName, run.projectId],
52
+ summary: manifest.requirementSummary,
53
+ updatedAt: Date.now(),
54
+ });
55
+ run.projectId = project.projectId;
56
+ run.projectDir = project.projectDir;
57
+ }
58
+ if (run.projectDir) {
59
+ const state = deps.getTeamState();
60
+ if (state) {
61
+ for (const taskId of run.createdTaskIds) {
62
+ const task = state.tasks[taskId];
63
+ if (task) {
64
+ if (!task.projectDir) {
65
+ task.projectDir = run.projectDir;
66
+ }
67
+ if (!task.projectId) {
68
+ task.projectId = run.projectId;
69
+ }
70
+ }
71
+ }
72
+ }
73
+ }
74
+ appendControllerRunEvent(run, {
75
+ type: "output",
76
+ phase: "manifest_recorded",
77
+ source: "controller",
78
+ status: "running",
79
+ sessionKey,
80
+ message: buildControllerManifestEventMessage(manifest),
81
+ });
82
+ });
83
+ if (!updatedRun) {
84
+ sendError(res, 404, "Controller run not found");
85
+ return;
86
+ }
87
+ if (manifest.requirementFullyComplete) {
88
+ logger.info(`Controller: requirement fully complete for session ${sessionKey} (run ${runId})`);
89
+ wsServer.broadcastUpdate({
90
+ type: "requirement:complete",
91
+ data: {
92
+ runId,
93
+ sessionKey,
94
+ requirementSummary: manifest.requirementSummary,
95
+ },
96
+ });
97
+ }
98
+ sendJson(res, 201, {
99
+ controllerRun: serializeControllerRun(updatedRun),
100
+ manifest,
101
+ });
102
+ }
103
+ async function controllerRunsListRoute(ctx) {
104
+ const { res, deps } = ctx;
105
+ const state = reconcileControllerClarifications(deps);
106
+ const controllerRuns = state
107
+ ? Object.values(state.controllerRuns)
108
+ .sort((left, right) => right.updatedAt - left.updatedAt)
109
+ .map((run) => serializeControllerRun(run))
110
+ : [];
111
+ sendJson(res, 200, { controllerRuns });
112
+ }
113
+ async function projectDeleteRoute(ctx) {
114
+ const { res, pathname, deps } = ctx;
115
+ const projectDir = decodeURIComponent(pathname.split("/").pop());
116
+ const result = await deleteProjectCascade(projectDir, deps);
117
+ if (!result.deleted) {
118
+ sendError(res, 404, "Project not found or project cleanup could not be confirmed");
119
+ return;
120
+ }
121
+ const safeProjectPath = resolveSafeProjectDirectory(projectDir);
122
+ const stillExists = safeProjectPath ? fs.existsSync(safeProjectPath) : true;
123
+ if (stillExists) {
124
+ sendError(res, 409, "Project cleanup could not be confirmed");
125
+ return;
126
+ }
127
+ sendJson(res, 200, {
128
+ status: "deleted",
129
+ confirmed: true,
130
+ projectDir,
131
+ cleanup: result.summary,
132
+ });
133
+ }
134
+ async function controllerRunDeleteRoute(ctx) {
135
+ const { res, pathname, deps } = ctx;
136
+ const { getTeamState } = deps;
137
+ const runId = pathname.split("/").pop();
138
+ const result = await deleteControllerRunCascade(runId, deps);
139
+ if (!result.deleted) {
140
+ sendError(res, 404, "Controller run not found");
141
+ return;
142
+ }
143
+ const stillExists = !!getTeamState()?.controllerRuns[runId];
144
+ if (stillExists) {
145
+ sendError(res, 409, "Planning run cleanup could not be confirmed");
146
+ return;
147
+ }
148
+ sendJson(res, 200, {
149
+ status: "deleted",
150
+ confirmed: true,
151
+ runId,
152
+ cleanup: result.summary,
153
+ });
154
+ }
155
+ async function controllerIntakeRoute(ctx) {
156
+ const { req, res, deps, currentState } = ctx;
157
+ const { logger } = deps;
158
+ const readinessGate = shouldBlockControllerUntilProvisioningReady(deps, currentState);
159
+ if (readinessGate.blocked && readinessGate.readiness) {
160
+ sendError(res, 503, buildStartupReadinessMessage(readinessGate.readiness));
161
+ return;
162
+ }
163
+ const body = await parseJsonBody(req);
164
+ const message = typeof body.message === "string" ? body.message.trim() : "";
165
+ if (!message) {
166
+ sendError(res, 400, "message is required");
167
+ return;
168
+ }
169
+ const sessionKey = normalizeControllerIntakeSessionKey(body.sessionKey);
170
+ try {
171
+ const result = await runControllerIntake(message, sessionKey, deps);
172
+ sendJson(res, 200, result);
173
+ }
174
+ catch (err) {
175
+ if (err instanceof ControllerIntakeSwitchInProgressError) {
176
+ // Same response shape as the URL-level transition gate (503 +
177
+ // Retry-After); reachable here when a switch starts between the gate
178
+ // and the intake entry (the gate reads the state once per request).
179
+ res.setHeader("Retry-After", String(SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS));
180
+ sendJson(res, 503, {
181
+ error: err.message,
182
+ retryAfterSeconds: SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS,
183
+ transition: {
184
+ phase: err.transition.phase,
185
+ targetProfileId: err.transition.targetProfileId,
186
+ },
187
+ });
188
+ return;
189
+ }
190
+ const errorMessage = err instanceof Error ? err.message : String(err);
191
+ logger.warn(`Controller: intake failed for ${sessionKey}: ${errorMessage}`);
192
+ sendError(res, errorMessage.includes("timed out") ? 504 : 500, errorMessage);
193
+ }
194
+ }
195
+ export { controllerManifestRoute, controllerRunsListRoute, projectDeleteRoute, controllerRunDeleteRoute, controllerIntakeRoute, };
@@ -7,6 +7,8 @@ import { createControllerHttpServer } from "./http-server.js";
7
7
  // PR-C of issue #204: the assignment pipeline incl. the gated auto-assign
8
8
  // loop lives in ./task-assignment.js, not http-server.ts.
9
9
  import { autoAssignPendingTasks } from "./task-assignment.js";
10
+ // Issue #222: worker dispatch-token header helper for controller -> worker calls.
11
+ import { withWorkerDispatchToken } from "./task-execution.js";
10
12
  // PR-A of issue #204: the profile switch state machine (incl. crash resume)
11
13
  // lives in ./profile-switch.ts, not http-server.ts.
12
14
  import { resumeTeamProfileSwitch } from "./profile-switch.js";
@@ -17,7 +19,9 @@ import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey } from "
17
19
  import { ensureControllerGitRepo } from "../git-collaboration.js";
18
20
  import { WorkerProvisioningManager } from "./worker-provisioning.js";
19
21
  import { PreviewManager } from "./preview-manager.js";
20
- import { runKickoffMeeting, buildKickoffAssessmentPrompt, ASSESSMENT_TIMEOUT_MS } from "./kickoff-orchestrator.js";
22
+ import { runKickoffMeeting, ASSESSMENT_TIMEOUT_MS } from "./kickoff-orchestrator.js";
23
+ // Issue #226 W3: the kickoff prompt contract lives in the shared layer now.
24
+ import { buildKickoffAssessmentPrompt } from "../shared/kickoff-prompt.js";
21
25
  import { resolvePreferredLanAddress } from "../networking.js";
22
26
  import { createTeamAutoScheduler } from "../teamauto/scheduler.js";
23
27
  import { getGithubAuthManager } from "./github-auth.js";
@@ -105,6 +109,10 @@ export function createControllerService(deps) {
105
109
  createdAt: Date.now(),
106
110
  updatedAt: Date.now(),
107
111
  };
112
+ // W4 write-face exemption (#226): first-boot TeamState creation.
113
+ // This is initialization, not an update - the updateState entry is
114
+ // only defined below and presupposes an existing shared object. No
115
+ // WS server exists yet, so there is nothing to broadcast to.
108
116
  await saveTeamState(teamState);
109
117
  logger.info(`Controller: created new team "${config.teamName}" (profile: ${seededProfileId})`);
110
118
  }
@@ -115,11 +123,38 @@ export function createControllerService(deps) {
115
123
  logger.info(`Controller: restored team "${config.teamName}" with ${Object.keys(teamState.workers).length} workers`);
116
124
  }
117
125
  deps.onTeamStateAvailable?.(() => teamState);
118
- const updateState = (updater) => {
119
- updater(teamState);
120
- void saveTeamState(teamState);
121
- return teamState;
122
- };
126
+ // Issue #226 W4: the single TeamState write entry (see the contract
127
+ // block above). The updater stays a synchronous closure over the
128
+ // shared object; persistence - and, when requested, the WS broadcast -
129
+ // happen strictly after the updater returned. Existing one-argument
130
+ // callers keep the exact pre-W4 fire-and-forget semantics.
131
+ const updateState = ((updater, options = {}) => {
132
+ const state = teamState;
133
+ updater(state);
134
+ if (options.persist === "awaited") {
135
+ // Durability variant (profile switch): the caller owns the save
136
+ // promise - broadcast events ride its fulfillment and never fire
137
+ // on failure; rejections surface to the caller's rollback. A
138
+ // dropped handle rejects unhandled, exactly like the historical
139
+ // floating void save.
140
+ let persisted = saveTeamState(state);
141
+ if (options.broadcast?.length) {
142
+ persisted = persisted.then(() => {
143
+ for (const event of options.broadcast) {
144
+ wsServer.broadcastUpdate(event);
145
+ }
146
+ });
147
+ }
148
+ return { state, persisted };
149
+ }
150
+ void saveTeamState(state);
151
+ if (options.broadcast?.length) {
152
+ for (const event of options.broadcast) {
153
+ wsServer.broadcastUpdate(event);
154
+ }
155
+ }
156
+ return state;
157
+ });
123
158
  // Provisioned workers die with the previous gateway process. Their
124
159
  // persisted entries flip to offline once heartbeats stop but were
125
160
  // never removed, so every gateway restart accumulated ghost rows in
@@ -155,6 +190,11 @@ export function createControllerService(deps) {
155
190
  // Run ALL syncState calls (avoid || short-circuit skipping some).
156
191
  const syncC = workerProvisioningManager.syncState(teamState);
157
192
  if (repoStateChanged || syncC) {
193
+ // W4 write-face exemption (#226): startup durability barrier for the
194
+ // startup state assembly above (repo stamp + provisioning syncState's
195
+ // in-place mutations, which belong to the provisioning module). Runs
196
+ // before the WS server exists; there is no updater closure to run
197
+ // here - the mutations already happened on the shared object.
158
198
  await saveTeamState(teamState);
159
199
  }
160
200
  // Clean up orphaned tasks — tasks assigned to workers that no longer
@@ -191,6 +231,12 @@ export function createControllerService(deps) {
191
231
  }
192
232
  }
193
233
  if (orphanCleaned) {
234
+ // W4 write-face exemption (#226): startup orphan-task sweep. The
235
+ // loop above mutates in place interleaved with per-task startup
236
+ // logging; this awaited save is the pre-HTTP durability barrier -
237
+ // folding the sweep into an updater closure would reshuffle the
238
+ // startup crash-window ordering for zero convergence gain (the WS
239
+ // server does not exist yet, nothing to broadcast).
194
240
  await saveTeamState(teamState);
195
241
  }
196
242
  }
@@ -340,7 +386,8 @@ export function createControllerService(deps) {
340
386
  }
341
387
  },
342
388
  requestWorkerAssessment: async (worker, req) => {
343
- return await requestKickoffAssessment(worker, req);
389
+ // Issue #222: carry the worker's dispatch token on the assess call.
390
+ return await requestKickoffAssessment(worker, req, withWorkerDispatchToken({}, worker.id, config, teamState));
344
391
  },
345
392
  });
346
393
  return { assessments: result.plan.assessments, summary: result.summary };
@@ -404,6 +451,12 @@ export function createControllerService(deps) {
404
451
  }
405
452
  }
406
453
  if (changed) {
454
+ // W4 write-face exemption (#226): heartbeat-timeout sweep. The
455
+ // mutations interleave with per-worker WS broadcasts inside the
456
+ // synchronous loop above; this floating save is byte-for-byte the
457
+ // entry's own background semantics (void saveTeamState), so
458
+ // routing it through updateState with a no-op updater would add
459
+ // ceremony without moving any save or broadcast.
407
460
  saveTeamState(teamState);
408
461
  }
409
462
  // Runtime orphan-task reconciliation (user-found: one live worker but
@@ -442,6 +495,9 @@ export function createControllerService(deps) {
442
495
  }
443
496
  }
444
497
  if (orphaned) {
498
+ // W4 write-face exemption (#226): runtime orphan-task
499
+ // reconciliation, same sweep-interleaved-broadcast shape as the
500
+ // worker loop above (see that exemption note).
445
501
  saveTeamState(teamState);
446
502
  changed = true;
447
503
  }
@@ -491,9 +547,10 @@ function openBrowser(url, logger) {
491
547
  /**
492
548
  * Request a kickoff assessment from a worker.
493
549
  *
494
- * Request kickoff assessment from a worker over HTTP.
550
+ * Request kickoff assessment from a worker over HTTP. `authHeaders` carries
551
+ * the worker's dispatch token (issue #222) when the controller knows one.
495
552
  */
496
- async function requestKickoffAssessment(worker, requirement) {
553
+ async function requestKickoffAssessment(worker, requirement, authHeaders = {}) {
497
554
  const role = worker.role;
498
555
  const prompt = buildKickoffAssessmentPrompt(role, requirement);
499
556
  // External worker — POST to kickoff assess endpoint
@@ -505,7 +562,7 @@ async function requestKickoffAssessment(worker, requirement) {
505
562
  try {
506
563
  const res = await fetch(`${worker.url}/api/v1/kickoff/assess`, {
507
564
  method: "POST",
508
- headers: { "Content-Type": "application/json" },
565
+ headers: { "Content-Type": "application/json", ...authHeaders },
509
566
  body: JSON.stringify({ requirement, role }),
510
567
  signal: controller.signal,
511
568
  });
@@ -1,6 +1,8 @@
1
1
  import { Type } from "@sinclair/typebox";
2
2
  import { buildControllerNoWorkersMessage, hasOnDemandWorkerProvisioning, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
3
- import { normalizeClarificationQuestionSchemas, normalizeManifestCompletionOpportunities, normalizeManifestCreatedTasks, normalizeManifestDeferredTasks, normalizeManifestRoleList, normalizeManifestStringList, normalizeOptionalManifestText, } from "./orchestration-manifest.js";
3
+ import { normalizeManifestCompletionOpportunities, normalizeManifestCreatedTasks, normalizeManifestDeferredTasks, normalizeManifestRoleList, normalizeManifestStringList, } from "./orchestration-manifest.js";
4
+ // Issue #226 W3: the clarification-schema family lives in the shared layer now.
5
+ import { normalizeClarificationQuestionSchemas, normalizeOptionalManifestText, } from "../shared/clarification-schema.js";
4
6
  import { ensureTeamMessageContract, normalizeContractRole, normalizeContractStringList, } from "../interaction-contracts.js";
5
7
  // Phase 2.1 debt item 1 (P1 closeout handover): tool input validation checks
6
8
  // the ACTIVE TeamProfile's role set via the profile loader. The previous
@@ -12,7 +12,8 @@ import path from "node:path";
12
12
  * Persistence: a single JSON file under the plugin state directory
13
13
  * (`auth/github.json`, mode 0600, atomic tmp+rename writes).
14
14
  */
15
- export const DEFAULT_GITHUB_CLIENT_ID = "Iv23liqWmzrS3swGiIvK";
15
+ import { DEFAULT_GITHUB_CLIENT_ID } from "../shared/github-auth.js";
16
+ export { DEFAULT_GITHUB_CLIENT_ID };
16
17
  export const GITHUB_AUTH_CALLBACK_PATH = "/api/v1/auth/github/callback";
17
18
  export const GITHUB_CLIENT_SECRET_ENV = "TEAMCLAW_GITHUB_CLIENT_SECRET";
18
19
  const GITHUB_AUTHORIZE_URL = "https://github.com/login/oauth/authorize";