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