@teamclaws/teamclaw 2026.7.0 → 2026.8.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.
package/README.md CHANGED
@@ -118,6 +118,14 @@ For a first-time setup, the safest path is:
118
118
 
119
119
  When on-demand provisioning is enabled, TeamClaw now treats controller startup as a readiness phase, not just a process-up check. During that warm-up, `/api/v1/health` returns a non-OK status until the controller has verified writable runtime paths and successfully brought the configured startup worker roles online. If `workerProvisioningRoles` is empty, startup readiness defaults to waiting for a warm `developer` worker.
120
120
 
121
+ ## Internet tunnel sharing
122
+
123
+ The Web UI ships with zero-config internet sharing (header `Tunnel` button):
124
+ managed `*.teamclaw.dev` (GitHub login, gate token), self-hosted Cloudflare
125
+ tunnels via connector token (`TEAMCLAW_TUNNEL_TOKEN` env or UI input), and
126
+ anonymous one-off tunnels (`*.trycloudflare.com` via cloudflared). See
127
+ the repo README's "Internet tunnel" section for the full matrix.
128
+
121
129
  ## Documentation
122
130
 
123
131
  - Website: <https://topcheer.github.io/teamclaw/>
package/index.ts CHANGED
@@ -39,6 +39,7 @@ function registerController(api: OpenClawPluginApi, config: ReturnType<typeof pa
39
39
  let getControllerTeamState = (): TeamState | null => null;
40
40
  let controllerUrl = `http://127.0.0.1:${config.port}`;
41
41
  let kickoffHandler: ((candidateRoles: import("./src/types.js").RoleId[], complexity: "simple" | "medium" | "complex", requirement: string) => Promise<{ assessments: import("./src/types.js").KickoffAssessment[]; summary: string }>) | undefined;
42
+ let getTeamAutoScheduler: () => import("./src/teamauto/scheduler.js").TeamAutoScheduler | null = () => null;
42
43
 
43
44
  // Service (starts HTTP server + mDNS + WebSocket)
44
45
  api.registerService(createControllerService({
@@ -55,6 +56,9 @@ function registerController(api: OpenClawPluginApi, config: ReturnType<typeof pa
55
56
  kickoffHandler = handler;
56
57
  logger.info("TeamClaw: kickoff handler registered successfully");
57
58
  },
59
+ onTeamAutoSchedulerAvailable: (getter) => {
60
+ getTeamAutoScheduler = getter;
61
+ },
58
62
  }));
59
63
 
60
64
  // Prompt injection
@@ -75,6 +79,7 @@ function registerController(api: OpenClawPluginApi, config: ReturnType<typeof pa
75
79
  getTeamState: getControllerTeamState,
76
80
  sessionKey: ctx.sessionKey ?? null,
77
81
  getKickoffHandler: () => kickoffHandler,
82
+ getTeamAutoScheduler: () => getTeamAutoScheduler(),
78
83
  });
79
84
  });
80
85
  }
@@ -2,7 +2,7 @@
2
2
  "id": "teamclaw",
3
3
  "name": "TeamClaw",
4
4
  "description": "Virtual team collaboration - multiple OpenClaw instances form a virtual software company with role-based task routing.",
5
- "version": "2026.7.0",
5
+ "version": "2026.8.0",
6
6
  "activation": {
7
7
  "onStartup": true
8
8
  },
@@ -22,7 +22,10 @@
22
22
  "teamclaw_send_message",
23
23
  "teamclaw_submit_manifest",
24
24
  "teamclaw_submit_result_contract",
25
- "teamclaw_suggest_handoff"
25
+ "teamclaw_suggest_handoff",
26
+ "teamclaw_teamauto_propose",
27
+ "teamclaw_teamauto_status",
28
+ "teamclaw_teamauto_sweep"
26
29
  ]
27
30
  },
28
31
  "skills": [
@@ -60,7 +63,7 @@
60
63
  "maxConcurrentTasks": {
61
64
  "label": "Max Concurrent Tasks",
62
65
  "hint": "number",
63
- "help": "Maximum number of tasks that can be in 'in_progress' status at the same time (1–50)"
66
+ "help": "Maximum number of tasks that can be in 'in_progress' status at the same time (1\u201350)"
64
67
  },
65
68
  "gitEnabled": {
66
69
  "label": "Git Collaboration",
package/package.json CHANGED
@@ -1,17 +1,19 @@
1
1
  {
2
2
  "name": "@teamclaws/teamclaw",
3
- "version": "2026.7.0",
4
- "description": "OpenClaw virtual software team orchestration plugin",
3
+ "version": "2026.8.0",
4
+ "description": "OpenClaw virtual software team orchestration plugin - controller, role-based workers, Web UI with internet tunnel sharing",
5
5
  "private": false,
6
6
  "keywords": [
7
- "openclaw",
8
- "plugin",
9
- "teamclaw",
7
+ "cloudflared",
10
8
  "multi-agent",
9
+ "multi-role",
10
+ "openclaw",
11
11
  "orchestration",
12
- "virtual-team",
12
+ "plugin",
13
13
  "sdlc",
14
- "multi-role"
14
+ "teamclaw",
15
+ "tunnel",
16
+ "virtual-team"
15
17
  ],
16
18
  "author": "Junjun Zhang <topcheer@me.com>",
17
19
  "homepage": "https://github.com/topcheer/teamclaw/tree/main/src#readme",
@@ -33,6 +33,8 @@ export type ControllerServiceDeps = {
33
33
  onActualPort?: (port: number) => void;
34
34
  /** Called once the kickoff handler is ready. */
35
35
  onKickoffHandlerAvailable?: (handler: KickoffHandler) => void;
36
+ /** Late-binding getter for the TeamAuto scheduler (created during service start). */
37
+ onTeamAutoSchedulerAvailable?: (getter: () => import("../teamauto/scheduler.js").TeamAutoScheduler | null) => void;
36
38
  };
37
39
 
38
40
  function getPreferredLanUiUrl(port: number): string | null {
@@ -274,6 +276,7 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
274
276
  },
275
277
  });
276
278
  await teamAutoSchedulerRef.start();
279
+ deps.onTeamAutoSchedulerAvailable?.(() => teamAutoSchedulerRef);
277
280
  } catch (err) {
278
281
  logger.warn(`Controller: TeamAuto scheduler failed to start: ${err instanceof Error ? err.message : String(err)}`);
279
282
  }
@@ -322,7 +325,20 @@ export function createControllerService(deps: ControllerServiceDeps): OpenClawPl
322
325
  const now = Date.now();
323
326
 
324
327
  for (const [workerId, worker] of Object.entries(teamState.workers)) {
325
- if (worker.status === "offline") continue;
328
+ if (worker.status === "offline") {
329
+ // Stale offline entries are dead session workers (provisioned
330
+ // per-task workers exit when their task ends; their registry
331
+ // entries used to linger forever and pile up - observed live:
332
+ // the intake agent read a wall of offline developers and
333
+ // misreported the repos they had served as "repo offline").
334
+ // Same reap semantics as the startup sweep, applied at runtime.
335
+ if (now - worker.lastHeartbeat > WORKER_TIMEOUT_MS) {
336
+ delete teamState.workers[workerId];
337
+ changed = true;
338
+ logger.info(`Controller: reaped stale offline worker ${workerId}`);
339
+ }
340
+ continue;
341
+ }
326
342
  if (now - worker.lastHeartbeat > WORKER_TIMEOUT_MS) {
327
343
  logger.info(`Controller: worker ${workerId} timed out`);
328
344
  const activeTaskId = worker.currentTaskId;
@@ -30,6 +30,8 @@ export type ControllerToolsDeps = {
30
30
  sessionKey?: string | null;
31
31
  /** Handler for kickoff meeting requests. Use a getter for late-binding (service may start after tool registration). */
32
32
  getKickoffHandler?: () => ((candidateRoles: RoleId[], complexity: "simple" | "medium" | "complex", requirement: string) => Promise<{ assessments: KickoffAssessment[]; summary: string }>) | undefined;
33
+ /** Late-binding TeamAuto scheduler getter (scheduler starts with the controller service). */
34
+ getTeamAutoScheduler?: () => import("../teamauto/scheduler.js").TeamAutoScheduler | null;
33
35
  };
34
36
 
35
37
  const EXECUTION_READY_BLOCKERS: Array<{ pattern: RegExp; reason: string }> = [
@@ -501,6 +503,76 @@ export function createControllerTools(deps: ControllerToolsDeps) {
501
503
  }
502
504
  },
503
505
  },
506
+ {
507
+ name: "teamclaw_teamauto_status",
508
+ label: "TeamAuto Status",
509
+ description: "List TeamAuto-managed repositories with their schedule, full-review cadence, pause state, and recent activity. Use this to discover which repos this controller autonomously maintains before proposing improvements to them.",
510
+ parameters: Type.Object({}),
511
+ async execute(_id: string, _params: Record<string, unknown>) {
512
+ const scheduler = deps.getTeamAutoScheduler?.();
513
+ if (!scheduler) {
514
+ return { details: {}, content: [{ type: "text" as const, text: "TeamAuto is not active on this controller." }] };
515
+ }
516
+ const status = await scheduler.getStatus();
517
+ const activity = (await scheduler.getActivity()).slice(-10).map((e: { at: number; repoId?: string; kind: string; text: string }) => `${new Date(e.at).toISOString().slice(11, 19)} ${e.repoId ?? ""} ${e.text}`);
518
+ return { details: {}, content: [{ type: "text" as const, text: `TeamAuto repos:\n${JSON.stringify(status, null, 2)}\nRecent activity:\n${activity.join("\n") || "(none)"}` }] };
519
+ },
520
+ },
521
+ {
522
+ name: "teamclaw_teamauto_sweep",
523
+ label: "TeamAuto Sweep Now",
524
+ description: "Trigger an immediate TeamAuto sweep of a bound repository (scans GitHub issues/PRs and creates review/ownership tasks) instead of waiting for the next cron tick.",
525
+ parameters: Type.Object({
526
+ repoId: Type.String({ description: "Bound repository id in owner/name form, e.g. topcheer/teamclaw" }),
527
+ }),
528
+ async execute(_id: string, params: Record<string, unknown>) {
529
+ const scheduler = deps.getTeamAutoScheduler?.();
530
+ if (!scheduler) {
531
+ return { details: {}, content: [{ type: "text" as const, text: "TeamAuto is not active on this controller." }] };
532
+ }
533
+ try {
534
+ const summary = await scheduler.runSweepNow(String(params.repoId ?? ""), true);
535
+ return { details: {}, content: [{ type: "text" as const, text: `Sweep done: ${summary}` }] };
536
+ } catch (err) {
537
+ return { details: {}, content: [{ type: "text" as const, text: `Sweep failed: ${err instanceof Error ? err.message : String(err)}` }] };
538
+ }
539
+ },
540
+ },
541
+ {
542
+ name: "teamclaw_teamauto_propose",
543
+ label: "TeamAuto Propose",
544
+ description: "Inject a manual work proposal into a TeamAuto-managed repository. The proposal flows through the normal TeamAuto task pipeline (dedup, failure caps, norms, worktree checkout, worker assignment) - no GitHub object is required. Prefer this over teamclaw_create_task when the target repo is TeamAuto-managed so the work inherits its governance.",
545
+ parameters: Type.Object({
546
+ repoId: Type.String({ description: "Bound repository id in owner/name form" }),
547
+ kind: Type.String({ description: "Candidate kind: issueReview, prReview, takeOwnership (write path), or fullReview" }),
548
+ title: Type.String({ description: "Short task title" }),
549
+ context: Type.String({ description: "Full task instructions: goal, scope, constraints, expected deliverable" }),
550
+ role: Type.Optional(Type.String({ description: "Target role id; defaults to developer for takeOwnership, architect otherwise" })),
551
+ writeMode: Type.Optional(Type.String({ description: "read-only (default) or write; takeOwnership defaults to write" })),
552
+ }),
553
+ async execute(_id: string, params: Record<string, unknown>) {
554
+ const scheduler = deps.getTeamAutoScheduler?.();
555
+ if (!scheduler) {
556
+ return { details: {}, content: [{ type: "text" as const, text: "TeamAuto is not active on this controller." }] };
557
+ }
558
+ const writeMode = params.writeMode === "write" ? "write" : params.writeMode === "read-only" ? "read-only" : undefined;
559
+ try {
560
+ const result = await scheduler.proposeManual(String(params.repoId ?? ""), {
561
+ kind: String(params.kind ?? "issueReview") as "issueReview" | "prReview" | "takeOwnership" | "fullReview",
562
+ title: String(params.title ?? ""),
563
+ context: String(params.context ?? ""),
564
+ role: params.role ? String(params.role) : undefined,
565
+ writeMode,
566
+ });
567
+ if (result === "duplicate-active-skipped") {
568
+ return { details: {}, content: [{ type: "text" as const, text: "Skipped: an active task for this proposal key already exists." }] };
569
+ }
570
+ return { details: {}, content: [{ type: "text" as const, text: `TeamAuto task created: ${result}` }] };
571
+ } catch (err) {
572
+ return { details: {}, content: [{ type: "text" as const, text: `Proposal failed: ${err instanceof Error ? err.message : String(err)}` }] };
573
+ }
574
+ },
575
+ },
504
576
  ];
505
577
  }
506
578
 
@@ -54,7 +54,7 @@ import type { WorkerProvisioningManager } from "./worker-provisioning.js";
54
54
  import type { PreviewManager } from "./preview-manager.js";
55
55
  import { createControllerPromptInjector } from "./prompt-injector.js";
56
56
  import { getGithubAuthManager } from "./github-auth.js";
57
- import { createTunnelManager, gatePageHtml, computeGateCookie, GATE_COOKIE_NAME, type TunnelManager } from "./tunnel-manager.js";
57
+ import { createTunnelManager, gatePageHtml, computeGateCookie, GATE_COOKIE_NAME, selfHostedTokenFromEnv, type TunnelManager } from "./tunnel-manager.js";
58
58
  import { createGithubClient } from "../teamauto/github-client.js";
59
59
  import type { TeamAutoScheduler } from "../teamauto/scheduler.js";
60
60
  import { buildControllerNoWorkersMessage, shouldBlockControllerWithoutWorkers } from "./controller-capacity.js";
@@ -4786,6 +4786,31 @@ export function createControllerHttpServer(deps: ControllerHttpDeps): http.Serve
4786
4786
  sendJson(res, 202, { launched, status: tunnelManager.status() });
4787
4787
  return;
4788
4788
  }
4789
+ // Self-hosted: user-owned Cloudflare tunnel via connector token (no
4790
+ // GitHub login, no platform tunnel server). Token from the request
4791
+ // body, or the TEAMCLAW_TUNNEL_TOKEN env injection when body is empty.
4792
+ if (req.method === "POST" && pathname === "/api/v1/tunnel/start-self-hosted") {
4793
+ let token = "";
4794
+ try {
4795
+ const body = await readFormBody(req) as { token?: unknown };
4796
+ token = String(body.token ?? "");
4797
+ } catch { /* fall through to env */ }
4798
+ if (!token.trim()) {
4799
+ const envToken = selfHostedTokenFromEnv();
4800
+ if (!envToken) { sendError(res, 400, "connector token required (or set TEAMCLAW_TUNNEL_TOKEN)"); return; }
4801
+ token = envToken;
4802
+ }
4803
+ const r = tunnelManager.startSelfHosted(token);
4804
+ if (!r.launched) { sendError(res, 400, r.error ?? "failed to start self-hosted tunnel"); return; }
4805
+ sendJson(res, 202, { launched: true, status: tunnelManager.status() });
4806
+ return;
4807
+ }
4808
+ if (req.method === "POST" && pathname === "/api/v1/tunnel/start-quick") {
4809
+ const r = tunnelManager.startQuick();
4810
+ if (!r.launched) { sendError(res, 400, r.error ?? "failed to start quick tunnel"); return; }
4811
+ sendJson(res, 202, { launched: true, status: tunnelManager.status() });
4812
+ return;
4813
+ }
4789
4814
  if (req.method === "POST" && pathname === "/api/v1/tunnel/stop") {
4790
4815
  await tunnelManager.stop();
4791
4816
  sendJson(res, 200, tunnelManager.status());
@@ -42,14 +42,27 @@ export const TUNNEL_SERVER_URL = "https://apps.teamclaw.dev/api";
42
42
  const TUNNEL_HOST_SUFFIX = ".teamclaw.dev";
43
43
  const GATE_COOKIE = "tc_tunnel_gate";
44
44
 
45
+ /** Env var that injects a user-owned Cloudflare connector token. When set,
46
+ * the UI skips the token input and offers direct one-click start. */
47
+ export const SELF_HOSTED_TOKEN_ENV = "TEAMCLAW_TUNNEL_TOKEN";
48
+ export function selfHostedTokenFromEnv(): string | null {
49
+ const v = process.env[SELF_HOSTED_TOKEN_ENV]?.trim();
50
+ return v ? v : null;
51
+ }
52
+
45
53
  export type TunnelStatus = {
46
54
  active: boolean;
55
+ /** "managed": platform tunnel on *.teamclaw.dev (gate-protected).
56
+ * "self-hosted": user-owned Cloudflare tunnel via connector token. */
57
+ mode: "managed" | "self-hosted" | "quick" | null;
47
58
  hostname: string | null;
48
59
  gateToken: string | null;
49
60
  connectorRunning: boolean;
50
61
  tunnelId: string | null;
51
62
  cloudflaredInstalled: boolean;
52
63
  cloudflaredPath: string | null;
64
+ /** True when SELF_HOSTED_TOKEN_ENV carries a token (UI hint: skip input). */
65
+ envTokenDetected: boolean;
53
66
  startOp: { running: boolean; phase: string; detail: string | null };
54
67
  install: { running: boolean; phase: string; percent: number | null; detail: string | null };
55
68
  error: string | null;
@@ -65,11 +78,41 @@ export type TunnelHandle = {
65
78
  };
66
79
 
67
80
  const CLOUDFLARED_CANDIDATES = [
68
- "cloudflared",
69
81
  "/opt/homebrew/bin/cloudflared",
70
82
  "/usr/local/bin/cloudflared",
71
83
  "/usr/bin/cloudflared",
72
84
  ];
85
+ function cloudflaredInstallTarget(): string {
86
+ // Keep in sync with installCloudflared(): the one-click install drops the
87
+ // binary at $HOME/.local/bin/cloudflared (no sudo needed, non-root friendly
88
+ // in containers where HOME is writable but /usr/local/bin is not).
89
+ const home = process.env.HOME ?? "/tmp";
90
+ return path.join(home, ".local", "bin", "cloudflared");
91
+ }
92
+ // curl-less download fallback (distroless images): plain https.get with
93
+ // redirect following. GitHub release URLs 302 to objects.githubusercontent.com.
94
+ function nativeDownload(url: string, dest: string, redirects = 0): Promise<void> {
95
+ return new Promise((resolve, reject) => {
96
+ if (redirects > 5) return reject(new Error("too many redirects"));
97
+ const req = https.get(url, (res: import("node:http").IncomingMessage) => {
98
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
99
+ res.resume();
100
+ nativeDownload(res.headers.location, dest, redirects + 1).then(resolve, reject);
101
+ return;
102
+ }
103
+ if (res.statusCode !== 200) {
104
+ res.resume();
105
+ reject(new Error("HTTP " + res.statusCode));
106
+ return;
107
+ }
108
+ const file = fs.createWriteStream(dest);
109
+ res.pipe(file);
110
+ file.on("finish", () => file.close((err?: NodeJS.ErrnoException | null) => (err ? reject(err) : resolve())));
111
+ file.on("error", reject);
112
+ });
113
+ req.on("error", reject);
114
+ });
115
+ }
73
116
  function tunnelRuntimeHome(): string {
74
117
  try {
75
118
  const dir = path.join(os.tmpdir(), "teamclaw-cloudflared-home");
@@ -125,7 +168,15 @@ function connectorPidIsCloudflared(pid: number): boolean {
125
168
  }
126
169
 
127
170
  function findCloudflared(): string | null {
128
- for (const bin of CLOUDFLARED_CANDIDATES) {
171
+ // The install target first: installCloudflared() puts the binary in
172
+ // $HOME/.local/bin, which is on PATH in stock images (Debian node images
173
+ // prepend it) but must be found even when PATH is minimal (K8s pods).
174
+ const candidates = [cloudflaredInstallTarget(), ...CLOUDFLARED_CANDIDATES];
175
+ // Real PATH scan. (fs.existsSync("cloudflared") checks CWD, not PATH -
176
+ // the old behavior missed every PATH-resolvable install.)
177
+ const pathDirs = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
178
+ for (const dir of pathDirs) candidates.push(path.join(dir, "cloudflared"));
179
+ for (const bin of candidates) {
129
180
  try {
130
181
  if (fs.existsSync(bin) && fs.accessSync(bin, fs.constants.X_OK) === undefined) {
131
182
  return bin;
@@ -146,6 +197,11 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
146
197
  let child: ChildProcess | null = null;
147
198
  let handle: TunnelHandle | null = null;
148
199
  let lastError: string | null = null;
200
+ // True while stop()/a restart path intentionally kills the connector; the
201
+ // cloudflared exit handler uses this to distinguish planned teardown from
202
+ // an unexpected crash (which must clear the active state so /tunnel/status
203
+ // never reports a dead tunnel as live).
204
+ let userStopping = false;
149
205
  let startOp: { running: boolean; phase: string; detail: string | null } = { running: false, phase: "idle", detail: null };
150
206
  let installState: { running: boolean; phase: string; percent: number | null; detail: string | null } = { running: false, phase: "idle", percent: null, detail: null };
151
207
 
@@ -194,6 +250,89 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
194
250
  return handle;
195
251
  }
196
252
 
253
+ /** Start a user-owned Cloudflare tunnel from a connector token (Zero Trust
254
+ * dashboard -> Tunnels -> <tunnel> -> copy token). The public hostname lives
255
+ * in the user's own CF zone, so it does NOT pass the .teamclaw.dev gate -
256
+ * protect it with Cloudflare Access if needed. Returns immediately; poll
257
+ * status() for connectorRunning. */
258
+ function startSelfHosted(rawToken: string): { launched: boolean; error: string | null } {
259
+ const token = rawToken.trim();
260
+ if (!token) return { launched: false, error: "empty connector token" };
261
+ if (token.length < 40 || !/^[A-Za-z0-9_\-=]+$/.test(token)) {
262
+ return { launched: false, error: "not a Cloudflare connector token (expected a long base64url string from the Zero Trust dashboard)" };
263
+ }
264
+ if (handle && child) return { launched: true, error: null };
265
+ const bin = findCloudflared();
266
+ if (!bin) return { launched: false, error: "cloudflared not found (brew install cloudflared)" };
267
+ startOp = { running: true, phase: "starting-connector", detail: "self-hosted tunnel" };
268
+ stopConnector();
269
+ child = spawnConnector(bin, token);
270
+ handle = { tunnelId: "self-hosted", hostname: "", gateToken: "", deleteToken: "" };
271
+ writeTunnelState({ tunnelId: "self-hosted", hostname: "", gateToken: "", deleteToken: "", connectorToken: token, pid: child.pid ?? null, savedAt: Date.now() });
272
+ startOp = { running: false, phase: "done", detail: "self-hosted tunnel" };
273
+ lastError = null;
274
+ logger.info("TeamClaw tunnel: self-hosted Cloudflare tunnel connector started");
275
+ return { launched: true, error: null };
276
+ }
277
+
278
+ /** Anonymous one-off tunnel: `cloudflared tunnel --url`, no Cloudflare
279
+ * account, no token, no platform server. Cloudflare assigns a random
280
+ * trycloudflare.com URL (printed on stderr) which dies with the process -
281
+ * it is NOT recovered on restart and must not be treated as stable. No
282
+ * TeamClaw gate: anyone with the URL can reach the dashboard. */
283
+ function startQuick(): { launched: boolean; error: string | null } {
284
+ if (handle && child) return { launched: true, error: null };
285
+ const bin = findCloudflared();
286
+ if (!bin) return { launched: false, error: "cloudflared not found (brew install cloudflared)" };
287
+ startOp = { running: true, phase: "starting-connector", detail: "quick tunnel" };
288
+ stopConnector();
289
+ const proc = spawn(bin, ["tunnel", "--no-autoupdate", "--url", "http://127.0.0.1:" + deps.localPort], {
290
+ stdio: ["ignore", "ignore", "pipe"],
291
+ detached: false,
292
+ env: { ...process.env, HOME: tunnelRuntimeHome() },
293
+ });
294
+ child = proc;
295
+ handle = { tunnelId: "quick", hostname: "", gateToken: "", deleteToken: "" };
296
+ lastError = null;
297
+ // The trycloudflare.com URL appears on stderr once the edge assigns it.
298
+ let announced = false;
299
+ const urlRe = /https:\/\/([a-z0-9-]+\.trycloudflare\.com)/i;
300
+ const timer = setTimeout(() => {
301
+ if (!announced) {
302
+ lastError = "quick tunnel did not announce its URL within 20s";
303
+ startOp = { running: false, phase: "error", detail: lastError };
304
+ }
305
+ }, 20000);
306
+ proc.stderr?.on("data", (c: Buffer) => {
307
+ const m = c.toString().match(urlRe);
308
+ if (m && !announced) {
309
+ announced = true;
310
+ clearTimeout(timer);
311
+ if (handle) handle.hostname = m[1]!;
312
+ startOp = { running: false, phase: "done", detail: m[1] };
313
+ logger.info(`TeamClaw tunnel: quick tunnel live at https://${m[1]}`);
314
+ }
315
+ try { fs.appendFileSync(path.join(tunnelRuntimeHome(), "cloudflared.log"), c); } catch { /* best effort */ }
316
+ });
317
+ // Quick tunnels are one-off: no persistent state, no recovery - but the
318
+ // connector-exit contract still applies: a dead connector must clear the
319
+ // active state so status() never reports a dead tunnel as live.
320
+ proc.on("exit", (code: number | null) => {
321
+ clearTimeout(timer);
322
+ logger.warn(`TeamClaw tunnel: cloudflared exited (code ${code})`);
323
+ if (child !== proc) return;
324
+ child = null;
325
+ if (!userStopping && handle) {
326
+ handle = null;
327
+ lastError = `tunnel connector exited unexpectedly (code ${code ?? "null"})`;
328
+ startOp = { running: false, phase: "error", detail: lastError };
329
+ clearTunnelState();
330
+ logger.warn("TeamClaw tunnel: state cleared after unexpected exit (quick)");
331
+ }
332
+ });
333
+ return { launched: true, error: null };
334
+ }
335
+
197
336
  function spawnConnector(bin: string, connectorToken: string): ChildProcess {
198
337
  const proc = spawn(bin, ["tunnel", "--no-autoupdate", "--protocol", "http2", "run", "--token", connectorToken], {
199
338
  stdio: ["ignore", "ignore", "pipe"],
@@ -205,7 +344,22 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
205
344
  });
206
345
  proc.on("exit", (code: number | null) => {
207
346
  logger.warn(`TeamClaw tunnel: cloudflared exited (code ${code})`);
208
- if (child === proc) child = null;
347
+ if (child !== proc) return;
348
+ child = null;
349
+ // Unexpected exit (crash, network loss, cloudflared auto-kill): tear
350
+ // the logical state down too, otherwise status() keeps reporting
351
+ // active=true and the UI shows a dead tunnel as live forever.
352
+ if (!userStopping && handle) {
353
+ const gone = handle;
354
+ handle = null;
355
+ lastError = `tunnel connector exited unexpectedly (code ${code ?? "null"})`;
356
+ startOp = { running: false, phase: "error", detail: lastError };
357
+ if (gone.tunnelId !== "self-hosted" && gone.tunnelId !== "quick") {
358
+ void tunnelFetch(`/tunnels/${gone.tunnelId}?user=${encodeURIComponent(gone.hostname.split(".")[0]!.replace(/^team-/, ""))}&token=${encodeURIComponent(gone.deleteToken)}`, "DELETE").catch(() => undefined);
359
+ }
360
+ clearTunnelState();
361
+ logger.warn(`TeamClaw tunnel: state cleared after unexpected exit (${gone.tunnelId})`);
362
+ }
209
363
  });
210
364
  // cloudflared logs (stderr) land in a single file for diagnosis.
211
365
  // (stdout is "ignore" in stdio above, so there is nothing to pipe.)
@@ -222,14 +376,20 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
222
376
  }
223
377
 
224
378
  async function stop(): Promise<void> {
379
+ userStopping = true;
225
380
  stopConnector();
226
381
  if (handle) {
227
382
  const gone = handle;
228
383
  handle = null;
229
- await tunnelFetch(`/tunnels/${gone.tunnelId}?user=${encodeURIComponent(gone.hostname.split(".")[0]!.replace(/^team-/, ""))}&token=${encodeURIComponent(gone.deleteToken)}`, "DELETE").catch(() => undefined);
384
+ // Self-hosted tunnels live in the user's CF account - nothing to
385
+ // delete server-side; the connector stop is the whole teardown.
386
+ if (gone.tunnelId !== "self-hosted" && gone.tunnelId !== "quick") {
387
+ await tunnelFetch(`/tunnels/${gone.tunnelId}?user=${encodeURIComponent(gone.hostname.split(".")[0]!.replace(/^team-/, ""))}&token=${encodeURIComponent(gone.deleteToken)}`, "DELETE").catch(() => undefined);
388
+ }
230
389
  clearTunnelState();
231
- logger.info(`TeamClaw tunnel: stopped ${gone.hostname}`);
390
+ logger.info(gone.tunnelId === "self-hosted" || gone.tunnelId === "quick" ? "TeamClaw tunnel: connector stopped" : `TeamClaw tunnel: stopped ${gone.hostname}`);
232
391
  }
392
+ userStopping = false;
233
393
  }
234
394
 
235
395
  // Boot reconciliation: reconnect the share persisted by a previous run.
@@ -239,41 +399,43 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
239
399
  async function recover(): Promise<TunnelHandle | null> {
240
400
  if (handle) return handle;
241
401
  const st = readTunnelState();
242
- if (!st) return null;
402
+ if (!st || st.tunnelId === "quick") return null; // one-off, not recoverable
243
403
  const bin = findCloudflared();
244
404
  if (!bin) {
245
405
  logger.warn("TeamClaw tunnel: previous share found but cloudflared is not installed; not recovering");
246
406
  return null;
247
407
  }
248
- // kill -9 of the gateway leaves an orphaned connector behind (SIGKILL
249
- // cannot run the close handler). Reap it before reconnecting - pid-reuse
250
- // safe: only when the binary still matches.
251
408
  if (st.pid && connectorPidIsCloudflared(st.pid)) {
252
409
  try {
253
410
  process.kill(st.pid, "SIGKILL");
254
411
  logger.warn(`TeamClaw tunnel: killed orphaned connector (pid ${st.pid})`);
255
412
  } catch { /* already gone */ }
256
413
  }
257
- startOp = { running: true, phase: "starting-connector", detail: st.hostname };
414
+ startOp = { running: true, phase: "starting-connector", detail: st.hostname || "self-hosted tunnel" };
258
415
  stopConnector();
259
416
  child = spawnConnector(bin, st.connectorToken);
260
- handle = { tunnelId: st.tunnelId, hostname: st.hostname, gateToken: st.gateToken, deleteToken: st.deleteToken };
417
+ const selfHosted = st.tunnelId === "self-hosted";
418
+ handle = selfHosted
419
+ ? { tunnelId: "self-hosted", hostname: "", gateToken: "", deleteToken: "" }
420
+ : { tunnelId: st.tunnelId, hostname: st.hostname, gateToken: st.gateToken, deleteToken: st.deleteToken };
261
421
  writeTunnelState({ ...st, pid: child.pid ?? null, savedAt: Date.now() });
262
- startOp = { running: false, phase: "done", detail: st.hostname };
422
+ startOp = { running: false, phase: "done", detail: st.hostname || "self-hosted tunnel" };
263
423
  lastError = null;
264
- logger.info(`TeamClaw tunnel: recovered https://${st.hostname} (tunnel id and gate token preserved)`);
424
+ logger.info(selfHosted ? "TeamClaw tunnel: recovered self-hosted Cloudflare tunnel" : `TeamClaw tunnel: recovered https://${st.hostname} (tunnel id and gate token preserved)`);
265
425
  return handle;
266
426
  }
267
427
 
268
428
  function status(): TunnelStatus {
269
429
  return {
270
430
  active: Boolean(handle),
271
- tunnelId: handle?.tunnelId ?? null,
272
- hostname: handle?.hostname ?? null,
273
- gateToken: handle?.gateToken ?? null,
431
+ mode: handle ? (handle.tunnelId === "self-hosted" ? "self-hosted" : handle.tunnelId === "quick" ? "quick" : "managed") : null,
432
+ hostname: handle?.hostname || null,
433
+ gateToken: handle?.gateToken || null,
274
434
  connectorRunning: Boolean(child),
435
+ tunnelId: handle?.tunnelId ?? null,
275
436
  cloudflaredInstalled: findCloudflared() !== null,
276
437
  cloudflaredPath: findCloudflared(),
438
+ envTokenDetected: selfHostedTokenFromEnv() !== null,
277
439
  startOp: { ...startOp },
278
440
  install: { ...installState },
279
441
  error: lastError,
@@ -283,7 +445,10 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
283
445
  /**
284
446
  * One-click cloudflared install across platforms:
285
447
  * darwin -> brew install cloudflared (Homebrew), tarball fallback
286
- * linux -> official tarball into ~/.local/bin (no sudo needed)
448
+ * linux -> official RAW binary into ~/.local/bin (no sudo needed;
449
+ * cloudflared ships NO .tgz asset for linux - only darwin
450
+ * has tgz packages, and the binary is statically linked so
451
+ * it runs on any distro without glibc concerns)
287
452
  * win32 -> winget install Cloudflare.cloudflared
288
453
  */
289
454
 
@@ -325,7 +490,10 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
325
490
  if (brew.code === 0) return { ok: true, detail: "installed via Homebrew" };
326
491
  }
327
492
  const arch = process.arch === "arm64" ? "arm64" : process.arch === "ia32" ? "386" : "amd64";
328
- const name = process.platform === "darwin" ? "cloudflared-darwin-" + arch + ".tgz" : "cloudflared-linux-" + arch + ".tgz";
493
+ const isDarwin = process.platform === "darwin";
494
+ // Linux assets are RAW binaries (no .tgz exists for linux - verified
495
+ // against the official release page; the old .tgz URL 404s there).
496
+ const name = isDarwin ? "cloudflared-darwin-" + arch + ".tgz" : "cloudflared-linux-" + arch;
329
497
  fs.mkdirSync(userBin, { recursive: true });
330
498
  const tgz = path.join(userBin, name);
331
499
  const url = "https://github.com/cloudflare/cloudflared/releases/latest/download/" + name;
@@ -338,19 +506,35 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
338
506
  total = Number(head.headers["content-length"] ?? 0);
339
507
  } catch { total = 0; }
340
508
  setPhase("downloading", 0, url);
341
- const timer = setInterval(() => {
509
+ const watch = (file: string) => {
510
+ const timer = setInterval(() => {
511
+ try {
512
+ const size = fs.statSync(file).size;
513
+ if (total > 0) setPhase("downloading", Math.min(99, Math.floor((size / total) * 100)), null);
514
+ } catch { /* file not created yet */ }
515
+ }, 500);
516
+ return () => clearInterval(timer);
517
+ };
518
+ // curl first (resume/retry flags), native https fallback for images
519
+ // without curl (distroless etc.). GitHub releases redirect - follow them.
520
+ const dlPath = isDarwin ? tgz : target;
521
+ const stopWatch = watch(dlPath);
522
+ const dl = await run("curl", ["-fsSL", "--retry", "3", "-o", dlPath, url]);
523
+ stopWatch();
524
+ if (dl.code !== 0) {
525
+ setPhase("downloading", null, "native https fallback");
342
526
  try {
343
- const size = fs.statSync(tgz).size;
344
- if (total > 0) setPhase("downloading", Math.min(99, Math.floor((size / total) * 100)), null);
345
- } catch { /* file not created yet */ }
346
- }, 500);
347
- const dl = await run("curl", ["-fsSL", "--retry", "3", "-o", tgz, url]);
348
- clearInterval(timer);
349
- if (dl.code !== 0) return { ok: false, detail: "download: " + tail(dl.out) };
350
- setPhase("extracting", 99, null);
351
- const ex = await run("tar", ["xzf", tgz, "-C", userBin]);
352
- fs.rmSync(tgz, { force: true });
353
- if (ex.code !== 0) return { ok: false, detail: "extract: " + tail(ex.out) };
527
+ await nativeDownload(url, dlPath);
528
+ } catch (e) {
529
+ return { ok: false, detail: "download: " + (e instanceof Error ? e.message : String(e)) };
530
+ }
531
+ }
532
+ if (isDarwin) {
533
+ setPhase("extracting", 99, null);
534
+ const ex = await run("tar", ["xzf", tgz, "-C", userBin]);
535
+ fs.rmSync(tgz, { force: true });
536
+ if (ex.code !== 0) return { ok: false, detail: "extract: " + tail(ex.out) };
537
+ }
354
538
  fs.chmodSync(target, 0o755);
355
539
  return { ok: true, detail: "installed to " + target };
356
540
  })();
@@ -363,7 +547,7 @@ export function createTunnelManager(deps: { logger: PluginLogger; localPort: num
363
547
  }
364
548
 
365
549
 
366
- return { start: launchStart, stop, recover, status, installCloudflared, isTunnelRequest, gateAllows };
550
+ return { start: launchStart, startSelfHosted, startQuick, stop, recover, status, installCloudflared, isTunnelRequest, gateAllows };
367
551
  }
368
552
 
369
553
  export type TunnelManager = ReturnType<typeof createTunnelManager>;
@@ -1522,7 +1522,20 @@ async function prepareProcessRuntimeExtensions(stateDir: string): Promise<void>
1522
1522
  await fs.symlink(controllerExtensionsDir, runtimeExtensionsDir, "dir");
1523
1523
  } else {
1524
1524
  await fs.mkdir(runtimeExtensionsDir, { recursive: true });
1525
- await fs.symlink(resolveCurrentTeamClawPluginRootDir(), path.join(runtimeExtensionsDir, "teamclaw"), "dir");
1525
+ // Baked-in images set TEAMCLAW_BAKED_IN=true and the legacy helper
1526
+ // returned "" for that case, so the symlink target was empty and
1527
+ // process workers fell back to resolving the plugin from their cwd
1528
+ // ("/app/dist/openclaw.plugin.json" not found → exit loop, k3s e2e
1529
+ // 2026-11-03). Probe the baked image layout instead: the controller
1530
+ // entrypoint (process.argv[1], e.g. /app/dist/index.js) sits below
1531
+ // the app root, where the runtime image ships
1532
+ // /app/extensions/teamclaw with its openclaw.plugin.json.
1533
+ const pluginRootDir = process.env.TEAMCLAW_BAKED_IN === "true"
1534
+ ? await resolveBakedTeamClawPluginRootDir()
1535
+ : resolveCurrentTeamClawPluginRootDir();
1536
+ if (pluginRootDir) {
1537
+ await fs.symlink(pluginRootDir, path.join(runtimeExtensionsDir, "teamclaw"), "dir");
1538
+ }
1526
1539
  }
1527
1540
 
1528
1541
  await copyControllerAuthProfiles(stateDir);
@@ -1697,6 +1710,33 @@ function resolveCurrentTeamClawPluginRootDir(): string {
1697
1710
  return process.env.TEAMCLAW_BAKED_IN === "true" ? "" : path.resolve(fileURLToPath(new URL("../../", import.meta.url)));
1698
1711
  }
1699
1712
 
1713
+ /**
1714
+ * Locate the teamclaw plugin root inside a baked runtime image. The image
1715
+ * ships the plugin at <app-root>/extensions/teamclaw; the controller
1716
+ * entrypoint (process.argv[1]) lives under <app-root>, so walk up from it.
1717
+ * Returns "" when no candidate carries an openclaw.plugin.json (the
1718
+ * caller then skips the symlink instead of creating a dangling one).
1719
+ */
1720
+ async function resolveBakedTeamClawPluginRootDir(): Promise<string> {
1721
+ const entrypoint = process.argv[1] ? path.resolve(process.argv[1]) : "";
1722
+ const candidates = entrypoint
1723
+ ? [
1724
+ path.resolve(entrypoint, "../../extensions/teamclaw"),
1725
+ path.resolve(entrypoint, "../extensions/teamclaw"),
1726
+ ]
1727
+ : [];
1728
+ candidates.push("/app/extensions/teamclaw");
1729
+ for (const candidate of candidates) {
1730
+ try {
1731
+ await fs.access(path.join(candidate, "openclaw.plugin.json"));
1732
+ return candidate;
1733
+ } catch {
1734
+ // try the next candidate layout
1735
+ }
1736
+ }
1737
+ return "";
1738
+ }
1739
+
1700
1740
  function attachChildLogs(child: ChildProcess, logger: PluginLogger, prefix: string): void {
1701
1741
  if (child.stdout) {
1702
1742
  const stdoutReader = readline.createInterface({ input: child.stdout });
@@ -285,6 +285,9 @@ export function buildControllerToolRules(): string[] {
285
285
  "- teamclaw_list_tasks: List all tasks with status filtering",
286
286
  "- teamclaw_assign_task: Assign a task to a specific worker",
287
287
  "- teamclaw_send_message: Send messages between team members",
288
+ "- teamclaw_teamauto_status: List TeamAuto-managed repos (schedule, cadence, pause state, recent activity) - call this first when a request mentions improving one of the bound repositories",
289
+ "- teamclaw_teamauto_sweep: Trigger an immediate TeamAuto sweep of a bound repo",
290
+ "- teamclaw_teamauto_propose: Inject a proposal into a TeamAuto-managed repo through its governed pipeline (dedup, failure caps, norms, worktree) - prefer over teamclaw_create_task for repos listed by teamclaw_teamauto_status",
288
291
  ];
289
292
  }
290
293
 
@@ -46,6 +46,64 @@ export type TeamAutoSchedulerDeps = {
46
46
  onActivity?: (entry: TeamAutoActivityEntry) => void;
47
47
  };
48
48
 
49
+ /** Max HARD (non-transient) failures before a candidate is dead-lettered. */
50
+ export const TEAMAUTO_DEAD_LETTER_ATTEMPTS = 3;
51
+
52
+ /** Max TOTAL failures (transient included) before a candidate is dead-lettered. */
53
+ export const TEAMAUTO_DEAD_LETTER_TRANSIENT_ATTEMPTS = 6;
54
+
55
+ /**
56
+ * Failure signatures that are environmental, not the task's fault - the same
57
+ * candidate is likely to succeed on a later sweep. Observed live (92-task
58
+ * dump): upstream rate limiting ("AI service needs a short break"), shared
59
+ * workspace snapshot races ("Workspace filesystem changed"), worker gateway
60
+ * lifecycle races ("Gateway request entry is closed"). These get a wider
61
+ * retry allowance than hard failures so they do not dead-letter good work.
62
+ */
63
+ export const TRANSIENT_FAILURE_RE = /workspace filesystem changed|ai service needs a short break|gateway request entry is closed|rate.?limit|timed? ?out|econnreset|socket hang up|bad gateway|service unavailable/i;
64
+
65
+ /** The dedup marker for a candidate as embedded in task descriptions. */
66
+ export function idempotencyMarker(candidate: { key: string; kind: string }): string {
67
+ return `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
68
+ }
69
+
70
+ /** Failed task attempts for a candidate (task history is the attempt log). */
71
+ export function failedAttemptCount(
72
+ state: { tasks: Record<string, { description: string; status: string; error?: string }> },
73
+ candidate: { key: string; kind: string },
74
+ ): number {
75
+ const marker = idempotencyMarker(candidate);
76
+ return Object.values(state.tasks).filter((t) => t.description.includes(marker) && t.status === "failed").length;
77
+ }
78
+
79
+ /** Failed attempts whose error is NOT a known transient signature. */
80
+ export function hardAttemptCount(
81
+ state: Parameters<typeof failedAttemptCount>[0],
82
+ candidate: { key: string; kind: string },
83
+ ): number {
84
+ const marker = idempotencyMarker(candidate);
85
+ return Object.values(state.tasks).filter(
86
+ (t) => t.description.includes(marker) && t.status === "failed" && !(t.error && TRANSIENT_FAILURE_RE.test(t.error)),
87
+ ).length;
88
+ }
89
+
90
+ /** Auto-pause retry backoff: 30m after the 1st failure, doubling, capped at 4h. */
91
+ export const SWEEP_RETRY_BASE_MINUTES = 30;
92
+ export const SWEEP_RETRY_MAX_MINUTES = 240;
93
+ export function sweepBackoffMinutes(failures: number): number {
94
+ return Math.min(SWEEP_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_RETRY_MAX_MINUTES);
95
+ }
96
+
97
+ /** Epoch ms when an auto-paused repo becomes due for its next retry attempt. */
98
+ export function sweepRetryDueAt(failures: number, lastErrorAt: number): number {
99
+ return lastErrorAt + sweepBackoffMinutes(failures) * 60_000;
100
+ }
101
+
102
+ /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
103
+ export function isAutoPause(reason: string | null | undefined): boolean {
104
+ return !!reason && reason.startsWith("sweep failed:");
105
+ }
106
+
49
107
  export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
50
108
  const { logger, auth } = deps;
51
109
 
@@ -259,7 +317,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
259
317
  } else {
260
318
  for (const candidate of capped) {
261
319
  const taskId = enqueueCandidate(repo, candidate);
262
- if (taskId) {
320
+ if (taskId === "dead-lettered") {
321
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
322
+ } else if (taskId) {
263
323
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
264
324
  const action = candidate.kind === "prReview"
265
325
  ? ("prComment" as const)
@@ -279,6 +339,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
279
339
  repo.lastSweepSummary = "no new work";
280
340
  }
281
341
  repo.lastSweepAt = Date.now();
342
+ if (isAutoPause(repo.pausedReason)) {
343
+ repo.pausedReason = null;
344
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
345
+ }
346
+ repo.sweepFailures = 0;
282
347
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
283
348
  await saveTeamAutoStore(s);
284
349
  if (created > 0) {
@@ -290,7 +355,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
290
355
  return repo.lastSweepSummary ?? "sweep complete";
291
356
  } catch (err) {
292
357
  const message = err instanceof Error ? err.message : String(err);
358
+ // Transient failures (network blips, restart-interrupted sweeps) used to
359
+ // pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
360
+ // failed". Auto-pauses are cooldowns now: the timer retries after the
361
+ // backoff below, and a success clears the state in the block above.
362
+ repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
363
+ repo.lastSweepErrorAt = Date.now();
293
364
  repo.pausedReason = `sweep failed: ${message}`;
365
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
294
366
  await saveTeamAutoStore(s).catch(() => {});
295
367
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
296
368
  return `error: ${message}`;
@@ -299,21 +371,36 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
299
371
  }
300
372
  }
301
373
 
302
- function enqueueCandidate(repo: TeamAutoRepo, candidate: Candidate): string | undefined {
374
+ function enqueueCandidate(repo: TeamAutoRepo, candidate: Candidate): string | "dead-lettered" | undefined {
303
375
  let createdId: string | undefined;
376
+ let deadLettered = false;
304
377
  deps.updateTeamState((state) => {
305
378
  // Idempotency: an active task for the same object AND kind wins. The
306
379
  // key rides in the description (TaskInfo has no dedicated field) and
307
380
  // must be a distinct marked line - titles contain human text that never
308
381
  // matches the raw key (that was the pre-fix bug). Kind-scoping matters:
309
382
  // object-level keys starved takeOwnership (review always enqueued first).
310
- const dedupMarker = `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
383
+ const dedupMarker = idempotencyMarker(candidate);
311
384
  const duplicate = Object.values(state.tasks).find(
312
385
  (t) => t.description.includes(dedupMarker) && t.status !== "completed" && t.status !== "failed",
313
386
  );
314
387
  if (duplicate) {
315
388
  return;
316
389
  }
390
+ // Dead-letter: task history doubles as the attempt log. The dedup above
391
+ // only blocks ACTIVE tasks, so a failed candidate would be re-enqueued
392
+ // every sweep forever (observed: issue #12 re-candidated 4 sweeps in a
393
+ // row, burning daily budget on churn). Cap the retries instead - hard
394
+ // failures fast (3), environmental/transient failures get a wider
395
+ // allowance (6 total) so rate limits or workspace races do not kill
396
+ // work that would succeed on a quieter sweep.
397
+ if (
398
+ hardAttemptCount(state, candidate) >= TEAMAUTO_DEAD_LETTER_ATTEMPTS
399
+ || failedAttemptCount(state, candidate) >= TEAMAUTO_DEAD_LETTER_TRANSIENT_ATTEMPTS
400
+ ) {
401
+ deadLettered = true;
402
+ return;
403
+ }
317
404
  const task: TaskInfo = {
318
405
  id: newId("teamauto"),
319
406
  title: `[${candidate.kind}] ${candidate.title}`,
@@ -349,7 +436,47 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
349
436
  state.tasks[task.id] = task;
350
437
  createdId = task.id;
351
438
  });
352
- return createdId;
439
+ return deadLettered ? "dead-lettered" : createdId;
440
+ }
441
+
442
+ /**
443
+ * Agent-facing manual proposal: inject a candidate directly (bypassing the
444
+ * GitHub-object sweep) while reusing the full pipeline - idempotency dedup,
445
+ * dead-letter caps, budget accounting, norms blocks, worktree checkout.
446
+ * No writeback is registered (there is no GitHub object to write back to);
447
+ * the result stays in the task system, visible via teamclaw_list_tasks.
448
+ */
449
+ async function proposeManual(
450
+ repoId: string,
451
+ input: { kind: Candidate["kind"]; title: string; context: string; role?: string; writeMode?: "read-only" | "write" },
452
+ ): Promise<string> {
453
+ const s = await ensureStore();
454
+ const repo = s.repos.find((r) => r.id === repoId);
455
+ if (!repo) {
456
+ throw new Error(`${repoId} not bound`);
457
+ }
458
+ const kind: Candidate["kind"] = input.kind === "takeOwnership" || input.kind === "issueReview" || input.kind === "prReview" || input.kind === "fullReview" ? input.kind : "issueReview";
459
+ const candidate: Candidate = {
460
+ repoId,
461
+ key: `${repoId}#manual-${Date.now()}`,
462
+ kind,
463
+ number: 0,
464
+ role: (input.role || (kind === "takeOwnership" ? "developer" : "architect")) as Candidate["role"],
465
+ writeMode: input.writeMode ?? (kind === "takeOwnership" ? "write" : "read-only"),
466
+ title: input.title.slice(0, 120),
467
+ reason: "manual proposal from agent tool",
468
+ context: input.context,
469
+ };
470
+ const taskId = enqueueCandidate(repo, candidate);
471
+ if (taskId === "dead-lettered") {
472
+ throw new Error(`proposal dead-lettered (${kind} exceeded failure caps for this repo)`);
473
+ }
474
+ if (taskId) {
475
+ recordActivity(s, { at: Date.now(), repoId, kind: "task", text: `manual ${kind}: ${candidate.title}` });
476
+ await saveTeamAutoStore(s);
477
+ return taskId;
478
+ }
479
+ return "duplicate-active-skipped";
353
480
  }
354
481
 
355
482
  // ---------- write-back reconciler ----------
@@ -436,10 +563,22 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
436
563
  await client.postIssueComment(owner, name, entry.targetId, body);
437
564
  entry.doneAt = Date.now();
438
565
  writebackDone = true;
566
+ // Our own comment bumps the issue's updatedAt, which the scanner
567
+ // treats as new activity - advance the seen cursor so we do not
568
+ // re-trigger a review of an object we just replied to. External
569
+ // edits (updatedAt > now) still re-arm the candidate.
570
+ const issueRepo = s.repos.find((r) => r.id === entry.repoId);
571
+ if (issueRepo) {
572
+ issueRepo.cursors.seen[`${entry.repoId}#issue-${entry.targetId}`] = Date.now();
573
+ }
439
574
  } else if (entry.action === "prComment" && entry.targetId) {
440
575
  await client.postPullReviewComment(owner, name, entry.targetId, body);
441
576
  entry.doneAt = Date.now();
442
577
  writebackDone = true;
578
+ const prRepo = s.repos.find((r) => r.id === entry.repoId);
579
+ if (prRepo) {
580
+ prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
581
+ }
443
582
  } else if (entry.action === "createIssue") {
444
583
  // Joint full review: same-cycle sections land in ONE umbrella issue
445
584
  // (first completed section creates it, the rest post as comments).
@@ -518,13 +657,32 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
518
657
  }
519
658
  const timer = setTimeout(() => {
520
659
  void (async () => {
521
- const s = await ensureStore();
522
- const fresh = s.repos.find((r) => r.id === repo.id);
523
- if (fresh?.enabled && fresh.pausedReason === null) {
524
- await runSweep(fresh, false);
525
- }
526
- if (fresh?.enabled) {
527
- scheduleRepo(fresh);
660
+ try {
661
+ const s = await ensureStore();
662
+ const fresh = s.repos.find((r) => r.id === repo.id);
663
+ const retryDue = fresh
664
+ ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0)
665
+ : false;
666
+ if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
667
+ await runSweep(fresh, false);
668
+ }
669
+ if (fresh?.enabled) {
670
+ scheduleRepo(fresh);
671
+ }
672
+ } catch (err) {
673
+ // The timer chain must survive any single tick failure. Before this
674
+ // guard, a rejected ensureStore() (corrupt store file, IO error)
675
+ // unhandled-rejected through `void`, scheduleRepo(fresh) never ran,
676
+ // and the repo's scheduling chain died silently until a gateway
677
+ // restart. Re-arm from the last known config; updateRepo re-arms on
678
+ // config change anyway, so a stale schedule here is bounded.
679
+ logger.warn(`TeamAuto: sweep tick failed for ${repo.id}, re-arming timer: ${err instanceof Error ? err.message : String(err)}`);
680
+ try {
681
+ scheduleRepo(repo);
682
+ } catch {
683
+ // scheduleRepo only throws on programmer error; a dead chain here
684
+ // is still recoverable by restart (start() rebuilds all timers).
685
+ }
528
686
  }
529
687
  })();
530
688
  }, delay);
@@ -572,7 +730,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
572
730
  return (s.activity ?? []).slice().reverse();
573
731
  }
574
732
 
575
- return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree };
733
+ return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
576
734
 
577
735
  /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
578
736
  async function ensureWriteWorktree(repoId: string, taskId: string): Promise<string> {
@@ -66,6 +66,10 @@ export type TeamAutoRepo = {
66
66
  lastSweepAt: number;
67
67
  lastSweepSummary: string | null;
68
68
  pausedReason: string | null;
69
+ /** Consecutive auto-paused sweep failures; drives retry backoff (0/undefined = healthy). */
70
+ sweepFailures?: number;
71
+ /** Epoch ms of the last auto-pausing sweep failure. */
72
+ lastSweepErrorAt?: number;
69
73
  dryRunDone: boolean;
70
74
  /** Bind-time provisioning state; ready/undefined means sweepable. */
71
75
  provision?: TeamAutoRepoProvision;
@@ -141,7 +145,7 @@ function emptyStore(): TeamAutoStore {
141
145
  writebacks: [],
142
146
  activity: [],
143
147
  budget: {
144
- maxTasksPerDay: 50,
148
+ maxTasksPerDay: 150,
145
149
  firstSweepDryRun: true,
146
150
  tasksToday: 0,
147
151
  dayStamp: now.toISOString().slice(0, 10),
package/src/ui/app.js CHANGED
@@ -2481,14 +2481,14 @@
2481
2481
  ? '<span class="task-origin-badge">' + escapeHtml(task.createdBy) + "</span>"
2482
2482
  : "";
2483
2483
  const contractSummary = task.resultContract
2484
- ? '<div class="task-contract-summary"><strong>Result:</strong> ' + escapeHtml(task.resultContract.summary || "") + "</div>"
2484
+ ? '<div class="task-contract-summary clamp"><strong>Result:</strong> ' + escapeHtml(task.resultContract.summary || "") + "</div>"
2485
2485
  : task.lastHandoff
2486
- ? '<div class="task-contract-summary"><strong>Handoff:</strong> ' + escapeHtml(task.lastHandoff.summary || "") + "</div>"
2486
+ ? '<div class="task-contract-summary clamp"><strong>Handoff:</strong> ' + escapeHtml(task.lastHandoff.summary || "") + "</div>"
2487
2487
  : task.progressContract
2488
- ? '<div class="task-contract-summary"><strong>Progress:</strong> ' + escapeHtml(task.progressContract.summary || "") + "</div>"
2488
+ ? '<div class="task-contract-summary clamp"><strong>Progress:</strong> ' + escapeHtml(task.progressContract.summary || "") + "</div>"
2489
2489
  : "";
2490
2490
  const note = task.progress
2491
- ? '<div class="task-note">' + escapeHtml(task.progress).slice(0, 220) + "</div>"
2491
+ ? '<div class="task-note clamp">' + escapeHtml(task.progress).slice(0, 220) + "</div>"
2492
2492
  : "";
2493
2493
  const clarification = task.clarificationRequestId
2494
2494
  ? '<span>Clarification: ' + escapeHtml(task.clarificationRequestId) + "</span>"
@@ -2500,7 +2500,7 @@
2500
2500
  ' <span class="task-priority ' + escapeHtml(priority) + '">' + escapeHtml(priority) + "</span>" +
2501
2501
  ' <div class="task-body">' +
2502
2502
  ' <div class="task-title-row"><div class="task-title">' + escapeHtml(task.title) + "</div>" + creatorBadge + "</div>" +
2503
- (task.description ? '<div class="task-desc">' + escapeHtml(task.description).slice(0, 220) + "</div>" : "") +
2503
+ (task.description ? '<div class="task-desc clamp">' + escapeHtml(task.description).slice(0, 220) + "</div>" : "") +
2504
2504
  renderSkillPills(recommendedSkills, "skill-pills task-skill-pills") +
2505
2505
  contractSummary +
2506
2506
  note +
@@ -4163,45 +4163,122 @@ function closeModelSettings() {
4163
4163
  }, 10000);
4164
4164
 
4165
4165
 
4166
- // Tunnel sharing (internet gate for the local web UI).
4166
+ // Tunnel sharing (internet gate for the local web UI). The settings UI is
4167
+ // a header-triggered popover; while the MANAGED tunnel (*.teamclaw.dev) is
4168
+ // active its URL surfaces as #tunnel-live-pill in the header (self-hosted
4169
+ // hostnames live in the user's Cloudflare dashboard and are not shown).
4167
4170
  function initTunnelPanel() {
4168
- const wrap = document.getElementById("tunnel-panel");
4171
+ const wrap = document.getElementById("tunnel-popover");
4172
+ const pill = document.getElementById("tunnel-live-pill");
4173
+ const toggleBtn = document.getElementById("tunnel-settings-toggle");
4169
4174
  if (!wrap || wrap.dataset.bound) return;
4170
4175
  wrap.dataset.bound = "true";
4176
+ const openPopover = () => { wrap.hidden = false; };
4177
+ const closePopover = () => { wrap.hidden = true; };
4178
+ if (toggleBtn) toggleBtn.addEventListener("click", () => { wrap.hidden = !wrap.hidden; });
4179
+ wrap.addEventListener("click", (e) => {
4180
+ if (e.target.getAttribute && e.target.getAttribute("data-act") === "close") closePopover();
4181
+ });
4182
+ document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !wrap.hidden) closePopover(); });
4171
4183
  // Visitor view: when the dashboard itself is reached through a tunnel
4172
- // domain, management APIs are gated - degrade to a provenance badge
4184
+ // domain, management APIs are gated - degrade to a provenance note
4173
4185
  // instead of a spinner that can never resolve.
4174
4186
  const host = (location.hostname || "").toLowerCase();
4175
4187
  const isLocalView = host === "127.0.0.1" || host === "localhost" || host.endsWith(".local");
4176
4188
  if (!isLocalView) {
4177
- wrap.innerHTML = '<h3>Internet Tunnel</h3><div class="tunnel-state"><span class="tunnel-note">This dashboard is shared via a TeamClaw tunnel.</span></div>';
4189
+ wrap.querySelector(".tunnel-state").innerHTML = '<span class="tunnel-note">This dashboard is shared via a TeamClaw tunnel.</span>';
4190
+ if (toggleBtn) toggleBtn.hidden = true;
4178
4191
  return;
4179
4192
  }
4180
4193
  const render = (st) => {
4194
+ // Header pill: managed tunnel only (*.teamclaw.dev). Self-hosted
4195
+ // hostnames are managed in the user's Cloudflare dashboard.
4196
+ if (pill) {
4197
+ if (st.active && st.mode === "managed" && st.hostname) {
4198
+ pill.href = "https://" + st.hostname;
4199
+ pill.textContent = st.hostname;
4200
+ pill.hidden = false;
4201
+ } else {
4202
+ pill.hidden = true;
4203
+ }
4204
+ }
4181
4205
  var progress = st.startOp && st.startOp.running
4182
4206
  ? '<div class="tunnel-note">Starting tunnel: ' + escapeHtml(st.startOp.phase) + '…</div>'
4183
4207
  : (st.install && st.install.running
4184
4208
  ? '<div class="tunnel-note">cloudflared ' + escapeHtml(st.install.phase) + (st.install.percent != null ? ' ' + st.install.percent + '%' : '') + '…</div>'
4185
4209
  : '');
4186
4210
  if (progress) { wrap.querySelector(".tunnel-state").innerHTML = progress; return; }
4187
- wrap.querySelector(".tunnel-state").innerHTML = st.active
4188
- ? '<div class="tunnel-on">Live: <a href="https://' + st.hostname + '" target="_blank" rel="noopener">https://' + st.hostname + '</a></div>'
4211
+ if (st.active && st.mode === "quick") {
4212
+ wrap.querySelector(".tunnel-state").innerHTML =
4213
+ '<div class="tunnel-on">Quick tunnel: ' + (st.hostname ? '<a href="https://' + st.hostname + '" target="_blank" rel="noopener">https://' + st.hostname + '</a>' : 'waiting for URL…') + '</div>'
4214
+ + '<div class="tunnel-note">One-off URL - dies on restart. Anyone with the link can open the dashboard.</div>'
4215
+ + '<button class="btn btn-small" data-act="stop">Stop sharing</button>';
4216
+ return;
4217
+ }
4218
+ if (st.active && st.mode === "self-hosted") {
4219
+ wrap.querySelector(".tunnel-state").innerHTML =
4220
+ '<div class="tunnel-on">Self-hosted Cloudflare tunnel: live on your own domain</div>'
4221
+ + '<div class="tunnel-note">Public hostname is managed in your Cloudflare Zero Trust dashboard.</div>'
4222
+ + '<button class="btn btn-small" data-act="stop">Stop sharing</button>';
4223
+ return;
4224
+ }
4225
+ if (st.active) {
4226
+ wrap.querySelector(".tunnel-state").innerHTML =
4227
+ '<div class="tunnel-on">Live: <a href="https://' + st.hostname + '" target="_blank" rel="noopener">https://' + st.hostname + '</a></div>'
4189
4228
  + '<div class="tunnel-token">Gate token: <b>' + st.gateToken + '</b></div>'
4190
- + '<button class="btn btn-small" data-act="stop">Stop sharing</button>'
4191
- : st.cloudflaredInstalled === false
4192
- ? '<div class="tunnel-note">cloudflared connector is not installed.</div>'
4193
- + '<button class="btn btn-small btn-primary" data-act="install">Install cloudflared</button>'
4194
- : '<button class="btn btn-small btn-primary" data-act="start">Share via tunnel</button>'
4195
- + '<span class="tunnel-note">requires GitHub login</span>';
4229
+ + '<button class="btn btn-small" data-act="stop">Stop sharing</button>';
4230
+ return;
4231
+ }
4232
+ if (st.cloudflaredInstalled === false) {
4233
+ wrap.querySelector(".tunnel-state").innerHTML = '<div class="tunnel-note">cloudflared connector is not installed.</div>'
4234
+ + '<button class="btn btn-small btn-primary" data-act="install">Install cloudflared</button>';
4235
+ return;
4236
+ }
4237
+ // Idle: self-hosted (env token detected -> one click; otherwise token
4238
+ // input) alongside the managed share button.
4239
+ var html = '';
4240
+ if (st.envTokenDetected) {
4241
+ html += '<div class="tunnel-note">Connector token detected via TEAMCLAW_TUNNEL_TOKEN — ready to start.</div>'
4242
+ + '<button class="btn btn-small btn-primary" data-act="start-self">Start self-hosted tunnel</button>';
4243
+ } else {
4244
+ html += '<div class="tunnel-note">Self-hosted tunnel (your own Cloudflare account/domain):</div>'
4245
+ + '<input type="password" class="tunnel-token-input" data-input="token" placeholder="Cloudflare connector token" autocomplete="off">'
4246
+ + '<button class="btn btn-small btn-primary" data-act="start-self-token">Start self-hosted tunnel</button>'
4247
+ + '<details class="tunnel-setup-help"><summary>How to get a token &amp; set up the tunnel</summary>'
4248
+ + '<div class="tunnel-note">Cloudflare Zero Trust → Networks → Tunnels → your tunnel → copy token. Point its public hostname at this machine’s URL (Service: HTTP + the controller port shown in the docs). Protect it with Cloudflare Access — self-hosted domains skip the TeamClaw gate.</div></details>';
4249
+ }
4250
+ html += '<div class="tunnel-note">— or —</div>'
4251
+ + '<button class="btn btn-small" data-act="start">Share via *.teamclaw.dev</button>'
4252
+ + '<span class="tunnel-note">requires GitHub login</span>'
4253
+ + '<div class="tunnel-note">— or —</div>'
4254
+ + '<button class="btn btn-small" data-act="start-quick">Anonymous one-off tunnel (trycloudflare.com)</button>'
4255
+ + '<div class="tunnel-note">No account needed. Random URL, dies on restart, anyone with the link can open the dashboard - use for quick demos only. Needs the cloudflared binary.</div>';
4256
+ wrap.querySelector(".tunnel-state").innerHTML = html;
4196
4257
  };
4197
4258
  const refresh = () => apiGet("/tunnel/status").then((st) => render(st || {})).catch(() => {});
4198
4259
  wrap.addEventListener("click", (e) => {
4199
4260
  const act = e.target.getAttribute && e.target.getAttribute("data-act");
4200
4261
  if (!act) return;
4201
4262
  e.target.disabled = true;
4202
- var call = act === "start" ? apiRequest("/tunnel/start", { method: "POST" })
4203
- : act === "install" ? apiRequest("/tunnel/install-cloudflared", { method: "POST" })
4204
- : apiRequest("/tunnel/stop", { method: "POST" });
4263
+ var call;
4264
+ if (act === "start-quick") {
4265
+ call = apiRequest("/tunnel/start-quick", { method: "POST" });
4266
+ } else if (act === "start-self" || act === "start-self-token") {
4267
+ const opts = { method: "POST", headers: { "Content-Type": "application/json" } };
4268
+ if (act === "start-self-token") {
4269
+ const input = wrap.querySelector('[data-input="token"]');
4270
+ if (!input || !input.value.trim()) {
4271
+ wrap.querySelector(".tunnel-state").innerHTML = '<div class="tunnel-err">Paste a Cloudflare connector token first.</div>';
4272
+ return;
4273
+ }
4274
+ opts.body = JSON.stringify({ token: input.value.trim() });
4275
+ }
4276
+ call = apiRequest("/tunnel/start-self-hosted", opts);
4277
+ } else {
4278
+ call = act === "start" ? apiRequest("/tunnel/start", { method: "POST" })
4279
+ : act === "install" ? apiRequest("/tunnel/install-cloudflared", { method: "POST" })
4280
+ : apiRequest("/tunnel/stop", { method: "POST" });
4281
+ }
4205
4282
  call.then(refresh).catch((err) => { wrap.querySelector(".tunnel-state").innerHTML = '<div class="tunnel-err">' + escapeHtml(String(err.message || err)) + "</div>"; });
4206
4283
  });
4207
4284
  refresh();
package/src/ui/index.html CHANGED
@@ -24,6 +24,8 @@
24
24
  </div>
25
25
  <div class="header-status">
26
26
  <span id="connection-status" class="status-dot disconnected"></span>
27
+ <a id="tunnel-live-pill" class="tunnel-live-pill" hidden target="_blank" rel="noopener" title="Managed tunnel is live - open in a new tab"></a>
28
+ <button id="tunnel-settings-toggle" class="header-mini-btn" type="button" title="Internet tunnel settings">Tunnel</button>
27
29
  <button id="language-toggle" class="header-mini-btn" type="button">中文</button>
28
30
  <button id="toast-settings-toggle" class="header-mini-btn" type="button" title="Toast notifications">Toasts</button>
29
31
  <button id="worker-install-toggle" class="header-mini-btn" type="button" hidden>Add worker</button>
@@ -131,10 +133,6 @@
131
133
 
132
134
  <!-- Workspace Tab -->
133
135
  <div id="tab-workspace" class="tab-panel">
134
- <div class="tunnel-card" id="tunnel-panel">
135
- <h3>Internet Tunnel</h3>
136
- <div class="tunnel-state"><span class="tunnel-note">loading…</span></div>
137
- </div>
138
136
  <div class="workspace-browser">
139
137
  <aside class="workspace-sidebar-panel">
140
138
  <div class="workspace-panel-header">
@@ -397,6 +395,20 @@
397
395
  </div>
398
396
  </footer>
399
397
 
398
+ <!-- Internet tunnel configuration popover (opened from the header
399
+ Tunnel button; the managed URL surfaces as #tunnel-live-pill while
400
+ active). -->
401
+ <div id="tunnel-popover" class="tunnel-popover" hidden>
402
+ <div class="tunnel-popover-backdrop" data-act="close"></div>
403
+ <div class="tunnel-popover-card" role="dialog" aria-modal="true" aria-label="Internet tunnel settings">
404
+ <div class="tunnel-popover-head">
405
+ <h3>Internet Tunnel</h3>
406
+ <button class="tunnel-popover-close" data-act="close" type="button" aria-label="Close">×</button>
407
+ </div>
408
+ <div class="tunnel-state"><span class="tunnel-note">loading…</span></div>
409
+ </div>
410
+ </div>
411
+
400
412
  <script src="/ui/app.js"></script>
401
413
  </body>
402
414
  </html>
package/src/ui/style.css CHANGED
@@ -502,6 +502,18 @@ body {
502
502
  }
503
503
  .task-title { font-weight: 600; font-size: 14px; margin-bottom: 4px; }
504
504
  .task-desc { font-size: 12px; color: var(--text-secondary); margin-bottom: 6px; }
505
+ /* List-density relief: long contract results/descriptions/notes clamp to
506
+ 3 lines on the card; full text lives in the task detail panel. */
507
+ .task-card .clamp {
508
+ display: -webkit-box;
509
+ -webkit-line-clamp: 3;
510
+ -webkit-box-orient: vertical;
511
+ overflow: hidden;
512
+ }
513
+ .tunnel-setup-help { margin: 6px 0 2px; }
514
+ .tunnel-setup-help summary { cursor: pointer; color: var(--text-muted); font-size: 12px; user-select: none; }
515
+ .tunnel-setup-help[open] summary { margin-bottom: 4px; }
516
+ .tunnel-setup-help div { padding-left: 2px; }
505
517
  .task-origin-badge {
506
518
  font-size: 10px;
507
519
  font-weight: 600;
@@ -2558,5 +2570,42 @@ body {
2558
2570
  .tunnel-on a { color: var(--accent); font-family: var(--mono); }
2559
2571
  .tunnel-token { margin: 8px 0; font-size: 13px; }
2560
2572
  .tunnel-token b { font-family: var(--mono); letter-spacing: .15em; color: var(--accent); }
2573
+ .tunnel-token-input {
2574
+ display: block; width: 100%; box-sizing: border-box; margin: 6px 0;
2575
+ padding: 8px 10px; border-radius: 8px; border: 1px solid var(--border, #3a3731);
2576
+ background: var(--surface-2, #232120); color: var(--text, #ecebe6);
2577
+ font-size: 12.5px; font-family: var(--mono, monospace);
2578
+ }
2579
+ /* Header pill: live managed (*.teamclaw.dev) tunnel URL. */
2580
+ .tunnel-live-pill {
2581
+ display: inline-flex; align-items: center; gap: 6px;
2582
+ max-width: 240px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
2583
+ padding: 3px 10px; border-radius: 999px;
2584
+ background: rgba(108, 190, 128, 0.14); border: 1px solid rgba(108, 190, 128, 0.4);
2585
+ color: #6cbe80; font-size: 11.5px; font-family: var(--mono, monospace);
2586
+ text-decoration: none; vertical-align: middle;
2587
+ }
2588
+ .tunnel-live-pill::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: #6cbe80; flex: none; box-shadow: 0 0 6px #6cbe80; }
2589
+ .tunnel-live-pill:hover { background: rgba(108, 190, 128, 0.22); }
2590
+ /* Tunnel settings popover (opened from the header Tunnel button). */
2591
+ .tunnel-popover { position: fixed; inset: 0; z-index: 300; }
2592
+ .tunnel-popover[hidden] { display: none; }
2593
+ .tunnel-popover-backdrop { position: absolute; inset: 0; background: rgba(10, 9, 7, 0.55); backdrop-filter: blur(2px); }
2594
+ .tunnel-popover-card {
2595
+ position: absolute; top: 64px; right: 18px; width: min(420px, calc(100vw - 36px));
2596
+ background: var(--surface-1, #1a1917); border: 1px solid var(--border, #2d2b27);
2597
+ border-radius: 14px; padding: 16px 18px 18px; box-shadow: 0 18px 48px rgba(0, 0, 0, 0.45);
2598
+ }
2599
+ .tunnel-popover-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
2600
+ .tunnel-popover-head h3 { margin: 0; font-size: 14px; }
2601
+ .tunnel-popover-close {
2602
+ background: none; border: none; color: var(--text-muted); font-size: 18px;
2603
+ line-height: 1; cursor: pointer; padding: 2px 6px; border-radius: 6px;
2604
+ }
2605
+ .tunnel-popover-close:hover { background: var(--surface-2); color: var(--text); }
2606
+ .tunnel-popover-card .tunnel-state { display: flex; flex-direction: column; align-items: flex-start; gap: 8px; }
2607
+ .tunnel-popover-card .tunnel-token-input { width: 100%; }
2608
+ .tunnel-popover-card .tunnel-note { margin-left: 0; }
2609
+ .tunnel-popover-card .tunnel-on { word-break: break-all; }
2561
2610
  .tunnel-note { margin-left: 10px; color: var(--text-muted); font-size: 12px; }
2562
2611
  .tunnel-err { color: var(--danger); font-size: 12.5px; margin-top: 8px; }