@gobius/t3ctl 0.5.0 → 0.7.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 +167 -12
- package/dist/t3ctl.js +796 -28
- package/dist/t3ctl.js.map +1 -1
- package/package.json +1 -1
package/dist/t3ctl.js
CHANGED
|
@@ -2,7 +2,10 @@
|
|
|
2
2
|
// t3ctl — a controller CLI for T3 Code hosts.
|
|
3
3
|
// Peer of the mobile app: pairs once per host, then reads/controls remotely.
|
|
4
4
|
// Spike scope: host registry + read-only listing.
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
5
7
|
import fs from 'node:fs';
|
|
8
|
+
import net from 'node:net';
|
|
6
9
|
import { Command } from 'commander';
|
|
7
10
|
import os from 'node:os';
|
|
8
11
|
import path from 'node:path';
|
|
@@ -18,6 +21,7 @@ const writeHosts = (hosts) => {
|
|
|
18
21
|
fs.writeFileSync(HOSTS_FILE, JSON.stringify({ hosts }, null, 2), { mode: 0o600 });
|
|
19
22
|
};
|
|
20
23
|
const snapshot = async (host) => {
|
|
24
|
+
await ensureTunnel(host);
|
|
21
25
|
const res = await fetch(`${host.origin}/api/orchestration/snapshot`, {
|
|
22
26
|
headers: host.token ? { authorization: `Bearer ${host.token}` } : {},
|
|
23
27
|
signal: AbortSignal.timeout(host.timeoutMs ?? 15000),
|
|
@@ -78,7 +82,7 @@ const cmdLs = async ({ threads: showThreads, all: showAll, json: asJson }) => {
|
|
|
78
82
|
const hosts = readHosts();
|
|
79
83
|
if (!hosts.length)
|
|
80
84
|
return console.error('No hosts registered. Run: t3ctl host add <origin> <token>');
|
|
81
|
-
const { ok, failed } = await collect(hosts);
|
|
85
|
+
const [{ ok, failed }] = await Promise.all([collect(hosts), warnRivals(hosts)]);
|
|
82
86
|
if (asJson) {
|
|
83
87
|
const out = ok.flatMap(({ host, snap }) => snap.projects
|
|
84
88
|
.filter((p) => showAll || !p.deletedAt)
|
|
@@ -183,7 +187,10 @@ const cmdHostAdd = async (pos, flags, hosts) => {
|
|
|
183
187
|
return usage(HOST_ADD_USAGE);
|
|
184
188
|
const origin = parsed.origin.replace(/\/$/, '');
|
|
185
189
|
const descriptor = await probe(origin);
|
|
186
|
-
|
|
190
|
+
// Re-pointing a named host at another port of the same environment (see the
|
|
191
|
+
// split-brain guard) keeps its token: both ports serve one auth database.
|
|
192
|
+
const existing = hosts.find((h) => h.origin === origin) ??
|
|
193
|
+
hosts.find((h) => !h.ssh && h.name === flags.name && h.environmentId === descriptor.environmentId);
|
|
187
194
|
// A changed environmentId on a known origin means the origin now points at a
|
|
188
195
|
// different machine — the stored token almost certainly belongs to the old one.
|
|
189
196
|
if (existing?.environmentId && existing.environmentId !== descriptor.environmentId) {
|
|
@@ -214,6 +221,7 @@ const cmdHostAdd = async (pos, flags, hosts) => {
|
|
|
214
221
|
const cmdHostsList = async (hosts) => {
|
|
215
222
|
if (!hosts.length)
|
|
216
223
|
return console.log('(no hosts)');
|
|
224
|
+
await Promise.allSettled(hosts.filter((h) => h.ssh).map((h) => ensureTunnel(h)));
|
|
217
225
|
const probes = await Promise.allSettled(hosts.map((h) => probe(h.origin)));
|
|
218
226
|
const drifted = [];
|
|
219
227
|
hosts.forEach((h, i) => {
|
|
@@ -228,13 +236,372 @@ const cmdHostsList = async (hosts) => {
|
|
|
228
236
|
// Values for an unreachable host are whatever was last stored, so dim the
|
|
229
237
|
// whole row to keep remembered data visually distinct from probed data.
|
|
230
238
|
const cell = (text, width) => (live ? text.padEnd(width) : dim(text.padEnd(width)));
|
|
231
|
-
|
|
239
|
+
const where = dim(h.ssh ? `${h.ssh} -> ${h.origin}` : h.origin);
|
|
240
|
+
console.log(`${icon} ${live ? bold(h.name.padEnd(14)) : dim(h.name.padEnd(14))} ${cell(label, 18)} ${dim(env.padEnd(9))} ${cell(version, 28)} ${where}` +
|
|
232
241
|
(live || !p || p.status !== 'rejected' ? '' : ` ${dim(errorMessage(p.reason))}`));
|
|
233
242
|
});
|
|
234
243
|
for (const { h, live } of drifted) {
|
|
235
244
|
warn(`${h.name} (${h.origin}) is now a DIFFERENT environment\n` +
|
|
236
245
|
` was ${h.environmentId} (${h.label ?? 'unknown'})\n now ${live.environmentId} (${live.label})`);
|
|
237
246
|
}
|
|
247
|
+
await warnRivals(hosts);
|
|
248
|
+
};
|
|
249
|
+
// ---- ssh hosts ----------------------------------------------------------
|
|
250
|
+
// `t3ctl host add agent@box` fully bootstraps a remote T3 Code host: detect a
|
|
251
|
+
// running server, install the boot service if none, mint a token, and keep a
|
|
252
|
+
// local ssh port-forward alive. Three properties of T3 Code make "just an ssh
|
|
253
|
+
// login" enough:
|
|
254
|
+
// * the server records {pid, port} in ~/.t3/userdata/server-runtime.json, so
|
|
255
|
+
// the port is discoverable, never hardcoded (3773 or an ephemeral fallback,
|
|
256
|
+
// rewritten on every start);
|
|
257
|
+
// * `t3 auth session issue` mints a bearer token filesystem-locally — no HTTP,
|
|
258
|
+
// no --port — valid for the already-running server sharing ~/.t3, so t3ctl
|
|
259
|
+
// can mint its own token over ssh;
|
|
260
|
+
// * `t3 service install` is per-user launchd/systemd (no sudo, macOS/Linux).
|
|
261
|
+
// Remote shell scripts pass data back on stdout as lines starting with a
|
|
262
|
+
// marker, parsed bottom-up: `t3 auth` can leak Effect error logs onto stdout
|
|
263
|
+
// (the desktop's own SSH path parses the same way, tunnel.ts:791).
|
|
264
|
+
// npm package is literally `t3`; exact versions are pinned because the boot
|
|
265
|
+
// service installs that same version into its pinned runtime.
|
|
266
|
+
const SSH_READY_MS = 90_000; // server readiness after install (npm download can be slow)
|
|
267
|
+
const TUNNEL_WAIT_MS = 30_000; // ssh auth may prompt interactively; give it time
|
|
268
|
+
const PROBE_MS = 2500; // liveness probe of the local tunnel end
|
|
269
|
+
const T3_PACKAGE = 't3';
|
|
270
|
+
const SSH_SCRIPT = `set -eu
|
|
271
|
+
# PATH discovery for NON-INTERACTIVE ssh shells, trimmed from T3 Code's own
|
|
272
|
+
# remote runner (packages/ssh/src/tunnel.ts REMOTE_NODE_ENV_SCRIPT): plain PATH
|
|
273
|
+
# additions, version-manager shims, nvm. Engine checks and the "prefer installed
|
|
274
|
+
# t3" branch are dropped on purpose — t3ctl pins an exact version and runs npx.
|
|
275
|
+
prepend_path_if_dir() {
|
|
276
|
+
if [ -d "$1" ]; then
|
|
277
|
+
case ":$PATH:" in
|
|
278
|
+
*":$1:"*) ;;
|
|
279
|
+
*) PATH="$1:$PATH" ;;
|
|
280
|
+
esac
|
|
281
|
+
fi
|
|
282
|
+
}
|
|
283
|
+
ensure_node_path() {
|
|
284
|
+
command -v node >/dev/null 2>&1 && return 0
|
|
285
|
+
prepend_path_if_dir "$HOME/.local/bin"
|
|
286
|
+
prepend_path_if_dir "$HOME/bin"
|
|
287
|
+
prepend_path_if_dir "/opt/homebrew/bin"
|
|
288
|
+
prepend_path_if_dir "/usr/local/bin"
|
|
289
|
+
prepend_path_if_dir "/usr/bin"
|
|
290
|
+
prepend_path_if_dir "/bin"
|
|
291
|
+
if [ -z "\${VOLTA_HOME:-}" ]; then VOLTA_HOME="$HOME/.volta"; fi
|
|
292
|
+
prepend_path_if_dir "$VOLTA_HOME/bin"
|
|
293
|
+
prepend_path_if_dir "$HOME/.asdf/shims"
|
|
294
|
+
prepend_path_if_dir "$HOME/.asdf/bin"
|
|
295
|
+
if [ ! -x "$HOME/.asdf/shims/node" ] && [ -s "$HOME/.asdf/asdf.sh" ]; then . "$HOME/.asdf/asdf.sh"; fi
|
|
296
|
+
prepend_path_if_dir "$HOME/.local/share/mise/shims"
|
|
297
|
+
prepend_path_if_dir "$HOME/.mise/shims"
|
|
298
|
+
if ! command -v node >/dev/null 2>&1 && command -v mise >/dev/null 2>&1; then eval "$(mise activate sh)" >/dev/null 2>&1 || true; fi
|
|
299
|
+
if [ -z "\${FNM_DIR:-}" ]; then FNM_DIR="$HOME/.local/share/fnm"; fi
|
|
300
|
+
prepend_path_if_dir "$FNM_DIR"
|
|
301
|
+
prepend_path_if_dir "$HOME/.fnm"
|
|
302
|
+
if ! command -v node >/dev/null 2>&1 && command -v fnm >/dev/null 2>&1; then
|
|
303
|
+
eval "$(fnm env --shell bash)" >/dev/null 2>&1 || true
|
|
304
|
+
fnm use --silent-if-unchanged >/dev/null 2>&1 || fnm use default >/dev/null 2>&1 || true
|
|
305
|
+
fi
|
|
306
|
+
prepend_path_if_dir "$HOME/.nodenv/bin"
|
|
307
|
+
prepend_path_if_dir "$HOME/.nodenv/shims"
|
|
308
|
+
if ! command -v node >/dev/null 2>&1 && command -v nodenv >/dev/null 2>&1; then eval "$(nodenv init -)" >/dev/null 2>&1 || true; fi
|
|
309
|
+
if [ -z "\${NVM_DIR:-}" ]; then NVM_DIR="$HOME/.nvm"; fi
|
|
310
|
+
if [ -s "$NVM_DIR/nvm.sh" ]; then
|
|
311
|
+
. "$NVM_DIR/nvm.sh"
|
|
312
|
+
if ! command -v node >/dev/null 2>&1 && command -v nvm >/dev/null 2>&1; then
|
|
313
|
+
nvm use --silent default >/dev/null 2>&1 || nvm use --silent node >/dev/null 2>&1 || nvm use --silent --lts >/dev/null 2>&1 || true
|
|
314
|
+
fi
|
|
315
|
+
fi
|
|
316
|
+
if ! command -v node >/dev/null 2>&1 && [ -d "$NVM_DIR/versions/node" ]; then
|
|
317
|
+
for NODE_BIN in "$NVM_DIR"/versions/node/*/bin; do
|
|
318
|
+
if [ -x "$NODE_BIN/node" ]; then PATH="$NODE_BIN:$PATH"; fi
|
|
319
|
+
done
|
|
320
|
+
fi
|
|
321
|
+
command -v node >/dev/null 2>&1
|
|
322
|
+
}
|
|
323
|
+
# npm extracts a package before running its deps' native builds; a failed
|
|
324
|
+
# node-pty build leaves the npx cache WITHOUT a t3 bin while \`npx --yes\` still
|
|
325
|
+
# exits 0 (same guard as T3 Code's require_installed_t3_cli). Resolve up front
|
|
326
|
+
# so the failure is reported here, with npm's own output on stderr.
|
|
327
|
+
require_t3_cli() {
|
|
328
|
+
T3_CLI_PATH="$(npx --yes --package t3@"$1" -- sh -c 'command -v t3' 2>/dev/null || true)"
|
|
329
|
+
if [ -n "$T3_CLI_PATH" ]; then return 0; fi
|
|
330
|
+
printf 'npm installed t3@"%s" but produced no t3 executable — usually a native dependency (node-pty) failed to build. Install a C toolchain on this host (Debian/Ubuntu: build-essential, Fedora/RHEL: gcc-c++ make, macOS: xcode-select --install) and retry.\\n' "$1" >&2
|
|
331
|
+
return 1
|
|
332
|
+
}
|
|
333
|
+
# detect: is there a T3 Code server running on this machine? The runtime file is
|
|
334
|
+
# rewritten on every server start and cleared on shutdown, so its pid is
|
|
335
|
+
# checked before its port is trusted (stale file, reused port).
|
|
336
|
+
RUNTIME_JSON="$HOME/.t3/userdata/server-runtime.json"
|
|
337
|
+
detect() {
|
|
338
|
+
if ! ensure_node_path; then
|
|
339
|
+
printf 'T3CTL {"node":false}\\n'
|
|
340
|
+
return 0
|
|
341
|
+
fi
|
|
342
|
+
node - "$RUNTIME_JSON" <<'NODE'
|
|
343
|
+
const fs = require('node:fs');
|
|
344
|
+
try {
|
|
345
|
+
const r = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
|
|
346
|
+
const pid = Number(r.pid), port = Number(r.port);
|
|
347
|
+
if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port)) throw 0;
|
|
348
|
+
const origin = new URL(String(r.origin ?? ''));
|
|
349
|
+
if (origin.protocol !== 'http:' || !['127.0.0.1', 'localhost'].includes(origin.hostname)) throw 0;
|
|
350
|
+
process.kill(pid, 0);
|
|
351
|
+
process.stdout.write('T3CTL {"running":true,"port":' + port + '}\\n');
|
|
352
|
+
} catch {
|
|
353
|
+
process.stdout.write('T3CTL {"running":false}\\n');
|
|
354
|
+
}
|
|
355
|
+
NODE
|
|
356
|
+
}
|
|
357
|
+
case "$1" in
|
|
358
|
+
detect) detect ;;
|
|
359
|
+
install)
|
|
360
|
+
ensure_node_path || { printf 'no node on this machine — install Node 22+ (non-interactive shells may need a version manager configured)\\n' >&2; exit 1; }
|
|
361
|
+
require_t3_cli "$2" || exit 1
|
|
362
|
+
exec npx --yes --package t3@"$2" t3 service install
|
|
363
|
+
;;
|
|
364
|
+
token)
|
|
365
|
+
ensure_node_path || { printf 'no node on this machine\\n' >&2; exit 1; }
|
|
366
|
+
require_t3_cli "$2" || exit 1
|
|
367
|
+
exec npx --yes --package t3@"$2" t3 auth session issue --json --label "$3" --ttl "$4"
|
|
368
|
+
;;
|
|
369
|
+
*) printf 'unknown op: %s\\n' "$1" >&2; exit 2 ;;
|
|
370
|
+
esac
|
|
371
|
+
`;
|
|
372
|
+
const sshRun = (target, args, { streamStderr = false } = {}) => {
|
|
373
|
+
const res = spawnSync('ssh', ['-o', 'ConnectTimeout=15', target, 'sh', '-s', '--', ...args], {
|
|
374
|
+
input: SSH_SCRIPT,
|
|
375
|
+
encoding: 'utf8',
|
|
376
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
377
|
+
stdio: streamStderr ? ['pipe', 'pipe', 'inherit'] : 'pipe',
|
|
378
|
+
});
|
|
379
|
+
if (res.error?.code === 'ENOENT')
|
|
380
|
+
throw new Error('ssh not found locally');
|
|
381
|
+
return { status: res.status ?? 1, stdout: String(res.stdout ?? ''), stderr: String(res.stderr ?? '') };
|
|
382
|
+
};
|
|
383
|
+
// Bottom-up scan for the last T3CTL JSON marker — immune to npm chatter above it.
|
|
384
|
+
const sshDetect = (target) => {
|
|
385
|
+
const res = sshRun(target, ['detect']);
|
|
386
|
+
if (res.status !== 0)
|
|
387
|
+
throw new Error(`ssh to ${target} failed (exit ${res.status})${res.stderr.trim() ? `: ${res.stderr.trim().split('\n').slice(-2).join('\n')}` : ''}`);
|
|
388
|
+
const line = res.stdout.split('\n').reverse().find((l) => l.startsWith('T3CTL {'));
|
|
389
|
+
if (!line)
|
|
390
|
+
throw new Error(`detect on ${target} produced no answer`);
|
|
391
|
+
return JSON.parse(line.slice('T3CTL '.length));
|
|
392
|
+
};
|
|
393
|
+
const sshToken = (target, version, label, ttl) => {
|
|
394
|
+
// First run downloads t3@<version> into the remote npx cache — minutes with
|
|
395
|
+
// nothing to show unless npm's progress on stderr streams through.
|
|
396
|
+
const res = sshRun(target, ['token', version, label, ttl], { streamStderr: true });
|
|
397
|
+
if (res.status !== 0)
|
|
398
|
+
throw new Error(`token minting failed on ${target}${res.stderr.trim() ? `: ${res.stderr.trim().split('\n').slice(-3).join('\n')}` : ''}`);
|
|
399
|
+
// The session JSON is pretty-printed over many lines and stray Effect error
|
|
400
|
+
// lines can precede it, so accumulate bottom-up until an object with a token
|
|
401
|
+
// field parses — the token is the only reliable anchor.
|
|
402
|
+
const lines = res.stdout.split('\n').filter((l) => l.trim() !== '');
|
|
403
|
+
let buf = '';
|
|
404
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
405
|
+
buf = `${lines[i]}\n${buf}`;
|
|
406
|
+
try {
|
|
407
|
+
const parsed = JSON.parse(buf);
|
|
408
|
+
if (typeof parsed.token === 'string' && parsed.token)
|
|
409
|
+
return { token: parsed.token, sessionId: parsed.sessionId };
|
|
410
|
+
}
|
|
411
|
+
catch { /* keep accumulating */ }
|
|
412
|
+
}
|
|
413
|
+
throw new Error(`no token in output from ${target}`);
|
|
414
|
+
};
|
|
415
|
+
// --t3-version wins; else ask npm locally for the exact latest, nightly only as
|
|
416
|
+
// a fallback. An exact version is required by the boot service's pinned runtime.
|
|
417
|
+
const resolveT3Version = (flags) => {
|
|
418
|
+
if (flags['t3-version'])
|
|
419
|
+
return flags['t3-version'];
|
|
420
|
+
if (spawnSync('npm', ['--version'], { stdio: 'ignore' }).status !== 0) {
|
|
421
|
+
throw new Error('npm not found locally — install npm or pass --t3-version <version-or-tag>');
|
|
422
|
+
}
|
|
423
|
+
const res = spawnSync('npm', ['view', `${T3_PACKAGE}@latest`, 'version'], { encoding: 'utf8' });
|
|
424
|
+
if (res.status === 0 && res.stdout.trim())
|
|
425
|
+
return res.stdout.trim();
|
|
426
|
+
const nightly = spawnSync('npm', ['view', `${T3_PACKAGE}@nightly`, 'version'], { encoding: 'utf8' });
|
|
427
|
+
if (nightly.status === 0 && nightly.stdout.trim())
|
|
428
|
+
return nightly.stdout.trim();
|
|
429
|
+
throw new Error(`cannot resolve a t3 CLI version via npm — pass --t3-version (tried: ${res.stderr?.trim().split('\n')[0] ?? 'npm failed'})`);
|
|
430
|
+
};
|
|
431
|
+
const freePort = async () =>
|
|
432
|
+
// TOCTOU between this probe and ssh binding the port is real; ExitOnForwardFailure
|
|
433
|
+
// turns the loss into a nonzero ssh exit, which spawnMaster retries on.
|
|
434
|
+
new Promise((resolve, reject) => {
|
|
435
|
+
const s = net.createServer();
|
|
436
|
+
s.listen(0, '127.0.0.1', () => {
|
|
437
|
+
const p = s.address();
|
|
438
|
+
s.close(() => resolve(p && typeof p === 'object' ? p.port : 0));
|
|
439
|
+
});
|
|
440
|
+
s.on('error', reject);
|
|
441
|
+
});
|
|
442
|
+
const ctlPath = (target, port) => path.join(CONFIG_DIR, `ssh-${createHash('sha256').update(`${target}:${port ?? ''}`).digest('hex').slice(0, 12)}`);
|
|
443
|
+
// ssh -fN + ControlPersist=yes keeps the master alive after t3ctl exits
|
|
444
|
+
// (ssh_config(5)); -f with ExitOnForwardFailure=yes means a clean return from
|
|
445
|
+
// spawnSync implies the local listener exists. stderr stays visible so
|
|
446
|
+
// passphrase prompts (ssh opens /dev/tty itself) and bind errors surface.
|
|
447
|
+
const spawnMaster = async (ssh, sshRemotePort) => {
|
|
448
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
449
|
+
const port = await freePort();
|
|
450
|
+
const res = spawnSync('ssh', [
|
|
451
|
+
'-M', '-S', ctlPath(ssh, port), '-fN',
|
|
452
|
+
'-o', 'ConnectTimeout=15', '-o', 'ControlPersist=yes',
|
|
453
|
+
'-o', 'ExitOnForwardFailure=yes', '-o', 'ServerAliveInterval=15',
|
|
454
|
+
'-o', 'StrictHostKeyChecking=accept-new',
|
|
455
|
+
'-L', `${port}:127.0.0.1:${sshRemotePort}`, ssh,
|
|
456
|
+
], { stdio: ['ignore', 'ignore', 'inherit'] });
|
|
457
|
+
if (res.status === 0)
|
|
458
|
+
return port;
|
|
459
|
+
if (res.error?.code === 'ENOENT')
|
|
460
|
+
throw new Error('ssh not found locally');
|
|
461
|
+
}
|
|
462
|
+
throw new Error(`could not establish the ssh tunnel to ${ssh} (3 attempts)`);
|
|
463
|
+
};
|
|
464
|
+
const waitForOrigin = async (origin, deadline) => {
|
|
465
|
+
while (Date.now() < deadline) {
|
|
466
|
+
if (await probe(origin, PROBE_MS).then(() => true, () => false))
|
|
467
|
+
return true;
|
|
468
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
469
|
+
}
|
|
470
|
+
return false;
|
|
471
|
+
};
|
|
472
|
+
// Single-flight per host name: cmdLs fans out concurrently and every write
|
|
473
|
+
// command re-enters here.
|
|
474
|
+
const tunnelJobs = new Map();
|
|
475
|
+
const ensureTunnel = (host) => {
|
|
476
|
+
if (!host.ssh)
|
|
477
|
+
return Promise.resolve();
|
|
478
|
+
const inFlight = tunnelJobs.get(host.name);
|
|
479
|
+
if (inFlight)
|
|
480
|
+
return inFlight;
|
|
481
|
+
const job = (async () => {
|
|
482
|
+
const target = host.ssh; // captured: TS cannot narrow the optional inside the closure
|
|
483
|
+
if (!target)
|
|
484
|
+
return;
|
|
485
|
+
// Liveness is the HTTP probe, never `ssh -O check` — a live master does not
|
|
486
|
+
// prove the forward works, and the remote port can change on server restart.
|
|
487
|
+
if (await probe(host.origin, PROBE_MS).then(() => true, () => false))
|
|
488
|
+
return;
|
|
489
|
+
spawnSync('ssh', ['-O', 'exit', '-S', ctlPath(target, host.sshLocalPort), target], { stdio: 'ignore' });
|
|
490
|
+
const detect = sshDetect(target);
|
|
491
|
+
if (!detect.running)
|
|
492
|
+
throw new Error(`${target}: no T3 Code server is running — rerun: t3ctl host add ${target}`);
|
|
493
|
+
// Re-pick the local port if something else grabbed it; the origin changes
|
|
494
|
+
// with it, so persist both.
|
|
495
|
+
const localPort = await spawnMaster(target, detect.port ?? 3773);
|
|
496
|
+
const origin = `http://127.0.0.1:${localPort}`;
|
|
497
|
+
writeHosts(readHosts().map((h) => h.name === host.name ? { ...h, sshLocalPort: localPort, sshRemotePort: detect.port ?? 3773, origin } : h));
|
|
498
|
+
if (!(await waitForOrigin(origin, Date.now() + TUNNEL_WAIT_MS))) {
|
|
499
|
+
throw new Error(`${host.ssh}: the ssh tunnel is up but ${origin} is not answering (is the server still running on the remote port?)`);
|
|
500
|
+
}
|
|
501
|
+
})().finally(() => tunnelJobs.delete(host.name));
|
|
502
|
+
tunnelJobs.set(host.name, job);
|
|
503
|
+
return job;
|
|
504
|
+
};
|
|
505
|
+
// `t3ctl host add agent@box` — the full bootstrap. Idempotent: rerunning
|
|
506
|
+
// refreshes the tunnel and keeps the stored token unless the machine behind
|
|
507
|
+
// the login changed (different environmentId).
|
|
508
|
+
const cmdHostAddSsh = async (target, flags, hosts) => {
|
|
509
|
+
const version = resolveT3Version(flags);
|
|
510
|
+
console.log(`probing ${bold(target)} over ssh`);
|
|
511
|
+
let detect = sshDetect(target);
|
|
512
|
+
if (detect.node === false) {
|
|
513
|
+
throw new Error(`${target} has no node on PATH for non-interactive ssh — install Node 22+ there (a version manager may need configuring for non-login shells)`);
|
|
514
|
+
}
|
|
515
|
+
if (!detect.running) {
|
|
516
|
+
console.log(`no T3 Code server on ${target} — installing the t3 boot service (t3@${version})`);
|
|
517
|
+
console.log(dim(` this downloads packages on ${target} and can take a few minutes; its output follows`));
|
|
518
|
+
// No timeout: t3code itself allows 10 minutes for the pinned-runtime npm
|
|
519
|
+
// install, and the user watches the output stream by.
|
|
520
|
+
const res = sshRun(target, ['install', version], { streamStderr: true });
|
|
521
|
+
if (res.status !== 0)
|
|
522
|
+
throw new Error(`t3 service install failed on ${target} (exit ${res.status})`);
|
|
523
|
+
const deadline = Date.now() + SSH_READY_MS;
|
|
524
|
+
let ready = null;
|
|
525
|
+
while (Date.now() < deadline) {
|
|
526
|
+
await new Promise((r) => setTimeout(r, 3000));
|
|
527
|
+
try {
|
|
528
|
+
ready = await sshDetect(target);
|
|
529
|
+
if (ready.running)
|
|
530
|
+
break;
|
|
531
|
+
}
|
|
532
|
+
catch { /* transient ssh hiccups while the service boots */ }
|
|
533
|
+
}
|
|
534
|
+
if (!ready?.running) {
|
|
535
|
+
// Nothing is written to the registry — the origin is not proven yet
|
|
536
|
+
// (probe-first discipline). A tunnel master is only spawned after the
|
|
537
|
+
// probe below, so there is nothing to clean up here either.
|
|
538
|
+
usage(`the boot service was installed on ${target} but no server became ready within ${SSH_READY_MS / 1000}s.\n` +
|
|
539
|
+
` Check its service log on ${target}: ~/.t3/userdata/logs/boot-service.log\n` +
|
|
540
|
+
` On a Mac this usually means nobody is logged in at that console — a launchd\n` +
|
|
541
|
+
` agent starts at login, and an ssh install alone cannot start it.\n` +
|
|
542
|
+
` Rerunning t3ctl host add ${target} is safe once the server is up.`);
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
detect = ready;
|
|
546
|
+
}
|
|
547
|
+
// The stored local port may be taken by now; spawnMaster retries with fresh
|
|
548
|
+
// ports and returns whichever won.
|
|
549
|
+
const existing = hosts.find((h) => h.ssh === target);
|
|
550
|
+
const localPort = await spawnMaster(target, detect.port ?? 3773);
|
|
551
|
+
const origin = `http://127.0.0.1:${localPort}`;
|
|
552
|
+
try {
|
|
553
|
+
if (!(await waitForOrigin(origin, Date.now() + TUNNEL_WAIT_MS))) {
|
|
554
|
+
throw new Error(`the tunnel is up but ${origin} is not answering — is the server listening on 127.0.0.1:${detect.port ?? 3773} on ${target}?`);
|
|
555
|
+
}
|
|
556
|
+
const descriptor = await probe(origin);
|
|
557
|
+
// A changed environmentId on a known login means it now lands on a
|
|
558
|
+
// different machine — same warning as a changed origin, same consequence.
|
|
559
|
+
if (existing?.environmentId && existing.environmentId !== descriptor.environmentId) {
|
|
560
|
+
warn(`${target} is now a DIFFERENT environment\n` +
|
|
561
|
+
` was ${existing.environmentId} (${existing.label ?? 'unknown'})\n` +
|
|
562
|
+
` now ${descriptor.environmentId} (${descriptor.label})\n` +
|
|
563
|
+
` the token stored for "${existing.name}" was issued by the old one and will be replaced`);
|
|
564
|
+
}
|
|
565
|
+
const name = flags.name ?? existing?.name ?? uniqueName(slugify(descriptor.label), hosts);
|
|
566
|
+
let token = existing?.token ?? null;
|
|
567
|
+
let session = null;
|
|
568
|
+
if (!token || (existing?.environmentId && existing.environmentId !== descriptor.environmentId)) {
|
|
569
|
+
const issued = sshToken(target, version, `t3ctl:${name}`, flags.ttl ?? '30d');
|
|
570
|
+
token = issued.token;
|
|
571
|
+
session = issued;
|
|
572
|
+
}
|
|
573
|
+
const others = hosts.filter((h) => h.name !== name && h.origin !== origin && h.serverVersion);
|
|
574
|
+
const skewed = [...new Set(others.flatMap((h) => (h.serverVersion ? [h.serverVersion] : [])))]
|
|
575
|
+
.filter((v) => v !== descriptor.serverVersion);
|
|
576
|
+
if (skewed.length)
|
|
577
|
+
warn(`serverVersion ${descriptor.serverVersion} differs from other hosts: ${skewed.join(', ')}`);
|
|
578
|
+
// A master on a superseded local port would linger forever otherwise.
|
|
579
|
+
if (existing?.sshLocalPort && existing.sshLocalPort !== localPort) {
|
|
580
|
+
spawnSync('ssh', ['-O', 'exit', '-S', ctlPath(target, existing.sshLocalPort), target], { stdio: 'ignore' });
|
|
581
|
+
}
|
|
582
|
+
writeHosts(hosts.filter((h) => h.name !== name && h.ssh !== target).concat({
|
|
583
|
+
name, origin, token,
|
|
584
|
+
environmentId: descriptor.environmentId,
|
|
585
|
+
label: descriptor.label,
|
|
586
|
+
serverVersion: descriptor.serverVersion,
|
|
587
|
+
ssh: target, sshLocalPort: localPort, sshRemotePort: detect.port ?? 3773, t3Version: version,
|
|
588
|
+
}));
|
|
589
|
+
console.log(`added ${bold(name)} -> ${origin} (via ssh)\n label ${descriptor.label}\n` +
|
|
590
|
+
` env ${descriptor.environmentId}\n version ${descriptor.serverVersion}\n` +
|
|
591
|
+
` tunnel 127.0.0.1:${localPort} -> 127.0.0.1:${detect.port ?? 3773} on ${target}`);
|
|
592
|
+
if (session) {
|
|
593
|
+
console.log(` session ${session.sessionId ?? '?'} (label t3ctl:${name})\n` +
|
|
594
|
+
` revoke on ${target} with: npx t3 auth session revoke ${session.sessionId ?? '?'}`);
|
|
595
|
+
}
|
|
596
|
+
else {
|
|
597
|
+
console.log(' token reusing the stored session');
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
catch (error) {
|
|
601
|
+
// Keep no half-registered host: the master would outlive t3ctl otherwise.
|
|
602
|
+
spawnSync('ssh', ['-O', 'exit', '-S', ctlPath(target, localPort), target], { stdio: 'ignore' });
|
|
603
|
+
throw error;
|
|
604
|
+
}
|
|
238
605
|
};
|
|
239
606
|
// ---- writes -------------------------------------------------------------
|
|
240
607
|
// Commands are dispatched directly (no envelope). The CLIENT mints every id;
|
|
@@ -257,7 +624,95 @@ const pickHost = (flags) => {
|
|
|
257
624
|
throw new Error('no hosts registered — run: t3ctl host add <origin> <token>');
|
|
258
625
|
return only;
|
|
259
626
|
};
|
|
627
|
+
const RUNTIME_JSON = '.t3/userdata/server-runtime.json';
|
|
628
|
+
const localRival = async (host) => {
|
|
629
|
+
let ours;
|
|
630
|
+
try {
|
|
631
|
+
ours = new URL(host.origin);
|
|
632
|
+
}
|
|
633
|
+
catch {
|
|
634
|
+
return null;
|
|
635
|
+
}
|
|
636
|
+
if (!LOOPBACK.has(ours.hostname))
|
|
637
|
+
return null;
|
|
638
|
+
let r;
|
|
639
|
+
try {
|
|
640
|
+
r = JSON.parse(fs.readFileSync(path.join(os.homedir(), RUNTIME_JSON), 'utf8'));
|
|
641
|
+
}
|
|
642
|
+
catch {
|
|
643
|
+
return null;
|
|
644
|
+
}
|
|
645
|
+
const pid = Number(r.pid);
|
|
646
|
+
let theirs;
|
|
647
|
+
try {
|
|
648
|
+
theirs = new URL(String(r.origin ?? ''));
|
|
649
|
+
}
|
|
650
|
+
catch {
|
|
651
|
+
return null;
|
|
652
|
+
}
|
|
653
|
+
if (!Number.isInteger(pid) || pid <= 0 || theirs.port === ours.port)
|
|
654
|
+
return null;
|
|
655
|
+
try {
|
|
656
|
+
process.kill(pid, 0);
|
|
657
|
+
}
|
|
658
|
+
catch {
|
|
659
|
+
return null;
|
|
660
|
+
}
|
|
661
|
+
// Same environmentId means same ~/.t3, i.e. the same database behind both ports.
|
|
662
|
+
const [live, mine] = await Promise.all([
|
|
663
|
+
probe(theirs.origin, PROBE_MS).catch(() => null),
|
|
664
|
+
probe(host.origin, PROBE_MS).catch(() => null),
|
|
665
|
+
]);
|
|
666
|
+
const env = mine?.environmentId ?? host.environmentId;
|
|
667
|
+
if (!live || !env || live.environmentId !== env)
|
|
668
|
+
return null;
|
|
669
|
+
return {
|
|
670
|
+
origin: theirs.origin, pid, serverVersion: live.serverVersion,
|
|
671
|
+
startedAt: typeof r.startedAt === 'string' ? r.startedAt : undefined,
|
|
672
|
+
moved: !mine,
|
|
673
|
+
};
|
|
674
|
+
};
|
|
675
|
+
// Over ssh the remote runtime file is only re-read when the tunnel is rebuilt,
|
|
676
|
+
// so a server that keeps running on the old port hides a newer one the same way.
|
|
677
|
+
const sshRival = (host) => {
|
|
678
|
+
// ensureTunnel may have just re-pointed the tunnel and rewritten the registry.
|
|
679
|
+
const current = readHosts().find((h) => h.name === host.name) ?? host;
|
|
680
|
+
if (!current.ssh || !current.sshRemotePort)
|
|
681
|
+
return null;
|
|
682
|
+
const detect = sshDetect(current.ssh);
|
|
683
|
+
if (!detect.running || !detect.port || detect.port === current.sshRemotePort)
|
|
684
|
+
return null;
|
|
685
|
+
return { origin: `${current.ssh}:${detect.port} (remote)` };
|
|
686
|
+
};
|
|
687
|
+
const findRival = (host) => host.ssh ? Promise.resolve().then(() => sshRival(host)) : localRival(host);
|
|
688
|
+
const rivalMessage = (host, rival) => (rival.moved
|
|
689
|
+
? `${host.name} (${host.origin}) is not answering; its T3 Code server now runs at `
|
|
690
|
+
: `${host.name} (${host.origin}) is not the only T3 Code server on this data dir — `) +
|
|
691
|
+
`${rival.origin}${rival.serverVersion ? ` (${rival.serverVersion}` : ''}` +
|
|
692
|
+
`${rival.pid ? `, pid ${rival.pid}` : ''}${rival.startedAt ? `, started ${rival.startedAt}` : ''}` +
|
|
693
|
+
`${rival.serverVersion ? ')' : ''}${rival.moved ? '' : ' started after it'}.\n` +
|
|
694
|
+
(rival.moved ? ' Point t3ctl at it:\n' :
|
|
695
|
+
` Each server only sees threads created through itself, so the app talking to one\n` +
|
|
696
|
+
` gets "Thread … does not exist" for threads made on the other.\n` +
|
|
697
|
+
` Stop the stale server, or point t3ctl at the current one:\n`) +
|
|
698
|
+
(host.ssh
|
|
699
|
+
? ` t3ctl host rm ${host.name} && t3ctl host add ${host.ssh} --name ${host.name}`
|
|
700
|
+
: ` t3ctl host add ${rival.origin} --name ${host.name}`);
|
|
701
|
+
// Writes are what strand threads, so they refuse; reads only warn.
|
|
702
|
+
const assertNoRival = async (host) => {
|
|
703
|
+
const rival = await findRival(host);
|
|
704
|
+
if (rival)
|
|
705
|
+
throw new Error(rivalMessage(host, rival));
|
|
706
|
+
};
|
|
707
|
+
// ssh hosts are skipped here: a detect round-trip per host per `ls` is too slow.
|
|
708
|
+
const warnRivals = async (hosts) => {
|
|
709
|
+
const rivals = await Promise.all(hosts.map((h) => (h.ssh ? null : localRival(h).catch(() => null))));
|
|
710
|
+
hosts.forEach((h, i) => { const r = rivals[i]; if (r)
|
|
711
|
+
warn(rivalMessage(h, r)); });
|
|
712
|
+
};
|
|
260
713
|
const dispatch = async (host, command) => {
|
|
714
|
+
await ensureTunnel(host);
|
|
715
|
+
await assertNoRival(host);
|
|
261
716
|
const res = await fetch(`${host.origin}/api/orchestration/dispatch`, {
|
|
262
717
|
method: 'POST',
|
|
263
718
|
headers: { ...(host.token ? { authorization: `Bearer ${host.token}` } : {}), 'content-type': 'application/json' },
|
|
@@ -293,6 +748,33 @@ const resolveThread = (snap, ref) => {
|
|
|
293
748
|
}
|
|
294
749
|
throw new Error(`no thread matching "${ref}"`);
|
|
295
750
|
};
|
|
751
|
+
// instanceId is the segment before the FIRST slash; the model keeps the rest,
|
|
752
|
+
// because opencode model ids are themselves slashed ("github-copilot/gpt-5.4").
|
|
753
|
+
const parseModel = (raw) => {
|
|
754
|
+
const slash = raw.indexOf('/');
|
|
755
|
+
if (slash < 1)
|
|
756
|
+
throw new Error(`--model must be <instance>/<model>, got "${raw}"`);
|
|
757
|
+
return { instanceId: raw.slice(0, slash), model: raw.slice(slash + 1) };
|
|
758
|
+
};
|
|
759
|
+
// `--option id=value` sets one entry of modelSelection.options, replacing an
|
|
760
|
+
// entry with the same id. The server accepts strings and booleans, so `true`
|
|
761
|
+
// and `false` are sent as booleans (`fastMode=true`), anything else as a string.
|
|
762
|
+
const withOptions = (selection, raw = []) => {
|
|
763
|
+
if (raw.length === 0)
|
|
764
|
+
return selection;
|
|
765
|
+
const options = new Map((selection.options ?? []).map((o) => [o.id, o]));
|
|
766
|
+
for (const entry of raw) {
|
|
767
|
+
const eq = entry.indexOf('=');
|
|
768
|
+
const id = entry.slice(0, eq).trim();
|
|
769
|
+
const text = entry.slice(eq + 1).trim();
|
|
770
|
+
if (eq < 0 || !id || !text)
|
|
771
|
+
throw new Error(`--option must be <id>=<value>, got "${entry}"`);
|
|
772
|
+
options.set(id, { id, value: text === 'true' ? true : text === 'false' ? false : text });
|
|
773
|
+
}
|
|
774
|
+
return { ...selection, options: [...options.values()] };
|
|
775
|
+
};
|
|
776
|
+
const describeModel = (m) => `${m.instanceId}/${m.model}` +
|
|
777
|
+
(m.options?.length ? ` (${m.options.map((o) => `${o.id}=${o.value}`).join(', ')})` : '');
|
|
296
778
|
// thread.turn.start is ONE command carrying the first message inline — this is
|
|
297
779
|
// what the UI fires immediately after thread.create, which is why a thread with
|
|
298
780
|
// no messages is a state the UI never produces. The client-side schema requires
|
|
@@ -307,19 +789,15 @@ const cmdThreadStart = async (thread, host, text, flags) => {
|
|
|
307
789
|
interactionMode: flags['interaction-mode'] ?? 'default',
|
|
308
790
|
createdAt: new Date().toISOString(),
|
|
309
791
|
};
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
command.modelSelection =
|
|
315
|
-
}
|
|
316
|
-
else if (thread.modelSelection) {
|
|
317
|
-
command.modelSelection = thread.modelSelection;
|
|
318
|
-
}
|
|
792
|
+
const base = flags.model ? parseModel(flags.model) : thread.modelSelection;
|
|
793
|
+
if (!base && flags.option?.length)
|
|
794
|
+
throw new Error('--option needs a model; the thread has none, so pass --model too');
|
|
795
|
+
if (base)
|
|
796
|
+
command.modelSelection = withOptions(base, flags.option);
|
|
319
797
|
const { sequence } = await dispatch(host, command);
|
|
320
798
|
const m = command['modelSelection'];
|
|
321
799
|
console.log(`started ${bold(thread.title || thread.id)}\n id ${thread.id}` +
|
|
322
|
-
(m ? `\n model ${m
|
|
800
|
+
(m ? `\n model ${describeModel(m)}` : '') +
|
|
323
801
|
`\n mode ${command.runtimeMode} / ${command.interactionMode}\n seq ${sequence}`);
|
|
324
802
|
};
|
|
325
803
|
const cmdThreadInterrupt = async (thread, host) => {
|
|
@@ -338,8 +816,12 @@ const cmdThreadRename = async (thread, host, title) => {
|
|
|
338
816
|
};
|
|
339
817
|
// Lighter than the full snapshot; retitle polls this so it does not refetch every
|
|
340
818
|
// thread's history once a second.
|
|
341
|
-
|
|
342
|
-
|
|
819
|
+
// `turnLimit` is null for callers that want the whole history (export), 1 for
|
|
820
|
+
// callers that only want to poll a field (retitle).
|
|
821
|
+
const threadDetail = async (host, threadId, turnLimit = 1) => {
|
|
822
|
+
await ensureTunnel(host);
|
|
823
|
+
const query = turnLimit === null ? '' : `?turnLimit=${turnLimit}`;
|
|
824
|
+
const res = await fetch(`${host.origin}/api/orchestration/threads/${threadId}${query}`, {
|
|
343
825
|
headers: { authorization: `Bearer ${host.token}` },
|
|
344
826
|
signal: AbortSignal.timeout(host.timeoutMs ?? 15000),
|
|
345
827
|
});
|
|
@@ -398,13 +880,7 @@ const cmdThreadCreate = async (projectRef, title, flags) => {
|
|
|
398
880
|
const project = resolveProject(await snapshot(host), projectRef);
|
|
399
881
|
if (!project)
|
|
400
882
|
throw new Error(`no project matching "${projectRef}" on ${host.name}`);
|
|
401
|
-
|
|
402
|
-
// because opencode model ids are themselves slashed ("github-copilot/gpt-5.4").
|
|
403
|
-
const raw = flags.model ?? 'claudeAgent/claude-opus-5';
|
|
404
|
-
const slash = raw.indexOf('/');
|
|
405
|
-
if (slash < 1)
|
|
406
|
-
throw new Error(`--model must be <instance>/<model>, got "${raw}"`);
|
|
407
|
-
const modelSelection = { instanceId: raw.slice(0, slash), model: raw.slice(slash + 1) };
|
|
883
|
+
const modelSelection = withOptions(parseModel(flags.model ?? 'claudeAgent/claude-opus-5'), flags.option);
|
|
408
884
|
const threadId = crypto.randomUUID();
|
|
409
885
|
const { sequence } = await dispatch(host, {
|
|
410
886
|
type: 'thread.create', commandId: crypto.randomUUID(),
|
|
@@ -415,7 +891,7 @@ const cmdThreadCreate = async (projectRef, title, flags) => {
|
|
|
415
891
|
worktreePath: flags.worktree ?? null,
|
|
416
892
|
createdAt: new Date().toISOString(),
|
|
417
893
|
});
|
|
418
|
-
console.log(`created thread ${bold(title)} in ${project.title} on ${host.name}\n id ${threadId}\n model ${modelSelection
|
|
894
|
+
console.log(`created thread ${bold(title)} in ${project.title} on ${host.name}\n id ${threadId}\n model ${describeModel(modelSelection)}\n seq ${sequence}`);
|
|
419
895
|
};
|
|
420
896
|
const cmdThreadSimple = async (verb, ref, flags) => {
|
|
421
897
|
const host = pickHost(flags);
|
|
@@ -425,6 +901,256 @@ const cmdThreadSimple = async (verb, ref, flags) => {
|
|
|
425
901
|
});
|
|
426
902
|
console.log(`${verb}d ${bold(thread.title || thread.id)}\n id ${thread.id}\n seq ${sequence}`);
|
|
427
903
|
};
|
|
904
|
+
const STRATEGY_LABEL = {
|
|
905
|
+
sqlite: 'local state.sqlite',
|
|
906
|
+
http: 'snapshot + per-thread fetch',
|
|
907
|
+
};
|
|
908
|
+
/** Fixed by T3 Code. Read relative to whichever machine's home directory applies. */
|
|
909
|
+
const STATE_DB = '.t3/userdata/state.sqlite';
|
|
910
|
+
const expandHome = (p) => path.resolve(p.replace(/^~(?=$|\/)/, os.homedir()));
|
|
911
|
+
/**
|
|
912
|
+
* Where a prompt happened, named the way a human would: the workspace path made
|
|
913
|
+
* relative to the watched root it sits under. Longest matching root wins, so
|
|
914
|
+
* `~/Code` and `~/Code/@clients` both configured gives `afa`, not `@clients/afa`.
|
|
915
|
+
* A workspace under no watched root has no marker and the prompt is dropped.
|
|
916
|
+
*/
|
|
917
|
+
const markerForWorkspace = (workspaceRoot, watched) => {
|
|
918
|
+
const ws = workspaceRoot.replace(/\/+$/, '');
|
|
919
|
+
let best = null;
|
|
920
|
+
let bestLen = -1;
|
|
921
|
+
for (const root of watched) {
|
|
922
|
+
const r = root.replace(/\/+$/, '');
|
|
923
|
+
if (ws === r)
|
|
924
|
+
return ws.split('/').pop() ?? ws;
|
|
925
|
+
if (ws.startsWith(`${r}/`) && r.length > bestLen) {
|
|
926
|
+
best = ws.slice(r.length + 1);
|
|
927
|
+
bestLen = r.length;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
return best;
|
|
931
|
+
};
|
|
932
|
+
/**
|
|
933
|
+
* Prompts arrive with the harness's wrapping still on them. Mirrors
|
|
934
|
+
* `cleanPrompt` in spr-time-entrier, which is the consumer this shape is for:
|
|
935
|
+
* unwrap `<user_query>` when present, then collapse whitespace to one line.
|
|
936
|
+
*/
|
|
937
|
+
const cleanPrompt = (text) => {
|
|
938
|
+
const tagged = text.match(/<user_query>\s*([\s\S]*?)\s*<\/user_query>/);
|
|
939
|
+
return (tagged?.[1] ?? text).replace(/\s+/g, ' ').trim();
|
|
940
|
+
};
|
|
941
|
+
// One statement, shared by every strategy that reads the local store directly,
|
|
942
|
+
// so it cannot drift from what the HTTP path reconstructs.
|
|
943
|
+
const PROMPT_SQL = `SELECT m.message_id, m.thread_id, m.text, m.created_at, p.workspace_root
|
|
944
|
+
FROM projection_thread_messages m
|
|
945
|
+
JOIN projection_threads t ON t.thread_id = m.thread_id
|
|
946
|
+
JOIN projection_projects p ON p.project_id = t.project_id
|
|
947
|
+
WHERE m.role = 'user'
|
|
948
|
+
AND t.deleted_at IS NULL
|
|
949
|
+
AND p.deleted_at IS NULL
|
|
950
|
+
AND m.created_at >= ? AND m.created_at < ?
|
|
951
|
+
ORDER BY m.created_at`;
|
|
952
|
+
/**
|
|
953
|
+
* A bare `--since 2026-09-14` is the UTC day boundary, not local midnight: the
|
|
954
|
+
* rows being filtered are UTC, and an export should describe the same window
|
|
955
|
+
* whichever machine runs it. Anything else is handed to `Date` as written.
|
|
956
|
+
*/
|
|
957
|
+
const isoBound = (value, flag) => {
|
|
958
|
+
const raw = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00:00.000Z` : value;
|
|
959
|
+
const at = new Date(raw);
|
|
960
|
+
if (Number.isNaN(at.getTime()))
|
|
961
|
+
throw new Error(`${flag}: not a date I can read: ${value}`);
|
|
962
|
+
return at.toISOString();
|
|
963
|
+
};
|
|
964
|
+
/**
|
|
965
|
+
* node:sqlite arrived in Node 22.5 behind `--experimental-sqlite`. Current
|
|
966
|
+
* releases have it unflagged (verified on 22.23 and 24), but `engines` allows
|
|
967
|
+
* `>=22`, which still admits the flagged ones. Importing it lazily means only
|
|
968
|
+
* this command fails there, instead of the whole CLI failing to start.
|
|
969
|
+
*/
|
|
970
|
+
const loadSqlite = async () => {
|
|
971
|
+
try {
|
|
972
|
+
return (await import('node:sqlite')).DatabaseSync;
|
|
973
|
+
}
|
|
974
|
+
catch {
|
|
975
|
+
throw new Error('reading state.sqlite needs node:sqlite — upgrade to Node >= 22.13, or pass --experimental-sqlite on 22.5-22.12');
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
const queryLocal = async (since, until) => {
|
|
979
|
+
const file = path.join(os.homedir(), STATE_DB);
|
|
980
|
+
if (!fs.existsSync(file))
|
|
981
|
+
throw new Error(`no T3 Code database at ${file}`);
|
|
982
|
+
const DatabaseSync = await loadSqlite();
|
|
983
|
+
// The database is in WAL mode, so this reader neither blocks the running app
|
|
984
|
+
// nor is blocked by it, and no copy is needed — it is ~500 MB.
|
|
985
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
986
|
+
try {
|
|
987
|
+
return db.prepare(PROMPT_SQL).all(since, until);
|
|
988
|
+
}
|
|
989
|
+
finally {
|
|
990
|
+
db.close();
|
|
991
|
+
}
|
|
992
|
+
};
|
|
993
|
+
/** `Date.parse` returns NaN for junk and for null; both mean "cannot compare". */
|
|
994
|
+
const instant = (value) => {
|
|
995
|
+
const t = value ? Date.parse(value) : Number.NaN;
|
|
996
|
+
return Number.isNaN(t) ? null : t;
|
|
997
|
+
};
|
|
998
|
+
/**
|
|
999
|
+
* Which threads are worth a request. `updatedAt` moves with every new message,
|
|
1000
|
+
* so a thread untouched since the window opened cannot hold one, and a thread
|
|
1001
|
+
* created after it closed cannot either. Anything unknown is fetched.
|
|
1002
|
+
*/
|
|
1003
|
+
const mayHavePrompts = (t, since, until) => {
|
|
1004
|
+
if (t.deletedAt)
|
|
1005
|
+
return false;
|
|
1006
|
+
const updated = instant(t.updatedAt);
|
|
1007
|
+
if (updated !== null && updated < since)
|
|
1008
|
+
return false;
|
|
1009
|
+
const created = instant(t.createdAt);
|
|
1010
|
+
if (created !== null && created >= until)
|
|
1011
|
+
return false;
|
|
1012
|
+
return true;
|
|
1013
|
+
};
|
|
1014
|
+
/** Bounded fan-out: a host with 200 live threads should not get 200 sockets at once. */
|
|
1015
|
+
const mapPool = async (items, limit, fn) => {
|
|
1016
|
+
const out = new Array(items.length);
|
|
1017
|
+
// Every worker pulls from the same iterator, so each entry goes to exactly one
|
|
1018
|
+
// of them and the last to finish is the last item, not the last worker.
|
|
1019
|
+
const queue = items.entries();
|
|
1020
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
1021
|
+
for (const [i, item] of queue)
|
|
1022
|
+
out[i] = await fn(item);
|
|
1023
|
+
}));
|
|
1024
|
+
return out;
|
|
1025
|
+
};
|
|
1026
|
+
const queryOverHttp = async (host, since, until) => {
|
|
1027
|
+
const snap = await snapshot(host);
|
|
1028
|
+
const roots = new Map(snap.projects.filter((p) => !p.deletedAt).map((p) => [p.id, p.workspaceRoot]));
|
|
1029
|
+
const from = Date.parse(since);
|
|
1030
|
+
const to = Date.parse(until);
|
|
1031
|
+
const threads = snap.threads.filter((t) => roots.has(t.projectId) && mayHavePrompts(t, from, to));
|
|
1032
|
+
const perThread = await mapPool(threads, 8, async (t) => {
|
|
1033
|
+
const workspaceRoot = roots.get(t.projectId);
|
|
1034
|
+
if (workspaceRoot === undefined)
|
|
1035
|
+
return [];
|
|
1036
|
+
const detail = await threadDetail(host, t.id, null);
|
|
1037
|
+
const rows = [];
|
|
1038
|
+
for (const m of detail.messages ?? []) {
|
|
1039
|
+
if (m.role !== 'user')
|
|
1040
|
+
continue;
|
|
1041
|
+
const at = instant(m.createdAt);
|
|
1042
|
+
if (at === null || at < from || at >= to)
|
|
1043
|
+
continue;
|
|
1044
|
+
const messageId = m.messageId ?? m.id;
|
|
1045
|
+
if (messageId === undefined)
|
|
1046
|
+
continue;
|
|
1047
|
+
rows.push({
|
|
1048
|
+
message_id: messageId,
|
|
1049
|
+
thread_id: t.id,
|
|
1050
|
+
text: m.text ?? '',
|
|
1051
|
+
created_at: new Date(at).toISOString(),
|
|
1052
|
+
workspace_root: workspaceRoot,
|
|
1053
|
+
});
|
|
1054
|
+
}
|
|
1055
|
+
return rows;
|
|
1056
|
+
});
|
|
1057
|
+
return perThread.flat();
|
|
1058
|
+
};
|
|
1059
|
+
/**
|
|
1060
|
+
* Loopback means the database this process can already open is the very one the
|
|
1061
|
+
* host serves, so read it and skip the network entirely. Everything else goes
|
|
1062
|
+
* over HTTP.
|
|
1063
|
+
*/
|
|
1064
|
+
const LOOPBACK = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
|
|
1065
|
+
const strategyFor = (host) => {
|
|
1066
|
+
let hostname = '';
|
|
1067
|
+
try {
|
|
1068
|
+
hostname = new URL(host.origin).hostname;
|
|
1069
|
+
}
|
|
1070
|
+
catch { /* an unparseable origin is not loopback; let the HTTP path report it */ }
|
|
1071
|
+
return LOOPBACK.has(hostname) ? 'sqlite' : 'http';
|
|
1072
|
+
};
|
|
1073
|
+
const readPrompts = (host, strategy, since, until) => {
|
|
1074
|
+
if (strategy === 'sqlite')
|
|
1075
|
+
return queryLocal(since, until);
|
|
1076
|
+
return queryOverHttp(host, since, until);
|
|
1077
|
+
};
|
|
1078
|
+
const cmdExportPrompts = async (o) => {
|
|
1079
|
+
const since = isoBound(o.since, '--since');
|
|
1080
|
+
const until = o.until ? isoBound(o.until, '--until') : new Date().toISOString();
|
|
1081
|
+
if (until <= since)
|
|
1082
|
+
throw new Error(`--until (${until}) must be after --since (${since})`);
|
|
1083
|
+
const registered = readHosts();
|
|
1084
|
+
if (!registered.length)
|
|
1085
|
+
throw new Error('no hosts registered — run: t3ctl host add <origin> <token>');
|
|
1086
|
+
const hosts = o.host ? registered.filter((h) => h.name === o.host) : registered;
|
|
1087
|
+
if (!hosts.length)
|
|
1088
|
+
throw new Error(`no such host: ${o.host}`);
|
|
1089
|
+
const watched = (o.watch?.length ? o.watch : ['~/Code']).map(expandHome);
|
|
1090
|
+
const settled = await Promise.allSettled(hosts.map(async (h) => {
|
|
1091
|
+
const strategy = strategyFor(h);
|
|
1092
|
+
return { strategy, rows: await readPrompts(h, strategy, since, until) };
|
|
1093
|
+
}));
|
|
1094
|
+
const messages = [];
|
|
1095
|
+
const unreachable = [];
|
|
1096
|
+
const reached = [];
|
|
1097
|
+
settled.forEach((result, i) => {
|
|
1098
|
+
const host = hosts[i];
|
|
1099
|
+
if (!host)
|
|
1100
|
+
return;
|
|
1101
|
+
if (result.status === 'rejected') {
|
|
1102
|
+
unreachable.push({ host: host.name, error: errorMessage(result.reason) });
|
|
1103
|
+
return;
|
|
1104
|
+
}
|
|
1105
|
+
const { strategy, rows } = result.value;
|
|
1106
|
+
let count = 0;
|
|
1107
|
+
for (const row of rows) {
|
|
1108
|
+
const marker = markerForWorkspace(row.workspace_root, watched);
|
|
1109
|
+
if (marker === null)
|
|
1110
|
+
continue; // outside every watched root
|
|
1111
|
+
messages.push({
|
|
1112
|
+
host: host.name,
|
|
1113
|
+
threadId: row.thread_id,
|
|
1114
|
+
messageId: row.message_id,
|
|
1115
|
+
createdAt: row.created_at,
|
|
1116
|
+
text: cleanPrompt(row.text),
|
|
1117
|
+
workspaceRoot: row.workspace_root,
|
|
1118
|
+
// Markers have to stay unique across machines, and two hosts routinely
|
|
1119
|
+
// hold a checkout of the same repo at the same path. The local host is
|
|
1120
|
+
// the unprefixed one so single-machine consumers see plain names.
|
|
1121
|
+
marker: strategy === 'sqlite' ? marker : `${host.name}/${marker}`,
|
|
1122
|
+
});
|
|
1123
|
+
count++;
|
|
1124
|
+
}
|
|
1125
|
+
reached.push({ host: host.name, strategy, count });
|
|
1126
|
+
});
|
|
1127
|
+
messages.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.messageId.localeCompare(b.messageId));
|
|
1128
|
+
if (o.json) {
|
|
1129
|
+
console.log(JSON.stringify({ messages, unreachable }, null, 2));
|
|
1130
|
+
}
|
|
1131
|
+
else {
|
|
1132
|
+
const n = messages.length;
|
|
1133
|
+
console.log(`${bold(String(n))} prompt${n === 1 ? '' : 's'} ${dim(`${since} -> ${until}`)}`);
|
|
1134
|
+
for (const { host, strategy, count } of reached) {
|
|
1135
|
+
console.log(`\n${bold(host)} ${count} ${dim(STRATEGY_LABEL[strategy])}`);
|
|
1136
|
+
const tally = new Map();
|
|
1137
|
+
for (const m of messages) {
|
|
1138
|
+
if (m.host === host)
|
|
1139
|
+
tally.set(m.marker, (tally.get(m.marker) ?? 0) + 1);
|
|
1140
|
+
}
|
|
1141
|
+
const width = Math.max(0, ...[...tally.keys()].map((k) => k.length));
|
|
1142
|
+
for (const [marker, hits] of [...tally].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))) {
|
|
1143
|
+
console.log(` ${marker.padEnd(width)} ${hits}`);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
for (const u of unreachable)
|
|
1148
|
+
console.error(`${ICON.error} ${u.host} ${dim(u.error)}`);
|
|
1149
|
+
// Partial results are still useful and `unreachable` reports what is missing,
|
|
1150
|
+
// so only a total failure is an error.
|
|
1151
|
+
if (unreachable.length === hosts.length)
|
|
1152
|
+
process.exitCode = 1;
|
|
1153
|
+
};
|
|
428
1154
|
// ---- cli ----------------------------------------------------------------
|
|
429
1155
|
// commander's option names arrive camelCased; the command implementations were
|
|
430
1156
|
// written against the kebab-case spellings, so translate once here rather than
|
|
@@ -433,6 +1159,7 @@ const FLAG_NAMES = {
|
|
|
433
1159
|
host: 'host', model: 'model', branch: 'branch', worktree: 'worktree',
|
|
434
1160
|
name: 'name', timeout: 'timeout',
|
|
435
1161
|
runtimeMode: 'runtime-mode', interactionMode: 'interaction-mode',
|
|
1162
|
+
option: 'option',
|
|
436
1163
|
};
|
|
437
1164
|
// Only carry options that were actually supplied. Emitting every key
|
|
438
1165
|
// unconditionally made `'name' in flags` always true, which made host add bail
|
|
@@ -454,6 +1181,7 @@ program
|
|
|
454
1181
|
.version(pkg.version, '-v, --version', 'print the t3ctl version')
|
|
455
1182
|
.showHelpAfterError('(run `t3ctl --help` or `t3ctl <command> --help`)')
|
|
456
1183
|
.configureHelp({ showGlobalOptions: true });
|
|
1184
|
+
const addOption = (value, previous) => [...(previous ?? []), value];
|
|
457
1185
|
const hostOption = (cmd) => cmd.option('--host <name>', 'which registered host to talk to (required when several are registered)');
|
|
458
1186
|
program.command('ls')
|
|
459
1187
|
.description('list projects and threads across all registered hosts')
|
|
@@ -463,18 +1191,43 @@ program.command('ls')
|
|
|
463
1191
|
.action((o) => cmdLs(o));
|
|
464
1192
|
const host = program.command('host').description('manage the host registry');
|
|
465
1193
|
host.command('add')
|
|
466
|
-
.argument('<origin>', 'base URL of the host, e.g. https://box.tailnet.ts.net:3773')
|
|
467
|
-
.argument('[token]', 'bearer token from `t3 auth session issue` on that host')
|
|
468
|
-
.description('register a host,
|
|
1194
|
+
.argument('<origin>', 'base URL of the host, e.g. https://box.tailnet.ts.net:3773 — or an ssh login like agent@box to bootstrap that machine end to end')
|
|
1195
|
+
.argument('[token]', 'bearer token from `t3 auth session issue` on that host (origin form only)')
|
|
1196
|
+
.description('register a host — from a URL, or from its ssh login alone')
|
|
469
1197
|
.option('--name <name>', 'override the label detected from the host')
|
|
470
|
-
.
|
|
1198
|
+
.option('--ttl <duration>', 'session lifetime for the ssh form, e.g. 30d (default 30d)', '30d')
|
|
1199
|
+
.option('--t3-version <version>', 'exact t3 CLI version to install remotely (default: npm-resolved latest, nightly as fallback)')
|
|
1200
|
+
.action(async (origin, token, o) => {
|
|
1201
|
+
const flags = toFlags(o);
|
|
1202
|
+
const hosts = readHosts();
|
|
1203
|
+
// Two shapes, told apart by scheme: an http(s) origin pairs with an existing
|
|
1204
|
+
// server; anything else is an ssh login that bootstraps one.
|
|
1205
|
+
if (isOrigin(origin)) {
|
|
1206
|
+
return cmdHostAdd([origin, ...(token ? [token] : [])], flags, hosts);
|
|
1207
|
+
}
|
|
1208
|
+
// An origin missing its scheme is still the old, deliberate rejection — not
|
|
1209
|
+
// guessed at, and not misread as an ssh target (ssh targets never carry a
|
|
1210
|
+
// colon; ports belong to origins).
|
|
1211
|
+
if (origin.includes(':')) {
|
|
1212
|
+
return usage('an origin needs a scheme, e.g. http://localhost:3773');
|
|
1213
|
+
}
|
|
1214
|
+
if (token) {
|
|
1215
|
+
throw new Error('a token argument only makes sense with an <origin>; the ssh form mints its own');
|
|
1216
|
+
}
|
|
1217
|
+
return cmdHostAddSsh(origin, flags, hosts);
|
|
1218
|
+
});
|
|
471
1219
|
host.command('rm')
|
|
472
1220
|
.argument('<name>', 'registered host name')
|
|
473
1221
|
.description('remove a host from the registry')
|
|
474
1222
|
.action((name) => {
|
|
475
1223
|
const hosts = readHosts();
|
|
476
|
-
|
|
1224
|
+
const gone = hosts.find((h) => h.name === name);
|
|
1225
|
+
if (!gone)
|
|
477
1226
|
throw new Error(`no such host: ${name}`);
|
|
1227
|
+
// Taking the ssh master down with the entry; a missing socket just exits 255.
|
|
1228
|
+
if (gone.ssh) {
|
|
1229
|
+
spawnSync('ssh', ['-O', 'exit', '-S', ctlPath(gone.ssh, gone.sshLocalPort), gone.ssh], { stdio: 'ignore' });
|
|
1230
|
+
}
|
|
478
1231
|
writeHosts(hosts.filter((h) => h.name !== name));
|
|
479
1232
|
console.log(`removed ${name}`);
|
|
480
1233
|
});
|
|
@@ -482,6 +1235,19 @@ host.command('ls').description('list registered hosts and probe each one')
|
|
|
482
1235
|
.action(() => cmdHostsList(readHosts()));
|
|
483
1236
|
program.command('hosts').description('list registered hosts and probe each one (alias of `host ls`)')
|
|
484
1237
|
.action(() => cmdHostsList(readHosts()));
|
|
1238
|
+
// Repeatable, because a workspace tree is not always one root. No default value
|
|
1239
|
+
// is handed to commander: it would print `(default: [])` in the help, which is
|
|
1240
|
+
// not what happens when the flag is omitted.
|
|
1241
|
+
const addWatch = (value, previous) => [...(previous ?? []), value];
|
|
1242
|
+
const exportGroup = program.command('export').description('read-only exports for other tools');
|
|
1243
|
+
exportGroup.command('prompts')
|
|
1244
|
+
.description('every prompt a human typed, across hosts, with the project it happened in')
|
|
1245
|
+
.requiredOption('--since <date>', 'window start, inclusive — a bare YYYY-MM-DD is a UTC day boundary')
|
|
1246
|
+
.option('--until <date>', 'window end, exclusive (default: now)')
|
|
1247
|
+
.option('--host <name>', 'only this registered host (default: every one of them)')
|
|
1248
|
+
.option('--watch <path>', 'only prompts in projects under this root; repeatable (default: ~/Code)', addWatch)
|
|
1249
|
+
.option('--json', 'emit JSON instead of a summary')
|
|
1250
|
+
.action((o) => cmdExportPrompts(o));
|
|
485
1251
|
const project = program.command('project').description('manage projects');
|
|
486
1252
|
hostOption(project.command('create')
|
|
487
1253
|
.argument('<title>', 'name for the project as it appears in T3 Code')
|
|
@@ -494,6 +1260,7 @@ hostOption(thread.command('create')
|
|
|
494
1260
|
.argument('<title...>', 'thread title; everything after the project is used')
|
|
495
1261
|
.description('create a thread (idle — use `thread send` to run it)')
|
|
496
1262
|
.option('--model <instance/model>', 'e.g. claudeAgent/claude-opus-5', 'claudeAgent/claude-opus-5')
|
|
1263
|
+
.option('--option <id=value>', 'model option, e.g. effort=high; repeatable', addOption)
|
|
497
1264
|
.option('--branch <branch>', 'git branch to associate with the thread')
|
|
498
1265
|
.option('--worktree <path>', 'git worktree the thread should run in')
|
|
499
1266
|
.option('--runtime-mode <mode>', 'approval-required | auto-accept-edits | auto | full-access', 'full-access')
|
|
@@ -505,6 +1272,7 @@ hostOption(thread.command('send')
|
|
|
505
1272
|
.argument('<message...>', 'the message; everything after the thread is sent')
|
|
506
1273
|
.description('send a message to a thread and run the agent')
|
|
507
1274
|
.option('--model <instance/model>', "override the thread's model for this turn")
|
|
1275
|
+
.option('--option <id=value>', "model option for this turn, e.g. effort=high; repeatable", addOption)
|
|
508
1276
|
.option('--runtime-mode <mode>', 'approval-required | auto-accept-edits | auto | full-access')
|
|
509
1277
|
.option('--interaction-mode <mode>', 'default | plan'))
|
|
510
1278
|
.action(async (ref, message, o) => {
|