@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,354 @@
1
+ // Issue #226 W2 (route-table carve-up): the team status / roles / profiles /
2
+ // profile-switch / archived-teams / stats route handlers (plus their private
3
+ // helpers: team stats computation and the external-worker install command
4
+ // builder with its shell-escape and LAN-URL helpers) moved verbatim from
5
+ // route-table.ts (PR-D had moved them verbatim from http-server.ts before
6
+ // that) - bodies byte-identical, only the module home changed. route-table.ts
7
+ // keeps the table entries that bind these handlers. Like security.ts, this
8
+ // module imports route-table.js as TYPE ONLY (RouteContext), so the module
9
+ // graph stays acyclic.
10
+ import type { IncomingMessage } from "node:http";
11
+ import type { PluginConfig, TeamProvisioningState, TeamState } from "../types.js";
12
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
13
+ import { listArchivedTeams } from "../state.js";
14
+ import {
15
+ BUILTIN_PROFILES,
16
+ getActiveProfile,
17
+ getActiveRoles,
18
+ getActiveDefaultRole,
19
+ hasProfile,
20
+ } from "../profile-loader.js";
21
+ import { getTeamClawModelReadiness } from "../openclaw-workspace.js";
22
+ import { resolvePreferredLanAddress } from "../networking.js";
23
+ import { serializeTask } from "./task-execution.js";
24
+ import { serializeControllerRun } from "./controller-runs.js";
25
+ import { reconcileControllerClarifications } from "./controller-intake.js";
26
+ import { getEffectiveStartupReadiness } from "./worker-routes.js";
27
+ import { buildTeamStatusSecurity } from "./security.js";
28
+ // PR-A of issue #204: the six-step switch state machine lives in
29
+ // ./profile-switch.ts; the POST endpoint below only runs step 1 (persist +
30
+ // announce) and hands off to startTeamProfileSwitch.
31
+ import { startTeamProfileSwitch } from "./profile-switch.js";
32
+ import type { RouteContext } from "./route-table.js";
33
+
34
+ type TeamStatsResponse = {
35
+ totalWorkers: number;
36
+ workersByStatus: { idle: number; busy: number; offline: number };
37
+ totalTasks: number;
38
+ tasksByStatus: Record<string, number>;
39
+ averageTaskDuration: number | null;
40
+ uptime: number;
41
+ };
42
+
43
+ // PR-D note: computeTeamStats used to be declared INSIDE handleRequest
44
+ // (between task-route shells); hoisted to module scope by PR-D, moved to
45
+ // this module by W2 - body unchanged, single call site unchanged.
46
+ function computeTeamStats(state: TeamState): TeamStatsResponse {
47
+ const workers = Object.values(state.workers);
48
+ const tasks = Object.values(state.tasks);
49
+
50
+ const workersByStatus = { idle: 0, busy: 0, offline: 0 };
51
+ for (const worker of workers) {
52
+ workersByStatus[worker.status] += 1;
53
+ }
54
+
55
+ const tasksByStatus: Record<string, number> = {};
56
+ for (const task of tasks) {
57
+ tasksByStatus[task.status] = (tasksByStatus[task.status] ?? 0) + 1;
58
+ }
59
+
60
+ const completedTasks = tasks.filter(
61
+ (task) => task.status === "completed" && task.startedAt && task.completedAt,
62
+ );
63
+ const averageTaskDuration = completedTasks.length > 0
64
+ ? completedTasks.reduce((sum, task) => sum + (task.completedAt! - task.startedAt!), 0) / completedTasks.length
65
+ : null;
66
+
67
+ return {
68
+ totalWorkers: workers.length,
69
+ workersByStatus,
70
+ totalTasks: tasks.length,
71
+ tasksByStatus,
72
+ averageTaskDuration,
73
+ uptime: process.uptime() * 1000,
74
+ };
75
+ }
76
+
77
+ const EXTERNAL_WORKER_INSTALL_SPEC = "@teamclaws/teamclaw";
78
+
79
+ function shellEscapeSingleQuotes(value: string): string {
80
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
81
+ }
82
+
83
+ function resolveRequestPort(req: IncomingMessage, fallbackPort: number): number {
84
+ const hostHeader = req.headers.host?.trim();
85
+ if (!hostHeader) {
86
+ return fallbackPort;
87
+ }
88
+ try {
89
+ const parsed = new URL(`http://${hostHeader}`);
90
+ return parsed.port ? Number(parsed.port) : fallbackPort;
91
+ } catch {
92
+ return fallbackPort;
93
+ }
94
+ }
95
+
96
+ function resolveRecommendedLanControllerUrl(req: IncomingMessage, fallbackPort: number): string {
97
+ const port = resolveRequestPort(req, fallbackPort);
98
+ const preferredLan = resolvePreferredLanAddress();
99
+ return preferredLan ? `http://${preferredLan}:${port}` : "";
100
+ }
101
+
102
+ /**
103
+ * Issue #255 P0-1: GET /team/status is unauthenticated at L0 and reachable by
104
+ * every LAN peer; spreading state.provisioning verbatim (the historical
105
+ * behavior) published each managed worker's plaintext launchToken - a bearer
106
+ * credential for worker registration. Consumers of this response (web UI
107
+ * src/src/ui/app.js, desktop renderer) read worker metadata and readiness
108
+ * only - none reads launchToken (verified by grep; the worker itself gets the
109
+ * token out-of-band via the TEAMCLAW_LAUNCH_TOKEN env at launch). So the wire
110
+ * copy drops the token field; the controller keeps the full record in memory
111
+ * and in TeamState.
112
+ */
113
+ function serializeProvisioningForStatus(
114
+ provisioning: TeamProvisioningState | undefined,
115
+ startupReadiness: ReturnType<typeof getEffectiveStartupReadiness>,
116
+ ): Record<string, unknown> {
117
+ const workers = Object.fromEntries(
118
+ Object.entries(provisioning?.workers ?? {}).map(([workerId, record]) => {
119
+ const { launchToken: _redacted, ...safeRecord } = record;
120
+ return [workerId, safeRecord];
121
+ }),
122
+ );
123
+ return { ...(provisioning ?? { workers: {} }), workers, startupReadiness };
124
+ }
125
+
126
+ function buildExternalWorkerInstallInfo(req: IncomingMessage, config: PluginConfig): Record<string, unknown> {
127
+ const recommendedControllerUrl = resolveRecommendedLanControllerUrl(req, config.port);
128
+ return {
129
+ teamName: config.teamName,
130
+ recommendedControllerUrl,
131
+ defaultRole: getActiveDefaultRole(),
132
+ roles: getActiveRoles().map((role) => ({ id: role.id, label: role.label, icon: role.icon })),
133
+ autoDiscoveryCommandPrefix:
134
+ `npx -y ${EXTERNAL_WORKER_INSTALL_SPEC} install --yes --install-mode worker --team-name ${shellEscapeSingleQuotes(config.teamName)} --worker-role `,
135
+ manualCommandPrefix:
136
+ `npx -y ${EXTERNAL_WORKER_INSTALL_SPEC} install --yes --install-mode worker --team-name ${shellEscapeSingleQuotes(config.teamName)} --worker-role `,
137
+ manualControllerUrlFlag: recommendedControllerUrl
138
+ ? ` --controller-url ${shellEscapeSingleQuotes(recommendedControllerUrl)}`
139
+ : "",
140
+ manualControllerWarning: recommendedControllerUrl
141
+ ? "Manual worker installs must use the controller LAN IP, not localhost/127.0.0.1."
142
+ : "No private LAN IPv4 address was detected on this controller host yet, so manual worker install commands are unavailable until a LAN address exists.",
143
+ autoDiscoveryWarning: "mDNS auto-discovery only works when the worker and controller are reachable on the same LAN.",
144
+ };
145
+ }
146
+
147
+ async function teamStatusRoute(ctx: RouteContext): Promise<void> {
148
+ const { req, res, deps } = ctx;
149
+ const { config } = deps;
150
+ const state = reconcileControllerClarifications(deps);
151
+ const startupReadiness = getEffectiveStartupReadiness(deps, state);
152
+ const modelReadiness = getTeamClawModelReadiness();
153
+ const externalWorkerInstall = buildExternalWorkerInstallInfo(req, config);
154
+ if (!state) {
155
+ sendJson(res, 200, {
156
+ teamName: config.teamName,
157
+ workers: [],
158
+ tasks: [],
159
+ controllerRuns: [],
160
+ messages: [],
161
+ clarifications: [],
162
+ previews: [],
163
+ repo: null,
164
+ pendingClarificationCount: 0,
165
+ modelReadiness,
166
+ externalWorkerInstall,
167
+ // No team state = no provisioning workers; only readiness rides along
168
+ // (still through the redacting serializer so the shape stays uniform).
169
+ provisioning: startupReadiness
170
+ ? serializeProvisioningForStatus(undefined, startupReadiness)
171
+ : undefined,
172
+ security: buildTeamStatusSecurity(null),
173
+ });
174
+ return;
175
+ }
176
+
177
+ const clarifications = Object.values(state.clarifications).sort((left, right) => right.createdAt - left.createdAt);
178
+ sendJson(res, 200, {
179
+ teamName: state.teamName,
180
+ workers: Object.values(state.workers),
181
+ tasks: Object.values(state.tasks).map((task) => serializeTask(task)),
182
+ controllerRuns: Object.values(state.controllerRuns)
183
+ .sort((left, right) => right.updatedAt - left.updatedAt)
184
+ .map((run) => serializeControllerRun(run)),
185
+ messages: state.messages,
186
+ clarifications,
187
+ previews: Object.values(state.previews ?? {}),
188
+ repo: state.repo ?? null,
189
+ modelReadiness,
190
+ externalWorkerInstall,
191
+ // Issue #255 P0-1: provisioning goes through the redacting serializer -
192
+ // the raw spread leaked per-worker plaintext launchTokens to the LAN.
193
+ provisioning: serializeProvisioningForStatus(state.provisioning, startupReadiness),
194
+ taskCount: Object.keys(state.tasks).length,
195
+ workerCount: Object.keys(state.workers).length,
196
+ pendingClarificationCount: clarifications.filter((item) => item.status === "pending").length,
197
+ // Issue #23: device-pairing protection state + the non-LAN-peer
198
+ // suggestion signal (additive field; consumers ignore it pre-issue).
199
+ security: buildTeamStatusSecurity(state),
200
+ });
201
+ }
202
+
203
+ function teamRolesRoute(ctx: RouteContext): void {
204
+ const { res } = ctx;
205
+ sendJson(res, 200, { roles: getActiveRoles(), defaultRole: getActiveDefaultRole() });
206
+ }
207
+
208
+ // GET /api/v1/profiles — list the available team profile packages
209
+ // (Phase 2.1, design section 4: the switcher UI reads this list).
210
+ function teamProfilesListRoute(ctx: RouteContext): void {
211
+ const { res } = ctx;
212
+ const profiles = [...BUILTIN_PROFILES.values()]
213
+ .sort((a, b) => a.id.localeCompare(b.id))
214
+ .map((profile) => ({
215
+ id: profile.id,
216
+ name: profile.name,
217
+ nameZh: profile.nameZh,
218
+ icon: profile.icon,
219
+ industry: profile.industry,
220
+ description: profile.description,
221
+ roleCount: profile.roles.length,
222
+ version: profile.version,
223
+ // Capability switches ride along so the switcher confirm step can
224
+ // warn that off -> on flips need a gateway restart to take effect
225
+ // (subsystems are wired at controller startup only; runtime teardown
226
+ // is one-directional). Additive field - existing consumers ignore it.
227
+ capabilities: profile.capabilities,
228
+ ...(profile.reviewedBy ? { reviewedBy: profile.reviewedBy } : {}),
229
+ }));
230
+ sendJson(res, 200, { profiles });
231
+ }
232
+
233
+ // GET /api/v1/team/profile — active profile detail incl. capabilities
234
+ // (design section 4: UI hides capability-gated entries based on this).
235
+ function teamProfileGetRoute(ctx: RouteContext): void {
236
+ const { res, deps } = ctx;
237
+ const { config } = deps;
238
+ const state = deps.getTeamState();
239
+ const profile = getActiveProfile();
240
+ sendJson(res, 200, {
241
+ profileId: state?.profileId ?? profile.id,
242
+ profile,
243
+ teamName: state?.teamName ?? config.teamName,
244
+ transition: state?.transition ?? null,
245
+ });
246
+ }
247
+
248
+ // POST /api/v1/team/profile { profileId } — six-step switch semantics
249
+ // (Phase 2.1, design section 2.3). Returns 202; progress arrives via the
250
+ // team.switch_started / team.switch_completed WS events.
251
+ async function teamProfileSwitchRoute(ctx: RouteContext): Promise<void> {
252
+ const { req, res, deps } = ctx;
253
+ const { config, logger, getTeamState, updateTeamState } = deps;
254
+ let body: Record<string, unknown>;
255
+ try {
256
+ body = await parseJsonBody(req);
257
+ } catch (error) {
258
+ // #251 L6: a malformed request body is a client error (400), not a
259
+ // top-level 500 - parseJsonBody throws "Invalid JSON body: ...".
260
+ sendError(res, 400, error instanceof Error ? error.message : "invalid JSON body");
261
+ return;
262
+ }
263
+ const profileId = typeof body.profileId === "string" ? body.profileId.trim() : "";
264
+ if (!profileId || !hasProfile(profileId)) {
265
+ sendError(
266
+ res,
267
+ 404,
268
+ `unknown team profile "${profileId || "<empty>"}" (available: ${[...BUILTIN_PROFILES.keys()].sort().join(", ")})`,
269
+ );
270
+ return;
271
+ }
272
+ const state = getTeamState();
273
+ if (!state) {
274
+ sendError(res, 503, "Team state not loaded");
275
+ return;
276
+ }
277
+ if (state.transition) {
278
+ sendJson(res, 409, {
279
+ error: `a team profile switch to "${state.transition.targetProfileId}" is already in progress (phase: ${state.transition.phase})`,
280
+ transition: state.transition,
281
+ });
282
+ return;
283
+ }
284
+
285
+ // Step 1: persist the transition (the crash-resume truth) and announce.
286
+ // The check-and-set above plus this mutation run without an await in
287
+ // between, so a concurrent second POST observes the transition (409).
288
+ // W4 (#226): mutation, awaited persistence and the switch_started
289
+ // broadcast all ride the single write entry - the broadcast fires from
290
+ // the save's fulfillment, so nothing is announced before the transition
291
+ // is durable, and it never fires when the write fails.
292
+ const previousProfileId = state.profileId;
293
+ const { persisted } = updateTeamState((s) => {
294
+ s.transition = { phase: "draining", targetProfileId: profileId, startedAt: Date.now() };
295
+ }, {
296
+ persist: "awaited",
297
+ broadcast: [{ type: "team.switch_started", data: { profileId, previousProfileId } }],
298
+ });
299
+ try {
300
+ await persisted;
301
+ } catch (err) {
302
+ // Durability failed: roll the in-memory transition back so the team is
303
+ // never wedged behind a transition the crash-resume path cannot see.
304
+ // Nothing has been broadcast yet, so no external observer was told a
305
+ // switch had started.
306
+ updateTeamState((s) => {
307
+ delete s.transition;
308
+ });
309
+ sendError(res, 500, `failed to persist the team profile switch transition: ${err instanceof Error ? err.message : String(err)}`);
310
+ return;
311
+ }
312
+ logger.info(`Controller: team profile switch started - "${previousProfileId}" -> "${profileId}"`);
313
+
314
+ // Steps 2-6 plus the failure broadcast path live in ./profile-switch.ts
315
+ // (startTeamProfileSwitch: fire-and-forget executeTeamProfileSwitch with
316
+ // the archive-preservation-aware team.switch_failed unwedging).
317
+ startTeamProfileSwitch(deps, state, profileId, previousProfileId);
318
+
319
+ sendJson(res, 202, { status: "switching", profileId, transition: state.transition });
320
+ }
321
+
322
+ // GET /api/v1/archived-teams — archived team metadata list
323
+ // (Phase 2.1, design section 4: profileId/teamName/time/taskCount; detail
324
+ // queries and the archive UI stay v1.1).
325
+ async function archivedTeamsRoute(ctx: RouteContext): Promise<void> {
326
+ const { res } = ctx;
327
+ const archives = await listArchivedTeams();
328
+ sendJson(res, 200, { archives });
329
+ }
330
+
331
+ async function teamStatsRoute(ctx: RouteContext): Promise<void> {
332
+ const { res, deps } = ctx;
333
+ const state = deps.getTeamState();
334
+ if (!state) {
335
+ sendError(res, 503, "Team state not available");
336
+ return;
337
+ }
338
+ try {
339
+ const stats = computeTeamStats(state);
340
+ sendJson(res, 200, stats);
341
+ } catch (err) {
342
+ sendError(res, 500, `Failed to compute stats: ${err instanceof Error ? err.message : String(err)}`);
343
+ }
344
+ }
345
+
346
+ export {
347
+ teamStatsRoute,
348
+ teamStatusRoute,
349
+ teamRolesRoute,
350
+ teamProfilesListRoute,
351
+ teamProfileGetRoute,
352
+ teamProfileSwitchRoute,
353
+ archivedTeamsRoute,
354
+ };
@@ -35,6 +35,7 @@ import {
35
35
  recordTaskExecutionEvent,
36
36
  resetTaskForFreshAttempt,
37
37
  serializeTask,
38
+ withWorkerDispatchToken,
38
39
  } from "./task-execution.js";
39
40
  import type { TaskRouter } from "./task-router.js";
40
41
  import type { ControllerTaskDomainDeps } from "./task-execution.js";
@@ -378,9 +379,12 @@ export async function dispatchTaskToWorker(
378
379
  teamContext: buildTaskContextSnapshot(task, state ?? null),
379
380
  };
380
381
 
382
+ // Issue #222: carry the worker's dispatch token (provisioning-record
383
+ // launchToken, else the synced securityToken) so a token-paired worker
384
+ // accepts the assignment; L0 sends the historical header set unchanged.
381
385
  const res = await fetch(`${worker.url}/api/v1/tasks/assign`, {
382
386
  method: "POST",
383
- headers: { "Content-Type": "application/json" },
387
+ headers: withWorkerDispatchToken({ "Content-Type": "application/json" }, worker.id, deps.config, state ?? null),
384
388
  body: JSON.stringify(assignment),
385
389
  });
386
390
 
@@ -63,6 +63,47 @@ export type ControllerTaskDomainDeps = {
63
63
 
64
64
  export const MAX_TASK_EXECUTION_EVENTS = 250;
65
65
 
66
+ // ---------------------------------------------------------------------------
67
+ // Controller -> worker dispatch auth (issue #222, coordinated scope).
68
+ //
69
+ // Workers paired with a token (issue #222 worker wave) reject inbound /api
70
+ // calls without X-TeamClaw-Token; these helpers attach the token the target
71
+ // worker expects. Resolution order (minimal invasion, no new pairing
72
+ // surface - see the worker/http-handler.ts counterpart for the full model):
73
+ // 1. the worker's provisioning record launchToken (the provisioner
74
+ // already generates it per worker, delivers it via the
75
+ // TEAMCLAW_LAUNCH_TOKEN env, and persists it here) - provisioned
76
+ // fleets are covered with zero new plumbing;
77
+ // 2. the controller's own securityToken config (manual/external workers:
78
+ // the operator syncs the same value on both ends - the documented
79
+ // stance for self-managed workers);
80
+ // 3. neither => no header (L0: byte-identical historical requests).
81
+ // ---------------------------------------------------------------------------
82
+
83
+ export function resolveWorkerDispatchToken(
84
+ workerId: string,
85
+ config: Pick<PluginConfig, "securityToken">,
86
+ state: TeamState | null,
87
+ ): string | undefined {
88
+ const record = state?.provisioning?.workers?.[workerId];
89
+ if (record?.launchToken) {
90
+ return record.launchToken;
91
+ }
92
+ const shared = config.securityToken?.trim();
93
+ return shared ? shared : undefined;
94
+ }
95
+
96
+ /** Fetch headers for a controller -> worker call, carrying the worker's dispatch token when one is known. */
97
+ export function withWorkerDispatchToken(
98
+ headers: Record<string, string>,
99
+ workerId: string,
100
+ config: Pick<PluginConfig, "securityToken">,
101
+ state: TeamState | null,
102
+ ): Record<string, string> {
103
+ const token = resolveWorkerDispatchToken(workerId, config, state);
104
+ return token ? { ...headers, "X-TeamClaw-Token": token } : headers;
105
+ }
106
+
66
107
  const CONTROLLER_INTAKE_SESSION_PREFIX = "teamclaw-controller-web:";
67
108
  const CONTROLLER_INTAKE_AGENT_SESSION_RE = /^agent:[^:]+:(teamclaw-controller-web:[a-zA-Z0-9:_-]{1,120})$/;
68
109
 
@@ -331,8 +372,10 @@ export async function cancelTaskExecution(
331
372
 
332
373
  let cancelled = false;
333
374
  try {
375
+ // Issue #222: carry the worker's dispatch token so a token-paired worker accepts the cancel.
334
376
  const res = await fetch(`${worker.url}/api/v1/tasks/${taskId}/cancel`, {
335
377
  method: "POST",
378
+ headers: withWorkerDispatchToken({}, workerId, deps.config, deps.getTeamState()),
336
379
  });
337
380
  cancelled = res.ok;
338
381
  if (!res.ok) {
@@ -35,6 +35,11 @@ import {
35
35
  import { autoAssignPendingTasks, scheduleProvisioningReconcile } from "./task-assignment.js";
36
36
  import { checkAndGenerateReport } from "./controller-planning.js";
37
37
  import { continueControllerWorkflow } from "./controller-intake.js";
38
+ // Design 2.4 workflow-chain routing: tasks carrying TaskInfo.workflow route
39
+ // their follow-up step deterministically from the template's conclusion
40
+ // branches (they are createdBy "workflow", so the generic controller LLM
41
+ // follow-up below never fires for them - the two continuations are disjoint).
42
+ import { continueWorkflowAfterTaskCompletion } from "./workflow-routes.js";
38
43
  import type { ControllerTaskDomainDeps } from "./task-execution.js";
39
44
 
40
45
  /**
@@ -404,6 +409,13 @@ export function applyTaskResult(
404
409
  });
405
410
  }
406
411
  scheduleProvisioningReconcile(deps, `task-result:${taskId}`);
412
+ if (!error && updatedTask.workflow) {
413
+ void continueWorkflowAfterTaskCompletion(updatedTask, deps).catch((err) => {
414
+ logger.warn(
415
+ `Controller: failed to continue workflow chain after ${taskId}: ${String(err)}`,
416
+ );
417
+ });
418
+ }
407
419
  if (!error && updatedTask.createdBy === "controller") {
408
420
  void continueControllerWorkflow(updatedTask, deps).catch((err) => {
409
421
  logger.warn(
@@ -5,9 +5,10 @@ import type { PluginLogger } from "../../api.js";
5
5
  import https from "node:https";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
+ import { getGithubAuthManager } from "./github-auth.js";
8
9
 
9
10
  const TUNNEL_API_HOST = "apps.teamclaw.dev";
10
- async function tunnelFetch(pathq: string, method: "POST" | "DELETE", body?: unknown): Promise<{ status: number; json: any }> {
11
+ async function tunnelFetch(pathq: string, method: "POST" | "DELETE", body?: unknown, headers?: Record<string, string>): Promise<{ status: number; json: any }> {
11
12
  const ip = await new Promise<string>((resolve, reject) => {
12
13
  const r = https.request({ host: "1.1.1.1", path: `/dns-query?name=${TUNNEL_API_HOST}&type=A`, method: "GET", headers: { accept: "application/dns-json" }, servername: "cloudflare-dns.com" } as never, (res: import("node:http").IncomingMessage) => {
13
14
  let d = ""; res.on("data", (c: Buffer) => (d += c)); res.on("end", () => {
@@ -18,7 +19,7 @@ async function tunnelFetch(pathq: string, method: "POST" | "DELETE", body?: unkn
18
19
  });
19
20
  return new Promise((resolve, reject) => {
20
21
  const payload = body === undefined ? null : JSON.stringify(body);
21
- const req = https.request({ host: ip, servername: TUNNEL_API_HOST, path: `/api${pathq}`, method, headers: { host: TUNNEL_API_HOST, "Content-Type": "application/json", ...(payload ? { "Content-Length": Buffer.byteLength(payload) } : {}) } } as never, (res: import("node:http").IncomingMessage) => {
22
+ const req = https.request({ host: ip, servername: TUNNEL_API_HOST, path: `/api${pathq}`, method, headers: { host: TUNNEL_API_HOST, "Content-Type": "application/json", ...(headers ?? {}), ...(payload ? { "Content-Length": Buffer.byteLength(payload) } : {}) } } as never, (res: import("node:http").IncomingMessage) => {
22
23
  let d = ""; res.on("data", (c: Buffer) => (d += c)); res.on("end", () => { try { resolve({ status: res.statusCode ?? 0, json: d ? JSON.parse(d) : {} }); } catch { resolve({ status: res.statusCode ?? 0, json: {} }); } });
23
24
  });
24
25
  req.on("error", reject);
@@ -206,7 +207,10 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
206
207
  let installState: { running: boolean; phase: string; percent: number | null; detail: string | null } = { running: false, phase: "idle", percent: null, detail: null };
207
208
 
208
209
  function isTunnelRequest(hostHeader: string | undefined): boolean {
209
- return Boolean(hostHeader && hostHeader.toLowerCase().endsWith(TUNNEL_HOST_SUFFIX));
210
+ // #255 P1-5: quick tunnels (*.trycloudflare.com) are internet-reachable
211
+ // too, so they join the same gate enforcement as *.teamclaw.dev.
212
+ const host = hostHeader?.toLowerCase() ?? "";
213
+ return host.endsWith(TUNNEL_HOST_SUFFIX) || host.endsWith(".trycloudflare.com");
210
214
  }
211
215
 
212
216
  function gateAllows(req: { headers: Record<string, unknown> }): boolean {
@@ -234,8 +238,35 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
234
238
  if (handle && child) return handle;
235
239
  const bin = findCloudflared();
236
240
  if (!bin) throw new Error("cloudflared not found (brew install cloudflared)");
237
- const gateToken = randomBytes(6).toString("base64url").replace(/[-_]/g, "").slice(0, 8).toUpperCase();
238
- const res = await tunnelFetch("/tunnels", "POST", { github_user: githubUser, local_port: deps.localPort });
241
+ // Issue #237 W3: the gate token guards an internet-reachable verify
242
+ // endpoint, so it must carry real entropy - 16 random bytes kept as
243
+ // base64url (22 case-sensitive chars = the full 128 bits). The retired
244
+ // 8-char form collapsed to ~41 effective bits and was online-guessable;
245
+ // the gate cookie stays a sha256 derivation of the token, so a longer
246
+ // token does not weaken the cookie.
247
+ const gateToken = randomBytes(16).toString("base64url");
248
+ // Issue #231: prove github_user ownership to the relay. The managed-start
249
+ // route already refuses anonymous starts ("GitHub login required"), so the
250
+ // OAuth token behind that login is obtainable here via the shared auth
251
+ // manager — the empty config resolves to the same default clientId (and
252
+ // therefore the same cached manager instance) the routes use, and the
253
+ // token store lives in the state dir regardless of config. If no token
254
+ // can be resolved (signed out between the route's check and here), the
255
+ // header is omitted: legal while the relay's ACCEPT_LEGACY_CREATE grey
256
+ // window is open; once the relay tightens, its 401 surfaces as the
257
+ // create error instead of a silent squat.
258
+ let githubToken: string | null = null;
259
+ try {
260
+ githubToken = await getGithubAuthManager({}, logger).getAccessToken();
261
+ } catch {
262
+ githubToken = null; // not signed in / token unavailable -> legacy headerless create
263
+ }
264
+ const res = await tunnelFetch(
265
+ "/tunnels",
266
+ "POST",
267
+ { github_user: githubUser, local_port: deps.localPort },
268
+ githubToken ? { Authorization: `Bearer ${githubToken}` } : undefined,
269
+ );
239
270
  const body = res.json as { tunnel_id?: string; connector_token?: string; hostname?: string; delete_token?: string; error?: string };
240
271
  if (res.status !== 201 || !body.tunnel_id || !body.connector_token || !body.hostname) {
241
272
  throw new Error(body.error ?? `tunnel server responded ${res.status}`);
@@ -278,8 +309,12 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
278
309
  /** Anonymous one-off tunnel: `cloudflared tunnel --url`, no Cloudflare
279
310
  * account, no token, no platform server. Cloudflare assigns a random
280
311
  * trycloudflare.com URL (printed on stderr) which dies with the process -
281
- * it is NOT recovered on restart and must not be treated as stable. No
282
- * TeamClaw gate: anyone with the URL can reach the dashboard. */
312
+ * it is NOT recovered on restart and must not be treated as stable.
313
+ * #255 P1-5: the quick URL is internet-reachable, so it now gets the SAME
314
+ * per-launch gate token as managed tunnels (cookie-gated by the shared
315
+ * http-server enforcement point). The token is deliberately NOT
316
+ * persisted: quick tunnels have no recovery, and a token that dies with
317
+ * the process is strictly safer than one saved to disk. */
283
318
  function startQuick(): { launched: boolean; error: string | null } {
284
319
  if (handle && child) return { launched: true, error: null };
285
320
  const bin = findCloudflared();
@@ -292,7 +327,9 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
292
327
  env: { ...process.env, HOME: tunnelRuntimeHome() },
293
328
  });
294
329
  child = proc;
295
- handle = { tunnelId: "quick", hostname: "", gateToken: "", deleteToken: "" };
330
+ // #255 P1-5: same entropy class as the managed gate token (16 CSPRNG
331
+ // bytes, base64url) - the cookie check gates on it via gateAllows().
332
+ handle = { tunnelId: "quick", hostname: "", gateToken: randomBytes(16).toString("base64url"), deleteToken: "" };
296
333
  lastError = null;
297
334
  // The trycloudflare.com URL appears on stderr once the edge assigns it.
298
335
  let announced = false;