@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.
- package/README.md +2 -0
- package/index.ts +16 -0
- package/openclaw.plugin.json +20 -1
- package/package.json +2 -2
- package/src/config.ts +19 -0
- package/src/controller/controller-service.ts +50 -2
- package/src/controller/github-auth.ts +699 -0
- package/src/controller/http-server.ts +482 -6
- package/src/controller/orchestration-manifest.ts +1 -0
- package/src/controller/tunnel-manager.ts +386 -0
- package/src/controller/websocket.ts +2 -1
- package/src/controller/worker-provisioning.ts +15 -0
- package/src/task-executor.ts +17 -1
- package/src/teamauto/github-client.ts +254 -0
- package/src/teamauto/norms.ts +103 -0
- package/src/teamauto/repo-sync.ts +218 -0
- package/src/teamauto/scanner.ts +221 -0
- package/src/teamauto/scheduler.ts +595 -0
- package/src/teamauto/store.ts +242 -0
- package/src/types.ts +39 -0
- package/src/ui/app.js +892 -10
- package/src/ui/github-login.html +296 -0
- package/src/ui/index.html +52 -1
- package/src/ui/style.css +208 -58
- package/src/worker/worker-service.ts +16 -1
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import type { PluginLogger } from "../../api.js";
|
|
5
|
+
import https from "node:https";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
|
|
9
|
+
const TUNNEL_API_HOST = "apps.teamclaw.dev";
|
|
10
|
+
async function tunnelFetch(pathq: string, method: "POST" | "DELETE", body?: unknown): Promise<{ status: number; json: any }> {
|
|
11
|
+
const ip = await new Promise<string>((resolve, reject) => {
|
|
12
|
+
const r = https.request({ host: "1.1.1.1", path: `/dns-query?name=${TUNNEL_API_HOST}&type=A`, method: "GET", headers: { accept: "application/dns-json" }, servername: "cloudflare-dns.com" } as never, (res: import("node:http").IncomingMessage) => {
|
|
13
|
+
let d = ""; res.on("data", (c: Buffer) => (d += c)); res.on("end", () => {
|
|
14
|
+
try { const rec = (JSON.parse(d).Answer || []).map((x: { data: string }) => x.data).find((x: string) => /^\d+\./.test(x)); rec ? resolve(rec) : reject(new Error("DoH no A record")); } catch (e) { reject(e); }
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
r.on("error", reject); r.end();
|
|
18
|
+
});
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
const payload = body === undefined ? null : JSON.stringify(body);
|
|
21
|
+
const req = https.request({ host: ip, servername: TUNNEL_API_HOST, path: `/api${pathq}`, method, headers: { host: TUNNEL_API_HOST, "Content-Type": "application/json", ...(payload ? { "Content-Length": Buffer.byteLength(payload) } : {}) } } as never, (res: import("node:http").IncomingMessage) => {
|
|
22
|
+
let d = ""; res.on("data", (c: Buffer) => (d += c)); res.on("end", () => { try { resolve({ status: res.statusCode ?? 0, json: d ? JSON.parse(d) : {} }); } catch { resolve({ status: res.statusCode ?? 0, json: {} }); } });
|
|
23
|
+
});
|
|
24
|
+
req.on("error", reject);
|
|
25
|
+
if (payload) req.write(payload);
|
|
26
|
+
req.end();
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Internet tunnel sharing for the local web UI.
|
|
33
|
+
*
|
|
34
|
+
* Flow: the controller asks the TeamClaw tunnel server (a Cloudflare Worker
|
|
35
|
+
* at apps.teamclaw.dev/api) to provision a per-user Cloudflare Tunnel, then
|
|
36
|
+
* runs `cloudflared` locally with the returned connector token. Visitors hit
|
|
37
|
+
* https://<github_user>.apps.teamclaw.dev and must enter the gate token that
|
|
38
|
+
* the local web UI displays (enforced by the controller's gate middleware).
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
export const TUNNEL_SERVER_URL = "https://apps.teamclaw.dev/api";
|
|
42
|
+
const TUNNEL_HOST_SUFFIX = ".teamclaw.dev";
|
|
43
|
+
const GATE_COOKIE = "tc_tunnel_gate";
|
|
44
|
+
|
|
45
|
+
export type TunnelStatus = {
|
|
46
|
+
active: boolean;
|
|
47
|
+
hostname: string | null;
|
|
48
|
+
gateToken: string | null;
|
|
49
|
+
connectorRunning: boolean;
|
|
50
|
+
tunnelId: string | null;
|
|
51
|
+
cloudflaredInstalled: boolean;
|
|
52
|
+
cloudflaredPath: string | null;
|
|
53
|
+
startOp: { running: boolean; phase: string; detail: string | null };
|
|
54
|
+
install: { running: boolean; phase: string; percent: number | null; detail: string | null };
|
|
55
|
+
error: string | null;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export type TunnelHandle = {
|
|
59
|
+
tunnelId: string;
|
|
60
|
+
hostname: string;
|
|
61
|
+
gateToken: string;
|
|
62
|
+
// HMAC(tunnelId) issued by the tunnel server at create time; required to
|
|
63
|
+
// delete a live tunnel (tunnel ids are public via the DNS CNAME).
|
|
64
|
+
deleteToken: string;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const CLOUDFLARED_CANDIDATES = [
|
|
68
|
+
"cloudflared",
|
|
69
|
+
"/opt/homebrew/bin/cloudflared",
|
|
70
|
+
"/usr/local/bin/cloudflared",
|
|
71
|
+
"/usr/bin/cloudflared",
|
|
72
|
+
];
|
|
73
|
+
function tunnelRuntimeHome(): string {
|
|
74
|
+
try {
|
|
75
|
+
const dir = path.join(os.tmpdir(), "teamclaw-cloudflared-home");
|
|
76
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
77
|
+
return dir;
|
|
78
|
+
} catch {
|
|
79
|
+
return process.env.HOME ?? "/tmp";
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface PersistedTunnelState {
|
|
84
|
+
tunnelId: string;
|
|
85
|
+
hostname: string;
|
|
86
|
+
gateToken: string;
|
|
87
|
+
deleteToken: string;
|
|
88
|
+
connectorToken: string;
|
|
89
|
+
pid: number | null;
|
|
90
|
+
savedAt: number;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function tunnelStatePath(): string {
|
|
94
|
+
return path.join(tunnelRuntimeHome(), "tunnel-state.json");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function readTunnelState(): PersistedTunnelState | null {
|
|
98
|
+
try {
|
|
99
|
+
const raw = JSON.parse(fs.readFileSync(tunnelStatePath(), "utf8")) as PersistedTunnelState;
|
|
100
|
+
return raw && raw.tunnelId && raw.connectorToken ? raw : null;
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function writeTunnelState(st: PersistedTunnelState): void {
|
|
107
|
+
try {
|
|
108
|
+
fs.writeFileSync(tunnelStatePath(), JSON.stringify(st), { mode: 0o600 });
|
|
109
|
+
} catch { /* best effort */ }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function clearTunnelState(): void {
|
|
113
|
+
try { fs.rmSync(tunnelStatePath(), { force: true }); } catch { /* best effort */ }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// pid-reuse-safe liveness: only treat the pid as OUR orphan when the binary
|
|
117
|
+
// still matches cloudflared.
|
|
118
|
+
function connectorPidIsCloudflared(pid: number): boolean {
|
|
119
|
+
try {
|
|
120
|
+
const out = execFileSync("ps", ["-p", String(pid), "-o", "comm="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
121
|
+
return out.includes("cloudflared");
|
|
122
|
+
} catch {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function findCloudflared(): string | null {
|
|
128
|
+
for (const bin of CLOUDFLARED_CANDIDATES) {
|
|
129
|
+
try {
|
|
130
|
+
if (fs.existsSync(bin) && fs.accessSync(bin, fs.constants.X_OK) === undefined) {
|
|
131
|
+
return bin;
|
|
132
|
+
}
|
|
133
|
+
} catch {
|
|
134
|
+
/* try next */
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function gateCookieValue(gateToken: string, tunnelId: string): string {
|
|
141
|
+
return createHash("sha256").update(`${gateToken}:${tunnelId}`).digest("hex").slice(0, 32);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function createTunnelManager(deps: { logger: PluginLogger; localPort: number }) {
|
|
145
|
+
const { logger } = deps;
|
|
146
|
+
let child: ChildProcess | null = null;
|
|
147
|
+
let handle: TunnelHandle | null = null;
|
|
148
|
+
let lastError: string | null = null;
|
|
149
|
+
let startOp: { running: boolean; phase: string; detail: string | null } = { running: false, phase: "idle", detail: null };
|
|
150
|
+
let installState: { running: boolean; phase: string; percent: number | null; detail: string | null } = { running: false, phase: "idle", percent: null, detail: null };
|
|
151
|
+
|
|
152
|
+
function isTunnelRequest(hostHeader: string | undefined): boolean {
|
|
153
|
+
return Boolean(hostHeader && hostHeader.toLowerCase().endsWith(TUNNEL_HOST_SUFFIX));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function gateAllows(req: { headers: Record<string, unknown> }): boolean {
|
|
157
|
+
if (!handle) return false;
|
|
158
|
+
const cookie = String(req.headers.cookie ?? "");
|
|
159
|
+
const match = cookie.match(new RegExp(`${GATE_COOKIE}=([0-9a-f]+)`));
|
|
160
|
+
return Boolean(match && match[1] === gateCookieValue(handle.gateToken, handle.tunnelId));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function launchStart(githubUser: string): { running: boolean; phase: string } {
|
|
164
|
+
if (startOp.running) return { running: true, phase: startOp.phase };
|
|
165
|
+
startOp = { running: true, phase: "creating-tunnel", detail: null };
|
|
166
|
+
void (async () => {
|
|
167
|
+
try {
|
|
168
|
+
const h = await start(githubUser);
|
|
169
|
+
startOp = { running: false, phase: "done", detail: h.hostname };
|
|
170
|
+
} catch (e) {
|
|
171
|
+
startOp = { running: false, phase: "error", detail: e instanceof Error ? e.message : String(e) };
|
|
172
|
+
}
|
|
173
|
+
})();
|
|
174
|
+
return { running: true, phase: startOp.phase };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async function start(githubUser: string): Promise<TunnelHandle> {
|
|
178
|
+
if (handle && child) return handle;
|
|
179
|
+
const bin = findCloudflared();
|
|
180
|
+
if (!bin) throw new Error("cloudflared not found (brew install cloudflared)");
|
|
181
|
+
const gateToken = randomBytes(6).toString("base64url").replace(/[-_]/g, "").slice(0, 8).toUpperCase();
|
|
182
|
+
const res = await tunnelFetch("/tunnels", "POST", { github_user: githubUser, local_port: deps.localPort });
|
|
183
|
+
const body = res.json as { tunnel_id?: string; connector_token?: string; hostname?: string; delete_token?: string; error?: string };
|
|
184
|
+
if (res.status !== 201 || !body.tunnel_id || !body.connector_token || !body.hostname) {
|
|
185
|
+
throw new Error(body.error ?? `tunnel server responded ${res.status}`);
|
|
186
|
+
}
|
|
187
|
+
startOp = { running: true, phase: "starting-connector", detail: body.hostname };
|
|
188
|
+
stopConnector();
|
|
189
|
+
child = spawnConnector(bin, body.connector_token);
|
|
190
|
+
handle = { tunnelId: body.tunnel_id, hostname: body.hostname, gateToken, deleteToken: body.delete_token ?? "" };
|
|
191
|
+
writeTunnelState({ tunnelId: body.tunnel_id, hostname: body.hostname, gateToken, deleteToken: body.delete_token ?? "", connectorToken: body.connector_token, pid: child.pid ?? null, savedAt: Date.now() });
|
|
192
|
+
lastError = null;
|
|
193
|
+
logger.info(`TeamClaw tunnel: serving https://${body.hostname}`);
|
|
194
|
+
return handle;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function spawnConnector(bin: string, connectorToken: string): ChildProcess {
|
|
198
|
+
const proc = spawn(bin, ["tunnel", "--no-autoupdate", "--protocol", "http2", "run", "--token", connectorToken], {
|
|
199
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
200
|
+
detached: false,
|
|
201
|
+
// Isolate from ~/.cloudflared/cert.pem (a local origin-cert would
|
|
202
|
+
// override the remotely-managed token config) and from QUIC-blocking
|
|
203
|
+
// networks (http2 rides regular TCP 443).
|
|
204
|
+
env: { ...process.env, HOME: tunnelRuntimeHome() },
|
|
205
|
+
});
|
|
206
|
+
proc.on("exit", (code: number | null) => {
|
|
207
|
+
logger.warn(`TeamClaw tunnel: cloudflared exited (code ${code})`);
|
|
208
|
+
if (child === proc) child = null;
|
|
209
|
+
});
|
|
210
|
+
// cloudflared logs (stderr) land in a single file for diagnosis.
|
|
211
|
+
// (stdout is "ignore" in stdio above, so there is nothing to pipe.)
|
|
212
|
+
const logPath = path.join(tunnelRuntimeHome(), "cloudflared.log");
|
|
213
|
+
proc.stderr?.pipe(fs.createWriteStream(logPath, { flags: "a" }));
|
|
214
|
+
return proc;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function stopConnector(): void {
|
|
218
|
+
if (child) {
|
|
219
|
+
child.kill("SIGTERM");
|
|
220
|
+
child = null;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function stop(): Promise<void> {
|
|
225
|
+
stopConnector();
|
|
226
|
+
if (handle) {
|
|
227
|
+
const gone = handle;
|
|
228
|
+
handle = null;
|
|
229
|
+
await tunnelFetch(`/tunnels/${gone.tunnelId}?user=${encodeURIComponent(gone.hostname.split(".")[0]!.replace(/^team-/, ""))}&token=${encodeURIComponent(gone.deleteToken)}`, "DELETE").catch(() => undefined);
|
|
230
|
+
clearTunnelState();
|
|
231
|
+
logger.info(`TeamClaw tunnel: stopped ${gone.hostname}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// Boot reconciliation: reconnect the share persisted by a previous run.
|
|
236
|
+
// Reuses the SAME remotely-managed tunnel (its connector token), so the
|
|
237
|
+
// tunnel id and gate token survive gateway restarts and visitor gate
|
|
238
|
+
// cookies stay valid.
|
|
239
|
+
async function recover(): Promise<TunnelHandle | null> {
|
|
240
|
+
if (handle) return handle;
|
|
241
|
+
const st = readTunnelState();
|
|
242
|
+
if (!st) return null;
|
|
243
|
+
const bin = findCloudflared();
|
|
244
|
+
if (!bin) {
|
|
245
|
+
logger.warn("TeamClaw tunnel: previous share found but cloudflared is not installed; not recovering");
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
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
|
+
if (st.pid && connectorPidIsCloudflared(st.pid)) {
|
|
252
|
+
try {
|
|
253
|
+
process.kill(st.pid, "SIGKILL");
|
|
254
|
+
logger.warn(`TeamClaw tunnel: killed orphaned connector (pid ${st.pid})`);
|
|
255
|
+
} catch { /* already gone */ }
|
|
256
|
+
}
|
|
257
|
+
startOp = { running: true, phase: "starting-connector", detail: st.hostname };
|
|
258
|
+
stopConnector();
|
|
259
|
+
child = spawnConnector(bin, st.connectorToken);
|
|
260
|
+
handle = { tunnelId: st.tunnelId, hostname: st.hostname, gateToken: st.gateToken, deleteToken: st.deleteToken };
|
|
261
|
+
writeTunnelState({ ...st, pid: child.pid ?? null, savedAt: Date.now() });
|
|
262
|
+
startOp = { running: false, phase: "done", detail: st.hostname };
|
|
263
|
+
lastError = null;
|
|
264
|
+
logger.info(`TeamClaw tunnel: recovered https://${st.hostname} (tunnel id and gate token preserved)`);
|
|
265
|
+
return handle;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function status(): TunnelStatus {
|
|
269
|
+
return {
|
|
270
|
+
active: Boolean(handle),
|
|
271
|
+
tunnelId: handle?.tunnelId ?? null,
|
|
272
|
+
hostname: handle?.hostname ?? null,
|
|
273
|
+
gateToken: handle?.gateToken ?? null,
|
|
274
|
+
connectorRunning: Boolean(child),
|
|
275
|
+
cloudflaredInstalled: findCloudflared() !== null,
|
|
276
|
+
cloudflaredPath: findCloudflared(),
|
|
277
|
+
startOp: { ...startOp },
|
|
278
|
+
install: { ...installState },
|
|
279
|
+
error: lastError,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* One-click cloudflared install across platforms:
|
|
285
|
+
* darwin -> brew install cloudflared (Homebrew), tarball fallback
|
|
286
|
+
* linux -> official tarball into ~/.local/bin (no sudo needed)
|
|
287
|
+
* win32 -> winget install Cloudflare.cloudflared
|
|
288
|
+
*/
|
|
289
|
+
|
|
290
|
+
function installCloudflared(): Promise<{ ok: boolean; detail: string }> {
|
|
291
|
+
if (installState.running) {
|
|
292
|
+
return Promise.resolve({ ok: false, detail: "install already in progress" });
|
|
293
|
+
}
|
|
294
|
+
const home = process.env.HOME ?? "/tmp";
|
|
295
|
+
const userBin = path.join(home, ".local", "bin");
|
|
296
|
+
const target = path.join(userBin, "cloudflared");
|
|
297
|
+
const tail = (s: string) => s.trim().split("\n").slice(-2).join(" ").slice(0, 200);
|
|
298
|
+
const setPhase = (phase: string, percent: number | null, detail: string | null) => {
|
|
299
|
+
installState = { running: true, phase, percent, detail };
|
|
300
|
+
};
|
|
301
|
+
const finish = (phase: string, detail: string) => {
|
|
302
|
+
installState = { running: false, phase, percent: phase === "done" ? 100 : null, detail };
|
|
303
|
+
};
|
|
304
|
+
const run = (cmd: string, args: string[]) =>
|
|
305
|
+
new Promise<{ code: number; out: string }>((resolve) => {
|
|
306
|
+
const proc = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
307
|
+
let out = "";
|
|
308
|
+
proc.stdout?.on("data", (c) => (out += c));
|
|
309
|
+
proc.stderr?.on("data", (c) => (out += c));
|
|
310
|
+
proc.on("error", (e) => resolve({ code: 1, out: String(e) }));
|
|
311
|
+
proc.on("close", (code) => resolve({ code: code ?? 1, out }));
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
const job = (async (): Promise<{ ok: boolean; detail: string }> => {
|
|
315
|
+
const plat = process.platform + ":" + process.arch;
|
|
316
|
+
logger.info("TeamClaw tunnel: installing cloudflared for " + plat);
|
|
317
|
+
setPhase("installing", null, plat);
|
|
318
|
+
if (process.platform === "win32") {
|
|
319
|
+
const w = await run("winget", ["install", "--id", "Cloudflare.cloudflared", "--accept-source-agreements", "--accept-package-agreements"]);
|
|
320
|
+
return w.code === 0 ? { ok: true, detail: "installed via winget" } : { ok: false, detail: "winget: " + tail(w.out) };
|
|
321
|
+
}
|
|
322
|
+
if (process.platform === "darwin") {
|
|
323
|
+
setPhase("brew", 30, "Homebrew");
|
|
324
|
+
const brew = await run("brew", ["install", "cloudflared"]);
|
|
325
|
+
if (brew.code === 0) return { ok: true, detail: "installed via Homebrew" };
|
|
326
|
+
}
|
|
327
|
+
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";
|
|
329
|
+
fs.mkdirSync(userBin, { recursive: true });
|
|
330
|
+
const tgz = path.join(userBin, name);
|
|
331
|
+
const url = "https://github.com/cloudflare/cloudflared/releases/latest/download/" + name;
|
|
332
|
+
let total = 0;
|
|
333
|
+
try {
|
|
334
|
+
const head = await new Promise<import("node:http").IncomingMessage>((resolve, reject) => {
|
|
335
|
+
const r = https.request(url, { method: "HEAD" } as never, resolve as never);
|
|
336
|
+
r.on("error", reject); r.end();
|
|
337
|
+
});
|
|
338
|
+
total = Number(head.headers["content-length"] ?? 0);
|
|
339
|
+
} catch { total = 0; }
|
|
340
|
+
setPhase("downloading", 0, url);
|
|
341
|
+
const timer = setInterval(() => {
|
|
342
|
+
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) };
|
|
354
|
+
fs.chmodSync(target, 0o755);
|
|
355
|
+
return { ok: true, detail: "installed to " + target };
|
|
356
|
+
})();
|
|
357
|
+
|
|
358
|
+
job.then(
|
|
359
|
+
(r) => finish(r.ok ? "done" : "error", r.detail),
|
|
360
|
+
(e) => finish("error", String(e)),
|
|
361
|
+
);
|
|
362
|
+
return job;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
return { start: launchStart, stop, recover, status, installCloudflared, isTunnelRequest, gateAllows };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
export type TunnelManager = ReturnType<typeof createTunnelManager>;
|
|
370
|
+
|
|
371
|
+
export function gatePageHtml(hostname: string, wrong: boolean): string {
|
|
372
|
+
return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>TeamClaw Tunnel</title>
|
|
373
|
+
<style>body{font-family:-apple-system,system-ui,sans-serif;background:#121110;color:#ecebe6;display:flex;align-items:center;justify-content:center;height:100vh;margin:0}
|
|
374
|
+
.card{background:#1a1917;border:1px solid #2d2b27;border-radius:12px;padding:32px;width:min(360px,90vw);text-align:center}
|
|
375
|
+
h1{font-size:16px;margin:0 0 6px}p{font-size:12.5px;color:#a8a49a;margin:0 0 18px}
|
|
376
|
+
input{width:100%;padding:10px 12px;border-radius:8px;border:1px solid #3a3731;background:#232120;color:#ecebe6;font-size:16px;letter-spacing:.2em;text-align:center;text-transform:uppercase;box-sizing:border-box}
|
|
377
|
+
button{margin-top:12px;width:100%;padding:10px;border:none;border-radius:8px;background:#d9a664;color:#1a1510;font-weight:600;font-size:14px;cursor:pointer}
|
|
378
|
+
.err{color:#c96f5e;font-size:12px;margin-top:10px}</style></head>
|
|
379
|
+
<body><div class="card"><h1>TeamClaw</h1><p>${hostname} is protected by a gate token. Ask the owner for it.</p>
|
|
380
|
+
<form method="POST" action="/__tunnel_gate/verify"><input name="token" placeholder="GATE TOKEN" autofocus autocomplete="off"><button type="submit">Enter</button>${wrong ? '<div class="err">Wrong token, try again.</div>' : ""}</form></div></body></html>`;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export const GATE_COOKIE_NAME = GATE_COOKIE;
|
|
384
|
+
export function computeGateCookie(gateToken: string, tunnelId: string): string {
|
|
385
|
+
return gateCookieValue(gateToken, tunnelId);
|
|
386
|
+
}
|
|
@@ -19,7 +19,8 @@ export type WsEvent =
|
|
|
19
19
|
| { type: "message:deleted"; data: unknown }
|
|
20
20
|
| { type: "project:deleted"; data: unknown }
|
|
21
21
|
| { type: "requirement:complete"; data: unknown }
|
|
22
|
-
| { type: "report:ready"; data: unknown }
|
|
22
|
+
| { type: "report:ready"; data: unknown }
|
|
23
|
+
| { type: "teamauto:activity"; data: unknown };
|
|
23
24
|
|
|
24
25
|
export class TeamWebSocketServer {
|
|
25
26
|
private wss: WebSocketServer | null = null;
|
|
@@ -1374,6 +1374,21 @@ function buildProvisionedWorkerConfig(
|
|
|
1374
1374
|
} else {
|
|
1375
1375
|
delete agentDefaults.workspace;
|
|
1376
1376
|
}
|
|
1377
|
+
// The host controller may run a newer openclaw that persists the keyed
|
|
1378
|
+
// agents.entries schema (e.g. agents.entries.teamclaw.model written by the
|
|
1379
|
+
// model-configuration feature). Provisioned workers can run an older
|
|
1380
|
+
// openclaw that rejects unknown agents keys ("Unrecognized key: entries"),
|
|
1381
|
+
// so fold the teamclaw entry's model back into the legacy
|
|
1382
|
+
// agents.defaults.model and drop the entries map. New-schema workers also
|
|
1383
|
+
// accept agents.defaults, keeping the folded config compatible both ways.
|
|
1384
|
+
const agentsRecord = agents as { entries?: Record<string, { model?: string }> };
|
|
1385
|
+
if (agentsRecord.entries && typeof agentsRecord.entries === "object") {
|
|
1386
|
+
const entryModel = agentsRecord.entries[TEAMCLAW_AGENT_ID]?.model;
|
|
1387
|
+
if (entryModel && !agentDefaults.model) {
|
|
1388
|
+
agentDefaults.model = entryModel;
|
|
1389
|
+
}
|
|
1390
|
+
delete agentsRecord.entries;
|
|
1391
|
+
}
|
|
1377
1392
|
agents.defaults = agentDefaults;
|
|
1378
1393
|
config.agents = agents;
|
|
1379
1394
|
|
package/src/task-executor.ts
CHANGED
|
@@ -21,6 +21,8 @@ const TEAMCLAW_ROLE_IDS_TEXT = [
|
|
|
21
21
|
];
|
|
22
22
|
|
|
23
23
|
const SESSION_PROGRESS_POLL_INTERVAL_MS = 1000;
|
|
24
|
+
/** Checkpoint heartbeat cadence (resume support). */
|
|
25
|
+
const CHECKPOINT_EMIT_INTERVAL_MS = 15_000;
|
|
24
26
|
const SESSION_PROGRESS_MESSAGE_LIMIT = 200;
|
|
25
27
|
const MAX_SESSION_PROGRESS_MESSAGE_CHARS = 4000;
|
|
26
28
|
const RUN_WAIT_SLICE_MS = 30_000;
|
|
@@ -76,10 +78,12 @@ export type RoleTaskExecutorDeps = {
|
|
|
76
78
|
getSessionKey: (assignment: TaskAssignmentPayload) => string;
|
|
77
79
|
getIdempotencyKey?: (assignment: TaskAssignmentPayload) => string;
|
|
78
80
|
reportExecutionEvent?: (taskId: string, event: TaskExecutionEventInput) => Promise<void> | void;
|
|
81
|
+
/** Persist a resumable progress snapshot (throttled by the executor). */
|
|
82
|
+
reportCheckpoint?: (taskId: string, checkpoint: { lastAssistantMessage: string; progressNote?: string; sessionKey: string }) => Promise<void> | void;
|
|
79
83
|
};
|
|
80
84
|
|
|
81
85
|
export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
|
|
82
|
-
const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent } = deps;
|
|
86
|
+
const { runtime, logger, role, taskTimeoutMs, getSessionKey, getIdempotencyKey, reportExecutionEvent, reportCheckpoint } = deps;
|
|
83
87
|
const roleDef = getRole(role);
|
|
84
88
|
const roleSystemPrompt = roleDef
|
|
85
89
|
? roleDef.systemPrompt
|
|
@@ -143,6 +147,8 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
|
|
|
143
147
|
}
|
|
144
148
|
|
|
145
149
|
try {
|
|
150
|
+
// Checkpoint heartbeat state for resume support.
|
|
151
|
+
let lastCheckpointAt = 0;
|
|
146
152
|
const runResult = await runtime.subagent.run(buildSubagentRunOptions({
|
|
147
153
|
sessionKey,
|
|
148
154
|
message: taskMessage,
|
|
@@ -291,6 +297,16 @@ export function createRoleTaskExecutor(deps: RoleTaskExecutorDeps) {
|
|
|
291
297
|
}
|
|
292
298
|
if (entry.stream === "assistant") {
|
|
293
299
|
progressSnapshot.lastAssistantMessage = entry.message;
|
|
300
|
+
// Checkpoint heartbeat: persist the latest assistant turn so an
|
|
301
|
+
// interrupted execution resumes with fresh context (max once per
|
|
302
|
+
// CHECKPOINT_EMIT_INTERVAL_MS to bound controller write load).
|
|
303
|
+
if (reportCheckpoint && Date.now() - lastCheckpointAt >= CHECKPOINT_EMIT_INTERVAL_MS) {
|
|
304
|
+
lastCheckpointAt = Date.now();
|
|
305
|
+
void Promise.resolve(reportCheckpoint(taskId, {
|
|
306
|
+
lastAssistantMessage: entry.message.slice(0, 8000),
|
|
307
|
+
sessionKey,
|
|
308
|
+
})).catch(() => { /* checkpointing is best-effort */ });
|
|
309
|
+
}
|
|
294
310
|
}
|
|
295
311
|
await emitExecutionEvent({
|
|
296
312
|
type: "progress",
|