@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
package/cli.mjs CHANGED
@@ -135,7 +135,20 @@ Usage:
135
135
 
136
136
  Commands:
137
137
  install Install/configure TeamClaw for OpenClaw
138
- help Show this help
138
+ pair <controller-url> Pair this instance with a controller that has device
139
+ protection enabled (issue #23). Without --code it
140
+ first tries zero-input LAN auto-pairing.
141
+ --code <code> One-shot pairing code from the controller owner
142
+ (web UI: Device security -> New pairing code)
143
+ --name <name> Device name shown in the controller device list
144
+ --kind <kind> Device kind: worker, desktop or cli (default cli)
145
+ --config <path> OpenClaw config path to store the token in
146
+ token reset <controller-url>
147
+ Revoke ALL paired devices and return the controller
148
+ to unpaired local mode (loopback host, or --token)
149
+ --token <token> Device token (required from a non-loopback host)
150
+ --config <path> OpenClaw config path to clear the stored token from
151
+ help Show this help
139
152
 
140
153
  Options:
141
154
  --config <path> Override the OpenClaw config path
@@ -249,6 +262,242 @@ function parseArgs(argv) {
249
262
  return { command: command || "help", options };
250
263
  }
251
264
 
265
+ // ===========================================================================
266
+ // Device pairing commands (issue #23, client wave).
267
+ //
268
+ // pair <controller-url> [--code] [--name] [--kind] - exchange a one-shot
269
+ // code (or a LAN auto-pair attempt) for a device token, then store it as
270
+ // plugins.entries.teamclaw.config.securityToken in the OpenClaw config so
271
+ // every later worker/controller API call from this instance carries the
272
+ // X-TeamClaw-Token header automatically.
273
+ // token reset <controller-url> [--token] - revoke all devices (loopback
274
+ // host needs no token) and clear any locally stored token.
275
+ // ===========================================================================
276
+
277
+ const PAIR_DEVICE_KINDS = new Set(["worker", "desktop", "cli"]);
278
+ const SECURITY_REQUEST_TIMEOUT_MS = 15_000;
279
+
280
+ function normalizeControllerUrlArg(raw) {
281
+ let value = String(raw || "").trim();
282
+ if (!value) {
283
+ throw new Error("A controller URL is required (e.g. http://192.168.1.10:9527).");
284
+ }
285
+ if (!value.startsWith("http://") && !value.startsWith("https://")) {
286
+ value = `http://${value}`;
287
+ }
288
+ try {
289
+ const parsed = new URL(value);
290
+ if (!parsed.hostname) {
291
+ throw new Error("empty host");
292
+ }
293
+ // Strip any trailing path/slash so endpoint joining stays predictable.
294
+ return `${parsed.protocol}//${parsed.host}`;
295
+ } catch (error) {
296
+ throw new Error(`Invalid controller URL: ${raw}`);
297
+ }
298
+ }
299
+
300
+ function readFlagValue(argv, index, flag) {
301
+ const value = argv[index + 1];
302
+ if (!value) {
303
+ throw new Error(`${flag} requires a value`);
304
+ }
305
+ return value;
306
+ }
307
+
308
+ function parsePairArgs(argv) {
309
+ const options = { controllerUrl: "", code: "", name: "", kind: "cli", configPath: "" };
310
+ const positional = [];
311
+ for (let index = 0; index < argv.length; index += 1) {
312
+ const arg = argv[index];
313
+ if (arg === "--help" || arg === "-h") {
314
+ return { help: true, options };
315
+ }
316
+ if (arg.startsWith("--")) {
317
+ if (arg === "--code") {
318
+ options.code = readFlagValue(argv, index, arg).trim();
319
+ index += 1;
320
+ } else if (arg === "--name") {
321
+ options.name = readFlagValue(argv, index, arg).trim();
322
+ index += 1;
323
+ } else if (arg === "--kind") {
324
+ const kind = readFlagValue(argv, index, arg).trim();
325
+ if (!PAIR_DEVICE_KINDS.has(kind)) {
326
+ throw new Error(`--kind requires one of: ${[...PAIR_DEVICE_KINDS].join(", ")}`);
327
+ }
328
+ options.kind = kind;
329
+ index += 1;
330
+ } else if (arg === "--config") {
331
+ options.configPath = readFlagValue(argv, index, arg);
332
+ index += 1;
333
+ } else {
334
+ throw new Error(`Unknown argument: ${arg}`);
335
+ }
336
+ continue;
337
+ }
338
+ positional.push(arg);
339
+ }
340
+ if (positional.length !== 1) {
341
+ throw new Error('Usage: teamclaw pair <controller-url> [--code <code>] [--name <name>] [--kind worker|desktop|cli]');
342
+ }
343
+ options.controllerUrl = positional[0];
344
+ return { help: false, options };
345
+ }
346
+
347
+ function parseTokenArgs(argv) {
348
+ const options = { controllerUrl: "", token: "", configPath: "" };
349
+ const positional = [];
350
+ for (let index = 0; index < argv.length; index += 1) {
351
+ const arg = argv[index];
352
+ if (arg === "--help" || arg === "-h") {
353
+ return { help: true, options };
354
+ }
355
+ if (arg.startsWith("--")) {
356
+ if (arg === "--token") {
357
+ options.token = readFlagValue(argv, index, arg).trim();
358
+ index += 1;
359
+ } else if (arg === "--config") {
360
+ options.configPath = readFlagValue(argv, index, arg);
361
+ index += 1;
362
+ } else {
363
+ throw new Error(`Unknown argument: ${arg}`);
364
+ }
365
+ continue;
366
+ }
367
+ positional.push(arg);
368
+ }
369
+ if (positional.length === 0 || positional[0] !== "reset") {
370
+ throw new Error('Usage: teamclaw token reset <controller-url> [--token <token>]');
371
+ }
372
+ if (positional.length !== 2) {
373
+ throw new Error('Usage: teamclaw token reset <controller-url> [--token <token>]');
374
+ }
375
+ options.controllerUrl = positional[1];
376
+ return { help: false, options };
377
+ }
378
+
379
+ async function securityFetch(controllerUrl, pathname, { method = "POST", body, token } = {}) {
380
+ const headers = {};
381
+ if (body !== undefined) {
382
+ headers["Content-Type"] = "application/json";
383
+ }
384
+ if (token) {
385
+ headers["X-TeamClaw-Token"] = token;
386
+ }
387
+ let response;
388
+ try {
389
+ response = await fetch(`${controllerUrl}/api/v1${pathname}`, {
390
+ method,
391
+ headers,
392
+ body: body !== undefined ? JSON.stringify(body) : undefined,
393
+ signal: AbortSignal.timeout(SECURITY_REQUEST_TIMEOUT_MS),
394
+ });
395
+ } catch (error) {
396
+ throw new Error(`Could not reach the controller at ${controllerUrl}: ${error instanceof Error ? error.message : String(error)}`);
397
+ }
398
+ let payload = null;
399
+ try {
400
+ payload = await response.json();
401
+ } catch {
402
+ payload = null;
403
+ }
404
+ return { status: response.status, ok: response.ok, payload };
405
+ }
406
+
407
+ function describeSecurityError(result, fallback) {
408
+ if (result.payload && typeof result.payload === "object") {
409
+ const parts = [result.payload.error, result.payload.hint].filter((part) => typeof part === "string" && part.trim());
410
+ if (parts.length > 0) {
411
+ return parts.join(" - ");
412
+ }
413
+ }
414
+ return `${fallback} (HTTP ${result.status})`;
415
+ }
416
+
417
+ async function upsertTeamClawConfig(configPath, update) {
418
+ const config = await readOpenClawConfig(configPath);
419
+ const plugins = ensureRecord(config, "plugins");
420
+ const entries = ensureRecord(plugins, "entries");
421
+ const teamclawEntry = ensureRecord(entries, PLUGIN_ID);
422
+ const teamclawConfig = ensureRecord(teamclawEntry, "config");
423
+ update(teamclawConfig);
424
+ await writeConfig(configPath, config);
425
+ }
426
+
427
+ async function runPair(options) {
428
+ const controllerUrl = normalizeControllerUrlArg(options.controllerUrl);
429
+ const kind = options.kind;
430
+ const name = options.name || `${os.hostname()} ${kind}`;
431
+ let result;
432
+ if (options.code) {
433
+ result = await securityFetch(controllerUrl, "/security/pair", {
434
+ body: { code: options.code.toUpperCase(), kind, name },
435
+ });
436
+ } else {
437
+ // Zero-input LAN path first (mDNS scenario): a LAN peer pairs without a
438
+ // code while the controller allows auto-pairing.
439
+ result = await securityFetch(controllerUrl, "/security/pair-auto", { body: { kind, name } });
440
+ if (result.status === 403) {
441
+ throw new Error(
442
+ "This controller did not accept zero-input pairing (not a LAN peer, or auto-pairing is disabled). " +
443
+ "Ask the controller owner for a one-shot pairing code (web UI: Device security -> New pairing code) and rerun with --code <code>.",
444
+ );
445
+ }
446
+ }
447
+ if (!result.ok || !result.payload || typeof result.payload.token !== "string") {
448
+ if (result.status === 409) {
449
+ throw new Error(describeSecurityError(result, "Device protection is not enabled on this controller; there is nothing to pair with yet"));
450
+ }
451
+ throw new Error(describeSecurityError(result, "Pairing failed"));
452
+ }
453
+ const configPath = expandUserPath(options.configPath || resolveDefaultOpenClawConfigPath());
454
+ await upsertTeamClawConfig(configPath, (teamclawConfig) => {
455
+ // Same layer as teamName: the worker/controller pipeline reads this and
456
+ // sends X-TeamClaw-Token on every API call automatically.
457
+ teamclawConfig.securityToken = result.payload.token;
458
+ if (!teamclawConfig.controllerUrl) {
459
+ teamclawConfig.controllerUrl = controllerUrl;
460
+ }
461
+ });
462
+ console.log(`Paired with ${controllerUrl}`);
463
+ console.log(` Device: "${result.payload.device?.name || name}" (kind ${kind}, id ${result.payload.deviceId || result.payload.device?.id || "?"})`);
464
+ console.log(` Token stored at plugins.entries.teamclaw.config.securityToken in ${configPath}`);
465
+ console.log(" This instance now authenticates automatically. Keep that config file private; the token is shown only once by the controller and cannot be recovered.");
466
+ console.log("Next step: restart this instance (or run `openclaw gateway restart`) so its API calls pick up the token.");
467
+ }
468
+
469
+ async function runTokenReset(options) {
470
+ const controllerUrl = normalizeControllerUrlArg(options.controllerUrl);
471
+ const result = await securityFetch(controllerUrl, "/security/reset", { body: {}, token: options.token });
472
+ if (!result.ok) {
473
+ if (result.status === 401) {
474
+ throw new Error(
475
+ "Reset refused: only the controller host itself (loopback) or an authenticated device may reset. " +
476
+ "Run this on the controller machine, or pass --token <device-token>.",
477
+ );
478
+ }
479
+ throw new Error(describeSecurityError(result, "Token reset failed"));
480
+ }
481
+ // Best effort: drop the now-invalid local token so the next pair starts clean.
482
+ const configPath = expandUserPath(options.configPath || resolveDefaultOpenClawConfigPath());
483
+ try {
484
+ const config = await readOpenClawConfig(configPath);
485
+ const teamclawConfig = getExistingTeamClawConfig(config);
486
+ if (typeof teamclawConfig.securityToken === "string" && teamclawConfig.securityToken) {
487
+ delete teamclawConfig.securityToken;
488
+ const plugins = ensureRecord(config, "plugins");
489
+ const entries = ensureRecord(plugins, "entries");
490
+ const teamclawEntry = ensureRecord(entries, PLUGIN_ID);
491
+ teamclawEntry.config = teamclawConfig;
492
+ await writeConfig(configPath, config);
493
+ console.log(`Cleared the stored device token from ${configPath}`);
494
+ }
495
+ } catch {
496
+ // No local config/token to clear - resetting a remote controller only.
497
+ }
498
+ console.log(`All paired devices on ${controllerUrl} were revoked; the controller is back to unpaired local mode (L0).`);
499
+ }
500
+
252
501
  function isRecord(value) {
253
502
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
254
503
  }
@@ -2103,8 +2352,29 @@ async function runInstall(options) {
2103
2352
  }
2104
2353
 
2105
2354
  async function main() {
2355
+ const argv = process.argv.slice(2);
2356
+ // Issue #23 pairing commands dispatch before the installer parser (their
2357
+ // positional <controller-url> argument is not an installer flag).
2358
+ if (argv[0] === "pair") {
2359
+ const { help, options } = parsePairArgs(argv.slice(1));
2360
+ if (help) {
2361
+ printHelp();
2362
+ return;
2363
+ }
2364
+ await runPair(options);
2365
+ return;
2366
+ }
2367
+ if (argv[0] === "token") {
2368
+ const { help, options } = parseTokenArgs(argv.slice(1));
2369
+ if (help) {
2370
+ printHelp();
2371
+ return;
2372
+ }
2373
+ await runTokenReset(options);
2374
+ return;
2375
+ }
2106
2376
  await loadRoleOptions();
2107
- const { command, options } = parseArgs(process.argv.slice(2));
2377
+ const { command, options } = parseArgs(argv);
2108
2378
  if (command === "help") {
2109
2379
  printHelp();
2110
2380
  return;
package/dist/index.js CHANGED
@@ -15,6 +15,9 @@ import { createControllerTools } from "./src/controller/controller-tools.js";
15
15
  import { publishWorkerRepo, syncWorkerRepo } from "./src/git-collaboration.js";
16
16
  import { resolveTeamClawProjectsDir } from "./src/openclaw-workspace.js";
17
17
  import { installRecommendedSkills } from "./src/worker/skill-installer.js";
18
+ // W6 of issue #226: local swallowing pathExists copy replaced by the shared
19
+ // one (identical semantics; alias keeps the call site byte-identical).
20
+ import { pathExistsTolerant as pathExists } from "./src/shared/utils.js";
18
21
  export default definePluginEntry({
19
22
  id: "teamclaw",
20
23
  name: "TeamClaw",
@@ -76,32 +79,36 @@ function registerController(api, config) {
76
79
  });
77
80
  });
78
81
  }
79
- function registerWorker(api, config) {
80
- const logger = api.logger;
81
- const messageQueue = new MessageQueue();
82
- let currentControllerUrl = null;
83
- let currentWorkerId = null;
84
- function getIdentity() {
85
- if (!currentWorkerId || !currentControllerUrl)
86
- return null;
87
- return {
88
- workerId: currentWorkerId,
89
- role: config.role,
90
- controllerUrl: currentControllerUrl,
91
- registeredAt: Date.now(),
92
- };
93
- }
82
+ /**
83
+ * Issue #23 (client wave): headers for worker -> controller calls, same
84
+ * pattern as identity.ts / worker-service.ts / worker/tools.ts. A configured
85
+ * device token rides X-TeamClaw-Token; without one the headers are unchanged
86
+ * (L0). The token value is never logged.
87
+ */
88
+ function withDeviceToken(config, headers) {
89
+ const token = config.securityToken?.trim();
90
+ return token ? { ...headers, "X-TeamClaw-Token": token } : headers;
91
+ }
92
+ /**
93
+ * Execution-event + checkpoint reporters (issue #23 review follow-up: the
94
+ * execution stream and resume checkpoints MUST survive device protection, so
95
+ * both POSTs carry the paired device token). Extracted from registerWorker
96
+ * as an exported factory so the dist-level client tests can exercise the
97
+ * real header behavior against a stub controller.
98
+ */
99
+ export function createWorkerEventReporters(config, logger, state) {
94
100
  async function reportExecutionEvent(taskId, event) {
95
- if (!currentControllerUrl) {
101
+ const controllerUrl = state.getControllerUrl();
102
+ if (!controllerUrl) {
96
103
  return;
97
104
  }
98
105
  try {
99
- const res = await fetch(`${currentControllerUrl}/api/v1/tasks/${taskId}/execution`, {
106
+ const res = await fetch(`${controllerUrl}/api/v1/tasks/${taskId}/execution`, {
100
107
  method: "POST",
101
- headers: { "Content-Type": "application/json" },
108
+ headers: withDeviceToken(config, { "Content-Type": "application/json" }),
102
109
  body: JSON.stringify({
103
110
  ...event,
104
- workerId: currentWorkerId ?? undefined,
111
+ workerId: state.getWorkerId() ?? undefined,
105
112
  role: config.role,
106
113
  }),
107
114
  });
@@ -114,20 +121,44 @@ function registerWorker(api, config) {
114
121
  }
115
122
  }
116
123
  async function reportCheckpoint(taskId, checkpoint) {
117
- if (!currentControllerUrl) {
124
+ const controllerUrl = state.getControllerUrl();
125
+ if (!controllerUrl) {
118
126
  return;
119
127
  }
120
128
  try {
121
- await fetch(`${currentControllerUrl}/api/v1/tasks/${taskId}/checkpoint`, {
129
+ await fetch(`${controllerUrl}/api/v1/tasks/${taskId}/checkpoint`, {
122
130
  method: "POST",
123
- headers: { "Content-Type": "application/json" },
124
- body: JSON.stringify({ ...checkpoint, workerId: currentWorkerId ?? undefined }),
131
+ headers: withDeviceToken(config, { "Content-Type": "application/json" }),
132
+ body: JSON.stringify({ ...checkpoint, workerId: state.getWorkerId() ?? undefined }),
125
133
  });
126
134
  }
127
135
  catch {
128
136
  // Checkpointing is best-effort; a lost heartbeat only costs resume freshness.
129
137
  }
130
138
  }
139
+ return { reportExecutionEvent, reportCheckpoint };
140
+ }
141
+ function registerWorker(api, config) {
142
+ const logger = api.logger;
143
+ const messageQueue = new MessageQueue();
144
+ let currentControllerUrl = null;
145
+ let currentWorkerId = null;
146
+ function getIdentity() {
147
+ if (!currentWorkerId || !currentControllerUrl)
148
+ return null;
149
+ return {
150
+ workerId: currentWorkerId,
151
+ role: config.role,
152
+ controllerUrl: currentControllerUrl,
153
+ registeredAt: Date.now(),
154
+ };
155
+ }
156
+ const { reportExecutionEvent, reportCheckpoint } = createWorkerEventReporters(config, logger, {
157
+ // Read through getters so the reporters always see the identity the
158
+ // worker service has established by the time an event fires.
159
+ getControllerUrl: () => currentControllerUrl,
160
+ getWorkerId: () => currentWorkerId,
161
+ });
131
162
  const getWorkerSessionKey = (assignment) => assignment.executionSessionKey?.trim() || `teamclaw-task-${assignment.taskId}`;
132
163
  const taskExecutor = createRoleTaskExecutor({
133
164
  runtime: api.runtime,
@@ -155,15 +186,6 @@ function registerWorker(api, config) {
155
186
  }
156
187
  return { sharedProjectDir, localProjectDir };
157
188
  }
158
- async function pathExists(targetPath) {
159
- try {
160
- await fs.access(targetPath);
161
- return true;
162
- }
163
- catch {
164
- return false;
165
- }
166
- }
167
189
  async function syncProjectDir(sourceDir, destinationDir) {
168
190
  if (!await pathExists(sourceDir)) {
169
191
  return false;
@@ -103,6 +103,26 @@ function buildConfigSchema() {
103
103
  default: "",
104
104
  description: "GitHub App OAuth client secret; the TEAMCLAW_GITHUB_CLIENT_SECRET environment variable takes precedence",
105
105
  },
106
+ security: {
107
+ type: "object",
108
+ default: {},
109
+ description: "Controller device-pairing security (issue #23); protection itself is enabled per-team via POST /api/v1/security/enable",
110
+ properties: {
111
+ autoPair: {
112
+ type: "boolean",
113
+ default: true,
114
+ description: "Allow zero-input pairing from LAN peers (POST /api/v1/security/pair-auto); disable to require a pairing code for every new device",
115
+ },
116
+ },
117
+ },
118
+ securityToken: {
119
+ type: "string",
120
+ default: "",
121
+ // Deliberately NO uiHints entry: the token is a secret written by
122
+ // `teamclaw pair` / the desktop pairing flow and must never be
123
+ // echoed back through config surfaces or logs.
124
+ description: "Device pairing token for a protected controller (issue #23); written by `teamclaw pair`, sent as X-TeamClaw-Token on API calls. Leave empty for unpaired local mode",
125
+ },
106
126
  agentIsolationMode: {
107
127
  type: "string",
108
128
  enum: ["independent", "main"],
@@ -307,6 +327,10 @@ function buildConfigSchema() {
307
327
  hint: "optional - prefer the TEAMCLAW_GITHUB_CLIENT_SECRET env var",
308
328
  help: "GitHub App OAuth client secret; the TEAMCLAW_GITHUB_CLIENT_SECRET environment variable takes precedence",
309
329
  },
330
+ security: {
331
+ label: "Device Pairing Security",
332
+ help: "Controller device-pairing options; autoPair allows LAN devices to pair with zero input (POST /api/v1/security/pair-auto), disable it to require a pairing code for every new device",
333
+ },
310
334
  agentIsolationMode: {
311
335
  label: "Agent Isolation Mode",
312
336
  help: "Use a dedicated TeamClaw agent/workspace by default, or the legacy shared main-agent mode",
@@ -0,0 +1,129 @@
1
+ import { parseJsonBody, sendJson, sendError } from "../protocol.js";
2
+ import { getGithubAuthManager } from "./github-auth.js";
3
+ function resolveRequestOrigin(req, config) {
4
+ const host = req.headers.host;
5
+ if (typeof host === "string" && host.trim()) {
6
+ return `http://${host.trim()}`;
7
+ }
8
+ return `http://127.0.0.1:${config.port}`;
9
+ }
10
+ function escapeHtmlText(value) {
11
+ return value
12
+ .replace(/&/g, "&amp;")
13
+ .replace(/</g, "&lt;")
14
+ .replace(/>/g, "&gt;")
15
+ .replace(/"/g, "&quot;")
16
+ .replace(/'/g, "&#39;");
17
+ }
18
+ function sendGithubCallbackHtml(res, statusCode, title, message) {
19
+ const html = [
20
+ "<!DOCTYPE html><html><head><meta charset=\"utf-8\">",
21
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
22
+ `<title>${escapeHtmlText(title)}</title>`,
23
+ "<style>body{font-family:-apple-system,system-ui,sans-serif;display:flex;min-height:100vh;align-items:center;justify-content:center;margin:0;background:#0f1117;color:#e6e8ee}main{max-width:520px;padding:32px 40px;border:1px solid #2a2f3a;border-radius:14px;background:#161923;text-align:center}h1{font-size:20px;margin:0 0 10px}p{margin:6px 0;color:#a8b0c0;line-height:1.6}</style>",
24
+ "</head><body><main>",
25
+ `<h1>${escapeHtmlText(title)}</h1>`,
26
+ `<p>${escapeHtmlText(message)}</p>`,
27
+ "</main></body></html>",
28
+ ].join("");
29
+ res.writeHead(statusCode, {
30
+ "Content-Type": "text/html; charset=utf-8",
31
+ "Content-Length": Buffer.byteLength(html),
32
+ });
33
+ res.end(html);
34
+ }
35
+ async function githubAuthStatusRoute(ctx) {
36
+ const { req, res, deps } = ctx;
37
+ const { config, logger } = deps;
38
+ try {
39
+ const status = await getGithubAuthManager(config, logger).getStatus(resolveRequestOrigin(req, config));
40
+ sendJson(res, 200, status);
41
+ }
42
+ catch (err) {
43
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read GitHub login status");
44
+ }
45
+ }
46
+ async function githubAuthLoginRoute(ctx) {
47
+ const { req, res, deps } = ctx;
48
+ const { config, logger } = deps;
49
+ let flow;
50
+ try {
51
+ const body = await parseJsonBody(req);
52
+ if (typeof body?.flow === "string") {
53
+ flow = body.flow.trim();
54
+ }
55
+ }
56
+ catch {
57
+ // No body or invalid body: fall through to the default (device) flow.
58
+ }
59
+ const manager = getGithubAuthManager(config, logger);
60
+ try {
61
+ const loginPageUrl = resolveRequestOrigin(req, config).replace(/\/+$/, "") + "/ui/auth/github";
62
+ if (flow === "web") {
63
+ // Web flow needs a client secret for the code exchange; the device
64
+ // flow (default) is fully secretless.
65
+ const start = manager.beginLogin(resolveRequestOrigin(req, config));
66
+ sendJson(res, 200, { mode: "web", loginPageUrl, ...start });
67
+ }
68
+ else {
69
+ const start = await manager.beginDeviceLogin();
70
+ // authorizeUrl intentionally points at our standalone login page so
71
+ // older UI clients that just open response.authorizeUrl land on the
72
+ // device-code page instead of a dead web-flow URL.
73
+ sendJson(res, 200, { mode: "device", loginPageUrl, authorizeUrl: loginPageUrl, ...start });
74
+ }
75
+ logger.info(`Controller: GitHub login flow started (${flow === "web" ? "web" : "device"})`);
76
+ }
77
+ catch (err) {
78
+ sendError(res, 400, err instanceof Error ? err.message : "failed to start GitHub login");
79
+ }
80
+ }
81
+ async function githubAuthCallbackRoute(ctx) {
82
+ const { req, res, requestUrl, deps } = ctx;
83
+ const { config, logger } = deps;
84
+ const callbackError = requestUrl.searchParams.get("error");
85
+ if (callbackError) {
86
+ const description = requestUrl.searchParams.get("error_description") ?? "";
87
+ logger.warn(`Controller: GitHub login was denied (${callbackError})`);
88
+ sendGithubCallbackHtml(res, 400, "GitHub login failed", `Authorization was denied: ${callbackError}${description ? ` (${description})` : ""}`);
89
+ return;
90
+ }
91
+ const code = requestUrl.searchParams.get("code") ?? "";
92
+ const state = requestUrl.searchParams.get("state") ?? "";
93
+ try {
94
+ const account = await getGithubAuthManager(config, logger).completeLogin({
95
+ code: code || undefined,
96
+ state: state || undefined,
97
+ });
98
+ logger.info(`Controller: GitHub login completed for @${account.login}`);
99
+ sendGithubCallbackHtml(res, 200, "GitHub login successful", `Signed in as @${account.login}(GitHub 登录成功,可关闭本页返回 TeamClaw)。`);
100
+ }
101
+ catch (err) {
102
+ const message = err instanceof Error ? err.message : String(err);
103
+ logger.warn(`Controller: GitHub login callback failed: ${message}`);
104
+ sendGithubCallbackHtml(res, 400, "GitHub login failed", `${message}`);
105
+ }
106
+ }
107
+ async function githubAuthLogoutRoute(ctx) {
108
+ const { res, deps } = ctx;
109
+ const { config, logger } = deps;
110
+ try {
111
+ await getGithubAuthManager(config, logger).logout();
112
+ sendJson(res, 200, { ok: true });
113
+ }
114
+ catch (err) {
115
+ sendError(res, 500, err instanceof Error ? err.message : "failed to sign out of GitHub");
116
+ }
117
+ }
118
+ async function githubAuthRefreshRoute(ctx) {
119
+ const { res, deps } = ctx;
120
+ const { config, logger } = deps;
121
+ try {
122
+ const store = await getGithubAuthManager(config, logger).forceRefresh();
123
+ sendJson(res, 200, { ok: true, account: store.account, expiresAt: store.expiresAt });
124
+ }
125
+ catch (err) {
126
+ sendError(res, 400, err instanceof Error ? err.message : "failed to refresh the GitHub token");
127
+ }
128
+ }
129
+ export { githubAuthStatusRoute, githubAuthLoginRoute, githubAuthCallbackRoute, githubAuthLogoutRoute, githubAuthRefreshRoute, };
@@ -1,7 +1,7 @@
1
1
  import { generateId, parseJsonBody, sendError, sendJson } from "../protocol.js";
2
2
  import { ensureTeamMessageContract } from "../interaction-contracts.js";
3
3
  import { validateActiveRoleId } from "../profile-loader.js";
4
- import { normalizeClarificationQuestionSchema } from "./orchestration-manifest.js";
4
+ import { normalizeClarificationQuestionSchema } from "../shared/clarification-schema.js";
5
5
  import { cancelTaskExecution, recordTaskExecutionEvent, resetTaskForFreshAttempt, serializeTask, } from "./task-execution.js";
6
6
  import { assignTaskToWorker } from "./task-assignment.js";
7
7
  import { routeDirectMessage } from "./message-delivery.js";
@@ -465,6 +465,7 @@ export async function createControllerManagedTask(input, deps) {
465
465
  recommendedSkills: normalizedRecommendedSkills.length > 0 ? normalizedRecommendedSkills : undefined,
466
466
  controllerRunId: input.createdBy === "controller" ? input.controllerRunId : undefined,
467
467
  controllerSessionKey: normalizedSessionKey,
468
+ workflow: input.workflow,
468
469
  projectId,
469
470
  projectDir,
470
471
  createdAt: now,