@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
@@ -9,17 +9,21 @@ import { createControllerHttpServer, type ControllerHttpDeps } from "./http-serv
9
9
  // PR-C of issue #204: the assignment pipeline incl. the gated auto-assign
10
10
  // loop lives in ./task-assignment.js, not http-server.ts.
11
11
  import { autoAssignPendingTasks } from "./task-assignment.js";
12
+ // Issue #222: worker dispatch-token header helper for controller -> worker calls.
13
+ import { withWorkerDispatchToken } from "./task-execution.js";
12
14
  // PR-A of issue #204: the profile switch state machine (incl. crash resume)
13
15
  // lives in ./profile-switch.ts, not http-server.ts.
14
16
  import { resumeTeamProfileSwitch } from "./profile-switch.js";
15
17
  import { TaskRouter } from "./task-router.js";
16
18
  import { MessageRouter } from "./message-router.js";
17
- import { TeamWebSocketServer } from "./websocket.js";
19
+ import { TeamWebSocketServer, type WsEvent } from "./websocket.js";
18
20
  import { ensureOpenClawWorkspaceMemoryDir, buildTeamClawAgentSessionKey } from "../openclaw-workspace.js";
19
21
  import { ensureControllerGitRepo } from "../git-collaboration.js";
20
22
  import { WorkerProvisioningManager } from "./worker-provisioning.js";
21
23
  import { PreviewManager } from "./preview-manager.js";
22
- import { runKickoffMeeting, buildKickoffAssessmentPrompt, ASSESSMENT_TIMEOUT_MS, type TaskRoleResolutionDeps } from "./kickoff-orchestrator.js";
24
+ import { runKickoffMeeting, ASSESSMENT_TIMEOUT_MS, type TaskRoleResolutionDeps } from "./kickoff-orchestrator.js";
25
+ // Issue #226 W3: the kickoff prompt contract lives in the shared layer now.
26
+ import { buildKickoffAssessmentPrompt } from "../shared/kickoff-prompt.js";
23
27
  import { resolvePreferredLanAddress } from "../networking.js";
24
28
  import { createTeamAutoScheduler, type TeamAutoScheduler } from "../teamauto/scheduler.js";
25
29
  import { getGithubAuthManager } from "./github-auth.js";
@@ -33,6 +37,66 @@ export type KickoffHandler = (
33
37
  requirement: string,
34
38
  ) => Promise<{ assessments: KickoffAssessment[]; summary: string }>;
35
39
 
40
+ // ===========================================================================
41
+ // Issue #226 W4: the single TeamState write-entry contract.
42
+ //
43
+ // `updateState` below is the ONLY sanctioned way to mutate the shared
44
+ // TeamState and persist it: the updater closure runs synchronously on the
45
+ // shared object, then the entry owns persistence (and, when asked, the WS
46
+ // broadcast). Before W4 there were three parallel write tracks - this
47
+ // controlled channel, direct mutation + saveTeamState in route-table's
48
+ // inline handlers, and profile-switch's independent saves - with
49
+ // lost-update / missed-broadcast risk across await interleavings. The
50
+ // route-handler and profile-switch tracks were migrated onto this entry;
51
+ // the remaining direct saveTeamState call sites are startup-early writes
52
+ // registered as explicit exemptions (search "W4 write-face exemption") and
53
+ // machine-pinned by tests/test-teamstate-writes.mjs, so a new unregistered
54
+ // direct save turns the suite red.
55
+ // ===========================================================================
56
+
57
+ /** A WS event the entry broadcasts on the caller's behalf (see below). */
58
+ export type TeamStateUpdateEvent = WsEvent;
59
+
60
+ export type TeamStateUpdateOptions = {
61
+ /**
62
+ * WS events to broadcast after the updater returned. With the default
63
+ * background persistence they fire synchronously right after the save was
64
+ * enqueued (the historical shape of callers broadcasting manually right
65
+ * after updateTeamState); with `persist: "awaited"` they fire only once
66
+ * the state-file write has fulfilled - the durability-before-broadcast
67
+ * contract the profile switch steps 1/6 rely on - and never fire when the
68
+ * write fails.
69
+ */
70
+ broadcast?: ReadonlyArray<TeamStateUpdateEvent>;
71
+ /**
72
+ * "background" (default): fire-and-forget save, the exact semantics every
73
+ * pre-W4 caller of updateTeamState relies on (an un-caught promise, same
74
+ * as the historical `void saveTeamState(...)`).
75
+ * "awaited": durability barrier - the update returns a handle carrying
76
+ * the save promise so the caller can enforce persisted-before-broadcast
77
+ * (profile switch transition step 1) and roll the in-memory mutation back
78
+ * when the write fails.
79
+ */
80
+ persist?: "background" | "awaited";
81
+ };
82
+
83
+ /** Return shape of the `persist: "awaited"` variant (see UpdateTeamStateFn). */
84
+ export type TeamStateUpdateHandle = {
85
+ state: TeamState;
86
+ /** Resolves when the state-file write settled; rejects on write failure. */
87
+ persisted: Promise<void>;
88
+ };
89
+
90
+ /**
91
+ * The deps-facing signature of the single write entry. Callers that pass no
92
+ * options keep the historical `(updater) => TeamState` behavior; the second
93
+ * overload is the awaited-durability variant used by the profile switch.
94
+ */
95
+ export type UpdateTeamStateFn = {
96
+ (updater: (state: TeamState) => void, options?: TeamStateUpdateOptions & { persist?: "background" }): TeamState;
97
+ (updater: (state: TeamState) => void, options: TeamStateUpdateOptions & { persist: "awaited" }): TeamStateUpdateHandle;
98
+ };
99
+
36
100
  export type ControllerServiceDeps = {
37
101
  config: PluginConfig;
38
102
  logger: PluginLogger;
@@ -133,6 +197,10 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
133
197
  createdAt: Date.now(),
134
198
  updatedAt: Date.now(),
135
199
  };
200
+ // W4 write-face exemption (#226): first-boot TeamState creation.
201
+ // This is initialization, not an update - the updateState entry is
202
+ // only defined below and presupposes an existing shared object. No
203
+ // WS server exists yet, so there is nothing to broadcast to.
136
204
  await saveTeamState(teamState);
137
205
  logger.info(`Controller: created new team "${config.teamName}" (profile: ${seededProfileId})`);
138
206
  } else {
@@ -143,11 +211,38 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
143
211
  }
144
212
  deps.onTeamStateAvailable?.(() => teamState);
145
213
 
146
- const updateState = (updater: (state: TeamState) => void): TeamState => {
147
- updater(teamState!);
148
- void saveTeamState(teamState!);
149
- return teamState!;
150
- };
214
+ // Issue #226 W4: the single TeamState write entry (see the contract
215
+ // block above). The updater stays a synchronous closure over the
216
+ // shared object; persistence - and, when requested, the WS broadcast -
217
+ // happen strictly after the updater returned. Existing one-argument
218
+ // callers keep the exact pre-W4 fire-and-forget semantics.
219
+ const updateState = ((updater: (state: TeamState) => void, options: TeamStateUpdateOptions = {}) => {
220
+ const state = teamState!;
221
+ updater(state);
222
+ if (options.persist === "awaited") {
223
+ // Durability variant (profile switch): the caller owns the save
224
+ // promise - broadcast events ride its fulfillment and never fire
225
+ // on failure; rejections surface to the caller's rollback. A
226
+ // dropped handle rejects unhandled, exactly like the historical
227
+ // floating void save.
228
+ let persisted = saveTeamState(state);
229
+ if (options.broadcast?.length) {
230
+ persisted = persisted.then(() => {
231
+ for (const event of options.broadcast!) {
232
+ wsServer.broadcastUpdate(event);
233
+ }
234
+ });
235
+ }
236
+ return { state, persisted };
237
+ }
238
+ void saveTeamState(state);
239
+ if (options.broadcast?.length) {
240
+ for (const event of options.broadcast) {
241
+ wsServer.broadcastUpdate(event);
242
+ }
243
+ }
244
+ return state;
245
+ }) as UpdateTeamStateFn;
151
246
 
152
247
  // Provisioned workers die with the previous gateway process. Their
153
248
  // persisted entries flip to offline once heartbeats stop but were
@@ -189,6 +284,11 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
189
284
  // Run ALL syncState calls (avoid || short-circuit skipping some).
190
285
  const syncC = workerProvisioningManager.syncState(teamState);
191
286
  if (repoStateChanged || syncC) {
287
+ // W4 write-face exemption (#226): startup durability barrier for the
288
+ // startup state assembly above (repo stamp + provisioning syncState's
289
+ // in-place mutations, which belong to the provisioning module). Runs
290
+ // before the WS server exists; there is no updater closure to run
291
+ // here - the mutations already happened on the shared object.
192
292
  await saveTeamState(teamState);
193
293
  }
194
294
 
@@ -228,6 +328,12 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
228
328
  }
229
329
  }
230
330
  if (orphanCleaned) {
331
+ // W4 write-face exemption (#226): startup orphan-task sweep. The
332
+ // loop above mutates in place interleaved with per-task startup
333
+ // logging; this awaited save is the pre-HTTP durability barrier -
334
+ // folding the sweep into an updater closure would reshuffle the
335
+ // startup crash-window ordering for zero convergence gain (the WS
336
+ // server does not exist yet, nothing to broadcast).
231
337
  await saveTeamState(teamState);
232
338
  }
233
339
  }
@@ -389,7 +495,8 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
389
495
  }
390
496
  },
391
497
  requestWorkerAssessment: async (worker, req) => {
392
- return await requestKickoffAssessment(worker, req);
498
+ // Issue #222: carry the worker's dispatch token on the assess call.
499
+ return await requestKickoffAssessment(worker, req, withWorkerDispatchToken({}, worker.id, config, teamState));
393
500
  },
394
501
  },
395
502
  );
@@ -462,6 +569,12 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
462
569
  }
463
570
 
464
571
  if (changed) {
572
+ // W4 write-face exemption (#226): heartbeat-timeout sweep. The
573
+ // mutations interleave with per-worker WS broadcasts inside the
574
+ // synchronous loop above; this floating save is byte-for-byte the
575
+ // entry's own background semantics (void saveTeamState), so
576
+ // routing it through updateState with a no-op updater would add
577
+ // ceremony without moving any save or broadcast.
465
578
  saveTeamState(teamState);
466
579
  }
467
580
 
@@ -502,6 +615,9 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
502
615
  }
503
616
  }
504
617
  if (orphaned) {
618
+ // W4 write-face exemption (#226): runtime orphan-task
619
+ // reconciliation, same sweep-interleaved-broadcast shape as the
620
+ // worker loop above (see that exemption note).
505
621
  saveTeamState(teamState);
506
622
  changed = true;
507
623
  }
@@ -554,11 +670,13 @@ function openBrowser(url: string, logger: PluginLogger): void {
554
670
  /**
555
671
  * Request a kickoff assessment from a worker.
556
672
  *
557
- * Request kickoff assessment from a worker over HTTP.
673
+ * Request kickoff assessment from a worker over HTTP. `authHeaders` carries
674
+ * the worker's dispatch token (issue #222) when the controller knows one.
558
675
  */
559
676
  async function requestKickoffAssessment(
560
677
  worker: import("../types.js").WorkerInfo,
561
678
  requirement: string,
679
+ authHeaders: Record<string, string> = {},
562
680
  ): Promise<import("../types.js").KickoffAssessment> {
563
681
  const role = worker.role;
564
682
  const prompt = buildKickoffAssessmentPrompt(role, requirement);
@@ -574,7 +692,7 @@ async function requestKickoffAssessment(
574
692
  try {
575
693
  const res = await fetch(`${worker.url}/api/v1/kickoff/assess`, {
576
694
  method: "POST",
577
- headers: { "Content-Type": "application/json" },
695
+ headers: { "Content-Type": "application/json", ...authHeaders },
578
696
  body: JSON.stringify({ requirement, role }),
579
697
  signal: controller.signal,
580
698
  });
@@ -9,14 +9,17 @@ import type {
9
9
  } from "../types.js";
10
10
  import { buildControllerNoWorkersMessage, hasOnDemandWorkerProvisioning, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
11
11
  import {
12
- normalizeClarificationQuestionSchemas,
13
12
  normalizeManifestCompletionOpportunities,
14
13
  normalizeManifestCreatedTasks,
15
14
  normalizeManifestDeferredTasks,
16
15
  normalizeManifestRoleList,
17
16
  normalizeManifestStringList,
18
- normalizeOptionalManifestText,
19
17
  } from "./orchestration-manifest.js";
18
+ // Issue #226 W3: the clarification-schema family lives in the shared layer now.
19
+ import {
20
+ normalizeClarificationQuestionSchemas,
21
+ normalizeOptionalManifestText,
22
+ } from "../shared/clarification-schema.js";
20
23
  import {
21
24
  ensureTeamMessageContract,
22
25
  normalizeContractRole,
@@ -2,6 +2,31 @@ import crypto from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ // Issue #226 W5: the GithubAuthManager contract (and the pure types it
6
+ // references) moved to the shared layer — teamauto consumes the type and must
7
+ // not import the controller tree. The factory below is annotated with the
8
+ // shared return type, so TypeScript keeps the structural contract in lockstep
9
+ // with the returned closures; the re-export keeps this module's historical
10
+ // public surface stable for existing importers.
11
+ import type {
12
+ GithubAccountInfo,
13
+ GithubAuthManager,
14
+ GithubAuthStatus,
15
+ GithubAuthStore,
16
+ GithubDeviceFlowInfo,
17
+ GithubLoginCallbackParams,
18
+ GithubLoginStart,
19
+ } from "../shared/github-auth.js";
20
+
21
+ export type {
22
+ GithubAccountInfo,
23
+ GithubAuthManager,
24
+ GithubAuthStatus,
25
+ GithubAuthStore,
26
+ GithubDeviceFlowInfo,
27
+ GithubLoginCallbackParams,
28
+ GithubLoginStart,
29
+ } from "../shared/github-auth.js";
5
30
 
6
31
  /**
7
32
  * GitHub (GitHub App) user login for the TeamClaw controller.
@@ -14,7 +39,8 @@ import path from "node:path";
14
39
  * (`auth/github.json`, mode 0600, atomic tmp+rename writes).
15
40
  */
16
41
 
17
- export const DEFAULT_GITHUB_CLIENT_ID = "Iv23liqWmzrS3swGiIvK";
42
+ import { DEFAULT_GITHUB_CLIENT_ID } from "../shared/github-auth.js";
43
+ export { DEFAULT_GITHUB_CLIENT_ID };
18
44
  export const GITHUB_AUTH_CALLBACK_PATH = "/api/v1/auth/github/callback";
19
45
  export const GITHUB_CLIENT_SECRET_ENV = "TEAMCLAW_GITHUB_CLIENT_SECRET";
20
46
 
@@ -43,65 +69,6 @@ export class GithubAuthError extends Error {
43
69
  }
44
70
  }
45
71
 
46
- export type GithubAccountInfo = {
47
- id: number;
48
- login: string;
49
- name: string | null;
50
- avatarUrl: string | null;
51
- htmlUrl: string | null;
52
- };
53
-
54
- export type GithubAuthStore = {
55
- version: number;
56
- clientId: string;
57
- /** Which OAuth flow produced this token; device-flow tokens refresh without a client secret. */
58
- flowOrigin: "device" | "web";
59
- account: GithubAccountInfo | null;
60
- accessToken: string;
61
- refreshToken: string | null;
62
- obtainedAt: number;
63
- /** Epoch ms when the access token expires; null when it does not expire. */
64
- expiresAt: number | null;
65
- /** Epoch ms when the refresh token expires; null when unknown. */
66
- refreshExpiresAt: number | null;
67
- updatedAt: number;
68
- };
69
-
70
- export type GithubAuthStatus = {
71
- authenticated: boolean;
72
- account: GithubAccountInfo | null;
73
- clientId: string;
74
- clientSecretConfigured: boolean;
75
- expiresAt: number | null;
76
- refreshExpiresAt: number | null;
77
- callbackPath: string;
78
- callbackUrl: string | null;
79
- /** Absolute URL of the standalone device-login page, when origin is known. */
80
- loginPageUrl: string | null;
81
- /** Active device-flow login (user code to enter at github.com/login/device), if any. */
82
- device: GithubDeviceFlowInfo | null;
83
- };
84
-
85
- export type GithubDeviceFlowInfo = {
86
- userCode: string;
87
- verificationUri: string;
88
- expiresAt: number;
89
- intervalMs: number;
90
- };
91
-
92
- export type GithubLoginStart = {
93
- authorizeUrl: string;
94
- state: string;
95
- callbackUrl: string;
96
- };
97
-
98
- export type GithubLoginCallbackParams = {
99
- code?: string;
100
- state?: string;
101
- error?: string;
102
- errorDescription?: string;
103
- };
104
-
105
72
  export type GithubAuthLogger = {
106
73
  info: (message: string) => void;
107
74
  warn: (message: string) => void;
@@ -203,7 +170,7 @@ export function createGithubAuthManager(options: {
203
170
  logger?: GithubAuthLogger;
204
171
  fetchImpl?: GithubFetch;
205
172
  now?: () => number;
206
- } = {}) {
173
+ } = {}): GithubAuthManager {
207
174
  const clientId = options.clientId?.trim() || DEFAULT_GITHUB_CLIENT_ID;
208
175
  // The environment variable wins so operators can keep the secret out of the
209
176
  // plugin config file.
@@ -670,8 +637,6 @@ export function createGithubAuthManager(options: {
670
637
  };
671
638
  }
672
639
 
673
- export type GithubAuthManager = ReturnType<typeof createGithubAuthManager>;
674
-
675
640
  const managerCache = new Map<string, GithubAuthManager>();
676
641
 
677
642
  /**
@@ -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):
@@ -46,7 +54,7 @@ import { MessageRouter } from "./message-router.js";
46
54
  import { TeamWebSocketServer } from "./websocket.js";
47
55
  import type { WorkerProvisioningManager } from "./worker-provisioning.js";
48
56
  import type { PreviewManager } from "./preview-manager.js";
49
- import type { KickoffHandler } from "./controller-service.js";
57
+ import type { KickoffHandler, UpdateTeamStateFn } from "./controller-service.js";
50
58
  import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
51
59
  import { autoAssignPendingTasks } from "./task-assignment.js";
52
60
  import { createTunnelManager, gatePageHtml, type TunnelManager } from "./tunnel-manager.js";
@@ -65,13 +73,29 @@ import {
65
73
  type RouteContext,
66
74
  type RouteDef,
67
75
  } from "./route-table.js";
76
+ // Issue #23 (backend wave): the device-pairing security module owns the
77
+ // auth middleware, the CORS narrowing policy, the WS upgrade guard and the
78
+ // pairing handlers (registered via route-table.ts). This file only wires
79
+ // them into the pipeline below - all pathname/method policy lives in
80
+ // security.ts.
81
+ import {
82
+ classifySecurityPeer,
83
+ corsPreflightDecision,
84
+ createSecurityMiddleware,
85
+ createWebSocketUpgradeGuard,
86
+ isProtectionOn,
87
+ type SecurityPeer,
88
+ } from "./security.js";
68
89
 
69
90
  export type ControllerHttpDeps = {
70
91
  config: PluginConfig;
71
92
  logger: PluginLogger;
72
93
  runtime: OpenClawPluginApi["runtime"];
73
94
  getTeamState: () => TeamState | null;
74
- updateTeamState: (updater: (state: TeamState) => void) => TeamState;
95
+ // Issue #226 W4: widened to the single-write-entry contract (the optional
96
+ // second argument + awaited-durability overload live in controller-service
97
+ // next to the implementation; one-argument callers are unaffected).
98
+ updateTeamState: UpdateTeamStateFn;
75
99
  taskRouter: TaskRouter;
76
100
  messageRouter: MessageRouter;
77
101
  wsServer: TeamWebSocketServer;
@@ -182,14 +206,18 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
182
206
  // tunnel manager singleton they close over) and reused for every request.
183
207
  let tunnelRoutesSingleton: { gate: readonly RouteDef[]; management: readonly RouteDef[] } | null = null;
184
208
 
209
+ // Issue #23: the device gate. Zero-friction ladder - while no device is
210
+ // paired (protection off) this is a no-op passthrough (L0, the exact
211
+ // pre-issue behavior); once devices exist it enforces per-device tokens
212
+ // on every non-exempt /api route (exemptions and 401 shape in security.ts).
213
+ const securityGate = createSecurityMiddleware(deps);
214
+
185
215
  const server = http.createServer(async (req: IncomingMessage, res: ServerResponse) => {
186
- // CORS preflight
216
+ // CORS preflight (issue #23: wildcard while protection is off - the
217
+ // historical bytes - and narrowed to the UI's own origin once on).
187
218
  if (req.method === "OPTIONS") {
188
- res.writeHead(200, {
189
- "Access-Control-Allow-Origin": "*",
190
- "Access-Control-Allow-Methods": "GET, POST, PATCH, DELETE, OPTIONS",
191
- "Access-Control-Allow-Headers": "Content-Type",
192
- });
219
+ const decision = corsPreflightDecision(req, isProtectionOn(deps.getTeamState()));
220
+ res.writeHead(decision.status, decision.headers);
193
221
  res.end();
194
222
  return;
195
223
  }
@@ -215,6 +243,19 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
215
243
  req, res, requestUrl: url, pathname, deps, currentState: null,
216
244
  };
217
245
  const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
246
+
247
+ // ==================== Device auth gate (issue #23) ====================
248
+ // Runs BEFORE the tunnel gate tables, the transition matrix and the
249
+ // capability gates so none of those surfaces answer - or leak response
250
+ // shape information - to unpaired callers while protection is on.
251
+ // Requests arriving through the sharing tunnel are classified from the
252
+ // Host header (cloudflared dials in from loopback, so the socket peer
253
+ // address would lie); see classifySecurityPeer in ./security.ts.
254
+ const peer = classifySecurityPeer(req.socket.remoteAddress, viaTunnel);
255
+ if (!securityGate(req, res, pathname, peer)) {
256
+ return;
257
+ }
258
+
218
259
  if (viaTunnel) {
219
260
  if (await dispatchRoutes(tunnelRoutesSingleton.gate, tunnelCtx)) {
220
261
  return;
@@ -231,15 +272,22 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
231
272
  }
232
273
 
233
274
  try {
234
- await handleRequest(req, res, pathname, deps);
275
+ await handleRequest(req, res, pathname, deps, peer);
235
276
  } catch (err) {
236
277
  logger.error(`Controller HTTP error: ${err instanceof Error ? err.message : String(err)}`);
237
278
  sendError(res, 500, "Internal server error");
238
279
  }
239
280
  });
240
281
 
241
- // Attach WebSocket
242
- wsServer.attach(server);
282
+ // Attach WebSocket (issue #23: while device protection is on, upgrades
283
+ // must carry a valid device token - ?token= query for browsers, cookie /
284
+ // Bearer for native clients; see createWebSocketUpgradeGuard).
285
+ wsServer.attach(server, {
286
+ verifyUpgrade: createWebSocketUpgradeGuard({
287
+ ...deps,
288
+ isTunnelHost: (host) => tunnelManagerSingleton?.isTunnelRequest(host) ?? false,
289
+ }),
290
+ });
243
291
 
244
292
  // Plugin shutdown: kill the local connector and tear down the remote
245
293
  // tunnel so gateway exits never leak orphan cloudflared processes.
@@ -277,6 +325,7 @@ async function handleRequest(
277
325
  res: ServerResponse,
278
326
  pathname: string,
279
327
  deps: ControllerHttpDeps,
328
+ peer?: SecurityPeer,
280
329
  ): Promise<void> {
281
330
  const requestUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
282
331
  const currentState = deps.getTeamState();
@@ -352,7 +401,7 @@ async function handleRequest(
352
401
  // false) to continue matching; an exhausted table falls through to the
353
402
  // final 404 below - both semantics are preserved from the old chain.
354
403
  const handled = await dispatchRoutes(controllerRouteTable, {
355
- req, res, requestUrl, pathname, deps, currentState,
404
+ req, res, requestUrl, pathname, deps, currentState, peer,
356
405
  });
357
406
  if (!handled) {
358
407
  sendError(res, 404, "Not found");
@@ -19,6 +19,9 @@ import type { PluginLogger } from "../../api.js";
19
19
  import type { KickoffAssessment, KickoffPlan, RoleId, TaskInfo, TeamState, WorkerInfo } from "../types.js";
20
20
  // Phase 1.3: role data comes from the active TeamProfile loader.
21
21
  import { getActiveDefaultRole, getActiveRole, getActiveRoleIds, validateActiveRoleId } from "../profile-loader.js";
22
+ // W6 of issue #226: the local sleep copy (byte-identical to the shared one)
23
+ // was removed in favor of shared/utils.js.
24
+ import { sleep } from "../shared/utils.js";
22
25
  import { inferTaskRoleWithConfidence } from "./role-inference.js";
23
26
  import type { RoleInferenceVerdict } from "./role-inference.js";
24
27
 
@@ -251,48 +254,6 @@ function buildKickoffSummary(plan: KickoffPlan, _requirement: string): string {
251
254
  return parts.join("\n");
252
255
  }
253
256
 
254
- /**
255
- * Build the kickoff assessment prompt sent to a worker.
256
- * The worker should respond with structured JSON matching KickoffAssessment.
257
- */
258
- export function buildKickoffAssessmentPrompt(role: RoleId, requirement: string): string {
259
- const roleDef = getActiveRole(role);
260
- const roleLabel = roleDef?.label ?? role;
261
-
262
- return [
263
- `You are the ${roleLabel} in a virtual software team.`,
264
- `Your team is conducting a kickoff meeting for a new requirement.`,
265
- ``,
266
- `## Requirement`,
267
- requirement,
268
- ``,
269
- `## Your Task`,
270
- `Evaluate this requirement from your professional perspective as ${roleLabel}.`,
271
- `Respond with a JSON object (and nothing else) with these fields:`,
272
- ``,
273
- `{`,
274
- ` "needed": boolean, // Is your role needed for this project?`,
275
- ` "scope": string, // What would you contribute? (1-2 sentences)`,
276
- ` "suggestedTasks": string[], // Specific tasks you'd handle (2-5 items)`,
277
- ` "dependencies": string[], // What you need from other roles before or during your work`,
278
- ` "risks": string[], // Concerns or risks from your perspective`,
279
- ` "questions": string[] // Clarifications you'd want before starting`,
280
- `}`,
281
- ``,
282
- `Guidelines:`,
283
- `- Be honest about whether your role is truly needed. Don't inflate your importance.`,
284
- `- For "needed", consider: does the project actually require ${roleLabel}-level expertise?`,
285
- `- A simple single-file script does NOT need an architect. A TODO app does NOT need a security engineer.`,
286
- `- Keep suggestedTasks concrete and actionable, not vague.`,
287
- `- Only list dependencies on roles that are actually relevant.`,
288
- `- Return ONLY the JSON object, no markdown fencing, no explanation.`,
289
- ].join("\n");
290
- }
291
-
292
- function sleep(ms: number): Promise<void> {
293
- return new Promise((resolve) => setTimeout(resolve, ms));
294
- }
295
-
296
257
  // ── Phase 2.5: LLM fallback for unconfident role inference (design 2.3) ─────
297
258
  //
298
259
  // The tiered token scoring in role-inference.ts is the FAST PATH only. When
@@ -6,6 +6,7 @@
6
6
  // message ROUTES because the controller-planning intake glue also delivers
7
7
  // messages and must stay below the route layer.
8
8
  import type { TeamMessage, WorkerInfo } from "../types.js";
9
+ import { withWorkerDispatchToken } from "./task-execution.js";
9
10
  import type { ControllerTaskDomainDeps } from "./task-execution.js";
10
11
 
11
12
  export async function deliverMessageToWorker(
@@ -13,9 +14,11 @@ export async function deliverMessageToWorker(
13
14
  message: TeamMessage,
14
15
  deps: ControllerTaskDomainDeps,
15
16
  ): Promise<void> {
17
+ // Issue #222: carry the worker's dispatch token so a token-paired worker
18
+ // accepts the injection; L0 sends the historical header set unchanged.
16
19
  const res = await fetch(`${worker.url}/api/v1/messages`, {
17
20
  method: "POST",
18
- headers: { "Content-Type": "application/json" },
21
+ headers: withWorkerDispatchToken({ "Content-Type": "application/json" }, worker.id, deps.config, deps.getTeamState()),
19
22
  body: JSON.stringify(message),
20
23
  });
21
24