@teamclaws/teamclaw 2026.4.4 → 2026.6.0

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.
@@ -2,6 +2,8 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import http from "node:http";
4
4
  import zlib from "node:zlib";
5
+ import { createHash } from "node:crypto";
6
+ import { execFileSync } from "node:child_process";
5
7
  import type { IncomingMessage, ServerResponse } from "node:http";
6
8
  import type { OpenClawPluginApi, PluginLogger } from "../../api.js";
7
9
  import type {
@@ -51,6 +53,10 @@ import { TeamWebSocketServer } from "./websocket.js";
51
53
  import type { WorkerProvisioningManager } from "./worker-provisioning.js";
52
54
  import type { PreviewManager } from "./preview-manager.js";
53
55
  import { createControllerPromptInjector } from "./prompt-injector.js";
56
+ import { getGithubAuthManager } from "./github-auth.js";
57
+ import { createTunnelManager, gatePageHtml, computeGateCookie, GATE_COOKIE_NAME, type TunnelManager } from "./tunnel-manager.js";
58
+ import { createGithubClient } from "../teamauto/github-client.js";
59
+ import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
54
60
  import { buildControllerNoWorkersMessage, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
55
61
  import { generateDeliveryReport, isSessionComplete, renderReportHtml, type DeliveryReport } from "./delivery-report.js";
56
62
  import {
@@ -93,6 +99,8 @@ export type ControllerHttpDeps = {
93
99
  previewManager?: PreviewManager;
94
100
  /** Late-bound kickoff handler for automatic team kickoff on complex projects. */
95
101
  getKickoffHandler?: () => KickoffHandler | undefined;
102
+ /** Late-bound TeamAuto scheduler (autonomous repo collaboration). */
103
+ getTeamAutoScheduler?: () => TeamAutoScheduler | null;
96
104
  };
97
105
 
98
106
  const MAX_TASK_EXECUTION_EVENTS = 250;
@@ -3460,6 +3468,22 @@ function scheduleProvisioningReconcile(deps: ControllerHttpDeps, reason: string)
3460
3468
  void deps.workerProvisioningManager?.requestReconcile(reason);
3461
3469
  }
3462
3470
 
3471
+ /** Collaboration contract helpers: at most ONE active write task per repo checkout. */
3472
+ function taskWriteRoot(task: TaskInfo): string | null {
3473
+ if (task.writeMode === "read-only" || !task.projectDir) { return null; }
3474
+ return task.projectDir.split("__task-")[0] ?? task.projectDir;
3475
+ }
3476
+
3477
+ function activeWriteRoots(state: TeamState): Set<string> {
3478
+ const roots = new Set<string>();
3479
+ for (const t of Object.values(state.tasks)) {
3480
+ if (t.status !== "assigned" && t.status !== "in_progress") { continue; }
3481
+ const root = taskWriteRoot(t);
3482
+ if (root) { roots.add(root); }
3483
+ }
3484
+ return roots;
3485
+ }
3486
+
3463
3487
  function broadcastTaskExecutionEvent(
3464
3488
  taskId: string,
3465
3489
  task: TaskInfo,
@@ -3560,12 +3584,61 @@ async function cancelTaskExecution(
3560
3584
  }, deps);
3561
3585
  }
3562
3586
 
3587
+ // Tunnel/CDN caches rewrite the origin's Cache-Control: no-cache into a long
3588
+ // browser freeze for cacheable extensions like .js (observed: Cloudflare
3589
+ // Browser Cache TTL max-age=14400 on tunneled UI assets). A UI update then
3590
+ // never reaches visitors through the tunnel. Serving content-versioned URLs
3591
+ // (?v=<hash>) makes every UI deploy a URL no browser or edge has ever seen,
3592
+ // so stale-cache behavior cannot recur.
3593
+ const uiAssetVersionCache = new Map<string, { mtimeMs: number; version: string }>();
3594
+
3595
+ function uiAssetVersion(uiPath: string, file: string): string {
3596
+ const full = path.join(uiPath, file);
3597
+ try {
3598
+ const mtimeMs = fs.statSync(full).mtimeMs;
3599
+ const cached = uiAssetVersionCache.get(full);
3600
+ if (cached && cached.mtimeMs === mtimeMs) return cached.version;
3601
+ const version = createHash("sha1").update(fs.readFileSync(full)).digest("hex").slice(0, 10);
3602
+ uiAssetVersionCache.set(full, { mtimeMs, version });
3603
+ return version;
3604
+ } catch {
3605
+ return String(Date.now()); // unreadable asset: bust for this request
3606
+ }
3607
+ }
3608
+
3609
+ const UI_HTML_ASSET_REFS = [
3610
+ "/ui/style.css",
3611
+ "/ui/app.js",
3612
+ "/ui/assets/teamclaw-app-icon.png",
3613
+ ];
3614
+
3615
+ function serveVersionedHtml(res: ServerResponse, htmlPath: string): void {
3616
+ try {
3617
+ const uiPath = path.dirname(htmlPath);
3618
+ let html = fs.readFileSync(htmlPath, "utf8");
3619
+ for (const ref of UI_HTML_ASSET_REFS) {
3620
+ html = html.split(`"${ref}"`).join(`"${ref}?v=${uiAssetVersion(uiPath, ref.slice("/ui/".length))}"`);
3621
+ }
3622
+ res.writeHead(200, {
3623
+ "Content-Type": "text/html; charset=utf-8",
3624
+ "Access-Control-Allow-Origin": "*",
3625
+ "Cache-Control": "no-cache",
3626
+ });
3627
+ res.end(html);
3628
+ } catch {
3629
+ sendError(res, 404, "File not found");
3630
+ }
3631
+ }
3632
+
3563
3633
  function serveStaticFile(res: ServerResponse, filePath: string, contentType: string): void {
3564
3634
  try {
3565
3635
  const content = fs.readFileSync(filePath);
3566
3636
  res.writeHead(200, {
3567
3637
  "Content-Type": contentType,
3568
3638
  "Access-Control-Allow-Origin": "*",
3639
+ // UI assets change with every plugin deploy on a localhost controller;
3640
+ // always revalidate so browsers never stick to a stale app.js.
3641
+ "Cache-Control": "no-cache",
3569
3642
  });
3570
3643
  res.end(content);
3571
3644
  } catch {
@@ -3869,6 +3942,18 @@ function projectHasMeaningfulFileChanges(
3869
3942
  if (!fs.existsSync(projectRoot)) {
3870
3943
  return false;
3871
3944
  }
3945
+ // Collaboration contract: write tasks deliver in a dedicated worktree.
3946
+ // An mtime scan is the wrong test there (committed files keep old mtimes
3947
+ // and the gate may run before the flush) - ask git instead: does HEAD carry
3948
+ // commits beyond the remote refs?
3949
+ if (task.projectDir.includes("__task-")) {
3950
+ try {
3951
+ const out = execFileSync("git", ["rev-list", "--count", "HEAD", "--not", "--remotes"], { cwd: projectRoot }).toString();
3952
+ return Number(out.trim()) > 0;
3953
+ } catch {
3954
+ return false;
3955
+ }
3956
+ }
3872
3957
  const threshold = Math.max(task.startedAt ?? 0, task.createdAt ?? 0) - 1000;
3873
3958
  const stack = [projectRoot];
3874
3959
  while (stack.length > 0) {
@@ -4403,7 +4488,7 @@ async function dispatchTaskToWorker(
4403
4488
  worker: WorkerInfo,
4404
4489
  deps: ControllerHttpDeps,
4405
4490
  ): Promise<void> {
4406
- const { getTeamState } = deps;
4491
+ const { getTeamState, logger, updateTeamState } = deps;
4407
4492
  const state = getTeamState();
4408
4493
  const task = state?.tasks[taskId];
4409
4494
  if (!task) {
@@ -4416,22 +4501,49 @@ async function dispatchTaskToWorker(
4416
4501
  try { fs.mkdirSync(projectPath, { recursive: true }); } catch { /* best-effort */ }
4417
4502
  }
4418
4503
 
4504
+ // Collaboration contract: WRITE tasks execute in a task-scoped git worktree
4505
+ // (branch teamclaw/task-<id>) so parallel roles never share a dirty checkout;
4506
+ // delivery happens via push + PR in the write-back reconciler.
4507
+ let assignmentProjectDir = task.projectDir;
4508
+ if (task.writeMode === "write" && task.projectDir?.startsWith("teamauto/") && !task.projectDir.includes("__task-")) {
4509
+ const scheduler = deps.getTeamAutoScheduler?.();
4510
+ if (scheduler) {
4511
+ const repoId = task.projectDir.slice("teamauto/".length).replace(/__/g, "/");
4512
+ try {
4513
+ assignmentProjectDir = await scheduler.ensureWriteWorktree(repoId, taskId);
4514
+ updateTeamState((s) => {
4515
+ const t = s.tasks[taskId];
4516
+ if (t) { t.projectDir = assignmentProjectDir; }
4517
+ });
4518
+ logger.info(`Controller: write task ${taskId} -> worktree projects/${assignmentProjectDir}`);
4519
+ } catch (err) {
4520
+ logger.warn(`Controller: worktree setup failed for ${taskId}, falling back to shared checkout: ${String(err)}`);
4521
+ }
4522
+ }
4523
+ }
4524
+
4419
4525
  const sharedWorkspace = deps.workerProvisioningManager?.isSharedWorkspaceWorker(worker.id)
4420
4526
  || false;
4421
4527
  const repoState = await refreshControllerRepoState(deps);
4422
4528
  const repoInfo = buildRepoSyncInfo(repoState, sharedWorkspace);
4423
4529
  const description = buildTaskAssignmentDescription(task, state ?? null, repoInfo);
4424
4530
  const recommendedSkills = resolveRecommendedSkillsForRole(task.assignedRole, task.recommendedSkills ?? []);
4425
- const executionIdentity = buildTaskExecutionIdentity(task.id, worker.id);
4531
+ // Resume support: reuse the interrupted execution's session so the worker
4532
+ // continues the same persisted OpenClaw conversation instead of starting over.
4533
+ const executionIdentity = (task.checkpoint?.sessionKey)
4534
+ ? { executionSessionKey: task.checkpoint.sessionKey, executionIdempotencyKey: buildTaskExecutionIdentity(task.id, worker.id).executionIdempotencyKey }
4535
+ : buildTaskExecutionIdentity(task.id, worker.id);
4426
4536
  const assignment: TaskAssignmentPayload = {
4427
4537
  taskId: task.id,
4428
4538
  title: task.title,
4429
4539
  description,
4430
4540
  priority: task.priority,
4431
4541
  recommendedSkills,
4432
- projectDir: task.projectDir,
4542
+ projectDir: assignmentProjectDir,
4433
4543
  executionSessionKey: executionIdentity.executionSessionKey,
4434
4544
  executionIdempotencyKey: executionIdentity.executionIdempotencyKey,
4545
+ checkpoint: task.checkpoint,
4546
+ resumeAttempt: task.resumeAttempt,
4435
4547
  repo: repoInfo,
4436
4548
  teamContext: buildTaskContextSnapshot(task, state ?? null),
4437
4549
  };
@@ -4518,7 +4630,7 @@ async function assignTaskToWorker(
4518
4630
  return deps.getTeamState()?.tasks[taskId];
4519
4631
  }
4520
4632
 
4521
- async function autoAssignPendingTasks(
4633
+ export async function autoAssignPendingTasks(
4522
4634
  deps: ControllerHttpDeps,
4523
4635
  preferredWorkerId?: string,
4524
4636
  ): Promise<TaskInfo[]> {
@@ -4544,9 +4656,16 @@ async function autoAssignPendingTasks(
4544
4656
  break;
4545
4657
  }
4546
4658
 
4659
+ // Collaboration contract: serialize write tasks per repo checkout - a
4660
+ // second writer on the same root waits until the active one settles.
4661
+ const busyWriteRoots = activeWriteRoots(state);
4547
4662
  const candidateAssignments = taskRouter
4548
4663
  .autoAssignPendingTasks(state.tasks, state.workers)
4549
- .filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`));
4664
+ .filter(({ task, worker }) => !attemptedPairs.has(`${task.id}:${worker.id}`))
4665
+ .filter(({ task }) => {
4666
+ const root = taskWriteRoot(task);
4667
+ return !(root && busyWriteRoots.has(root));
4668
+ });
4550
4669
 
4551
4670
  const nextAssignment = (
4552
4671
  (preferredWorkerId
@@ -4587,6 +4706,16 @@ async function autoAssignPendingTasks(
4587
4706
 
4588
4707
  export function createControllerHttpServer(deps: ControllerHttpDeps): http.Server {
4589
4708
  const { logger, wsServer } = deps;
4709
+ let tunnelManagerSingleton: TunnelManager | null = null;
4710
+
4711
+ const readFormBody = async (request: IncomingMessage): Promise<Record<string, unknown>> => {
4712
+ const chunks: Buffer[] = [];
4713
+ for await (const chunk of request) chunks.push(chunk as Buffer);
4714
+ const raw = Buffer.concat(chunks).toString("utf8");
4715
+ const out: Record<string, unknown> = {};
4716
+ for (const [k, v] of new URLSearchParams(raw)) out[k] = v;
4717
+ return out;
4718
+ };
4590
4719
 
4591
4720
  const server = http.createServer(async (req: IncomingMessage, res: ServerResponse) => {
4592
4721
  // CORS preflight
@@ -4603,6 +4732,76 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
4603
4732
  const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
4604
4733
  const pathname = url.pathname;
4605
4734
 
4735
+ // Tunnel sharing: every request arriving via <user>.apps.teamclaw.dev is
4736
+ // gated behind the token the local web UI displays.
4737
+ let tunnelManager = tunnelManagerSingleton;
4738
+ if (!tunnelManager) {
4739
+ tunnelManager = tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
4740
+ }
4741
+ const viaTunnel = tunnelManager.isTunnelRequest(typeof req.headers.host === "string" ? req.headers.host : undefined);
4742
+ if (viaTunnel) {
4743
+ if (req.method === "GET" && (pathname === "/__tunnel_gate" || pathname === "/")) {
4744
+ // Valid gate cookie on "/" goes straight to the dashboard; the gate
4745
+ // page only greets visitors who have not authenticated yet.
4746
+ if (pathname === "/" && tunnelManager.gateAllows(req)) {
4747
+ res.writeHead(302, { Location: "/ui/" });
4748
+ res.end();
4749
+ return;
4750
+ }
4751
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
4752
+ res.end(gatePageHtml(String(req.headers.host), false));
4753
+ return;
4754
+ }
4755
+ if (req.method === "POST" && pathname === "/__tunnel_gate/verify") {
4756
+ const form = await readFormBody(req);
4757
+ const submitted = String((form as { token?: unknown }).token ?? "").trim().toUpperCase();
4758
+ const st = tunnelManager.status();
4759
+ if (st.active && st.gateToken && submitted === st.gateToken) {
4760
+ const cookie = `${GATE_COOKIE_NAME}=${computeGateCookie(st.gateToken, st.tunnelId ?? "")}; Path=/; Max-Age=43200; HttpOnly; SameSite=Lax`;
4761
+ res.writeHead(302, { "Set-Cookie": cookie, Location: "/" });
4762
+ res.end();
4763
+ return;
4764
+ }
4765
+ res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
4766
+ res.end(gatePageHtml(String(req.headers.host), true));
4767
+ return;
4768
+ }
4769
+ if (!tunnelManager.gateAllows(req)) {
4770
+ res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
4771
+ res.end(gatePageHtml(String(req.headers.host), false));
4772
+ return;
4773
+ }
4774
+ } else {
4775
+ if (req.method === "GET" && pathname === "/api/v1/tunnel/status") {
4776
+ sendJson(res, 200, tunnelManager.status());
4777
+ return;
4778
+ }
4779
+ if (req.method === "POST" && pathname === "/api/v1/tunnel/start") {
4780
+ const authStatus = await getGithubAuthManager(deps.config, logger).getStatus();
4781
+ const account = authStatus.account;
4782
+ if (!account?.login) { sendError(res, 401, "GitHub login required to share a tunnel"); return; }
4783
+ // Async launch: poll /tunnel/status for phase progress and the
4784
+ // resulting hostname/gateToken once startOp.phase === "done".
4785
+ const launched = tunnelManager.start(account.login);
4786
+ sendJson(res, 202, { launched, status: tunnelManager.status() });
4787
+ return;
4788
+ }
4789
+ if (req.method === "POST" && pathname === "/api/v1/tunnel/stop") {
4790
+ await tunnelManager.stop();
4791
+ sendJson(res, 200, tunnelManager.status());
4792
+ return;
4793
+ }
4794
+ if (req.method === "POST" && pathname === "/api/v1/tunnel/install-cloudflared") {
4795
+ try {
4796
+ const result = await tunnelManager.installCloudflared();
4797
+ sendJson(res, result.ok ? 200 : 500, { ...result, status: tunnelManager.status() });
4798
+ } catch (err) {
4799
+ sendError(res, 500, err instanceof Error ? err.message : "install failed");
4800
+ }
4801
+ return;
4802
+ }
4803
+ }
4804
+
4606
4805
  try {
4607
4806
  await handleRequest(req, res, pathname, deps);
4608
4807
  } catch (err) {
@@ -4614,6 +4813,21 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
4614
4813
  // Attach WebSocket
4615
4814
  wsServer.attach(server);
4616
4815
 
4816
+ // Plugin shutdown: kill the local connector and tear down the remote
4817
+ // tunnel so gateway exits never leak orphan cloudflared processes.
4818
+ server.on("close", () => {
4819
+ void tunnelManagerSingleton?.stop().catch(() => undefined);
4820
+ });
4821
+
4822
+ // Boot reconciliation: reconnect a share persisted by a previous run
4823
+ // (gateway restart or kill -9) so the tunnel id and gate token survive.
4824
+ if (!tunnelManagerSingleton) {
4825
+ tunnelManagerSingleton = createTunnelManager({ logger, localPort: deps.config.port });
4826
+ }
4827
+ void tunnelManagerSingleton.recover().catch((err) => {
4828
+ logger.warn(`TeamClaw tunnel: boot recovery failed: ${String(err)}`);
4829
+ });
4830
+
4617
4831
  setTimeout(() => {
4618
4832
  const state = deps.getTeamState();
4619
4833
  const pendingCount = state
@@ -4630,12 +4844,48 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
4630
4844
  return server;
4631
4845
  }
4632
4846
 
4847
+ function resolveRequestOrigin(req: IncomingMessage, config: PluginConfig): string {
4848
+ const host = req.headers.host;
4849
+ if (typeof host === "string" && host.trim()) {
4850
+ return `http://${host.trim()}`;
4851
+ }
4852
+ return `http://127.0.0.1:${config.port}`;
4853
+ }
4854
+
4855
+ function escapeHtmlText(value: string): string {
4856
+ return value
4857
+ .replace(/&/g, "&amp;")
4858
+ .replace(/</g, "&lt;")
4859
+ .replace(/>/g, "&gt;")
4860
+ .replace(/"/g, "&quot;")
4861
+ .replace(/'/g, "&#39;");
4862
+ }
4863
+
4864
+ function sendGithubCallbackHtml(res: ServerResponse, statusCode: number, title: string, message: string): void {
4865
+ const html = [
4866
+ "<!DOCTYPE html><html><head><meta charset=\"utf-8\">",
4867
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">",
4868
+ `<title>${escapeHtmlText(title)}</title>`,
4869
+ "<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>",
4870
+ "</head><body><main>",
4871
+ `<h1>${escapeHtmlText(title)}</h1>`,
4872
+ `<p>${escapeHtmlText(message)}</p>`,
4873
+ "</main></body></html>",
4874
+ ].join("");
4875
+ res.writeHead(statusCode, {
4876
+ "Content-Type": "text/html; charset=utf-8",
4877
+ "Content-Length": Buffer.byteLength(html),
4878
+ });
4879
+ res.end(html);
4880
+ }
4881
+
4633
4882
  async function handleRequest(
4634
4883
  req: IncomingMessage,
4635
4884
  res: ServerResponse,
4636
4885
  pathname: string,
4637
4886
  deps: ControllerHttpDeps,
4638
4887
  ): Promise<void> {
4888
+ void pathname;
4639
4889
  const { config, logger, getTeamState, updateTeamState, taskRouter, messageRouter, wsServer } = deps;
4640
4890
  const requestUrl = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
4641
4891
  const currentState = getTeamState();
@@ -4650,7 +4900,14 @@ async function handleRequest(
4650
4900
 
4651
4901
  if (req.method === "GET" && (pathname === "/ui" || pathname === "/ui/")) {
4652
4902
  const uiPath = path.join(import.meta.dirname, "..", "ui");
4653
- serveStaticFile(res, path.join(uiPath, "index.html"), "text/html; charset=utf-8");
4903
+ serveVersionedHtml(res, path.join(uiPath, "index.html"));
4904
+ return;
4905
+ }
4906
+
4907
+ // Standalone GitHub device-login page (big user code + prefilled link + polling).
4908
+ if (req.method === "GET" && (pathname === "/ui/auth/github" || pathname === "/ui/auth/github/")) {
4909
+ const uiPath = path.join(import.meta.dirname, "..", "ui");
4910
+ serveStaticFile(res, path.join(uiPath, "github-login.html"), "text/html; charset=utf-8");
4654
4911
  return;
4655
4912
  }
4656
4913
 
@@ -4673,6 +4930,191 @@ async function handleRequest(
4673
4930
  return;
4674
4931
  }
4675
4932
 
4933
+ // ==================== TeamAuto ====================
4934
+
4935
+ const teamAuto = deps.getTeamAutoScheduler?.() ?? null;
4936
+
4937
+ if (req.method === "GET" && pathname === "/api/v1/teamauto/activity") {
4938
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
4939
+ try {
4940
+ const activity = await teamAuto.getActivity();
4941
+ sendJson(res, 200, { activity });
4942
+ } catch (err) {
4943
+ sendError(res, 500, err instanceof Error ? err.message : "failed to load activity");
4944
+ }
4945
+ return;
4946
+ }
4947
+
4948
+ if (req.method === "GET" && pathname === "/api/v1/teamauto/repos") {
4949
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
4950
+ try {
4951
+ sendJson(res, 200, await teamAuto.getStatus());
4952
+ } catch (err) {
4953
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read TeamAuto status");
4954
+ }
4955
+ return;
4956
+ }
4957
+
4958
+ // Selectable repos for the bind picker (the logged-in GitHub account's).
4959
+ if (req.method === "GET" && pathname === "/api/v1/teamauto/repo-candidates") {
4960
+ try {
4961
+ const auth = getGithubAuthManager(config, logger);
4962
+ const candidates = await createGithubClient(auth).listUserRepos();
4963
+ sendJson(res, 200, { candidates });
4964
+ } catch (err) {
4965
+ sendError(res, 400, err instanceof Error ? err.message : "failed to list repositories");
4966
+ }
4967
+ return;
4968
+ }
4969
+
4970
+ if (req.method === "POST" && pathname === "/api/v1/teamauto/repos") {
4971
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
4972
+ let body: Record<string, unknown> = {};
4973
+ try { body = await parseJsonBody(req); } catch { /* empty body */ }
4974
+ const repo = typeof body.repo === "string" ? body.repo : "";
4975
+ if (!repo) { sendError(res, 400, "repo (owner/name) is required"); return; }
4976
+ try {
4977
+ const created = await teamAuto.addRepo(repo, {
4978
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
4979
+ keywordInclude: Array.isArray(body.keywordInclude) ? body.keywordInclude.filter((k): k is string => typeof k === "string") : undefined,
4980
+ keywordExclude: Array.isArray(body.keywordExclude) ? body.keywordExclude.filter((k): k is string => typeof k === "string") : undefined,
4981
+ });
4982
+ sendJson(res, 201, created);
4983
+ } catch (err) {
4984
+ sendError(res, 400, err instanceof Error ? err.message : "failed to bind repo");
4985
+ }
4986
+ return;
4987
+ }
4988
+
4989
+ if (pathname.startsWith("/api/v1/teamauto/repos/")) {
4990
+ if (!teamAuto) { sendError(res, 503, "TeamAuto scheduler is not running"); return; }
4991
+ const repoId = decodeURIComponent(pathname.slice("/api/v1/teamauto/repos/".length).replace(/\/sweep$/, ""));
4992
+ const isSweep = pathname.endsWith("/sweep");
4993
+ if (req.method === "DELETE" && !isSweep) {
4994
+ try { await teamAuto.removeRepo(repoId); sendJson(res, 200, { ok: true }); }
4995
+ catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to unbind"); }
4996
+ return;
4997
+ }
4998
+ if (req.method === "PATCH" && !isSweep) {
4999
+ let body: Record<string, unknown> = {};
5000
+ try { body = await parseJsonBody(req); } catch { /* empty */ }
5001
+ try {
5002
+ const updated = await teamAuto.updateRepo(repoId, {
5003
+ schedule: typeof body.schedule === "string" ? body.schedule : undefined,
5004
+ maxTasksPerSweep: typeof body.maxTasksPerSweep === "number" ? body.maxTasksPerSweep : undefined,
5005
+ fullReview: body.fullReview === "off" || body.fullReview === "weekly" || body.fullReview === "daily" ? body.fullReview : undefined,
5006
+ takeOwnership: typeof body.takeOwnership === "boolean" ? body.takeOwnership : undefined,
5007
+ });
5008
+ sendJson(res, 200, updated);
5009
+ } catch (err) { sendError(res, 400, err instanceof Error ? err.message : "failed to update"); }
5010
+ return;
5011
+ }
5012
+ if (req.method === "POST" && isSweep) {
5013
+ try { sendJson(res, 200, { summary: await teamAuto.runSweepNow(repoId, true) }); }
5014
+ catch (err) { sendError(res, 400, err instanceof Error ? err.message : "sweep failed"); }
5015
+ return;
5016
+ }
5017
+ }
5018
+
5019
+ // ==================== GitHub Auth ====================
5020
+
5021
+ if (req.method === "GET" && pathname === "/api/v1/auth/github/status") {
5022
+ try {
5023
+ const status = await getGithubAuthManager(config, logger).getStatus(resolveRequestOrigin(req, config));
5024
+ sendJson(res, 200, status);
5025
+ } catch (err) {
5026
+ sendError(res, 500, err instanceof Error ? err.message : "failed to read GitHub login status");
5027
+ }
5028
+ return;
5029
+ }
5030
+
5031
+ if (req.method === "POST" && pathname === "/api/v1/auth/github/login") {
5032
+ let flow: string | undefined;
5033
+ try {
5034
+ const body = await parseJsonBody(req) as { flow?: unknown };
5035
+ if (typeof body?.flow === "string") {
5036
+ flow = body.flow.trim();
5037
+ }
5038
+ } catch {
5039
+ // No body or invalid body: fall through to the default (device) flow.
5040
+ }
5041
+ const manager = getGithubAuthManager(config, logger);
5042
+ try {
5043
+ const loginPageUrl = resolveRequestOrigin(req, config).replace(/\/+$/, "") + "/ui/auth/github";
5044
+ if (flow === "web") {
5045
+ // Web flow needs a client secret for the code exchange; the device
5046
+ // flow (default) is fully secretless.
5047
+ const start = manager.beginLogin(resolveRequestOrigin(req, config));
5048
+ sendJson(res, 200, { mode: "web", loginPageUrl, ...start });
5049
+ } else {
5050
+ const start = await manager.beginDeviceLogin();
5051
+ // authorizeUrl intentionally points at our standalone login page so
5052
+ // older UI clients that just open response.authorizeUrl land on the
5053
+ // device-code page instead of a dead web-flow URL.
5054
+ sendJson(res, 200, { mode: "device", loginPageUrl, authorizeUrl: loginPageUrl, ...start });
5055
+ }
5056
+ logger.info(`Controller: GitHub login flow started (${flow === "web" ? "web" : "device"})`);
5057
+ } catch (err) {
5058
+ sendError(res, 400, err instanceof Error ? err.message : "failed to start GitHub login");
5059
+ }
5060
+ return;
5061
+ }
5062
+
5063
+ if (req.method === "GET" && pathname === "/api/v1/auth/github/callback") {
5064
+ const callbackError = requestUrl.searchParams.get("error");
5065
+ if (callbackError) {
5066
+ const description = requestUrl.searchParams.get("error_description") ?? "";
5067
+ logger.warn(`Controller: GitHub login was denied (${callbackError})`);
5068
+ sendGithubCallbackHtml(
5069
+ res,
5070
+ 400,
5071
+ "GitHub login failed",
5072
+ `Authorization was denied: ${callbackError}${description ? ` (${description})` : ""}`,
5073
+ );
5074
+ return;
5075
+ }
5076
+ const code = requestUrl.searchParams.get("code") ?? "";
5077
+ const state = requestUrl.searchParams.get("state") ?? "";
5078
+ try {
5079
+ const account = await getGithubAuthManager(config, logger).completeLogin({
5080
+ code: code || undefined,
5081
+ state: state || undefined,
5082
+ });
5083
+ logger.info(`Controller: GitHub login completed for @${account.login}`);
5084
+ sendGithubCallbackHtml(
5085
+ res,
5086
+ 200,
5087
+ "GitHub login successful",
5088
+ `Signed in as @${account.login}(GitHub 登录成功,可关闭本页返回 TeamClaw)。`,
5089
+ );
5090
+ } catch (err) {
5091
+ const message = err instanceof Error ? err.message : String(err);
5092
+ logger.warn(`Controller: GitHub login callback failed: ${message}`);
5093
+ sendGithubCallbackHtml(res, 400, "GitHub login failed", `${message}`);
5094
+ }
5095
+ return;
5096
+ }
5097
+
5098
+ if (req.method === "POST" && pathname === "/api/v1/auth/github/logout") {
5099
+ try {
5100
+ await getGithubAuthManager(config, logger).logout();
5101
+ sendJson(res, 200, { ok: true });
5102
+ } catch (err) {
5103
+ sendError(res, 500, err instanceof Error ? err.message : "failed to sign out of GitHub");
5104
+ }
5105
+ return;
5106
+ }
5107
+
5108
+ if (req.method === "POST" && pathname === "/api/v1/auth/github/refresh") {
5109
+ try {
5110
+ const store = await getGithubAuthManager(config, logger).forceRefresh();
5111
+ sendJson(res, 200, { ok: true, account: store.account, expiresAt: store.expiresAt });
5112
+ } catch (err) {
5113
+ sendError(res, 400, err instanceof Error ? err.message : "failed to refresh the GitHub token");
5114
+ }
5115
+ return;
5116
+ }
5117
+
4676
5118
  // ==================== Workspace Browser ====================
4677
5119
 
4678
5120
  if (req.method === "GET" && pathname === "/api/v1/workspace/status") {
@@ -5419,6 +5861,40 @@ function computeTeamStats(state: TeamState): TeamStatsResponse {
5419
5861
  return;
5420
5862
  }
5421
5863
 
5864
+ // POST /api/v1/tasks/:id/checkpoint - worker persists an execution progress
5865
+ // snapshot so an interrupted task can resume instead of restarting.
5866
+ if (req.method === "POST" && pathname.match(/^\/api\/v1\/tasks\/[^/]+\/checkpoint$/)) {
5867
+ const taskId = pathname.split("/")[4];
5868
+ let body: Record<string, unknown> = {};
5869
+ try { body = await parseJsonBody(req); } catch { sendError(res, 400, "invalid JSON body"); return; }
5870
+ const lastAssistantMessage = typeof body.lastAssistantMessage === "string" ? body.lastAssistantMessage.slice(0, 8000) : "";
5871
+ const progressNote = typeof body.progressNote === "string" ? body.progressNote.slice(0, 1000) : "";
5872
+ const sessionKey = typeof body.sessionKey === "string" ? body.sessionKey : "";
5873
+ if (!lastAssistantMessage && !progressNote) {
5874
+ sendError(res, 400, "lastAssistantMessage or progressNote is required");
5875
+ return;
5876
+ }
5877
+ const updated = updateTeamState((s) => {
5878
+ const task = s.tasks[taskId];
5879
+ if (!task) { return; }
5880
+ const prev = task.checkpoint;
5881
+ const notes = [...(prev?.progressNotes ?? [])];
5882
+ if (progressNote && !notes.includes(progressNote)) { notes.push(progressNote); }
5883
+ task.checkpoint = {
5884
+ updatedAt: Date.now(),
5885
+ attempt: prev?.attempt ?? 0,
5886
+ sessionKey: sessionKey || prev?.sessionKey || "",
5887
+ lastAssistantMessage: lastAssistantMessage || prev?.lastAssistantMessage || "",
5888
+ progressNotes: notes.slice(-10),
5889
+ };
5890
+ task.updatedAt = Date.now();
5891
+ });
5892
+ const task = updated?.tasks[taskId];
5893
+ if (!task) { sendError(res, 404, "task not found"); return; }
5894
+ sendJson(res, 200, { ok: true, updatedAt: task.checkpoint?.updatedAt });
5895
+ return;
5896
+ }
5897
+
5422
5898
  // POST /api/v1/tasks/:id/result-contract
5423
5899
  if (req.method === "POST" && pathname.match(/^\/api\/v1\/tasks\/[^/]+\/result-contract$/)) {
5424
5900
  const taskId = pathname.split("/")[4]!;
@@ -20,6 +20,7 @@ const TEAMCLAW_ROLE_IDS = new Set<RoleId>([
20
20
  "security-engineer",
21
21
  "designer",
22
22
  "marketing",
23
+ "data-engineer",
23
24
  ]);
24
25
 
25
26
  export function normalizeManifestRoleList(raw: unknown): RoleId[] {