@teamclaws/teamclaw 2026.11.0 → 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 (120) hide show
  1. package/cli.mjs +272 -2
  2. package/dist/index.js +54 -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/controller-planning.js +1 -0
  7. package/dist/src/controller/controller-routes.js +195 -0
  8. package/dist/src/controller/controller-service.js +67 -10
  9. package/dist/src/controller/controller-tools.js +3 -1
  10. package/dist/src/controller/github-auth.js +2 -1
  11. package/dist/src/controller/http-server.js +51 -16
  12. package/dist/src/controller/kickoff-orchestrator.js +3 -39
  13. package/dist/src/controller/message-delivery.js +4 -1
  14. package/dist/src/controller/orchestration-manifest.js +5 -65
  15. package/dist/src/controller/preview-manager.js +51 -3
  16. package/dist/src/controller/profile-switch.js +42 -22
  17. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  18. package/dist/src/controller/provisioning/container-shared.js +64 -0
  19. package/dist/src/controller/provisioning/docker.js +214 -0
  20. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  21. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  22. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  23. package/dist/src/controller/provisioning-config.js +239 -0
  24. package/dist/src/controller/repo-routes.js +70 -4
  25. package/dist/src/controller/report-routes.js +56 -0
  26. package/dist/src/controller/route-table.js +67 -1045
  27. package/dist/src/controller/security.js +775 -0
  28. package/dist/src/controller/status-routes.js +287 -0
  29. package/dist/src/controller/task-assignment.js +5 -2
  30. package/dist/src/controller/task-execution.js +31 -0
  31. package/dist/src/controller/task-results.js +10 -0
  32. package/dist/src/controller/tunnel-manager.js +41 -8
  33. package/dist/src/controller/tunnel-routes.js +225 -0
  34. package/dist/src/controller/websocket.js +6 -2
  35. package/dist/src/controller/webui-routes.js +49 -0
  36. package/dist/src/controller/worker-provisioning.js +39 -949
  37. package/dist/src/controller/workflow-routes.js +407 -0
  38. package/dist/src/controller/workspace-routes.js +200 -0
  39. package/dist/src/git-collaboration.js +4 -9
  40. package/dist/src/identity.js +12 -1
  41. package/dist/src/profile-loader.js +119 -1
  42. package/dist/src/profiles/banking.json +26 -2
  43. package/dist/src/profiles/schema.json +82 -2
  44. package/dist/src/prompt-policy.js +18 -6
  45. package/dist/src/protocol.js +66 -3
  46. package/dist/src/shared/clarification-schema.js +65 -0
  47. package/dist/src/shared/github-auth.js +15 -0
  48. package/dist/src/shared/kickoff-prompt.js +37 -0
  49. package/dist/src/shared/utils.js +47 -0
  50. package/dist/src/state.js +89 -3
  51. package/dist/src/types.js +15 -1
  52. package/dist/src/ui/app.js +846 -62
  53. package/dist/src/ui/github-login.html +1 -0
  54. package/dist/src/ui/index.html +102 -36
  55. package/dist/src/worker/http-handler.js +59 -0
  56. package/dist/src/worker/skill-installer.js +3 -9
  57. package/dist/src/worker/tools.js +20 -10
  58. package/dist/src/worker/worker-service.js +17 -4
  59. package/index.ts +61 -32
  60. package/openclaw.plugin.json +23 -2
  61. package/package.json +1 -1
  62. package/src/config.ts +24 -0
  63. package/src/controller/auth-routes.ts +157 -0
  64. package/src/controller/clarification-routes.ts +1 -1
  65. package/src/controller/controller-planning.ts +8 -0
  66. package/src/controller/controller-routes.ts +237 -0
  67. package/src/controller/controller-service.ts +128 -10
  68. package/src/controller/controller-tools.ts +5 -2
  69. package/src/controller/github-auth.ts +28 -63
  70. package/src/controller/http-server.ts +66 -17
  71. package/src/controller/kickoff-orchestrator.ts +3 -42
  72. package/src/controller/message-delivery.ts +4 -1
  73. package/src/controller/orchestration-manifest.ts +8 -71
  74. package/src/controller/preview-manager.ts +53 -3
  75. package/src/controller/profile-switch.ts +53 -23
  76. package/src/controller/provisioning/backend-contract.ts +51 -0
  77. package/src/controller/provisioning/container-shared.ts +84 -0
  78. package/src/controller/provisioning/docker.ts +260 -0
  79. package/src/controller/provisioning/kubernetes.ts +263 -0
  80. package/src/controller/provisioning/plugin-root.ts +42 -0
  81. package/src/controller/provisioning/process-supervisor.ts +214 -0
  82. package/src/controller/provisioning-config.ts +289 -0
  83. package/src/controller/repo-routes.ts +84 -12
  84. package/src/controller/report-routes.ts +64 -0
  85. package/src/controller/route-table.ts +133 -1152
  86. package/src/controller/security.ts +899 -0
  87. package/src/controller/status-routes.ts +354 -0
  88. package/src/controller/task-assignment.ts +5 -1
  89. package/src/controller/task-execution.ts +43 -0
  90. package/src/controller/task-results.ts +12 -0
  91. package/src/controller/tunnel-manager.ts +45 -8
  92. package/src/controller/tunnel-routes.ts +231 -0
  93. package/src/controller/websocket.ts +19 -3
  94. package/src/controller/webui-routes.ts +55 -0
  95. package/src/controller/worker-provisioning.ts +51 -1117
  96. package/src/controller/workflow-routes.ts +498 -0
  97. package/src/controller/workspace-routes.ts +222 -0
  98. package/src/git-collaboration.ts +4 -9
  99. package/src/identity.ts +13 -1
  100. package/src/profile-loader.ts +167 -1
  101. package/src/profiles/banking.json +26 -2
  102. package/src/profiles/schema.json +82 -2
  103. package/src/prompt-policy.ts +19 -6
  104. package/src/protocol.ts +72 -2
  105. package/src/shared/clarification-schema.ts +81 -0
  106. package/src/shared/github-auth.ts +92 -0
  107. package/src/shared/kickoff-prompt.ts +47 -0
  108. package/src/shared/utils.ts +51 -0
  109. package/src/state.ts +92 -3
  110. package/src/teamauto/github-client.ts +2 -1
  111. package/src/teamauto/repo-sync.ts +2 -1
  112. package/src/teamauto/scheduler.ts +2 -1
  113. package/src/types.ts +130 -1
  114. package/src/ui/app.js +846 -62
  115. package/src/ui/github-login.html +1 -0
  116. package/src/ui/index.html +102 -36
  117. package/src/worker/http-handler.ts +64 -1
  118. package/src/worker/skill-installer.ts +3 -9
  119. package/src/worker/tools.ts +21 -10
  120. package/src/worker/worker-service.ts +18 -4
@@ -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";
@@ -6,17 +6,25 @@
6
6
  // ./route-table.ts, PR-D) and every handler body lives in a domain module.
7
7
  // Request pipeline, in order:
8
8
  //
9
- // 1. CORS preflight (OPTIONS short-circuit)
10
- // 2. Tunnel gate (viaTunnel classification: gate page routes / gate
9
+ // 1. CORS preflight (OPTIONS short-circuit; wildcard while device
10
+ // protection is off - the historical behavior - and narrowed to the
11
+ // UI's own origin once it is on)
12
+ // 2. Device-auth gate (issue #23, ./security.ts createSecurityMiddleware):
13
+ // zero-op while no devices are paired (L0); once devices exist every
14
+ // non-exempt /api request must present a valid device token and the
15
+ // response CORS policy is pinned before dispatch. Runs BEFORE the
16
+ // tunnel gate and the handleRequest gates so transition/capability/
17
+ // tunnel-management responses never leak to unpaired callers.
18
+ // 3. Tunnel gate (viaTunnel classification: gate page routes / gate
11
19
  // cookie 403 / tunnel management API - tables in ./route-table.ts)
12
- // 3. handleRequest gates (verbatim, NOT part of the route table):
20
+ // 4. handleRequest gates (verbatim, NOT part of the route table):
13
21
  // a. profile-switch transition matrix (409 worker re-register,
14
22
  // 503+Retry-After task submission / repo import)
15
23
  // b. capability 404 gates (steady-state existence gate, after (a) on
16
24
  // purpose: transition semantics win over the 404)
17
- // 4. declarative route table match (./route-table.ts, array order =
25
+ // 5. declarative route table match (./route-table.ts, array order =
18
26
  // the historical if/startsWith chain, one-to-one)
19
- // 5. fall-through 404
27
+ // 6. fall-through 404
20
28
  //
21
29
  // Domain module index (the 18 modules this root composes; none of them may
22
30
  // import this file):
@@ -47,6 +55,12 @@ import { createTunnelManager, gatePageHtml } from "./tunnel-manager.js";
47
55
  // (route-table imports this file as TYPE ONLY), so the module graph stays
48
56
  // acyclic.
49
57
  import { controllerRouteTable, createTunnelGateRoutes, createTunnelManagementRoutes, dispatchRoutes, SWITCH_TASK_SUBMISSION_RETRY_AFTER_SECONDS, } from "./route-table.js";
58
+ // Issue #23 (backend wave): the device-pairing security module owns the
59
+ // auth middleware, the CORS narrowing policy, the WS upgrade guard and the
60
+ // pairing handlers (registered via route-table.ts). This file only wires
61
+ // them into the pipeline below - all pathname/method policy lives in
62
+ // security.ts.
63
+ import { classifySecurityPeer, corsPreflightDecision, createSecurityMiddleware, createWebSocketUpgradeGuard, isProtectionOn, } from "./security.js";
50
64
  // ===========================================================================
51
65
  // Team profile switch dispatch-layer constants (Phase 2.1,
52
66
  // vertical-team-profiles-design.md 2.3). The six-step switch machine itself
@@ -123,14 +137,17 @@ export function createControllerHttpServer(deps) {
123
137
  // Tunnel-side route tables are built once (lazily, next to the lazy
124
138
  // tunnel manager singleton they close over) and reused for every request.
125
139
  let tunnelRoutesSingleton = null;
140
+ // Issue #23: the device gate. Zero-friction ladder - while no device is
141
+ // paired (protection off) this is a no-op passthrough (L0, the exact
142
+ // pre-issue behavior); once devices exist it enforces per-device tokens
143
+ // on every non-exempt /api route (exemptions and 401 shape in security.ts).
144
+ const securityGate = createSecurityMiddleware(deps);
126
145
  const server = http.createServer(async (req, res) => {
127
- // CORS preflight
146
+ // CORS preflight (issue #23: wildcard while protection is off - the
147
+ // historical bytes - and narrowed to the UI's own origin once on).
128
148
  if (req.method === "OPTIONS") {
129
- res.writeHead(200, {
130
- "Access-Control-Allow-Origin": "*",
131
- "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
132
- "Access-Control-Allow-Headers": "Content-Type",
133
- });
149
+ const decision = corsPreflightDecision(req, isProtectionOn(deps.getTeamState()));
150
+ res.writeHead(decision.status, decision.headers);
134
151
  res.end();
135
152
  return;
136
153
  }
@@ -154,6 +171,17 @@ export function createControllerHttpServer(deps) {
154
171
  req, res, requestUrl: url, pathname, deps, currentState: null,
155
172
  };
156
173
  const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
174
+ // ==================== Device auth gate (issue #23) ====================
175
+ // Runs BEFORE the tunnel gate tables, the transition matrix and the
176
+ // capability gates so none of those surfaces answer - or leak response
177
+ // shape information - to unpaired callers while protection is on.
178
+ // Requests arriving through the sharing tunnel are classified from the
179
+ // Host header (cloudflared dials in from loopback, so the socket peer
180
+ // address would lie); see classifySecurityPeer in ./security.ts.
181
+ const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
182
+ if (!securityGate(req, res, pathname, peer)) {
183
+ return;
184
+ }
157
185
  if (viaTunnel) {
158
186
  if (await dispatchRoutes(tunnelRoutesSingleton.gate, tunnelCtx)) {
159
187
  return;
@@ -170,15 +198,22 @@ export function createControllerHttpServer(deps) {
170
198
  }
171
199
  }
172
200
  try {
173
- await handleRequest(req, res, pathname, deps);
201
+ await handleRequest(req, res, pathname, deps, peer);
174
202
  }
175
203
  catch (err) {
176
204
  logger.error(`Controller HTTP error: ${err instanceof Error ? err.message : String(err)}`);
177
205
  sendError(res, 500, "Internal server error");
178
206
  }
179
207
  });
180
- // Attach WebSocket
181
- wsServer.attach(server);
208
+ // Attach WebSocket (issue #23: while device protection is on, upgrades
209
+ // must carry a valid device token - ?token= query for browsers, cookie /
210
+ // Bearer for native clients; see createWebSocketUpgradeGuard).
211
+ wsServer.attach(server, {
212
+ verifyUpgrade: createWebSocketUpgradeGuard({
213
+ ...deps,
214
+ isTunnelHost: (host) => tunnelManagerSingleton?.isTunnelRequest(host) ?? false,
215
+ }),
216
+ });
182
217
  // Plugin shutdown: kill the local connector and tear down the remote
183
218
  // tunnel so gateway exits never leak orphan cloudflared processes.
184
219
  server.on("close", () => {
@@ -206,7 +241,7 @@ export function createControllerHttpServer(deps) {
206
241
  }, 2000);
207
242
  return server;
208
243
  }
209
- async function handleRequest(req, res, pathname, deps) {
244
+ async function handleRequest(req, res, pathname, deps, peer) {
210
245
  const requestUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
211
246
  const currentState = deps.getTeamState();
212
247
  // ==================== Profile switch concurrency matrix ====================
@@ -276,7 +311,7 @@ async function handleRequest(req, res, pathname, deps) {
276
311
  // false) to continue matching; an exhausted table falls through to the
277
312
  // final 404 below - both semantics are preserved from the old chain.
278
313
  const handled = await dispatchRoutes(controllerRouteTable, {
279
- req, res, requestUrl, pathname, deps, currentState,
314
+ req, res, requestUrl, pathname, deps, currentState, peer,
280
315
  });
281
316
  if (!handled) {
282
317
  sendError(res, 404, "Not found");
@@ -16,6 +16,9 @@
16
16
  */
17
17
  // Phase 1.3: role data comes from the active TeamProfile loader.
18
18
  import { getActiveDefaultRole, getActiveRole, getActiveRoleIds, validateActiveRoleId } from "../profile-loader.js";
19
+ // W6 of issue #226: the local sleep copy (byte-identical to the shared one)
20
+ // was removed in favor of shared/utils.js.
21
+ import { sleep } from "../shared/utils.js";
19
22
  import { inferTaskRoleWithConfidence } from "./role-inference.js";
20
23
  // ── Constants ────────────────────────────────────────────────────────────────
21
24
  /** Maximum time to wait for all workers to register after provisioning. */
@@ -180,45 +183,6 @@ function buildKickoffSummary(plan, _requirement) {
180
183
  parts.push("Use these team assessments to create the final execution plan. Only create tasks for roles that confirmed they are needed. Respect the dependency ordering suggested by the team.");
181
184
  return parts.join("\n");
182
185
  }
183
- /**
184
- * Build the kickoff assessment prompt sent to a worker.
185
- * The worker should respond with structured JSON matching KickoffAssessment.
186
- */
187
- export function buildKickoffAssessmentPrompt(role, requirement) {
188
- const roleDef = getActiveRole(role);
189
- const roleLabel = roleDef?.label ?? role;
190
- return [
191
- `You are the ${roleLabel} in a virtual software team.`,
192
- `Your team is conducting a kickoff meeting for a new requirement.`,
193
- ``,
194
- `## Requirement`,
195
- requirement,
196
- ``,
197
- `## Your Task`,
198
- `Evaluate this requirement from your professional perspective as ${roleLabel}.`,
199
- `Respond with a JSON object (and nothing else) with these fields:`,
200
- ``,
201
- `{`,
202
- ` "needed": boolean, // Is your role needed for this project?`,
203
- ` "scope": string, // What would you contribute? (1-2 sentences)`,
204
- ` "suggestedTasks": string[], // Specific tasks you'd handle (2-5 items)`,
205
- ` "dependencies": string[], // What you need from other roles before or during your work`,
206
- ` "risks": string[], // Concerns or risks from your perspective`,
207
- ` "questions": string[] // Clarifications you'd want before starting`,
208
- `}`,
209
- ``,
210
- `Guidelines:`,
211
- `- Be honest about whether your role is truly needed. Don't inflate your importance.`,
212
- `- For "needed", consider: does the project actually require ${roleLabel}-level expertise?`,
213
- `- A simple single-file script does NOT need an architect. A TODO app does NOT need a security engineer.`,
214
- `- Keep suggestedTasks concrete and actionable, not vague.`,
215
- `- Only list dependencies on roles that are actually relevant.`,
216
- `- Return ONLY the JSON object, no markdown fencing, no explanation.`,
217
- ].join("\n");
218
- }
219
- function sleep(ms) {
220
- return new Promise((resolve) => setTimeout(resolve, ms));
221
- }
222
186
  export async function resolveTaskRoleWithLlmFallback(task, deps = {}) {
223
187
  const verdict = (deps.inferWithConfidence ?? inferTaskRoleWithConfidence)(task);
224
188
  if (!verdict.needsLlmFallback) {
@@ -1,7 +1,10 @@
1
+ import { withWorkerDispatchToken } from "./task-execution.js";
1
2
  export async function deliverMessageToWorker(worker, message, deps) {
3
+ // Issue #222: carry the worker's dispatch token so a token-paired worker
4
+ // accepts the injection; L0 sends the historical header set unchanged.
2
5
  const res = await fetch(`${worker.url}/api/v1/messages`, {
3
6
  method: "POST",
4
- headers: { "Content-Type": "application/json" },
7
+ headers: withWorkerDispatchToken({ "Content-Type": "application/json" }, worker.id, deps.config, deps.getTeamState()),
5
8
  body: JSON.stringify(message),
6
9
  });
7
10
  if (!res.ok) {
@@ -1,5 +1,10 @@
1
1
  import { validateRoleIdList } from "../roles.js";
2
2
  import { deriveStableProjectKey } from "../openclaw-workspace.js";
3
+ // Issue #226 W3: the clarification-schema normalization family moved to the
4
+ // shared layer (worker/tools.ts consumes it; the worker must not import the
5
+ // controller tree). This module keeps the manifest-specific normalizers and
6
+ // imports the shared contract — controller -> shared direction only.
7
+ import { normalizeClarificationQuestionSchemas, normalizeOptionalManifestText, } from "../shared/clarification-schema.js";
3
8
  export function normalizeManifestRoleList(raw) {
4
9
  // Phase 0.3: delegates to the shared validateRoleIdList guard in roles.ts.
5
10
  // The hand-written TEAMCLAW_ROLE_IDS copy this function used to keep was
@@ -15,71 +20,6 @@ export function normalizeManifestStringList(raw) {
15
20
  .map((entry) => (typeof entry === "string" ? entry.trim() : ""))
16
21
  .filter(Boolean);
17
22
  }
18
- export function normalizeOptionalManifestText(raw) {
19
- if (typeof raw !== "string") {
20
- return undefined;
21
- }
22
- const normalized = raw.trim();
23
- return normalized || undefined;
24
- }
25
- export function normalizeClarificationOptions(raw) {
26
- if (!Array.isArray(raw)) {
27
- return [];
28
- }
29
- return raw
30
- .filter((entry) => !!entry && typeof entry === "object")
31
- .map((entry) => ({
32
- value: typeof entry.value === "string" ? entry.value.trim() : "",
33
- label: typeof entry.label === "string" ? entry.label.trim() : "",
34
- hint: typeof entry.hint === "string" && entry.hint.trim() ? entry.hint.trim() : undefined,
35
- }))
36
- .filter((entry) => entry.value && entry.label);
37
- }
38
- export function normalizeClarificationQuestionSchema(raw) {
39
- if (!raw || typeof raw !== "object") {
40
- return undefined;
41
- }
42
- const input = raw;
43
- const kind = typeof input.kind === "string" ? input.kind.trim() : "";
44
- const title = typeof input.title === "string" ? input.title.trim() : "";
45
- if (!title || !["single-select", "multi-select", "number", "text"].includes(kind)) {
46
- return undefined;
47
- }
48
- const options = normalizeClarificationOptions(input.options);
49
- const schema = {
50
- kind: kind,
51
- title,
52
- description: normalizeOptionalManifestText(input.description),
53
- required: input.required == null ? true : Boolean(input.required),
54
- allowOther: Boolean(input.allowOther),
55
- placeholder: normalizeOptionalManifestText(input.placeholder),
56
- unit: normalizeOptionalManifestText(input.unit),
57
- };
58
- if (options.length > 0) {
59
- schema.options = options;
60
- }
61
- if (typeof input.min === "number" && Number.isFinite(input.min)) {
62
- schema.min = input.min;
63
- }
64
- if (typeof input.max === "number" && Number.isFinite(input.max)) {
65
- schema.max = input.max;
66
- }
67
- if (typeof input.step === "number" && Number.isFinite(input.step)) {
68
- schema.step = input.step;
69
- }
70
- if ((schema.kind === "single-select" || schema.kind === "multi-select") && (!schema.options || schema.options.length === 0)) {
71
- return undefined;
72
- }
73
- return schema;
74
- }
75
- export function normalizeClarificationQuestionSchemas(raw) {
76
- if (!Array.isArray(raw)) {
77
- return [];
78
- }
79
- return raw
80
- .map((entry) => normalizeClarificationQuestionSchema(entry))
81
- .filter((entry) => Boolean(entry));
82
- }
83
23
  export function normalizeManifestCreatedTasks(raw) {
84
24
  if (!Array.isArray(raw)) {
85
25
  return [];